blob: 2c6cc4b97d972d4387068341e55893c63acf58ae [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"
Karl Wiberge40468b2017-11-22 10:42:26 +010043#include "rtc_base/numerics/safe_conversions.h"
Elad Alon83ccca12017-10-04 13:18:26 +020044#include "rtc_base/ptr_util.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
Henrik Boström31638672017-11-23 17:48:32 +0100644// Upon completion, posts a task to execute the callback of the
645// SetSessionDescriptionObserver asynchronously on the same thread. At this
646// point, the state of the peer connection might no longer reflect the effects
647// of the SetRemoteDescription operation, as the peer connection could have been
648// modified during the post.
649// TODO(hbos): Remove this class once we remove the version of
650// PeerConnectionInterface::SetRemoteDescription() that takes a
651// SetSessionDescriptionObserver as an argument.
652class PeerConnection::SetRemoteDescriptionObserverAdapter
653 : public rtc::RefCountedObject<SetRemoteDescriptionObserverInterface> {
654 public:
655 SetRemoteDescriptionObserverAdapter(
656 rtc::scoped_refptr<PeerConnection> pc,
657 rtc::scoped_refptr<SetSessionDescriptionObserver> wrapper)
658 : pc_(std::move(pc)), wrapper_(std::move(wrapper)) {}
659
660 // SetRemoteDescriptionObserverInterface implementation.
661 void OnSetRemoteDescriptionComplete(RTCError error) override {
662 if (error.ok())
663 pc_->PostSetSessionDescriptionSuccess(wrapper_);
664 else
665 pc_->PostSetSessionDescriptionFailure(wrapper_, error.message());
666 }
667
668 private:
669 rtc::scoped_refptr<PeerConnection> pc_;
670 rtc::scoped_refptr<SetSessionDescriptionObserver> wrapper_;
671};
672
deadbeef293e9262017-01-11 12:28:30 -0800673bool PeerConnectionInterface::RTCConfiguration::operator==(
674 const PeerConnectionInterface::RTCConfiguration& o) const {
675 // This static_assert prevents us from accidentally breaking operator==.
Steve Anton300bf8e2017-07-14 10:13:10 -0700676 // Note: Order matters! Fields must be ordered the same as RTCConfiguration.
deadbeef293e9262017-01-11 12:28:30 -0800677 struct stuff_being_tested_for_equality {
Magnus Jedvert3beb2072017-07-14 14:23:56 +0000678 IceServers servers;
Steve Anton300bf8e2017-07-14 10:13:10 -0700679 IceTransportsType type;
deadbeef293e9262017-01-11 12:28:30 -0800680 BundlePolicy bundle_policy;
681 RtcpMuxPolicy rtcp_mux_policy;
Steve Anton300bf8e2017-07-14 10:13:10 -0700682 std::vector<rtc::scoped_refptr<rtc::RTCCertificate>> certificates;
683 int ice_candidate_pool_size;
684 bool disable_ipv6;
685 bool disable_ipv6_on_wifi;
deadbeefd21eab32017-07-26 16:50:11 -0700686 int max_ipv6_networks;
Steve Anton300bf8e2017-07-14 10:13:10 -0700687 bool enable_rtp_data_channel;
688 rtc::Optional<int> screencast_min_bitrate;
689 rtc::Optional<bool> combined_audio_video_bwe;
690 rtc::Optional<bool> enable_dtls_srtp;
deadbeef293e9262017-01-11 12:28:30 -0800691 TcpCandidatePolicy tcp_candidate_policy;
692 CandidateNetworkPolicy candidate_network_policy;
693 int audio_jitter_buffer_max_packets;
694 bool audio_jitter_buffer_fast_accelerate;
695 int ice_connection_receiving_timeout;
696 int ice_backup_candidate_pair_ping_interval;
697 ContinualGatheringPolicy continual_gathering_policy;
deadbeef293e9262017-01-11 12:28:30 -0800698 bool prioritize_most_likely_ice_candidate_pairs;
699 struct cricket::MediaConfig media_config;
deadbeef293e9262017-01-11 12:28:30 -0800700 bool prune_turn_ports;
701 bool presume_writable_when_fully_relayed;
702 bool enable_ice_renomination;
703 bool redetermine_role_on_ice_restart;
skvlad51072462017-02-02 11:50:14 -0800704 rtc::Optional<int> ice_check_min_interval;
Steve Anton300bf8e2017-07-14 10:13:10 -0700705 rtc::Optional<rtc::IntervalRange> ice_regather_interval_range;
Jonas Orelandbdcee282017-10-10 14:01:40 +0200706 webrtc::TurnCustomizer* turn_customizer;
Steve Anton79e79602017-11-20 10:25:56 -0800707 SdpSemantics sdp_semantics;
deadbeef293e9262017-01-11 12:28:30 -0800708 };
709 static_assert(sizeof(stuff_being_tested_for_equality) == sizeof(*this),
710 "Did you add something to RTCConfiguration and forget to "
711 "update operator==?");
712 return type == o.type && servers == o.servers &&
713 bundle_policy == o.bundle_policy &&
714 rtcp_mux_policy == o.rtcp_mux_policy &&
715 tcp_candidate_policy == o.tcp_candidate_policy &&
716 candidate_network_policy == o.candidate_network_policy &&
717 audio_jitter_buffer_max_packets == o.audio_jitter_buffer_max_packets &&
718 audio_jitter_buffer_fast_accelerate ==
719 o.audio_jitter_buffer_fast_accelerate &&
720 ice_connection_receiving_timeout ==
721 o.ice_connection_receiving_timeout &&
722 ice_backup_candidate_pair_ping_interval ==
723 o.ice_backup_candidate_pair_ping_interval &&
724 continual_gathering_policy == o.continual_gathering_policy &&
725 certificates == o.certificates &&
726 prioritize_most_likely_ice_candidate_pairs ==
727 o.prioritize_most_likely_ice_candidate_pairs &&
728 media_config == o.media_config && disable_ipv6 == o.disable_ipv6 &&
zhihuangb09b3f92017-03-07 14:40:51 -0800729 disable_ipv6_on_wifi == o.disable_ipv6_on_wifi &&
deadbeefd21eab32017-07-26 16:50:11 -0700730 max_ipv6_networks == o.max_ipv6_networks &&
deadbeef293e9262017-01-11 12:28:30 -0800731 enable_rtp_data_channel == o.enable_rtp_data_channel &&
deadbeef293e9262017-01-11 12:28:30 -0800732 screencast_min_bitrate == o.screencast_min_bitrate &&
733 combined_audio_video_bwe == o.combined_audio_video_bwe &&
734 enable_dtls_srtp == o.enable_dtls_srtp &&
735 ice_candidate_pool_size == o.ice_candidate_pool_size &&
736 prune_turn_ports == o.prune_turn_ports &&
737 presume_writable_when_fully_relayed ==
738 o.presume_writable_when_fully_relayed &&
739 enable_ice_renomination == o.enable_ice_renomination &&
skvlad51072462017-02-02 11:50:14 -0800740 redetermine_role_on_ice_restart == o.redetermine_role_on_ice_restart &&
Steve Anton300bf8e2017-07-14 10:13:10 -0700741 ice_check_min_interval == o.ice_check_min_interval &&
Jonas Orelandbdcee282017-10-10 14:01:40 +0200742 ice_regather_interval_range == o.ice_regather_interval_range &&
Steve Anton79e79602017-11-20 10:25:56 -0800743 turn_customizer == o.turn_customizer &&
744 sdp_semantics == o.sdp_semantics;
deadbeef293e9262017-01-11 12:28:30 -0800745}
746
747bool PeerConnectionInterface::RTCConfiguration::operator!=(
748 const PeerConnectionInterface::RTCConfiguration& o) const {
749 return !(*this == o);
deadbeef3edec7c2016-12-10 11:44:26 -0800750}
751
zhihuang8f65cdf2016-05-06 18:40:30 -0700752// Generate a RTCP CNAME when a PeerConnection is created.
753std::string GenerateRtcpCname() {
754 std::string cname;
755 if (!rtc::CreateRandomString(kRtcpCnameLength, &cname)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100756 RTC_LOG(LS_ERROR) << "Failed to generate CNAME.";
nisseeb4ca4e2017-01-12 02:24:27 -0800757 RTC_NOTREACHED();
zhihuang8f65cdf2016-05-06 18:40:30 -0700758 }
759 return cname;
760}
761
zhihuang1c378ed2017-08-17 14:10:50 -0700762bool ValidateOfferAnswerOptions(
763 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options) {
764 return IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_audio) &&
765 IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_video);
olka3c747662017-08-17 06:50:32 -0700766}
767
zhihuang1c378ed2017-08-17 14:10:50 -0700768// From |rtc_options|, fill parts of |session_options| shared by all generated
769// m= sections (in other words, nothing that involves a map/array).
770void ExtractSharedMediaSessionOptions(
771 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options,
772 cricket::MediaSessionOptions* session_options) {
773 session_options->vad_enabled = rtc_options.voice_activity_detection;
774 session_options->bundle_enabled = rtc_options.use_rtp_mux;
775}
zhihuanga77e6bb2017-08-14 18:17:48 -0700776
zhihuang1c378ed2017-08-17 14:10:50 -0700777bool ConvertConstraintsToOfferAnswerOptions(
778 const MediaConstraintsInterface* constraints,
779 PeerConnectionInterface::RTCOfferAnswerOptions* offer_answer_options) {
olka3c747662017-08-17 06:50:32 -0700780 if (!constraints) {
781 return true;
782 }
zhihuang1c378ed2017-08-17 14:10:50 -0700783
784 bool value = false;
785 size_t mandatory_constraints_satisfied = 0;
786
787 if (FindConstraint(constraints,
788 MediaConstraintsInterface::kOfferToReceiveAudio, &value,
789 &mandatory_constraints_satisfied)) {
790 offer_answer_options->offer_to_receive_audio =
791 value ? PeerConnectionInterface::RTCOfferAnswerOptions::
792 kOfferToReceiveMediaTrue
793 : 0;
794 }
795
796 if (FindConstraint(constraints,
797 MediaConstraintsInterface::kOfferToReceiveVideo, &value,
798 &mandatory_constraints_satisfied)) {
799 offer_answer_options->offer_to_receive_video =
800 value ? PeerConnectionInterface::RTCOfferAnswerOptions::
801 kOfferToReceiveMediaTrue
802 : 0;
803 }
804 if (FindConstraint(constraints,
805 MediaConstraintsInterface::kVoiceActivityDetection, &value,
806 &mandatory_constraints_satisfied)) {
807 offer_answer_options->voice_activity_detection = value;
808 }
809 if (FindConstraint(constraints, MediaConstraintsInterface::kUseRtpMux, &value,
810 &mandatory_constraints_satisfied)) {
811 offer_answer_options->use_rtp_mux = value;
812 }
813 if (FindConstraint(constraints, MediaConstraintsInterface::kIceRestart,
814 &value, &mandatory_constraints_satisfied)) {
815 offer_answer_options->ice_restart = value;
816 }
817
deadbeefab9b2d12015-10-14 11:33:11 -0700818 return mandatory_constraints_satisfied == constraints->GetMandatory().size();
819}
820
zhihuang38ede132017-06-15 12:52:32 -0700821PeerConnection::PeerConnection(PeerConnectionFactory* factory,
822 std::unique_ptr<RtcEventLog> event_log,
823 std::unique_ptr<Call> call)
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000824 : factory_(factory),
zhihuang38ede132017-06-15 12:52:32 -0700825 event_log_(std::move(event_log)),
zhihuang8f65cdf2016-05-06 18:40:30 -0700826 rtcp_cname_(GenerateRtcpCname()),
deadbeefab9b2d12015-10-14 11:33:11 -0700827 local_streams_(StreamCollection::Create()),
zhihuang38ede132017-06-15 12:52:32 -0700828 remote_streams_(StreamCollection::Create()),
829 call_(std::move(call)) {}
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000830
831PeerConnection::~PeerConnection() {
Peter Boström1a9d6152015-12-08 22:15:17 +0100832 TRACE_EVENT0("webrtc", "PeerConnection::~PeerConnection");
Steve Anton4171afb2017-11-20 10:20:22 -0800833 RTC_DCHECK_RUN_ON(signaling_thread());
834
835 // Need to detach RTP transceivers from PeerConnection, since it's about to be
836 // destroyed.
837 for (auto transceiver : transceivers_) {
838 transceiver->Stop();
deadbeef70ab1a12015-09-28 16:53:55 -0700839 }
Steve Anton4171afb2017-11-20 10:20:22 -0800840
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700841 // Destroy stats_ because it depends on session_.
842 stats_.reset(nullptr);
hbosb78306a2016-12-19 05:06:57 -0800843 if (stats_collector_) {
844 stats_collector_->WaitForPendingRequest();
845 stats_collector_ = nullptr;
846 }
Steve Anton75737c02017-11-06 10:37:17 -0800847
848 // Destroy video channels first since they may have a pointer to a voice
849 // channel.
Steve Anton4171afb2017-11-20 10:20:22 -0800850 for (auto transceiver : transceivers_) {
851 if (transceiver->internal()->media_type() == cricket::MEDIA_TYPE_VIDEO &&
852 transceiver->internal()->channel()) {
853 DestroyVideoChannel(static_cast<cricket::VideoChannel*>(
854 transceiver->internal()->channel()));
855 }
Steve Anton75737c02017-11-06 10:37:17 -0800856 }
Steve Anton4171afb2017-11-20 10:20:22 -0800857 for (auto transceiver : transceivers_) {
858 if (transceiver->internal()->media_type() == cricket::MEDIA_TYPE_AUDIO &&
859 transceiver->internal()->channel()) {
860 DestroyVoiceChannel(static_cast<cricket::VoiceChannel*>(
861 transceiver->internal()->channel()));
862 }
Steve Anton75737c02017-11-06 10:37:17 -0800863 }
864 if (rtp_data_channel_) {
865 DestroyDataChannel();
866 }
867
868 // Note: Cannot use rtc::Bind to create a functor to invoke because it will
869 // grab a reference to this PeerConnection. The RefCountedObject vtable will
870 // have already been destroyed (since it is a subclass of PeerConnection) and
871 // using rtc::Bind will cause "Pure virtual function called" error to appear.
872
873 if (sctp_transport_) {
874 OnDataChannelDestroyed();
875 network_thread()->Invoke<void>(RTC_FROM_HERE,
876 [this] { DestroySctpTransport_n(); });
877 }
878
Mirko Bonadei675513b2017-11-09 11:09:25 +0100879 RTC_LOG(LS_INFO) << "Session: " << session_id() << " is destroyed.";
Steve Anton75737c02017-11-06 10:37:17 -0800880
881 webrtc_session_desc_factory_.reset();
882 sctp_invoker_.reset();
883 sctp_factory_.reset();
884 transport_controller_.reset();
885
deadbeef91dd5672016-05-18 16:55:30 -0700886 // port_allocator_ lives on the network thread and should be destroyed there.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700887 network_thread()->Invoke<void>(RTC_FROM_HERE,
nisseeaabdf62017-05-05 02:23:02 -0700888 [this] { port_allocator_.reset(); });
eladalon248fd4f2017-09-06 05:18:15 -0700889 // call_ and event_log_ must be destroyed on the worker thread.
Steve Anton978b8762017-09-29 12:15:02 -0700890 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
eladalon248fd4f2017-09-06 05:18:15 -0700891 call_.reset();
892 event_log_.reset();
893 });
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000894}
895
896bool PeerConnection::Initialize(
buildbot@webrtc.org41451d42014-05-03 05:39:45 +0000897 const PeerConnectionInterface::RTCConfiguration& configuration,
kwibergd1fe2812016-04-27 06:47:29 -0700898 std::unique_ptr<cricket::PortAllocator> allocator,
Henrik Boströmd03c23b2016-06-01 11:44:18 +0200899 std::unique_ptr<rtc::RTCCertificateGeneratorInterface> cert_generator,
deadbeef653b8e02015-11-11 12:55:10 -0800900 PeerConnectionObserver* observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100901 TRACE_EVENT0("webrtc", "PeerConnection::Initialize");
Steve Anton038834f2017-07-14 15:59:59 -0700902
903 RTCError config_error = ValidateConfiguration(configuration);
904 if (!config_error.ok()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100905 RTC_LOG(LS_ERROR) << "Invalid configuration: " << config_error.message();
Steve Anton038834f2017-07-14 15:59:59 -0700906 return false;
907 }
908
deadbeef293e9262017-01-11 12:28:30 -0800909 if (!allocator) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100910 RTC_LOG(LS_ERROR)
911 << "PeerConnection initialized without a PortAllocator? "
912 << "This shouldn't happen if using PeerConnectionFactory.";
deadbeef293e9262017-01-11 12:28:30 -0800913 return false;
914 }
Jonas Orelandbdcee282017-10-10 14:01:40 +0200915
deadbeef653b8e02015-11-11 12:55:10 -0800916 if (!observer) {
deadbeef293e9262017-01-11 12:28:30 -0800917 // TODO(deadbeef): Why do we do this?
Mirko Bonadei675513b2017-11-09 11:09:25 +0100918 RTC_LOG(LS_ERROR) << "PeerConnection initialized without a "
919 << "PeerConnectionObserver";
deadbeef653b8e02015-11-11 12:55:10 -0800920 return false;
921 }
pthatcher@webrtc.org877ac762015-02-04 22:03:09 +0000922 observer_ = observer;
kwiberg0eb15ed2015-12-17 03:04:15 -0800923 port_allocator_ = std::move(allocator);
deadbeef653b8e02015-11-11 12:55:10 -0800924
deadbeef91dd5672016-05-18 16:55:30 -0700925 // The port allocator lives on the network thread and should be initialized
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700926 // there.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700927 if (!network_thread()->Invoke<bool>(
928 RTC_FROM_HERE, rtc::Bind(&PeerConnection::InitializePortAllocator_n,
929 this, configuration))) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000930 return false;
931 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000932
Steve Anton75737c02017-11-06 10:37:17 -0800933 // RFC 3264: The numeric value of the session id and version in the
934 // o line MUST be representable with a "64 bit signed integer".
935 // Due to this constraint session id |session_id_| is max limited to
936 // LLONG_MAX.
937 session_id_ = rtc::ToString(rtc::CreateRandomId64() & LLONG_MAX);
938 transport_controller_.reset(factory_->CreateTransportController(
939 port_allocator_.get(), configuration.redetermine_role_on_ice_restart));
940 transport_controller_->SetIceRole(cricket::ICEROLE_CONTROLLED);
941 transport_controller_->SignalConnectionState.connect(
942 this, &PeerConnection::OnTransportControllerConnectionState);
943 transport_controller_->SignalGatheringState.connect(
944 this, &PeerConnection::OnTransportControllerGatheringState);
945 transport_controller_->SignalCandidatesGathered.connect(
946 this, &PeerConnection::OnTransportControllerCandidatesGathered);
947 transport_controller_->SignalCandidatesRemoved.connect(
948 this, &PeerConnection::OnTransportControllerCandidatesRemoved);
949 transport_controller_->SignalDtlsHandshakeError.connect(
950 this, &PeerConnection::OnTransportControllerDtlsHandshakeError);
951
952 sctp_factory_ = factory_->CreateSctpTransportInternalFactory();
zhihuang29ff8442016-07-27 11:07:25 -0700953
deadbeefab9b2d12015-10-14 11:33:11 -0700954 stats_.reset(new StatsCollector(this));
hbos74e1a4f2016-09-15 23:33:01 -0700955 stats_collector_ = RTCStatsCollector::Create(this);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000956
Steve Antonba818672017-11-06 10:21:57 -0800957 configuration_ = configuration;
958
Steve Anton75737c02017-11-06 10:37:17 -0800959 const PeerConnectionFactoryInterface::Options& options = factory_->options();
960
961 transport_controller_->SetSslMaxProtocolVersion(options.ssl_max_version);
962
963 // Obtain a certificate from RTCConfiguration if any were provided (optional).
964 rtc::scoped_refptr<rtc::RTCCertificate> certificate;
965 if (!configuration.certificates.empty()) {
966 // TODO(hbos,torbjorng): Decide on certificate-selection strategy instead of
967 // just picking the first one. The decision should be made based on the DTLS
968 // handshake. The DTLS negotiations need to know about all certificates.
969 certificate = configuration.certificates[0];
970 }
971
Steve Antond25da372017-11-06 14:50:29 -0800972 transport_controller_->SetIceConfig(ParseIceConfig(configuration));
Steve Anton75737c02017-11-06 10:37:17 -0800973
974 if (options.disable_encryption) {
975 dtls_enabled_ = false;
976 } else {
977 // Enable DTLS by default if we have an identity store or a certificate.
978 dtls_enabled_ = (cert_generator || certificate);
979 // |configuration| can override the default |dtls_enabled_| value.
980 if (configuration.enable_dtls_srtp) {
981 dtls_enabled_ = *(configuration.enable_dtls_srtp);
982 }
983 }
984
985 // Enable creation of RTP data channels if the kEnableRtpDataChannels is set.
986 // It takes precendence over the disable_sctp_data_channels
987 // PeerConnectionFactoryInterface::Options.
988 if (configuration.enable_rtp_data_channel) {
989 data_channel_type_ = cricket::DCT_RTP;
990 } else {
991 // DTLS has to be enabled to use SCTP.
992 if (!options.disable_sctp_data_channels && dtls_enabled_) {
993 data_channel_type_ = cricket::DCT_SCTP;
994 }
995 }
996
997 video_options_.screencast_min_bitrate_kbps =
998 configuration.screencast_min_bitrate;
999 audio_options_.combined_audio_video_bwe =
1000 configuration.combined_audio_video_bwe;
1001
1002 audio_options_.audio_jitter_buffer_max_packets =
Oskar Sundbom9b28a032017-11-16 10:53:30 +01001003 configuration.audio_jitter_buffer_max_packets;
Steve Anton75737c02017-11-06 10:37:17 -08001004
1005 audio_options_.audio_jitter_buffer_fast_accelerate =
Oskar Sundbom9b28a032017-11-16 10:53:30 +01001006 configuration.audio_jitter_buffer_fast_accelerate;
Steve Anton75737c02017-11-06 10:37:17 -08001007
1008 // Whether the certificate generator/certificate is null or not determines
1009 // what PeerConnectionDescriptionFactory will do, so make sure that we give it
1010 // the right instructions by clearing the variables if needed.
1011 if (!dtls_enabled_) {
1012 cert_generator.reset();
1013 certificate = nullptr;
1014 } else if (certificate) {
1015 // Favor generated certificate over the certificate generator.
1016 cert_generator.reset();
1017 }
1018
1019 webrtc_session_desc_factory_.reset(new WebRtcSessionDescriptionFactory(
1020 signaling_thread(), channel_manager(), this, session_id(),
1021 std::move(cert_generator), certificate));
1022 webrtc_session_desc_factory_->SignalCertificateReady.connect(
1023 this, &PeerConnection::OnCertificateReady);
1024
1025 if (options.disable_encryption) {
1026 webrtc_session_desc_factory_->SetSdesPolicy(cricket::SEC_DISABLED);
1027 }
1028
1029 webrtc_session_desc_factory_->set_enable_encrypted_rtp_header_extensions(
1030 options.crypto_options.enable_encrypted_rtp_header_extensions);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001031
Steve Anton4171afb2017-11-20 10:20:22 -08001032 // Add default audio/video transceivers for Plan B SDP.
1033 if (!IsUnifiedPlan()) {
1034 transceivers_.push_back(
1035 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1036 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_AUDIO)));
1037 transceivers_.push_back(
1038 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1039 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_VIDEO)));
1040 }
1041
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001042 return true;
1043}
1044
Steve Anton038834f2017-07-14 15:59:59 -07001045RTCError PeerConnection::ValidateConfiguration(
1046 const RTCConfiguration& config) const {
1047 if (config.ice_regather_interval_range &&
1048 config.continual_gathering_policy == GATHER_ONCE) {
1049 return RTCError(RTCErrorType::INVALID_PARAMETER,
1050 "ice_regather_interval_range specified but continual "
1051 "gathering policy is GATHER_ONCE");
1052 }
1053 return RTCError::OK();
1054}
1055
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001056rtc::scoped_refptr<StreamCollectionInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001057PeerConnection::local_streams() {
deadbeefab9b2d12015-10-14 11:33:11 -07001058 return local_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001059}
1060
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001061rtc::scoped_refptr<StreamCollectionInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001062PeerConnection::remote_streams() {
deadbeefab9b2d12015-10-14 11:33:11 -07001063 return remote_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001064}
1065
perkj@webrtc.orgc2dd5ee2014-11-04 11:31:29 +00001066bool PeerConnection::AddStream(MediaStreamInterface* local_stream) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001067 TRACE_EVENT0("webrtc", "PeerConnection::AddStream");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001068 if (IsClosed()) {
1069 return false;
1070 }
deadbeefab9b2d12015-10-14 11:33:11 -07001071 if (!CanAddLocalMediaStream(local_streams_, local_stream)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001072 return false;
1073 }
deadbeefab9b2d12015-10-14 11:33:11 -07001074
1075 local_streams_->AddStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -08001076 MediaStreamObserver* observer = new MediaStreamObserver(local_stream);
1077 observer->SignalAudioTrackAdded.connect(this,
1078 &PeerConnection::OnAudioTrackAdded);
1079 observer->SignalAudioTrackRemoved.connect(
1080 this, &PeerConnection::OnAudioTrackRemoved);
1081 observer->SignalVideoTrackAdded.connect(this,
1082 &PeerConnection::OnVideoTrackAdded);
1083 observer->SignalVideoTrackRemoved.connect(
1084 this, &PeerConnection::OnVideoTrackRemoved);
kwibergd1fe2812016-04-27 06:47:29 -07001085 stream_observers_.push_back(std::unique_ptr<MediaStreamObserver>(observer));
deadbeefab9b2d12015-10-14 11:33:11 -07001086
deadbeefab9b2d12015-10-14 11:33:11 -07001087 for (const auto& track : local_stream->GetAudioTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001088 AddAudioTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -07001089 }
1090 for (const auto& track : local_stream->GetVideoTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001091 AddVideoTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -07001092 }
1093
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001094 stats_->AddStream(local_stream);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001095 observer_->OnRenegotiationNeeded();
1096 return true;
1097}
1098
1099void PeerConnection::RemoveStream(MediaStreamInterface* local_stream) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001100 TRACE_EVENT0("webrtc", "PeerConnection::RemoveStream");
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001101 if (!IsClosed()) {
1102 for (const auto& track : local_stream->GetAudioTracks()) {
1103 RemoveAudioTrack(track.get(), local_stream);
1104 }
1105 for (const auto& track : local_stream->GetVideoTracks()) {
1106 RemoveVideoTrack(track.get(), local_stream);
1107 }
deadbeefab9b2d12015-10-14 11:33:11 -07001108 }
deadbeefab9b2d12015-10-14 11:33:11 -07001109 local_streams_->RemoveStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -08001110 stream_observers_.erase(
1111 std::remove_if(
1112 stream_observers_.begin(), stream_observers_.end(),
kwibergd1fe2812016-04-27 06:47:29 -07001113 [local_stream](const std::unique_ptr<MediaStreamObserver>& observer) {
deadbeefeb459812015-12-15 19:24:43 -08001114 return observer->stream()->label().compare(local_stream->label()) ==
1115 0;
1116 }),
1117 stream_observers_.end());
deadbeefab9b2d12015-10-14 11:33:11 -07001118
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001119 if (IsClosed()) {
1120 return;
1121 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001122 observer_->OnRenegotiationNeeded();
1123}
1124
deadbeefe1f9d832016-01-14 15:35:42 -08001125rtc::scoped_refptr<RtpSenderInterface> PeerConnection::AddTrack(
1126 MediaStreamTrackInterface* track,
1127 std::vector<MediaStreamInterface*> streams) {
1128 TRACE_EVENT0("webrtc", "PeerConnection::AddTrack");
1129 if (IsClosed()) {
1130 return nullptr;
1131 }
1132 if (streams.size() >= 2) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001133 RTC_LOG(LS_ERROR)
deadbeefe1f9d832016-01-14 15:35:42 -08001134 << "Adding a track with two streams is not currently supported.";
1135 return nullptr;
1136 }
Steve Anton4171afb2017-11-20 10:20:22 -08001137 if (FindSenderForTrack(track)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001138 RTC_LOG(LS_ERROR) << "Sender for track " << track->id()
1139 << " already exists.";
deadbeefe1f9d832016-01-14 15:35:42 -08001140 return nullptr;
1141 }
1142
1143 // TODO(deadbeef): Support adding a track to multiple streams.
deadbeefa601f5c2016-06-06 14:27:39 -07001144 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender;
deadbeefe1f9d832016-01-14 15:35:42 -08001145 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
deadbeefa601f5c2016-06-06 14:27:39 -07001146 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
deadbeefe1f9d832016-01-14 15:35:42 -08001147 signaling_thread(),
1148 new AudioRtpSender(static_cast<AudioTrackInterface*>(track),
Steve Anton75737c02017-11-06 10:37:17 -08001149 voice_channel(), stats_.get()));
Steve Anton4171afb2017-11-20 10:20:22 -08001150 GetAudioTransceiver()->internal()->AddSender(new_sender);
deadbeefe1f9d832016-01-14 15:35:42 -08001151 if (!streams.empty()) {
deadbeefa601f5c2016-06-06 14:27:39 -07001152 new_sender->internal()->set_stream_id(streams[0]->label());
deadbeefe1f9d832016-01-14 15:35:42 -08001153 }
Steve Anton4171afb2017-11-20 10:20:22 -08001154 const RtpSenderInfo* sender_info =
1155 FindSenderInfo(local_audio_sender_infos_,
1156 new_sender->internal()->stream_id(), track->id());
1157 if (sender_info) {
1158 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -08001159 }
1160 } else if (track->kind() == MediaStreamTrackInterface::kVideoKind) {
deadbeefa601f5c2016-06-06 14:27:39 -07001161 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
deadbeefe1f9d832016-01-14 15:35:42 -08001162 signaling_thread(),
1163 new VideoRtpSender(static_cast<VideoTrackInterface*>(track),
Steve Anton75737c02017-11-06 10:37:17 -08001164 video_channel()));
Steve Anton4171afb2017-11-20 10:20:22 -08001165 GetVideoTransceiver()->internal()->AddSender(new_sender);
deadbeefe1f9d832016-01-14 15:35:42 -08001166 if (!streams.empty()) {
deadbeefa601f5c2016-06-06 14:27:39 -07001167 new_sender->internal()->set_stream_id(streams[0]->label());
deadbeefe1f9d832016-01-14 15:35:42 -08001168 }
Steve Anton4171afb2017-11-20 10:20:22 -08001169 const RtpSenderInfo* sender_info =
1170 FindSenderInfo(local_video_sender_infos_,
1171 new_sender->internal()->stream_id(), track->id());
1172 if (sender_info) {
1173 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -08001174 }
1175 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001176 RTC_LOG(LS_ERROR) << "CreateSender called with invalid kind: "
1177 << track->kind();
deadbeefe1f9d832016-01-14 15:35:42 -08001178 return rtc::scoped_refptr<RtpSenderInterface>();
1179 }
1180
deadbeefe1f9d832016-01-14 15:35:42 -08001181 observer_->OnRenegotiationNeeded();
1182 return new_sender;
1183}
1184
1185bool PeerConnection::RemoveTrack(RtpSenderInterface* sender) {
1186 TRACE_EVENT0("webrtc", "PeerConnection::RemoveTrack");
1187 if (IsClosed()) {
1188 return false;
1189 }
1190
Steve Anton4171afb2017-11-20 10:20:22 -08001191 bool removed;
1192 if (sender->media_type() == cricket::MEDIA_TYPE_AUDIO) {
1193 removed = GetAudioTransceiver()->internal()->RemoveSender(sender);
1194 } else {
1195 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, sender->media_type());
1196 removed = GetVideoTransceiver()->internal()->RemoveSender(sender);
1197 }
1198 if (!removed) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001199 RTC_LOG(LS_ERROR) << "Couldn't find sender " << sender->id()
1200 << " to remove.";
deadbeefe1f9d832016-01-14 15:35:42 -08001201 return false;
1202 }
deadbeefe1f9d832016-01-14 15:35:42 -08001203
1204 observer_->OnRenegotiationNeeded();
1205 return true;
1206}
1207
Steve Anton9158ef62017-11-27 13:01:52 -08001208RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1209PeerConnection::AddTransceiver(
1210 rtc::scoped_refptr<MediaStreamTrackInterface> track) {
1211 return AddTransceiver(track, RtpTransceiverInit());
1212}
1213
1214RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1215PeerConnection::AddTransceiver(
1216 rtc::scoped_refptr<MediaStreamTrackInterface> track,
1217 const RtpTransceiverInit& init) {
1218 if (!IsUnifiedPlan()) {
1219 LOG_AND_RETURN_ERROR(
1220 RTCErrorType::INTERNAL_ERROR,
1221 "AddTransceiver only supported when Unified Plan is enabled.");
1222 }
1223 if (!track) {
1224 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "track is null");
1225 }
1226 cricket::MediaType media_type;
1227 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
1228 media_type = cricket::MEDIA_TYPE_AUDIO;
1229 } else if (track->kind() == MediaStreamTrackInterface::kVideoKind) {
1230 media_type = cricket::MEDIA_TYPE_VIDEO;
1231 } else {
1232 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1233 "Track kind is not audio or video");
1234 }
1235 return AddTransceiver(media_type, track, init);
1236}
1237
1238RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1239PeerConnection::AddTransceiver(cricket::MediaType media_type) {
1240 return AddTransceiver(media_type, RtpTransceiverInit());
1241}
1242
1243RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1244PeerConnection::AddTransceiver(cricket::MediaType media_type,
1245 const RtpTransceiverInit& init) {
1246 if (!IsUnifiedPlan()) {
1247 LOG_AND_RETURN_ERROR(
1248 RTCErrorType::INTERNAL_ERROR,
1249 "AddTransceiver only supported when Unified Plan is enabled.");
1250 }
1251 if (!(media_type == cricket::MEDIA_TYPE_AUDIO ||
1252 media_type == cricket::MEDIA_TYPE_VIDEO)) {
1253 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1254 "media type is not audio or video");
1255 }
1256 return AddTransceiver(media_type, nullptr, init);
1257}
1258
1259RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1260PeerConnection::AddTransceiver(
1261 cricket::MediaType media_type,
1262 rtc::scoped_refptr<MediaStreamTrackInterface> track,
1263 const RtpTransceiverInit& init) {
1264 RTC_DCHECK((media_type == cricket::MEDIA_TYPE_AUDIO ||
1265 media_type == cricket::MEDIA_TYPE_VIDEO));
1266 if (track) {
1267 RTC_DCHECK_EQ(media_type,
1268 (track->kind() == MediaStreamTrackInterface::kAudioKind
1269 ? cricket::MEDIA_TYPE_AUDIO
1270 : cricket::MEDIA_TYPE_VIDEO));
1271 }
1272
1273 // TODO(bugs.webrtc.org/7600): Verify init.
1274
1275 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> sender;
1276 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1277 receiver;
1278 std::string receiver_id = rtc::CreateRandomUuid();
1279 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
1280 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
1281 signaling_thread(), new AudioRtpSender(nullptr, stats_.get()));
1282 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
1283 signaling_thread(), new AudioRtpReceiver(receiver_id, {}, 0, nullptr));
1284 } else {
1285 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, media_type);
1286 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
1287 signaling_thread(), new VideoRtpSender(nullptr));
1288 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
1289 signaling_thread(),
1290 new VideoRtpReceiver(receiver_id, {}, worker_thread(), 0, nullptr));
1291 }
1292 // TODO(bugs.webrtc.org/7600): Initializing the sender/receiver with a null
1293 // channel prevents users from calling SetParameters on them, which is needed
1294 // to be in compliance with the spec.
1295
1296 if (track) {
1297 sender->SetTrack(track);
1298 }
1299
1300 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1301 transceiver = RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1302 signaling_thread(), new RtpTransceiver(sender, receiver));
1303 transceiver->SetDirection(init.direction);
1304
1305 transceivers_.push_back(transceiver);
1306
1307 observer_->OnRenegotiationNeeded();
1308
1309 return rtc::scoped_refptr<RtpTransceiverInterface>(transceiver);
1310}
1311
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001312rtc::scoped_refptr<DtmfSenderInterface> PeerConnection::CreateDtmfSender(
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001313 AudioTrackInterface* track) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001314 TRACE_EVENT0("webrtc", "PeerConnection::CreateDtmfSender");
zhihuang29ff8442016-07-27 11:07:25 -07001315 if (IsClosed()) {
1316 return nullptr;
1317 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001318 if (!track) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001319 RTC_LOG(LS_ERROR) << "CreateDtmfSender - track is NULL.";
deadbeef20cb0c12017-02-01 20:27:00 -08001320 return nullptr;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001321 }
Steve Anton4171afb2017-11-20 10:20:22 -08001322 auto track_sender = FindSenderForTrack(track);
1323 if (!track_sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001324 RTC_LOG(LS_ERROR) << "CreateDtmfSender called with a non-added track.";
deadbeef20cb0c12017-02-01 20:27:00 -08001325 return nullptr;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001326 }
1327
Steve Anton4171afb2017-11-20 10:20:22 -08001328 return track_sender->GetDtmfSender();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001329}
1330
deadbeeffac06552015-11-25 11:26:01 -08001331rtc::scoped_refptr<RtpSenderInterface> PeerConnection::CreateSender(
deadbeefbd7d8f72015-12-18 16:58:44 -08001332 const std::string& kind,
1333 const std::string& stream_id) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001334 TRACE_EVENT0("webrtc", "PeerConnection::CreateSender");
zhihuang29ff8442016-07-27 11:07:25 -07001335 if (IsClosed()) {
1336 return nullptr;
1337 }
Steve Anton4171afb2017-11-20 10:20:22 -08001338
1339 // TODO(steveanton): Move construction of the RtpSenders to RtpTransceiver.
deadbeefa601f5c2016-06-06 14:27:39 -07001340 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender;
deadbeeffac06552015-11-25 11:26:01 -08001341 if (kind == MediaStreamTrackInterface::kAudioKind) {
deadbeefa601f5c2016-06-06 14:27:39 -07001342 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton75737c02017-11-06 10:37:17 -08001343 signaling_thread(), new AudioRtpSender(voice_channel(), stats_.get()));
Steve Anton4171afb2017-11-20 10:20:22 -08001344 GetAudioTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 11:26:01 -08001345 } else if (kind == MediaStreamTrackInterface::kVideoKind) {
deadbeefa601f5c2016-06-06 14:27:39 -07001346 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton75737c02017-11-06 10:37:17 -08001347 signaling_thread(), new VideoRtpSender(video_channel()));
Steve Anton4171afb2017-11-20 10:20:22 -08001348 GetVideoTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 11:26:01 -08001349 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001350 RTC_LOG(LS_ERROR) << "CreateSender called with invalid kind: " << kind;
Steve Anton4171afb2017-11-20 10:20:22 -08001351 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08001352 }
Steve Anton4171afb2017-11-20 10:20:22 -08001353
deadbeefbd7d8f72015-12-18 16:58:44 -08001354 if (!stream_id.empty()) {
deadbeefa601f5c2016-06-06 14:27:39 -07001355 new_sender->internal()->set_stream_id(stream_id);
deadbeefbd7d8f72015-12-18 16:58:44 -08001356 }
Steve Anton4171afb2017-11-20 10:20:22 -08001357
deadbeefe1f9d832016-01-14 15:35:42 -08001358 return new_sender;
deadbeeffac06552015-11-25 11:26:01 -08001359}
1360
deadbeef70ab1a12015-09-28 16:53:55 -07001361std::vector<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::GetSenders()
1362 const {
deadbeefa601f5c2016-06-06 14:27:39 -07001363 std::vector<rtc::scoped_refptr<RtpSenderInterface>> ret;
Steve Anton4171afb2017-11-20 10:20:22 -08001364 for (auto sender : GetSendersInternal()) {
1365 ret.push_back(sender);
deadbeefa601f5c2016-06-06 14:27:39 -07001366 }
1367 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -07001368}
1369
Steve Anton4171afb2017-11-20 10:20:22 -08001370std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1371PeerConnection::GetSendersInternal() const {
1372 std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1373 all_senders;
1374 for (auto transceiver : transceivers_) {
1375 auto senders = transceiver->internal()->senders();
1376 all_senders.insert(all_senders.end(), senders.begin(), senders.end());
1377 }
1378 return all_senders;
1379}
1380
deadbeef70ab1a12015-09-28 16:53:55 -07001381std::vector<rtc::scoped_refptr<RtpReceiverInterface>>
1382PeerConnection::GetReceivers() const {
deadbeefa601f5c2016-06-06 14:27:39 -07001383 std::vector<rtc::scoped_refptr<RtpReceiverInterface>> ret;
Steve Anton4171afb2017-11-20 10:20:22 -08001384 for (const auto& receiver : GetReceiversInternal()) {
1385 ret.push_back(receiver);
deadbeefa601f5c2016-06-06 14:27:39 -07001386 }
1387 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -07001388}
1389
Steve Anton4171afb2017-11-20 10:20:22 -08001390std::vector<
1391 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1392PeerConnection::GetReceiversInternal() const {
1393 std::vector<
1394 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1395 all_receivers;
1396 for (auto transceiver : transceivers_) {
1397 auto receivers = transceiver->internal()->receivers();
1398 all_receivers.insert(all_receivers.end(), receivers.begin(),
1399 receivers.end());
1400 }
1401 return all_receivers;
1402}
1403
Steve Anton9158ef62017-11-27 13:01:52 -08001404std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
1405PeerConnection::GetTransceivers() const {
1406 RTC_DCHECK(IsUnifiedPlan());
1407 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> all_transceivers;
1408 for (auto transceiver : transceivers_) {
1409 all_transceivers.push_back(transceiver);
1410 }
1411 return all_transceivers;
1412}
1413
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001414bool PeerConnection::GetStats(StatsObserver* observer,
wu@webrtc.orgb9a088b2014-02-13 23:18:49 +00001415 MediaStreamTrackInterface* track,
1416 StatsOutputLevel level) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001417 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
deadbeef0a6c4ca2015-10-06 11:38:28 -07001418 RTC_DCHECK(signaling_thread()->IsCurrent());
nisse7ce109a2017-01-31 00:57:56 -08001419 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001420 RTC_LOG(LS_ERROR) << "GetStats - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001421 return false;
1422 }
1423
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001424 stats_->UpdateStats(level);
zhihuange9e94c32016-11-04 11:38:15 -07001425 // The StatsCollector is used to tell if a track is valid because it may
1426 // remember tracks that the PeerConnection previously removed.
1427 if (track && !stats_->IsValidTrack(track->id())) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001428 RTC_LOG(LS_WARNING) << "GetStats is called with an invalid track: "
1429 << track->id();
zhihuange9e94c32016-11-04 11:38:15 -07001430 return false;
1431 }
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001432 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_GETSTATS,
tommi@webrtc.org5b06b062014-08-15 08:38:30 +00001433 new GetStatsMsg(observer, track));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001434 return true;
1435}
1436
hbos74e1a4f2016-09-15 23:33:01 -07001437void PeerConnection::GetStats(RTCStatsCollectorCallback* callback) {
1438 RTC_DCHECK(stats_collector_);
1439 stats_collector_->GetStatsReport(callback);
1440}
1441
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001442PeerConnectionInterface::SignalingState PeerConnection::signaling_state() {
1443 return signaling_state_;
1444}
1445
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001446PeerConnectionInterface::IceConnectionState
1447PeerConnection::ice_connection_state() {
1448 return ice_connection_state_;
1449}
1450
1451PeerConnectionInterface::IceGatheringState
1452PeerConnection::ice_gathering_state() {
1453 return ice_gathering_state_;
1454}
1455
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001456rtc::scoped_refptr<DataChannelInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001457PeerConnection::CreateDataChannel(
1458 const std::string& label,
1459 const DataChannelInit* config) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001460 TRACE_EVENT0("webrtc", "PeerConnection::CreateDataChannel");
zhihuang9763d562016-08-05 11:14:50 -07001461
deadbeefab9b2d12015-10-14 11:33:11 -07001462 bool first_datachannel = !HasDataChannels();
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001463
kwibergd1fe2812016-04-27 06:47:29 -07001464 std::unique_ptr<InternalDataChannelInit> internal_config;
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00001465 if (config) {
1466 internal_config.reset(new InternalDataChannelInit(*config));
1467 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001468 rtc::scoped_refptr<DataChannelInterface> channel(
deadbeefab9b2d12015-10-14 11:33:11 -07001469 InternalCreateDataChannel(label, internal_config.get()));
1470 if (!channel.get()) {
1471 return nullptr;
1472 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001473
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001474 // Trigger the onRenegotiationNeeded event for every new RTP DataChannel, or
1475 // the first SCTP DataChannel.
Steve Anton75737c02017-11-06 10:37:17 -08001476 if (data_channel_type() == cricket::DCT_RTP || first_datachannel) {
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001477 observer_->OnRenegotiationNeeded();
1478 }
wu@webrtc.org91053e72013-08-10 07:18:04 +00001479
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001480 return DataChannelProxy::Create(signaling_thread(), channel.get());
1481}
1482
1483void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
1484 const MediaConstraintsInterface* constraints) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001485 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
Steve Anton8d3444d2017-10-20 15:30:51 -07001486
zhihuang1c378ed2017-08-17 14:10:50 -07001487 PeerConnectionInterface::RTCOfferAnswerOptions offer_answer_options;
1488 // Always create an offer even if |ConvertConstraintsToOfferAnswerOptions|
1489 // returns false for now. Because |ConvertConstraintsToOfferAnswerOptions|
1490 // compares the mandatory fields parsed with the mandatory fields added in the
1491 // |constraints| and some downstream applications might create offers with
1492 // mandatory fields which would not be parsed in the helper method. For
1493 // example, in Chromium/remoting, |kEnableDtlsSrtp| is added to the
1494 // |constraints| as a mandatory field but it is not parsed.
1495 ConvertConstraintsToOfferAnswerOptions(constraints, &offer_answer_options);
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001496
zhihuang1c378ed2017-08-17 14:10:50 -07001497 CreateOffer(observer, offer_answer_options);
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001498}
1499
1500void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
1501 const RTCOfferAnswerOptions& options) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001502 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
Steve Anton8d3444d2017-10-20 15:30:51 -07001503
nisse7ce109a2017-01-31 00:57:56 -08001504 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001505 RTC_LOG(LS_ERROR) << "CreateOffer - observer is NULL.";
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001506 return;
1507 }
deadbeefab9b2d12015-10-14 11:33:11 -07001508
Steve Anton8d3444d2017-10-20 15:30:51 -07001509 if (IsClosed()) {
1510 std::string error = "CreateOffer called when PeerConnection is closed.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001511 RTC_LOG(LS_ERROR) << error;
Steve Anton8d3444d2017-10-20 15:30:51 -07001512 PostCreateSessionDescriptionFailure(observer, error);
1513 return;
1514 }
1515
zhihuang1c378ed2017-08-17 14:10:50 -07001516 if (!ValidateOfferAnswerOptions(options)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001517 std::string error = "CreateOffer called with invalid options.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001518 RTC_LOG(LS_ERROR) << error;
deadbeefab9b2d12015-10-14 11:33:11 -07001519 PostCreateSessionDescriptionFailure(observer, error);
1520 return;
1521 }
1522
zhihuang1c378ed2017-08-17 14:10:50 -07001523 cricket::MediaSessionOptions session_options;
1524 GetOptionsForOffer(options, &session_options);
Steve Antond25da372017-11-06 14:50:29 -08001525 webrtc_session_desc_factory_->CreateOffer(observer, options, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001526}
1527
1528void PeerConnection::CreateAnswer(
1529 CreateSessionDescriptionObserver* observer,
1530 const MediaConstraintsInterface* constraints) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001531 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
Steve Anton8d3444d2017-10-20 15:30:51 -07001532
nisse7ce109a2017-01-31 00:57:56 -08001533 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001534 RTC_LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001535 return;
1536 }
deadbeefab9b2d12015-10-14 11:33:11 -07001537
zhihuang1c378ed2017-08-17 14:10:50 -07001538 PeerConnectionInterface::RTCOfferAnswerOptions offer_answer_options;
1539 if (!ConvertConstraintsToOfferAnswerOptions(constraints,
1540 &offer_answer_options)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001541 std::string error = "CreateAnswer called with invalid constraints.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001542 RTC_LOG(LS_ERROR) << error;
deadbeefab9b2d12015-10-14 11:33:11 -07001543 PostCreateSessionDescriptionFailure(observer, error);
1544 return;
1545 }
1546
Steve Anton8d3444d2017-10-20 15:30:51 -07001547 CreateAnswer(observer, offer_answer_options);
htaa2a49d92016-03-04 02:51:39 -08001548}
1549
1550void PeerConnection::CreateAnswer(CreateSessionDescriptionObserver* observer,
1551 const RTCOfferAnswerOptions& options) {
1552 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
nisse7ce109a2017-01-31 00:57:56 -08001553 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001554 RTC_LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
htaa2a49d92016-03-04 02:51:39 -08001555 return;
1556 }
1557
Steve Anton8d3444d2017-10-20 15:30:51 -07001558 if (IsClosed()) {
1559 std::string error = "CreateAnswer called when PeerConnection is closed.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001560 RTC_LOG(LS_ERROR) << error;
Steve Anton8d3444d2017-10-20 15:30:51 -07001561 PostCreateSessionDescriptionFailure(observer, error);
1562 return;
1563 }
1564
Steve Anton75737c02017-11-06 10:37:17 -08001565 if (remote_description() &&
1566 remote_description()->type() != SessionDescriptionInterface::kOffer) {
Steve Anton8d3444d2017-10-20 15:30:51 -07001567 std::string error = "CreateAnswer called without remote offer.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001568 RTC_LOG(LS_ERROR) << error;
Steve Anton8d3444d2017-10-20 15:30:51 -07001569 PostCreateSessionDescriptionFailure(observer, error);
1570 return;
1571 }
1572
htaa2a49d92016-03-04 02:51:39 -08001573 cricket::MediaSessionOptions session_options;
zhihuang1c378ed2017-08-17 14:10:50 -07001574 GetOptionsForAnswer(options, &session_options);
htaa2a49d92016-03-04 02:51:39 -08001575
Steve Antond25da372017-11-06 14:50:29 -08001576 webrtc_session_desc_factory_->CreateAnswer(observer, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001577}
1578
1579void PeerConnection::SetLocalDescription(
1580 SetSessionDescriptionObserver* observer,
1581 SessionDescriptionInterface* desc) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001582 TRACE_EVENT0("webrtc", "PeerConnection::SetLocalDescription");
nisse7ce109a2017-01-31 00:57:56 -08001583 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001584 RTC_LOG(LS_ERROR) << "SetLocalDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001585 return;
1586 }
1587 if (!desc) {
1588 PostSetSessionDescriptionFailure(observer, "SessionDescription is NULL.");
1589 return;
1590 }
Steve Anton8d3444d2017-10-20 15:30:51 -07001591
1592 // Takes the ownership of |desc| regardless of the result.
1593 std::unique_ptr<SessionDescriptionInterface> desc_temp(desc);
1594
1595 if (IsClosed()) {
Henrik Boströmfdb92012017-11-09 19:55:44 +01001596 std::string error = "Failed to set local " + desc_temp->type() +
Steve Anton8d3444d2017-10-20 15:30:51 -07001597 " sdp: Called in wrong state: STATE_CLOSED";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001598 RTC_LOG(LS_ERROR) << error;
Steve Anton8d3444d2017-10-20 15:30:51 -07001599 PostSetSessionDescriptionFailure(observer, error);
1600 return;
1601 }
1602
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001603 // Update stats here so that we have the most recent stats for tracks and
1604 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001605 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001606 std::string error;
Henrik Boströmfdb92012017-11-09 19:55:44 +01001607 // Takes the ownership of |desc_temp|. On success, local_description() is
1608 // updated to reflect the description that was passed in.
Henrik Boström31638672017-11-23 17:48:32 +01001609 if (!SetCurrentOrPendingLocalDescription(std::move(desc_temp), &error)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001610 PostSetSessionDescriptionFailure(observer, error);
1611 return;
1612 }
Henrik Boströmfdb92012017-11-09 19:55:44 +01001613 RTC_DCHECK(local_description());
deadbeefab9b2d12015-10-14 11:33:11 -07001614
1615 // If setting the description decided our SSL role, allocate any necessary
1616 // SCTP sids.
1617 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08001618 if (data_channel_type() == cricket::DCT_SCTP && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001619 AllocateSctpSids(role);
1620 }
1621
1622 // Update state and SSRC of local MediaStreams and DataChannels based on the
1623 // local session description.
1624 const cricket::ContentInfo* audio_content =
Henrik Boströmfdb92012017-11-09 19:55:44 +01001625 GetFirstAudioContent(local_description()->description());
deadbeefab9b2d12015-10-14 11:33:11 -07001626 if (audio_content) {
deadbeeffaac4972015-11-12 15:33:07 -08001627 if (audio_content->rejected) {
Steve Anton4171afb2017-11-20 10:20:22 -08001628 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
deadbeeffaac4972015-11-12 15:33:07 -08001629 } else {
1630 const cricket::AudioContentDescription* audio_desc =
1631 static_cast<const cricket::AudioContentDescription*>(
1632 audio_content->description);
Steve Anton4171afb2017-11-20 10:20:22 -08001633 UpdateLocalSenders(audio_desc->streams(), audio_desc->type());
deadbeeffaac4972015-11-12 15:33:07 -08001634 }
deadbeefab9b2d12015-10-14 11:33:11 -07001635 }
1636
1637 const cricket::ContentInfo* video_content =
Henrik Boströmfdb92012017-11-09 19:55:44 +01001638 GetFirstVideoContent(local_description()->description());
deadbeefab9b2d12015-10-14 11:33:11 -07001639 if (video_content) {
deadbeeffaac4972015-11-12 15:33:07 -08001640 if (video_content->rejected) {
Steve Anton4171afb2017-11-20 10:20:22 -08001641 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
deadbeeffaac4972015-11-12 15:33:07 -08001642 } else {
1643 const cricket::VideoContentDescription* video_desc =
1644 static_cast<const cricket::VideoContentDescription*>(
1645 video_content->description);
Steve Anton4171afb2017-11-20 10:20:22 -08001646 UpdateLocalSenders(video_desc->streams(), video_desc->type());
deadbeeffaac4972015-11-12 15:33:07 -08001647 }
deadbeefab9b2d12015-10-14 11:33:11 -07001648 }
1649
1650 const cricket::ContentInfo* data_content =
Henrik Boströmfdb92012017-11-09 19:55:44 +01001651 GetFirstDataContent(local_description()->description());
deadbeefab9b2d12015-10-14 11:33:11 -07001652 if (data_content) {
1653 const cricket::DataContentDescription* data_desc =
1654 static_cast<const cricket::DataContentDescription*>(
1655 data_content->description);
1656 if (rtc::starts_with(data_desc->protocol().data(),
1657 cricket::kMediaProtocolRtpPrefix)) {
1658 UpdateLocalRtpDataChannels(data_desc->streams());
1659 }
1660 }
1661
Henrik Boström31638672017-11-23 17:48:32 +01001662 PostSetSessionDescriptionSuccess(observer);
deadbeefab9b2d12015-10-14 11:33:11 -07001663
deadbeef42a42632017-03-10 15:18:00 -08001664 // According to JSEP, after setLocalDescription, changing the candidate pool
1665 // size is not allowed, and changing the set of ICE servers will not result
1666 // in new candidates being gathered.
1667 port_allocator_->FreezeCandidatePool();
1668
deadbeefcbecd352015-09-23 11:50:27 -07001669 // MaybeStartGathering needs to be called after posting
1670 // MSG_SET_SESSIONDESCRIPTION_SUCCESS, so that we don't signal any candidates
1671 // before signaling that SetLocalDescription completed.
Steve Antond25da372017-11-06 14:50:29 -08001672 transport_controller_->MaybeStartGathering();
deadbeef42a42632017-03-10 15:18:00 -08001673
Henrik Boströmfdb92012017-11-09 19:55:44 +01001674 if (local_description()->type() == SessionDescriptionInterface::kAnswer) {
deadbeef42a42632017-03-10 15:18:00 -08001675 // TODO(deadbeef): We already had to hop to the network thread for
1676 // MaybeStartGathering...
1677 network_thread()->Invoke<void>(
1678 RTC_FROM_HERE,
1679 rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
1680 port_allocator_.get()));
1681 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001682}
1683
1684void PeerConnection::SetRemoteDescription(
Henrik Boströma4ecf552017-11-23 14:17:07 +00001685 SetSessionDescriptionObserver* observer,
1686 SessionDescriptionInterface* desc) {
Henrik Boström31638672017-11-23 17:48:32 +01001687 SetRemoteDescription(
1688 std::unique_ptr<SessionDescriptionInterface>(desc),
1689 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface>(
1690 new SetRemoteDescriptionObserverAdapter(this, observer)));
1691}
1692
1693void PeerConnection::SetRemoteDescription(
1694 std::unique_ptr<SessionDescriptionInterface> desc,
1695 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface> observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001696 TRACE_EVENT0("webrtc", "PeerConnection::SetRemoteDescription");
nisse7ce109a2017-01-31 00:57:56 -08001697 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001698 RTC_LOG(LS_ERROR) << "SetRemoteDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001699 return;
1700 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001701 if (!desc) {
Henrik Boström31638672017-11-23 17:48:32 +01001702 observer->OnSetRemoteDescriptionComplete(RTCError(
1703 RTCErrorType::UNSUPPORTED_PARAMETER, "SessionDescription is NULL."));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001704 return;
1705 }
Steve Anton8d3444d2017-10-20 15:30:51 -07001706
Steve Anton8d3444d2017-10-20 15:30:51 -07001707 if (IsClosed()) {
Henrik Boström31638672017-11-23 17:48:32 +01001708 std::string error = "Failed to set remote " + desc->type() +
Steve Anton8d3444d2017-10-20 15:30:51 -07001709 " sdp: Called in wrong state: STATE_CLOSED";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001710 RTC_LOG(LS_ERROR) << error;
Henrik Boström31638672017-11-23 17:48:32 +01001711 observer->OnSetRemoteDescriptionComplete(
1712 RTCError(RTCErrorType::INVALID_STATE, std::move(error)));
Steve Anton8d3444d2017-10-20 15:30:51 -07001713 return;
1714 }
1715
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001716 // Update stats here so that we have the most recent stats for tracks and
1717 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001718 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001719 std::string error;
Henrik Boström31638672017-11-23 17:48:32 +01001720 // Takes the ownership of |desc|. On success, remote_description() is updated
1721 // to reflect the description that was passed in.
1722 if (!SetCurrentOrPendingRemoteDescription(std::move(desc), &error)) {
1723 observer->OnSetRemoteDescriptionComplete(
1724 RTCError(RTCErrorType::UNSUPPORTED_PARAMETER, std::move(error)));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001725 return;
1726 }
Henrik Boströmfdb92012017-11-09 19:55:44 +01001727 RTC_DCHECK(remote_description());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001728
deadbeefab9b2d12015-10-14 11:33:11 -07001729 // If setting the description decided our SSL role, allocate any necessary
1730 // SCTP sids.
1731 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08001732 if (data_channel_type() == cricket::DCT_SCTP && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001733 AllocateSctpSids(role);
1734 }
1735
Henrik Boströmfdb92012017-11-09 19:55:44 +01001736 const cricket::ContentInfo* audio_content =
1737 GetFirstAudioContent(remote_description()->description());
1738 const cricket::ContentInfo* video_content =
1739 GetFirstVideoContent(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08001740 const cricket::AudioContentDescription* audio_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01001741 GetFirstAudioContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08001742 const cricket::VideoContentDescription* video_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01001743 GetFirstVideoContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08001744 const cricket::DataContentDescription* data_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01001745 GetFirstDataContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08001746
1747 // Check if the descriptions include streams, just in case the peer supports
1748 // MSID, but doesn't indicate so with "a=msid-semantic".
Henrik Boströmfdb92012017-11-09 19:55:44 +01001749 if (remote_description()->description()->msid_supported() ||
deadbeefbda7e0b2015-12-08 17:13:40 -08001750 (audio_desc && !audio_desc->streams().empty()) ||
1751 (video_desc && !video_desc->streams().empty())) {
1752 remote_peer_supports_msid_ = true;
1753 }
deadbeefab9b2d12015-10-14 11:33:11 -07001754
1755 // We wait to signal new streams until we finish processing the description,
1756 // since only at that point will new streams have all their tracks.
1757 rtc::scoped_refptr<StreamCollection> new_streams(StreamCollection::Create());
1758
Steve Anton8d3444d2017-10-20 15:30:51 -07001759 // TODO(steveanton): When removing RTP senders/receivers in response to a
1760 // rejected media section, there is some cleanup logic that expects the voice/
1761 // video channel to still be set. But in this method the voice/video channel
Steve Anton75737c02017-11-06 10:37:17 -08001762 // would have been destroyed by the SetRemoteDescription caller above so the
Steve Anton4171afb2017-11-20 10:20:22 -08001763 // cleanup that relies on them fails to run. The RemoveSenders calls should be
Steve Anton75737c02017-11-06 10:37:17 -08001764 // moved to right before the DestroyChannel calls to fix this.
Steve Anton8d3444d2017-10-20 15:30:51 -07001765
deadbeefab9b2d12015-10-14 11:33:11 -07001766 // Find all audio rtp streams and create corresponding remote AudioTracks
1767 // and MediaStreams.
deadbeefab9b2d12015-10-14 11:33:11 -07001768 if (audio_content) {
deadbeeffaac4972015-11-12 15:33:07 -08001769 if (audio_content->rejected) {
Steve Anton4171afb2017-11-20 10:20:22 -08001770 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
deadbeeffaac4972015-11-12 15:33:07 -08001771 } else {
deadbeefbda7e0b2015-12-08 17:13:40 -08001772 bool default_audio_track_needed =
1773 !remote_peer_supports_msid_ &&
1774 MediaContentDirectionHasSend(audio_desc->direction());
Steve Anton4171afb2017-11-20 10:20:22 -08001775 UpdateRemoteSendersList(GetActiveStreams(audio_desc),
deadbeefbda7e0b2015-12-08 17:13:40 -08001776 default_audio_track_needed, audio_desc->type(),
deadbeeffaac4972015-11-12 15:33:07 -08001777 new_streams);
deadbeeffaac4972015-11-12 15:33:07 -08001778 }
deadbeefab9b2d12015-10-14 11:33:11 -07001779 }
1780
1781 // Find all video rtp streams and create corresponding remote VideoTracks
1782 // and MediaStreams.
deadbeefab9b2d12015-10-14 11:33:11 -07001783 if (video_content) {
deadbeeffaac4972015-11-12 15:33:07 -08001784 if (video_content->rejected) {
Steve Anton4171afb2017-11-20 10:20:22 -08001785 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
deadbeeffaac4972015-11-12 15:33:07 -08001786 } else {
deadbeefbda7e0b2015-12-08 17:13:40 -08001787 bool default_video_track_needed =
1788 !remote_peer_supports_msid_ &&
1789 MediaContentDirectionHasSend(video_desc->direction());
Steve Anton4171afb2017-11-20 10:20:22 -08001790 UpdateRemoteSendersList(GetActiveStreams(video_desc),
deadbeefbda7e0b2015-12-08 17:13:40 -08001791 default_video_track_needed, video_desc->type(),
deadbeeffaac4972015-11-12 15:33:07 -08001792 new_streams);
deadbeeffaac4972015-11-12 15:33:07 -08001793 }
deadbeefab9b2d12015-10-14 11:33:11 -07001794 }
1795
1796 // Update the DataChannels with the information from the remote peer.
deadbeefbda7e0b2015-12-08 17:13:40 -08001797 if (data_desc) {
1798 if (rtc::starts_with(data_desc->protocol().data(),
deadbeefab9b2d12015-10-14 11:33:11 -07001799 cricket::kMediaProtocolRtpPrefix)) {
deadbeefbda7e0b2015-12-08 17:13:40 -08001800 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
deadbeefab9b2d12015-10-14 11:33:11 -07001801 }
1802 }
1803
1804 // Iterate new_streams and notify the observer about new MediaStreams.
1805 for (size_t i = 0; i < new_streams->count(); ++i) {
1806 MediaStreamInterface* new_stream = new_streams->at(i);
1807 stats_->AddStream(new_stream);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07001808 observer_->OnAddStream(
1809 rtc::scoped_refptr<MediaStreamInterface>(new_stream));
deadbeefab9b2d12015-10-14 11:33:11 -07001810 }
1811
deadbeefbda7e0b2015-12-08 17:13:40 -08001812 UpdateEndedRemoteMediaStreams();
deadbeefab9b2d12015-10-14 11:33:11 -07001813
Henrik Boström31638672017-11-23 17:48:32 +01001814 observer->OnSetRemoteDescriptionComplete(RTCError::OK());
deadbeef42a42632017-03-10 15:18:00 -08001815
Henrik Boströmfdb92012017-11-09 19:55:44 +01001816 if (remote_description()->type() == SessionDescriptionInterface::kAnswer) {
deadbeef42a42632017-03-10 15:18:00 -08001817 // TODO(deadbeef): We already had to hop to the network thread for
1818 // MaybeStartGathering...
1819 network_thread()->Invoke<void>(
1820 RTC_FROM_HERE,
1821 rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
1822 port_allocator_.get()));
1823 }
deadbeeffc648b62015-10-13 16:42:33 -07001824}
1825
deadbeef46c73892016-11-16 19:42:04 -08001826PeerConnectionInterface::RTCConfiguration PeerConnection::GetConfiguration() {
1827 return configuration_;
1828}
1829
deadbeef293e9262017-01-11 12:28:30 -08001830bool PeerConnection::SetConfiguration(const RTCConfiguration& configuration,
1831 RTCError* error) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001832 TRACE_EVENT0("webrtc", "PeerConnection::SetConfiguration");
deadbeef6de92f92016-12-12 18:49:32 -08001833
Steve Anton75737c02017-11-06 10:37:17 -08001834 if (local_description() && configuration.ice_candidate_pool_size !=
1835 configuration_.ice_candidate_pool_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001836 RTC_LOG(LS_ERROR) << "Can't change candidate pool size after calling "
1837 "SetLocalDescription.";
deadbeef293e9262017-01-11 12:28:30 -08001838 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00001839 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07001840
deadbeef293e9262017-01-11 12:28:30 -08001841 // The simplest (and most future-compatible) way to tell if the config was
1842 // modified in an invalid way is to copy each property we do support
1843 // modifying, then use operator==. There are far more properties we don't
1844 // support modifying than those we do, and more could be added.
1845 RTCConfiguration modified_config = configuration_;
1846 modified_config.servers = configuration.servers;
1847 modified_config.type = configuration.type;
1848 modified_config.ice_candidate_pool_size =
1849 configuration.ice_candidate_pool_size;
1850 modified_config.prune_turn_ports = configuration.prune_turn_ports;
skvladd1f5fda2017-02-03 16:54:05 -08001851 modified_config.ice_check_min_interval = configuration.ice_check_min_interval;
Jonas Orelandbdcee282017-10-10 14:01:40 +02001852 modified_config.turn_customizer = configuration.turn_customizer;
deadbeef293e9262017-01-11 12:28:30 -08001853 if (configuration != modified_config) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001854 RTC_LOG(LS_ERROR) << "Modifying the configuration in an unsupported way.";
deadbeef293e9262017-01-11 12:28:30 -08001855 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
1856 }
1857
Steve Anton038834f2017-07-14 15:59:59 -07001858 // Validate the modified configuration.
1859 RTCError validate_error = ValidateConfiguration(modified_config);
1860 if (!validate_error.ok()) {
1861 return SafeSetError(std::move(validate_error), error);
1862 }
1863
deadbeef293e9262017-01-11 12:28:30 -08001864 // Note that this isn't possible through chromium, since it's an unsigned
1865 // short in WebIDL.
1866 if (configuration.ice_candidate_pool_size < 0 ||
1867 configuration.ice_candidate_pool_size > UINT16_MAX) {
1868 return SafeSetError(RTCErrorType::INVALID_RANGE, error);
1869 }
1870
1871 // Parse ICE servers before hopping to network thread.
1872 cricket::ServerAddresses stun_servers;
1873 std::vector<cricket::RelayServerConfig> turn_servers;
1874 RTCErrorType parse_error =
1875 ParseIceServers(configuration.servers, &stun_servers, &turn_servers);
1876 if (parse_error != RTCErrorType::NONE) {
1877 return SafeSetError(parse_error, error);
1878 }
1879
1880 // In theory this shouldn't fail.
1881 if (!network_thread()->Invoke<bool>(
1882 RTC_FROM_HERE,
1883 rtc::Bind(&PeerConnection::ReconfigurePortAllocator_n, this,
1884 stun_servers, turn_servers, modified_config.type,
1885 modified_config.ice_candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02001886 modified_config.prune_turn_ports,
1887 modified_config.turn_customizer))) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001888 RTC_LOG(LS_ERROR) << "Failed to apply configuration to PortAllocator.";
deadbeef293e9262017-01-11 12:28:30 -08001889 return SafeSetError(RTCErrorType::INTERNAL_ERROR, error);
1890 }
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07001891
deadbeefd1a38b52016-12-10 13:15:33 -08001892 // As described in JSEP, calling setConfiguration with new ICE servers or
1893 // candidate policy must set a "needs-ice-restart" bit so that the next offer
1894 // triggers an ICE restart which will pick up the changes.
deadbeef293e9262017-01-11 12:28:30 -08001895 if (modified_config.servers != configuration_.servers ||
1896 modified_config.type != configuration_.type ||
1897 modified_config.prune_turn_ports != configuration_.prune_turn_ports) {
Steve Antond25da372017-11-06 14:50:29 -08001898 transport_controller_->SetNeedsIceRestartFlag();
deadbeefd1a38b52016-12-10 13:15:33 -08001899 }
skvladd1f5fda2017-02-03 16:54:05 -08001900
1901 if (modified_config.ice_check_min_interval !=
1902 configuration_.ice_check_min_interval) {
Steve Antond25da372017-11-06 14:50:29 -08001903 transport_controller_->SetIceConfig(ParseIceConfig(modified_config));
skvladd1f5fda2017-02-03 16:54:05 -08001904 }
1905
deadbeef293e9262017-01-11 12:28:30 -08001906 configuration_ = modified_config;
1907 return SafeSetError(RTCErrorType::NONE, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00001908}
1909
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001910bool PeerConnection::AddIceCandidate(
1911 const IceCandidateInterface* ice_candidate) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001912 TRACE_EVENT0("webrtc", "PeerConnection::AddIceCandidate");
zhihuang29ff8442016-07-27 11:07:25 -07001913 if (IsClosed()) {
1914 return false;
1915 }
Steve Antond25da372017-11-06 14:50:29 -08001916
1917 if (!remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001918 RTC_LOG(LS_ERROR) << "ProcessIceMessage: ICE candidates can't be added "
1919 << "without any remote session description.";
Steve Antond25da372017-11-06 14:50:29 -08001920 return false;
1921 }
1922
1923 if (!ice_candidate) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001924 RTC_LOG(LS_ERROR) << "ProcessIceMessage: Candidate is NULL.";
Steve Antond25da372017-11-06 14:50:29 -08001925 return false;
1926 }
1927
1928 bool valid = false;
1929 bool ready = ReadyToUseRemoteCandidate(ice_candidate, nullptr, &valid);
1930 if (!valid) {
1931 return false;
1932 }
1933
1934 // Add this candidate to the remote session description.
1935 if (!mutable_remote_description()->AddCandidate(ice_candidate)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001936 RTC_LOG(LS_ERROR) << "ProcessIceMessage: Candidate cannot be used.";
Steve Antond25da372017-11-06 14:50:29 -08001937 return false;
1938 }
1939
1940 if (ready) {
1941 return UseCandidate(ice_candidate);
1942 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001943 RTC_LOG(LS_INFO) << "ProcessIceMessage: Not ready to use candidate.";
Steve Antond25da372017-11-06 14:50:29 -08001944 return true;
1945 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001946}
1947
Honghai Zhang7fb69db2016-03-14 11:59:18 -07001948bool PeerConnection::RemoveIceCandidates(
1949 const std::vector<cricket::Candidate>& candidates) {
1950 TRACE_EVENT0("webrtc", "PeerConnection::RemoveIceCandidates");
Steve Antond25da372017-11-06 14:50:29 -08001951 if (!remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001952 RTC_LOG(LS_ERROR) << "RemoveRemoteIceCandidates: ICE candidates can't be "
1953 << "removed without any remote session description.";
Steve Antond25da372017-11-06 14:50:29 -08001954 return false;
1955 }
1956
1957 if (candidates.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001958 RTC_LOG(LS_ERROR) << "RemoveRemoteIceCandidates: candidates are empty.";
Steve Antond25da372017-11-06 14:50:29 -08001959 return false;
1960 }
1961
1962 size_t number_removed =
1963 mutable_remote_description()->RemoveCandidates(candidates);
1964 if (number_removed != candidates.size()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001965 RTC_LOG(LS_ERROR)
1966 << "RemoveRemoteIceCandidates: Failed to remove candidates. "
1967 << "Requested " << candidates.size() << " but only " << number_removed
1968 << " are removed.";
Steve Antond25da372017-11-06 14:50:29 -08001969 }
1970
1971 // Remove the candidates from the transport controller.
1972 std::string error;
1973 bool res = transport_controller_->RemoveRemoteCandidates(candidates, &error);
1974 if (!res && !error.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001975 RTC_LOG(LS_ERROR) << "Error when removing remote candidates: " << error;
Steve Antond25da372017-11-06 14:50:29 -08001976 }
1977 return true;
Honghai Zhang7fb69db2016-03-14 11:59:18 -07001978}
1979
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00001980void PeerConnection::RegisterUMAObserver(UMAObserver* observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001981 TRACE_EVENT0("webrtc", "PeerConnection::RegisterUmaObserver");
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00001982 uma_observer_ = observer;
guoweis@webrtc.org7169afd2014-12-04 17:59:29 +00001983
Steve Anton75737c02017-11-06 10:37:17 -08001984 if (transport_controller()) {
1985 transport_controller()->SetMetricsObserver(uma_observer_);
guoweis@webrtc.org7169afd2014-12-04 17:59:29 +00001986 }
1987
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00001988 // Send information about IPv4/IPv6 status.
deadbeef293e9262017-01-11 12:28:30 -08001989 if (uma_observer_) {
Honghai Zhangd93f50c2016-10-05 11:47:22 -07001990 port_allocator_->SetMetricsObserver(uma_observer_);
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00001991 if (port_allocator_->flags() & cricket::PORTALLOCATOR_ENABLE_IPV6) {
Guo-wei Shiehdfbe6792015-09-03 17:12:07 -07001992 uma_observer_->IncrementEnumCounter(
1993 kEnumCounterAddressFamily, kPeerConnection_IPv6,
1994 kPeerConnectionAddressFamilyCounter_Max);
mallinath@webrtc.orgb445f262014-05-23 22:19:37 +00001995 } else {
Guo-wei Shiehdfbe6792015-09-03 17:12:07 -07001996 uma_observer_->IncrementEnumCounter(
1997 kEnumCounterAddressFamily, kPeerConnection_IPv4,
1998 kPeerConnectionAddressFamilyCounter_Max);
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00001999 }
2000 }
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00002001}
2002
zstein4b979802017-06-02 14:37:37 -07002003RTCError PeerConnection::SetBitrate(const BitrateParameters& bitrate) {
Steve Anton978b8762017-09-29 12:15:02 -07002004 if (!worker_thread()->IsCurrent()) {
2005 return worker_thread()->Invoke<RTCError>(
zstein4b979802017-06-02 14:37:37 -07002006 RTC_FROM_HERE, rtc::Bind(&PeerConnection::SetBitrate, this, bitrate));
2007 }
2008
2009 const bool has_min = static_cast<bool>(bitrate.min_bitrate_bps);
2010 const bool has_current = static_cast<bool>(bitrate.current_bitrate_bps);
2011 const bool has_max = static_cast<bool>(bitrate.max_bitrate_bps);
2012 if (has_min && *bitrate.min_bitrate_bps < 0) {
2013 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2014 "min_bitrate_bps <= 0");
2015 }
2016 if (has_current) {
2017 if (has_min && *bitrate.current_bitrate_bps < *bitrate.min_bitrate_bps) {
2018 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2019 "current_bitrate_bps < min_bitrate_bps");
2020 } else if (*bitrate.current_bitrate_bps < 0) {
2021 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2022 "curent_bitrate_bps < 0");
2023 }
2024 }
2025 if (has_max) {
2026 if (has_current &&
2027 *bitrate.max_bitrate_bps < *bitrate.current_bitrate_bps) {
2028 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2029 "max_bitrate_bps < current_bitrate_bps");
2030 } else if (has_min && *bitrate.max_bitrate_bps < *bitrate.min_bitrate_bps) {
2031 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2032 "max_bitrate_bps < min_bitrate_bps");
2033 } else if (*bitrate.max_bitrate_bps < 0) {
2034 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2035 "max_bitrate_bps < 0");
2036 }
2037 }
2038
2039 Call::Config::BitrateConfigMask mask;
2040 mask.min_bitrate_bps = bitrate.min_bitrate_bps;
2041 mask.start_bitrate_bps = bitrate.current_bitrate_bps;
2042 mask.max_bitrate_bps = bitrate.max_bitrate_bps;
2043
2044 RTC_DCHECK(call_.get());
2045 call_->SetBitrateConfigMask(mask);
2046
2047 return RTCError::OK();
2048}
2049
Alex Narest78609d52017-10-20 10:37:47 +02002050void PeerConnection::SetBitrateAllocationStrategy(
2051 std::unique_ptr<rtc::BitrateAllocationStrategy>
2052 bitrate_allocation_strategy) {
2053 rtc::Thread* worker_thread = factory_->worker_thread();
2054 if (!worker_thread->IsCurrent()) {
2055 rtc::BitrateAllocationStrategy* strategy_raw =
2056 bitrate_allocation_strategy.release();
2057 auto functor = [this, strategy_raw]() {
2058 call_->SetBitrateAllocationStrategy(
2059 rtc::WrapUnique<rtc::BitrateAllocationStrategy>(strategy_raw));
2060 };
2061 worker_thread->Invoke<void>(RTC_FROM_HERE, functor);
2062 return;
2063 }
2064 RTC_DCHECK(call_.get());
2065 call_->SetBitrateAllocationStrategy(std::move(bitrate_allocation_strategy));
2066}
2067
henrika5f6bf242017-11-01 11:06:56 +01002068void PeerConnection::SetAudioPlayout(bool playout) {
2069 if (!worker_thread()->IsCurrent()) {
2070 worker_thread()->Invoke<void>(
2071 RTC_FROM_HERE,
2072 rtc::Bind(&PeerConnection::SetAudioPlayout, this, playout));
2073 return;
2074 }
2075 auto audio_state =
2076 factory_->channel_manager()->media_engine()->GetAudioState();
2077 audio_state->SetPlayout(playout);
2078}
2079
2080void PeerConnection::SetAudioRecording(bool recording) {
2081 if (!worker_thread()->IsCurrent()) {
2082 worker_thread()->Invoke<void>(
2083 RTC_FROM_HERE,
2084 rtc::Bind(&PeerConnection::SetAudioRecording, this, recording));
2085 return;
2086 }
2087 auto audio_state =
2088 factory_->channel_manager()->media_engine()->GetAudioState();
2089 audio_state->SetRecording(recording);
2090}
2091
Steve Anton8c0f7a72017-10-03 10:03:10 -07002092std::unique_ptr<rtc::SSLCertificate>
2093PeerConnection::GetRemoteAudioSSLCertificate() {
Steve Anton75737c02017-11-06 10:37:17 -08002094 if (!voice_channel()) {
Steve Anton8c0f7a72017-10-03 10:03:10 -07002095 return nullptr;
2096 }
Steve Anton75737c02017-11-06 10:37:17 -08002097 return GetRemoteSSLCertificate(voice_channel()->transport_name());
Steve Anton8c0f7a72017-10-03 10:03:10 -07002098}
2099
ivoc14d5dbe2016-07-04 07:06:55 -07002100bool PeerConnection::StartRtcEventLog(rtc::PlatformFile file,
2101 int64_t max_size_bytes) {
Elad Alon99c3fe52017-10-13 16:29:40 +02002102 // TODO(eladalon): It would be better to not allow negative values into PC.
2103 const size_t max_size = (max_size_bytes < 0)
2104 ? RtcEventLog::kUnlimitedOutput
2105 : rtc::saturated_cast<size_t>(max_size_bytes);
2106 return StartRtcEventLog(
Bjorn Tereliusde939432017-11-20 17:38:14 +01002107 rtc::MakeUnique<RtcEventLogOutputFile>(file, max_size),
2108 webrtc::RtcEventLog::kImmediateOutput);
Elad Alon99c3fe52017-10-13 16:29:40 +02002109}
2110
Bjorn Tereliusde939432017-11-20 17:38:14 +01002111bool PeerConnection::StartRtcEventLog(std::unique_ptr<RtcEventLogOutput> output,
2112 int64_t output_period_ms) {
Karl Wibergd6b48192017-10-16 23:01:06 +02002113 // TODO(eladalon): In C++14, this can be done with a lambda.
2114 struct Functor {
Bjorn Tereliusde939432017-11-20 17:38:14 +01002115 bool operator()() {
2116 return pc->StartRtcEventLog_w(std::move(output), output_period_ms);
2117 }
Karl Wibergd6b48192017-10-16 23:01:06 +02002118 PeerConnection* const pc;
2119 std::unique_ptr<RtcEventLogOutput> output;
Bjorn Tereliusde939432017-11-20 17:38:14 +01002120 const int64_t output_period_ms;
Elad Alon99c3fe52017-10-13 16:29:40 +02002121 };
Bjorn Tereliusde939432017-11-20 17:38:14 +01002122 return worker_thread()->Invoke<bool>(
2123 RTC_FROM_HERE, Functor{this, std::move(output), output_period_ms});
ivoc14d5dbe2016-07-04 07:06:55 -07002124}
2125
2126void PeerConnection::StopRtcEventLog() {
Steve Anton978b8762017-09-29 12:15:02 -07002127 worker_thread()->Invoke<void>(
ivoc14d5dbe2016-07-04 07:06:55 -07002128 RTC_FROM_HERE, rtc::Bind(&PeerConnection::StopRtcEventLog_w, this));
2129}
2130
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002131const SessionDescriptionInterface* PeerConnection::local_description() const {
Steve Anton75737c02017-11-06 10:37:17 -08002132 return pending_local_description_ ? pending_local_description_.get()
2133 : current_local_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002134}
2135
2136const SessionDescriptionInterface* PeerConnection::remote_description() const {
Steve Anton75737c02017-11-06 10:37:17 -08002137 return pending_remote_description_ ? pending_remote_description_.get()
2138 : current_remote_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002139}
2140
deadbeeffe4a8a42016-12-20 17:56:17 -08002141const SessionDescriptionInterface* PeerConnection::current_local_description()
2142 const {
Steve Anton75737c02017-11-06 10:37:17 -08002143 return current_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08002144}
2145
2146const SessionDescriptionInterface* PeerConnection::current_remote_description()
2147 const {
Steve Anton75737c02017-11-06 10:37:17 -08002148 return current_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08002149}
2150
2151const SessionDescriptionInterface* PeerConnection::pending_local_description()
2152 const {
Steve Anton75737c02017-11-06 10:37:17 -08002153 return pending_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08002154}
2155
2156const SessionDescriptionInterface* PeerConnection::pending_remote_description()
2157 const {
Steve Anton75737c02017-11-06 10:37:17 -08002158 return pending_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08002159}
2160
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002161void PeerConnection::Close() {
Peter Boström1a9d6152015-12-08 22:15:17 +01002162 TRACE_EVENT0("webrtc", "PeerConnection::Close");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002163 // Update stats here so that we have the most recent stats for tracks and
2164 // streams before the channels are closed.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00002165 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002166
Steve Anton75737c02017-11-06 10:37:17 -08002167 ChangeSignalingState(PeerConnectionInterface::kClosed);
2168 RemoveUnusedChannels(nullptr);
Steve Anton4171afb2017-11-20 10:20:22 -08002169 RTC_DCHECK(!GetAudioTransceiver()->internal()->channel());
2170 RTC_DCHECK(!GetVideoTransceiver()->internal()->channel());
Steve Anton75737c02017-11-06 10:37:17 -08002171 RTC_DCHECK(!rtp_data_channel_);
2172 RTC_DCHECK(!sctp_transport_);
2173
deadbeef42a42632017-03-10 15:18:00 -08002174 network_thread()->Invoke<void>(
2175 RTC_FROM_HERE,
2176 rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
2177 port_allocator_.get()));
nisseeaabdf62017-05-05 02:23:02 -07002178
Steve Anton978b8762017-09-29 12:15:02 -07002179 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
eladalon248fd4f2017-09-06 05:18:15 -07002180 call_.reset();
2181 // The event log must outlive call (and any other object that uses it).
2182 event_log_.reset();
2183 });
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002184}
2185
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002186void PeerConnection::OnMessage(rtc::Message* msg) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002187 switch (msg->message_id) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002188 case MSG_SET_SESSIONDESCRIPTION_SUCCESS: {
2189 SetSessionDescriptionMsg* param =
2190 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
2191 param->observer->OnSuccess();
2192 delete param;
2193 break;
2194 }
2195 case MSG_SET_SESSIONDESCRIPTION_FAILED: {
2196 SetSessionDescriptionMsg* param =
2197 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
2198 param->observer->OnFailure(param->error);
2199 delete param;
2200 break;
2201 }
deadbeefab9b2d12015-10-14 11:33:11 -07002202 case MSG_CREATE_SESSIONDESCRIPTION_FAILED: {
2203 CreateSessionDescriptionMsg* param =
2204 static_cast<CreateSessionDescriptionMsg*>(msg->pdata);
2205 param->observer->OnFailure(param->error);
2206 delete param;
2207 break;
2208 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002209 case MSG_GETSTATS: {
2210 GetStatsMsg* param = static_cast<GetStatsMsg*>(msg->pdata);
nissee8abe3e2017-01-18 05:00:34 -08002211 StatsReports reports;
2212 stats_->GetStats(param->track, &reports);
2213 param->observer->OnComplete(reports);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002214 delete param;
2215 break;
2216 }
deadbeefbd292462015-12-14 18:15:29 -08002217 case MSG_FREE_DATACHANNELS: {
2218 sctp_data_channels_to_free_.clear();
2219 break;
2220 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002221 default:
nisseeb4ca4e2017-01-12 02:24:27 -08002222 RTC_NOTREACHED() << "Not implemented";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002223 break;
2224 }
2225}
2226
Steve Anton4171afb2017-11-20 10:20:22 -08002227void PeerConnection::CreateAudioReceiver(
2228 MediaStreamInterface* stream,
2229 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01002230 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
2231 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
zhihuang81c3a032016-11-17 12:06:24 -08002232 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
2233 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
deadbeefe814a0d2017-02-25 18:15:09 -08002234 signaling_thread(),
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01002235 new AudioRtpReceiver(remote_sender_info.sender_id, streams,
Steve Anton4171afb2017-11-20 10:20:22 -08002236 remote_sender_info.first_ssrc, voice_channel()));
deadbeefe814a0d2017-02-25 18:15:09 -08002237 stream->AddTrack(
2238 static_cast<AudioTrackInterface*>(receiver->internal()->track().get()));
Steve Anton4171afb2017-11-20 10:20:22 -08002239 GetAudioTransceiver()->internal()->AddReceiver(receiver);
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01002240 observer_->OnAddTrack(receiver, std::move(streams));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002241}
2242
Steve Anton4171afb2017-11-20 10:20:22 -08002243void PeerConnection::CreateVideoReceiver(
2244 MediaStreamInterface* stream,
2245 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01002246 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
2247 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
zhihuang81c3a032016-11-17 12:06:24 -08002248 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
2249 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
Steve Anton4171afb2017-11-20 10:20:22 -08002250 signaling_thread(),
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01002251 new VideoRtpReceiver(remote_sender_info.sender_id, streams,
2252 worker_thread(), remote_sender_info.first_ssrc,
2253 video_channel()));
deadbeefe814a0d2017-02-25 18:15:09 -08002254 stream->AddTrack(
2255 static_cast<VideoTrackInterface*>(receiver->internal()->track().get()));
Steve Anton4171afb2017-11-20 10:20:22 -08002256 GetVideoTransceiver()->internal()->AddReceiver(receiver);
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01002257 observer_->OnAddTrack(receiver, std::move(streams));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002258}
2259
deadbeef70ab1a12015-09-28 16:53:55 -07002260// TODO(deadbeef): Keep RtpReceivers around even if track goes away in remote
2261// description.
Henrik Boström933d8b02017-10-10 10:05:16 -07002262rtc::scoped_refptr<RtpReceiverInterface> PeerConnection::RemoveAndStopReceiver(
Steve Anton4171afb2017-11-20 10:20:22 -08002263 const RtpSenderInfo& remote_sender_info) {
2264 auto receiver = FindReceiverById(remote_sender_info.sender_id);
2265 if (!receiver) {
2266 RTC_LOG(LS_WARNING) << "RtpReceiver for track with id "
2267 << remote_sender_info.sender_id << " doesn't exist.";
Henrik Boström933d8b02017-10-10 10:05:16 -07002268 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07002269 }
Steve Anton4171afb2017-11-20 10:20:22 -08002270 if (receiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
2271 GetAudioTransceiver()->internal()->RemoveReceiver(receiver);
2272 } else {
2273 GetVideoTransceiver()->internal()->RemoveReceiver(receiver);
2274 }
Henrik Boström933d8b02017-10-10 10:05:16 -07002275 return receiver;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002276}
2277
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002278void PeerConnection::AddAudioTrack(AudioTrackInterface* track,
2279 MediaStreamInterface* stream) {
2280 RTC_DCHECK(!IsClosed());
2281 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08002282 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002283 // We already have a sender for this track, so just change the stream_id
2284 // so that it's correct in the next call to CreateOffer.
Steve Anton4171afb2017-11-20 10:20:22 -08002285 sender->internal()->set_stream_id(stream->label());
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002286 return;
2287 }
2288
2289 // Normal case; we've never seen this track before.
2290 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender =
2291 RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
2292 signaling_thread(),
Steve Anton75737c02017-11-06 10:37:17 -08002293 new AudioRtpSender(track, {stream->label()}, voice_channel(),
2294 stats_.get()));
Steve Anton4171afb2017-11-20 10:20:22 -08002295 GetAudioTransceiver()->internal()->AddSender(new_sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002296 // If the sender has already been configured in SDP, we call SetSsrc,
2297 // which will connect the sender to the underlying transport. This can
2298 // occur if a local session description that contains the ID of the sender
2299 // is set before AddStream is called. It can also occur if the local
2300 // session description is not changed and RemoveStream is called, and
2301 // later AddStream is called again with the same stream.
Steve Anton4171afb2017-11-20 10:20:22 -08002302 const RtpSenderInfo* sender_info =
2303 FindSenderInfo(local_audio_sender_infos_, stream->label(), track->id());
2304 if (sender_info) {
2305 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002306 }
2307}
2308
2309// TODO(deadbeef): Don't destroy RtpSenders here; they should be kept around
2310// indefinitely, when we have unified plan SDP.
2311void PeerConnection::RemoveAudioTrack(AudioTrackInterface* track,
2312 MediaStreamInterface* stream) {
2313 RTC_DCHECK(!IsClosed());
2314 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08002315 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002316 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
2317 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002318 return;
2319 }
Steve Anton4171afb2017-11-20 10:20:22 -08002320 GetAudioTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002321}
2322
2323void PeerConnection::AddVideoTrack(VideoTrackInterface* track,
2324 MediaStreamInterface* stream) {
2325 RTC_DCHECK(!IsClosed());
2326 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08002327 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002328 // We already have a sender for this track, so just change the stream_id
2329 // so that it's correct in the next call to CreateOffer.
Steve Anton4171afb2017-11-20 10:20:22 -08002330 sender->internal()->set_stream_id(stream->label());
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002331 return;
2332 }
2333
2334 // Normal case; we've never seen this track before.
2335 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender =
2336 RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton75737c02017-11-06 10:37:17 -08002337 signaling_thread(),
2338 new VideoRtpSender(track, {stream->label()}, video_channel()));
Steve Anton4171afb2017-11-20 10:20:22 -08002339 GetVideoTransceiver()->internal()->AddSender(new_sender);
2340 const RtpSenderInfo* sender_info =
2341 FindSenderInfo(local_video_sender_infos_, stream->label(), track->id());
2342 if (sender_info) {
2343 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002344 }
2345}
2346
2347void PeerConnection::RemoveVideoTrack(VideoTrackInterface* track,
2348 MediaStreamInterface* stream) {
2349 RTC_DCHECK(!IsClosed());
2350 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08002351 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002352 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
2353 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002354 return;
2355 }
Steve Anton4171afb2017-11-20 10:20:22 -08002356 GetVideoTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002357}
2358
Steve Antonba818672017-11-06 10:21:57 -08002359void PeerConnection::SetIceConnectionState(IceConnectionState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07002360 RTC_DCHECK(signaling_thread()->IsCurrent());
Steve Antonba818672017-11-06 10:21:57 -08002361 if (ice_connection_state_ == new_state) {
2362 return;
2363 }
2364
deadbeefcbecd352015-09-23 11:50:27 -07002365 // After transitioning to "closed", ignore any additional states from
Steve Antonba818672017-11-06 10:21:57 -08002366 // TransportController (such as "disconnected").
deadbeefab9b2d12015-10-14 11:33:11 -07002367 if (IsClosed()) {
deadbeefcbecd352015-09-23 11:50:27 -07002368 return;
2369 }
Steve Antonba818672017-11-06 10:21:57 -08002370
Mirko Bonadei675513b2017-11-09 11:09:25 +01002371 RTC_LOG(LS_INFO) << "Changing IceConnectionState " << ice_connection_state_
2372 << " => " << new_state;
Steve Antonba818672017-11-06 10:21:57 -08002373 RTC_DCHECK(ice_connection_state_ !=
2374 PeerConnectionInterface::kIceConnectionClosed);
2375
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002376 ice_connection_state_ = new_state;
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00002377 observer_->OnIceConnectionChange(ice_connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002378}
2379
2380void PeerConnection::OnIceGatheringChange(
2381 PeerConnectionInterface::IceGatheringState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07002382 RTC_DCHECK(signaling_thread()->IsCurrent());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002383 if (IsClosed()) {
2384 return;
2385 }
2386 ice_gathering_state_ = new_state;
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00002387 observer_->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002388}
2389
jbauch81bf7b02017-03-25 08:31:12 -07002390void PeerConnection::OnIceCandidate(
2391 std::unique_ptr<IceCandidateInterface> candidate) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07002392 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07002393 if (IsClosed()) {
2394 return;
2395 }
jbauch81bf7b02017-03-25 08:31:12 -07002396 observer_->OnIceCandidate(candidate.get());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002397}
2398
Honghai Zhang7fb69db2016-03-14 11:59:18 -07002399void PeerConnection::OnIceCandidatesRemoved(
2400 const std::vector<cricket::Candidate>& candidates) {
2401 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07002402 if (IsClosed()) {
2403 return;
2404 }
Honghai Zhang7fb69db2016-03-14 11:59:18 -07002405 observer_->OnIceCandidatesRemoved(candidates);
2406}
2407
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002408void PeerConnection::ChangeSignalingState(
2409 PeerConnectionInterface::SignalingState signaling_state) {
Steve Antonba818672017-11-06 10:21:57 -08002410 RTC_DCHECK(signaling_thread()->IsCurrent());
2411 if (signaling_state_ == signaling_state) {
2412 return;
2413 }
Mirko Bonadei675513b2017-11-09 11:09:25 +01002414 RTC_LOG(LS_INFO) << "Session: " << session_id() << " Old state: "
2415 << GetSignalingStateString(signaling_state_)
2416 << " New state: "
2417 << GetSignalingStateString(signaling_state);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002418 signaling_state_ = signaling_state;
2419 if (signaling_state == kClosed) {
2420 ice_connection_state_ = kIceConnectionClosed;
2421 observer_->OnIceConnectionChange(ice_connection_state_);
2422 if (ice_gathering_state_ != kIceGatheringComplete) {
2423 ice_gathering_state_ = kIceGatheringComplete;
2424 observer_->OnIceGatheringChange(ice_gathering_state_);
2425 }
2426 }
2427 observer_->OnSignalingChange(signaling_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002428}
2429
deadbeefeb459812015-12-15 19:24:43 -08002430void PeerConnection::OnAudioTrackAdded(AudioTrackInterface* track,
2431 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07002432 if (IsClosed()) {
2433 return;
2434 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002435 AddAudioTrack(track, stream);
2436 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08002437}
2438
deadbeefeb459812015-12-15 19:24:43 -08002439void PeerConnection::OnAudioTrackRemoved(AudioTrackInterface* track,
2440 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07002441 if (IsClosed()) {
2442 return;
2443 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002444 RemoveAudioTrack(track, stream);
2445 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08002446}
2447
2448void PeerConnection::OnVideoTrackAdded(VideoTrackInterface* track,
2449 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07002450 if (IsClosed()) {
2451 return;
2452 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002453 AddVideoTrack(track, stream);
2454 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08002455}
2456
2457void PeerConnection::OnVideoTrackRemoved(VideoTrackInterface* track,
2458 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07002459 if (IsClosed()) {
2460 return;
2461 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002462 RemoveVideoTrack(track, stream);
2463 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08002464}
2465
Henrik Boström31638672017-11-23 17:48:32 +01002466void PeerConnection::PostSetSessionDescriptionSuccess(
2467 SetSessionDescriptionObserver* observer) {
2468 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
2469 signaling_thread()->Post(RTC_FROM_HERE, this,
2470 MSG_SET_SESSIONDESCRIPTION_SUCCESS, msg);
2471}
2472
deadbeefab9b2d12015-10-14 11:33:11 -07002473void PeerConnection::PostSetSessionDescriptionFailure(
2474 SetSessionDescriptionObserver* observer,
2475 const std::string& error) {
2476 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
2477 msg->error = error;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07002478 signaling_thread()->Post(RTC_FROM_HERE, this,
2479 MSG_SET_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07002480}
2481
2482void PeerConnection::PostCreateSessionDescriptionFailure(
2483 CreateSessionDescriptionObserver* observer,
2484 const std::string& error) {
2485 CreateSessionDescriptionMsg* msg = new CreateSessionDescriptionMsg(observer);
2486 msg->error = error;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07002487 signaling_thread()->Post(RTC_FROM_HERE, this,
2488 MSG_CREATE_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07002489}
2490
zhihuang1c378ed2017-08-17 14:10:50 -07002491void PeerConnection::GetOptionsForOffer(
deadbeefab9b2d12015-10-14 11:33:11 -07002492 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options,
2493 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07002494 ExtractSharedMediaSessionOptions(rtc_options, session_options);
2495
2496 // Figure out transceiver directional preferences.
2497 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
2498 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
2499
2500 // By default, generate sendrecv/recvonly m= sections.
2501 bool recv_audio = true;
2502 bool recv_video = true;
2503
2504 // By default, only offer a new m= section if we have media to send with it.
2505 bool offer_new_audio_description = send_audio;
2506 bool offer_new_video_description = send_video;
2507 bool offer_new_data_description = HasDataChannels();
2508
2509 // The "offer_to_receive_X" options allow those defaults to be overridden.
2510 if (rtc_options.offer_to_receive_audio != RTCOfferAnswerOptions::kUndefined) {
2511 recv_audio = (rtc_options.offer_to_receive_audio > 0);
2512 offer_new_audio_description =
2513 offer_new_audio_description || (rtc_options.offer_to_receive_audio > 0);
2514 }
2515 if (rtc_options.offer_to_receive_video != RTCOfferAnswerOptions::kUndefined) {
2516 recv_video = (rtc_options.offer_to_receive_video > 0);
2517 offer_new_video_description =
2518 offer_new_video_description || (rtc_options.offer_to_receive_video > 0);
2519 }
2520
2521 rtc::Optional<size_t> audio_index;
2522 rtc::Optional<size_t> video_index;
2523 rtc::Optional<size_t> data_index;
2524 // If a current description exists, generate m= sections in the same order,
2525 // using the first audio/video/data section that appears and rejecting
2526 // extraneous ones.
Steve Anton75737c02017-11-06 10:37:17 -08002527 if (local_description()) {
zhihuang1c378ed2017-08-17 14:10:50 -07002528 GenerateMediaDescriptionOptions(
Steve Anton75737c02017-11-06 10:37:17 -08002529 local_description(),
zhihuang1c378ed2017-08-17 14:10:50 -07002530 cricket::RtpTransceiverDirection(send_audio, recv_audio),
2531 cricket::RtpTransceiverDirection(send_video, recv_video), &audio_index,
2532 &video_index, &data_index, session_options);
deadbeefab9b2d12015-10-14 11:33:11 -07002533 }
2534
zhihuang1c378ed2017-08-17 14:10:50 -07002535 // Add audio/video/data m= sections to the end if needed.
2536 if (!audio_index && offer_new_audio_description) {
2537 session_options->media_description_options.push_back(
2538 cricket::MediaDescriptionOptions(
2539 cricket::MEDIA_TYPE_AUDIO, cricket::CN_AUDIO,
2540 cricket::RtpTransceiverDirection(send_audio, recv_audio), false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01002541 audio_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07002542 }
zhihuang1c378ed2017-08-17 14:10:50 -07002543 if (!video_index && offer_new_video_description) {
2544 session_options->media_description_options.push_back(
2545 cricket::MediaDescriptionOptions(
2546 cricket::MEDIA_TYPE_VIDEO, cricket::CN_VIDEO,
2547 cricket::RtpTransceiverDirection(send_video, recv_video), false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01002548 video_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07002549 }
zhihuang1c378ed2017-08-17 14:10:50 -07002550 if (!data_index && offer_new_data_description) {
2551 session_options->media_description_options.push_back(
2552 cricket::MediaDescriptionOptions(
2553 cricket::MEDIA_TYPE_DATA, cricket::CN_DATA,
2554 cricket::RtpTransceiverDirection(true, true), false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01002555 data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07002556 }
2557
2558 cricket::MediaDescriptionOptions* audio_media_description_options =
2559 !audio_index ? nullptr
2560 : &session_options->media_description_options[*audio_index];
2561 cricket::MediaDescriptionOptions* video_media_description_options =
2562 !video_index ? nullptr
2563 : &session_options->media_description_options[*video_index];
2564 cricket::MediaDescriptionOptions* data_media_description_options =
2565 !data_index ? nullptr
2566 : &session_options->media_description_options[*data_index];
2567
2568 // Apply ICE restart flag and renomination flag.
2569 for (auto& options : session_options->media_description_options) {
2570 options.transport_options.ice_restart = rtc_options.ice_restart;
2571 options.transport_options.enable_ice_renomination =
2572 configuration_.enable_ice_renomination;
2573 }
2574
Steve Anton4171afb2017-11-20 10:20:22 -08002575 AddRtpSenderOptions(GetSendersInternal(), audio_media_description_options,
zhihuang1c378ed2017-08-17 14:10:50 -07002576 video_media_description_options);
2577 AddRtpDataChannelOptions(rtp_data_channels_, data_media_description_options);
deadbeefc80741f2015-10-22 13:14:45 -07002578
zhihuang9763d562016-08-05 11:14:50 -07002579 // Intentionally unset the data channel type for RTP data channel with the
2580 // second condition. Otherwise the RTP data channels would be successfully
2581 // negotiated by default and the unit tests in WebRtcDataBrowserTest will fail
2582 // when building with chromium. We want to leave RTP data channels broken, so
2583 // people won't try to use them.
Steve Anton75737c02017-11-06 10:37:17 -08002584 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
2585 session_options->data_channel_type = data_channel_type();
deadbeefab9b2d12015-10-14 11:33:11 -07002586 }
zhihuang8f65cdf2016-05-06 18:40:30 -07002587
2588 session_options->rtcp_cname = rtcp_cname_;
jbauchcb560652016-08-04 05:20:32 -07002589 session_options->crypto_options = factory_->options().crypto_options;
deadbeefab9b2d12015-10-14 11:33:11 -07002590}
2591
zhihuang1c378ed2017-08-17 14:10:50 -07002592void PeerConnection::GetOptionsForAnswer(
2593 const RTCOfferAnswerOptions& rtc_options,
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07002594 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07002595 ExtractSharedMediaSessionOptions(rtc_options, session_options);
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07002596
zhihuang1c378ed2017-08-17 14:10:50 -07002597 // Figure out transceiver directional preferences.
2598 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
2599 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
2600
2601 // By default, generate sendrecv/recvonly m= sections. The direction is also
2602 // restricted by the direction in the offer.
2603 bool recv_audio = true;
2604 bool recv_video = true;
2605
2606 // The "offer_to_receive_X" options allow those defaults to be overridden.
2607 if (rtc_options.offer_to_receive_audio != RTCOfferAnswerOptions::kUndefined) {
2608 recv_audio = (rtc_options.offer_to_receive_audio > 0);
deadbeef0ed85b22016-02-23 17:24:52 -08002609 }
zhihuang1c378ed2017-08-17 14:10:50 -07002610 if (rtc_options.offer_to_receive_video != RTCOfferAnswerOptions::kUndefined) {
2611 recv_video = (rtc_options.offer_to_receive_video > 0);
2612 }
2613
2614 rtc::Optional<size_t> audio_index;
2615 rtc::Optional<size_t> video_index;
2616 rtc::Optional<size_t> data_index;
Steve Anton75737c02017-11-06 10:37:17 -08002617 if (remote_description()) {
zhihuang141aacb2017-08-29 13:23:53 -07002618 // The pending remote description should be an offer.
Steve Anton75737c02017-11-06 10:37:17 -08002619 RTC_DCHECK(remote_description()->type() ==
zhihuang141aacb2017-08-29 13:23:53 -07002620 SessionDescriptionInterface::kOffer);
2621 // Generate m= sections that match those in the offer.
2622 // Note that mediasession.cc will handle intersection our preferred
2623 // direction with the offered direction.
2624 GenerateMediaDescriptionOptions(
Steve Anton75737c02017-11-06 10:37:17 -08002625 remote_description(),
zhihuang141aacb2017-08-29 13:23:53 -07002626 cricket::RtpTransceiverDirection(send_audio, recv_audio),
2627 cricket::RtpTransceiverDirection(send_video, recv_video), &audio_index,
2628 &video_index, &data_index, session_options);
2629 }
zhihuang1c378ed2017-08-17 14:10:50 -07002630
2631 cricket::MediaDescriptionOptions* audio_media_description_options =
2632 !audio_index ? nullptr
2633 : &session_options->media_description_options[*audio_index];
2634 cricket::MediaDescriptionOptions* video_media_description_options =
2635 !video_index ? nullptr
2636 : &session_options->media_description_options[*video_index];
2637 cricket::MediaDescriptionOptions* data_media_description_options =
2638 !data_index ? nullptr
2639 : &session_options->media_description_options[*data_index];
2640
2641 // Apply ICE renomination flag.
2642 for (auto& options : session_options->media_description_options) {
2643 options.transport_options.enable_ice_renomination =
2644 configuration_.enable_ice_renomination;
2645 }
2646
Steve Anton4171afb2017-11-20 10:20:22 -08002647 AddRtpSenderOptions(GetSendersInternal(), audio_media_description_options,
zhihuang1c378ed2017-08-17 14:10:50 -07002648 video_media_description_options);
2649 AddRtpDataChannelOptions(rtp_data_channels_, data_media_description_options);
2650
zhihuang9763d562016-08-05 11:14:50 -07002651 // Intentionally unset the data channel type for RTP data channel. Otherwise
2652 // the RTP data channels would be successfully negotiated by default and the
2653 // unit tests in WebRtcDataBrowserTest will fail when building with chromium.
2654 // We want to leave RTP data channels broken, so people won't try to use them.
Steve Anton75737c02017-11-06 10:37:17 -08002655 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
2656 session_options->data_channel_type = data_channel_type();
deadbeef907abe42016-08-04 12:22:18 -07002657 }
zhihuangaf388472016-11-02 16:49:48 -07002658
zhihuang1c378ed2017-08-17 14:10:50 -07002659 session_options->rtcp_cname = rtcp_cname_;
jbauchcb560652016-08-04 05:20:32 -07002660 session_options->crypto_options = factory_->options().crypto_options;
htaa2a49d92016-03-04 02:51:39 -08002661}
2662
zhihuang1c378ed2017-08-17 14:10:50 -07002663void PeerConnection::GenerateMediaDescriptionOptions(
2664 const SessionDescriptionInterface* session_desc,
2665 cricket::RtpTransceiverDirection audio_direction,
2666 cricket::RtpTransceiverDirection video_direction,
2667 rtc::Optional<size_t>* audio_index,
2668 rtc::Optional<size_t>* video_index,
2669 rtc::Optional<size_t>* data_index,
htaa2a49d92016-03-04 02:51:39 -08002670 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07002671 for (const cricket::ContentInfo& content :
2672 session_desc->description()->contents()) {
2673 if (IsAudioContent(&content)) {
2674 // If we already have an audio m= section, reject this extra one.
2675 if (*audio_index) {
2676 session_options->media_description_options.push_back(
2677 cricket::MediaDescriptionOptions(
2678 cricket::MEDIA_TYPE_AUDIO, content.name,
2679 cricket::RtpTransceiverDirection(false, false), true));
2680 } else {
2681 session_options->media_description_options.push_back(
2682 cricket::MediaDescriptionOptions(
2683 cricket::MEDIA_TYPE_AUDIO, content.name, audio_direction,
2684 !audio_direction.send && !audio_direction.recv));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01002685 *audio_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07002686 }
2687 } else if (IsVideoContent(&content)) {
2688 // If we already have an video m= section, reject this extra one.
2689 if (*video_index) {
2690 session_options->media_description_options.push_back(
2691 cricket::MediaDescriptionOptions(
2692 cricket::MEDIA_TYPE_VIDEO, content.name,
2693 cricket::RtpTransceiverDirection(false, false), true));
2694 } else {
2695 session_options->media_description_options.push_back(
2696 cricket::MediaDescriptionOptions(
2697 cricket::MEDIA_TYPE_VIDEO, content.name, video_direction,
2698 !video_direction.send && !video_direction.recv));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01002699 *video_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07002700 }
2701 } else {
2702 RTC_DCHECK(IsDataContent(&content));
2703 // If we already have an data m= section, reject this extra one.
2704 if (*data_index) {
2705 session_options->media_description_options.push_back(
2706 cricket::MediaDescriptionOptions(
2707 cricket::MEDIA_TYPE_DATA, content.name,
2708 cricket::RtpTransceiverDirection(false, false), true));
2709 } else {
2710 session_options->media_description_options.push_back(
2711 cricket::MediaDescriptionOptions(
2712 cricket::MEDIA_TYPE_DATA, content.name,
2713 // Direction for data sections is meaningless, but legacy
2714 // endpoints might expect sendrecv.
2715 cricket::RtpTransceiverDirection(true, true), false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01002716 *data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07002717 }
2718 }
htaa2a49d92016-03-04 02:51:39 -08002719 }
deadbeefab9b2d12015-10-14 11:33:11 -07002720}
2721
Steve Anton4171afb2017-11-20 10:20:22 -08002722void PeerConnection::RemoveSenders(cricket::MediaType media_type) {
2723 UpdateLocalSenders(std::vector<cricket::StreamParams>(), media_type);
2724 UpdateRemoteSendersList(std::vector<cricket::StreamParams>(), false,
deadbeefbda7e0b2015-12-08 17:13:40 -08002725 media_type, nullptr);
deadbeeffaac4972015-11-12 15:33:07 -08002726}
2727
Steve Anton4171afb2017-11-20 10:20:22 -08002728void PeerConnection::UpdateRemoteSendersList(
deadbeefab9b2d12015-10-14 11:33:11 -07002729 const cricket::StreamParamsVec& streams,
Steve Anton4171afb2017-11-20 10:20:22 -08002730 bool default_sender_needed,
deadbeefab9b2d12015-10-14 11:33:11 -07002731 cricket::MediaType media_type,
2732 StreamCollection* new_streams) {
Steve Anton4171afb2017-11-20 10:20:22 -08002733 std::vector<RtpSenderInfo>* current_senders =
2734 GetRemoteSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07002735
Steve Anton4171afb2017-11-20 10:20:22 -08002736 // Find removed senders. I.e., senders where the sender id or ssrc don't match
deadbeeffac06552015-11-25 11:26:01 -08002737 // the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08002738 for (auto sender_it = current_senders->begin();
2739 sender_it != current_senders->end();
2740 /* incremented manually */) {
2741 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07002742 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08002743 cricket::GetStreamBySsrc(streams, info.first_ssrc);
2744 bool sender_exists = params && params->id == info.sender_id;
deadbeefbda7e0b2015-12-08 17:13:40 -08002745 // If this is a default track, and we still need it, don't remove it.
Steve Anton4171afb2017-11-20 10:20:22 -08002746 if ((info.stream_label == kDefaultStreamLabel && default_sender_needed) ||
2747 sender_exists) {
2748 ++sender_it;
deadbeefbda7e0b2015-12-08 17:13:40 -08002749 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08002750 OnRemoteSenderRemoved(info, media_type);
2751 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07002752 }
2753 }
2754
Steve Anton4171afb2017-11-20 10:20:22 -08002755 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07002756 for (const cricket::StreamParams& params : streams) {
2757 // The sync_label is the MediaStream label and the |stream.id| is the
Steve Anton4171afb2017-11-20 10:20:22 -08002758 // sender id.
deadbeefab9b2d12015-10-14 11:33:11 -07002759 const std::string& stream_label = params.sync_label;
Steve Anton4171afb2017-11-20 10:20:22 -08002760 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07002761 uint32_t ssrc = params.first_ssrc();
2762
2763 rtc::scoped_refptr<MediaStreamInterface> stream =
2764 remote_streams_->find(stream_label);
2765 if (!stream) {
2766 // This is a new MediaStream. Create a new remote MediaStream.
perkjd61bf802016-03-24 03:16:19 -07002767 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
2768 MediaStream::Create(stream_label));
deadbeefab9b2d12015-10-14 11:33:11 -07002769 remote_streams_->AddStream(stream);
2770 new_streams->AddStream(stream);
2771 }
2772
Steve Anton4171afb2017-11-20 10:20:22 -08002773 const RtpSenderInfo* sender_info =
2774 FindSenderInfo(*current_senders, stream_label, sender_id);
2775 if (!sender_info) {
2776 current_senders->push_back(RtpSenderInfo(stream_label, sender_id, ssrc));
2777 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07002778 }
2779 }
deadbeefbda7e0b2015-12-08 17:13:40 -08002780
Steve Anton4171afb2017-11-20 10:20:22 -08002781 // Add default sender if necessary.
2782 if (default_sender_needed) {
deadbeefbda7e0b2015-12-08 17:13:40 -08002783 rtc::scoped_refptr<MediaStreamInterface> default_stream =
2784 remote_streams_->find(kDefaultStreamLabel);
2785 if (!default_stream) {
2786 // Create the new default MediaStream.
perkjd61bf802016-03-24 03:16:19 -07002787 default_stream = MediaStreamProxy::Create(
2788 rtc::Thread::Current(), MediaStream::Create(kDefaultStreamLabel));
deadbeefbda7e0b2015-12-08 17:13:40 -08002789 remote_streams_->AddStream(default_stream);
2790 new_streams->AddStream(default_stream);
2791 }
Steve Anton4171afb2017-11-20 10:20:22 -08002792 std::string default_sender_id = (media_type == cricket::MEDIA_TYPE_AUDIO)
2793 ? kDefaultAudioSenderId
2794 : kDefaultVideoSenderId;
2795 const RtpSenderInfo* default_sender_info = FindSenderInfo(
2796 *current_senders, kDefaultStreamLabel, default_sender_id);
2797 if (!default_sender_info) {
2798 current_senders->push_back(
2799 RtpSenderInfo(kDefaultStreamLabel, default_sender_id, 0));
2800 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefbda7e0b2015-12-08 17:13:40 -08002801 }
2802 }
deadbeefab9b2d12015-10-14 11:33:11 -07002803}
2804
Steve Anton4171afb2017-11-20 10:20:22 -08002805void PeerConnection::OnRemoteSenderAdded(const RtpSenderInfo& sender_info,
2806 cricket::MediaType media_type) {
2807 MediaStreamInterface* stream =
2808 remote_streams_->find(sender_info.stream_label);
deadbeefab9b2d12015-10-14 11:33:11 -07002809
2810 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 10:20:22 -08002811 CreateAudioReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07002812 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 10:20:22 -08002813 CreateVideoReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07002814 } else {
nisseeb4ca4e2017-01-12 02:24:27 -08002815 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07002816 }
2817}
2818
Steve Anton4171afb2017-11-20 10:20:22 -08002819void PeerConnection::OnRemoteSenderRemoved(const RtpSenderInfo& sender_info,
2820 cricket::MediaType media_type) {
2821 MediaStreamInterface* stream =
2822 remote_streams_->find(sender_info.stream_label);
deadbeefab9b2d12015-10-14 11:33:11 -07002823
Henrik Boström933d8b02017-10-10 10:05:16 -07002824 rtc::scoped_refptr<RtpReceiverInterface> receiver;
deadbeefab9b2d12015-10-14 11:33:11 -07002825 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
perkjd61bf802016-03-24 03:16:19 -07002826 // When the MediaEngine audio channel is destroyed, the RemoteAudioSource
2827 // will be notified which will end the AudioRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08002828 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07002829 rtc::scoped_refptr<AudioTrackInterface> audio_track =
Steve Anton4171afb2017-11-20 10:20:22 -08002830 stream->FindAudioTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07002831 if (audio_track) {
deadbeefab9b2d12015-10-14 11:33:11 -07002832 stream->RemoveTrack(audio_track);
deadbeefab9b2d12015-10-14 11:33:11 -07002833 }
2834 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
perkjd61bf802016-03-24 03:16:19 -07002835 // Stopping or destroying a VideoRtpReceiver will end the
2836 // VideoRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08002837 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07002838 rtc::scoped_refptr<VideoTrackInterface> video_track =
Steve Anton4171afb2017-11-20 10:20:22 -08002839 stream->FindVideoTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07002840 if (video_track) {
perkjd61bf802016-03-24 03:16:19 -07002841 // There's no guarantee the track is still available, e.g. the track may
2842 // have been removed from the stream by an application.
deadbeefab9b2d12015-10-14 11:33:11 -07002843 stream->RemoveTrack(video_track);
deadbeefab9b2d12015-10-14 11:33:11 -07002844 }
2845 } else {
nisseede5da42017-01-12 05:15:36 -08002846 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07002847 }
Henrik Boström933d8b02017-10-10 10:05:16 -07002848 if (receiver) {
2849 observer_->OnRemoveTrack(receiver);
2850 }
deadbeefab9b2d12015-10-14 11:33:11 -07002851}
2852
2853void PeerConnection::UpdateEndedRemoteMediaStreams() {
2854 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams_to_remove;
2855 for (size_t i = 0; i < remote_streams_->count(); ++i) {
2856 MediaStreamInterface* stream = remote_streams_->at(i);
2857 if (stream->GetAudioTracks().empty() && stream->GetVideoTracks().empty()) {
2858 streams_to_remove.push_back(stream);
2859 }
2860 }
2861
Taylor Brandstetter98cde262016-05-31 13:02:21 -07002862 for (auto& stream : streams_to_remove) {
deadbeefab9b2d12015-10-14 11:33:11 -07002863 remote_streams_->RemoveStream(stream);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07002864 observer_->OnRemoveStream(std::move(stream));
deadbeefab9b2d12015-10-14 11:33:11 -07002865 }
2866}
2867
Steve Anton4171afb2017-11-20 10:20:22 -08002868void PeerConnection::UpdateLocalSenders(
deadbeefab9b2d12015-10-14 11:33:11 -07002869 const std::vector<cricket::StreamParams>& streams,
2870 cricket::MediaType media_type) {
Steve Anton4171afb2017-11-20 10:20:22 -08002871 std::vector<RtpSenderInfo>* current_senders = GetLocalSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07002872
2873 // Find removed tracks. I.e., tracks where the track id, stream label or ssrc
2874 // don't match the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08002875 for (auto sender_it = current_senders->begin();
2876 sender_it != current_senders->end();
2877 /* incremented manually */) {
2878 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07002879 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08002880 cricket::GetStreamBySsrc(streams, info.first_ssrc);
2881 if (!params || params->id != info.sender_id ||
deadbeefab9b2d12015-10-14 11:33:11 -07002882 params->sync_label != info.stream_label) {
Steve Anton4171afb2017-11-20 10:20:22 -08002883 OnLocalSenderRemoved(info, media_type);
2884 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07002885 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08002886 ++sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07002887 }
2888 }
2889
Steve Anton4171afb2017-11-20 10:20:22 -08002890 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07002891 for (const cricket::StreamParams& params : streams) {
2892 // The sync_label is the MediaStream label and the |stream.id| is the
Steve Anton4171afb2017-11-20 10:20:22 -08002893 // sender id.
deadbeefab9b2d12015-10-14 11:33:11 -07002894 const std::string& stream_label = params.sync_label;
Steve Anton4171afb2017-11-20 10:20:22 -08002895 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07002896 uint32_t ssrc = params.first_ssrc();
Steve Anton4171afb2017-11-20 10:20:22 -08002897 const RtpSenderInfo* sender_info =
2898 FindSenderInfo(*current_senders, stream_label, sender_id);
2899 if (!sender_info) {
2900 current_senders->push_back(RtpSenderInfo(stream_label, sender_id, ssrc));
2901 OnLocalSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07002902 }
2903 }
2904}
2905
Steve Anton4171afb2017-11-20 10:20:22 -08002906void PeerConnection::OnLocalSenderAdded(const RtpSenderInfo& sender_info,
2907 cricket::MediaType media_type) {
2908 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08002909 if (!sender) {
Steve Anton4171afb2017-11-20 10:20:22 -08002910 RTC_LOG(LS_WARNING) << "An unknown RtpSender with id "
2911 << sender_info.sender_id
Mirko Bonadei675513b2017-11-09 11:09:25 +01002912 << " has been configured in the local description.";
deadbeefab9b2d12015-10-14 11:33:11 -07002913 return;
2914 }
2915
deadbeeffac06552015-11-25 11:26:01 -08002916 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002917 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
2918 << " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08002919 return;
deadbeefab9b2d12015-10-14 11:33:11 -07002920 }
deadbeeffac06552015-11-25 11:26:01 -08002921
Steve Anton4171afb2017-11-20 10:20:22 -08002922 sender->internal()->set_stream_id(sender_info.stream_label);
2923 sender->internal()->SetSsrc(sender_info.first_ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07002924}
2925
Steve Anton4171afb2017-11-20 10:20:22 -08002926void PeerConnection::OnLocalSenderRemoved(const RtpSenderInfo& sender_info,
2927 cricket::MediaType media_type) {
2928 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08002929 if (!sender) {
2930 // This is the normal case. I.e., RemoveStream has been called and the
deadbeefab9b2d12015-10-14 11:33:11 -07002931 // SessionDescriptions has been renegotiated.
2932 return;
2933 }
deadbeeffac06552015-11-25 11:26:01 -08002934
2935 // A sender has been removed from the SessionDescription but it's still
2936 // associated with the PeerConnection. This only occurs if the SDP doesn't
2937 // match with the calls to CreateSender, AddStream and RemoveStream.
2938 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002939 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
2940 << " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08002941 return;
deadbeefab9b2d12015-10-14 11:33:11 -07002942 }
deadbeeffac06552015-11-25 11:26:01 -08002943
Steve Anton4171afb2017-11-20 10:20:22 -08002944 sender->internal()->SetSsrc(0);
deadbeefab9b2d12015-10-14 11:33:11 -07002945}
2946
2947void PeerConnection::UpdateLocalRtpDataChannels(
2948 const cricket::StreamParamsVec& streams) {
2949 std::vector<std::string> existing_channels;
2950
2951 // Find new and active data channels.
2952 for (const cricket::StreamParams& params : streams) {
2953 // |it->sync_label| is actually the data channel label. The reason is that
2954 // we use the same naming of data channels as we do for
2955 // MediaStreams and Tracks.
2956 // For MediaStreams, the sync_label is the MediaStream label and the
2957 // track label is the same as |streamid|.
2958 const std::string& channel_label = params.sync_label;
2959 auto data_channel_it = rtp_data_channels_.find(channel_label);
nisse7ce109a2017-01-31 00:57:56 -08002960 if (data_channel_it == rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002961 RTC_LOG(LS_ERROR) << "channel label not found";
deadbeefab9b2d12015-10-14 11:33:11 -07002962 continue;
2963 }
2964 // Set the SSRC the data channel should use for sending.
2965 data_channel_it->second->SetSendSsrc(params.first_ssrc());
2966 existing_channels.push_back(data_channel_it->first);
2967 }
2968
2969 UpdateClosingRtpDataChannels(existing_channels, true);
2970}
2971
2972void PeerConnection::UpdateRemoteRtpDataChannels(
2973 const cricket::StreamParamsVec& streams) {
2974 std::vector<std::string> existing_channels;
2975
2976 // Find new and active data channels.
2977 for (const cricket::StreamParams& params : streams) {
2978 // The data channel label is either the mslabel or the SSRC if the mslabel
2979 // does not exist. Ex a=ssrc:444330170 mslabel:test1.
2980 std::string label = params.sync_label.empty()
2981 ? rtc::ToString(params.first_ssrc())
2982 : params.sync_label;
2983 auto data_channel_it = rtp_data_channels_.find(label);
2984 if (data_channel_it == rtp_data_channels_.end()) {
2985 // This is a new data channel.
2986 CreateRemoteRtpDataChannel(label, params.first_ssrc());
2987 } else {
2988 data_channel_it->second->SetReceiveSsrc(params.first_ssrc());
2989 }
2990 existing_channels.push_back(label);
2991 }
2992
2993 UpdateClosingRtpDataChannels(existing_channels, false);
2994}
2995
2996void PeerConnection::UpdateClosingRtpDataChannels(
2997 const std::vector<std::string>& active_channels,
2998 bool is_local_update) {
2999 auto it = rtp_data_channels_.begin();
3000 while (it != rtp_data_channels_.end()) {
3001 DataChannel* data_channel = it->second;
3002 if (std::find(active_channels.begin(), active_channels.end(),
3003 data_channel->label()) != active_channels.end()) {
3004 ++it;
3005 continue;
3006 }
3007
3008 if (is_local_update) {
3009 data_channel->SetSendSsrc(0);
3010 } else {
3011 data_channel->RemotePeerRequestClose();
3012 }
3013
3014 if (data_channel->state() == DataChannel::kClosed) {
3015 rtp_data_channels_.erase(it);
3016 it = rtp_data_channels_.begin();
3017 } else {
3018 ++it;
3019 }
3020 }
3021}
3022
3023void PeerConnection::CreateRemoteRtpDataChannel(const std::string& label,
3024 uint32_t remote_ssrc) {
3025 rtc::scoped_refptr<DataChannel> channel(
3026 InternalCreateDataChannel(label, nullptr));
3027 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003028 RTC_LOG(LS_WARNING) << "Remote peer requested a DataChannel but"
3029 << "CreateDataChannel failed.";
deadbeefab9b2d12015-10-14 11:33:11 -07003030 return;
3031 }
3032 channel->SetReceiveSsrc(remote_ssrc);
deadbeefa601f5c2016-06-06 14:27:39 -07003033 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
3034 DataChannelProxy::Create(signaling_thread(), channel);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07003035 observer_->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07003036}
3037
3038rtc::scoped_refptr<DataChannel> PeerConnection::InternalCreateDataChannel(
3039 const std::string& label,
3040 const InternalDataChannelInit* config) {
3041 if (IsClosed()) {
3042 return nullptr;
3043 }
Steve Anton75737c02017-11-06 10:37:17 -08003044 if (data_channel_type() == cricket::DCT_NONE) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003045 RTC_LOG(LS_ERROR)
deadbeefab9b2d12015-10-14 11:33:11 -07003046 << "InternalCreateDataChannel: Data is not supported in this call.";
3047 return nullptr;
3048 }
3049 InternalDataChannelInit new_config =
3050 config ? (*config) : InternalDataChannelInit();
Steve Anton75737c02017-11-06 10:37:17 -08003051 if (data_channel_type() == cricket::DCT_SCTP) {
deadbeefab9b2d12015-10-14 11:33:11 -07003052 if (new_config.id < 0) {
3053 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08003054 if ((GetSctpSslRole(&role)) &&
deadbeefab9b2d12015-10-14 11:33:11 -07003055 !sid_allocator_.AllocateSid(role, &new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003056 RTC_LOG(LS_ERROR)
3057 << "No id can be allocated for the SCTP data channel.";
deadbeefab9b2d12015-10-14 11:33:11 -07003058 return nullptr;
3059 }
3060 } else if (!sid_allocator_.ReserveSid(new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003061 RTC_LOG(LS_ERROR) << "Failed to create a SCTP data channel "
3062 << "because the id is already in use or out of range.";
deadbeefab9b2d12015-10-14 11:33:11 -07003063 return nullptr;
3064 }
3065 }
3066
Steve Anton75737c02017-11-06 10:37:17 -08003067 rtc::scoped_refptr<DataChannel> channel(
3068 DataChannel::Create(this, data_channel_type(), label, new_config));
deadbeefab9b2d12015-10-14 11:33:11 -07003069 if (!channel) {
3070 sid_allocator_.ReleaseSid(new_config.id);
3071 return nullptr;
3072 }
3073
3074 if (channel->data_channel_type() == cricket::DCT_RTP) {
3075 if (rtp_data_channels_.find(channel->label()) != rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003076 RTC_LOG(LS_ERROR) << "DataChannel with label " << channel->label()
3077 << " already exists.";
deadbeefab9b2d12015-10-14 11:33:11 -07003078 return nullptr;
3079 }
3080 rtp_data_channels_[channel->label()] = channel;
3081 } else {
3082 RTC_DCHECK(channel->data_channel_type() == cricket::DCT_SCTP);
3083 sctp_data_channels_.push_back(channel);
3084 channel->SignalClosed.connect(this,
3085 &PeerConnection::OnSctpDataChannelClosed);
3086 }
3087
hbos82ebe022016-11-14 01:41:09 -08003088 SignalDataChannelCreated(channel.get());
deadbeefab9b2d12015-10-14 11:33:11 -07003089 return channel;
3090}
3091
3092bool PeerConnection::HasDataChannels() const {
3093 return !rtp_data_channels_.empty() || !sctp_data_channels_.empty();
3094}
3095
3096void PeerConnection::AllocateSctpSids(rtc::SSLRole role) {
3097 for (const auto& channel : sctp_data_channels_) {
3098 if (channel->id() < 0) {
3099 int sid;
3100 if (!sid_allocator_.AllocateSid(role, &sid)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003101 RTC_LOG(LS_ERROR) << "Failed to allocate SCTP sid.";
deadbeefab9b2d12015-10-14 11:33:11 -07003102 continue;
3103 }
3104 channel->SetSctpSid(sid);
3105 }
3106 }
3107}
3108
3109void PeerConnection::OnSctpDataChannelClosed(DataChannel* channel) {
deadbeefbd292462015-12-14 18:15:29 -08003110 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeefab9b2d12015-10-14 11:33:11 -07003111 for (auto it = sctp_data_channels_.begin(); it != sctp_data_channels_.end();
3112 ++it) {
3113 if (it->get() == channel) {
3114 if (channel->id() >= 0) {
3115 sid_allocator_.ReleaseSid(channel->id());
3116 }
deadbeefbd292462015-12-14 18:15:29 -08003117 // Since this method is triggered by a signal from the DataChannel,
3118 // we can't free it directly here; we need to free it asynchronously.
3119 sctp_data_channels_to_free_.push_back(*it);
deadbeefab9b2d12015-10-14 11:33:11 -07003120 sctp_data_channels_.erase(it);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07003121 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_FREE_DATACHANNELS,
3122 nullptr);
deadbeefab9b2d12015-10-14 11:33:11 -07003123 return;
3124 }
3125 }
3126}
3127
deadbeefab9b2d12015-10-14 11:33:11 -07003128void PeerConnection::OnDataChannelDestroyed() {
3129 // Use a temporary copy of the RTP/SCTP DataChannel list because the
3130 // DataChannel may callback to us and try to modify the list.
3131 std::map<std::string, rtc::scoped_refptr<DataChannel>> temp_rtp_dcs;
3132 temp_rtp_dcs.swap(rtp_data_channels_);
3133 for (const auto& kv : temp_rtp_dcs) {
3134 kv.second->OnTransportChannelDestroyed();
3135 }
3136
3137 std::vector<rtc::scoped_refptr<DataChannel>> temp_sctp_dcs;
3138 temp_sctp_dcs.swap(sctp_data_channels_);
3139 for (const auto& channel : temp_sctp_dcs) {
3140 channel->OnTransportChannelDestroyed();
3141 }
3142}
3143
3144void PeerConnection::OnDataChannelOpenMessage(
3145 const std::string& label,
3146 const InternalDataChannelInit& config) {
3147 rtc::scoped_refptr<DataChannel> channel(
3148 InternalCreateDataChannel(label, &config));
3149 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003150 RTC_LOG(LS_ERROR) << "Failed to create DataChannel from the OPEN message.";
deadbeefab9b2d12015-10-14 11:33:11 -07003151 return;
3152 }
3153
deadbeefa601f5c2016-06-06 14:27:39 -07003154 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
3155 DataChannelProxy::Create(signaling_thread(), channel);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07003156 observer_->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07003157}
3158
Steve Anton4171afb2017-11-20 10:20:22 -08003159rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3160PeerConnection::GetAudioTransceiver() const {
3161 // This method only works with Plan B SDP, where there is a single
3162 // audio/video transceiver.
3163 RTC_DCHECK(!IsUnifiedPlan());
3164 for (auto transceiver : transceivers_) {
3165 if (transceiver->internal()->media_type() == cricket::MEDIA_TYPE_AUDIO) {
3166 return transceiver;
3167 }
3168 }
3169 RTC_NOTREACHED();
3170 return nullptr;
3171}
3172
3173rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3174PeerConnection::GetVideoTransceiver() const {
3175 // This method only works with Plan B SDP, where there is a single
3176 // audio/video transceiver.
3177 RTC_DCHECK(!IsUnifiedPlan());
3178 for (auto transceiver : transceivers_) {
3179 if (transceiver->internal()->media_type() == cricket::MEDIA_TYPE_VIDEO) {
3180 return transceiver;
3181 }
3182 }
3183 RTC_NOTREACHED();
3184 return nullptr;
3185}
3186
3187// TODO(bugs.webrtc.org/7600): Remove this when multiple transceivers with
3188// individual transceiver directions are supported.
zhihuang1c378ed2017-08-17 14:10:50 -07003189bool PeerConnection::HasRtpSender(cricket::MediaType type) const {
Steve Anton4171afb2017-11-20 10:20:22 -08003190 switch (type) {
3191 case cricket::MEDIA_TYPE_AUDIO:
3192 return !GetAudioTransceiver()->internal()->senders().empty();
3193 case cricket::MEDIA_TYPE_VIDEO:
3194 return !GetVideoTransceiver()->internal()->senders().empty();
3195 case cricket::MEDIA_TYPE_DATA:
3196 return false;
3197 }
3198 RTC_NOTREACHED();
3199 return false;
zhihuang1c378ed2017-08-17 14:10:50 -07003200}
3201
Steve Anton4171afb2017-11-20 10:20:22 -08003202rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
3203PeerConnection::FindSenderForTrack(MediaStreamTrackInterface* track) const {
3204 for (auto transceiver : transceivers_) {
3205 for (auto sender : transceiver->internal()->senders()) {
3206 if (sender->track() == track) {
3207 return sender;
3208 }
3209 }
3210 }
3211 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08003212}
3213
Steve Anton4171afb2017-11-20 10:20:22 -08003214rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
3215PeerConnection::FindSenderById(const std::string& sender_id) const {
3216 for (auto transceiver : transceivers_) {
3217 for (auto sender : transceiver->internal()->senders()) {
3218 if (sender->id() == sender_id) {
3219 return sender;
3220 }
3221 }
3222 }
3223 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07003224}
3225
Steve Anton4171afb2017-11-20 10:20:22 -08003226rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
3227PeerConnection::FindReceiverById(const std::string& receiver_id) const {
3228 for (auto transceiver : transceivers_) {
3229 for (auto receiver : transceiver->internal()->receivers()) {
3230 if (receiver->id() == receiver_id) {
3231 return receiver;
3232 }
3233 }
3234 }
3235 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07003236}
3237
Steve Anton4171afb2017-11-20 10:20:22 -08003238std::vector<PeerConnection::RtpSenderInfo>*
3239PeerConnection::GetRemoteSenderInfos(cricket::MediaType media_type) {
3240 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
3241 media_type == cricket::MEDIA_TYPE_VIDEO);
3242 return (media_type == cricket::MEDIA_TYPE_AUDIO)
3243 ? &remote_audio_sender_infos_
3244 : &remote_video_sender_infos_;
3245}
3246
3247std::vector<PeerConnection::RtpSenderInfo>* PeerConnection::GetLocalSenderInfos(
deadbeefab9b2d12015-10-14 11:33:11 -07003248 cricket::MediaType media_type) {
3249 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
3250 media_type == cricket::MEDIA_TYPE_VIDEO);
Steve Anton4171afb2017-11-20 10:20:22 -08003251 return (media_type == cricket::MEDIA_TYPE_AUDIO) ? &local_audio_sender_infos_
3252 : &local_video_sender_infos_;
deadbeefab9b2d12015-10-14 11:33:11 -07003253}
3254
Steve Anton4171afb2017-11-20 10:20:22 -08003255const PeerConnection::RtpSenderInfo* PeerConnection::FindSenderInfo(
3256 const std::vector<PeerConnection::RtpSenderInfo>& infos,
deadbeefab9b2d12015-10-14 11:33:11 -07003257 const std::string& stream_label,
Steve Anton4171afb2017-11-20 10:20:22 -08003258 const std::string sender_id) const {
3259 for (const RtpSenderInfo& sender_info : infos) {
3260 if (sender_info.stream_label == stream_label &&
3261 sender_info.sender_id == sender_id) {
3262 return &sender_info;
deadbeefab9b2d12015-10-14 11:33:11 -07003263 }
3264 }
3265 return nullptr;
3266}
3267
3268DataChannel* PeerConnection::FindDataChannelBySid(int sid) const {
3269 for (const auto& channel : sctp_data_channels_) {
3270 if (channel->id() == sid) {
3271 return channel;
3272 }
3273 }
3274 return nullptr;
3275}
3276
deadbeef91dd5672016-05-18 16:55:30 -07003277bool PeerConnection::InitializePortAllocator_n(
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003278 const RTCConfiguration& configuration) {
3279 cricket::ServerAddresses stun_servers;
3280 std::vector<cricket::RelayServerConfig> turn_servers;
deadbeef293e9262017-01-11 12:28:30 -08003281 if (ParseIceServers(configuration.servers, &stun_servers, &turn_servers) !=
3282 RTCErrorType::NONE) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003283 return false;
3284 }
3285
Taylor Brandstetterf8e65772016-06-27 17:20:15 -07003286 port_allocator_->Initialize();
3287
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003288 // To handle both internal and externally created port allocator, we will
3289 // enable BUNDLE here.
3290 int portallocator_flags = port_allocator_->flags();
3291 portallocator_flags |= cricket::PORTALLOCATOR_ENABLE_SHARED_SOCKET |
zhihuangb09b3f92017-03-07 14:40:51 -08003292 cricket::PORTALLOCATOR_ENABLE_IPV6 |
3293 cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI;
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003294 // If the disable-IPv6 flag was specified, we'll not override it
3295 // by experiment.
3296 if (configuration.disable_ipv6) {
3297 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
sprangc1b57a12017-02-28 08:50:47 -08003298 } else if (webrtc::field_trial::FindFullName("WebRTC-IPv6Default")
3299 .find("Disabled") == 0) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003300 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
3301 }
3302
zhihuangb09b3f92017-03-07 14:40:51 -08003303 if (configuration.disable_ipv6_on_wifi) {
3304 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI);
Mirko Bonadei675513b2017-11-09 11:09:25 +01003305 RTC_LOG(LS_INFO) << "IPv6 candidates on Wi-Fi are disabled.";
zhihuangb09b3f92017-03-07 14:40:51 -08003306 }
3307
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003308 if (configuration.tcp_candidate_policy == kTcpCandidatePolicyDisabled) {
3309 portallocator_flags |= cricket::PORTALLOCATOR_DISABLE_TCP;
Mirko Bonadei675513b2017-11-09 11:09:25 +01003310 RTC_LOG(LS_INFO) << "TCP candidates are disabled.";
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003311 }
3312
honghaiz60347052016-05-31 18:29:12 -07003313 if (configuration.candidate_network_policy ==
3314 kCandidateNetworkPolicyLowCost) {
3315 portallocator_flags |= cricket::PORTALLOCATOR_DISABLE_COSTLY_NETWORKS;
Mirko Bonadei675513b2017-11-09 11:09:25 +01003316 RTC_LOG(LS_INFO) << "Do not gather candidates on high-cost networks";
honghaiz60347052016-05-31 18:29:12 -07003317 }
3318
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003319 port_allocator_->set_flags(portallocator_flags);
3320 // No step delay is used while allocating ports.
3321 port_allocator_->set_step_delay(cricket::kMinimumStepDelay);
3322 port_allocator_->set_candidate_filter(
3323 ConvertIceTransportTypeToCandidateFilter(configuration.type));
deadbeefd21eab32017-07-26 16:50:11 -07003324 port_allocator_->set_max_ipv6_networks(configuration.max_ipv6_networks);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003325
3326 // Call this last since it may create pooled allocator sessions using the
3327 // properties set above.
3328 port_allocator_->SetConfiguration(stun_servers, turn_servers,
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -07003329 configuration.ice_candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02003330 configuration.prune_turn_ports,
3331 configuration.turn_customizer);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003332 return true;
3333}
3334
deadbeef91dd5672016-05-18 16:55:30 -07003335bool PeerConnection::ReconfigurePortAllocator_n(
deadbeef293e9262017-01-11 12:28:30 -08003336 const cricket::ServerAddresses& stun_servers,
3337 const std::vector<cricket::RelayServerConfig>& turn_servers,
3338 IceTransportsType type,
3339 int candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02003340 bool prune_turn_ports,
3341 webrtc::TurnCustomizer* turn_customizer) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003342 port_allocator_->set_candidate_filter(
deadbeef293e9262017-01-11 12:28:30 -08003343 ConvertIceTransportTypeToCandidateFilter(type));
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003344 // Call this last since it may create pooled allocator sessions using the
3345 // candidate filter set above.
deadbeef6de92f92016-12-12 18:49:32 -08003346 return port_allocator_->SetConfiguration(
Jonas Orelandbdcee282017-10-10 14:01:40 +02003347 stun_servers, turn_servers, candidate_pool_size, prune_turn_ports,
3348 turn_customizer);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003349}
3350
Steve Antonba818672017-11-06 10:21:57 -08003351cricket::ChannelManager* PeerConnection::channel_manager() const {
3352 return factory_->channel_manager();
3353}
3354
3355MetricsObserverInterface* PeerConnection::metrics_observer() const {
3356 return uma_observer_;
3357}
3358
Elad Alon99c3fe52017-10-13 16:29:40 +02003359bool PeerConnection::StartRtcEventLog_w(
Bjorn Tereliusde939432017-11-20 17:38:14 +01003360 std::unique_ptr<RtcEventLogOutput> output,
3361 int64_t output_period_ms) {
zhihuang77985012017-02-07 15:45:16 -08003362 if (!event_log_) {
3363 return false;
3364 }
Bjorn Tereliusde939432017-11-20 17:38:14 +01003365 return event_log_->StartLogging(std::move(output), output_period_ms);
ivoc14d5dbe2016-07-04 07:06:55 -07003366}
3367
3368void PeerConnection::StopRtcEventLog_w() {
zhihuang77985012017-02-07 15:45:16 -08003369 if (event_log_) {
3370 event_log_->StopLogging();
3371 }
ivoc14d5dbe2016-07-04 07:06:55 -07003372}
nisseeaabdf62017-05-05 02:23:02 -07003373
Steve Anton75737c02017-11-06 10:37:17 -08003374cricket::BaseChannel* PeerConnection::GetChannel(
3375 const std::string& content_name) {
3376 if (voice_channel() && voice_channel()->content_name() == content_name) {
3377 return voice_channel();
3378 }
3379 if (video_channel() && video_channel()->content_name() == content_name) {
3380 return video_channel();
3381 }
3382 if (rtp_data_channel() &&
3383 rtp_data_channel()->content_name() == content_name) {
3384 return rtp_data_channel();
3385 }
3386 return nullptr;
3387}
3388
3389bool PeerConnection::GetSctpSslRole(rtc::SSLRole* role) {
3390 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003391 RTC_LOG(LS_INFO)
3392 << "Local and Remote descriptions must be applied to get the "
3393 << "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08003394 return false;
3395 }
3396 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003397 RTC_LOG(LS_INFO) << "Non-rejected SCTP m= section is needed to get the "
3398 << "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08003399 return false;
3400 }
3401
3402 return transport_controller_->GetSslRole(*sctp_transport_name_, role);
3403}
3404
3405bool PeerConnection::GetSslRole(const std::string& content_name,
3406 rtc::SSLRole* role) {
3407 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003408 RTC_LOG(LS_INFO)
3409 << "Local and Remote descriptions must be applied to get the "
3410 << "SSL Role of the session.";
Steve Anton75737c02017-11-06 10:37:17 -08003411 return false;
3412 }
3413
3414 return transport_controller_->GetSslRole(GetTransportName(content_name),
3415 role);
3416}
3417
Henrik Boström31638672017-11-23 17:48:32 +01003418bool PeerConnection::SetCurrentOrPendingLocalDescription(
Steve Anton75737c02017-11-06 10:37:17 -08003419 std::unique_ptr<SessionDescriptionInterface> desc,
3420 std::string* err_desc) {
3421 RTC_DCHECK(signaling_thread()->IsCurrent());
3422
3423 // Validate SDP.
3424 if (!ValidateSessionDescription(desc.get(), cricket::CS_LOCAL, err_desc)) {
3425 return false;
3426 }
3427
3428 // Update the initial_offerer flag if this session is the initial_offerer.
3429 Action action = GetAction(desc->type());
3430 if (!initial_offerer_.has_value()) {
3431 initial_offerer_.emplace(action == kOffer);
3432 if (*initial_offerer_) {
3433 transport_controller_->SetIceRole(cricket::ICEROLE_CONTROLLING);
3434 } else {
3435 transport_controller_->SetIceRole(cricket::ICEROLE_CONTROLLED);
3436 }
3437 }
3438
3439 if (action == kAnswer) {
3440 current_local_description_ = std::move(desc);
3441 pending_local_description_ = nullptr;
3442 current_remote_description_ = std::move(pending_remote_description_);
3443 } else {
3444 pending_local_description_ = std::move(desc);
3445 }
3446
3447 // Transport and Media channels will be created only when offer is set.
3448 if (action == kOffer && !CreateChannels(local_description()->description())) {
3449 // TODO(mallinath) - Handle CreateChannel failure, as new local description
3450 // is applied. Restore back to old description.
3451 return BadLocalSdp(local_description()->type(), kCreateChannelFailed,
3452 err_desc);
3453 }
3454
3455 // Remove unused channels if MediaContentDescription is rejected.
3456 RemoveUnusedChannels(local_description()->description());
3457
3458 if (!UpdateSessionState(action, cricket::CS_LOCAL, err_desc)) {
3459 return false;
3460 }
3461 if (remote_description()) {
3462 // Now that we have a local description, we can push down remote candidates.
3463 UseCandidatesInSessionDescription(remote_description());
3464 }
3465
3466 pending_ice_restarts_.clear();
3467 if (error() != ERROR_NONE) {
3468 return BadLocalSdp(local_description()->type(), GetSessionErrorMsg(),
3469 err_desc);
3470 }
3471 return true;
3472}
3473
Henrik Boström31638672017-11-23 17:48:32 +01003474bool PeerConnection::SetCurrentOrPendingRemoteDescription(
Steve Anton75737c02017-11-06 10:37:17 -08003475 std::unique_ptr<SessionDescriptionInterface> desc,
3476 std::string* err_desc) {
3477 RTC_DCHECK(signaling_thread()->IsCurrent());
3478
3479 // Validate SDP.
3480 if (!ValidateSessionDescription(desc.get(), cricket::CS_REMOTE, err_desc)) {
3481 return false;
3482 }
3483
3484 // Hold this pointer so candidates can be copied to it later in the method.
3485 SessionDescriptionInterface* desc_ptr = desc.get();
3486
3487 const SessionDescriptionInterface* old_remote_description =
3488 remote_description();
3489 // Grab ownership of the description being replaced for the remainder of this
3490 // method, since it's used below as |old_remote_description|.
3491 std::unique_ptr<SessionDescriptionInterface> replaced_remote_description;
3492 Action action = GetAction(desc->type());
3493 if (action == kAnswer) {
3494 replaced_remote_description = pending_remote_description_
3495 ? std::move(pending_remote_description_)
3496 : std::move(current_remote_description_);
3497 current_remote_description_ = std::move(desc);
3498 pending_remote_description_ = nullptr;
3499 current_local_description_ = std::move(pending_local_description_);
3500 } else {
3501 replaced_remote_description = std::move(pending_remote_description_);
3502 pending_remote_description_ = std::move(desc);
3503 }
3504
3505 // Transport and Media channels will be created only when offer is set.
3506 if (action == kOffer &&
3507 !CreateChannels(remote_description()->description())) {
3508 // TODO(mallinath) - Handle CreateChannel failure, as new local description
3509 // is applied. Restore back to old description.
3510 return BadRemoteSdp(remote_description()->type(), kCreateChannelFailed,
3511 err_desc);
3512 }
3513
3514 // Remove unused channels if MediaContentDescription is rejected.
3515 RemoveUnusedChannels(remote_description()->description());
3516
3517 // NOTE: Candidates allocation will be initiated only when SetLocalDescription
3518 // is called.
3519 if (!UpdateSessionState(action, cricket::CS_REMOTE, err_desc)) {
3520 return false;
3521 }
3522
3523 if (local_description() &&
3524 !UseCandidatesInSessionDescription(remote_description())) {
3525 return BadRemoteSdp(remote_description()->type(), kInvalidCandidates,
3526 err_desc);
3527 }
3528
3529 if (old_remote_description) {
3530 for (const cricket::ContentInfo& content :
3531 old_remote_description->description()->contents()) {
3532 // Check if this new SessionDescription contains new ICE ufrag and
3533 // password that indicates the remote peer requests an ICE restart.
3534 // TODO(deadbeef): When we start storing both the current and pending
3535 // remote description, this should reset pending_ice_restarts and compare
3536 // against the current description.
3537 if (CheckForRemoteIceRestart(old_remote_description, remote_description(),
3538 content.name)) {
3539 if (action == kOffer) {
3540 pending_ice_restarts_.insert(content.name);
3541 }
3542 } else {
3543 // We retain all received candidates only if ICE is not restarted.
3544 // When ICE is restarted, all previous candidates belong to an old
3545 // generation and should not be kept.
3546 // TODO(deadbeef): This goes against the W3C spec which says the remote
3547 // description should only contain candidates from the last set remote
3548 // description plus any candidates added since then. We should remove
3549 // this once we're sure it won't break anything.
3550 WebRtcSessionDescriptionFactory::CopyCandidatesFromSessionDescription(
3551 old_remote_description, content.name, desc_ptr);
3552 }
3553 }
3554 }
3555
3556 if (error() != ERROR_NONE) {
3557 return BadRemoteSdp(remote_description()->type(), GetSessionErrorMsg(),
3558 err_desc);
3559 }
3560
3561 // Set the the ICE connection state to connecting since the connection may
3562 // become writable with peer reflexive candidates before any remote candidate
3563 // is signaled.
3564 // TODO(pthatcher): This is a short-term solution for crbug/446908. A real fix
3565 // is to have a new signal the indicates a change in checking state from the
3566 // transport and expose a new checking() member from transport that can be
3567 // read to determine the current checking state. The existing SignalConnecting
3568 // actually means "gathering candidates", so cannot be be used here.
3569 if (remote_description()->type() != SessionDescriptionInterface::kOffer &&
3570 ice_connection_state() == PeerConnectionInterface::kIceConnectionNew) {
3571 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
3572 }
3573 return true;
3574}
3575
3576// TODO(steveanton): Eventually it'd be nice to store the channels as a single
3577// vector of BaseChannel pointers instead of separate voice and video channel
3578// vectors. At that point, this will become a simple getter.
3579std::vector<cricket::BaseChannel*> PeerConnection::Channels() const {
3580 std::vector<cricket::BaseChannel*> channels;
Steve Anton4171afb2017-11-20 10:20:22 -08003581 if (voice_channel()) {
3582 channels.push_back(voice_channel());
3583 }
3584 if (video_channel()) {
3585 channels.push_back(video_channel());
3586 }
Steve Anton75737c02017-11-06 10:37:17 -08003587 if (rtp_data_channel_) {
3588 channels.push_back(rtp_data_channel_);
3589 }
3590 return channels;
3591}
3592
3593void PeerConnection::SetError(Error error, const std::string& error_desc) {
3594 RTC_DCHECK(signaling_thread()->IsCurrent());
3595 if (error != error_) {
3596 error_ = error;
3597 error_desc_ = error_desc;
3598 }
3599}
3600
3601bool PeerConnection::UpdateSessionState(Action action,
3602 cricket::ContentSource source,
3603 std::string* err_desc) {
3604 RTC_DCHECK(signaling_thread()->IsCurrent());
3605
3606 // If there's already a pending error then no state transition should happen.
3607 // But all call-sites should be verifying this before calling us!
3608 RTC_DCHECK(error() == ERROR_NONE);
3609 std::string td_err;
3610 if (action == kOffer) {
3611 if (!PushdownTransportDescription(source, cricket::CA_OFFER, &td_err)) {
3612 return BadOfferSdp(source, MakeTdErrorString(td_err), err_desc);
3613 }
3614 ChangeSignalingState(source == cricket::CS_LOCAL
3615 ? PeerConnectionInterface::kHaveLocalOffer
3616 : PeerConnectionInterface::kHaveRemoteOffer);
3617 if (!PushdownMediaDescription(cricket::CA_OFFER, source, err_desc)) {
3618 SetError(ERROR_CONTENT, *err_desc);
3619 }
3620 if (error() != ERROR_NONE) {
3621 return BadOfferSdp(source, GetSessionErrorMsg(), err_desc);
3622 }
3623 } else if (action == kPrAnswer) {
3624 if (!PushdownTransportDescription(source, cricket::CA_PRANSWER, &td_err)) {
3625 return BadPranswerSdp(source, MakeTdErrorString(td_err), err_desc);
3626 }
3627 EnableChannels();
3628 ChangeSignalingState(source == cricket::CS_LOCAL
3629 ? PeerConnectionInterface::kHaveLocalPrAnswer
3630 : PeerConnectionInterface::kHaveRemotePrAnswer);
3631 if (!PushdownMediaDescription(cricket::CA_PRANSWER, source, err_desc)) {
3632 SetError(ERROR_CONTENT, *err_desc);
3633 }
3634 if (error() != ERROR_NONE) {
3635 return BadPranswerSdp(source, GetSessionErrorMsg(), err_desc);
3636 }
3637 } else if (action == kAnswer) {
3638 const cricket::ContentGroup* local_bundle =
3639 local_description()->description()->GetGroupByName(
3640 cricket::GROUP_TYPE_BUNDLE);
3641 const cricket::ContentGroup* remote_bundle =
3642 remote_description()->description()->GetGroupByName(
3643 cricket::GROUP_TYPE_BUNDLE);
3644 if (local_bundle && remote_bundle) {
3645 // The answerer decides the transport to bundle on.
3646 const cricket::ContentGroup* answer_bundle =
3647 (source == cricket::CS_LOCAL ? local_bundle : remote_bundle);
3648 if (!EnableBundle(*answer_bundle)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003649 RTC_LOG(LS_WARNING) << "Failed to enable BUNDLE.";
Steve Anton75737c02017-11-06 10:37:17 -08003650 return BadAnswerSdp(source, kEnableBundleFailed, err_desc);
3651 }
3652 }
3653 // Only push down the transport description after enabling BUNDLE; we don't
3654 // want to push down a description on a transport about to be destroyed.
3655 if (!PushdownTransportDescription(source, cricket::CA_ANSWER, &td_err)) {
3656 return BadAnswerSdp(source, MakeTdErrorString(td_err), err_desc);
3657 }
3658 EnableChannels();
3659 ChangeSignalingState(PeerConnectionInterface::kStable);
3660 if (!PushdownMediaDescription(cricket::CA_ANSWER, source, err_desc)) {
3661 SetError(ERROR_CONTENT, *err_desc);
3662 }
3663 if (error() != ERROR_NONE) {
3664 return BadAnswerSdp(source, GetSessionErrorMsg(), err_desc);
3665 }
3666 }
3667 return true;
3668}
3669
3670PeerConnection::Action PeerConnection::GetAction(const std::string& type) {
3671 if (type == SessionDescriptionInterface::kOffer) {
3672 return PeerConnection::kOffer;
3673 } else if (type == SessionDescriptionInterface::kPrAnswer) {
3674 return PeerConnection::kPrAnswer;
3675 } else if (type == SessionDescriptionInterface::kAnswer) {
3676 return PeerConnection::kAnswer;
3677 }
3678 RTC_NOTREACHED() << "unknown action type";
3679 return PeerConnection::kOffer;
3680}
3681
3682bool PeerConnection::PushdownMediaDescription(cricket::ContentAction action,
3683 cricket::ContentSource source,
3684 std::string* err) {
3685 const SessionDescription* sdesc =
3686 (source == cricket::CS_LOCAL ? local_description() : remote_description())
3687 ->description();
3688 RTC_DCHECK(sdesc);
3689 bool all_success = true;
3690 for (auto* channel : Channels()) {
3691 // TODO(steveanton): Add support for multiple channels of the same type.
3692 const ContentInfo* content_info =
3693 cricket::GetFirstMediaContent(sdesc->contents(), channel->media_type());
3694 if (!content_info) {
3695 continue;
3696 }
3697 const MediaContentDescription* content_desc =
3698 static_cast<const MediaContentDescription*>(content_info->description);
3699 if (content_desc && !content_info->rejected) {
3700 bool success = (source == cricket::CS_LOCAL)
3701 ? channel->SetLocalContent(content_desc, action, err)
3702 : channel->SetRemoteContent(content_desc, action, err);
3703 if (!success) {
3704 all_success = false;
3705 break;
3706 }
3707 }
3708 }
3709 // Need complete offer/answer with an SCTP m= section before starting SCTP,
3710 // according to https://tools.ietf.org/html/draft-ietf-mmusic-sctp-sdp-19
3711 if (sctp_transport_ && local_description() && remote_description() &&
3712 cricket::GetFirstDataContent(local_description()->description()) &&
3713 cricket::GetFirstDataContent(remote_description()->description())) {
3714 all_success &= network_thread()->Invoke<bool>(
3715 RTC_FROM_HERE,
3716 rtc::Bind(&PeerConnection::PushdownSctpParameters_n, this, source));
3717 }
3718 return all_success;
3719}
3720
3721bool PeerConnection::PushdownSctpParameters_n(cricket::ContentSource source) {
3722 RTC_DCHECK(network_thread()->IsCurrent());
3723 RTC_DCHECK(local_description());
3724 RTC_DCHECK(remote_description());
3725 // Apply the SCTP port (which is hidden inside a DataCodec structure...)
3726 // When we support "max-message-size", that would also be pushed down here.
3727 return sctp_transport_->Start(
3728 GetSctpPort(local_description()->description()),
3729 GetSctpPort(remote_description()->description()));
3730}
3731
3732bool PeerConnection::PushdownTransportDescription(cricket::ContentSource source,
3733 cricket::ContentAction action,
3734 std::string* error_desc) {
3735 RTC_DCHECK(signaling_thread()->IsCurrent());
3736
3737 if (source == cricket::CS_LOCAL) {
3738 return PushdownLocalTransportDescription(local_description()->description(),
3739 action, error_desc);
3740 }
3741 return PushdownRemoteTransportDescription(remote_description()->description(),
3742 action, error_desc);
3743}
3744
3745bool PeerConnection::PushdownLocalTransportDescription(
3746 const SessionDescription* sdesc,
3747 cricket::ContentAction action,
3748 std::string* err) {
3749 RTC_DCHECK(signaling_thread()->IsCurrent());
3750
3751 if (!sdesc) {
3752 return false;
3753 }
3754
3755 for (const TransportInfo& tinfo : sdesc->transport_infos()) {
3756 if (!transport_controller_->SetLocalTransportDescription(
3757 tinfo.content_name, tinfo.description, action, err)) {
3758 return false;
3759 }
3760 }
3761
3762 return true;
3763}
3764
3765bool PeerConnection::PushdownRemoteTransportDescription(
3766 const SessionDescription* sdesc,
3767 cricket::ContentAction action,
3768 std::string* err) {
3769 RTC_DCHECK(signaling_thread()->IsCurrent());
3770
3771 if (!sdesc) {
3772 return false;
3773 }
3774
3775 for (const TransportInfo& tinfo : sdesc->transport_infos()) {
3776 if (!transport_controller_->SetRemoteTransportDescription(
3777 tinfo.content_name, tinfo.description, action, err)) {
3778 return false;
3779 }
3780 }
3781
3782 return true;
3783}
3784
3785bool PeerConnection::GetTransportDescription(
3786 const SessionDescription* description,
3787 const std::string& content_name,
3788 cricket::TransportDescription* tdesc) {
3789 if (!description || !tdesc) {
3790 return false;
3791 }
3792 const TransportInfo* transport_info =
3793 description->GetTransportInfoByName(content_name);
3794 if (!transport_info) {
3795 return false;
3796 }
3797 *tdesc = transport_info->description;
3798 return true;
3799}
3800
3801bool PeerConnection::EnableBundle(const cricket::ContentGroup& bundle) {
3802 const std::string* first_content_name = bundle.FirstContentName();
3803 if (!first_content_name) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003804 RTC_LOG(LS_WARNING) << "Tried to BUNDLE with no contents.";
Steve Anton75737c02017-11-06 10:37:17 -08003805 return false;
3806 }
3807 const std::string& transport_name = *first_content_name;
3808
3809 auto maybe_set_transport = [this, bundle,
3810 transport_name](cricket::BaseChannel* ch) {
3811 if (!ch || !bundle.HasContentName(ch->content_name())) {
3812 return true;
3813 }
3814
3815 std::string old_transport_name = ch->transport_name();
3816 if (old_transport_name == transport_name) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003817 RTC_LOG(LS_INFO) << "BUNDLE already enabled for " << ch->content_name()
3818 << " on " << transport_name << ".";
Steve Anton75737c02017-11-06 10:37:17 -08003819 return true;
3820 }
3821
3822 cricket::DtlsTransportInternal* rtp_dtls_transport =
3823 transport_controller_->CreateDtlsTransport(
3824 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
3825 bool need_rtcp = (ch->rtcp_dtls_transport() != nullptr);
3826 cricket::DtlsTransportInternal* rtcp_dtls_transport = nullptr;
3827 if (need_rtcp) {
3828 rtcp_dtls_transport = transport_controller_->CreateDtlsTransport(
3829 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
3830 }
3831
3832 ch->SetTransports(rtp_dtls_transport, rtcp_dtls_transport);
Mirko Bonadei675513b2017-11-09 11:09:25 +01003833 RTC_LOG(LS_INFO) << "Enabled BUNDLE for " << ch->content_name() << " on "
3834 << transport_name << ".";
Steve Anton75737c02017-11-06 10:37:17 -08003835 transport_controller_->DestroyDtlsTransport(
3836 old_transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
3837 // If the channel needs rtcp, it means that the channel used to have a
3838 // rtcp transport which needs to be deleted now.
3839 if (need_rtcp) {
3840 transport_controller_->DestroyDtlsTransport(
3841 old_transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
3842 }
3843 return true;
3844 };
3845
3846 if (!maybe_set_transport(voice_channel()) ||
3847 !maybe_set_transport(video_channel()) ||
3848 !maybe_set_transport(rtp_data_channel())) {
3849 return false;
3850 }
3851 // For SCTP, transport creation/deletion happens here instead of in the
3852 // object itself.
3853 if (sctp_transport_) {
3854 RTC_DCHECK(sctp_transport_name_);
3855 RTC_DCHECK(sctp_content_name_);
3856 if (transport_name != *sctp_transport_name_ &&
3857 bundle.HasContentName(*sctp_content_name_)) {
3858 network_thread()->Invoke<void>(
3859 RTC_FROM_HERE, rtc::Bind(&PeerConnection::ChangeSctpTransport_n, this,
3860 transport_name));
3861 }
3862 }
3863
3864 return true;
3865}
3866
Steve Anton75737c02017-11-06 10:37:17 -08003867cricket::IceConfig PeerConnection::ParseIceConfig(
3868 const PeerConnectionInterface::RTCConfiguration& config) const {
3869 cricket::ContinualGatheringPolicy gathering_policy;
3870 // TODO(honghaiz): Add the third continual gathering policy in
3871 // PeerConnectionInterface and map it to GATHER_CONTINUALLY_AND_RECOVER.
3872 switch (config.continual_gathering_policy) {
3873 case PeerConnectionInterface::GATHER_ONCE:
3874 gathering_policy = cricket::GATHER_ONCE;
3875 break;
3876 case PeerConnectionInterface::GATHER_CONTINUALLY:
3877 gathering_policy = cricket::GATHER_CONTINUALLY;
3878 break;
3879 default:
3880 RTC_NOTREACHED();
3881 gathering_policy = cricket::GATHER_ONCE;
3882 }
3883 cricket::IceConfig ice_config;
3884 ice_config.receiving_timeout = config.ice_connection_receiving_timeout;
3885 ice_config.prioritize_most_likely_candidate_pairs =
3886 config.prioritize_most_likely_ice_candidate_pairs;
3887 ice_config.backup_connection_ping_interval =
3888 config.ice_backup_candidate_pair_ping_interval;
3889 ice_config.continual_gathering_policy = gathering_policy;
3890 ice_config.presume_writable_when_fully_relayed =
3891 config.presume_writable_when_fully_relayed;
3892 ice_config.ice_check_min_interval = config.ice_check_min_interval;
3893 ice_config.regather_all_networks_interval_range =
3894 config.ice_regather_interval_range;
3895 return ice_config;
3896}
3897
Steve Anton75737c02017-11-06 10:37:17 -08003898bool PeerConnection::GetLocalTrackIdBySsrc(uint32_t ssrc,
3899 std::string* track_id) {
3900 if (!local_description()) {
3901 return false;
3902 }
3903 return webrtc::GetTrackIdBySsrc(local_description()->description(), ssrc,
3904 track_id);
3905}
3906
3907bool PeerConnection::GetRemoteTrackIdBySsrc(uint32_t ssrc,
3908 std::string* track_id) {
3909 if (!remote_description()) {
3910 return false;
3911 }
3912 return webrtc::GetTrackIdBySsrc(remote_description()->description(), ssrc,
3913 track_id);
3914}
3915
3916bool PeerConnection::SendData(const cricket::SendDataParams& params,
3917 const rtc::CopyOnWriteBuffer& payload,
3918 cricket::SendDataResult* result) {
3919 if (!rtp_data_channel_ && !sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003920 RTC_LOG(LS_ERROR) << "SendData called when rtp_data_channel_ "
3921 << "and sctp_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08003922 return false;
3923 }
3924 return rtp_data_channel_
3925 ? rtp_data_channel_->SendData(params, payload, result)
3926 : network_thread()->Invoke<bool>(
3927 RTC_FROM_HERE,
3928 Bind(&cricket::SctpTransportInternal::SendData,
3929 sctp_transport_.get(), params, payload, result));
3930}
3931
3932bool PeerConnection::ConnectDataChannel(DataChannel* webrtc_data_channel) {
3933 if (!rtp_data_channel_ && !sctp_transport_) {
3934 // Don't log an error here, because DataChannels are expected to call
3935 // ConnectDataChannel in this state. It's the only way to initially tell
3936 // whether or not the underlying transport is ready.
3937 return false;
3938 }
3939 if (rtp_data_channel_) {
3940 rtp_data_channel_->SignalReadyToSendData.connect(
3941 webrtc_data_channel, &DataChannel::OnChannelReady);
3942 rtp_data_channel_->SignalDataReceived.connect(webrtc_data_channel,
3943 &DataChannel::OnDataReceived);
3944 } else {
3945 SignalSctpReadyToSendData.connect(webrtc_data_channel,
3946 &DataChannel::OnChannelReady);
3947 SignalSctpDataReceived.connect(webrtc_data_channel,
3948 &DataChannel::OnDataReceived);
3949 SignalSctpStreamClosedRemotely.connect(
3950 webrtc_data_channel, &DataChannel::OnStreamClosedRemotely);
3951 }
3952 return true;
3953}
3954
3955void PeerConnection::DisconnectDataChannel(DataChannel* webrtc_data_channel) {
3956 if (!rtp_data_channel_ && !sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003957 RTC_LOG(LS_ERROR)
3958 << "DisconnectDataChannel called when rtp_data_channel_ and "
3959 "sctp_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08003960 return;
3961 }
3962 if (rtp_data_channel_) {
3963 rtp_data_channel_->SignalReadyToSendData.disconnect(webrtc_data_channel);
3964 rtp_data_channel_->SignalDataReceived.disconnect(webrtc_data_channel);
3965 } else {
3966 SignalSctpReadyToSendData.disconnect(webrtc_data_channel);
3967 SignalSctpDataReceived.disconnect(webrtc_data_channel);
3968 SignalSctpStreamClosedRemotely.disconnect(webrtc_data_channel);
3969 }
3970}
3971
3972void PeerConnection::AddSctpDataStream(int sid) {
3973 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003974 RTC_LOG(LS_ERROR)
3975 << "AddSctpDataStream called when sctp_transport_ is NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08003976 return;
3977 }
3978 network_thread()->Invoke<void>(
3979 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::OpenStream,
3980 sctp_transport_.get(), sid));
3981}
3982
3983void PeerConnection::RemoveSctpDataStream(int sid) {
3984 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003985 RTC_LOG(LS_ERROR) << "RemoveSctpDataStream called when sctp_transport_ is "
3986 << "NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08003987 return;
3988 }
3989 network_thread()->Invoke<void>(
3990 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::ResetStream,
3991 sctp_transport_.get(), sid));
3992}
3993
3994bool PeerConnection::ReadyToSendData() const {
3995 return (rtp_data_channel_ && rtp_data_channel_->ready_to_send_data()) ||
3996 sctp_ready_to_send_data_;
3997}
3998
3999std::unique_ptr<SessionStats> PeerConnection::GetSessionStats_s() {
4000 RTC_DCHECK(signaling_thread()->IsCurrent());
4001 ChannelNamePairs channel_name_pairs;
4002 if (voice_channel()) {
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004003 channel_name_pairs.voice = ChannelNamePair(
4004 voice_channel()->content_name(), voice_channel()->transport_name());
Steve Anton75737c02017-11-06 10:37:17 -08004005 }
4006 if (video_channel()) {
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004007 channel_name_pairs.video = ChannelNamePair(
4008 video_channel()->content_name(), video_channel()->transport_name());
Steve Anton75737c02017-11-06 10:37:17 -08004009 }
4010 if (rtp_data_channel()) {
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004011 channel_name_pairs.data =
Steve Anton75737c02017-11-06 10:37:17 -08004012 ChannelNamePair(rtp_data_channel()->content_name(),
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004013 rtp_data_channel()->transport_name());
Steve Anton75737c02017-11-06 10:37:17 -08004014 }
4015 if (sctp_transport_) {
4016 RTC_DCHECK(sctp_content_name_);
4017 RTC_DCHECK(sctp_transport_name_);
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004018 channel_name_pairs.data =
4019 ChannelNamePair(*sctp_content_name_, *sctp_transport_name_);
Steve Anton75737c02017-11-06 10:37:17 -08004020 }
4021 return GetSessionStats(channel_name_pairs);
4022}
4023
4024std::unique_ptr<SessionStats> PeerConnection::GetSessionStats(
4025 const ChannelNamePairs& channel_name_pairs) {
4026 if (network_thread()->IsCurrent()) {
4027 return GetSessionStats_n(channel_name_pairs);
4028 }
4029 return network_thread()->Invoke<std::unique_ptr<SessionStats>>(
4030 RTC_FROM_HERE,
4031 rtc::Bind(&PeerConnection::GetSessionStats_n, this, channel_name_pairs));
4032}
4033
4034bool PeerConnection::GetLocalCertificate(
4035 const std::string& transport_name,
4036 rtc::scoped_refptr<rtc::RTCCertificate>* certificate) {
4037 return transport_controller_->GetLocalCertificate(transport_name,
4038 certificate);
4039}
4040
4041std::unique_ptr<rtc::SSLCertificate> PeerConnection::GetRemoteSSLCertificate(
4042 const std::string& transport_name) {
4043 return transport_controller_->GetRemoteSSLCertificate(transport_name);
4044}
4045
4046cricket::DataChannelType PeerConnection::data_channel_type() const {
4047 return data_channel_type_;
4048}
4049
4050bool PeerConnection::IceRestartPending(const std::string& content_name) const {
4051 return pending_ice_restarts_.find(content_name) !=
4052 pending_ice_restarts_.end();
4053}
4054
Steve Anton75737c02017-11-06 10:37:17 -08004055bool PeerConnection::NeedsIceRestart(const std::string& content_name) const {
4056 return transport_controller_->NeedsIceRestart(content_name);
4057}
4058
4059void PeerConnection::OnCertificateReady(
4060 const rtc::scoped_refptr<rtc::RTCCertificate>& certificate) {
4061 transport_controller_->SetLocalCertificate(certificate);
4062}
4063
4064void PeerConnection::OnDtlsSrtpSetupFailure(cricket::BaseChannel*, bool rtcp) {
4065 SetError(ERROR_TRANSPORT,
4066 rtcp ? kDtlsSrtpSetupFailureRtcp : kDtlsSrtpSetupFailureRtp);
4067}
4068
4069void PeerConnection::OnTransportControllerConnectionState(
4070 cricket::IceConnectionState state) {
4071 switch (state) {
4072 case cricket::kIceConnectionConnecting:
4073 // If the current state is Connected or Completed, then there were
4074 // writable channels but now there are not, so the next state must
4075 // be Disconnected.
4076 // kIceConnectionConnecting is currently used as the default,
4077 // un-connected state by the TransportController, so its only use is
4078 // detecting disconnections.
4079 if (ice_connection_state_ ==
4080 PeerConnectionInterface::kIceConnectionConnected ||
4081 ice_connection_state_ ==
4082 PeerConnectionInterface::kIceConnectionCompleted) {
4083 SetIceConnectionState(
4084 PeerConnectionInterface::kIceConnectionDisconnected);
4085 }
4086 break;
4087 case cricket::kIceConnectionFailed:
4088 SetIceConnectionState(PeerConnectionInterface::kIceConnectionFailed);
4089 break;
4090 case cricket::kIceConnectionConnected:
Mirko Bonadei675513b2017-11-09 11:09:25 +01004091 RTC_LOG(LS_INFO) << "Changing to ICE connected state because "
4092 << "all transports are writable.";
Steve Anton75737c02017-11-06 10:37:17 -08004093 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
4094 break;
4095 case cricket::kIceConnectionCompleted:
Mirko Bonadei675513b2017-11-09 11:09:25 +01004096 RTC_LOG(LS_INFO) << "Changing to ICE completed state because "
4097 << "all transports are complete.";
Steve Anton75737c02017-11-06 10:37:17 -08004098 if (ice_connection_state_ !=
4099 PeerConnectionInterface::kIceConnectionConnected) {
4100 // If jumping directly from "checking" to "connected",
4101 // signal "connected" first.
4102 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
4103 }
4104 SetIceConnectionState(PeerConnectionInterface::kIceConnectionCompleted);
4105 if (metrics_observer()) {
4106 ReportTransportStats();
4107 }
4108 break;
4109 default:
4110 RTC_NOTREACHED();
4111 }
4112}
4113
4114void PeerConnection::OnTransportControllerCandidatesGathered(
4115 const std::string& transport_name,
4116 const cricket::Candidates& candidates) {
4117 RTC_DCHECK(signaling_thread()->IsCurrent());
4118 int sdp_mline_index;
4119 if (!GetLocalCandidateMediaIndex(transport_name, &sdp_mline_index)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004120 RTC_LOG(LS_ERROR)
4121 << "OnTransportControllerCandidatesGathered: content name "
4122 << transport_name << " not found";
Steve Anton75737c02017-11-06 10:37:17 -08004123 return;
4124 }
4125
4126 for (cricket::Candidates::const_iterator citer = candidates.begin();
4127 citer != candidates.end(); ++citer) {
4128 // Use transport_name as the candidate media id.
4129 std::unique_ptr<JsepIceCandidate> candidate(
4130 new JsepIceCandidate(transport_name, sdp_mline_index, *citer));
4131 if (local_description()) {
4132 mutable_local_description()->AddCandidate(candidate.get());
4133 }
4134 OnIceCandidate(std::move(candidate));
4135 }
4136}
4137
4138void PeerConnection::OnTransportControllerCandidatesRemoved(
4139 const std::vector<cricket::Candidate>& candidates) {
4140 RTC_DCHECK(signaling_thread()->IsCurrent());
4141 // Sanity check.
4142 for (const cricket::Candidate& candidate : candidates) {
4143 if (candidate.transport_name().empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004144 RTC_LOG(LS_ERROR) << "OnTransportControllerCandidatesRemoved: "
4145 << "empty content name in candidate "
4146 << candidate.ToString();
Steve Anton75737c02017-11-06 10:37:17 -08004147 return;
4148 }
4149 }
4150
4151 if (local_description()) {
4152 mutable_local_description()->RemoveCandidates(candidates);
4153 }
4154 OnIceCandidatesRemoved(candidates);
4155}
4156
4157void PeerConnection::OnTransportControllerDtlsHandshakeError(
4158 rtc::SSLHandshakeError error) {
4159 if (metrics_observer()) {
4160 metrics_observer()->IncrementEnumCounter(
4161 webrtc::kEnumCounterDtlsHandshakeError, static_cast<int>(error),
4162 static_cast<int>(rtc::SSLHandshakeError::MAX_VALUE));
4163 }
4164}
4165
4166// Enabling voice and video (and RTP data) channels.
4167void PeerConnection::EnableChannels() {
Steve Anton4171afb2017-11-20 10:20:22 -08004168 if (voice_channel() && !voice_channel()->enabled()) {
4169 voice_channel()->Enable(true);
Steve Anton75737c02017-11-06 10:37:17 -08004170 }
4171
Steve Anton4171afb2017-11-20 10:20:22 -08004172 if (video_channel() && !video_channel()->enabled()) {
4173 video_channel()->Enable(true);
Steve Anton75737c02017-11-06 10:37:17 -08004174 }
4175
Steve Anton4171afb2017-11-20 10:20:22 -08004176 if (rtp_data_channel_ && !rtp_data_channel_->enabled()) {
Steve Anton75737c02017-11-06 10:37:17 -08004177 rtp_data_channel_->Enable(true);
Steve Anton4171afb2017-11-20 10:20:22 -08004178 }
Steve Anton75737c02017-11-06 10:37:17 -08004179}
4180
4181// Returns the media index for a local ice candidate given the content name.
4182bool PeerConnection::GetLocalCandidateMediaIndex(
4183 const std::string& content_name,
4184 int* sdp_mline_index) {
4185 if (!local_description() || !sdp_mline_index) {
4186 return false;
4187 }
4188
4189 bool content_found = false;
4190 const ContentInfos& contents = local_description()->description()->contents();
4191 for (size_t index = 0; index < contents.size(); ++index) {
4192 if (contents[index].name == content_name) {
4193 *sdp_mline_index = static_cast<int>(index);
4194 content_found = true;
4195 break;
4196 }
4197 }
4198 return content_found;
4199}
4200
4201bool PeerConnection::UseCandidatesInSessionDescription(
4202 const SessionDescriptionInterface* remote_desc) {
4203 if (!remote_desc) {
4204 return true;
4205 }
4206 bool ret = true;
4207
4208 for (size_t m = 0; m < remote_desc->number_of_mediasections(); ++m) {
4209 const IceCandidateCollection* candidates = remote_desc->candidates(m);
4210 for (size_t n = 0; n < candidates->count(); ++n) {
4211 const IceCandidateInterface* candidate = candidates->at(n);
4212 bool valid = false;
4213 if (!ReadyToUseRemoteCandidate(candidate, remote_desc, &valid)) {
4214 if (valid) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004215 RTC_LOG(LS_INFO)
4216 << "UseCandidatesInSessionDescription: Not ready to use "
4217 << "candidate.";
Steve Anton75737c02017-11-06 10:37:17 -08004218 }
4219 continue;
4220 }
4221 ret = UseCandidate(candidate);
4222 if (!ret) {
4223 break;
4224 }
4225 }
4226 }
4227 return ret;
4228}
4229
4230bool PeerConnection::UseCandidate(const IceCandidateInterface* candidate) {
4231 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
4232 size_t remote_content_size =
4233 remote_description()->description()->contents().size();
4234 if (mediacontent_index >= remote_content_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004235 RTC_LOG(LS_ERROR) << "UseCandidate: Invalid candidate media index.";
Steve Anton75737c02017-11-06 10:37:17 -08004236 return false;
4237 }
4238
4239 cricket::ContentInfo content =
4240 remote_description()->description()->contents()[mediacontent_index];
4241 std::vector<cricket::Candidate> candidates;
4242 candidates.push_back(candidate->candidate());
4243 // Invoking BaseSession method to handle remote candidates.
4244 std::string error;
4245 if (transport_controller_->AddRemoteCandidates(content.name, candidates,
4246 &error)) {
4247 // Candidates successfully submitted for checking.
4248 if (ice_connection_state_ == PeerConnectionInterface::kIceConnectionNew ||
4249 ice_connection_state_ ==
4250 PeerConnectionInterface::kIceConnectionDisconnected) {
4251 // If state is New, then the session has just gotten its first remote ICE
4252 // candidates, so go to Checking.
4253 // If state is Disconnected, the session is re-using old candidates or
4254 // receiving additional ones, so go to Checking.
4255 // If state is Connected, stay Connected.
4256 // TODO(bemasc): If state is Connected, and the new candidates are for a
4257 // newly added transport, then the state actually _should_ move to
4258 // checking. Add a way to distinguish that case.
4259 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
4260 }
4261 // TODO(bemasc): If state is Completed, go back to Connected.
4262 } else {
4263 if (!error.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004264 RTC_LOG(LS_WARNING) << error;
Steve Anton75737c02017-11-06 10:37:17 -08004265 }
4266 }
4267 return true;
4268}
4269
4270void PeerConnection::RemoveUnusedChannels(const SessionDescription* desc) {
4271 // TODO(steveanton): Add support for multiple audio/video channels.
4272 // Destroy video channel first since it may have a pointer to the
4273 // voice channel.
4274 const cricket::ContentInfo* video_info = cricket::GetFirstVideoContent(desc);
4275 if ((!video_info || video_info->rejected) && video_channel()) {
Steve Anton4171afb2017-11-20 10:20:22 -08004276 DestroyVideoChannel(video_channel());
Steve Anton75737c02017-11-06 10:37:17 -08004277 }
4278
4279 const cricket::ContentInfo* voice_info = cricket::GetFirstAudioContent(desc);
4280 if ((!voice_info || voice_info->rejected) && voice_channel()) {
Steve Anton4171afb2017-11-20 10:20:22 -08004281 DestroyVoiceChannel(voice_channel());
Steve Anton75737c02017-11-06 10:37:17 -08004282 }
4283
4284 const cricket::ContentInfo* data_info = cricket::GetFirstDataContent(desc);
4285 if (!data_info || data_info->rejected) {
4286 if (rtp_data_channel_) {
4287 DestroyDataChannel();
4288 }
4289 if (sctp_transport_) {
4290 OnDataChannelDestroyed();
4291 network_thread()->Invoke<void>(
4292 RTC_FROM_HERE,
4293 rtc::Bind(&PeerConnection::DestroySctpTransport_n, this));
4294 }
4295 }
4296}
4297
4298// Returns the name of the transport channel when BUNDLE is enabled, or nullptr
4299// if the channel is not part of any bundle.
4300const std::string* PeerConnection::GetBundleTransportName(
4301 const cricket::ContentInfo* content,
4302 const cricket::ContentGroup* bundle) {
4303 if (!bundle) {
4304 return nullptr;
4305 }
4306 const std::string* first_content_name = bundle->FirstContentName();
4307 if (!first_content_name) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004308 RTC_LOG(LS_WARNING) << "Tried to BUNDLE with no contents.";
Steve Anton75737c02017-11-06 10:37:17 -08004309 return nullptr;
4310 }
4311 if (!bundle->HasContentName(content->name)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004312 RTC_LOG(LS_WARNING) << content->name << " is not part of any bundle group";
Steve Anton75737c02017-11-06 10:37:17 -08004313 return nullptr;
4314 }
Mirko Bonadei675513b2017-11-09 11:09:25 +01004315 RTC_LOG(LS_INFO) << "Bundling " << content->name << " on "
4316 << *first_content_name;
Steve Anton75737c02017-11-06 10:37:17 -08004317 return first_content_name;
4318}
4319
4320bool PeerConnection::CreateChannels(const SessionDescription* desc) {
4321 // TODO(steveanton): Add support for multiple audio/video channels.
4322 const cricket::ContentGroup* bundle_group = nullptr;
4323 if (configuration_.bundle_policy ==
4324 PeerConnectionInterface::kBundlePolicyMaxBundle) {
4325 bundle_group = desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
4326 if (!bundle_group) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004327 RTC_LOG(LS_WARNING) << "max-bundle specified without BUNDLE specified";
Steve Anton75737c02017-11-06 10:37:17 -08004328 return false;
4329 }
4330 }
4331 // Creating the media channels and transport proxies.
4332 const cricket::ContentInfo* voice = cricket::GetFirstAudioContent(desc);
4333 if (voice && !voice->rejected && !voice_channel()) {
4334 if (!CreateVoiceChannel(voice,
4335 GetBundleTransportName(voice, bundle_group))) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004336 RTC_LOG(LS_ERROR) << "Failed to create voice channel.";
Steve Anton75737c02017-11-06 10:37:17 -08004337 return false;
4338 }
4339 }
4340
4341 const cricket::ContentInfo* video = cricket::GetFirstVideoContent(desc);
4342 if (video && !video->rejected && !video_channel()) {
4343 if (!CreateVideoChannel(video,
4344 GetBundleTransportName(video, bundle_group))) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004345 RTC_LOG(LS_ERROR) << "Failed to create video channel.";
Steve Anton75737c02017-11-06 10:37:17 -08004346 return false;
4347 }
4348 }
4349
4350 const cricket::ContentInfo* data = cricket::GetFirstDataContent(desc);
4351 if (data_channel_type_ != cricket::DCT_NONE && data && !data->rejected &&
4352 !rtp_data_channel_ && !sctp_transport_) {
4353 if (!CreateDataChannel(data, GetBundleTransportName(data, bundle_group))) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004354 RTC_LOG(LS_ERROR) << "Failed to create data channel.";
Steve Anton75737c02017-11-06 10:37:17 -08004355 return false;
4356 }
4357 }
4358
4359 return true;
4360}
4361
Steve Anton4171afb2017-11-20 10:20:22 -08004362// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Anton75737c02017-11-06 10:37:17 -08004363bool PeerConnection::CreateVoiceChannel(const cricket::ContentInfo* content,
4364 const std::string* bundle_transport) {
4365 // TODO(steveanton): Check to see if it's safe to create multiple voice
4366 // channels.
Steve Anton4171afb2017-11-20 10:20:22 -08004367 RTC_DCHECK(!voice_channel());
Steve Anton75737c02017-11-06 10:37:17 -08004368
4369 std::string transport_name =
4370 bundle_transport ? *bundle_transport : content->name;
4371
4372 cricket::DtlsTransportInternal* rtp_dtls_transport =
4373 transport_controller_->CreateDtlsTransport(
4374 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4375 cricket::DtlsTransportInternal* rtcp_dtls_transport = nullptr;
4376 if (configuration_.rtcp_mux_policy !=
4377 PeerConnectionInterface::kRtcpMuxPolicyRequire) {
4378 rtcp_dtls_transport = transport_controller_->CreateDtlsTransport(
4379 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
4380 }
4381
4382 cricket::VoiceChannel* voice_channel = channel_manager()->CreateVoiceChannel(
4383 call_.get(), configuration_.media_config, rtp_dtls_transport,
4384 rtcp_dtls_transport, transport_controller_->signaling_thread(),
4385 content->name, SrtpRequired(), audio_options_);
4386 if (!voice_channel) {
4387 transport_controller_->DestroyDtlsTransport(
4388 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4389 if (rtcp_dtls_transport) {
4390 transport_controller_->DestroyDtlsTransport(
4391 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
4392 }
4393 return false;
4394 }
Steve Anton75737c02017-11-06 10:37:17 -08004395 voice_channel->SignalRtcpMuxFullyActive.connect(
4396 this, &PeerConnection::DestroyRtcpTransport_n);
4397 voice_channel->SignalDtlsSrtpSetupFailure.connect(
4398 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08004399 voice_channel->SignalSentPacket.connect(this,
4400 &PeerConnection::OnSentPacket_w);
Steve Anton4171afb2017-11-20 10:20:22 -08004401
4402 GetAudioTransceiver()->internal()->SetChannel(voice_channel);
4403
Steve Anton75737c02017-11-06 10:37:17 -08004404 return true;
4405}
4406
Steve Anton4171afb2017-11-20 10:20:22 -08004407// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Anton75737c02017-11-06 10:37:17 -08004408bool PeerConnection::CreateVideoChannel(const cricket::ContentInfo* content,
4409 const std::string* bundle_transport) {
4410 // TODO(steveanton): Check to see if it's safe to create multiple video
4411 // channels.
Steve Anton4171afb2017-11-20 10:20:22 -08004412 RTC_DCHECK(!video_channel());
Steve Anton75737c02017-11-06 10:37:17 -08004413
4414 std::string transport_name =
4415 bundle_transport ? *bundle_transport : content->name;
4416
4417 cricket::DtlsTransportInternal* rtp_dtls_transport =
4418 transport_controller_->CreateDtlsTransport(
4419 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4420 cricket::DtlsTransportInternal* rtcp_dtls_transport = nullptr;
4421 if (configuration_.rtcp_mux_policy !=
4422 PeerConnectionInterface::kRtcpMuxPolicyRequire) {
4423 rtcp_dtls_transport = transport_controller_->CreateDtlsTransport(
4424 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
4425 }
4426
4427 cricket::VideoChannel* video_channel = channel_manager()->CreateVideoChannel(
4428 call_.get(), configuration_.media_config, rtp_dtls_transport,
4429 rtcp_dtls_transport, transport_controller_->signaling_thread(),
4430 content->name, SrtpRequired(), video_options_);
4431
4432 if (!video_channel) {
4433 transport_controller_->DestroyDtlsTransport(
4434 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4435 if (rtcp_dtls_transport) {
4436 transport_controller_->DestroyDtlsTransport(
4437 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
4438 }
4439 return false;
4440 }
Steve Anton75737c02017-11-06 10:37:17 -08004441 video_channel->SignalRtcpMuxFullyActive.connect(
4442 this, &PeerConnection::DestroyRtcpTransport_n);
4443 video_channel->SignalDtlsSrtpSetupFailure.connect(
4444 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08004445 video_channel->SignalSentPacket.connect(this,
4446 &PeerConnection::OnSentPacket_w);
Steve Anton4171afb2017-11-20 10:20:22 -08004447
4448 GetVideoTransceiver()->internal()->SetChannel(video_channel);
4449
Steve Anton75737c02017-11-06 10:37:17 -08004450 return true;
4451}
4452
4453bool PeerConnection::CreateDataChannel(const cricket::ContentInfo* content,
4454 const std::string* bundle_transport) {
4455 const std::string transport_name =
4456 bundle_transport ? *bundle_transport : content->name;
4457 bool sctp = (data_channel_type_ == cricket::DCT_SCTP);
4458 if (sctp) {
4459 if (!sctp_factory_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004460 RTC_LOG(LS_ERROR)
Steve Anton75737c02017-11-06 10:37:17 -08004461 << "Trying to create SCTP transport, but didn't compile with "
4462 "SCTP support (HAVE_SCTP)";
4463 return false;
4464 }
4465 if (!network_thread()->Invoke<bool>(
4466 RTC_FROM_HERE, rtc::Bind(&PeerConnection::CreateSctpTransport_n,
4467 this, content->name, transport_name))) {
4468 return false;
4469 }
4470 } else {
4471 std::string transport_name =
4472 bundle_transport ? *bundle_transport : content->name;
4473 cricket::DtlsTransportInternal* rtp_dtls_transport =
4474 transport_controller_->CreateDtlsTransport(
4475 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4476 cricket::DtlsTransportInternal* rtcp_dtls_transport = nullptr;
4477 if (configuration_.rtcp_mux_policy !=
4478 PeerConnectionInterface::kRtcpMuxPolicyRequire) {
4479 rtcp_dtls_transport = transport_controller_->CreateDtlsTransport(
4480 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
4481 }
4482
4483 rtp_data_channel_ = channel_manager()->CreateRtpDataChannel(
4484 configuration_.media_config, rtp_dtls_transport, rtcp_dtls_transport,
4485 transport_controller_->signaling_thread(), content->name,
4486 SrtpRequired());
4487
4488 if (!rtp_data_channel_) {
4489 transport_controller_->DestroyDtlsTransport(
4490 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4491 if (rtcp_dtls_transport) {
4492 transport_controller_->DestroyDtlsTransport(
4493 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
4494 }
4495 return false;
4496 }
4497
4498 rtp_data_channel_->SignalRtcpMuxFullyActive.connect(
4499 this, &PeerConnection::DestroyRtcpTransport_n);
4500 rtp_data_channel_->SignalDtlsSrtpSetupFailure.connect(
4501 this, &PeerConnection::OnDtlsSrtpSetupFailure);
4502 rtp_data_channel_->SignalSentPacket.connect(
4503 this, &PeerConnection::OnSentPacket_w);
4504 }
4505
Steve Antond25da372017-11-06 14:50:29 -08004506 for (const auto& channel : sctp_data_channels_) {
4507 channel->OnTransportChannelCreated();
4508 }
Steve Anton75737c02017-11-06 10:37:17 -08004509
4510 return true;
4511}
4512
4513Call::Stats PeerConnection::GetCallStats() {
4514 if (!worker_thread()->IsCurrent()) {
4515 return worker_thread()->Invoke<Call::Stats>(
4516 RTC_FROM_HERE, rtc::Bind(&PeerConnection::GetCallStats, this));
4517 }
4518 if (call_) {
4519 return call_->GetStats();
4520 } else {
4521 return Call::Stats();
4522 }
4523}
4524
4525std::unique_ptr<SessionStats> PeerConnection::GetSessionStats_n(
4526 const ChannelNamePairs& channel_name_pairs) {
4527 RTC_DCHECK(network_thread()->IsCurrent());
4528 std::unique_ptr<SessionStats> session_stats(new SessionStats());
4529 for (const auto channel_name_pair :
4530 {&channel_name_pairs.voice, &channel_name_pairs.video,
4531 &channel_name_pairs.data}) {
4532 if (*channel_name_pair) {
4533 cricket::TransportStats transport_stats;
4534 if (!transport_controller_->GetStats((*channel_name_pair)->transport_name,
4535 &transport_stats)) {
4536 return nullptr;
4537 }
4538 session_stats->proxy_to_transport[(*channel_name_pair)->content_name] =
4539 (*channel_name_pair)->transport_name;
4540 session_stats->transport_stats[(*channel_name_pair)->transport_name] =
4541 std::move(transport_stats);
4542 }
4543 }
4544 return session_stats;
4545}
4546
4547bool PeerConnection::CreateSctpTransport_n(const std::string& content_name,
4548 const std::string& transport_name) {
4549 RTC_DCHECK(network_thread()->IsCurrent());
4550 RTC_DCHECK(sctp_factory_);
4551 cricket::DtlsTransportInternal* tc =
4552 transport_controller_->CreateDtlsTransport_n(
4553 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4554 sctp_transport_ = sctp_factory_->CreateSctpTransport(tc);
4555 RTC_DCHECK(sctp_transport_);
4556 sctp_invoker_.reset(new rtc::AsyncInvoker());
4557 sctp_transport_->SignalReadyToSendData.connect(
4558 this, &PeerConnection::OnSctpTransportReadyToSendData_n);
4559 sctp_transport_->SignalDataReceived.connect(
4560 this, &PeerConnection::OnSctpTransportDataReceived_n);
4561 sctp_transport_->SignalStreamClosedRemotely.connect(
4562 this, &PeerConnection::OnSctpStreamClosedRemotely_n);
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004563 sctp_transport_name_ = transport_name;
4564 sctp_content_name_ = content_name;
Steve Anton75737c02017-11-06 10:37:17 -08004565 return true;
4566}
4567
4568void PeerConnection::ChangeSctpTransport_n(const std::string& transport_name) {
4569 RTC_DCHECK(network_thread()->IsCurrent());
4570 RTC_DCHECK(sctp_transport_);
4571 RTC_DCHECK(sctp_transport_name_);
4572 std::string old_sctp_transport_name = *sctp_transport_name_;
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004573 sctp_transport_name_ = transport_name;
Steve Anton75737c02017-11-06 10:37:17 -08004574 cricket::DtlsTransportInternal* tc =
4575 transport_controller_->CreateDtlsTransport_n(
4576 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4577 sctp_transport_->SetTransportChannel(tc);
4578 transport_controller_->DestroyDtlsTransport_n(
4579 old_sctp_transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4580}
4581
4582void PeerConnection::DestroySctpTransport_n() {
4583 RTC_DCHECK(network_thread()->IsCurrent());
4584 sctp_transport_.reset(nullptr);
4585 sctp_content_name_.reset();
4586 sctp_transport_name_.reset();
4587 sctp_invoker_.reset(nullptr);
4588 sctp_ready_to_send_data_ = false;
4589}
4590
4591void PeerConnection::OnSctpTransportReadyToSendData_n() {
4592 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
4593 RTC_DCHECK(network_thread()->IsCurrent());
4594 // Note: Cannot use rtc::Bind here because it will grab a reference to
4595 // PeerConnection and potentially cause PeerConnection to live longer than
4596 // expected. It is safe not to grab a reference since the sctp_invoker_ will
4597 // be destroyed before PeerConnection is destroyed, and at that point all
4598 // pending tasks will be cleared.
4599 sctp_invoker_->AsyncInvoke<void>(RTC_FROM_HERE, signaling_thread(), [this] {
4600 OnSctpTransportReadyToSendData_s(true);
4601 });
4602}
4603
4604void PeerConnection::OnSctpTransportReadyToSendData_s(bool ready) {
4605 RTC_DCHECK(signaling_thread()->IsCurrent());
4606 sctp_ready_to_send_data_ = ready;
4607 SignalSctpReadyToSendData(ready);
4608}
4609
4610void PeerConnection::OnSctpTransportDataReceived_n(
4611 const cricket::ReceiveDataParams& params,
4612 const rtc::CopyOnWriteBuffer& payload) {
4613 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
4614 RTC_DCHECK(network_thread()->IsCurrent());
4615 // Note: Cannot use rtc::Bind here because it will grab a reference to
4616 // PeerConnection and potentially cause PeerConnection to live longer than
4617 // expected. It is safe not to grab a reference since the sctp_invoker_ will
4618 // be destroyed before PeerConnection is destroyed, and at that point all
4619 // pending tasks will be cleared.
4620 sctp_invoker_->AsyncInvoke<void>(
4621 RTC_FROM_HERE, signaling_thread(), [this, params, payload] {
4622 OnSctpTransportDataReceived_s(params, payload);
4623 });
4624}
4625
4626void PeerConnection::OnSctpTransportDataReceived_s(
4627 const cricket::ReceiveDataParams& params,
4628 const rtc::CopyOnWriteBuffer& payload) {
4629 RTC_DCHECK(signaling_thread()->IsCurrent());
4630 if (params.type == cricket::DMT_CONTROL && IsOpenMessage(payload)) {
4631 // Received OPEN message; parse and signal that a new data channel should
4632 // be created.
4633 std::string label;
4634 InternalDataChannelInit config;
4635 config.id = params.ssrc;
4636 if (!ParseDataChannelOpenMessage(payload, &label, &config)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004637 RTC_LOG(LS_WARNING) << "Failed to parse the OPEN message for sid "
4638 << params.ssrc;
Steve Anton75737c02017-11-06 10:37:17 -08004639 return;
4640 }
4641 config.open_handshake_role = InternalDataChannelInit::kAcker;
4642 OnDataChannelOpenMessage(label, config);
4643 } else {
4644 // Otherwise just forward the signal.
4645 SignalSctpDataReceived(params, payload);
4646 }
4647}
4648
4649void PeerConnection::OnSctpStreamClosedRemotely_n(int sid) {
4650 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
4651 RTC_DCHECK(network_thread()->IsCurrent());
4652 sctp_invoker_->AsyncInvoke<void>(
4653 RTC_FROM_HERE, signaling_thread(),
4654 rtc::Bind(&sigslot::signal1<int>::operator(),
4655 &SignalSctpStreamClosedRemotely, sid));
4656}
4657
4658// Returns false if bundle is enabled and rtcp_mux is disabled.
4659bool PeerConnection::ValidateBundleSettings(const SessionDescription* desc) {
4660 bool bundle_enabled = desc->HasGroup(cricket::GROUP_TYPE_BUNDLE);
4661 if (!bundle_enabled)
4662 return true;
4663
4664 const cricket::ContentGroup* bundle_group =
4665 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
4666 RTC_DCHECK(bundle_group != NULL);
4667
4668 const cricket::ContentInfos& contents = desc->contents();
4669 for (cricket::ContentInfos::const_iterator citer = contents.begin();
4670 citer != contents.end(); ++citer) {
4671 const cricket::ContentInfo* content = (&*citer);
4672 RTC_DCHECK(content != NULL);
4673 if (bundle_group->HasContentName(content->name) && !content->rejected &&
4674 content->type == cricket::NS_JINGLE_RTP) {
4675 if (!HasRtcpMuxEnabled(content))
4676 return false;
4677 }
4678 }
4679 // RTCP-MUX is enabled in all the contents.
4680 return true;
4681}
4682
4683bool PeerConnection::HasRtcpMuxEnabled(const cricket::ContentInfo* content) {
4684 const cricket::MediaContentDescription* description =
4685 static_cast<cricket::MediaContentDescription*>(content->description);
4686 return description->rtcp_mux();
4687}
4688
4689bool PeerConnection::ValidateSessionDescription(
4690 const SessionDescriptionInterface* sdesc,
4691 cricket::ContentSource source,
4692 std::string* err_desc) {
4693 std::string type;
4694 if (error() != ERROR_NONE) {
4695 return BadSdp(source, type, GetSessionErrorMsg(), err_desc);
4696 }
4697
4698 if (!sdesc || !sdesc->description()) {
4699 return BadSdp(source, type, kInvalidSdp, err_desc);
4700 }
4701
4702 type = sdesc->type();
4703 Action action = GetAction(sdesc->type());
4704 if (source == cricket::CS_LOCAL) {
4705 if (!ExpectSetLocalDescription(action))
4706 return BadLocalSdp(type, BadStateErrMsg(signaling_state()), err_desc);
4707 } else {
4708 if (!ExpectSetRemoteDescription(action))
4709 return BadRemoteSdp(type, BadStateErrMsg(signaling_state()), err_desc);
4710 }
4711
4712 // Verify crypto settings.
4713 std::string crypto_error;
4714 if ((webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED ||
4715 dtls_enabled_) &&
4716 !VerifyCrypto(sdesc->description(), dtls_enabled_, &crypto_error)) {
4717 return BadSdp(source, type, crypto_error, err_desc);
4718 }
4719
4720 // Verify ice-ufrag and ice-pwd.
4721 if (!VerifyIceUfragPwdPresent(sdesc->description())) {
4722 return BadSdp(source, type, kSdpWithoutIceUfragPwd, err_desc);
4723 }
4724
4725 if (!ValidateBundleSettings(sdesc->description())) {
4726 return BadSdp(source, type, kBundleWithoutRtcpMux, err_desc);
4727 }
4728
4729 // TODO(skvlad): When the local rtcp-mux policy is Require, reject any
4730 // m-lines that do not rtcp-mux enabled.
4731
4732 // Verify m-lines in Answer when compared against Offer.
4733 if (action == kAnswer || action == kPrAnswer) {
4734 const cricket::SessionDescription* offer_desc =
4735 (source == cricket::CS_LOCAL) ? remote_description()->description()
4736 : local_description()->description();
4737 if (!MediaSectionsHaveSameCount(offer_desc, sdesc->description()) ||
4738 !MediaSectionsInSameOrder(offer_desc, sdesc->description())) {
4739 return BadAnswerSdp(source, kMlineMismatchInAnswer, err_desc);
4740 }
4741 } else {
4742 const cricket::SessionDescription* current_desc = nullptr;
4743 if (source == cricket::CS_LOCAL && local_description()) {
4744 current_desc = local_description()->description();
4745 } else if (source == cricket::CS_REMOTE && remote_description()) {
4746 current_desc = remote_description()->description();
4747 }
4748 // The re-offers should respect the order of m= sections in current
4749 // description. See RFC3264 Section 8 paragraph 4 for more details.
4750 if (current_desc &&
4751 !MediaSectionsInSameOrder(current_desc, sdesc->description())) {
4752 return BadOfferSdp(source, kMlineMismatchInSubsequentOffer, err_desc);
4753 }
4754 }
4755
4756 return true;
4757}
4758
4759bool PeerConnection::ExpectSetLocalDescription(Action action) {
4760 PeerConnectionInterface::SignalingState state = signaling_state();
4761 if (action == kOffer) {
4762 return (state == PeerConnectionInterface::kStable) ||
4763 (state == PeerConnectionInterface::kHaveLocalOffer);
4764 } else { // Answer or PrAnswer
4765 return (state == PeerConnectionInterface::kHaveRemoteOffer) ||
4766 (state == PeerConnectionInterface::kHaveLocalPrAnswer);
4767 }
4768}
4769
4770bool PeerConnection::ExpectSetRemoteDescription(Action action) {
4771 PeerConnectionInterface::SignalingState state = signaling_state();
4772 if (action == kOffer) {
4773 return (state == PeerConnectionInterface::kStable) ||
4774 (state == PeerConnectionInterface::kHaveRemoteOffer);
4775 } else { // Answer or PrAnswer.
4776 return (state == PeerConnectionInterface::kHaveLocalOffer) ||
4777 (state == PeerConnectionInterface::kHaveRemotePrAnswer);
4778 }
4779}
4780
4781std::string PeerConnection::GetSessionErrorMsg() {
4782 std::ostringstream desc;
4783 desc << kSessionError << GetErrorCodeString(error()) << ". ";
4784 desc << kSessionErrorDesc << error_desc() << ".";
4785 return desc.str();
4786}
4787
4788// We need to check the local/remote description for the Transport instead of
4789// the session, because a new Transport added during renegotiation may have
4790// them unset while the session has them set from the previous negotiation.
4791// Not doing so may trigger the auto generation of transport description and
4792// mess up DTLS identity information, ICE credential, etc.
4793bool PeerConnection::ReadyToUseRemoteCandidate(
4794 const IceCandidateInterface* candidate,
4795 const SessionDescriptionInterface* remote_desc,
4796 bool* valid) {
4797 *valid = true;
4798
4799 const SessionDescriptionInterface* current_remote_desc =
4800 remote_desc ? remote_desc : remote_description();
4801
4802 if (!current_remote_desc) {
4803 return false;
4804 }
4805
4806 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
4807 size_t remote_content_size =
4808 current_remote_desc->description()->contents().size();
4809 if (mediacontent_index >= remote_content_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004810 RTC_LOG(LS_ERROR)
4811 << "ReadyToUseRemoteCandidate: Invalid candidate media index "
4812 << mediacontent_index;
Steve Anton75737c02017-11-06 10:37:17 -08004813
4814 *valid = false;
4815 return false;
4816 }
4817
4818 cricket::ContentInfo content =
4819 current_remote_desc->description()->contents()[mediacontent_index];
4820
4821 const std::string transport_name = GetTransportName(content.name);
4822 if (transport_name.empty()) {
4823 return false;
4824 }
4825 return transport_controller_->ReadyForRemoteCandidates(transport_name);
4826}
4827
4828bool PeerConnection::SrtpRequired() const {
4829 return dtls_enabled_ ||
4830 webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED;
4831}
4832
4833void PeerConnection::OnTransportControllerGatheringState(
4834 cricket::IceGatheringState state) {
4835 RTC_DCHECK(signaling_thread()->IsCurrent());
4836 if (state == cricket::kIceGatheringGathering) {
4837 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringGathering);
4838 } else if (state == cricket::kIceGatheringComplete) {
4839 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringComplete);
4840 }
4841}
4842
4843void PeerConnection::ReportTransportStats() {
4844 // Use a set so we don't report the same stats twice if two channels share
4845 // a transport.
4846 std::set<std::string> transport_names;
4847 if (voice_channel()) {
4848 transport_names.insert(voice_channel()->transport_name());
4849 }
4850 if (video_channel()) {
4851 transport_names.insert(video_channel()->transport_name());
4852 }
4853 if (rtp_data_channel()) {
4854 transport_names.insert(rtp_data_channel()->transport_name());
4855 }
4856 if (sctp_transport_name_) {
4857 transport_names.insert(*sctp_transport_name_);
4858 }
4859 for (const auto& name : transport_names) {
4860 cricket::TransportStats stats;
4861 if (transport_controller_->GetStats(name, &stats)) {
4862 ReportBestConnectionState(stats);
4863 ReportNegotiatedCiphers(stats);
4864 }
4865 }
4866}
4867// Walk through the ConnectionInfos to gather best connection usage
4868// for IPv4 and IPv6.
4869void PeerConnection::ReportBestConnectionState(
4870 const cricket::TransportStats& stats) {
4871 RTC_DCHECK(metrics_observer());
4872 for (cricket::TransportChannelStatsList::const_iterator it =
4873 stats.channel_stats.begin();
4874 it != stats.channel_stats.end(); ++it) {
4875 for (cricket::ConnectionInfos::const_iterator it_info =
4876 it->connection_infos.begin();
4877 it_info != it->connection_infos.end(); ++it_info) {
4878 if (!it_info->best_connection) {
4879 continue;
4880 }
4881
4882 PeerConnectionEnumCounterType type = kPeerConnectionEnumCounterMax;
4883 const cricket::Candidate& local = it_info->local_candidate;
4884 const cricket::Candidate& remote = it_info->remote_candidate;
4885
4886 // Increment the counter for IceCandidatePairType.
4887 if (local.protocol() == cricket::TCP_PROTOCOL_NAME ||
4888 (local.type() == RELAY_PORT_TYPE &&
4889 local.relay_protocol() == cricket::TCP_PROTOCOL_NAME)) {
4890 type = kEnumCounterIceCandidatePairTypeTcp;
4891 } else if (local.protocol() == cricket::UDP_PROTOCOL_NAME) {
4892 type = kEnumCounterIceCandidatePairTypeUdp;
4893 } else {
4894 RTC_CHECK(0);
4895 }
4896 metrics_observer()->IncrementEnumCounter(
4897 type, GetIceCandidatePairCounter(local, remote),
4898 kIceCandidatePairMax);
4899
4900 // Increment the counter for IP type.
4901 if (local.address().family() == AF_INET) {
4902 metrics_observer()->IncrementEnumCounter(
4903 kEnumCounterAddressFamily, kBestConnections_IPv4,
4904 kPeerConnectionAddressFamilyCounter_Max);
4905
4906 } else if (local.address().family() == AF_INET6) {
4907 metrics_observer()->IncrementEnumCounter(
4908 kEnumCounterAddressFamily, kBestConnections_IPv6,
4909 kPeerConnectionAddressFamilyCounter_Max);
4910 } else {
4911 RTC_CHECK(0);
4912 }
4913
4914 return;
4915 }
4916 }
4917}
4918
4919void PeerConnection::ReportNegotiatedCiphers(
4920 const cricket::TransportStats& stats) {
4921 RTC_DCHECK(metrics_observer());
4922 if (!dtls_enabled_ || stats.channel_stats.empty()) {
4923 return;
4924 }
4925
4926 int srtp_crypto_suite = stats.channel_stats[0].srtp_crypto_suite;
4927 int ssl_cipher_suite = stats.channel_stats[0].ssl_cipher_suite;
4928 if (srtp_crypto_suite == rtc::SRTP_INVALID_CRYPTO_SUITE &&
4929 ssl_cipher_suite == rtc::TLS_NULL_WITH_NULL_NULL) {
4930 return;
4931 }
4932
4933 PeerConnectionEnumCounterType srtp_counter_type;
4934 PeerConnectionEnumCounterType ssl_counter_type;
4935 if (stats.transport_name == cricket::CN_AUDIO) {
4936 srtp_counter_type = kEnumCounterAudioSrtpCipher;
4937 ssl_counter_type = kEnumCounterAudioSslCipher;
4938 } else if (stats.transport_name == cricket::CN_VIDEO) {
4939 srtp_counter_type = kEnumCounterVideoSrtpCipher;
4940 ssl_counter_type = kEnumCounterVideoSslCipher;
4941 } else if (stats.transport_name == cricket::CN_DATA) {
4942 srtp_counter_type = kEnumCounterDataSrtpCipher;
4943 ssl_counter_type = kEnumCounterDataSslCipher;
4944 } else {
4945 RTC_NOTREACHED();
4946 return;
4947 }
4948
4949 if (srtp_crypto_suite != rtc::SRTP_INVALID_CRYPTO_SUITE) {
4950 metrics_observer()->IncrementSparseEnumCounter(srtp_counter_type,
4951 srtp_crypto_suite);
4952 }
4953 if (ssl_cipher_suite != rtc::TLS_NULL_WITH_NULL_NULL) {
4954 metrics_observer()->IncrementSparseEnumCounter(ssl_counter_type,
4955 ssl_cipher_suite);
4956 }
4957}
4958
4959void PeerConnection::OnSentPacket_w(const rtc::SentPacket& sent_packet) {
4960 RTC_DCHECK(worker_thread()->IsCurrent());
4961 RTC_DCHECK(call_);
4962 call_->OnSentPacket(sent_packet);
4963}
4964
4965const std::string PeerConnection::GetTransportName(
4966 const std::string& content_name) {
4967 cricket::BaseChannel* channel = GetChannel(content_name);
4968 if (!channel) {
4969 if (sctp_transport_) {
4970 RTC_DCHECK(sctp_content_name_);
4971 RTC_DCHECK(sctp_transport_name_);
4972 if (content_name == *sctp_content_name_) {
4973 return *sctp_transport_name_;
4974 }
4975 }
4976 // Return an empty string if failed to retrieve the transport name.
4977 return "";
4978 }
4979 return channel->transport_name();
4980}
4981
4982void PeerConnection::DestroyRtcpTransport_n(const std::string& transport_name) {
4983 RTC_DCHECK(network_thread()->IsCurrent());
4984 transport_controller_->DestroyDtlsTransport_n(
4985 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
4986}
4987
Steve Anton4171afb2017-11-20 10:20:22 -08004988// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Anton75737c02017-11-06 10:37:17 -08004989void PeerConnection::DestroyVideoChannel(cricket::VideoChannel* video_channel) {
Steve Anton4171afb2017-11-20 10:20:22 -08004990 RTC_DCHECK(video_channel);
Steve Anton75737c02017-11-06 10:37:17 -08004991 RTC_DCHECK(video_channel->rtp_dtls_transport());
Steve Anton4171afb2017-11-20 10:20:22 -08004992 RTC_DCHECK_EQ(GetVideoTransceiver()->internal()->channel(), video_channel);
4993 GetVideoTransceiver()->internal()->SetChannel(nullptr);
Steve Anton75737c02017-11-06 10:37:17 -08004994 const std::string transport_name =
4995 video_channel->rtp_dtls_transport()->transport_name();
4996 const bool need_to_delete_rtcp =
4997 (video_channel->rtcp_dtls_transport() != nullptr);
4998 // The above need to be cached before destroying the video channel so that we
4999 // do not access uninitialized memory.
5000 channel_manager()->DestroyVideoChannel(video_channel);
5001 transport_controller_->DestroyDtlsTransport(
5002 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5003 if (need_to_delete_rtcp) {
5004 transport_controller_->DestroyDtlsTransport(
5005 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
5006 }
5007}
5008
Steve Anton4171afb2017-11-20 10:20:22 -08005009// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Anton75737c02017-11-06 10:37:17 -08005010void PeerConnection::DestroyVoiceChannel(cricket::VoiceChannel* voice_channel) {
Steve Anton4171afb2017-11-20 10:20:22 -08005011 RTC_DCHECK(voice_channel);
Steve Anton75737c02017-11-06 10:37:17 -08005012 RTC_DCHECK(voice_channel->rtp_dtls_transport());
Steve Anton4171afb2017-11-20 10:20:22 -08005013 RTC_DCHECK_EQ(GetAudioTransceiver()->internal()->channel(), voice_channel);
5014 GetAudioTransceiver()->internal()->SetChannel(nullptr);
Steve Anton75737c02017-11-06 10:37:17 -08005015 const std::string transport_name =
5016 voice_channel->rtp_dtls_transport()->transport_name();
5017 const bool need_to_delete_rtcp =
5018 (voice_channel->rtcp_dtls_transport() != nullptr);
5019 // The above need to be cached before destroying the video channel so that we
5020 // do not access uninitialized memory.
5021 channel_manager()->DestroyVoiceChannel(voice_channel);
5022 transport_controller_->DestroyDtlsTransport(
5023 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5024 if (need_to_delete_rtcp) {
5025 transport_controller_->DestroyDtlsTransport(
5026 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
5027 }
5028}
5029
5030void PeerConnection::DestroyDataChannel() {
5031 OnDataChannelDestroyed();
5032 RTC_DCHECK(rtp_data_channel_->rtp_dtls_transport());
5033 std::string transport_name;
5034 transport_name = rtp_data_channel_->rtp_dtls_transport()->transport_name();
5035 bool need_to_delete_rtcp =
5036 (rtp_data_channel_->rtcp_dtls_transport() != nullptr);
5037 channel_manager()->DestroyRtpDataChannel(rtp_data_channel_);
5038 rtp_data_channel_ = nullptr;
5039 transport_controller_->DestroyDtlsTransport(
5040 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5041 if (need_to_delete_rtcp) {
5042 transport_controller_->DestroyDtlsTransport(
5043 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
5044 }
5045}
5046
henrike@webrtc.org28e20752013-07-10 00:45:36 +00005047} // namespace webrtc