blob: b9091c7a3319401561e93806fe902a80e30dbd63 [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";
Steve Anton4171afb2017-11-20 10:20:22 -080094static const char kDefaultAudioSenderId[] = "defaulta0";
95static const char kDefaultVideoSenderId[] = "defaultv0";
deadbeefab9b2d12015-10-14 11:33:11 -070096
zhihuang8f65cdf2016-05-06 18:40:30 -070097// The length of RTCP CNAMEs.
98static const int kRtcpCnameLength = 16;
99
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000100enum {
wu@webrtc.org91053e72013-08-10 07:18:04 +0000101 MSG_SET_SESSIONDESCRIPTION_SUCCESS = 0,
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000102 MSG_SET_SESSIONDESCRIPTION_FAILED,
deadbeefab9b2d12015-10-14 11:33:11 -0700103 MSG_CREATE_SESSIONDESCRIPTION_FAILED,
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000104 MSG_GETSTATS,
deadbeefbd292462015-12-14 18:15:29 -0800105 MSG_FREE_DATACHANNELS,
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000106};
107
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000108struct SetSessionDescriptionMsg : public rtc::MessageData {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000109 explicit SetSessionDescriptionMsg(
110 webrtc::SetSessionDescriptionObserver* observer)
111 : observer(observer) {
112 }
113
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000114 rtc::scoped_refptr<webrtc::SetSessionDescriptionObserver> observer;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000115 std::string error;
116};
117
deadbeefab9b2d12015-10-14 11:33:11 -0700118struct CreateSessionDescriptionMsg : public rtc::MessageData {
119 explicit CreateSessionDescriptionMsg(
120 webrtc::CreateSessionDescriptionObserver* observer)
121 : observer(observer) {}
122
123 rtc::scoped_refptr<webrtc::CreateSessionDescriptionObserver> observer;
124 std::string error;
125};
126
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000127struct GetStatsMsg : public rtc::MessageData {
tommi@webrtc.org5b06b062014-08-15 08:38:30 +0000128 GetStatsMsg(webrtc::StatsObserver* observer,
129 webrtc::MediaStreamTrackInterface* track)
130 : observer(observer), track(track) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000131 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000132 rtc::scoped_refptr<webrtc::StatsObserver> observer;
tommi@webrtc.org5b06b062014-08-15 08:38:30 +0000133 rtc::scoped_refptr<webrtc::MediaStreamTrackInterface> track;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000134};
135
deadbeefab9b2d12015-10-14 11:33:11 -0700136// Check if we can send |new_stream| on a PeerConnection.
137bool CanAddLocalMediaStream(webrtc::StreamCollectionInterface* current_streams,
138 webrtc::MediaStreamInterface* new_stream) {
139 if (!new_stream || !current_streams) {
140 return false;
141 }
142 if (current_streams->find(new_stream->label()) != nullptr) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100143 RTC_LOG(LS_ERROR) << "MediaStream with label " << new_stream->label()
144 << " is already added.";
deadbeefab9b2d12015-10-14 11:33:11 -0700145 return false;
146 }
147 return true;
148}
149
150bool MediaContentDirectionHasSend(cricket::MediaContentDirection dir) {
151 return dir == cricket::MD_SENDONLY || dir == cricket::MD_SENDRECV;
152}
153
deadbeef5e97fb52015-10-15 12:49:08 -0700154// If the direction is "recvonly" or "inactive", treat the description
155// as containing no streams.
156// See: https://code.google.com/p/webrtc/issues/detail?id=5054
157std::vector<cricket::StreamParams> GetActiveStreams(
158 const cricket::MediaContentDescription* desc) {
159 return MediaContentDirectionHasSend(desc->direction())
160 ? desc->streams()
161 : std::vector<cricket::StreamParams>();
162}
163
deadbeefab9b2d12015-10-14 11:33:11 -0700164bool IsValidOfferToReceiveMedia(int value) {
165 typedef PeerConnectionInterface::RTCOfferAnswerOptions Options;
166 return (value >= Options::kUndefined) &&
167 (value <= Options::kMaxOfferToReceiveMedia);
168}
169
zhihuang1c378ed2017-08-17 14:10:50 -0700170// Add options to |[audio/video]_media_description_options| from |senders|.
171void AddRtpSenderOptions(
deadbeefa601f5c2016-06-06 14:27:39 -0700172 const std::vector<rtc::scoped_refptr<
173 RtpSenderProxyWithInternal<RtpSenderInternal>>>& senders,
zhihuang1c378ed2017-08-17 14:10:50 -0700174 cricket::MediaDescriptionOptions* audio_media_description_options,
175 cricket::MediaDescriptionOptions* video_media_description_options) {
olka3c747662017-08-17 06:50:32 -0700176 for (const auto& sender : senders) {
zhihuang1c378ed2017-08-17 14:10:50 -0700177 if (sender->media_type() == cricket::MEDIA_TYPE_AUDIO) {
178 if (audio_media_description_options) {
179 audio_media_description_options->AddAudioSender(
Steve Anton8ffb9c32017-08-31 15:45:38 -0700180 sender->id(), sender->internal()->stream_ids());
zhihuang1c378ed2017-08-17 14:10:50 -0700181 }
182 } else {
183 RTC_DCHECK(sender->media_type() == cricket::MEDIA_TYPE_VIDEO);
184 if (video_media_description_options) {
185 video_media_description_options->AddVideoSender(
Steve Anton8ffb9c32017-08-31 15:45:38 -0700186 sender->id(), sender->internal()->stream_ids(), 1);
zhihuang1c378ed2017-08-17 14:10:50 -0700187 }
188 }
zhihuanga77e6bb2017-08-14 18:17:48 -0700189 }
zhihuang1c378ed2017-08-17 14:10:50 -0700190}
olka3c747662017-08-17 06:50:32 -0700191
zhihuang1c378ed2017-08-17 14:10:50 -0700192// Add options to |session_options| from |rtp_data_channels|.
193void AddRtpDataChannelOptions(
194 const std::map<std::string, rtc::scoped_refptr<DataChannel>>&
195 rtp_data_channels,
196 cricket::MediaDescriptionOptions* data_media_description_options) {
197 if (!data_media_description_options) {
198 return;
199 }
deadbeefab9b2d12015-10-14 11:33:11 -0700200 // Check for data channels.
201 for (const auto& kv : rtp_data_channels) {
202 const DataChannel* channel = kv.second;
203 if (channel->state() == DataChannel::kConnecting ||
204 channel->state() == DataChannel::kOpen) {
zhihuang1c378ed2017-08-17 14:10:50 -0700205 // Legacy RTP data channels are signaled with the track/stream ID set to
206 // the data channel's label.
207 data_media_description_options->AddRtpDataChannel(channel->label(),
208 channel->label());
deadbeefab9b2d12015-10-14 11:33:11 -0700209 }
210 }
211}
212
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700213uint32_t ConvertIceTransportTypeToCandidateFilter(
214 PeerConnectionInterface::IceTransportsType type) {
215 switch (type) {
216 case PeerConnectionInterface::kNone:
217 return cricket::CF_NONE;
218 case PeerConnectionInterface::kRelay:
219 return cricket::CF_RELAY;
220 case PeerConnectionInterface::kNoHost:
221 return (cricket::CF_ALL & ~cricket::CF_HOST);
222 case PeerConnectionInterface::kAll:
223 return cricket::CF_ALL;
224 default:
nissec80e7412017-01-11 05:56:46 -0800225 RTC_NOTREACHED();
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700226 }
227 return cricket::CF_NONE;
228}
229
deadbeef293e9262017-01-11 12:28:30 -0800230// Helper to set an error and return from a method.
231bool SafeSetError(webrtc::RTCErrorType type, webrtc::RTCError* error) {
232 if (error) {
233 error->set_type(type);
234 }
235 return type == webrtc::RTCErrorType::NONE;
236}
237
Steve Anton038834f2017-07-14 15:59:59 -0700238bool SafeSetError(webrtc::RTCError error, webrtc::RTCError* error_out) {
239 if (error_out) {
240 *error_out = std::move(error);
241 }
242 return error.ok();
243}
244
Steve Antonba818672017-11-06 10:21:57 -0800245std::string GetSignalingStateString(
246 PeerConnectionInterface::SignalingState state) {
247 switch (state) {
248 case PeerConnectionInterface::kStable:
249 return "kStable";
250 case PeerConnectionInterface::kHaveLocalOffer:
251 return "kHaveLocalOffer";
252 case PeerConnectionInterface::kHaveLocalPrAnswer:
253 return "kHavePrAnswer";
254 case PeerConnectionInterface::kHaveRemoteOffer:
255 return "kHaveRemoteOffer";
256 case PeerConnectionInterface::kHaveRemotePrAnswer:
257 return "kHaveRemotePrAnswer";
258 case PeerConnectionInterface::kClosed:
259 return "kClosed";
260 }
261 RTC_NOTREACHED();
262 return "";
263}
deadbeef0a6c4ca2015-10-06 11:38:28 -0700264
Steve Anton75737c02017-11-06 10:37:17 -0800265IceCandidatePairType GetIceCandidatePairCounter(
266 const cricket::Candidate& local,
267 const cricket::Candidate& remote) {
268 const auto& l = local.type();
269 const auto& r = remote.type();
270 const auto& host = LOCAL_PORT_TYPE;
271 const auto& srflx = STUN_PORT_TYPE;
272 const auto& relay = RELAY_PORT_TYPE;
273 const auto& prflx = PRFLX_PORT_TYPE;
274 if (l == host && r == host) {
275 bool local_private = IPIsPrivate(local.address().ipaddr());
276 bool remote_private = IPIsPrivate(remote.address().ipaddr());
277 if (local_private) {
278 if (remote_private) {
279 return kIceCandidatePairHostPrivateHostPrivate;
280 } else {
281 return kIceCandidatePairHostPrivateHostPublic;
282 }
283 } else {
284 if (remote_private) {
285 return kIceCandidatePairHostPublicHostPrivate;
286 } else {
287 return kIceCandidatePairHostPublicHostPublic;
288 }
289 }
290 }
291 if (l == host && r == srflx)
292 return kIceCandidatePairHostSrflx;
293 if (l == host && r == relay)
294 return kIceCandidatePairHostRelay;
295 if (l == host && r == prflx)
296 return kIceCandidatePairHostPrflx;
297 if (l == srflx && r == host)
298 return kIceCandidatePairSrflxHost;
299 if (l == srflx && r == srflx)
300 return kIceCandidatePairSrflxSrflx;
301 if (l == srflx && r == relay)
302 return kIceCandidatePairSrflxRelay;
303 if (l == srflx && r == prflx)
304 return kIceCandidatePairSrflxPrflx;
305 if (l == relay && r == host)
306 return kIceCandidatePairRelayHost;
307 if (l == relay && r == srflx)
308 return kIceCandidatePairRelaySrflx;
309 if (l == relay && r == relay)
310 return kIceCandidatePairRelayRelay;
311 if (l == relay && r == prflx)
312 return kIceCandidatePairRelayPrflx;
313 if (l == prflx && r == host)
314 return kIceCandidatePairPrflxHost;
315 if (l == prflx && r == srflx)
316 return kIceCandidatePairPrflxSrflx;
317 if (l == prflx && r == relay)
318 return kIceCandidatePairPrflxRelay;
319 return kIceCandidatePairMax;
320}
321
322// Verify that the order of media sections in |new_desc| matches
323// |existing_desc|. The number of m= sections in |new_desc| should be no less
324// than |existing_desc|.
325bool MediaSectionsInSameOrder(const SessionDescription* existing_desc,
326 const SessionDescription* new_desc) {
327 if (!existing_desc || !new_desc) {
328 return false;
329 }
330
331 if (existing_desc->contents().size() > new_desc->contents().size()) {
332 return false;
333 }
334
335 for (size_t i = 0; i < existing_desc->contents().size(); ++i) {
336 if (new_desc->contents()[i].name != existing_desc->contents()[i].name) {
337 return false;
338 }
339 const MediaContentDescription* new_desc_mdesc =
340 static_cast<const MediaContentDescription*>(
341 new_desc->contents()[i].description);
342 const MediaContentDescription* existing_desc_mdesc =
343 static_cast<const MediaContentDescription*>(
344 existing_desc->contents()[i].description);
345 if (new_desc_mdesc->type() != existing_desc_mdesc->type()) {
346 return false;
347 }
348 }
349 return true;
350}
351
352bool MediaSectionsHaveSameCount(const SessionDescription* desc1,
353 const SessionDescription* desc2) {
354 if (!desc1 || !desc2) {
355 return false;
356 }
357 return desc1->contents().size() == desc2->contents().size();
358}
359
360// Checks that each non-rejected content has SDES crypto keys or a DTLS
361// fingerprint, unless it's in a BUNDLE group, in which case only the
362// BUNDLE-tag section (first media section/description in the BUNDLE group)
363// needs a ufrag and pwd. Mismatches, such as replying with a DTLS fingerprint
364// to SDES keys, will be caught in JsepTransport negotiation, and backstopped
365// by Channel's |srtp_required| check.
366bool VerifyCrypto(const SessionDescription* desc,
367 bool dtls_enabled,
368 std::string* error) {
369 const cricket::ContentGroup* bundle =
370 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
371 const ContentInfos& contents = desc->contents();
372 for (size_t index = 0; index < contents.size(); ++index) {
373 const ContentInfo* cinfo = &contents[index];
374 if (cinfo->rejected) {
375 continue;
376 }
377 if (bundle && bundle->HasContentName(cinfo->name) &&
378 cinfo->name != *(bundle->FirstContentName())) {
379 // This isn't the first media section in the BUNDLE group, so it's not
380 // required to have crypto attributes, since only the crypto attributes
381 // from the first section actually get used.
382 continue;
383 }
384
385 // If the content isn't rejected or bundled into another m= section, crypto
386 // must be present.
387 const MediaContentDescription* media =
388 static_cast<const MediaContentDescription*>(cinfo->description);
389 const TransportInfo* tinfo = desc->GetTransportInfoByName(cinfo->name);
390 if (!media || !tinfo) {
391 // Something is not right.
Mirko Bonadei675513b2017-11-09 11:09:25 +0100392 RTC_LOG(LS_ERROR) << kInvalidSdp;
Steve Anton75737c02017-11-06 10:37:17 -0800393 *error = kInvalidSdp;
394 return false;
395 }
396 if (dtls_enabled) {
397 if (!tinfo->description.identity_fingerprint) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100398 RTC_LOG(LS_WARNING)
399 << "Session description must have DTLS fingerprint if "
400 "DTLS enabled.";
Steve Anton75737c02017-11-06 10:37:17 -0800401 *error = kSdpWithoutDtlsFingerprint;
402 return false;
403 }
404 } else {
405 if (media->cryptos().empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100406 RTC_LOG(LS_WARNING)
Steve Anton75737c02017-11-06 10:37:17 -0800407 << "Session description must have SDES when DTLS disabled.";
408 *error = kSdpWithoutSdesCrypto;
409 return false;
410 }
411 }
412 }
413
414 return true;
415}
416
417// Checks that each non-rejected content has ice-ufrag and ice-pwd set, unless
418// it's in a BUNDLE group, in which case only the BUNDLE-tag section (first
419// media section/description in the BUNDLE group) needs a ufrag and pwd.
420bool VerifyIceUfragPwdPresent(const SessionDescription* desc) {
421 const cricket::ContentGroup* bundle =
422 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
423 const ContentInfos& contents = desc->contents();
424 for (size_t index = 0; index < contents.size(); ++index) {
425 const ContentInfo* cinfo = &contents[index];
426 if (cinfo->rejected) {
427 continue;
428 }
429 if (bundle && bundle->HasContentName(cinfo->name) &&
430 cinfo->name != *(bundle->FirstContentName())) {
431 // This isn't the first media section in the BUNDLE group, so it's not
432 // required to have ufrag/password, since only the ufrag/password from
433 // the first section actually get used.
434 continue;
435 }
436
437 // If the content isn't rejected or bundled into another m= section,
438 // ice-ufrag and ice-pwd must be present.
439 const TransportInfo* tinfo = desc->GetTransportInfoByName(cinfo->name);
440 if (!tinfo) {
441 // Something is not right.
Mirko Bonadei675513b2017-11-09 11:09:25 +0100442 RTC_LOG(LS_ERROR) << kInvalidSdp;
Steve Anton75737c02017-11-06 10:37:17 -0800443 return false;
444 }
445 if (tinfo->description.ice_ufrag.empty() ||
446 tinfo->description.ice_pwd.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100447 RTC_LOG(LS_ERROR) << "Session description must have ice ufrag and pwd.";
Steve Anton75737c02017-11-06 10:37:17 -0800448 return false;
449 }
450 }
451 return true;
452}
453
454bool GetTrackIdBySsrc(const SessionDescription* session_description,
455 uint32_t ssrc,
456 std::string* track_id) {
457 RTC_DCHECK(track_id != NULL);
458
459 const cricket::ContentInfo* audio_info =
460 cricket::GetFirstAudioContent(session_description);
461 if (audio_info) {
462 const cricket::MediaContentDescription* audio_content =
463 static_cast<const cricket::MediaContentDescription*>(
464 audio_info->description);
465
466 const auto* found =
467 cricket::GetStreamBySsrc(audio_content->streams(), ssrc);
468 if (found) {
469 *track_id = found->id;
470 return true;
471 }
472 }
473
474 const cricket::ContentInfo* video_info =
475 cricket::GetFirstVideoContent(session_description);
476 if (video_info) {
477 const cricket::MediaContentDescription* video_content =
478 static_cast<const cricket::MediaContentDescription*>(
479 video_info->description);
480
481 const auto* found =
482 cricket::GetStreamBySsrc(video_content->streams(), ssrc);
483 if (found) {
484 *track_id = found->id;
485 return true;
486 }
487 }
488 return false;
489}
490
491// Get the SCTP port out of a SessionDescription.
492// Return -1 if not found.
493int GetSctpPort(const SessionDescription* session_description) {
494 const ContentInfo* content_info = GetFirstDataContent(session_description);
495 RTC_DCHECK(content_info);
496 if (!content_info) {
497 return -1;
498 }
499 const cricket::DataContentDescription* data =
500 static_cast<const cricket::DataContentDescription*>(
501 (content_info->description));
502 std::string value;
503 cricket::DataCodec match_pattern(cricket::kGoogleSctpDataCodecPlType,
504 cricket::kGoogleSctpDataCodecName);
505 for (const cricket::DataCodec& codec : data->codecs()) {
506 if (!codec.Matches(match_pattern)) {
507 continue;
508 }
509 if (codec.GetParam(cricket::kCodecParamPort, &value)) {
510 return rtc::FromString<int>(value);
511 }
512 }
513 return -1;
514}
515
516bool BadSdp(const std::string& source,
517 const std::string& type,
518 const std::string& reason,
519 std::string* err_desc) {
520 std::ostringstream desc;
521 desc << "Failed to set " << source;
522 if (!type.empty()) {
523 desc << " " << type;
524 }
525 desc << " sdp: " << reason;
526
527 if (err_desc) {
528 *err_desc = desc.str();
529 }
Mirko Bonadei675513b2017-11-09 11:09:25 +0100530 RTC_LOG(LS_ERROR) << desc.str();
Steve Anton75737c02017-11-06 10:37:17 -0800531 return false;
532}
533
534bool BadSdp(cricket::ContentSource source,
535 const std::string& type,
536 const std::string& reason,
537 std::string* err_desc) {
538 if (source == cricket::CS_LOCAL) {
539 return BadSdp("local", type, reason, err_desc);
540 } else {
541 return BadSdp("remote", type, reason, err_desc);
542 }
543}
544
545bool BadLocalSdp(const std::string& type,
546 const std::string& reason,
547 std::string* err_desc) {
548 return BadSdp(cricket::CS_LOCAL, type, reason, err_desc);
549}
550
551bool BadRemoteSdp(const std::string& type,
552 const std::string& reason,
553 std::string* err_desc) {
554 return BadSdp(cricket::CS_REMOTE, type, reason, err_desc);
555}
556
557bool BadOfferSdp(cricket::ContentSource source,
558 const std::string& reason,
559 std::string* err_desc) {
560 return BadSdp(source, SessionDescriptionInterface::kOffer, reason, err_desc);
561}
562
563bool BadPranswerSdp(cricket::ContentSource source,
564 const std::string& reason,
565 std::string* err_desc) {
566 return BadSdp(source, SessionDescriptionInterface::kPrAnswer, reason,
567 err_desc);
568}
569
570bool BadAnswerSdp(cricket::ContentSource source,
571 const std::string& reason,
572 std::string* err_desc) {
573 return BadSdp(source, SessionDescriptionInterface::kAnswer, reason, err_desc);
574}
575
576std::string BadStateErrMsg(PeerConnectionInterface::SignalingState state) {
577 std::ostringstream desc;
578 desc << "Called in wrong state: " << GetSignalingStateString(state);
579 return desc.str();
580}
581
582#define GET_STRING_OF_ERROR_CODE(err) \
583 case webrtc::PeerConnection::err: \
584 result = #err; \
585 break;
586
587std::string GetErrorCodeString(webrtc::PeerConnection::Error err) {
588 std::string result;
589 switch (err) {
590 GET_STRING_OF_ERROR_CODE(ERROR_NONE)
591 GET_STRING_OF_ERROR_CODE(ERROR_CONTENT)
592 GET_STRING_OF_ERROR_CODE(ERROR_TRANSPORT)
593 default:
594 RTC_NOTREACHED();
595 break;
596 }
597 return result;
598}
599
600std::string MakeErrorString(const std::string& error, const std::string& desc) {
601 std::ostringstream ret;
602 ret << error << " " << desc;
603 return ret.str();
604}
605
606std::string MakeTdErrorString(const std::string& desc) {
607 return MakeErrorString(kPushDownTDFailed, desc);
608}
609
610// Returns true if |new_desc| requests an ICE restart (i.e., new ufrag/pwd).
611bool CheckForRemoteIceRestart(const SessionDescriptionInterface* old_desc,
612 const SessionDescriptionInterface* new_desc,
613 const std::string& content_name) {
614 if (!old_desc) {
615 return false;
616 }
617 const SessionDescription* new_sd = new_desc->description();
618 const SessionDescription* old_sd = old_desc->description();
619 const ContentInfo* cinfo = new_sd->GetContentByName(content_name);
620 if (!cinfo || cinfo->rejected) {
621 return false;
622 }
623 // If the content isn't rejected, check if ufrag and password has changed.
624 const cricket::TransportDescription* new_transport_desc =
625 new_sd->GetTransportDescriptionByName(content_name);
626 const cricket::TransportDescription* old_transport_desc =
627 old_sd->GetTransportDescriptionByName(content_name);
628 if (!new_transport_desc || !old_transport_desc) {
629 // No transport description exists. This is not an ICE restart.
630 return false;
631 }
632 if (cricket::IceCredentialsChanged(
633 old_transport_desc->ice_ufrag, old_transport_desc->ice_pwd,
634 new_transport_desc->ice_ufrag, new_transport_desc->ice_pwd)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100635 RTC_LOG(LS_INFO) << "Remote peer requests ICE restart for " << content_name
636 << ".";
Steve Anton75737c02017-11-06 10:37:17 -0800637 return true;
638 }
639 return false;
640}
641
642} // namespace
643
deadbeef293e9262017-01-11 12:28:30 -0800644bool PeerConnectionInterface::RTCConfiguration::operator==(
645 const PeerConnectionInterface::RTCConfiguration& o) const {
646 // This static_assert prevents us from accidentally breaking operator==.
Steve Anton300bf8e2017-07-14 10:13:10 -0700647 // Note: Order matters! Fields must be ordered the same as RTCConfiguration.
deadbeef293e9262017-01-11 12:28:30 -0800648 struct stuff_being_tested_for_equality {
Magnus Jedvert3beb2072017-07-14 14:23:56 +0000649 IceServers servers;
Steve Anton300bf8e2017-07-14 10:13:10 -0700650 IceTransportsType type;
deadbeef293e9262017-01-11 12:28:30 -0800651 BundlePolicy bundle_policy;
652 RtcpMuxPolicy rtcp_mux_policy;
Steve Anton300bf8e2017-07-14 10:13:10 -0700653 std::vector<rtc::scoped_refptr<rtc::RTCCertificate>> certificates;
654 int ice_candidate_pool_size;
655 bool disable_ipv6;
656 bool disable_ipv6_on_wifi;
deadbeefd21eab32017-07-26 16:50:11 -0700657 int max_ipv6_networks;
Steve Anton300bf8e2017-07-14 10:13:10 -0700658 bool enable_rtp_data_channel;
659 rtc::Optional<int> screencast_min_bitrate;
660 rtc::Optional<bool> combined_audio_video_bwe;
661 rtc::Optional<bool> enable_dtls_srtp;
deadbeef293e9262017-01-11 12:28:30 -0800662 TcpCandidatePolicy tcp_candidate_policy;
663 CandidateNetworkPolicy candidate_network_policy;
664 int audio_jitter_buffer_max_packets;
665 bool audio_jitter_buffer_fast_accelerate;
666 int ice_connection_receiving_timeout;
667 int ice_backup_candidate_pair_ping_interval;
668 ContinualGatheringPolicy continual_gathering_policy;
deadbeef293e9262017-01-11 12:28:30 -0800669 bool prioritize_most_likely_ice_candidate_pairs;
670 struct cricket::MediaConfig media_config;
deadbeef293e9262017-01-11 12:28:30 -0800671 bool prune_turn_ports;
672 bool presume_writable_when_fully_relayed;
673 bool enable_ice_renomination;
674 bool redetermine_role_on_ice_restart;
skvlad51072462017-02-02 11:50:14 -0800675 rtc::Optional<int> ice_check_min_interval;
Steve Anton300bf8e2017-07-14 10:13:10 -0700676 rtc::Optional<rtc::IntervalRange> ice_regather_interval_range;
Jonas Orelandbdcee282017-10-10 14:01:40 +0200677 webrtc::TurnCustomizer* turn_customizer;
Steve Anton79e79602017-11-20 10:25:56 -0800678 SdpSemantics sdp_semantics;
deadbeef293e9262017-01-11 12:28:30 -0800679 };
680 static_assert(sizeof(stuff_being_tested_for_equality) == sizeof(*this),
681 "Did you add something to RTCConfiguration and forget to "
682 "update operator==?");
683 return type == o.type && servers == o.servers &&
684 bundle_policy == o.bundle_policy &&
685 rtcp_mux_policy == o.rtcp_mux_policy &&
686 tcp_candidate_policy == o.tcp_candidate_policy &&
687 candidate_network_policy == o.candidate_network_policy &&
688 audio_jitter_buffer_max_packets == o.audio_jitter_buffer_max_packets &&
689 audio_jitter_buffer_fast_accelerate ==
690 o.audio_jitter_buffer_fast_accelerate &&
691 ice_connection_receiving_timeout ==
692 o.ice_connection_receiving_timeout &&
693 ice_backup_candidate_pair_ping_interval ==
694 o.ice_backup_candidate_pair_ping_interval &&
695 continual_gathering_policy == o.continual_gathering_policy &&
696 certificates == o.certificates &&
697 prioritize_most_likely_ice_candidate_pairs ==
698 o.prioritize_most_likely_ice_candidate_pairs &&
699 media_config == o.media_config && disable_ipv6 == o.disable_ipv6 &&
zhihuangb09b3f92017-03-07 14:40:51 -0800700 disable_ipv6_on_wifi == o.disable_ipv6_on_wifi &&
deadbeefd21eab32017-07-26 16:50:11 -0700701 max_ipv6_networks == o.max_ipv6_networks &&
deadbeef293e9262017-01-11 12:28:30 -0800702 enable_rtp_data_channel == o.enable_rtp_data_channel &&
deadbeef293e9262017-01-11 12:28:30 -0800703 screencast_min_bitrate == o.screencast_min_bitrate &&
704 combined_audio_video_bwe == o.combined_audio_video_bwe &&
705 enable_dtls_srtp == o.enable_dtls_srtp &&
706 ice_candidate_pool_size == o.ice_candidate_pool_size &&
707 prune_turn_ports == o.prune_turn_ports &&
708 presume_writable_when_fully_relayed ==
709 o.presume_writable_when_fully_relayed &&
710 enable_ice_renomination == o.enable_ice_renomination &&
skvlad51072462017-02-02 11:50:14 -0800711 redetermine_role_on_ice_restart == o.redetermine_role_on_ice_restart &&
Steve Anton300bf8e2017-07-14 10:13:10 -0700712 ice_check_min_interval == o.ice_check_min_interval &&
Jonas Orelandbdcee282017-10-10 14:01:40 +0200713 ice_regather_interval_range == o.ice_regather_interval_range &&
Steve Anton79e79602017-11-20 10:25:56 -0800714 turn_customizer == o.turn_customizer &&
715 sdp_semantics == o.sdp_semantics;
deadbeef293e9262017-01-11 12:28:30 -0800716}
717
718bool PeerConnectionInterface::RTCConfiguration::operator!=(
719 const PeerConnectionInterface::RTCConfiguration& o) const {
720 return !(*this == o);
deadbeef3edec7c2016-12-10 11:44:26 -0800721}
722
zhihuang8f65cdf2016-05-06 18:40:30 -0700723// Generate a RTCP CNAME when a PeerConnection is created.
724std::string GenerateRtcpCname() {
725 std::string cname;
726 if (!rtc::CreateRandomString(kRtcpCnameLength, &cname)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100727 RTC_LOG(LS_ERROR) << "Failed to generate CNAME.";
nisseeb4ca4e2017-01-12 02:24:27 -0800728 RTC_NOTREACHED();
zhihuang8f65cdf2016-05-06 18:40:30 -0700729 }
730 return cname;
731}
732
zhihuang1c378ed2017-08-17 14:10:50 -0700733bool ValidateOfferAnswerOptions(
734 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options) {
735 return IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_audio) &&
736 IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_video);
olka3c747662017-08-17 06:50:32 -0700737}
738
zhihuang1c378ed2017-08-17 14:10:50 -0700739// From |rtc_options|, fill parts of |session_options| shared by all generated
740// m= sections (in other words, nothing that involves a map/array).
741void ExtractSharedMediaSessionOptions(
742 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options,
743 cricket::MediaSessionOptions* session_options) {
744 session_options->vad_enabled = rtc_options.voice_activity_detection;
745 session_options->bundle_enabled = rtc_options.use_rtp_mux;
746}
zhihuanga77e6bb2017-08-14 18:17:48 -0700747
zhihuang1c378ed2017-08-17 14:10:50 -0700748bool ConvertConstraintsToOfferAnswerOptions(
749 const MediaConstraintsInterface* constraints,
750 PeerConnectionInterface::RTCOfferAnswerOptions* offer_answer_options) {
olka3c747662017-08-17 06:50:32 -0700751 if (!constraints) {
752 return true;
753 }
zhihuang1c378ed2017-08-17 14:10:50 -0700754
755 bool value = false;
756 size_t mandatory_constraints_satisfied = 0;
757
758 if (FindConstraint(constraints,
759 MediaConstraintsInterface::kOfferToReceiveAudio, &value,
760 &mandatory_constraints_satisfied)) {
761 offer_answer_options->offer_to_receive_audio =
762 value ? PeerConnectionInterface::RTCOfferAnswerOptions::
763 kOfferToReceiveMediaTrue
764 : 0;
765 }
766
767 if (FindConstraint(constraints,
768 MediaConstraintsInterface::kOfferToReceiveVideo, &value,
769 &mandatory_constraints_satisfied)) {
770 offer_answer_options->offer_to_receive_video =
771 value ? PeerConnectionInterface::RTCOfferAnswerOptions::
772 kOfferToReceiveMediaTrue
773 : 0;
774 }
775 if (FindConstraint(constraints,
776 MediaConstraintsInterface::kVoiceActivityDetection, &value,
777 &mandatory_constraints_satisfied)) {
778 offer_answer_options->voice_activity_detection = value;
779 }
780 if (FindConstraint(constraints, MediaConstraintsInterface::kUseRtpMux, &value,
781 &mandatory_constraints_satisfied)) {
782 offer_answer_options->use_rtp_mux = value;
783 }
784 if (FindConstraint(constraints, MediaConstraintsInterface::kIceRestart,
785 &value, &mandatory_constraints_satisfied)) {
786 offer_answer_options->ice_restart = value;
787 }
788
deadbeefab9b2d12015-10-14 11:33:11 -0700789 return mandatory_constraints_satisfied == constraints->GetMandatory().size();
790}
791
zhihuang38ede132017-06-15 12:52:32 -0700792PeerConnection::PeerConnection(PeerConnectionFactory* factory,
793 std::unique_ptr<RtcEventLog> event_log,
794 std::unique_ptr<Call> call)
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000795 : factory_(factory),
zhihuang38ede132017-06-15 12:52:32 -0700796 event_log_(std::move(event_log)),
zhihuang8f65cdf2016-05-06 18:40:30 -0700797 rtcp_cname_(GenerateRtcpCname()),
deadbeefab9b2d12015-10-14 11:33:11 -0700798 local_streams_(StreamCollection::Create()),
zhihuang38ede132017-06-15 12:52:32 -0700799 remote_streams_(StreamCollection::Create()),
800 call_(std::move(call)) {}
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000801
802PeerConnection::~PeerConnection() {
Peter Boström1a9d6152015-12-08 22:15:17 +0100803 TRACE_EVENT0("webrtc", "PeerConnection::~PeerConnection");
Steve Anton4171afb2017-11-20 10:20:22 -0800804 RTC_DCHECK_RUN_ON(signaling_thread());
805
806 // Need to detach RTP transceivers from PeerConnection, since it's about to be
807 // destroyed.
808 for (auto transceiver : transceivers_) {
809 transceiver->Stop();
deadbeef70ab1a12015-09-28 16:53:55 -0700810 }
Steve Anton4171afb2017-11-20 10:20:22 -0800811
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700812 // Destroy stats_ because it depends on session_.
813 stats_.reset(nullptr);
hbosb78306a2016-12-19 05:06:57 -0800814 if (stats_collector_) {
815 stats_collector_->WaitForPendingRequest();
816 stats_collector_ = nullptr;
817 }
Steve Anton75737c02017-11-06 10:37:17 -0800818
819 // Destroy video channels first since they may have a pointer to a voice
820 // channel.
Steve Anton4171afb2017-11-20 10:20:22 -0800821 for (auto transceiver : transceivers_) {
822 if (transceiver->internal()->media_type() == cricket::MEDIA_TYPE_VIDEO &&
823 transceiver->internal()->channel()) {
824 DestroyVideoChannel(static_cast<cricket::VideoChannel*>(
825 transceiver->internal()->channel()));
826 }
Steve Anton75737c02017-11-06 10:37:17 -0800827 }
Steve Anton4171afb2017-11-20 10:20:22 -0800828 for (auto transceiver : transceivers_) {
829 if (transceiver->internal()->media_type() == cricket::MEDIA_TYPE_AUDIO &&
830 transceiver->internal()->channel()) {
831 DestroyVoiceChannel(static_cast<cricket::VoiceChannel*>(
832 transceiver->internal()->channel()));
833 }
Steve Anton75737c02017-11-06 10:37:17 -0800834 }
835 if (rtp_data_channel_) {
836 DestroyDataChannel();
837 }
838
839 // Note: Cannot use rtc::Bind to create a functor to invoke because it will
840 // grab a reference to this PeerConnection. The RefCountedObject vtable will
841 // have already been destroyed (since it is a subclass of PeerConnection) and
842 // using rtc::Bind will cause "Pure virtual function called" error to appear.
843
844 if (sctp_transport_) {
845 OnDataChannelDestroyed();
846 network_thread()->Invoke<void>(RTC_FROM_HERE,
847 [this] { DestroySctpTransport_n(); });
848 }
849
Mirko Bonadei675513b2017-11-09 11:09:25 +0100850 RTC_LOG(LS_INFO) << "Session: " << session_id() << " is destroyed.";
Steve Anton75737c02017-11-06 10:37:17 -0800851
852 webrtc_session_desc_factory_.reset();
853 sctp_invoker_.reset();
854 sctp_factory_.reset();
855 transport_controller_.reset();
856
deadbeef91dd5672016-05-18 16:55:30 -0700857 // port_allocator_ lives on the network thread and should be destroyed there.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700858 network_thread()->Invoke<void>(RTC_FROM_HERE,
nisseeaabdf62017-05-05 02:23:02 -0700859 [this] { port_allocator_.reset(); });
eladalon248fd4f2017-09-06 05:18:15 -0700860 // call_ and event_log_ must be destroyed on the worker thread.
Steve Anton978b8762017-09-29 12:15:02 -0700861 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
eladalon248fd4f2017-09-06 05:18:15 -0700862 call_.reset();
863 event_log_.reset();
864 });
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000865}
866
867bool PeerConnection::Initialize(
buildbot@webrtc.org41451d42014-05-03 05:39:45 +0000868 const PeerConnectionInterface::RTCConfiguration& configuration,
kwibergd1fe2812016-04-27 06:47:29 -0700869 std::unique_ptr<cricket::PortAllocator> allocator,
Henrik Boströmd03c23b2016-06-01 11:44:18 +0200870 std::unique_ptr<rtc::RTCCertificateGeneratorInterface> cert_generator,
deadbeef653b8e02015-11-11 12:55:10 -0800871 PeerConnectionObserver* observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100872 TRACE_EVENT0("webrtc", "PeerConnection::Initialize");
Steve Anton038834f2017-07-14 15:59:59 -0700873
874 RTCError config_error = ValidateConfiguration(configuration);
875 if (!config_error.ok()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100876 RTC_LOG(LS_ERROR) << "Invalid configuration: " << config_error.message();
Steve Anton038834f2017-07-14 15:59:59 -0700877 return false;
878 }
879
deadbeef293e9262017-01-11 12:28:30 -0800880 if (!allocator) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100881 RTC_LOG(LS_ERROR)
882 << "PeerConnection initialized without a PortAllocator? "
883 << "This shouldn't happen if using PeerConnectionFactory.";
deadbeef293e9262017-01-11 12:28:30 -0800884 return false;
885 }
Jonas Orelandbdcee282017-10-10 14:01:40 +0200886
deadbeef653b8e02015-11-11 12:55:10 -0800887 if (!observer) {
deadbeef293e9262017-01-11 12:28:30 -0800888 // TODO(deadbeef): Why do we do this?
Mirko Bonadei675513b2017-11-09 11:09:25 +0100889 RTC_LOG(LS_ERROR) << "PeerConnection initialized without a "
890 << "PeerConnectionObserver";
deadbeef653b8e02015-11-11 12:55:10 -0800891 return false;
892 }
pthatcher@webrtc.org877ac762015-02-04 22:03:09 +0000893 observer_ = observer;
kwiberg0eb15ed2015-12-17 03:04:15 -0800894 port_allocator_ = std::move(allocator);
deadbeef653b8e02015-11-11 12:55:10 -0800895
deadbeef91dd5672016-05-18 16:55:30 -0700896 // The port allocator lives on the network thread and should be initialized
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700897 // there.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700898 if (!network_thread()->Invoke<bool>(
899 RTC_FROM_HERE, rtc::Bind(&PeerConnection::InitializePortAllocator_n,
900 this, configuration))) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000901 return false;
902 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000903
Steve Anton75737c02017-11-06 10:37:17 -0800904 // RFC 3264: The numeric value of the session id and version in the
905 // o line MUST be representable with a "64 bit signed integer".
906 // Due to this constraint session id |session_id_| is max limited to
907 // LLONG_MAX.
908 session_id_ = rtc::ToString(rtc::CreateRandomId64() & LLONG_MAX);
909 transport_controller_.reset(factory_->CreateTransportController(
910 port_allocator_.get(), configuration.redetermine_role_on_ice_restart));
911 transport_controller_->SetIceRole(cricket::ICEROLE_CONTROLLED);
912 transport_controller_->SignalConnectionState.connect(
913 this, &PeerConnection::OnTransportControllerConnectionState);
914 transport_controller_->SignalGatheringState.connect(
915 this, &PeerConnection::OnTransportControllerGatheringState);
916 transport_controller_->SignalCandidatesGathered.connect(
917 this, &PeerConnection::OnTransportControllerCandidatesGathered);
918 transport_controller_->SignalCandidatesRemoved.connect(
919 this, &PeerConnection::OnTransportControllerCandidatesRemoved);
920 transport_controller_->SignalDtlsHandshakeError.connect(
921 this, &PeerConnection::OnTransportControllerDtlsHandshakeError);
922
923 sctp_factory_ = factory_->CreateSctpTransportInternalFactory();
zhihuang29ff8442016-07-27 11:07:25 -0700924
deadbeefab9b2d12015-10-14 11:33:11 -0700925 stats_.reset(new StatsCollector(this));
hbos74e1a4f2016-09-15 23:33:01 -0700926 stats_collector_ = RTCStatsCollector::Create(this);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000927
Steve Antonba818672017-11-06 10:21:57 -0800928 configuration_ = configuration;
929
Steve Anton75737c02017-11-06 10:37:17 -0800930 const PeerConnectionFactoryInterface::Options& options = factory_->options();
931
932 transport_controller_->SetSslMaxProtocolVersion(options.ssl_max_version);
933
934 // Obtain a certificate from RTCConfiguration if any were provided (optional).
935 rtc::scoped_refptr<rtc::RTCCertificate> certificate;
936 if (!configuration.certificates.empty()) {
937 // TODO(hbos,torbjorng): Decide on certificate-selection strategy instead of
938 // just picking the first one. The decision should be made based on the DTLS
939 // handshake. The DTLS negotiations need to know about all certificates.
940 certificate = configuration.certificates[0];
941 }
942
Steve Antond25da372017-11-06 14:50:29 -0800943 transport_controller_->SetIceConfig(ParseIceConfig(configuration));
Steve Anton75737c02017-11-06 10:37:17 -0800944
945 if (options.disable_encryption) {
946 dtls_enabled_ = false;
947 } else {
948 // Enable DTLS by default if we have an identity store or a certificate.
949 dtls_enabled_ = (cert_generator || certificate);
950 // |configuration| can override the default |dtls_enabled_| value.
951 if (configuration.enable_dtls_srtp) {
952 dtls_enabled_ = *(configuration.enable_dtls_srtp);
953 }
954 }
955
956 // Enable creation of RTP data channels if the kEnableRtpDataChannels is set.
957 // It takes precendence over the disable_sctp_data_channels
958 // PeerConnectionFactoryInterface::Options.
959 if (configuration.enable_rtp_data_channel) {
960 data_channel_type_ = cricket::DCT_RTP;
961 } else {
962 // DTLS has to be enabled to use SCTP.
963 if (!options.disable_sctp_data_channels && dtls_enabled_) {
964 data_channel_type_ = cricket::DCT_SCTP;
965 }
966 }
967
968 video_options_.screencast_min_bitrate_kbps =
969 configuration.screencast_min_bitrate;
970 audio_options_.combined_audio_video_bwe =
971 configuration.combined_audio_video_bwe;
972
973 audio_options_.audio_jitter_buffer_max_packets =
974 rtc::Optional<int>(configuration.audio_jitter_buffer_max_packets);
975
976 audio_options_.audio_jitter_buffer_fast_accelerate =
977 rtc::Optional<bool>(configuration.audio_jitter_buffer_fast_accelerate);
978
979 // Whether the certificate generator/certificate is null or not determines
980 // what PeerConnectionDescriptionFactory will do, so make sure that we give it
981 // the right instructions by clearing the variables if needed.
982 if (!dtls_enabled_) {
983 cert_generator.reset();
984 certificate = nullptr;
985 } else if (certificate) {
986 // Favor generated certificate over the certificate generator.
987 cert_generator.reset();
988 }
989
990 webrtc_session_desc_factory_.reset(new WebRtcSessionDescriptionFactory(
991 signaling_thread(), channel_manager(), this, session_id(),
992 std::move(cert_generator), certificate));
993 webrtc_session_desc_factory_->SignalCertificateReady.connect(
994 this, &PeerConnection::OnCertificateReady);
995
996 if (options.disable_encryption) {
997 webrtc_session_desc_factory_->SetSdesPolicy(cricket::SEC_DISABLED);
998 }
999
1000 webrtc_session_desc_factory_->set_enable_encrypted_rtp_header_extensions(
1001 options.crypto_options.enable_encrypted_rtp_header_extensions);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001002
Steve Anton4171afb2017-11-20 10:20:22 -08001003 // Add default audio/video transceivers for Plan B SDP.
1004 if (!IsUnifiedPlan()) {
1005 transceivers_.push_back(
1006 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1007 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_AUDIO)));
1008 transceivers_.push_back(
1009 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1010 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_VIDEO)));
1011 }
1012
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001013 return true;
1014}
1015
Steve Anton038834f2017-07-14 15:59:59 -07001016RTCError PeerConnection::ValidateConfiguration(
1017 const RTCConfiguration& config) const {
1018 if (config.ice_regather_interval_range &&
1019 config.continual_gathering_policy == GATHER_ONCE) {
1020 return RTCError(RTCErrorType::INVALID_PARAMETER,
1021 "ice_regather_interval_range specified but continual "
1022 "gathering policy is GATHER_ONCE");
1023 }
1024 return RTCError::OK();
1025}
1026
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001027rtc::scoped_refptr<StreamCollectionInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001028PeerConnection::local_streams() {
deadbeefab9b2d12015-10-14 11:33:11 -07001029 return local_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001030}
1031
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001032rtc::scoped_refptr<StreamCollectionInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001033PeerConnection::remote_streams() {
deadbeefab9b2d12015-10-14 11:33:11 -07001034 return remote_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001035}
1036
perkj@webrtc.orgc2dd5ee2014-11-04 11:31:29 +00001037bool PeerConnection::AddStream(MediaStreamInterface* local_stream) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001038 TRACE_EVENT0("webrtc", "PeerConnection::AddStream");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001039 if (IsClosed()) {
1040 return false;
1041 }
deadbeefab9b2d12015-10-14 11:33:11 -07001042 if (!CanAddLocalMediaStream(local_streams_, local_stream)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001043 return false;
1044 }
deadbeefab9b2d12015-10-14 11:33:11 -07001045
1046 local_streams_->AddStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -08001047 MediaStreamObserver* observer = new MediaStreamObserver(local_stream);
1048 observer->SignalAudioTrackAdded.connect(this,
1049 &PeerConnection::OnAudioTrackAdded);
1050 observer->SignalAudioTrackRemoved.connect(
1051 this, &PeerConnection::OnAudioTrackRemoved);
1052 observer->SignalVideoTrackAdded.connect(this,
1053 &PeerConnection::OnVideoTrackAdded);
1054 observer->SignalVideoTrackRemoved.connect(
1055 this, &PeerConnection::OnVideoTrackRemoved);
kwibergd1fe2812016-04-27 06:47:29 -07001056 stream_observers_.push_back(std::unique_ptr<MediaStreamObserver>(observer));
deadbeefab9b2d12015-10-14 11:33:11 -07001057
deadbeefab9b2d12015-10-14 11:33:11 -07001058 for (const auto& track : local_stream->GetAudioTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001059 AddAudioTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -07001060 }
1061 for (const auto& track : local_stream->GetVideoTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001062 AddVideoTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -07001063 }
1064
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001065 stats_->AddStream(local_stream);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001066 observer_->OnRenegotiationNeeded();
1067 return true;
1068}
1069
1070void PeerConnection::RemoveStream(MediaStreamInterface* local_stream) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001071 TRACE_EVENT0("webrtc", "PeerConnection::RemoveStream");
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001072 if (!IsClosed()) {
1073 for (const auto& track : local_stream->GetAudioTracks()) {
1074 RemoveAudioTrack(track.get(), local_stream);
1075 }
1076 for (const auto& track : local_stream->GetVideoTracks()) {
1077 RemoveVideoTrack(track.get(), local_stream);
1078 }
deadbeefab9b2d12015-10-14 11:33:11 -07001079 }
deadbeefab9b2d12015-10-14 11:33:11 -07001080 local_streams_->RemoveStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -08001081 stream_observers_.erase(
1082 std::remove_if(
1083 stream_observers_.begin(), stream_observers_.end(),
kwibergd1fe2812016-04-27 06:47:29 -07001084 [local_stream](const std::unique_ptr<MediaStreamObserver>& observer) {
deadbeefeb459812015-12-15 19:24:43 -08001085 return observer->stream()->label().compare(local_stream->label()) ==
1086 0;
1087 }),
1088 stream_observers_.end());
deadbeefab9b2d12015-10-14 11:33:11 -07001089
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001090 if (IsClosed()) {
1091 return;
1092 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001093 observer_->OnRenegotiationNeeded();
1094}
1095
deadbeefe1f9d832016-01-14 15:35:42 -08001096rtc::scoped_refptr<RtpSenderInterface> PeerConnection::AddTrack(
1097 MediaStreamTrackInterface* track,
1098 std::vector<MediaStreamInterface*> streams) {
1099 TRACE_EVENT0("webrtc", "PeerConnection::AddTrack");
1100 if (IsClosed()) {
1101 return nullptr;
1102 }
1103 if (streams.size() >= 2) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001104 RTC_LOG(LS_ERROR)
deadbeefe1f9d832016-01-14 15:35:42 -08001105 << "Adding a track with two streams is not currently supported.";
1106 return nullptr;
1107 }
Steve Anton4171afb2017-11-20 10:20:22 -08001108 if (FindSenderForTrack(track)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001109 RTC_LOG(LS_ERROR) << "Sender for track " << track->id()
1110 << " already exists.";
deadbeefe1f9d832016-01-14 15:35:42 -08001111 return nullptr;
1112 }
1113
1114 // TODO(deadbeef): Support adding a track to multiple streams.
deadbeefa601f5c2016-06-06 14:27:39 -07001115 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender;
deadbeefe1f9d832016-01-14 15:35:42 -08001116 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
deadbeefa601f5c2016-06-06 14:27:39 -07001117 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
deadbeefe1f9d832016-01-14 15:35:42 -08001118 signaling_thread(),
1119 new AudioRtpSender(static_cast<AudioTrackInterface*>(track),
Steve Anton75737c02017-11-06 10:37:17 -08001120 voice_channel(), stats_.get()));
Steve Anton4171afb2017-11-20 10:20:22 -08001121 GetAudioTransceiver()->internal()->AddSender(new_sender);
deadbeefe1f9d832016-01-14 15:35:42 -08001122 if (!streams.empty()) {
deadbeefa601f5c2016-06-06 14:27:39 -07001123 new_sender->internal()->set_stream_id(streams[0]->label());
deadbeefe1f9d832016-01-14 15:35:42 -08001124 }
Steve Anton4171afb2017-11-20 10:20:22 -08001125 const RtpSenderInfo* sender_info =
1126 FindSenderInfo(local_audio_sender_infos_,
1127 new_sender->internal()->stream_id(), track->id());
1128 if (sender_info) {
1129 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -08001130 }
1131 } else if (track->kind() == MediaStreamTrackInterface::kVideoKind) {
deadbeefa601f5c2016-06-06 14:27:39 -07001132 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
deadbeefe1f9d832016-01-14 15:35:42 -08001133 signaling_thread(),
1134 new VideoRtpSender(static_cast<VideoTrackInterface*>(track),
Steve Anton75737c02017-11-06 10:37:17 -08001135 video_channel()));
Steve Anton4171afb2017-11-20 10:20:22 -08001136 GetVideoTransceiver()->internal()->AddSender(new_sender);
deadbeefe1f9d832016-01-14 15:35:42 -08001137 if (!streams.empty()) {
deadbeefa601f5c2016-06-06 14:27:39 -07001138 new_sender->internal()->set_stream_id(streams[0]->label());
deadbeefe1f9d832016-01-14 15:35:42 -08001139 }
Steve Anton4171afb2017-11-20 10:20:22 -08001140 const RtpSenderInfo* sender_info =
1141 FindSenderInfo(local_video_sender_infos_,
1142 new_sender->internal()->stream_id(), track->id());
1143 if (sender_info) {
1144 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -08001145 }
1146 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001147 RTC_LOG(LS_ERROR) << "CreateSender called with invalid kind: "
1148 << track->kind();
deadbeefe1f9d832016-01-14 15:35:42 -08001149 return rtc::scoped_refptr<RtpSenderInterface>();
1150 }
1151
deadbeefe1f9d832016-01-14 15:35:42 -08001152 observer_->OnRenegotiationNeeded();
1153 return new_sender;
1154}
1155
1156bool PeerConnection::RemoveTrack(RtpSenderInterface* sender) {
1157 TRACE_EVENT0("webrtc", "PeerConnection::RemoveTrack");
1158 if (IsClosed()) {
1159 return false;
1160 }
1161
Steve Anton4171afb2017-11-20 10:20:22 -08001162 bool removed;
1163 if (sender->media_type() == cricket::MEDIA_TYPE_AUDIO) {
1164 removed = GetAudioTransceiver()->internal()->RemoveSender(sender);
1165 } else {
1166 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, sender->media_type());
1167 removed = GetVideoTransceiver()->internal()->RemoveSender(sender);
1168 }
1169 if (!removed) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001170 RTC_LOG(LS_ERROR) << "Couldn't find sender " << sender->id()
1171 << " to remove.";
deadbeefe1f9d832016-01-14 15:35:42 -08001172 return false;
1173 }
deadbeefe1f9d832016-01-14 15:35:42 -08001174
1175 observer_->OnRenegotiationNeeded();
1176 return true;
1177}
1178
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001179rtc::scoped_refptr<DtmfSenderInterface> PeerConnection::CreateDtmfSender(
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001180 AudioTrackInterface* track) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001181 TRACE_EVENT0("webrtc", "PeerConnection::CreateDtmfSender");
zhihuang29ff8442016-07-27 11:07:25 -07001182 if (IsClosed()) {
1183 return nullptr;
1184 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001185 if (!track) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001186 RTC_LOG(LS_ERROR) << "CreateDtmfSender - track is NULL.";
deadbeef20cb0c12017-02-01 20:27:00 -08001187 return nullptr;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001188 }
Steve Anton4171afb2017-11-20 10:20:22 -08001189 auto track_sender = FindSenderForTrack(track);
1190 if (!track_sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001191 RTC_LOG(LS_ERROR) << "CreateDtmfSender called with a non-added track.";
deadbeef20cb0c12017-02-01 20:27:00 -08001192 return nullptr;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001193 }
1194
Steve Anton4171afb2017-11-20 10:20:22 -08001195 return track_sender->GetDtmfSender();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001196}
1197
deadbeeffac06552015-11-25 11:26:01 -08001198rtc::scoped_refptr<RtpSenderInterface> PeerConnection::CreateSender(
deadbeefbd7d8f72015-12-18 16:58:44 -08001199 const std::string& kind,
1200 const std::string& stream_id) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001201 TRACE_EVENT0("webrtc", "PeerConnection::CreateSender");
zhihuang29ff8442016-07-27 11:07:25 -07001202 if (IsClosed()) {
1203 return nullptr;
1204 }
Steve Anton4171afb2017-11-20 10:20:22 -08001205
1206 // TODO(steveanton): Move construction of the RtpSenders to RtpTransceiver.
deadbeefa601f5c2016-06-06 14:27:39 -07001207 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender;
deadbeeffac06552015-11-25 11:26:01 -08001208 if (kind == MediaStreamTrackInterface::kAudioKind) {
deadbeefa601f5c2016-06-06 14:27:39 -07001209 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton75737c02017-11-06 10:37:17 -08001210 signaling_thread(), new AudioRtpSender(voice_channel(), stats_.get()));
Steve Anton4171afb2017-11-20 10:20:22 -08001211 GetAudioTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 11:26:01 -08001212 } else if (kind == MediaStreamTrackInterface::kVideoKind) {
deadbeefa601f5c2016-06-06 14:27:39 -07001213 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton75737c02017-11-06 10:37:17 -08001214 signaling_thread(), new VideoRtpSender(video_channel()));
Steve Anton4171afb2017-11-20 10:20:22 -08001215 GetVideoTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 11:26:01 -08001216 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001217 RTC_LOG(LS_ERROR) << "CreateSender called with invalid kind: " << kind;
Steve Anton4171afb2017-11-20 10:20:22 -08001218 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08001219 }
Steve Anton4171afb2017-11-20 10:20:22 -08001220
deadbeefbd7d8f72015-12-18 16:58:44 -08001221 if (!stream_id.empty()) {
deadbeefa601f5c2016-06-06 14:27:39 -07001222 new_sender->internal()->set_stream_id(stream_id);
deadbeefbd7d8f72015-12-18 16:58:44 -08001223 }
Steve Anton4171afb2017-11-20 10:20:22 -08001224
deadbeefe1f9d832016-01-14 15:35:42 -08001225 return new_sender;
deadbeeffac06552015-11-25 11:26:01 -08001226}
1227
deadbeef70ab1a12015-09-28 16:53:55 -07001228std::vector<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::GetSenders()
1229 const {
deadbeefa601f5c2016-06-06 14:27:39 -07001230 std::vector<rtc::scoped_refptr<RtpSenderInterface>> ret;
Steve Anton4171afb2017-11-20 10:20:22 -08001231 for (auto sender : GetSendersInternal()) {
1232 ret.push_back(sender);
deadbeefa601f5c2016-06-06 14:27:39 -07001233 }
1234 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -07001235}
1236
Steve Anton4171afb2017-11-20 10:20:22 -08001237std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1238PeerConnection::GetSendersInternal() const {
1239 std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1240 all_senders;
1241 for (auto transceiver : transceivers_) {
1242 auto senders = transceiver->internal()->senders();
1243 all_senders.insert(all_senders.end(), senders.begin(), senders.end());
1244 }
1245 return all_senders;
1246}
1247
deadbeef70ab1a12015-09-28 16:53:55 -07001248std::vector<rtc::scoped_refptr<RtpReceiverInterface>>
1249PeerConnection::GetReceivers() const {
deadbeefa601f5c2016-06-06 14:27:39 -07001250 std::vector<rtc::scoped_refptr<RtpReceiverInterface>> ret;
Steve Anton4171afb2017-11-20 10:20:22 -08001251 for (const auto& receiver : GetReceiversInternal()) {
1252 ret.push_back(receiver);
deadbeefa601f5c2016-06-06 14:27:39 -07001253 }
1254 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -07001255}
1256
Steve Anton4171afb2017-11-20 10:20:22 -08001257std::vector<
1258 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1259PeerConnection::GetReceiversInternal() const {
1260 std::vector<
1261 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1262 all_receivers;
1263 for (auto transceiver : transceivers_) {
1264 auto receivers = transceiver->internal()->receivers();
1265 all_receivers.insert(all_receivers.end(), receivers.begin(),
1266 receivers.end());
1267 }
1268 return all_receivers;
1269}
1270
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001271bool PeerConnection::GetStats(StatsObserver* observer,
wu@webrtc.orgb9a088b2014-02-13 23:18:49 +00001272 MediaStreamTrackInterface* track,
1273 StatsOutputLevel level) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001274 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
deadbeef0a6c4ca2015-10-06 11:38:28 -07001275 RTC_DCHECK(signaling_thread()->IsCurrent());
nisse7ce109a2017-01-31 00:57:56 -08001276 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001277 RTC_LOG(LS_ERROR) << "GetStats - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001278 return false;
1279 }
1280
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001281 stats_->UpdateStats(level);
zhihuange9e94c32016-11-04 11:38:15 -07001282 // The StatsCollector is used to tell if a track is valid because it may
1283 // remember tracks that the PeerConnection previously removed.
1284 if (track && !stats_->IsValidTrack(track->id())) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001285 RTC_LOG(LS_WARNING) << "GetStats is called with an invalid track: "
1286 << track->id();
zhihuange9e94c32016-11-04 11:38:15 -07001287 return false;
1288 }
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001289 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_GETSTATS,
tommi@webrtc.org5b06b062014-08-15 08:38:30 +00001290 new GetStatsMsg(observer, track));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001291 return true;
1292}
1293
hbos74e1a4f2016-09-15 23:33:01 -07001294void PeerConnection::GetStats(RTCStatsCollectorCallback* callback) {
1295 RTC_DCHECK(stats_collector_);
1296 stats_collector_->GetStatsReport(callback);
1297}
1298
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001299PeerConnectionInterface::SignalingState PeerConnection::signaling_state() {
1300 return signaling_state_;
1301}
1302
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001303PeerConnectionInterface::IceConnectionState
1304PeerConnection::ice_connection_state() {
1305 return ice_connection_state_;
1306}
1307
1308PeerConnectionInterface::IceGatheringState
1309PeerConnection::ice_gathering_state() {
1310 return ice_gathering_state_;
1311}
1312
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001313rtc::scoped_refptr<DataChannelInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001314PeerConnection::CreateDataChannel(
1315 const std::string& label,
1316 const DataChannelInit* config) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001317 TRACE_EVENT0("webrtc", "PeerConnection::CreateDataChannel");
zhihuang9763d562016-08-05 11:14:50 -07001318
deadbeefab9b2d12015-10-14 11:33:11 -07001319 bool first_datachannel = !HasDataChannels();
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001320
kwibergd1fe2812016-04-27 06:47:29 -07001321 std::unique_ptr<InternalDataChannelInit> internal_config;
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00001322 if (config) {
1323 internal_config.reset(new InternalDataChannelInit(*config));
1324 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001325 rtc::scoped_refptr<DataChannelInterface> channel(
deadbeefab9b2d12015-10-14 11:33:11 -07001326 InternalCreateDataChannel(label, internal_config.get()));
1327 if (!channel.get()) {
1328 return nullptr;
1329 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001330
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001331 // Trigger the onRenegotiationNeeded event for every new RTP DataChannel, or
1332 // the first SCTP DataChannel.
Steve Anton75737c02017-11-06 10:37:17 -08001333 if (data_channel_type() == cricket::DCT_RTP || first_datachannel) {
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001334 observer_->OnRenegotiationNeeded();
1335 }
wu@webrtc.org91053e72013-08-10 07:18:04 +00001336
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001337 return DataChannelProxy::Create(signaling_thread(), channel.get());
1338}
1339
1340void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
1341 const MediaConstraintsInterface* constraints) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001342 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
Steve Anton8d3444d2017-10-20 15:30:51 -07001343
zhihuang1c378ed2017-08-17 14:10:50 -07001344 PeerConnectionInterface::RTCOfferAnswerOptions offer_answer_options;
1345 // Always create an offer even if |ConvertConstraintsToOfferAnswerOptions|
1346 // returns false for now. Because |ConvertConstraintsToOfferAnswerOptions|
1347 // compares the mandatory fields parsed with the mandatory fields added in the
1348 // |constraints| and some downstream applications might create offers with
1349 // mandatory fields which would not be parsed in the helper method. For
1350 // example, in Chromium/remoting, |kEnableDtlsSrtp| is added to the
1351 // |constraints| as a mandatory field but it is not parsed.
1352 ConvertConstraintsToOfferAnswerOptions(constraints, &offer_answer_options);
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001353
zhihuang1c378ed2017-08-17 14:10:50 -07001354 CreateOffer(observer, offer_answer_options);
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001355}
1356
1357void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
1358 const RTCOfferAnswerOptions& options) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001359 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
Steve Anton8d3444d2017-10-20 15:30:51 -07001360
nisse7ce109a2017-01-31 00:57:56 -08001361 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001362 RTC_LOG(LS_ERROR) << "CreateOffer - observer is NULL.";
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001363 return;
1364 }
deadbeefab9b2d12015-10-14 11:33:11 -07001365
Steve Anton8d3444d2017-10-20 15:30:51 -07001366 if (IsClosed()) {
1367 std::string error = "CreateOffer called when PeerConnection is closed.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001368 RTC_LOG(LS_ERROR) << error;
Steve Anton8d3444d2017-10-20 15:30:51 -07001369 PostCreateSessionDescriptionFailure(observer, error);
1370 return;
1371 }
1372
zhihuang1c378ed2017-08-17 14:10:50 -07001373 if (!ValidateOfferAnswerOptions(options)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001374 std::string error = "CreateOffer called with invalid options.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001375 RTC_LOG(LS_ERROR) << error;
deadbeefab9b2d12015-10-14 11:33:11 -07001376 PostCreateSessionDescriptionFailure(observer, error);
1377 return;
1378 }
1379
zhihuang1c378ed2017-08-17 14:10:50 -07001380 cricket::MediaSessionOptions session_options;
1381 GetOptionsForOffer(options, &session_options);
Steve Antond25da372017-11-06 14:50:29 -08001382 webrtc_session_desc_factory_->CreateOffer(observer, options, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001383}
1384
1385void PeerConnection::CreateAnswer(
1386 CreateSessionDescriptionObserver* observer,
1387 const MediaConstraintsInterface* constraints) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001388 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
Steve Anton8d3444d2017-10-20 15:30:51 -07001389
nisse7ce109a2017-01-31 00:57:56 -08001390 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001391 RTC_LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001392 return;
1393 }
deadbeefab9b2d12015-10-14 11:33:11 -07001394
zhihuang1c378ed2017-08-17 14:10:50 -07001395 PeerConnectionInterface::RTCOfferAnswerOptions offer_answer_options;
1396 if (!ConvertConstraintsToOfferAnswerOptions(constraints,
1397 &offer_answer_options)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001398 std::string error = "CreateAnswer called with invalid constraints.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001399 RTC_LOG(LS_ERROR) << error;
deadbeefab9b2d12015-10-14 11:33:11 -07001400 PostCreateSessionDescriptionFailure(observer, error);
1401 return;
1402 }
1403
Steve Anton8d3444d2017-10-20 15:30:51 -07001404 CreateAnswer(observer, offer_answer_options);
htaa2a49d92016-03-04 02:51:39 -08001405}
1406
1407void PeerConnection::CreateAnswer(CreateSessionDescriptionObserver* observer,
1408 const RTCOfferAnswerOptions& options) {
1409 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
nisse7ce109a2017-01-31 00:57:56 -08001410 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001411 RTC_LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
htaa2a49d92016-03-04 02:51:39 -08001412 return;
1413 }
1414
Steve Anton8d3444d2017-10-20 15:30:51 -07001415 if (IsClosed()) {
1416 std::string error = "CreateAnswer called when PeerConnection is closed.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001417 RTC_LOG(LS_ERROR) << error;
Steve Anton8d3444d2017-10-20 15:30:51 -07001418 PostCreateSessionDescriptionFailure(observer, error);
1419 return;
1420 }
1421
Steve Anton75737c02017-11-06 10:37:17 -08001422 if (remote_description() &&
1423 remote_description()->type() != SessionDescriptionInterface::kOffer) {
Steve Anton8d3444d2017-10-20 15:30:51 -07001424 std::string error = "CreateAnswer called without remote offer.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001425 RTC_LOG(LS_ERROR) << error;
Steve Anton8d3444d2017-10-20 15:30:51 -07001426 PostCreateSessionDescriptionFailure(observer, error);
1427 return;
1428 }
1429
htaa2a49d92016-03-04 02:51:39 -08001430 cricket::MediaSessionOptions session_options;
zhihuang1c378ed2017-08-17 14:10:50 -07001431 GetOptionsForAnswer(options, &session_options);
htaa2a49d92016-03-04 02:51:39 -08001432
Steve Antond25da372017-11-06 14:50:29 -08001433 webrtc_session_desc_factory_->CreateAnswer(observer, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001434}
1435
1436void PeerConnection::SetLocalDescription(
1437 SetSessionDescriptionObserver* observer,
1438 SessionDescriptionInterface* desc) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001439 TRACE_EVENT0("webrtc", "PeerConnection::SetLocalDescription");
nisse7ce109a2017-01-31 00:57:56 -08001440 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001441 RTC_LOG(LS_ERROR) << "SetLocalDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001442 return;
1443 }
1444 if (!desc) {
1445 PostSetSessionDescriptionFailure(observer, "SessionDescription is NULL.");
1446 return;
1447 }
Steve Anton8d3444d2017-10-20 15:30:51 -07001448
1449 // Takes the ownership of |desc| regardless of the result.
1450 std::unique_ptr<SessionDescriptionInterface> desc_temp(desc);
1451
1452 if (IsClosed()) {
Henrik Boströmfdb92012017-11-09 19:55:44 +01001453 std::string error = "Failed to set local " + desc_temp->type() +
Steve Anton8d3444d2017-10-20 15:30:51 -07001454 " sdp: Called in wrong state: STATE_CLOSED";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001455 RTC_LOG(LS_ERROR) << error;
Steve Anton8d3444d2017-10-20 15:30:51 -07001456 PostSetSessionDescriptionFailure(observer, error);
1457 return;
1458 }
1459
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001460 // Update stats here so that we have the most recent stats for tracks and
1461 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001462 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001463 std::string error;
Henrik Boströmfdb92012017-11-09 19:55:44 +01001464 // Takes the ownership of |desc_temp|. On success, local_description() is
1465 // updated to reflect the description that was passed in.
Steve Anton75737c02017-11-06 10:37:17 -08001466 if (!SetLocalDescription(std::move(desc_temp), &error)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001467 PostSetSessionDescriptionFailure(observer, error);
1468 return;
1469 }
Henrik Boströmfdb92012017-11-09 19:55:44 +01001470 RTC_DCHECK(local_description());
deadbeefab9b2d12015-10-14 11:33:11 -07001471
1472 // If setting the description decided our SSL role, allocate any necessary
1473 // SCTP sids.
1474 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08001475 if (data_channel_type() == cricket::DCT_SCTP && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001476 AllocateSctpSids(role);
1477 }
1478
1479 // Update state and SSRC of local MediaStreams and DataChannels based on the
1480 // local session description.
1481 const cricket::ContentInfo* audio_content =
Henrik Boströmfdb92012017-11-09 19:55:44 +01001482 GetFirstAudioContent(local_description()->description());
deadbeefab9b2d12015-10-14 11:33:11 -07001483 if (audio_content) {
deadbeeffaac4972015-11-12 15:33:07 -08001484 if (audio_content->rejected) {
Steve Anton4171afb2017-11-20 10:20:22 -08001485 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
deadbeeffaac4972015-11-12 15:33:07 -08001486 } else {
1487 const cricket::AudioContentDescription* audio_desc =
1488 static_cast<const cricket::AudioContentDescription*>(
1489 audio_content->description);
Steve Anton4171afb2017-11-20 10:20:22 -08001490 UpdateLocalSenders(audio_desc->streams(), audio_desc->type());
deadbeeffaac4972015-11-12 15:33:07 -08001491 }
deadbeefab9b2d12015-10-14 11:33:11 -07001492 }
1493
1494 const cricket::ContentInfo* video_content =
Henrik Boströmfdb92012017-11-09 19:55:44 +01001495 GetFirstVideoContent(local_description()->description());
deadbeefab9b2d12015-10-14 11:33:11 -07001496 if (video_content) {
deadbeeffaac4972015-11-12 15:33:07 -08001497 if (video_content->rejected) {
Steve Anton4171afb2017-11-20 10:20:22 -08001498 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
deadbeeffaac4972015-11-12 15:33:07 -08001499 } else {
1500 const cricket::VideoContentDescription* video_desc =
1501 static_cast<const cricket::VideoContentDescription*>(
1502 video_content->description);
Steve Anton4171afb2017-11-20 10:20:22 -08001503 UpdateLocalSenders(video_desc->streams(), video_desc->type());
deadbeeffaac4972015-11-12 15:33:07 -08001504 }
deadbeefab9b2d12015-10-14 11:33:11 -07001505 }
1506
1507 const cricket::ContentInfo* data_content =
Henrik Boströmfdb92012017-11-09 19:55:44 +01001508 GetFirstDataContent(local_description()->description());
deadbeefab9b2d12015-10-14 11:33:11 -07001509 if (data_content) {
1510 const cricket::DataContentDescription* data_desc =
1511 static_cast<const cricket::DataContentDescription*>(
1512 data_content->description);
1513 if (rtc::starts_with(data_desc->protocol().data(),
1514 cricket::kMediaProtocolRtpPrefix)) {
1515 UpdateLocalRtpDataChannels(data_desc->streams());
1516 }
1517 }
1518
1519 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001520 signaling_thread()->Post(RTC_FROM_HERE, this,
1521 MSG_SET_SESSIONDESCRIPTION_SUCCESS, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07001522
deadbeef42a42632017-03-10 15:18:00 -08001523 // According to JSEP, after setLocalDescription, changing the candidate pool
1524 // size is not allowed, and changing the set of ICE servers will not result
1525 // in new candidates being gathered.
1526 port_allocator_->FreezeCandidatePool();
1527
deadbeefcbecd352015-09-23 11:50:27 -07001528 // MaybeStartGathering needs to be called after posting
1529 // MSG_SET_SESSIONDESCRIPTION_SUCCESS, so that we don't signal any candidates
1530 // before signaling that SetLocalDescription completed.
Steve Antond25da372017-11-06 14:50:29 -08001531 transport_controller_->MaybeStartGathering();
deadbeef42a42632017-03-10 15:18:00 -08001532
Henrik Boströmfdb92012017-11-09 19:55:44 +01001533 if (local_description()->type() == SessionDescriptionInterface::kAnswer) {
deadbeef42a42632017-03-10 15:18:00 -08001534 // TODO(deadbeef): We already had to hop to the network thread for
1535 // MaybeStartGathering...
1536 network_thread()->Invoke<void>(
1537 RTC_FROM_HERE,
1538 rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
1539 port_allocator_.get()));
1540 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001541}
1542
1543void PeerConnection::SetRemoteDescription(
1544 SetSessionDescriptionObserver* observer,
1545 SessionDescriptionInterface* desc) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001546 TRACE_EVENT0("webrtc", "PeerConnection::SetRemoteDescription");
nisse7ce109a2017-01-31 00:57:56 -08001547 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001548 RTC_LOG(LS_ERROR) << "SetRemoteDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001549 return;
1550 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001551 if (!desc) {
1552 PostSetSessionDescriptionFailure(observer, "SessionDescription is NULL.");
1553 return;
1554 }
Steve Anton8d3444d2017-10-20 15:30:51 -07001555
1556 // Takes the ownership of |desc| regardless of the result.
1557 std::unique_ptr<SessionDescriptionInterface> desc_temp(desc);
1558
1559 if (IsClosed()) {
Henrik Boströmfdb92012017-11-09 19:55:44 +01001560 std::string error = "Failed to set remote " + desc_temp->type() +
Steve Anton8d3444d2017-10-20 15:30:51 -07001561 " sdp: Called in wrong state: STATE_CLOSED";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001562 RTC_LOG(LS_ERROR) << error;
Steve Anton8d3444d2017-10-20 15:30:51 -07001563 PostSetSessionDescriptionFailure(observer, error);
1564 return;
1565 }
1566
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001567 // Update stats here so that we have the most recent stats for tracks and
1568 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001569 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001570 std::string error;
Henrik Boströmfdb92012017-11-09 19:55:44 +01001571 // Takes the ownership of |desc_temp|. On success, remote_description() is
1572 // updated to reflect the description that was passed in.
Steve Anton75737c02017-11-06 10:37:17 -08001573 if (!SetRemoteDescription(std::move(desc_temp), &error)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001574 PostSetSessionDescriptionFailure(observer, error);
1575 return;
1576 }
Henrik Boströmfdb92012017-11-09 19:55:44 +01001577 RTC_DCHECK(remote_description());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001578
deadbeefab9b2d12015-10-14 11:33:11 -07001579 // If setting the description decided our SSL role, allocate any necessary
1580 // SCTP sids.
1581 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08001582 if (data_channel_type() == cricket::DCT_SCTP && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001583 AllocateSctpSids(role);
1584 }
1585
Henrik Boströmfdb92012017-11-09 19:55:44 +01001586 const cricket::ContentInfo* audio_content =
1587 GetFirstAudioContent(remote_description()->description());
1588 const cricket::ContentInfo* video_content =
1589 GetFirstVideoContent(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08001590 const cricket::AudioContentDescription* audio_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01001591 GetFirstAudioContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08001592 const cricket::VideoContentDescription* video_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01001593 GetFirstVideoContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08001594 const cricket::DataContentDescription* data_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01001595 GetFirstDataContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08001596
1597 // Check if the descriptions include streams, just in case the peer supports
1598 // MSID, but doesn't indicate so with "a=msid-semantic".
Henrik Boströmfdb92012017-11-09 19:55:44 +01001599 if (remote_description()->description()->msid_supported() ||
deadbeefbda7e0b2015-12-08 17:13:40 -08001600 (audio_desc && !audio_desc->streams().empty()) ||
1601 (video_desc && !video_desc->streams().empty())) {
1602 remote_peer_supports_msid_ = true;
1603 }
deadbeefab9b2d12015-10-14 11:33:11 -07001604
1605 // We wait to signal new streams until we finish processing the description,
1606 // since only at that point will new streams have all their tracks.
1607 rtc::scoped_refptr<StreamCollection> new_streams(StreamCollection::Create());
1608
Steve Anton8d3444d2017-10-20 15:30:51 -07001609 // TODO(steveanton): When removing RTP senders/receivers in response to a
1610 // rejected media section, there is some cleanup logic that expects the voice/
1611 // video channel to still be set. But in this method the voice/video channel
Steve Anton75737c02017-11-06 10:37:17 -08001612 // would have been destroyed by the SetRemoteDescription caller above so the
Steve Anton4171afb2017-11-20 10:20:22 -08001613 // cleanup that relies on them fails to run. The RemoveSenders calls should be
Steve Anton75737c02017-11-06 10:37:17 -08001614 // moved to right before the DestroyChannel calls to fix this.
Steve Anton8d3444d2017-10-20 15:30:51 -07001615
deadbeefab9b2d12015-10-14 11:33:11 -07001616 // Find all audio rtp streams and create corresponding remote AudioTracks
1617 // and MediaStreams.
deadbeefab9b2d12015-10-14 11:33:11 -07001618 if (audio_content) {
deadbeeffaac4972015-11-12 15:33:07 -08001619 if (audio_content->rejected) {
Steve Anton4171afb2017-11-20 10:20:22 -08001620 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
deadbeeffaac4972015-11-12 15:33:07 -08001621 } else {
deadbeefbda7e0b2015-12-08 17:13:40 -08001622 bool default_audio_track_needed =
1623 !remote_peer_supports_msid_ &&
1624 MediaContentDirectionHasSend(audio_desc->direction());
Steve Anton4171afb2017-11-20 10:20:22 -08001625 UpdateRemoteSendersList(GetActiveStreams(audio_desc),
deadbeefbda7e0b2015-12-08 17:13:40 -08001626 default_audio_track_needed, audio_desc->type(),
deadbeeffaac4972015-11-12 15:33:07 -08001627 new_streams);
deadbeeffaac4972015-11-12 15:33:07 -08001628 }
deadbeefab9b2d12015-10-14 11:33:11 -07001629 }
1630
1631 // Find all video rtp streams and create corresponding remote VideoTracks
1632 // and MediaStreams.
deadbeefab9b2d12015-10-14 11:33:11 -07001633 if (video_content) {
deadbeeffaac4972015-11-12 15:33:07 -08001634 if (video_content->rejected) {
Steve Anton4171afb2017-11-20 10:20:22 -08001635 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
deadbeeffaac4972015-11-12 15:33:07 -08001636 } else {
deadbeefbda7e0b2015-12-08 17:13:40 -08001637 bool default_video_track_needed =
1638 !remote_peer_supports_msid_ &&
1639 MediaContentDirectionHasSend(video_desc->direction());
Steve Anton4171afb2017-11-20 10:20:22 -08001640 UpdateRemoteSendersList(GetActiveStreams(video_desc),
deadbeefbda7e0b2015-12-08 17:13:40 -08001641 default_video_track_needed, video_desc->type(),
deadbeeffaac4972015-11-12 15:33:07 -08001642 new_streams);
deadbeeffaac4972015-11-12 15:33:07 -08001643 }
deadbeefab9b2d12015-10-14 11:33:11 -07001644 }
1645
1646 // Update the DataChannels with the information from the remote peer.
deadbeefbda7e0b2015-12-08 17:13:40 -08001647 if (data_desc) {
1648 if (rtc::starts_with(data_desc->protocol().data(),
deadbeefab9b2d12015-10-14 11:33:11 -07001649 cricket::kMediaProtocolRtpPrefix)) {
deadbeefbda7e0b2015-12-08 17:13:40 -08001650 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
deadbeefab9b2d12015-10-14 11:33:11 -07001651 }
1652 }
1653
1654 // Iterate new_streams and notify the observer about new MediaStreams.
1655 for (size_t i = 0; i < new_streams->count(); ++i) {
1656 MediaStreamInterface* new_stream = new_streams->at(i);
1657 stats_->AddStream(new_stream);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07001658 observer_->OnAddStream(
1659 rtc::scoped_refptr<MediaStreamInterface>(new_stream));
deadbeefab9b2d12015-10-14 11:33:11 -07001660 }
1661
deadbeefbda7e0b2015-12-08 17:13:40 -08001662 UpdateEndedRemoteMediaStreams();
deadbeefab9b2d12015-10-14 11:33:11 -07001663
1664 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001665 signaling_thread()->Post(RTC_FROM_HERE, this,
1666 MSG_SET_SESSIONDESCRIPTION_SUCCESS, msg);
deadbeef42a42632017-03-10 15:18:00 -08001667
Henrik Boströmfdb92012017-11-09 19:55:44 +01001668 if (remote_description()->type() == SessionDescriptionInterface::kAnswer) {
deadbeef42a42632017-03-10 15:18:00 -08001669 // TODO(deadbeef): We already had to hop to the network thread for
1670 // MaybeStartGathering...
1671 network_thread()->Invoke<void>(
1672 RTC_FROM_HERE,
1673 rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
1674 port_allocator_.get()));
1675 }
deadbeeffc648b62015-10-13 16:42:33 -07001676}
1677
deadbeef46c73892016-11-16 19:42:04 -08001678PeerConnectionInterface::RTCConfiguration PeerConnection::GetConfiguration() {
1679 return configuration_;
1680}
1681
deadbeef293e9262017-01-11 12:28:30 -08001682bool PeerConnection::SetConfiguration(const RTCConfiguration& configuration,
1683 RTCError* error) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001684 TRACE_EVENT0("webrtc", "PeerConnection::SetConfiguration");
deadbeef6de92f92016-12-12 18:49:32 -08001685
Steve Anton75737c02017-11-06 10:37:17 -08001686 if (local_description() && configuration.ice_candidate_pool_size !=
1687 configuration_.ice_candidate_pool_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001688 RTC_LOG(LS_ERROR) << "Can't change candidate pool size after calling "
1689 "SetLocalDescription.";
deadbeef293e9262017-01-11 12:28:30 -08001690 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00001691 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07001692
deadbeef293e9262017-01-11 12:28:30 -08001693 // The simplest (and most future-compatible) way to tell if the config was
1694 // modified in an invalid way is to copy each property we do support
1695 // modifying, then use operator==. There are far more properties we don't
1696 // support modifying than those we do, and more could be added.
1697 RTCConfiguration modified_config = configuration_;
1698 modified_config.servers = configuration.servers;
1699 modified_config.type = configuration.type;
1700 modified_config.ice_candidate_pool_size =
1701 configuration.ice_candidate_pool_size;
1702 modified_config.prune_turn_ports = configuration.prune_turn_ports;
skvladd1f5fda2017-02-03 16:54:05 -08001703 modified_config.ice_check_min_interval = configuration.ice_check_min_interval;
Jonas Orelandbdcee282017-10-10 14:01:40 +02001704 modified_config.turn_customizer = configuration.turn_customizer;
deadbeef293e9262017-01-11 12:28:30 -08001705 if (configuration != modified_config) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001706 RTC_LOG(LS_ERROR) << "Modifying the configuration in an unsupported way.";
deadbeef293e9262017-01-11 12:28:30 -08001707 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
1708 }
1709
Steve Anton038834f2017-07-14 15:59:59 -07001710 // Validate the modified configuration.
1711 RTCError validate_error = ValidateConfiguration(modified_config);
1712 if (!validate_error.ok()) {
1713 return SafeSetError(std::move(validate_error), error);
1714 }
1715
deadbeef293e9262017-01-11 12:28:30 -08001716 // Note that this isn't possible through chromium, since it's an unsigned
1717 // short in WebIDL.
1718 if (configuration.ice_candidate_pool_size < 0 ||
1719 configuration.ice_candidate_pool_size > UINT16_MAX) {
1720 return SafeSetError(RTCErrorType::INVALID_RANGE, error);
1721 }
1722
1723 // Parse ICE servers before hopping to network thread.
1724 cricket::ServerAddresses stun_servers;
1725 std::vector<cricket::RelayServerConfig> turn_servers;
1726 RTCErrorType parse_error =
1727 ParseIceServers(configuration.servers, &stun_servers, &turn_servers);
1728 if (parse_error != RTCErrorType::NONE) {
1729 return SafeSetError(parse_error, error);
1730 }
1731
1732 // In theory this shouldn't fail.
1733 if (!network_thread()->Invoke<bool>(
1734 RTC_FROM_HERE,
1735 rtc::Bind(&PeerConnection::ReconfigurePortAllocator_n, this,
1736 stun_servers, turn_servers, modified_config.type,
1737 modified_config.ice_candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02001738 modified_config.prune_turn_ports,
1739 modified_config.turn_customizer))) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001740 RTC_LOG(LS_ERROR) << "Failed to apply configuration to PortAllocator.";
deadbeef293e9262017-01-11 12:28:30 -08001741 return SafeSetError(RTCErrorType::INTERNAL_ERROR, error);
1742 }
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07001743
deadbeefd1a38b52016-12-10 13:15:33 -08001744 // As described in JSEP, calling setConfiguration with new ICE servers or
1745 // candidate policy must set a "needs-ice-restart" bit so that the next offer
1746 // triggers an ICE restart which will pick up the changes.
deadbeef293e9262017-01-11 12:28:30 -08001747 if (modified_config.servers != configuration_.servers ||
1748 modified_config.type != configuration_.type ||
1749 modified_config.prune_turn_ports != configuration_.prune_turn_ports) {
Steve Antond25da372017-11-06 14:50:29 -08001750 transport_controller_->SetNeedsIceRestartFlag();
deadbeefd1a38b52016-12-10 13:15:33 -08001751 }
skvladd1f5fda2017-02-03 16:54:05 -08001752
1753 if (modified_config.ice_check_min_interval !=
1754 configuration_.ice_check_min_interval) {
Steve Antond25da372017-11-06 14:50:29 -08001755 transport_controller_->SetIceConfig(ParseIceConfig(modified_config));
skvladd1f5fda2017-02-03 16:54:05 -08001756 }
1757
deadbeef293e9262017-01-11 12:28:30 -08001758 configuration_ = modified_config;
1759 return SafeSetError(RTCErrorType::NONE, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00001760}
1761
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001762bool PeerConnection::AddIceCandidate(
1763 const IceCandidateInterface* ice_candidate) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001764 TRACE_EVENT0("webrtc", "PeerConnection::AddIceCandidate");
zhihuang29ff8442016-07-27 11:07:25 -07001765 if (IsClosed()) {
1766 return false;
1767 }
Steve Antond25da372017-11-06 14:50:29 -08001768
1769 if (!remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001770 RTC_LOG(LS_ERROR) << "ProcessIceMessage: ICE candidates can't be added "
1771 << "without any remote session description.";
Steve Antond25da372017-11-06 14:50:29 -08001772 return false;
1773 }
1774
1775 if (!ice_candidate) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001776 RTC_LOG(LS_ERROR) << "ProcessIceMessage: Candidate is NULL.";
Steve Antond25da372017-11-06 14:50:29 -08001777 return false;
1778 }
1779
1780 bool valid = false;
1781 bool ready = ReadyToUseRemoteCandidate(ice_candidate, nullptr, &valid);
1782 if (!valid) {
1783 return false;
1784 }
1785
1786 // Add this candidate to the remote session description.
1787 if (!mutable_remote_description()->AddCandidate(ice_candidate)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001788 RTC_LOG(LS_ERROR) << "ProcessIceMessage: Candidate cannot be used.";
Steve Antond25da372017-11-06 14:50:29 -08001789 return false;
1790 }
1791
1792 if (ready) {
1793 return UseCandidate(ice_candidate);
1794 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001795 RTC_LOG(LS_INFO) << "ProcessIceMessage: Not ready to use candidate.";
Steve Antond25da372017-11-06 14:50:29 -08001796 return true;
1797 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001798}
1799
Honghai Zhang7fb69db2016-03-14 11:59:18 -07001800bool PeerConnection::RemoveIceCandidates(
1801 const std::vector<cricket::Candidate>& candidates) {
1802 TRACE_EVENT0("webrtc", "PeerConnection::RemoveIceCandidates");
Steve Antond25da372017-11-06 14:50:29 -08001803 if (!remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001804 RTC_LOG(LS_ERROR) << "RemoveRemoteIceCandidates: ICE candidates can't be "
1805 << "removed without any remote session description.";
Steve Antond25da372017-11-06 14:50:29 -08001806 return false;
1807 }
1808
1809 if (candidates.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001810 RTC_LOG(LS_ERROR) << "RemoveRemoteIceCandidates: candidates are empty.";
Steve Antond25da372017-11-06 14:50:29 -08001811 return false;
1812 }
1813
1814 size_t number_removed =
1815 mutable_remote_description()->RemoveCandidates(candidates);
1816 if (number_removed != candidates.size()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001817 RTC_LOG(LS_ERROR)
1818 << "RemoveRemoteIceCandidates: Failed to remove candidates. "
1819 << "Requested " << candidates.size() << " but only " << number_removed
1820 << " are removed.";
Steve Antond25da372017-11-06 14:50:29 -08001821 }
1822
1823 // Remove the candidates from the transport controller.
1824 std::string error;
1825 bool res = transport_controller_->RemoveRemoteCandidates(candidates, &error);
1826 if (!res && !error.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001827 RTC_LOG(LS_ERROR) << "Error when removing remote candidates: " << error;
Steve Antond25da372017-11-06 14:50:29 -08001828 }
1829 return true;
Honghai Zhang7fb69db2016-03-14 11:59:18 -07001830}
1831
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00001832void PeerConnection::RegisterUMAObserver(UMAObserver* observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001833 TRACE_EVENT0("webrtc", "PeerConnection::RegisterUmaObserver");
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00001834 uma_observer_ = observer;
guoweis@webrtc.org7169afd2014-12-04 17:59:29 +00001835
Steve Anton75737c02017-11-06 10:37:17 -08001836 if (transport_controller()) {
1837 transport_controller()->SetMetricsObserver(uma_observer_);
guoweis@webrtc.org7169afd2014-12-04 17:59:29 +00001838 }
1839
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00001840 // Send information about IPv4/IPv6 status.
deadbeef293e9262017-01-11 12:28:30 -08001841 if (uma_observer_) {
Honghai Zhangd93f50c2016-10-05 11:47:22 -07001842 port_allocator_->SetMetricsObserver(uma_observer_);
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00001843 if (port_allocator_->flags() & cricket::PORTALLOCATOR_ENABLE_IPV6) {
Guo-wei Shiehdfbe6792015-09-03 17:12:07 -07001844 uma_observer_->IncrementEnumCounter(
1845 kEnumCounterAddressFamily, kPeerConnection_IPv6,
1846 kPeerConnectionAddressFamilyCounter_Max);
mallinath@webrtc.orgb445f262014-05-23 22:19:37 +00001847 } else {
Guo-wei Shiehdfbe6792015-09-03 17:12:07 -07001848 uma_observer_->IncrementEnumCounter(
1849 kEnumCounterAddressFamily, kPeerConnection_IPv4,
1850 kPeerConnectionAddressFamilyCounter_Max);
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00001851 }
1852 }
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00001853}
1854
zstein4b979802017-06-02 14:37:37 -07001855RTCError PeerConnection::SetBitrate(const BitrateParameters& bitrate) {
Steve Anton978b8762017-09-29 12:15:02 -07001856 if (!worker_thread()->IsCurrent()) {
1857 return worker_thread()->Invoke<RTCError>(
zstein4b979802017-06-02 14:37:37 -07001858 RTC_FROM_HERE, rtc::Bind(&PeerConnection::SetBitrate, this, bitrate));
1859 }
1860
1861 const bool has_min = static_cast<bool>(bitrate.min_bitrate_bps);
1862 const bool has_current = static_cast<bool>(bitrate.current_bitrate_bps);
1863 const bool has_max = static_cast<bool>(bitrate.max_bitrate_bps);
1864 if (has_min && *bitrate.min_bitrate_bps < 0) {
1865 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1866 "min_bitrate_bps <= 0");
1867 }
1868 if (has_current) {
1869 if (has_min && *bitrate.current_bitrate_bps < *bitrate.min_bitrate_bps) {
1870 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1871 "current_bitrate_bps < min_bitrate_bps");
1872 } else if (*bitrate.current_bitrate_bps < 0) {
1873 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1874 "curent_bitrate_bps < 0");
1875 }
1876 }
1877 if (has_max) {
1878 if (has_current &&
1879 *bitrate.max_bitrate_bps < *bitrate.current_bitrate_bps) {
1880 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1881 "max_bitrate_bps < current_bitrate_bps");
1882 } else if (has_min && *bitrate.max_bitrate_bps < *bitrate.min_bitrate_bps) {
1883 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1884 "max_bitrate_bps < min_bitrate_bps");
1885 } else if (*bitrate.max_bitrate_bps < 0) {
1886 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1887 "max_bitrate_bps < 0");
1888 }
1889 }
1890
1891 Call::Config::BitrateConfigMask mask;
1892 mask.min_bitrate_bps = bitrate.min_bitrate_bps;
1893 mask.start_bitrate_bps = bitrate.current_bitrate_bps;
1894 mask.max_bitrate_bps = bitrate.max_bitrate_bps;
1895
1896 RTC_DCHECK(call_.get());
1897 call_->SetBitrateConfigMask(mask);
1898
1899 return RTCError::OK();
1900}
1901
Alex Narest78609d52017-10-20 10:37:47 +02001902void PeerConnection::SetBitrateAllocationStrategy(
1903 std::unique_ptr<rtc::BitrateAllocationStrategy>
1904 bitrate_allocation_strategy) {
1905 rtc::Thread* worker_thread = factory_->worker_thread();
1906 if (!worker_thread->IsCurrent()) {
1907 rtc::BitrateAllocationStrategy* strategy_raw =
1908 bitrate_allocation_strategy.release();
1909 auto functor = [this, strategy_raw]() {
1910 call_->SetBitrateAllocationStrategy(
1911 rtc::WrapUnique<rtc::BitrateAllocationStrategy>(strategy_raw));
1912 };
1913 worker_thread->Invoke<void>(RTC_FROM_HERE, functor);
1914 return;
1915 }
1916 RTC_DCHECK(call_.get());
1917 call_->SetBitrateAllocationStrategy(std::move(bitrate_allocation_strategy));
1918}
1919
henrika5f6bf242017-11-01 11:06:56 +01001920void PeerConnection::SetAudioPlayout(bool playout) {
1921 if (!worker_thread()->IsCurrent()) {
1922 worker_thread()->Invoke<void>(
1923 RTC_FROM_HERE,
1924 rtc::Bind(&PeerConnection::SetAudioPlayout, this, playout));
1925 return;
1926 }
1927 auto audio_state =
1928 factory_->channel_manager()->media_engine()->GetAudioState();
1929 audio_state->SetPlayout(playout);
1930}
1931
1932void PeerConnection::SetAudioRecording(bool recording) {
1933 if (!worker_thread()->IsCurrent()) {
1934 worker_thread()->Invoke<void>(
1935 RTC_FROM_HERE,
1936 rtc::Bind(&PeerConnection::SetAudioRecording, this, recording));
1937 return;
1938 }
1939 auto audio_state =
1940 factory_->channel_manager()->media_engine()->GetAudioState();
1941 audio_state->SetRecording(recording);
1942}
1943
Steve Anton8c0f7a72017-10-03 10:03:10 -07001944std::unique_ptr<rtc::SSLCertificate>
1945PeerConnection::GetRemoteAudioSSLCertificate() {
Steve Anton75737c02017-11-06 10:37:17 -08001946 if (!voice_channel()) {
Steve Anton8c0f7a72017-10-03 10:03:10 -07001947 return nullptr;
1948 }
Steve Anton75737c02017-11-06 10:37:17 -08001949 return GetRemoteSSLCertificate(voice_channel()->transport_name());
Steve Anton8c0f7a72017-10-03 10:03:10 -07001950}
1951
ivoc14d5dbe2016-07-04 07:06:55 -07001952bool PeerConnection::StartRtcEventLog(rtc::PlatformFile file,
1953 int64_t max_size_bytes) {
Elad Alon99c3fe52017-10-13 16:29:40 +02001954 // TODO(eladalon): It would be better to not allow negative values into PC.
1955 const size_t max_size = (max_size_bytes < 0)
1956 ? RtcEventLog::kUnlimitedOutput
1957 : rtc::saturated_cast<size_t>(max_size_bytes);
1958 return StartRtcEventLog(
Bjorn Tereliusde939432017-11-20 17:38:14 +01001959 rtc::MakeUnique<RtcEventLogOutputFile>(file, max_size),
1960 webrtc::RtcEventLog::kImmediateOutput);
Elad Alon99c3fe52017-10-13 16:29:40 +02001961}
1962
Bjorn Tereliusde939432017-11-20 17:38:14 +01001963bool PeerConnection::StartRtcEventLog(std::unique_ptr<RtcEventLogOutput> output,
1964 int64_t output_period_ms) {
Karl Wibergd6b48192017-10-16 23:01:06 +02001965 // TODO(eladalon): In C++14, this can be done with a lambda.
1966 struct Functor {
Bjorn Tereliusde939432017-11-20 17:38:14 +01001967 bool operator()() {
1968 return pc->StartRtcEventLog_w(std::move(output), output_period_ms);
1969 }
Karl Wibergd6b48192017-10-16 23:01:06 +02001970 PeerConnection* const pc;
1971 std::unique_ptr<RtcEventLogOutput> output;
Bjorn Tereliusde939432017-11-20 17:38:14 +01001972 const int64_t output_period_ms;
Elad Alon99c3fe52017-10-13 16:29:40 +02001973 };
Bjorn Tereliusde939432017-11-20 17:38:14 +01001974 return worker_thread()->Invoke<bool>(
1975 RTC_FROM_HERE, Functor{this, std::move(output), output_period_ms});
ivoc14d5dbe2016-07-04 07:06:55 -07001976}
1977
1978void PeerConnection::StopRtcEventLog() {
Steve Anton978b8762017-09-29 12:15:02 -07001979 worker_thread()->Invoke<void>(
ivoc14d5dbe2016-07-04 07:06:55 -07001980 RTC_FROM_HERE, rtc::Bind(&PeerConnection::StopRtcEventLog_w, this));
1981}
1982
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001983const SessionDescriptionInterface* PeerConnection::local_description() const {
Steve Anton75737c02017-11-06 10:37:17 -08001984 return pending_local_description_ ? pending_local_description_.get()
1985 : current_local_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001986}
1987
1988const SessionDescriptionInterface* PeerConnection::remote_description() const {
Steve Anton75737c02017-11-06 10:37:17 -08001989 return pending_remote_description_ ? pending_remote_description_.get()
1990 : current_remote_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001991}
1992
deadbeeffe4a8a42016-12-20 17:56:17 -08001993const SessionDescriptionInterface* PeerConnection::current_local_description()
1994 const {
Steve Anton75737c02017-11-06 10:37:17 -08001995 return current_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08001996}
1997
1998const SessionDescriptionInterface* PeerConnection::current_remote_description()
1999 const {
Steve Anton75737c02017-11-06 10:37:17 -08002000 return current_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08002001}
2002
2003const SessionDescriptionInterface* PeerConnection::pending_local_description()
2004 const {
Steve Anton75737c02017-11-06 10:37:17 -08002005 return pending_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08002006}
2007
2008const SessionDescriptionInterface* PeerConnection::pending_remote_description()
2009 const {
Steve Anton75737c02017-11-06 10:37:17 -08002010 return pending_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08002011}
2012
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002013void PeerConnection::Close() {
Peter Boström1a9d6152015-12-08 22:15:17 +01002014 TRACE_EVENT0("webrtc", "PeerConnection::Close");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002015 // Update stats here so that we have the most recent stats for tracks and
2016 // streams before the channels are closed.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00002017 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002018
Steve Anton75737c02017-11-06 10:37:17 -08002019 ChangeSignalingState(PeerConnectionInterface::kClosed);
2020 RemoveUnusedChannels(nullptr);
Steve Anton4171afb2017-11-20 10:20:22 -08002021 RTC_DCHECK(!GetAudioTransceiver()->internal()->channel());
2022 RTC_DCHECK(!GetVideoTransceiver()->internal()->channel());
Steve Anton75737c02017-11-06 10:37:17 -08002023 RTC_DCHECK(!rtp_data_channel_);
2024 RTC_DCHECK(!sctp_transport_);
2025
deadbeef42a42632017-03-10 15:18:00 -08002026 network_thread()->Invoke<void>(
2027 RTC_FROM_HERE,
2028 rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
2029 port_allocator_.get()));
nisseeaabdf62017-05-05 02:23:02 -07002030
Steve Anton978b8762017-09-29 12:15:02 -07002031 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
eladalon248fd4f2017-09-06 05:18:15 -07002032 call_.reset();
2033 // The event log must outlive call (and any other object that uses it).
2034 event_log_.reset();
2035 });
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002036}
2037
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002038void PeerConnection::OnMessage(rtc::Message* msg) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002039 switch (msg->message_id) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002040 case MSG_SET_SESSIONDESCRIPTION_SUCCESS: {
2041 SetSessionDescriptionMsg* param =
2042 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
2043 param->observer->OnSuccess();
2044 delete param;
2045 break;
2046 }
2047 case MSG_SET_SESSIONDESCRIPTION_FAILED: {
2048 SetSessionDescriptionMsg* param =
2049 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
2050 param->observer->OnFailure(param->error);
2051 delete param;
2052 break;
2053 }
deadbeefab9b2d12015-10-14 11:33:11 -07002054 case MSG_CREATE_SESSIONDESCRIPTION_FAILED: {
2055 CreateSessionDescriptionMsg* param =
2056 static_cast<CreateSessionDescriptionMsg*>(msg->pdata);
2057 param->observer->OnFailure(param->error);
2058 delete param;
2059 break;
2060 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002061 case MSG_GETSTATS: {
2062 GetStatsMsg* param = static_cast<GetStatsMsg*>(msg->pdata);
nissee8abe3e2017-01-18 05:00:34 -08002063 StatsReports reports;
2064 stats_->GetStats(param->track, &reports);
2065 param->observer->OnComplete(reports);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002066 delete param;
2067 break;
2068 }
deadbeefbd292462015-12-14 18:15:29 -08002069 case MSG_FREE_DATACHANNELS: {
2070 sctp_data_channels_to_free_.clear();
2071 break;
2072 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002073 default:
nisseeb4ca4e2017-01-12 02:24:27 -08002074 RTC_NOTREACHED() << "Not implemented";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002075 break;
2076 }
2077}
2078
Steve Anton4171afb2017-11-20 10:20:22 -08002079void PeerConnection::CreateAudioReceiver(
2080 MediaStreamInterface* stream,
2081 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01002082 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
2083 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
zhihuang81c3a032016-11-17 12:06:24 -08002084 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
2085 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
deadbeefe814a0d2017-02-25 18:15:09 -08002086 signaling_thread(),
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01002087 new AudioRtpReceiver(remote_sender_info.sender_id, streams,
Steve Anton4171afb2017-11-20 10:20:22 -08002088 remote_sender_info.first_ssrc, voice_channel()));
deadbeefe814a0d2017-02-25 18:15:09 -08002089 stream->AddTrack(
2090 static_cast<AudioTrackInterface*>(receiver->internal()->track().get()));
Steve Anton4171afb2017-11-20 10:20:22 -08002091 GetAudioTransceiver()->internal()->AddReceiver(receiver);
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01002092 observer_->OnAddTrack(receiver, std::move(streams));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002093}
2094
Steve Anton4171afb2017-11-20 10:20:22 -08002095void PeerConnection::CreateVideoReceiver(
2096 MediaStreamInterface* stream,
2097 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01002098 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
2099 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
zhihuang81c3a032016-11-17 12:06:24 -08002100 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
2101 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
Steve Anton4171afb2017-11-20 10:20:22 -08002102 signaling_thread(),
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01002103 new VideoRtpReceiver(remote_sender_info.sender_id, streams,
2104 worker_thread(), remote_sender_info.first_ssrc,
2105 video_channel()));
deadbeefe814a0d2017-02-25 18:15:09 -08002106 stream->AddTrack(
2107 static_cast<VideoTrackInterface*>(receiver->internal()->track().get()));
Steve Anton4171afb2017-11-20 10:20:22 -08002108 GetVideoTransceiver()->internal()->AddReceiver(receiver);
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01002109 observer_->OnAddTrack(receiver, std::move(streams));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002110}
2111
deadbeef70ab1a12015-09-28 16:53:55 -07002112// TODO(deadbeef): Keep RtpReceivers around even if track goes away in remote
2113// description.
Henrik Boström933d8b02017-10-10 10:05:16 -07002114rtc::scoped_refptr<RtpReceiverInterface> PeerConnection::RemoveAndStopReceiver(
Steve Anton4171afb2017-11-20 10:20:22 -08002115 const RtpSenderInfo& remote_sender_info) {
2116 auto receiver = FindReceiverById(remote_sender_info.sender_id);
2117 if (!receiver) {
2118 RTC_LOG(LS_WARNING) << "RtpReceiver for track with id "
2119 << remote_sender_info.sender_id << " doesn't exist.";
Henrik Boström933d8b02017-10-10 10:05:16 -07002120 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07002121 }
Steve Anton4171afb2017-11-20 10:20:22 -08002122 if (receiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
2123 GetAudioTransceiver()->internal()->RemoveReceiver(receiver);
2124 } else {
2125 GetVideoTransceiver()->internal()->RemoveReceiver(receiver);
2126 }
Henrik Boström933d8b02017-10-10 10:05:16 -07002127 return receiver;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002128}
2129
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002130void PeerConnection::AddAudioTrack(AudioTrackInterface* track,
2131 MediaStreamInterface* stream) {
2132 RTC_DCHECK(!IsClosed());
2133 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08002134 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002135 // We already have a sender for this track, so just change the stream_id
2136 // so that it's correct in the next call to CreateOffer.
Steve Anton4171afb2017-11-20 10:20:22 -08002137 sender->internal()->set_stream_id(stream->label());
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002138 return;
2139 }
2140
2141 // Normal case; we've never seen this track before.
2142 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender =
2143 RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
2144 signaling_thread(),
Steve Anton75737c02017-11-06 10:37:17 -08002145 new AudioRtpSender(track, {stream->label()}, voice_channel(),
2146 stats_.get()));
Steve Anton4171afb2017-11-20 10:20:22 -08002147 GetAudioTransceiver()->internal()->AddSender(new_sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002148 // If the sender has already been configured in SDP, we call SetSsrc,
2149 // which will connect the sender to the underlying transport. This can
2150 // occur if a local session description that contains the ID of the sender
2151 // is set before AddStream is called. It can also occur if the local
2152 // session description is not changed and RemoveStream is called, and
2153 // later AddStream is called again with the same stream.
Steve Anton4171afb2017-11-20 10:20:22 -08002154 const RtpSenderInfo* sender_info =
2155 FindSenderInfo(local_audio_sender_infos_, stream->label(), track->id());
2156 if (sender_info) {
2157 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002158 }
2159}
2160
2161// TODO(deadbeef): Don't destroy RtpSenders here; they should be kept around
2162// indefinitely, when we have unified plan SDP.
2163void PeerConnection::RemoveAudioTrack(AudioTrackInterface* track,
2164 MediaStreamInterface* stream) {
2165 RTC_DCHECK(!IsClosed());
2166 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08002167 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002168 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
2169 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002170 return;
2171 }
Steve Anton4171afb2017-11-20 10:20:22 -08002172 GetAudioTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002173}
2174
2175void PeerConnection::AddVideoTrack(VideoTrackInterface* track,
2176 MediaStreamInterface* stream) {
2177 RTC_DCHECK(!IsClosed());
2178 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08002179 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002180 // We already have a sender for this track, so just change the stream_id
2181 // so that it's correct in the next call to CreateOffer.
Steve Anton4171afb2017-11-20 10:20:22 -08002182 sender->internal()->set_stream_id(stream->label());
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002183 return;
2184 }
2185
2186 // Normal case; we've never seen this track before.
2187 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender =
2188 RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton75737c02017-11-06 10:37:17 -08002189 signaling_thread(),
2190 new VideoRtpSender(track, {stream->label()}, video_channel()));
Steve Anton4171afb2017-11-20 10:20:22 -08002191 GetVideoTransceiver()->internal()->AddSender(new_sender);
2192 const RtpSenderInfo* sender_info =
2193 FindSenderInfo(local_video_sender_infos_, stream->label(), track->id());
2194 if (sender_info) {
2195 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002196 }
2197}
2198
2199void PeerConnection::RemoveVideoTrack(VideoTrackInterface* track,
2200 MediaStreamInterface* stream) {
2201 RTC_DCHECK(!IsClosed());
2202 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08002203 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002204 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
2205 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002206 return;
2207 }
Steve Anton4171afb2017-11-20 10:20:22 -08002208 GetVideoTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002209}
2210
Steve Antonba818672017-11-06 10:21:57 -08002211void PeerConnection::SetIceConnectionState(IceConnectionState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07002212 RTC_DCHECK(signaling_thread()->IsCurrent());
Steve Antonba818672017-11-06 10:21:57 -08002213 if (ice_connection_state_ == new_state) {
2214 return;
2215 }
2216
deadbeefcbecd352015-09-23 11:50:27 -07002217 // After transitioning to "closed", ignore any additional states from
Steve Antonba818672017-11-06 10:21:57 -08002218 // TransportController (such as "disconnected").
deadbeefab9b2d12015-10-14 11:33:11 -07002219 if (IsClosed()) {
deadbeefcbecd352015-09-23 11:50:27 -07002220 return;
2221 }
Steve Antonba818672017-11-06 10:21:57 -08002222
Mirko Bonadei675513b2017-11-09 11:09:25 +01002223 RTC_LOG(LS_INFO) << "Changing IceConnectionState " << ice_connection_state_
2224 << " => " << new_state;
Steve Antonba818672017-11-06 10:21:57 -08002225 RTC_DCHECK(ice_connection_state_ !=
2226 PeerConnectionInterface::kIceConnectionClosed);
2227
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002228 ice_connection_state_ = new_state;
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00002229 observer_->OnIceConnectionChange(ice_connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002230}
2231
2232void PeerConnection::OnIceGatheringChange(
2233 PeerConnectionInterface::IceGatheringState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07002234 RTC_DCHECK(signaling_thread()->IsCurrent());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002235 if (IsClosed()) {
2236 return;
2237 }
2238 ice_gathering_state_ = new_state;
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00002239 observer_->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002240}
2241
jbauch81bf7b02017-03-25 08:31:12 -07002242void PeerConnection::OnIceCandidate(
2243 std::unique_ptr<IceCandidateInterface> candidate) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07002244 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07002245 if (IsClosed()) {
2246 return;
2247 }
jbauch81bf7b02017-03-25 08:31:12 -07002248 observer_->OnIceCandidate(candidate.get());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002249}
2250
Honghai Zhang7fb69db2016-03-14 11:59:18 -07002251void PeerConnection::OnIceCandidatesRemoved(
2252 const std::vector<cricket::Candidate>& candidates) {
2253 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07002254 if (IsClosed()) {
2255 return;
2256 }
Honghai Zhang7fb69db2016-03-14 11:59:18 -07002257 observer_->OnIceCandidatesRemoved(candidates);
2258}
2259
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002260void PeerConnection::ChangeSignalingState(
2261 PeerConnectionInterface::SignalingState signaling_state) {
Steve Antonba818672017-11-06 10:21:57 -08002262 RTC_DCHECK(signaling_thread()->IsCurrent());
2263 if (signaling_state_ == signaling_state) {
2264 return;
2265 }
Mirko Bonadei675513b2017-11-09 11:09:25 +01002266 RTC_LOG(LS_INFO) << "Session: " << session_id() << " Old state: "
2267 << GetSignalingStateString(signaling_state_)
2268 << " New state: "
2269 << GetSignalingStateString(signaling_state);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002270 signaling_state_ = signaling_state;
2271 if (signaling_state == kClosed) {
2272 ice_connection_state_ = kIceConnectionClosed;
2273 observer_->OnIceConnectionChange(ice_connection_state_);
2274 if (ice_gathering_state_ != kIceGatheringComplete) {
2275 ice_gathering_state_ = kIceGatheringComplete;
2276 observer_->OnIceGatheringChange(ice_gathering_state_);
2277 }
2278 }
2279 observer_->OnSignalingChange(signaling_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002280}
2281
deadbeefeb459812015-12-15 19:24:43 -08002282void PeerConnection::OnAudioTrackAdded(AudioTrackInterface* track,
2283 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07002284 if (IsClosed()) {
2285 return;
2286 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002287 AddAudioTrack(track, stream);
2288 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08002289}
2290
deadbeefeb459812015-12-15 19:24:43 -08002291void PeerConnection::OnAudioTrackRemoved(AudioTrackInterface* track,
2292 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07002293 if (IsClosed()) {
2294 return;
2295 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002296 RemoveAudioTrack(track, stream);
2297 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08002298}
2299
2300void PeerConnection::OnVideoTrackAdded(VideoTrackInterface* track,
2301 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07002302 if (IsClosed()) {
2303 return;
2304 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002305 AddVideoTrack(track, stream);
2306 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08002307}
2308
2309void PeerConnection::OnVideoTrackRemoved(VideoTrackInterface* track,
2310 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07002311 if (IsClosed()) {
2312 return;
2313 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002314 RemoveVideoTrack(track, stream);
2315 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08002316}
2317
deadbeefab9b2d12015-10-14 11:33:11 -07002318void PeerConnection::PostSetSessionDescriptionFailure(
2319 SetSessionDescriptionObserver* observer,
2320 const std::string& error) {
2321 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
2322 msg->error = error;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07002323 signaling_thread()->Post(RTC_FROM_HERE, this,
2324 MSG_SET_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07002325}
2326
2327void PeerConnection::PostCreateSessionDescriptionFailure(
2328 CreateSessionDescriptionObserver* observer,
2329 const std::string& error) {
2330 CreateSessionDescriptionMsg* msg = new CreateSessionDescriptionMsg(observer);
2331 msg->error = error;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07002332 signaling_thread()->Post(RTC_FROM_HERE, this,
2333 MSG_CREATE_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07002334}
2335
zhihuang1c378ed2017-08-17 14:10:50 -07002336void PeerConnection::GetOptionsForOffer(
deadbeefab9b2d12015-10-14 11:33:11 -07002337 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options,
2338 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07002339 ExtractSharedMediaSessionOptions(rtc_options, session_options);
2340
2341 // Figure out transceiver directional preferences.
2342 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
2343 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
2344
2345 // By default, generate sendrecv/recvonly m= sections.
2346 bool recv_audio = true;
2347 bool recv_video = true;
2348
2349 // By default, only offer a new m= section if we have media to send with it.
2350 bool offer_new_audio_description = send_audio;
2351 bool offer_new_video_description = send_video;
2352 bool offer_new_data_description = HasDataChannels();
2353
2354 // The "offer_to_receive_X" options allow those defaults to be overridden.
2355 if (rtc_options.offer_to_receive_audio != RTCOfferAnswerOptions::kUndefined) {
2356 recv_audio = (rtc_options.offer_to_receive_audio > 0);
2357 offer_new_audio_description =
2358 offer_new_audio_description || (rtc_options.offer_to_receive_audio > 0);
2359 }
2360 if (rtc_options.offer_to_receive_video != RTCOfferAnswerOptions::kUndefined) {
2361 recv_video = (rtc_options.offer_to_receive_video > 0);
2362 offer_new_video_description =
2363 offer_new_video_description || (rtc_options.offer_to_receive_video > 0);
2364 }
2365
2366 rtc::Optional<size_t> audio_index;
2367 rtc::Optional<size_t> video_index;
2368 rtc::Optional<size_t> data_index;
2369 // If a current description exists, generate m= sections in the same order,
2370 // using the first audio/video/data section that appears and rejecting
2371 // extraneous ones.
Steve Anton75737c02017-11-06 10:37:17 -08002372 if (local_description()) {
zhihuang1c378ed2017-08-17 14:10:50 -07002373 GenerateMediaDescriptionOptions(
Steve Anton75737c02017-11-06 10:37:17 -08002374 local_description(),
zhihuang1c378ed2017-08-17 14:10:50 -07002375 cricket::RtpTransceiverDirection(send_audio, recv_audio),
2376 cricket::RtpTransceiverDirection(send_video, recv_video), &audio_index,
2377 &video_index, &data_index, session_options);
deadbeefab9b2d12015-10-14 11:33:11 -07002378 }
2379
zhihuang1c378ed2017-08-17 14:10:50 -07002380 // Add audio/video/data m= sections to the end if needed.
2381 if (!audio_index && offer_new_audio_description) {
2382 session_options->media_description_options.push_back(
2383 cricket::MediaDescriptionOptions(
2384 cricket::MEDIA_TYPE_AUDIO, cricket::CN_AUDIO,
2385 cricket::RtpTransceiverDirection(send_audio, recv_audio), false));
2386 audio_index = rtc::Optional<size_t>(
2387 session_options->media_description_options.size() - 1);
deadbeefc80741f2015-10-22 13:14:45 -07002388 }
zhihuang1c378ed2017-08-17 14:10:50 -07002389 if (!video_index && offer_new_video_description) {
2390 session_options->media_description_options.push_back(
2391 cricket::MediaDescriptionOptions(
2392 cricket::MEDIA_TYPE_VIDEO, cricket::CN_VIDEO,
2393 cricket::RtpTransceiverDirection(send_video, recv_video), false));
2394 video_index = rtc::Optional<size_t>(
2395 session_options->media_description_options.size() - 1);
deadbeefc80741f2015-10-22 13:14:45 -07002396 }
zhihuang1c378ed2017-08-17 14:10:50 -07002397 if (!data_index && offer_new_data_description) {
2398 session_options->media_description_options.push_back(
2399 cricket::MediaDescriptionOptions(
2400 cricket::MEDIA_TYPE_DATA, cricket::CN_DATA,
2401 cricket::RtpTransceiverDirection(true, true), false));
2402 data_index = rtc::Optional<size_t>(
2403 session_options->media_description_options.size() - 1);
2404 }
2405
2406 cricket::MediaDescriptionOptions* audio_media_description_options =
2407 !audio_index ? nullptr
2408 : &session_options->media_description_options[*audio_index];
2409 cricket::MediaDescriptionOptions* video_media_description_options =
2410 !video_index ? nullptr
2411 : &session_options->media_description_options[*video_index];
2412 cricket::MediaDescriptionOptions* data_media_description_options =
2413 !data_index ? nullptr
2414 : &session_options->media_description_options[*data_index];
2415
2416 // Apply ICE restart flag and renomination flag.
2417 for (auto& options : session_options->media_description_options) {
2418 options.transport_options.ice_restart = rtc_options.ice_restart;
2419 options.transport_options.enable_ice_renomination =
2420 configuration_.enable_ice_renomination;
2421 }
2422
Steve Anton4171afb2017-11-20 10:20:22 -08002423 AddRtpSenderOptions(GetSendersInternal(), audio_media_description_options,
zhihuang1c378ed2017-08-17 14:10:50 -07002424 video_media_description_options);
2425 AddRtpDataChannelOptions(rtp_data_channels_, data_media_description_options);
deadbeefc80741f2015-10-22 13:14:45 -07002426
zhihuang9763d562016-08-05 11:14:50 -07002427 // Intentionally unset the data channel type for RTP data channel with the
2428 // second condition. Otherwise the RTP data channels would be successfully
2429 // negotiated by default and the unit tests in WebRtcDataBrowserTest will fail
2430 // when building with chromium. We want to leave RTP data channels broken, so
2431 // people won't try to use them.
Steve Anton75737c02017-11-06 10:37:17 -08002432 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
2433 session_options->data_channel_type = data_channel_type();
deadbeefab9b2d12015-10-14 11:33:11 -07002434 }
zhihuang8f65cdf2016-05-06 18:40:30 -07002435
2436 session_options->rtcp_cname = rtcp_cname_;
jbauchcb560652016-08-04 05:20:32 -07002437 session_options->crypto_options = factory_->options().crypto_options;
deadbeefab9b2d12015-10-14 11:33:11 -07002438}
2439
zhihuang1c378ed2017-08-17 14:10:50 -07002440void PeerConnection::GetOptionsForAnswer(
2441 const RTCOfferAnswerOptions& rtc_options,
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07002442 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07002443 ExtractSharedMediaSessionOptions(rtc_options, session_options);
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07002444
zhihuang1c378ed2017-08-17 14:10:50 -07002445 // Figure out transceiver directional preferences.
2446 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
2447 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
2448
2449 // By default, generate sendrecv/recvonly m= sections. The direction is also
2450 // restricted by the direction in the offer.
2451 bool recv_audio = true;
2452 bool recv_video = true;
2453
2454 // The "offer_to_receive_X" options allow those defaults to be overridden.
2455 if (rtc_options.offer_to_receive_audio != RTCOfferAnswerOptions::kUndefined) {
2456 recv_audio = (rtc_options.offer_to_receive_audio > 0);
deadbeef0ed85b22016-02-23 17:24:52 -08002457 }
zhihuang1c378ed2017-08-17 14:10:50 -07002458 if (rtc_options.offer_to_receive_video != RTCOfferAnswerOptions::kUndefined) {
2459 recv_video = (rtc_options.offer_to_receive_video > 0);
2460 }
2461
2462 rtc::Optional<size_t> audio_index;
2463 rtc::Optional<size_t> video_index;
2464 rtc::Optional<size_t> data_index;
Steve Anton75737c02017-11-06 10:37:17 -08002465 if (remote_description()) {
zhihuang141aacb2017-08-29 13:23:53 -07002466 // The pending remote description should be an offer.
Steve Anton75737c02017-11-06 10:37:17 -08002467 RTC_DCHECK(remote_description()->type() ==
zhihuang141aacb2017-08-29 13:23:53 -07002468 SessionDescriptionInterface::kOffer);
2469 // Generate m= sections that match those in the offer.
2470 // Note that mediasession.cc will handle intersection our preferred
2471 // direction with the offered direction.
2472 GenerateMediaDescriptionOptions(
Steve Anton75737c02017-11-06 10:37:17 -08002473 remote_description(),
zhihuang141aacb2017-08-29 13:23:53 -07002474 cricket::RtpTransceiverDirection(send_audio, recv_audio),
2475 cricket::RtpTransceiverDirection(send_video, recv_video), &audio_index,
2476 &video_index, &data_index, session_options);
2477 }
zhihuang1c378ed2017-08-17 14:10:50 -07002478
2479 cricket::MediaDescriptionOptions* audio_media_description_options =
2480 !audio_index ? nullptr
2481 : &session_options->media_description_options[*audio_index];
2482 cricket::MediaDescriptionOptions* video_media_description_options =
2483 !video_index ? nullptr
2484 : &session_options->media_description_options[*video_index];
2485 cricket::MediaDescriptionOptions* data_media_description_options =
2486 !data_index ? nullptr
2487 : &session_options->media_description_options[*data_index];
2488
2489 // Apply ICE renomination flag.
2490 for (auto& options : session_options->media_description_options) {
2491 options.transport_options.enable_ice_renomination =
2492 configuration_.enable_ice_renomination;
2493 }
2494
Steve Anton4171afb2017-11-20 10:20:22 -08002495 AddRtpSenderOptions(GetSendersInternal(), audio_media_description_options,
zhihuang1c378ed2017-08-17 14:10:50 -07002496 video_media_description_options);
2497 AddRtpDataChannelOptions(rtp_data_channels_, data_media_description_options);
2498
zhihuang9763d562016-08-05 11:14:50 -07002499 // Intentionally unset the data channel type for RTP data channel. Otherwise
2500 // the RTP data channels would be successfully negotiated by default and the
2501 // unit tests in WebRtcDataBrowserTest will fail when building with chromium.
2502 // We want to leave RTP data channels broken, so people won't try to use them.
Steve Anton75737c02017-11-06 10:37:17 -08002503 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
2504 session_options->data_channel_type = data_channel_type();
deadbeef907abe42016-08-04 12:22:18 -07002505 }
zhihuangaf388472016-11-02 16:49:48 -07002506
zhihuang1c378ed2017-08-17 14:10:50 -07002507 session_options->rtcp_cname = rtcp_cname_;
jbauchcb560652016-08-04 05:20:32 -07002508 session_options->crypto_options = factory_->options().crypto_options;
htaa2a49d92016-03-04 02:51:39 -08002509}
2510
zhihuang1c378ed2017-08-17 14:10:50 -07002511void PeerConnection::GenerateMediaDescriptionOptions(
2512 const SessionDescriptionInterface* session_desc,
2513 cricket::RtpTransceiverDirection audio_direction,
2514 cricket::RtpTransceiverDirection video_direction,
2515 rtc::Optional<size_t>* audio_index,
2516 rtc::Optional<size_t>* video_index,
2517 rtc::Optional<size_t>* data_index,
htaa2a49d92016-03-04 02:51:39 -08002518 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07002519 for (const cricket::ContentInfo& content :
2520 session_desc->description()->contents()) {
2521 if (IsAudioContent(&content)) {
2522 // If we already have an audio m= section, reject this extra one.
2523 if (*audio_index) {
2524 session_options->media_description_options.push_back(
2525 cricket::MediaDescriptionOptions(
2526 cricket::MEDIA_TYPE_AUDIO, content.name,
2527 cricket::RtpTransceiverDirection(false, false), true));
2528 } else {
2529 session_options->media_description_options.push_back(
2530 cricket::MediaDescriptionOptions(
2531 cricket::MEDIA_TYPE_AUDIO, content.name, audio_direction,
2532 !audio_direction.send && !audio_direction.recv));
2533 *audio_index = rtc::Optional<size_t>(
2534 session_options->media_description_options.size() - 1);
2535 }
2536 } else if (IsVideoContent(&content)) {
2537 // If we already have an video m= section, reject this extra one.
2538 if (*video_index) {
2539 session_options->media_description_options.push_back(
2540 cricket::MediaDescriptionOptions(
2541 cricket::MEDIA_TYPE_VIDEO, content.name,
2542 cricket::RtpTransceiverDirection(false, false), true));
2543 } else {
2544 session_options->media_description_options.push_back(
2545 cricket::MediaDescriptionOptions(
2546 cricket::MEDIA_TYPE_VIDEO, content.name, video_direction,
2547 !video_direction.send && !video_direction.recv));
2548 *video_index = rtc::Optional<size_t>(
2549 session_options->media_description_options.size() - 1);
2550 }
2551 } else {
2552 RTC_DCHECK(IsDataContent(&content));
2553 // If we already have an data m= section, reject this extra one.
2554 if (*data_index) {
2555 session_options->media_description_options.push_back(
2556 cricket::MediaDescriptionOptions(
2557 cricket::MEDIA_TYPE_DATA, content.name,
2558 cricket::RtpTransceiverDirection(false, false), true));
2559 } else {
2560 session_options->media_description_options.push_back(
2561 cricket::MediaDescriptionOptions(
2562 cricket::MEDIA_TYPE_DATA, content.name,
2563 // Direction for data sections is meaningless, but legacy
2564 // endpoints might expect sendrecv.
2565 cricket::RtpTransceiverDirection(true, true), false));
2566 *data_index = rtc::Optional<size_t>(
2567 session_options->media_description_options.size() - 1);
2568 }
2569 }
htaa2a49d92016-03-04 02:51:39 -08002570 }
deadbeefab9b2d12015-10-14 11:33:11 -07002571}
2572
Steve Anton4171afb2017-11-20 10:20:22 -08002573void PeerConnection::RemoveSenders(cricket::MediaType media_type) {
2574 UpdateLocalSenders(std::vector<cricket::StreamParams>(), media_type);
2575 UpdateRemoteSendersList(std::vector<cricket::StreamParams>(), false,
deadbeefbda7e0b2015-12-08 17:13:40 -08002576 media_type, nullptr);
deadbeeffaac4972015-11-12 15:33:07 -08002577}
2578
Steve Anton4171afb2017-11-20 10:20:22 -08002579void PeerConnection::UpdateRemoteSendersList(
deadbeefab9b2d12015-10-14 11:33:11 -07002580 const cricket::StreamParamsVec& streams,
Steve Anton4171afb2017-11-20 10:20:22 -08002581 bool default_sender_needed,
deadbeefab9b2d12015-10-14 11:33:11 -07002582 cricket::MediaType media_type,
2583 StreamCollection* new_streams) {
Steve Anton4171afb2017-11-20 10:20:22 -08002584 std::vector<RtpSenderInfo>* current_senders =
2585 GetRemoteSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07002586
Steve Anton4171afb2017-11-20 10:20:22 -08002587 // Find removed senders. I.e., senders where the sender id or ssrc don't match
deadbeeffac06552015-11-25 11:26:01 -08002588 // the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08002589 for (auto sender_it = current_senders->begin();
2590 sender_it != current_senders->end();
2591 /* incremented manually */) {
2592 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07002593 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08002594 cricket::GetStreamBySsrc(streams, info.first_ssrc);
2595 bool sender_exists = params && params->id == info.sender_id;
deadbeefbda7e0b2015-12-08 17:13:40 -08002596 // If this is a default track, and we still need it, don't remove it.
Steve Anton4171afb2017-11-20 10:20:22 -08002597 if ((info.stream_label == kDefaultStreamLabel && default_sender_needed) ||
2598 sender_exists) {
2599 ++sender_it;
deadbeefbda7e0b2015-12-08 17:13:40 -08002600 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08002601 OnRemoteSenderRemoved(info, media_type);
2602 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07002603 }
2604 }
2605
Steve Anton4171afb2017-11-20 10:20:22 -08002606 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07002607 for (const cricket::StreamParams& params : streams) {
2608 // The sync_label is the MediaStream label and the |stream.id| is the
Steve Anton4171afb2017-11-20 10:20:22 -08002609 // sender id.
deadbeefab9b2d12015-10-14 11:33:11 -07002610 const std::string& stream_label = params.sync_label;
Steve Anton4171afb2017-11-20 10:20:22 -08002611 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07002612 uint32_t ssrc = params.first_ssrc();
2613
2614 rtc::scoped_refptr<MediaStreamInterface> stream =
2615 remote_streams_->find(stream_label);
2616 if (!stream) {
2617 // This is a new MediaStream. Create a new remote MediaStream.
perkjd61bf802016-03-24 03:16:19 -07002618 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
2619 MediaStream::Create(stream_label));
deadbeefab9b2d12015-10-14 11:33:11 -07002620 remote_streams_->AddStream(stream);
2621 new_streams->AddStream(stream);
2622 }
2623
Steve Anton4171afb2017-11-20 10:20:22 -08002624 const RtpSenderInfo* sender_info =
2625 FindSenderInfo(*current_senders, stream_label, sender_id);
2626 if (!sender_info) {
2627 current_senders->push_back(RtpSenderInfo(stream_label, sender_id, ssrc));
2628 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07002629 }
2630 }
deadbeefbda7e0b2015-12-08 17:13:40 -08002631
Steve Anton4171afb2017-11-20 10:20:22 -08002632 // Add default sender if necessary.
2633 if (default_sender_needed) {
deadbeefbda7e0b2015-12-08 17:13:40 -08002634 rtc::scoped_refptr<MediaStreamInterface> default_stream =
2635 remote_streams_->find(kDefaultStreamLabel);
2636 if (!default_stream) {
2637 // Create the new default MediaStream.
perkjd61bf802016-03-24 03:16:19 -07002638 default_stream = MediaStreamProxy::Create(
2639 rtc::Thread::Current(), MediaStream::Create(kDefaultStreamLabel));
deadbeefbda7e0b2015-12-08 17:13:40 -08002640 remote_streams_->AddStream(default_stream);
2641 new_streams->AddStream(default_stream);
2642 }
Steve Anton4171afb2017-11-20 10:20:22 -08002643 std::string default_sender_id = (media_type == cricket::MEDIA_TYPE_AUDIO)
2644 ? kDefaultAudioSenderId
2645 : kDefaultVideoSenderId;
2646 const RtpSenderInfo* default_sender_info = FindSenderInfo(
2647 *current_senders, kDefaultStreamLabel, default_sender_id);
2648 if (!default_sender_info) {
2649 current_senders->push_back(
2650 RtpSenderInfo(kDefaultStreamLabel, default_sender_id, 0));
2651 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefbda7e0b2015-12-08 17:13:40 -08002652 }
2653 }
deadbeefab9b2d12015-10-14 11:33:11 -07002654}
2655
Steve Anton4171afb2017-11-20 10:20:22 -08002656void PeerConnection::OnRemoteSenderAdded(const RtpSenderInfo& sender_info,
2657 cricket::MediaType media_type) {
2658 MediaStreamInterface* stream =
2659 remote_streams_->find(sender_info.stream_label);
deadbeefab9b2d12015-10-14 11:33:11 -07002660
2661 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 10:20:22 -08002662 CreateAudioReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07002663 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 10:20:22 -08002664 CreateVideoReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07002665 } else {
nisseeb4ca4e2017-01-12 02:24:27 -08002666 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07002667 }
2668}
2669
Steve Anton4171afb2017-11-20 10:20:22 -08002670void PeerConnection::OnRemoteSenderRemoved(const RtpSenderInfo& sender_info,
2671 cricket::MediaType media_type) {
2672 MediaStreamInterface* stream =
2673 remote_streams_->find(sender_info.stream_label);
deadbeefab9b2d12015-10-14 11:33:11 -07002674
Henrik Boström933d8b02017-10-10 10:05:16 -07002675 rtc::scoped_refptr<RtpReceiverInterface> receiver;
deadbeefab9b2d12015-10-14 11:33:11 -07002676 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
perkjd61bf802016-03-24 03:16:19 -07002677 // When the MediaEngine audio channel is destroyed, the RemoteAudioSource
2678 // will be notified which will end the AudioRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08002679 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07002680 rtc::scoped_refptr<AudioTrackInterface> audio_track =
Steve Anton4171afb2017-11-20 10:20:22 -08002681 stream->FindAudioTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07002682 if (audio_track) {
deadbeefab9b2d12015-10-14 11:33:11 -07002683 stream->RemoveTrack(audio_track);
deadbeefab9b2d12015-10-14 11:33:11 -07002684 }
2685 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
perkjd61bf802016-03-24 03:16:19 -07002686 // Stopping or destroying a VideoRtpReceiver will end the
2687 // VideoRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08002688 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07002689 rtc::scoped_refptr<VideoTrackInterface> video_track =
Steve Anton4171afb2017-11-20 10:20:22 -08002690 stream->FindVideoTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07002691 if (video_track) {
perkjd61bf802016-03-24 03:16:19 -07002692 // There's no guarantee the track is still available, e.g. the track may
2693 // have been removed from the stream by an application.
deadbeefab9b2d12015-10-14 11:33:11 -07002694 stream->RemoveTrack(video_track);
deadbeefab9b2d12015-10-14 11:33:11 -07002695 }
2696 } else {
nisseede5da42017-01-12 05:15:36 -08002697 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07002698 }
Henrik Boström933d8b02017-10-10 10:05:16 -07002699 if (receiver) {
2700 observer_->OnRemoveTrack(receiver);
2701 }
deadbeefab9b2d12015-10-14 11:33:11 -07002702}
2703
2704void PeerConnection::UpdateEndedRemoteMediaStreams() {
2705 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams_to_remove;
2706 for (size_t i = 0; i < remote_streams_->count(); ++i) {
2707 MediaStreamInterface* stream = remote_streams_->at(i);
2708 if (stream->GetAudioTracks().empty() && stream->GetVideoTracks().empty()) {
2709 streams_to_remove.push_back(stream);
2710 }
2711 }
2712
Taylor Brandstetter98cde262016-05-31 13:02:21 -07002713 for (auto& stream : streams_to_remove) {
deadbeefab9b2d12015-10-14 11:33:11 -07002714 remote_streams_->RemoveStream(stream);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07002715 observer_->OnRemoveStream(std::move(stream));
deadbeefab9b2d12015-10-14 11:33:11 -07002716 }
2717}
2718
Steve Anton4171afb2017-11-20 10:20:22 -08002719void PeerConnection::UpdateLocalSenders(
deadbeefab9b2d12015-10-14 11:33:11 -07002720 const std::vector<cricket::StreamParams>& streams,
2721 cricket::MediaType media_type) {
Steve Anton4171afb2017-11-20 10:20:22 -08002722 std::vector<RtpSenderInfo>* current_senders = GetLocalSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07002723
2724 // Find removed tracks. I.e., tracks where the track id, stream label or ssrc
2725 // don't match the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08002726 for (auto sender_it = current_senders->begin();
2727 sender_it != current_senders->end();
2728 /* incremented manually */) {
2729 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07002730 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08002731 cricket::GetStreamBySsrc(streams, info.first_ssrc);
2732 if (!params || params->id != info.sender_id ||
deadbeefab9b2d12015-10-14 11:33:11 -07002733 params->sync_label != info.stream_label) {
Steve Anton4171afb2017-11-20 10:20:22 -08002734 OnLocalSenderRemoved(info, media_type);
2735 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07002736 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08002737 ++sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07002738 }
2739 }
2740
Steve Anton4171afb2017-11-20 10:20:22 -08002741 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07002742 for (const cricket::StreamParams& params : streams) {
2743 // The sync_label is the MediaStream label and the |stream.id| is the
Steve Anton4171afb2017-11-20 10:20:22 -08002744 // sender id.
deadbeefab9b2d12015-10-14 11:33:11 -07002745 const std::string& stream_label = params.sync_label;
Steve Anton4171afb2017-11-20 10:20:22 -08002746 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07002747 uint32_t ssrc = params.first_ssrc();
Steve Anton4171afb2017-11-20 10:20:22 -08002748 const RtpSenderInfo* sender_info =
2749 FindSenderInfo(*current_senders, stream_label, sender_id);
2750 if (!sender_info) {
2751 current_senders->push_back(RtpSenderInfo(stream_label, sender_id, ssrc));
2752 OnLocalSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07002753 }
2754 }
2755}
2756
Steve Anton4171afb2017-11-20 10:20:22 -08002757void PeerConnection::OnLocalSenderAdded(const RtpSenderInfo& sender_info,
2758 cricket::MediaType media_type) {
2759 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08002760 if (!sender) {
Steve Anton4171afb2017-11-20 10:20:22 -08002761 RTC_LOG(LS_WARNING) << "An unknown RtpSender with id "
2762 << sender_info.sender_id
Mirko Bonadei675513b2017-11-09 11:09:25 +01002763 << " has been configured in the local description.";
deadbeefab9b2d12015-10-14 11:33:11 -07002764 return;
2765 }
2766
deadbeeffac06552015-11-25 11:26:01 -08002767 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002768 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
2769 << " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08002770 return;
deadbeefab9b2d12015-10-14 11:33:11 -07002771 }
deadbeeffac06552015-11-25 11:26:01 -08002772
Steve Anton4171afb2017-11-20 10:20:22 -08002773 sender->internal()->set_stream_id(sender_info.stream_label);
2774 sender->internal()->SetSsrc(sender_info.first_ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07002775}
2776
Steve Anton4171afb2017-11-20 10:20:22 -08002777void PeerConnection::OnLocalSenderRemoved(const RtpSenderInfo& sender_info,
2778 cricket::MediaType media_type) {
2779 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08002780 if (!sender) {
2781 // This is the normal case. I.e., RemoveStream has been called and the
deadbeefab9b2d12015-10-14 11:33:11 -07002782 // SessionDescriptions has been renegotiated.
2783 return;
2784 }
deadbeeffac06552015-11-25 11:26:01 -08002785
2786 // A sender has been removed from the SessionDescription but it's still
2787 // associated with the PeerConnection. This only occurs if the SDP doesn't
2788 // match with the calls to CreateSender, AddStream and RemoveStream.
2789 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002790 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
2791 << " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08002792 return;
deadbeefab9b2d12015-10-14 11:33:11 -07002793 }
deadbeeffac06552015-11-25 11:26:01 -08002794
Steve Anton4171afb2017-11-20 10:20:22 -08002795 sender->internal()->SetSsrc(0);
deadbeefab9b2d12015-10-14 11:33:11 -07002796}
2797
2798void PeerConnection::UpdateLocalRtpDataChannels(
2799 const cricket::StreamParamsVec& streams) {
2800 std::vector<std::string> existing_channels;
2801
2802 // Find new and active data channels.
2803 for (const cricket::StreamParams& params : streams) {
2804 // |it->sync_label| is actually the data channel label. The reason is that
2805 // we use the same naming of data channels as we do for
2806 // MediaStreams and Tracks.
2807 // For MediaStreams, the sync_label is the MediaStream label and the
2808 // track label is the same as |streamid|.
2809 const std::string& channel_label = params.sync_label;
2810 auto data_channel_it = rtp_data_channels_.find(channel_label);
nisse7ce109a2017-01-31 00:57:56 -08002811 if (data_channel_it == rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002812 RTC_LOG(LS_ERROR) << "channel label not found";
deadbeefab9b2d12015-10-14 11:33:11 -07002813 continue;
2814 }
2815 // Set the SSRC the data channel should use for sending.
2816 data_channel_it->second->SetSendSsrc(params.first_ssrc());
2817 existing_channels.push_back(data_channel_it->first);
2818 }
2819
2820 UpdateClosingRtpDataChannels(existing_channels, true);
2821}
2822
2823void PeerConnection::UpdateRemoteRtpDataChannels(
2824 const cricket::StreamParamsVec& streams) {
2825 std::vector<std::string> existing_channels;
2826
2827 // Find new and active data channels.
2828 for (const cricket::StreamParams& params : streams) {
2829 // The data channel label is either the mslabel or the SSRC if the mslabel
2830 // does not exist. Ex a=ssrc:444330170 mslabel:test1.
2831 std::string label = params.sync_label.empty()
2832 ? rtc::ToString(params.first_ssrc())
2833 : params.sync_label;
2834 auto data_channel_it = rtp_data_channels_.find(label);
2835 if (data_channel_it == rtp_data_channels_.end()) {
2836 // This is a new data channel.
2837 CreateRemoteRtpDataChannel(label, params.first_ssrc());
2838 } else {
2839 data_channel_it->second->SetReceiveSsrc(params.first_ssrc());
2840 }
2841 existing_channels.push_back(label);
2842 }
2843
2844 UpdateClosingRtpDataChannels(existing_channels, false);
2845}
2846
2847void PeerConnection::UpdateClosingRtpDataChannels(
2848 const std::vector<std::string>& active_channels,
2849 bool is_local_update) {
2850 auto it = rtp_data_channels_.begin();
2851 while (it != rtp_data_channels_.end()) {
2852 DataChannel* data_channel = it->second;
2853 if (std::find(active_channels.begin(), active_channels.end(),
2854 data_channel->label()) != active_channels.end()) {
2855 ++it;
2856 continue;
2857 }
2858
2859 if (is_local_update) {
2860 data_channel->SetSendSsrc(0);
2861 } else {
2862 data_channel->RemotePeerRequestClose();
2863 }
2864
2865 if (data_channel->state() == DataChannel::kClosed) {
2866 rtp_data_channels_.erase(it);
2867 it = rtp_data_channels_.begin();
2868 } else {
2869 ++it;
2870 }
2871 }
2872}
2873
2874void PeerConnection::CreateRemoteRtpDataChannel(const std::string& label,
2875 uint32_t remote_ssrc) {
2876 rtc::scoped_refptr<DataChannel> channel(
2877 InternalCreateDataChannel(label, nullptr));
2878 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002879 RTC_LOG(LS_WARNING) << "Remote peer requested a DataChannel but"
2880 << "CreateDataChannel failed.";
deadbeefab9b2d12015-10-14 11:33:11 -07002881 return;
2882 }
2883 channel->SetReceiveSsrc(remote_ssrc);
deadbeefa601f5c2016-06-06 14:27:39 -07002884 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
2885 DataChannelProxy::Create(signaling_thread(), channel);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07002886 observer_->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07002887}
2888
2889rtc::scoped_refptr<DataChannel> PeerConnection::InternalCreateDataChannel(
2890 const std::string& label,
2891 const InternalDataChannelInit* config) {
2892 if (IsClosed()) {
2893 return nullptr;
2894 }
Steve Anton75737c02017-11-06 10:37:17 -08002895 if (data_channel_type() == cricket::DCT_NONE) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002896 RTC_LOG(LS_ERROR)
deadbeefab9b2d12015-10-14 11:33:11 -07002897 << "InternalCreateDataChannel: Data is not supported in this call.";
2898 return nullptr;
2899 }
2900 InternalDataChannelInit new_config =
2901 config ? (*config) : InternalDataChannelInit();
Steve Anton75737c02017-11-06 10:37:17 -08002902 if (data_channel_type() == cricket::DCT_SCTP) {
deadbeefab9b2d12015-10-14 11:33:11 -07002903 if (new_config.id < 0) {
2904 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08002905 if ((GetSctpSslRole(&role)) &&
deadbeefab9b2d12015-10-14 11:33:11 -07002906 !sid_allocator_.AllocateSid(role, &new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002907 RTC_LOG(LS_ERROR)
2908 << "No id can be allocated for the SCTP data channel.";
deadbeefab9b2d12015-10-14 11:33:11 -07002909 return nullptr;
2910 }
2911 } else if (!sid_allocator_.ReserveSid(new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002912 RTC_LOG(LS_ERROR) << "Failed to create a SCTP data channel "
2913 << "because the id is already in use or out of range.";
deadbeefab9b2d12015-10-14 11:33:11 -07002914 return nullptr;
2915 }
2916 }
2917
Steve Anton75737c02017-11-06 10:37:17 -08002918 rtc::scoped_refptr<DataChannel> channel(
2919 DataChannel::Create(this, data_channel_type(), label, new_config));
deadbeefab9b2d12015-10-14 11:33:11 -07002920 if (!channel) {
2921 sid_allocator_.ReleaseSid(new_config.id);
2922 return nullptr;
2923 }
2924
2925 if (channel->data_channel_type() == cricket::DCT_RTP) {
2926 if (rtp_data_channels_.find(channel->label()) != rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002927 RTC_LOG(LS_ERROR) << "DataChannel with label " << channel->label()
2928 << " already exists.";
deadbeefab9b2d12015-10-14 11:33:11 -07002929 return nullptr;
2930 }
2931 rtp_data_channels_[channel->label()] = channel;
2932 } else {
2933 RTC_DCHECK(channel->data_channel_type() == cricket::DCT_SCTP);
2934 sctp_data_channels_.push_back(channel);
2935 channel->SignalClosed.connect(this,
2936 &PeerConnection::OnSctpDataChannelClosed);
2937 }
2938
hbos82ebe022016-11-14 01:41:09 -08002939 SignalDataChannelCreated(channel.get());
deadbeefab9b2d12015-10-14 11:33:11 -07002940 return channel;
2941}
2942
2943bool PeerConnection::HasDataChannels() const {
2944 return !rtp_data_channels_.empty() || !sctp_data_channels_.empty();
2945}
2946
2947void PeerConnection::AllocateSctpSids(rtc::SSLRole role) {
2948 for (const auto& channel : sctp_data_channels_) {
2949 if (channel->id() < 0) {
2950 int sid;
2951 if (!sid_allocator_.AllocateSid(role, &sid)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002952 RTC_LOG(LS_ERROR) << "Failed to allocate SCTP sid.";
deadbeefab9b2d12015-10-14 11:33:11 -07002953 continue;
2954 }
2955 channel->SetSctpSid(sid);
2956 }
2957 }
2958}
2959
2960void PeerConnection::OnSctpDataChannelClosed(DataChannel* channel) {
deadbeefbd292462015-12-14 18:15:29 -08002961 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeefab9b2d12015-10-14 11:33:11 -07002962 for (auto it = sctp_data_channels_.begin(); it != sctp_data_channels_.end();
2963 ++it) {
2964 if (it->get() == channel) {
2965 if (channel->id() >= 0) {
2966 sid_allocator_.ReleaseSid(channel->id());
2967 }
deadbeefbd292462015-12-14 18:15:29 -08002968 // Since this method is triggered by a signal from the DataChannel,
2969 // we can't free it directly here; we need to free it asynchronously.
2970 sctp_data_channels_to_free_.push_back(*it);
deadbeefab9b2d12015-10-14 11:33:11 -07002971 sctp_data_channels_.erase(it);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07002972 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_FREE_DATACHANNELS,
2973 nullptr);
deadbeefab9b2d12015-10-14 11:33:11 -07002974 return;
2975 }
2976 }
2977}
2978
deadbeefab9b2d12015-10-14 11:33:11 -07002979void PeerConnection::OnDataChannelDestroyed() {
2980 // Use a temporary copy of the RTP/SCTP DataChannel list because the
2981 // DataChannel may callback to us and try to modify the list.
2982 std::map<std::string, rtc::scoped_refptr<DataChannel>> temp_rtp_dcs;
2983 temp_rtp_dcs.swap(rtp_data_channels_);
2984 for (const auto& kv : temp_rtp_dcs) {
2985 kv.second->OnTransportChannelDestroyed();
2986 }
2987
2988 std::vector<rtc::scoped_refptr<DataChannel>> temp_sctp_dcs;
2989 temp_sctp_dcs.swap(sctp_data_channels_);
2990 for (const auto& channel : temp_sctp_dcs) {
2991 channel->OnTransportChannelDestroyed();
2992 }
2993}
2994
2995void PeerConnection::OnDataChannelOpenMessage(
2996 const std::string& label,
2997 const InternalDataChannelInit& config) {
2998 rtc::scoped_refptr<DataChannel> channel(
2999 InternalCreateDataChannel(label, &config));
3000 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003001 RTC_LOG(LS_ERROR) << "Failed to create DataChannel from the OPEN message.";
deadbeefab9b2d12015-10-14 11:33:11 -07003002 return;
3003 }
3004
deadbeefa601f5c2016-06-06 14:27:39 -07003005 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
3006 DataChannelProxy::Create(signaling_thread(), channel);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07003007 observer_->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07003008}
3009
Steve Anton4171afb2017-11-20 10:20:22 -08003010rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3011PeerConnection::GetAudioTransceiver() const {
3012 // This method only works with Plan B SDP, where there is a single
3013 // audio/video transceiver.
3014 RTC_DCHECK(!IsUnifiedPlan());
3015 for (auto transceiver : transceivers_) {
3016 if (transceiver->internal()->media_type() == cricket::MEDIA_TYPE_AUDIO) {
3017 return transceiver;
3018 }
3019 }
3020 RTC_NOTREACHED();
3021 return nullptr;
3022}
3023
3024rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3025PeerConnection::GetVideoTransceiver() const {
3026 // This method only works with Plan B SDP, where there is a single
3027 // audio/video transceiver.
3028 RTC_DCHECK(!IsUnifiedPlan());
3029 for (auto transceiver : transceivers_) {
3030 if (transceiver->internal()->media_type() == cricket::MEDIA_TYPE_VIDEO) {
3031 return transceiver;
3032 }
3033 }
3034 RTC_NOTREACHED();
3035 return nullptr;
3036}
3037
3038// TODO(bugs.webrtc.org/7600): Remove this when multiple transceivers with
3039// individual transceiver directions are supported.
zhihuang1c378ed2017-08-17 14:10:50 -07003040bool PeerConnection::HasRtpSender(cricket::MediaType type) const {
Steve Anton4171afb2017-11-20 10:20:22 -08003041 switch (type) {
3042 case cricket::MEDIA_TYPE_AUDIO:
3043 return !GetAudioTransceiver()->internal()->senders().empty();
3044 case cricket::MEDIA_TYPE_VIDEO:
3045 return !GetVideoTransceiver()->internal()->senders().empty();
3046 case cricket::MEDIA_TYPE_DATA:
3047 return false;
3048 }
3049 RTC_NOTREACHED();
3050 return false;
zhihuang1c378ed2017-08-17 14:10:50 -07003051}
3052
Steve Anton4171afb2017-11-20 10:20:22 -08003053rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
3054PeerConnection::FindSenderForTrack(MediaStreamTrackInterface* track) const {
3055 for (auto transceiver : transceivers_) {
3056 for (auto sender : transceiver->internal()->senders()) {
3057 if (sender->track() == track) {
3058 return sender;
3059 }
3060 }
3061 }
3062 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08003063}
3064
Steve Anton4171afb2017-11-20 10:20:22 -08003065rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
3066PeerConnection::FindSenderById(const std::string& sender_id) const {
3067 for (auto transceiver : transceivers_) {
3068 for (auto sender : transceiver->internal()->senders()) {
3069 if (sender->id() == sender_id) {
3070 return sender;
3071 }
3072 }
3073 }
3074 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07003075}
3076
Steve Anton4171afb2017-11-20 10:20:22 -08003077rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
3078PeerConnection::FindReceiverById(const std::string& receiver_id) const {
3079 for (auto transceiver : transceivers_) {
3080 for (auto receiver : transceiver->internal()->receivers()) {
3081 if (receiver->id() == receiver_id) {
3082 return receiver;
3083 }
3084 }
3085 }
3086 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07003087}
3088
Steve Anton4171afb2017-11-20 10:20:22 -08003089std::vector<PeerConnection::RtpSenderInfo>*
3090PeerConnection::GetRemoteSenderInfos(cricket::MediaType media_type) {
3091 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
3092 media_type == cricket::MEDIA_TYPE_VIDEO);
3093 return (media_type == cricket::MEDIA_TYPE_AUDIO)
3094 ? &remote_audio_sender_infos_
3095 : &remote_video_sender_infos_;
3096}
3097
3098std::vector<PeerConnection::RtpSenderInfo>* PeerConnection::GetLocalSenderInfos(
deadbeefab9b2d12015-10-14 11:33:11 -07003099 cricket::MediaType media_type) {
3100 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
3101 media_type == cricket::MEDIA_TYPE_VIDEO);
Steve Anton4171afb2017-11-20 10:20:22 -08003102 return (media_type == cricket::MEDIA_TYPE_AUDIO) ? &local_audio_sender_infos_
3103 : &local_video_sender_infos_;
deadbeefab9b2d12015-10-14 11:33:11 -07003104}
3105
Steve Anton4171afb2017-11-20 10:20:22 -08003106const PeerConnection::RtpSenderInfo* PeerConnection::FindSenderInfo(
3107 const std::vector<PeerConnection::RtpSenderInfo>& infos,
deadbeefab9b2d12015-10-14 11:33:11 -07003108 const std::string& stream_label,
Steve Anton4171afb2017-11-20 10:20:22 -08003109 const std::string sender_id) const {
3110 for (const RtpSenderInfo& sender_info : infos) {
3111 if (sender_info.stream_label == stream_label &&
3112 sender_info.sender_id == sender_id) {
3113 return &sender_info;
deadbeefab9b2d12015-10-14 11:33:11 -07003114 }
3115 }
3116 return nullptr;
3117}
3118
3119DataChannel* PeerConnection::FindDataChannelBySid(int sid) const {
3120 for (const auto& channel : sctp_data_channels_) {
3121 if (channel->id() == sid) {
3122 return channel;
3123 }
3124 }
3125 return nullptr;
3126}
3127
deadbeef91dd5672016-05-18 16:55:30 -07003128bool PeerConnection::InitializePortAllocator_n(
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003129 const RTCConfiguration& configuration) {
3130 cricket::ServerAddresses stun_servers;
3131 std::vector<cricket::RelayServerConfig> turn_servers;
deadbeef293e9262017-01-11 12:28:30 -08003132 if (ParseIceServers(configuration.servers, &stun_servers, &turn_servers) !=
3133 RTCErrorType::NONE) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003134 return false;
3135 }
3136
Taylor Brandstetterf8e65772016-06-27 17:20:15 -07003137 port_allocator_->Initialize();
3138
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003139 // To handle both internal and externally created port allocator, we will
3140 // enable BUNDLE here.
3141 int portallocator_flags = port_allocator_->flags();
3142 portallocator_flags |= cricket::PORTALLOCATOR_ENABLE_SHARED_SOCKET |
zhihuangb09b3f92017-03-07 14:40:51 -08003143 cricket::PORTALLOCATOR_ENABLE_IPV6 |
3144 cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI;
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003145 // If the disable-IPv6 flag was specified, we'll not override it
3146 // by experiment.
3147 if (configuration.disable_ipv6) {
3148 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
sprangc1b57a12017-02-28 08:50:47 -08003149 } else if (webrtc::field_trial::FindFullName("WebRTC-IPv6Default")
3150 .find("Disabled") == 0) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003151 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
3152 }
3153
zhihuangb09b3f92017-03-07 14:40:51 -08003154 if (configuration.disable_ipv6_on_wifi) {
3155 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI);
Mirko Bonadei675513b2017-11-09 11:09:25 +01003156 RTC_LOG(LS_INFO) << "IPv6 candidates on Wi-Fi are disabled.";
zhihuangb09b3f92017-03-07 14:40:51 -08003157 }
3158
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003159 if (configuration.tcp_candidate_policy == kTcpCandidatePolicyDisabled) {
3160 portallocator_flags |= cricket::PORTALLOCATOR_DISABLE_TCP;
Mirko Bonadei675513b2017-11-09 11:09:25 +01003161 RTC_LOG(LS_INFO) << "TCP candidates are disabled.";
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003162 }
3163
honghaiz60347052016-05-31 18:29:12 -07003164 if (configuration.candidate_network_policy ==
3165 kCandidateNetworkPolicyLowCost) {
3166 portallocator_flags |= cricket::PORTALLOCATOR_DISABLE_COSTLY_NETWORKS;
Mirko Bonadei675513b2017-11-09 11:09:25 +01003167 RTC_LOG(LS_INFO) << "Do not gather candidates on high-cost networks";
honghaiz60347052016-05-31 18:29:12 -07003168 }
3169
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003170 port_allocator_->set_flags(portallocator_flags);
3171 // No step delay is used while allocating ports.
3172 port_allocator_->set_step_delay(cricket::kMinimumStepDelay);
3173 port_allocator_->set_candidate_filter(
3174 ConvertIceTransportTypeToCandidateFilter(configuration.type));
deadbeefd21eab32017-07-26 16:50:11 -07003175 port_allocator_->set_max_ipv6_networks(configuration.max_ipv6_networks);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003176
3177 // Call this last since it may create pooled allocator sessions using the
3178 // properties set above.
3179 port_allocator_->SetConfiguration(stun_servers, turn_servers,
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -07003180 configuration.ice_candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02003181 configuration.prune_turn_ports,
3182 configuration.turn_customizer);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003183 return true;
3184}
3185
deadbeef91dd5672016-05-18 16:55:30 -07003186bool PeerConnection::ReconfigurePortAllocator_n(
deadbeef293e9262017-01-11 12:28:30 -08003187 const cricket::ServerAddresses& stun_servers,
3188 const std::vector<cricket::RelayServerConfig>& turn_servers,
3189 IceTransportsType type,
3190 int candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02003191 bool prune_turn_ports,
3192 webrtc::TurnCustomizer* turn_customizer) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003193 port_allocator_->set_candidate_filter(
deadbeef293e9262017-01-11 12:28:30 -08003194 ConvertIceTransportTypeToCandidateFilter(type));
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003195 // Call this last since it may create pooled allocator sessions using the
3196 // candidate filter set above.
deadbeef6de92f92016-12-12 18:49:32 -08003197 return port_allocator_->SetConfiguration(
Jonas Orelandbdcee282017-10-10 14:01:40 +02003198 stun_servers, turn_servers, candidate_pool_size, prune_turn_ports,
3199 turn_customizer);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003200}
3201
Steve Antonba818672017-11-06 10:21:57 -08003202cricket::ChannelManager* PeerConnection::channel_manager() const {
3203 return factory_->channel_manager();
3204}
3205
3206MetricsObserverInterface* PeerConnection::metrics_observer() const {
3207 return uma_observer_;
3208}
3209
Elad Alon99c3fe52017-10-13 16:29:40 +02003210bool PeerConnection::StartRtcEventLog_w(
Bjorn Tereliusde939432017-11-20 17:38:14 +01003211 std::unique_ptr<RtcEventLogOutput> output,
3212 int64_t output_period_ms) {
zhihuang77985012017-02-07 15:45:16 -08003213 if (!event_log_) {
3214 return false;
3215 }
Bjorn Tereliusde939432017-11-20 17:38:14 +01003216 return event_log_->StartLogging(std::move(output), output_period_ms);
ivoc14d5dbe2016-07-04 07:06:55 -07003217}
3218
3219void PeerConnection::StopRtcEventLog_w() {
zhihuang77985012017-02-07 15:45:16 -08003220 if (event_log_) {
3221 event_log_->StopLogging();
3222 }
ivoc14d5dbe2016-07-04 07:06:55 -07003223}
nisseeaabdf62017-05-05 02:23:02 -07003224
Steve Anton75737c02017-11-06 10:37:17 -08003225cricket::BaseChannel* PeerConnection::GetChannel(
3226 const std::string& content_name) {
3227 if (voice_channel() && voice_channel()->content_name() == content_name) {
3228 return voice_channel();
3229 }
3230 if (video_channel() && video_channel()->content_name() == content_name) {
3231 return video_channel();
3232 }
3233 if (rtp_data_channel() &&
3234 rtp_data_channel()->content_name() == content_name) {
3235 return rtp_data_channel();
3236 }
3237 return nullptr;
3238}
3239
3240bool PeerConnection::GetSctpSslRole(rtc::SSLRole* role) {
3241 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003242 RTC_LOG(LS_INFO)
3243 << "Local and Remote descriptions must be applied to get the "
3244 << "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08003245 return false;
3246 }
3247 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003248 RTC_LOG(LS_INFO) << "Non-rejected SCTP m= section is needed to get the "
3249 << "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08003250 return false;
3251 }
3252
3253 return transport_controller_->GetSslRole(*sctp_transport_name_, role);
3254}
3255
3256bool PeerConnection::GetSslRole(const std::string& content_name,
3257 rtc::SSLRole* role) {
3258 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003259 RTC_LOG(LS_INFO)
3260 << "Local and Remote descriptions must be applied to get the "
3261 << "SSL Role of the session.";
Steve Anton75737c02017-11-06 10:37:17 -08003262 return false;
3263 }
3264
3265 return transport_controller_->GetSslRole(GetTransportName(content_name),
3266 role);
3267}
3268
Steve Anton75737c02017-11-06 10:37:17 -08003269bool PeerConnection::SetLocalDescription(
3270 std::unique_ptr<SessionDescriptionInterface> desc,
3271 std::string* err_desc) {
3272 RTC_DCHECK(signaling_thread()->IsCurrent());
3273
3274 // Validate SDP.
3275 if (!ValidateSessionDescription(desc.get(), cricket::CS_LOCAL, err_desc)) {
3276 return false;
3277 }
3278
3279 // Update the initial_offerer flag if this session is the initial_offerer.
3280 Action action = GetAction(desc->type());
3281 if (!initial_offerer_.has_value()) {
3282 initial_offerer_.emplace(action == kOffer);
3283 if (*initial_offerer_) {
3284 transport_controller_->SetIceRole(cricket::ICEROLE_CONTROLLING);
3285 } else {
3286 transport_controller_->SetIceRole(cricket::ICEROLE_CONTROLLED);
3287 }
3288 }
3289
3290 if (action == kAnswer) {
3291 current_local_description_ = std::move(desc);
3292 pending_local_description_ = nullptr;
3293 current_remote_description_ = std::move(pending_remote_description_);
3294 } else {
3295 pending_local_description_ = std::move(desc);
3296 }
3297
3298 // Transport and Media channels will be created only when offer is set.
3299 if (action == kOffer && !CreateChannels(local_description()->description())) {
3300 // TODO(mallinath) - Handle CreateChannel failure, as new local description
3301 // is applied. Restore back to old description.
3302 return BadLocalSdp(local_description()->type(), kCreateChannelFailed,
3303 err_desc);
3304 }
3305
3306 // Remove unused channels if MediaContentDescription is rejected.
3307 RemoveUnusedChannels(local_description()->description());
3308
3309 if (!UpdateSessionState(action, cricket::CS_LOCAL, err_desc)) {
3310 return false;
3311 }
3312 if (remote_description()) {
3313 // Now that we have a local description, we can push down remote candidates.
3314 UseCandidatesInSessionDescription(remote_description());
3315 }
3316
3317 pending_ice_restarts_.clear();
3318 if (error() != ERROR_NONE) {
3319 return BadLocalSdp(local_description()->type(), GetSessionErrorMsg(),
3320 err_desc);
3321 }
3322 return true;
3323}
3324
3325bool PeerConnection::SetRemoteDescription(
3326 std::unique_ptr<SessionDescriptionInterface> desc,
3327 std::string* err_desc) {
3328 RTC_DCHECK(signaling_thread()->IsCurrent());
3329
3330 // Validate SDP.
3331 if (!ValidateSessionDescription(desc.get(), cricket::CS_REMOTE, err_desc)) {
3332 return false;
3333 }
3334
3335 // Hold this pointer so candidates can be copied to it later in the method.
3336 SessionDescriptionInterface* desc_ptr = desc.get();
3337
3338 const SessionDescriptionInterface* old_remote_description =
3339 remote_description();
3340 // Grab ownership of the description being replaced for the remainder of this
3341 // method, since it's used below as |old_remote_description|.
3342 std::unique_ptr<SessionDescriptionInterface> replaced_remote_description;
3343 Action action = GetAction(desc->type());
3344 if (action == kAnswer) {
3345 replaced_remote_description = pending_remote_description_
3346 ? std::move(pending_remote_description_)
3347 : std::move(current_remote_description_);
3348 current_remote_description_ = std::move(desc);
3349 pending_remote_description_ = nullptr;
3350 current_local_description_ = std::move(pending_local_description_);
3351 } else {
3352 replaced_remote_description = std::move(pending_remote_description_);
3353 pending_remote_description_ = std::move(desc);
3354 }
3355
3356 // Transport and Media channels will be created only when offer is set.
3357 if (action == kOffer &&
3358 !CreateChannels(remote_description()->description())) {
3359 // TODO(mallinath) - Handle CreateChannel failure, as new local description
3360 // is applied. Restore back to old description.
3361 return BadRemoteSdp(remote_description()->type(), kCreateChannelFailed,
3362 err_desc);
3363 }
3364
3365 // Remove unused channels if MediaContentDescription is rejected.
3366 RemoveUnusedChannels(remote_description()->description());
3367
3368 // NOTE: Candidates allocation will be initiated only when SetLocalDescription
3369 // is called.
3370 if (!UpdateSessionState(action, cricket::CS_REMOTE, err_desc)) {
3371 return false;
3372 }
3373
3374 if (local_description() &&
3375 !UseCandidatesInSessionDescription(remote_description())) {
3376 return BadRemoteSdp(remote_description()->type(), kInvalidCandidates,
3377 err_desc);
3378 }
3379
3380 if (old_remote_description) {
3381 for (const cricket::ContentInfo& content :
3382 old_remote_description->description()->contents()) {
3383 // Check if this new SessionDescription contains new ICE ufrag and
3384 // password that indicates the remote peer requests an ICE restart.
3385 // TODO(deadbeef): When we start storing both the current and pending
3386 // remote description, this should reset pending_ice_restarts and compare
3387 // against the current description.
3388 if (CheckForRemoteIceRestart(old_remote_description, remote_description(),
3389 content.name)) {
3390 if (action == kOffer) {
3391 pending_ice_restarts_.insert(content.name);
3392 }
3393 } else {
3394 // We retain all received candidates only if ICE is not restarted.
3395 // When ICE is restarted, all previous candidates belong to an old
3396 // generation and should not be kept.
3397 // TODO(deadbeef): This goes against the W3C spec which says the remote
3398 // description should only contain candidates from the last set remote
3399 // description plus any candidates added since then. We should remove
3400 // this once we're sure it won't break anything.
3401 WebRtcSessionDescriptionFactory::CopyCandidatesFromSessionDescription(
3402 old_remote_description, content.name, desc_ptr);
3403 }
3404 }
3405 }
3406
3407 if (error() != ERROR_NONE) {
3408 return BadRemoteSdp(remote_description()->type(), GetSessionErrorMsg(),
3409 err_desc);
3410 }
3411
3412 // Set the the ICE connection state to connecting since the connection may
3413 // become writable with peer reflexive candidates before any remote candidate
3414 // is signaled.
3415 // TODO(pthatcher): This is a short-term solution for crbug/446908. A real fix
3416 // is to have a new signal the indicates a change in checking state from the
3417 // transport and expose a new checking() member from transport that can be
3418 // read to determine the current checking state. The existing SignalConnecting
3419 // actually means "gathering candidates", so cannot be be used here.
3420 if (remote_description()->type() != SessionDescriptionInterface::kOffer &&
3421 ice_connection_state() == PeerConnectionInterface::kIceConnectionNew) {
3422 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
3423 }
3424 return true;
3425}
3426
3427// TODO(steveanton): Eventually it'd be nice to store the channels as a single
3428// vector of BaseChannel pointers instead of separate voice and video channel
3429// vectors. At that point, this will become a simple getter.
3430std::vector<cricket::BaseChannel*> PeerConnection::Channels() const {
3431 std::vector<cricket::BaseChannel*> channels;
Steve Anton4171afb2017-11-20 10:20:22 -08003432 if (voice_channel()) {
3433 channels.push_back(voice_channel());
3434 }
3435 if (video_channel()) {
3436 channels.push_back(video_channel());
3437 }
Steve Anton75737c02017-11-06 10:37:17 -08003438 if (rtp_data_channel_) {
3439 channels.push_back(rtp_data_channel_);
3440 }
3441 return channels;
3442}
3443
3444void PeerConnection::SetError(Error error, const std::string& error_desc) {
3445 RTC_DCHECK(signaling_thread()->IsCurrent());
3446 if (error != error_) {
3447 error_ = error;
3448 error_desc_ = error_desc;
3449 }
3450}
3451
3452bool PeerConnection::UpdateSessionState(Action action,
3453 cricket::ContentSource source,
3454 std::string* err_desc) {
3455 RTC_DCHECK(signaling_thread()->IsCurrent());
3456
3457 // If there's already a pending error then no state transition should happen.
3458 // But all call-sites should be verifying this before calling us!
3459 RTC_DCHECK(error() == ERROR_NONE);
3460 std::string td_err;
3461 if (action == kOffer) {
3462 if (!PushdownTransportDescription(source, cricket::CA_OFFER, &td_err)) {
3463 return BadOfferSdp(source, MakeTdErrorString(td_err), err_desc);
3464 }
3465 ChangeSignalingState(source == cricket::CS_LOCAL
3466 ? PeerConnectionInterface::kHaveLocalOffer
3467 : PeerConnectionInterface::kHaveRemoteOffer);
3468 if (!PushdownMediaDescription(cricket::CA_OFFER, source, err_desc)) {
3469 SetError(ERROR_CONTENT, *err_desc);
3470 }
3471 if (error() != ERROR_NONE) {
3472 return BadOfferSdp(source, GetSessionErrorMsg(), err_desc);
3473 }
3474 } else if (action == kPrAnswer) {
3475 if (!PushdownTransportDescription(source, cricket::CA_PRANSWER, &td_err)) {
3476 return BadPranswerSdp(source, MakeTdErrorString(td_err), err_desc);
3477 }
3478 EnableChannels();
3479 ChangeSignalingState(source == cricket::CS_LOCAL
3480 ? PeerConnectionInterface::kHaveLocalPrAnswer
3481 : PeerConnectionInterface::kHaveRemotePrAnswer);
3482 if (!PushdownMediaDescription(cricket::CA_PRANSWER, source, err_desc)) {
3483 SetError(ERROR_CONTENT, *err_desc);
3484 }
3485 if (error() != ERROR_NONE) {
3486 return BadPranswerSdp(source, GetSessionErrorMsg(), err_desc);
3487 }
3488 } else if (action == kAnswer) {
3489 const cricket::ContentGroup* local_bundle =
3490 local_description()->description()->GetGroupByName(
3491 cricket::GROUP_TYPE_BUNDLE);
3492 const cricket::ContentGroup* remote_bundle =
3493 remote_description()->description()->GetGroupByName(
3494 cricket::GROUP_TYPE_BUNDLE);
3495 if (local_bundle && remote_bundle) {
3496 // The answerer decides the transport to bundle on.
3497 const cricket::ContentGroup* answer_bundle =
3498 (source == cricket::CS_LOCAL ? local_bundle : remote_bundle);
3499 if (!EnableBundle(*answer_bundle)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003500 RTC_LOG(LS_WARNING) << "Failed to enable BUNDLE.";
Steve Anton75737c02017-11-06 10:37:17 -08003501 return BadAnswerSdp(source, kEnableBundleFailed, err_desc);
3502 }
3503 }
3504 // Only push down the transport description after enabling BUNDLE; we don't
3505 // want to push down a description on a transport about to be destroyed.
3506 if (!PushdownTransportDescription(source, cricket::CA_ANSWER, &td_err)) {
3507 return BadAnswerSdp(source, MakeTdErrorString(td_err), err_desc);
3508 }
3509 EnableChannels();
3510 ChangeSignalingState(PeerConnectionInterface::kStable);
3511 if (!PushdownMediaDescription(cricket::CA_ANSWER, source, err_desc)) {
3512 SetError(ERROR_CONTENT, *err_desc);
3513 }
3514 if (error() != ERROR_NONE) {
3515 return BadAnswerSdp(source, GetSessionErrorMsg(), err_desc);
3516 }
3517 }
3518 return true;
3519}
3520
3521PeerConnection::Action PeerConnection::GetAction(const std::string& type) {
3522 if (type == SessionDescriptionInterface::kOffer) {
3523 return PeerConnection::kOffer;
3524 } else if (type == SessionDescriptionInterface::kPrAnswer) {
3525 return PeerConnection::kPrAnswer;
3526 } else if (type == SessionDescriptionInterface::kAnswer) {
3527 return PeerConnection::kAnswer;
3528 }
3529 RTC_NOTREACHED() << "unknown action type";
3530 return PeerConnection::kOffer;
3531}
3532
3533bool PeerConnection::PushdownMediaDescription(cricket::ContentAction action,
3534 cricket::ContentSource source,
3535 std::string* err) {
3536 const SessionDescription* sdesc =
3537 (source == cricket::CS_LOCAL ? local_description() : remote_description())
3538 ->description();
3539 RTC_DCHECK(sdesc);
3540 bool all_success = true;
3541 for (auto* channel : Channels()) {
3542 // TODO(steveanton): Add support for multiple channels of the same type.
3543 const ContentInfo* content_info =
3544 cricket::GetFirstMediaContent(sdesc->contents(), channel->media_type());
3545 if (!content_info) {
3546 continue;
3547 }
3548 const MediaContentDescription* content_desc =
3549 static_cast<const MediaContentDescription*>(content_info->description);
3550 if (content_desc && !content_info->rejected) {
3551 bool success = (source == cricket::CS_LOCAL)
3552 ? channel->SetLocalContent(content_desc, action, err)
3553 : channel->SetRemoteContent(content_desc, action, err);
3554 if (!success) {
3555 all_success = false;
3556 break;
3557 }
3558 }
3559 }
3560 // Need complete offer/answer with an SCTP m= section before starting SCTP,
3561 // according to https://tools.ietf.org/html/draft-ietf-mmusic-sctp-sdp-19
3562 if (sctp_transport_ && local_description() && remote_description() &&
3563 cricket::GetFirstDataContent(local_description()->description()) &&
3564 cricket::GetFirstDataContent(remote_description()->description())) {
3565 all_success &= network_thread()->Invoke<bool>(
3566 RTC_FROM_HERE,
3567 rtc::Bind(&PeerConnection::PushdownSctpParameters_n, this, source));
3568 }
3569 return all_success;
3570}
3571
3572bool PeerConnection::PushdownSctpParameters_n(cricket::ContentSource source) {
3573 RTC_DCHECK(network_thread()->IsCurrent());
3574 RTC_DCHECK(local_description());
3575 RTC_DCHECK(remote_description());
3576 // Apply the SCTP port (which is hidden inside a DataCodec structure...)
3577 // When we support "max-message-size", that would also be pushed down here.
3578 return sctp_transport_->Start(
3579 GetSctpPort(local_description()->description()),
3580 GetSctpPort(remote_description()->description()));
3581}
3582
3583bool PeerConnection::PushdownTransportDescription(cricket::ContentSource source,
3584 cricket::ContentAction action,
3585 std::string* error_desc) {
3586 RTC_DCHECK(signaling_thread()->IsCurrent());
3587
3588 if (source == cricket::CS_LOCAL) {
3589 return PushdownLocalTransportDescription(local_description()->description(),
3590 action, error_desc);
3591 }
3592 return PushdownRemoteTransportDescription(remote_description()->description(),
3593 action, error_desc);
3594}
3595
3596bool PeerConnection::PushdownLocalTransportDescription(
3597 const SessionDescription* sdesc,
3598 cricket::ContentAction action,
3599 std::string* err) {
3600 RTC_DCHECK(signaling_thread()->IsCurrent());
3601
3602 if (!sdesc) {
3603 return false;
3604 }
3605
3606 for (const TransportInfo& tinfo : sdesc->transport_infos()) {
3607 if (!transport_controller_->SetLocalTransportDescription(
3608 tinfo.content_name, tinfo.description, action, err)) {
3609 return false;
3610 }
3611 }
3612
3613 return true;
3614}
3615
3616bool PeerConnection::PushdownRemoteTransportDescription(
3617 const SessionDescription* sdesc,
3618 cricket::ContentAction action,
3619 std::string* err) {
3620 RTC_DCHECK(signaling_thread()->IsCurrent());
3621
3622 if (!sdesc) {
3623 return false;
3624 }
3625
3626 for (const TransportInfo& tinfo : sdesc->transport_infos()) {
3627 if (!transport_controller_->SetRemoteTransportDescription(
3628 tinfo.content_name, tinfo.description, action, err)) {
3629 return false;
3630 }
3631 }
3632
3633 return true;
3634}
3635
3636bool PeerConnection::GetTransportDescription(
3637 const SessionDescription* description,
3638 const std::string& content_name,
3639 cricket::TransportDescription* tdesc) {
3640 if (!description || !tdesc) {
3641 return false;
3642 }
3643 const TransportInfo* transport_info =
3644 description->GetTransportInfoByName(content_name);
3645 if (!transport_info) {
3646 return false;
3647 }
3648 *tdesc = transport_info->description;
3649 return true;
3650}
3651
3652bool PeerConnection::EnableBundle(const cricket::ContentGroup& bundle) {
3653 const std::string* first_content_name = bundle.FirstContentName();
3654 if (!first_content_name) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003655 RTC_LOG(LS_WARNING) << "Tried to BUNDLE with no contents.";
Steve Anton75737c02017-11-06 10:37:17 -08003656 return false;
3657 }
3658 const std::string& transport_name = *first_content_name;
3659
3660 auto maybe_set_transport = [this, bundle,
3661 transport_name](cricket::BaseChannel* ch) {
3662 if (!ch || !bundle.HasContentName(ch->content_name())) {
3663 return true;
3664 }
3665
3666 std::string old_transport_name = ch->transport_name();
3667 if (old_transport_name == transport_name) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003668 RTC_LOG(LS_INFO) << "BUNDLE already enabled for " << ch->content_name()
3669 << " on " << transport_name << ".";
Steve Anton75737c02017-11-06 10:37:17 -08003670 return true;
3671 }
3672
3673 cricket::DtlsTransportInternal* rtp_dtls_transport =
3674 transport_controller_->CreateDtlsTransport(
3675 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
3676 bool need_rtcp = (ch->rtcp_dtls_transport() != nullptr);
3677 cricket::DtlsTransportInternal* rtcp_dtls_transport = nullptr;
3678 if (need_rtcp) {
3679 rtcp_dtls_transport = transport_controller_->CreateDtlsTransport(
3680 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
3681 }
3682
3683 ch->SetTransports(rtp_dtls_transport, rtcp_dtls_transport);
Mirko Bonadei675513b2017-11-09 11:09:25 +01003684 RTC_LOG(LS_INFO) << "Enabled BUNDLE for " << ch->content_name() << " on "
3685 << transport_name << ".";
Steve Anton75737c02017-11-06 10:37:17 -08003686 transport_controller_->DestroyDtlsTransport(
3687 old_transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
3688 // If the channel needs rtcp, it means that the channel used to have a
3689 // rtcp transport which needs to be deleted now.
3690 if (need_rtcp) {
3691 transport_controller_->DestroyDtlsTransport(
3692 old_transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
3693 }
3694 return true;
3695 };
3696
3697 if (!maybe_set_transport(voice_channel()) ||
3698 !maybe_set_transport(video_channel()) ||
3699 !maybe_set_transport(rtp_data_channel())) {
3700 return false;
3701 }
3702 // For SCTP, transport creation/deletion happens here instead of in the
3703 // object itself.
3704 if (sctp_transport_) {
3705 RTC_DCHECK(sctp_transport_name_);
3706 RTC_DCHECK(sctp_content_name_);
3707 if (transport_name != *sctp_transport_name_ &&
3708 bundle.HasContentName(*sctp_content_name_)) {
3709 network_thread()->Invoke<void>(
3710 RTC_FROM_HERE, rtc::Bind(&PeerConnection::ChangeSctpTransport_n, this,
3711 transport_name));
3712 }
3713 }
3714
3715 return true;
3716}
3717
Steve Anton75737c02017-11-06 10:37:17 -08003718cricket::IceConfig PeerConnection::ParseIceConfig(
3719 const PeerConnectionInterface::RTCConfiguration& config) const {
3720 cricket::ContinualGatheringPolicy gathering_policy;
3721 // TODO(honghaiz): Add the third continual gathering policy in
3722 // PeerConnectionInterface and map it to GATHER_CONTINUALLY_AND_RECOVER.
3723 switch (config.continual_gathering_policy) {
3724 case PeerConnectionInterface::GATHER_ONCE:
3725 gathering_policy = cricket::GATHER_ONCE;
3726 break;
3727 case PeerConnectionInterface::GATHER_CONTINUALLY:
3728 gathering_policy = cricket::GATHER_CONTINUALLY;
3729 break;
3730 default:
3731 RTC_NOTREACHED();
3732 gathering_policy = cricket::GATHER_ONCE;
3733 }
3734 cricket::IceConfig ice_config;
3735 ice_config.receiving_timeout = config.ice_connection_receiving_timeout;
3736 ice_config.prioritize_most_likely_candidate_pairs =
3737 config.prioritize_most_likely_ice_candidate_pairs;
3738 ice_config.backup_connection_ping_interval =
3739 config.ice_backup_candidate_pair_ping_interval;
3740 ice_config.continual_gathering_policy = gathering_policy;
3741 ice_config.presume_writable_when_fully_relayed =
3742 config.presume_writable_when_fully_relayed;
3743 ice_config.ice_check_min_interval = config.ice_check_min_interval;
3744 ice_config.regather_all_networks_interval_range =
3745 config.ice_regather_interval_range;
3746 return ice_config;
3747}
3748
Steve Anton75737c02017-11-06 10:37:17 -08003749bool PeerConnection::GetLocalTrackIdBySsrc(uint32_t ssrc,
3750 std::string* track_id) {
3751 if (!local_description()) {
3752 return false;
3753 }
3754 return webrtc::GetTrackIdBySsrc(local_description()->description(), ssrc,
3755 track_id);
3756}
3757
3758bool PeerConnection::GetRemoteTrackIdBySsrc(uint32_t ssrc,
3759 std::string* track_id) {
3760 if (!remote_description()) {
3761 return false;
3762 }
3763 return webrtc::GetTrackIdBySsrc(remote_description()->description(), ssrc,
3764 track_id);
3765}
3766
3767bool PeerConnection::SendData(const cricket::SendDataParams& params,
3768 const rtc::CopyOnWriteBuffer& payload,
3769 cricket::SendDataResult* result) {
3770 if (!rtp_data_channel_ && !sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003771 RTC_LOG(LS_ERROR) << "SendData called when rtp_data_channel_ "
3772 << "and sctp_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08003773 return false;
3774 }
3775 return rtp_data_channel_
3776 ? rtp_data_channel_->SendData(params, payload, result)
3777 : network_thread()->Invoke<bool>(
3778 RTC_FROM_HERE,
3779 Bind(&cricket::SctpTransportInternal::SendData,
3780 sctp_transport_.get(), params, payload, result));
3781}
3782
3783bool PeerConnection::ConnectDataChannel(DataChannel* webrtc_data_channel) {
3784 if (!rtp_data_channel_ && !sctp_transport_) {
3785 // Don't log an error here, because DataChannels are expected to call
3786 // ConnectDataChannel in this state. It's the only way to initially tell
3787 // whether or not the underlying transport is ready.
3788 return false;
3789 }
3790 if (rtp_data_channel_) {
3791 rtp_data_channel_->SignalReadyToSendData.connect(
3792 webrtc_data_channel, &DataChannel::OnChannelReady);
3793 rtp_data_channel_->SignalDataReceived.connect(webrtc_data_channel,
3794 &DataChannel::OnDataReceived);
3795 } else {
3796 SignalSctpReadyToSendData.connect(webrtc_data_channel,
3797 &DataChannel::OnChannelReady);
3798 SignalSctpDataReceived.connect(webrtc_data_channel,
3799 &DataChannel::OnDataReceived);
3800 SignalSctpStreamClosedRemotely.connect(
3801 webrtc_data_channel, &DataChannel::OnStreamClosedRemotely);
3802 }
3803 return true;
3804}
3805
3806void PeerConnection::DisconnectDataChannel(DataChannel* webrtc_data_channel) {
3807 if (!rtp_data_channel_ && !sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003808 RTC_LOG(LS_ERROR)
3809 << "DisconnectDataChannel called when rtp_data_channel_ and "
3810 "sctp_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08003811 return;
3812 }
3813 if (rtp_data_channel_) {
3814 rtp_data_channel_->SignalReadyToSendData.disconnect(webrtc_data_channel);
3815 rtp_data_channel_->SignalDataReceived.disconnect(webrtc_data_channel);
3816 } else {
3817 SignalSctpReadyToSendData.disconnect(webrtc_data_channel);
3818 SignalSctpDataReceived.disconnect(webrtc_data_channel);
3819 SignalSctpStreamClosedRemotely.disconnect(webrtc_data_channel);
3820 }
3821}
3822
3823void PeerConnection::AddSctpDataStream(int sid) {
3824 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003825 RTC_LOG(LS_ERROR)
3826 << "AddSctpDataStream called when sctp_transport_ is NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08003827 return;
3828 }
3829 network_thread()->Invoke<void>(
3830 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::OpenStream,
3831 sctp_transport_.get(), sid));
3832}
3833
3834void PeerConnection::RemoveSctpDataStream(int sid) {
3835 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003836 RTC_LOG(LS_ERROR) << "RemoveSctpDataStream called when sctp_transport_ is "
3837 << "NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08003838 return;
3839 }
3840 network_thread()->Invoke<void>(
3841 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::ResetStream,
3842 sctp_transport_.get(), sid));
3843}
3844
3845bool PeerConnection::ReadyToSendData() const {
3846 return (rtp_data_channel_ && rtp_data_channel_->ready_to_send_data()) ||
3847 sctp_ready_to_send_data_;
3848}
3849
3850std::unique_ptr<SessionStats> PeerConnection::GetSessionStats_s() {
3851 RTC_DCHECK(signaling_thread()->IsCurrent());
3852 ChannelNamePairs channel_name_pairs;
3853 if (voice_channel()) {
3854 channel_name_pairs.voice = rtc::Optional<ChannelNamePair>(ChannelNamePair(
3855 voice_channel()->content_name(), voice_channel()->transport_name()));
3856 }
3857 if (video_channel()) {
3858 channel_name_pairs.video = rtc::Optional<ChannelNamePair>(ChannelNamePair(
3859 video_channel()->content_name(), video_channel()->transport_name()));
3860 }
3861 if (rtp_data_channel()) {
3862 channel_name_pairs.data = rtc::Optional<ChannelNamePair>(
3863 ChannelNamePair(rtp_data_channel()->content_name(),
3864 rtp_data_channel()->transport_name()));
3865 }
3866 if (sctp_transport_) {
3867 RTC_DCHECK(sctp_content_name_);
3868 RTC_DCHECK(sctp_transport_name_);
3869 channel_name_pairs.data = rtc::Optional<ChannelNamePair>(
3870 ChannelNamePair(*sctp_content_name_, *sctp_transport_name_));
3871 }
3872 return GetSessionStats(channel_name_pairs);
3873}
3874
3875std::unique_ptr<SessionStats> PeerConnection::GetSessionStats(
3876 const ChannelNamePairs& channel_name_pairs) {
3877 if (network_thread()->IsCurrent()) {
3878 return GetSessionStats_n(channel_name_pairs);
3879 }
3880 return network_thread()->Invoke<std::unique_ptr<SessionStats>>(
3881 RTC_FROM_HERE,
3882 rtc::Bind(&PeerConnection::GetSessionStats_n, this, channel_name_pairs));
3883}
3884
3885bool PeerConnection::GetLocalCertificate(
3886 const std::string& transport_name,
3887 rtc::scoped_refptr<rtc::RTCCertificate>* certificate) {
3888 return transport_controller_->GetLocalCertificate(transport_name,
3889 certificate);
3890}
3891
3892std::unique_ptr<rtc::SSLCertificate> PeerConnection::GetRemoteSSLCertificate(
3893 const std::string& transport_name) {
3894 return transport_controller_->GetRemoteSSLCertificate(transport_name);
3895}
3896
3897cricket::DataChannelType PeerConnection::data_channel_type() const {
3898 return data_channel_type_;
3899}
3900
3901bool PeerConnection::IceRestartPending(const std::string& content_name) const {
3902 return pending_ice_restarts_.find(content_name) !=
3903 pending_ice_restarts_.end();
3904}
3905
Steve Anton75737c02017-11-06 10:37:17 -08003906bool PeerConnection::NeedsIceRestart(const std::string& content_name) const {
3907 return transport_controller_->NeedsIceRestart(content_name);
3908}
3909
3910void PeerConnection::OnCertificateReady(
3911 const rtc::scoped_refptr<rtc::RTCCertificate>& certificate) {
3912 transport_controller_->SetLocalCertificate(certificate);
3913}
3914
3915void PeerConnection::OnDtlsSrtpSetupFailure(cricket::BaseChannel*, bool rtcp) {
3916 SetError(ERROR_TRANSPORT,
3917 rtcp ? kDtlsSrtpSetupFailureRtcp : kDtlsSrtpSetupFailureRtp);
3918}
3919
3920void PeerConnection::OnTransportControllerConnectionState(
3921 cricket::IceConnectionState state) {
3922 switch (state) {
3923 case cricket::kIceConnectionConnecting:
3924 // If the current state is Connected or Completed, then there were
3925 // writable channels but now there are not, so the next state must
3926 // be Disconnected.
3927 // kIceConnectionConnecting is currently used as the default,
3928 // un-connected state by the TransportController, so its only use is
3929 // detecting disconnections.
3930 if (ice_connection_state_ ==
3931 PeerConnectionInterface::kIceConnectionConnected ||
3932 ice_connection_state_ ==
3933 PeerConnectionInterface::kIceConnectionCompleted) {
3934 SetIceConnectionState(
3935 PeerConnectionInterface::kIceConnectionDisconnected);
3936 }
3937 break;
3938 case cricket::kIceConnectionFailed:
3939 SetIceConnectionState(PeerConnectionInterface::kIceConnectionFailed);
3940 break;
3941 case cricket::kIceConnectionConnected:
Mirko Bonadei675513b2017-11-09 11:09:25 +01003942 RTC_LOG(LS_INFO) << "Changing to ICE connected state because "
3943 << "all transports are writable.";
Steve Anton75737c02017-11-06 10:37:17 -08003944 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
3945 break;
3946 case cricket::kIceConnectionCompleted:
Mirko Bonadei675513b2017-11-09 11:09:25 +01003947 RTC_LOG(LS_INFO) << "Changing to ICE completed state because "
3948 << "all transports are complete.";
Steve Anton75737c02017-11-06 10:37:17 -08003949 if (ice_connection_state_ !=
3950 PeerConnectionInterface::kIceConnectionConnected) {
3951 // If jumping directly from "checking" to "connected",
3952 // signal "connected" first.
3953 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
3954 }
3955 SetIceConnectionState(PeerConnectionInterface::kIceConnectionCompleted);
3956 if (metrics_observer()) {
3957 ReportTransportStats();
3958 }
3959 break;
3960 default:
3961 RTC_NOTREACHED();
3962 }
3963}
3964
3965void PeerConnection::OnTransportControllerCandidatesGathered(
3966 const std::string& transport_name,
3967 const cricket::Candidates& candidates) {
3968 RTC_DCHECK(signaling_thread()->IsCurrent());
3969 int sdp_mline_index;
3970 if (!GetLocalCandidateMediaIndex(transport_name, &sdp_mline_index)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003971 RTC_LOG(LS_ERROR)
3972 << "OnTransportControllerCandidatesGathered: content name "
3973 << transport_name << " not found";
Steve Anton75737c02017-11-06 10:37:17 -08003974 return;
3975 }
3976
3977 for (cricket::Candidates::const_iterator citer = candidates.begin();
3978 citer != candidates.end(); ++citer) {
3979 // Use transport_name as the candidate media id.
3980 std::unique_ptr<JsepIceCandidate> candidate(
3981 new JsepIceCandidate(transport_name, sdp_mline_index, *citer));
3982 if (local_description()) {
3983 mutable_local_description()->AddCandidate(candidate.get());
3984 }
3985 OnIceCandidate(std::move(candidate));
3986 }
3987}
3988
3989void PeerConnection::OnTransportControllerCandidatesRemoved(
3990 const std::vector<cricket::Candidate>& candidates) {
3991 RTC_DCHECK(signaling_thread()->IsCurrent());
3992 // Sanity check.
3993 for (const cricket::Candidate& candidate : candidates) {
3994 if (candidate.transport_name().empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003995 RTC_LOG(LS_ERROR) << "OnTransportControllerCandidatesRemoved: "
3996 << "empty content name in candidate "
3997 << candidate.ToString();
Steve Anton75737c02017-11-06 10:37:17 -08003998 return;
3999 }
4000 }
4001
4002 if (local_description()) {
4003 mutable_local_description()->RemoveCandidates(candidates);
4004 }
4005 OnIceCandidatesRemoved(candidates);
4006}
4007
4008void PeerConnection::OnTransportControllerDtlsHandshakeError(
4009 rtc::SSLHandshakeError error) {
4010 if (metrics_observer()) {
4011 metrics_observer()->IncrementEnumCounter(
4012 webrtc::kEnumCounterDtlsHandshakeError, static_cast<int>(error),
4013 static_cast<int>(rtc::SSLHandshakeError::MAX_VALUE));
4014 }
4015}
4016
4017// Enabling voice and video (and RTP data) channels.
4018void PeerConnection::EnableChannels() {
Steve Anton4171afb2017-11-20 10:20:22 -08004019 if (voice_channel() && !voice_channel()->enabled()) {
4020 voice_channel()->Enable(true);
Steve Anton75737c02017-11-06 10:37:17 -08004021 }
4022
Steve Anton4171afb2017-11-20 10:20:22 -08004023 if (video_channel() && !video_channel()->enabled()) {
4024 video_channel()->Enable(true);
Steve Anton75737c02017-11-06 10:37:17 -08004025 }
4026
Steve Anton4171afb2017-11-20 10:20:22 -08004027 if (rtp_data_channel_ && !rtp_data_channel_->enabled()) {
Steve Anton75737c02017-11-06 10:37:17 -08004028 rtp_data_channel_->Enable(true);
Steve Anton4171afb2017-11-20 10:20:22 -08004029 }
Steve Anton75737c02017-11-06 10:37:17 -08004030}
4031
4032// Returns the media index for a local ice candidate given the content name.
4033bool PeerConnection::GetLocalCandidateMediaIndex(
4034 const std::string& content_name,
4035 int* sdp_mline_index) {
4036 if (!local_description() || !sdp_mline_index) {
4037 return false;
4038 }
4039
4040 bool content_found = false;
4041 const ContentInfos& contents = local_description()->description()->contents();
4042 for (size_t index = 0; index < contents.size(); ++index) {
4043 if (contents[index].name == content_name) {
4044 *sdp_mline_index = static_cast<int>(index);
4045 content_found = true;
4046 break;
4047 }
4048 }
4049 return content_found;
4050}
4051
4052bool PeerConnection::UseCandidatesInSessionDescription(
4053 const SessionDescriptionInterface* remote_desc) {
4054 if (!remote_desc) {
4055 return true;
4056 }
4057 bool ret = true;
4058
4059 for (size_t m = 0; m < remote_desc->number_of_mediasections(); ++m) {
4060 const IceCandidateCollection* candidates = remote_desc->candidates(m);
4061 for (size_t n = 0; n < candidates->count(); ++n) {
4062 const IceCandidateInterface* candidate = candidates->at(n);
4063 bool valid = false;
4064 if (!ReadyToUseRemoteCandidate(candidate, remote_desc, &valid)) {
4065 if (valid) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004066 RTC_LOG(LS_INFO)
4067 << "UseCandidatesInSessionDescription: Not ready to use "
4068 << "candidate.";
Steve Anton75737c02017-11-06 10:37:17 -08004069 }
4070 continue;
4071 }
4072 ret = UseCandidate(candidate);
4073 if (!ret) {
4074 break;
4075 }
4076 }
4077 }
4078 return ret;
4079}
4080
4081bool PeerConnection::UseCandidate(const IceCandidateInterface* candidate) {
4082 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
4083 size_t remote_content_size =
4084 remote_description()->description()->contents().size();
4085 if (mediacontent_index >= remote_content_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004086 RTC_LOG(LS_ERROR) << "UseCandidate: Invalid candidate media index.";
Steve Anton75737c02017-11-06 10:37:17 -08004087 return false;
4088 }
4089
4090 cricket::ContentInfo content =
4091 remote_description()->description()->contents()[mediacontent_index];
4092 std::vector<cricket::Candidate> candidates;
4093 candidates.push_back(candidate->candidate());
4094 // Invoking BaseSession method to handle remote candidates.
4095 std::string error;
4096 if (transport_controller_->AddRemoteCandidates(content.name, candidates,
4097 &error)) {
4098 // Candidates successfully submitted for checking.
4099 if (ice_connection_state_ == PeerConnectionInterface::kIceConnectionNew ||
4100 ice_connection_state_ ==
4101 PeerConnectionInterface::kIceConnectionDisconnected) {
4102 // If state is New, then the session has just gotten its first remote ICE
4103 // candidates, so go to Checking.
4104 // If state is Disconnected, the session is re-using old candidates or
4105 // receiving additional ones, so go to Checking.
4106 // If state is Connected, stay Connected.
4107 // TODO(bemasc): If state is Connected, and the new candidates are for a
4108 // newly added transport, then the state actually _should_ move to
4109 // checking. Add a way to distinguish that case.
4110 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
4111 }
4112 // TODO(bemasc): If state is Completed, go back to Connected.
4113 } else {
4114 if (!error.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004115 RTC_LOG(LS_WARNING) << error;
Steve Anton75737c02017-11-06 10:37:17 -08004116 }
4117 }
4118 return true;
4119}
4120
4121void PeerConnection::RemoveUnusedChannels(const SessionDescription* desc) {
4122 // TODO(steveanton): Add support for multiple audio/video channels.
4123 // Destroy video channel first since it may have a pointer to the
4124 // voice channel.
4125 const cricket::ContentInfo* video_info = cricket::GetFirstVideoContent(desc);
4126 if ((!video_info || video_info->rejected) && video_channel()) {
Steve Anton4171afb2017-11-20 10:20:22 -08004127 DestroyVideoChannel(video_channel());
Steve Anton75737c02017-11-06 10:37:17 -08004128 }
4129
4130 const cricket::ContentInfo* voice_info = cricket::GetFirstAudioContent(desc);
4131 if ((!voice_info || voice_info->rejected) && voice_channel()) {
Steve Anton4171afb2017-11-20 10:20:22 -08004132 DestroyVoiceChannel(voice_channel());
Steve Anton75737c02017-11-06 10:37:17 -08004133 }
4134
4135 const cricket::ContentInfo* data_info = cricket::GetFirstDataContent(desc);
4136 if (!data_info || data_info->rejected) {
4137 if (rtp_data_channel_) {
4138 DestroyDataChannel();
4139 }
4140 if (sctp_transport_) {
4141 OnDataChannelDestroyed();
4142 network_thread()->Invoke<void>(
4143 RTC_FROM_HERE,
4144 rtc::Bind(&PeerConnection::DestroySctpTransport_n, this));
4145 }
4146 }
4147}
4148
4149// Returns the name of the transport channel when BUNDLE is enabled, or nullptr
4150// if the channel is not part of any bundle.
4151const std::string* PeerConnection::GetBundleTransportName(
4152 const cricket::ContentInfo* content,
4153 const cricket::ContentGroup* bundle) {
4154 if (!bundle) {
4155 return nullptr;
4156 }
4157 const std::string* first_content_name = bundle->FirstContentName();
4158 if (!first_content_name) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004159 RTC_LOG(LS_WARNING) << "Tried to BUNDLE with no contents.";
Steve Anton75737c02017-11-06 10:37:17 -08004160 return nullptr;
4161 }
4162 if (!bundle->HasContentName(content->name)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004163 RTC_LOG(LS_WARNING) << content->name << " is not part of any bundle group";
Steve Anton75737c02017-11-06 10:37:17 -08004164 return nullptr;
4165 }
Mirko Bonadei675513b2017-11-09 11:09:25 +01004166 RTC_LOG(LS_INFO) << "Bundling " << content->name << " on "
4167 << *first_content_name;
Steve Anton75737c02017-11-06 10:37:17 -08004168 return first_content_name;
4169}
4170
4171bool PeerConnection::CreateChannels(const SessionDescription* desc) {
4172 // TODO(steveanton): Add support for multiple audio/video channels.
4173 const cricket::ContentGroup* bundle_group = nullptr;
4174 if (configuration_.bundle_policy ==
4175 PeerConnectionInterface::kBundlePolicyMaxBundle) {
4176 bundle_group = desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
4177 if (!bundle_group) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004178 RTC_LOG(LS_WARNING) << "max-bundle specified without BUNDLE specified";
Steve Anton75737c02017-11-06 10:37:17 -08004179 return false;
4180 }
4181 }
4182 // Creating the media channels and transport proxies.
4183 const cricket::ContentInfo* voice = cricket::GetFirstAudioContent(desc);
4184 if (voice && !voice->rejected && !voice_channel()) {
4185 if (!CreateVoiceChannel(voice,
4186 GetBundleTransportName(voice, bundle_group))) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004187 RTC_LOG(LS_ERROR) << "Failed to create voice channel.";
Steve Anton75737c02017-11-06 10:37:17 -08004188 return false;
4189 }
4190 }
4191
4192 const cricket::ContentInfo* video = cricket::GetFirstVideoContent(desc);
4193 if (video && !video->rejected && !video_channel()) {
4194 if (!CreateVideoChannel(video,
4195 GetBundleTransportName(video, bundle_group))) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004196 RTC_LOG(LS_ERROR) << "Failed to create video channel.";
Steve Anton75737c02017-11-06 10:37:17 -08004197 return false;
4198 }
4199 }
4200
4201 const cricket::ContentInfo* data = cricket::GetFirstDataContent(desc);
4202 if (data_channel_type_ != cricket::DCT_NONE && data && !data->rejected &&
4203 !rtp_data_channel_ && !sctp_transport_) {
4204 if (!CreateDataChannel(data, GetBundleTransportName(data, bundle_group))) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004205 RTC_LOG(LS_ERROR) << "Failed to create data channel.";
Steve Anton75737c02017-11-06 10:37:17 -08004206 return false;
4207 }
4208 }
4209
4210 return true;
4211}
4212
Steve Anton4171afb2017-11-20 10:20:22 -08004213// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Anton75737c02017-11-06 10:37:17 -08004214bool PeerConnection::CreateVoiceChannel(const cricket::ContentInfo* content,
4215 const std::string* bundle_transport) {
4216 // TODO(steveanton): Check to see if it's safe to create multiple voice
4217 // channels.
Steve Anton4171afb2017-11-20 10:20:22 -08004218 RTC_DCHECK(!voice_channel());
Steve Anton75737c02017-11-06 10:37:17 -08004219
4220 std::string transport_name =
4221 bundle_transport ? *bundle_transport : content->name;
4222
4223 cricket::DtlsTransportInternal* rtp_dtls_transport =
4224 transport_controller_->CreateDtlsTransport(
4225 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4226 cricket::DtlsTransportInternal* rtcp_dtls_transport = nullptr;
4227 if (configuration_.rtcp_mux_policy !=
4228 PeerConnectionInterface::kRtcpMuxPolicyRequire) {
4229 rtcp_dtls_transport = transport_controller_->CreateDtlsTransport(
4230 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
4231 }
4232
4233 cricket::VoiceChannel* voice_channel = channel_manager()->CreateVoiceChannel(
4234 call_.get(), configuration_.media_config, rtp_dtls_transport,
4235 rtcp_dtls_transport, transport_controller_->signaling_thread(),
4236 content->name, SrtpRequired(), audio_options_);
4237 if (!voice_channel) {
4238 transport_controller_->DestroyDtlsTransport(
4239 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4240 if (rtcp_dtls_transport) {
4241 transport_controller_->DestroyDtlsTransport(
4242 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
4243 }
4244 return false;
4245 }
Steve Anton75737c02017-11-06 10:37:17 -08004246 voice_channel->SignalRtcpMuxFullyActive.connect(
4247 this, &PeerConnection::DestroyRtcpTransport_n);
4248 voice_channel->SignalDtlsSrtpSetupFailure.connect(
4249 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08004250 voice_channel->SignalSentPacket.connect(this,
4251 &PeerConnection::OnSentPacket_w);
Steve Anton4171afb2017-11-20 10:20:22 -08004252
4253 GetAudioTransceiver()->internal()->SetChannel(voice_channel);
4254
Steve Anton75737c02017-11-06 10:37:17 -08004255 return true;
4256}
4257
Steve Anton4171afb2017-11-20 10:20:22 -08004258// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Anton75737c02017-11-06 10:37:17 -08004259bool PeerConnection::CreateVideoChannel(const cricket::ContentInfo* content,
4260 const std::string* bundle_transport) {
4261 // TODO(steveanton): Check to see if it's safe to create multiple video
4262 // channels.
Steve Anton4171afb2017-11-20 10:20:22 -08004263 RTC_DCHECK(!video_channel());
Steve Anton75737c02017-11-06 10:37:17 -08004264
4265 std::string transport_name =
4266 bundle_transport ? *bundle_transport : content->name;
4267
4268 cricket::DtlsTransportInternal* rtp_dtls_transport =
4269 transport_controller_->CreateDtlsTransport(
4270 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4271 cricket::DtlsTransportInternal* rtcp_dtls_transport = nullptr;
4272 if (configuration_.rtcp_mux_policy !=
4273 PeerConnectionInterface::kRtcpMuxPolicyRequire) {
4274 rtcp_dtls_transport = transport_controller_->CreateDtlsTransport(
4275 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
4276 }
4277
4278 cricket::VideoChannel* video_channel = channel_manager()->CreateVideoChannel(
4279 call_.get(), configuration_.media_config, rtp_dtls_transport,
4280 rtcp_dtls_transport, transport_controller_->signaling_thread(),
4281 content->name, SrtpRequired(), video_options_);
4282
4283 if (!video_channel) {
4284 transport_controller_->DestroyDtlsTransport(
4285 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4286 if (rtcp_dtls_transport) {
4287 transport_controller_->DestroyDtlsTransport(
4288 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
4289 }
4290 return false;
4291 }
Steve Anton75737c02017-11-06 10:37:17 -08004292 video_channel->SignalRtcpMuxFullyActive.connect(
4293 this, &PeerConnection::DestroyRtcpTransport_n);
4294 video_channel->SignalDtlsSrtpSetupFailure.connect(
4295 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08004296 video_channel->SignalSentPacket.connect(this,
4297 &PeerConnection::OnSentPacket_w);
Steve Anton4171afb2017-11-20 10:20:22 -08004298
4299 GetVideoTransceiver()->internal()->SetChannel(video_channel);
4300
Steve Anton75737c02017-11-06 10:37:17 -08004301 return true;
4302}
4303
4304bool PeerConnection::CreateDataChannel(const cricket::ContentInfo* content,
4305 const std::string* bundle_transport) {
4306 const std::string transport_name =
4307 bundle_transport ? *bundle_transport : content->name;
4308 bool sctp = (data_channel_type_ == cricket::DCT_SCTP);
4309 if (sctp) {
4310 if (!sctp_factory_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004311 RTC_LOG(LS_ERROR)
Steve Anton75737c02017-11-06 10:37:17 -08004312 << "Trying to create SCTP transport, but didn't compile with "
4313 "SCTP support (HAVE_SCTP)";
4314 return false;
4315 }
4316 if (!network_thread()->Invoke<bool>(
4317 RTC_FROM_HERE, rtc::Bind(&PeerConnection::CreateSctpTransport_n,
4318 this, content->name, transport_name))) {
4319 return false;
4320 }
4321 } else {
4322 std::string transport_name =
4323 bundle_transport ? *bundle_transport : content->name;
4324 cricket::DtlsTransportInternal* rtp_dtls_transport =
4325 transport_controller_->CreateDtlsTransport(
4326 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4327 cricket::DtlsTransportInternal* rtcp_dtls_transport = nullptr;
4328 if (configuration_.rtcp_mux_policy !=
4329 PeerConnectionInterface::kRtcpMuxPolicyRequire) {
4330 rtcp_dtls_transport = transport_controller_->CreateDtlsTransport(
4331 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
4332 }
4333
4334 rtp_data_channel_ = channel_manager()->CreateRtpDataChannel(
4335 configuration_.media_config, rtp_dtls_transport, rtcp_dtls_transport,
4336 transport_controller_->signaling_thread(), content->name,
4337 SrtpRequired());
4338
4339 if (!rtp_data_channel_) {
4340 transport_controller_->DestroyDtlsTransport(
4341 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4342 if (rtcp_dtls_transport) {
4343 transport_controller_->DestroyDtlsTransport(
4344 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
4345 }
4346 return false;
4347 }
4348
4349 rtp_data_channel_->SignalRtcpMuxFullyActive.connect(
4350 this, &PeerConnection::DestroyRtcpTransport_n);
4351 rtp_data_channel_->SignalDtlsSrtpSetupFailure.connect(
4352 this, &PeerConnection::OnDtlsSrtpSetupFailure);
4353 rtp_data_channel_->SignalSentPacket.connect(
4354 this, &PeerConnection::OnSentPacket_w);
4355 }
4356
Steve Antond25da372017-11-06 14:50:29 -08004357 for (const auto& channel : sctp_data_channels_) {
4358 channel->OnTransportChannelCreated();
4359 }
Steve Anton75737c02017-11-06 10:37:17 -08004360
4361 return true;
4362}
4363
4364Call::Stats PeerConnection::GetCallStats() {
4365 if (!worker_thread()->IsCurrent()) {
4366 return worker_thread()->Invoke<Call::Stats>(
4367 RTC_FROM_HERE, rtc::Bind(&PeerConnection::GetCallStats, this));
4368 }
4369 if (call_) {
4370 return call_->GetStats();
4371 } else {
4372 return Call::Stats();
4373 }
4374}
4375
4376std::unique_ptr<SessionStats> PeerConnection::GetSessionStats_n(
4377 const ChannelNamePairs& channel_name_pairs) {
4378 RTC_DCHECK(network_thread()->IsCurrent());
4379 std::unique_ptr<SessionStats> session_stats(new SessionStats());
4380 for (const auto channel_name_pair :
4381 {&channel_name_pairs.voice, &channel_name_pairs.video,
4382 &channel_name_pairs.data}) {
4383 if (*channel_name_pair) {
4384 cricket::TransportStats transport_stats;
4385 if (!transport_controller_->GetStats((*channel_name_pair)->transport_name,
4386 &transport_stats)) {
4387 return nullptr;
4388 }
4389 session_stats->proxy_to_transport[(*channel_name_pair)->content_name] =
4390 (*channel_name_pair)->transport_name;
4391 session_stats->transport_stats[(*channel_name_pair)->transport_name] =
4392 std::move(transport_stats);
4393 }
4394 }
4395 return session_stats;
4396}
4397
4398bool PeerConnection::CreateSctpTransport_n(const std::string& content_name,
4399 const std::string& transport_name) {
4400 RTC_DCHECK(network_thread()->IsCurrent());
4401 RTC_DCHECK(sctp_factory_);
4402 cricket::DtlsTransportInternal* tc =
4403 transport_controller_->CreateDtlsTransport_n(
4404 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4405 sctp_transport_ = sctp_factory_->CreateSctpTransport(tc);
4406 RTC_DCHECK(sctp_transport_);
4407 sctp_invoker_.reset(new rtc::AsyncInvoker());
4408 sctp_transport_->SignalReadyToSendData.connect(
4409 this, &PeerConnection::OnSctpTransportReadyToSendData_n);
4410 sctp_transport_->SignalDataReceived.connect(
4411 this, &PeerConnection::OnSctpTransportDataReceived_n);
4412 sctp_transport_->SignalStreamClosedRemotely.connect(
4413 this, &PeerConnection::OnSctpStreamClosedRemotely_n);
4414 sctp_transport_name_ = rtc::Optional<std::string>(transport_name);
4415 sctp_content_name_ = rtc::Optional<std::string>(content_name);
4416 return true;
4417}
4418
4419void PeerConnection::ChangeSctpTransport_n(const std::string& transport_name) {
4420 RTC_DCHECK(network_thread()->IsCurrent());
4421 RTC_DCHECK(sctp_transport_);
4422 RTC_DCHECK(sctp_transport_name_);
4423 std::string old_sctp_transport_name = *sctp_transport_name_;
4424 sctp_transport_name_ = rtc::Optional<std::string>(transport_name);
4425 cricket::DtlsTransportInternal* tc =
4426 transport_controller_->CreateDtlsTransport_n(
4427 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4428 sctp_transport_->SetTransportChannel(tc);
4429 transport_controller_->DestroyDtlsTransport_n(
4430 old_sctp_transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4431}
4432
4433void PeerConnection::DestroySctpTransport_n() {
4434 RTC_DCHECK(network_thread()->IsCurrent());
4435 sctp_transport_.reset(nullptr);
4436 sctp_content_name_.reset();
4437 sctp_transport_name_.reset();
4438 sctp_invoker_.reset(nullptr);
4439 sctp_ready_to_send_data_ = false;
4440}
4441
4442void PeerConnection::OnSctpTransportReadyToSendData_n() {
4443 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
4444 RTC_DCHECK(network_thread()->IsCurrent());
4445 // Note: Cannot use rtc::Bind here because it will grab a reference to
4446 // PeerConnection and potentially cause PeerConnection to live longer than
4447 // expected. It is safe not to grab a reference since the sctp_invoker_ will
4448 // be destroyed before PeerConnection is destroyed, and at that point all
4449 // pending tasks will be cleared.
4450 sctp_invoker_->AsyncInvoke<void>(RTC_FROM_HERE, signaling_thread(), [this] {
4451 OnSctpTransportReadyToSendData_s(true);
4452 });
4453}
4454
4455void PeerConnection::OnSctpTransportReadyToSendData_s(bool ready) {
4456 RTC_DCHECK(signaling_thread()->IsCurrent());
4457 sctp_ready_to_send_data_ = ready;
4458 SignalSctpReadyToSendData(ready);
4459}
4460
4461void PeerConnection::OnSctpTransportDataReceived_n(
4462 const cricket::ReceiveDataParams& params,
4463 const rtc::CopyOnWriteBuffer& payload) {
4464 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
4465 RTC_DCHECK(network_thread()->IsCurrent());
4466 // Note: Cannot use rtc::Bind here because it will grab a reference to
4467 // PeerConnection and potentially cause PeerConnection to live longer than
4468 // expected. It is safe not to grab a reference since the sctp_invoker_ will
4469 // be destroyed before PeerConnection is destroyed, and at that point all
4470 // pending tasks will be cleared.
4471 sctp_invoker_->AsyncInvoke<void>(
4472 RTC_FROM_HERE, signaling_thread(), [this, params, payload] {
4473 OnSctpTransportDataReceived_s(params, payload);
4474 });
4475}
4476
4477void PeerConnection::OnSctpTransportDataReceived_s(
4478 const cricket::ReceiveDataParams& params,
4479 const rtc::CopyOnWriteBuffer& payload) {
4480 RTC_DCHECK(signaling_thread()->IsCurrent());
4481 if (params.type == cricket::DMT_CONTROL && IsOpenMessage(payload)) {
4482 // Received OPEN message; parse and signal that a new data channel should
4483 // be created.
4484 std::string label;
4485 InternalDataChannelInit config;
4486 config.id = params.ssrc;
4487 if (!ParseDataChannelOpenMessage(payload, &label, &config)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004488 RTC_LOG(LS_WARNING) << "Failed to parse the OPEN message for sid "
4489 << params.ssrc;
Steve Anton75737c02017-11-06 10:37:17 -08004490 return;
4491 }
4492 config.open_handshake_role = InternalDataChannelInit::kAcker;
4493 OnDataChannelOpenMessage(label, config);
4494 } else {
4495 // Otherwise just forward the signal.
4496 SignalSctpDataReceived(params, payload);
4497 }
4498}
4499
4500void PeerConnection::OnSctpStreamClosedRemotely_n(int sid) {
4501 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
4502 RTC_DCHECK(network_thread()->IsCurrent());
4503 sctp_invoker_->AsyncInvoke<void>(
4504 RTC_FROM_HERE, signaling_thread(),
4505 rtc::Bind(&sigslot::signal1<int>::operator(),
4506 &SignalSctpStreamClosedRemotely, sid));
4507}
4508
4509// Returns false if bundle is enabled and rtcp_mux is disabled.
4510bool PeerConnection::ValidateBundleSettings(const SessionDescription* desc) {
4511 bool bundle_enabled = desc->HasGroup(cricket::GROUP_TYPE_BUNDLE);
4512 if (!bundle_enabled)
4513 return true;
4514
4515 const cricket::ContentGroup* bundle_group =
4516 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
4517 RTC_DCHECK(bundle_group != NULL);
4518
4519 const cricket::ContentInfos& contents = desc->contents();
4520 for (cricket::ContentInfos::const_iterator citer = contents.begin();
4521 citer != contents.end(); ++citer) {
4522 const cricket::ContentInfo* content = (&*citer);
4523 RTC_DCHECK(content != NULL);
4524 if (bundle_group->HasContentName(content->name) && !content->rejected &&
4525 content->type == cricket::NS_JINGLE_RTP) {
4526 if (!HasRtcpMuxEnabled(content))
4527 return false;
4528 }
4529 }
4530 // RTCP-MUX is enabled in all the contents.
4531 return true;
4532}
4533
4534bool PeerConnection::HasRtcpMuxEnabled(const cricket::ContentInfo* content) {
4535 const cricket::MediaContentDescription* description =
4536 static_cast<cricket::MediaContentDescription*>(content->description);
4537 return description->rtcp_mux();
4538}
4539
4540bool PeerConnection::ValidateSessionDescription(
4541 const SessionDescriptionInterface* sdesc,
4542 cricket::ContentSource source,
4543 std::string* err_desc) {
4544 std::string type;
4545 if (error() != ERROR_NONE) {
4546 return BadSdp(source, type, GetSessionErrorMsg(), err_desc);
4547 }
4548
4549 if (!sdesc || !sdesc->description()) {
4550 return BadSdp(source, type, kInvalidSdp, err_desc);
4551 }
4552
4553 type = sdesc->type();
4554 Action action = GetAction(sdesc->type());
4555 if (source == cricket::CS_LOCAL) {
4556 if (!ExpectSetLocalDescription(action))
4557 return BadLocalSdp(type, BadStateErrMsg(signaling_state()), err_desc);
4558 } else {
4559 if (!ExpectSetRemoteDescription(action))
4560 return BadRemoteSdp(type, BadStateErrMsg(signaling_state()), err_desc);
4561 }
4562
4563 // Verify crypto settings.
4564 std::string crypto_error;
4565 if ((webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED ||
4566 dtls_enabled_) &&
4567 !VerifyCrypto(sdesc->description(), dtls_enabled_, &crypto_error)) {
4568 return BadSdp(source, type, crypto_error, err_desc);
4569 }
4570
4571 // Verify ice-ufrag and ice-pwd.
4572 if (!VerifyIceUfragPwdPresent(sdesc->description())) {
4573 return BadSdp(source, type, kSdpWithoutIceUfragPwd, err_desc);
4574 }
4575
4576 if (!ValidateBundleSettings(sdesc->description())) {
4577 return BadSdp(source, type, kBundleWithoutRtcpMux, err_desc);
4578 }
4579
4580 // TODO(skvlad): When the local rtcp-mux policy is Require, reject any
4581 // m-lines that do not rtcp-mux enabled.
4582
4583 // Verify m-lines in Answer when compared against Offer.
4584 if (action == kAnswer || action == kPrAnswer) {
4585 const cricket::SessionDescription* offer_desc =
4586 (source == cricket::CS_LOCAL) ? remote_description()->description()
4587 : local_description()->description();
4588 if (!MediaSectionsHaveSameCount(offer_desc, sdesc->description()) ||
4589 !MediaSectionsInSameOrder(offer_desc, sdesc->description())) {
4590 return BadAnswerSdp(source, kMlineMismatchInAnswer, err_desc);
4591 }
4592 } else {
4593 const cricket::SessionDescription* current_desc = nullptr;
4594 if (source == cricket::CS_LOCAL && local_description()) {
4595 current_desc = local_description()->description();
4596 } else if (source == cricket::CS_REMOTE && remote_description()) {
4597 current_desc = remote_description()->description();
4598 }
4599 // The re-offers should respect the order of m= sections in current
4600 // description. See RFC3264 Section 8 paragraph 4 for more details.
4601 if (current_desc &&
4602 !MediaSectionsInSameOrder(current_desc, sdesc->description())) {
4603 return BadOfferSdp(source, kMlineMismatchInSubsequentOffer, err_desc);
4604 }
4605 }
4606
4607 return true;
4608}
4609
4610bool PeerConnection::ExpectSetLocalDescription(Action action) {
4611 PeerConnectionInterface::SignalingState state = signaling_state();
4612 if (action == kOffer) {
4613 return (state == PeerConnectionInterface::kStable) ||
4614 (state == PeerConnectionInterface::kHaveLocalOffer);
4615 } else { // Answer or PrAnswer
4616 return (state == PeerConnectionInterface::kHaveRemoteOffer) ||
4617 (state == PeerConnectionInterface::kHaveLocalPrAnswer);
4618 }
4619}
4620
4621bool PeerConnection::ExpectSetRemoteDescription(Action action) {
4622 PeerConnectionInterface::SignalingState state = signaling_state();
4623 if (action == kOffer) {
4624 return (state == PeerConnectionInterface::kStable) ||
4625 (state == PeerConnectionInterface::kHaveRemoteOffer);
4626 } else { // Answer or PrAnswer.
4627 return (state == PeerConnectionInterface::kHaveLocalOffer) ||
4628 (state == PeerConnectionInterface::kHaveRemotePrAnswer);
4629 }
4630}
4631
4632std::string PeerConnection::GetSessionErrorMsg() {
4633 std::ostringstream desc;
4634 desc << kSessionError << GetErrorCodeString(error()) << ". ";
4635 desc << kSessionErrorDesc << error_desc() << ".";
4636 return desc.str();
4637}
4638
4639// We need to check the local/remote description for the Transport instead of
4640// the session, because a new Transport added during renegotiation may have
4641// them unset while the session has them set from the previous negotiation.
4642// Not doing so may trigger the auto generation of transport description and
4643// mess up DTLS identity information, ICE credential, etc.
4644bool PeerConnection::ReadyToUseRemoteCandidate(
4645 const IceCandidateInterface* candidate,
4646 const SessionDescriptionInterface* remote_desc,
4647 bool* valid) {
4648 *valid = true;
4649
4650 const SessionDescriptionInterface* current_remote_desc =
4651 remote_desc ? remote_desc : remote_description();
4652
4653 if (!current_remote_desc) {
4654 return false;
4655 }
4656
4657 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
4658 size_t remote_content_size =
4659 current_remote_desc->description()->contents().size();
4660 if (mediacontent_index >= remote_content_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004661 RTC_LOG(LS_ERROR)
4662 << "ReadyToUseRemoteCandidate: Invalid candidate media index "
4663 << mediacontent_index;
Steve Anton75737c02017-11-06 10:37:17 -08004664
4665 *valid = false;
4666 return false;
4667 }
4668
4669 cricket::ContentInfo content =
4670 current_remote_desc->description()->contents()[mediacontent_index];
4671
4672 const std::string transport_name = GetTransportName(content.name);
4673 if (transport_name.empty()) {
4674 return false;
4675 }
4676 return transport_controller_->ReadyForRemoteCandidates(transport_name);
4677}
4678
4679bool PeerConnection::SrtpRequired() const {
4680 return dtls_enabled_ ||
4681 webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED;
4682}
4683
4684void PeerConnection::OnTransportControllerGatheringState(
4685 cricket::IceGatheringState state) {
4686 RTC_DCHECK(signaling_thread()->IsCurrent());
4687 if (state == cricket::kIceGatheringGathering) {
4688 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringGathering);
4689 } else if (state == cricket::kIceGatheringComplete) {
4690 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringComplete);
4691 }
4692}
4693
4694void PeerConnection::ReportTransportStats() {
4695 // Use a set so we don't report the same stats twice if two channels share
4696 // a transport.
4697 std::set<std::string> transport_names;
4698 if (voice_channel()) {
4699 transport_names.insert(voice_channel()->transport_name());
4700 }
4701 if (video_channel()) {
4702 transport_names.insert(video_channel()->transport_name());
4703 }
4704 if (rtp_data_channel()) {
4705 transport_names.insert(rtp_data_channel()->transport_name());
4706 }
4707 if (sctp_transport_name_) {
4708 transport_names.insert(*sctp_transport_name_);
4709 }
4710 for (const auto& name : transport_names) {
4711 cricket::TransportStats stats;
4712 if (transport_controller_->GetStats(name, &stats)) {
4713 ReportBestConnectionState(stats);
4714 ReportNegotiatedCiphers(stats);
4715 }
4716 }
4717}
4718// Walk through the ConnectionInfos to gather best connection usage
4719// for IPv4 and IPv6.
4720void PeerConnection::ReportBestConnectionState(
4721 const cricket::TransportStats& stats) {
4722 RTC_DCHECK(metrics_observer());
4723 for (cricket::TransportChannelStatsList::const_iterator it =
4724 stats.channel_stats.begin();
4725 it != stats.channel_stats.end(); ++it) {
4726 for (cricket::ConnectionInfos::const_iterator it_info =
4727 it->connection_infos.begin();
4728 it_info != it->connection_infos.end(); ++it_info) {
4729 if (!it_info->best_connection) {
4730 continue;
4731 }
4732
4733 PeerConnectionEnumCounterType type = kPeerConnectionEnumCounterMax;
4734 const cricket::Candidate& local = it_info->local_candidate;
4735 const cricket::Candidate& remote = it_info->remote_candidate;
4736
4737 // Increment the counter for IceCandidatePairType.
4738 if (local.protocol() == cricket::TCP_PROTOCOL_NAME ||
4739 (local.type() == RELAY_PORT_TYPE &&
4740 local.relay_protocol() == cricket::TCP_PROTOCOL_NAME)) {
4741 type = kEnumCounterIceCandidatePairTypeTcp;
4742 } else if (local.protocol() == cricket::UDP_PROTOCOL_NAME) {
4743 type = kEnumCounterIceCandidatePairTypeUdp;
4744 } else {
4745 RTC_CHECK(0);
4746 }
4747 metrics_observer()->IncrementEnumCounter(
4748 type, GetIceCandidatePairCounter(local, remote),
4749 kIceCandidatePairMax);
4750
4751 // Increment the counter for IP type.
4752 if (local.address().family() == AF_INET) {
4753 metrics_observer()->IncrementEnumCounter(
4754 kEnumCounterAddressFamily, kBestConnections_IPv4,
4755 kPeerConnectionAddressFamilyCounter_Max);
4756
4757 } else if (local.address().family() == AF_INET6) {
4758 metrics_observer()->IncrementEnumCounter(
4759 kEnumCounterAddressFamily, kBestConnections_IPv6,
4760 kPeerConnectionAddressFamilyCounter_Max);
4761 } else {
4762 RTC_CHECK(0);
4763 }
4764
4765 return;
4766 }
4767 }
4768}
4769
4770void PeerConnection::ReportNegotiatedCiphers(
4771 const cricket::TransportStats& stats) {
4772 RTC_DCHECK(metrics_observer());
4773 if (!dtls_enabled_ || stats.channel_stats.empty()) {
4774 return;
4775 }
4776
4777 int srtp_crypto_suite = stats.channel_stats[0].srtp_crypto_suite;
4778 int ssl_cipher_suite = stats.channel_stats[0].ssl_cipher_suite;
4779 if (srtp_crypto_suite == rtc::SRTP_INVALID_CRYPTO_SUITE &&
4780 ssl_cipher_suite == rtc::TLS_NULL_WITH_NULL_NULL) {
4781 return;
4782 }
4783
4784 PeerConnectionEnumCounterType srtp_counter_type;
4785 PeerConnectionEnumCounterType ssl_counter_type;
4786 if (stats.transport_name == cricket::CN_AUDIO) {
4787 srtp_counter_type = kEnumCounterAudioSrtpCipher;
4788 ssl_counter_type = kEnumCounterAudioSslCipher;
4789 } else if (stats.transport_name == cricket::CN_VIDEO) {
4790 srtp_counter_type = kEnumCounterVideoSrtpCipher;
4791 ssl_counter_type = kEnumCounterVideoSslCipher;
4792 } else if (stats.transport_name == cricket::CN_DATA) {
4793 srtp_counter_type = kEnumCounterDataSrtpCipher;
4794 ssl_counter_type = kEnumCounterDataSslCipher;
4795 } else {
4796 RTC_NOTREACHED();
4797 return;
4798 }
4799
4800 if (srtp_crypto_suite != rtc::SRTP_INVALID_CRYPTO_SUITE) {
4801 metrics_observer()->IncrementSparseEnumCounter(srtp_counter_type,
4802 srtp_crypto_suite);
4803 }
4804 if (ssl_cipher_suite != rtc::TLS_NULL_WITH_NULL_NULL) {
4805 metrics_observer()->IncrementSparseEnumCounter(ssl_counter_type,
4806 ssl_cipher_suite);
4807 }
4808}
4809
4810void PeerConnection::OnSentPacket_w(const rtc::SentPacket& sent_packet) {
4811 RTC_DCHECK(worker_thread()->IsCurrent());
4812 RTC_DCHECK(call_);
4813 call_->OnSentPacket(sent_packet);
4814}
4815
4816const std::string PeerConnection::GetTransportName(
4817 const std::string& content_name) {
4818 cricket::BaseChannel* channel = GetChannel(content_name);
4819 if (!channel) {
4820 if (sctp_transport_) {
4821 RTC_DCHECK(sctp_content_name_);
4822 RTC_DCHECK(sctp_transport_name_);
4823 if (content_name == *sctp_content_name_) {
4824 return *sctp_transport_name_;
4825 }
4826 }
4827 // Return an empty string if failed to retrieve the transport name.
4828 return "";
4829 }
4830 return channel->transport_name();
4831}
4832
4833void PeerConnection::DestroyRtcpTransport_n(const std::string& transport_name) {
4834 RTC_DCHECK(network_thread()->IsCurrent());
4835 transport_controller_->DestroyDtlsTransport_n(
4836 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
4837}
4838
Steve Anton4171afb2017-11-20 10:20:22 -08004839// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Anton75737c02017-11-06 10:37:17 -08004840void PeerConnection::DestroyVideoChannel(cricket::VideoChannel* video_channel) {
Steve Anton4171afb2017-11-20 10:20:22 -08004841 RTC_DCHECK(video_channel);
Steve Anton75737c02017-11-06 10:37:17 -08004842 RTC_DCHECK(video_channel->rtp_dtls_transport());
Steve Anton4171afb2017-11-20 10:20:22 -08004843 RTC_DCHECK_EQ(GetVideoTransceiver()->internal()->channel(), video_channel);
4844 GetVideoTransceiver()->internal()->SetChannel(nullptr);
Steve Anton75737c02017-11-06 10:37:17 -08004845 const std::string transport_name =
4846 video_channel->rtp_dtls_transport()->transport_name();
4847 const bool need_to_delete_rtcp =
4848 (video_channel->rtcp_dtls_transport() != nullptr);
4849 // The above need to be cached before destroying the video channel so that we
4850 // do not access uninitialized memory.
4851 channel_manager()->DestroyVideoChannel(video_channel);
4852 transport_controller_->DestroyDtlsTransport(
4853 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4854 if (need_to_delete_rtcp) {
4855 transport_controller_->DestroyDtlsTransport(
4856 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
4857 }
4858}
4859
Steve Anton4171afb2017-11-20 10:20:22 -08004860// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Anton75737c02017-11-06 10:37:17 -08004861void PeerConnection::DestroyVoiceChannel(cricket::VoiceChannel* voice_channel) {
Steve Anton4171afb2017-11-20 10:20:22 -08004862 RTC_DCHECK(voice_channel);
Steve Anton75737c02017-11-06 10:37:17 -08004863 RTC_DCHECK(voice_channel->rtp_dtls_transport());
Steve Anton4171afb2017-11-20 10:20:22 -08004864 RTC_DCHECK_EQ(GetAudioTransceiver()->internal()->channel(), voice_channel);
4865 GetAudioTransceiver()->internal()->SetChannel(nullptr);
Steve Anton75737c02017-11-06 10:37:17 -08004866 const std::string transport_name =
4867 voice_channel->rtp_dtls_transport()->transport_name();
4868 const bool need_to_delete_rtcp =
4869 (voice_channel->rtcp_dtls_transport() != nullptr);
4870 // The above need to be cached before destroying the video channel so that we
4871 // do not access uninitialized memory.
4872 channel_manager()->DestroyVoiceChannel(voice_channel);
4873 transport_controller_->DestroyDtlsTransport(
4874 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4875 if (need_to_delete_rtcp) {
4876 transport_controller_->DestroyDtlsTransport(
4877 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
4878 }
4879}
4880
4881void PeerConnection::DestroyDataChannel() {
4882 OnDataChannelDestroyed();
4883 RTC_DCHECK(rtp_data_channel_->rtp_dtls_transport());
4884 std::string transport_name;
4885 transport_name = rtp_data_channel_->rtp_dtls_transport()->transport_name();
4886 bool need_to_delete_rtcp =
4887 (rtp_data_channel_->rtcp_dtls_transport() != nullptr);
4888 channel_manager()->DestroyRtpDataChannel(rtp_data_channel_);
4889 rtp_data_channel_ = nullptr;
4890 transport_controller_->DestroyDtlsTransport(
4891 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4892 if (need_to_delete_rtcp) {
4893 transport_controller_->DestroyDtlsTransport(
4894 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
4895 }
4896}
4897
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004898} // namespace webrtc