blob: 4e65c311d0c5af249bf849f8434b36243c8c38b7 [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"
Steve Anton1d03a752017-11-27 14:30:09 -080034#include "pc/rtpmediautils.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020035#include "pc/rtpreceiver.h"
36#include "pc/rtpsender.h"
Steve Anton75737c02017-11-06 10:37:17 -080037#include "pc/sctputils.h"
Steve Antona3a92c22017-12-07 10:27:41 -080038#include "pc/sdputils.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020039#include "pc/streamcollection.h"
40#include "pc/videocapturertracksource.h"
41#include "pc/videotrack.h"
42#include "rtc_base/bind.h"
43#include "rtc_base/checks.h"
44#include "rtc_base/logging.h"
Karl Wiberge40468b2017-11-22 10:42:26 +010045#include "rtc_base/numerics/safe_conversions.h"
Elad Alon83ccca12017-10-04 13:18:26 +020046#include "rtc_base/ptr_util.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020047#include "rtc_base/stringencode.h"
48#include "rtc_base/stringutils.h"
49#include "rtc_base/trace_event.h"
50#include "system_wrappers/include/clock.h"
51#include "system_wrappers/include/field_trial.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000052
Steve Anton75737c02017-11-06 10:37:17 -080053using cricket::ContentInfo;
54using cricket::ContentInfos;
55using cricket::MediaContentDescription;
56using cricket::SessionDescription;
57using cricket::TransportInfo;
58
59using cricket::LOCAL_PORT_TYPE;
60using cricket::STUN_PORT_TYPE;
61using cricket::RELAY_PORT_TYPE;
62using cricket::PRFLX_PORT_TYPE;
63
Steve Antonba818672017-11-06 10:21:57 -080064namespace webrtc {
65
Steve Anton75737c02017-11-06 10:37:17 -080066// Error messages
67const char kBundleWithoutRtcpMux[] =
68 "rtcp-mux must be enabled when BUNDLE "
69 "is enabled.";
Steve Anton75737c02017-11-06 10:37:17 -080070const char kInvalidCandidates[] = "Description contains invalid candidates.";
71const char kInvalidSdp[] = "Invalid session description.";
72const char kMlineMismatchInAnswer[] =
73 "The order of m-lines in answer doesn't match order in offer. Rejecting "
74 "answer.";
75const char kMlineMismatchInSubsequentOffer[] =
76 "The order of m-lines in subsequent offer doesn't match order from "
77 "previous offer/answer.";
Steve Anton75737c02017-11-06 10:37:17 -080078const 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
deadbeef5e97fb52015-10-15 12:49:08 -0700150// If the direction is "recvonly" or "inactive", treat the description
151// as containing no streams.
152// See: https://code.google.com/p/webrtc/issues/detail?id=5054
153std::vector<cricket::StreamParams> GetActiveStreams(
154 const cricket::MediaContentDescription* desc) {
Steve Anton4e70a722017-11-28 14:57:10 -0800155 return RtpTransceiverDirectionHasSend(desc->direction())
deadbeef5e97fb52015-10-15 12:49:08 -0700156 ? desc->streams()
157 : std::vector<cricket::StreamParams>();
158}
159
deadbeefab9b2d12015-10-14 11:33:11 -0700160bool IsValidOfferToReceiveMedia(int value) {
161 typedef PeerConnectionInterface::RTCOfferAnswerOptions Options;
162 return (value >= Options::kUndefined) &&
163 (value <= Options::kMaxOfferToReceiveMedia);
164}
165
zhihuang1c378ed2017-08-17 14:10:50 -0700166// Add options to |[audio/video]_media_description_options| from |senders|.
167void AddRtpSenderOptions(
deadbeefa601f5c2016-06-06 14:27:39 -0700168 const std::vector<rtc::scoped_refptr<
169 RtpSenderProxyWithInternal<RtpSenderInternal>>>& senders,
zhihuang1c378ed2017-08-17 14:10:50 -0700170 cricket::MediaDescriptionOptions* audio_media_description_options,
171 cricket::MediaDescriptionOptions* video_media_description_options) {
olka3c747662017-08-17 06:50:32 -0700172 for (const auto& sender : senders) {
zhihuang1c378ed2017-08-17 14:10:50 -0700173 if (sender->media_type() == cricket::MEDIA_TYPE_AUDIO) {
174 if (audio_media_description_options) {
175 audio_media_description_options->AddAudioSender(
Steve Anton8ffb9c32017-08-31 15:45:38 -0700176 sender->id(), sender->internal()->stream_ids());
zhihuang1c378ed2017-08-17 14:10:50 -0700177 }
178 } else {
179 RTC_DCHECK(sender->media_type() == cricket::MEDIA_TYPE_VIDEO);
180 if (video_media_description_options) {
181 video_media_description_options->AddVideoSender(
Steve Anton8ffb9c32017-08-31 15:45:38 -0700182 sender->id(), sender->internal()->stream_ids(), 1);
zhihuang1c378ed2017-08-17 14:10:50 -0700183 }
184 }
zhihuanga77e6bb2017-08-14 18:17:48 -0700185 }
zhihuang1c378ed2017-08-17 14:10:50 -0700186}
olka3c747662017-08-17 06:50:32 -0700187
zhihuang1c378ed2017-08-17 14:10:50 -0700188// Add options to |session_options| from |rtp_data_channels|.
189void AddRtpDataChannelOptions(
190 const std::map<std::string, rtc::scoped_refptr<DataChannel>>&
191 rtp_data_channels,
192 cricket::MediaDescriptionOptions* data_media_description_options) {
193 if (!data_media_description_options) {
194 return;
195 }
deadbeefab9b2d12015-10-14 11:33:11 -0700196 // Check for data channels.
197 for (const auto& kv : rtp_data_channels) {
198 const DataChannel* channel = kv.second;
199 if (channel->state() == DataChannel::kConnecting ||
200 channel->state() == DataChannel::kOpen) {
zhihuang1c378ed2017-08-17 14:10:50 -0700201 // Legacy RTP data channels are signaled with the track/stream ID set to
202 // the data channel's label.
203 data_media_description_options->AddRtpDataChannel(channel->label(),
204 channel->label());
deadbeefab9b2d12015-10-14 11:33:11 -0700205 }
206 }
207}
208
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700209uint32_t ConvertIceTransportTypeToCandidateFilter(
210 PeerConnectionInterface::IceTransportsType type) {
211 switch (type) {
212 case PeerConnectionInterface::kNone:
213 return cricket::CF_NONE;
214 case PeerConnectionInterface::kRelay:
215 return cricket::CF_RELAY;
216 case PeerConnectionInterface::kNoHost:
217 return (cricket::CF_ALL & ~cricket::CF_HOST);
218 case PeerConnectionInterface::kAll:
219 return cricket::CF_ALL;
220 default:
nissec80e7412017-01-11 05:56:46 -0800221 RTC_NOTREACHED();
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700222 }
223 return cricket::CF_NONE;
224}
225
deadbeef293e9262017-01-11 12:28:30 -0800226// Helper to set an error and return from a method.
227bool SafeSetError(webrtc::RTCErrorType type, webrtc::RTCError* error) {
228 if (error) {
229 error->set_type(type);
230 }
231 return type == webrtc::RTCErrorType::NONE;
232}
233
Steve Anton038834f2017-07-14 15:59:59 -0700234bool SafeSetError(webrtc::RTCError error, webrtc::RTCError* error_out) {
235 if (error_out) {
236 *error_out = std::move(error);
237 }
238 return error.ok();
239}
240
Steve Antonba818672017-11-06 10:21:57 -0800241std::string GetSignalingStateString(
242 PeerConnectionInterface::SignalingState state) {
243 switch (state) {
244 case PeerConnectionInterface::kStable:
245 return "kStable";
246 case PeerConnectionInterface::kHaveLocalOffer:
247 return "kHaveLocalOffer";
248 case PeerConnectionInterface::kHaveLocalPrAnswer:
249 return "kHavePrAnswer";
250 case PeerConnectionInterface::kHaveRemoteOffer:
251 return "kHaveRemoteOffer";
252 case PeerConnectionInterface::kHaveRemotePrAnswer:
253 return "kHaveRemotePrAnswer";
254 case PeerConnectionInterface::kClosed:
255 return "kClosed";
256 }
257 RTC_NOTREACHED();
258 return "";
259}
deadbeef0a6c4ca2015-10-06 11:38:28 -0700260
Steve Anton75737c02017-11-06 10:37:17 -0800261IceCandidatePairType GetIceCandidatePairCounter(
262 const cricket::Candidate& local,
263 const cricket::Candidate& remote) {
264 const auto& l = local.type();
265 const auto& r = remote.type();
266 const auto& host = LOCAL_PORT_TYPE;
267 const auto& srflx = STUN_PORT_TYPE;
268 const auto& relay = RELAY_PORT_TYPE;
269 const auto& prflx = PRFLX_PORT_TYPE;
270 if (l == host && r == host) {
271 bool local_private = IPIsPrivate(local.address().ipaddr());
272 bool remote_private = IPIsPrivate(remote.address().ipaddr());
273 if (local_private) {
274 if (remote_private) {
275 return kIceCandidatePairHostPrivateHostPrivate;
276 } else {
277 return kIceCandidatePairHostPrivateHostPublic;
278 }
279 } else {
280 if (remote_private) {
281 return kIceCandidatePairHostPublicHostPrivate;
282 } else {
283 return kIceCandidatePairHostPublicHostPublic;
284 }
285 }
286 }
287 if (l == host && r == srflx)
288 return kIceCandidatePairHostSrflx;
289 if (l == host && r == relay)
290 return kIceCandidatePairHostRelay;
291 if (l == host && r == prflx)
292 return kIceCandidatePairHostPrflx;
293 if (l == srflx && r == host)
294 return kIceCandidatePairSrflxHost;
295 if (l == srflx && r == srflx)
296 return kIceCandidatePairSrflxSrflx;
297 if (l == srflx && r == relay)
298 return kIceCandidatePairSrflxRelay;
299 if (l == srflx && r == prflx)
300 return kIceCandidatePairSrflxPrflx;
301 if (l == relay && r == host)
302 return kIceCandidatePairRelayHost;
303 if (l == relay && r == srflx)
304 return kIceCandidatePairRelaySrflx;
305 if (l == relay && r == relay)
306 return kIceCandidatePairRelayRelay;
307 if (l == relay && r == prflx)
308 return kIceCandidatePairRelayPrflx;
309 if (l == prflx && r == host)
310 return kIceCandidatePairPrflxHost;
311 if (l == prflx && r == srflx)
312 return kIceCandidatePairPrflxSrflx;
313 if (l == prflx && r == relay)
314 return kIceCandidatePairPrflxRelay;
315 return kIceCandidatePairMax;
316}
317
318// Verify that the order of media sections in |new_desc| matches
319// |existing_desc|. The number of m= sections in |new_desc| should be no less
320// than |existing_desc|.
321bool MediaSectionsInSameOrder(const SessionDescription* existing_desc,
322 const SessionDescription* new_desc) {
323 if (!existing_desc || !new_desc) {
324 return false;
325 }
326
327 if (existing_desc->contents().size() > new_desc->contents().size()) {
328 return false;
329 }
330
331 for (size_t i = 0; i < existing_desc->contents().size(); ++i) {
332 if (new_desc->contents()[i].name != existing_desc->contents()[i].name) {
333 return false;
334 }
335 const MediaContentDescription* new_desc_mdesc =
336 static_cast<const MediaContentDescription*>(
337 new_desc->contents()[i].description);
338 const MediaContentDescription* existing_desc_mdesc =
339 static_cast<const MediaContentDescription*>(
340 existing_desc->contents()[i].description);
341 if (new_desc_mdesc->type() != existing_desc_mdesc->type()) {
342 return false;
343 }
344 }
345 return true;
346}
347
348bool MediaSectionsHaveSameCount(const SessionDescription* desc1,
349 const SessionDescription* desc2) {
350 if (!desc1 || !desc2) {
351 return false;
352 }
353 return desc1->contents().size() == desc2->contents().size();
354}
355
356// Checks that each non-rejected content has SDES crypto keys or a DTLS
357// fingerprint, unless it's in a BUNDLE group, in which case only the
358// BUNDLE-tag section (first media section/description in the BUNDLE group)
359// needs a ufrag and pwd. Mismatches, such as replying with a DTLS fingerprint
360// to SDES keys, will be caught in JsepTransport negotiation, and backstopped
361// by Channel's |srtp_required| check.
Steve Anton8a006912017-12-04 15:25:56 -0800362RTCError VerifyCrypto(const SessionDescription* desc, bool dtls_enabled) {
Steve Anton75737c02017-11-06 10:37:17 -0800363 const cricket::ContentGroup* bundle =
364 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton8a006912017-12-04 15:25:56 -0800365 for (const cricket::ContentInfo& content_info : desc->contents()) {
366 if (content_info.rejected) {
Steve Anton75737c02017-11-06 10:37:17 -0800367 continue;
368 }
Steve Anton8a006912017-12-04 15:25:56 -0800369 const std::string& mid = content_info.name;
370 if (bundle && bundle->HasContentName(mid) &&
371 mid != *(bundle->FirstContentName())) {
Steve Anton75737c02017-11-06 10:37:17 -0800372 // This isn't the first media section in the BUNDLE group, so it's not
373 // required to have crypto attributes, since only the crypto attributes
374 // from the first section actually get used.
375 continue;
376 }
377
378 // If the content isn't rejected or bundled into another m= section, crypto
379 // must be present.
380 const MediaContentDescription* media =
Steve Anton8a006912017-12-04 15:25:56 -0800381 static_cast<const MediaContentDescription*>(content_info.description);
382 const TransportInfo* tinfo = desc->GetTransportInfoByName(mid);
Steve Anton75737c02017-11-06 10:37:17 -0800383 if (!media || !tinfo) {
384 // Something is not right.
Steve Anton8a006912017-12-04 15:25:56 -0800385 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidSdp);
Steve Anton75737c02017-11-06 10:37:17 -0800386 }
387 if (dtls_enabled) {
388 if (!tinfo->description.identity_fingerprint) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100389 RTC_LOG(LS_WARNING)
390 << "Session description must have DTLS fingerprint if "
391 "DTLS enabled.";
Steve Anton8a006912017-12-04 15:25:56 -0800392 return RTCError(RTCErrorType::INVALID_PARAMETER,
393 kSdpWithoutDtlsFingerprint);
Steve Anton75737c02017-11-06 10:37:17 -0800394 }
395 } else {
396 if (media->cryptos().empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100397 RTC_LOG(LS_WARNING)
Steve Anton75737c02017-11-06 10:37:17 -0800398 << "Session description must have SDES when DTLS disabled.";
Steve Anton8a006912017-12-04 15:25:56 -0800399 return RTCError(RTCErrorType::INVALID_PARAMETER, kSdpWithoutSdesCrypto);
Steve Anton75737c02017-11-06 10:37:17 -0800400 }
401 }
402 }
Steve Anton8a006912017-12-04 15:25:56 -0800403 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -0800404}
405
406// Checks that each non-rejected content has ice-ufrag and ice-pwd set, unless
407// it's in a BUNDLE group, in which case only the BUNDLE-tag section (first
408// media section/description in the BUNDLE group) needs a ufrag and pwd.
409bool VerifyIceUfragPwdPresent(const SessionDescription* desc) {
410 const cricket::ContentGroup* bundle =
411 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton8a006912017-12-04 15:25:56 -0800412 for (const cricket::ContentInfo& content_info : desc->contents()) {
413 if (content_info.rejected) {
Steve Anton75737c02017-11-06 10:37:17 -0800414 continue;
415 }
Steve Anton8a006912017-12-04 15:25:56 -0800416 const std::string& mid = content_info.name;
417 if (bundle && bundle->HasContentName(mid) &&
418 mid != *(bundle->FirstContentName())) {
Steve Anton75737c02017-11-06 10:37:17 -0800419 // This isn't the first media section in the BUNDLE group, so it's not
420 // required to have ufrag/password, since only the ufrag/password from
421 // the first section actually get used.
422 continue;
423 }
424
425 // If the content isn't rejected or bundled into another m= section,
426 // ice-ufrag and ice-pwd must be present.
Steve Anton8a006912017-12-04 15:25:56 -0800427 const TransportInfo* tinfo = desc->GetTransportInfoByName(mid);
Steve Anton75737c02017-11-06 10:37:17 -0800428 if (!tinfo) {
429 // Something is not right.
Mirko Bonadei675513b2017-11-09 11:09:25 +0100430 RTC_LOG(LS_ERROR) << kInvalidSdp;
Steve Anton75737c02017-11-06 10:37:17 -0800431 return false;
432 }
433 if (tinfo->description.ice_ufrag.empty() ||
434 tinfo->description.ice_pwd.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100435 RTC_LOG(LS_ERROR) << "Session description must have ice ufrag and pwd.";
Steve Anton75737c02017-11-06 10:37:17 -0800436 return false;
437 }
438 }
439 return true;
440}
441
442bool GetTrackIdBySsrc(const SessionDescription* session_description,
443 uint32_t ssrc,
444 std::string* track_id) {
445 RTC_DCHECK(track_id != NULL);
446
447 const cricket::ContentInfo* audio_info =
448 cricket::GetFirstAudioContent(session_description);
449 if (audio_info) {
450 const cricket::MediaContentDescription* audio_content =
451 static_cast<const cricket::MediaContentDescription*>(
452 audio_info->description);
453
454 const auto* found =
455 cricket::GetStreamBySsrc(audio_content->streams(), ssrc);
456 if (found) {
457 *track_id = found->id;
458 return true;
459 }
460 }
461
462 const cricket::ContentInfo* video_info =
463 cricket::GetFirstVideoContent(session_description);
464 if (video_info) {
465 const cricket::MediaContentDescription* video_content =
466 static_cast<const cricket::MediaContentDescription*>(
467 video_info->description);
468
469 const auto* found =
470 cricket::GetStreamBySsrc(video_content->streams(), ssrc);
471 if (found) {
472 *track_id = found->id;
473 return true;
474 }
475 }
476 return false;
477}
478
479// Get the SCTP port out of a SessionDescription.
480// Return -1 if not found.
481int GetSctpPort(const SessionDescription* session_description) {
482 const ContentInfo* content_info = GetFirstDataContent(session_description);
483 RTC_DCHECK(content_info);
484 if (!content_info) {
485 return -1;
486 }
487 const cricket::DataContentDescription* data =
488 static_cast<const cricket::DataContentDescription*>(
489 (content_info->description));
490 std::string value;
491 cricket::DataCodec match_pattern(cricket::kGoogleSctpDataCodecPlType,
492 cricket::kGoogleSctpDataCodecName);
493 for (const cricket::DataCodec& codec : data->codecs()) {
494 if (!codec.Matches(match_pattern)) {
495 continue;
496 }
497 if (codec.GetParam(cricket::kCodecParamPort, &value)) {
498 return rtc::FromString<int>(value);
499 }
500 }
501 return -1;
502}
503
Steve Anton75737c02017-11-06 10:37:17 -0800504// Returns true if |new_desc| requests an ICE restart (i.e., new ufrag/pwd).
505bool CheckForRemoteIceRestart(const SessionDescriptionInterface* old_desc,
506 const SessionDescriptionInterface* new_desc,
507 const std::string& content_name) {
508 if (!old_desc) {
509 return false;
510 }
511 const SessionDescription* new_sd = new_desc->description();
512 const SessionDescription* old_sd = old_desc->description();
513 const ContentInfo* cinfo = new_sd->GetContentByName(content_name);
514 if (!cinfo || cinfo->rejected) {
515 return false;
516 }
517 // If the content isn't rejected, check if ufrag and password has changed.
518 const cricket::TransportDescription* new_transport_desc =
519 new_sd->GetTransportDescriptionByName(content_name);
520 const cricket::TransportDescription* old_transport_desc =
521 old_sd->GetTransportDescriptionByName(content_name);
522 if (!new_transport_desc || !old_transport_desc) {
523 // No transport description exists. This is not an ICE restart.
524 return false;
525 }
526 if (cricket::IceCredentialsChanged(
527 old_transport_desc->ice_ufrag, old_transport_desc->ice_pwd,
528 new_transport_desc->ice_ufrag, new_transport_desc->ice_pwd)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100529 RTC_LOG(LS_INFO) << "Remote peer requests ICE restart for " << content_name
530 << ".";
Steve Anton75737c02017-11-06 10:37:17 -0800531 return true;
532 }
533 return false;
534}
535
536} // namespace
537
Henrik Boström31638672017-11-23 17:48:32 +0100538// Upon completion, posts a task to execute the callback of the
539// SetSessionDescriptionObserver asynchronously on the same thread. At this
540// point, the state of the peer connection might no longer reflect the effects
541// of the SetRemoteDescription operation, as the peer connection could have been
542// modified during the post.
543// TODO(hbos): Remove this class once we remove the version of
544// PeerConnectionInterface::SetRemoteDescription() that takes a
545// SetSessionDescriptionObserver as an argument.
546class PeerConnection::SetRemoteDescriptionObserverAdapter
547 : public rtc::RefCountedObject<SetRemoteDescriptionObserverInterface> {
548 public:
549 SetRemoteDescriptionObserverAdapter(
550 rtc::scoped_refptr<PeerConnection> pc,
551 rtc::scoped_refptr<SetSessionDescriptionObserver> wrapper)
552 : pc_(std::move(pc)), wrapper_(std::move(wrapper)) {}
553
554 // SetRemoteDescriptionObserverInterface implementation.
555 void OnSetRemoteDescriptionComplete(RTCError error) override {
556 if (error.ok())
557 pc_->PostSetSessionDescriptionSuccess(wrapper_);
558 else
559 pc_->PostSetSessionDescriptionFailure(wrapper_, error.message());
560 }
561
562 private:
563 rtc::scoped_refptr<PeerConnection> pc_;
564 rtc::scoped_refptr<SetSessionDescriptionObserver> wrapper_;
565};
566
deadbeef293e9262017-01-11 12:28:30 -0800567bool PeerConnectionInterface::RTCConfiguration::operator==(
568 const PeerConnectionInterface::RTCConfiguration& o) const {
569 // This static_assert prevents us from accidentally breaking operator==.
Steve Anton300bf8e2017-07-14 10:13:10 -0700570 // Note: Order matters! Fields must be ordered the same as RTCConfiguration.
deadbeef293e9262017-01-11 12:28:30 -0800571 struct stuff_being_tested_for_equality {
Magnus Jedvert3beb2072017-07-14 14:23:56 +0000572 IceServers servers;
Steve Anton300bf8e2017-07-14 10:13:10 -0700573 IceTransportsType type;
deadbeef293e9262017-01-11 12:28:30 -0800574 BundlePolicy bundle_policy;
575 RtcpMuxPolicy rtcp_mux_policy;
Steve Anton300bf8e2017-07-14 10:13:10 -0700576 std::vector<rtc::scoped_refptr<rtc::RTCCertificate>> certificates;
577 int ice_candidate_pool_size;
578 bool disable_ipv6;
579 bool disable_ipv6_on_wifi;
deadbeefd21eab32017-07-26 16:50:11 -0700580 int max_ipv6_networks;
Steve Anton300bf8e2017-07-14 10:13:10 -0700581 bool enable_rtp_data_channel;
582 rtc::Optional<int> screencast_min_bitrate;
583 rtc::Optional<bool> combined_audio_video_bwe;
584 rtc::Optional<bool> enable_dtls_srtp;
deadbeef293e9262017-01-11 12:28:30 -0800585 TcpCandidatePolicy tcp_candidate_policy;
586 CandidateNetworkPolicy candidate_network_policy;
587 int audio_jitter_buffer_max_packets;
588 bool audio_jitter_buffer_fast_accelerate;
589 int ice_connection_receiving_timeout;
590 int ice_backup_candidate_pair_ping_interval;
591 ContinualGatheringPolicy continual_gathering_policy;
deadbeef293e9262017-01-11 12:28:30 -0800592 bool prioritize_most_likely_ice_candidate_pairs;
593 struct cricket::MediaConfig media_config;
deadbeef293e9262017-01-11 12:28:30 -0800594 bool prune_turn_ports;
595 bool presume_writable_when_fully_relayed;
596 bool enable_ice_renomination;
597 bool redetermine_role_on_ice_restart;
skvlad51072462017-02-02 11:50:14 -0800598 rtc::Optional<int> ice_check_min_interval;
Steve Anton300bf8e2017-07-14 10:13:10 -0700599 rtc::Optional<rtc::IntervalRange> ice_regather_interval_range;
Jonas Orelandbdcee282017-10-10 14:01:40 +0200600 webrtc::TurnCustomizer* turn_customizer;
Steve Anton79e79602017-11-20 10:25:56 -0800601 SdpSemantics sdp_semantics;
deadbeef293e9262017-01-11 12:28:30 -0800602 };
603 static_assert(sizeof(stuff_being_tested_for_equality) == sizeof(*this),
604 "Did you add something to RTCConfiguration and forget to "
605 "update operator==?");
606 return type == o.type && servers == o.servers &&
607 bundle_policy == o.bundle_policy &&
608 rtcp_mux_policy == o.rtcp_mux_policy &&
609 tcp_candidate_policy == o.tcp_candidate_policy &&
610 candidate_network_policy == o.candidate_network_policy &&
611 audio_jitter_buffer_max_packets == o.audio_jitter_buffer_max_packets &&
612 audio_jitter_buffer_fast_accelerate ==
613 o.audio_jitter_buffer_fast_accelerate &&
614 ice_connection_receiving_timeout ==
615 o.ice_connection_receiving_timeout &&
616 ice_backup_candidate_pair_ping_interval ==
617 o.ice_backup_candidate_pair_ping_interval &&
618 continual_gathering_policy == o.continual_gathering_policy &&
619 certificates == o.certificates &&
620 prioritize_most_likely_ice_candidate_pairs ==
621 o.prioritize_most_likely_ice_candidate_pairs &&
622 media_config == o.media_config && disable_ipv6 == o.disable_ipv6 &&
zhihuangb09b3f92017-03-07 14:40:51 -0800623 disable_ipv6_on_wifi == o.disable_ipv6_on_wifi &&
deadbeefd21eab32017-07-26 16:50:11 -0700624 max_ipv6_networks == o.max_ipv6_networks &&
deadbeef293e9262017-01-11 12:28:30 -0800625 enable_rtp_data_channel == o.enable_rtp_data_channel &&
deadbeef293e9262017-01-11 12:28:30 -0800626 screencast_min_bitrate == o.screencast_min_bitrate &&
627 combined_audio_video_bwe == o.combined_audio_video_bwe &&
628 enable_dtls_srtp == o.enable_dtls_srtp &&
629 ice_candidate_pool_size == o.ice_candidate_pool_size &&
630 prune_turn_ports == o.prune_turn_ports &&
631 presume_writable_when_fully_relayed ==
632 o.presume_writable_when_fully_relayed &&
633 enable_ice_renomination == o.enable_ice_renomination &&
skvlad51072462017-02-02 11:50:14 -0800634 redetermine_role_on_ice_restart == o.redetermine_role_on_ice_restart &&
Steve Anton300bf8e2017-07-14 10:13:10 -0700635 ice_check_min_interval == o.ice_check_min_interval &&
Jonas Orelandbdcee282017-10-10 14:01:40 +0200636 ice_regather_interval_range == o.ice_regather_interval_range &&
Steve Anton79e79602017-11-20 10:25:56 -0800637 turn_customizer == o.turn_customizer &&
638 sdp_semantics == o.sdp_semantics;
deadbeef293e9262017-01-11 12:28:30 -0800639}
640
641bool PeerConnectionInterface::RTCConfiguration::operator!=(
642 const PeerConnectionInterface::RTCConfiguration& o) const {
643 return !(*this == o);
deadbeef3edec7c2016-12-10 11:44:26 -0800644}
645
zhihuang8f65cdf2016-05-06 18:40:30 -0700646// Generate a RTCP CNAME when a PeerConnection is created.
647std::string GenerateRtcpCname() {
648 std::string cname;
649 if (!rtc::CreateRandomString(kRtcpCnameLength, &cname)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100650 RTC_LOG(LS_ERROR) << "Failed to generate CNAME.";
nisseeb4ca4e2017-01-12 02:24:27 -0800651 RTC_NOTREACHED();
zhihuang8f65cdf2016-05-06 18:40:30 -0700652 }
653 return cname;
654}
655
zhihuang1c378ed2017-08-17 14:10:50 -0700656bool ValidateOfferAnswerOptions(
657 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options) {
658 return IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_audio) &&
659 IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_video);
olka3c747662017-08-17 06:50:32 -0700660}
661
zhihuang1c378ed2017-08-17 14:10:50 -0700662// From |rtc_options|, fill parts of |session_options| shared by all generated
663// m= sections (in other words, nothing that involves a map/array).
664void ExtractSharedMediaSessionOptions(
665 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options,
666 cricket::MediaSessionOptions* session_options) {
667 session_options->vad_enabled = rtc_options.voice_activity_detection;
668 session_options->bundle_enabled = rtc_options.use_rtp_mux;
669}
zhihuanga77e6bb2017-08-14 18:17:48 -0700670
zhihuang1c378ed2017-08-17 14:10:50 -0700671bool ConvertConstraintsToOfferAnswerOptions(
672 const MediaConstraintsInterface* constraints,
673 PeerConnectionInterface::RTCOfferAnswerOptions* offer_answer_options) {
olka3c747662017-08-17 06:50:32 -0700674 if (!constraints) {
675 return true;
676 }
zhihuang1c378ed2017-08-17 14:10:50 -0700677
678 bool value = false;
679 size_t mandatory_constraints_satisfied = 0;
680
681 if (FindConstraint(constraints,
682 MediaConstraintsInterface::kOfferToReceiveAudio, &value,
683 &mandatory_constraints_satisfied)) {
684 offer_answer_options->offer_to_receive_audio =
685 value ? PeerConnectionInterface::RTCOfferAnswerOptions::
686 kOfferToReceiveMediaTrue
687 : 0;
688 }
689
690 if (FindConstraint(constraints,
691 MediaConstraintsInterface::kOfferToReceiveVideo, &value,
692 &mandatory_constraints_satisfied)) {
693 offer_answer_options->offer_to_receive_video =
694 value ? PeerConnectionInterface::RTCOfferAnswerOptions::
695 kOfferToReceiveMediaTrue
696 : 0;
697 }
698 if (FindConstraint(constraints,
699 MediaConstraintsInterface::kVoiceActivityDetection, &value,
700 &mandatory_constraints_satisfied)) {
701 offer_answer_options->voice_activity_detection = value;
702 }
703 if (FindConstraint(constraints, MediaConstraintsInterface::kUseRtpMux, &value,
704 &mandatory_constraints_satisfied)) {
705 offer_answer_options->use_rtp_mux = value;
706 }
707 if (FindConstraint(constraints, MediaConstraintsInterface::kIceRestart,
708 &value, &mandatory_constraints_satisfied)) {
709 offer_answer_options->ice_restart = value;
710 }
711
deadbeefab9b2d12015-10-14 11:33:11 -0700712 return mandatory_constraints_satisfied == constraints->GetMandatory().size();
713}
714
zhihuang38ede132017-06-15 12:52:32 -0700715PeerConnection::PeerConnection(PeerConnectionFactory* factory,
716 std::unique_ptr<RtcEventLog> event_log,
717 std::unique_ptr<Call> call)
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000718 : factory_(factory),
zhihuang38ede132017-06-15 12:52:32 -0700719 event_log_(std::move(event_log)),
zhihuang8f65cdf2016-05-06 18:40:30 -0700720 rtcp_cname_(GenerateRtcpCname()),
deadbeefab9b2d12015-10-14 11:33:11 -0700721 local_streams_(StreamCollection::Create()),
zhihuang38ede132017-06-15 12:52:32 -0700722 remote_streams_(StreamCollection::Create()),
723 call_(std::move(call)) {}
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000724
725PeerConnection::~PeerConnection() {
Peter Boström1a9d6152015-12-08 22:15:17 +0100726 TRACE_EVENT0("webrtc", "PeerConnection::~PeerConnection");
Steve Anton4171afb2017-11-20 10:20:22 -0800727 RTC_DCHECK_RUN_ON(signaling_thread());
728
729 // Need to detach RTP transceivers from PeerConnection, since it's about to be
730 // destroyed.
731 for (auto transceiver : transceivers_) {
732 transceiver->Stop();
deadbeef70ab1a12015-09-28 16:53:55 -0700733 }
Steve Anton4171afb2017-11-20 10:20:22 -0800734
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700735 // Destroy stats_ because it depends on session_.
736 stats_.reset(nullptr);
hbosb78306a2016-12-19 05:06:57 -0800737 if (stats_collector_) {
738 stats_collector_->WaitForPendingRequest();
739 stats_collector_ = nullptr;
740 }
Steve Anton75737c02017-11-06 10:37:17 -0800741
742 // Destroy video channels first since they may have a pointer to a voice
743 // channel.
Steve Anton4171afb2017-11-20 10:20:22 -0800744 for (auto transceiver : transceivers_) {
Steve Anton6fec8802017-12-04 10:37:29 -0800745 if (transceiver->internal()->media_type() == cricket::MEDIA_TYPE_VIDEO) {
746 DestroyTransceiverChannel(transceiver);
Steve Anton4171afb2017-11-20 10:20:22 -0800747 }
Steve Anton75737c02017-11-06 10:37:17 -0800748 }
Steve Anton4171afb2017-11-20 10:20:22 -0800749 for (auto transceiver : transceivers_) {
Steve Anton6fec8802017-12-04 10:37:29 -0800750 if (transceiver->internal()->media_type() == cricket::MEDIA_TYPE_AUDIO) {
751 DestroyTransceiverChannel(transceiver);
Steve Anton4171afb2017-11-20 10:20:22 -0800752 }
Steve Anton75737c02017-11-06 10:37:17 -0800753 }
Steve Anton6fec8802017-12-04 10:37:29 -0800754 DestroyDataChannel();
Steve Anton75737c02017-11-06 10:37:17 -0800755
Mirko Bonadei675513b2017-11-09 11:09:25 +0100756 RTC_LOG(LS_INFO) << "Session: " << session_id() << " is destroyed.";
Steve Anton75737c02017-11-06 10:37:17 -0800757
758 webrtc_session_desc_factory_.reset();
759 sctp_invoker_.reset();
760 sctp_factory_.reset();
761 transport_controller_.reset();
762
deadbeef91dd5672016-05-18 16:55:30 -0700763 // port_allocator_ lives on the network thread and should be destroyed there.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700764 network_thread()->Invoke<void>(RTC_FROM_HERE,
nisseeaabdf62017-05-05 02:23:02 -0700765 [this] { port_allocator_.reset(); });
eladalon248fd4f2017-09-06 05:18:15 -0700766 // call_ and event_log_ must be destroyed on the worker thread.
Steve Anton978b8762017-09-29 12:15:02 -0700767 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
eladalon248fd4f2017-09-06 05:18:15 -0700768 call_.reset();
769 event_log_.reset();
770 });
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000771}
772
773bool PeerConnection::Initialize(
buildbot@webrtc.org41451d42014-05-03 05:39:45 +0000774 const PeerConnectionInterface::RTCConfiguration& configuration,
kwibergd1fe2812016-04-27 06:47:29 -0700775 std::unique_ptr<cricket::PortAllocator> allocator,
Henrik Boströmd03c23b2016-06-01 11:44:18 +0200776 std::unique_ptr<rtc::RTCCertificateGeneratorInterface> cert_generator,
deadbeef653b8e02015-11-11 12:55:10 -0800777 PeerConnectionObserver* observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100778 TRACE_EVENT0("webrtc", "PeerConnection::Initialize");
Steve Anton038834f2017-07-14 15:59:59 -0700779
780 RTCError config_error = ValidateConfiguration(configuration);
781 if (!config_error.ok()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100782 RTC_LOG(LS_ERROR) << "Invalid configuration: " << config_error.message();
Steve Anton038834f2017-07-14 15:59:59 -0700783 return false;
784 }
785
deadbeef293e9262017-01-11 12:28:30 -0800786 if (!allocator) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100787 RTC_LOG(LS_ERROR)
788 << "PeerConnection initialized without a PortAllocator? "
789 << "This shouldn't happen if using PeerConnectionFactory.";
deadbeef293e9262017-01-11 12:28:30 -0800790 return false;
791 }
Jonas Orelandbdcee282017-10-10 14:01:40 +0200792
deadbeef653b8e02015-11-11 12:55:10 -0800793 if (!observer) {
deadbeef293e9262017-01-11 12:28:30 -0800794 // TODO(deadbeef): Why do we do this?
Mirko Bonadei675513b2017-11-09 11:09:25 +0100795 RTC_LOG(LS_ERROR) << "PeerConnection initialized without a "
796 << "PeerConnectionObserver";
deadbeef653b8e02015-11-11 12:55:10 -0800797 return false;
798 }
pthatcher@webrtc.org877ac762015-02-04 22:03:09 +0000799 observer_ = observer;
kwiberg0eb15ed2015-12-17 03:04:15 -0800800 port_allocator_ = std::move(allocator);
deadbeef653b8e02015-11-11 12:55:10 -0800801
deadbeef91dd5672016-05-18 16:55:30 -0700802 // The port allocator lives on the network thread and should be initialized
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700803 // there.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700804 if (!network_thread()->Invoke<bool>(
805 RTC_FROM_HERE, rtc::Bind(&PeerConnection::InitializePortAllocator_n,
806 this, configuration))) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000807 return false;
808 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000809
Steve Anton75737c02017-11-06 10:37:17 -0800810 // RFC 3264: The numeric value of the session id and version in the
811 // o line MUST be representable with a "64 bit signed integer".
812 // Due to this constraint session id |session_id_| is max limited to
813 // LLONG_MAX.
814 session_id_ = rtc::ToString(rtc::CreateRandomId64() & LLONG_MAX);
815 transport_controller_.reset(factory_->CreateTransportController(
816 port_allocator_.get(), configuration.redetermine_role_on_ice_restart));
817 transport_controller_->SetIceRole(cricket::ICEROLE_CONTROLLED);
818 transport_controller_->SignalConnectionState.connect(
819 this, &PeerConnection::OnTransportControllerConnectionState);
820 transport_controller_->SignalGatheringState.connect(
821 this, &PeerConnection::OnTransportControllerGatheringState);
822 transport_controller_->SignalCandidatesGathered.connect(
823 this, &PeerConnection::OnTransportControllerCandidatesGathered);
824 transport_controller_->SignalCandidatesRemoved.connect(
825 this, &PeerConnection::OnTransportControllerCandidatesRemoved);
826 transport_controller_->SignalDtlsHandshakeError.connect(
827 this, &PeerConnection::OnTransportControllerDtlsHandshakeError);
828
829 sctp_factory_ = factory_->CreateSctpTransportInternalFactory();
zhihuang29ff8442016-07-27 11:07:25 -0700830
deadbeefab9b2d12015-10-14 11:33:11 -0700831 stats_.reset(new StatsCollector(this));
hbos74e1a4f2016-09-15 23:33:01 -0700832 stats_collector_ = RTCStatsCollector::Create(this);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000833
Steve Antonba818672017-11-06 10:21:57 -0800834 configuration_ = configuration;
835
Steve Anton75737c02017-11-06 10:37:17 -0800836 const PeerConnectionFactoryInterface::Options& options = factory_->options();
837
838 transport_controller_->SetSslMaxProtocolVersion(options.ssl_max_version);
839
840 // Obtain a certificate from RTCConfiguration if any were provided (optional).
841 rtc::scoped_refptr<rtc::RTCCertificate> certificate;
842 if (!configuration.certificates.empty()) {
843 // TODO(hbos,torbjorng): Decide on certificate-selection strategy instead of
844 // just picking the first one. The decision should be made based on the DTLS
845 // handshake. The DTLS negotiations need to know about all certificates.
846 certificate = configuration.certificates[0];
847 }
848
Steve Antond25da372017-11-06 14:50:29 -0800849 transport_controller_->SetIceConfig(ParseIceConfig(configuration));
Steve Anton75737c02017-11-06 10:37:17 -0800850
851 if (options.disable_encryption) {
852 dtls_enabled_ = false;
853 } else {
854 // Enable DTLS by default if we have an identity store or a certificate.
855 dtls_enabled_ = (cert_generator || certificate);
856 // |configuration| can override the default |dtls_enabled_| value.
857 if (configuration.enable_dtls_srtp) {
858 dtls_enabled_ = *(configuration.enable_dtls_srtp);
859 }
860 }
861
862 // Enable creation of RTP data channels if the kEnableRtpDataChannels is set.
863 // It takes precendence over the disable_sctp_data_channels
864 // PeerConnectionFactoryInterface::Options.
865 if (configuration.enable_rtp_data_channel) {
866 data_channel_type_ = cricket::DCT_RTP;
867 } else {
868 // DTLS has to be enabled to use SCTP.
869 if (!options.disable_sctp_data_channels && dtls_enabled_) {
870 data_channel_type_ = cricket::DCT_SCTP;
871 }
872 }
873
874 video_options_.screencast_min_bitrate_kbps =
875 configuration.screencast_min_bitrate;
876 audio_options_.combined_audio_video_bwe =
877 configuration.combined_audio_video_bwe;
878
879 audio_options_.audio_jitter_buffer_max_packets =
Oskar Sundbom9b28a032017-11-16 10:53:30 +0100880 configuration.audio_jitter_buffer_max_packets;
Steve Anton75737c02017-11-06 10:37:17 -0800881
882 audio_options_.audio_jitter_buffer_fast_accelerate =
Oskar Sundbom9b28a032017-11-16 10:53:30 +0100883 configuration.audio_jitter_buffer_fast_accelerate;
Steve Anton75737c02017-11-06 10:37:17 -0800884
885 // Whether the certificate generator/certificate is null or not determines
886 // what PeerConnectionDescriptionFactory will do, so make sure that we give it
887 // the right instructions by clearing the variables if needed.
888 if (!dtls_enabled_) {
889 cert_generator.reset();
890 certificate = nullptr;
891 } else if (certificate) {
892 // Favor generated certificate over the certificate generator.
893 cert_generator.reset();
894 }
895
896 webrtc_session_desc_factory_.reset(new WebRtcSessionDescriptionFactory(
897 signaling_thread(), channel_manager(), this, session_id(),
898 std::move(cert_generator), certificate));
899 webrtc_session_desc_factory_->SignalCertificateReady.connect(
900 this, &PeerConnection::OnCertificateReady);
901
902 if (options.disable_encryption) {
903 webrtc_session_desc_factory_->SetSdesPolicy(cricket::SEC_DISABLED);
904 }
905
906 webrtc_session_desc_factory_->set_enable_encrypted_rtp_header_extensions(
907 options.crypto_options.enable_encrypted_rtp_header_extensions);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000908
Steve Anton4171afb2017-11-20 10:20:22 -0800909 // Add default audio/video transceivers for Plan B SDP.
910 if (!IsUnifiedPlan()) {
911 transceivers_.push_back(
912 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
913 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_AUDIO)));
914 transceivers_.push_back(
915 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
916 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_VIDEO)));
917 }
918
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000919 return true;
920}
921
Steve Anton038834f2017-07-14 15:59:59 -0700922RTCError PeerConnection::ValidateConfiguration(
923 const RTCConfiguration& config) const {
924 if (config.ice_regather_interval_range &&
925 config.continual_gathering_policy == GATHER_ONCE) {
926 return RTCError(RTCErrorType::INVALID_PARAMETER,
927 "ice_regather_interval_range specified but continual "
928 "gathering policy is GATHER_ONCE");
929 }
930 return RTCError::OK();
931}
932
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000933rtc::scoped_refptr<StreamCollectionInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000934PeerConnection::local_streams() {
deadbeefab9b2d12015-10-14 11:33:11 -0700935 return local_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000936}
937
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000938rtc::scoped_refptr<StreamCollectionInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000939PeerConnection::remote_streams() {
deadbeefab9b2d12015-10-14 11:33:11 -0700940 return remote_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000941}
942
perkj@webrtc.orgc2dd5ee2014-11-04 11:31:29 +0000943bool PeerConnection::AddStream(MediaStreamInterface* local_stream) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100944 TRACE_EVENT0("webrtc", "PeerConnection::AddStream");
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000945 if (IsClosed()) {
946 return false;
947 }
deadbeefab9b2d12015-10-14 11:33:11 -0700948 if (!CanAddLocalMediaStream(local_streams_, local_stream)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000949 return false;
950 }
deadbeefab9b2d12015-10-14 11:33:11 -0700951
952 local_streams_->AddStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -0800953 MediaStreamObserver* observer = new MediaStreamObserver(local_stream);
954 observer->SignalAudioTrackAdded.connect(this,
955 &PeerConnection::OnAudioTrackAdded);
956 observer->SignalAudioTrackRemoved.connect(
957 this, &PeerConnection::OnAudioTrackRemoved);
958 observer->SignalVideoTrackAdded.connect(this,
959 &PeerConnection::OnVideoTrackAdded);
960 observer->SignalVideoTrackRemoved.connect(
961 this, &PeerConnection::OnVideoTrackRemoved);
kwibergd1fe2812016-04-27 06:47:29 -0700962 stream_observers_.push_back(std::unique_ptr<MediaStreamObserver>(observer));
deadbeefab9b2d12015-10-14 11:33:11 -0700963
deadbeefab9b2d12015-10-14 11:33:11 -0700964 for (const auto& track : local_stream->GetAudioTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -0700965 AddAudioTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -0700966 }
967 for (const auto& track : local_stream->GetVideoTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -0700968 AddVideoTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -0700969 }
970
tommi@webrtc.org03505bc2014-07-14 20:15:26 +0000971 stats_->AddStream(local_stream);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000972 observer_->OnRenegotiationNeeded();
973 return true;
974}
975
976void PeerConnection::RemoveStream(MediaStreamInterface* local_stream) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100977 TRACE_EVENT0("webrtc", "PeerConnection::RemoveStream");
korniltsev.anatolyec390b52017-07-24 17:00:25 -0700978 if (!IsClosed()) {
979 for (const auto& track : local_stream->GetAudioTracks()) {
980 RemoveAudioTrack(track.get(), local_stream);
981 }
982 for (const auto& track : local_stream->GetVideoTracks()) {
983 RemoveVideoTrack(track.get(), local_stream);
984 }
deadbeefab9b2d12015-10-14 11:33:11 -0700985 }
deadbeefab9b2d12015-10-14 11:33:11 -0700986 local_streams_->RemoveStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -0800987 stream_observers_.erase(
988 std::remove_if(
989 stream_observers_.begin(), stream_observers_.end(),
kwibergd1fe2812016-04-27 06:47:29 -0700990 [local_stream](const std::unique_ptr<MediaStreamObserver>& observer) {
deadbeefeb459812015-12-15 19:24:43 -0800991 return observer->stream()->label().compare(local_stream->label()) ==
992 0;
993 }),
994 stream_observers_.end());
deadbeefab9b2d12015-10-14 11:33:11 -0700995
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000996 if (IsClosed()) {
997 return;
998 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000999 observer_->OnRenegotiationNeeded();
1000}
1001
deadbeefe1f9d832016-01-14 15:35:42 -08001002rtc::scoped_refptr<RtpSenderInterface> PeerConnection::AddTrack(
1003 MediaStreamTrackInterface* track,
1004 std::vector<MediaStreamInterface*> streams) {
1005 TRACE_EVENT0("webrtc", "PeerConnection::AddTrack");
1006 if (IsClosed()) {
1007 return nullptr;
1008 }
1009 if (streams.size() >= 2) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001010 RTC_LOG(LS_ERROR)
deadbeefe1f9d832016-01-14 15:35:42 -08001011 << "Adding a track with two streams is not currently supported.";
1012 return nullptr;
1013 }
Steve Anton4171afb2017-11-20 10:20:22 -08001014 if (FindSenderForTrack(track)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001015 RTC_LOG(LS_ERROR) << "Sender for track " << track->id()
1016 << " already exists.";
deadbeefe1f9d832016-01-14 15:35:42 -08001017 return nullptr;
1018 }
1019
1020 // TODO(deadbeef): Support adding a track to multiple streams.
deadbeefa601f5c2016-06-06 14:27:39 -07001021 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender;
deadbeefe1f9d832016-01-14 15:35:42 -08001022 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
deadbeefa601f5c2016-06-06 14:27:39 -07001023 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
deadbeefe1f9d832016-01-14 15:35:42 -08001024 signaling_thread(),
1025 new AudioRtpSender(static_cast<AudioTrackInterface*>(track),
Steve Anton75737c02017-11-06 10:37:17 -08001026 voice_channel(), stats_.get()));
Steve Anton4171afb2017-11-20 10:20:22 -08001027 GetAudioTransceiver()->internal()->AddSender(new_sender);
deadbeefe1f9d832016-01-14 15:35:42 -08001028 if (!streams.empty()) {
deadbeefa601f5c2016-06-06 14:27:39 -07001029 new_sender->internal()->set_stream_id(streams[0]->label());
deadbeefe1f9d832016-01-14 15:35:42 -08001030 }
Steve Anton4171afb2017-11-20 10:20:22 -08001031 const RtpSenderInfo* sender_info =
1032 FindSenderInfo(local_audio_sender_infos_,
1033 new_sender->internal()->stream_id(), track->id());
1034 if (sender_info) {
1035 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -08001036 }
1037 } else if (track->kind() == MediaStreamTrackInterface::kVideoKind) {
deadbeefa601f5c2016-06-06 14:27:39 -07001038 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
deadbeefe1f9d832016-01-14 15:35:42 -08001039 signaling_thread(),
1040 new VideoRtpSender(static_cast<VideoTrackInterface*>(track),
Steve Anton75737c02017-11-06 10:37:17 -08001041 video_channel()));
Steve Anton4171afb2017-11-20 10:20:22 -08001042 GetVideoTransceiver()->internal()->AddSender(new_sender);
deadbeefe1f9d832016-01-14 15:35:42 -08001043 if (!streams.empty()) {
deadbeefa601f5c2016-06-06 14:27:39 -07001044 new_sender->internal()->set_stream_id(streams[0]->label());
deadbeefe1f9d832016-01-14 15:35:42 -08001045 }
Steve Anton4171afb2017-11-20 10:20:22 -08001046 const RtpSenderInfo* sender_info =
1047 FindSenderInfo(local_video_sender_infos_,
1048 new_sender->internal()->stream_id(), track->id());
1049 if (sender_info) {
1050 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -08001051 }
1052 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001053 RTC_LOG(LS_ERROR) << "CreateSender called with invalid kind: "
1054 << track->kind();
deadbeefe1f9d832016-01-14 15:35:42 -08001055 return rtc::scoped_refptr<RtpSenderInterface>();
1056 }
1057
deadbeefe1f9d832016-01-14 15:35:42 -08001058 observer_->OnRenegotiationNeeded();
1059 return new_sender;
1060}
1061
1062bool PeerConnection::RemoveTrack(RtpSenderInterface* sender) {
1063 TRACE_EVENT0("webrtc", "PeerConnection::RemoveTrack");
1064 if (IsClosed()) {
1065 return false;
1066 }
1067
Steve Anton4171afb2017-11-20 10:20:22 -08001068 bool removed;
1069 if (sender->media_type() == cricket::MEDIA_TYPE_AUDIO) {
1070 removed = GetAudioTransceiver()->internal()->RemoveSender(sender);
1071 } else {
1072 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, sender->media_type());
1073 removed = GetVideoTransceiver()->internal()->RemoveSender(sender);
1074 }
1075 if (!removed) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001076 RTC_LOG(LS_ERROR) << "Couldn't find sender " << sender->id()
1077 << " to remove.";
deadbeefe1f9d832016-01-14 15:35:42 -08001078 return false;
1079 }
deadbeefe1f9d832016-01-14 15:35:42 -08001080
1081 observer_->OnRenegotiationNeeded();
1082 return true;
1083}
1084
Steve Anton9158ef62017-11-27 13:01:52 -08001085RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1086PeerConnection::AddTransceiver(
1087 rtc::scoped_refptr<MediaStreamTrackInterface> track) {
1088 return AddTransceiver(track, RtpTransceiverInit());
1089}
1090
1091RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1092PeerConnection::AddTransceiver(
1093 rtc::scoped_refptr<MediaStreamTrackInterface> track,
1094 const RtpTransceiverInit& init) {
1095 if (!IsUnifiedPlan()) {
1096 LOG_AND_RETURN_ERROR(
1097 RTCErrorType::INTERNAL_ERROR,
1098 "AddTransceiver only supported when Unified Plan is enabled.");
1099 }
1100 if (!track) {
1101 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "track is null");
1102 }
1103 cricket::MediaType media_type;
1104 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
1105 media_type = cricket::MEDIA_TYPE_AUDIO;
1106 } else if (track->kind() == MediaStreamTrackInterface::kVideoKind) {
1107 media_type = cricket::MEDIA_TYPE_VIDEO;
1108 } else {
1109 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1110 "Track kind is not audio or video");
1111 }
1112 return AddTransceiver(media_type, track, init);
1113}
1114
1115RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1116PeerConnection::AddTransceiver(cricket::MediaType media_type) {
1117 return AddTransceiver(media_type, RtpTransceiverInit());
1118}
1119
1120RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1121PeerConnection::AddTransceiver(cricket::MediaType media_type,
1122 const RtpTransceiverInit& init) {
1123 if (!IsUnifiedPlan()) {
1124 LOG_AND_RETURN_ERROR(
1125 RTCErrorType::INTERNAL_ERROR,
1126 "AddTransceiver only supported when Unified Plan is enabled.");
1127 }
1128 if (!(media_type == cricket::MEDIA_TYPE_AUDIO ||
1129 media_type == cricket::MEDIA_TYPE_VIDEO)) {
1130 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1131 "media type is not audio or video");
1132 }
1133 return AddTransceiver(media_type, nullptr, init);
1134}
1135
1136RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1137PeerConnection::AddTransceiver(
1138 cricket::MediaType media_type,
1139 rtc::scoped_refptr<MediaStreamTrackInterface> track,
1140 const RtpTransceiverInit& init) {
1141 RTC_DCHECK((media_type == cricket::MEDIA_TYPE_AUDIO ||
1142 media_type == cricket::MEDIA_TYPE_VIDEO));
1143 if (track) {
1144 RTC_DCHECK_EQ(media_type,
1145 (track->kind() == MediaStreamTrackInterface::kAudioKind
1146 ? cricket::MEDIA_TYPE_AUDIO
1147 : cricket::MEDIA_TYPE_VIDEO));
1148 }
1149
1150 // TODO(bugs.webrtc.org/7600): Verify init.
1151
1152 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> sender;
1153 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1154 receiver;
1155 std::string receiver_id = rtc::CreateRandomUuid();
1156 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
1157 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
1158 signaling_thread(), new AudioRtpSender(nullptr, stats_.get()));
1159 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
1160 signaling_thread(), new AudioRtpReceiver(receiver_id, {}, 0, nullptr));
1161 } else {
1162 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, media_type);
1163 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
1164 signaling_thread(), new VideoRtpSender(nullptr));
1165 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
1166 signaling_thread(),
1167 new VideoRtpReceiver(receiver_id, {}, worker_thread(), 0, nullptr));
1168 }
1169 // TODO(bugs.webrtc.org/7600): Initializing the sender/receiver with a null
1170 // channel prevents users from calling SetParameters on them, which is needed
1171 // to be in compliance with the spec.
1172
1173 if (track) {
1174 sender->SetTrack(track);
1175 }
1176
1177 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1178 transceiver = RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1179 signaling_thread(), new RtpTransceiver(sender, receiver));
1180 transceiver->SetDirection(init.direction);
1181
1182 transceivers_.push_back(transceiver);
1183
1184 observer_->OnRenegotiationNeeded();
1185
1186 return rtc::scoped_refptr<RtpTransceiverInterface>(transceiver);
1187}
1188
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001189rtc::scoped_refptr<DtmfSenderInterface> PeerConnection::CreateDtmfSender(
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001190 AudioTrackInterface* track) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001191 TRACE_EVENT0("webrtc", "PeerConnection::CreateDtmfSender");
zhihuang29ff8442016-07-27 11:07:25 -07001192 if (IsClosed()) {
1193 return nullptr;
1194 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001195 if (!track) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001196 RTC_LOG(LS_ERROR) << "CreateDtmfSender - track is NULL.";
deadbeef20cb0c12017-02-01 20:27:00 -08001197 return nullptr;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001198 }
Steve Anton4171afb2017-11-20 10:20:22 -08001199 auto track_sender = FindSenderForTrack(track);
1200 if (!track_sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001201 RTC_LOG(LS_ERROR) << "CreateDtmfSender called with a non-added track.";
deadbeef20cb0c12017-02-01 20:27:00 -08001202 return nullptr;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001203 }
1204
Steve Anton4171afb2017-11-20 10:20:22 -08001205 return track_sender->GetDtmfSender();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001206}
1207
deadbeeffac06552015-11-25 11:26:01 -08001208rtc::scoped_refptr<RtpSenderInterface> PeerConnection::CreateSender(
deadbeefbd7d8f72015-12-18 16:58:44 -08001209 const std::string& kind,
1210 const std::string& stream_id) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001211 TRACE_EVENT0("webrtc", "PeerConnection::CreateSender");
zhihuang29ff8442016-07-27 11:07:25 -07001212 if (IsClosed()) {
1213 return nullptr;
1214 }
Steve Anton4171afb2017-11-20 10:20:22 -08001215
1216 // TODO(steveanton): Move construction of the RtpSenders to RtpTransceiver.
deadbeefa601f5c2016-06-06 14:27:39 -07001217 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender;
deadbeeffac06552015-11-25 11:26:01 -08001218 if (kind == MediaStreamTrackInterface::kAudioKind) {
deadbeefa601f5c2016-06-06 14:27:39 -07001219 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton75737c02017-11-06 10:37:17 -08001220 signaling_thread(), new AudioRtpSender(voice_channel(), stats_.get()));
Steve Anton4171afb2017-11-20 10:20:22 -08001221 GetAudioTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 11:26:01 -08001222 } else if (kind == MediaStreamTrackInterface::kVideoKind) {
deadbeefa601f5c2016-06-06 14:27:39 -07001223 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton75737c02017-11-06 10:37:17 -08001224 signaling_thread(), new VideoRtpSender(video_channel()));
Steve Anton4171afb2017-11-20 10:20:22 -08001225 GetVideoTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 11:26:01 -08001226 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001227 RTC_LOG(LS_ERROR) << "CreateSender called with invalid kind: " << kind;
Steve Anton4171afb2017-11-20 10:20:22 -08001228 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08001229 }
Steve Anton4171afb2017-11-20 10:20:22 -08001230
deadbeefbd7d8f72015-12-18 16:58:44 -08001231 if (!stream_id.empty()) {
deadbeefa601f5c2016-06-06 14:27:39 -07001232 new_sender->internal()->set_stream_id(stream_id);
deadbeefbd7d8f72015-12-18 16:58:44 -08001233 }
Steve Anton4171afb2017-11-20 10:20:22 -08001234
deadbeefe1f9d832016-01-14 15:35:42 -08001235 return new_sender;
deadbeeffac06552015-11-25 11:26:01 -08001236}
1237
deadbeef70ab1a12015-09-28 16:53:55 -07001238std::vector<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::GetSenders()
1239 const {
deadbeefa601f5c2016-06-06 14:27:39 -07001240 std::vector<rtc::scoped_refptr<RtpSenderInterface>> ret;
Steve Anton4171afb2017-11-20 10:20:22 -08001241 for (auto sender : GetSendersInternal()) {
1242 ret.push_back(sender);
deadbeefa601f5c2016-06-06 14:27:39 -07001243 }
1244 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -07001245}
1246
Steve Anton4171afb2017-11-20 10:20:22 -08001247std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1248PeerConnection::GetSendersInternal() const {
1249 std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1250 all_senders;
1251 for (auto transceiver : transceivers_) {
1252 auto senders = transceiver->internal()->senders();
1253 all_senders.insert(all_senders.end(), senders.begin(), senders.end());
1254 }
1255 return all_senders;
1256}
1257
deadbeef70ab1a12015-09-28 16:53:55 -07001258std::vector<rtc::scoped_refptr<RtpReceiverInterface>>
1259PeerConnection::GetReceivers() const {
deadbeefa601f5c2016-06-06 14:27:39 -07001260 std::vector<rtc::scoped_refptr<RtpReceiverInterface>> ret;
Steve Anton4171afb2017-11-20 10:20:22 -08001261 for (const auto& receiver : GetReceiversInternal()) {
1262 ret.push_back(receiver);
deadbeefa601f5c2016-06-06 14:27:39 -07001263 }
1264 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -07001265}
1266
Steve Anton4171afb2017-11-20 10:20:22 -08001267std::vector<
1268 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1269PeerConnection::GetReceiversInternal() const {
1270 std::vector<
1271 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1272 all_receivers;
1273 for (auto transceiver : transceivers_) {
1274 auto receivers = transceiver->internal()->receivers();
1275 all_receivers.insert(all_receivers.end(), receivers.begin(),
1276 receivers.end());
1277 }
1278 return all_receivers;
1279}
1280
Steve Anton9158ef62017-11-27 13:01:52 -08001281std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
1282PeerConnection::GetTransceivers() const {
1283 RTC_DCHECK(IsUnifiedPlan());
1284 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> all_transceivers;
1285 for (auto transceiver : transceivers_) {
1286 all_transceivers.push_back(transceiver);
1287 }
1288 return all_transceivers;
1289}
1290
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001291bool PeerConnection::GetStats(StatsObserver* observer,
wu@webrtc.orgb9a088b2014-02-13 23:18:49 +00001292 MediaStreamTrackInterface* track,
1293 StatsOutputLevel level) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001294 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
deadbeef0a6c4ca2015-10-06 11:38:28 -07001295 RTC_DCHECK(signaling_thread()->IsCurrent());
nisse7ce109a2017-01-31 00:57:56 -08001296 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001297 RTC_LOG(LS_ERROR) << "GetStats - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001298 return false;
1299 }
1300
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001301 stats_->UpdateStats(level);
zhihuange9e94c32016-11-04 11:38:15 -07001302 // The StatsCollector is used to tell if a track is valid because it may
1303 // remember tracks that the PeerConnection previously removed.
1304 if (track && !stats_->IsValidTrack(track->id())) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001305 RTC_LOG(LS_WARNING) << "GetStats is called with an invalid track: "
1306 << track->id();
zhihuange9e94c32016-11-04 11:38:15 -07001307 return false;
1308 }
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001309 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_GETSTATS,
tommi@webrtc.org5b06b062014-08-15 08:38:30 +00001310 new GetStatsMsg(observer, track));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001311 return true;
1312}
1313
hbos74e1a4f2016-09-15 23:33:01 -07001314void PeerConnection::GetStats(RTCStatsCollectorCallback* callback) {
1315 RTC_DCHECK(stats_collector_);
1316 stats_collector_->GetStatsReport(callback);
1317}
1318
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001319PeerConnectionInterface::SignalingState PeerConnection::signaling_state() {
1320 return signaling_state_;
1321}
1322
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001323PeerConnectionInterface::IceConnectionState
1324PeerConnection::ice_connection_state() {
1325 return ice_connection_state_;
1326}
1327
1328PeerConnectionInterface::IceGatheringState
1329PeerConnection::ice_gathering_state() {
1330 return ice_gathering_state_;
1331}
1332
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001333rtc::scoped_refptr<DataChannelInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001334PeerConnection::CreateDataChannel(
1335 const std::string& label,
1336 const DataChannelInit* config) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001337 TRACE_EVENT0("webrtc", "PeerConnection::CreateDataChannel");
zhihuang9763d562016-08-05 11:14:50 -07001338
deadbeefab9b2d12015-10-14 11:33:11 -07001339 bool first_datachannel = !HasDataChannels();
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001340
kwibergd1fe2812016-04-27 06:47:29 -07001341 std::unique_ptr<InternalDataChannelInit> internal_config;
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00001342 if (config) {
1343 internal_config.reset(new InternalDataChannelInit(*config));
1344 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001345 rtc::scoped_refptr<DataChannelInterface> channel(
deadbeefab9b2d12015-10-14 11:33:11 -07001346 InternalCreateDataChannel(label, internal_config.get()));
1347 if (!channel.get()) {
1348 return nullptr;
1349 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001350
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001351 // Trigger the onRenegotiationNeeded event for every new RTP DataChannel, or
1352 // the first SCTP DataChannel.
Steve Anton75737c02017-11-06 10:37:17 -08001353 if (data_channel_type() == cricket::DCT_RTP || first_datachannel) {
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001354 observer_->OnRenegotiationNeeded();
1355 }
wu@webrtc.org91053e72013-08-10 07:18:04 +00001356
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001357 return DataChannelProxy::Create(signaling_thread(), channel.get());
1358}
1359
1360void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
1361 const MediaConstraintsInterface* constraints) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001362 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
Steve Anton8d3444d2017-10-20 15:30:51 -07001363
zhihuang1c378ed2017-08-17 14:10:50 -07001364 PeerConnectionInterface::RTCOfferAnswerOptions offer_answer_options;
1365 // Always create an offer even if |ConvertConstraintsToOfferAnswerOptions|
1366 // returns false for now. Because |ConvertConstraintsToOfferAnswerOptions|
1367 // compares the mandatory fields parsed with the mandatory fields added in the
1368 // |constraints| and some downstream applications might create offers with
1369 // mandatory fields which would not be parsed in the helper method. For
1370 // example, in Chromium/remoting, |kEnableDtlsSrtp| is added to the
1371 // |constraints| as a mandatory field but it is not parsed.
1372 ConvertConstraintsToOfferAnswerOptions(constraints, &offer_answer_options);
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001373
zhihuang1c378ed2017-08-17 14:10:50 -07001374 CreateOffer(observer, offer_answer_options);
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001375}
1376
1377void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
1378 const RTCOfferAnswerOptions& options) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001379 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
Steve Anton8d3444d2017-10-20 15:30:51 -07001380
nisse7ce109a2017-01-31 00:57:56 -08001381 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001382 RTC_LOG(LS_ERROR) << "CreateOffer - observer is NULL.";
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001383 return;
1384 }
deadbeefab9b2d12015-10-14 11:33:11 -07001385
Steve Anton8d3444d2017-10-20 15:30:51 -07001386 if (IsClosed()) {
1387 std::string error = "CreateOffer called when PeerConnection is closed.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001388 RTC_LOG(LS_ERROR) << error;
Steve Anton8d3444d2017-10-20 15:30:51 -07001389 PostCreateSessionDescriptionFailure(observer, error);
1390 return;
1391 }
1392
zhihuang1c378ed2017-08-17 14:10:50 -07001393 if (!ValidateOfferAnswerOptions(options)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001394 std::string error = "CreateOffer called with invalid options.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001395 RTC_LOG(LS_ERROR) << error;
deadbeefab9b2d12015-10-14 11:33:11 -07001396 PostCreateSessionDescriptionFailure(observer, error);
1397 return;
1398 }
1399
zhihuang1c378ed2017-08-17 14:10:50 -07001400 cricket::MediaSessionOptions session_options;
1401 GetOptionsForOffer(options, &session_options);
Steve Antond25da372017-11-06 14:50:29 -08001402 webrtc_session_desc_factory_->CreateOffer(observer, options, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001403}
1404
1405void PeerConnection::CreateAnswer(
1406 CreateSessionDescriptionObserver* observer,
1407 const MediaConstraintsInterface* constraints) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001408 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
Steve Anton8d3444d2017-10-20 15:30:51 -07001409
nisse7ce109a2017-01-31 00:57:56 -08001410 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001411 RTC_LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001412 return;
1413 }
deadbeefab9b2d12015-10-14 11:33:11 -07001414
zhihuang1c378ed2017-08-17 14:10:50 -07001415 PeerConnectionInterface::RTCOfferAnswerOptions offer_answer_options;
1416 if (!ConvertConstraintsToOfferAnswerOptions(constraints,
1417 &offer_answer_options)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001418 std::string error = "CreateAnswer called with invalid constraints.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001419 RTC_LOG(LS_ERROR) << error;
deadbeefab9b2d12015-10-14 11:33:11 -07001420 PostCreateSessionDescriptionFailure(observer, error);
1421 return;
1422 }
1423
Steve Anton8d3444d2017-10-20 15:30:51 -07001424 CreateAnswer(observer, offer_answer_options);
htaa2a49d92016-03-04 02:51:39 -08001425}
1426
1427void PeerConnection::CreateAnswer(CreateSessionDescriptionObserver* observer,
1428 const RTCOfferAnswerOptions& options) {
1429 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
nisse7ce109a2017-01-31 00:57:56 -08001430 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001431 RTC_LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
htaa2a49d92016-03-04 02:51:39 -08001432 return;
1433 }
1434
Steve Anton8d3444d2017-10-20 15:30:51 -07001435 if (IsClosed()) {
1436 std::string error = "CreateAnswer called when PeerConnection is closed.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001437 RTC_LOG(LS_ERROR) << error;
Steve Anton8d3444d2017-10-20 15:30:51 -07001438 PostCreateSessionDescriptionFailure(observer, error);
1439 return;
1440 }
1441
Steve Anton75737c02017-11-06 10:37:17 -08001442 if (remote_description() &&
Steve Antona3a92c22017-12-07 10:27:41 -08001443 remote_description()->GetType() != SdpType::kOffer) {
Steve Anton8d3444d2017-10-20 15:30:51 -07001444 std::string error = "CreateAnswer called without remote offer.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001445 RTC_LOG(LS_ERROR) << error;
Steve Anton8d3444d2017-10-20 15:30:51 -07001446 PostCreateSessionDescriptionFailure(observer, error);
1447 return;
1448 }
1449
htaa2a49d92016-03-04 02:51:39 -08001450 cricket::MediaSessionOptions session_options;
zhihuang1c378ed2017-08-17 14:10:50 -07001451 GetOptionsForAnswer(options, &session_options);
htaa2a49d92016-03-04 02:51:39 -08001452
Steve Antond25da372017-11-06 14:50:29 -08001453 webrtc_session_desc_factory_->CreateAnswer(observer, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001454}
1455
1456void PeerConnection::SetLocalDescription(
1457 SetSessionDescriptionObserver* observer,
1458 SessionDescriptionInterface* desc) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001459 TRACE_EVENT0("webrtc", "PeerConnection::SetLocalDescription");
Steve Anton8a006912017-12-04 15:25:56 -08001460
nisse7ce109a2017-01-31 00:57:56 -08001461 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001462 RTC_LOG(LS_ERROR) << "SetLocalDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001463 return;
1464 }
Steve Anton8a006912017-12-04 15:25:56 -08001465
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001466 if (!desc) {
1467 PostSetSessionDescriptionFailure(observer, "SessionDescription is NULL.");
1468 return;
1469 }
Steve Anton8d3444d2017-10-20 15:30:51 -07001470
Steve Antona3a92c22017-12-07 10:27:41 -08001471 SdpType type = desc->GetType();
Steve Anton8d3444d2017-10-20 15:30:51 -07001472
Steve Anton8a006912017-12-04 15:25:56 -08001473 RTCError error = ApplyLocalDescription(rtc::WrapUnique(desc));
1474 // |desc| may be destroyed at this point.
1475
1476 if (!error.ok()) {
Steve Antona3a92c22017-12-07 10:27:41 -08001477 std::ostringstream oss;
1478 oss << "Failed to set local " << SdpTypeToString(type)
1479 << " sdp: " << error.message();
1480 std::string error_message = oss.str();
Steve Anton8a006912017-12-04 15:25:56 -08001481 RTC_LOG(LS_ERROR) << error_message << " (" << error.type() << ")";
1482 PostSetSessionDescriptionFailure(observer, std::move(error_message));
Steve Anton8d3444d2017-10-20 15:30:51 -07001483 return;
1484 }
Steve Anton8a006912017-12-04 15:25:56 -08001485 RTC_DCHECK(local_description());
1486
1487 PostSetSessionDescriptionSuccess(observer);
1488
1489 // According to JSEP, after setLocalDescription, changing the candidate pool
1490 // size is not allowed, and changing the set of ICE servers will not result
1491 // in new candidates being gathered.
1492 port_allocator_->FreezeCandidatePool();
1493
1494 // MaybeStartGathering needs to be called after posting
1495 // MSG_SET_SESSIONDESCRIPTION_SUCCESS, so that we don't signal any candidates
1496 // before signaling that SetLocalDescription completed.
1497 transport_controller_->MaybeStartGathering();
1498
Steve Antona3a92c22017-12-07 10:27:41 -08001499 if (local_description()->GetType() == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08001500 // TODO(deadbeef): We already had to hop to the network thread for
1501 // MaybeStartGathering...
1502 network_thread()->Invoke<void>(
1503 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
1504 port_allocator_.get()));
1505 }
1506}
1507
1508RTCError PeerConnection::ApplyLocalDescription(
1509 std::unique_ptr<SessionDescriptionInterface> desc) {
1510 RTC_DCHECK_RUN_ON(signaling_thread());
1511 RTC_DCHECK(desc);
1512
1513 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_LOCAL);
1514 if (!error.ok()) {
1515 return error;
1516 }
Steve Anton8d3444d2017-10-20 15:30:51 -07001517
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001518 // Update stats here so that we have the most recent stats for tracks and
1519 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001520 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 15:25:56 -08001521
1522 // Update the initial_offerer flag if this session is the initial_offerer.
Steve Anton3828c062017-12-06 10:34:51 -08001523 SdpType type = desc->GetType();
Steve Anton8a006912017-12-04 15:25:56 -08001524 if (!initial_offerer_.has_value()) {
Steve Anton3828c062017-12-06 10:34:51 -08001525 initial_offerer_.emplace(type == SdpType::kOffer);
Steve Anton8a006912017-12-04 15:25:56 -08001526 if (*initial_offerer_) {
1527 transport_controller_->SetIceRole(cricket::ICEROLE_CONTROLLING);
1528 } else {
1529 transport_controller_->SetIceRole(cricket::ICEROLE_CONTROLLED);
1530 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001531 }
Steve Anton8a006912017-12-04 15:25:56 -08001532
Steve Anton3828c062017-12-06 10:34:51 -08001533 if (type == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08001534 current_local_description_ = std::move(desc);
1535 pending_local_description_ = nullptr;
1536 current_remote_description_ = std::move(pending_remote_description_);
1537 } else {
1538 pending_local_description_ = std::move(desc);
1539 }
1540 // The session description to apply now must be accessed by
1541 // |local_description()|.
Henrik Boströmfdb92012017-11-09 19:55:44 +01001542 RTC_DCHECK(local_description());
deadbeefab9b2d12015-10-14 11:33:11 -07001543
Steve Anton8a006912017-12-04 15:25:56 -08001544 // Transport and Media channels will be created only when offer is set.
Steve Anton3828c062017-12-06 10:34:51 -08001545 if (type == SdpType::kOffer) {
Steve Anton8a006912017-12-04 15:25:56 -08001546 // TODO(mallinath) - Handle CreateChannel failure, as new local description
1547 // is applied. Restore back to old description.
1548 RTCError error = CreateChannels(local_description()->description());
1549 if (!error.ok()) {
1550 return error;
1551 }
1552 }
1553
1554 // Remove unused channels if MediaContentDescription is rejected.
1555 RemoveUnusedChannels(local_description()->description());
1556
Steve Anton3828c062017-12-06 10:34:51 -08001557 error = UpdateSessionState(type, cricket::CS_LOCAL);
Steve Anton8a006912017-12-04 15:25:56 -08001558 if (!error.ok()) {
1559 return error;
1560 }
1561 if (remote_description()) {
1562 // Now that we have a local description, we can push down remote candidates.
1563 UseCandidatesInSessionDescription(remote_description());
1564 }
1565
1566 pending_ice_restarts_.clear();
1567 if (session_error() != SessionError::kNone) {
1568 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
1569 }
1570
deadbeefab9b2d12015-10-14 11:33:11 -07001571 // If setting the description decided our SSL role, allocate any necessary
1572 // SCTP sids.
1573 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08001574 if (data_channel_type() == cricket::DCT_SCTP && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001575 AllocateSctpSids(role);
1576 }
1577
1578 // Update state and SSRC of local MediaStreams and DataChannels based on the
1579 // local session description.
1580 const cricket::ContentInfo* audio_content =
Henrik Boströmfdb92012017-11-09 19:55:44 +01001581 GetFirstAudioContent(local_description()->description());
deadbeefab9b2d12015-10-14 11:33:11 -07001582 if (audio_content) {
deadbeeffaac4972015-11-12 15:33:07 -08001583 if (audio_content->rejected) {
Steve Anton4171afb2017-11-20 10:20:22 -08001584 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
deadbeeffaac4972015-11-12 15:33:07 -08001585 } else {
1586 const cricket::AudioContentDescription* audio_desc =
1587 static_cast<const cricket::AudioContentDescription*>(
1588 audio_content->description);
Steve Anton4171afb2017-11-20 10:20:22 -08001589 UpdateLocalSenders(audio_desc->streams(), audio_desc->type());
deadbeeffaac4972015-11-12 15:33:07 -08001590 }
deadbeefab9b2d12015-10-14 11:33:11 -07001591 }
1592
1593 const cricket::ContentInfo* video_content =
Henrik Boströmfdb92012017-11-09 19:55:44 +01001594 GetFirstVideoContent(local_description()->description());
deadbeefab9b2d12015-10-14 11:33:11 -07001595 if (video_content) {
deadbeeffaac4972015-11-12 15:33:07 -08001596 if (video_content->rejected) {
Steve Anton4171afb2017-11-20 10:20:22 -08001597 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
deadbeeffaac4972015-11-12 15:33:07 -08001598 } else {
1599 const cricket::VideoContentDescription* video_desc =
1600 static_cast<const cricket::VideoContentDescription*>(
1601 video_content->description);
Steve Anton4171afb2017-11-20 10:20:22 -08001602 UpdateLocalSenders(video_desc->streams(), video_desc->type());
deadbeeffaac4972015-11-12 15:33:07 -08001603 }
deadbeefab9b2d12015-10-14 11:33:11 -07001604 }
1605
1606 const cricket::ContentInfo* data_content =
Henrik Boströmfdb92012017-11-09 19:55:44 +01001607 GetFirstDataContent(local_description()->description());
deadbeefab9b2d12015-10-14 11:33:11 -07001608 if (data_content) {
1609 const cricket::DataContentDescription* data_desc =
1610 static_cast<const cricket::DataContentDescription*>(
1611 data_content->description);
1612 if (rtc::starts_with(data_desc->protocol().data(),
1613 cricket::kMediaProtocolRtpPrefix)) {
1614 UpdateLocalRtpDataChannels(data_desc->streams());
1615 }
1616 }
1617
Steve Anton8a006912017-12-04 15:25:56 -08001618 return RTCError::OK();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001619}
1620
1621void PeerConnection::SetRemoteDescription(
Henrik Boströma4ecf552017-11-23 14:17:07 +00001622 SetSessionDescriptionObserver* observer,
1623 SessionDescriptionInterface* desc) {
Henrik Boström31638672017-11-23 17:48:32 +01001624 SetRemoteDescription(
1625 std::unique_ptr<SessionDescriptionInterface>(desc),
1626 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface>(
1627 new SetRemoteDescriptionObserverAdapter(this, observer)));
1628}
1629
1630void PeerConnection::SetRemoteDescription(
1631 std::unique_ptr<SessionDescriptionInterface> desc,
1632 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface> observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001633 TRACE_EVENT0("webrtc", "PeerConnection::SetRemoteDescription");
Steve Anton8a006912017-12-04 15:25:56 -08001634
nisse7ce109a2017-01-31 00:57:56 -08001635 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001636 RTC_LOG(LS_ERROR) << "SetRemoteDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001637 return;
1638 }
Steve Anton8a006912017-12-04 15:25:56 -08001639
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001640 if (!desc) {
Henrik Boström31638672017-11-23 17:48:32 +01001641 observer->OnSetRemoteDescriptionComplete(RTCError(
Steve Anton8a006912017-12-04 15:25:56 -08001642 RTCErrorType::INVALID_PARAMETER, "SessionDescription is NULL."));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001643 return;
1644 }
Steve Anton8d3444d2017-10-20 15:30:51 -07001645
Steve Antona3a92c22017-12-07 10:27:41 -08001646 const SdpType type = desc->GetType();
Steve Anton8a006912017-12-04 15:25:56 -08001647
1648 RTCError error = ApplyRemoteDescription(std::move(desc));
1649 // |desc| may be destroyed at this point.
1650
1651 if (!error.ok()) {
Steve Antona3a92c22017-12-07 10:27:41 -08001652 std::ostringstream oss;
1653 oss << "Failed to set remote " << SdpTypeToString(type)
1654 << " sdp: " << error.message();
1655 std::string error_message = oss.str();
Steve Anton8a006912017-12-04 15:25:56 -08001656 RTC_LOG(LS_ERROR) << error_message << " (" << error.type() << ")";
Henrik Boström31638672017-11-23 17:48:32 +01001657 observer->OnSetRemoteDescriptionComplete(
Steve Anton8a006912017-12-04 15:25:56 -08001658 RTCError(error.type(), std::move(error_message)));
Steve Anton8d3444d2017-10-20 15:30:51 -07001659 return;
1660 }
1661
Steve Antona3a92c22017-12-07 10:27:41 -08001662 if (remote_description()->GetType() == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08001663 // TODO(deadbeef): We already had to hop to the network thread for
1664 // MaybeStartGathering...
1665 network_thread()->Invoke<void>(
1666 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
1667 port_allocator_.get()));
1668 }
1669
1670 observer->OnSetRemoteDescriptionComplete(RTCError::OK());
1671}
1672
1673RTCError PeerConnection::ApplyRemoteDescription(
1674 std::unique_ptr<SessionDescriptionInterface> desc) {
1675 RTC_DCHECK_RUN_ON(signaling_thread());
1676 RTC_DCHECK(desc);
1677
1678 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_REMOTE);
1679 if (!error.ok()) {
1680 return error;
1681 }
1682
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001683 // Update stats here so that we have the most recent stats for tracks and
1684 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001685 stats_->UpdateStats(kStatsOutputLevelStandard);
Henrik Boström31638672017-11-23 17:48:32 +01001686 // Takes the ownership of |desc|. On success, remote_description() is updated
1687 // to reflect the description that was passed in.
Steve Anton8a006912017-12-04 15:25:56 -08001688
1689 const SessionDescriptionInterface* old_remote_description =
1690 remote_description();
1691 // Grab ownership of the description being replaced for the remainder of this
1692 // method, since it's used below as |old_remote_description|.
1693 std::unique_ptr<SessionDescriptionInterface> replaced_remote_description;
Steve Anton3828c062017-12-06 10:34:51 -08001694 SdpType type = desc->GetType();
1695 if (type == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08001696 replaced_remote_description = pending_remote_description_
1697 ? std::move(pending_remote_description_)
1698 : std::move(current_remote_description_);
1699 current_remote_description_ = std::move(desc);
1700 pending_remote_description_ = nullptr;
1701 current_local_description_ = std::move(pending_local_description_);
1702 } else {
1703 replaced_remote_description = std::move(pending_remote_description_);
1704 pending_remote_description_ = std::move(desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001705 }
Steve Anton8a006912017-12-04 15:25:56 -08001706 // The session description to apply now must be accessed by
1707 // |remote_description()|.
Henrik Boströmfdb92012017-11-09 19:55:44 +01001708 RTC_DCHECK(remote_description());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001709
Steve Anton8a006912017-12-04 15:25:56 -08001710 // Transport and Media channels will be created only when offer is set.
Steve Anton3828c062017-12-06 10:34:51 -08001711 if (type == SdpType::kOffer) {
Steve Anton8a006912017-12-04 15:25:56 -08001712 // TODO(mallinath) - Handle CreateChannel failure, as new local description
1713 // is applied. Restore back to old description.
1714 RTCError error = CreateChannels(remote_description()->description());
1715 if (!error.ok()) {
1716 return error;
1717 }
1718 }
1719
1720 // Remove unused channels if MediaContentDescription is rejected.
1721 RemoveUnusedChannels(remote_description()->description());
1722
1723 // NOTE: Candidates allocation will be initiated only when SetLocalDescription
1724 // is called.
Steve Anton3828c062017-12-06 10:34:51 -08001725 error = UpdateSessionState(type, cricket::CS_REMOTE);
Steve Anton8a006912017-12-04 15:25:56 -08001726 if (!error.ok()) {
1727 return error;
1728 }
1729
1730 if (local_description() &&
1731 !UseCandidatesInSessionDescription(remote_description())) {
1732 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidCandidates);
1733 }
1734
1735 if (old_remote_description) {
1736 for (const cricket::ContentInfo& content :
1737 old_remote_description->description()->contents()) {
1738 // Check if this new SessionDescription contains new ICE ufrag and
1739 // password that indicates the remote peer requests an ICE restart.
1740 // TODO(deadbeef): When we start storing both the current and pending
1741 // remote description, this should reset pending_ice_restarts and compare
1742 // against the current description.
1743 if (CheckForRemoteIceRestart(old_remote_description, remote_description(),
1744 content.name)) {
Steve Anton3828c062017-12-06 10:34:51 -08001745 if (type == SdpType::kOffer) {
Steve Anton8a006912017-12-04 15:25:56 -08001746 pending_ice_restarts_.insert(content.name);
1747 }
1748 } else {
1749 // We retain all received candidates only if ICE is not restarted.
1750 // When ICE is restarted, all previous candidates belong to an old
1751 // generation and should not be kept.
1752 // TODO(deadbeef): This goes against the W3C spec which says the remote
1753 // description should only contain candidates from the last set remote
1754 // description plus any candidates added since then. We should remove
1755 // this once we're sure it won't break anything.
1756 WebRtcSessionDescriptionFactory::CopyCandidatesFromSessionDescription(
1757 old_remote_description, content.name, mutable_remote_description());
1758 }
1759 }
1760 }
1761
1762 if (session_error() != SessionError::kNone) {
1763 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
1764 }
1765
1766 // Set the the ICE connection state to connecting since the connection may
1767 // become writable with peer reflexive candidates before any remote candidate
1768 // is signaled.
1769 // TODO(pthatcher): This is a short-term solution for crbug/446908. A real fix
1770 // is to have a new signal the indicates a change in checking state from the
1771 // transport and expose a new checking() member from transport that can be
1772 // read to determine the current checking state. The existing SignalConnecting
1773 // actually means "gathering candidates", so cannot be be used here.
Steve Antona3a92c22017-12-07 10:27:41 -08001774 if (remote_description()->GetType() != SdpType::kOffer &&
Steve Anton8a006912017-12-04 15:25:56 -08001775 ice_connection_state() == PeerConnectionInterface::kIceConnectionNew) {
1776 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
1777 }
1778
deadbeefab9b2d12015-10-14 11:33:11 -07001779 // If setting the description decided our SSL role, allocate any necessary
1780 // SCTP sids.
1781 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08001782 if (data_channel_type() == cricket::DCT_SCTP && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001783 AllocateSctpSids(role);
1784 }
1785
Henrik Boströmfdb92012017-11-09 19:55:44 +01001786 const cricket::ContentInfo* audio_content =
1787 GetFirstAudioContent(remote_description()->description());
1788 const cricket::ContentInfo* video_content =
1789 GetFirstVideoContent(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08001790 const cricket::AudioContentDescription* audio_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01001791 GetFirstAudioContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08001792 const cricket::VideoContentDescription* video_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01001793 GetFirstVideoContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08001794 const cricket::DataContentDescription* data_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01001795 GetFirstDataContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08001796
1797 // Check if the descriptions include streams, just in case the peer supports
1798 // MSID, but doesn't indicate so with "a=msid-semantic".
Henrik Boströmfdb92012017-11-09 19:55:44 +01001799 if (remote_description()->description()->msid_supported() ||
deadbeefbda7e0b2015-12-08 17:13:40 -08001800 (audio_desc && !audio_desc->streams().empty()) ||
1801 (video_desc && !video_desc->streams().empty())) {
1802 remote_peer_supports_msid_ = true;
1803 }
deadbeefab9b2d12015-10-14 11:33:11 -07001804
1805 // We wait to signal new streams until we finish processing the description,
1806 // since only at that point will new streams have all their tracks.
1807 rtc::scoped_refptr<StreamCollection> new_streams(StreamCollection::Create());
1808
Steve Anton8d3444d2017-10-20 15:30:51 -07001809 // TODO(steveanton): When removing RTP senders/receivers in response to a
1810 // rejected media section, there is some cleanup logic that expects the voice/
1811 // video channel to still be set. But in this method the voice/video channel
Steve Anton75737c02017-11-06 10:37:17 -08001812 // would have been destroyed by the SetRemoteDescription caller above so the
Steve Anton4171afb2017-11-20 10:20:22 -08001813 // cleanup that relies on them fails to run. The RemoveSenders calls should be
Steve Anton75737c02017-11-06 10:37:17 -08001814 // moved to right before the DestroyChannel calls to fix this.
Steve Anton8d3444d2017-10-20 15:30:51 -07001815
deadbeefab9b2d12015-10-14 11:33:11 -07001816 // Find all audio rtp streams and create corresponding remote AudioTracks
1817 // and MediaStreams.
deadbeefab9b2d12015-10-14 11:33:11 -07001818 if (audio_content) {
deadbeeffaac4972015-11-12 15:33:07 -08001819 if (audio_content->rejected) {
Steve Anton4171afb2017-11-20 10:20:22 -08001820 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
deadbeeffaac4972015-11-12 15:33:07 -08001821 } else {
deadbeefbda7e0b2015-12-08 17:13:40 -08001822 bool default_audio_track_needed =
1823 !remote_peer_supports_msid_ &&
Steve Anton4e70a722017-11-28 14:57:10 -08001824 RtpTransceiverDirectionHasSend(audio_desc->direction());
Steve Anton4171afb2017-11-20 10:20:22 -08001825 UpdateRemoteSendersList(GetActiveStreams(audio_desc),
deadbeefbda7e0b2015-12-08 17:13:40 -08001826 default_audio_track_needed, audio_desc->type(),
deadbeeffaac4972015-11-12 15:33:07 -08001827 new_streams);
deadbeeffaac4972015-11-12 15:33:07 -08001828 }
deadbeefab9b2d12015-10-14 11:33:11 -07001829 }
1830
1831 // Find all video rtp streams and create corresponding remote VideoTracks
1832 // and MediaStreams.
deadbeefab9b2d12015-10-14 11:33:11 -07001833 if (video_content) {
deadbeeffaac4972015-11-12 15:33:07 -08001834 if (video_content->rejected) {
Steve Anton4171afb2017-11-20 10:20:22 -08001835 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
deadbeeffaac4972015-11-12 15:33:07 -08001836 } else {
deadbeefbda7e0b2015-12-08 17:13:40 -08001837 bool default_video_track_needed =
1838 !remote_peer_supports_msid_ &&
Steve Anton4e70a722017-11-28 14:57:10 -08001839 RtpTransceiverDirectionHasSend(video_desc->direction());
Steve Anton4171afb2017-11-20 10:20:22 -08001840 UpdateRemoteSendersList(GetActiveStreams(video_desc),
deadbeefbda7e0b2015-12-08 17:13:40 -08001841 default_video_track_needed, video_desc->type(),
deadbeeffaac4972015-11-12 15:33:07 -08001842 new_streams);
deadbeeffaac4972015-11-12 15:33:07 -08001843 }
deadbeefab9b2d12015-10-14 11:33:11 -07001844 }
1845
1846 // Update the DataChannels with the information from the remote peer.
deadbeefbda7e0b2015-12-08 17:13:40 -08001847 if (data_desc) {
1848 if (rtc::starts_with(data_desc->protocol().data(),
deadbeefab9b2d12015-10-14 11:33:11 -07001849 cricket::kMediaProtocolRtpPrefix)) {
deadbeefbda7e0b2015-12-08 17:13:40 -08001850 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
deadbeefab9b2d12015-10-14 11:33:11 -07001851 }
1852 }
1853
1854 // Iterate new_streams and notify the observer about new MediaStreams.
1855 for (size_t i = 0; i < new_streams->count(); ++i) {
1856 MediaStreamInterface* new_stream = new_streams->at(i);
1857 stats_->AddStream(new_stream);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07001858 observer_->OnAddStream(
1859 rtc::scoped_refptr<MediaStreamInterface>(new_stream));
deadbeefab9b2d12015-10-14 11:33:11 -07001860 }
1861
deadbeefbda7e0b2015-12-08 17:13:40 -08001862 UpdateEndedRemoteMediaStreams();
deadbeefab9b2d12015-10-14 11:33:11 -07001863
Steve Anton8a006912017-12-04 15:25:56 -08001864 return RTCError::OK();
deadbeeffc648b62015-10-13 16:42:33 -07001865}
1866
Steve Antoned10bd92017-12-05 10:52:59 -08001867const cricket::ContentInfo* PeerConnection::FindMediaSectionForTransceiver(
1868 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1869 transceiver,
1870 const SessionDescriptionInterface* sdesc) const {
1871 RTC_DCHECK(transceiver);
1872 RTC_DCHECK(sdesc);
1873 if (IsUnifiedPlan()) {
1874 if (!transceiver->internal()->mid()) {
1875 // This transceiver is not associated with a media section yet.
1876 return nullptr;
1877 }
1878 return sdesc->description()->GetContentByName(
1879 *transceiver->internal()->mid());
1880 } else {
1881 // Plan B only allows at most one audio and one video section, so use the
1882 // first media section of that type.
1883 return cricket::GetFirstMediaContent(sdesc->description()->contents(),
1884 transceiver->internal()->media_type());
1885 }
1886}
1887
deadbeef46c73892016-11-16 19:42:04 -08001888PeerConnectionInterface::RTCConfiguration PeerConnection::GetConfiguration() {
1889 return configuration_;
1890}
1891
deadbeef293e9262017-01-11 12:28:30 -08001892bool PeerConnection::SetConfiguration(const RTCConfiguration& configuration,
1893 RTCError* error) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001894 TRACE_EVENT0("webrtc", "PeerConnection::SetConfiguration");
deadbeef6de92f92016-12-12 18:49:32 -08001895
Steve Anton75737c02017-11-06 10:37:17 -08001896 if (local_description() && configuration.ice_candidate_pool_size !=
1897 configuration_.ice_candidate_pool_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001898 RTC_LOG(LS_ERROR) << "Can't change candidate pool size after calling "
1899 "SetLocalDescription.";
deadbeef293e9262017-01-11 12:28:30 -08001900 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00001901 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07001902
deadbeef293e9262017-01-11 12:28:30 -08001903 // The simplest (and most future-compatible) way to tell if the config was
1904 // modified in an invalid way is to copy each property we do support
1905 // modifying, then use operator==. There are far more properties we don't
1906 // support modifying than those we do, and more could be added.
1907 RTCConfiguration modified_config = configuration_;
1908 modified_config.servers = configuration.servers;
1909 modified_config.type = configuration.type;
1910 modified_config.ice_candidate_pool_size =
1911 configuration.ice_candidate_pool_size;
1912 modified_config.prune_turn_ports = configuration.prune_turn_ports;
skvladd1f5fda2017-02-03 16:54:05 -08001913 modified_config.ice_check_min_interval = configuration.ice_check_min_interval;
Jonas Orelandbdcee282017-10-10 14:01:40 +02001914 modified_config.turn_customizer = configuration.turn_customizer;
deadbeef293e9262017-01-11 12:28:30 -08001915 if (configuration != modified_config) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001916 RTC_LOG(LS_ERROR) << "Modifying the configuration in an unsupported way.";
deadbeef293e9262017-01-11 12:28:30 -08001917 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
1918 }
1919
Steve Anton038834f2017-07-14 15:59:59 -07001920 // Validate the modified configuration.
1921 RTCError validate_error = ValidateConfiguration(modified_config);
1922 if (!validate_error.ok()) {
1923 return SafeSetError(std::move(validate_error), error);
1924 }
1925
deadbeef293e9262017-01-11 12:28:30 -08001926 // Note that this isn't possible through chromium, since it's an unsigned
1927 // short in WebIDL.
1928 if (configuration.ice_candidate_pool_size < 0 ||
1929 configuration.ice_candidate_pool_size > UINT16_MAX) {
1930 return SafeSetError(RTCErrorType::INVALID_RANGE, error);
1931 }
1932
1933 // Parse ICE servers before hopping to network thread.
1934 cricket::ServerAddresses stun_servers;
1935 std::vector<cricket::RelayServerConfig> turn_servers;
1936 RTCErrorType parse_error =
1937 ParseIceServers(configuration.servers, &stun_servers, &turn_servers);
1938 if (parse_error != RTCErrorType::NONE) {
1939 return SafeSetError(parse_error, error);
1940 }
1941
1942 // In theory this shouldn't fail.
1943 if (!network_thread()->Invoke<bool>(
1944 RTC_FROM_HERE,
1945 rtc::Bind(&PeerConnection::ReconfigurePortAllocator_n, this,
1946 stun_servers, turn_servers, modified_config.type,
1947 modified_config.ice_candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02001948 modified_config.prune_turn_ports,
1949 modified_config.turn_customizer))) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001950 RTC_LOG(LS_ERROR) << "Failed to apply configuration to PortAllocator.";
deadbeef293e9262017-01-11 12:28:30 -08001951 return SafeSetError(RTCErrorType::INTERNAL_ERROR, error);
1952 }
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07001953
deadbeefd1a38b52016-12-10 13:15:33 -08001954 // As described in JSEP, calling setConfiguration with new ICE servers or
1955 // candidate policy must set a "needs-ice-restart" bit so that the next offer
1956 // triggers an ICE restart which will pick up the changes.
deadbeef293e9262017-01-11 12:28:30 -08001957 if (modified_config.servers != configuration_.servers ||
1958 modified_config.type != configuration_.type ||
1959 modified_config.prune_turn_ports != configuration_.prune_turn_ports) {
Steve Antond25da372017-11-06 14:50:29 -08001960 transport_controller_->SetNeedsIceRestartFlag();
deadbeefd1a38b52016-12-10 13:15:33 -08001961 }
skvladd1f5fda2017-02-03 16:54:05 -08001962
1963 if (modified_config.ice_check_min_interval !=
1964 configuration_.ice_check_min_interval) {
Steve Antond25da372017-11-06 14:50:29 -08001965 transport_controller_->SetIceConfig(ParseIceConfig(modified_config));
skvladd1f5fda2017-02-03 16:54:05 -08001966 }
1967
deadbeef293e9262017-01-11 12:28:30 -08001968 configuration_ = modified_config;
1969 return SafeSetError(RTCErrorType::NONE, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00001970}
1971
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001972bool PeerConnection::AddIceCandidate(
1973 const IceCandidateInterface* ice_candidate) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001974 TRACE_EVENT0("webrtc", "PeerConnection::AddIceCandidate");
zhihuang29ff8442016-07-27 11:07:25 -07001975 if (IsClosed()) {
1976 return false;
1977 }
Steve Antond25da372017-11-06 14:50:29 -08001978
1979 if (!remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001980 RTC_LOG(LS_ERROR) << "ProcessIceMessage: ICE candidates can't be added "
1981 << "without any remote session description.";
Steve Antond25da372017-11-06 14:50:29 -08001982 return false;
1983 }
1984
1985 if (!ice_candidate) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001986 RTC_LOG(LS_ERROR) << "ProcessIceMessage: Candidate is NULL.";
Steve Antond25da372017-11-06 14:50:29 -08001987 return false;
1988 }
1989
1990 bool valid = false;
1991 bool ready = ReadyToUseRemoteCandidate(ice_candidate, nullptr, &valid);
1992 if (!valid) {
1993 return false;
1994 }
1995
1996 // Add this candidate to the remote session description.
1997 if (!mutable_remote_description()->AddCandidate(ice_candidate)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001998 RTC_LOG(LS_ERROR) << "ProcessIceMessage: Candidate cannot be used.";
Steve Antond25da372017-11-06 14:50:29 -08001999 return false;
2000 }
2001
2002 if (ready) {
2003 return UseCandidate(ice_candidate);
2004 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002005 RTC_LOG(LS_INFO) << "ProcessIceMessage: Not ready to use candidate.";
Steve Antond25da372017-11-06 14:50:29 -08002006 return true;
2007 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002008}
2009
Honghai Zhang7fb69db2016-03-14 11:59:18 -07002010bool PeerConnection::RemoveIceCandidates(
2011 const std::vector<cricket::Candidate>& candidates) {
2012 TRACE_EVENT0("webrtc", "PeerConnection::RemoveIceCandidates");
Steve Antond25da372017-11-06 14:50:29 -08002013 if (!remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002014 RTC_LOG(LS_ERROR) << "RemoveRemoteIceCandidates: ICE candidates can't be "
2015 << "removed without any remote session description.";
Steve Antond25da372017-11-06 14:50:29 -08002016 return false;
2017 }
2018
2019 if (candidates.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002020 RTC_LOG(LS_ERROR) << "RemoveRemoteIceCandidates: candidates are empty.";
Steve Antond25da372017-11-06 14:50:29 -08002021 return false;
2022 }
2023
2024 size_t number_removed =
2025 mutable_remote_description()->RemoveCandidates(candidates);
2026 if (number_removed != candidates.size()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002027 RTC_LOG(LS_ERROR)
2028 << "RemoveRemoteIceCandidates: Failed to remove candidates. "
2029 << "Requested " << candidates.size() << " but only " << number_removed
2030 << " are removed.";
Steve Antond25da372017-11-06 14:50:29 -08002031 }
2032
2033 // Remove the candidates from the transport controller.
2034 std::string error;
2035 bool res = transport_controller_->RemoveRemoteCandidates(candidates, &error);
2036 if (!res && !error.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002037 RTC_LOG(LS_ERROR) << "Error when removing remote candidates: " << error;
Steve Antond25da372017-11-06 14:50:29 -08002038 }
2039 return true;
Honghai Zhang7fb69db2016-03-14 11:59:18 -07002040}
2041
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00002042void PeerConnection::RegisterUMAObserver(UMAObserver* observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +01002043 TRACE_EVENT0("webrtc", "PeerConnection::RegisterUmaObserver");
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00002044 uma_observer_ = observer;
guoweis@webrtc.org7169afd2014-12-04 17:59:29 +00002045
Steve Anton75737c02017-11-06 10:37:17 -08002046 if (transport_controller()) {
2047 transport_controller()->SetMetricsObserver(uma_observer_);
guoweis@webrtc.org7169afd2014-12-04 17:59:29 +00002048 }
2049
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00002050 // Send information about IPv4/IPv6 status.
deadbeef293e9262017-01-11 12:28:30 -08002051 if (uma_observer_) {
Honghai Zhangd93f50c2016-10-05 11:47:22 -07002052 port_allocator_->SetMetricsObserver(uma_observer_);
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00002053 if (port_allocator_->flags() & cricket::PORTALLOCATOR_ENABLE_IPV6) {
Guo-wei Shiehdfbe6792015-09-03 17:12:07 -07002054 uma_observer_->IncrementEnumCounter(
2055 kEnumCounterAddressFamily, kPeerConnection_IPv6,
2056 kPeerConnectionAddressFamilyCounter_Max);
mallinath@webrtc.orgb445f262014-05-23 22:19:37 +00002057 } else {
Guo-wei Shiehdfbe6792015-09-03 17:12:07 -07002058 uma_observer_->IncrementEnumCounter(
2059 kEnumCounterAddressFamily, kPeerConnection_IPv4,
2060 kPeerConnectionAddressFamilyCounter_Max);
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00002061 }
2062 }
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00002063}
2064
zstein4b979802017-06-02 14:37:37 -07002065RTCError PeerConnection::SetBitrate(const BitrateParameters& bitrate) {
Steve Anton978b8762017-09-29 12:15:02 -07002066 if (!worker_thread()->IsCurrent()) {
2067 return worker_thread()->Invoke<RTCError>(
zstein4b979802017-06-02 14:37:37 -07002068 RTC_FROM_HERE, rtc::Bind(&PeerConnection::SetBitrate, this, bitrate));
2069 }
2070
2071 const bool has_min = static_cast<bool>(bitrate.min_bitrate_bps);
2072 const bool has_current = static_cast<bool>(bitrate.current_bitrate_bps);
2073 const bool has_max = static_cast<bool>(bitrate.max_bitrate_bps);
2074 if (has_min && *bitrate.min_bitrate_bps < 0) {
2075 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2076 "min_bitrate_bps <= 0");
2077 }
2078 if (has_current) {
2079 if (has_min && *bitrate.current_bitrate_bps < *bitrate.min_bitrate_bps) {
2080 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2081 "current_bitrate_bps < min_bitrate_bps");
2082 } else if (*bitrate.current_bitrate_bps < 0) {
2083 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2084 "curent_bitrate_bps < 0");
2085 }
2086 }
2087 if (has_max) {
2088 if (has_current &&
2089 *bitrate.max_bitrate_bps < *bitrate.current_bitrate_bps) {
2090 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2091 "max_bitrate_bps < current_bitrate_bps");
2092 } else if (has_min && *bitrate.max_bitrate_bps < *bitrate.min_bitrate_bps) {
2093 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2094 "max_bitrate_bps < min_bitrate_bps");
2095 } else if (*bitrate.max_bitrate_bps < 0) {
2096 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2097 "max_bitrate_bps < 0");
2098 }
2099 }
2100
2101 Call::Config::BitrateConfigMask mask;
2102 mask.min_bitrate_bps = bitrate.min_bitrate_bps;
2103 mask.start_bitrate_bps = bitrate.current_bitrate_bps;
2104 mask.max_bitrate_bps = bitrate.max_bitrate_bps;
2105
2106 RTC_DCHECK(call_.get());
2107 call_->SetBitrateConfigMask(mask);
2108
2109 return RTCError::OK();
2110}
2111
Alex Narest78609d52017-10-20 10:37:47 +02002112void PeerConnection::SetBitrateAllocationStrategy(
2113 std::unique_ptr<rtc::BitrateAllocationStrategy>
2114 bitrate_allocation_strategy) {
2115 rtc::Thread* worker_thread = factory_->worker_thread();
2116 if (!worker_thread->IsCurrent()) {
2117 rtc::BitrateAllocationStrategy* strategy_raw =
2118 bitrate_allocation_strategy.release();
2119 auto functor = [this, strategy_raw]() {
2120 call_->SetBitrateAllocationStrategy(
2121 rtc::WrapUnique<rtc::BitrateAllocationStrategy>(strategy_raw));
2122 };
2123 worker_thread->Invoke<void>(RTC_FROM_HERE, functor);
2124 return;
2125 }
2126 RTC_DCHECK(call_.get());
2127 call_->SetBitrateAllocationStrategy(std::move(bitrate_allocation_strategy));
2128}
2129
henrika5f6bf242017-11-01 11:06:56 +01002130void PeerConnection::SetAudioPlayout(bool playout) {
2131 if (!worker_thread()->IsCurrent()) {
2132 worker_thread()->Invoke<void>(
2133 RTC_FROM_HERE,
2134 rtc::Bind(&PeerConnection::SetAudioPlayout, this, playout));
2135 return;
2136 }
2137 auto audio_state =
2138 factory_->channel_manager()->media_engine()->GetAudioState();
2139 audio_state->SetPlayout(playout);
2140}
2141
2142void PeerConnection::SetAudioRecording(bool recording) {
2143 if (!worker_thread()->IsCurrent()) {
2144 worker_thread()->Invoke<void>(
2145 RTC_FROM_HERE,
2146 rtc::Bind(&PeerConnection::SetAudioRecording, this, recording));
2147 return;
2148 }
2149 auto audio_state =
2150 factory_->channel_manager()->media_engine()->GetAudioState();
2151 audio_state->SetRecording(recording);
2152}
2153
Steve Anton8c0f7a72017-10-03 10:03:10 -07002154std::unique_ptr<rtc::SSLCertificate>
2155PeerConnection::GetRemoteAudioSSLCertificate() {
Steve Anton75737c02017-11-06 10:37:17 -08002156 if (!voice_channel()) {
Steve Anton8c0f7a72017-10-03 10:03:10 -07002157 return nullptr;
2158 }
Steve Anton75737c02017-11-06 10:37:17 -08002159 return GetRemoteSSLCertificate(voice_channel()->transport_name());
Steve Anton8c0f7a72017-10-03 10:03:10 -07002160}
2161
ivoc14d5dbe2016-07-04 07:06:55 -07002162bool PeerConnection::StartRtcEventLog(rtc::PlatformFile file,
2163 int64_t max_size_bytes) {
Elad Alon99c3fe52017-10-13 16:29:40 +02002164 // TODO(eladalon): It would be better to not allow negative values into PC.
2165 const size_t max_size = (max_size_bytes < 0)
2166 ? RtcEventLog::kUnlimitedOutput
2167 : rtc::saturated_cast<size_t>(max_size_bytes);
2168 return StartRtcEventLog(
Bjorn Tereliusde939432017-11-20 17:38:14 +01002169 rtc::MakeUnique<RtcEventLogOutputFile>(file, max_size),
2170 webrtc::RtcEventLog::kImmediateOutput);
Elad Alon99c3fe52017-10-13 16:29:40 +02002171}
2172
Bjorn Tereliusde939432017-11-20 17:38:14 +01002173bool PeerConnection::StartRtcEventLog(std::unique_ptr<RtcEventLogOutput> output,
2174 int64_t output_period_ms) {
Karl Wibergd6b48192017-10-16 23:01:06 +02002175 // TODO(eladalon): In C++14, this can be done with a lambda.
2176 struct Functor {
Bjorn Tereliusde939432017-11-20 17:38:14 +01002177 bool operator()() {
2178 return pc->StartRtcEventLog_w(std::move(output), output_period_ms);
2179 }
Karl Wibergd6b48192017-10-16 23:01:06 +02002180 PeerConnection* const pc;
2181 std::unique_ptr<RtcEventLogOutput> output;
Bjorn Tereliusde939432017-11-20 17:38:14 +01002182 const int64_t output_period_ms;
Elad Alon99c3fe52017-10-13 16:29:40 +02002183 };
Bjorn Tereliusde939432017-11-20 17:38:14 +01002184 return worker_thread()->Invoke<bool>(
2185 RTC_FROM_HERE, Functor{this, std::move(output), output_period_ms});
ivoc14d5dbe2016-07-04 07:06:55 -07002186}
2187
2188void PeerConnection::StopRtcEventLog() {
Steve Anton978b8762017-09-29 12:15:02 -07002189 worker_thread()->Invoke<void>(
ivoc14d5dbe2016-07-04 07:06:55 -07002190 RTC_FROM_HERE, rtc::Bind(&PeerConnection::StopRtcEventLog_w, this));
2191}
2192
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002193const SessionDescriptionInterface* PeerConnection::local_description() const {
Steve Anton75737c02017-11-06 10:37:17 -08002194 return pending_local_description_ ? pending_local_description_.get()
2195 : current_local_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002196}
2197
2198const SessionDescriptionInterface* PeerConnection::remote_description() const {
Steve Anton75737c02017-11-06 10:37:17 -08002199 return pending_remote_description_ ? pending_remote_description_.get()
2200 : current_remote_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002201}
2202
deadbeeffe4a8a42016-12-20 17:56:17 -08002203const SessionDescriptionInterface* PeerConnection::current_local_description()
2204 const {
Steve Anton75737c02017-11-06 10:37:17 -08002205 return current_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08002206}
2207
2208const SessionDescriptionInterface* PeerConnection::current_remote_description()
2209 const {
Steve Anton75737c02017-11-06 10:37:17 -08002210 return current_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08002211}
2212
2213const SessionDescriptionInterface* PeerConnection::pending_local_description()
2214 const {
Steve Anton75737c02017-11-06 10:37:17 -08002215 return pending_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08002216}
2217
2218const SessionDescriptionInterface* PeerConnection::pending_remote_description()
2219 const {
Steve Anton75737c02017-11-06 10:37:17 -08002220 return pending_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08002221}
2222
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002223void PeerConnection::Close() {
Peter Boström1a9d6152015-12-08 22:15:17 +01002224 TRACE_EVENT0("webrtc", "PeerConnection::Close");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002225 // Update stats here so that we have the most recent stats for tracks and
2226 // streams before the channels are closed.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00002227 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002228
Steve Anton75737c02017-11-06 10:37:17 -08002229 ChangeSignalingState(PeerConnectionInterface::kClosed);
2230 RemoveUnusedChannels(nullptr);
Steve Anton4171afb2017-11-20 10:20:22 -08002231 RTC_DCHECK(!GetAudioTransceiver()->internal()->channel());
2232 RTC_DCHECK(!GetVideoTransceiver()->internal()->channel());
Steve Anton75737c02017-11-06 10:37:17 -08002233 RTC_DCHECK(!rtp_data_channel_);
2234 RTC_DCHECK(!sctp_transport_);
2235
deadbeef42a42632017-03-10 15:18:00 -08002236 network_thread()->Invoke<void>(
2237 RTC_FROM_HERE,
2238 rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
2239 port_allocator_.get()));
nisseeaabdf62017-05-05 02:23:02 -07002240
Steve Anton978b8762017-09-29 12:15:02 -07002241 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
eladalon248fd4f2017-09-06 05:18:15 -07002242 call_.reset();
2243 // The event log must outlive call (and any other object that uses it).
2244 event_log_.reset();
2245 });
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002246}
2247
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002248void PeerConnection::OnMessage(rtc::Message* msg) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002249 switch (msg->message_id) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002250 case MSG_SET_SESSIONDESCRIPTION_SUCCESS: {
2251 SetSessionDescriptionMsg* param =
2252 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
2253 param->observer->OnSuccess();
2254 delete param;
2255 break;
2256 }
2257 case MSG_SET_SESSIONDESCRIPTION_FAILED: {
2258 SetSessionDescriptionMsg* param =
2259 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
2260 param->observer->OnFailure(param->error);
2261 delete param;
2262 break;
2263 }
deadbeefab9b2d12015-10-14 11:33:11 -07002264 case MSG_CREATE_SESSIONDESCRIPTION_FAILED: {
2265 CreateSessionDescriptionMsg* param =
2266 static_cast<CreateSessionDescriptionMsg*>(msg->pdata);
2267 param->observer->OnFailure(param->error);
2268 delete param;
2269 break;
2270 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002271 case MSG_GETSTATS: {
2272 GetStatsMsg* param = static_cast<GetStatsMsg*>(msg->pdata);
nissee8abe3e2017-01-18 05:00:34 -08002273 StatsReports reports;
2274 stats_->GetStats(param->track, &reports);
2275 param->observer->OnComplete(reports);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002276 delete param;
2277 break;
2278 }
deadbeefbd292462015-12-14 18:15:29 -08002279 case MSG_FREE_DATACHANNELS: {
2280 sctp_data_channels_to_free_.clear();
2281 break;
2282 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002283 default:
nisseeb4ca4e2017-01-12 02:24:27 -08002284 RTC_NOTREACHED() << "Not implemented";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002285 break;
2286 }
2287}
2288
Steve Anton4171afb2017-11-20 10:20:22 -08002289void PeerConnection::CreateAudioReceiver(
2290 MediaStreamInterface* stream,
2291 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01002292 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
2293 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
zhihuang81c3a032016-11-17 12:06:24 -08002294 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
2295 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
deadbeefe814a0d2017-02-25 18:15:09 -08002296 signaling_thread(),
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01002297 new AudioRtpReceiver(remote_sender_info.sender_id, streams,
Steve Anton4171afb2017-11-20 10:20:22 -08002298 remote_sender_info.first_ssrc, voice_channel()));
deadbeefe814a0d2017-02-25 18:15:09 -08002299 stream->AddTrack(
2300 static_cast<AudioTrackInterface*>(receiver->internal()->track().get()));
Steve Anton4171afb2017-11-20 10:20:22 -08002301 GetAudioTransceiver()->internal()->AddReceiver(receiver);
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01002302 observer_->OnAddTrack(receiver, std::move(streams));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002303}
2304
Steve Anton4171afb2017-11-20 10:20:22 -08002305void PeerConnection::CreateVideoReceiver(
2306 MediaStreamInterface* stream,
2307 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01002308 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
2309 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
zhihuang81c3a032016-11-17 12:06:24 -08002310 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
2311 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
Steve Anton4171afb2017-11-20 10:20:22 -08002312 signaling_thread(),
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01002313 new VideoRtpReceiver(remote_sender_info.sender_id, streams,
2314 worker_thread(), remote_sender_info.first_ssrc,
2315 video_channel()));
deadbeefe814a0d2017-02-25 18:15:09 -08002316 stream->AddTrack(
2317 static_cast<VideoTrackInterface*>(receiver->internal()->track().get()));
Steve Anton4171afb2017-11-20 10:20:22 -08002318 GetVideoTransceiver()->internal()->AddReceiver(receiver);
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01002319 observer_->OnAddTrack(receiver, std::move(streams));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002320}
2321
deadbeef70ab1a12015-09-28 16:53:55 -07002322// TODO(deadbeef): Keep RtpReceivers around even if track goes away in remote
2323// description.
Henrik Boström933d8b02017-10-10 10:05:16 -07002324rtc::scoped_refptr<RtpReceiverInterface> PeerConnection::RemoveAndStopReceiver(
Steve Anton4171afb2017-11-20 10:20:22 -08002325 const RtpSenderInfo& remote_sender_info) {
2326 auto receiver = FindReceiverById(remote_sender_info.sender_id);
2327 if (!receiver) {
2328 RTC_LOG(LS_WARNING) << "RtpReceiver for track with id "
2329 << remote_sender_info.sender_id << " doesn't exist.";
Henrik Boström933d8b02017-10-10 10:05:16 -07002330 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07002331 }
Steve Anton4171afb2017-11-20 10:20:22 -08002332 if (receiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
2333 GetAudioTransceiver()->internal()->RemoveReceiver(receiver);
2334 } else {
2335 GetVideoTransceiver()->internal()->RemoveReceiver(receiver);
2336 }
Henrik Boström933d8b02017-10-10 10:05:16 -07002337 return receiver;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002338}
2339
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002340void PeerConnection::AddAudioTrack(AudioTrackInterface* track,
2341 MediaStreamInterface* stream) {
2342 RTC_DCHECK(!IsClosed());
2343 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08002344 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002345 // We already have a sender for this track, so just change the stream_id
2346 // so that it's correct in the next call to CreateOffer.
Steve Anton4171afb2017-11-20 10:20:22 -08002347 sender->internal()->set_stream_id(stream->label());
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002348 return;
2349 }
2350
2351 // Normal case; we've never seen this track before.
2352 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender =
2353 RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
2354 signaling_thread(),
Steve Anton75737c02017-11-06 10:37:17 -08002355 new AudioRtpSender(track, {stream->label()}, voice_channel(),
2356 stats_.get()));
Steve Anton4171afb2017-11-20 10:20:22 -08002357 GetAudioTransceiver()->internal()->AddSender(new_sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002358 // If the sender has already been configured in SDP, we call SetSsrc,
2359 // which will connect the sender to the underlying transport. This can
2360 // occur if a local session description that contains the ID of the sender
2361 // is set before AddStream is called. It can also occur if the local
2362 // session description is not changed and RemoveStream is called, and
2363 // later AddStream is called again with the same stream.
Steve Anton4171afb2017-11-20 10:20:22 -08002364 const RtpSenderInfo* sender_info =
2365 FindSenderInfo(local_audio_sender_infos_, stream->label(), track->id());
2366 if (sender_info) {
2367 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002368 }
2369}
2370
2371// TODO(deadbeef): Don't destroy RtpSenders here; they should be kept around
2372// indefinitely, when we have unified plan SDP.
2373void PeerConnection::RemoveAudioTrack(AudioTrackInterface* track,
2374 MediaStreamInterface* stream) {
2375 RTC_DCHECK(!IsClosed());
2376 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08002377 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002378 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
2379 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002380 return;
2381 }
Steve Anton4171afb2017-11-20 10:20:22 -08002382 GetAudioTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002383}
2384
2385void PeerConnection::AddVideoTrack(VideoTrackInterface* track,
2386 MediaStreamInterface* stream) {
2387 RTC_DCHECK(!IsClosed());
2388 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08002389 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002390 // We already have a sender for this track, so just change the stream_id
2391 // so that it's correct in the next call to CreateOffer.
Steve Anton4171afb2017-11-20 10:20:22 -08002392 sender->internal()->set_stream_id(stream->label());
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002393 return;
2394 }
2395
2396 // Normal case; we've never seen this track before.
2397 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender =
2398 RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton75737c02017-11-06 10:37:17 -08002399 signaling_thread(),
2400 new VideoRtpSender(track, {stream->label()}, video_channel()));
Steve Anton4171afb2017-11-20 10:20:22 -08002401 GetVideoTransceiver()->internal()->AddSender(new_sender);
2402 const RtpSenderInfo* sender_info =
2403 FindSenderInfo(local_video_sender_infos_, stream->label(), track->id());
2404 if (sender_info) {
2405 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002406 }
2407}
2408
2409void PeerConnection::RemoveVideoTrack(VideoTrackInterface* track,
2410 MediaStreamInterface* stream) {
2411 RTC_DCHECK(!IsClosed());
2412 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08002413 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002414 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
2415 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002416 return;
2417 }
Steve Anton4171afb2017-11-20 10:20:22 -08002418 GetVideoTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002419}
2420
Steve Antonba818672017-11-06 10:21:57 -08002421void PeerConnection::SetIceConnectionState(IceConnectionState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07002422 RTC_DCHECK(signaling_thread()->IsCurrent());
Steve Antonba818672017-11-06 10:21:57 -08002423 if (ice_connection_state_ == new_state) {
2424 return;
2425 }
2426
deadbeefcbecd352015-09-23 11:50:27 -07002427 // After transitioning to "closed", ignore any additional states from
Steve Antonba818672017-11-06 10:21:57 -08002428 // TransportController (such as "disconnected").
deadbeefab9b2d12015-10-14 11:33:11 -07002429 if (IsClosed()) {
deadbeefcbecd352015-09-23 11:50:27 -07002430 return;
2431 }
Steve Antonba818672017-11-06 10:21:57 -08002432
Mirko Bonadei675513b2017-11-09 11:09:25 +01002433 RTC_LOG(LS_INFO) << "Changing IceConnectionState " << ice_connection_state_
2434 << " => " << new_state;
Steve Antonba818672017-11-06 10:21:57 -08002435 RTC_DCHECK(ice_connection_state_ !=
2436 PeerConnectionInterface::kIceConnectionClosed);
2437
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002438 ice_connection_state_ = new_state;
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00002439 observer_->OnIceConnectionChange(ice_connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002440}
2441
2442void PeerConnection::OnIceGatheringChange(
2443 PeerConnectionInterface::IceGatheringState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07002444 RTC_DCHECK(signaling_thread()->IsCurrent());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002445 if (IsClosed()) {
2446 return;
2447 }
2448 ice_gathering_state_ = new_state;
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00002449 observer_->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002450}
2451
jbauch81bf7b02017-03-25 08:31:12 -07002452void PeerConnection::OnIceCandidate(
2453 std::unique_ptr<IceCandidateInterface> candidate) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07002454 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07002455 if (IsClosed()) {
2456 return;
2457 }
jbauch81bf7b02017-03-25 08:31:12 -07002458 observer_->OnIceCandidate(candidate.get());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002459}
2460
Honghai Zhang7fb69db2016-03-14 11:59:18 -07002461void PeerConnection::OnIceCandidatesRemoved(
2462 const std::vector<cricket::Candidate>& candidates) {
2463 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07002464 if (IsClosed()) {
2465 return;
2466 }
Honghai Zhang7fb69db2016-03-14 11:59:18 -07002467 observer_->OnIceCandidatesRemoved(candidates);
2468}
2469
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002470void PeerConnection::ChangeSignalingState(
2471 PeerConnectionInterface::SignalingState signaling_state) {
Steve Antonba818672017-11-06 10:21:57 -08002472 RTC_DCHECK(signaling_thread()->IsCurrent());
2473 if (signaling_state_ == signaling_state) {
2474 return;
2475 }
Mirko Bonadei675513b2017-11-09 11:09:25 +01002476 RTC_LOG(LS_INFO) << "Session: " << session_id() << " Old state: "
2477 << GetSignalingStateString(signaling_state_)
2478 << " New state: "
2479 << GetSignalingStateString(signaling_state);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002480 signaling_state_ = signaling_state;
2481 if (signaling_state == kClosed) {
2482 ice_connection_state_ = kIceConnectionClosed;
2483 observer_->OnIceConnectionChange(ice_connection_state_);
2484 if (ice_gathering_state_ != kIceGatheringComplete) {
2485 ice_gathering_state_ = kIceGatheringComplete;
2486 observer_->OnIceGatheringChange(ice_gathering_state_);
2487 }
2488 }
2489 observer_->OnSignalingChange(signaling_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002490}
2491
deadbeefeb459812015-12-15 19:24:43 -08002492void PeerConnection::OnAudioTrackAdded(AudioTrackInterface* track,
2493 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07002494 if (IsClosed()) {
2495 return;
2496 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002497 AddAudioTrack(track, stream);
2498 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08002499}
2500
deadbeefeb459812015-12-15 19:24:43 -08002501void PeerConnection::OnAudioTrackRemoved(AudioTrackInterface* track,
2502 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07002503 if (IsClosed()) {
2504 return;
2505 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002506 RemoveAudioTrack(track, stream);
2507 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08002508}
2509
2510void PeerConnection::OnVideoTrackAdded(VideoTrackInterface* track,
2511 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07002512 if (IsClosed()) {
2513 return;
2514 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002515 AddVideoTrack(track, stream);
2516 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08002517}
2518
2519void PeerConnection::OnVideoTrackRemoved(VideoTrackInterface* track,
2520 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07002521 if (IsClosed()) {
2522 return;
2523 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002524 RemoveVideoTrack(track, stream);
2525 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08002526}
2527
Henrik Boström31638672017-11-23 17:48:32 +01002528void PeerConnection::PostSetSessionDescriptionSuccess(
2529 SetSessionDescriptionObserver* observer) {
2530 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
2531 signaling_thread()->Post(RTC_FROM_HERE, this,
2532 MSG_SET_SESSIONDESCRIPTION_SUCCESS, msg);
2533}
2534
deadbeefab9b2d12015-10-14 11:33:11 -07002535void PeerConnection::PostSetSessionDescriptionFailure(
2536 SetSessionDescriptionObserver* observer,
2537 const std::string& error) {
2538 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
2539 msg->error = error;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07002540 signaling_thread()->Post(RTC_FROM_HERE, this,
2541 MSG_SET_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07002542}
2543
2544void PeerConnection::PostCreateSessionDescriptionFailure(
2545 CreateSessionDescriptionObserver* observer,
2546 const std::string& error) {
2547 CreateSessionDescriptionMsg* msg = new CreateSessionDescriptionMsg(observer);
2548 msg->error = error;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07002549 signaling_thread()->Post(RTC_FROM_HERE, this,
2550 MSG_CREATE_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07002551}
2552
zhihuang1c378ed2017-08-17 14:10:50 -07002553void PeerConnection::GetOptionsForOffer(
deadbeefab9b2d12015-10-14 11:33:11 -07002554 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options,
2555 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07002556 ExtractSharedMediaSessionOptions(rtc_options, session_options);
2557
2558 // Figure out transceiver directional preferences.
2559 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
2560 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
2561
2562 // By default, generate sendrecv/recvonly m= sections.
2563 bool recv_audio = true;
2564 bool recv_video = true;
2565
2566 // By default, only offer a new m= section if we have media to send with it.
2567 bool offer_new_audio_description = send_audio;
2568 bool offer_new_video_description = send_video;
2569 bool offer_new_data_description = HasDataChannels();
2570
2571 // The "offer_to_receive_X" options allow those defaults to be overridden.
2572 if (rtc_options.offer_to_receive_audio != RTCOfferAnswerOptions::kUndefined) {
2573 recv_audio = (rtc_options.offer_to_receive_audio > 0);
2574 offer_new_audio_description =
2575 offer_new_audio_description || (rtc_options.offer_to_receive_audio > 0);
2576 }
2577 if (rtc_options.offer_to_receive_video != RTCOfferAnswerOptions::kUndefined) {
2578 recv_video = (rtc_options.offer_to_receive_video > 0);
2579 offer_new_video_description =
2580 offer_new_video_description || (rtc_options.offer_to_receive_video > 0);
2581 }
2582
2583 rtc::Optional<size_t> audio_index;
2584 rtc::Optional<size_t> video_index;
2585 rtc::Optional<size_t> data_index;
2586 // If a current description exists, generate m= sections in the same order,
2587 // using the first audio/video/data section that appears and rejecting
2588 // extraneous ones.
Steve Anton75737c02017-11-06 10:37:17 -08002589 if (local_description()) {
zhihuang1c378ed2017-08-17 14:10:50 -07002590 GenerateMediaDescriptionOptions(
Steve Anton75737c02017-11-06 10:37:17 -08002591 local_description(),
Steve Anton1d03a752017-11-27 14:30:09 -08002592 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
2593 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
2594 &audio_index, &video_index, &data_index, session_options);
deadbeefab9b2d12015-10-14 11:33:11 -07002595 }
2596
zhihuang1c378ed2017-08-17 14:10:50 -07002597 // Add audio/video/data m= sections to the end if needed.
2598 if (!audio_index && offer_new_audio_description) {
2599 session_options->media_description_options.push_back(
2600 cricket::MediaDescriptionOptions(
2601 cricket::MEDIA_TYPE_AUDIO, cricket::CN_AUDIO,
Steve Anton1d03a752017-11-27 14:30:09 -08002602 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
2603 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01002604 audio_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07002605 }
zhihuang1c378ed2017-08-17 14:10:50 -07002606 if (!video_index && offer_new_video_description) {
2607 session_options->media_description_options.push_back(
2608 cricket::MediaDescriptionOptions(
2609 cricket::MEDIA_TYPE_VIDEO, cricket::CN_VIDEO,
Steve Anton1d03a752017-11-27 14:30:09 -08002610 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
2611 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01002612 video_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07002613 }
zhihuang1c378ed2017-08-17 14:10:50 -07002614 if (!data_index && offer_new_data_description) {
2615 session_options->media_description_options.push_back(
2616 cricket::MediaDescriptionOptions(
2617 cricket::MEDIA_TYPE_DATA, cricket::CN_DATA,
Steve Anton1d03a752017-11-27 14:30:09 -08002618 RtpTransceiverDirection::kSendRecv, false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01002619 data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07002620 }
2621
2622 cricket::MediaDescriptionOptions* audio_media_description_options =
2623 !audio_index ? nullptr
2624 : &session_options->media_description_options[*audio_index];
2625 cricket::MediaDescriptionOptions* video_media_description_options =
2626 !video_index ? nullptr
2627 : &session_options->media_description_options[*video_index];
2628 cricket::MediaDescriptionOptions* data_media_description_options =
2629 !data_index ? nullptr
2630 : &session_options->media_description_options[*data_index];
2631
2632 // Apply ICE restart flag and renomination flag.
2633 for (auto& options : session_options->media_description_options) {
2634 options.transport_options.ice_restart = rtc_options.ice_restart;
2635 options.transport_options.enable_ice_renomination =
2636 configuration_.enable_ice_renomination;
2637 }
2638
Steve Anton4171afb2017-11-20 10:20:22 -08002639 AddRtpSenderOptions(GetSendersInternal(), audio_media_description_options,
zhihuang1c378ed2017-08-17 14:10:50 -07002640 video_media_description_options);
2641 AddRtpDataChannelOptions(rtp_data_channels_, data_media_description_options);
deadbeefc80741f2015-10-22 13:14:45 -07002642
zhihuang9763d562016-08-05 11:14:50 -07002643 // Intentionally unset the data channel type for RTP data channel with the
2644 // second condition. Otherwise the RTP data channels would be successfully
2645 // negotiated by default and the unit tests in WebRtcDataBrowserTest will fail
2646 // when building with chromium. We want to leave RTP data channels broken, so
2647 // people won't try to use them.
Steve Anton75737c02017-11-06 10:37:17 -08002648 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
2649 session_options->data_channel_type = data_channel_type();
deadbeefab9b2d12015-10-14 11:33:11 -07002650 }
zhihuang8f65cdf2016-05-06 18:40:30 -07002651
2652 session_options->rtcp_cname = rtcp_cname_;
jbauchcb560652016-08-04 05:20:32 -07002653 session_options->crypto_options = factory_->options().crypto_options;
deadbeefab9b2d12015-10-14 11:33:11 -07002654}
2655
zhihuang1c378ed2017-08-17 14:10:50 -07002656void PeerConnection::GetOptionsForAnswer(
2657 const RTCOfferAnswerOptions& rtc_options,
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07002658 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07002659 ExtractSharedMediaSessionOptions(rtc_options, session_options);
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07002660
zhihuang1c378ed2017-08-17 14:10:50 -07002661 // Figure out transceiver directional preferences.
2662 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
2663 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
2664
2665 // By default, generate sendrecv/recvonly m= sections. The direction is also
2666 // restricted by the direction in the offer.
2667 bool recv_audio = true;
2668 bool recv_video = true;
2669
2670 // The "offer_to_receive_X" options allow those defaults to be overridden.
2671 if (rtc_options.offer_to_receive_audio != RTCOfferAnswerOptions::kUndefined) {
2672 recv_audio = (rtc_options.offer_to_receive_audio > 0);
deadbeef0ed85b22016-02-23 17:24:52 -08002673 }
zhihuang1c378ed2017-08-17 14:10:50 -07002674 if (rtc_options.offer_to_receive_video != RTCOfferAnswerOptions::kUndefined) {
2675 recv_video = (rtc_options.offer_to_receive_video > 0);
2676 }
2677
2678 rtc::Optional<size_t> audio_index;
2679 rtc::Optional<size_t> video_index;
2680 rtc::Optional<size_t> data_index;
Steve Anton75737c02017-11-06 10:37:17 -08002681 if (remote_description()) {
zhihuang141aacb2017-08-29 13:23:53 -07002682 // The pending remote description should be an offer.
Steve Antona3a92c22017-12-07 10:27:41 -08002683 RTC_DCHECK(remote_description()->GetType() == SdpType::kOffer);
zhihuang141aacb2017-08-29 13:23:53 -07002684 // Generate m= sections that match those in the offer.
2685 // Note that mediasession.cc will handle intersection our preferred
2686 // direction with the offered direction.
2687 GenerateMediaDescriptionOptions(
Steve Anton75737c02017-11-06 10:37:17 -08002688 remote_description(),
Steve Anton1d03a752017-11-27 14:30:09 -08002689 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
2690 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
2691 &audio_index, &video_index, &data_index, session_options);
zhihuang141aacb2017-08-29 13:23:53 -07002692 }
zhihuang1c378ed2017-08-17 14:10:50 -07002693
2694 cricket::MediaDescriptionOptions* audio_media_description_options =
2695 !audio_index ? nullptr
2696 : &session_options->media_description_options[*audio_index];
2697 cricket::MediaDescriptionOptions* video_media_description_options =
2698 !video_index ? nullptr
2699 : &session_options->media_description_options[*video_index];
2700 cricket::MediaDescriptionOptions* data_media_description_options =
2701 !data_index ? nullptr
2702 : &session_options->media_description_options[*data_index];
2703
2704 // Apply ICE renomination flag.
2705 for (auto& options : session_options->media_description_options) {
2706 options.transport_options.enable_ice_renomination =
2707 configuration_.enable_ice_renomination;
2708 }
2709
Steve Anton4171afb2017-11-20 10:20:22 -08002710 AddRtpSenderOptions(GetSendersInternal(), audio_media_description_options,
zhihuang1c378ed2017-08-17 14:10:50 -07002711 video_media_description_options);
2712 AddRtpDataChannelOptions(rtp_data_channels_, data_media_description_options);
2713
zhihuang9763d562016-08-05 11:14:50 -07002714 // Intentionally unset the data channel type for RTP data channel. Otherwise
2715 // the RTP data channels would be successfully negotiated by default and the
2716 // unit tests in WebRtcDataBrowserTest will fail when building with chromium.
2717 // We want to leave RTP data channels broken, so people won't try to use them.
Steve Anton75737c02017-11-06 10:37:17 -08002718 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
2719 session_options->data_channel_type = data_channel_type();
deadbeef907abe42016-08-04 12:22:18 -07002720 }
zhihuangaf388472016-11-02 16:49:48 -07002721
zhihuang1c378ed2017-08-17 14:10:50 -07002722 session_options->rtcp_cname = rtcp_cname_;
jbauchcb560652016-08-04 05:20:32 -07002723 session_options->crypto_options = factory_->options().crypto_options;
htaa2a49d92016-03-04 02:51:39 -08002724}
2725
zhihuang1c378ed2017-08-17 14:10:50 -07002726void PeerConnection::GenerateMediaDescriptionOptions(
2727 const SessionDescriptionInterface* session_desc,
Steve Anton1d03a752017-11-27 14:30:09 -08002728 RtpTransceiverDirection audio_direction,
2729 RtpTransceiverDirection video_direction,
zhihuang1c378ed2017-08-17 14:10:50 -07002730 rtc::Optional<size_t>* audio_index,
2731 rtc::Optional<size_t>* video_index,
2732 rtc::Optional<size_t>* data_index,
htaa2a49d92016-03-04 02:51:39 -08002733 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07002734 for (const cricket::ContentInfo& content :
2735 session_desc->description()->contents()) {
2736 if (IsAudioContent(&content)) {
2737 // If we already have an audio m= section, reject this extra one.
2738 if (*audio_index) {
2739 session_options->media_description_options.push_back(
2740 cricket::MediaDescriptionOptions(
2741 cricket::MEDIA_TYPE_AUDIO, content.name,
Steve Anton1d03a752017-11-27 14:30:09 -08002742 RtpTransceiverDirection::kInactive, true));
zhihuang1c378ed2017-08-17 14:10:50 -07002743 } else {
2744 session_options->media_description_options.push_back(
2745 cricket::MediaDescriptionOptions(
2746 cricket::MEDIA_TYPE_AUDIO, content.name, audio_direction,
Steve Anton1d03a752017-11-27 14:30:09 -08002747 audio_direction == RtpTransceiverDirection::kInactive));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01002748 *audio_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07002749 }
2750 } else if (IsVideoContent(&content)) {
2751 // If we already have an video m= section, reject this extra one.
2752 if (*video_index) {
2753 session_options->media_description_options.push_back(
2754 cricket::MediaDescriptionOptions(
2755 cricket::MEDIA_TYPE_VIDEO, content.name,
Steve Anton1d03a752017-11-27 14:30:09 -08002756 RtpTransceiverDirection::kInactive, true));
zhihuang1c378ed2017-08-17 14:10:50 -07002757 } else {
2758 session_options->media_description_options.push_back(
2759 cricket::MediaDescriptionOptions(
2760 cricket::MEDIA_TYPE_VIDEO, content.name, video_direction,
Steve Anton1d03a752017-11-27 14:30:09 -08002761 video_direction == RtpTransceiverDirection::kInactive));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01002762 *video_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07002763 }
2764 } else {
2765 RTC_DCHECK(IsDataContent(&content));
2766 // If we already have an data m= section, reject this extra one.
2767 if (*data_index) {
2768 session_options->media_description_options.push_back(
2769 cricket::MediaDescriptionOptions(
2770 cricket::MEDIA_TYPE_DATA, content.name,
Steve Anton1d03a752017-11-27 14:30:09 -08002771 RtpTransceiverDirection::kInactive, true));
zhihuang1c378ed2017-08-17 14:10:50 -07002772 } else {
2773 session_options->media_description_options.push_back(
2774 cricket::MediaDescriptionOptions(
2775 cricket::MEDIA_TYPE_DATA, content.name,
2776 // Direction for data sections is meaningless, but legacy
2777 // endpoints might expect sendrecv.
Steve Anton1d03a752017-11-27 14:30:09 -08002778 RtpTransceiverDirection::kSendRecv, false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01002779 *data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07002780 }
2781 }
htaa2a49d92016-03-04 02:51:39 -08002782 }
deadbeefab9b2d12015-10-14 11:33:11 -07002783}
2784
Steve Anton4171afb2017-11-20 10:20:22 -08002785void PeerConnection::RemoveSenders(cricket::MediaType media_type) {
2786 UpdateLocalSenders(std::vector<cricket::StreamParams>(), media_type);
2787 UpdateRemoteSendersList(std::vector<cricket::StreamParams>(), false,
deadbeefbda7e0b2015-12-08 17:13:40 -08002788 media_type, nullptr);
deadbeeffaac4972015-11-12 15:33:07 -08002789}
2790
Steve Anton4171afb2017-11-20 10:20:22 -08002791void PeerConnection::UpdateRemoteSendersList(
deadbeefab9b2d12015-10-14 11:33:11 -07002792 const cricket::StreamParamsVec& streams,
Steve Anton4171afb2017-11-20 10:20:22 -08002793 bool default_sender_needed,
deadbeefab9b2d12015-10-14 11:33:11 -07002794 cricket::MediaType media_type,
2795 StreamCollection* new_streams) {
Steve Anton4171afb2017-11-20 10:20:22 -08002796 std::vector<RtpSenderInfo>* current_senders =
2797 GetRemoteSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07002798
Steve Anton4171afb2017-11-20 10:20:22 -08002799 // Find removed senders. I.e., senders where the sender id or ssrc don't match
deadbeeffac06552015-11-25 11:26:01 -08002800 // the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08002801 for (auto sender_it = current_senders->begin();
2802 sender_it != current_senders->end();
2803 /* incremented manually */) {
2804 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07002805 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08002806 cricket::GetStreamBySsrc(streams, info.first_ssrc);
2807 bool sender_exists = params && params->id == info.sender_id;
deadbeefbda7e0b2015-12-08 17:13:40 -08002808 // If this is a default track, and we still need it, don't remove it.
Steve Anton4171afb2017-11-20 10:20:22 -08002809 if ((info.stream_label == kDefaultStreamLabel && default_sender_needed) ||
2810 sender_exists) {
2811 ++sender_it;
deadbeefbda7e0b2015-12-08 17:13:40 -08002812 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08002813 OnRemoteSenderRemoved(info, media_type);
2814 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07002815 }
2816 }
2817
Steve Anton4171afb2017-11-20 10:20:22 -08002818 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07002819 for (const cricket::StreamParams& params : streams) {
2820 // The sync_label is the MediaStream label and the |stream.id| is the
Steve Anton4171afb2017-11-20 10:20:22 -08002821 // sender id.
deadbeefab9b2d12015-10-14 11:33:11 -07002822 const std::string& stream_label = params.sync_label;
Steve Anton4171afb2017-11-20 10:20:22 -08002823 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07002824 uint32_t ssrc = params.first_ssrc();
2825
2826 rtc::scoped_refptr<MediaStreamInterface> stream =
2827 remote_streams_->find(stream_label);
2828 if (!stream) {
2829 // This is a new MediaStream. Create a new remote MediaStream.
perkjd61bf802016-03-24 03:16:19 -07002830 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
2831 MediaStream::Create(stream_label));
deadbeefab9b2d12015-10-14 11:33:11 -07002832 remote_streams_->AddStream(stream);
2833 new_streams->AddStream(stream);
2834 }
2835
Steve Anton4171afb2017-11-20 10:20:22 -08002836 const RtpSenderInfo* sender_info =
2837 FindSenderInfo(*current_senders, stream_label, sender_id);
2838 if (!sender_info) {
2839 current_senders->push_back(RtpSenderInfo(stream_label, sender_id, ssrc));
2840 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07002841 }
2842 }
deadbeefbda7e0b2015-12-08 17:13:40 -08002843
Steve Anton4171afb2017-11-20 10:20:22 -08002844 // Add default sender if necessary.
2845 if (default_sender_needed) {
deadbeefbda7e0b2015-12-08 17:13:40 -08002846 rtc::scoped_refptr<MediaStreamInterface> default_stream =
2847 remote_streams_->find(kDefaultStreamLabel);
2848 if (!default_stream) {
2849 // Create the new default MediaStream.
perkjd61bf802016-03-24 03:16:19 -07002850 default_stream = MediaStreamProxy::Create(
2851 rtc::Thread::Current(), MediaStream::Create(kDefaultStreamLabel));
deadbeefbda7e0b2015-12-08 17:13:40 -08002852 remote_streams_->AddStream(default_stream);
2853 new_streams->AddStream(default_stream);
2854 }
Steve Anton4171afb2017-11-20 10:20:22 -08002855 std::string default_sender_id = (media_type == cricket::MEDIA_TYPE_AUDIO)
2856 ? kDefaultAudioSenderId
2857 : kDefaultVideoSenderId;
2858 const RtpSenderInfo* default_sender_info = FindSenderInfo(
2859 *current_senders, kDefaultStreamLabel, default_sender_id);
2860 if (!default_sender_info) {
2861 current_senders->push_back(
2862 RtpSenderInfo(kDefaultStreamLabel, default_sender_id, 0));
2863 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefbda7e0b2015-12-08 17:13:40 -08002864 }
2865 }
deadbeefab9b2d12015-10-14 11:33:11 -07002866}
2867
Steve Anton4171afb2017-11-20 10:20:22 -08002868void PeerConnection::OnRemoteSenderAdded(const RtpSenderInfo& sender_info,
2869 cricket::MediaType media_type) {
2870 MediaStreamInterface* stream =
2871 remote_streams_->find(sender_info.stream_label);
deadbeefab9b2d12015-10-14 11:33:11 -07002872
2873 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 10:20:22 -08002874 CreateAudioReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07002875 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 10:20:22 -08002876 CreateVideoReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07002877 } else {
nisseeb4ca4e2017-01-12 02:24:27 -08002878 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07002879 }
2880}
2881
Steve Anton4171afb2017-11-20 10:20:22 -08002882void PeerConnection::OnRemoteSenderRemoved(const RtpSenderInfo& sender_info,
2883 cricket::MediaType media_type) {
2884 MediaStreamInterface* stream =
2885 remote_streams_->find(sender_info.stream_label);
deadbeefab9b2d12015-10-14 11:33:11 -07002886
Henrik Boström933d8b02017-10-10 10:05:16 -07002887 rtc::scoped_refptr<RtpReceiverInterface> receiver;
deadbeefab9b2d12015-10-14 11:33:11 -07002888 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
perkjd61bf802016-03-24 03:16:19 -07002889 // When the MediaEngine audio channel is destroyed, the RemoteAudioSource
2890 // will be notified which will end the AudioRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08002891 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07002892 rtc::scoped_refptr<AudioTrackInterface> audio_track =
Steve Anton4171afb2017-11-20 10:20:22 -08002893 stream->FindAudioTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07002894 if (audio_track) {
deadbeefab9b2d12015-10-14 11:33:11 -07002895 stream->RemoveTrack(audio_track);
deadbeefab9b2d12015-10-14 11:33:11 -07002896 }
2897 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
perkjd61bf802016-03-24 03:16:19 -07002898 // Stopping or destroying a VideoRtpReceiver will end the
2899 // VideoRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08002900 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07002901 rtc::scoped_refptr<VideoTrackInterface> video_track =
Steve Anton4171afb2017-11-20 10:20:22 -08002902 stream->FindVideoTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07002903 if (video_track) {
perkjd61bf802016-03-24 03:16:19 -07002904 // There's no guarantee the track is still available, e.g. the track may
2905 // have been removed from the stream by an application.
deadbeefab9b2d12015-10-14 11:33:11 -07002906 stream->RemoveTrack(video_track);
deadbeefab9b2d12015-10-14 11:33:11 -07002907 }
2908 } else {
nisseede5da42017-01-12 05:15:36 -08002909 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07002910 }
Henrik Boström933d8b02017-10-10 10:05:16 -07002911 if (receiver) {
2912 observer_->OnRemoveTrack(receiver);
2913 }
deadbeefab9b2d12015-10-14 11:33:11 -07002914}
2915
2916void PeerConnection::UpdateEndedRemoteMediaStreams() {
2917 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams_to_remove;
2918 for (size_t i = 0; i < remote_streams_->count(); ++i) {
2919 MediaStreamInterface* stream = remote_streams_->at(i);
2920 if (stream->GetAudioTracks().empty() && stream->GetVideoTracks().empty()) {
2921 streams_to_remove.push_back(stream);
2922 }
2923 }
2924
Taylor Brandstetter98cde262016-05-31 13:02:21 -07002925 for (auto& stream : streams_to_remove) {
deadbeefab9b2d12015-10-14 11:33:11 -07002926 remote_streams_->RemoveStream(stream);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07002927 observer_->OnRemoveStream(std::move(stream));
deadbeefab9b2d12015-10-14 11:33:11 -07002928 }
2929}
2930
Steve Anton4171afb2017-11-20 10:20:22 -08002931void PeerConnection::UpdateLocalSenders(
deadbeefab9b2d12015-10-14 11:33:11 -07002932 const std::vector<cricket::StreamParams>& streams,
2933 cricket::MediaType media_type) {
Steve Anton4171afb2017-11-20 10:20:22 -08002934 std::vector<RtpSenderInfo>* current_senders = GetLocalSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07002935
2936 // Find removed tracks. I.e., tracks where the track id, stream label or ssrc
2937 // don't match the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08002938 for (auto sender_it = current_senders->begin();
2939 sender_it != current_senders->end();
2940 /* incremented manually */) {
2941 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07002942 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08002943 cricket::GetStreamBySsrc(streams, info.first_ssrc);
2944 if (!params || params->id != info.sender_id ||
deadbeefab9b2d12015-10-14 11:33:11 -07002945 params->sync_label != info.stream_label) {
Steve Anton4171afb2017-11-20 10:20:22 -08002946 OnLocalSenderRemoved(info, media_type);
2947 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07002948 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08002949 ++sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07002950 }
2951 }
2952
Steve Anton4171afb2017-11-20 10:20:22 -08002953 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07002954 for (const cricket::StreamParams& params : streams) {
2955 // The sync_label is the MediaStream label and the |stream.id| is the
Steve Anton4171afb2017-11-20 10:20:22 -08002956 // sender id.
deadbeefab9b2d12015-10-14 11:33:11 -07002957 const std::string& stream_label = params.sync_label;
Steve Anton4171afb2017-11-20 10:20:22 -08002958 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07002959 uint32_t ssrc = params.first_ssrc();
Steve Anton4171afb2017-11-20 10:20:22 -08002960 const RtpSenderInfo* sender_info =
2961 FindSenderInfo(*current_senders, stream_label, sender_id);
2962 if (!sender_info) {
2963 current_senders->push_back(RtpSenderInfo(stream_label, sender_id, ssrc));
2964 OnLocalSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07002965 }
2966 }
2967}
2968
Steve Anton4171afb2017-11-20 10:20:22 -08002969void PeerConnection::OnLocalSenderAdded(const RtpSenderInfo& sender_info,
2970 cricket::MediaType media_type) {
2971 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08002972 if (!sender) {
Steve Anton4171afb2017-11-20 10:20:22 -08002973 RTC_LOG(LS_WARNING) << "An unknown RtpSender with id "
2974 << sender_info.sender_id
Mirko Bonadei675513b2017-11-09 11:09:25 +01002975 << " has been configured in the local description.";
deadbeefab9b2d12015-10-14 11:33:11 -07002976 return;
2977 }
2978
deadbeeffac06552015-11-25 11:26:01 -08002979 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002980 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
2981 << " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08002982 return;
deadbeefab9b2d12015-10-14 11:33:11 -07002983 }
deadbeeffac06552015-11-25 11:26:01 -08002984
Steve Anton4171afb2017-11-20 10:20:22 -08002985 sender->internal()->set_stream_id(sender_info.stream_label);
2986 sender->internal()->SetSsrc(sender_info.first_ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07002987}
2988
Steve Anton4171afb2017-11-20 10:20:22 -08002989void PeerConnection::OnLocalSenderRemoved(const RtpSenderInfo& sender_info,
2990 cricket::MediaType media_type) {
2991 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08002992 if (!sender) {
2993 // This is the normal case. I.e., RemoveStream has been called and the
deadbeefab9b2d12015-10-14 11:33:11 -07002994 // SessionDescriptions has been renegotiated.
2995 return;
2996 }
deadbeeffac06552015-11-25 11:26:01 -08002997
2998 // A sender has been removed from the SessionDescription but it's still
2999 // associated with the PeerConnection. This only occurs if the SDP doesn't
3000 // match with the calls to CreateSender, AddStream and RemoveStream.
3001 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003002 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
3003 << " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08003004 return;
deadbeefab9b2d12015-10-14 11:33:11 -07003005 }
deadbeeffac06552015-11-25 11:26:01 -08003006
Steve Anton4171afb2017-11-20 10:20:22 -08003007 sender->internal()->SetSsrc(0);
deadbeefab9b2d12015-10-14 11:33:11 -07003008}
3009
3010void PeerConnection::UpdateLocalRtpDataChannels(
3011 const cricket::StreamParamsVec& streams) {
3012 std::vector<std::string> existing_channels;
3013
3014 // Find new and active data channels.
3015 for (const cricket::StreamParams& params : streams) {
3016 // |it->sync_label| is actually the data channel label. The reason is that
3017 // we use the same naming of data channels as we do for
3018 // MediaStreams and Tracks.
3019 // For MediaStreams, the sync_label is the MediaStream label and the
3020 // track label is the same as |streamid|.
3021 const std::string& channel_label = params.sync_label;
3022 auto data_channel_it = rtp_data_channels_.find(channel_label);
nisse7ce109a2017-01-31 00:57:56 -08003023 if (data_channel_it == rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003024 RTC_LOG(LS_ERROR) << "channel label not found";
deadbeefab9b2d12015-10-14 11:33:11 -07003025 continue;
3026 }
3027 // Set the SSRC the data channel should use for sending.
3028 data_channel_it->second->SetSendSsrc(params.first_ssrc());
3029 existing_channels.push_back(data_channel_it->first);
3030 }
3031
3032 UpdateClosingRtpDataChannels(existing_channels, true);
3033}
3034
3035void PeerConnection::UpdateRemoteRtpDataChannels(
3036 const cricket::StreamParamsVec& streams) {
3037 std::vector<std::string> existing_channels;
3038
3039 // Find new and active data channels.
3040 for (const cricket::StreamParams& params : streams) {
3041 // The data channel label is either the mslabel or the SSRC if the mslabel
3042 // does not exist. Ex a=ssrc:444330170 mslabel:test1.
3043 std::string label = params.sync_label.empty()
3044 ? rtc::ToString(params.first_ssrc())
3045 : params.sync_label;
3046 auto data_channel_it = rtp_data_channels_.find(label);
3047 if (data_channel_it == rtp_data_channels_.end()) {
3048 // This is a new data channel.
3049 CreateRemoteRtpDataChannel(label, params.first_ssrc());
3050 } else {
3051 data_channel_it->second->SetReceiveSsrc(params.first_ssrc());
3052 }
3053 existing_channels.push_back(label);
3054 }
3055
3056 UpdateClosingRtpDataChannels(existing_channels, false);
3057}
3058
3059void PeerConnection::UpdateClosingRtpDataChannels(
3060 const std::vector<std::string>& active_channels,
3061 bool is_local_update) {
3062 auto it = rtp_data_channels_.begin();
3063 while (it != rtp_data_channels_.end()) {
3064 DataChannel* data_channel = it->second;
3065 if (std::find(active_channels.begin(), active_channels.end(),
3066 data_channel->label()) != active_channels.end()) {
3067 ++it;
3068 continue;
3069 }
3070
3071 if (is_local_update) {
3072 data_channel->SetSendSsrc(0);
3073 } else {
3074 data_channel->RemotePeerRequestClose();
3075 }
3076
3077 if (data_channel->state() == DataChannel::kClosed) {
3078 rtp_data_channels_.erase(it);
3079 it = rtp_data_channels_.begin();
3080 } else {
3081 ++it;
3082 }
3083 }
3084}
3085
3086void PeerConnection::CreateRemoteRtpDataChannel(const std::string& label,
3087 uint32_t remote_ssrc) {
3088 rtc::scoped_refptr<DataChannel> channel(
3089 InternalCreateDataChannel(label, nullptr));
3090 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003091 RTC_LOG(LS_WARNING) << "Remote peer requested a DataChannel but"
3092 << "CreateDataChannel failed.";
deadbeefab9b2d12015-10-14 11:33:11 -07003093 return;
3094 }
3095 channel->SetReceiveSsrc(remote_ssrc);
deadbeefa601f5c2016-06-06 14:27:39 -07003096 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
3097 DataChannelProxy::Create(signaling_thread(), channel);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07003098 observer_->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07003099}
3100
3101rtc::scoped_refptr<DataChannel> PeerConnection::InternalCreateDataChannel(
3102 const std::string& label,
3103 const InternalDataChannelInit* config) {
3104 if (IsClosed()) {
3105 return nullptr;
3106 }
Steve Anton75737c02017-11-06 10:37:17 -08003107 if (data_channel_type() == cricket::DCT_NONE) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003108 RTC_LOG(LS_ERROR)
deadbeefab9b2d12015-10-14 11:33:11 -07003109 << "InternalCreateDataChannel: Data is not supported in this call.";
3110 return nullptr;
3111 }
3112 InternalDataChannelInit new_config =
3113 config ? (*config) : InternalDataChannelInit();
Steve Anton75737c02017-11-06 10:37:17 -08003114 if (data_channel_type() == cricket::DCT_SCTP) {
deadbeefab9b2d12015-10-14 11:33:11 -07003115 if (new_config.id < 0) {
3116 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08003117 if ((GetSctpSslRole(&role)) &&
deadbeefab9b2d12015-10-14 11:33:11 -07003118 !sid_allocator_.AllocateSid(role, &new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003119 RTC_LOG(LS_ERROR)
3120 << "No id can be allocated for the SCTP data channel.";
deadbeefab9b2d12015-10-14 11:33:11 -07003121 return nullptr;
3122 }
3123 } else if (!sid_allocator_.ReserveSid(new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003124 RTC_LOG(LS_ERROR) << "Failed to create a SCTP data channel "
3125 << "because the id is already in use or out of range.";
deadbeefab9b2d12015-10-14 11:33:11 -07003126 return nullptr;
3127 }
3128 }
3129
Steve Anton75737c02017-11-06 10:37:17 -08003130 rtc::scoped_refptr<DataChannel> channel(
3131 DataChannel::Create(this, data_channel_type(), label, new_config));
deadbeefab9b2d12015-10-14 11:33:11 -07003132 if (!channel) {
3133 sid_allocator_.ReleaseSid(new_config.id);
3134 return nullptr;
3135 }
3136
3137 if (channel->data_channel_type() == cricket::DCT_RTP) {
3138 if (rtp_data_channels_.find(channel->label()) != rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003139 RTC_LOG(LS_ERROR) << "DataChannel with label " << channel->label()
3140 << " already exists.";
deadbeefab9b2d12015-10-14 11:33:11 -07003141 return nullptr;
3142 }
3143 rtp_data_channels_[channel->label()] = channel;
3144 } else {
3145 RTC_DCHECK(channel->data_channel_type() == cricket::DCT_SCTP);
3146 sctp_data_channels_.push_back(channel);
3147 channel->SignalClosed.connect(this,
3148 &PeerConnection::OnSctpDataChannelClosed);
3149 }
3150
hbos82ebe022016-11-14 01:41:09 -08003151 SignalDataChannelCreated(channel.get());
deadbeefab9b2d12015-10-14 11:33:11 -07003152 return channel;
3153}
3154
3155bool PeerConnection::HasDataChannels() const {
3156 return !rtp_data_channels_.empty() || !sctp_data_channels_.empty();
3157}
3158
3159void PeerConnection::AllocateSctpSids(rtc::SSLRole role) {
3160 for (const auto& channel : sctp_data_channels_) {
3161 if (channel->id() < 0) {
3162 int sid;
3163 if (!sid_allocator_.AllocateSid(role, &sid)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003164 RTC_LOG(LS_ERROR) << "Failed to allocate SCTP sid.";
deadbeefab9b2d12015-10-14 11:33:11 -07003165 continue;
3166 }
3167 channel->SetSctpSid(sid);
3168 }
3169 }
3170}
3171
3172void PeerConnection::OnSctpDataChannelClosed(DataChannel* channel) {
deadbeefbd292462015-12-14 18:15:29 -08003173 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeefab9b2d12015-10-14 11:33:11 -07003174 for (auto it = sctp_data_channels_.begin(); it != sctp_data_channels_.end();
3175 ++it) {
3176 if (it->get() == channel) {
3177 if (channel->id() >= 0) {
3178 sid_allocator_.ReleaseSid(channel->id());
3179 }
deadbeefbd292462015-12-14 18:15:29 -08003180 // Since this method is triggered by a signal from the DataChannel,
3181 // we can't free it directly here; we need to free it asynchronously.
3182 sctp_data_channels_to_free_.push_back(*it);
deadbeefab9b2d12015-10-14 11:33:11 -07003183 sctp_data_channels_.erase(it);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07003184 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_FREE_DATACHANNELS,
3185 nullptr);
deadbeefab9b2d12015-10-14 11:33:11 -07003186 return;
3187 }
3188 }
3189}
3190
deadbeefab9b2d12015-10-14 11:33:11 -07003191void PeerConnection::OnDataChannelDestroyed() {
3192 // Use a temporary copy of the RTP/SCTP DataChannel list because the
3193 // DataChannel may callback to us and try to modify the list.
3194 std::map<std::string, rtc::scoped_refptr<DataChannel>> temp_rtp_dcs;
3195 temp_rtp_dcs.swap(rtp_data_channels_);
3196 for (const auto& kv : temp_rtp_dcs) {
3197 kv.second->OnTransportChannelDestroyed();
3198 }
3199
3200 std::vector<rtc::scoped_refptr<DataChannel>> temp_sctp_dcs;
3201 temp_sctp_dcs.swap(sctp_data_channels_);
3202 for (const auto& channel : temp_sctp_dcs) {
3203 channel->OnTransportChannelDestroyed();
3204 }
3205}
3206
3207void PeerConnection::OnDataChannelOpenMessage(
3208 const std::string& label,
3209 const InternalDataChannelInit& config) {
3210 rtc::scoped_refptr<DataChannel> channel(
3211 InternalCreateDataChannel(label, &config));
3212 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003213 RTC_LOG(LS_ERROR) << "Failed to create DataChannel from the OPEN message.";
deadbeefab9b2d12015-10-14 11:33:11 -07003214 return;
3215 }
3216
deadbeefa601f5c2016-06-06 14:27:39 -07003217 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
3218 DataChannelProxy::Create(signaling_thread(), channel);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07003219 observer_->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07003220}
3221
Steve Anton4171afb2017-11-20 10:20:22 -08003222rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3223PeerConnection::GetAudioTransceiver() const {
3224 // This method only works with Plan B SDP, where there is a single
3225 // audio/video transceiver.
3226 RTC_DCHECK(!IsUnifiedPlan());
3227 for (auto transceiver : transceivers_) {
3228 if (transceiver->internal()->media_type() == cricket::MEDIA_TYPE_AUDIO) {
3229 return transceiver;
3230 }
3231 }
3232 RTC_NOTREACHED();
3233 return nullptr;
3234}
3235
3236rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3237PeerConnection::GetVideoTransceiver() const {
3238 // This method only works with Plan B SDP, where there is a single
3239 // audio/video transceiver.
3240 RTC_DCHECK(!IsUnifiedPlan());
3241 for (auto transceiver : transceivers_) {
3242 if (transceiver->internal()->media_type() == cricket::MEDIA_TYPE_VIDEO) {
3243 return transceiver;
3244 }
3245 }
3246 RTC_NOTREACHED();
3247 return nullptr;
3248}
3249
3250// TODO(bugs.webrtc.org/7600): Remove this when multiple transceivers with
3251// individual transceiver directions are supported.
zhihuang1c378ed2017-08-17 14:10:50 -07003252bool PeerConnection::HasRtpSender(cricket::MediaType type) const {
Steve Anton4171afb2017-11-20 10:20:22 -08003253 switch (type) {
3254 case cricket::MEDIA_TYPE_AUDIO:
3255 return !GetAudioTransceiver()->internal()->senders().empty();
3256 case cricket::MEDIA_TYPE_VIDEO:
3257 return !GetVideoTransceiver()->internal()->senders().empty();
3258 case cricket::MEDIA_TYPE_DATA:
3259 return false;
3260 }
3261 RTC_NOTREACHED();
3262 return false;
zhihuang1c378ed2017-08-17 14:10:50 -07003263}
3264
Steve Anton4171afb2017-11-20 10:20:22 -08003265rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
3266PeerConnection::FindSenderForTrack(MediaStreamTrackInterface* track) const {
3267 for (auto transceiver : transceivers_) {
3268 for (auto sender : transceiver->internal()->senders()) {
3269 if (sender->track() == track) {
3270 return sender;
3271 }
3272 }
3273 }
3274 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08003275}
3276
Steve Anton4171afb2017-11-20 10:20:22 -08003277rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
3278PeerConnection::FindSenderById(const std::string& sender_id) const {
3279 for (auto transceiver : transceivers_) {
3280 for (auto sender : transceiver->internal()->senders()) {
3281 if (sender->id() == sender_id) {
3282 return sender;
3283 }
3284 }
3285 }
3286 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07003287}
3288
Steve Anton4171afb2017-11-20 10:20:22 -08003289rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
3290PeerConnection::FindReceiverById(const std::string& receiver_id) const {
3291 for (auto transceiver : transceivers_) {
3292 for (auto receiver : transceiver->internal()->receivers()) {
3293 if (receiver->id() == receiver_id) {
3294 return receiver;
3295 }
3296 }
3297 }
3298 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07003299}
3300
Steve Anton4171afb2017-11-20 10:20:22 -08003301std::vector<PeerConnection::RtpSenderInfo>*
3302PeerConnection::GetRemoteSenderInfos(cricket::MediaType media_type) {
3303 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
3304 media_type == cricket::MEDIA_TYPE_VIDEO);
3305 return (media_type == cricket::MEDIA_TYPE_AUDIO)
3306 ? &remote_audio_sender_infos_
3307 : &remote_video_sender_infos_;
3308}
3309
3310std::vector<PeerConnection::RtpSenderInfo>* PeerConnection::GetLocalSenderInfos(
deadbeefab9b2d12015-10-14 11:33:11 -07003311 cricket::MediaType media_type) {
3312 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
3313 media_type == cricket::MEDIA_TYPE_VIDEO);
Steve Anton4171afb2017-11-20 10:20:22 -08003314 return (media_type == cricket::MEDIA_TYPE_AUDIO) ? &local_audio_sender_infos_
3315 : &local_video_sender_infos_;
deadbeefab9b2d12015-10-14 11:33:11 -07003316}
3317
Steve Anton4171afb2017-11-20 10:20:22 -08003318const PeerConnection::RtpSenderInfo* PeerConnection::FindSenderInfo(
3319 const std::vector<PeerConnection::RtpSenderInfo>& infos,
deadbeefab9b2d12015-10-14 11:33:11 -07003320 const std::string& stream_label,
Steve Anton4171afb2017-11-20 10:20:22 -08003321 const std::string sender_id) const {
3322 for (const RtpSenderInfo& sender_info : infos) {
3323 if (sender_info.stream_label == stream_label &&
3324 sender_info.sender_id == sender_id) {
3325 return &sender_info;
deadbeefab9b2d12015-10-14 11:33:11 -07003326 }
3327 }
3328 return nullptr;
3329}
3330
3331DataChannel* PeerConnection::FindDataChannelBySid(int sid) const {
3332 for (const auto& channel : sctp_data_channels_) {
3333 if (channel->id() == sid) {
3334 return channel;
3335 }
3336 }
3337 return nullptr;
3338}
3339
deadbeef91dd5672016-05-18 16:55:30 -07003340bool PeerConnection::InitializePortAllocator_n(
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003341 const RTCConfiguration& configuration) {
3342 cricket::ServerAddresses stun_servers;
3343 std::vector<cricket::RelayServerConfig> turn_servers;
deadbeef293e9262017-01-11 12:28:30 -08003344 if (ParseIceServers(configuration.servers, &stun_servers, &turn_servers) !=
3345 RTCErrorType::NONE) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003346 return false;
3347 }
3348
Taylor Brandstetterf8e65772016-06-27 17:20:15 -07003349 port_allocator_->Initialize();
3350
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003351 // To handle both internal and externally created port allocator, we will
3352 // enable BUNDLE here.
3353 int portallocator_flags = port_allocator_->flags();
3354 portallocator_flags |= cricket::PORTALLOCATOR_ENABLE_SHARED_SOCKET |
zhihuangb09b3f92017-03-07 14:40:51 -08003355 cricket::PORTALLOCATOR_ENABLE_IPV6 |
3356 cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI;
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003357 // If the disable-IPv6 flag was specified, we'll not override it
3358 // by experiment.
3359 if (configuration.disable_ipv6) {
3360 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
sprangc1b57a12017-02-28 08:50:47 -08003361 } else if (webrtc::field_trial::FindFullName("WebRTC-IPv6Default")
3362 .find("Disabled") == 0) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003363 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
3364 }
3365
zhihuangb09b3f92017-03-07 14:40:51 -08003366 if (configuration.disable_ipv6_on_wifi) {
3367 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI);
Mirko Bonadei675513b2017-11-09 11:09:25 +01003368 RTC_LOG(LS_INFO) << "IPv6 candidates on Wi-Fi are disabled.";
zhihuangb09b3f92017-03-07 14:40:51 -08003369 }
3370
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003371 if (configuration.tcp_candidate_policy == kTcpCandidatePolicyDisabled) {
3372 portallocator_flags |= cricket::PORTALLOCATOR_DISABLE_TCP;
Mirko Bonadei675513b2017-11-09 11:09:25 +01003373 RTC_LOG(LS_INFO) << "TCP candidates are disabled.";
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003374 }
3375
honghaiz60347052016-05-31 18:29:12 -07003376 if (configuration.candidate_network_policy ==
3377 kCandidateNetworkPolicyLowCost) {
3378 portallocator_flags |= cricket::PORTALLOCATOR_DISABLE_COSTLY_NETWORKS;
Mirko Bonadei675513b2017-11-09 11:09:25 +01003379 RTC_LOG(LS_INFO) << "Do not gather candidates on high-cost networks";
honghaiz60347052016-05-31 18:29:12 -07003380 }
3381
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003382 port_allocator_->set_flags(portallocator_flags);
3383 // No step delay is used while allocating ports.
3384 port_allocator_->set_step_delay(cricket::kMinimumStepDelay);
3385 port_allocator_->set_candidate_filter(
3386 ConvertIceTransportTypeToCandidateFilter(configuration.type));
deadbeefd21eab32017-07-26 16:50:11 -07003387 port_allocator_->set_max_ipv6_networks(configuration.max_ipv6_networks);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003388
3389 // Call this last since it may create pooled allocator sessions using the
3390 // properties set above.
3391 port_allocator_->SetConfiguration(stun_servers, turn_servers,
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -07003392 configuration.ice_candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02003393 configuration.prune_turn_ports,
3394 configuration.turn_customizer);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003395 return true;
3396}
3397
deadbeef91dd5672016-05-18 16:55:30 -07003398bool PeerConnection::ReconfigurePortAllocator_n(
deadbeef293e9262017-01-11 12:28:30 -08003399 const cricket::ServerAddresses& stun_servers,
3400 const std::vector<cricket::RelayServerConfig>& turn_servers,
3401 IceTransportsType type,
3402 int candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02003403 bool prune_turn_ports,
3404 webrtc::TurnCustomizer* turn_customizer) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003405 port_allocator_->set_candidate_filter(
deadbeef293e9262017-01-11 12:28:30 -08003406 ConvertIceTransportTypeToCandidateFilter(type));
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003407 // Call this last since it may create pooled allocator sessions using the
3408 // candidate filter set above.
deadbeef6de92f92016-12-12 18:49:32 -08003409 return port_allocator_->SetConfiguration(
Jonas Orelandbdcee282017-10-10 14:01:40 +02003410 stun_servers, turn_servers, candidate_pool_size, prune_turn_ports,
3411 turn_customizer);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003412}
3413
Steve Antonba818672017-11-06 10:21:57 -08003414cricket::ChannelManager* PeerConnection::channel_manager() const {
3415 return factory_->channel_manager();
3416}
3417
3418MetricsObserverInterface* PeerConnection::metrics_observer() const {
3419 return uma_observer_;
3420}
3421
Elad Alon99c3fe52017-10-13 16:29:40 +02003422bool PeerConnection::StartRtcEventLog_w(
Bjorn Tereliusde939432017-11-20 17:38:14 +01003423 std::unique_ptr<RtcEventLogOutput> output,
3424 int64_t output_period_ms) {
zhihuang77985012017-02-07 15:45:16 -08003425 if (!event_log_) {
3426 return false;
3427 }
Bjorn Tereliusde939432017-11-20 17:38:14 +01003428 return event_log_->StartLogging(std::move(output), output_period_ms);
ivoc14d5dbe2016-07-04 07:06:55 -07003429}
3430
3431void PeerConnection::StopRtcEventLog_w() {
zhihuang77985012017-02-07 15:45:16 -08003432 if (event_log_) {
3433 event_log_->StopLogging();
3434 }
ivoc14d5dbe2016-07-04 07:06:55 -07003435}
nisseeaabdf62017-05-05 02:23:02 -07003436
Steve Anton75737c02017-11-06 10:37:17 -08003437cricket::BaseChannel* PeerConnection::GetChannel(
3438 const std::string& content_name) {
3439 if (voice_channel() && voice_channel()->content_name() == content_name) {
3440 return voice_channel();
3441 }
3442 if (video_channel() && video_channel()->content_name() == content_name) {
3443 return video_channel();
3444 }
3445 if (rtp_data_channel() &&
3446 rtp_data_channel()->content_name() == content_name) {
3447 return rtp_data_channel();
3448 }
3449 return nullptr;
3450}
3451
3452bool PeerConnection::GetSctpSslRole(rtc::SSLRole* role) {
3453 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003454 RTC_LOG(LS_INFO)
3455 << "Local and Remote descriptions must be applied to get the "
3456 << "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08003457 return false;
3458 }
3459 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003460 RTC_LOG(LS_INFO) << "Non-rejected SCTP m= section is needed to get the "
3461 << "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08003462 return false;
3463 }
3464
3465 return transport_controller_->GetSslRole(*sctp_transport_name_, role);
3466}
3467
3468bool PeerConnection::GetSslRole(const std::string& content_name,
3469 rtc::SSLRole* role) {
3470 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003471 RTC_LOG(LS_INFO)
3472 << "Local and Remote descriptions must be applied to get the "
3473 << "SSL Role of the session.";
Steve Anton75737c02017-11-06 10:37:17 -08003474 return false;
3475 }
3476
3477 return transport_controller_->GetSslRole(GetTransportName(content_name),
3478 role);
3479}
3480
Steve Anton75737c02017-11-06 10:37:17 -08003481// TODO(steveanton): Eventually it'd be nice to store the channels as a single
3482// vector of BaseChannel pointers instead of separate voice and video channel
3483// vectors. At that point, this will become a simple getter.
3484std::vector<cricket::BaseChannel*> PeerConnection::Channels() const {
3485 std::vector<cricket::BaseChannel*> channels;
Steve Anton4171afb2017-11-20 10:20:22 -08003486 if (voice_channel()) {
3487 channels.push_back(voice_channel());
3488 }
3489 if (video_channel()) {
3490 channels.push_back(video_channel());
3491 }
Steve Anton75737c02017-11-06 10:37:17 -08003492 if (rtp_data_channel_) {
3493 channels.push_back(rtp_data_channel_);
3494 }
3495 return channels;
3496}
3497
Steve Antonf8470812017-12-04 10:46:21 -08003498void PeerConnection::SetSessionError(SessionError error,
3499 const std::string& error_desc) {
3500 RTC_DCHECK_RUN_ON(signaling_thread());
3501 if (error != session_error_) {
3502 session_error_ = error;
3503 session_error_desc_ = error_desc;
Steve Anton75737c02017-11-06 10:37:17 -08003504 }
3505}
3506
Steve Anton3828c062017-12-06 10:34:51 -08003507RTCError PeerConnection::UpdateSessionState(SdpType type,
Steve Anton8a006912017-12-04 15:25:56 -08003508 cricket::ContentSource source) {
3509 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08003510
3511 // If there's already a pending error then no state transition should happen.
3512 // But all call-sites should be verifying this before calling us!
Steve Antonf8470812017-12-04 10:46:21 -08003513 RTC_DCHECK(session_error() == SessionError::kNone);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08003514
3515 // If this is an answer then we know whether to BUNDLE or not. If both the
3516 // local and remote side have agreed to BUNDLE, go ahead and enable it.
Steve Anton3828c062017-12-06 10:34:51 -08003517 if (type == SdpType::kAnswer) {
Steve Anton75737c02017-11-06 10:37:17 -08003518 const cricket::ContentGroup* local_bundle =
3519 local_description()->description()->GetGroupByName(
3520 cricket::GROUP_TYPE_BUNDLE);
3521 const cricket::ContentGroup* remote_bundle =
3522 remote_description()->description()->GetGroupByName(
3523 cricket::GROUP_TYPE_BUNDLE);
3524 if (local_bundle && remote_bundle) {
3525 // The answerer decides the transport to bundle on.
3526 const cricket::ContentGroup* answer_bundle =
3527 (source == cricket::CS_LOCAL ? local_bundle : remote_bundle);
3528 if (!EnableBundle(*answer_bundle)) {
Steve Anton8a006912017-12-04 15:25:56 -08003529 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3530 kEnableBundleFailed);
Steve Anton75737c02017-11-06 10:37:17 -08003531 }
3532 }
Steve Anton75737c02017-11-06 10:37:17 -08003533 }
Steve Anton6d6a2ae2017-12-04 17:19:47 -08003534
3535 // Only push down the transport description after potentially enabling BUNDLE;
3536 // we don't want to push down a description on a transport about to be
3537 // destroyed.
Steve Anton3828c062017-12-06 10:34:51 -08003538 RTCError error = PushdownTransportDescription(source, type);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08003539 if (!error.ok()) {
3540 return error;
3541 }
3542
3543 // If this is answer-ish we're ready to let media flow.
Steve Anton3828c062017-12-06 10:34:51 -08003544 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Antoned10bd92017-12-05 10:52:59 -08003545 EnableSending();
Steve Anton6d6a2ae2017-12-04 17:19:47 -08003546 }
3547
3548 // Update the signaling state according to the specified state machine (see
3549 // https://w3c.github.io/webrtc-pc/#rtcsignalingstate-enum).
Steve Anton3828c062017-12-06 10:34:51 -08003550 if (type == SdpType::kOffer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08003551 ChangeSignalingState(source == cricket::CS_LOCAL
3552 ? PeerConnectionInterface::kHaveLocalOffer
3553 : PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton3828c062017-12-06 10:34:51 -08003554 } else if (type == SdpType::kPrAnswer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08003555 ChangeSignalingState(source == cricket::CS_LOCAL
3556 ? PeerConnectionInterface::kHaveLocalPrAnswer
3557 : PeerConnectionInterface::kHaveRemotePrAnswer);
3558 } else {
Steve Anton3828c062017-12-06 10:34:51 -08003559 RTC_DCHECK(type == SdpType::kAnswer);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08003560 ChangeSignalingState(PeerConnectionInterface::kStable);
3561 }
3562
3563 // Update internal objects according to the session description's media
3564 // descriptions.
Steve Anton3828c062017-12-06 10:34:51 -08003565 error = PushdownMediaDescription(type, source);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08003566 if (!error.ok()) {
3567 SetSessionError(SessionError::kContent, error.message());
3568 }
3569 if (session_error() != SessionError::kNone) {
3570 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
3571 }
3572
Steve Anton8a006912017-12-04 15:25:56 -08003573 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08003574}
3575
Steve Anton8a006912017-12-04 15:25:56 -08003576RTCError PeerConnection::PushdownMediaDescription(
Steve Anton3828c062017-12-06 10:34:51 -08003577 SdpType type,
Steve Anton8a006912017-12-04 15:25:56 -08003578 cricket::ContentSource source) {
Steve Antoned10bd92017-12-05 10:52:59 -08003579 const SessionDescriptionInterface* sdesc =
3580 (source == cricket::CS_LOCAL ? local_description()
3581 : remote_description());
Steve Anton75737c02017-11-06 10:37:17 -08003582 RTC_DCHECK(sdesc);
Steve Antoned10bd92017-12-05 10:52:59 -08003583
3584 // Push down the new SDP media section for each audio/video transceiver.
3585 for (auto transceiver : transceivers_) {
Steve Anton75737c02017-11-06 10:37:17 -08003586 const ContentInfo* content_info =
Steve Antoned10bd92017-12-05 10:52:59 -08003587 FindMediaSectionForTransceiver(transceiver, sdesc);
3588 cricket::BaseChannel* channel = transceiver->internal()->channel();
3589 if (!channel || !content_info || content_info->rejected) {
Steve Anton75737c02017-11-06 10:37:17 -08003590 continue;
3591 }
3592 const MediaContentDescription* content_desc =
3593 static_cast<const MediaContentDescription*>(content_info->description);
Steve Antoned10bd92017-12-05 10:52:59 -08003594 if (!content_desc) {
3595 continue;
3596 }
3597 std::string error;
3598 bool success =
3599 (source == cricket::CS_LOCAL)
Steve Anton3828c062017-12-06 10:34:51 -08003600 ? channel->SetLocalContent(content_desc, type, &error)
3601 : channel->SetRemoteContent(content_desc, type, &error);
Steve Antoned10bd92017-12-05 10:52:59 -08003602 if (!success) {
3603 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, std::move(error));
3604 }
3605 }
3606
3607 // If using the RtpDataChannel, push down the new SDP section for it too.
3608 if (rtp_data_channel_) {
3609 const ContentInfo* data_content =
3610 cricket::GetFirstDataContent(sdesc->description());
3611 if (data_content && !data_content->rejected) {
3612 const MediaContentDescription* data_desc =
3613 static_cast<const MediaContentDescription*>(
3614 data_content->description);
3615 if (data_desc) {
3616 std::string error;
3617 bool success =
3618 (source == cricket::CS_LOCAL)
Steve Anton3828c062017-12-06 10:34:51 -08003619 ? rtp_data_channel_->SetLocalContent(data_desc, type, &error)
3620 : rtp_data_channel_->SetRemoteContent(data_desc, type,
Steve Antoned10bd92017-12-05 10:52:59 -08003621 &error);
3622 if (!success) {
3623 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3624 std::move(error));
3625 }
Steve Anton75737c02017-11-06 10:37:17 -08003626 }
3627 }
3628 }
Steve Antoned10bd92017-12-05 10:52:59 -08003629
Steve Anton75737c02017-11-06 10:37:17 -08003630 // Need complete offer/answer with an SCTP m= section before starting SCTP,
3631 // according to https://tools.ietf.org/html/draft-ietf-mmusic-sctp-sdp-19
3632 if (sctp_transport_ && local_description() && remote_description() &&
3633 cricket::GetFirstDataContent(local_description()->description()) &&
3634 cricket::GetFirstDataContent(remote_description()->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08003635 bool success = network_thread()->Invoke<bool>(
Steve Anton75737c02017-11-06 10:37:17 -08003636 RTC_FROM_HERE,
3637 rtc::Bind(&PeerConnection::PushdownSctpParameters_n, this, source));
Steve Anton8a006912017-12-04 15:25:56 -08003638 if (!success) {
3639 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
3640 "Failed to push down SCTP parameters.");
3641 }
Steve Anton75737c02017-11-06 10:37:17 -08003642 }
Steve Antoned10bd92017-12-05 10:52:59 -08003643
Steve Anton8a006912017-12-04 15:25:56 -08003644 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08003645}
3646
3647bool PeerConnection::PushdownSctpParameters_n(cricket::ContentSource source) {
3648 RTC_DCHECK(network_thread()->IsCurrent());
3649 RTC_DCHECK(local_description());
3650 RTC_DCHECK(remote_description());
3651 // Apply the SCTP port (which is hidden inside a DataCodec structure...)
3652 // When we support "max-message-size", that would also be pushed down here.
3653 return sctp_transport_->Start(
3654 GetSctpPort(local_description()->description()),
3655 GetSctpPort(remote_description()->description()));
3656}
3657
Steve Anton8a006912017-12-04 15:25:56 -08003658RTCError PeerConnection::PushdownTransportDescription(
3659 cricket::ContentSource source,
Steve Anton3828c062017-12-06 10:34:51 -08003660 SdpType type) {
Steve Anton8a006912017-12-04 15:25:56 -08003661 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08003662
Steve Anton8a006912017-12-04 15:25:56 -08003663 const SessionDescriptionInterface* sdesc =
3664 (source == cricket::CS_LOCAL ? local_description()
3665 : remote_description());
3666 RTC_DCHECK(sdesc);
3667 for (const cricket::TransportInfo& tinfo :
3668 sdesc->description()->transport_infos()) {
3669 std::string error;
3670 bool success;
3671 if (source == cricket::CS_LOCAL) {
3672 success = transport_controller_->SetLocalTransportDescription(
Steve Anton3828c062017-12-06 10:34:51 -08003673 tinfo.content_name, tinfo.description, type, &error);
Steve Anton8a006912017-12-04 15:25:56 -08003674 } else {
3675 success = transport_controller_->SetRemoteTransportDescription(
Steve Anton3828c062017-12-06 10:34:51 -08003676 tinfo.content_name, tinfo.description, type, &error);
Steve Anton8a006912017-12-04 15:25:56 -08003677 }
3678 if (!success) {
3679 LOG_AND_RETURN_ERROR(
3680 RTCErrorType::INVALID_PARAMETER,
3681 "Failed to push down transport description: " + error);
Steve Anton75737c02017-11-06 10:37:17 -08003682 }
3683 }
3684
Steve Anton8a006912017-12-04 15:25:56 -08003685 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08003686}
3687
3688bool PeerConnection::GetTransportDescription(
3689 const SessionDescription* description,
3690 const std::string& content_name,
3691 cricket::TransportDescription* tdesc) {
3692 if (!description || !tdesc) {
3693 return false;
3694 }
3695 const TransportInfo* transport_info =
3696 description->GetTransportInfoByName(content_name);
3697 if (!transport_info) {
3698 return false;
3699 }
3700 *tdesc = transport_info->description;
3701 return true;
3702}
3703
3704bool PeerConnection::EnableBundle(const cricket::ContentGroup& bundle) {
3705 const std::string* first_content_name = bundle.FirstContentName();
3706 if (!first_content_name) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003707 RTC_LOG(LS_WARNING) << "Tried to BUNDLE with no contents.";
Steve Anton75737c02017-11-06 10:37:17 -08003708 return false;
3709 }
3710 const std::string& transport_name = *first_content_name;
3711
3712 auto maybe_set_transport = [this, bundle,
3713 transport_name](cricket::BaseChannel* ch) {
3714 if (!ch || !bundle.HasContentName(ch->content_name())) {
Steve Antoned10bd92017-12-05 10:52:59 -08003715 return;
Steve Anton75737c02017-11-06 10:37:17 -08003716 }
3717
3718 std::string old_transport_name = ch->transport_name();
3719 if (old_transport_name == transport_name) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003720 RTC_LOG(LS_INFO) << "BUNDLE already enabled for " << ch->content_name()
3721 << " on " << transport_name << ".";
Steve Antoned10bd92017-12-05 10:52:59 -08003722 return;
Steve Anton75737c02017-11-06 10:37:17 -08003723 }
3724
3725 cricket::DtlsTransportInternal* rtp_dtls_transport =
3726 transport_controller_->CreateDtlsTransport(
3727 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
3728 bool need_rtcp = (ch->rtcp_dtls_transport() != nullptr);
3729 cricket::DtlsTransportInternal* rtcp_dtls_transport = nullptr;
3730 if (need_rtcp) {
3731 rtcp_dtls_transport = transport_controller_->CreateDtlsTransport(
3732 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
3733 }
3734
3735 ch->SetTransports(rtp_dtls_transport, rtcp_dtls_transport);
Mirko Bonadei675513b2017-11-09 11:09:25 +01003736 RTC_LOG(LS_INFO) << "Enabled BUNDLE for " << ch->content_name() << " on "
3737 << transport_name << ".";
Steve Anton75737c02017-11-06 10:37:17 -08003738 transport_controller_->DestroyDtlsTransport(
3739 old_transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
3740 // If the channel needs rtcp, it means that the channel used to have a
3741 // rtcp transport which needs to be deleted now.
3742 if (need_rtcp) {
3743 transport_controller_->DestroyDtlsTransport(
3744 old_transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
3745 }
Steve Anton75737c02017-11-06 10:37:17 -08003746 };
3747
Steve Antoned10bd92017-12-05 10:52:59 -08003748 for (auto transceiver : transceivers_) {
3749 maybe_set_transport(transceiver->internal()->channel());
Steve Anton75737c02017-11-06 10:37:17 -08003750 }
Steve Antoned10bd92017-12-05 10:52:59 -08003751 maybe_set_transport(rtp_data_channel_);
3752
Steve Anton75737c02017-11-06 10:37:17 -08003753 // For SCTP, transport creation/deletion happens here instead of in the
3754 // object itself.
3755 if (sctp_transport_) {
3756 RTC_DCHECK(sctp_transport_name_);
3757 RTC_DCHECK(sctp_content_name_);
3758 if (transport_name != *sctp_transport_name_ &&
3759 bundle.HasContentName(*sctp_content_name_)) {
3760 network_thread()->Invoke<void>(
3761 RTC_FROM_HERE, rtc::Bind(&PeerConnection::ChangeSctpTransport_n, this,
3762 transport_name));
3763 }
3764 }
3765
3766 return true;
3767}
3768
Steve Anton75737c02017-11-06 10:37:17 -08003769cricket::IceConfig PeerConnection::ParseIceConfig(
3770 const PeerConnectionInterface::RTCConfiguration& config) const {
3771 cricket::ContinualGatheringPolicy gathering_policy;
3772 // TODO(honghaiz): Add the third continual gathering policy in
3773 // PeerConnectionInterface and map it to GATHER_CONTINUALLY_AND_RECOVER.
3774 switch (config.continual_gathering_policy) {
3775 case PeerConnectionInterface::GATHER_ONCE:
3776 gathering_policy = cricket::GATHER_ONCE;
3777 break;
3778 case PeerConnectionInterface::GATHER_CONTINUALLY:
3779 gathering_policy = cricket::GATHER_CONTINUALLY;
3780 break;
3781 default:
3782 RTC_NOTREACHED();
3783 gathering_policy = cricket::GATHER_ONCE;
3784 }
3785 cricket::IceConfig ice_config;
3786 ice_config.receiving_timeout = config.ice_connection_receiving_timeout;
3787 ice_config.prioritize_most_likely_candidate_pairs =
3788 config.prioritize_most_likely_ice_candidate_pairs;
3789 ice_config.backup_connection_ping_interval =
3790 config.ice_backup_candidate_pair_ping_interval;
3791 ice_config.continual_gathering_policy = gathering_policy;
3792 ice_config.presume_writable_when_fully_relayed =
3793 config.presume_writable_when_fully_relayed;
3794 ice_config.ice_check_min_interval = config.ice_check_min_interval;
3795 ice_config.regather_all_networks_interval_range =
3796 config.ice_regather_interval_range;
3797 return ice_config;
3798}
3799
Steve Anton75737c02017-11-06 10:37:17 -08003800bool PeerConnection::GetLocalTrackIdBySsrc(uint32_t ssrc,
3801 std::string* track_id) {
3802 if (!local_description()) {
3803 return false;
3804 }
3805 return webrtc::GetTrackIdBySsrc(local_description()->description(), ssrc,
3806 track_id);
3807}
3808
3809bool PeerConnection::GetRemoteTrackIdBySsrc(uint32_t ssrc,
3810 std::string* track_id) {
3811 if (!remote_description()) {
3812 return false;
3813 }
3814 return webrtc::GetTrackIdBySsrc(remote_description()->description(), ssrc,
3815 track_id);
3816}
3817
3818bool PeerConnection::SendData(const cricket::SendDataParams& params,
3819 const rtc::CopyOnWriteBuffer& payload,
3820 cricket::SendDataResult* result) {
3821 if (!rtp_data_channel_ && !sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003822 RTC_LOG(LS_ERROR) << "SendData called when rtp_data_channel_ "
3823 << "and sctp_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08003824 return false;
3825 }
3826 return rtp_data_channel_
3827 ? rtp_data_channel_->SendData(params, payload, result)
3828 : network_thread()->Invoke<bool>(
3829 RTC_FROM_HERE,
3830 Bind(&cricket::SctpTransportInternal::SendData,
3831 sctp_transport_.get(), params, payload, result));
3832}
3833
3834bool PeerConnection::ConnectDataChannel(DataChannel* webrtc_data_channel) {
3835 if (!rtp_data_channel_ && !sctp_transport_) {
3836 // Don't log an error here, because DataChannels are expected to call
3837 // ConnectDataChannel in this state. It's the only way to initially tell
3838 // whether or not the underlying transport is ready.
3839 return false;
3840 }
3841 if (rtp_data_channel_) {
3842 rtp_data_channel_->SignalReadyToSendData.connect(
3843 webrtc_data_channel, &DataChannel::OnChannelReady);
3844 rtp_data_channel_->SignalDataReceived.connect(webrtc_data_channel,
3845 &DataChannel::OnDataReceived);
3846 } else {
3847 SignalSctpReadyToSendData.connect(webrtc_data_channel,
3848 &DataChannel::OnChannelReady);
3849 SignalSctpDataReceived.connect(webrtc_data_channel,
3850 &DataChannel::OnDataReceived);
3851 SignalSctpStreamClosedRemotely.connect(
3852 webrtc_data_channel, &DataChannel::OnStreamClosedRemotely);
3853 }
3854 return true;
3855}
3856
3857void PeerConnection::DisconnectDataChannel(DataChannel* webrtc_data_channel) {
3858 if (!rtp_data_channel_ && !sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003859 RTC_LOG(LS_ERROR)
3860 << "DisconnectDataChannel called when rtp_data_channel_ and "
3861 "sctp_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08003862 return;
3863 }
3864 if (rtp_data_channel_) {
3865 rtp_data_channel_->SignalReadyToSendData.disconnect(webrtc_data_channel);
3866 rtp_data_channel_->SignalDataReceived.disconnect(webrtc_data_channel);
3867 } else {
3868 SignalSctpReadyToSendData.disconnect(webrtc_data_channel);
3869 SignalSctpDataReceived.disconnect(webrtc_data_channel);
3870 SignalSctpStreamClosedRemotely.disconnect(webrtc_data_channel);
3871 }
3872}
3873
3874void PeerConnection::AddSctpDataStream(int sid) {
3875 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003876 RTC_LOG(LS_ERROR)
3877 << "AddSctpDataStream called when sctp_transport_ is NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08003878 return;
3879 }
3880 network_thread()->Invoke<void>(
3881 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::OpenStream,
3882 sctp_transport_.get(), sid));
3883}
3884
3885void PeerConnection::RemoveSctpDataStream(int sid) {
3886 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003887 RTC_LOG(LS_ERROR) << "RemoveSctpDataStream called when sctp_transport_ is "
3888 << "NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08003889 return;
3890 }
3891 network_thread()->Invoke<void>(
3892 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::ResetStream,
3893 sctp_transport_.get(), sid));
3894}
3895
3896bool PeerConnection::ReadyToSendData() const {
3897 return (rtp_data_channel_ && rtp_data_channel_->ready_to_send_data()) ||
3898 sctp_ready_to_send_data_;
3899}
3900
3901std::unique_ptr<SessionStats> PeerConnection::GetSessionStats_s() {
3902 RTC_DCHECK(signaling_thread()->IsCurrent());
3903 ChannelNamePairs channel_name_pairs;
3904 if (voice_channel()) {
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003905 channel_name_pairs.voice = ChannelNamePair(
3906 voice_channel()->content_name(), voice_channel()->transport_name());
Steve Anton75737c02017-11-06 10:37:17 -08003907 }
3908 if (video_channel()) {
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003909 channel_name_pairs.video = ChannelNamePair(
3910 video_channel()->content_name(), video_channel()->transport_name());
Steve Anton75737c02017-11-06 10:37:17 -08003911 }
3912 if (rtp_data_channel()) {
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003913 channel_name_pairs.data =
Steve Anton75737c02017-11-06 10:37:17 -08003914 ChannelNamePair(rtp_data_channel()->content_name(),
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003915 rtp_data_channel()->transport_name());
Steve Anton75737c02017-11-06 10:37:17 -08003916 }
3917 if (sctp_transport_) {
3918 RTC_DCHECK(sctp_content_name_);
3919 RTC_DCHECK(sctp_transport_name_);
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003920 channel_name_pairs.data =
3921 ChannelNamePair(*sctp_content_name_, *sctp_transport_name_);
Steve Anton75737c02017-11-06 10:37:17 -08003922 }
3923 return GetSessionStats(channel_name_pairs);
3924}
3925
3926std::unique_ptr<SessionStats> PeerConnection::GetSessionStats(
3927 const ChannelNamePairs& channel_name_pairs) {
3928 if (network_thread()->IsCurrent()) {
3929 return GetSessionStats_n(channel_name_pairs);
3930 }
3931 return network_thread()->Invoke<std::unique_ptr<SessionStats>>(
3932 RTC_FROM_HERE,
3933 rtc::Bind(&PeerConnection::GetSessionStats_n, this, channel_name_pairs));
3934}
3935
3936bool PeerConnection::GetLocalCertificate(
3937 const std::string& transport_name,
3938 rtc::scoped_refptr<rtc::RTCCertificate>* certificate) {
3939 return transport_controller_->GetLocalCertificate(transport_name,
3940 certificate);
3941}
3942
3943std::unique_ptr<rtc::SSLCertificate> PeerConnection::GetRemoteSSLCertificate(
3944 const std::string& transport_name) {
3945 return transport_controller_->GetRemoteSSLCertificate(transport_name);
3946}
3947
3948cricket::DataChannelType PeerConnection::data_channel_type() const {
3949 return data_channel_type_;
3950}
3951
3952bool PeerConnection::IceRestartPending(const std::string& content_name) const {
3953 return pending_ice_restarts_.find(content_name) !=
3954 pending_ice_restarts_.end();
3955}
3956
Steve Anton75737c02017-11-06 10:37:17 -08003957bool PeerConnection::NeedsIceRestart(const std::string& content_name) const {
3958 return transport_controller_->NeedsIceRestart(content_name);
3959}
3960
3961void PeerConnection::OnCertificateReady(
3962 const rtc::scoped_refptr<rtc::RTCCertificate>& certificate) {
3963 transport_controller_->SetLocalCertificate(certificate);
3964}
3965
3966void PeerConnection::OnDtlsSrtpSetupFailure(cricket::BaseChannel*, bool rtcp) {
Steve Antonf8470812017-12-04 10:46:21 -08003967 SetSessionError(SessionError::kTransport,
3968 rtcp ? kDtlsSrtpSetupFailureRtcp : kDtlsSrtpSetupFailureRtp);
Steve Anton75737c02017-11-06 10:37:17 -08003969}
3970
3971void PeerConnection::OnTransportControllerConnectionState(
3972 cricket::IceConnectionState state) {
3973 switch (state) {
3974 case cricket::kIceConnectionConnecting:
3975 // If the current state is Connected or Completed, then there were
3976 // writable channels but now there are not, so the next state must
3977 // be Disconnected.
3978 // kIceConnectionConnecting is currently used as the default,
3979 // un-connected state by the TransportController, so its only use is
3980 // detecting disconnections.
3981 if (ice_connection_state_ ==
3982 PeerConnectionInterface::kIceConnectionConnected ||
3983 ice_connection_state_ ==
3984 PeerConnectionInterface::kIceConnectionCompleted) {
3985 SetIceConnectionState(
3986 PeerConnectionInterface::kIceConnectionDisconnected);
3987 }
3988 break;
3989 case cricket::kIceConnectionFailed:
3990 SetIceConnectionState(PeerConnectionInterface::kIceConnectionFailed);
3991 break;
3992 case cricket::kIceConnectionConnected:
Mirko Bonadei675513b2017-11-09 11:09:25 +01003993 RTC_LOG(LS_INFO) << "Changing to ICE connected state because "
3994 << "all transports are writable.";
Steve Anton75737c02017-11-06 10:37:17 -08003995 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
3996 break;
3997 case cricket::kIceConnectionCompleted:
Mirko Bonadei675513b2017-11-09 11:09:25 +01003998 RTC_LOG(LS_INFO) << "Changing to ICE completed state because "
3999 << "all transports are complete.";
Steve Anton75737c02017-11-06 10:37:17 -08004000 if (ice_connection_state_ !=
4001 PeerConnectionInterface::kIceConnectionConnected) {
4002 // If jumping directly from "checking" to "connected",
4003 // signal "connected" first.
4004 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
4005 }
4006 SetIceConnectionState(PeerConnectionInterface::kIceConnectionCompleted);
4007 if (metrics_observer()) {
4008 ReportTransportStats();
4009 }
4010 break;
4011 default:
4012 RTC_NOTREACHED();
4013 }
4014}
4015
4016void PeerConnection::OnTransportControllerCandidatesGathered(
4017 const std::string& transport_name,
4018 const cricket::Candidates& candidates) {
4019 RTC_DCHECK(signaling_thread()->IsCurrent());
4020 int sdp_mline_index;
4021 if (!GetLocalCandidateMediaIndex(transport_name, &sdp_mline_index)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004022 RTC_LOG(LS_ERROR)
4023 << "OnTransportControllerCandidatesGathered: content name "
4024 << transport_name << " not found";
Steve Anton75737c02017-11-06 10:37:17 -08004025 return;
4026 }
4027
4028 for (cricket::Candidates::const_iterator citer = candidates.begin();
4029 citer != candidates.end(); ++citer) {
4030 // Use transport_name as the candidate media id.
4031 std::unique_ptr<JsepIceCandidate> candidate(
4032 new JsepIceCandidate(transport_name, sdp_mline_index, *citer));
4033 if (local_description()) {
4034 mutable_local_description()->AddCandidate(candidate.get());
4035 }
4036 OnIceCandidate(std::move(candidate));
4037 }
4038}
4039
4040void PeerConnection::OnTransportControllerCandidatesRemoved(
4041 const std::vector<cricket::Candidate>& candidates) {
4042 RTC_DCHECK(signaling_thread()->IsCurrent());
4043 // Sanity check.
4044 for (const cricket::Candidate& candidate : candidates) {
4045 if (candidate.transport_name().empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004046 RTC_LOG(LS_ERROR) << "OnTransportControllerCandidatesRemoved: "
4047 << "empty content name in candidate "
4048 << candidate.ToString();
Steve Anton75737c02017-11-06 10:37:17 -08004049 return;
4050 }
4051 }
4052
4053 if (local_description()) {
4054 mutable_local_description()->RemoveCandidates(candidates);
4055 }
4056 OnIceCandidatesRemoved(candidates);
4057}
4058
4059void PeerConnection::OnTransportControllerDtlsHandshakeError(
4060 rtc::SSLHandshakeError error) {
4061 if (metrics_observer()) {
4062 metrics_observer()->IncrementEnumCounter(
4063 webrtc::kEnumCounterDtlsHandshakeError, static_cast<int>(error),
4064 static_cast<int>(rtc::SSLHandshakeError::MAX_VALUE));
4065 }
4066}
4067
Steve Antoned10bd92017-12-05 10:52:59 -08004068void PeerConnection::EnableSending() {
4069 for (auto transceiver : transceivers_) {
4070 cricket::BaseChannel* channel = transceiver->internal()->channel();
4071 if (channel && !channel->enabled()) {
4072 channel->Enable(true);
4073 }
Steve Anton75737c02017-11-06 10:37:17 -08004074 }
4075
Steve Anton4171afb2017-11-20 10:20:22 -08004076 if (rtp_data_channel_ && !rtp_data_channel_->enabled()) {
Steve Anton75737c02017-11-06 10:37:17 -08004077 rtp_data_channel_->Enable(true);
Steve Anton4171afb2017-11-20 10:20:22 -08004078 }
Steve Anton75737c02017-11-06 10:37:17 -08004079}
4080
4081// Returns the media index for a local ice candidate given the content name.
4082bool PeerConnection::GetLocalCandidateMediaIndex(
4083 const std::string& content_name,
4084 int* sdp_mline_index) {
4085 if (!local_description() || !sdp_mline_index) {
4086 return false;
4087 }
4088
4089 bool content_found = false;
4090 const ContentInfos& contents = local_description()->description()->contents();
4091 for (size_t index = 0; index < contents.size(); ++index) {
4092 if (contents[index].name == content_name) {
4093 *sdp_mline_index = static_cast<int>(index);
4094 content_found = true;
4095 break;
4096 }
4097 }
4098 return content_found;
4099}
4100
4101bool PeerConnection::UseCandidatesInSessionDescription(
4102 const SessionDescriptionInterface* remote_desc) {
4103 if (!remote_desc) {
4104 return true;
4105 }
4106 bool ret = true;
4107
4108 for (size_t m = 0; m < remote_desc->number_of_mediasections(); ++m) {
4109 const IceCandidateCollection* candidates = remote_desc->candidates(m);
4110 for (size_t n = 0; n < candidates->count(); ++n) {
4111 const IceCandidateInterface* candidate = candidates->at(n);
4112 bool valid = false;
4113 if (!ReadyToUseRemoteCandidate(candidate, remote_desc, &valid)) {
4114 if (valid) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004115 RTC_LOG(LS_INFO)
4116 << "UseCandidatesInSessionDescription: Not ready to use "
4117 << "candidate.";
Steve Anton75737c02017-11-06 10:37:17 -08004118 }
4119 continue;
4120 }
4121 ret = UseCandidate(candidate);
4122 if (!ret) {
4123 break;
4124 }
4125 }
4126 }
4127 return ret;
4128}
4129
4130bool PeerConnection::UseCandidate(const IceCandidateInterface* candidate) {
4131 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
4132 size_t remote_content_size =
4133 remote_description()->description()->contents().size();
4134 if (mediacontent_index >= remote_content_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004135 RTC_LOG(LS_ERROR) << "UseCandidate: Invalid candidate media index.";
Steve Anton75737c02017-11-06 10:37:17 -08004136 return false;
4137 }
4138
4139 cricket::ContentInfo content =
4140 remote_description()->description()->contents()[mediacontent_index];
4141 std::vector<cricket::Candidate> candidates;
4142 candidates.push_back(candidate->candidate());
4143 // Invoking BaseSession method to handle remote candidates.
4144 std::string error;
4145 if (transport_controller_->AddRemoteCandidates(content.name, candidates,
4146 &error)) {
4147 // Candidates successfully submitted for checking.
4148 if (ice_connection_state_ == PeerConnectionInterface::kIceConnectionNew ||
4149 ice_connection_state_ ==
4150 PeerConnectionInterface::kIceConnectionDisconnected) {
4151 // If state is New, then the session has just gotten its first remote ICE
4152 // candidates, so go to Checking.
4153 // If state is Disconnected, the session is re-using old candidates or
4154 // receiving additional ones, so go to Checking.
4155 // If state is Connected, stay Connected.
4156 // TODO(bemasc): If state is Connected, and the new candidates are for a
4157 // newly added transport, then the state actually _should_ move to
4158 // checking. Add a way to distinguish that case.
4159 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
4160 }
4161 // TODO(bemasc): If state is Completed, go back to Connected.
4162 } else {
4163 if (!error.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004164 RTC_LOG(LS_WARNING) << error;
Steve Anton75737c02017-11-06 10:37:17 -08004165 }
4166 }
4167 return true;
4168}
4169
4170void PeerConnection::RemoveUnusedChannels(const SessionDescription* desc) {
Steve Anton75737c02017-11-06 10:37:17 -08004171 // Destroy video channel first since it may have a pointer to the
4172 // voice channel.
4173 const cricket::ContentInfo* video_info = cricket::GetFirstVideoContent(desc);
Steve Anton6fec8802017-12-04 10:37:29 -08004174 if (!video_info || video_info->rejected) {
4175 DestroyTransceiverChannel(GetVideoTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08004176 }
4177
Steve Anton6fec8802017-12-04 10:37:29 -08004178 const cricket::ContentInfo* audio_info = cricket::GetFirstAudioContent(desc);
4179 if (!audio_info || audio_info->rejected) {
4180 DestroyTransceiverChannel(GetAudioTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08004181 }
4182
4183 const cricket::ContentInfo* data_info = cricket::GetFirstDataContent(desc);
4184 if (!data_info || data_info->rejected) {
Steve Anton6fec8802017-12-04 10:37:29 -08004185 DestroyDataChannel();
Steve Anton75737c02017-11-06 10:37:17 -08004186 }
4187}
4188
Steve Antoneda6ccd2017-12-04 10:21:55 -08004189std::string PeerConnection::GetTransportNameForMediaSection(
4190 const std::string& mid,
4191 const cricket::ContentGroup* bundle_group) const {
4192 if (!bundle_group) {
4193 return mid;
Steve Anton75737c02017-11-06 10:37:17 -08004194 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08004195 const std::string* first_content_name = bundle_group->FirstContentName();
Steve Anton75737c02017-11-06 10:37:17 -08004196 if (!first_content_name) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004197 RTC_LOG(LS_WARNING) << "Tried to BUNDLE with no contents.";
Steve Antoneda6ccd2017-12-04 10:21:55 -08004198 return mid;
Steve Anton75737c02017-11-06 10:37:17 -08004199 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08004200 if (!bundle_group->HasContentName(mid)) {
4201 RTC_LOG(LS_WARNING) << mid << " is not part of any bundle group";
4202 return mid;
Steve Anton75737c02017-11-06 10:37:17 -08004203 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08004204 RTC_LOG(LS_INFO) << "Bundling " << mid << " on " << *first_content_name;
4205 return *first_content_name;
Steve Anton75737c02017-11-06 10:37:17 -08004206}
4207
Steve Anton8a006912017-12-04 15:25:56 -08004208RTCError PeerConnection::CreateChannels(const SessionDescription* desc) {
Steve Antoneda6ccd2017-12-04 10:21:55 -08004209 RTC_DCHECK(desc);
4210
Steve Anton75737c02017-11-06 10:37:17 -08004211 const cricket::ContentGroup* bundle_group = nullptr;
4212 if (configuration_.bundle_policy ==
4213 PeerConnectionInterface::kBundlePolicyMaxBundle) {
4214 bundle_group = desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
4215 if (!bundle_group) {
Steve Anton8a006912017-12-04 15:25:56 -08004216 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
4217 "max-bundle configured but session description "
4218 "has no BUNDLE group");
Steve Anton75737c02017-11-06 10:37:17 -08004219 }
4220 }
4221
Steve Antoneda6ccd2017-12-04 10:21:55 -08004222 // Creating the media channels and transport proxies.
4223 const cricket::ContentInfo* voice = cricket::GetFirstAudioContent(desc);
4224 if (voice && !voice->rejected &&
4225 !GetAudioTransceiver()->internal()->channel()) {
4226 cricket::VoiceChannel* voice_channel = CreateVoiceChannel(
4227 voice->name,
4228 GetTransportNameForMediaSection(voice->name, bundle_group));
4229 if (!voice_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08004230 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
4231 "Failed to create voice channel.");
Steve Antoneda6ccd2017-12-04 10:21:55 -08004232 }
4233 GetAudioTransceiver()->internal()->SetChannel(voice_channel);
4234 }
4235
Steve Anton75737c02017-11-06 10:37:17 -08004236 const cricket::ContentInfo* video = cricket::GetFirstVideoContent(desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08004237 if (video && !video->rejected &&
4238 !GetVideoTransceiver()->internal()->channel()) {
4239 cricket::VideoChannel* video_channel = CreateVideoChannel(
4240 video->name,
4241 GetTransportNameForMediaSection(video->name, bundle_group));
4242 if (!video_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08004243 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
4244 "Failed to create video channel.");
Steve Anton75737c02017-11-06 10:37:17 -08004245 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08004246 GetVideoTransceiver()->internal()->SetChannel(video_channel);
Steve Anton75737c02017-11-06 10:37:17 -08004247 }
4248
4249 const cricket::ContentInfo* data = cricket::GetFirstDataContent(desc);
4250 if (data_channel_type_ != cricket::DCT_NONE && data && !data->rejected &&
4251 !rtp_data_channel_ && !sctp_transport_) {
Steve Antoneda6ccd2017-12-04 10:21:55 -08004252 if (!CreateDataChannel(data->name, GetTransportNameForMediaSection(
4253 data->name, bundle_group))) {
Steve Anton8a006912017-12-04 15:25:56 -08004254 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
4255 "Failed to create data channel.");
Steve Anton75737c02017-11-06 10:37:17 -08004256 }
4257 }
4258
Steve Anton8a006912017-12-04 15:25:56 -08004259 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08004260}
4261
Steve Anton4171afb2017-11-20 10:20:22 -08004262// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08004263cricket::VoiceChannel* PeerConnection::CreateVoiceChannel(
4264 const std::string& mid,
4265 const std::string& transport_name) {
Steve Anton75737c02017-11-06 10:37:17 -08004266 cricket::DtlsTransportInternal* rtp_dtls_transport =
4267 transport_controller_->CreateDtlsTransport(
4268 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4269 cricket::DtlsTransportInternal* rtcp_dtls_transport = nullptr;
4270 if (configuration_.rtcp_mux_policy !=
4271 PeerConnectionInterface::kRtcpMuxPolicyRequire) {
4272 rtcp_dtls_transport = transport_controller_->CreateDtlsTransport(
4273 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
4274 }
4275
4276 cricket::VoiceChannel* voice_channel = channel_manager()->CreateVoiceChannel(
4277 call_.get(), configuration_.media_config, rtp_dtls_transport,
Steve Antoneda6ccd2017-12-04 10:21:55 -08004278 rtcp_dtls_transport, signaling_thread(), mid, SrtpRequired(),
4279 audio_options_);
Steve Anton75737c02017-11-06 10:37:17 -08004280 if (!voice_channel) {
4281 transport_controller_->DestroyDtlsTransport(
4282 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4283 if (rtcp_dtls_transport) {
4284 transport_controller_->DestroyDtlsTransport(
4285 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
4286 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08004287 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08004288 }
Steve Anton75737c02017-11-06 10:37:17 -08004289 voice_channel->SignalRtcpMuxFullyActive.connect(
4290 this, &PeerConnection::DestroyRtcpTransport_n);
4291 voice_channel->SignalDtlsSrtpSetupFailure.connect(
4292 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08004293 voice_channel->SignalSentPacket.connect(this,
4294 &PeerConnection::OnSentPacket_w);
Steve Anton4171afb2017-11-20 10:20:22 -08004295
Steve Antoneda6ccd2017-12-04 10:21:55 -08004296 return voice_channel;
Steve Anton75737c02017-11-06 10:37:17 -08004297}
4298
Steve Anton4171afb2017-11-20 10:20:22 -08004299// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08004300cricket::VideoChannel* PeerConnection::CreateVideoChannel(
4301 const std::string& mid,
4302 const std::string& transport_name) {
Steve Anton75737c02017-11-06 10:37:17 -08004303 cricket::DtlsTransportInternal* rtp_dtls_transport =
4304 transport_controller_->CreateDtlsTransport(
4305 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4306 cricket::DtlsTransportInternal* rtcp_dtls_transport = nullptr;
4307 if (configuration_.rtcp_mux_policy !=
4308 PeerConnectionInterface::kRtcpMuxPolicyRequire) {
4309 rtcp_dtls_transport = transport_controller_->CreateDtlsTransport(
4310 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
4311 }
4312
4313 cricket::VideoChannel* video_channel = channel_manager()->CreateVideoChannel(
4314 call_.get(), configuration_.media_config, rtp_dtls_transport,
Steve Antoneda6ccd2017-12-04 10:21:55 -08004315 rtcp_dtls_transport, signaling_thread(), mid, SrtpRequired(),
4316 video_options_);
Steve Anton75737c02017-11-06 10:37:17 -08004317
4318 if (!video_channel) {
4319 transport_controller_->DestroyDtlsTransport(
4320 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4321 if (rtcp_dtls_transport) {
4322 transport_controller_->DestroyDtlsTransport(
4323 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
4324 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08004325 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08004326 }
Steve Anton75737c02017-11-06 10:37:17 -08004327 video_channel->SignalRtcpMuxFullyActive.connect(
4328 this, &PeerConnection::DestroyRtcpTransport_n);
4329 video_channel->SignalDtlsSrtpSetupFailure.connect(
4330 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08004331 video_channel->SignalSentPacket.connect(this,
4332 &PeerConnection::OnSentPacket_w);
Steve Anton4171afb2017-11-20 10:20:22 -08004333
Steve Antoneda6ccd2017-12-04 10:21:55 -08004334 return video_channel;
Steve Anton75737c02017-11-06 10:37:17 -08004335}
4336
Steve Antoneda6ccd2017-12-04 10:21:55 -08004337bool PeerConnection::CreateDataChannel(const std::string& mid,
4338 const std::string& transport_name) {
Steve Anton75737c02017-11-06 10:37:17 -08004339 bool sctp = (data_channel_type_ == cricket::DCT_SCTP);
4340 if (sctp) {
4341 if (!sctp_factory_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004342 RTC_LOG(LS_ERROR)
Steve Anton75737c02017-11-06 10:37:17 -08004343 << "Trying to create SCTP transport, but didn't compile with "
4344 "SCTP support (HAVE_SCTP)";
4345 return false;
4346 }
4347 if (!network_thread()->Invoke<bool>(
4348 RTC_FROM_HERE, rtc::Bind(&PeerConnection::CreateSctpTransport_n,
Steve Antoneda6ccd2017-12-04 10:21:55 -08004349 this, mid, transport_name))) {
Steve Anton75737c02017-11-06 10:37:17 -08004350 return false;
4351 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08004352 for (const auto& channel : sctp_data_channels_) {
4353 channel->OnTransportChannelCreated();
4354 }
Steve Anton75737c02017-11-06 10:37:17 -08004355 } else {
Steve Anton75737c02017-11-06 10:37:17 -08004356 cricket::DtlsTransportInternal* rtp_dtls_transport =
4357 transport_controller_->CreateDtlsTransport(
4358 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4359 cricket::DtlsTransportInternal* rtcp_dtls_transport = nullptr;
4360 if (configuration_.rtcp_mux_policy !=
4361 PeerConnectionInterface::kRtcpMuxPolicyRequire) {
4362 rtcp_dtls_transport = transport_controller_->CreateDtlsTransport(
4363 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
4364 }
4365
4366 rtp_data_channel_ = channel_manager()->CreateRtpDataChannel(
4367 configuration_.media_config, rtp_dtls_transport, rtcp_dtls_transport,
Steve Antoneda6ccd2017-12-04 10:21:55 -08004368 signaling_thread(), mid, SrtpRequired());
Steve Anton75737c02017-11-06 10:37:17 -08004369
4370 if (!rtp_data_channel_) {
4371 transport_controller_->DestroyDtlsTransport(
4372 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4373 if (rtcp_dtls_transport) {
4374 transport_controller_->DestroyDtlsTransport(
4375 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
4376 }
4377 return false;
4378 }
4379
4380 rtp_data_channel_->SignalRtcpMuxFullyActive.connect(
4381 this, &PeerConnection::DestroyRtcpTransport_n);
4382 rtp_data_channel_->SignalDtlsSrtpSetupFailure.connect(
4383 this, &PeerConnection::OnDtlsSrtpSetupFailure);
4384 rtp_data_channel_->SignalSentPacket.connect(
4385 this, &PeerConnection::OnSentPacket_w);
4386 }
4387
Steve Anton75737c02017-11-06 10:37:17 -08004388 return true;
4389}
4390
4391Call::Stats PeerConnection::GetCallStats() {
4392 if (!worker_thread()->IsCurrent()) {
4393 return worker_thread()->Invoke<Call::Stats>(
4394 RTC_FROM_HERE, rtc::Bind(&PeerConnection::GetCallStats, this));
4395 }
4396 if (call_) {
4397 return call_->GetStats();
4398 } else {
4399 return Call::Stats();
4400 }
4401}
4402
4403std::unique_ptr<SessionStats> PeerConnection::GetSessionStats_n(
4404 const ChannelNamePairs& channel_name_pairs) {
4405 RTC_DCHECK(network_thread()->IsCurrent());
4406 std::unique_ptr<SessionStats> session_stats(new SessionStats());
4407 for (const auto channel_name_pair :
4408 {&channel_name_pairs.voice, &channel_name_pairs.video,
4409 &channel_name_pairs.data}) {
4410 if (*channel_name_pair) {
4411 cricket::TransportStats transport_stats;
4412 if (!transport_controller_->GetStats((*channel_name_pair)->transport_name,
4413 &transport_stats)) {
4414 return nullptr;
4415 }
4416 session_stats->proxy_to_transport[(*channel_name_pair)->content_name] =
4417 (*channel_name_pair)->transport_name;
4418 session_stats->transport_stats[(*channel_name_pair)->transport_name] =
4419 std::move(transport_stats);
4420 }
4421 }
4422 return session_stats;
4423}
4424
4425bool PeerConnection::CreateSctpTransport_n(const std::string& content_name,
4426 const std::string& transport_name) {
4427 RTC_DCHECK(network_thread()->IsCurrent());
4428 RTC_DCHECK(sctp_factory_);
4429 cricket::DtlsTransportInternal* tc =
4430 transport_controller_->CreateDtlsTransport_n(
4431 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4432 sctp_transport_ = sctp_factory_->CreateSctpTransport(tc);
4433 RTC_DCHECK(sctp_transport_);
4434 sctp_invoker_.reset(new rtc::AsyncInvoker());
4435 sctp_transport_->SignalReadyToSendData.connect(
4436 this, &PeerConnection::OnSctpTransportReadyToSendData_n);
4437 sctp_transport_->SignalDataReceived.connect(
4438 this, &PeerConnection::OnSctpTransportDataReceived_n);
4439 sctp_transport_->SignalStreamClosedRemotely.connect(
4440 this, &PeerConnection::OnSctpStreamClosedRemotely_n);
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004441 sctp_transport_name_ = transport_name;
4442 sctp_content_name_ = content_name;
Steve Anton75737c02017-11-06 10:37:17 -08004443 return true;
4444}
4445
4446void PeerConnection::ChangeSctpTransport_n(const std::string& transport_name) {
4447 RTC_DCHECK(network_thread()->IsCurrent());
4448 RTC_DCHECK(sctp_transport_);
4449 RTC_DCHECK(sctp_transport_name_);
4450 std::string old_sctp_transport_name = *sctp_transport_name_;
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004451 sctp_transport_name_ = transport_name;
Steve Anton75737c02017-11-06 10:37:17 -08004452 cricket::DtlsTransportInternal* tc =
4453 transport_controller_->CreateDtlsTransport_n(
4454 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4455 sctp_transport_->SetTransportChannel(tc);
4456 transport_controller_->DestroyDtlsTransport_n(
4457 old_sctp_transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4458}
4459
4460void PeerConnection::DestroySctpTransport_n() {
4461 RTC_DCHECK(network_thread()->IsCurrent());
4462 sctp_transport_.reset(nullptr);
4463 sctp_content_name_.reset();
4464 sctp_transport_name_.reset();
4465 sctp_invoker_.reset(nullptr);
4466 sctp_ready_to_send_data_ = false;
4467}
4468
4469void PeerConnection::OnSctpTransportReadyToSendData_n() {
4470 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
4471 RTC_DCHECK(network_thread()->IsCurrent());
4472 // Note: Cannot use rtc::Bind here because it will grab a reference to
4473 // PeerConnection and potentially cause PeerConnection to live longer than
4474 // expected. It is safe not to grab a reference since the sctp_invoker_ will
4475 // be destroyed before PeerConnection is destroyed, and at that point all
4476 // pending tasks will be cleared.
4477 sctp_invoker_->AsyncInvoke<void>(RTC_FROM_HERE, signaling_thread(), [this] {
4478 OnSctpTransportReadyToSendData_s(true);
4479 });
4480}
4481
4482void PeerConnection::OnSctpTransportReadyToSendData_s(bool ready) {
4483 RTC_DCHECK(signaling_thread()->IsCurrent());
4484 sctp_ready_to_send_data_ = ready;
4485 SignalSctpReadyToSendData(ready);
4486}
4487
4488void PeerConnection::OnSctpTransportDataReceived_n(
4489 const cricket::ReceiveDataParams& params,
4490 const rtc::CopyOnWriteBuffer& payload) {
4491 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
4492 RTC_DCHECK(network_thread()->IsCurrent());
4493 // Note: Cannot use rtc::Bind here because it will grab a reference to
4494 // PeerConnection and potentially cause PeerConnection to live longer than
4495 // expected. It is safe not to grab a reference since the sctp_invoker_ will
4496 // be destroyed before PeerConnection is destroyed, and at that point all
4497 // pending tasks will be cleared.
4498 sctp_invoker_->AsyncInvoke<void>(
4499 RTC_FROM_HERE, signaling_thread(), [this, params, payload] {
4500 OnSctpTransportDataReceived_s(params, payload);
4501 });
4502}
4503
4504void PeerConnection::OnSctpTransportDataReceived_s(
4505 const cricket::ReceiveDataParams& params,
4506 const rtc::CopyOnWriteBuffer& payload) {
4507 RTC_DCHECK(signaling_thread()->IsCurrent());
4508 if (params.type == cricket::DMT_CONTROL && IsOpenMessage(payload)) {
4509 // Received OPEN message; parse and signal that a new data channel should
4510 // be created.
4511 std::string label;
4512 InternalDataChannelInit config;
4513 config.id = params.ssrc;
4514 if (!ParseDataChannelOpenMessage(payload, &label, &config)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004515 RTC_LOG(LS_WARNING) << "Failed to parse the OPEN message for sid "
4516 << params.ssrc;
Steve Anton75737c02017-11-06 10:37:17 -08004517 return;
4518 }
4519 config.open_handshake_role = InternalDataChannelInit::kAcker;
4520 OnDataChannelOpenMessage(label, config);
4521 } else {
4522 // Otherwise just forward the signal.
4523 SignalSctpDataReceived(params, payload);
4524 }
4525}
4526
4527void PeerConnection::OnSctpStreamClosedRemotely_n(int sid) {
4528 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
4529 RTC_DCHECK(network_thread()->IsCurrent());
4530 sctp_invoker_->AsyncInvoke<void>(
4531 RTC_FROM_HERE, signaling_thread(),
4532 rtc::Bind(&sigslot::signal1<int>::operator(),
4533 &SignalSctpStreamClosedRemotely, sid));
4534}
4535
4536// Returns false if bundle is enabled and rtcp_mux is disabled.
4537bool PeerConnection::ValidateBundleSettings(const SessionDescription* desc) {
4538 bool bundle_enabled = desc->HasGroup(cricket::GROUP_TYPE_BUNDLE);
4539 if (!bundle_enabled)
4540 return true;
4541
4542 const cricket::ContentGroup* bundle_group =
4543 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
4544 RTC_DCHECK(bundle_group != NULL);
4545
4546 const cricket::ContentInfos& contents = desc->contents();
4547 for (cricket::ContentInfos::const_iterator citer = contents.begin();
4548 citer != contents.end(); ++citer) {
4549 const cricket::ContentInfo* content = (&*citer);
4550 RTC_DCHECK(content != NULL);
4551 if (bundle_group->HasContentName(content->name) && !content->rejected &&
4552 content->type == cricket::NS_JINGLE_RTP) {
4553 if (!HasRtcpMuxEnabled(content))
4554 return false;
4555 }
4556 }
4557 // RTCP-MUX is enabled in all the contents.
4558 return true;
4559}
4560
4561bool PeerConnection::HasRtcpMuxEnabled(const cricket::ContentInfo* content) {
4562 const cricket::MediaContentDescription* description =
4563 static_cast<cricket::MediaContentDescription*>(content->description);
4564 return description->rtcp_mux();
4565}
4566
Steve Anton8a006912017-12-04 15:25:56 -08004567RTCError PeerConnection::ValidateSessionDescription(
Steve Anton75737c02017-11-06 10:37:17 -08004568 const SessionDescriptionInterface* sdesc,
Steve Anton8a006912017-12-04 15:25:56 -08004569 cricket::ContentSource source) {
Steve Antonf8470812017-12-04 10:46:21 -08004570 if (session_error() != SessionError::kNone) {
Steve Anton8a006912017-12-04 15:25:56 -08004571 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
Steve Anton75737c02017-11-06 10:37:17 -08004572 }
4573
4574 if (!sdesc || !sdesc->description()) {
Steve Anton8a006912017-12-04 15:25:56 -08004575 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidSdp);
Steve Anton75737c02017-11-06 10:37:17 -08004576 }
4577
Steve Anton3828c062017-12-06 10:34:51 -08004578 SdpType type = sdesc->GetType();
4579 if ((source == cricket::CS_LOCAL && !ExpectSetLocalDescription(type)) ||
4580 (source == cricket::CS_REMOTE && !ExpectSetRemoteDescription(type))) {
Steve Anton8a006912017-12-04 15:25:56 -08004581 LOG_AND_RETURN_ERROR(
4582 RTCErrorType::INVALID_PARAMETER,
4583 "Called in wrong state: " + GetSignalingStateString(signaling_state()));
Steve Anton75737c02017-11-06 10:37:17 -08004584 }
4585
4586 // Verify crypto settings.
4587 std::string crypto_error;
Steve Anton8a006912017-12-04 15:25:56 -08004588 if (webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED ||
4589 dtls_enabled_) {
4590 RTCError crypto_error = VerifyCrypto(sdesc->description(), dtls_enabled_);
4591 if (!crypto_error.ok()) {
4592 return crypto_error;
4593 }
Steve Anton75737c02017-11-06 10:37:17 -08004594 }
4595
4596 // Verify ice-ufrag and ice-pwd.
4597 if (!VerifyIceUfragPwdPresent(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08004598 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
4599 kSdpWithoutIceUfragPwd);
Steve Anton75737c02017-11-06 10:37:17 -08004600 }
4601
4602 if (!ValidateBundleSettings(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08004603 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
4604 kBundleWithoutRtcpMux);
Steve Anton75737c02017-11-06 10:37:17 -08004605 }
4606
4607 // TODO(skvlad): When the local rtcp-mux policy is Require, reject any
4608 // m-lines that do not rtcp-mux enabled.
4609
4610 // Verify m-lines in Answer when compared against Offer.
Steve Anton3828c062017-12-06 10:34:51 -08004611 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Anton75737c02017-11-06 10:37:17 -08004612 const cricket::SessionDescription* offer_desc =
4613 (source == cricket::CS_LOCAL) ? remote_description()->description()
4614 : local_description()->description();
4615 if (!MediaSectionsHaveSameCount(offer_desc, sdesc->description()) ||
4616 !MediaSectionsInSameOrder(offer_desc, sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08004617 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
4618 kMlineMismatchInAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08004619 }
4620 } else {
4621 const cricket::SessionDescription* current_desc = nullptr;
4622 if (source == cricket::CS_LOCAL && local_description()) {
4623 current_desc = local_description()->description();
4624 } else if (source == cricket::CS_REMOTE && remote_description()) {
4625 current_desc = remote_description()->description();
4626 }
4627 // The re-offers should respect the order of m= sections in current
4628 // description. See RFC3264 Section 8 paragraph 4 for more details.
4629 if (current_desc &&
4630 !MediaSectionsInSameOrder(current_desc, sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08004631 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
4632 kMlineMismatchInSubsequentOffer);
Steve Anton75737c02017-11-06 10:37:17 -08004633 }
4634 }
4635
Steve Anton8a006912017-12-04 15:25:56 -08004636 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08004637}
4638
Steve Anton3828c062017-12-06 10:34:51 -08004639bool PeerConnection::ExpectSetLocalDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08004640 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08004641 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08004642 return (state == PeerConnectionInterface::kStable) ||
4643 (state == PeerConnectionInterface::kHaveLocalOffer);
Steve Anton20393062017-12-04 16:24:52 -08004644 } else {
Steve Anton3828c062017-12-06 10:34:51 -08004645 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08004646 return (state == PeerConnectionInterface::kHaveRemoteOffer) ||
4647 (state == PeerConnectionInterface::kHaveLocalPrAnswer);
4648 }
4649}
4650
Steve Anton3828c062017-12-06 10:34:51 -08004651bool PeerConnection::ExpectSetRemoteDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08004652 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08004653 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08004654 return (state == PeerConnectionInterface::kStable) ||
4655 (state == PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton20393062017-12-04 16:24:52 -08004656 } else {
Steve Anton3828c062017-12-06 10:34:51 -08004657 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08004658 return (state == PeerConnectionInterface::kHaveLocalOffer) ||
4659 (state == PeerConnectionInterface::kHaveRemotePrAnswer);
4660 }
4661}
4662
Steve Antonf8470812017-12-04 10:46:21 -08004663const char* PeerConnection::SessionErrorToString(SessionError error) const {
4664 switch (error) {
4665 case SessionError::kNone:
4666 return "ERROR_NONE";
4667 case SessionError::kContent:
4668 return "ERROR_CONTENT";
4669 case SessionError::kTransport:
4670 return "ERROR_TRANSPORT";
4671 }
4672 RTC_NOTREACHED();
4673 return "";
4674}
4675
Steve Anton75737c02017-11-06 10:37:17 -08004676std::string PeerConnection::GetSessionErrorMsg() {
4677 std::ostringstream desc;
Steve Antonf8470812017-12-04 10:46:21 -08004678 desc << kSessionError << SessionErrorToString(session_error()) << ". ";
4679 desc << kSessionErrorDesc << session_error_desc() << ".";
Steve Anton75737c02017-11-06 10:37:17 -08004680 return desc.str();
4681}
4682
4683// We need to check the local/remote description for the Transport instead of
4684// the session, because a new Transport added during renegotiation may have
4685// them unset while the session has them set from the previous negotiation.
4686// Not doing so may trigger the auto generation of transport description and
4687// mess up DTLS identity information, ICE credential, etc.
4688bool PeerConnection::ReadyToUseRemoteCandidate(
4689 const IceCandidateInterface* candidate,
4690 const SessionDescriptionInterface* remote_desc,
4691 bool* valid) {
4692 *valid = true;
4693
4694 const SessionDescriptionInterface* current_remote_desc =
4695 remote_desc ? remote_desc : remote_description();
4696
4697 if (!current_remote_desc) {
4698 return false;
4699 }
4700
4701 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
4702 size_t remote_content_size =
4703 current_remote_desc->description()->contents().size();
4704 if (mediacontent_index >= remote_content_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004705 RTC_LOG(LS_ERROR)
4706 << "ReadyToUseRemoteCandidate: Invalid candidate media index "
4707 << mediacontent_index;
Steve Anton75737c02017-11-06 10:37:17 -08004708
4709 *valid = false;
4710 return false;
4711 }
4712
4713 cricket::ContentInfo content =
4714 current_remote_desc->description()->contents()[mediacontent_index];
4715
4716 const std::string transport_name = GetTransportName(content.name);
4717 if (transport_name.empty()) {
4718 return false;
4719 }
4720 return transport_controller_->ReadyForRemoteCandidates(transport_name);
4721}
4722
4723bool PeerConnection::SrtpRequired() const {
4724 return dtls_enabled_ ||
4725 webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED;
4726}
4727
4728void PeerConnection::OnTransportControllerGatheringState(
4729 cricket::IceGatheringState state) {
4730 RTC_DCHECK(signaling_thread()->IsCurrent());
4731 if (state == cricket::kIceGatheringGathering) {
4732 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringGathering);
4733 } else if (state == cricket::kIceGatheringComplete) {
4734 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringComplete);
4735 }
4736}
4737
4738void PeerConnection::ReportTransportStats() {
4739 // Use a set so we don't report the same stats twice if two channels share
4740 // a transport.
4741 std::set<std::string> transport_names;
4742 if (voice_channel()) {
4743 transport_names.insert(voice_channel()->transport_name());
4744 }
4745 if (video_channel()) {
4746 transport_names.insert(video_channel()->transport_name());
4747 }
4748 if (rtp_data_channel()) {
4749 transport_names.insert(rtp_data_channel()->transport_name());
4750 }
4751 if (sctp_transport_name_) {
4752 transport_names.insert(*sctp_transport_name_);
4753 }
4754 for (const auto& name : transport_names) {
4755 cricket::TransportStats stats;
4756 if (transport_controller_->GetStats(name, &stats)) {
4757 ReportBestConnectionState(stats);
4758 ReportNegotiatedCiphers(stats);
4759 }
4760 }
4761}
4762// Walk through the ConnectionInfos to gather best connection usage
4763// for IPv4 and IPv6.
4764void PeerConnection::ReportBestConnectionState(
4765 const cricket::TransportStats& stats) {
4766 RTC_DCHECK(metrics_observer());
4767 for (cricket::TransportChannelStatsList::const_iterator it =
4768 stats.channel_stats.begin();
4769 it != stats.channel_stats.end(); ++it) {
4770 for (cricket::ConnectionInfos::const_iterator it_info =
4771 it->connection_infos.begin();
4772 it_info != it->connection_infos.end(); ++it_info) {
4773 if (!it_info->best_connection) {
4774 continue;
4775 }
4776
4777 PeerConnectionEnumCounterType type = kPeerConnectionEnumCounterMax;
4778 const cricket::Candidate& local = it_info->local_candidate;
4779 const cricket::Candidate& remote = it_info->remote_candidate;
4780
4781 // Increment the counter for IceCandidatePairType.
4782 if (local.protocol() == cricket::TCP_PROTOCOL_NAME ||
4783 (local.type() == RELAY_PORT_TYPE &&
4784 local.relay_protocol() == cricket::TCP_PROTOCOL_NAME)) {
4785 type = kEnumCounterIceCandidatePairTypeTcp;
4786 } else if (local.protocol() == cricket::UDP_PROTOCOL_NAME) {
4787 type = kEnumCounterIceCandidatePairTypeUdp;
4788 } else {
4789 RTC_CHECK(0);
4790 }
4791 metrics_observer()->IncrementEnumCounter(
4792 type, GetIceCandidatePairCounter(local, remote),
4793 kIceCandidatePairMax);
4794
4795 // Increment the counter for IP type.
4796 if (local.address().family() == AF_INET) {
4797 metrics_observer()->IncrementEnumCounter(
4798 kEnumCounterAddressFamily, kBestConnections_IPv4,
4799 kPeerConnectionAddressFamilyCounter_Max);
4800
4801 } else if (local.address().family() == AF_INET6) {
4802 metrics_observer()->IncrementEnumCounter(
4803 kEnumCounterAddressFamily, kBestConnections_IPv6,
4804 kPeerConnectionAddressFamilyCounter_Max);
4805 } else {
4806 RTC_CHECK(0);
4807 }
4808
4809 return;
4810 }
4811 }
4812}
4813
4814void PeerConnection::ReportNegotiatedCiphers(
4815 const cricket::TransportStats& stats) {
4816 RTC_DCHECK(metrics_observer());
4817 if (!dtls_enabled_ || stats.channel_stats.empty()) {
4818 return;
4819 }
4820
4821 int srtp_crypto_suite = stats.channel_stats[0].srtp_crypto_suite;
4822 int ssl_cipher_suite = stats.channel_stats[0].ssl_cipher_suite;
4823 if (srtp_crypto_suite == rtc::SRTP_INVALID_CRYPTO_SUITE &&
4824 ssl_cipher_suite == rtc::TLS_NULL_WITH_NULL_NULL) {
4825 return;
4826 }
4827
4828 PeerConnectionEnumCounterType srtp_counter_type;
4829 PeerConnectionEnumCounterType ssl_counter_type;
4830 if (stats.transport_name == cricket::CN_AUDIO) {
4831 srtp_counter_type = kEnumCounterAudioSrtpCipher;
4832 ssl_counter_type = kEnumCounterAudioSslCipher;
4833 } else if (stats.transport_name == cricket::CN_VIDEO) {
4834 srtp_counter_type = kEnumCounterVideoSrtpCipher;
4835 ssl_counter_type = kEnumCounterVideoSslCipher;
4836 } else if (stats.transport_name == cricket::CN_DATA) {
4837 srtp_counter_type = kEnumCounterDataSrtpCipher;
4838 ssl_counter_type = kEnumCounterDataSslCipher;
4839 } else {
4840 RTC_NOTREACHED();
4841 return;
4842 }
4843
4844 if (srtp_crypto_suite != rtc::SRTP_INVALID_CRYPTO_SUITE) {
4845 metrics_observer()->IncrementSparseEnumCounter(srtp_counter_type,
4846 srtp_crypto_suite);
4847 }
4848 if (ssl_cipher_suite != rtc::TLS_NULL_WITH_NULL_NULL) {
4849 metrics_observer()->IncrementSparseEnumCounter(ssl_counter_type,
4850 ssl_cipher_suite);
4851 }
4852}
4853
4854void PeerConnection::OnSentPacket_w(const rtc::SentPacket& sent_packet) {
4855 RTC_DCHECK(worker_thread()->IsCurrent());
4856 RTC_DCHECK(call_);
4857 call_->OnSentPacket(sent_packet);
4858}
4859
4860const std::string PeerConnection::GetTransportName(
4861 const std::string& content_name) {
4862 cricket::BaseChannel* channel = GetChannel(content_name);
Steve Anton6fec8802017-12-04 10:37:29 -08004863 if (channel) {
4864 return channel->transport_name();
Steve Anton75737c02017-11-06 10:37:17 -08004865 }
Steve Anton6fec8802017-12-04 10:37:29 -08004866 if (sctp_transport_) {
4867 RTC_DCHECK(sctp_content_name_);
4868 RTC_DCHECK(sctp_transport_name_);
4869 if (content_name == *sctp_content_name_) {
4870 return *sctp_transport_name_;
4871 }
4872 }
4873 // Return an empty string if failed to retrieve the transport name.
4874 return "";
Steve Anton75737c02017-11-06 10:37:17 -08004875}
4876
4877void PeerConnection::DestroyRtcpTransport_n(const std::string& transport_name) {
4878 RTC_DCHECK(network_thread()->IsCurrent());
4879 transport_controller_->DestroyDtlsTransport_n(
4880 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
4881}
4882
Steve Anton6fec8802017-12-04 10:37:29 -08004883void PeerConnection::DestroyTransceiverChannel(
4884 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
4885 transceiver) {
4886 RTC_DCHECK(transceiver);
Steve Anton75737c02017-11-06 10:37:17 -08004887
Steve Anton6fec8802017-12-04 10:37:29 -08004888 cricket::BaseChannel* channel = transceiver->internal()->channel();
4889 if (channel) {
4890 transceiver->internal()->SetChannel(nullptr);
4891 DestroyBaseChannel(channel);
Steve Anton75737c02017-11-06 10:37:17 -08004892 }
4893}
4894
4895void PeerConnection::DestroyDataChannel() {
Steve Anton6fec8802017-12-04 10:37:29 -08004896 if (rtp_data_channel_) {
4897 OnDataChannelDestroyed();
4898 DestroyBaseChannel(rtp_data_channel_);
4899 rtp_data_channel_ = nullptr;
4900 }
4901
4902 // Note: Cannot use rtc::Bind to create a functor to invoke because it will
4903 // grab a reference to this PeerConnection. If this is called from the
4904 // PeerConnection destructor, the RefCountedObject vtable will have already
4905 // been destroyed (since it is a subclass of PeerConnection) and using
4906 // rtc::Bind will cause "Pure virtual function called" error to appear.
4907
4908 if (sctp_transport_) {
4909 OnDataChannelDestroyed();
4910 network_thread()->Invoke<void>(RTC_FROM_HERE,
4911 [this] { DestroySctpTransport_n(); });
4912 }
4913}
4914
4915void PeerConnection::DestroyBaseChannel(cricket::BaseChannel* channel) {
4916 RTC_DCHECK(channel);
4917 RTC_DCHECK(channel->rtp_dtls_transport());
4918
4919 // Need to cache these before destroying the base channel so that we do not
4920 // access uninitialized memory.
4921 const std::string transport_name =
4922 channel->rtp_dtls_transport()->transport_name();
4923 const bool need_to_delete_rtcp = (channel->rtcp_dtls_transport() != nullptr);
4924
4925 switch (channel->media_type()) {
4926 case cricket::MEDIA_TYPE_AUDIO:
4927 channel_manager()->DestroyVoiceChannel(
4928 static_cast<cricket::VoiceChannel*>(channel));
4929 break;
4930 case cricket::MEDIA_TYPE_VIDEO:
4931 channel_manager()->DestroyVideoChannel(
4932 static_cast<cricket::VideoChannel*>(channel));
4933 break;
4934 case cricket::MEDIA_TYPE_DATA:
4935 channel_manager()->DestroyRtpDataChannel(
4936 static_cast<cricket::RtpDataChannel*>(channel));
4937 break;
4938 default:
4939 RTC_NOTREACHED() << "Unknown media type: " << channel->media_type();
4940 break;
4941 }
4942
4943 // |channel| can no longer be used.
4944
Steve Anton75737c02017-11-06 10:37:17 -08004945 transport_controller_->DestroyDtlsTransport(
4946 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4947 if (need_to_delete_rtcp) {
4948 transport_controller_->DestroyDtlsTransport(
4949 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
4950 }
4951}
4952
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004953} // namespace webrtc