blob: d617c715d0a6f205add076a510fa387ea129ce5a [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;
deadbeef293e9262017-01-11 12:28:30 -0800678 };
679 static_assert(sizeof(stuff_being_tested_for_equality) == sizeof(*this),
680 "Did you add something to RTCConfiguration and forget to "
681 "update operator==?");
682 return type == o.type && servers == o.servers &&
683 bundle_policy == o.bundle_policy &&
684 rtcp_mux_policy == o.rtcp_mux_policy &&
685 tcp_candidate_policy == o.tcp_candidate_policy &&
686 candidate_network_policy == o.candidate_network_policy &&
687 audio_jitter_buffer_max_packets == o.audio_jitter_buffer_max_packets &&
688 audio_jitter_buffer_fast_accelerate ==
689 o.audio_jitter_buffer_fast_accelerate &&
690 ice_connection_receiving_timeout ==
691 o.ice_connection_receiving_timeout &&
692 ice_backup_candidate_pair_ping_interval ==
693 o.ice_backup_candidate_pair_ping_interval &&
694 continual_gathering_policy == o.continual_gathering_policy &&
695 certificates == o.certificates &&
696 prioritize_most_likely_ice_candidate_pairs ==
697 o.prioritize_most_likely_ice_candidate_pairs &&
698 media_config == o.media_config && disable_ipv6 == o.disable_ipv6 &&
zhihuangb09b3f92017-03-07 14:40:51 -0800699 disable_ipv6_on_wifi == o.disable_ipv6_on_wifi &&
deadbeefd21eab32017-07-26 16:50:11 -0700700 max_ipv6_networks == o.max_ipv6_networks &&
deadbeef293e9262017-01-11 12:28:30 -0800701 enable_rtp_data_channel == o.enable_rtp_data_channel &&
deadbeef293e9262017-01-11 12:28:30 -0800702 screencast_min_bitrate == o.screencast_min_bitrate &&
703 combined_audio_video_bwe == o.combined_audio_video_bwe &&
704 enable_dtls_srtp == o.enable_dtls_srtp &&
705 ice_candidate_pool_size == o.ice_candidate_pool_size &&
706 prune_turn_ports == o.prune_turn_ports &&
707 presume_writable_when_fully_relayed ==
708 o.presume_writable_when_fully_relayed &&
709 enable_ice_renomination == o.enable_ice_renomination &&
skvlad51072462017-02-02 11:50:14 -0800710 redetermine_role_on_ice_restart == o.redetermine_role_on_ice_restart &&
Steve Anton300bf8e2017-07-14 10:13:10 -0700711 ice_check_min_interval == o.ice_check_min_interval &&
Jonas Orelandbdcee282017-10-10 14:01:40 +0200712 ice_regather_interval_range == o.ice_regather_interval_range &&
713 turn_customizer == o.turn_customizer;
deadbeef293e9262017-01-11 12:28:30 -0800714}
715
716bool PeerConnectionInterface::RTCConfiguration::operator!=(
717 const PeerConnectionInterface::RTCConfiguration& o) const {
718 return !(*this == o);
deadbeef3edec7c2016-12-10 11:44:26 -0800719}
720
zhihuang8f65cdf2016-05-06 18:40:30 -0700721// Generate a RTCP CNAME when a PeerConnection is created.
722std::string GenerateRtcpCname() {
723 std::string cname;
724 if (!rtc::CreateRandomString(kRtcpCnameLength, &cname)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100725 RTC_LOG(LS_ERROR) << "Failed to generate CNAME.";
nisseeb4ca4e2017-01-12 02:24:27 -0800726 RTC_NOTREACHED();
zhihuang8f65cdf2016-05-06 18:40:30 -0700727 }
728 return cname;
729}
730
zhihuang1c378ed2017-08-17 14:10:50 -0700731bool ValidateOfferAnswerOptions(
732 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options) {
733 return IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_audio) &&
734 IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_video);
olka3c747662017-08-17 06:50:32 -0700735}
736
zhihuang1c378ed2017-08-17 14:10:50 -0700737// From |rtc_options|, fill parts of |session_options| shared by all generated
738// m= sections (in other words, nothing that involves a map/array).
739void ExtractSharedMediaSessionOptions(
740 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options,
741 cricket::MediaSessionOptions* session_options) {
742 session_options->vad_enabled = rtc_options.voice_activity_detection;
743 session_options->bundle_enabled = rtc_options.use_rtp_mux;
744}
zhihuanga77e6bb2017-08-14 18:17:48 -0700745
zhihuang1c378ed2017-08-17 14:10:50 -0700746bool ConvertConstraintsToOfferAnswerOptions(
747 const MediaConstraintsInterface* constraints,
748 PeerConnectionInterface::RTCOfferAnswerOptions* offer_answer_options) {
olka3c747662017-08-17 06:50:32 -0700749 if (!constraints) {
750 return true;
751 }
zhihuang1c378ed2017-08-17 14:10:50 -0700752
753 bool value = false;
754 size_t mandatory_constraints_satisfied = 0;
755
756 if (FindConstraint(constraints,
757 MediaConstraintsInterface::kOfferToReceiveAudio, &value,
758 &mandatory_constraints_satisfied)) {
759 offer_answer_options->offer_to_receive_audio =
760 value ? PeerConnectionInterface::RTCOfferAnswerOptions::
761 kOfferToReceiveMediaTrue
762 : 0;
763 }
764
765 if (FindConstraint(constraints,
766 MediaConstraintsInterface::kOfferToReceiveVideo, &value,
767 &mandatory_constraints_satisfied)) {
768 offer_answer_options->offer_to_receive_video =
769 value ? PeerConnectionInterface::RTCOfferAnswerOptions::
770 kOfferToReceiveMediaTrue
771 : 0;
772 }
773 if (FindConstraint(constraints,
774 MediaConstraintsInterface::kVoiceActivityDetection, &value,
775 &mandatory_constraints_satisfied)) {
776 offer_answer_options->voice_activity_detection = value;
777 }
778 if (FindConstraint(constraints, MediaConstraintsInterface::kUseRtpMux, &value,
779 &mandatory_constraints_satisfied)) {
780 offer_answer_options->use_rtp_mux = value;
781 }
782 if (FindConstraint(constraints, MediaConstraintsInterface::kIceRestart,
783 &value, &mandatory_constraints_satisfied)) {
784 offer_answer_options->ice_restart = value;
785 }
786
deadbeefab9b2d12015-10-14 11:33:11 -0700787 return mandatory_constraints_satisfied == constraints->GetMandatory().size();
788}
789
zhihuang38ede132017-06-15 12:52:32 -0700790PeerConnection::PeerConnection(PeerConnectionFactory* factory,
791 std::unique_ptr<RtcEventLog> event_log,
792 std::unique_ptr<Call> call)
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000793 : factory_(factory),
zhihuang38ede132017-06-15 12:52:32 -0700794 event_log_(std::move(event_log)),
zhihuang8f65cdf2016-05-06 18:40:30 -0700795 rtcp_cname_(GenerateRtcpCname()),
deadbeefab9b2d12015-10-14 11:33:11 -0700796 local_streams_(StreamCollection::Create()),
zhihuang38ede132017-06-15 12:52:32 -0700797 remote_streams_(StreamCollection::Create()),
798 call_(std::move(call)) {}
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000799
800PeerConnection::~PeerConnection() {
Peter Boström1a9d6152015-12-08 22:15:17 +0100801 TRACE_EVENT0("webrtc", "PeerConnection::~PeerConnection");
Steve Anton4171afb2017-11-20 10:20:22 -0800802 RTC_DCHECK_RUN_ON(signaling_thread());
803
804 // Need to detach RTP transceivers from PeerConnection, since it's about to be
805 // destroyed.
806 for (auto transceiver : transceivers_) {
807 transceiver->Stop();
deadbeef70ab1a12015-09-28 16:53:55 -0700808 }
Steve Anton4171afb2017-11-20 10:20:22 -0800809
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700810 // Destroy stats_ because it depends on session_.
811 stats_.reset(nullptr);
hbosb78306a2016-12-19 05:06:57 -0800812 if (stats_collector_) {
813 stats_collector_->WaitForPendingRequest();
814 stats_collector_ = nullptr;
815 }
Steve Anton75737c02017-11-06 10:37:17 -0800816
817 // Destroy video channels first since they may have a pointer to a voice
818 // channel.
Steve Anton4171afb2017-11-20 10:20:22 -0800819 for (auto transceiver : transceivers_) {
820 if (transceiver->internal()->media_type() == cricket::MEDIA_TYPE_VIDEO &&
821 transceiver->internal()->channel()) {
822 DestroyVideoChannel(static_cast<cricket::VideoChannel*>(
823 transceiver->internal()->channel()));
824 }
Steve Anton75737c02017-11-06 10:37:17 -0800825 }
Steve Anton4171afb2017-11-20 10:20:22 -0800826 for (auto transceiver : transceivers_) {
827 if (transceiver->internal()->media_type() == cricket::MEDIA_TYPE_AUDIO &&
828 transceiver->internal()->channel()) {
829 DestroyVoiceChannel(static_cast<cricket::VoiceChannel*>(
830 transceiver->internal()->channel()));
831 }
Steve Anton75737c02017-11-06 10:37:17 -0800832 }
833 if (rtp_data_channel_) {
834 DestroyDataChannel();
835 }
836
837 // Note: Cannot use rtc::Bind to create a functor to invoke because it will
838 // grab a reference to this PeerConnection. The RefCountedObject vtable will
839 // have already been destroyed (since it is a subclass of PeerConnection) and
840 // using rtc::Bind will cause "Pure virtual function called" error to appear.
841
842 if (sctp_transport_) {
843 OnDataChannelDestroyed();
844 network_thread()->Invoke<void>(RTC_FROM_HERE,
845 [this] { DestroySctpTransport_n(); });
846 }
847
Mirko Bonadei675513b2017-11-09 11:09:25 +0100848 RTC_LOG(LS_INFO) << "Session: " << session_id() << " is destroyed.";
Steve Anton75737c02017-11-06 10:37:17 -0800849
850 webrtc_session_desc_factory_.reset();
851 sctp_invoker_.reset();
852 sctp_factory_.reset();
853 transport_controller_.reset();
854
deadbeef91dd5672016-05-18 16:55:30 -0700855 // port_allocator_ lives on the network thread and should be destroyed there.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700856 network_thread()->Invoke<void>(RTC_FROM_HERE,
nisseeaabdf62017-05-05 02:23:02 -0700857 [this] { port_allocator_.reset(); });
eladalon248fd4f2017-09-06 05:18:15 -0700858 // call_ and event_log_ must be destroyed on the worker thread.
Steve Anton978b8762017-09-29 12:15:02 -0700859 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
eladalon248fd4f2017-09-06 05:18:15 -0700860 call_.reset();
861 event_log_.reset();
862 });
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000863}
864
865bool PeerConnection::Initialize(
buildbot@webrtc.org41451d42014-05-03 05:39:45 +0000866 const PeerConnectionInterface::RTCConfiguration& configuration,
kwibergd1fe2812016-04-27 06:47:29 -0700867 std::unique_ptr<cricket::PortAllocator> allocator,
Henrik Boströmd03c23b2016-06-01 11:44:18 +0200868 std::unique_ptr<rtc::RTCCertificateGeneratorInterface> cert_generator,
deadbeef653b8e02015-11-11 12:55:10 -0800869 PeerConnectionObserver* observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100870 TRACE_EVENT0("webrtc", "PeerConnection::Initialize");
Steve Anton038834f2017-07-14 15:59:59 -0700871
872 RTCError config_error = ValidateConfiguration(configuration);
873 if (!config_error.ok()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100874 RTC_LOG(LS_ERROR) << "Invalid configuration: " << config_error.message();
Steve Anton038834f2017-07-14 15:59:59 -0700875 return false;
876 }
877
deadbeef293e9262017-01-11 12:28:30 -0800878 if (!allocator) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100879 RTC_LOG(LS_ERROR)
880 << "PeerConnection initialized without a PortAllocator? "
881 << "This shouldn't happen if using PeerConnectionFactory.";
deadbeef293e9262017-01-11 12:28:30 -0800882 return false;
883 }
Jonas Orelandbdcee282017-10-10 14:01:40 +0200884
deadbeef653b8e02015-11-11 12:55:10 -0800885 if (!observer) {
deadbeef293e9262017-01-11 12:28:30 -0800886 // TODO(deadbeef): Why do we do this?
Mirko Bonadei675513b2017-11-09 11:09:25 +0100887 RTC_LOG(LS_ERROR) << "PeerConnection initialized without a "
888 << "PeerConnectionObserver";
deadbeef653b8e02015-11-11 12:55:10 -0800889 return false;
890 }
pthatcher@webrtc.org877ac762015-02-04 22:03:09 +0000891 observer_ = observer;
kwiberg0eb15ed2015-12-17 03:04:15 -0800892 port_allocator_ = std::move(allocator);
deadbeef653b8e02015-11-11 12:55:10 -0800893
deadbeef91dd5672016-05-18 16:55:30 -0700894 // The port allocator lives on the network thread and should be initialized
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700895 // there.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700896 if (!network_thread()->Invoke<bool>(
897 RTC_FROM_HERE, rtc::Bind(&PeerConnection::InitializePortAllocator_n,
898 this, configuration))) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000899 return false;
900 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000901
Steve Anton75737c02017-11-06 10:37:17 -0800902 // RFC 3264: The numeric value of the session id and version in the
903 // o line MUST be representable with a "64 bit signed integer".
904 // Due to this constraint session id |session_id_| is max limited to
905 // LLONG_MAX.
906 session_id_ = rtc::ToString(rtc::CreateRandomId64() & LLONG_MAX);
907 transport_controller_.reset(factory_->CreateTransportController(
908 port_allocator_.get(), configuration.redetermine_role_on_ice_restart));
909 transport_controller_->SetIceRole(cricket::ICEROLE_CONTROLLED);
910 transport_controller_->SignalConnectionState.connect(
911 this, &PeerConnection::OnTransportControllerConnectionState);
912 transport_controller_->SignalGatheringState.connect(
913 this, &PeerConnection::OnTransportControllerGatheringState);
914 transport_controller_->SignalCandidatesGathered.connect(
915 this, &PeerConnection::OnTransportControllerCandidatesGathered);
916 transport_controller_->SignalCandidatesRemoved.connect(
917 this, &PeerConnection::OnTransportControllerCandidatesRemoved);
918 transport_controller_->SignalDtlsHandshakeError.connect(
919 this, &PeerConnection::OnTransportControllerDtlsHandshakeError);
920
921 sctp_factory_ = factory_->CreateSctpTransportInternalFactory();
zhihuang29ff8442016-07-27 11:07:25 -0700922
deadbeefab9b2d12015-10-14 11:33:11 -0700923 stats_.reset(new StatsCollector(this));
hbos74e1a4f2016-09-15 23:33:01 -0700924 stats_collector_ = RTCStatsCollector::Create(this);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000925
Steve Antonba818672017-11-06 10:21:57 -0800926 configuration_ = configuration;
927
Steve Anton75737c02017-11-06 10:37:17 -0800928 const PeerConnectionFactoryInterface::Options& options = factory_->options();
929
930 transport_controller_->SetSslMaxProtocolVersion(options.ssl_max_version);
931
932 // Obtain a certificate from RTCConfiguration if any were provided (optional).
933 rtc::scoped_refptr<rtc::RTCCertificate> certificate;
934 if (!configuration.certificates.empty()) {
935 // TODO(hbos,torbjorng): Decide on certificate-selection strategy instead of
936 // just picking the first one. The decision should be made based on the DTLS
937 // handshake. The DTLS negotiations need to know about all certificates.
938 certificate = configuration.certificates[0];
939 }
940
Steve Antond25da372017-11-06 14:50:29 -0800941 transport_controller_->SetIceConfig(ParseIceConfig(configuration));
Steve Anton75737c02017-11-06 10:37:17 -0800942
943 if (options.disable_encryption) {
944 dtls_enabled_ = false;
945 } else {
946 // Enable DTLS by default if we have an identity store or a certificate.
947 dtls_enabled_ = (cert_generator || certificate);
948 // |configuration| can override the default |dtls_enabled_| value.
949 if (configuration.enable_dtls_srtp) {
950 dtls_enabled_ = *(configuration.enable_dtls_srtp);
951 }
952 }
953
954 // Enable creation of RTP data channels if the kEnableRtpDataChannels is set.
955 // It takes precendence over the disable_sctp_data_channels
956 // PeerConnectionFactoryInterface::Options.
957 if (configuration.enable_rtp_data_channel) {
958 data_channel_type_ = cricket::DCT_RTP;
959 } else {
960 // DTLS has to be enabled to use SCTP.
961 if (!options.disable_sctp_data_channels && dtls_enabled_) {
962 data_channel_type_ = cricket::DCT_SCTP;
963 }
964 }
965
966 video_options_.screencast_min_bitrate_kbps =
967 configuration.screencast_min_bitrate;
968 audio_options_.combined_audio_video_bwe =
969 configuration.combined_audio_video_bwe;
970
971 audio_options_.audio_jitter_buffer_max_packets =
972 rtc::Optional<int>(configuration.audio_jitter_buffer_max_packets);
973
974 audio_options_.audio_jitter_buffer_fast_accelerate =
975 rtc::Optional<bool>(configuration.audio_jitter_buffer_fast_accelerate);
976
977 // Whether the certificate generator/certificate is null or not determines
978 // what PeerConnectionDescriptionFactory will do, so make sure that we give it
979 // the right instructions by clearing the variables if needed.
980 if (!dtls_enabled_) {
981 cert_generator.reset();
982 certificate = nullptr;
983 } else if (certificate) {
984 // Favor generated certificate over the certificate generator.
985 cert_generator.reset();
986 }
987
988 webrtc_session_desc_factory_.reset(new WebRtcSessionDescriptionFactory(
989 signaling_thread(), channel_manager(), this, session_id(),
990 std::move(cert_generator), certificate));
991 webrtc_session_desc_factory_->SignalCertificateReady.connect(
992 this, &PeerConnection::OnCertificateReady);
993
994 if (options.disable_encryption) {
995 webrtc_session_desc_factory_->SetSdesPolicy(cricket::SEC_DISABLED);
996 }
997
998 webrtc_session_desc_factory_->set_enable_encrypted_rtp_header_extensions(
999 options.crypto_options.enable_encrypted_rtp_header_extensions);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001000
Steve Anton4171afb2017-11-20 10:20:22 -08001001 // Add default audio/video transceivers for Plan B SDP.
1002 if (!IsUnifiedPlan()) {
1003 transceivers_.push_back(
1004 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1005 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_AUDIO)));
1006 transceivers_.push_back(
1007 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1008 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_VIDEO)));
1009 }
1010
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001011 return true;
1012}
1013
Steve Anton038834f2017-07-14 15:59:59 -07001014RTCError PeerConnection::ValidateConfiguration(
1015 const RTCConfiguration& config) const {
1016 if (config.ice_regather_interval_range &&
1017 config.continual_gathering_policy == GATHER_ONCE) {
1018 return RTCError(RTCErrorType::INVALID_PARAMETER,
1019 "ice_regather_interval_range specified but continual "
1020 "gathering policy is GATHER_ONCE");
1021 }
1022 return RTCError::OK();
1023}
1024
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001025rtc::scoped_refptr<StreamCollectionInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001026PeerConnection::local_streams() {
deadbeefab9b2d12015-10-14 11:33:11 -07001027 return local_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001028}
1029
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001030rtc::scoped_refptr<StreamCollectionInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001031PeerConnection::remote_streams() {
deadbeefab9b2d12015-10-14 11:33:11 -07001032 return remote_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001033}
1034
perkj@webrtc.orgc2dd5ee2014-11-04 11:31:29 +00001035bool PeerConnection::AddStream(MediaStreamInterface* local_stream) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001036 TRACE_EVENT0("webrtc", "PeerConnection::AddStream");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001037 if (IsClosed()) {
1038 return false;
1039 }
deadbeefab9b2d12015-10-14 11:33:11 -07001040 if (!CanAddLocalMediaStream(local_streams_, local_stream)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001041 return false;
1042 }
deadbeefab9b2d12015-10-14 11:33:11 -07001043
1044 local_streams_->AddStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -08001045 MediaStreamObserver* observer = new MediaStreamObserver(local_stream);
1046 observer->SignalAudioTrackAdded.connect(this,
1047 &PeerConnection::OnAudioTrackAdded);
1048 observer->SignalAudioTrackRemoved.connect(
1049 this, &PeerConnection::OnAudioTrackRemoved);
1050 observer->SignalVideoTrackAdded.connect(this,
1051 &PeerConnection::OnVideoTrackAdded);
1052 observer->SignalVideoTrackRemoved.connect(
1053 this, &PeerConnection::OnVideoTrackRemoved);
kwibergd1fe2812016-04-27 06:47:29 -07001054 stream_observers_.push_back(std::unique_ptr<MediaStreamObserver>(observer));
deadbeefab9b2d12015-10-14 11:33:11 -07001055
deadbeefab9b2d12015-10-14 11:33:11 -07001056 for (const auto& track : local_stream->GetAudioTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001057 AddAudioTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -07001058 }
1059 for (const auto& track : local_stream->GetVideoTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001060 AddVideoTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -07001061 }
1062
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001063 stats_->AddStream(local_stream);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001064 observer_->OnRenegotiationNeeded();
1065 return true;
1066}
1067
1068void PeerConnection::RemoveStream(MediaStreamInterface* local_stream) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001069 TRACE_EVENT0("webrtc", "PeerConnection::RemoveStream");
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001070 if (!IsClosed()) {
1071 for (const auto& track : local_stream->GetAudioTracks()) {
1072 RemoveAudioTrack(track.get(), local_stream);
1073 }
1074 for (const auto& track : local_stream->GetVideoTracks()) {
1075 RemoveVideoTrack(track.get(), local_stream);
1076 }
deadbeefab9b2d12015-10-14 11:33:11 -07001077 }
deadbeefab9b2d12015-10-14 11:33:11 -07001078 local_streams_->RemoveStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -08001079 stream_observers_.erase(
1080 std::remove_if(
1081 stream_observers_.begin(), stream_observers_.end(),
kwibergd1fe2812016-04-27 06:47:29 -07001082 [local_stream](const std::unique_ptr<MediaStreamObserver>& observer) {
deadbeefeb459812015-12-15 19:24:43 -08001083 return observer->stream()->label().compare(local_stream->label()) ==
1084 0;
1085 }),
1086 stream_observers_.end());
deadbeefab9b2d12015-10-14 11:33:11 -07001087
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001088 if (IsClosed()) {
1089 return;
1090 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001091 observer_->OnRenegotiationNeeded();
1092}
1093
deadbeefe1f9d832016-01-14 15:35:42 -08001094rtc::scoped_refptr<RtpSenderInterface> PeerConnection::AddTrack(
1095 MediaStreamTrackInterface* track,
1096 std::vector<MediaStreamInterface*> streams) {
1097 TRACE_EVENT0("webrtc", "PeerConnection::AddTrack");
1098 if (IsClosed()) {
1099 return nullptr;
1100 }
1101 if (streams.size() >= 2) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001102 RTC_LOG(LS_ERROR)
deadbeefe1f9d832016-01-14 15:35:42 -08001103 << "Adding a track with two streams is not currently supported.";
1104 return nullptr;
1105 }
Steve Anton4171afb2017-11-20 10:20:22 -08001106 if (FindSenderForTrack(track)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001107 RTC_LOG(LS_ERROR) << "Sender for track " << track->id()
1108 << " already exists.";
deadbeefe1f9d832016-01-14 15:35:42 -08001109 return nullptr;
1110 }
1111
1112 // TODO(deadbeef): Support adding a track to multiple streams.
deadbeefa601f5c2016-06-06 14:27:39 -07001113 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender;
deadbeefe1f9d832016-01-14 15:35:42 -08001114 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
deadbeefa601f5c2016-06-06 14:27:39 -07001115 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
deadbeefe1f9d832016-01-14 15:35:42 -08001116 signaling_thread(),
1117 new AudioRtpSender(static_cast<AudioTrackInterface*>(track),
Steve Anton75737c02017-11-06 10:37:17 -08001118 voice_channel(), stats_.get()));
Steve Anton4171afb2017-11-20 10:20:22 -08001119 GetAudioTransceiver()->internal()->AddSender(new_sender);
deadbeefe1f9d832016-01-14 15:35:42 -08001120 if (!streams.empty()) {
deadbeefa601f5c2016-06-06 14:27:39 -07001121 new_sender->internal()->set_stream_id(streams[0]->label());
deadbeefe1f9d832016-01-14 15:35:42 -08001122 }
Steve Anton4171afb2017-11-20 10:20:22 -08001123 const RtpSenderInfo* sender_info =
1124 FindSenderInfo(local_audio_sender_infos_,
1125 new_sender->internal()->stream_id(), track->id());
1126 if (sender_info) {
1127 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -08001128 }
1129 } else if (track->kind() == MediaStreamTrackInterface::kVideoKind) {
deadbeefa601f5c2016-06-06 14:27:39 -07001130 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
deadbeefe1f9d832016-01-14 15:35:42 -08001131 signaling_thread(),
1132 new VideoRtpSender(static_cast<VideoTrackInterface*>(track),
Steve Anton75737c02017-11-06 10:37:17 -08001133 video_channel()));
Steve Anton4171afb2017-11-20 10:20:22 -08001134 GetVideoTransceiver()->internal()->AddSender(new_sender);
deadbeefe1f9d832016-01-14 15:35:42 -08001135 if (!streams.empty()) {
deadbeefa601f5c2016-06-06 14:27:39 -07001136 new_sender->internal()->set_stream_id(streams[0]->label());
deadbeefe1f9d832016-01-14 15:35:42 -08001137 }
Steve Anton4171afb2017-11-20 10:20:22 -08001138 const RtpSenderInfo* sender_info =
1139 FindSenderInfo(local_video_sender_infos_,
1140 new_sender->internal()->stream_id(), track->id());
1141 if (sender_info) {
1142 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -08001143 }
1144 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001145 RTC_LOG(LS_ERROR) << "CreateSender called with invalid kind: "
1146 << track->kind();
deadbeefe1f9d832016-01-14 15:35:42 -08001147 return rtc::scoped_refptr<RtpSenderInterface>();
1148 }
1149
deadbeefe1f9d832016-01-14 15:35:42 -08001150 observer_->OnRenegotiationNeeded();
1151 return new_sender;
1152}
1153
1154bool PeerConnection::RemoveTrack(RtpSenderInterface* sender) {
1155 TRACE_EVENT0("webrtc", "PeerConnection::RemoveTrack");
1156 if (IsClosed()) {
1157 return false;
1158 }
1159
Steve Anton4171afb2017-11-20 10:20:22 -08001160 bool removed;
1161 if (sender->media_type() == cricket::MEDIA_TYPE_AUDIO) {
1162 removed = GetAudioTransceiver()->internal()->RemoveSender(sender);
1163 } else {
1164 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, sender->media_type());
1165 removed = GetVideoTransceiver()->internal()->RemoveSender(sender);
1166 }
1167 if (!removed) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001168 RTC_LOG(LS_ERROR) << "Couldn't find sender " << sender->id()
1169 << " to remove.";
deadbeefe1f9d832016-01-14 15:35:42 -08001170 return false;
1171 }
deadbeefe1f9d832016-01-14 15:35:42 -08001172
1173 observer_->OnRenegotiationNeeded();
1174 return true;
1175}
1176
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001177rtc::scoped_refptr<DtmfSenderInterface> PeerConnection::CreateDtmfSender(
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001178 AudioTrackInterface* track) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001179 TRACE_EVENT0("webrtc", "PeerConnection::CreateDtmfSender");
zhihuang29ff8442016-07-27 11:07:25 -07001180 if (IsClosed()) {
1181 return nullptr;
1182 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001183 if (!track) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001184 RTC_LOG(LS_ERROR) << "CreateDtmfSender - track is NULL.";
deadbeef20cb0c12017-02-01 20:27:00 -08001185 return nullptr;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001186 }
Steve Anton4171afb2017-11-20 10:20:22 -08001187 auto track_sender = FindSenderForTrack(track);
1188 if (!track_sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001189 RTC_LOG(LS_ERROR) << "CreateDtmfSender called with a non-added track.";
deadbeef20cb0c12017-02-01 20:27:00 -08001190 return nullptr;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001191 }
1192
Steve Anton4171afb2017-11-20 10:20:22 -08001193 return track_sender->GetDtmfSender();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001194}
1195
deadbeeffac06552015-11-25 11:26:01 -08001196rtc::scoped_refptr<RtpSenderInterface> PeerConnection::CreateSender(
deadbeefbd7d8f72015-12-18 16:58:44 -08001197 const std::string& kind,
1198 const std::string& stream_id) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001199 TRACE_EVENT0("webrtc", "PeerConnection::CreateSender");
zhihuang29ff8442016-07-27 11:07:25 -07001200 if (IsClosed()) {
1201 return nullptr;
1202 }
Steve Anton4171afb2017-11-20 10:20:22 -08001203
1204 // TODO(steveanton): Move construction of the RtpSenders to RtpTransceiver.
deadbeefa601f5c2016-06-06 14:27:39 -07001205 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender;
deadbeeffac06552015-11-25 11:26:01 -08001206 if (kind == MediaStreamTrackInterface::kAudioKind) {
deadbeefa601f5c2016-06-06 14:27:39 -07001207 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton75737c02017-11-06 10:37:17 -08001208 signaling_thread(), new AudioRtpSender(voice_channel(), stats_.get()));
Steve Anton4171afb2017-11-20 10:20:22 -08001209 GetAudioTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 11:26:01 -08001210 } else if (kind == MediaStreamTrackInterface::kVideoKind) {
deadbeefa601f5c2016-06-06 14:27:39 -07001211 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton75737c02017-11-06 10:37:17 -08001212 signaling_thread(), new VideoRtpSender(video_channel()));
Steve Anton4171afb2017-11-20 10:20:22 -08001213 GetVideoTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 11:26:01 -08001214 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001215 RTC_LOG(LS_ERROR) << "CreateSender called with invalid kind: " << kind;
Steve Anton4171afb2017-11-20 10:20:22 -08001216 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08001217 }
Steve Anton4171afb2017-11-20 10:20:22 -08001218
deadbeefbd7d8f72015-12-18 16:58:44 -08001219 if (!stream_id.empty()) {
deadbeefa601f5c2016-06-06 14:27:39 -07001220 new_sender->internal()->set_stream_id(stream_id);
deadbeefbd7d8f72015-12-18 16:58:44 -08001221 }
Steve Anton4171afb2017-11-20 10:20:22 -08001222
deadbeefe1f9d832016-01-14 15:35:42 -08001223 return new_sender;
deadbeeffac06552015-11-25 11:26:01 -08001224}
1225
deadbeef70ab1a12015-09-28 16:53:55 -07001226std::vector<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::GetSenders()
1227 const {
deadbeefa601f5c2016-06-06 14:27:39 -07001228 std::vector<rtc::scoped_refptr<RtpSenderInterface>> ret;
Steve Anton4171afb2017-11-20 10:20:22 -08001229 for (auto sender : GetSendersInternal()) {
1230 ret.push_back(sender);
deadbeefa601f5c2016-06-06 14:27:39 -07001231 }
1232 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -07001233}
1234
Steve Anton4171afb2017-11-20 10:20:22 -08001235std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1236PeerConnection::GetSendersInternal() const {
1237 std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1238 all_senders;
1239 for (auto transceiver : transceivers_) {
1240 auto senders = transceiver->internal()->senders();
1241 all_senders.insert(all_senders.end(), senders.begin(), senders.end());
1242 }
1243 return all_senders;
1244}
1245
deadbeef70ab1a12015-09-28 16:53:55 -07001246std::vector<rtc::scoped_refptr<RtpReceiverInterface>>
1247PeerConnection::GetReceivers() const {
deadbeefa601f5c2016-06-06 14:27:39 -07001248 std::vector<rtc::scoped_refptr<RtpReceiverInterface>> ret;
Steve Anton4171afb2017-11-20 10:20:22 -08001249 for (const auto& receiver : GetReceiversInternal()) {
1250 ret.push_back(receiver);
deadbeefa601f5c2016-06-06 14:27:39 -07001251 }
1252 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -07001253}
1254
Steve Anton4171afb2017-11-20 10:20:22 -08001255std::vector<
1256 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1257PeerConnection::GetReceiversInternal() const {
1258 std::vector<
1259 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1260 all_receivers;
1261 for (auto transceiver : transceivers_) {
1262 auto receivers = transceiver->internal()->receivers();
1263 all_receivers.insert(all_receivers.end(), receivers.begin(),
1264 receivers.end());
1265 }
1266 return all_receivers;
1267}
1268
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001269bool PeerConnection::GetStats(StatsObserver* observer,
wu@webrtc.orgb9a088b2014-02-13 23:18:49 +00001270 MediaStreamTrackInterface* track,
1271 StatsOutputLevel level) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001272 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
deadbeef0a6c4ca2015-10-06 11:38:28 -07001273 RTC_DCHECK(signaling_thread()->IsCurrent());
nisse7ce109a2017-01-31 00:57:56 -08001274 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001275 RTC_LOG(LS_ERROR) << "GetStats - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001276 return false;
1277 }
1278
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001279 stats_->UpdateStats(level);
zhihuange9e94c32016-11-04 11:38:15 -07001280 // The StatsCollector is used to tell if a track is valid because it may
1281 // remember tracks that the PeerConnection previously removed.
1282 if (track && !stats_->IsValidTrack(track->id())) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001283 RTC_LOG(LS_WARNING) << "GetStats is called with an invalid track: "
1284 << track->id();
zhihuange9e94c32016-11-04 11:38:15 -07001285 return false;
1286 }
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001287 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_GETSTATS,
tommi@webrtc.org5b06b062014-08-15 08:38:30 +00001288 new GetStatsMsg(observer, track));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001289 return true;
1290}
1291
hbos74e1a4f2016-09-15 23:33:01 -07001292void PeerConnection::GetStats(RTCStatsCollectorCallback* callback) {
1293 RTC_DCHECK(stats_collector_);
1294 stats_collector_->GetStatsReport(callback);
1295}
1296
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001297PeerConnectionInterface::SignalingState PeerConnection::signaling_state() {
1298 return signaling_state_;
1299}
1300
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001301PeerConnectionInterface::IceConnectionState
1302PeerConnection::ice_connection_state() {
1303 return ice_connection_state_;
1304}
1305
1306PeerConnectionInterface::IceGatheringState
1307PeerConnection::ice_gathering_state() {
1308 return ice_gathering_state_;
1309}
1310
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001311rtc::scoped_refptr<DataChannelInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001312PeerConnection::CreateDataChannel(
1313 const std::string& label,
1314 const DataChannelInit* config) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001315 TRACE_EVENT0("webrtc", "PeerConnection::CreateDataChannel");
zhihuang9763d562016-08-05 11:14:50 -07001316
deadbeefab9b2d12015-10-14 11:33:11 -07001317 bool first_datachannel = !HasDataChannels();
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001318
kwibergd1fe2812016-04-27 06:47:29 -07001319 std::unique_ptr<InternalDataChannelInit> internal_config;
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00001320 if (config) {
1321 internal_config.reset(new InternalDataChannelInit(*config));
1322 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001323 rtc::scoped_refptr<DataChannelInterface> channel(
deadbeefab9b2d12015-10-14 11:33:11 -07001324 InternalCreateDataChannel(label, internal_config.get()));
1325 if (!channel.get()) {
1326 return nullptr;
1327 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001328
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001329 // Trigger the onRenegotiationNeeded event for every new RTP DataChannel, or
1330 // the first SCTP DataChannel.
Steve Anton75737c02017-11-06 10:37:17 -08001331 if (data_channel_type() == cricket::DCT_RTP || first_datachannel) {
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001332 observer_->OnRenegotiationNeeded();
1333 }
wu@webrtc.org91053e72013-08-10 07:18:04 +00001334
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001335 return DataChannelProxy::Create(signaling_thread(), channel.get());
1336}
1337
1338void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
1339 const MediaConstraintsInterface* constraints) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001340 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
Steve Anton8d3444d2017-10-20 15:30:51 -07001341
zhihuang1c378ed2017-08-17 14:10:50 -07001342 PeerConnectionInterface::RTCOfferAnswerOptions offer_answer_options;
1343 // Always create an offer even if |ConvertConstraintsToOfferAnswerOptions|
1344 // returns false for now. Because |ConvertConstraintsToOfferAnswerOptions|
1345 // compares the mandatory fields parsed with the mandatory fields added in the
1346 // |constraints| and some downstream applications might create offers with
1347 // mandatory fields which would not be parsed in the helper method. For
1348 // example, in Chromium/remoting, |kEnableDtlsSrtp| is added to the
1349 // |constraints| as a mandatory field but it is not parsed.
1350 ConvertConstraintsToOfferAnswerOptions(constraints, &offer_answer_options);
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001351
zhihuang1c378ed2017-08-17 14:10:50 -07001352 CreateOffer(observer, offer_answer_options);
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001353}
1354
1355void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
1356 const RTCOfferAnswerOptions& options) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001357 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
Steve Anton8d3444d2017-10-20 15:30:51 -07001358
nisse7ce109a2017-01-31 00:57:56 -08001359 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001360 RTC_LOG(LS_ERROR) << "CreateOffer - observer is NULL.";
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001361 return;
1362 }
deadbeefab9b2d12015-10-14 11:33:11 -07001363
Steve Anton8d3444d2017-10-20 15:30:51 -07001364 if (IsClosed()) {
1365 std::string error = "CreateOffer called when PeerConnection is closed.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001366 RTC_LOG(LS_ERROR) << error;
Steve Anton8d3444d2017-10-20 15:30:51 -07001367 PostCreateSessionDescriptionFailure(observer, error);
1368 return;
1369 }
1370
zhihuang1c378ed2017-08-17 14:10:50 -07001371 if (!ValidateOfferAnswerOptions(options)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001372 std::string error = "CreateOffer called with invalid options.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001373 RTC_LOG(LS_ERROR) << error;
deadbeefab9b2d12015-10-14 11:33:11 -07001374 PostCreateSessionDescriptionFailure(observer, error);
1375 return;
1376 }
1377
zhihuang1c378ed2017-08-17 14:10:50 -07001378 cricket::MediaSessionOptions session_options;
1379 GetOptionsForOffer(options, &session_options);
Steve Antond25da372017-11-06 14:50:29 -08001380 webrtc_session_desc_factory_->CreateOffer(observer, options, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001381}
1382
1383void PeerConnection::CreateAnswer(
1384 CreateSessionDescriptionObserver* observer,
1385 const MediaConstraintsInterface* constraints) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001386 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
Steve Anton8d3444d2017-10-20 15:30:51 -07001387
nisse7ce109a2017-01-31 00:57:56 -08001388 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001389 RTC_LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001390 return;
1391 }
deadbeefab9b2d12015-10-14 11:33:11 -07001392
zhihuang1c378ed2017-08-17 14:10:50 -07001393 PeerConnectionInterface::RTCOfferAnswerOptions offer_answer_options;
1394 if (!ConvertConstraintsToOfferAnswerOptions(constraints,
1395 &offer_answer_options)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001396 std::string error = "CreateAnswer called with invalid constraints.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001397 RTC_LOG(LS_ERROR) << error;
deadbeefab9b2d12015-10-14 11:33:11 -07001398 PostCreateSessionDescriptionFailure(observer, error);
1399 return;
1400 }
1401
Steve Anton8d3444d2017-10-20 15:30:51 -07001402 CreateAnswer(observer, offer_answer_options);
htaa2a49d92016-03-04 02:51:39 -08001403}
1404
1405void PeerConnection::CreateAnswer(CreateSessionDescriptionObserver* observer,
1406 const RTCOfferAnswerOptions& options) {
1407 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
nisse7ce109a2017-01-31 00:57:56 -08001408 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001409 RTC_LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
htaa2a49d92016-03-04 02:51:39 -08001410 return;
1411 }
1412
Steve Anton8d3444d2017-10-20 15:30:51 -07001413 if (IsClosed()) {
1414 std::string error = "CreateAnswer called when PeerConnection is closed.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001415 RTC_LOG(LS_ERROR) << error;
Steve Anton8d3444d2017-10-20 15:30:51 -07001416 PostCreateSessionDescriptionFailure(observer, error);
1417 return;
1418 }
1419
Steve Anton75737c02017-11-06 10:37:17 -08001420 if (remote_description() &&
1421 remote_description()->type() != SessionDescriptionInterface::kOffer) {
Steve Anton8d3444d2017-10-20 15:30:51 -07001422 std::string error = "CreateAnswer called without remote offer.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001423 RTC_LOG(LS_ERROR) << error;
Steve Anton8d3444d2017-10-20 15:30:51 -07001424 PostCreateSessionDescriptionFailure(observer, error);
1425 return;
1426 }
1427
htaa2a49d92016-03-04 02:51:39 -08001428 cricket::MediaSessionOptions session_options;
zhihuang1c378ed2017-08-17 14:10:50 -07001429 GetOptionsForAnswer(options, &session_options);
htaa2a49d92016-03-04 02:51:39 -08001430
Steve Antond25da372017-11-06 14:50:29 -08001431 webrtc_session_desc_factory_->CreateAnswer(observer, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001432}
1433
1434void PeerConnection::SetLocalDescription(
1435 SetSessionDescriptionObserver* observer,
1436 SessionDescriptionInterface* desc) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001437 TRACE_EVENT0("webrtc", "PeerConnection::SetLocalDescription");
nisse7ce109a2017-01-31 00:57:56 -08001438 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001439 RTC_LOG(LS_ERROR) << "SetLocalDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001440 return;
1441 }
1442 if (!desc) {
1443 PostSetSessionDescriptionFailure(observer, "SessionDescription is NULL.");
1444 return;
1445 }
Steve Anton8d3444d2017-10-20 15:30:51 -07001446
1447 // Takes the ownership of |desc| regardless of the result.
1448 std::unique_ptr<SessionDescriptionInterface> desc_temp(desc);
1449
1450 if (IsClosed()) {
Henrik Boströmfdb92012017-11-09 19:55:44 +01001451 std::string error = "Failed to set local " + desc_temp->type() +
Steve Anton8d3444d2017-10-20 15:30:51 -07001452 " sdp: Called in wrong state: STATE_CLOSED";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001453 RTC_LOG(LS_ERROR) << error;
Steve Anton8d3444d2017-10-20 15:30:51 -07001454 PostSetSessionDescriptionFailure(observer, error);
1455 return;
1456 }
1457
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001458 // Update stats here so that we have the most recent stats for tracks and
1459 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001460 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001461 std::string error;
Henrik Boströmfdb92012017-11-09 19:55:44 +01001462 // Takes the ownership of |desc_temp|. On success, local_description() is
1463 // updated to reflect the description that was passed in.
Steve Anton75737c02017-11-06 10:37:17 -08001464 if (!SetLocalDescription(std::move(desc_temp), &error)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001465 PostSetSessionDescriptionFailure(observer, error);
1466 return;
1467 }
Henrik Boströmfdb92012017-11-09 19:55:44 +01001468 RTC_DCHECK(local_description());
deadbeefab9b2d12015-10-14 11:33:11 -07001469
1470 // If setting the description decided our SSL role, allocate any necessary
1471 // SCTP sids.
1472 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08001473 if (data_channel_type() == cricket::DCT_SCTP && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001474 AllocateSctpSids(role);
1475 }
1476
1477 // Update state and SSRC of local MediaStreams and DataChannels based on the
1478 // local session description.
1479 const cricket::ContentInfo* audio_content =
Henrik Boströmfdb92012017-11-09 19:55:44 +01001480 GetFirstAudioContent(local_description()->description());
deadbeefab9b2d12015-10-14 11:33:11 -07001481 if (audio_content) {
deadbeeffaac4972015-11-12 15:33:07 -08001482 if (audio_content->rejected) {
Steve Anton4171afb2017-11-20 10:20:22 -08001483 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
deadbeeffaac4972015-11-12 15:33:07 -08001484 } else {
1485 const cricket::AudioContentDescription* audio_desc =
1486 static_cast<const cricket::AudioContentDescription*>(
1487 audio_content->description);
Steve Anton4171afb2017-11-20 10:20:22 -08001488 UpdateLocalSenders(audio_desc->streams(), audio_desc->type());
deadbeeffaac4972015-11-12 15:33:07 -08001489 }
deadbeefab9b2d12015-10-14 11:33:11 -07001490 }
1491
1492 const cricket::ContentInfo* video_content =
Henrik Boströmfdb92012017-11-09 19:55:44 +01001493 GetFirstVideoContent(local_description()->description());
deadbeefab9b2d12015-10-14 11:33:11 -07001494 if (video_content) {
deadbeeffaac4972015-11-12 15:33:07 -08001495 if (video_content->rejected) {
Steve Anton4171afb2017-11-20 10:20:22 -08001496 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
deadbeeffaac4972015-11-12 15:33:07 -08001497 } else {
1498 const cricket::VideoContentDescription* video_desc =
1499 static_cast<const cricket::VideoContentDescription*>(
1500 video_content->description);
Steve Anton4171afb2017-11-20 10:20:22 -08001501 UpdateLocalSenders(video_desc->streams(), video_desc->type());
deadbeeffaac4972015-11-12 15:33:07 -08001502 }
deadbeefab9b2d12015-10-14 11:33:11 -07001503 }
1504
1505 const cricket::ContentInfo* data_content =
Henrik Boströmfdb92012017-11-09 19:55:44 +01001506 GetFirstDataContent(local_description()->description());
deadbeefab9b2d12015-10-14 11:33:11 -07001507 if (data_content) {
1508 const cricket::DataContentDescription* data_desc =
1509 static_cast<const cricket::DataContentDescription*>(
1510 data_content->description);
1511 if (rtc::starts_with(data_desc->protocol().data(),
1512 cricket::kMediaProtocolRtpPrefix)) {
1513 UpdateLocalRtpDataChannels(data_desc->streams());
1514 }
1515 }
1516
1517 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001518 signaling_thread()->Post(RTC_FROM_HERE, this,
1519 MSG_SET_SESSIONDESCRIPTION_SUCCESS, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07001520
deadbeef42a42632017-03-10 15:18:00 -08001521 // According to JSEP, after setLocalDescription, changing the candidate pool
1522 // size is not allowed, and changing the set of ICE servers will not result
1523 // in new candidates being gathered.
1524 port_allocator_->FreezeCandidatePool();
1525
deadbeefcbecd352015-09-23 11:50:27 -07001526 // MaybeStartGathering needs to be called after posting
1527 // MSG_SET_SESSIONDESCRIPTION_SUCCESS, so that we don't signal any candidates
1528 // before signaling that SetLocalDescription completed.
Steve Antond25da372017-11-06 14:50:29 -08001529 transport_controller_->MaybeStartGathering();
deadbeef42a42632017-03-10 15:18:00 -08001530
Henrik Boströmfdb92012017-11-09 19:55:44 +01001531 if (local_description()->type() == SessionDescriptionInterface::kAnswer) {
deadbeef42a42632017-03-10 15:18:00 -08001532 // TODO(deadbeef): We already had to hop to the network thread for
1533 // MaybeStartGathering...
1534 network_thread()->Invoke<void>(
1535 RTC_FROM_HERE,
1536 rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
1537 port_allocator_.get()));
1538 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001539}
1540
1541void PeerConnection::SetRemoteDescription(
1542 SetSessionDescriptionObserver* observer,
1543 SessionDescriptionInterface* desc) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001544 TRACE_EVENT0("webrtc", "PeerConnection::SetRemoteDescription");
nisse7ce109a2017-01-31 00:57:56 -08001545 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001546 RTC_LOG(LS_ERROR) << "SetRemoteDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001547 return;
1548 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001549 if (!desc) {
1550 PostSetSessionDescriptionFailure(observer, "SessionDescription is NULL.");
1551 return;
1552 }
Steve Anton8d3444d2017-10-20 15:30:51 -07001553
1554 // Takes the ownership of |desc| regardless of the result.
1555 std::unique_ptr<SessionDescriptionInterface> desc_temp(desc);
1556
1557 if (IsClosed()) {
Henrik Boströmfdb92012017-11-09 19:55:44 +01001558 std::string error = "Failed to set remote " + desc_temp->type() +
Steve Anton8d3444d2017-10-20 15:30:51 -07001559 " sdp: Called in wrong state: STATE_CLOSED";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001560 RTC_LOG(LS_ERROR) << error;
Steve Anton8d3444d2017-10-20 15:30:51 -07001561 PostSetSessionDescriptionFailure(observer, error);
1562 return;
1563 }
1564
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001565 // Update stats here so that we have the most recent stats for tracks and
1566 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001567 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001568 std::string error;
Henrik Boströmfdb92012017-11-09 19:55:44 +01001569 // Takes the ownership of |desc_temp|. On success, remote_description() is
1570 // updated to reflect the description that was passed in.
Steve Anton75737c02017-11-06 10:37:17 -08001571 if (!SetRemoteDescription(std::move(desc_temp), &error)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001572 PostSetSessionDescriptionFailure(observer, error);
1573 return;
1574 }
Henrik Boströmfdb92012017-11-09 19:55:44 +01001575 RTC_DCHECK(remote_description());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001576
deadbeefab9b2d12015-10-14 11:33:11 -07001577 // If setting the description decided our SSL role, allocate any necessary
1578 // SCTP sids.
1579 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08001580 if (data_channel_type() == cricket::DCT_SCTP && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001581 AllocateSctpSids(role);
1582 }
1583
Henrik Boströmfdb92012017-11-09 19:55:44 +01001584 const cricket::ContentInfo* audio_content =
1585 GetFirstAudioContent(remote_description()->description());
1586 const cricket::ContentInfo* video_content =
1587 GetFirstVideoContent(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08001588 const cricket::AudioContentDescription* audio_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01001589 GetFirstAudioContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08001590 const cricket::VideoContentDescription* video_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01001591 GetFirstVideoContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08001592 const cricket::DataContentDescription* data_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01001593 GetFirstDataContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08001594
1595 // Check if the descriptions include streams, just in case the peer supports
1596 // MSID, but doesn't indicate so with "a=msid-semantic".
Henrik Boströmfdb92012017-11-09 19:55:44 +01001597 if (remote_description()->description()->msid_supported() ||
deadbeefbda7e0b2015-12-08 17:13:40 -08001598 (audio_desc && !audio_desc->streams().empty()) ||
1599 (video_desc && !video_desc->streams().empty())) {
1600 remote_peer_supports_msid_ = true;
1601 }
deadbeefab9b2d12015-10-14 11:33:11 -07001602
1603 // We wait to signal new streams until we finish processing the description,
1604 // since only at that point will new streams have all their tracks.
1605 rtc::scoped_refptr<StreamCollection> new_streams(StreamCollection::Create());
1606
Steve Anton8d3444d2017-10-20 15:30:51 -07001607 // TODO(steveanton): When removing RTP senders/receivers in response to a
1608 // rejected media section, there is some cleanup logic that expects the voice/
1609 // video channel to still be set. But in this method the voice/video channel
Steve Anton75737c02017-11-06 10:37:17 -08001610 // would have been destroyed by the SetRemoteDescription caller above so the
Steve Anton4171afb2017-11-20 10:20:22 -08001611 // cleanup that relies on them fails to run. The RemoveSenders calls should be
Steve Anton75737c02017-11-06 10:37:17 -08001612 // moved to right before the DestroyChannel calls to fix this.
Steve Anton8d3444d2017-10-20 15:30:51 -07001613
deadbeefab9b2d12015-10-14 11:33:11 -07001614 // Find all audio rtp streams and create corresponding remote AudioTracks
1615 // and MediaStreams.
deadbeefab9b2d12015-10-14 11:33:11 -07001616 if (audio_content) {
deadbeeffaac4972015-11-12 15:33:07 -08001617 if (audio_content->rejected) {
Steve Anton4171afb2017-11-20 10:20:22 -08001618 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
deadbeeffaac4972015-11-12 15:33:07 -08001619 } else {
deadbeefbda7e0b2015-12-08 17:13:40 -08001620 bool default_audio_track_needed =
1621 !remote_peer_supports_msid_ &&
1622 MediaContentDirectionHasSend(audio_desc->direction());
Steve Anton4171afb2017-11-20 10:20:22 -08001623 UpdateRemoteSendersList(GetActiveStreams(audio_desc),
deadbeefbda7e0b2015-12-08 17:13:40 -08001624 default_audio_track_needed, audio_desc->type(),
deadbeeffaac4972015-11-12 15:33:07 -08001625 new_streams);
deadbeeffaac4972015-11-12 15:33:07 -08001626 }
deadbeefab9b2d12015-10-14 11:33:11 -07001627 }
1628
1629 // Find all video rtp streams and create corresponding remote VideoTracks
1630 // and MediaStreams.
deadbeefab9b2d12015-10-14 11:33:11 -07001631 if (video_content) {
deadbeeffaac4972015-11-12 15:33:07 -08001632 if (video_content->rejected) {
Steve Anton4171afb2017-11-20 10:20:22 -08001633 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
deadbeeffaac4972015-11-12 15:33:07 -08001634 } else {
deadbeefbda7e0b2015-12-08 17:13:40 -08001635 bool default_video_track_needed =
1636 !remote_peer_supports_msid_ &&
1637 MediaContentDirectionHasSend(video_desc->direction());
Steve Anton4171afb2017-11-20 10:20:22 -08001638 UpdateRemoteSendersList(GetActiveStreams(video_desc),
deadbeefbda7e0b2015-12-08 17:13:40 -08001639 default_video_track_needed, video_desc->type(),
deadbeeffaac4972015-11-12 15:33:07 -08001640 new_streams);
deadbeeffaac4972015-11-12 15:33:07 -08001641 }
deadbeefab9b2d12015-10-14 11:33:11 -07001642 }
1643
1644 // Update the DataChannels with the information from the remote peer.
deadbeefbda7e0b2015-12-08 17:13:40 -08001645 if (data_desc) {
1646 if (rtc::starts_with(data_desc->protocol().data(),
deadbeefab9b2d12015-10-14 11:33:11 -07001647 cricket::kMediaProtocolRtpPrefix)) {
deadbeefbda7e0b2015-12-08 17:13:40 -08001648 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
deadbeefab9b2d12015-10-14 11:33:11 -07001649 }
1650 }
1651
1652 // Iterate new_streams and notify the observer about new MediaStreams.
1653 for (size_t i = 0; i < new_streams->count(); ++i) {
1654 MediaStreamInterface* new_stream = new_streams->at(i);
1655 stats_->AddStream(new_stream);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07001656 observer_->OnAddStream(
1657 rtc::scoped_refptr<MediaStreamInterface>(new_stream));
deadbeefab9b2d12015-10-14 11:33:11 -07001658 }
1659
deadbeefbda7e0b2015-12-08 17:13:40 -08001660 UpdateEndedRemoteMediaStreams();
deadbeefab9b2d12015-10-14 11:33:11 -07001661
1662 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001663 signaling_thread()->Post(RTC_FROM_HERE, this,
1664 MSG_SET_SESSIONDESCRIPTION_SUCCESS, msg);
deadbeef42a42632017-03-10 15:18:00 -08001665
Henrik Boströmfdb92012017-11-09 19:55:44 +01001666 if (remote_description()->type() == SessionDescriptionInterface::kAnswer) {
deadbeef42a42632017-03-10 15:18:00 -08001667 // TODO(deadbeef): We already had to hop to the network thread for
1668 // MaybeStartGathering...
1669 network_thread()->Invoke<void>(
1670 RTC_FROM_HERE,
1671 rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
1672 port_allocator_.get()));
1673 }
deadbeeffc648b62015-10-13 16:42:33 -07001674}
1675
deadbeef46c73892016-11-16 19:42:04 -08001676PeerConnectionInterface::RTCConfiguration PeerConnection::GetConfiguration() {
1677 return configuration_;
1678}
1679
deadbeef293e9262017-01-11 12:28:30 -08001680bool PeerConnection::SetConfiguration(const RTCConfiguration& configuration,
1681 RTCError* error) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001682 TRACE_EVENT0("webrtc", "PeerConnection::SetConfiguration");
deadbeef6de92f92016-12-12 18:49:32 -08001683
Steve Anton75737c02017-11-06 10:37:17 -08001684 if (local_description() && configuration.ice_candidate_pool_size !=
1685 configuration_.ice_candidate_pool_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001686 RTC_LOG(LS_ERROR) << "Can't change candidate pool size after calling "
1687 "SetLocalDescription.";
deadbeef293e9262017-01-11 12:28:30 -08001688 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00001689 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07001690
deadbeef293e9262017-01-11 12:28:30 -08001691 // The simplest (and most future-compatible) way to tell if the config was
1692 // modified in an invalid way is to copy each property we do support
1693 // modifying, then use operator==. There are far more properties we don't
1694 // support modifying than those we do, and more could be added.
1695 RTCConfiguration modified_config = configuration_;
1696 modified_config.servers = configuration.servers;
1697 modified_config.type = configuration.type;
1698 modified_config.ice_candidate_pool_size =
1699 configuration.ice_candidate_pool_size;
1700 modified_config.prune_turn_ports = configuration.prune_turn_ports;
skvladd1f5fda2017-02-03 16:54:05 -08001701 modified_config.ice_check_min_interval = configuration.ice_check_min_interval;
Jonas Orelandbdcee282017-10-10 14:01:40 +02001702 modified_config.turn_customizer = configuration.turn_customizer;
deadbeef293e9262017-01-11 12:28:30 -08001703 if (configuration != modified_config) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001704 RTC_LOG(LS_ERROR) << "Modifying the configuration in an unsupported way.";
deadbeef293e9262017-01-11 12:28:30 -08001705 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
1706 }
1707
Steve Anton038834f2017-07-14 15:59:59 -07001708 // Validate the modified configuration.
1709 RTCError validate_error = ValidateConfiguration(modified_config);
1710 if (!validate_error.ok()) {
1711 return SafeSetError(std::move(validate_error), error);
1712 }
1713
deadbeef293e9262017-01-11 12:28:30 -08001714 // Note that this isn't possible through chromium, since it's an unsigned
1715 // short in WebIDL.
1716 if (configuration.ice_candidate_pool_size < 0 ||
1717 configuration.ice_candidate_pool_size > UINT16_MAX) {
1718 return SafeSetError(RTCErrorType::INVALID_RANGE, error);
1719 }
1720
1721 // Parse ICE servers before hopping to network thread.
1722 cricket::ServerAddresses stun_servers;
1723 std::vector<cricket::RelayServerConfig> turn_servers;
1724 RTCErrorType parse_error =
1725 ParseIceServers(configuration.servers, &stun_servers, &turn_servers);
1726 if (parse_error != RTCErrorType::NONE) {
1727 return SafeSetError(parse_error, error);
1728 }
1729
1730 // In theory this shouldn't fail.
1731 if (!network_thread()->Invoke<bool>(
1732 RTC_FROM_HERE,
1733 rtc::Bind(&PeerConnection::ReconfigurePortAllocator_n, this,
1734 stun_servers, turn_servers, modified_config.type,
1735 modified_config.ice_candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02001736 modified_config.prune_turn_ports,
1737 modified_config.turn_customizer))) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001738 RTC_LOG(LS_ERROR) << "Failed to apply configuration to PortAllocator.";
deadbeef293e9262017-01-11 12:28:30 -08001739 return SafeSetError(RTCErrorType::INTERNAL_ERROR, error);
1740 }
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07001741
deadbeefd1a38b52016-12-10 13:15:33 -08001742 // As described in JSEP, calling setConfiguration with new ICE servers or
1743 // candidate policy must set a "needs-ice-restart" bit so that the next offer
1744 // triggers an ICE restart which will pick up the changes.
deadbeef293e9262017-01-11 12:28:30 -08001745 if (modified_config.servers != configuration_.servers ||
1746 modified_config.type != configuration_.type ||
1747 modified_config.prune_turn_ports != configuration_.prune_turn_ports) {
Steve Antond25da372017-11-06 14:50:29 -08001748 transport_controller_->SetNeedsIceRestartFlag();
deadbeefd1a38b52016-12-10 13:15:33 -08001749 }
skvladd1f5fda2017-02-03 16:54:05 -08001750
1751 if (modified_config.ice_check_min_interval !=
1752 configuration_.ice_check_min_interval) {
Steve Antond25da372017-11-06 14:50:29 -08001753 transport_controller_->SetIceConfig(ParseIceConfig(modified_config));
skvladd1f5fda2017-02-03 16:54:05 -08001754 }
1755
deadbeef293e9262017-01-11 12:28:30 -08001756 configuration_ = modified_config;
1757 return SafeSetError(RTCErrorType::NONE, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00001758}
1759
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001760bool PeerConnection::AddIceCandidate(
1761 const IceCandidateInterface* ice_candidate) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001762 TRACE_EVENT0("webrtc", "PeerConnection::AddIceCandidate");
zhihuang29ff8442016-07-27 11:07:25 -07001763 if (IsClosed()) {
1764 return false;
1765 }
Steve Antond25da372017-11-06 14:50:29 -08001766
1767 if (!remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001768 RTC_LOG(LS_ERROR) << "ProcessIceMessage: ICE candidates can't be added "
1769 << "without any remote session description.";
Steve Antond25da372017-11-06 14:50:29 -08001770 return false;
1771 }
1772
1773 if (!ice_candidate) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001774 RTC_LOG(LS_ERROR) << "ProcessIceMessage: Candidate is NULL.";
Steve Antond25da372017-11-06 14:50:29 -08001775 return false;
1776 }
1777
1778 bool valid = false;
1779 bool ready = ReadyToUseRemoteCandidate(ice_candidate, nullptr, &valid);
1780 if (!valid) {
1781 return false;
1782 }
1783
1784 // Add this candidate to the remote session description.
1785 if (!mutable_remote_description()->AddCandidate(ice_candidate)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001786 RTC_LOG(LS_ERROR) << "ProcessIceMessage: Candidate cannot be used.";
Steve Antond25da372017-11-06 14:50:29 -08001787 return false;
1788 }
1789
1790 if (ready) {
1791 return UseCandidate(ice_candidate);
1792 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001793 RTC_LOG(LS_INFO) << "ProcessIceMessage: Not ready to use candidate.";
Steve Antond25da372017-11-06 14:50:29 -08001794 return true;
1795 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001796}
1797
Honghai Zhang7fb69db2016-03-14 11:59:18 -07001798bool PeerConnection::RemoveIceCandidates(
1799 const std::vector<cricket::Candidate>& candidates) {
1800 TRACE_EVENT0("webrtc", "PeerConnection::RemoveIceCandidates");
Steve Antond25da372017-11-06 14:50:29 -08001801 if (!remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001802 RTC_LOG(LS_ERROR) << "RemoveRemoteIceCandidates: ICE candidates can't be "
1803 << "removed without any remote session description.";
Steve Antond25da372017-11-06 14:50:29 -08001804 return false;
1805 }
1806
1807 if (candidates.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001808 RTC_LOG(LS_ERROR) << "RemoveRemoteIceCandidates: candidates are empty.";
Steve Antond25da372017-11-06 14:50:29 -08001809 return false;
1810 }
1811
1812 size_t number_removed =
1813 mutable_remote_description()->RemoveCandidates(candidates);
1814 if (number_removed != candidates.size()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001815 RTC_LOG(LS_ERROR)
1816 << "RemoveRemoteIceCandidates: Failed to remove candidates. "
1817 << "Requested " << candidates.size() << " but only " << number_removed
1818 << " are removed.";
Steve Antond25da372017-11-06 14:50:29 -08001819 }
1820
1821 // Remove the candidates from the transport controller.
1822 std::string error;
1823 bool res = transport_controller_->RemoveRemoteCandidates(candidates, &error);
1824 if (!res && !error.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001825 RTC_LOG(LS_ERROR) << "Error when removing remote candidates: " << error;
Steve Antond25da372017-11-06 14:50:29 -08001826 }
1827 return true;
Honghai Zhang7fb69db2016-03-14 11:59:18 -07001828}
1829
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00001830void PeerConnection::RegisterUMAObserver(UMAObserver* observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001831 TRACE_EVENT0("webrtc", "PeerConnection::RegisterUmaObserver");
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00001832 uma_observer_ = observer;
guoweis@webrtc.org7169afd2014-12-04 17:59:29 +00001833
Steve Anton75737c02017-11-06 10:37:17 -08001834 if (transport_controller()) {
1835 transport_controller()->SetMetricsObserver(uma_observer_);
guoweis@webrtc.org7169afd2014-12-04 17:59:29 +00001836 }
1837
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00001838 // Send information about IPv4/IPv6 status.
deadbeef293e9262017-01-11 12:28:30 -08001839 if (uma_observer_) {
Honghai Zhangd93f50c2016-10-05 11:47:22 -07001840 port_allocator_->SetMetricsObserver(uma_observer_);
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00001841 if (port_allocator_->flags() & cricket::PORTALLOCATOR_ENABLE_IPV6) {
Guo-wei Shiehdfbe6792015-09-03 17:12:07 -07001842 uma_observer_->IncrementEnumCounter(
1843 kEnumCounterAddressFamily, kPeerConnection_IPv6,
1844 kPeerConnectionAddressFamilyCounter_Max);
mallinath@webrtc.orgb445f262014-05-23 22:19:37 +00001845 } else {
Guo-wei Shiehdfbe6792015-09-03 17:12:07 -07001846 uma_observer_->IncrementEnumCounter(
1847 kEnumCounterAddressFamily, kPeerConnection_IPv4,
1848 kPeerConnectionAddressFamilyCounter_Max);
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00001849 }
1850 }
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00001851}
1852
zstein4b979802017-06-02 14:37:37 -07001853RTCError PeerConnection::SetBitrate(const BitrateParameters& bitrate) {
Steve Anton978b8762017-09-29 12:15:02 -07001854 if (!worker_thread()->IsCurrent()) {
1855 return worker_thread()->Invoke<RTCError>(
zstein4b979802017-06-02 14:37:37 -07001856 RTC_FROM_HERE, rtc::Bind(&PeerConnection::SetBitrate, this, bitrate));
1857 }
1858
1859 const bool has_min = static_cast<bool>(bitrate.min_bitrate_bps);
1860 const bool has_current = static_cast<bool>(bitrate.current_bitrate_bps);
1861 const bool has_max = static_cast<bool>(bitrate.max_bitrate_bps);
1862 if (has_min && *bitrate.min_bitrate_bps < 0) {
1863 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1864 "min_bitrate_bps <= 0");
1865 }
1866 if (has_current) {
1867 if (has_min && *bitrate.current_bitrate_bps < *bitrate.min_bitrate_bps) {
1868 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1869 "current_bitrate_bps < min_bitrate_bps");
1870 } else if (*bitrate.current_bitrate_bps < 0) {
1871 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1872 "curent_bitrate_bps < 0");
1873 }
1874 }
1875 if (has_max) {
1876 if (has_current &&
1877 *bitrate.max_bitrate_bps < *bitrate.current_bitrate_bps) {
1878 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1879 "max_bitrate_bps < current_bitrate_bps");
1880 } else if (has_min && *bitrate.max_bitrate_bps < *bitrate.min_bitrate_bps) {
1881 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1882 "max_bitrate_bps < min_bitrate_bps");
1883 } else if (*bitrate.max_bitrate_bps < 0) {
1884 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1885 "max_bitrate_bps < 0");
1886 }
1887 }
1888
1889 Call::Config::BitrateConfigMask mask;
1890 mask.min_bitrate_bps = bitrate.min_bitrate_bps;
1891 mask.start_bitrate_bps = bitrate.current_bitrate_bps;
1892 mask.max_bitrate_bps = bitrate.max_bitrate_bps;
1893
1894 RTC_DCHECK(call_.get());
1895 call_->SetBitrateConfigMask(mask);
1896
1897 return RTCError::OK();
1898}
1899
Alex Narest78609d52017-10-20 10:37:47 +02001900void PeerConnection::SetBitrateAllocationStrategy(
1901 std::unique_ptr<rtc::BitrateAllocationStrategy>
1902 bitrate_allocation_strategy) {
1903 rtc::Thread* worker_thread = factory_->worker_thread();
1904 if (!worker_thread->IsCurrent()) {
1905 rtc::BitrateAllocationStrategy* strategy_raw =
1906 bitrate_allocation_strategy.release();
1907 auto functor = [this, strategy_raw]() {
1908 call_->SetBitrateAllocationStrategy(
1909 rtc::WrapUnique<rtc::BitrateAllocationStrategy>(strategy_raw));
1910 };
1911 worker_thread->Invoke<void>(RTC_FROM_HERE, functor);
1912 return;
1913 }
1914 RTC_DCHECK(call_.get());
1915 call_->SetBitrateAllocationStrategy(std::move(bitrate_allocation_strategy));
1916}
1917
henrika5f6bf242017-11-01 11:06:56 +01001918void PeerConnection::SetAudioPlayout(bool playout) {
1919 if (!worker_thread()->IsCurrent()) {
1920 worker_thread()->Invoke<void>(
1921 RTC_FROM_HERE,
1922 rtc::Bind(&PeerConnection::SetAudioPlayout, this, playout));
1923 return;
1924 }
1925 auto audio_state =
1926 factory_->channel_manager()->media_engine()->GetAudioState();
1927 audio_state->SetPlayout(playout);
1928}
1929
1930void PeerConnection::SetAudioRecording(bool recording) {
1931 if (!worker_thread()->IsCurrent()) {
1932 worker_thread()->Invoke<void>(
1933 RTC_FROM_HERE,
1934 rtc::Bind(&PeerConnection::SetAudioRecording, this, recording));
1935 return;
1936 }
1937 auto audio_state =
1938 factory_->channel_manager()->media_engine()->GetAudioState();
1939 audio_state->SetRecording(recording);
1940}
1941
Steve Anton8c0f7a72017-10-03 10:03:10 -07001942std::unique_ptr<rtc::SSLCertificate>
1943PeerConnection::GetRemoteAudioSSLCertificate() {
Steve Anton75737c02017-11-06 10:37:17 -08001944 if (!voice_channel()) {
Steve Anton8c0f7a72017-10-03 10:03:10 -07001945 return nullptr;
1946 }
Steve Anton75737c02017-11-06 10:37:17 -08001947 return GetRemoteSSLCertificate(voice_channel()->transport_name());
Steve Anton8c0f7a72017-10-03 10:03:10 -07001948}
1949
ivoc14d5dbe2016-07-04 07:06:55 -07001950bool PeerConnection::StartRtcEventLog(rtc::PlatformFile file,
1951 int64_t max_size_bytes) {
Elad Alon99c3fe52017-10-13 16:29:40 +02001952 // TODO(eladalon): It would be better to not allow negative values into PC.
1953 const size_t max_size = (max_size_bytes < 0)
1954 ? RtcEventLog::kUnlimitedOutput
1955 : rtc::saturated_cast<size_t>(max_size_bytes);
1956 return StartRtcEventLog(
1957 rtc::MakeUnique<RtcEventLogOutputFile>(file, max_size));
1958}
1959
1960bool PeerConnection::StartRtcEventLog(
1961 std::unique_ptr<RtcEventLogOutput> output) {
Karl Wibergd6b48192017-10-16 23:01:06 +02001962 // TODO(eladalon): In C++14, this can be done with a lambda.
1963 struct Functor {
Zhi Huang33c5c7f2017-11-17 20:59:29 +00001964 bool operator()() { return pc->StartRtcEventLog_w(std::move(output)); }
Karl Wibergd6b48192017-10-16 23:01:06 +02001965 PeerConnection* const pc;
1966 std::unique_ptr<RtcEventLogOutput> output;
Elad Alon99c3fe52017-10-13 16:29:40 +02001967 };
Zhi Huang33c5c7f2017-11-17 20:59:29 +00001968 return worker_thread()->Invoke<bool>(RTC_FROM_HERE,
1969 Functor{this, std::move(output)});
ivoc14d5dbe2016-07-04 07:06:55 -07001970}
1971
1972void PeerConnection::StopRtcEventLog() {
Steve Anton978b8762017-09-29 12:15:02 -07001973 worker_thread()->Invoke<void>(
ivoc14d5dbe2016-07-04 07:06:55 -07001974 RTC_FROM_HERE, rtc::Bind(&PeerConnection::StopRtcEventLog_w, this));
1975}
1976
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001977const SessionDescriptionInterface* PeerConnection::local_description() const {
Steve Anton75737c02017-11-06 10:37:17 -08001978 return pending_local_description_ ? pending_local_description_.get()
1979 : current_local_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001980}
1981
1982const SessionDescriptionInterface* PeerConnection::remote_description() const {
Steve Anton75737c02017-11-06 10:37:17 -08001983 return pending_remote_description_ ? pending_remote_description_.get()
1984 : current_remote_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001985}
1986
deadbeeffe4a8a42016-12-20 17:56:17 -08001987const SessionDescriptionInterface* PeerConnection::current_local_description()
1988 const {
Steve Anton75737c02017-11-06 10:37:17 -08001989 return current_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08001990}
1991
1992const SessionDescriptionInterface* PeerConnection::current_remote_description()
1993 const {
Steve Anton75737c02017-11-06 10:37:17 -08001994 return current_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08001995}
1996
1997const SessionDescriptionInterface* PeerConnection::pending_local_description()
1998 const {
Steve Anton75737c02017-11-06 10:37:17 -08001999 return pending_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08002000}
2001
2002const SessionDescriptionInterface* PeerConnection::pending_remote_description()
2003 const {
Steve Anton75737c02017-11-06 10:37:17 -08002004 return pending_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08002005}
2006
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002007void PeerConnection::Close() {
Peter Boström1a9d6152015-12-08 22:15:17 +01002008 TRACE_EVENT0("webrtc", "PeerConnection::Close");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002009 // Update stats here so that we have the most recent stats for tracks and
2010 // streams before the channels are closed.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00002011 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002012
Steve Anton75737c02017-11-06 10:37:17 -08002013 ChangeSignalingState(PeerConnectionInterface::kClosed);
2014 RemoveUnusedChannels(nullptr);
Steve Anton4171afb2017-11-20 10:20:22 -08002015 RTC_DCHECK(!GetAudioTransceiver()->internal()->channel());
2016 RTC_DCHECK(!GetVideoTransceiver()->internal()->channel());
Steve Anton75737c02017-11-06 10:37:17 -08002017 RTC_DCHECK(!rtp_data_channel_);
2018 RTC_DCHECK(!sctp_transport_);
2019
deadbeef42a42632017-03-10 15:18:00 -08002020 network_thread()->Invoke<void>(
2021 RTC_FROM_HERE,
2022 rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
2023 port_allocator_.get()));
nisseeaabdf62017-05-05 02:23:02 -07002024
Steve Anton978b8762017-09-29 12:15:02 -07002025 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
eladalon248fd4f2017-09-06 05:18:15 -07002026 call_.reset();
2027 // The event log must outlive call (and any other object that uses it).
2028 event_log_.reset();
2029 });
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002030}
2031
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002032void PeerConnection::OnMessage(rtc::Message* msg) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002033 switch (msg->message_id) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002034 case MSG_SET_SESSIONDESCRIPTION_SUCCESS: {
2035 SetSessionDescriptionMsg* param =
2036 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
2037 param->observer->OnSuccess();
2038 delete param;
2039 break;
2040 }
2041 case MSG_SET_SESSIONDESCRIPTION_FAILED: {
2042 SetSessionDescriptionMsg* param =
2043 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
2044 param->observer->OnFailure(param->error);
2045 delete param;
2046 break;
2047 }
deadbeefab9b2d12015-10-14 11:33:11 -07002048 case MSG_CREATE_SESSIONDESCRIPTION_FAILED: {
2049 CreateSessionDescriptionMsg* param =
2050 static_cast<CreateSessionDescriptionMsg*>(msg->pdata);
2051 param->observer->OnFailure(param->error);
2052 delete param;
2053 break;
2054 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002055 case MSG_GETSTATS: {
2056 GetStatsMsg* param = static_cast<GetStatsMsg*>(msg->pdata);
nissee8abe3e2017-01-18 05:00:34 -08002057 StatsReports reports;
2058 stats_->GetStats(param->track, &reports);
2059 param->observer->OnComplete(reports);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002060 delete param;
2061 break;
2062 }
deadbeefbd292462015-12-14 18:15:29 -08002063 case MSG_FREE_DATACHANNELS: {
2064 sctp_data_channels_to_free_.clear();
2065 break;
2066 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002067 default:
nisseeb4ca4e2017-01-12 02:24:27 -08002068 RTC_NOTREACHED() << "Not implemented";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002069 break;
2070 }
2071}
2072
Steve Anton4171afb2017-11-20 10:20:22 -08002073void PeerConnection::CreateAudioReceiver(
2074 MediaStreamInterface* stream,
2075 const RtpSenderInfo& remote_sender_info) {
zhihuang81c3a032016-11-17 12:06:24 -08002076 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
2077 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
deadbeefe814a0d2017-02-25 18:15:09 -08002078 signaling_thread(),
Steve Anton4171afb2017-11-20 10:20:22 -08002079 new AudioRtpReceiver(remote_sender_info.sender_id,
2080 remote_sender_info.first_ssrc, voice_channel()));
deadbeefe814a0d2017-02-25 18:15:09 -08002081 stream->AddTrack(
2082 static_cast<AudioTrackInterface*>(receiver->internal()->track().get()));
Steve Anton4171afb2017-11-20 10:20:22 -08002083 GetAudioTransceiver()->internal()->AddReceiver(receiver);
zhihuang81c3a032016-11-17 12:06:24 -08002084 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
2085 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
2086 observer_->OnAddTrack(receiver, streams);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002087}
2088
Steve Anton4171afb2017-11-20 10:20:22 -08002089void PeerConnection::CreateVideoReceiver(
2090 MediaStreamInterface* stream,
2091 const RtpSenderInfo& remote_sender_info) {
zhihuang81c3a032016-11-17 12:06:24 -08002092 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
2093 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
Steve Anton4171afb2017-11-20 10:20:22 -08002094 signaling_thread(),
2095 new VideoRtpReceiver(remote_sender_info.sender_id, worker_thread(),
2096 remote_sender_info.first_ssrc, video_channel()));
deadbeefe814a0d2017-02-25 18:15:09 -08002097 stream->AddTrack(
2098 static_cast<VideoTrackInterface*>(receiver->internal()->track().get()));
Steve Anton4171afb2017-11-20 10:20:22 -08002099 GetVideoTransceiver()->internal()->AddReceiver(receiver);
zhihuang81c3a032016-11-17 12:06:24 -08002100 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
2101 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
2102 observer_->OnAddTrack(receiver, streams);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002103}
2104
deadbeef70ab1a12015-09-28 16:53:55 -07002105// TODO(deadbeef): Keep RtpReceivers around even if track goes away in remote
2106// description.
Henrik Boström933d8b02017-10-10 10:05:16 -07002107rtc::scoped_refptr<RtpReceiverInterface> PeerConnection::RemoveAndStopReceiver(
Steve Anton4171afb2017-11-20 10:20:22 -08002108 const RtpSenderInfo& remote_sender_info) {
2109 auto receiver = FindReceiverById(remote_sender_info.sender_id);
2110 if (!receiver) {
2111 RTC_LOG(LS_WARNING) << "RtpReceiver for track with id "
2112 << remote_sender_info.sender_id << " doesn't exist.";
Henrik Boström933d8b02017-10-10 10:05:16 -07002113 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07002114 }
Steve Anton4171afb2017-11-20 10:20:22 -08002115 if (receiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
2116 GetAudioTransceiver()->internal()->RemoveReceiver(receiver);
2117 } else {
2118 GetVideoTransceiver()->internal()->RemoveReceiver(receiver);
2119 }
Henrik Boström933d8b02017-10-10 10:05:16 -07002120 return receiver;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002121}
2122
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002123void PeerConnection::AddAudioTrack(AudioTrackInterface* track,
2124 MediaStreamInterface* stream) {
2125 RTC_DCHECK(!IsClosed());
2126 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08002127 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002128 // We already have a sender for this track, so just change the stream_id
2129 // so that it's correct in the next call to CreateOffer.
Steve Anton4171afb2017-11-20 10:20:22 -08002130 sender->internal()->set_stream_id(stream->label());
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002131 return;
2132 }
2133
2134 // Normal case; we've never seen this track before.
2135 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender =
2136 RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
2137 signaling_thread(),
Steve Anton75737c02017-11-06 10:37:17 -08002138 new AudioRtpSender(track, {stream->label()}, voice_channel(),
2139 stats_.get()));
Steve Anton4171afb2017-11-20 10:20:22 -08002140 GetAudioTransceiver()->internal()->AddSender(new_sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002141 // If the sender has already been configured in SDP, we call SetSsrc,
2142 // which will connect the sender to the underlying transport. This can
2143 // occur if a local session description that contains the ID of the sender
2144 // is set before AddStream is called. It can also occur if the local
2145 // session description is not changed and RemoveStream is called, and
2146 // later AddStream is called again with the same stream.
Steve Anton4171afb2017-11-20 10:20:22 -08002147 const RtpSenderInfo* sender_info =
2148 FindSenderInfo(local_audio_sender_infos_, stream->label(), track->id());
2149 if (sender_info) {
2150 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002151 }
2152}
2153
2154// TODO(deadbeef): Don't destroy RtpSenders here; they should be kept around
2155// indefinitely, when we have unified plan SDP.
2156void PeerConnection::RemoveAudioTrack(AudioTrackInterface* track,
2157 MediaStreamInterface* stream) {
2158 RTC_DCHECK(!IsClosed());
2159 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08002160 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002161 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
2162 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002163 return;
2164 }
Steve Anton4171afb2017-11-20 10:20:22 -08002165 GetAudioTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002166}
2167
2168void PeerConnection::AddVideoTrack(VideoTrackInterface* track,
2169 MediaStreamInterface* stream) {
2170 RTC_DCHECK(!IsClosed());
2171 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08002172 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002173 // We already have a sender for this track, so just change the stream_id
2174 // so that it's correct in the next call to CreateOffer.
Steve Anton4171afb2017-11-20 10:20:22 -08002175 sender->internal()->set_stream_id(stream->label());
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002176 return;
2177 }
2178
2179 // Normal case; we've never seen this track before.
2180 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender =
2181 RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton75737c02017-11-06 10:37:17 -08002182 signaling_thread(),
2183 new VideoRtpSender(track, {stream->label()}, video_channel()));
Steve Anton4171afb2017-11-20 10:20:22 -08002184 GetVideoTransceiver()->internal()->AddSender(new_sender);
2185 const RtpSenderInfo* sender_info =
2186 FindSenderInfo(local_video_sender_infos_, stream->label(), track->id());
2187 if (sender_info) {
2188 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002189 }
2190}
2191
2192void PeerConnection::RemoveVideoTrack(VideoTrackInterface* track,
2193 MediaStreamInterface* stream) {
2194 RTC_DCHECK(!IsClosed());
2195 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08002196 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002197 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
2198 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002199 return;
2200 }
Steve Anton4171afb2017-11-20 10:20:22 -08002201 GetVideoTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002202}
2203
Steve Antonba818672017-11-06 10:21:57 -08002204void PeerConnection::SetIceConnectionState(IceConnectionState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07002205 RTC_DCHECK(signaling_thread()->IsCurrent());
Steve Antonba818672017-11-06 10:21:57 -08002206 if (ice_connection_state_ == new_state) {
2207 return;
2208 }
2209
deadbeefcbecd352015-09-23 11:50:27 -07002210 // After transitioning to "closed", ignore any additional states from
Steve Antonba818672017-11-06 10:21:57 -08002211 // TransportController (such as "disconnected").
deadbeefab9b2d12015-10-14 11:33:11 -07002212 if (IsClosed()) {
deadbeefcbecd352015-09-23 11:50:27 -07002213 return;
2214 }
Steve Antonba818672017-11-06 10:21:57 -08002215
Mirko Bonadei675513b2017-11-09 11:09:25 +01002216 RTC_LOG(LS_INFO) << "Changing IceConnectionState " << ice_connection_state_
2217 << " => " << new_state;
Steve Antonba818672017-11-06 10:21:57 -08002218 RTC_DCHECK(ice_connection_state_ !=
2219 PeerConnectionInterface::kIceConnectionClosed);
2220
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002221 ice_connection_state_ = new_state;
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00002222 observer_->OnIceConnectionChange(ice_connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002223}
2224
2225void PeerConnection::OnIceGatheringChange(
2226 PeerConnectionInterface::IceGatheringState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07002227 RTC_DCHECK(signaling_thread()->IsCurrent());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002228 if (IsClosed()) {
2229 return;
2230 }
2231 ice_gathering_state_ = new_state;
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00002232 observer_->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002233}
2234
jbauch81bf7b02017-03-25 08:31:12 -07002235void PeerConnection::OnIceCandidate(
2236 std::unique_ptr<IceCandidateInterface> candidate) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07002237 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07002238 if (IsClosed()) {
2239 return;
2240 }
jbauch81bf7b02017-03-25 08:31:12 -07002241 observer_->OnIceCandidate(candidate.get());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002242}
2243
Honghai Zhang7fb69db2016-03-14 11:59:18 -07002244void PeerConnection::OnIceCandidatesRemoved(
2245 const std::vector<cricket::Candidate>& candidates) {
2246 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07002247 if (IsClosed()) {
2248 return;
2249 }
Honghai Zhang7fb69db2016-03-14 11:59:18 -07002250 observer_->OnIceCandidatesRemoved(candidates);
2251}
2252
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002253void PeerConnection::ChangeSignalingState(
2254 PeerConnectionInterface::SignalingState signaling_state) {
Steve Antonba818672017-11-06 10:21:57 -08002255 RTC_DCHECK(signaling_thread()->IsCurrent());
2256 if (signaling_state_ == signaling_state) {
2257 return;
2258 }
Mirko Bonadei675513b2017-11-09 11:09:25 +01002259 RTC_LOG(LS_INFO) << "Session: " << session_id() << " Old state: "
2260 << GetSignalingStateString(signaling_state_)
2261 << " New state: "
2262 << GetSignalingStateString(signaling_state);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002263 signaling_state_ = signaling_state;
2264 if (signaling_state == kClosed) {
2265 ice_connection_state_ = kIceConnectionClosed;
2266 observer_->OnIceConnectionChange(ice_connection_state_);
2267 if (ice_gathering_state_ != kIceGatheringComplete) {
2268 ice_gathering_state_ = kIceGatheringComplete;
2269 observer_->OnIceGatheringChange(ice_gathering_state_);
2270 }
2271 }
2272 observer_->OnSignalingChange(signaling_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002273}
2274
deadbeefeb459812015-12-15 19:24:43 -08002275void PeerConnection::OnAudioTrackAdded(AudioTrackInterface* track,
2276 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07002277 if (IsClosed()) {
2278 return;
2279 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002280 AddAudioTrack(track, stream);
2281 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08002282}
2283
deadbeefeb459812015-12-15 19:24:43 -08002284void PeerConnection::OnAudioTrackRemoved(AudioTrackInterface* track,
2285 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07002286 if (IsClosed()) {
2287 return;
2288 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002289 RemoveAudioTrack(track, stream);
2290 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08002291}
2292
2293void PeerConnection::OnVideoTrackAdded(VideoTrackInterface* track,
2294 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07002295 if (IsClosed()) {
2296 return;
2297 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002298 AddVideoTrack(track, stream);
2299 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08002300}
2301
2302void PeerConnection::OnVideoTrackRemoved(VideoTrackInterface* track,
2303 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07002304 if (IsClosed()) {
2305 return;
2306 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002307 RemoveVideoTrack(track, stream);
2308 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08002309}
2310
deadbeefab9b2d12015-10-14 11:33:11 -07002311void PeerConnection::PostSetSessionDescriptionFailure(
2312 SetSessionDescriptionObserver* observer,
2313 const std::string& error) {
2314 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
2315 msg->error = error;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07002316 signaling_thread()->Post(RTC_FROM_HERE, this,
2317 MSG_SET_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07002318}
2319
2320void PeerConnection::PostCreateSessionDescriptionFailure(
2321 CreateSessionDescriptionObserver* observer,
2322 const std::string& error) {
2323 CreateSessionDescriptionMsg* msg = new CreateSessionDescriptionMsg(observer);
2324 msg->error = error;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07002325 signaling_thread()->Post(RTC_FROM_HERE, this,
2326 MSG_CREATE_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07002327}
2328
zhihuang1c378ed2017-08-17 14:10:50 -07002329void PeerConnection::GetOptionsForOffer(
deadbeefab9b2d12015-10-14 11:33:11 -07002330 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options,
2331 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07002332 ExtractSharedMediaSessionOptions(rtc_options, session_options);
2333
2334 // Figure out transceiver directional preferences.
2335 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
2336 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
2337
2338 // By default, generate sendrecv/recvonly m= sections.
2339 bool recv_audio = true;
2340 bool recv_video = true;
2341
2342 // By default, only offer a new m= section if we have media to send with it.
2343 bool offer_new_audio_description = send_audio;
2344 bool offer_new_video_description = send_video;
2345 bool offer_new_data_description = HasDataChannels();
2346
2347 // The "offer_to_receive_X" options allow those defaults to be overridden.
2348 if (rtc_options.offer_to_receive_audio != RTCOfferAnswerOptions::kUndefined) {
2349 recv_audio = (rtc_options.offer_to_receive_audio > 0);
2350 offer_new_audio_description =
2351 offer_new_audio_description || (rtc_options.offer_to_receive_audio > 0);
2352 }
2353 if (rtc_options.offer_to_receive_video != RTCOfferAnswerOptions::kUndefined) {
2354 recv_video = (rtc_options.offer_to_receive_video > 0);
2355 offer_new_video_description =
2356 offer_new_video_description || (rtc_options.offer_to_receive_video > 0);
2357 }
2358
2359 rtc::Optional<size_t> audio_index;
2360 rtc::Optional<size_t> video_index;
2361 rtc::Optional<size_t> data_index;
2362 // If a current description exists, generate m= sections in the same order,
2363 // using the first audio/video/data section that appears and rejecting
2364 // extraneous ones.
Steve Anton75737c02017-11-06 10:37:17 -08002365 if (local_description()) {
zhihuang1c378ed2017-08-17 14:10:50 -07002366 GenerateMediaDescriptionOptions(
Steve Anton75737c02017-11-06 10:37:17 -08002367 local_description(),
zhihuang1c378ed2017-08-17 14:10:50 -07002368 cricket::RtpTransceiverDirection(send_audio, recv_audio),
2369 cricket::RtpTransceiverDirection(send_video, recv_video), &audio_index,
2370 &video_index, &data_index, session_options);
deadbeefab9b2d12015-10-14 11:33:11 -07002371 }
2372
zhihuang1c378ed2017-08-17 14:10:50 -07002373 // Add audio/video/data m= sections to the end if needed.
2374 if (!audio_index && offer_new_audio_description) {
2375 session_options->media_description_options.push_back(
2376 cricket::MediaDescriptionOptions(
2377 cricket::MEDIA_TYPE_AUDIO, cricket::CN_AUDIO,
2378 cricket::RtpTransceiverDirection(send_audio, recv_audio), false));
2379 audio_index = rtc::Optional<size_t>(
2380 session_options->media_description_options.size() - 1);
deadbeefc80741f2015-10-22 13:14:45 -07002381 }
zhihuang1c378ed2017-08-17 14:10:50 -07002382 if (!video_index && offer_new_video_description) {
2383 session_options->media_description_options.push_back(
2384 cricket::MediaDescriptionOptions(
2385 cricket::MEDIA_TYPE_VIDEO, cricket::CN_VIDEO,
2386 cricket::RtpTransceiverDirection(send_video, recv_video), false));
2387 video_index = rtc::Optional<size_t>(
2388 session_options->media_description_options.size() - 1);
deadbeefc80741f2015-10-22 13:14:45 -07002389 }
zhihuang1c378ed2017-08-17 14:10:50 -07002390 if (!data_index && offer_new_data_description) {
2391 session_options->media_description_options.push_back(
2392 cricket::MediaDescriptionOptions(
2393 cricket::MEDIA_TYPE_DATA, cricket::CN_DATA,
2394 cricket::RtpTransceiverDirection(true, true), false));
2395 data_index = rtc::Optional<size_t>(
2396 session_options->media_description_options.size() - 1);
2397 }
2398
2399 cricket::MediaDescriptionOptions* audio_media_description_options =
2400 !audio_index ? nullptr
2401 : &session_options->media_description_options[*audio_index];
2402 cricket::MediaDescriptionOptions* video_media_description_options =
2403 !video_index ? nullptr
2404 : &session_options->media_description_options[*video_index];
2405 cricket::MediaDescriptionOptions* data_media_description_options =
2406 !data_index ? nullptr
2407 : &session_options->media_description_options[*data_index];
2408
2409 // Apply ICE restart flag and renomination flag.
2410 for (auto& options : session_options->media_description_options) {
2411 options.transport_options.ice_restart = rtc_options.ice_restart;
2412 options.transport_options.enable_ice_renomination =
2413 configuration_.enable_ice_renomination;
2414 }
2415
Steve Anton4171afb2017-11-20 10:20:22 -08002416 AddRtpSenderOptions(GetSendersInternal(), audio_media_description_options,
zhihuang1c378ed2017-08-17 14:10:50 -07002417 video_media_description_options);
2418 AddRtpDataChannelOptions(rtp_data_channels_, data_media_description_options);
deadbeefc80741f2015-10-22 13:14:45 -07002419
zhihuang9763d562016-08-05 11:14:50 -07002420 // Intentionally unset the data channel type for RTP data channel with the
2421 // second condition. Otherwise the RTP data channels would be successfully
2422 // negotiated by default and the unit tests in WebRtcDataBrowserTest will fail
2423 // when building with chromium. We want to leave RTP data channels broken, so
2424 // people won't try to use them.
Steve Anton75737c02017-11-06 10:37:17 -08002425 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
2426 session_options->data_channel_type = data_channel_type();
deadbeefab9b2d12015-10-14 11:33:11 -07002427 }
zhihuang8f65cdf2016-05-06 18:40:30 -07002428
2429 session_options->rtcp_cname = rtcp_cname_;
jbauchcb560652016-08-04 05:20:32 -07002430 session_options->crypto_options = factory_->options().crypto_options;
deadbeefab9b2d12015-10-14 11:33:11 -07002431}
2432
zhihuang1c378ed2017-08-17 14:10:50 -07002433void PeerConnection::GetOptionsForAnswer(
2434 const RTCOfferAnswerOptions& rtc_options,
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07002435 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07002436 ExtractSharedMediaSessionOptions(rtc_options, session_options);
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07002437
zhihuang1c378ed2017-08-17 14:10:50 -07002438 // Figure out transceiver directional preferences.
2439 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
2440 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
2441
2442 // By default, generate sendrecv/recvonly m= sections. The direction is also
2443 // restricted by the direction in the offer.
2444 bool recv_audio = true;
2445 bool recv_video = true;
2446
2447 // The "offer_to_receive_X" options allow those defaults to be overridden.
2448 if (rtc_options.offer_to_receive_audio != RTCOfferAnswerOptions::kUndefined) {
2449 recv_audio = (rtc_options.offer_to_receive_audio > 0);
deadbeef0ed85b22016-02-23 17:24:52 -08002450 }
zhihuang1c378ed2017-08-17 14:10:50 -07002451 if (rtc_options.offer_to_receive_video != RTCOfferAnswerOptions::kUndefined) {
2452 recv_video = (rtc_options.offer_to_receive_video > 0);
2453 }
2454
2455 rtc::Optional<size_t> audio_index;
2456 rtc::Optional<size_t> video_index;
2457 rtc::Optional<size_t> data_index;
Steve Anton75737c02017-11-06 10:37:17 -08002458 if (remote_description()) {
zhihuang141aacb2017-08-29 13:23:53 -07002459 // The pending remote description should be an offer.
Steve Anton75737c02017-11-06 10:37:17 -08002460 RTC_DCHECK(remote_description()->type() ==
zhihuang141aacb2017-08-29 13:23:53 -07002461 SessionDescriptionInterface::kOffer);
2462 // Generate m= sections that match those in the offer.
2463 // Note that mediasession.cc will handle intersection our preferred
2464 // direction with the offered direction.
2465 GenerateMediaDescriptionOptions(
Steve Anton75737c02017-11-06 10:37:17 -08002466 remote_description(),
zhihuang141aacb2017-08-29 13:23:53 -07002467 cricket::RtpTransceiverDirection(send_audio, recv_audio),
2468 cricket::RtpTransceiverDirection(send_video, recv_video), &audio_index,
2469 &video_index, &data_index, session_options);
2470 }
zhihuang1c378ed2017-08-17 14:10:50 -07002471
2472 cricket::MediaDescriptionOptions* audio_media_description_options =
2473 !audio_index ? nullptr
2474 : &session_options->media_description_options[*audio_index];
2475 cricket::MediaDescriptionOptions* video_media_description_options =
2476 !video_index ? nullptr
2477 : &session_options->media_description_options[*video_index];
2478 cricket::MediaDescriptionOptions* data_media_description_options =
2479 !data_index ? nullptr
2480 : &session_options->media_description_options[*data_index];
2481
2482 // Apply ICE renomination flag.
2483 for (auto& options : session_options->media_description_options) {
2484 options.transport_options.enable_ice_renomination =
2485 configuration_.enable_ice_renomination;
2486 }
2487
Steve Anton4171afb2017-11-20 10:20:22 -08002488 AddRtpSenderOptions(GetSendersInternal(), audio_media_description_options,
zhihuang1c378ed2017-08-17 14:10:50 -07002489 video_media_description_options);
2490 AddRtpDataChannelOptions(rtp_data_channels_, data_media_description_options);
2491
zhihuang9763d562016-08-05 11:14:50 -07002492 // Intentionally unset the data channel type for RTP data channel. Otherwise
2493 // the RTP data channels would be successfully negotiated by default and the
2494 // unit tests in WebRtcDataBrowserTest will fail when building with chromium.
2495 // We want to leave RTP data channels broken, so people won't try to use them.
Steve Anton75737c02017-11-06 10:37:17 -08002496 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
2497 session_options->data_channel_type = data_channel_type();
deadbeef907abe42016-08-04 12:22:18 -07002498 }
zhihuangaf388472016-11-02 16:49:48 -07002499
zhihuang1c378ed2017-08-17 14:10:50 -07002500 session_options->rtcp_cname = rtcp_cname_;
jbauchcb560652016-08-04 05:20:32 -07002501 session_options->crypto_options = factory_->options().crypto_options;
htaa2a49d92016-03-04 02:51:39 -08002502}
2503
zhihuang1c378ed2017-08-17 14:10:50 -07002504void PeerConnection::GenerateMediaDescriptionOptions(
2505 const SessionDescriptionInterface* session_desc,
2506 cricket::RtpTransceiverDirection audio_direction,
2507 cricket::RtpTransceiverDirection video_direction,
2508 rtc::Optional<size_t>* audio_index,
2509 rtc::Optional<size_t>* video_index,
2510 rtc::Optional<size_t>* data_index,
htaa2a49d92016-03-04 02:51:39 -08002511 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07002512 for (const cricket::ContentInfo& content :
2513 session_desc->description()->contents()) {
2514 if (IsAudioContent(&content)) {
2515 // If we already have an audio m= section, reject this extra one.
2516 if (*audio_index) {
2517 session_options->media_description_options.push_back(
2518 cricket::MediaDescriptionOptions(
2519 cricket::MEDIA_TYPE_AUDIO, content.name,
2520 cricket::RtpTransceiverDirection(false, false), true));
2521 } else {
2522 session_options->media_description_options.push_back(
2523 cricket::MediaDescriptionOptions(
2524 cricket::MEDIA_TYPE_AUDIO, content.name, audio_direction,
2525 !audio_direction.send && !audio_direction.recv));
2526 *audio_index = rtc::Optional<size_t>(
2527 session_options->media_description_options.size() - 1);
2528 }
2529 } else if (IsVideoContent(&content)) {
2530 // If we already have an video m= section, reject this extra one.
2531 if (*video_index) {
2532 session_options->media_description_options.push_back(
2533 cricket::MediaDescriptionOptions(
2534 cricket::MEDIA_TYPE_VIDEO, content.name,
2535 cricket::RtpTransceiverDirection(false, false), true));
2536 } else {
2537 session_options->media_description_options.push_back(
2538 cricket::MediaDescriptionOptions(
2539 cricket::MEDIA_TYPE_VIDEO, content.name, video_direction,
2540 !video_direction.send && !video_direction.recv));
2541 *video_index = rtc::Optional<size_t>(
2542 session_options->media_description_options.size() - 1);
2543 }
2544 } else {
2545 RTC_DCHECK(IsDataContent(&content));
2546 // If we already have an data m= section, reject this extra one.
2547 if (*data_index) {
2548 session_options->media_description_options.push_back(
2549 cricket::MediaDescriptionOptions(
2550 cricket::MEDIA_TYPE_DATA, content.name,
2551 cricket::RtpTransceiverDirection(false, false), true));
2552 } else {
2553 session_options->media_description_options.push_back(
2554 cricket::MediaDescriptionOptions(
2555 cricket::MEDIA_TYPE_DATA, content.name,
2556 // Direction for data sections is meaningless, but legacy
2557 // endpoints might expect sendrecv.
2558 cricket::RtpTransceiverDirection(true, true), false));
2559 *data_index = rtc::Optional<size_t>(
2560 session_options->media_description_options.size() - 1);
2561 }
2562 }
htaa2a49d92016-03-04 02:51:39 -08002563 }
deadbeefab9b2d12015-10-14 11:33:11 -07002564}
2565
Steve Anton4171afb2017-11-20 10:20:22 -08002566void PeerConnection::RemoveSenders(cricket::MediaType media_type) {
2567 UpdateLocalSenders(std::vector<cricket::StreamParams>(), media_type);
2568 UpdateRemoteSendersList(std::vector<cricket::StreamParams>(), false,
deadbeefbda7e0b2015-12-08 17:13:40 -08002569 media_type, nullptr);
deadbeeffaac4972015-11-12 15:33:07 -08002570}
2571
Steve Anton4171afb2017-11-20 10:20:22 -08002572void PeerConnection::UpdateRemoteSendersList(
deadbeefab9b2d12015-10-14 11:33:11 -07002573 const cricket::StreamParamsVec& streams,
Steve Anton4171afb2017-11-20 10:20:22 -08002574 bool default_sender_needed,
deadbeefab9b2d12015-10-14 11:33:11 -07002575 cricket::MediaType media_type,
2576 StreamCollection* new_streams) {
Steve Anton4171afb2017-11-20 10:20:22 -08002577 std::vector<RtpSenderInfo>* current_senders =
2578 GetRemoteSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07002579
Steve Anton4171afb2017-11-20 10:20:22 -08002580 // Find removed senders. I.e., senders where the sender id or ssrc don't match
deadbeeffac06552015-11-25 11:26:01 -08002581 // the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08002582 for (auto sender_it = current_senders->begin();
2583 sender_it != current_senders->end();
2584 /* incremented manually */) {
2585 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07002586 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08002587 cricket::GetStreamBySsrc(streams, info.first_ssrc);
2588 bool sender_exists = params && params->id == info.sender_id;
deadbeefbda7e0b2015-12-08 17:13:40 -08002589 // If this is a default track, and we still need it, don't remove it.
Steve Anton4171afb2017-11-20 10:20:22 -08002590 if ((info.stream_label == kDefaultStreamLabel && default_sender_needed) ||
2591 sender_exists) {
2592 ++sender_it;
deadbeefbda7e0b2015-12-08 17:13:40 -08002593 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08002594 OnRemoteSenderRemoved(info, media_type);
2595 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07002596 }
2597 }
2598
Steve Anton4171afb2017-11-20 10:20:22 -08002599 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07002600 for (const cricket::StreamParams& params : streams) {
2601 // The sync_label is the MediaStream label and the |stream.id| is the
Steve Anton4171afb2017-11-20 10:20:22 -08002602 // sender id.
deadbeefab9b2d12015-10-14 11:33:11 -07002603 const std::string& stream_label = params.sync_label;
Steve Anton4171afb2017-11-20 10:20:22 -08002604 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07002605 uint32_t ssrc = params.first_ssrc();
2606
2607 rtc::scoped_refptr<MediaStreamInterface> stream =
2608 remote_streams_->find(stream_label);
2609 if (!stream) {
2610 // This is a new MediaStream. Create a new remote MediaStream.
perkjd61bf802016-03-24 03:16:19 -07002611 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
2612 MediaStream::Create(stream_label));
deadbeefab9b2d12015-10-14 11:33:11 -07002613 remote_streams_->AddStream(stream);
2614 new_streams->AddStream(stream);
2615 }
2616
Steve Anton4171afb2017-11-20 10:20:22 -08002617 const RtpSenderInfo* sender_info =
2618 FindSenderInfo(*current_senders, stream_label, sender_id);
2619 if (!sender_info) {
2620 current_senders->push_back(RtpSenderInfo(stream_label, sender_id, ssrc));
2621 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07002622 }
2623 }
deadbeefbda7e0b2015-12-08 17:13:40 -08002624
Steve Anton4171afb2017-11-20 10:20:22 -08002625 // Add default sender if necessary.
2626 if (default_sender_needed) {
deadbeefbda7e0b2015-12-08 17:13:40 -08002627 rtc::scoped_refptr<MediaStreamInterface> default_stream =
2628 remote_streams_->find(kDefaultStreamLabel);
2629 if (!default_stream) {
2630 // Create the new default MediaStream.
perkjd61bf802016-03-24 03:16:19 -07002631 default_stream = MediaStreamProxy::Create(
2632 rtc::Thread::Current(), MediaStream::Create(kDefaultStreamLabel));
deadbeefbda7e0b2015-12-08 17:13:40 -08002633 remote_streams_->AddStream(default_stream);
2634 new_streams->AddStream(default_stream);
2635 }
Steve Anton4171afb2017-11-20 10:20:22 -08002636 std::string default_sender_id = (media_type == cricket::MEDIA_TYPE_AUDIO)
2637 ? kDefaultAudioSenderId
2638 : kDefaultVideoSenderId;
2639 const RtpSenderInfo* default_sender_info = FindSenderInfo(
2640 *current_senders, kDefaultStreamLabel, default_sender_id);
2641 if (!default_sender_info) {
2642 current_senders->push_back(
2643 RtpSenderInfo(kDefaultStreamLabel, default_sender_id, 0));
2644 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefbda7e0b2015-12-08 17:13:40 -08002645 }
2646 }
deadbeefab9b2d12015-10-14 11:33:11 -07002647}
2648
Steve Anton4171afb2017-11-20 10:20:22 -08002649void PeerConnection::OnRemoteSenderAdded(const RtpSenderInfo& sender_info,
2650 cricket::MediaType media_type) {
2651 MediaStreamInterface* stream =
2652 remote_streams_->find(sender_info.stream_label);
deadbeefab9b2d12015-10-14 11:33:11 -07002653
2654 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 10:20:22 -08002655 CreateAudioReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07002656 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 10:20:22 -08002657 CreateVideoReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07002658 } else {
nisseeb4ca4e2017-01-12 02:24:27 -08002659 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07002660 }
2661}
2662
Steve Anton4171afb2017-11-20 10:20:22 -08002663void PeerConnection::OnRemoteSenderRemoved(const RtpSenderInfo& sender_info,
2664 cricket::MediaType media_type) {
2665 MediaStreamInterface* stream =
2666 remote_streams_->find(sender_info.stream_label);
deadbeefab9b2d12015-10-14 11:33:11 -07002667
Henrik Boström933d8b02017-10-10 10:05:16 -07002668 rtc::scoped_refptr<RtpReceiverInterface> receiver;
deadbeefab9b2d12015-10-14 11:33:11 -07002669 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
perkjd61bf802016-03-24 03:16:19 -07002670 // When the MediaEngine audio channel is destroyed, the RemoteAudioSource
2671 // will be notified which will end the AudioRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08002672 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07002673 rtc::scoped_refptr<AudioTrackInterface> audio_track =
Steve Anton4171afb2017-11-20 10:20:22 -08002674 stream->FindAudioTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07002675 if (audio_track) {
deadbeefab9b2d12015-10-14 11:33:11 -07002676 stream->RemoveTrack(audio_track);
deadbeefab9b2d12015-10-14 11:33:11 -07002677 }
2678 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
perkjd61bf802016-03-24 03:16:19 -07002679 // Stopping or destroying a VideoRtpReceiver will end the
2680 // VideoRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08002681 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07002682 rtc::scoped_refptr<VideoTrackInterface> video_track =
Steve Anton4171afb2017-11-20 10:20:22 -08002683 stream->FindVideoTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07002684 if (video_track) {
perkjd61bf802016-03-24 03:16:19 -07002685 // There's no guarantee the track is still available, e.g. the track may
2686 // have been removed from the stream by an application.
deadbeefab9b2d12015-10-14 11:33:11 -07002687 stream->RemoveTrack(video_track);
deadbeefab9b2d12015-10-14 11:33:11 -07002688 }
2689 } else {
nisseede5da42017-01-12 05:15:36 -08002690 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07002691 }
Henrik Boström933d8b02017-10-10 10:05:16 -07002692 if (receiver) {
2693 observer_->OnRemoveTrack(receiver);
2694 }
deadbeefab9b2d12015-10-14 11:33:11 -07002695}
2696
2697void PeerConnection::UpdateEndedRemoteMediaStreams() {
2698 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams_to_remove;
2699 for (size_t i = 0; i < remote_streams_->count(); ++i) {
2700 MediaStreamInterface* stream = remote_streams_->at(i);
2701 if (stream->GetAudioTracks().empty() && stream->GetVideoTracks().empty()) {
2702 streams_to_remove.push_back(stream);
2703 }
2704 }
2705
Taylor Brandstetter98cde262016-05-31 13:02:21 -07002706 for (auto& stream : streams_to_remove) {
deadbeefab9b2d12015-10-14 11:33:11 -07002707 remote_streams_->RemoveStream(stream);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07002708 observer_->OnRemoveStream(std::move(stream));
deadbeefab9b2d12015-10-14 11:33:11 -07002709 }
2710}
2711
Steve Anton4171afb2017-11-20 10:20:22 -08002712void PeerConnection::UpdateLocalSenders(
deadbeefab9b2d12015-10-14 11:33:11 -07002713 const std::vector<cricket::StreamParams>& streams,
2714 cricket::MediaType media_type) {
Steve Anton4171afb2017-11-20 10:20:22 -08002715 std::vector<RtpSenderInfo>* current_senders = GetLocalSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07002716
2717 // Find removed tracks. I.e., tracks where the track id, stream label or ssrc
2718 // don't match the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08002719 for (auto sender_it = current_senders->begin();
2720 sender_it != current_senders->end();
2721 /* incremented manually */) {
2722 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07002723 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08002724 cricket::GetStreamBySsrc(streams, info.first_ssrc);
2725 if (!params || params->id != info.sender_id ||
deadbeefab9b2d12015-10-14 11:33:11 -07002726 params->sync_label != info.stream_label) {
Steve Anton4171afb2017-11-20 10:20:22 -08002727 OnLocalSenderRemoved(info, media_type);
2728 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07002729 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08002730 ++sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07002731 }
2732 }
2733
Steve Anton4171afb2017-11-20 10:20:22 -08002734 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07002735 for (const cricket::StreamParams& params : streams) {
2736 // The sync_label is the MediaStream label and the |stream.id| is the
Steve Anton4171afb2017-11-20 10:20:22 -08002737 // sender id.
deadbeefab9b2d12015-10-14 11:33:11 -07002738 const std::string& stream_label = params.sync_label;
Steve Anton4171afb2017-11-20 10:20:22 -08002739 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07002740 uint32_t ssrc = params.first_ssrc();
Steve Anton4171afb2017-11-20 10:20:22 -08002741 const RtpSenderInfo* sender_info =
2742 FindSenderInfo(*current_senders, stream_label, sender_id);
2743 if (!sender_info) {
2744 current_senders->push_back(RtpSenderInfo(stream_label, sender_id, ssrc));
2745 OnLocalSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07002746 }
2747 }
2748}
2749
Steve Anton4171afb2017-11-20 10:20:22 -08002750void PeerConnection::OnLocalSenderAdded(const RtpSenderInfo& sender_info,
2751 cricket::MediaType media_type) {
2752 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08002753 if (!sender) {
Steve Anton4171afb2017-11-20 10:20:22 -08002754 RTC_LOG(LS_WARNING) << "An unknown RtpSender with id "
2755 << sender_info.sender_id
Mirko Bonadei675513b2017-11-09 11:09:25 +01002756 << " has been configured in the local description.";
deadbeefab9b2d12015-10-14 11:33:11 -07002757 return;
2758 }
2759
deadbeeffac06552015-11-25 11:26:01 -08002760 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002761 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
2762 << " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08002763 return;
deadbeefab9b2d12015-10-14 11:33:11 -07002764 }
deadbeeffac06552015-11-25 11:26:01 -08002765
Steve Anton4171afb2017-11-20 10:20:22 -08002766 sender->internal()->set_stream_id(sender_info.stream_label);
2767 sender->internal()->SetSsrc(sender_info.first_ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07002768}
2769
Steve Anton4171afb2017-11-20 10:20:22 -08002770void PeerConnection::OnLocalSenderRemoved(const RtpSenderInfo& sender_info,
2771 cricket::MediaType media_type) {
2772 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08002773 if (!sender) {
2774 // This is the normal case. I.e., RemoveStream has been called and the
deadbeefab9b2d12015-10-14 11:33:11 -07002775 // SessionDescriptions has been renegotiated.
2776 return;
2777 }
deadbeeffac06552015-11-25 11:26:01 -08002778
2779 // A sender has been removed from the SessionDescription but it's still
2780 // associated with the PeerConnection. This only occurs if the SDP doesn't
2781 // match with the calls to CreateSender, AddStream and RemoveStream.
2782 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002783 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
2784 << " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08002785 return;
deadbeefab9b2d12015-10-14 11:33:11 -07002786 }
deadbeeffac06552015-11-25 11:26:01 -08002787
Steve Anton4171afb2017-11-20 10:20:22 -08002788 sender->internal()->SetSsrc(0);
deadbeefab9b2d12015-10-14 11:33:11 -07002789}
2790
2791void PeerConnection::UpdateLocalRtpDataChannels(
2792 const cricket::StreamParamsVec& streams) {
2793 std::vector<std::string> existing_channels;
2794
2795 // Find new and active data channels.
2796 for (const cricket::StreamParams& params : streams) {
2797 // |it->sync_label| is actually the data channel label. The reason is that
2798 // we use the same naming of data channels as we do for
2799 // MediaStreams and Tracks.
2800 // For MediaStreams, the sync_label is the MediaStream label and the
2801 // track label is the same as |streamid|.
2802 const std::string& channel_label = params.sync_label;
2803 auto data_channel_it = rtp_data_channels_.find(channel_label);
nisse7ce109a2017-01-31 00:57:56 -08002804 if (data_channel_it == rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002805 RTC_LOG(LS_ERROR) << "channel label not found";
deadbeefab9b2d12015-10-14 11:33:11 -07002806 continue;
2807 }
2808 // Set the SSRC the data channel should use for sending.
2809 data_channel_it->second->SetSendSsrc(params.first_ssrc());
2810 existing_channels.push_back(data_channel_it->first);
2811 }
2812
2813 UpdateClosingRtpDataChannels(existing_channels, true);
2814}
2815
2816void PeerConnection::UpdateRemoteRtpDataChannels(
2817 const cricket::StreamParamsVec& streams) {
2818 std::vector<std::string> existing_channels;
2819
2820 // Find new and active data channels.
2821 for (const cricket::StreamParams& params : streams) {
2822 // The data channel label is either the mslabel or the SSRC if the mslabel
2823 // does not exist. Ex a=ssrc:444330170 mslabel:test1.
2824 std::string label = params.sync_label.empty()
2825 ? rtc::ToString(params.first_ssrc())
2826 : params.sync_label;
2827 auto data_channel_it = rtp_data_channels_.find(label);
2828 if (data_channel_it == rtp_data_channels_.end()) {
2829 // This is a new data channel.
2830 CreateRemoteRtpDataChannel(label, params.first_ssrc());
2831 } else {
2832 data_channel_it->second->SetReceiveSsrc(params.first_ssrc());
2833 }
2834 existing_channels.push_back(label);
2835 }
2836
2837 UpdateClosingRtpDataChannels(existing_channels, false);
2838}
2839
2840void PeerConnection::UpdateClosingRtpDataChannels(
2841 const std::vector<std::string>& active_channels,
2842 bool is_local_update) {
2843 auto it = rtp_data_channels_.begin();
2844 while (it != rtp_data_channels_.end()) {
2845 DataChannel* data_channel = it->second;
2846 if (std::find(active_channels.begin(), active_channels.end(),
2847 data_channel->label()) != active_channels.end()) {
2848 ++it;
2849 continue;
2850 }
2851
2852 if (is_local_update) {
2853 data_channel->SetSendSsrc(0);
2854 } else {
2855 data_channel->RemotePeerRequestClose();
2856 }
2857
2858 if (data_channel->state() == DataChannel::kClosed) {
2859 rtp_data_channels_.erase(it);
2860 it = rtp_data_channels_.begin();
2861 } else {
2862 ++it;
2863 }
2864 }
2865}
2866
2867void PeerConnection::CreateRemoteRtpDataChannel(const std::string& label,
2868 uint32_t remote_ssrc) {
2869 rtc::scoped_refptr<DataChannel> channel(
2870 InternalCreateDataChannel(label, nullptr));
2871 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002872 RTC_LOG(LS_WARNING) << "Remote peer requested a DataChannel but"
2873 << "CreateDataChannel failed.";
deadbeefab9b2d12015-10-14 11:33:11 -07002874 return;
2875 }
2876 channel->SetReceiveSsrc(remote_ssrc);
deadbeefa601f5c2016-06-06 14:27:39 -07002877 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
2878 DataChannelProxy::Create(signaling_thread(), channel);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07002879 observer_->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07002880}
2881
2882rtc::scoped_refptr<DataChannel> PeerConnection::InternalCreateDataChannel(
2883 const std::string& label,
2884 const InternalDataChannelInit* config) {
2885 if (IsClosed()) {
2886 return nullptr;
2887 }
Steve Anton75737c02017-11-06 10:37:17 -08002888 if (data_channel_type() == cricket::DCT_NONE) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002889 RTC_LOG(LS_ERROR)
deadbeefab9b2d12015-10-14 11:33:11 -07002890 << "InternalCreateDataChannel: Data is not supported in this call.";
2891 return nullptr;
2892 }
2893 InternalDataChannelInit new_config =
2894 config ? (*config) : InternalDataChannelInit();
Steve Anton75737c02017-11-06 10:37:17 -08002895 if (data_channel_type() == cricket::DCT_SCTP) {
deadbeefab9b2d12015-10-14 11:33:11 -07002896 if (new_config.id < 0) {
2897 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08002898 if ((GetSctpSslRole(&role)) &&
deadbeefab9b2d12015-10-14 11:33:11 -07002899 !sid_allocator_.AllocateSid(role, &new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002900 RTC_LOG(LS_ERROR)
2901 << "No id can be allocated for the SCTP data channel.";
deadbeefab9b2d12015-10-14 11:33:11 -07002902 return nullptr;
2903 }
2904 } else if (!sid_allocator_.ReserveSid(new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002905 RTC_LOG(LS_ERROR) << "Failed to create a SCTP data channel "
2906 << "because the id is already in use or out of range.";
deadbeefab9b2d12015-10-14 11:33:11 -07002907 return nullptr;
2908 }
2909 }
2910
Steve Anton75737c02017-11-06 10:37:17 -08002911 rtc::scoped_refptr<DataChannel> channel(
2912 DataChannel::Create(this, data_channel_type(), label, new_config));
deadbeefab9b2d12015-10-14 11:33:11 -07002913 if (!channel) {
2914 sid_allocator_.ReleaseSid(new_config.id);
2915 return nullptr;
2916 }
2917
2918 if (channel->data_channel_type() == cricket::DCT_RTP) {
2919 if (rtp_data_channels_.find(channel->label()) != rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002920 RTC_LOG(LS_ERROR) << "DataChannel with label " << channel->label()
2921 << " already exists.";
deadbeefab9b2d12015-10-14 11:33:11 -07002922 return nullptr;
2923 }
2924 rtp_data_channels_[channel->label()] = channel;
2925 } else {
2926 RTC_DCHECK(channel->data_channel_type() == cricket::DCT_SCTP);
2927 sctp_data_channels_.push_back(channel);
2928 channel->SignalClosed.connect(this,
2929 &PeerConnection::OnSctpDataChannelClosed);
2930 }
2931
hbos82ebe022016-11-14 01:41:09 -08002932 SignalDataChannelCreated(channel.get());
deadbeefab9b2d12015-10-14 11:33:11 -07002933 return channel;
2934}
2935
2936bool PeerConnection::HasDataChannels() const {
2937 return !rtp_data_channels_.empty() || !sctp_data_channels_.empty();
2938}
2939
2940void PeerConnection::AllocateSctpSids(rtc::SSLRole role) {
2941 for (const auto& channel : sctp_data_channels_) {
2942 if (channel->id() < 0) {
2943 int sid;
2944 if (!sid_allocator_.AllocateSid(role, &sid)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002945 RTC_LOG(LS_ERROR) << "Failed to allocate SCTP sid.";
deadbeefab9b2d12015-10-14 11:33:11 -07002946 continue;
2947 }
2948 channel->SetSctpSid(sid);
2949 }
2950 }
2951}
2952
2953void PeerConnection::OnSctpDataChannelClosed(DataChannel* channel) {
deadbeefbd292462015-12-14 18:15:29 -08002954 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeefab9b2d12015-10-14 11:33:11 -07002955 for (auto it = sctp_data_channels_.begin(); it != sctp_data_channels_.end();
2956 ++it) {
2957 if (it->get() == channel) {
2958 if (channel->id() >= 0) {
2959 sid_allocator_.ReleaseSid(channel->id());
2960 }
deadbeefbd292462015-12-14 18:15:29 -08002961 // Since this method is triggered by a signal from the DataChannel,
2962 // we can't free it directly here; we need to free it asynchronously.
2963 sctp_data_channels_to_free_.push_back(*it);
deadbeefab9b2d12015-10-14 11:33:11 -07002964 sctp_data_channels_.erase(it);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07002965 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_FREE_DATACHANNELS,
2966 nullptr);
deadbeefab9b2d12015-10-14 11:33:11 -07002967 return;
2968 }
2969 }
2970}
2971
deadbeefab9b2d12015-10-14 11:33:11 -07002972void PeerConnection::OnDataChannelDestroyed() {
2973 // Use a temporary copy of the RTP/SCTP DataChannel list because the
2974 // DataChannel may callback to us and try to modify the list.
2975 std::map<std::string, rtc::scoped_refptr<DataChannel>> temp_rtp_dcs;
2976 temp_rtp_dcs.swap(rtp_data_channels_);
2977 for (const auto& kv : temp_rtp_dcs) {
2978 kv.second->OnTransportChannelDestroyed();
2979 }
2980
2981 std::vector<rtc::scoped_refptr<DataChannel>> temp_sctp_dcs;
2982 temp_sctp_dcs.swap(sctp_data_channels_);
2983 for (const auto& channel : temp_sctp_dcs) {
2984 channel->OnTransportChannelDestroyed();
2985 }
2986}
2987
2988void PeerConnection::OnDataChannelOpenMessage(
2989 const std::string& label,
2990 const InternalDataChannelInit& config) {
2991 rtc::scoped_refptr<DataChannel> channel(
2992 InternalCreateDataChannel(label, &config));
2993 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002994 RTC_LOG(LS_ERROR) << "Failed to create DataChannel from the OPEN message.";
deadbeefab9b2d12015-10-14 11:33:11 -07002995 return;
2996 }
2997
deadbeefa601f5c2016-06-06 14:27:39 -07002998 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
2999 DataChannelProxy::Create(signaling_thread(), channel);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07003000 observer_->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07003001}
3002
Steve Anton4171afb2017-11-20 10:20:22 -08003003rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3004PeerConnection::GetAudioTransceiver() const {
3005 // This method only works with Plan B SDP, where there is a single
3006 // audio/video transceiver.
3007 RTC_DCHECK(!IsUnifiedPlan());
3008 for (auto transceiver : transceivers_) {
3009 if (transceiver->internal()->media_type() == cricket::MEDIA_TYPE_AUDIO) {
3010 return transceiver;
3011 }
3012 }
3013 RTC_NOTREACHED();
3014 return nullptr;
3015}
3016
3017rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3018PeerConnection::GetVideoTransceiver() const {
3019 // This method only works with Plan B SDP, where there is a single
3020 // audio/video transceiver.
3021 RTC_DCHECK(!IsUnifiedPlan());
3022 for (auto transceiver : transceivers_) {
3023 if (transceiver->internal()->media_type() == cricket::MEDIA_TYPE_VIDEO) {
3024 return transceiver;
3025 }
3026 }
3027 RTC_NOTREACHED();
3028 return nullptr;
3029}
3030
3031// TODO(bugs.webrtc.org/7600): Remove this when multiple transceivers with
3032// individual transceiver directions are supported.
zhihuang1c378ed2017-08-17 14:10:50 -07003033bool PeerConnection::HasRtpSender(cricket::MediaType type) const {
Steve Anton4171afb2017-11-20 10:20:22 -08003034 switch (type) {
3035 case cricket::MEDIA_TYPE_AUDIO:
3036 return !GetAudioTransceiver()->internal()->senders().empty();
3037 case cricket::MEDIA_TYPE_VIDEO:
3038 return !GetVideoTransceiver()->internal()->senders().empty();
3039 case cricket::MEDIA_TYPE_DATA:
3040 return false;
3041 }
3042 RTC_NOTREACHED();
3043 return false;
zhihuang1c378ed2017-08-17 14:10:50 -07003044}
3045
Steve Anton4171afb2017-11-20 10:20:22 -08003046rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
3047PeerConnection::FindSenderForTrack(MediaStreamTrackInterface* track) const {
3048 for (auto transceiver : transceivers_) {
3049 for (auto sender : transceiver->internal()->senders()) {
3050 if (sender->track() == track) {
3051 return sender;
3052 }
3053 }
3054 }
3055 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08003056}
3057
Steve Anton4171afb2017-11-20 10:20:22 -08003058rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
3059PeerConnection::FindSenderById(const std::string& sender_id) const {
3060 for (auto transceiver : transceivers_) {
3061 for (auto sender : transceiver->internal()->senders()) {
3062 if (sender->id() == sender_id) {
3063 return sender;
3064 }
3065 }
3066 }
3067 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07003068}
3069
Steve Anton4171afb2017-11-20 10:20:22 -08003070rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
3071PeerConnection::FindReceiverById(const std::string& receiver_id) const {
3072 for (auto transceiver : transceivers_) {
3073 for (auto receiver : transceiver->internal()->receivers()) {
3074 if (receiver->id() == receiver_id) {
3075 return receiver;
3076 }
3077 }
3078 }
3079 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07003080}
3081
Steve Anton4171afb2017-11-20 10:20:22 -08003082std::vector<PeerConnection::RtpSenderInfo>*
3083PeerConnection::GetRemoteSenderInfos(cricket::MediaType media_type) {
3084 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
3085 media_type == cricket::MEDIA_TYPE_VIDEO);
3086 return (media_type == cricket::MEDIA_TYPE_AUDIO)
3087 ? &remote_audio_sender_infos_
3088 : &remote_video_sender_infos_;
3089}
3090
3091std::vector<PeerConnection::RtpSenderInfo>* PeerConnection::GetLocalSenderInfos(
deadbeefab9b2d12015-10-14 11:33:11 -07003092 cricket::MediaType media_type) {
3093 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
3094 media_type == cricket::MEDIA_TYPE_VIDEO);
Steve Anton4171afb2017-11-20 10:20:22 -08003095 return (media_type == cricket::MEDIA_TYPE_AUDIO) ? &local_audio_sender_infos_
3096 : &local_video_sender_infos_;
deadbeefab9b2d12015-10-14 11:33:11 -07003097}
3098
Steve Anton4171afb2017-11-20 10:20:22 -08003099const PeerConnection::RtpSenderInfo* PeerConnection::FindSenderInfo(
3100 const std::vector<PeerConnection::RtpSenderInfo>& infos,
deadbeefab9b2d12015-10-14 11:33:11 -07003101 const std::string& stream_label,
Steve Anton4171afb2017-11-20 10:20:22 -08003102 const std::string sender_id) const {
3103 for (const RtpSenderInfo& sender_info : infos) {
3104 if (sender_info.stream_label == stream_label &&
3105 sender_info.sender_id == sender_id) {
3106 return &sender_info;
deadbeefab9b2d12015-10-14 11:33:11 -07003107 }
3108 }
3109 return nullptr;
3110}
3111
3112DataChannel* PeerConnection::FindDataChannelBySid(int sid) const {
3113 for (const auto& channel : sctp_data_channels_) {
3114 if (channel->id() == sid) {
3115 return channel;
3116 }
3117 }
3118 return nullptr;
3119}
3120
deadbeef91dd5672016-05-18 16:55:30 -07003121bool PeerConnection::InitializePortAllocator_n(
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003122 const RTCConfiguration& configuration) {
3123 cricket::ServerAddresses stun_servers;
3124 std::vector<cricket::RelayServerConfig> turn_servers;
deadbeef293e9262017-01-11 12:28:30 -08003125 if (ParseIceServers(configuration.servers, &stun_servers, &turn_servers) !=
3126 RTCErrorType::NONE) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003127 return false;
3128 }
3129
Taylor Brandstetterf8e65772016-06-27 17:20:15 -07003130 port_allocator_->Initialize();
3131
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003132 // To handle both internal and externally created port allocator, we will
3133 // enable BUNDLE here.
3134 int portallocator_flags = port_allocator_->flags();
3135 portallocator_flags |= cricket::PORTALLOCATOR_ENABLE_SHARED_SOCKET |
zhihuangb09b3f92017-03-07 14:40:51 -08003136 cricket::PORTALLOCATOR_ENABLE_IPV6 |
3137 cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI;
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003138 // If the disable-IPv6 flag was specified, we'll not override it
3139 // by experiment.
3140 if (configuration.disable_ipv6) {
3141 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
sprangc1b57a12017-02-28 08:50:47 -08003142 } else if (webrtc::field_trial::FindFullName("WebRTC-IPv6Default")
3143 .find("Disabled") == 0) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003144 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
3145 }
3146
zhihuangb09b3f92017-03-07 14:40:51 -08003147 if (configuration.disable_ipv6_on_wifi) {
3148 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI);
Mirko Bonadei675513b2017-11-09 11:09:25 +01003149 RTC_LOG(LS_INFO) << "IPv6 candidates on Wi-Fi are disabled.";
zhihuangb09b3f92017-03-07 14:40:51 -08003150 }
3151
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003152 if (configuration.tcp_candidate_policy == kTcpCandidatePolicyDisabled) {
3153 portallocator_flags |= cricket::PORTALLOCATOR_DISABLE_TCP;
Mirko Bonadei675513b2017-11-09 11:09:25 +01003154 RTC_LOG(LS_INFO) << "TCP candidates are disabled.";
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003155 }
3156
honghaiz60347052016-05-31 18:29:12 -07003157 if (configuration.candidate_network_policy ==
3158 kCandidateNetworkPolicyLowCost) {
3159 portallocator_flags |= cricket::PORTALLOCATOR_DISABLE_COSTLY_NETWORKS;
Mirko Bonadei675513b2017-11-09 11:09:25 +01003160 RTC_LOG(LS_INFO) << "Do not gather candidates on high-cost networks";
honghaiz60347052016-05-31 18:29:12 -07003161 }
3162
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003163 port_allocator_->set_flags(portallocator_flags);
3164 // No step delay is used while allocating ports.
3165 port_allocator_->set_step_delay(cricket::kMinimumStepDelay);
3166 port_allocator_->set_candidate_filter(
3167 ConvertIceTransportTypeToCandidateFilter(configuration.type));
deadbeefd21eab32017-07-26 16:50:11 -07003168 port_allocator_->set_max_ipv6_networks(configuration.max_ipv6_networks);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003169
3170 // Call this last since it may create pooled allocator sessions using the
3171 // properties set above.
3172 port_allocator_->SetConfiguration(stun_servers, turn_servers,
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -07003173 configuration.ice_candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02003174 configuration.prune_turn_ports,
3175 configuration.turn_customizer);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003176 return true;
3177}
3178
deadbeef91dd5672016-05-18 16:55:30 -07003179bool PeerConnection::ReconfigurePortAllocator_n(
deadbeef293e9262017-01-11 12:28:30 -08003180 const cricket::ServerAddresses& stun_servers,
3181 const std::vector<cricket::RelayServerConfig>& turn_servers,
3182 IceTransportsType type,
3183 int candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02003184 bool prune_turn_ports,
3185 webrtc::TurnCustomizer* turn_customizer) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003186 port_allocator_->set_candidate_filter(
deadbeef293e9262017-01-11 12:28:30 -08003187 ConvertIceTransportTypeToCandidateFilter(type));
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003188 // Call this last since it may create pooled allocator sessions using the
3189 // candidate filter set above.
deadbeef6de92f92016-12-12 18:49:32 -08003190 return port_allocator_->SetConfiguration(
Jonas Orelandbdcee282017-10-10 14:01:40 +02003191 stun_servers, turn_servers, candidate_pool_size, prune_turn_ports,
3192 turn_customizer);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003193}
3194
Steve Antonba818672017-11-06 10:21:57 -08003195cricket::ChannelManager* PeerConnection::channel_manager() const {
3196 return factory_->channel_manager();
3197}
3198
3199MetricsObserverInterface* PeerConnection::metrics_observer() const {
3200 return uma_observer_;
3201}
3202
Elad Alon99c3fe52017-10-13 16:29:40 +02003203bool PeerConnection::StartRtcEventLog_w(
Zhi Huang33c5c7f2017-11-17 20:59:29 +00003204 std::unique_ptr<RtcEventLogOutput> output) {
zhihuang77985012017-02-07 15:45:16 -08003205 if (!event_log_) {
3206 return false;
3207 }
Zhi Huang33c5c7f2017-11-17 20:59:29 +00003208 return event_log_->StartLogging(std::move(output));
ivoc14d5dbe2016-07-04 07:06:55 -07003209}
3210
3211void PeerConnection::StopRtcEventLog_w() {
zhihuang77985012017-02-07 15:45:16 -08003212 if (event_log_) {
3213 event_log_->StopLogging();
3214 }
ivoc14d5dbe2016-07-04 07:06:55 -07003215}
nisseeaabdf62017-05-05 02:23:02 -07003216
Steve Anton75737c02017-11-06 10:37:17 -08003217cricket::BaseChannel* PeerConnection::GetChannel(
3218 const std::string& content_name) {
3219 if (voice_channel() && voice_channel()->content_name() == content_name) {
3220 return voice_channel();
3221 }
3222 if (video_channel() && video_channel()->content_name() == content_name) {
3223 return video_channel();
3224 }
3225 if (rtp_data_channel() &&
3226 rtp_data_channel()->content_name() == content_name) {
3227 return rtp_data_channel();
3228 }
3229 return nullptr;
3230}
3231
3232bool PeerConnection::GetSctpSslRole(rtc::SSLRole* role) {
3233 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003234 RTC_LOG(LS_INFO)
3235 << "Local and Remote descriptions must be applied to get the "
3236 << "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08003237 return false;
3238 }
3239 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003240 RTC_LOG(LS_INFO) << "Non-rejected SCTP m= section is needed to get the "
3241 << "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08003242 return false;
3243 }
3244
3245 return transport_controller_->GetSslRole(*sctp_transport_name_, role);
3246}
3247
3248bool PeerConnection::GetSslRole(const std::string& content_name,
3249 rtc::SSLRole* role) {
3250 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003251 RTC_LOG(LS_INFO)
3252 << "Local and Remote descriptions must be applied to get the "
3253 << "SSL Role of the session.";
Steve Anton75737c02017-11-06 10:37:17 -08003254 return false;
3255 }
3256
3257 return transport_controller_->GetSslRole(GetTransportName(content_name),
3258 role);
3259}
3260
Steve Anton75737c02017-11-06 10:37:17 -08003261bool PeerConnection::SetLocalDescription(
3262 std::unique_ptr<SessionDescriptionInterface> desc,
3263 std::string* err_desc) {
3264 RTC_DCHECK(signaling_thread()->IsCurrent());
3265
3266 // Validate SDP.
3267 if (!ValidateSessionDescription(desc.get(), cricket::CS_LOCAL, err_desc)) {
3268 return false;
3269 }
3270
3271 // Update the initial_offerer flag if this session is the initial_offerer.
3272 Action action = GetAction(desc->type());
3273 if (!initial_offerer_.has_value()) {
3274 initial_offerer_.emplace(action == kOffer);
3275 if (*initial_offerer_) {
3276 transport_controller_->SetIceRole(cricket::ICEROLE_CONTROLLING);
3277 } else {
3278 transport_controller_->SetIceRole(cricket::ICEROLE_CONTROLLED);
3279 }
3280 }
3281
3282 if (action == kAnswer) {
3283 current_local_description_ = std::move(desc);
3284 pending_local_description_ = nullptr;
3285 current_remote_description_ = std::move(pending_remote_description_);
3286 } else {
3287 pending_local_description_ = std::move(desc);
3288 }
3289
3290 // Transport and Media channels will be created only when offer is set.
3291 if (action == kOffer && !CreateChannels(local_description()->description())) {
3292 // TODO(mallinath) - Handle CreateChannel failure, as new local description
3293 // is applied. Restore back to old description.
3294 return BadLocalSdp(local_description()->type(), kCreateChannelFailed,
3295 err_desc);
3296 }
3297
3298 // Remove unused channels if MediaContentDescription is rejected.
3299 RemoveUnusedChannels(local_description()->description());
3300
3301 if (!UpdateSessionState(action, cricket::CS_LOCAL, err_desc)) {
3302 return false;
3303 }
3304 if (remote_description()) {
3305 // Now that we have a local description, we can push down remote candidates.
3306 UseCandidatesInSessionDescription(remote_description());
3307 }
3308
3309 pending_ice_restarts_.clear();
3310 if (error() != ERROR_NONE) {
3311 return BadLocalSdp(local_description()->type(), GetSessionErrorMsg(),
3312 err_desc);
3313 }
3314 return true;
3315}
3316
3317bool PeerConnection::SetRemoteDescription(
3318 std::unique_ptr<SessionDescriptionInterface> desc,
3319 std::string* err_desc) {
3320 RTC_DCHECK(signaling_thread()->IsCurrent());
3321
3322 // Validate SDP.
3323 if (!ValidateSessionDescription(desc.get(), cricket::CS_REMOTE, err_desc)) {
3324 return false;
3325 }
3326
3327 // Hold this pointer so candidates can be copied to it later in the method.
3328 SessionDescriptionInterface* desc_ptr = desc.get();
3329
3330 const SessionDescriptionInterface* old_remote_description =
3331 remote_description();
3332 // Grab ownership of the description being replaced for the remainder of this
3333 // method, since it's used below as |old_remote_description|.
3334 std::unique_ptr<SessionDescriptionInterface> replaced_remote_description;
3335 Action action = GetAction(desc->type());
3336 if (action == kAnswer) {
3337 replaced_remote_description = pending_remote_description_
3338 ? std::move(pending_remote_description_)
3339 : std::move(current_remote_description_);
3340 current_remote_description_ = std::move(desc);
3341 pending_remote_description_ = nullptr;
3342 current_local_description_ = std::move(pending_local_description_);
3343 } else {
3344 replaced_remote_description = std::move(pending_remote_description_);
3345 pending_remote_description_ = std::move(desc);
3346 }
3347
3348 // Transport and Media channels will be created only when offer is set.
3349 if (action == kOffer &&
3350 !CreateChannels(remote_description()->description())) {
3351 // TODO(mallinath) - Handle CreateChannel failure, as new local description
3352 // is applied. Restore back to old description.
3353 return BadRemoteSdp(remote_description()->type(), kCreateChannelFailed,
3354 err_desc);
3355 }
3356
3357 // Remove unused channels if MediaContentDescription is rejected.
3358 RemoveUnusedChannels(remote_description()->description());
3359
3360 // NOTE: Candidates allocation will be initiated only when SetLocalDescription
3361 // is called.
3362 if (!UpdateSessionState(action, cricket::CS_REMOTE, err_desc)) {
3363 return false;
3364 }
3365
3366 if (local_description() &&
3367 !UseCandidatesInSessionDescription(remote_description())) {
3368 return BadRemoteSdp(remote_description()->type(), kInvalidCandidates,
3369 err_desc);
3370 }
3371
3372 if (old_remote_description) {
3373 for (const cricket::ContentInfo& content :
3374 old_remote_description->description()->contents()) {
3375 // Check if this new SessionDescription contains new ICE ufrag and
3376 // password that indicates the remote peer requests an ICE restart.
3377 // TODO(deadbeef): When we start storing both the current and pending
3378 // remote description, this should reset pending_ice_restarts and compare
3379 // against the current description.
3380 if (CheckForRemoteIceRestart(old_remote_description, remote_description(),
3381 content.name)) {
3382 if (action == kOffer) {
3383 pending_ice_restarts_.insert(content.name);
3384 }
3385 } else {
3386 // We retain all received candidates only if ICE is not restarted.
3387 // When ICE is restarted, all previous candidates belong to an old
3388 // generation and should not be kept.
3389 // TODO(deadbeef): This goes against the W3C spec which says the remote
3390 // description should only contain candidates from the last set remote
3391 // description plus any candidates added since then. We should remove
3392 // this once we're sure it won't break anything.
3393 WebRtcSessionDescriptionFactory::CopyCandidatesFromSessionDescription(
3394 old_remote_description, content.name, desc_ptr);
3395 }
3396 }
3397 }
3398
3399 if (error() != ERROR_NONE) {
3400 return BadRemoteSdp(remote_description()->type(), GetSessionErrorMsg(),
3401 err_desc);
3402 }
3403
3404 // Set the the ICE connection state to connecting since the connection may
3405 // become writable with peer reflexive candidates before any remote candidate
3406 // is signaled.
3407 // TODO(pthatcher): This is a short-term solution for crbug/446908. A real fix
3408 // is to have a new signal the indicates a change in checking state from the
3409 // transport and expose a new checking() member from transport that can be
3410 // read to determine the current checking state. The existing SignalConnecting
3411 // actually means "gathering candidates", so cannot be be used here.
3412 if (remote_description()->type() != SessionDescriptionInterface::kOffer &&
3413 ice_connection_state() == PeerConnectionInterface::kIceConnectionNew) {
3414 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
3415 }
3416 return true;
3417}
3418
3419// TODO(steveanton): Eventually it'd be nice to store the channels as a single
3420// vector of BaseChannel pointers instead of separate voice and video channel
3421// vectors. At that point, this will become a simple getter.
3422std::vector<cricket::BaseChannel*> PeerConnection::Channels() const {
3423 std::vector<cricket::BaseChannel*> channels;
Steve Anton4171afb2017-11-20 10:20:22 -08003424 if (voice_channel()) {
3425 channels.push_back(voice_channel());
3426 }
3427 if (video_channel()) {
3428 channels.push_back(video_channel());
3429 }
Steve Anton75737c02017-11-06 10:37:17 -08003430 if (rtp_data_channel_) {
3431 channels.push_back(rtp_data_channel_);
3432 }
3433 return channels;
3434}
3435
3436void PeerConnection::SetError(Error error, const std::string& error_desc) {
3437 RTC_DCHECK(signaling_thread()->IsCurrent());
3438 if (error != error_) {
3439 error_ = error;
3440 error_desc_ = error_desc;
3441 }
3442}
3443
3444bool PeerConnection::UpdateSessionState(Action action,
3445 cricket::ContentSource source,
3446 std::string* err_desc) {
3447 RTC_DCHECK(signaling_thread()->IsCurrent());
3448
3449 // If there's already a pending error then no state transition should happen.
3450 // But all call-sites should be verifying this before calling us!
3451 RTC_DCHECK(error() == ERROR_NONE);
3452 std::string td_err;
3453 if (action == kOffer) {
3454 if (!PushdownTransportDescription(source, cricket::CA_OFFER, &td_err)) {
3455 return BadOfferSdp(source, MakeTdErrorString(td_err), err_desc);
3456 }
3457 ChangeSignalingState(source == cricket::CS_LOCAL
3458 ? PeerConnectionInterface::kHaveLocalOffer
3459 : PeerConnectionInterface::kHaveRemoteOffer);
3460 if (!PushdownMediaDescription(cricket::CA_OFFER, source, err_desc)) {
3461 SetError(ERROR_CONTENT, *err_desc);
3462 }
3463 if (error() != ERROR_NONE) {
3464 return BadOfferSdp(source, GetSessionErrorMsg(), err_desc);
3465 }
3466 } else if (action == kPrAnswer) {
3467 if (!PushdownTransportDescription(source, cricket::CA_PRANSWER, &td_err)) {
3468 return BadPranswerSdp(source, MakeTdErrorString(td_err), err_desc);
3469 }
3470 EnableChannels();
3471 ChangeSignalingState(source == cricket::CS_LOCAL
3472 ? PeerConnectionInterface::kHaveLocalPrAnswer
3473 : PeerConnectionInterface::kHaveRemotePrAnswer);
3474 if (!PushdownMediaDescription(cricket::CA_PRANSWER, source, err_desc)) {
3475 SetError(ERROR_CONTENT, *err_desc);
3476 }
3477 if (error() != ERROR_NONE) {
3478 return BadPranswerSdp(source, GetSessionErrorMsg(), err_desc);
3479 }
3480 } else if (action == kAnswer) {
3481 const cricket::ContentGroup* local_bundle =
3482 local_description()->description()->GetGroupByName(
3483 cricket::GROUP_TYPE_BUNDLE);
3484 const cricket::ContentGroup* remote_bundle =
3485 remote_description()->description()->GetGroupByName(
3486 cricket::GROUP_TYPE_BUNDLE);
3487 if (local_bundle && remote_bundle) {
3488 // The answerer decides the transport to bundle on.
3489 const cricket::ContentGroup* answer_bundle =
3490 (source == cricket::CS_LOCAL ? local_bundle : remote_bundle);
3491 if (!EnableBundle(*answer_bundle)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003492 RTC_LOG(LS_WARNING) << "Failed to enable BUNDLE.";
Steve Anton75737c02017-11-06 10:37:17 -08003493 return BadAnswerSdp(source, kEnableBundleFailed, err_desc);
3494 }
3495 }
3496 // Only push down the transport description after enabling BUNDLE; we don't
3497 // want to push down a description on a transport about to be destroyed.
3498 if (!PushdownTransportDescription(source, cricket::CA_ANSWER, &td_err)) {
3499 return BadAnswerSdp(source, MakeTdErrorString(td_err), err_desc);
3500 }
3501 EnableChannels();
3502 ChangeSignalingState(PeerConnectionInterface::kStable);
3503 if (!PushdownMediaDescription(cricket::CA_ANSWER, source, err_desc)) {
3504 SetError(ERROR_CONTENT, *err_desc);
3505 }
3506 if (error() != ERROR_NONE) {
3507 return BadAnswerSdp(source, GetSessionErrorMsg(), err_desc);
3508 }
3509 }
3510 return true;
3511}
3512
3513PeerConnection::Action PeerConnection::GetAction(const std::string& type) {
3514 if (type == SessionDescriptionInterface::kOffer) {
3515 return PeerConnection::kOffer;
3516 } else if (type == SessionDescriptionInterface::kPrAnswer) {
3517 return PeerConnection::kPrAnswer;
3518 } else if (type == SessionDescriptionInterface::kAnswer) {
3519 return PeerConnection::kAnswer;
3520 }
3521 RTC_NOTREACHED() << "unknown action type";
3522 return PeerConnection::kOffer;
3523}
3524
3525bool PeerConnection::PushdownMediaDescription(cricket::ContentAction action,
3526 cricket::ContentSource source,
3527 std::string* err) {
3528 const SessionDescription* sdesc =
3529 (source == cricket::CS_LOCAL ? local_description() : remote_description())
3530 ->description();
3531 RTC_DCHECK(sdesc);
3532 bool all_success = true;
3533 for (auto* channel : Channels()) {
3534 // TODO(steveanton): Add support for multiple channels of the same type.
3535 const ContentInfo* content_info =
3536 cricket::GetFirstMediaContent(sdesc->contents(), channel->media_type());
3537 if (!content_info) {
3538 continue;
3539 }
3540 const MediaContentDescription* content_desc =
3541 static_cast<const MediaContentDescription*>(content_info->description);
3542 if (content_desc && !content_info->rejected) {
3543 bool success = (source == cricket::CS_LOCAL)
3544 ? channel->SetLocalContent(content_desc, action, err)
3545 : channel->SetRemoteContent(content_desc, action, err);
3546 if (!success) {
3547 all_success = false;
3548 break;
3549 }
3550 }
3551 }
3552 // Need complete offer/answer with an SCTP m= section before starting SCTP,
3553 // according to https://tools.ietf.org/html/draft-ietf-mmusic-sctp-sdp-19
3554 if (sctp_transport_ && local_description() && remote_description() &&
3555 cricket::GetFirstDataContent(local_description()->description()) &&
3556 cricket::GetFirstDataContent(remote_description()->description())) {
3557 all_success &= network_thread()->Invoke<bool>(
3558 RTC_FROM_HERE,
3559 rtc::Bind(&PeerConnection::PushdownSctpParameters_n, this, source));
3560 }
3561 return all_success;
3562}
3563
3564bool PeerConnection::PushdownSctpParameters_n(cricket::ContentSource source) {
3565 RTC_DCHECK(network_thread()->IsCurrent());
3566 RTC_DCHECK(local_description());
3567 RTC_DCHECK(remote_description());
3568 // Apply the SCTP port (which is hidden inside a DataCodec structure...)
3569 // When we support "max-message-size", that would also be pushed down here.
3570 return sctp_transport_->Start(
3571 GetSctpPort(local_description()->description()),
3572 GetSctpPort(remote_description()->description()));
3573}
3574
3575bool PeerConnection::PushdownTransportDescription(cricket::ContentSource source,
3576 cricket::ContentAction action,
3577 std::string* error_desc) {
3578 RTC_DCHECK(signaling_thread()->IsCurrent());
3579
3580 if (source == cricket::CS_LOCAL) {
3581 return PushdownLocalTransportDescription(local_description()->description(),
3582 action, error_desc);
3583 }
3584 return PushdownRemoteTransportDescription(remote_description()->description(),
3585 action, error_desc);
3586}
3587
3588bool PeerConnection::PushdownLocalTransportDescription(
3589 const SessionDescription* sdesc,
3590 cricket::ContentAction action,
3591 std::string* err) {
3592 RTC_DCHECK(signaling_thread()->IsCurrent());
3593
3594 if (!sdesc) {
3595 return false;
3596 }
3597
3598 for (const TransportInfo& tinfo : sdesc->transport_infos()) {
3599 if (!transport_controller_->SetLocalTransportDescription(
3600 tinfo.content_name, tinfo.description, action, err)) {
3601 return false;
3602 }
3603 }
3604
3605 return true;
3606}
3607
3608bool PeerConnection::PushdownRemoteTransportDescription(
3609 const SessionDescription* sdesc,
3610 cricket::ContentAction action,
3611 std::string* err) {
3612 RTC_DCHECK(signaling_thread()->IsCurrent());
3613
3614 if (!sdesc) {
3615 return false;
3616 }
3617
3618 for (const TransportInfo& tinfo : sdesc->transport_infos()) {
3619 if (!transport_controller_->SetRemoteTransportDescription(
3620 tinfo.content_name, tinfo.description, action, err)) {
3621 return false;
3622 }
3623 }
3624
3625 return true;
3626}
3627
3628bool PeerConnection::GetTransportDescription(
3629 const SessionDescription* description,
3630 const std::string& content_name,
3631 cricket::TransportDescription* tdesc) {
3632 if (!description || !tdesc) {
3633 return false;
3634 }
3635 const TransportInfo* transport_info =
3636 description->GetTransportInfoByName(content_name);
3637 if (!transport_info) {
3638 return false;
3639 }
3640 *tdesc = transport_info->description;
3641 return true;
3642}
3643
3644bool PeerConnection::EnableBundle(const cricket::ContentGroup& bundle) {
3645 const std::string* first_content_name = bundle.FirstContentName();
3646 if (!first_content_name) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003647 RTC_LOG(LS_WARNING) << "Tried to BUNDLE with no contents.";
Steve Anton75737c02017-11-06 10:37:17 -08003648 return false;
3649 }
3650 const std::string& transport_name = *first_content_name;
3651
3652 auto maybe_set_transport = [this, bundle,
3653 transport_name](cricket::BaseChannel* ch) {
3654 if (!ch || !bundle.HasContentName(ch->content_name())) {
3655 return true;
3656 }
3657
3658 std::string old_transport_name = ch->transport_name();
3659 if (old_transport_name == transport_name) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003660 RTC_LOG(LS_INFO) << "BUNDLE already enabled for " << ch->content_name()
3661 << " on " << transport_name << ".";
Steve Anton75737c02017-11-06 10:37:17 -08003662 return true;
3663 }
3664
3665 cricket::DtlsTransportInternal* rtp_dtls_transport =
3666 transport_controller_->CreateDtlsTransport(
3667 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
3668 bool need_rtcp = (ch->rtcp_dtls_transport() != nullptr);
3669 cricket::DtlsTransportInternal* rtcp_dtls_transport = nullptr;
3670 if (need_rtcp) {
3671 rtcp_dtls_transport = transport_controller_->CreateDtlsTransport(
3672 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
3673 }
3674
3675 ch->SetTransports(rtp_dtls_transport, rtcp_dtls_transport);
Mirko Bonadei675513b2017-11-09 11:09:25 +01003676 RTC_LOG(LS_INFO) << "Enabled BUNDLE for " << ch->content_name() << " on "
3677 << transport_name << ".";
Steve Anton75737c02017-11-06 10:37:17 -08003678 transport_controller_->DestroyDtlsTransport(
3679 old_transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
3680 // If the channel needs rtcp, it means that the channel used to have a
3681 // rtcp transport which needs to be deleted now.
3682 if (need_rtcp) {
3683 transport_controller_->DestroyDtlsTransport(
3684 old_transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
3685 }
3686 return true;
3687 };
3688
3689 if (!maybe_set_transport(voice_channel()) ||
3690 !maybe_set_transport(video_channel()) ||
3691 !maybe_set_transport(rtp_data_channel())) {
3692 return false;
3693 }
3694 // For SCTP, transport creation/deletion happens here instead of in the
3695 // object itself.
3696 if (sctp_transport_) {
3697 RTC_DCHECK(sctp_transport_name_);
3698 RTC_DCHECK(sctp_content_name_);
3699 if (transport_name != *sctp_transport_name_ &&
3700 bundle.HasContentName(*sctp_content_name_)) {
3701 network_thread()->Invoke<void>(
3702 RTC_FROM_HERE, rtc::Bind(&PeerConnection::ChangeSctpTransport_n, this,
3703 transport_name));
3704 }
3705 }
3706
3707 return true;
3708}
3709
Steve Anton75737c02017-11-06 10:37:17 -08003710cricket::IceConfig PeerConnection::ParseIceConfig(
3711 const PeerConnectionInterface::RTCConfiguration& config) const {
3712 cricket::ContinualGatheringPolicy gathering_policy;
3713 // TODO(honghaiz): Add the third continual gathering policy in
3714 // PeerConnectionInterface and map it to GATHER_CONTINUALLY_AND_RECOVER.
3715 switch (config.continual_gathering_policy) {
3716 case PeerConnectionInterface::GATHER_ONCE:
3717 gathering_policy = cricket::GATHER_ONCE;
3718 break;
3719 case PeerConnectionInterface::GATHER_CONTINUALLY:
3720 gathering_policy = cricket::GATHER_CONTINUALLY;
3721 break;
3722 default:
3723 RTC_NOTREACHED();
3724 gathering_policy = cricket::GATHER_ONCE;
3725 }
3726 cricket::IceConfig ice_config;
3727 ice_config.receiving_timeout = config.ice_connection_receiving_timeout;
3728 ice_config.prioritize_most_likely_candidate_pairs =
3729 config.prioritize_most_likely_ice_candidate_pairs;
3730 ice_config.backup_connection_ping_interval =
3731 config.ice_backup_candidate_pair_ping_interval;
3732 ice_config.continual_gathering_policy = gathering_policy;
3733 ice_config.presume_writable_when_fully_relayed =
3734 config.presume_writable_when_fully_relayed;
3735 ice_config.ice_check_min_interval = config.ice_check_min_interval;
3736 ice_config.regather_all_networks_interval_range =
3737 config.ice_regather_interval_range;
3738 return ice_config;
3739}
3740
Steve Anton75737c02017-11-06 10:37:17 -08003741bool PeerConnection::GetLocalTrackIdBySsrc(uint32_t ssrc,
3742 std::string* track_id) {
3743 if (!local_description()) {
3744 return false;
3745 }
3746 return webrtc::GetTrackIdBySsrc(local_description()->description(), ssrc,
3747 track_id);
3748}
3749
3750bool PeerConnection::GetRemoteTrackIdBySsrc(uint32_t ssrc,
3751 std::string* track_id) {
3752 if (!remote_description()) {
3753 return false;
3754 }
3755 return webrtc::GetTrackIdBySsrc(remote_description()->description(), ssrc,
3756 track_id);
3757}
3758
3759bool PeerConnection::SendData(const cricket::SendDataParams& params,
3760 const rtc::CopyOnWriteBuffer& payload,
3761 cricket::SendDataResult* result) {
3762 if (!rtp_data_channel_ && !sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003763 RTC_LOG(LS_ERROR) << "SendData called when rtp_data_channel_ "
3764 << "and sctp_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08003765 return false;
3766 }
3767 return rtp_data_channel_
3768 ? rtp_data_channel_->SendData(params, payload, result)
3769 : network_thread()->Invoke<bool>(
3770 RTC_FROM_HERE,
3771 Bind(&cricket::SctpTransportInternal::SendData,
3772 sctp_transport_.get(), params, payload, result));
3773}
3774
3775bool PeerConnection::ConnectDataChannel(DataChannel* webrtc_data_channel) {
3776 if (!rtp_data_channel_ && !sctp_transport_) {
3777 // Don't log an error here, because DataChannels are expected to call
3778 // ConnectDataChannel in this state. It's the only way to initially tell
3779 // whether or not the underlying transport is ready.
3780 return false;
3781 }
3782 if (rtp_data_channel_) {
3783 rtp_data_channel_->SignalReadyToSendData.connect(
3784 webrtc_data_channel, &DataChannel::OnChannelReady);
3785 rtp_data_channel_->SignalDataReceived.connect(webrtc_data_channel,
3786 &DataChannel::OnDataReceived);
3787 } else {
3788 SignalSctpReadyToSendData.connect(webrtc_data_channel,
3789 &DataChannel::OnChannelReady);
3790 SignalSctpDataReceived.connect(webrtc_data_channel,
3791 &DataChannel::OnDataReceived);
3792 SignalSctpStreamClosedRemotely.connect(
3793 webrtc_data_channel, &DataChannel::OnStreamClosedRemotely);
3794 }
3795 return true;
3796}
3797
3798void PeerConnection::DisconnectDataChannel(DataChannel* webrtc_data_channel) {
3799 if (!rtp_data_channel_ && !sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003800 RTC_LOG(LS_ERROR)
3801 << "DisconnectDataChannel called when rtp_data_channel_ and "
3802 "sctp_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08003803 return;
3804 }
3805 if (rtp_data_channel_) {
3806 rtp_data_channel_->SignalReadyToSendData.disconnect(webrtc_data_channel);
3807 rtp_data_channel_->SignalDataReceived.disconnect(webrtc_data_channel);
3808 } else {
3809 SignalSctpReadyToSendData.disconnect(webrtc_data_channel);
3810 SignalSctpDataReceived.disconnect(webrtc_data_channel);
3811 SignalSctpStreamClosedRemotely.disconnect(webrtc_data_channel);
3812 }
3813}
3814
3815void PeerConnection::AddSctpDataStream(int sid) {
3816 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003817 RTC_LOG(LS_ERROR)
3818 << "AddSctpDataStream called when sctp_transport_ is NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08003819 return;
3820 }
3821 network_thread()->Invoke<void>(
3822 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::OpenStream,
3823 sctp_transport_.get(), sid));
3824}
3825
3826void PeerConnection::RemoveSctpDataStream(int sid) {
3827 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003828 RTC_LOG(LS_ERROR) << "RemoveSctpDataStream called when sctp_transport_ is "
3829 << "NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08003830 return;
3831 }
3832 network_thread()->Invoke<void>(
3833 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::ResetStream,
3834 sctp_transport_.get(), sid));
3835}
3836
3837bool PeerConnection::ReadyToSendData() const {
3838 return (rtp_data_channel_ && rtp_data_channel_->ready_to_send_data()) ||
3839 sctp_ready_to_send_data_;
3840}
3841
3842std::unique_ptr<SessionStats> PeerConnection::GetSessionStats_s() {
3843 RTC_DCHECK(signaling_thread()->IsCurrent());
3844 ChannelNamePairs channel_name_pairs;
3845 if (voice_channel()) {
3846 channel_name_pairs.voice = rtc::Optional<ChannelNamePair>(ChannelNamePair(
3847 voice_channel()->content_name(), voice_channel()->transport_name()));
3848 }
3849 if (video_channel()) {
3850 channel_name_pairs.video = rtc::Optional<ChannelNamePair>(ChannelNamePair(
3851 video_channel()->content_name(), video_channel()->transport_name()));
3852 }
3853 if (rtp_data_channel()) {
3854 channel_name_pairs.data = rtc::Optional<ChannelNamePair>(
3855 ChannelNamePair(rtp_data_channel()->content_name(),
3856 rtp_data_channel()->transport_name()));
3857 }
3858 if (sctp_transport_) {
3859 RTC_DCHECK(sctp_content_name_);
3860 RTC_DCHECK(sctp_transport_name_);
3861 channel_name_pairs.data = rtc::Optional<ChannelNamePair>(
3862 ChannelNamePair(*sctp_content_name_, *sctp_transport_name_));
3863 }
3864 return GetSessionStats(channel_name_pairs);
3865}
3866
3867std::unique_ptr<SessionStats> PeerConnection::GetSessionStats(
3868 const ChannelNamePairs& channel_name_pairs) {
3869 if (network_thread()->IsCurrent()) {
3870 return GetSessionStats_n(channel_name_pairs);
3871 }
3872 return network_thread()->Invoke<std::unique_ptr<SessionStats>>(
3873 RTC_FROM_HERE,
3874 rtc::Bind(&PeerConnection::GetSessionStats_n, this, channel_name_pairs));
3875}
3876
3877bool PeerConnection::GetLocalCertificate(
3878 const std::string& transport_name,
3879 rtc::scoped_refptr<rtc::RTCCertificate>* certificate) {
3880 return transport_controller_->GetLocalCertificate(transport_name,
3881 certificate);
3882}
3883
3884std::unique_ptr<rtc::SSLCertificate> PeerConnection::GetRemoteSSLCertificate(
3885 const std::string& transport_name) {
3886 return transport_controller_->GetRemoteSSLCertificate(transport_name);
3887}
3888
3889cricket::DataChannelType PeerConnection::data_channel_type() const {
3890 return data_channel_type_;
3891}
3892
3893bool PeerConnection::IceRestartPending(const std::string& content_name) const {
3894 return pending_ice_restarts_.find(content_name) !=
3895 pending_ice_restarts_.end();
3896}
3897
Steve Anton75737c02017-11-06 10:37:17 -08003898bool PeerConnection::NeedsIceRestart(const std::string& content_name) const {
3899 return transport_controller_->NeedsIceRestart(content_name);
3900}
3901
3902void PeerConnection::OnCertificateReady(
3903 const rtc::scoped_refptr<rtc::RTCCertificate>& certificate) {
3904 transport_controller_->SetLocalCertificate(certificate);
3905}
3906
3907void PeerConnection::OnDtlsSrtpSetupFailure(cricket::BaseChannel*, bool rtcp) {
3908 SetError(ERROR_TRANSPORT,
3909 rtcp ? kDtlsSrtpSetupFailureRtcp : kDtlsSrtpSetupFailureRtp);
3910}
3911
3912void PeerConnection::OnTransportControllerConnectionState(
3913 cricket::IceConnectionState state) {
3914 switch (state) {
3915 case cricket::kIceConnectionConnecting:
3916 // If the current state is Connected or Completed, then there were
3917 // writable channels but now there are not, so the next state must
3918 // be Disconnected.
3919 // kIceConnectionConnecting is currently used as the default,
3920 // un-connected state by the TransportController, so its only use is
3921 // detecting disconnections.
3922 if (ice_connection_state_ ==
3923 PeerConnectionInterface::kIceConnectionConnected ||
3924 ice_connection_state_ ==
3925 PeerConnectionInterface::kIceConnectionCompleted) {
3926 SetIceConnectionState(
3927 PeerConnectionInterface::kIceConnectionDisconnected);
3928 }
3929 break;
3930 case cricket::kIceConnectionFailed:
3931 SetIceConnectionState(PeerConnectionInterface::kIceConnectionFailed);
3932 break;
3933 case cricket::kIceConnectionConnected:
Mirko Bonadei675513b2017-11-09 11:09:25 +01003934 RTC_LOG(LS_INFO) << "Changing to ICE connected state because "
3935 << "all transports are writable.";
Steve Anton75737c02017-11-06 10:37:17 -08003936 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
3937 break;
3938 case cricket::kIceConnectionCompleted:
Mirko Bonadei675513b2017-11-09 11:09:25 +01003939 RTC_LOG(LS_INFO) << "Changing to ICE completed state because "
3940 << "all transports are complete.";
Steve Anton75737c02017-11-06 10:37:17 -08003941 if (ice_connection_state_ !=
3942 PeerConnectionInterface::kIceConnectionConnected) {
3943 // If jumping directly from "checking" to "connected",
3944 // signal "connected" first.
3945 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
3946 }
3947 SetIceConnectionState(PeerConnectionInterface::kIceConnectionCompleted);
3948 if (metrics_observer()) {
3949 ReportTransportStats();
3950 }
3951 break;
3952 default:
3953 RTC_NOTREACHED();
3954 }
3955}
3956
3957void PeerConnection::OnTransportControllerCandidatesGathered(
3958 const std::string& transport_name,
3959 const cricket::Candidates& candidates) {
3960 RTC_DCHECK(signaling_thread()->IsCurrent());
3961 int sdp_mline_index;
3962 if (!GetLocalCandidateMediaIndex(transport_name, &sdp_mline_index)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003963 RTC_LOG(LS_ERROR)
3964 << "OnTransportControllerCandidatesGathered: content name "
3965 << transport_name << " not found";
Steve Anton75737c02017-11-06 10:37:17 -08003966 return;
3967 }
3968
3969 for (cricket::Candidates::const_iterator citer = candidates.begin();
3970 citer != candidates.end(); ++citer) {
3971 // Use transport_name as the candidate media id.
3972 std::unique_ptr<JsepIceCandidate> candidate(
3973 new JsepIceCandidate(transport_name, sdp_mline_index, *citer));
3974 if (local_description()) {
3975 mutable_local_description()->AddCandidate(candidate.get());
3976 }
3977 OnIceCandidate(std::move(candidate));
3978 }
3979}
3980
3981void PeerConnection::OnTransportControllerCandidatesRemoved(
3982 const std::vector<cricket::Candidate>& candidates) {
3983 RTC_DCHECK(signaling_thread()->IsCurrent());
3984 // Sanity check.
3985 for (const cricket::Candidate& candidate : candidates) {
3986 if (candidate.transport_name().empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003987 RTC_LOG(LS_ERROR) << "OnTransportControllerCandidatesRemoved: "
3988 << "empty content name in candidate "
3989 << candidate.ToString();
Steve Anton75737c02017-11-06 10:37:17 -08003990 return;
3991 }
3992 }
3993
3994 if (local_description()) {
3995 mutable_local_description()->RemoveCandidates(candidates);
3996 }
3997 OnIceCandidatesRemoved(candidates);
3998}
3999
4000void PeerConnection::OnTransportControllerDtlsHandshakeError(
4001 rtc::SSLHandshakeError error) {
4002 if (metrics_observer()) {
4003 metrics_observer()->IncrementEnumCounter(
4004 webrtc::kEnumCounterDtlsHandshakeError, static_cast<int>(error),
4005 static_cast<int>(rtc::SSLHandshakeError::MAX_VALUE));
4006 }
4007}
4008
4009// Enabling voice and video (and RTP data) channels.
4010void PeerConnection::EnableChannels() {
Steve Anton4171afb2017-11-20 10:20:22 -08004011 if (voice_channel() && !voice_channel()->enabled()) {
4012 voice_channel()->Enable(true);
Steve Anton75737c02017-11-06 10:37:17 -08004013 }
4014
Steve Anton4171afb2017-11-20 10:20:22 -08004015 if (video_channel() && !video_channel()->enabled()) {
4016 video_channel()->Enable(true);
Steve Anton75737c02017-11-06 10:37:17 -08004017 }
4018
Steve Anton4171afb2017-11-20 10:20:22 -08004019 if (rtp_data_channel_ && !rtp_data_channel_->enabled()) {
Steve Anton75737c02017-11-06 10:37:17 -08004020 rtp_data_channel_->Enable(true);
Steve Anton4171afb2017-11-20 10:20:22 -08004021 }
Steve Anton75737c02017-11-06 10:37:17 -08004022}
4023
4024// Returns the media index for a local ice candidate given the content name.
4025bool PeerConnection::GetLocalCandidateMediaIndex(
4026 const std::string& content_name,
4027 int* sdp_mline_index) {
4028 if (!local_description() || !sdp_mline_index) {
4029 return false;
4030 }
4031
4032 bool content_found = false;
4033 const ContentInfos& contents = local_description()->description()->contents();
4034 for (size_t index = 0; index < contents.size(); ++index) {
4035 if (contents[index].name == content_name) {
4036 *sdp_mline_index = static_cast<int>(index);
4037 content_found = true;
4038 break;
4039 }
4040 }
4041 return content_found;
4042}
4043
4044bool PeerConnection::UseCandidatesInSessionDescription(
4045 const SessionDescriptionInterface* remote_desc) {
4046 if (!remote_desc) {
4047 return true;
4048 }
4049 bool ret = true;
4050
4051 for (size_t m = 0; m < remote_desc->number_of_mediasections(); ++m) {
4052 const IceCandidateCollection* candidates = remote_desc->candidates(m);
4053 for (size_t n = 0; n < candidates->count(); ++n) {
4054 const IceCandidateInterface* candidate = candidates->at(n);
4055 bool valid = false;
4056 if (!ReadyToUseRemoteCandidate(candidate, remote_desc, &valid)) {
4057 if (valid) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004058 RTC_LOG(LS_INFO)
4059 << "UseCandidatesInSessionDescription: Not ready to use "
4060 << "candidate.";
Steve Anton75737c02017-11-06 10:37:17 -08004061 }
4062 continue;
4063 }
4064 ret = UseCandidate(candidate);
4065 if (!ret) {
4066 break;
4067 }
4068 }
4069 }
4070 return ret;
4071}
4072
4073bool PeerConnection::UseCandidate(const IceCandidateInterface* candidate) {
4074 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
4075 size_t remote_content_size =
4076 remote_description()->description()->contents().size();
4077 if (mediacontent_index >= remote_content_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004078 RTC_LOG(LS_ERROR) << "UseCandidate: Invalid candidate media index.";
Steve Anton75737c02017-11-06 10:37:17 -08004079 return false;
4080 }
4081
4082 cricket::ContentInfo content =
4083 remote_description()->description()->contents()[mediacontent_index];
4084 std::vector<cricket::Candidate> candidates;
4085 candidates.push_back(candidate->candidate());
4086 // Invoking BaseSession method to handle remote candidates.
4087 std::string error;
4088 if (transport_controller_->AddRemoteCandidates(content.name, candidates,
4089 &error)) {
4090 // Candidates successfully submitted for checking.
4091 if (ice_connection_state_ == PeerConnectionInterface::kIceConnectionNew ||
4092 ice_connection_state_ ==
4093 PeerConnectionInterface::kIceConnectionDisconnected) {
4094 // If state is New, then the session has just gotten its first remote ICE
4095 // candidates, so go to Checking.
4096 // If state is Disconnected, the session is re-using old candidates or
4097 // receiving additional ones, so go to Checking.
4098 // If state is Connected, stay Connected.
4099 // TODO(bemasc): If state is Connected, and the new candidates are for a
4100 // newly added transport, then the state actually _should_ move to
4101 // checking. Add a way to distinguish that case.
4102 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
4103 }
4104 // TODO(bemasc): If state is Completed, go back to Connected.
4105 } else {
4106 if (!error.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004107 RTC_LOG(LS_WARNING) << error;
Steve Anton75737c02017-11-06 10:37:17 -08004108 }
4109 }
4110 return true;
4111}
4112
4113void PeerConnection::RemoveUnusedChannels(const SessionDescription* desc) {
4114 // TODO(steveanton): Add support for multiple audio/video channels.
4115 // Destroy video channel first since it may have a pointer to the
4116 // voice channel.
4117 const cricket::ContentInfo* video_info = cricket::GetFirstVideoContent(desc);
4118 if ((!video_info || video_info->rejected) && video_channel()) {
Steve Anton4171afb2017-11-20 10:20:22 -08004119 DestroyVideoChannel(video_channel());
Steve Anton75737c02017-11-06 10:37:17 -08004120 }
4121
4122 const cricket::ContentInfo* voice_info = cricket::GetFirstAudioContent(desc);
4123 if ((!voice_info || voice_info->rejected) && voice_channel()) {
Steve Anton4171afb2017-11-20 10:20:22 -08004124 DestroyVoiceChannel(voice_channel());
Steve Anton75737c02017-11-06 10:37:17 -08004125 }
4126
4127 const cricket::ContentInfo* data_info = cricket::GetFirstDataContent(desc);
4128 if (!data_info || data_info->rejected) {
4129 if (rtp_data_channel_) {
4130 DestroyDataChannel();
4131 }
4132 if (sctp_transport_) {
4133 OnDataChannelDestroyed();
4134 network_thread()->Invoke<void>(
4135 RTC_FROM_HERE,
4136 rtc::Bind(&PeerConnection::DestroySctpTransport_n, this));
4137 }
4138 }
4139}
4140
4141// Returns the name of the transport channel when BUNDLE is enabled, or nullptr
4142// if the channel is not part of any bundle.
4143const std::string* PeerConnection::GetBundleTransportName(
4144 const cricket::ContentInfo* content,
4145 const cricket::ContentGroup* bundle) {
4146 if (!bundle) {
4147 return nullptr;
4148 }
4149 const std::string* first_content_name = bundle->FirstContentName();
4150 if (!first_content_name) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004151 RTC_LOG(LS_WARNING) << "Tried to BUNDLE with no contents.";
Steve Anton75737c02017-11-06 10:37:17 -08004152 return nullptr;
4153 }
4154 if (!bundle->HasContentName(content->name)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004155 RTC_LOG(LS_WARNING) << content->name << " is not part of any bundle group";
Steve Anton75737c02017-11-06 10:37:17 -08004156 return nullptr;
4157 }
Mirko Bonadei675513b2017-11-09 11:09:25 +01004158 RTC_LOG(LS_INFO) << "Bundling " << content->name << " on "
4159 << *first_content_name;
Steve Anton75737c02017-11-06 10:37:17 -08004160 return first_content_name;
4161}
4162
4163bool PeerConnection::CreateChannels(const SessionDescription* desc) {
4164 // TODO(steveanton): Add support for multiple audio/video channels.
4165 const cricket::ContentGroup* bundle_group = nullptr;
4166 if (configuration_.bundle_policy ==
4167 PeerConnectionInterface::kBundlePolicyMaxBundle) {
4168 bundle_group = desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
4169 if (!bundle_group) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004170 RTC_LOG(LS_WARNING) << "max-bundle specified without BUNDLE specified";
Steve Anton75737c02017-11-06 10:37:17 -08004171 return false;
4172 }
4173 }
4174 // Creating the media channels and transport proxies.
4175 const cricket::ContentInfo* voice = cricket::GetFirstAudioContent(desc);
4176 if (voice && !voice->rejected && !voice_channel()) {
4177 if (!CreateVoiceChannel(voice,
4178 GetBundleTransportName(voice, bundle_group))) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004179 RTC_LOG(LS_ERROR) << "Failed to create voice channel.";
Steve Anton75737c02017-11-06 10:37:17 -08004180 return false;
4181 }
4182 }
4183
4184 const cricket::ContentInfo* video = cricket::GetFirstVideoContent(desc);
4185 if (video && !video->rejected && !video_channel()) {
4186 if (!CreateVideoChannel(video,
4187 GetBundleTransportName(video, bundle_group))) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004188 RTC_LOG(LS_ERROR) << "Failed to create video channel.";
Steve Anton75737c02017-11-06 10:37:17 -08004189 return false;
4190 }
4191 }
4192
4193 const cricket::ContentInfo* data = cricket::GetFirstDataContent(desc);
4194 if (data_channel_type_ != cricket::DCT_NONE && data && !data->rejected &&
4195 !rtp_data_channel_ && !sctp_transport_) {
4196 if (!CreateDataChannel(data, GetBundleTransportName(data, bundle_group))) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004197 RTC_LOG(LS_ERROR) << "Failed to create data channel.";
Steve Anton75737c02017-11-06 10:37:17 -08004198 return false;
4199 }
4200 }
4201
4202 return true;
4203}
4204
Steve Anton4171afb2017-11-20 10:20:22 -08004205// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Anton75737c02017-11-06 10:37:17 -08004206bool PeerConnection::CreateVoiceChannel(const cricket::ContentInfo* content,
4207 const std::string* bundle_transport) {
4208 // TODO(steveanton): Check to see if it's safe to create multiple voice
4209 // channels.
Steve Anton4171afb2017-11-20 10:20:22 -08004210 RTC_DCHECK(!voice_channel());
Steve Anton75737c02017-11-06 10:37:17 -08004211
4212 std::string transport_name =
4213 bundle_transport ? *bundle_transport : content->name;
4214
4215 cricket::DtlsTransportInternal* rtp_dtls_transport =
4216 transport_controller_->CreateDtlsTransport(
4217 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4218 cricket::DtlsTransportInternal* rtcp_dtls_transport = nullptr;
4219 if (configuration_.rtcp_mux_policy !=
4220 PeerConnectionInterface::kRtcpMuxPolicyRequire) {
4221 rtcp_dtls_transport = transport_controller_->CreateDtlsTransport(
4222 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
4223 }
4224
4225 cricket::VoiceChannel* voice_channel = channel_manager()->CreateVoiceChannel(
4226 call_.get(), configuration_.media_config, rtp_dtls_transport,
4227 rtcp_dtls_transport, transport_controller_->signaling_thread(),
4228 content->name, SrtpRequired(), audio_options_);
4229 if (!voice_channel) {
4230 transport_controller_->DestroyDtlsTransport(
4231 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4232 if (rtcp_dtls_transport) {
4233 transport_controller_->DestroyDtlsTransport(
4234 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
4235 }
4236 return false;
4237 }
Steve Anton75737c02017-11-06 10:37:17 -08004238 voice_channel->SignalRtcpMuxFullyActive.connect(
4239 this, &PeerConnection::DestroyRtcpTransport_n);
4240 voice_channel->SignalDtlsSrtpSetupFailure.connect(
4241 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08004242 voice_channel->SignalSentPacket.connect(this,
4243 &PeerConnection::OnSentPacket_w);
Steve Anton4171afb2017-11-20 10:20:22 -08004244
4245 GetAudioTransceiver()->internal()->SetChannel(voice_channel);
4246
Steve Anton75737c02017-11-06 10:37:17 -08004247 return true;
4248}
4249
Steve Anton4171afb2017-11-20 10:20:22 -08004250// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Anton75737c02017-11-06 10:37:17 -08004251bool PeerConnection::CreateVideoChannel(const cricket::ContentInfo* content,
4252 const std::string* bundle_transport) {
4253 // TODO(steveanton): Check to see if it's safe to create multiple video
4254 // channels.
Steve Anton4171afb2017-11-20 10:20:22 -08004255 RTC_DCHECK(!video_channel());
Steve Anton75737c02017-11-06 10:37:17 -08004256
4257 std::string transport_name =
4258 bundle_transport ? *bundle_transport : content->name;
4259
4260 cricket::DtlsTransportInternal* rtp_dtls_transport =
4261 transport_controller_->CreateDtlsTransport(
4262 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4263 cricket::DtlsTransportInternal* rtcp_dtls_transport = nullptr;
4264 if (configuration_.rtcp_mux_policy !=
4265 PeerConnectionInterface::kRtcpMuxPolicyRequire) {
4266 rtcp_dtls_transport = transport_controller_->CreateDtlsTransport(
4267 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
4268 }
4269
4270 cricket::VideoChannel* video_channel = channel_manager()->CreateVideoChannel(
4271 call_.get(), configuration_.media_config, rtp_dtls_transport,
4272 rtcp_dtls_transport, transport_controller_->signaling_thread(),
4273 content->name, SrtpRequired(), video_options_);
4274
4275 if (!video_channel) {
4276 transport_controller_->DestroyDtlsTransport(
4277 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4278 if (rtcp_dtls_transport) {
4279 transport_controller_->DestroyDtlsTransport(
4280 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
4281 }
4282 return false;
4283 }
Steve Anton75737c02017-11-06 10:37:17 -08004284 video_channel->SignalRtcpMuxFullyActive.connect(
4285 this, &PeerConnection::DestroyRtcpTransport_n);
4286 video_channel->SignalDtlsSrtpSetupFailure.connect(
4287 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08004288 video_channel->SignalSentPacket.connect(this,
4289 &PeerConnection::OnSentPacket_w);
Steve Anton4171afb2017-11-20 10:20:22 -08004290
4291 GetVideoTransceiver()->internal()->SetChannel(video_channel);
4292
Steve Anton75737c02017-11-06 10:37:17 -08004293 return true;
4294}
4295
4296bool PeerConnection::CreateDataChannel(const cricket::ContentInfo* content,
4297 const std::string* bundle_transport) {
4298 const std::string transport_name =
4299 bundle_transport ? *bundle_transport : content->name;
4300 bool sctp = (data_channel_type_ == cricket::DCT_SCTP);
4301 if (sctp) {
4302 if (!sctp_factory_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004303 RTC_LOG(LS_ERROR)
Steve Anton75737c02017-11-06 10:37:17 -08004304 << "Trying to create SCTP transport, but didn't compile with "
4305 "SCTP support (HAVE_SCTP)";
4306 return false;
4307 }
4308 if (!network_thread()->Invoke<bool>(
4309 RTC_FROM_HERE, rtc::Bind(&PeerConnection::CreateSctpTransport_n,
4310 this, content->name, transport_name))) {
4311 return false;
4312 }
4313 } else {
4314 std::string transport_name =
4315 bundle_transport ? *bundle_transport : content->name;
4316 cricket::DtlsTransportInternal* rtp_dtls_transport =
4317 transport_controller_->CreateDtlsTransport(
4318 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4319 cricket::DtlsTransportInternal* rtcp_dtls_transport = nullptr;
4320 if (configuration_.rtcp_mux_policy !=
4321 PeerConnectionInterface::kRtcpMuxPolicyRequire) {
4322 rtcp_dtls_transport = transport_controller_->CreateDtlsTransport(
4323 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
4324 }
4325
4326 rtp_data_channel_ = channel_manager()->CreateRtpDataChannel(
4327 configuration_.media_config, rtp_dtls_transport, rtcp_dtls_transport,
4328 transport_controller_->signaling_thread(), content->name,
4329 SrtpRequired());
4330
4331 if (!rtp_data_channel_) {
4332 transport_controller_->DestroyDtlsTransport(
4333 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4334 if (rtcp_dtls_transport) {
4335 transport_controller_->DestroyDtlsTransport(
4336 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
4337 }
4338 return false;
4339 }
4340
4341 rtp_data_channel_->SignalRtcpMuxFullyActive.connect(
4342 this, &PeerConnection::DestroyRtcpTransport_n);
4343 rtp_data_channel_->SignalDtlsSrtpSetupFailure.connect(
4344 this, &PeerConnection::OnDtlsSrtpSetupFailure);
4345 rtp_data_channel_->SignalSentPacket.connect(
4346 this, &PeerConnection::OnSentPacket_w);
4347 }
4348
Steve Antond25da372017-11-06 14:50:29 -08004349 for (const auto& channel : sctp_data_channels_) {
4350 channel->OnTransportChannelCreated();
4351 }
Steve Anton75737c02017-11-06 10:37:17 -08004352
4353 return true;
4354}
4355
4356Call::Stats PeerConnection::GetCallStats() {
4357 if (!worker_thread()->IsCurrent()) {
4358 return worker_thread()->Invoke<Call::Stats>(
4359 RTC_FROM_HERE, rtc::Bind(&PeerConnection::GetCallStats, this));
4360 }
4361 if (call_) {
4362 return call_->GetStats();
4363 } else {
4364 return Call::Stats();
4365 }
4366}
4367
4368std::unique_ptr<SessionStats> PeerConnection::GetSessionStats_n(
4369 const ChannelNamePairs& channel_name_pairs) {
4370 RTC_DCHECK(network_thread()->IsCurrent());
4371 std::unique_ptr<SessionStats> session_stats(new SessionStats());
4372 for (const auto channel_name_pair :
4373 {&channel_name_pairs.voice, &channel_name_pairs.video,
4374 &channel_name_pairs.data}) {
4375 if (*channel_name_pair) {
4376 cricket::TransportStats transport_stats;
4377 if (!transport_controller_->GetStats((*channel_name_pair)->transport_name,
4378 &transport_stats)) {
4379 return nullptr;
4380 }
4381 session_stats->proxy_to_transport[(*channel_name_pair)->content_name] =
4382 (*channel_name_pair)->transport_name;
4383 session_stats->transport_stats[(*channel_name_pair)->transport_name] =
4384 std::move(transport_stats);
4385 }
4386 }
4387 return session_stats;
4388}
4389
4390bool PeerConnection::CreateSctpTransport_n(const std::string& content_name,
4391 const std::string& transport_name) {
4392 RTC_DCHECK(network_thread()->IsCurrent());
4393 RTC_DCHECK(sctp_factory_);
4394 cricket::DtlsTransportInternal* tc =
4395 transport_controller_->CreateDtlsTransport_n(
4396 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4397 sctp_transport_ = sctp_factory_->CreateSctpTransport(tc);
4398 RTC_DCHECK(sctp_transport_);
4399 sctp_invoker_.reset(new rtc::AsyncInvoker());
4400 sctp_transport_->SignalReadyToSendData.connect(
4401 this, &PeerConnection::OnSctpTransportReadyToSendData_n);
4402 sctp_transport_->SignalDataReceived.connect(
4403 this, &PeerConnection::OnSctpTransportDataReceived_n);
4404 sctp_transport_->SignalStreamClosedRemotely.connect(
4405 this, &PeerConnection::OnSctpStreamClosedRemotely_n);
4406 sctp_transport_name_ = rtc::Optional<std::string>(transport_name);
4407 sctp_content_name_ = rtc::Optional<std::string>(content_name);
4408 return true;
4409}
4410
4411void PeerConnection::ChangeSctpTransport_n(const std::string& transport_name) {
4412 RTC_DCHECK(network_thread()->IsCurrent());
4413 RTC_DCHECK(sctp_transport_);
4414 RTC_DCHECK(sctp_transport_name_);
4415 std::string old_sctp_transport_name = *sctp_transport_name_;
4416 sctp_transport_name_ = rtc::Optional<std::string>(transport_name);
4417 cricket::DtlsTransportInternal* tc =
4418 transport_controller_->CreateDtlsTransport_n(
4419 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4420 sctp_transport_->SetTransportChannel(tc);
4421 transport_controller_->DestroyDtlsTransport_n(
4422 old_sctp_transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4423}
4424
4425void PeerConnection::DestroySctpTransport_n() {
4426 RTC_DCHECK(network_thread()->IsCurrent());
4427 sctp_transport_.reset(nullptr);
4428 sctp_content_name_.reset();
4429 sctp_transport_name_.reset();
4430 sctp_invoker_.reset(nullptr);
4431 sctp_ready_to_send_data_ = false;
4432}
4433
4434void PeerConnection::OnSctpTransportReadyToSendData_n() {
4435 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
4436 RTC_DCHECK(network_thread()->IsCurrent());
4437 // Note: Cannot use rtc::Bind here because it will grab a reference to
4438 // PeerConnection and potentially cause PeerConnection to live longer than
4439 // expected. It is safe not to grab a reference since the sctp_invoker_ will
4440 // be destroyed before PeerConnection is destroyed, and at that point all
4441 // pending tasks will be cleared.
4442 sctp_invoker_->AsyncInvoke<void>(RTC_FROM_HERE, signaling_thread(), [this] {
4443 OnSctpTransportReadyToSendData_s(true);
4444 });
4445}
4446
4447void PeerConnection::OnSctpTransportReadyToSendData_s(bool ready) {
4448 RTC_DCHECK(signaling_thread()->IsCurrent());
4449 sctp_ready_to_send_data_ = ready;
4450 SignalSctpReadyToSendData(ready);
4451}
4452
4453void PeerConnection::OnSctpTransportDataReceived_n(
4454 const cricket::ReceiveDataParams& params,
4455 const rtc::CopyOnWriteBuffer& payload) {
4456 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
4457 RTC_DCHECK(network_thread()->IsCurrent());
4458 // Note: Cannot use rtc::Bind here because it will grab a reference to
4459 // PeerConnection and potentially cause PeerConnection to live longer than
4460 // expected. It is safe not to grab a reference since the sctp_invoker_ will
4461 // be destroyed before PeerConnection is destroyed, and at that point all
4462 // pending tasks will be cleared.
4463 sctp_invoker_->AsyncInvoke<void>(
4464 RTC_FROM_HERE, signaling_thread(), [this, params, payload] {
4465 OnSctpTransportDataReceived_s(params, payload);
4466 });
4467}
4468
4469void PeerConnection::OnSctpTransportDataReceived_s(
4470 const cricket::ReceiveDataParams& params,
4471 const rtc::CopyOnWriteBuffer& payload) {
4472 RTC_DCHECK(signaling_thread()->IsCurrent());
4473 if (params.type == cricket::DMT_CONTROL && IsOpenMessage(payload)) {
4474 // Received OPEN message; parse and signal that a new data channel should
4475 // be created.
4476 std::string label;
4477 InternalDataChannelInit config;
4478 config.id = params.ssrc;
4479 if (!ParseDataChannelOpenMessage(payload, &label, &config)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004480 RTC_LOG(LS_WARNING) << "Failed to parse the OPEN message for sid "
4481 << params.ssrc;
Steve Anton75737c02017-11-06 10:37:17 -08004482 return;
4483 }
4484 config.open_handshake_role = InternalDataChannelInit::kAcker;
4485 OnDataChannelOpenMessage(label, config);
4486 } else {
4487 // Otherwise just forward the signal.
4488 SignalSctpDataReceived(params, payload);
4489 }
4490}
4491
4492void PeerConnection::OnSctpStreamClosedRemotely_n(int sid) {
4493 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
4494 RTC_DCHECK(network_thread()->IsCurrent());
4495 sctp_invoker_->AsyncInvoke<void>(
4496 RTC_FROM_HERE, signaling_thread(),
4497 rtc::Bind(&sigslot::signal1<int>::operator(),
4498 &SignalSctpStreamClosedRemotely, sid));
4499}
4500
4501// Returns false if bundle is enabled and rtcp_mux is disabled.
4502bool PeerConnection::ValidateBundleSettings(const SessionDescription* desc) {
4503 bool bundle_enabled = desc->HasGroup(cricket::GROUP_TYPE_BUNDLE);
4504 if (!bundle_enabled)
4505 return true;
4506
4507 const cricket::ContentGroup* bundle_group =
4508 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
4509 RTC_DCHECK(bundle_group != NULL);
4510
4511 const cricket::ContentInfos& contents = desc->contents();
4512 for (cricket::ContentInfos::const_iterator citer = contents.begin();
4513 citer != contents.end(); ++citer) {
4514 const cricket::ContentInfo* content = (&*citer);
4515 RTC_DCHECK(content != NULL);
4516 if (bundle_group->HasContentName(content->name) && !content->rejected &&
4517 content->type == cricket::NS_JINGLE_RTP) {
4518 if (!HasRtcpMuxEnabled(content))
4519 return false;
4520 }
4521 }
4522 // RTCP-MUX is enabled in all the contents.
4523 return true;
4524}
4525
4526bool PeerConnection::HasRtcpMuxEnabled(const cricket::ContentInfo* content) {
4527 const cricket::MediaContentDescription* description =
4528 static_cast<cricket::MediaContentDescription*>(content->description);
4529 return description->rtcp_mux();
4530}
4531
4532bool PeerConnection::ValidateSessionDescription(
4533 const SessionDescriptionInterface* sdesc,
4534 cricket::ContentSource source,
4535 std::string* err_desc) {
4536 std::string type;
4537 if (error() != ERROR_NONE) {
4538 return BadSdp(source, type, GetSessionErrorMsg(), err_desc);
4539 }
4540
4541 if (!sdesc || !sdesc->description()) {
4542 return BadSdp(source, type, kInvalidSdp, err_desc);
4543 }
4544
4545 type = sdesc->type();
4546 Action action = GetAction(sdesc->type());
4547 if (source == cricket::CS_LOCAL) {
4548 if (!ExpectSetLocalDescription(action))
4549 return BadLocalSdp(type, BadStateErrMsg(signaling_state()), err_desc);
4550 } else {
4551 if (!ExpectSetRemoteDescription(action))
4552 return BadRemoteSdp(type, BadStateErrMsg(signaling_state()), err_desc);
4553 }
4554
4555 // Verify crypto settings.
4556 std::string crypto_error;
4557 if ((webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED ||
4558 dtls_enabled_) &&
4559 !VerifyCrypto(sdesc->description(), dtls_enabled_, &crypto_error)) {
4560 return BadSdp(source, type, crypto_error, err_desc);
4561 }
4562
4563 // Verify ice-ufrag and ice-pwd.
4564 if (!VerifyIceUfragPwdPresent(sdesc->description())) {
4565 return BadSdp(source, type, kSdpWithoutIceUfragPwd, err_desc);
4566 }
4567
4568 if (!ValidateBundleSettings(sdesc->description())) {
4569 return BadSdp(source, type, kBundleWithoutRtcpMux, err_desc);
4570 }
4571
4572 // TODO(skvlad): When the local rtcp-mux policy is Require, reject any
4573 // m-lines that do not rtcp-mux enabled.
4574
4575 // Verify m-lines in Answer when compared against Offer.
4576 if (action == kAnswer || action == kPrAnswer) {
4577 const cricket::SessionDescription* offer_desc =
4578 (source == cricket::CS_LOCAL) ? remote_description()->description()
4579 : local_description()->description();
4580 if (!MediaSectionsHaveSameCount(offer_desc, sdesc->description()) ||
4581 !MediaSectionsInSameOrder(offer_desc, sdesc->description())) {
4582 return BadAnswerSdp(source, kMlineMismatchInAnswer, err_desc);
4583 }
4584 } else {
4585 const cricket::SessionDescription* current_desc = nullptr;
4586 if (source == cricket::CS_LOCAL && local_description()) {
4587 current_desc = local_description()->description();
4588 } else if (source == cricket::CS_REMOTE && remote_description()) {
4589 current_desc = remote_description()->description();
4590 }
4591 // The re-offers should respect the order of m= sections in current
4592 // description. See RFC3264 Section 8 paragraph 4 for more details.
4593 if (current_desc &&
4594 !MediaSectionsInSameOrder(current_desc, sdesc->description())) {
4595 return BadOfferSdp(source, kMlineMismatchInSubsequentOffer, err_desc);
4596 }
4597 }
4598
4599 return true;
4600}
4601
4602bool PeerConnection::ExpectSetLocalDescription(Action action) {
4603 PeerConnectionInterface::SignalingState state = signaling_state();
4604 if (action == kOffer) {
4605 return (state == PeerConnectionInterface::kStable) ||
4606 (state == PeerConnectionInterface::kHaveLocalOffer);
4607 } else { // Answer or PrAnswer
4608 return (state == PeerConnectionInterface::kHaveRemoteOffer) ||
4609 (state == PeerConnectionInterface::kHaveLocalPrAnswer);
4610 }
4611}
4612
4613bool PeerConnection::ExpectSetRemoteDescription(Action action) {
4614 PeerConnectionInterface::SignalingState state = signaling_state();
4615 if (action == kOffer) {
4616 return (state == PeerConnectionInterface::kStable) ||
4617 (state == PeerConnectionInterface::kHaveRemoteOffer);
4618 } else { // Answer or PrAnswer.
4619 return (state == PeerConnectionInterface::kHaveLocalOffer) ||
4620 (state == PeerConnectionInterface::kHaveRemotePrAnswer);
4621 }
4622}
4623
4624std::string PeerConnection::GetSessionErrorMsg() {
4625 std::ostringstream desc;
4626 desc << kSessionError << GetErrorCodeString(error()) << ". ";
4627 desc << kSessionErrorDesc << error_desc() << ".";
4628 return desc.str();
4629}
4630
4631// We need to check the local/remote description for the Transport instead of
4632// the session, because a new Transport added during renegotiation may have
4633// them unset while the session has them set from the previous negotiation.
4634// Not doing so may trigger the auto generation of transport description and
4635// mess up DTLS identity information, ICE credential, etc.
4636bool PeerConnection::ReadyToUseRemoteCandidate(
4637 const IceCandidateInterface* candidate,
4638 const SessionDescriptionInterface* remote_desc,
4639 bool* valid) {
4640 *valid = true;
4641
4642 const SessionDescriptionInterface* current_remote_desc =
4643 remote_desc ? remote_desc : remote_description();
4644
4645 if (!current_remote_desc) {
4646 return false;
4647 }
4648
4649 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
4650 size_t remote_content_size =
4651 current_remote_desc->description()->contents().size();
4652 if (mediacontent_index >= remote_content_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004653 RTC_LOG(LS_ERROR)
4654 << "ReadyToUseRemoteCandidate: Invalid candidate media index "
4655 << mediacontent_index;
Steve Anton75737c02017-11-06 10:37:17 -08004656
4657 *valid = false;
4658 return false;
4659 }
4660
4661 cricket::ContentInfo content =
4662 current_remote_desc->description()->contents()[mediacontent_index];
4663
4664 const std::string transport_name = GetTransportName(content.name);
4665 if (transport_name.empty()) {
4666 return false;
4667 }
4668 return transport_controller_->ReadyForRemoteCandidates(transport_name);
4669}
4670
4671bool PeerConnection::SrtpRequired() const {
4672 return dtls_enabled_ ||
4673 webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED;
4674}
4675
4676void PeerConnection::OnTransportControllerGatheringState(
4677 cricket::IceGatheringState state) {
4678 RTC_DCHECK(signaling_thread()->IsCurrent());
4679 if (state == cricket::kIceGatheringGathering) {
4680 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringGathering);
4681 } else if (state == cricket::kIceGatheringComplete) {
4682 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringComplete);
4683 }
4684}
4685
4686void PeerConnection::ReportTransportStats() {
4687 // Use a set so we don't report the same stats twice if two channels share
4688 // a transport.
4689 std::set<std::string> transport_names;
4690 if (voice_channel()) {
4691 transport_names.insert(voice_channel()->transport_name());
4692 }
4693 if (video_channel()) {
4694 transport_names.insert(video_channel()->transport_name());
4695 }
4696 if (rtp_data_channel()) {
4697 transport_names.insert(rtp_data_channel()->transport_name());
4698 }
4699 if (sctp_transport_name_) {
4700 transport_names.insert(*sctp_transport_name_);
4701 }
4702 for (const auto& name : transport_names) {
4703 cricket::TransportStats stats;
4704 if (transport_controller_->GetStats(name, &stats)) {
4705 ReportBestConnectionState(stats);
4706 ReportNegotiatedCiphers(stats);
4707 }
4708 }
4709}
4710// Walk through the ConnectionInfos to gather best connection usage
4711// for IPv4 and IPv6.
4712void PeerConnection::ReportBestConnectionState(
4713 const cricket::TransportStats& stats) {
4714 RTC_DCHECK(metrics_observer());
4715 for (cricket::TransportChannelStatsList::const_iterator it =
4716 stats.channel_stats.begin();
4717 it != stats.channel_stats.end(); ++it) {
4718 for (cricket::ConnectionInfos::const_iterator it_info =
4719 it->connection_infos.begin();
4720 it_info != it->connection_infos.end(); ++it_info) {
4721 if (!it_info->best_connection) {
4722 continue;
4723 }
4724
4725 PeerConnectionEnumCounterType type = kPeerConnectionEnumCounterMax;
4726 const cricket::Candidate& local = it_info->local_candidate;
4727 const cricket::Candidate& remote = it_info->remote_candidate;
4728
4729 // Increment the counter for IceCandidatePairType.
4730 if (local.protocol() == cricket::TCP_PROTOCOL_NAME ||
4731 (local.type() == RELAY_PORT_TYPE &&
4732 local.relay_protocol() == cricket::TCP_PROTOCOL_NAME)) {
4733 type = kEnumCounterIceCandidatePairTypeTcp;
4734 } else if (local.protocol() == cricket::UDP_PROTOCOL_NAME) {
4735 type = kEnumCounterIceCandidatePairTypeUdp;
4736 } else {
4737 RTC_CHECK(0);
4738 }
4739 metrics_observer()->IncrementEnumCounter(
4740 type, GetIceCandidatePairCounter(local, remote),
4741 kIceCandidatePairMax);
4742
4743 // Increment the counter for IP type.
4744 if (local.address().family() == AF_INET) {
4745 metrics_observer()->IncrementEnumCounter(
4746 kEnumCounterAddressFamily, kBestConnections_IPv4,
4747 kPeerConnectionAddressFamilyCounter_Max);
4748
4749 } else if (local.address().family() == AF_INET6) {
4750 metrics_observer()->IncrementEnumCounter(
4751 kEnumCounterAddressFamily, kBestConnections_IPv6,
4752 kPeerConnectionAddressFamilyCounter_Max);
4753 } else {
4754 RTC_CHECK(0);
4755 }
4756
4757 return;
4758 }
4759 }
4760}
4761
4762void PeerConnection::ReportNegotiatedCiphers(
4763 const cricket::TransportStats& stats) {
4764 RTC_DCHECK(metrics_observer());
4765 if (!dtls_enabled_ || stats.channel_stats.empty()) {
4766 return;
4767 }
4768
4769 int srtp_crypto_suite = stats.channel_stats[0].srtp_crypto_suite;
4770 int ssl_cipher_suite = stats.channel_stats[0].ssl_cipher_suite;
4771 if (srtp_crypto_suite == rtc::SRTP_INVALID_CRYPTO_SUITE &&
4772 ssl_cipher_suite == rtc::TLS_NULL_WITH_NULL_NULL) {
4773 return;
4774 }
4775
4776 PeerConnectionEnumCounterType srtp_counter_type;
4777 PeerConnectionEnumCounterType ssl_counter_type;
4778 if (stats.transport_name == cricket::CN_AUDIO) {
4779 srtp_counter_type = kEnumCounterAudioSrtpCipher;
4780 ssl_counter_type = kEnumCounterAudioSslCipher;
4781 } else if (stats.transport_name == cricket::CN_VIDEO) {
4782 srtp_counter_type = kEnumCounterVideoSrtpCipher;
4783 ssl_counter_type = kEnumCounterVideoSslCipher;
4784 } else if (stats.transport_name == cricket::CN_DATA) {
4785 srtp_counter_type = kEnumCounterDataSrtpCipher;
4786 ssl_counter_type = kEnumCounterDataSslCipher;
4787 } else {
4788 RTC_NOTREACHED();
4789 return;
4790 }
4791
4792 if (srtp_crypto_suite != rtc::SRTP_INVALID_CRYPTO_SUITE) {
4793 metrics_observer()->IncrementSparseEnumCounter(srtp_counter_type,
4794 srtp_crypto_suite);
4795 }
4796 if (ssl_cipher_suite != rtc::TLS_NULL_WITH_NULL_NULL) {
4797 metrics_observer()->IncrementSparseEnumCounter(ssl_counter_type,
4798 ssl_cipher_suite);
4799 }
4800}
4801
4802void PeerConnection::OnSentPacket_w(const rtc::SentPacket& sent_packet) {
4803 RTC_DCHECK(worker_thread()->IsCurrent());
4804 RTC_DCHECK(call_);
4805 call_->OnSentPacket(sent_packet);
4806}
4807
4808const std::string PeerConnection::GetTransportName(
4809 const std::string& content_name) {
4810 cricket::BaseChannel* channel = GetChannel(content_name);
4811 if (!channel) {
4812 if (sctp_transport_) {
4813 RTC_DCHECK(sctp_content_name_);
4814 RTC_DCHECK(sctp_transport_name_);
4815 if (content_name == *sctp_content_name_) {
4816 return *sctp_transport_name_;
4817 }
4818 }
4819 // Return an empty string if failed to retrieve the transport name.
4820 return "";
4821 }
4822 return channel->transport_name();
4823}
4824
4825void PeerConnection::DestroyRtcpTransport_n(const std::string& transport_name) {
4826 RTC_DCHECK(network_thread()->IsCurrent());
4827 transport_controller_->DestroyDtlsTransport_n(
4828 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
4829}
4830
Steve Anton4171afb2017-11-20 10:20:22 -08004831// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Anton75737c02017-11-06 10:37:17 -08004832void PeerConnection::DestroyVideoChannel(cricket::VideoChannel* video_channel) {
Steve Anton4171afb2017-11-20 10:20:22 -08004833 RTC_DCHECK(video_channel);
Steve Anton75737c02017-11-06 10:37:17 -08004834 RTC_DCHECK(video_channel->rtp_dtls_transport());
Steve Anton4171afb2017-11-20 10:20:22 -08004835 RTC_DCHECK_EQ(GetVideoTransceiver()->internal()->channel(), video_channel);
4836 GetVideoTransceiver()->internal()->SetChannel(nullptr);
Steve Anton75737c02017-11-06 10:37:17 -08004837 const std::string transport_name =
4838 video_channel->rtp_dtls_transport()->transport_name();
4839 const bool need_to_delete_rtcp =
4840 (video_channel->rtcp_dtls_transport() != nullptr);
4841 // The above need to be cached before destroying the video channel so that we
4842 // do not access uninitialized memory.
4843 channel_manager()->DestroyVideoChannel(video_channel);
4844 transport_controller_->DestroyDtlsTransport(
4845 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4846 if (need_to_delete_rtcp) {
4847 transport_controller_->DestroyDtlsTransport(
4848 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
4849 }
4850}
4851
Steve Anton4171afb2017-11-20 10:20:22 -08004852// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Anton75737c02017-11-06 10:37:17 -08004853void PeerConnection::DestroyVoiceChannel(cricket::VoiceChannel* voice_channel) {
Steve Anton4171afb2017-11-20 10:20:22 -08004854 RTC_DCHECK(voice_channel);
Steve Anton75737c02017-11-06 10:37:17 -08004855 RTC_DCHECK(voice_channel->rtp_dtls_transport());
Steve Anton4171afb2017-11-20 10:20:22 -08004856 RTC_DCHECK_EQ(GetAudioTransceiver()->internal()->channel(), voice_channel);
4857 GetAudioTransceiver()->internal()->SetChannel(nullptr);
Steve Anton75737c02017-11-06 10:37:17 -08004858 const std::string transport_name =
4859 voice_channel->rtp_dtls_transport()->transport_name();
4860 const bool need_to_delete_rtcp =
4861 (voice_channel->rtcp_dtls_transport() != nullptr);
4862 // The above need to be cached before destroying the video channel so that we
4863 // do not access uninitialized memory.
4864 channel_manager()->DestroyVoiceChannel(voice_channel);
4865 transport_controller_->DestroyDtlsTransport(
4866 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4867 if (need_to_delete_rtcp) {
4868 transport_controller_->DestroyDtlsTransport(
4869 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
4870 }
4871}
4872
4873void PeerConnection::DestroyDataChannel() {
4874 OnDataChannelDestroyed();
4875 RTC_DCHECK(rtp_data_channel_->rtp_dtls_transport());
4876 std::string transport_name;
4877 transport_name = rtp_data_channel_->rtp_dtls_transport()->transport_name();
4878 bool need_to_delete_rtcp =
4879 (rtp_data_channel_->rtcp_dtls_transport() != nullptr);
4880 channel_manager()->DestroyRtpDataChannel(rtp_data_channel_);
4881 rtp_data_channel_ = nullptr;
4882 transport_controller_->DestroyDtlsTransport(
4883 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4884 if (need_to_delete_rtcp) {
4885 transport_controller_->DestroyDtlsTransport(
4886 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
4887 }
4888}
4889
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004890} // namespace webrtc