blob: da190ada3962d4f9c702920f8c5b10ee2a3d2c97 [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
Steve Anton3fe1b152017-12-12 10:20:08 -0800729 StopAndDestroyChannels();
Steve Anton4171afb2017-11-20 10:20:22 -0800730
Steve Anton3fe1b152017-12-12 10:20:08 -0800731 // Destroy stats after stopping all transceivers because the senders/receivers
732 // will update the stats collector before stopping.
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700733 stats_.reset(nullptr);
hbosb78306a2016-12-19 05:06:57 -0800734 if (stats_collector_) {
735 stats_collector_->WaitForPendingRequest();
736 stats_collector_ = nullptr;
737 }
Steve Anton75737c02017-11-06 10:37:17 -0800738
Mirko Bonadei675513b2017-11-09 11:09:25 +0100739 RTC_LOG(LS_INFO) << "Session: " << session_id() << " is destroyed.";
Steve Anton75737c02017-11-06 10:37:17 -0800740
741 webrtc_session_desc_factory_.reset();
742 sctp_invoker_.reset();
743 sctp_factory_.reset();
744 transport_controller_.reset();
745
deadbeef91dd5672016-05-18 16:55:30 -0700746 // port_allocator_ lives on the network thread and should be destroyed there.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700747 network_thread()->Invoke<void>(RTC_FROM_HERE,
nisseeaabdf62017-05-05 02:23:02 -0700748 [this] { port_allocator_.reset(); });
eladalon248fd4f2017-09-06 05:18:15 -0700749 // call_ and event_log_ must be destroyed on the worker thread.
Steve Anton978b8762017-09-29 12:15:02 -0700750 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
eladalon248fd4f2017-09-06 05:18:15 -0700751 call_.reset();
752 event_log_.reset();
753 });
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000754}
755
Steve Anton3fe1b152017-12-12 10:20:08 -0800756void PeerConnection::StopAndDestroyChannels() {
757 for (auto transceiver : transceivers_) {
758 transceiver->Stop();
759 }
760 // Destroy video channels first since they may have a pointer to a voice
761 // channel.
762 for (auto transceiver : transceivers_) {
763 if (transceiver->internal()->media_type() == cricket::MEDIA_TYPE_VIDEO) {
764 DestroyTransceiverChannel(transceiver);
765 }
766 }
767 for (auto transceiver : transceivers_) {
768 if (transceiver->internal()->media_type() == cricket::MEDIA_TYPE_AUDIO) {
769 DestroyTransceiverChannel(transceiver);
770 }
771 }
772 DestroyDataChannel();
773}
774
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000775bool PeerConnection::Initialize(
buildbot@webrtc.org41451d42014-05-03 05:39:45 +0000776 const PeerConnectionInterface::RTCConfiguration& configuration,
kwibergd1fe2812016-04-27 06:47:29 -0700777 std::unique_ptr<cricket::PortAllocator> allocator,
Henrik Boströmd03c23b2016-06-01 11:44:18 +0200778 std::unique_ptr<rtc::RTCCertificateGeneratorInterface> cert_generator,
deadbeef653b8e02015-11-11 12:55:10 -0800779 PeerConnectionObserver* observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100780 TRACE_EVENT0("webrtc", "PeerConnection::Initialize");
Steve Anton038834f2017-07-14 15:59:59 -0700781
782 RTCError config_error = ValidateConfiguration(configuration);
783 if (!config_error.ok()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100784 RTC_LOG(LS_ERROR) << "Invalid configuration: " << config_error.message();
Steve Anton038834f2017-07-14 15:59:59 -0700785 return false;
786 }
787
deadbeef293e9262017-01-11 12:28:30 -0800788 if (!allocator) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100789 RTC_LOG(LS_ERROR)
790 << "PeerConnection initialized without a PortAllocator? "
791 << "This shouldn't happen if using PeerConnectionFactory.";
deadbeef293e9262017-01-11 12:28:30 -0800792 return false;
793 }
Jonas Orelandbdcee282017-10-10 14:01:40 +0200794
deadbeef653b8e02015-11-11 12:55:10 -0800795 if (!observer) {
deadbeef293e9262017-01-11 12:28:30 -0800796 // TODO(deadbeef): Why do we do this?
Mirko Bonadei675513b2017-11-09 11:09:25 +0100797 RTC_LOG(LS_ERROR) << "PeerConnection initialized without a "
798 << "PeerConnectionObserver";
deadbeef653b8e02015-11-11 12:55:10 -0800799 return false;
800 }
pthatcher@webrtc.org877ac762015-02-04 22:03:09 +0000801 observer_ = observer;
kwiberg0eb15ed2015-12-17 03:04:15 -0800802 port_allocator_ = std::move(allocator);
deadbeef653b8e02015-11-11 12:55:10 -0800803
deadbeef91dd5672016-05-18 16:55:30 -0700804 // The port allocator lives on the network thread and should be initialized
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700805 // there.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700806 if (!network_thread()->Invoke<bool>(
807 RTC_FROM_HERE, rtc::Bind(&PeerConnection::InitializePortAllocator_n,
808 this, configuration))) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000809 return false;
810 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000811
Steve Anton75737c02017-11-06 10:37:17 -0800812 // RFC 3264: The numeric value of the session id and version in the
813 // o line MUST be representable with a "64 bit signed integer".
814 // Due to this constraint session id |session_id_| is max limited to
815 // LLONG_MAX.
816 session_id_ = rtc::ToString(rtc::CreateRandomId64() & LLONG_MAX);
817 transport_controller_.reset(factory_->CreateTransportController(
818 port_allocator_.get(), configuration.redetermine_role_on_ice_restart));
819 transport_controller_->SetIceRole(cricket::ICEROLE_CONTROLLED);
820 transport_controller_->SignalConnectionState.connect(
821 this, &PeerConnection::OnTransportControllerConnectionState);
822 transport_controller_->SignalGatheringState.connect(
823 this, &PeerConnection::OnTransportControllerGatheringState);
824 transport_controller_->SignalCandidatesGathered.connect(
825 this, &PeerConnection::OnTransportControllerCandidatesGathered);
826 transport_controller_->SignalCandidatesRemoved.connect(
827 this, &PeerConnection::OnTransportControllerCandidatesRemoved);
828 transport_controller_->SignalDtlsHandshakeError.connect(
829 this, &PeerConnection::OnTransportControllerDtlsHandshakeError);
830
831 sctp_factory_ = factory_->CreateSctpTransportInternalFactory();
zhihuang29ff8442016-07-27 11:07:25 -0700832
deadbeefab9b2d12015-10-14 11:33:11 -0700833 stats_.reset(new StatsCollector(this));
hbos74e1a4f2016-09-15 23:33:01 -0700834 stats_collector_ = RTCStatsCollector::Create(this);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000835
Steve Antonba818672017-11-06 10:21:57 -0800836 configuration_ = configuration;
837
Steve Anton75737c02017-11-06 10:37:17 -0800838 const PeerConnectionFactoryInterface::Options& options = factory_->options();
839
840 transport_controller_->SetSslMaxProtocolVersion(options.ssl_max_version);
841
842 // Obtain a certificate from RTCConfiguration if any were provided (optional).
843 rtc::scoped_refptr<rtc::RTCCertificate> certificate;
844 if (!configuration.certificates.empty()) {
845 // TODO(hbos,torbjorng): Decide on certificate-selection strategy instead of
846 // just picking the first one. The decision should be made based on the DTLS
847 // handshake. The DTLS negotiations need to know about all certificates.
848 certificate = configuration.certificates[0];
849 }
850
Steve Antond25da372017-11-06 14:50:29 -0800851 transport_controller_->SetIceConfig(ParseIceConfig(configuration));
Steve Anton75737c02017-11-06 10:37:17 -0800852
853 if (options.disable_encryption) {
854 dtls_enabled_ = false;
855 } else {
856 // Enable DTLS by default if we have an identity store or a certificate.
857 dtls_enabled_ = (cert_generator || certificate);
858 // |configuration| can override the default |dtls_enabled_| value.
859 if (configuration.enable_dtls_srtp) {
860 dtls_enabled_ = *(configuration.enable_dtls_srtp);
861 }
862 }
863
864 // Enable creation of RTP data channels if the kEnableRtpDataChannels is set.
865 // It takes precendence over the disable_sctp_data_channels
866 // PeerConnectionFactoryInterface::Options.
867 if (configuration.enable_rtp_data_channel) {
868 data_channel_type_ = cricket::DCT_RTP;
869 } else {
870 // DTLS has to be enabled to use SCTP.
871 if (!options.disable_sctp_data_channels && dtls_enabled_) {
872 data_channel_type_ = cricket::DCT_SCTP;
873 }
874 }
875
876 video_options_.screencast_min_bitrate_kbps =
877 configuration.screencast_min_bitrate;
878 audio_options_.combined_audio_video_bwe =
879 configuration.combined_audio_video_bwe;
880
881 audio_options_.audio_jitter_buffer_max_packets =
Oskar Sundbom9b28a032017-11-16 10:53:30 +0100882 configuration.audio_jitter_buffer_max_packets;
Steve Anton75737c02017-11-06 10:37:17 -0800883
884 audio_options_.audio_jitter_buffer_fast_accelerate =
Oskar Sundbom9b28a032017-11-16 10:53:30 +0100885 configuration.audio_jitter_buffer_fast_accelerate;
Steve Anton75737c02017-11-06 10:37:17 -0800886
887 // Whether the certificate generator/certificate is null or not determines
888 // what PeerConnectionDescriptionFactory will do, so make sure that we give it
889 // the right instructions by clearing the variables if needed.
890 if (!dtls_enabled_) {
891 cert_generator.reset();
892 certificate = nullptr;
893 } else if (certificate) {
894 // Favor generated certificate over the certificate generator.
895 cert_generator.reset();
896 }
897
898 webrtc_session_desc_factory_.reset(new WebRtcSessionDescriptionFactory(
899 signaling_thread(), channel_manager(), this, session_id(),
900 std::move(cert_generator), certificate));
901 webrtc_session_desc_factory_->SignalCertificateReady.connect(
902 this, &PeerConnection::OnCertificateReady);
903
904 if (options.disable_encryption) {
905 webrtc_session_desc_factory_->SetSdesPolicy(cricket::SEC_DISABLED);
906 }
907
908 webrtc_session_desc_factory_->set_enable_encrypted_rtp_header_extensions(
909 options.crypto_options.enable_encrypted_rtp_header_extensions);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000910
Steve Anton4171afb2017-11-20 10:20:22 -0800911 // Add default audio/video transceivers for Plan B SDP.
912 if (!IsUnifiedPlan()) {
913 transceivers_.push_back(
914 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
915 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_AUDIO)));
916 transceivers_.push_back(
917 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
918 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_VIDEO)));
919 }
920
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000921 return true;
922}
923
Steve Anton038834f2017-07-14 15:59:59 -0700924RTCError PeerConnection::ValidateConfiguration(
925 const RTCConfiguration& config) const {
926 if (config.ice_regather_interval_range &&
927 config.continual_gathering_policy == GATHER_ONCE) {
928 return RTCError(RTCErrorType::INVALID_PARAMETER,
929 "ice_regather_interval_range specified but continual "
930 "gathering policy is GATHER_ONCE");
931 }
932 return RTCError::OK();
933}
934
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000935rtc::scoped_refptr<StreamCollectionInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000936PeerConnection::local_streams() {
deadbeefab9b2d12015-10-14 11:33:11 -0700937 return local_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000938}
939
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000940rtc::scoped_refptr<StreamCollectionInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000941PeerConnection::remote_streams() {
deadbeefab9b2d12015-10-14 11:33:11 -0700942 return remote_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000943}
944
perkj@webrtc.orgc2dd5ee2014-11-04 11:31:29 +0000945bool PeerConnection::AddStream(MediaStreamInterface* local_stream) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100946 TRACE_EVENT0("webrtc", "PeerConnection::AddStream");
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000947 if (IsClosed()) {
948 return false;
949 }
deadbeefab9b2d12015-10-14 11:33:11 -0700950 if (!CanAddLocalMediaStream(local_streams_, local_stream)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000951 return false;
952 }
deadbeefab9b2d12015-10-14 11:33:11 -0700953
954 local_streams_->AddStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -0800955 MediaStreamObserver* observer = new MediaStreamObserver(local_stream);
956 observer->SignalAudioTrackAdded.connect(this,
957 &PeerConnection::OnAudioTrackAdded);
958 observer->SignalAudioTrackRemoved.connect(
959 this, &PeerConnection::OnAudioTrackRemoved);
960 observer->SignalVideoTrackAdded.connect(this,
961 &PeerConnection::OnVideoTrackAdded);
962 observer->SignalVideoTrackRemoved.connect(
963 this, &PeerConnection::OnVideoTrackRemoved);
kwibergd1fe2812016-04-27 06:47:29 -0700964 stream_observers_.push_back(std::unique_ptr<MediaStreamObserver>(observer));
deadbeefab9b2d12015-10-14 11:33:11 -0700965
deadbeefab9b2d12015-10-14 11:33:11 -0700966 for (const auto& track : local_stream->GetAudioTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -0700967 AddAudioTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -0700968 }
969 for (const auto& track : local_stream->GetVideoTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -0700970 AddVideoTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -0700971 }
972
tommi@webrtc.org03505bc2014-07-14 20:15:26 +0000973 stats_->AddStream(local_stream);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000974 observer_->OnRenegotiationNeeded();
975 return true;
976}
977
978void PeerConnection::RemoveStream(MediaStreamInterface* local_stream) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100979 TRACE_EVENT0("webrtc", "PeerConnection::RemoveStream");
korniltsev.anatolyec390b52017-07-24 17:00:25 -0700980 if (!IsClosed()) {
981 for (const auto& track : local_stream->GetAudioTracks()) {
982 RemoveAudioTrack(track.get(), local_stream);
983 }
984 for (const auto& track : local_stream->GetVideoTracks()) {
985 RemoveVideoTrack(track.get(), local_stream);
986 }
deadbeefab9b2d12015-10-14 11:33:11 -0700987 }
deadbeefab9b2d12015-10-14 11:33:11 -0700988 local_streams_->RemoveStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -0800989 stream_observers_.erase(
990 std::remove_if(
991 stream_observers_.begin(), stream_observers_.end(),
kwibergd1fe2812016-04-27 06:47:29 -0700992 [local_stream](const std::unique_ptr<MediaStreamObserver>& observer) {
deadbeefeb459812015-12-15 19:24:43 -0800993 return observer->stream()->label().compare(local_stream->label()) ==
994 0;
995 }),
996 stream_observers_.end());
deadbeefab9b2d12015-10-14 11:33:11 -0700997
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000998 if (IsClosed()) {
999 return;
1000 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001001 observer_->OnRenegotiationNeeded();
1002}
1003
deadbeefe1f9d832016-01-14 15:35:42 -08001004rtc::scoped_refptr<RtpSenderInterface> PeerConnection::AddTrack(
1005 MediaStreamTrackInterface* track,
1006 std::vector<MediaStreamInterface*> streams) {
1007 TRACE_EVENT0("webrtc", "PeerConnection::AddTrack");
1008 if (IsClosed()) {
1009 return nullptr;
1010 }
1011 if (streams.size() >= 2) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001012 RTC_LOG(LS_ERROR)
deadbeefe1f9d832016-01-14 15:35:42 -08001013 << "Adding a track with two streams is not currently supported.";
1014 return nullptr;
1015 }
Steve Anton4171afb2017-11-20 10:20:22 -08001016 if (FindSenderForTrack(track)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001017 RTC_LOG(LS_ERROR) << "Sender for track " << track->id()
1018 << " already exists.";
deadbeefe1f9d832016-01-14 15:35:42 -08001019 return nullptr;
1020 }
1021
1022 // TODO(deadbeef): Support adding a track to multiple streams.
deadbeefa601f5c2016-06-06 14:27:39 -07001023 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender;
deadbeefe1f9d832016-01-14 15:35:42 -08001024 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
deadbeefa601f5c2016-06-06 14:27:39 -07001025 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
deadbeefe1f9d832016-01-14 15:35:42 -08001026 signaling_thread(),
1027 new AudioRtpSender(static_cast<AudioTrackInterface*>(track),
Steve Anton75737c02017-11-06 10:37:17 -08001028 voice_channel(), stats_.get()));
Steve Anton4171afb2017-11-20 10:20:22 -08001029 GetAudioTransceiver()->internal()->AddSender(new_sender);
deadbeefe1f9d832016-01-14 15:35:42 -08001030 if (!streams.empty()) {
deadbeefa601f5c2016-06-06 14:27:39 -07001031 new_sender->internal()->set_stream_id(streams[0]->label());
deadbeefe1f9d832016-01-14 15:35:42 -08001032 }
Steve Anton4171afb2017-11-20 10:20:22 -08001033 const RtpSenderInfo* sender_info =
1034 FindSenderInfo(local_audio_sender_infos_,
1035 new_sender->internal()->stream_id(), track->id());
1036 if (sender_info) {
1037 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -08001038 }
1039 } else if (track->kind() == MediaStreamTrackInterface::kVideoKind) {
deadbeefa601f5c2016-06-06 14:27:39 -07001040 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
deadbeefe1f9d832016-01-14 15:35:42 -08001041 signaling_thread(),
1042 new VideoRtpSender(static_cast<VideoTrackInterface*>(track),
Steve Anton75737c02017-11-06 10:37:17 -08001043 video_channel()));
Steve Anton4171afb2017-11-20 10:20:22 -08001044 GetVideoTransceiver()->internal()->AddSender(new_sender);
deadbeefe1f9d832016-01-14 15:35:42 -08001045 if (!streams.empty()) {
deadbeefa601f5c2016-06-06 14:27:39 -07001046 new_sender->internal()->set_stream_id(streams[0]->label());
deadbeefe1f9d832016-01-14 15:35:42 -08001047 }
Steve Anton4171afb2017-11-20 10:20:22 -08001048 const RtpSenderInfo* sender_info =
1049 FindSenderInfo(local_video_sender_infos_,
1050 new_sender->internal()->stream_id(), track->id());
1051 if (sender_info) {
1052 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -08001053 }
1054 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001055 RTC_LOG(LS_ERROR) << "CreateSender called with invalid kind: "
1056 << track->kind();
deadbeefe1f9d832016-01-14 15:35:42 -08001057 return rtc::scoped_refptr<RtpSenderInterface>();
1058 }
1059
deadbeefe1f9d832016-01-14 15:35:42 -08001060 observer_->OnRenegotiationNeeded();
1061 return new_sender;
1062}
1063
1064bool PeerConnection::RemoveTrack(RtpSenderInterface* sender) {
1065 TRACE_EVENT0("webrtc", "PeerConnection::RemoveTrack");
1066 if (IsClosed()) {
1067 return false;
1068 }
1069
Steve Anton4171afb2017-11-20 10:20:22 -08001070 bool removed;
1071 if (sender->media_type() == cricket::MEDIA_TYPE_AUDIO) {
1072 removed = GetAudioTransceiver()->internal()->RemoveSender(sender);
1073 } else {
1074 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, sender->media_type());
1075 removed = GetVideoTransceiver()->internal()->RemoveSender(sender);
1076 }
1077 if (!removed) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001078 RTC_LOG(LS_ERROR) << "Couldn't find sender " << sender->id()
1079 << " to remove.";
deadbeefe1f9d832016-01-14 15:35:42 -08001080 return false;
1081 }
deadbeefe1f9d832016-01-14 15:35:42 -08001082
1083 observer_->OnRenegotiationNeeded();
1084 return true;
1085}
1086
Steve Anton9158ef62017-11-27 13:01:52 -08001087RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1088PeerConnection::AddTransceiver(
1089 rtc::scoped_refptr<MediaStreamTrackInterface> track) {
1090 return AddTransceiver(track, RtpTransceiverInit());
1091}
1092
1093RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1094PeerConnection::AddTransceiver(
1095 rtc::scoped_refptr<MediaStreamTrackInterface> track,
1096 const RtpTransceiverInit& init) {
1097 if (!IsUnifiedPlan()) {
1098 LOG_AND_RETURN_ERROR(
1099 RTCErrorType::INTERNAL_ERROR,
1100 "AddTransceiver only supported when Unified Plan is enabled.");
1101 }
1102 if (!track) {
1103 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "track is null");
1104 }
1105 cricket::MediaType media_type;
1106 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
1107 media_type = cricket::MEDIA_TYPE_AUDIO;
1108 } else if (track->kind() == MediaStreamTrackInterface::kVideoKind) {
1109 media_type = cricket::MEDIA_TYPE_VIDEO;
1110 } else {
1111 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1112 "Track kind is not audio or video");
1113 }
1114 return AddTransceiver(media_type, track, init);
1115}
1116
1117RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1118PeerConnection::AddTransceiver(cricket::MediaType media_type) {
1119 return AddTransceiver(media_type, RtpTransceiverInit());
1120}
1121
1122RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1123PeerConnection::AddTransceiver(cricket::MediaType media_type,
1124 const RtpTransceiverInit& init) {
1125 if (!IsUnifiedPlan()) {
1126 LOG_AND_RETURN_ERROR(
1127 RTCErrorType::INTERNAL_ERROR,
1128 "AddTransceiver only supported when Unified Plan is enabled.");
1129 }
1130 if (!(media_type == cricket::MEDIA_TYPE_AUDIO ||
1131 media_type == cricket::MEDIA_TYPE_VIDEO)) {
1132 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1133 "media type is not audio or video");
1134 }
1135 return AddTransceiver(media_type, nullptr, init);
1136}
1137
1138RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1139PeerConnection::AddTransceiver(
1140 cricket::MediaType media_type,
1141 rtc::scoped_refptr<MediaStreamTrackInterface> track,
1142 const RtpTransceiverInit& init) {
1143 RTC_DCHECK((media_type == cricket::MEDIA_TYPE_AUDIO ||
1144 media_type == cricket::MEDIA_TYPE_VIDEO));
1145 if (track) {
1146 RTC_DCHECK_EQ(media_type,
1147 (track->kind() == MediaStreamTrackInterface::kAudioKind
1148 ? cricket::MEDIA_TYPE_AUDIO
1149 : cricket::MEDIA_TYPE_VIDEO));
1150 }
1151
1152 // TODO(bugs.webrtc.org/7600): Verify init.
1153
1154 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> sender;
1155 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1156 receiver;
1157 std::string receiver_id = rtc::CreateRandomUuid();
1158 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
1159 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
1160 signaling_thread(), new AudioRtpSender(nullptr, stats_.get()));
1161 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
1162 signaling_thread(), new AudioRtpReceiver(receiver_id, {}, 0, nullptr));
1163 } else {
1164 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, media_type);
1165 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
1166 signaling_thread(), new VideoRtpSender(nullptr));
1167 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
1168 signaling_thread(),
1169 new VideoRtpReceiver(receiver_id, {}, worker_thread(), 0, nullptr));
1170 }
1171 // TODO(bugs.webrtc.org/7600): Initializing the sender/receiver with a null
1172 // channel prevents users from calling SetParameters on them, which is needed
1173 // to be in compliance with the spec.
1174
1175 if (track) {
1176 sender->SetTrack(track);
1177 }
1178
1179 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1180 transceiver = RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1181 signaling_thread(), new RtpTransceiver(sender, receiver));
1182 transceiver->SetDirection(init.direction);
1183
1184 transceivers_.push_back(transceiver);
1185
1186 observer_->OnRenegotiationNeeded();
1187
1188 return rtc::scoped_refptr<RtpTransceiverInterface>(transceiver);
1189}
1190
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001191rtc::scoped_refptr<DtmfSenderInterface> PeerConnection::CreateDtmfSender(
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001192 AudioTrackInterface* track) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001193 TRACE_EVENT0("webrtc", "PeerConnection::CreateDtmfSender");
zhihuang29ff8442016-07-27 11:07:25 -07001194 if (IsClosed()) {
1195 return nullptr;
1196 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001197 if (!track) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001198 RTC_LOG(LS_ERROR) << "CreateDtmfSender - track is NULL.";
deadbeef20cb0c12017-02-01 20:27:00 -08001199 return nullptr;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001200 }
Steve Anton4171afb2017-11-20 10:20:22 -08001201 auto track_sender = FindSenderForTrack(track);
1202 if (!track_sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001203 RTC_LOG(LS_ERROR) << "CreateDtmfSender called with a non-added track.";
deadbeef20cb0c12017-02-01 20:27:00 -08001204 return nullptr;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001205 }
1206
Steve Anton4171afb2017-11-20 10:20:22 -08001207 return track_sender->GetDtmfSender();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001208}
1209
deadbeeffac06552015-11-25 11:26:01 -08001210rtc::scoped_refptr<RtpSenderInterface> PeerConnection::CreateSender(
deadbeefbd7d8f72015-12-18 16:58:44 -08001211 const std::string& kind,
1212 const std::string& stream_id) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001213 TRACE_EVENT0("webrtc", "PeerConnection::CreateSender");
zhihuang29ff8442016-07-27 11:07:25 -07001214 if (IsClosed()) {
1215 return nullptr;
1216 }
Steve Anton4171afb2017-11-20 10:20:22 -08001217
1218 // TODO(steveanton): Move construction of the RtpSenders to RtpTransceiver.
deadbeefa601f5c2016-06-06 14:27:39 -07001219 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender;
deadbeeffac06552015-11-25 11:26:01 -08001220 if (kind == MediaStreamTrackInterface::kAudioKind) {
deadbeefa601f5c2016-06-06 14:27:39 -07001221 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton75737c02017-11-06 10:37:17 -08001222 signaling_thread(), new AudioRtpSender(voice_channel(), stats_.get()));
Steve Anton4171afb2017-11-20 10:20:22 -08001223 GetAudioTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 11:26:01 -08001224 } else if (kind == MediaStreamTrackInterface::kVideoKind) {
deadbeefa601f5c2016-06-06 14:27:39 -07001225 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton75737c02017-11-06 10:37:17 -08001226 signaling_thread(), new VideoRtpSender(video_channel()));
Steve Anton4171afb2017-11-20 10:20:22 -08001227 GetVideoTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 11:26:01 -08001228 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001229 RTC_LOG(LS_ERROR) << "CreateSender called with invalid kind: " << kind;
Steve Anton4171afb2017-11-20 10:20:22 -08001230 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08001231 }
Steve Anton4171afb2017-11-20 10:20:22 -08001232
deadbeefbd7d8f72015-12-18 16:58:44 -08001233 if (!stream_id.empty()) {
deadbeefa601f5c2016-06-06 14:27:39 -07001234 new_sender->internal()->set_stream_id(stream_id);
deadbeefbd7d8f72015-12-18 16:58:44 -08001235 }
Steve Anton4171afb2017-11-20 10:20:22 -08001236
deadbeefe1f9d832016-01-14 15:35:42 -08001237 return new_sender;
deadbeeffac06552015-11-25 11:26:01 -08001238}
1239
deadbeef70ab1a12015-09-28 16:53:55 -07001240std::vector<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::GetSenders()
1241 const {
deadbeefa601f5c2016-06-06 14:27:39 -07001242 std::vector<rtc::scoped_refptr<RtpSenderInterface>> ret;
Steve Anton4171afb2017-11-20 10:20:22 -08001243 for (auto sender : GetSendersInternal()) {
1244 ret.push_back(sender);
deadbeefa601f5c2016-06-06 14:27:39 -07001245 }
1246 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -07001247}
1248
Steve Anton4171afb2017-11-20 10:20:22 -08001249std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1250PeerConnection::GetSendersInternal() const {
1251 std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1252 all_senders;
1253 for (auto transceiver : transceivers_) {
1254 auto senders = transceiver->internal()->senders();
1255 all_senders.insert(all_senders.end(), senders.begin(), senders.end());
1256 }
1257 return all_senders;
1258}
1259
deadbeef70ab1a12015-09-28 16:53:55 -07001260std::vector<rtc::scoped_refptr<RtpReceiverInterface>>
1261PeerConnection::GetReceivers() const {
deadbeefa601f5c2016-06-06 14:27:39 -07001262 std::vector<rtc::scoped_refptr<RtpReceiverInterface>> ret;
Steve Anton4171afb2017-11-20 10:20:22 -08001263 for (const auto& receiver : GetReceiversInternal()) {
1264 ret.push_back(receiver);
deadbeefa601f5c2016-06-06 14:27:39 -07001265 }
1266 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -07001267}
1268
Steve Anton4171afb2017-11-20 10:20:22 -08001269std::vector<
1270 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1271PeerConnection::GetReceiversInternal() const {
1272 std::vector<
1273 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1274 all_receivers;
1275 for (auto transceiver : transceivers_) {
1276 auto receivers = transceiver->internal()->receivers();
1277 all_receivers.insert(all_receivers.end(), receivers.begin(),
1278 receivers.end());
1279 }
1280 return all_receivers;
1281}
1282
Steve Anton9158ef62017-11-27 13:01:52 -08001283std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
1284PeerConnection::GetTransceivers() const {
1285 RTC_DCHECK(IsUnifiedPlan());
1286 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> all_transceivers;
1287 for (auto transceiver : transceivers_) {
1288 all_transceivers.push_back(transceiver);
1289 }
1290 return all_transceivers;
1291}
1292
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001293bool PeerConnection::GetStats(StatsObserver* observer,
wu@webrtc.orgb9a088b2014-02-13 23:18:49 +00001294 MediaStreamTrackInterface* track,
1295 StatsOutputLevel level) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001296 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
deadbeef0a6c4ca2015-10-06 11:38:28 -07001297 RTC_DCHECK(signaling_thread()->IsCurrent());
nisse7ce109a2017-01-31 00:57:56 -08001298 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001299 RTC_LOG(LS_ERROR) << "GetStats - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001300 return false;
1301 }
1302
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001303 stats_->UpdateStats(level);
zhihuange9e94c32016-11-04 11:38:15 -07001304 // The StatsCollector is used to tell if a track is valid because it may
1305 // remember tracks that the PeerConnection previously removed.
1306 if (track && !stats_->IsValidTrack(track->id())) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001307 RTC_LOG(LS_WARNING) << "GetStats is called with an invalid track: "
1308 << track->id();
zhihuange9e94c32016-11-04 11:38:15 -07001309 return false;
1310 }
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001311 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_GETSTATS,
tommi@webrtc.org5b06b062014-08-15 08:38:30 +00001312 new GetStatsMsg(observer, track));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001313 return true;
1314}
1315
hbos74e1a4f2016-09-15 23:33:01 -07001316void PeerConnection::GetStats(RTCStatsCollectorCallback* callback) {
1317 RTC_DCHECK(stats_collector_);
1318 stats_collector_->GetStatsReport(callback);
1319}
1320
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001321PeerConnectionInterface::SignalingState PeerConnection::signaling_state() {
1322 return signaling_state_;
1323}
1324
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001325PeerConnectionInterface::IceConnectionState
1326PeerConnection::ice_connection_state() {
1327 return ice_connection_state_;
1328}
1329
1330PeerConnectionInterface::IceGatheringState
1331PeerConnection::ice_gathering_state() {
1332 return ice_gathering_state_;
1333}
1334
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001335rtc::scoped_refptr<DataChannelInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001336PeerConnection::CreateDataChannel(
1337 const std::string& label,
1338 const DataChannelInit* config) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001339 TRACE_EVENT0("webrtc", "PeerConnection::CreateDataChannel");
zhihuang9763d562016-08-05 11:14:50 -07001340
deadbeefab9b2d12015-10-14 11:33:11 -07001341 bool first_datachannel = !HasDataChannels();
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001342
kwibergd1fe2812016-04-27 06:47:29 -07001343 std::unique_ptr<InternalDataChannelInit> internal_config;
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00001344 if (config) {
1345 internal_config.reset(new InternalDataChannelInit(*config));
1346 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001347 rtc::scoped_refptr<DataChannelInterface> channel(
deadbeefab9b2d12015-10-14 11:33:11 -07001348 InternalCreateDataChannel(label, internal_config.get()));
1349 if (!channel.get()) {
1350 return nullptr;
1351 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001352
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001353 // Trigger the onRenegotiationNeeded event for every new RTP DataChannel, or
1354 // the first SCTP DataChannel.
Steve Anton75737c02017-11-06 10:37:17 -08001355 if (data_channel_type() == cricket::DCT_RTP || first_datachannel) {
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001356 observer_->OnRenegotiationNeeded();
1357 }
wu@webrtc.org91053e72013-08-10 07:18:04 +00001358
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001359 return DataChannelProxy::Create(signaling_thread(), channel.get());
1360}
1361
1362void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
1363 const MediaConstraintsInterface* constraints) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001364 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
Steve Anton8d3444d2017-10-20 15:30:51 -07001365
zhihuang1c378ed2017-08-17 14:10:50 -07001366 PeerConnectionInterface::RTCOfferAnswerOptions offer_answer_options;
1367 // Always create an offer even if |ConvertConstraintsToOfferAnswerOptions|
1368 // returns false for now. Because |ConvertConstraintsToOfferAnswerOptions|
1369 // compares the mandatory fields parsed with the mandatory fields added in the
1370 // |constraints| and some downstream applications might create offers with
1371 // mandatory fields which would not be parsed in the helper method. For
1372 // example, in Chromium/remoting, |kEnableDtlsSrtp| is added to the
1373 // |constraints| as a mandatory field but it is not parsed.
1374 ConvertConstraintsToOfferAnswerOptions(constraints, &offer_answer_options);
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001375
zhihuang1c378ed2017-08-17 14:10:50 -07001376 CreateOffer(observer, offer_answer_options);
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001377}
1378
1379void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
1380 const RTCOfferAnswerOptions& options) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001381 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
Steve Anton8d3444d2017-10-20 15:30:51 -07001382
nisse7ce109a2017-01-31 00:57:56 -08001383 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001384 RTC_LOG(LS_ERROR) << "CreateOffer - observer is NULL.";
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001385 return;
1386 }
deadbeefab9b2d12015-10-14 11:33:11 -07001387
Steve Anton8d3444d2017-10-20 15:30:51 -07001388 if (IsClosed()) {
1389 std::string error = "CreateOffer called when PeerConnection is closed.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001390 RTC_LOG(LS_ERROR) << error;
Steve Anton8d3444d2017-10-20 15:30:51 -07001391 PostCreateSessionDescriptionFailure(observer, error);
1392 return;
1393 }
1394
zhihuang1c378ed2017-08-17 14:10:50 -07001395 if (!ValidateOfferAnswerOptions(options)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001396 std::string error = "CreateOffer called with invalid options.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001397 RTC_LOG(LS_ERROR) << error;
deadbeefab9b2d12015-10-14 11:33:11 -07001398 PostCreateSessionDescriptionFailure(observer, error);
1399 return;
1400 }
1401
zhihuang1c378ed2017-08-17 14:10:50 -07001402 cricket::MediaSessionOptions session_options;
1403 GetOptionsForOffer(options, &session_options);
Steve Antond25da372017-11-06 14:50:29 -08001404 webrtc_session_desc_factory_->CreateOffer(observer, options, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001405}
1406
1407void PeerConnection::CreateAnswer(
1408 CreateSessionDescriptionObserver* observer,
1409 const MediaConstraintsInterface* constraints) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001410 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
Steve Anton8d3444d2017-10-20 15:30:51 -07001411
nisse7ce109a2017-01-31 00:57:56 -08001412 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001413 RTC_LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001414 return;
1415 }
deadbeefab9b2d12015-10-14 11:33:11 -07001416
zhihuang1c378ed2017-08-17 14:10:50 -07001417 PeerConnectionInterface::RTCOfferAnswerOptions offer_answer_options;
1418 if (!ConvertConstraintsToOfferAnswerOptions(constraints,
1419 &offer_answer_options)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001420 std::string error = "CreateAnswer called with invalid constraints.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001421 RTC_LOG(LS_ERROR) << error;
deadbeefab9b2d12015-10-14 11:33:11 -07001422 PostCreateSessionDescriptionFailure(observer, error);
1423 return;
1424 }
1425
Steve Anton8d3444d2017-10-20 15:30:51 -07001426 CreateAnswer(observer, offer_answer_options);
htaa2a49d92016-03-04 02:51:39 -08001427}
1428
1429void PeerConnection::CreateAnswer(CreateSessionDescriptionObserver* observer,
1430 const RTCOfferAnswerOptions& options) {
1431 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
nisse7ce109a2017-01-31 00:57:56 -08001432 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001433 RTC_LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
htaa2a49d92016-03-04 02:51:39 -08001434 return;
1435 }
1436
Steve Anton8d3444d2017-10-20 15:30:51 -07001437 if (IsClosed()) {
1438 std::string error = "CreateAnswer called when PeerConnection is closed.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001439 RTC_LOG(LS_ERROR) << error;
Steve Anton8d3444d2017-10-20 15:30:51 -07001440 PostCreateSessionDescriptionFailure(observer, error);
1441 return;
1442 }
1443
Steve Anton75737c02017-11-06 10:37:17 -08001444 if (remote_description() &&
Steve Antona3a92c22017-12-07 10:27:41 -08001445 remote_description()->GetType() != SdpType::kOffer) {
Steve Anton8d3444d2017-10-20 15:30:51 -07001446 std::string error = "CreateAnswer called without remote offer.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001447 RTC_LOG(LS_ERROR) << error;
Steve Anton8d3444d2017-10-20 15:30:51 -07001448 PostCreateSessionDescriptionFailure(observer, error);
1449 return;
1450 }
1451
htaa2a49d92016-03-04 02:51:39 -08001452 cricket::MediaSessionOptions session_options;
zhihuang1c378ed2017-08-17 14:10:50 -07001453 GetOptionsForAnswer(options, &session_options);
htaa2a49d92016-03-04 02:51:39 -08001454
Steve Antond25da372017-11-06 14:50:29 -08001455 webrtc_session_desc_factory_->CreateAnswer(observer, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001456}
1457
1458void PeerConnection::SetLocalDescription(
1459 SetSessionDescriptionObserver* observer,
1460 SessionDescriptionInterface* desc) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001461 TRACE_EVENT0("webrtc", "PeerConnection::SetLocalDescription");
Steve Anton8a006912017-12-04 15:25:56 -08001462
nisse7ce109a2017-01-31 00:57:56 -08001463 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001464 RTC_LOG(LS_ERROR) << "SetLocalDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001465 return;
1466 }
Steve Anton8a006912017-12-04 15:25:56 -08001467
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001468 if (!desc) {
1469 PostSetSessionDescriptionFailure(observer, "SessionDescription is NULL.");
1470 return;
1471 }
Steve Anton8d3444d2017-10-20 15:30:51 -07001472
Steve Antona3a92c22017-12-07 10:27:41 -08001473 SdpType type = desc->GetType();
Steve Anton8d3444d2017-10-20 15:30:51 -07001474
Steve Anton8a006912017-12-04 15:25:56 -08001475 RTCError error = ApplyLocalDescription(rtc::WrapUnique(desc));
1476 // |desc| may be destroyed at this point.
1477
1478 if (!error.ok()) {
Steve Antona3a92c22017-12-07 10:27:41 -08001479 std::ostringstream oss;
1480 oss << "Failed to set local " << SdpTypeToString(type)
1481 << " sdp: " << error.message();
1482 std::string error_message = oss.str();
Steve Anton8a006912017-12-04 15:25:56 -08001483 RTC_LOG(LS_ERROR) << error_message << " (" << error.type() << ")";
1484 PostSetSessionDescriptionFailure(observer, std::move(error_message));
Steve Anton8d3444d2017-10-20 15:30:51 -07001485 return;
1486 }
Steve Anton8a006912017-12-04 15:25:56 -08001487 RTC_DCHECK(local_description());
1488
1489 PostSetSessionDescriptionSuccess(observer);
1490
1491 // According to JSEP, after setLocalDescription, changing the candidate pool
1492 // size is not allowed, and changing the set of ICE servers will not result
1493 // in new candidates being gathered.
1494 port_allocator_->FreezeCandidatePool();
1495
1496 // MaybeStartGathering needs to be called after posting
1497 // MSG_SET_SESSIONDESCRIPTION_SUCCESS, so that we don't signal any candidates
1498 // before signaling that SetLocalDescription completed.
1499 transport_controller_->MaybeStartGathering();
1500
Steve Antona3a92c22017-12-07 10:27:41 -08001501 if (local_description()->GetType() == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08001502 // TODO(deadbeef): We already had to hop to the network thread for
1503 // MaybeStartGathering...
1504 network_thread()->Invoke<void>(
1505 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
1506 port_allocator_.get()));
1507 }
1508}
1509
1510RTCError PeerConnection::ApplyLocalDescription(
1511 std::unique_ptr<SessionDescriptionInterface> desc) {
1512 RTC_DCHECK_RUN_ON(signaling_thread());
1513 RTC_DCHECK(desc);
1514
1515 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_LOCAL);
1516 if (!error.ok()) {
1517 return error;
1518 }
Steve Anton8d3444d2017-10-20 15:30:51 -07001519
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001520 // Update stats here so that we have the most recent stats for tracks and
1521 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001522 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 15:25:56 -08001523
1524 // Update the initial_offerer flag if this session is the initial_offerer.
Steve Anton3828c062017-12-06 10:34:51 -08001525 SdpType type = desc->GetType();
Steve Anton8a006912017-12-04 15:25:56 -08001526 if (!initial_offerer_.has_value()) {
Steve Anton3828c062017-12-06 10:34:51 -08001527 initial_offerer_.emplace(type == SdpType::kOffer);
Steve Anton8a006912017-12-04 15:25:56 -08001528 if (*initial_offerer_) {
1529 transport_controller_->SetIceRole(cricket::ICEROLE_CONTROLLING);
1530 } else {
1531 transport_controller_->SetIceRole(cricket::ICEROLE_CONTROLLED);
1532 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001533 }
Steve Anton8a006912017-12-04 15:25:56 -08001534
Steve Anton3828c062017-12-06 10:34:51 -08001535 if (type == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08001536 current_local_description_ = std::move(desc);
1537 pending_local_description_ = nullptr;
1538 current_remote_description_ = std::move(pending_remote_description_);
1539 } else {
1540 pending_local_description_ = std::move(desc);
1541 }
1542 // The session description to apply now must be accessed by
1543 // |local_description()|.
Henrik Boströmfdb92012017-11-09 19:55:44 +01001544 RTC_DCHECK(local_description());
deadbeefab9b2d12015-10-14 11:33:11 -07001545
Steve Anton8a006912017-12-04 15:25:56 -08001546 // Transport and Media channels will be created only when offer is set.
Steve Anton3828c062017-12-06 10:34:51 -08001547 if (type == SdpType::kOffer) {
Steve Anton8a006912017-12-04 15:25:56 -08001548 // TODO(mallinath) - Handle CreateChannel failure, as new local description
1549 // is applied. Restore back to old description.
1550 RTCError error = CreateChannels(local_description()->description());
1551 if (!error.ok()) {
1552 return error;
1553 }
1554 }
1555
1556 // Remove unused channels if MediaContentDescription is rejected.
1557 RemoveUnusedChannels(local_description()->description());
1558
Steve Anton3828c062017-12-06 10:34:51 -08001559 error = UpdateSessionState(type, cricket::CS_LOCAL);
Steve Anton8a006912017-12-04 15:25:56 -08001560 if (!error.ok()) {
1561 return error;
1562 }
1563 if (remote_description()) {
1564 // Now that we have a local description, we can push down remote candidates.
1565 UseCandidatesInSessionDescription(remote_description());
1566 }
1567
1568 pending_ice_restarts_.clear();
1569 if (session_error() != SessionError::kNone) {
1570 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
1571 }
1572
deadbeefab9b2d12015-10-14 11:33:11 -07001573 // If setting the description decided our SSL role, allocate any necessary
1574 // SCTP sids.
1575 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08001576 if (data_channel_type() == cricket::DCT_SCTP && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001577 AllocateSctpSids(role);
1578 }
1579
1580 // Update state and SSRC of local MediaStreams and DataChannels based on the
1581 // local session description.
1582 const cricket::ContentInfo* audio_content =
Henrik Boströmfdb92012017-11-09 19:55:44 +01001583 GetFirstAudioContent(local_description()->description());
deadbeefab9b2d12015-10-14 11:33:11 -07001584 if (audio_content) {
deadbeeffaac4972015-11-12 15:33:07 -08001585 if (audio_content->rejected) {
Steve Anton4171afb2017-11-20 10:20:22 -08001586 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
deadbeeffaac4972015-11-12 15:33:07 -08001587 } else {
1588 const cricket::AudioContentDescription* audio_desc =
1589 static_cast<const cricket::AudioContentDescription*>(
1590 audio_content->description);
Steve Anton4171afb2017-11-20 10:20:22 -08001591 UpdateLocalSenders(audio_desc->streams(), audio_desc->type());
deadbeeffaac4972015-11-12 15:33:07 -08001592 }
deadbeefab9b2d12015-10-14 11:33:11 -07001593 }
1594
1595 const cricket::ContentInfo* video_content =
Henrik Boströmfdb92012017-11-09 19:55:44 +01001596 GetFirstVideoContent(local_description()->description());
deadbeefab9b2d12015-10-14 11:33:11 -07001597 if (video_content) {
deadbeeffaac4972015-11-12 15:33:07 -08001598 if (video_content->rejected) {
Steve Anton4171afb2017-11-20 10:20:22 -08001599 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
deadbeeffaac4972015-11-12 15:33:07 -08001600 } else {
1601 const cricket::VideoContentDescription* video_desc =
1602 static_cast<const cricket::VideoContentDescription*>(
1603 video_content->description);
Steve Anton4171afb2017-11-20 10:20:22 -08001604 UpdateLocalSenders(video_desc->streams(), video_desc->type());
deadbeeffaac4972015-11-12 15:33:07 -08001605 }
deadbeefab9b2d12015-10-14 11:33:11 -07001606 }
1607
1608 const cricket::ContentInfo* data_content =
Henrik Boströmfdb92012017-11-09 19:55:44 +01001609 GetFirstDataContent(local_description()->description());
deadbeefab9b2d12015-10-14 11:33:11 -07001610 if (data_content) {
1611 const cricket::DataContentDescription* data_desc =
1612 static_cast<const cricket::DataContentDescription*>(
1613 data_content->description);
1614 if (rtc::starts_with(data_desc->protocol().data(),
1615 cricket::kMediaProtocolRtpPrefix)) {
1616 UpdateLocalRtpDataChannels(data_desc->streams());
1617 }
1618 }
1619
Steve Anton8a006912017-12-04 15:25:56 -08001620 return RTCError::OK();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001621}
1622
1623void PeerConnection::SetRemoteDescription(
Henrik Boströma4ecf552017-11-23 14:17:07 +00001624 SetSessionDescriptionObserver* observer,
1625 SessionDescriptionInterface* desc) {
Henrik Boström31638672017-11-23 17:48:32 +01001626 SetRemoteDescription(
1627 std::unique_ptr<SessionDescriptionInterface>(desc),
1628 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface>(
1629 new SetRemoteDescriptionObserverAdapter(this, observer)));
1630}
1631
1632void PeerConnection::SetRemoteDescription(
1633 std::unique_ptr<SessionDescriptionInterface> desc,
1634 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface> observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001635 TRACE_EVENT0("webrtc", "PeerConnection::SetRemoteDescription");
Steve Anton8a006912017-12-04 15:25:56 -08001636
nisse7ce109a2017-01-31 00:57:56 -08001637 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001638 RTC_LOG(LS_ERROR) << "SetRemoteDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001639 return;
1640 }
Steve Anton8a006912017-12-04 15:25:56 -08001641
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001642 if (!desc) {
Henrik Boström31638672017-11-23 17:48:32 +01001643 observer->OnSetRemoteDescriptionComplete(RTCError(
Steve Anton8a006912017-12-04 15:25:56 -08001644 RTCErrorType::INVALID_PARAMETER, "SessionDescription is NULL."));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001645 return;
1646 }
Steve Anton8d3444d2017-10-20 15:30:51 -07001647
Steve Antona3a92c22017-12-07 10:27:41 -08001648 const SdpType type = desc->GetType();
Steve Anton8a006912017-12-04 15:25:56 -08001649
1650 RTCError error = ApplyRemoteDescription(std::move(desc));
1651 // |desc| may be destroyed at this point.
1652
1653 if (!error.ok()) {
Steve Antona3a92c22017-12-07 10:27:41 -08001654 std::ostringstream oss;
1655 oss << "Failed to set remote " << SdpTypeToString(type)
1656 << " sdp: " << error.message();
1657 std::string error_message = oss.str();
Steve Anton8a006912017-12-04 15:25:56 -08001658 RTC_LOG(LS_ERROR) << error_message << " (" << error.type() << ")";
Henrik Boström31638672017-11-23 17:48:32 +01001659 observer->OnSetRemoteDescriptionComplete(
Steve Anton8a006912017-12-04 15:25:56 -08001660 RTCError(error.type(), std::move(error_message)));
Steve Anton8d3444d2017-10-20 15:30:51 -07001661 return;
1662 }
1663
Steve Antona3a92c22017-12-07 10:27:41 -08001664 if (remote_description()->GetType() == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08001665 // TODO(deadbeef): We already had to hop to the network thread for
1666 // MaybeStartGathering...
1667 network_thread()->Invoke<void>(
1668 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
1669 port_allocator_.get()));
1670 }
1671
1672 observer->OnSetRemoteDescriptionComplete(RTCError::OK());
1673}
1674
1675RTCError PeerConnection::ApplyRemoteDescription(
1676 std::unique_ptr<SessionDescriptionInterface> desc) {
1677 RTC_DCHECK_RUN_ON(signaling_thread());
1678 RTC_DCHECK(desc);
1679
1680 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_REMOTE);
1681 if (!error.ok()) {
1682 return error;
1683 }
1684
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001685 // Update stats here so that we have the most recent stats for tracks and
1686 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001687 stats_->UpdateStats(kStatsOutputLevelStandard);
Henrik Boström31638672017-11-23 17:48:32 +01001688 // Takes the ownership of |desc|. On success, remote_description() is updated
1689 // to reflect the description that was passed in.
Steve Anton8a006912017-12-04 15:25:56 -08001690
1691 const SessionDescriptionInterface* old_remote_description =
1692 remote_description();
1693 // Grab ownership of the description being replaced for the remainder of this
1694 // method, since it's used below as |old_remote_description|.
1695 std::unique_ptr<SessionDescriptionInterface> replaced_remote_description;
Steve Anton3828c062017-12-06 10:34:51 -08001696 SdpType type = desc->GetType();
1697 if (type == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08001698 replaced_remote_description = pending_remote_description_
1699 ? std::move(pending_remote_description_)
1700 : std::move(current_remote_description_);
1701 current_remote_description_ = std::move(desc);
1702 pending_remote_description_ = nullptr;
1703 current_local_description_ = std::move(pending_local_description_);
1704 } else {
1705 replaced_remote_description = std::move(pending_remote_description_);
1706 pending_remote_description_ = std::move(desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001707 }
Steve Anton8a006912017-12-04 15:25:56 -08001708 // The session description to apply now must be accessed by
1709 // |remote_description()|.
Henrik Boströmfdb92012017-11-09 19:55:44 +01001710 RTC_DCHECK(remote_description());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001711
Steve Anton8a006912017-12-04 15:25:56 -08001712 // Transport and Media channels will be created only when offer is set.
Steve Anton3828c062017-12-06 10:34:51 -08001713 if (type == SdpType::kOffer) {
Steve Anton8a006912017-12-04 15:25:56 -08001714 // TODO(mallinath) - Handle CreateChannel failure, as new local description
1715 // is applied. Restore back to old description.
1716 RTCError error = CreateChannels(remote_description()->description());
1717 if (!error.ok()) {
1718 return error;
1719 }
1720 }
1721
1722 // Remove unused channels if MediaContentDescription is rejected.
1723 RemoveUnusedChannels(remote_description()->description());
1724
1725 // NOTE: Candidates allocation will be initiated only when SetLocalDescription
1726 // is called.
Steve Anton3828c062017-12-06 10:34:51 -08001727 error = UpdateSessionState(type, cricket::CS_REMOTE);
Steve Anton8a006912017-12-04 15:25:56 -08001728 if (!error.ok()) {
1729 return error;
1730 }
1731
1732 if (local_description() &&
1733 !UseCandidatesInSessionDescription(remote_description())) {
1734 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidCandidates);
1735 }
1736
1737 if (old_remote_description) {
1738 for (const cricket::ContentInfo& content :
1739 old_remote_description->description()->contents()) {
1740 // Check if this new SessionDescription contains new ICE ufrag and
1741 // password that indicates the remote peer requests an ICE restart.
1742 // TODO(deadbeef): When we start storing both the current and pending
1743 // remote description, this should reset pending_ice_restarts and compare
1744 // against the current description.
1745 if (CheckForRemoteIceRestart(old_remote_description, remote_description(),
1746 content.name)) {
Steve Anton3828c062017-12-06 10:34:51 -08001747 if (type == SdpType::kOffer) {
Steve Anton8a006912017-12-04 15:25:56 -08001748 pending_ice_restarts_.insert(content.name);
1749 }
1750 } else {
1751 // We retain all received candidates only if ICE is not restarted.
1752 // When ICE is restarted, all previous candidates belong to an old
1753 // generation and should not be kept.
1754 // TODO(deadbeef): This goes against the W3C spec which says the remote
1755 // description should only contain candidates from the last set remote
1756 // description plus any candidates added since then. We should remove
1757 // this once we're sure it won't break anything.
1758 WebRtcSessionDescriptionFactory::CopyCandidatesFromSessionDescription(
1759 old_remote_description, content.name, mutable_remote_description());
1760 }
1761 }
1762 }
1763
1764 if (session_error() != SessionError::kNone) {
1765 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
1766 }
1767
1768 // Set the the ICE connection state to connecting since the connection may
1769 // become writable with peer reflexive candidates before any remote candidate
1770 // is signaled.
1771 // TODO(pthatcher): This is a short-term solution for crbug/446908. A real fix
1772 // is to have a new signal the indicates a change in checking state from the
1773 // transport and expose a new checking() member from transport that can be
1774 // read to determine the current checking state. The existing SignalConnecting
1775 // actually means "gathering candidates", so cannot be be used here.
Steve Antona3a92c22017-12-07 10:27:41 -08001776 if (remote_description()->GetType() != SdpType::kOffer &&
Steve Anton8a006912017-12-04 15:25:56 -08001777 ice_connection_state() == PeerConnectionInterface::kIceConnectionNew) {
1778 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
1779 }
1780
deadbeefab9b2d12015-10-14 11:33:11 -07001781 // If setting the description decided our SSL role, allocate any necessary
1782 // SCTP sids.
1783 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08001784 if (data_channel_type() == cricket::DCT_SCTP && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001785 AllocateSctpSids(role);
1786 }
1787
Henrik Boströmfdb92012017-11-09 19:55:44 +01001788 const cricket::ContentInfo* audio_content =
1789 GetFirstAudioContent(remote_description()->description());
1790 const cricket::ContentInfo* video_content =
1791 GetFirstVideoContent(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08001792 const cricket::AudioContentDescription* audio_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01001793 GetFirstAudioContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08001794 const cricket::VideoContentDescription* video_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01001795 GetFirstVideoContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08001796 const cricket::DataContentDescription* data_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01001797 GetFirstDataContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08001798
1799 // Check if the descriptions include streams, just in case the peer supports
1800 // MSID, but doesn't indicate so with "a=msid-semantic".
Henrik Boströmfdb92012017-11-09 19:55:44 +01001801 if (remote_description()->description()->msid_supported() ||
deadbeefbda7e0b2015-12-08 17:13:40 -08001802 (audio_desc && !audio_desc->streams().empty()) ||
1803 (video_desc && !video_desc->streams().empty())) {
1804 remote_peer_supports_msid_ = true;
1805 }
deadbeefab9b2d12015-10-14 11:33:11 -07001806
1807 // We wait to signal new streams until we finish processing the description,
1808 // since only at that point will new streams have all their tracks.
1809 rtc::scoped_refptr<StreamCollection> new_streams(StreamCollection::Create());
1810
Steve Anton8d3444d2017-10-20 15:30:51 -07001811 // TODO(steveanton): When removing RTP senders/receivers in response to a
1812 // rejected media section, there is some cleanup logic that expects the voice/
1813 // video channel to still be set. But in this method the voice/video channel
Steve Anton75737c02017-11-06 10:37:17 -08001814 // would have been destroyed by the SetRemoteDescription caller above so the
Steve Anton4171afb2017-11-20 10:20:22 -08001815 // cleanup that relies on them fails to run. The RemoveSenders calls should be
Steve Anton75737c02017-11-06 10:37:17 -08001816 // moved to right before the DestroyChannel calls to fix this.
Steve Anton8d3444d2017-10-20 15:30:51 -07001817
deadbeefab9b2d12015-10-14 11:33:11 -07001818 // Find all audio rtp streams and create corresponding remote AudioTracks
1819 // and MediaStreams.
deadbeefab9b2d12015-10-14 11:33:11 -07001820 if (audio_content) {
deadbeeffaac4972015-11-12 15:33:07 -08001821 if (audio_content->rejected) {
Steve Anton4171afb2017-11-20 10:20:22 -08001822 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
deadbeeffaac4972015-11-12 15:33:07 -08001823 } else {
deadbeefbda7e0b2015-12-08 17:13:40 -08001824 bool default_audio_track_needed =
1825 !remote_peer_supports_msid_ &&
Steve Anton4e70a722017-11-28 14:57:10 -08001826 RtpTransceiverDirectionHasSend(audio_desc->direction());
Steve Anton4171afb2017-11-20 10:20:22 -08001827 UpdateRemoteSendersList(GetActiveStreams(audio_desc),
deadbeefbda7e0b2015-12-08 17:13:40 -08001828 default_audio_track_needed, audio_desc->type(),
deadbeeffaac4972015-11-12 15:33:07 -08001829 new_streams);
deadbeeffaac4972015-11-12 15:33:07 -08001830 }
deadbeefab9b2d12015-10-14 11:33:11 -07001831 }
1832
1833 // Find all video rtp streams and create corresponding remote VideoTracks
1834 // and MediaStreams.
deadbeefab9b2d12015-10-14 11:33:11 -07001835 if (video_content) {
deadbeeffaac4972015-11-12 15:33:07 -08001836 if (video_content->rejected) {
Steve Anton4171afb2017-11-20 10:20:22 -08001837 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
deadbeeffaac4972015-11-12 15:33:07 -08001838 } else {
deadbeefbda7e0b2015-12-08 17:13:40 -08001839 bool default_video_track_needed =
1840 !remote_peer_supports_msid_ &&
Steve Anton4e70a722017-11-28 14:57:10 -08001841 RtpTransceiverDirectionHasSend(video_desc->direction());
Steve Anton4171afb2017-11-20 10:20:22 -08001842 UpdateRemoteSendersList(GetActiveStreams(video_desc),
deadbeefbda7e0b2015-12-08 17:13:40 -08001843 default_video_track_needed, video_desc->type(),
deadbeeffaac4972015-11-12 15:33:07 -08001844 new_streams);
deadbeeffaac4972015-11-12 15:33:07 -08001845 }
deadbeefab9b2d12015-10-14 11:33:11 -07001846 }
1847
1848 // Update the DataChannels with the information from the remote peer.
deadbeefbda7e0b2015-12-08 17:13:40 -08001849 if (data_desc) {
1850 if (rtc::starts_with(data_desc->protocol().data(),
deadbeefab9b2d12015-10-14 11:33:11 -07001851 cricket::kMediaProtocolRtpPrefix)) {
deadbeefbda7e0b2015-12-08 17:13:40 -08001852 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
deadbeefab9b2d12015-10-14 11:33:11 -07001853 }
1854 }
1855
1856 // Iterate new_streams and notify the observer about new MediaStreams.
1857 for (size_t i = 0; i < new_streams->count(); ++i) {
1858 MediaStreamInterface* new_stream = new_streams->at(i);
1859 stats_->AddStream(new_stream);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07001860 observer_->OnAddStream(
1861 rtc::scoped_refptr<MediaStreamInterface>(new_stream));
deadbeefab9b2d12015-10-14 11:33:11 -07001862 }
1863
deadbeefbda7e0b2015-12-08 17:13:40 -08001864 UpdateEndedRemoteMediaStreams();
deadbeefab9b2d12015-10-14 11:33:11 -07001865
Steve Anton8a006912017-12-04 15:25:56 -08001866 return RTCError::OK();
deadbeeffc648b62015-10-13 16:42:33 -07001867}
1868
Steve Antoned10bd92017-12-05 10:52:59 -08001869const cricket::ContentInfo* PeerConnection::FindMediaSectionForTransceiver(
1870 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1871 transceiver,
1872 const SessionDescriptionInterface* sdesc) const {
1873 RTC_DCHECK(transceiver);
1874 RTC_DCHECK(sdesc);
1875 if (IsUnifiedPlan()) {
1876 if (!transceiver->internal()->mid()) {
1877 // This transceiver is not associated with a media section yet.
1878 return nullptr;
1879 }
1880 return sdesc->description()->GetContentByName(
1881 *transceiver->internal()->mid());
1882 } else {
1883 // Plan B only allows at most one audio and one video section, so use the
1884 // first media section of that type.
1885 return cricket::GetFirstMediaContent(sdesc->description()->contents(),
1886 transceiver->internal()->media_type());
1887 }
1888}
1889
deadbeef46c73892016-11-16 19:42:04 -08001890PeerConnectionInterface::RTCConfiguration PeerConnection::GetConfiguration() {
1891 return configuration_;
1892}
1893
deadbeef293e9262017-01-11 12:28:30 -08001894bool PeerConnection::SetConfiguration(const RTCConfiguration& configuration,
1895 RTCError* error) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001896 TRACE_EVENT0("webrtc", "PeerConnection::SetConfiguration");
deadbeef6de92f92016-12-12 18:49:32 -08001897
Steve Anton75737c02017-11-06 10:37:17 -08001898 if (local_description() && configuration.ice_candidate_pool_size !=
1899 configuration_.ice_candidate_pool_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001900 RTC_LOG(LS_ERROR) << "Can't change candidate pool size after calling "
1901 "SetLocalDescription.";
deadbeef293e9262017-01-11 12:28:30 -08001902 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00001903 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07001904
deadbeef293e9262017-01-11 12:28:30 -08001905 // The simplest (and most future-compatible) way to tell if the config was
1906 // modified in an invalid way is to copy each property we do support
1907 // modifying, then use operator==. There are far more properties we don't
1908 // support modifying than those we do, and more could be added.
1909 RTCConfiguration modified_config = configuration_;
1910 modified_config.servers = configuration.servers;
1911 modified_config.type = configuration.type;
1912 modified_config.ice_candidate_pool_size =
1913 configuration.ice_candidate_pool_size;
1914 modified_config.prune_turn_ports = configuration.prune_turn_ports;
skvladd1f5fda2017-02-03 16:54:05 -08001915 modified_config.ice_check_min_interval = configuration.ice_check_min_interval;
Jonas Orelandbdcee282017-10-10 14:01:40 +02001916 modified_config.turn_customizer = configuration.turn_customizer;
deadbeef293e9262017-01-11 12:28:30 -08001917 if (configuration != modified_config) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001918 RTC_LOG(LS_ERROR) << "Modifying the configuration in an unsupported way.";
deadbeef293e9262017-01-11 12:28:30 -08001919 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
1920 }
1921
Steve Anton038834f2017-07-14 15:59:59 -07001922 // Validate the modified configuration.
1923 RTCError validate_error = ValidateConfiguration(modified_config);
1924 if (!validate_error.ok()) {
1925 return SafeSetError(std::move(validate_error), error);
1926 }
1927
deadbeef293e9262017-01-11 12:28:30 -08001928 // Note that this isn't possible through chromium, since it's an unsigned
1929 // short in WebIDL.
1930 if (configuration.ice_candidate_pool_size < 0 ||
1931 configuration.ice_candidate_pool_size > UINT16_MAX) {
1932 return SafeSetError(RTCErrorType::INVALID_RANGE, error);
1933 }
1934
1935 // Parse ICE servers before hopping to network thread.
1936 cricket::ServerAddresses stun_servers;
1937 std::vector<cricket::RelayServerConfig> turn_servers;
1938 RTCErrorType parse_error =
1939 ParseIceServers(configuration.servers, &stun_servers, &turn_servers);
1940 if (parse_error != RTCErrorType::NONE) {
1941 return SafeSetError(parse_error, error);
1942 }
1943
1944 // In theory this shouldn't fail.
1945 if (!network_thread()->Invoke<bool>(
1946 RTC_FROM_HERE,
1947 rtc::Bind(&PeerConnection::ReconfigurePortAllocator_n, this,
1948 stun_servers, turn_servers, modified_config.type,
1949 modified_config.ice_candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02001950 modified_config.prune_turn_ports,
1951 modified_config.turn_customizer))) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001952 RTC_LOG(LS_ERROR) << "Failed to apply configuration to PortAllocator.";
deadbeef293e9262017-01-11 12:28:30 -08001953 return SafeSetError(RTCErrorType::INTERNAL_ERROR, error);
1954 }
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07001955
deadbeefd1a38b52016-12-10 13:15:33 -08001956 // As described in JSEP, calling setConfiguration with new ICE servers or
1957 // candidate policy must set a "needs-ice-restart" bit so that the next offer
1958 // triggers an ICE restart which will pick up the changes.
deadbeef293e9262017-01-11 12:28:30 -08001959 if (modified_config.servers != configuration_.servers ||
1960 modified_config.type != configuration_.type ||
1961 modified_config.prune_turn_ports != configuration_.prune_turn_ports) {
Steve Antond25da372017-11-06 14:50:29 -08001962 transport_controller_->SetNeedsIceRestartFlag();
deadbeefd1a38b52016-12-10 13:15:33 -08001963 }
skvladd1f5fda2017-02-03 16:54:05 -08001964
1965 if (modified_config.ice_check_min_interval !=
1966 configuration_.ice_check_min_interval) {
Steve Antond25da372017-11-06 14:50:29 -08001967 transport_controller_->SetIceConfig(ParseIceConfig(modified_config));
skvladd1f5fda2017-02-03 16:54:05 -08001968 }
1969
deadbeef293e9262017-01-11 12:28:30 -08001970 configuration_ = modified_config;
1971 return SafeSetError(RTCErrorType::NONE, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00001972}
1973
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001974bool PeerConnection::AddIceCandidate(
1975 const IceCandidateInterface* ice_candidate) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001976 TRACE_EVENT0("webrtc", "PeerConnection::AddIceCandidate");
zhihuang29ff8442016-07-27 11:07:25 -07001977 if (IsClosed()) {
1978 return false;
1979 }
Steve Antond25da372017-11-06 14:50:29 -08001980
1981 if (!remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001982 RTC_LOG(LS_ERROR) << "ProcessIceMessage: ICE candidates can't be added "
1983 << "without any remote session description.";
Steve Antond25da372017-11-06 14:50:29 -08001984 return false;
1985 }
1986
1987 if (!ice_candidate) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001988 RTC_LOG(LS_ERROR) << "ProcessIceMessage: Candidate is NULL.";
Steve Antond25da372017-11-06 14:50:29 -08001989 return false;
1990 }
1991
1992 bool valid = false;
1993 bool ready = ReadyToUseRemoteCandidate(ice_candidate, nullptr, &valid);
1994 if (!valid) {
1995 return false;
1996 }
1997
1998 // Add this candidate to the remote session description.
1999 if (!mutable_remote_description()->AddCandidate(ice_candidate)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002000 RTC_LOG(LS_ERROR) << "ProcessIceMessage: Candidate cannot be used.";
Steve Antond25da372017-11-06 14:50:29 -08002001 return false;
2002 }
2003
2004 if (ready) {
2005 return UseCandidate(ice_candidate);
2006 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002007 RTC_LOG(LS_INFO) << "ProcessIceMessage: Not ready to use candidate.";
Steve Antond25da372017-11-06 14:50:29 -08002008 return true;
2009 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002010}
2011
Honghai Zhang7fb69db2016-03-14 11:59:18 -07002012bool PeerConnection::RemoveIceCandidates(
2013 const std::vector<cricket::Candidate>& candidates) {
2014 TRACE_EVENT0("webrtc", "PeerConnection::RemoveIceCandidates");
Steve Antond25da372017-11-06 14:50:29 -08002015 if (!remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002016 RTC_LOG(LS_ERROR) << "RemoveRemoteIceCandidates: ICE candidates can't be "
2017 << "removed without any remote session description.";
Steve Antond25da372017-11-06 14:50:29 -08002018 return false;
2019 }
2020
2021 if (candidates.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002022 RTC_LOG(LS_ERROR) << "RemoveRemoteIceCandidates: candidates are empty.";
Steve Antond25da372017-11-06 14:50:29 -08002023 return false;
2024 }
2025
2026 size_t number_removed =
2027 mutable_remote_description()->RemoveCandidates(candidates);
2028 if (number_removed != candidates.size()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002029 RTC_LOG(LS_ERROR)
2030 << "RemoveRemoteIceCandidates: Failed to remove candidates. "
2031 << "Requested " << candidates.size() << " but only " << number_removed
2032 << " are removed.";
Steve Antond25da372017-11-06 14:50:29 -08002033 }
2034
2035 // Remove the candidates from the transport controller.
2036 std::string error;
2037 bool res = transport_controller_->RemoveRemoteCandidates(candidates, &error);
2038 if (!res && !error.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002039 RTC_LOG(LS_ERROR) << "Error when removing remote candidates: " << error;
Steve Antond25da372017-11-06 14:50:29 -08002040 }
2041 return true;
Honghai Zhang7fb69db2016-03-14 11:59:18 -07002042}
2043
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00002044void PeerConnection::RegisterUMAObserver(UMAObserver* observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +01002045 TRACE_EVENT0("webrtc", "PeerConnection::RegisterUmaObserver");
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00002046 uma_observer_ = observer;
guoweis@webrtc.org7169afd2014-12-04 17:59:29 +00002047
Steve Anton75737c02017-11-06 10:37:17 -08002048 if (transport_controller()) {
2049 transport_controller()->SetMetricsObserver(uma_observer_);
guoweis@webrtc.org7169afd2014-12-04 17:59:29 +00002050 }
2051
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00002052 // Send information about IPv4/IPv6 status.
deadbeef293e9262017-01-11 12:28:30 -08002053 if (uma_observer_) {
Honghai Zhangd93f50c2016-10-05 11:47:22 -07002054 port_allocator_->SetMetricsObserver(uma_observer_);
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00002055 if (port_allocator_->flags() & cricket::PORTALLOCATOR_ENABLE_IPV6) {
Guo-wei Shiehdfbe6792015-09-03 17:12:07 -07002056 uma_observer_->IncrementEnumCounter(
2057 kEnumCounterAddressFamily, kPeerConnection_IPv6,
2058 kPeerConnectionAddressFamilyCounter_Max);
mallinath@webrtc.orgb445f262014-05-23 22:19:37 +00002059 } else {
Guo-wei Shiehdfbe6792015-09-03 17:12:07 -07002060 uma_observer_->IncrementEnumCounter(
2061 kEnumCounterAddressFamily, kPeerConnection_IPv4,
2062 kPeerConnectionAddressFamilyCounter_Max);
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00002063 }
2064 }
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00002065}
2066
zstein4b979802017-06-02 14:37:37 -07002067RTCError PeerConnection::SetBitrate(const BitrateParameters& bitrate) {
Steve Anton978b8762017-09-29 12:15:02 -07002068 if (!worker_thread()->IsCurrent()) {
2069 return worker_thread()->Invoke<RTCError>(
zstein4b979802017-06-02 14:37:37 -07002070 RTC_FROM_HERE, rtc::Bind(&PeerConnection::SetBitrate, this, bitrate));
2071 }
2072
2073 const bool has_min = static_cast<bool>(bitrate.min_bitrate_bps);
2074 const bool has_current = static_cast<bool>(bitrate.current_bitrate_bps);
2075 const bool has_max = static_cast<bool>(bitrate.max_bitrate_bps);
2076 if (has_min && *bitrate.min_bitrate_bps < 0) {
2077 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2078 "min_bitrate_bps <= 0");
2079 }
2080 if (has_current) {
2081 if (has_min && *bitrate.current_bitrate_bps < *bitrate.min_bitrate_bps) {
2082 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2083 "current_bitrate_bps < min_bitrate_bps");
2084 } else if (*bitrate.current_bitrate_bps < 0) {
2085 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2086 "curent_bitrate_bps < 0");
2087 }
2088 }
2089 if (has_max) {
2090 if (has_current &&
2091 *bitrate.max_bitrate_bps < *bitrate.current_bitrate_bps) {
2092 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2093 "max_bitrate_bps < current_bitrate_bps");
2094 } else if (has_min && *bitrate.max_bitrate_bps < *bitrate.min_bitrate_bps) {
2095 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2096 "max_bitrate_bps < min_bitrate_bps");
2097 } else if (*bitrate.max_bitrate_bps < 0) {
2098 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2099 "max_bitrate_bps < 0");
2100 }
2101 }
2102
2103 Call::Config::BitrateConfigMask mask;
2104 mask.min_bitrate_bps = bitrate.min_bitrate_bps;
2105 mask.start_bitrate_bps = bitrate.current_bitrate_bps;
2106 mask.max_bitrate_bps = bitrate.max_bitrate_bps;
2107
2108 RTC_DCHECK(call_.get());
2109 call_->SetBitrateConfigMask(mask);
2110
2111 return RTCError::OK();
2112}
2113
Alex Narest78609d52017-10-20 10:37:47 +02002114void PeerConnection::SetBitrateAllocationStrategy(
2115 std::unique_ptr<rtc::BitrateAllocationStrategy>
2116 bitrate_allocation_strategy) {
2117 rtc::Thread* worker_thread = factory_->worker_thread();
2118 if (!worker_thread->IsCurrent()) {
2119 rtc::BitrateAllocationStrategy* strategy_raw =
2120 bitrate_allocation_strategy.release();
2121 auto functor = [this, strategy_raw]() {
2122 call_->SetBitrateAllocationStrategy(
2123 rtc::WrapUnique<rtc::BitrateAllocationStrategy>(strategy_raw));
2124 };
2125 worker_thread->Invoke<void>(RTC_FROM_HERE, functor);
2126 return;
2127 }
2128 RTC_DCHECK(call_.get());
2129 call_->SetBitrateAllocationStrategy(std::move(bitrate_allocation_strategy));
2130}
2131
henrika5f6bf242017-11-01 11:06:56 +01002132void PeerConnection::SetAudioPlayout(bool playout) {
2133 if (!worker_thread()->IsCurrent()) {
2134 worker_thread()->Invoke<void>(
2135 RTC_FROM_HERE,
2136 rtc::Bind(&PeerConnection::SetAudioPlayout, this, playout));
2137 return;
2138 }
2139 auto audio_state =
2140 factory_->channel_manager()->media_engine()->GetAudioState();
2141 audio_state->SetPlayout(playout);
2142}
2143
2144void PeerConnection::SetAudioRecording(bool recording) {
2145 if (!worker_thread()->IsCurrent()) {
2146 worker_thread()->Invoke<void>(
2147 RTC_FROM_HERE,
2148 rtc::Bind(&PeerConnection::SetAudioRecording, this, recording));
2149 return;
2150 }
2151 auto audio_state =
2152 factory_->channel_manager()->media_engine()->GetAudioState();
2153 audio_state->SetRecording(recording);
2154}
2155
Steve Anton8c0f7a72017-10-03 10:03:10 -07002156std::unique_ptr<rtc::SSLCertificate>
2157PeerConnection::GetRemoteAudioSSLCertificate() {
Steve Anton75737c02017-11-06 10:37:17 -08002158 if (!voice_channel()) {
Steve Anton8c0f7a72017-10-03 10:03:10 -07002159 return nullptr;
2160 }
Steve Anton75737c02017-11-06 10:37:17 -08002161 return GetRemoteSSLCertificate(voice_channel()->transport_name());
Steve Anton8c0f7a72017-10-03 10:03:10 -07002162}
2163
ivoc14d5dbe2016-07-04 07:06:55 -07002164bool PeerConnection::StartRtcEventLog(rtc::PlatformFile file,
2165 int64_t max_size_bytes) {
Elad Alon99c3fe52017-10-13 16:29:40 +02002166 // TODO(eladalon): It would be better to not allow negative values into PC.
2167 const size_t max_size = (max_size_bytes < 0)
2168 ? RtcEventLog::kUnlimitedOutput
2169 : rtc::saturated_cast<size_t>(max_size_bytes);
2170 return StartRtcEventLog(
Bjorn Tereliusde939432017-11-20 17:38:14 +01002171 rtc::MakeUnique<RtcEventLogOutputFile>(file, max_size),
2172 webrtc::RtcEventLog::kImmediateOutput);
Elad Alon99c3fe52017-10-13 16:29:40 +02002173}
2174
Bjorn Tereliusde939432017-11-20 17:38:14 +01002175bool PeerConnection::StartRtcEventLog(std::unique_ptr<RtcEventLogOutput> output,
2176 int64_t output_period_ms) {
Karl Wibergd6b48192017-10-16 23:01:06 +02002177 // TODO(eladalon): In C++14, this can be done with a lambda.
2178 struct Functor {
Bjorn Tereliusde939432017-11-20 17:38:14 +01002179 bool operator()() {
2180 return pc->StartRtcEventLog_w(std::move(output), output_period_ms);
2181 }
Karl Wibergd6b48192017-10-16 23:01:06 +02002182 PeerConnection* const pc;
2183 std::unique_ptr<RtcEventLogOutput> output;
Bjorn Tereliusde939432017-11-20 17:38:14 +01002184 const int64_t output_period_ms;
Elad Alon99c3fe52017-10-13 16:29:40 +02002185 };
Bjorn Tereliusde939432017-11-20 17:38:14 +01002186 return worker_thread()->Invoke<bool>(
2187 RTC_FROM_HERE, Functor{this, std::move(output), output_period_ms});
ivoc14d5dbe2016-07-04 07:06:55 -07002188}
2189
2190void PeerConnection::StopRtcEventLog() {
Steve Anton978b8762017-09-29 12:15:02 -07002191 worker_thread()->Invoke<void>(
ivoc14d5dbe2016-07-04 07:06:55 -07002192 RTC_FROM_HERE, rtc::Bind(&PeerConnection::StopRtcEventLog_w, this));
2193}
2194
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002195const SessionDescriptionInterface* PeerConnection::local_description() const {
Steve Anton75737c02017-11-06 10:37:17 -08002196 return pending_local_description_ ? pending_local_description_.get()
2197 : current_local_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002198}
2199
2200const SessionDescriptionInterface* PeerConnection::remote_description() const {
Steve Anton75737c02017-11-06 10:37:17 -08002201 return pending_remote_description_ ? pending_remote_description_.get()
2202 : current_remote_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002203}
2204
deadbeeffe4a8a42016-12-20 17:56:17 -08002205const SessionDescriptionInterface* PeerConnection::current_local_description()
2206 const {
Steve Anton75737c02017-11-06 10:37:17 -08002207 return current_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08002208}
2209
2210const SessionDescriptionInterface* PeerConnection::current_remote_description()
2211 const {
Steve Anton75737c02017-11-06 10:37:17 -08002212 return current_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08002213}
2214
2215const SessionDescriptionInterface* PeerConnection::pending_local_description()
2216 const {
Steve Anton75737c02017-11-06 10:37:17 -08002217 return pending_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08002218}
2219
2220const SessionDescriptionInterface* PeerConnection::pending_remote_description()
2221 const {
Steve Anton75737c02017-11-06 10:37:17 -08002222 return pending_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08002223}
2224
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002225void PeerConnection::Close() {
Peter Boström1a9d6152015-12-08 22:15:17 +01002226 TRACE_EVENT0("webrtc", "PeerConnection::Close");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002227 // Update stats here so that we have the most recent stats for tracks and
2228 // streams before the channels are closed.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00002229 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002230
Steve Anton75737c02017-11-06 10:37:17 -08002231 ChangeSignalingState(PeerConnectionInterface::kClosed);
Steve Anton3fe1b152017-12-12 10:20:08 -08002232
2233 StopAndDestroyChannels();
Steve Anton75737c02017-11-06 10:37:17 -08002234
deadbeef42a42632017-03-10 15:18:00 -08002235 network_thread()->Invoke<void>(
2236 RTC_FROM_HERE,
2237 rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
2238 port_allocator_.get()));
nisseeaabdf62017-05-05 02:23:02 -07002239
Steve Anton978b8762017-09-29 12:15:02 -07002240 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
eladalon248fd4f2017-09-06 05:18:15 -07002241 call_.reset();
2242 // The event log must outlive call (and any other object that uses it).
2243 event_log_.reset();
2244 });
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002245}
2246
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002247void PeerConnection::OnMessage(rtc::Message* msg) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002248 switch (msg->message_id) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002249 case MSG_SET_SESSIONDESCRIPTION_SUCCESS: {
2250 SetSessionDescriptionMsg* param =
2251 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
2252 param->observer->OnSuccess();
2253 delete param;
2254 break;
2255 }
2256 case MSG_SET_SESSIONDESCRIPTION_FAILED: {
2257 SetSessionDescriptionMsg* param =
2258 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
2259 param->observer->OnFailure(param->error);
2260 delete param;
2261 break;
2262 }
deadbeefab9b2d12015-10-14 11:33:11 -07002263 case MSG_CREATE_SESSIONDESCRIPTION_FAILED: {
2264 CreateSessionDescriptionMsg* param =
2265 static_cast<CreateSessionDescriptionMsg*>(msg->pdata);
2266 param->observer->OnFailure(param->error);
2267 delete param;
2268 break;
2269 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002270 case MSG_GETSTATS: {
2271 GetStatsMsg* param = static_cast<GetStatsMsg*>(msg->pdata);
nissee8abe3e2017-01-18 05:00:34 -08002272 StatsReports reports;
2273 stats_->GetStats(param->track, &reports);
2274 param->observer->OnComplete(reports);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002275 delete param;
2276 break;
2277 }
deadbeefbd292462015-12-14 18:15:29 -08002278 case MSG_FREE_DATACHANNELS: {
2279 sctp_data_channels_to_free_.clear();
2280 break;
2281 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002282 default:
nisseeb4ca4e2017-01-12 02:24:27 -08002283 RTC_NOTREACHED() << "Not implemented";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002284 break;
2285 }
2286}
2287
Steve Anton4171afb2017-11-20 10:20:22 -08002288void PeerConnection::CreateAudioReceiver(
2289 MediaStreamInterface* stream,
2290 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01002291 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
2292 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
zhihuang81c3a032016-11-17 12:06:24 -08002293 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
2294 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
deadbeefe814a0d2017-02-25 18:15:09 -08002295 signaling_thread(),
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01002296 new AudioRtpReceiver(remote_sender_info.sender_id, streams,
Steve Anton4171afb2017-11-20 10:20:22 -08002297 remote_sender_info.first_ssrc, voice_channel()));
deadbeefe814a0d2017-02-25 18:15:09 -08002298 stream->AddTrack(
2299 static_cast<AudioTrackInterface*>(receiver->internal()->track().get()));
Steve Anton4171afb2017-11-20 10:20:22 -08002300 GetAudioTransceiver()->internal()->AddReceiver(receiver);
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01002301 observer_->OnAddTrack(receiver, std::move(streams));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002302}
2303
Steve Anton4171afb2017-11-20 10:20:22 -08002304void PeerConnection::CreateVideoReceiver(
2305 MediaStreamInterface* stream,
2306 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01002307 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
2308 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
zhihuang81c3a032016-11-17 12:06:24 -08002309 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
2310 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
Steve Anton4171afb2017-11-20 10:20:22 -08002311 signaling_thread(),
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01002312 new VideoRtpReceiver(remote_sender_info.sender_id, streams,
2313 worker_thread(), remote_sender_info.first_ssrc,
2314 video_channel()));
deadbeefe814a0d2017-02-25 18:15:09 -08002315 stream->AddTrack(
2316 static_cast<VideoTrackInterface*>(receiver->internal()->track().get()));
Steve Anton4171afb2017-11-20 10:20:22 -08002317 GetVideoTransceiver()->internal()->AddReceiver(receiver);
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01002318 observer_->OnAddTrack(receiver, std::move(streams));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002319}
2320
deadbeef70ab1a12015-09-28 16:53:55 -07002321// TODO(deadbeef): Keep RtpReceivers around even if track goes away in remote
2322// description.
Henrik Boström933d8b02017-10-10 10:05:16 -07002323rtc::scoped_refptr<RtpReceiverInterface> PeerConnection::RemoveAndStopReceiver(
Steve Anton4171afb2017-11-20 10:20:22 -08002324 const RtpSenderInfo& remote_sender_info) {
2325 auto receiver = FindReceiverById(remote_sender_info.sender_id);
2326 if (!receiver) {
2327 RTC_LOG(LS_WARNING) << "RtpReceiver for track with id "
2328 << remote_sender_info.sender_id << " doesn't exist.";
Henrik Boström933d8b02017-10-10 10:05:16 -07002329 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07002330 }
Steve Anton4171afb2017-11-20 10:20:22 -08002331 if (receiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
2332 GetAudioTransceiver()->internal()->RemoveReceiver(receiver);
2333 } else {
2334 GetVideoTransceiver()->internal()->RemoveReceiver(receiver);
2335 }
Henrik Boström933d8b02017-10-10 10:05:16 -07002336 return receiver;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002337}
2338
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002339void PeerConnection::AddAudioTrack(AudioTrackInterface* track,
2340 MediaStreamInterface* stream) {
2341 RTC_DCHECK(!IsClosed());
2342 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08002343 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002344 // We already have a sender for this track, so just change the stream_id
2345 // so that it's correct in the next call to CreateOffer.
Steve Anton4171afb2017-11-20 10:20:22 -08002346 sender->internal()->set_stream_id(stream->label());
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002347 return;
2348 }
2349
2350 // Normal case; we've never seen this track before.
2351 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender =
2352 RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
2353 signaling_thread(),
Steve Anton75737c02017-11-06 10:37:17 -08002354 new AudioRtpSender(track, {stream->label()}, voice_channel(),
2355 stats_.get()));
Steve Anton4171afb2017-11-20 10:20:22 -08002356 GetAudioTransceiver()->internal()->AddSender(new_sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002357 // If the sender has already been configured in SDP, we call SetSsrc,
2358 // which will connect the sender to the underlying transport. This can
2359 // occur if a local session description that contains the ID of the sender
2360 // is set before AddStream is called. It can also occur if the local
2361 // session description is not changed and RemoveStream is called, and
2362 // later AddStream is called again with the same stream.
Steve Anton4171afb2017-11-20 10:20:22 -08002363 const RtpSenderInfo* sender_info =
2364 FindSenderInfo(local_audio_sender_infos_, stream->label(), track->id());
2365 if (sender_info) {
2366 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002367 }
2368}
2369
2370// TODO(deadbeef): Don't destroy RtpSenders here; they should be kept around
2371// indefinitely, when we have unified plan SDP.
2372void PeerConnection::RemoveAudioTrack(AudioTrackInterface* track,
2373 MediaStreamInterface* stream) {
2374 RTC_DCHECK(!IsClosed());
2375 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08002376 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002377 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
2378 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002379 return;
2380 }
Steve Anton4171afb2017-11-20 10:20:22 -08002381 GetAudioTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002382}
2383
2384void PeerConnection::AddVideoTrack(VideoTrackInterface* track,
2385 MediaStreamInterface* stream) {
2386 RTC_DCHECK(!IsClosed());
2387 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08002388 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002389 // We already have a sender for this track, so just change the stream_id
2390 // so that it's correct in the next call to CreateOffer.
Steve Anton4171afb2017-11-20 10:20:22 -08002391 sender->internal()->set_stream_id(stream->label());
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002392 return;
2393 }
2394
2395 // Normal case; we've never seen this track before.
2396 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender =
2397 RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton75737c02017-11-06 10:37:17 -08002398 signaling_thread(),
2399 new VideoRtpSender(track, {stream->label()}, video_channel()));
Steve Anton4171afb2017-11-20 10:20:22 -08002400 GetVideoTransceiver()->internal()->AddSender(new_sender);
2401 const RtpSenderInfo* sender_info =
2402 FindSenderInfo(local_video_sender_infos_, stream->label(), track->id());
2403 if (sender_info) {
2404 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002405 }
2406}
2407
2408void PeerConnection::RemoveVideoTrack(VideoTrackInterface* track,
2409 MediaStreamInterface* stream) {
2410 RTC_DCHECK(!IsClosed());
2411 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08002412 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002413 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
2414 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002415 return;
2416 }
Steve Anton4171afb2017-11-20 10:20:22 -08002417 GetVideoTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002418}
2419
Steve Antonba818672017-11-06 10:21:57 -08002420void PeerConnection::SetIceConnectionState(IceConnectionState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07002421 RTC_DCHECK(signaling_thread()->IsCurrent());
Steve Antonba818672017-11-06 10:21:57 -08002422 if (ice_connection_state_ == new_state) {
2423 return;
2424 }
2425
deadbeefcbecd352015-09-23 11:50:27 -07002426 // After transitioning to "closed", ignore any additional states from
Steve Antonba818672017-11-06 10:21:57 -08002427 // TransportController (such as "disconnected").
deadbeefab9b2d12015-10-14 11:33:11 -07002428 if (IsClosed()) {
deadbeefcbecd352015-09-23 11:50:27 -07002429 return;
2430 }
Steve Antonba818672017-11-06 10:21:57 -08002431
Mirko Bonadei675513b2017-11-09 11:09:25 +01002432 RTC_LOG(LS_INFO) << "Changing IceConnectionState " << ice_connection_state_
2433 << " => " << new_state;
Steve Antonba818672017-11-06 10:21:57 -08002434 RTC_DCHECK(ice_connection_state_ !=
2435 PeerConnectionInterface::kIceConnectionClosed);
2436
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002437 ice_connection_state_ = new_state;
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00002438 observer_->OnIceConnectionChange(ice_connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002439}
2440
2441void PeerConnection::OnIceGatheringChange(
2442 PeerConnectionInterface::IceGatheringState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07002443 RTC_DCHECK(signaling_thread()->IsCurrent());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002444 if (IsClosed()) {
2445 return;
2446 }
2447 ice_gathering_state_ = new_state;
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00002448 observer_->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002449}
2450
jbauch81bf7b02017-03-25 08:31:12 -07002451void PeerConnection::OnIceCandidate(
2452 std::unique_ptr<IceCandidateInterface> candidate) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07002453 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07002454 if (IsClosed()) {
2455 return;
2456 }
jbauch81bf7b02017-03-25 08:31:12 -07002457 observer_->OnIceCandidate(candidate.get());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002458}
2459
Honghai Zhang7fb69db2016-03-14 11:59:18 -07002460void PeerConnection::OnIceCandidatesRemoved(
2461 const std::vector<cricket::Candidate>& candidates) {
2462 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07002463 if (IsClosed()) {
2464 return;
2465 }
Honghai Zhang7fb69db2016-03-14 11:59:18 -07002466 observer_->OnIceCandidatesRemoved(candidates);
2467}
2468
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002469void PeerConnection::ChangeSignalingState(
2470 PeerConnectionInterface::SignalingState signaling_state) {
Steve Antonba818672017-11-06 10:21:57 -08002471 RTC_DCHECK(signaling_thread()->IsCurrent());
2472 if (signaling_state_ == signaling_state) {
2473 return;
2474 }
Mirko Bonadei675513b2017-11-09 11:09:25 +01002475 RTC_LOG(LS_INFO) << "Session: " << session_id() << " Old state: "
2476 << GetSignalingStateString(signaling_state_)
2477 << " New state: "
2478 << GetSignalingStateString(signaling_state);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002479 signaling_state_ = signaling_state;
2480 if (signaling_state == kClosed) {
2481 ice_connection_state_ = kIceConnectionClosed;
2482 observer_->OnIceConnectionChange(ice_connection_state_);
2483 if (ice_gathering_state_ != kIceGatheringComplete) {
2484 ice_gathering_state_ = kIceGatheringComplete;
2485 observer_->OnIceGatheringChange(ice_gathering_state_);
2486 }
2487 }
2488 observer_->OnSignalingChange(signaling_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002489}
2490
deadbeefeb459812015-12-15 19:24:43 -08002491void PeerConnection::OnAudioTrackAdded(AudioTrackInterface* track,
2492 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07002493 if (IsClosed()) {
2494 return;
2495 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002496 AddAudioTrack(track, stream);
2497 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08002498}
2499
deadbeefeb459812015-12-15 19:24:43 -08002500void PeerConnection::OnAudioTrackRemoved(AudioTrackInterface* track,
2501 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07002502 if (IsClosed()) {
2503 return;
2504 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002505 RemoveAudioTrack(track, stream);
2506 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08002507}
2508
2509void PeerConnection::OnVideoTrackAdded(VideoTrackInterface* track,
2510 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07002511 if (IsClosed()) {
2512 return;
2513 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002514 AddVideoTrack(track, stream);
2515 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08002516}
2517
2518void PeerConnection::OnVideoTrackRemoved(VideoTrackInterface* track,
2519 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07002520 if (IsClosed()) {
2521 return;
2522 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002523 RemoveVideoTrack(track, stream);
2524 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08002525}
2526
Henrik Boström31638672017-11-23 17:48:32 +01002527void PeerConnection::PostSetSessionDescriptionSuccess(
2528 SetSessionDescriptionObserver* observer) {
2529 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
2530 signaling_thread()->Post(RTC_FROM_HERE, this,
2531 MSG_SET_SESSIONDESCRIPTION_SUCCESS, msg);
2532}
2533
deadbeefab9b2d12015-10-14 11:33:11 -07002534void PeerConnection::PostSetSessionDescriptionFailure(
2535 SetSessionDescriptionObserver* observer,
2536 const std::string& error) {
2537 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
2538 msg->error = error;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07002539 signaling_thread()->Post(RTC_FROM_HERE, this,
2540 MSG_SET_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07002541}
2542
2543void PeerConnection::PostCreateSessionDescriptionFailure(
2544 CreateSessionDescriptionObserver* observer,
2545 const std::string& error) {
2546 CreateSessionDescriptionMsg* msg = new CreateSessionDescriptionMsg(observer);
2547 msg->error = error;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07002548 signaling_thread()->Post(RTC_FROM_HERE, this,
2549 MSG_CREATE_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07002550}
2551
zhihuang1c378ed2017-08-17 14:10:50 -07002552void PeerConnection::GetOptionsForOffer(
deadbeefab9b2d12015-10-14 11:33:11 -07002553 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options,
2554 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07002555 ExtractSharedMediaSessionOptions(rtc_options, session_options);
2556
2557 // Figure out transceiver directional preferences.
2558 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
2559 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
2560
2561 // By default, generate sendrecv/recvonly m= sections.
2562 bool recv_audio = true;
2563 bool recv_video = true;
2564
2565 // By default, only offer a new m= section if we have media to send with it.
2566 bool offer_new_audio_description = send_audio;
2567 bool offer_new_video_description = send_video;
2568 bool offer_new_data_description = HasDataChannels();
2569
2570 // The "offer_to_receive_X" options allow those defaults to be overridden.
2571 if (rtc_options.offer_to_receive_audio != RTCOfferAnswerOptions::kUndefined) {
2572 recv_audio = (rtc_options.offer_to_receive_audio > 0);
2573 offer_new_audio_description =
2574 offer_new_audio_description || (rtc_options.offer_to_receive_audio > 0);
2575 }
2576 if (rtc_options.offer_to_receive_video != RTCOfferAnswerOptions::kUndefined) {
2577 recv_video = (rtc_options.offer_to_receive_video > 0);
2578 offer_new_video_description =
2579 offer_new_video_description || (rtc_options.offer_to_receive_video > 0);
2580 }
2581
2582 rtc::Optional<size_t> audio_index;
2583 rtc::Optional<size_t> video_index;
2584 rtc::Optional<size_t> data_index;
2585 // If a current description exists, generate m= sections in the same order,
2586 // using the first audio/video/data section that appears and rejecting
2587 // extraneous ones.
Steve Anton75737c02017-11-06 10:37:17 -08002588 if (local_description()) {
zhihuang1c378ed2017-08-17 14:10:50 -07002589 GenerateMediaDescriptionOptions(
Steve Anton75737c02017-11-06 10:37:17 -08002590 local_description(),
Steve Anton1d03a752017-11-27 14:30:09 -08002591 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
2592 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
2593 &audio_index, &video_index, &data_index, session_options);
deadbeefab9b2d12015-10-14 11:33:11 -07002594 }
2595
zhihuang1c378ed2017-08-17 14:10:50 -07002596 // Add audio/video/data m= sections to the end if needed.
2597 if (!audio_index && offer_new_audio_description) {
2598 session_options->media_description_options.push_back(
2599 cricket::MediaDescriptionOptions(
2600 cricket::MEDIA_TYPE_AUDIO, cricket::CN_AUDIO,
Steve Anton1d03a752017-11-27 14:30:09 -08002601 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
2602 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01002603 audio_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07002604 }
zhihuang1c378ed2017-08-17 14:10:50 -07002605 if (!video_index && offer_new_video_description) {
2606 session_options->media_description_options.push_back(
2607 cricket::MediaDescriptionOptions(
2608 cricket::MEDIA_TYPE_VIDEO, cricket::CN_VIDEO,
Steve Anton1d03a752017-11-27 14:30:09 -08002609 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
2610 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01002611 video_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07002612 }
zhihuang1c378ed2017-08-17 14:10:50 -07002613 if (!data_index && offer_new_data_description) {
2614 session_options->media_description_options.push_back(
2615 cricket::MediaDescriptionOptions(
2616 cricket::MEDIA_TYPE_DATA, cricket::CN_DATA,
Steve Anton1d03a752017-11-27 14:30:09 -08002617 RtpTransceiverDirection::kSendRecv, false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01002618 data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07002619 }
2620
2621 cricket::MediaDescriptionOptions* audio_media_description_options =
2622 !audio_index ? nullptr
2623 : &session_options->media_description_options[*audio_index];
2624 cricket::MediaDescriptionOptions* video_media_description_options =
2625 !video_index ? nullptr
2626 : &session_options->media_description_options[*video_index];
2627 cricket::MediaDescriptionOptions* data_media_description_options =
2628 !data_index ? nullptr
2629 : &session_options->media_description_options[*data_index];
2630
2631 // Apply ICE restart flag and renomination flag.
2632 for (auto& options : session_options->media_description_options) {
2633 options.transport_options.ice_restart = rtc_options.ice_restart;
2634 options.transport_options.enable_ice_renomination =
2635 configuration_.enable_ice_renomination;
2636 }
2637
Steve Anton4171afb2017-11-20 10:20:22 -08002638 AddRtpSenderOptions(GetSendersInternal(), audio_media_description_options,
zhihuang1c378ed2017-08-17 14:10:50 -07002639 video_media_description_options);
2640 AddRtpDataChannelOptions(rtp_data_channels_, data_media_description_options);
deadbeefc80741f2015-10-22 13:14:45 -07002641
zhihuang9763d562016-08-05 11:14:50 -07002642 // Intentionally unset the data channel type for RTP data channel with the
2643 // second condition. Otherwise the RTP data channels would be successfully
2644 // negotiated by default and the unit tests in WebRtcDataBrowserTest will fail
2645 // when building with chromium. We want to leave RTP data channels broken, so
2646 // people won't try to use them.
Steve Anton75737c02017-11-06 10:37:17 -08002647 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
2648 session_options->data_channel_type = data_channel_type();
deadbeefab9b2d12015-10-14 11:33:11 -07002649 }
zhihuang8f65cdf2016-05-06 18:40:30 -07002650
2651 session_options->rtcp_cname = rtcp_cname_;
jbauchcb560652016-08-04 05:20:32 -07002652 session_options->crypto_options = factory_->options().crypto_options;
deadbeefab9b2d12015-10-14 11:33:11 -07002653}
2654
zhihuang1c378ed2017-08-17 14:10:50 -07002655void PeerConnection::GetOptionsForAnswer(
2656 const RTCOfferAnswerOptions& rtc_options,
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07002657 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07002658 ExtractSharedMediaSessionOptions(rtc_options, session_options);
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07002659
zhihuang1c378ed2017-08-17 14:10:50 -07002660 // Figure out transceiver directional preferences.
2661 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
2662 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
2663
2664 // By default, generate sendrecv/recvonly m= sections. The direction is also
2665 // restricted by the direction in the offer.
2666 bool recv_audio = true;
2667 bool recv_video = true;
2668
2669 // The "offer_to_receive_X" options allow those defaults to be overridden.
2670 if (rtc_options.offer_to_receive_audio != RTCOfferAnswerOptions::kUndefined) {
2671 recv_audio = (rtc_options.offer_to_receive_audio > 0);
deadbeef0ed85b22016-02-23 17:24:52 -08002672 }
zhihuang1c378ed2017-08-17 14:10:50 -07002673 if (rtc_options.offer_to_receive_video != RTCOfferAnswerOptions::kUndefined) {
2674 recv_video = (rtc_options.offer_to_receive_video > 0);
2675 }
2676
2677 rtc::Optional<size_t> audio_index;
2678 rtc::Optional<size_t> video_index;
2679 rtc::Optional<size_t> data_index;
Steve Anton75737c02017-11-06 10:37:17 -08002680 if (remote_description()) {
zhihuang141aacb2017-08-29 13:23:53 -07002681 // The pending remote description should be an offer.
Steve Antona3a92c22017-12-07 10:27:41 -08002682 RTC_DCHECK(remote_description()->GetType() == SdpType::kOffer);
zhihuang141aacb2017-08-29 13:23:53 -07002683 // Generate m= sections that match those in the offer.
2684 // Note that mediasession.cc will handle intersection our preferred
2685 // direction with the offered direction.
2686 GenerateMediaDescriptionOptions(
Steve Anton75737c02017-11-06 10:37:17 -08002687 remote_description(),
Steve Anton1d03a752017-11-27 14:30:09 -08002688 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
2689 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
2690 &audio_index, &video_index, &data_index, session_options);
zhihuang141aacb2017-08-29 13:23:53 -07002691 }
zhihuang1c378ed2017-08-17 14:10:50 -07002692
2693 cricket::MediaDescriptionOptions* audio_media_description_options =
2694 !audio_index ? nullptr
2695 : &session_options->media_description_options[*audio_index];
2696 cricket::MediaDescriptionOptions* video_media_description_options =
2697 !video_index ? nullptr
2698 : &session_options->media_description_options[*video_index];
2699 cricket::MediaDescriptionOptions* data_media_description_options =
2700 !data_index ? nullptr
2701 : &session_options->media_description_options[*data_index];
2702
2703 // Apply ICE renomination flag.
2704 for (auto& options : session_options->media_description_options) {
2705 options.transport_options.enable_ice_renomination =
2706 configuration_.enable_ice_renomination;
2707 }
2708
Steve Anton4171afb2017-11-20 10:20:22 -08002709 AddRtpSenderOptions(GetSendersInternal(), audio_media_description_options,
zhihuang1c378ed2017-08-17 14:10:50 -07002710 video_media_description_options);
2711 AddRtpDataChannelOptions(rtp_data_channels_, data_media_description_options);
2712
zhihuang9763d562016-08-05 11:14:50 -07002713 // Intentionally unset the data channel type for RTP data channel. Otherwise
2714 // the RTP data channels would be successfully negotiated by default and the
2715 // unit tests in WebRtcDataBrowserTest will fail when building with chromium.
2716 // We want to leave RTP data channels broken, so people won't try to use them.
Steve Anton75737c02017-11-06 10:37:17 -08002717 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
2718 session_options->data_channel_type = data_channel_type();
deadbeef907abe42016-08-04 12:22:18 -07002719 }
zhihuangaf388472016-11-02 16:49:48 -07002720
zhihuang1c378ed2017-08-17 14:10:50 -07002721 session_options->rtcp_cname = rtcp_cname_;
jbauchcb560652016-08-04 05:20:32 -07002722 session_options->crypto_options = factory_->options().crypto_options;
htaa2a49d92016-03-04 02:51:39 -08002723}
2724
zhihuang1c378ed2017-08-17 14:10:50 -07002725void PeerConnection::GenerateMediaDescriptionOptions(
2726 const SessionDescriptionInterface* session_desc,
Steve Anton1d03a752017-11-27 14:30:09 -08002727 RtpTransceiverDirection audio_direction,
2728 RtpTransceiverDirection video_direction,
zhihuang1c378ed2017-08-17 14:10:50 -07002729 rtc::Optional<size_t>* audio_index,
2730 rtc::Optional<size_t>* video_index,
2731 rtc::Optional<size_t>* data_index,
htaa2a49d92016-03-04 02:51:39 -08002732 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07002733 for (const cricket::ContentInfo& content :
2734 session_desc->description()->contents()) {
2735 if (IsAudioContent(&content)) {
2736 // If we already have an audio m= section, reject this extra one.
2737 if (*audio_index) {
2738 session_options->media_description_options.push_back(
2739 cricket::MediaDescriptionOptions(
2740 cricket::MEDIA_TYPE_AUDIO, content.name,
Steve Anton1d03a752017-11-27 14:30:09 -08002741 RtpTransceiverDirection::kInactive, true));
zhihuang1c378ed2017-08-17 14:10:50 -07002742 } else {
2743 session_options->media_description_options.push_back(
2744 cricket::MediaDescriptionOptions(
2745 cricket::MEDIA_TYPE_AUDIO, content.name, audio_direction,
Steve Anton1d03a752017-11-27 14:30:09 -08002746 audio_direction == RtpTransceiverDirection::kInactive));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01002747 *audio_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07002748 }
2749 } else if (IsVideoContent(&content)) {
2750 // If we already have an video m= section, reject this extra one.
2751 if (*video_index) {
2752 session_options->media_description_options.push_back(
2753 cricket::MediaDescriptionOptions(
2754 cricket::MEDIA_TYPE_VIDEO, content.name,
Steve Anton1d03a752017-11-27 14:30:09 -08002755 RtpTransceiverDirection::kInactive, true));
zhihuang1c378ed2017-08-17 14:10:50 -07002756 } else {
2757 session_options->media_description_options.push_back(
2758 cricket::MediaDescriptionOptions(
2759 cricket::MEDIA_TYPE_VIDEO, content.name, video_direction,
Steve Anton1d03a752017-11-27 14:30:09 -08002760 video_direction == RtpTransceiverDirection::kInactive));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01002761 *video_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07002762 }
2763 } else {
2764 RTC_DCHECK(IsDataContent(&content));
2765 // If we already have an data m= section, reject this extra one.
2766 if (*data_index) {
2767 session_options->media_description_options.push_back(
2768 cricket::MediaDescriptionOptions(
2769 cricket::MEDIA_TYPE_DATA, content.name,
Steve Anton1d03a752017-11-27 14:30:09 -08002770 RtpTransceiverDirection::kInactive, true));
zhihuang1c378ed2017-08-17 14:10:50 -07002771 } else {
2772 session_options->media_description_options.push_back(
2773 cricket::MediaDescriptionOptions(
2774 cricket::MEDIA_TYPE_DATA, content.name,
2775 // Direction for data sections is meaningless, but legacy
2776 // endpoints might expect sendrecv.
Steve Anton1d03a752017-11-27 14:30:09 -08002777 RtpTransceiverDirection::kSendRecv, false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01002778 *data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07002779 }
2780 }
htaa2a49d92016-03-04 02:51:39 -08002781 }
deadbeefab9b2d12015-10-14 11:33:11 -07002782}
2783
Steve Anton4171afb2017-11-20 10:20:22 -08002784void PeerConnection::RemoveSenders(cricket::MediaType media_type) {
2785 UpdateLocalSenders(std::vector<cricket::StreamParams>(), media_type);
2786 UpdateRemoteSendersList(std::vector<cricket::StreamParams>(), false,
deadbeefbda7e0b2015-12-08 17:13:40 -08002787 media_type, nullptr);
deadbeeffaac4972015-11-12 15:33:07 -08002788}
2789
Steve Anton4171afb2017-11-20 10:20:22 -08002790void PeerConnection::UpdateRemoteSendersList(
deadbeefab9b2d12015-10-14 11:33:11 -07002791 const cricket::StreamParamsVec& streams,
Steve Anton4171afb2017-11-20 10:20:22 -08002792 bool default_sender_needed,
deadbeefab9b2d12015-10-14 11:33:11 -07002793 cricket::MediaType media_type,
2794 StreamCollection* new_streams) {
Steve Anton4171afb2017-11-20 10:20:22 -08002795 std::vector<RtpSenderInfo>* current_senders =
2796 GetRemoteSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07002797
Steve Anton4171afb2017-11-20 10:20:22 -08002798 // Find removed senders. I.e., senders where the sender id or ssrc don't match
deadbeeffac06552015-11-25 11:26:01 -08002799 // the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08002800 for (auto sender_it = current_senders->begin();
2801 sender_it != current_senders->end();
2802 /* incremented manually */) {
2803 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07002804 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08002805 cricket::GetStreamBySsrc(streams, info.first_ssrc);
2806 bool sender_exists = params && params->id == info.sender_id;
deadbeefbda7e0b2015-12-08 17:13:40 -08002807 // If this is a default track, and we still need it, don't remove it.
Steve Anton4171afb2017-11-20 10:20:22 -08002808 if ((info.stream_label == kDefaultStreamLabel && default_sender_needed) ||
2809 sender_exists) {
2810 ++sender_it;
deadbeefbda7e0b2015-12-08 17:13:40 -08002811 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08002812 OnRemoteSenderRemoved(info, media_type);
2813 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07002814 }
2815 }
2816
Steve Anton4171afb2017-11-20 10:20:22 -08002817 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07002818 for (const cricket::StreamParams& params : streams) {
2819 // The sync_label is the MediaStream label and the |stream.id| is the
Steve Anton4171afb2017-11-20 10:20:22 -08002820 // sender id.
deadbeefab9b2d12015-10-14 11:33:11 -07002821 const std::string& stream_label = params.sync_label;
Steve Anton4171afb2017-11-20 10:20:22 -08002822 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07002823 uint32_t ssrc = params.first_ssrc();
2824
2825 rtc::scoped_refptr<MediaStreamInterface> stream =
2826 remote_streams_->find(stream_label);
2827 if (!stream) {
2828 // This is a new MediaStream. Create a new remote MediaStream.
perkjd61bf802016-03-24 03:16:19 -07002829 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
2830 MediaStream::Create(stream_label));
deadbeefab9b2d12015-10-14 11:33:11 -07002831 remote_streams_->AddStream(stream);
2832 new_streams->AddStream(stream);
2833 }
2834
Steve Anton4171afb2017-11-20 10:20:22 -08002835 const RtpSenderInfo* sender_info =
2836 FindSenderInfo(*current_senders, stream_label, sender_id);
2837 if (!sender_info) {
2838 current_senders->push_back(RtpSenderInfo(stream_label, sender_id, ssrc));
2839 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07002840 }
2841 }
deadbeefbda7e0b2015-12-08 17:13:40 -08002842
Steve Anton4171afb2017-11-20 10:20:22 -08002843 // Add default sender if necessary.
2844 if (default_sender_needed) {
deadbeefbda7e0b2015-12-08 17:13:40 -08002845 rtc::scoped_refptr<MediaStreamInterface> default_stream =
2846 remote_streams_->find(kDefaultStreamLabel);
2847 if (!default_stream) {
2848 // Create the new default MediaStream.
perkjd61bf802016-03-24 03:16:19 -07002849 default_stream = MediaStreamProxy::Create(
2850 rtc::Thread::Current(), MediaStream::Create(kDefaultStreamLabel));
deadbeefbda7e0b2015-12-08 17:13:40 -08002851 remote_streams_->AddStream(default_stream);
2852 new_streams->AddStream(default_stream);
2853 }
Steve Anton4171afb2017-11-20 10:20:22 -08002854 std::string default_sender_id = (media_type == cricket::MEDIA_TYPE_AUDIO)
2855 ? kDefaultAudioSenderId
2856 : kDefaultVideoSenderId;
2857 const RtpSenderInfo* default_sender_info = FindSenderInfo(
2858 *current_senders, kDefaultStreamLabel, default_sender_id);
2859 if (!default_sender_info) {
2860 current_senders->push_back(
2861 RtpSenderInfo(kDefaultStreamLabel, default_sender_id, 0));
2862 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefbda7e0b2015-12-08 17:13:40 -08002863 }
2864 }
deadbeefab9b2d12015-10-14 11:33:11 -07002865}
2866
Steve Anton4171afb2017-11-20 10:20:22 -08002867void PeerConnection::OnRemoteSenderAdded(const RtpSenderInfo& sender_info,
2868 cricket::MediaType media_type) {
2869 MediaStreamInterface* stream =
2870 remote_streams_->find(sender_info.stream_label);
deadbeefab9b2d12015-10-14 11:33:11 -07002871
2872 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 10:20:22 -08002873 CreateAudioReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07002874 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 10:20:22 -08002875 CreateVideoReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07002876 } else {
nisseeb4ca4e2017-01-12 02:24:27 -08002877 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07002878 }
2879}
2880
Steve Anton4171afb2017-11-20 10:20:22 -08002881void PeerConnection::OnRemoteSenderRemoved(const RtpSenderInfo& sender_info,
2882 cricket::MediaType media_type) {
2883 MediaStreamInterface* stream =
2884 remote_streams_->find(sender_info.stream_label);
deadbeefab9b2d12015-10-14 11:33:11 -07002885
Henrik Boström933d8b02017-10-10 10:05:16 -07002886 rtc::scoped_refptr<RtpReceiverInterface> receiver;
deadbeefab9b2d12015-10-14 11:33:11 -07002887 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
perkjd61bf802016-03-24 03:16:19 -07002888 // When the MediaEngine audio channel is destroyed, the RemoteAudioSource
2889 // will be notified which will end the AudioRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08002890 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07002891 rtc::scoped_refptr<AudioTrackInterface> audio_track =
Steve Anton4171afb2017-11-20 10:20:22 -08002892 stream->FindAudioTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07002893 if (audio_track) {
deadbeefab9b2d12015-10-14 11:33:11 -07002894 stream->RemoveTrack(audio_track);
deadbeefab9b2d12015-10-14 11:33:11 -07002895 }
2896 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
perkjd61bf802016-03-24 03:16:19 -07002897 // Stopping or destroying a VideoRtpReceiver will end the
2898 // VideoRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08002899 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07002900 rtc::scoped_refptr<VideoTrackInterface> video_track =
Steve Anton4171afb2017-11-20 10:20:22 -08002901 stream->FindVideoTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07002902 if (video_track) {
perkjd61bf802016-03-24 03:16:19 -07002903 // There's no guarantee the track is still available, e.g. the track may
2904 // have been removed from the stream by an application.
deadbeefab9b2d12015-10-14 11:33:11 -07002905 stream->RemoveTrack(video_track);
deadbeefab9b2d12015-10-14 11:33:11 -07002906 }
2907 } else {
nisseede5da42017-01-12 05:15:36 -08002908 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07002909 }
Henrik Boström933d8b02017-10-10 10:05:16 -07002910 if (receiver) {
2911 observer_->OnRemoveTrack(receiver);
2912 }
deadbeefab9b2d12015-10-14 11:33:11 -07002913}
2914
2915void PeerConnection::UpdateEndedRemoteMediaStreams() {
2916 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams_to_remove;
2917 for (size_t i = 0; i < remote_streams_->count(); ++i) {
2918 MediaStreamInterface* stream = remote_streams_->at(i);
2919 if (stream->GetAudioTracks().empty() && stream->GetVideoTracks().empty()) {
2920 streams_to_remove.push_back(stream);
2921 }
2922 }
2923
Taylor Brandstetter98cde262016-05-31 13:02:21 -07002924 for (auto& stream : streams_to_remove) {
deadbeefab9b2d12015-10-14 11:33:11 -07002925 remote_streams_->RemoveStream(stream);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07002926 observer_->OnRemoveStream(std::move(stream));
deadbeefab9b2d12015-10-14 11:33:11 -07002927 }
2928}
2929
Steve Anton4171afb2017-11-20 10:20:22 -08002930void PeerConnection::UpdateLocalSenders(
deadbeefab9b2d12015-10-14 11:33:11 -07002931 const std::vector<cricket::StreamParams>& streams,
2932 cricket::MediaType media_type) {
Steve Anton4171afb2017-11-20 10:20:22 -08002933 std::vector<RtpSenderInfo>* current_senders = GetLocalSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07002934
2935 // Find removed tracks. I.e., tracks where the track id, stream label or ssrc
2936 // don't match the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08002937 for (auto sender_it = current_senders->begin();
2938 sender_it != current_senders->end();
2939 /* incremented manually */) {
2940 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07002941 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08002942 cricket::GetStreamBySsrc(streams, info.first_ssrc);
2943 if (!params || params->id != info.sender_id ||
deadbeefab9b2d12015-10-14 11:33:11 -07002944 params->sync_label != info.stream_label) {
Steve Anton4171afb2017-11-20 10:20:22 -08002945 OnLocalSenderRemoved(info, media_type);
2946 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07002947 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08002948 ++sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07002949 }
2950 }
2951
Steve Anton4171afb2017-11-20 10:20:22 -08002952 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07002953 for (const cricket::StreamParams& params : streams) {
2954 // The sync_label is the MediaStream label and the |stream.id| is the
Steve Anton4171afb2017-11-20 10:20:22 -08002955 // sender id.
deadbeefab9b2d12015-10-14 11:33:11 -07002956 const std::string& stream_label = params.sync_label;
Steve Anton4171afb2017-11-20 10:20:22 -08002957 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07002958 uint32_t ssrc = params.first_ssrc();
Steve Anton4171afb2017-11-20 10:20:22 -08002959 const RtpSenderInfo* sender_info =
2960 FindSenderInfo(*current_senders, stream_label, sender_id);
2961 if (!sender_info) {
2962 current_senders->push_back(RtpSenderInfo(stream_label, sender_id, ssrc));
2963 OnLocalSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07002964 }
2965 }
2966}
2967
Steve Anton4171afb2017-11-20 10:20:22 -08002968void PeerConnection::OnLocalSenderAdded(const RtpSenderInfo& sender_info,
2969 cricket::MediaType media_type) {
2970 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08002971 if (!sender) {
Steve Anton4171afb2017-11-20 10:20:22 -08002972 RTC_LOG(LS_WARNING) << "An unknown RtpSender with id "
2973 << sender_info.sender_id
Mirko Bonadei675513b2017-11-09 11:09:25 +01002974 << " has been configured in the local description.";
deadbeefab9b2d12015-10-14 11:33:11 -07002975 return;
2976 }
2977
deadbeeffac06552015-11-25 11:26:01 -08002978 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002979 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
2980 << " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08002981 return;
deadbeefab9b2d12015-10-14 11:33:11 -07002982 }
deadbeeffac06552015-11-25 11:26:01 -08002983
Steve Anton4171afb2017-11-20 10:20:22 -08002984 sender->internal()->set_stream_id(sender_info.stream_label);
2985 sender->internal()->SetSsrc(sender_info.first_ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07002986}
2987
Steve Anton4171afb2017-11-20 10:20:22 -08002988void PeerConnection::OnLocalSenderRemoved(const RtpSenderInfo& sender_info,
2989 cricket::MediaType media_type) {
2990 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08002991 if (!sender) {
2992 // This is the normal case. I.e., RemoveStream has been called and the
deadbeefab9b2d12015-10-14 11:33:11 -07002993 // SessionDescriptions has been renegotiated.
2994 return;
2995 }
deadbeeffac06552015-11-25 11:26:01 -08002996
2997 // A sender has been removed from the SessionDescription but it's still
2998 // associated with the PeerConnection. This only occurs if the SDP doesn't
2999 // match with the calls to CreateSender, AddStream and RemoveStream.
3000 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003001 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
3002 << " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08003003 return;
deadbeefab9b2d12015-10-14 11:33:11 -07003004 }
deadbeeffac06552015-11-25 11:26:01 -08003005
Steve Anton4171afb2017-11-20 10:20:22 -08003006 sender->internal()->SetSsrc(0);
deadbeefab9b2d12015-10-14 11:33:11 -07003007}
3008
3009void PeerConnection::UpdateLocalRtpDataChannels(
3010 const cricket::StreamParamsVec& streams) {
3011 std::vector<std::string> existing_channels;
3012
3013 // Find new and active data channels.
3014 for (const cricket::StreamParams& params : streams) {
3015 // |it->sync_label| is actually the data channel label. The reason is that
3016 // we use the same naming of data channels as we do for
3017 // MediaStreams and Tracks.
3018 // For MediaStreams, the sync_label is the MediaStream label and the
3019 // track label is the same as |streamid|.
3020 const std::string& channel_label = params.sync_label;
3021 auto data_channel_it = rtp_data_channels_.find(channel_label);
nisse7ce109a2017-01-31 00:57:56 -08003022 if (data_channel_it == rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003023 RTC_LOG(LS_ERROR) << "channel label not found";
deadbeefab9b2d12015-10-14 11:33:11 -07003024 continue;
3025 }
3026 // Set the SSRC the data channel should use for sending.
3027 data_channel_it->second->SetSendSsrc(params.first_ssrc());
3028 existing_channels.push_back(data_channel_it->first);
3029 }
3030
3031 UpdateClosingRtpDataChannels(existing_channels, true);
3032}
3033
3034void PeerConnection::UpdateRemoteRtpDataChannels(
3035 const cricket::StreamParamsVec& streams) {
3036 std::vector<std::string> existing_channels;
3037
3038 // Find new and active data channels.
3039 for (const cricket::StreamParams& params : streams) {
3040 // The data channel label is either the mslabel or the SSRC if the mslabel
3041 // does not exist. Ex a=ssrc:444330170 mslabel:test1.
3042 std::string label = params.sync_label.empty()
3043 ? rtc::ToString(params.first_ssrc())
3044 : params.sync_label;
3045 auto data_channel_it = rtp_data_channels_.find(label);
3046 if (data_channel_it == rtp_data_channels_.end()) {
3047 // This is a new data channel.
3048 CreateRemoteRtpDataChannel(label, params.first_ssrc());
3049 } else {
3050 data_channel_it->second->SetReceiveSsrc(params.first_ssrc());
3051 }
3052 existing_channels.push_back(label);
3053 }
3054
3055 UpdateClosingRtpDataChannels(existing_channels, false);
3056}
3057
3058void PeerConnection::UpdateClosingRtpDataChannels(
3059 const std::vector<std::string>& active_channels,
3060 bool is_local_update) {
3061 auto it = rtp_data_channels_.begin();
3062 while (it != rtp_data_channels_.end()) {
3063 DataChannel* data_channel = it->second;
3064 if (std::find(active_channels.begin(), active_channels.end(),
3065 data_channel->label()) != active_channels.end()) {
3066 ++it;
3067 continue;
3068 }
3069
3070 if (is_local_update) {
3071 data_channel->SetSendSsrc(0);
3072 } else {
3073 data_channel->RemotePeerRequestClose();
3074 }
3075
3076 if (data_channel->state() == DataChannel::kClosed) {
3077 rtp_data_channels_.erase(it);
3078 it = rtp_data_channels_.begin();
3079 } else {
3080 ++it;
3081 }
3082 }
3083}
3084
3085void PeerConnection::CreateRemoteRtpDataChannel(const std::string& label,
3086 uint32_t remote_ssrc) {
3087 rtc::scoped_refptr<DataChannel> channel(
3088 InternalCreateDataChannel(label, nullptr));
3089 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003090 RTC_LOG(LS_WARNING) << "Remote peer requested a DataChannel but"
3091 << "CreateDataChannel failed.";
deadbeefab9b2d12015-10-14 11:33:11 -07003092 return;
3093 }
3094 channel->SetReceiveSsrc(remote_ssrc);
deadbeefa601f5c2016-06-06 14:27:39 -07003095 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
3096 DataChannelProxy::Create(signaling_thread(), channel);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07003097 observer_->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07003098}
3099
3100rtc::scoped_refptr<DataChannel> PeerConnection::InternalCreateDataChannel(
3101 const std::string& label,
3102 const InternalDataChannelInit* config) {
3103 if (IsClosed()) {
3104 return nullptr;
3105 }
Steve Anton75737c02017-11-06 10:37:17 -08003106 if (data_channel_type() == cricket::DCT_NONE) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003107 RTC_LOG(LS_ERROR)
deadbeefab9b2d12015-10-14 11:33:11 -07003108 << "InternalCreateDataChannel: Data is not supported in this call.";
3109 return nullptr;
3110 }
3111 InternalDataChannelInit new_config =
3112 config ? (*config) : InternalDataChannelInit();
Steve Anton75737c02017-11-06 10:37:17 -08003113 if (data_channel_type() == cricket::DCT_SCTP) {
deadbeefab9b2d12015-10-14 11:33:11 -07003114 if (new_config.id < 0) {
3115 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08003116 if ((GetSctpSslRole(&role)) &&
deadbeefab9b2d12015-10-14 11:33:11 -07003117 !sid_allocator_.AllocateSid(role, &new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003118 RTC_LOG(LS_ERROR)
3119 << "No id can be allocated for the SCTP data channel.";
deadbeefab9b2d12015-10-14 11:33:11 -07003120 return nullptr;
3121 }
3122 } else if (!sid_allocator_.ReserveSid(new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003123 RTC_LOG(LS_ERROR) << "Failed to create a SCTP data channel "
3124 << "because the id is already in use or out of range.";
deadbeefab9b2d12015-10-14 11:33:11 -07003125 return nullptr;
3126 }
3127 }
3128
Steve Anton75737c02017-11-06 10:37:17 -08003129 rtc::scoped_refptr<DataChannel> channel(
3130 DataChannel::Create(this, data_channel_type(), label, new_config));
deadbeefab9b2d12015-10-14 11:33:11 -07003131 if (!channel) {
3132 sid_allocator_.ReleaseSid(new_config.id);
3133 return nullptr;
3134 }
3135
3136 if (channel->data_channel_type() == cricket::DCT_RTP) {
3137 if (rtp_data_channels_.find(channel->label()) != rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003138 RTC_LOG(LS_ERROR) << "DataChannel with label " << channel->label()
3139 << " already exists.";
deadbeefab9b2d12015-10-14 11:33:11 -07003140 return nullptr;
3141 }
3142 rtp_data_channels_[channel->label()] = channel;
3143 } else {
3144 RTC_DCHECK(channel->data_channel_type() == cricket::DCT_SCTP);
3145 sctp_data_channels_.push_back(channel);
3146 channel->SignalClosed.connect(this,
3147 &PeerConnection::OnSctpDataChannelClosed);
3148 }
3149
hbos82ebe022016-11-14 01:41:09 -08003150 SignalDataChannelCreated(channel.get());
deadbeefab9b2d12015-10-14 11:33:11 -07003151 return channel;
3152}
3153
3154bool PeerConnection::HasDataChannels() const {
3155 return !rtp_data_channels_.empty() || !sctp_data_channels_.empty();
3156}
3157
3158void PeerConnection::AllocateSctpSids(rtc::SSLRole role) {
3159 for (const auto& channel : sctp_data_channels_) {
3160 if (channel->id() < 0) {
3161 int sid;
3162 if (!sid_allocator_.AllocateSid(role, &sid)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003163 RTC_LOG(LS_ERROR) << "Failed to allocate SCTP sid.";
deadbeefab9b2d12015-10-14 11:33:11 -07003164 continue;
3165 }
3166 channel->SetSctpSid(sid);
3167 }
3168 }
3169}
3170
3171void PeerConnection::OnSctpDataChannelClosed(DataChannel* channel) {
deadbeefbd292462015-12-14 18:15:29 -08003172 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeefab9b2d12015-10-14 11:33:11 -07003173 for (auto it = sctp_data_channels_.begin(); it != sctp_data_channels_.end();
3174 ++it) {
3175 if (it->get() == channel) {
3176 if (channel->id() >= 0) {
3177 sid_allocator_.ReleaseSid(channel->id());
3178 }
deadbeefbd292462015-12-14 18:15:29 -08003179 // Since this method is triggered by a signal from the DataChannel,
3180 // we can't free it directly here; we need to free it asynchronously.
3181 sctp_data_channels_to_free_.push_back(*it);
deadbeefab9b2d12015-10-14 11:33:11 -07003182 sctp_data_channels_.erase(it);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07003183 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_FREE_DATACHANNELS,
3184 nullptr);
deadbeefab9b2d12015-10-14 11:33:11 -07003185 return;
3186 }
3187 }
3188}
3189
deadbeefab9b2d12015-10-14 11:33:11 -07003190void PeerConnection::OnDataChannelDestroyed() {
3191 // Use a temporary copy of the RTP/SCTP DataChannel list because the
3192 // DataChannel may callback to us and try to modify the list.
3193 std::map<std::string, rtc::scoped_refptr<DataChannel>> temp_rtp_dcs;
3194 temp_rtp_dcs.swap(rtp_data_channels_);
3195 for (const auto& kv : temp_rtp_dcs) {
3196 kv.second->OnTransportChannelDestroyed();
3197 }
3198
3199 std::vector<rtc::scoped_refptr<DataChannel>> temp_sctp_dcs;
3200 temp_sctp_dcs.swap(sctp_data_channels_);
3201 for (const auto& channel : temp_sctp_dcs) {
3202 channel->OnTransportChannelDestroyed();
3203 }
3204}
3205
3206void PeerConnection::OnDataChannelOpenMessage(
3207 const std::string& label,
3208 const InternalDataChannelInit& config) {
3209 rtc::scoped_refptr<DataChannel> channel(
3210 InternalCreateDataChannel(label, &config));
3211 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003212 RTC_LOG(LS_ERROR) << "Failed to create DataChannel from the OPEN message.";
deadbeefab9b2d12015-10-14 11:33:11 -07003213 return;
3214 }
3215
deadbeefa601f5c2016-06-06 14:27:39 -07003216 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
3217 DataChannelProxy::Create(signaling_thread(), channel);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07003218 observer_->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07003219}
3220
Steve Anton4171afb2017-11-20 10:20:22 -08003221rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3222PeerConnection::GetAudioTransceiver() const {
3223 // This method only works with Plan B SDP, where there is a single
3224 // audio/video transceiver.
3225 RTC_DCHECK(!IsUnifiedPlan());
3226 for (auto transceiver : transceivers_) {
3227 if (transceiver->internal()->media_type() == cricket::MEDIA_TYPE_AUDIO) {
3228 return transceiver;
3229 }
3230 }
3231 RTC_NOTREACHED();
3232 return nullptr;
3233}
3234
3235rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3236PeerConnection::GetVideoTransceiver() const {
3237 // This method only works with Plan B SDP, where there is a single
3238 // audio/video transceiver.
3239 RTC_DCHECK(!IsUnifiedPlan());
3240 for (auto transceiver : transceivers_) {
3241 if (transceiver->internal()->media_type() == cricket::MEDIA_TYPE_VIDEO) {
3242 return transceiver;
3243 }
3244 }
3245 RTC_NOTREACHED();
3246 return nullptr;
3247}
3248
3249// TODO(bugs.webrtc.org/7600): Remove this when multiple transceivers with
3250// individual transceiver directions are supported.
zhihuang1c378ed2017-08-17 14:10:50 -07003251bool PeerConnection::HasRtpSender(cricket::MediaType type) const {
Steve Anton4171afb2017-11-20 10:20:22 -08003252 switch (type) {
3253 case cricket::MEDIA_TYPE_AUDIO:
3254 return !GetAudioTransceiver()->internal()->senders().empty();
3255 case cricket::MEDIA_TYPE_VIDEO:
3256 return !GetVideoTransceiver()->internal()->senders().empty();
3257 case cricket::MEDIA_TYPE_DATA:
3258 return false;
3259 }
3260 RTC_NOTREACHED();
3261 return false;
zhihuang1c378ed2017-08-17 14:10:50 -07003262}
3263
Steve Anton4171afb2017-11-20 10:20:22 -08003264rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
3265PeerConnection::FindSenderForTrack(MediaStreamTrackInterface* track) const {
3266 for (auto transceiver : transceivers_) {
3267 for (auto sender : transceiver->internal()->senders()) {
3268 if (sender->track() == track) {
3269 return sender;
3270 }
3271 }
3272 }
3273 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08003274}
3275
Steve Anton4171afb2017-11-20 10:20:22 -08003276rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
3277PeerConnection::FindSenderById(const std::string& sender_id) const {
3278 for (auto transceiver : transceivers_) {
3279 for (auto sender : transceiver->internal()->senders()) {
3280 if (sender->id() == sender_id) {
3281 return sender;
3282 }
3283 }
3284 }
3285 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07003286}
3287
Steve Anton4171afb2017-11-20 10:20:22 -08003288rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
3289PeerConnection::FindReceiverById(const std::string& receiver_id) const {
3290 for (auto transceiver : transceivers_) {
3291 for (auto receiver : transceiver->internal()->receivers()) {
3292 if (receiver->id() == receiver_id) {
3293 return receiver;
3294 }
3295 }
3296 }
3297 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07003298}
3299
Steve Anton4171afb2017-11-20 10:20:22 -08003300std::vector<PeerConnection::RtpSenderInfo>*
3301PeerConnection::GetRemoteSenderInfos(cricket::MediaType media_type) {
3302 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
3303 media_type == cricket::MEDIA_TYPE_VIDEO);
3304 return (media_type == cricket::MEDIA_TYPE_AUDIO)
3305 ? &remote_audio_sender_infos_
3306 : &remote_video_sender_infos_;
3307}
3308
3309std::vector<PeerConnection::RtpSenderInfo>* PeerConnection::GetLocalSenderInfos(
deadbeefab9b2d12015-10-14 11:33:11 -07003310 cricket::MediaType media_type) {
3311 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
3312 media_type == cricket::MEDIA_TYPE_VIDEO);
Steve Anton4171afb2017-11-20 10:20:22 -08003313 return (media_type == cricket::MEDIA_TYPE_AUDIO) ? &local_audio_sender_infos_
3314 : &local_video_sender_infos_;
deadbeefab9b2d12015-10-14 11:33:11 -07003315}
3316
Steve Anton4171afb2017-11-20 10:20:22 -08003317const PeerConnection::RtpSenderInfo* PeerConnection::FindSenderInfo(
3318 const std::vector<PeerConnection::RtpSenderInfo>& infos,
deadbeefab9b2d12015-10-14 11:33:11 -07003319 const std::string& stream_label,
Steve Anton4171afb2017-11-20 10:20:22 -08003320 const std::string sender_id) const {
3321 for (const RtpSenderInfo& sender_info : infos) {
3322 if (sender_info.stream_label == stream_label &&
3323 sender_info.sender_id == sender_id) {
3324 return &sender_info;
deadbeefab9b2d12015-10-14 11:33:11 -07003325 }
3326 }
3327 return nullptr;
3328}
3329
3330DataChannel* PeerConnection::FindDataChannelBySid(int sid) const {
3331 for (const auto& channel : sctp_data_channels_) {
3332 if (channel->id() == sid) {
3333 return channel;
3334 }
3335 }
3336 return nullptr;
3337}
3338
deadbeef91dd5672016-05-18 16:55:30 -07003339bool PeerConnection::InitializePortAllocator_n(
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003340 const RTCConfiguration& configuration) {
3341 cricket::ServerAddresses stun_servers;
3342 std::vector<cricket::RelayServerConfig> turn_servers;
deadbeef293e9262017-01-11 12:28:30 -08003343 if (ParseIceServers(configuration.servers, &stun_servers, &turn_servers) !=
3344 RTCErrorType::NONE) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003345 return false;
3346 }
3347
Taylor Brandstetterf8e65772016-06-27 17:20:15 -07003348 port_allocator_->Initialize();
3349
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003350 // To handle both internal and externally created port allocator, we will
3351 // enable BUNDLE here.
3352 int portallocator_flags = port_allocator_->flags();
3353 portallocator_flags |= cricket::PORTALLOCATOR_ENABLE_SHARED_SOCKET |
zhihuangb09b3f92017-03-07 14:40:51 -08003354 cricket::PORTALLOCATOR_ENABLE_IPV6 |
3355 cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI;
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003356 // If the disable-IPv6 flag was specified, we'll not override it
3357 // by experiment.
3358 if (configuration.disable_ipv6) {
3359 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
sprangc1b57a12017-02-28 08:50:47 -08003360 } else if (webrtc::field_trial::FindFullName("WebRTC-IPv6Default")
3361 .find("Disabled") == 0) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003362 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
3363 }
3364
zhihuangb09b3f92017-03-07 14:40:51 -08003365 if (configuration.disable_ipv6_on_wifi) {
3366 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI);
Mirko Bonadei675513b2017-11-09 11:09:25 +01003367 RTC_LOG(LS_INFO) << "IPv6 candidates on Wi-Fi are disabled.";
zhihuangb09b3f92017-03-07 14:40:51 -08003368 }
3369
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003370 if (configuration.tcp_candidate_policy == kTcpCandidatePolicyDisabled) {
3371 portallocator_flags |= cricket::PORTALLOCATOR_DISABLE_TCP;
Mirko Bonadei675513b2017-11-09 11:09:25 +01003372 RTC_LOG(LS_INFO) << "TCP candidates are disabled.";
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003373 }
3374
honghaiz60347052016-05-31 18:29:12 -07003375 if (configuration.candidate_network_policy ==
3376 kCandidateNetworkPolicyLowCost) {
3377 portallocator_flags |= cricket::PORTALLOCATOR_DISABLE_COSTLY_NETWORKS;
Mirko Bonadei675513b2017-11-09 11:09:25 +01003378 RTC_LOG(LS_INFO) << "Do not gather candidates on high-cost networks";
honghaiz60347052016-05-31 18:29:12 -07003379 }
3380
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003381 port_allocator_->set_flags(portallocator_flags);
3382 // No step delay is used while allocating ports.
3383 port_allocator_->set_step_delay(cricket::kMinimumStepDelay);
3384 port_allocator_->set_candidate_filter(
3385 ConvertIceTransportTypeToCandidateFilter(configuration.type));
deadbeefd21eab32017-07-26 16:50:11 -07003386 port_allocator_->set_max_ipv6_networks(configuration.max_ipv6_networks);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003387
3388 // Call this last since it may create pooled allocator sessions using the
3389 // properties set above.
3390 port_allocator_->SetConfiguration(stun_servers, turn_servers,
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -07003391 configuration.ice_candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02003392 configuration.prune_turn_ports,
3393 configuration.turn_customizer);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003394 return true;
3395}
3396
deadbeef91dd5672016-05-18 16:55:30 -07003397bool PeerConnection::ReconfigurePortAllocator_n(
deadbeef293e9262017-01-11 12:28:30 -08003398 const cricket::ServerAddresses& stun_servers,
3399 const std::vector<cricket::RelayServerConfig>& turn_servers,
3400 IceTransportsType type,
3401 int candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02003402 bool prune_turn_ports,
3403 webrtc::TurnCustomizer* turn_customizer) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003404 port_allocator_->set_candidate_filter(
deadbeef293e9262017-01-11 12:28:30 -08003405 ConvertIceTransportTypeToCandidateFilter(type));
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003406 // Call this last since it may create pooled allocator sessions using the
3407 // candidate filter set above.
deadbeef6de92f92016-12-12 18:49:32 -08003408 return port_allocator_->SetConfiguration(
Jonas Orelandbdcee282017-10-10 14:01:40 +02003409 stun_servers, turn_servers, candidate_pool_size, prune_turn_ports,
3410 turn_customizer);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003411}
3412
Steve Antonba818672017-11-06 10:21:57 -08003413cricket::ChannelManager* PeerConnection::channel_manager() const {
3414 return factory_->channel_manager();
3415}
3416
3417MetricsObserverInterface* PeerConnection::metrics_observer() const {
3418 return uma_observer_;
3419}
3420
Elad Alon99c3fe52017-10-13 16:29:40 +02003421bool PeerConnection::StartRtcEventLog_w(
Bjorn Tereliusde939432017-11-20 17:38:14 +01003422 std::unique_ptr<RtcEventLogOutput> output,
3423 int64_t output_period_ms) {
zhihuang77985012017-02-07 15:45:16 -08003424 if (!event_log_) {
3425 return false;
3426 }
Bjorn Tereliusde939432017-11-20 17:38:14 +01003427 return event_log_->StartLogging(std::move(output), output_period_ms);
ivoc14d5dbe2016-07-04 07:06:55 -07003428}
3429
3430void PeerConnection::StopRtcEventLog_w() {
zhihuang77985012017-02-07 15:45:16 -08003431 if (event_log_) {
3432 event_log_->StopLogging();
3433 }
ivoc14d5dbe2016-07-04 07:06:55 -07003434}
nisseeaabdf62017-05-05 02:23:02 -07003435
Steve Anton75737c02017-11-06 10:37:17 -08003436cricket::BaseChannel* PeerConnection::GetChannel(
3437 const std::string& content_name) {
3438 if (voice_channel() && voice_channel()->content_name() == content_name) {
3439 return voice_channel();
3440 }
3441 if (video_channel() && video_channel()->content_name() == content_name) {
3442 return video_channel();
3443 }
3444 if (rtp_data_channel() &&
3445 rtp_data_channel()->content_name() == content_name) {
3446 return rtp_data_channel();
3447 }
3448 return nullptr;
3449}
3450
3451bool PeerConnection::GetSctpSslRole(rtc::SSLRole* role) {
3452 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003453 RTC_LOG(LS_INFO)
3454 << "Local and Remote descriptions must be applied to get the "
3455 << "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08003456 return false;
3457 }
3458 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003459 RTC_LOG(LS_INFO) << "Non-rejected SCTP m= section is needed to get the "
3460 << "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08003461 return false;
3462 }
3463
3464 return transport_controller_->GetSslRole(*sctp_transport_name_, role);
3465}
3466
3467bool PeerConnection::GetSslRole(const std::string& content_name,
3468 rtc::SSLRole* role) {
3469 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003470 RTC_LOG(LS_INFO)
3471 << "Local and Remote descriptions must be applied to get the "
3472 << "SSL Role of the session.";
Steve Anton75737c02017-11-06 10:37:17 -08003473 return false;
3474 }
3475
3476 return transport_controller_->GetSslRole(GetTransportName(content_name),
3477 role);
3478}
3479
Steve Anton75737c02017-11-06 10:37:17 -08003480// TODO(steveanton): Eventually it'd be nice to store the channels as a single
3481// vector of BaseChannel pointers instead of separate voice and video channel
3482// vectors. At that point, this will become a simple getter.
3483std::vector<cricket::BaseChannel*> PeerConnection::Channels() const {
3484 std::vector<cricket::BaseChannel*> channels;
Steve Anton4171afb2017-11-20 10:20:22 -08003485 if (voice_channel()) {
3486 channels.push_back(voice_channel());
3487 }
3488 if (video_channel()) {
3489 channels.push_back(video_channel());
3490 }
Steve Anton75737c02017-11-06 10:37:17 -08003491 if (rtp_data_channel_) {
3492 channels.push_back(rtp_data_channel_);
3493 }
3494 return channels;
3495}
3496
Steve Antonf8470812017-12-04 10:46:21 -08003497void PeerConnection::SetSessionError(SessionError error,
3498 const std::string& error_desc) {
3499 RTC_DCHECK_RUN_ON(signaling_thread());
3500 if (error != session_error_) {
3501 session_error_ = error;
3502 session_error_desc_ = error_desc;
Steve Anton75737c02017-11-06 10:37:17 -08003503 }
3504}
3505
Steve Anton3828c062017-12-06 10:34:51 -08003506RTCError PeerConnection::UpdateSessionState(SdpType type,
Steve Anton8a006912017-12-04 15:25:56 -08003507 cricket::ContentSource source) {
3508 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08003509
3510 // If there's already a pending error then no state transition should happen.
3511 // But all call-sites should be verifying this before calling us!
Steve Antonf8470812017-12-04 10:46:21 -08003512 RTC_DCHECK(session_error() == SessionError::kNone);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08003513
3514 // If this is an answer then we know whether to BUNDLE or not. If both the
3515 // local and remote side have agreed to BUNDLE, go ahead and enable it.
Steve Anton3828c062017-12-06 10:34:51 -08003516 if (type == SdpType::kAnswer) {
Steve Anton75737c02017-11-06 10:37:17 -08003517 const cricket::ContentGroup* local_bundle =
3518 local_description()->description()->GetGroupByName(
3519 cricket::GROUP_TYPE_BUNDLE);
3520 const cricket::ContentGroup* remote_bundle =
3521 remote_description()->description()->GetGroupByName(
3522 cricket::GROUP_TYPE_BUNDLE);
3523 if (local_bundle && remote_bundle) {
3524 // The answerer decides the transport to bundle on.
3525 const cricket::ContentGroup* answer_bundle =
3526 (source == cricket::CS_LOCAL ? local_bundle : remote_bundle);
3527 if (!EnableBundle(*answer_bundle)) {
Steve Anton8a006912017-12-04 15:25:56 -08003528 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3529 kEnableBundleFailed);
Steve Anton75737c02017-11-06 10:37:17 -08003530 }
3531 }
Steve Anton75737c02017-11-06 10:37:17 -08003532 }
Steve Anton6d6a2ae2017-12-04 17:19:47 -08003533
3534 // Only push down the transport description after potentially enabling BUNDLE;
3535 // we don't want to push down a description on a transport about to be
3536 // destroyed.
Steve Anton3828c062017-12-06 10:34:51 -08003537 RTCError error = PushdownTransportDescription(source, type);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08003538 if (!error.ok()) {
3539 return error;
3540 }
3541
3542 // If this is answer-ish we're ready to let media flow.
Steve Anton3828c062017-12-06 10:34:51 -08003543 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Antoned10bd92017-12-05 10:52:59 -08003544 EnableSending();
Steve Anton6d6a2ae2017-12-04 17:19:47 -08003545 }
3546
3547 // Update the signaling state according to the specified state machine (see
3548 // https://w3c.github.io/webrtc-pc/#rtcsignalingstate-enum).
Steve Anton3828c062017-12-06 10:34:51 -08003549 if (type == SdpType::kOffer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08003550 ChangeSignalingState(source == cricket::CS_LOCAL
3551 ? PeerConnectionInterface::kHaveLocalOffer
3552 : PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton3828c062017-12-06 10:34:51 -08003553 } else if (type == SdpType::kPrAnswer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08003554 ChangeSignalingState(source == cricket::CS_LOCAL
3555 ? PeerConnectionInterface::kHaveLocalPrAnswer
3556 : PeerConnectionInterface::kHaveRemotePrAnswer);
3557 } else {
Steve Anton3828c062017-12-06 10:34:51 -08003558 RTC_DCHECK(type == SdpType::kAnswer);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08003559 ChangeSignalingState(PeerConnectionInterface::kStable);
3560 }
3561
3562 // Update internal objects according to the session description's media
3563 // descriptions.
Steve Anton3828c062017-12-06 10:34:51 -08003564 error = PushdownMediaDescription(type, source);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08003565 if (!error.ok()) {
3566 SetSessionError(SessionError::kContent, error.message());
3567 }
3568 if (session_error() != SessionError::kNone) {
3569 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
3570 }
3571
Steve Anton8a006912017-12-04 15:25:56 -08003572 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08003573}
3574
Steve Anton8a006912017-12-04 15:25:56 -08003575RTCError PeerConnection::PushdownMediaDescription(
Steve Anton3828c062017-12-06 10:34:51 -08003576 SdpType type,
Steve Anton8a006912017-12-04 15:25:56 -08003577 cricket::ContentSource source) {
Steve Antoned10bd92017-12-05 10:52:59 -08003578 const SessionDescriptionInterface* sdesc =
3579 (source == cricket::CS_LOCAL ? local_description()
3580 : remote_description());
Steve Anton75737c02017-11-06 10:37:17 -08003581 RTC_DCHECK(sdesc);
Steve Antoned10bd92017-12-05 10:52:59 -08003582
3583 // Push down the new SDP media section for each audio/video transceiver.
3584 for (auto transceiver : transceivers_) {
Steve Anton75737c02017-11-06 10:37:17 -08003585 const ContentInfo* content_info =
Steve Antoned10bd92017-12-05 10:52:59 -08003586 FindMediaSectionForTransceiver(transceiver, sdesc);
3587 cricket::BaseChannel* channel = transceiver->internal()->channel();
3588 if (!channel || !content_info || content_info->rejected) {
Steve Anton75737c02017-11-06 10:37:17 -08003589 continue;
3590 }
3591 const MediaContentDescription* content_desc =
3592 static_cast<const MediaContentDescription*>(content_info->description);
Steve Antoned10bd92017-12-05 10:52:59 -08003593 if (!content_desc) {
3594 continue;
3595 }
3596 std::string error;
3597 bool success =
3598 (source == cricket::CS_LOCAL)
Steve Anton3828c062017-12-06 10:34:51 -08003599 ? channel->SetLocalContent(content_desc, type, &error)
3600 : channel->SetRemoteContent(content_desc, type, &error);
Steve Antoned10bd92017-12-05 10:52:59 -08003601 if (!success) {
3602 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, std::move(error));
3603 }
3604 }
3605
3606 // If using the RtpDataChannel, push down the new SDP section for it too.
3607 if (rtp_data_channel_) {
3608 const ContentInfo* data_content =
3609 cricket::GetFirstDataContent(sdesc->description());
3610 if (data_content && !data_content->rejected) {
3611 const MediaContentDescription* data_desc =
3612 static_cast<const MediaContentDescription*>(
3613 data_content->description);
3614 if (data_desc) {
3615 std::string error;
3616 bool success =
3617 (source == cricket::CS_LOCAL)
Steve Anton3828c062017-12-06 10:34:51 -08003618 ? rtp_data_channel_->SetLocalContent(data_desc, type, &error)
3619 : rtp_data_channel_->SetRemoteContent(data_desc, type,
Steve Antoned10bd92017-12-05 10:52:59 -08003620 &error);
3621 if (!success) {
3622 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3623 std::move(error));
3624 }
Steve Anton75737c02017-11-06 10:37:17 -08003625 }
3626 }
3627 }
Steve Antoned10bd92017-12-05 10:52:59 -08003628
Steve Anton75737c02017-11-06 10:37:17 -08003629 // Need complete offer/answer with an SCTP m= section before starting SCTP,
3630 // according to https://tools.ietf.org/html/draft-ietf-mmusic-sctp-sdp-19
3631 if (sctp_transport_ && local_description() && remote_description() &&
3632 cricket::GetFirstDataContent(local_description()->description()) &&
3633 cricket::GetFirstDataContent(remote_description()->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08003634 bool success = network_thread()->Invoke<bool>(
Steve Anton75737c02017-11-06 10:37:17 -08003635 RTC_FROM_HERE,
3636 rtc::Bind(&PeerConnection::PushdownSctpParameters_n, this, source));
Steve Anton8a006912017-12-04 15:25:56 -08003637 if (!success) {
3638 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
3639 "Failed to push down SCTP parameters.");
3640 }
Steve Anton75737c02017-11-06 10:37:17 -08003641 }
Steve Antoned10bd92017-12-05 10:52:59 -08003642
Steve Anton8a006912017-12-04 15:25:56 -08003643 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08003644}
3645
3646bool PeerConnection::PushdownSctpParameters_n(cricket::ContentSource source) {
3647 RTC_DCHECK(network_thread()->IsCurrent());
3648 RTC_DCHECK(local_description());
3649 RTC_DCHECK(remote_description());
3650 // Apply the SCTP port (which is hidden inside a DataCodec structure...)
3651 // When we support "max-message-size", that would also be pushed down here.
3652 return sctp_transport_->Start(
3653 GetSctpPort(local_description()->description()),
3654 GetSctpPort(remote_description()->description()));
3655}
3656
Steve Anton8a006912017-12-04 15:25:56 -08003657RTCError PeerConnection::PushdownTransportDescription(
3658 cricket::ContentSource source,
Steve Anton3828c062017-12-06 10:34:51 -08003659 SdpType type) {
Steve Anton8a006912017-12-04 15:25:56 -08003660 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08003661
Steve Anton8a006912017-12-04 15:25:56 -08003662 const SessionDescriptionInterface* sdesc =
3663 (source == cricket::CS_LOCAL ? local_description()
3664 : remote_description());
3665 RTC_DCHECK(sdesc);
3666 for (const cricket::TransportInfo& tinfo :
3667 sdesc->description()->transport_infos()) {
3668 std::string error;
3669 bool success;
3670 if (source == cricket::CS_LOCAL) {
3671 success = transport_controller_->SetLocalTransportDescription(
Steve Anton3828c062017-12-06 10:34:51 -08003672 tinfo.content_name, tinfo.description, type, &error);
Steve Anton8a006912017-12-04 15:25:56 -08003673 } else {
3674 success = transport_controller_->SetRemoteTransportDescription(
Steve Anton3828c062017-12-06 10:34:51 -08003675 tinfo.content_name, tinfo.description, type, &error);
Steve Anton8a006912017-12-04 15:25:56 -08003676 }
3677 if (!success) {
3678 LOG_AND_RETURN_ERROR(
3679 RTCErrorType::INVALID_PARAMETER,
3680 "Failed to push down transport description: " + error);
Steve Anton75737c02017-11-06 10:37:17 -08003681 }
3682 }
3683
Steve Anton8a006912017-12-04 15:25:56 -08003684 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08003685}
3686
3687bool PeerConnection::GetTransportDescription(
3688 const SessionDescription* description,
3689 const std::string& content_name,
3690 cricket::TransportDescription* tdesc) {
3691 if (!description || !tdesc) {
3692 return false;
3693 }
3694 const TransportInfo* transport_info =
3695 description->GetTransportInfoByName(content_name);
3696 if (!transport_info) {
3697 return false;
3698 }
3699 *tdesc = transport_info->description;
3700 return true;
3701}
3702
3703bool PeerConnection::EnableBundle(const cricket::ContentGroup& bundle) {
3704 const std::string* first_content_name = bundle.FirstContentName();
3705 if (!first_content_name) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003706 RTC_LOG(LS_WARNING) << "Tried to BUNDLE with no contents.";
Steve Anton75737c02017-11-06 10:37:17 -08003707 return false;
3708 }
3709 const std::string& transport_name = *first_content_name;
3710
3711 auto maybe_set_transport = [this, bundle,
3712 transport_name](cricket::BaseChannel* ch) {
3713 if (!ch || !bundle.HasContentName(ch->content_name())) {
Steve Antoned10bd92017-12-05 10:52:59 -08003714 return;
Steve Anton75737c02017-11-06 10:37:17 -08003715 }
3716
3717 std::string old_transport_name = ch->transport_name();
3718 if (old_transport_name == transport_name) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003719 RTC_LOG(LS_INFO) << "BUNDLE already enabled for " << ch->content_name()
3720 << " on " << transport_name << ".";
Steve Antoned10bd92017-12-05 10:52:59 -08003721 return;
Steve Anton75737c02017-11-06 10:37:17 -08003722 }
3723
3724 cricket::DtlsTransportInternal* rtp_dtls_transport =
3725 transport_controller_->CreateDtlsTransport(
3726 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
3727 bool need_rtcp = (ch->rtcp_dtls_transport() != nullptr);
3728 cricket::DtlsTransportInternal* rtcp_dtls_transport = nullptr;
3729 if (need_rtcp) {
3730 rtcp_dtls_transport = transport_controller_->CreateDtlsTransport(
3731 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
3732 }
3733
3734 ch->SetTransports(rtp_dtls_transport, rtcp_dtls_transport);
Mirko Bonadei675513b2017-11-09 11:09:25 +01003735 RTC_LOG(LS_INFO) << "Enabled BUNDLE for " << ch->content_name() << " on "
3736 << transport_name << ".";
Steve Anton75737c02017-11-06 10:37:17 -08003737 transport_controller_->DestroyDtlsTransport(
3738 old_transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
3739 // If the channel needs rtcp, it means that the channel used to have a
3740 // rtcp transport which needs to be deleted now.
3741 if (need_rtcp) {
3742 transport_controller_->DestroyDtlsTransport(
3743 old_transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
3744 }
Steve Anton75737c02017-11-06 10:37:17 -08003745 };
3746
Steve Antoned10bd92017-12-05 10:52:59 -08003747 for (auto transceiver : transceivers_) {
3748 maybe_set_transport(transceiver->internal()->channel());
Steve Anton75737c02017-11-06 10:37:17 -08003749 }
Steve Antoned10bd92017-12-05 10:52:59 -08003750 maybe_set_transport(rtp_data_channel_);
3751
Steve Anton75737c02017-11-06 10:37:17 -08003752 // For SCTP, transport creation/deletion happens here instead of in the
3753 // object itself.
3754 if (sctp_transport_) {
3755 RTC_DCHECK(sctp_transport_name_);
3756 RTC_DCHECK(sctp_content_name_);
3757 if (transport_name != *sctp_transport_name_ &&
3758 bundle.HasContentName(*sctp_content_name_)) {
3759 network_thread()->Invoke<void>(
3760 RTC_FROM_HERE, rtc::Bind(&PeerConnection::ChangeSctpTransport_n, this,
3761 transport_name));
3762 }
3763 }
3764
3765 return true;
3766}
3767
Steve Anton75737c02017-11-06 10:37:17 -08003768cricket::IceConfig PeerConnection::ParseIceConfig(
3769 const PeerConnectionInterface::RTCConfiguration& config) const {
3770 cricket::ContinualGatheringPolicy gathering_policy;
3771 // TODO(honghaiz): Add the third continual gathering policy in
3772 // PeerConnectionInterface and map it to GATHER_CONTINUALLY_AND_RECOVER.
3773 switch (config.continual_gathering_policy) {
3774 case PeerConnectionInterface::GATHER_ONCE:
3775 gathering_policy = cricket::GATHER_ONCE;
3776 break;
3777 case PeerConnectionInterface::GATHER_CONTINUALLY:
3778 gathering_policy = cricket::GATHER_CONTINUALLY;
3779 break;
3780 default:
3781 RTC_NOTREACHED();
3782 gathering_policy = cricket::GATHER_ONCE;
3783 }
3784 cricket::IceConfig ice_config;
3785 ice_config.receiving_timeout = config.ice_connection_receiving_timeout;
3786 ice_config.prioritize_most_likely_candidate_pairs =
3787 config.prioritize_most_likely_ice_candidate_pairs;
3788 ice_config.backup_connection_ping_interval =
3789 config.ice_backup_candidate_pair_ping_interval;
3790 ice_config.continual_gathering_policy = gathering_policy;
3791 ice_config.presume_writable_when_fully_relayed =
3792 config.presume_writable_when_fully_relayed;
3793 ice_config.ice_check_min_interval = config.ice_check_min_interval;
3794 ice_config.regather_all_networks_interval_range =
3795 config.ice_regather_interval_range;
3796 return ice_config;
3797}
3798
Steve Anton75737c02017-11-06 10:37:17 -08003799bool PeerConnection::GetLocalTrackIdBySsrc(uint32_t ssrc,
3800 std::string* track_id) {
3801 if (!local_description()) {
3802 return false;
3803 }
3804 return webrtc::GetTrackIdBySsrc(local_description()->description(), ssrc,
3805 track_id);
3806}
3807
3808bool PeerConnection::GetRemoteTrackIdBySsrc(uint32_t ssrc,
3809 std::string* track_id) {
3810 if (!remote_description()) {
3811 return false;
3812 }
3813 return webrtc::GetTrackIdBySsrc(remote_description()->description(), ssrc,
3814 track_id);
3815}
3816
3817bool PeerConnection::SendData(const cricket::SendDataParams& params,
3818 const rtc::CopyOnWriteBuffer& payload,
3819 cricket::SendDataResult* result) {
3820 if (!rtp_data_channel_ && !sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003821 RTC_LOG(LS_ERROR) << "SendData called when rtp_data_channel_ "
3822 << "and sctp_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08003823 return false;
3824 }
3825 return rtp_data_channel_
3826 ? rtp_data_channel_->SendData(params, payload, result)
3827 : network_thread()->Invoke<bool>(
3828 RTC_FROM_HERE,
3829 Bind(&cricket::SctpTransportInternal::SendData,
3830 sctp_transport_.get(), params, payload, result));
3831}
3832
3833bool PeerConnection::ConnectDataChannel(DataChannel* webrtc_data_channel) {
3834 if (!rtp_data_channel_ && !sctp_transport_) {
3835 // Don't log an error here, because DataChannels are expected to call
3836 // ConnectDataChannel in this state. It's the only way to initially tell
3837 // whether or not the underlying transport is ready.
3838 return false;
3839 }
3840 if (rtp_data_channel_) {
3841 rtp_data_channel_->SignalReadyToSendData.connect(
3842 webrtc_data_channel, &DataChannel::OnChannelReady);
3843 rtp_data_channel_->SignalDataReceived.connect(webrtc_data_channel,
3844 &DataChannel::OnDataReceived);
3845 } else {
3846 SignalSctpReadyToSendData.connect(webrtc_data_channel,
3847 &DataChannel::OnChannelReady);
3848 SignalSctpDataReceived.connect(webrtc_data_channel,
3849 &DataChannel::OnDataReceived);
3850 SignalSctpStreamClosedRemotely.connect(
3851 webrtc_data_channel, &DataChannel::OnStreamClosedRemotely);
3852 }
3853 return true;
3854}
3855
3856void PeerConnection::DisconnectDataChannel(DataChannel* webrtc_data_channel) {
3857 if (!rtp_data_channel_ && !sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003858 RTC_LOG(LS_ERROR)
3859 << "DisconnectDataChannel called when rtp_data_channel_ and "
3860 "sctp_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08003861 return;
3862 }
3863 if (rtp_data_channel_) {
3864 rtp_data_channel_->SignalReadyToSendData.disconnect(webrtc_data_channel);
3865 rtp_data_channel_->SignalDataReceived.disconnect(webrtc_data_channel);
3866 } else {
3867 SignalSctpReadyToSendData.disconnect(webrtc_data_channel);
3868 SignalSctpDataReceived.disconnect(webrtc_data_channel);
3869 SignalSctpStreamClosedRemotely.disconnect(webrtc_data_channel);
3870 }
3871}
3872
3873void PeerConnection::AddSctpDataStream(int sid) {
3874 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003875 RTC_LOG(LS_ERROR)
3876 << "AddSctpDataStream called when sctp_transport_ is NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08003877 return;
3878 }
3879 network_thread()->Invoke<void>(
3880 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::OpenStream,
3881 sctp_transport_.get(), sid));
3882}
3883
3884void PeerConnection::RemoveSctpDataStream(int sid) {
3885 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003886 RTC_LOG(LS_ERROR) << "RemoveSctpDataStream called when sctp_transport_ is "
3887 << "NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08003888 return;
3889 }
3890 network_thread()->Invoke<void>(
3891 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::ResetStream,
3892 sctp_transport_.get(), sid));
3893}
3894
3895bool PeerConnection::ReadyToSendData() const {
3896 return (rtp_data_channel_ && rtp_data_channel_->ready_to_send_data()) ||
3897 sctp_ready_to_send_data_;
3898}
3899
3900std::unique_ptr<SessionStats> PeerConnection::GetSessionStats_s() {
3901 RTC_DCHECK(signaling_thread()->IsCurrent());
3902 ChannelNamePairs channel_name_pairs;
3903 if (voice_channel()) {
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003904 channel_name_pairs.voice = ChannelNamePair(
3905 voice_channel()->content_name(), voice_channel()->transport_name());
Steve Anton75737c02017-11-06 10:37:17 -08003906 }
3907 if (video_channel()) {
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003908 channel_name_pairs.video = ChannelNamePair(
3909 video_channel()->content_name(), video_channel()->transport_name());
Steve Anton75737c02017-11-06 10:37:17 -08003910 }
3911 if (rtp_data_channel()) {
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003912 channel_name_pairs.data =
Steve Anton75737c02017-11-06 10:37:17 -08003913 ChannelNamePair(rtp_data_channel()->content_name(),
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003914 rtp_data_channel()->transport_name());
Steve Anton75737c02017-11-06 10:37:17 -08003915 }
3916 if (sctp_transport_) {
3917 RTC_DCHECK(sctp_content_name_);
3918 RTC_DCHECK(sctp_transport_name_);
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003919 channel_name_pairs.data =
3920 ChannelNamePair(*sctp_content_name_, *sctp_transport_name_);
Steve Anton75737c02017-11-06 10:37:17 -08003921 }
3922 return GetSessionStats(channel_name_pairs);
3923}
3924
3925std::unique_ptr<SessionStats> PeerConnection::GetSessionStats(
3926 const ChannelNamePairs& channel_name_pairs) {
3927 if (network_thread()->IsCurrent()) {
3928 return GetSessionStats_n(channel_name_pairs);
3929 }
3930 return network_thread()->Invoke<std::unique_ptr<SessionStats>>(
3931 RTC_FROM_HERE,
3932 rtc::Bind(&PeerConnection::GetSessionStats_n, this, channel_name_pairs));
3933}
3934
3935bool PeerConnection::GetLocalCertificate(
3936 const std::string& transport_name,
3937 rtc::scoped_refptr<rtc::RTCCertificate>* certificate) {
3938 return transport_controller_->GetLocalCertificate(transport_name,
3939 certificate);
3940}
3941
3942std::unique_ptr<rtc::SSLCertificate> PeerConnection::GetRemoteSSLCertificate(
3943 const std::string& transport_name) {
3944 return transport_controller_->GetRemoteSSLCertificate(transport_name);
3945}
3946
3947cricket::DataChannelType PeerConnection::data_channel_type() const {
3948 return data_channel_type_;
3949}
3950
3951bool PeerConnection::IceRestartPending(const std::string& content_name) const {
3952 return pending_ice_restarts_.find(content_name) !=
3953 pending_ice_restarts_.end();
3954}
3955
Steve Anton75737c02017-11-06 10:37:17 -08003956bool PeerConnection::NeedsIceRestart(const std::string& content_name) const {
3957 return transport_controller_->NeedsIceRestart(content_name);
3958}
3959
3960void PeerConnection::OnCertificateReady(
3961 const rtc::scoped_refptr<rtc::RTCCertificate>& certificate) {
3962 transport_controller_->SetLocalCertificate(certificate);
3963}
3964
3965void PeerConnection::OnDtlsSrtpSetupFailure(cricket::BaseChannel*, bool rtcp) {
Steve Antonf8470812017-12-04 10:46:21 -08003966 SetSessionError(SessionError::kTransport,
3967 rtcp ? kDtlsSrtpSetupFailureRtcp : kDtlsSrtpSetupFailureRtp);
Steve Anton75737c02017-11-06 10:37:17 -08003968}
3969
3970void PeerConnection::OnTransportControllerConnectionState(
3971 cricket::IceConnectionState state) {
3972 switch (state) {
3973 case cricket::kIceConnectionConnecting:
3974 // If the current state is Connected or Completed, then there were
3975 // writable channels but now there are not, so the next state must
3976 // be Disconnected.
3977 // kIceConnectionConnecting is currently used as the default,
3978 // un-connected state by the TransportController, so its only use is
3979 // detecting disconnections.
3980 if (ice_connection_state_ ==
3981 PeerConnectionInterface::kIceConnectionConnected ||
3982 ice_connection_state_ ==
3983 PeerConnectionInterface::kIceConnectionCompleted) {
3984 SetIceConnectionState(
3985 PeerConnectionInterface::kIceConnectionDisconnected);
3986 }
3987 break;
3988 case cricket::kIceConnectionFailed:
3989 SetIceConnectionState(PeerConnectionInterface::kIceConnectionFailed);
3990 break;
3991 case cricket::kIceConnectionConnected:
Mirko Bonadei675513b2017-11-09 11:09:25 +01003992 RTC_LOG(LS_INFO) << "Changing to ICE connected state because "
3993 << "all transports are writable.";
Steve Anton75737c02017-11-06 10:37:17 -08003994 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
3995 break;
3996 case cricket::kIceConnectionCompleted:
Mirko Bonadei675513b2017-11-09 11:09:25 +01003997 RTC_LOG(LS_INFO) << "Changing to ICE completed state because "
3998 << "all transports are complete.";
Steve Anton75737c02017-11-06 10:37:17 -08003999 if (ice_connection_state_ !=
4000 PeerConnectionInterface::kIceConnectionConnected) {
4001 // If jumping directly from "checking" to "connected",
4002 // signal "connected" first.
4003 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
4004 }
4005 SetIceConnectionState(PeerConnectionInterface::kIceConnectionCompleted);
4006 if (metrics_observer()) {
4007 ReportTransportStats();
4008 }
4009 break;
4010 default:
4011 RTC_NOTREACHED();
4012 }
4013}
4014
4015void PeerConnection::OnTransportControllerCandidatesGathered(
4016 const std::string& transport_name,
4017 const cricket::Candidates& candidates) {
4018 RTC_DCHECK(signaling_thread()->IsCurrent());
4019 int sdp_mline_index;
4020 if (!GetLocalCandidateMediaIndex(transport_name, &sdp_mline_index)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004021 RTC_LOG(LS_ERROR)
4022 << "OnTransportControllerCandidatesGathered: content name "
4023 << transport_name << " not found";
Steve Anton75737c02017-11-06 10:37:17 -08004024 return;
4025 }
4026
4027 for (cricket::Candidates::const_iterator citer = candidates.begin();
4028 citer != candidates.end(); ++citer) {
4029 // Use transport_name as the candidate media id.
4030 std::unique_ptr<JsepIceCandidate> candidate(
4031 new JsepIceCandidate(transport_name, sdp_mline_index, *citer));
4032 if (local_description()) {
4033 mutable_local_description()->AddCandidate(candidate.get());
4034 }
4035 OnIceCandidate(std::move(candidate));
4036 }
4037}
4038
4039void PeerConnection::OnTransportControllerCandidatesRemoved(
4040 const std::vector<cricket::Candidate>& candidates) {
4041 RTC_DCHECK(signaling_thread()->IsCurrent());
4042 // Sanity check.
4043 for (const cricket::Candidate& candidate : candidates) {
4044 if (candidate.transport_name().empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004045 RTC_LOG(LS_ERROR) << "OnTransportControllerCandidatesRemoved: "
4046 << "empty content name in candidate "
4047 << candidate.ToString();
Steve Anton75737c02017-11-06 10:37:17 -08004048 return;
4049 }
4050 }
4051
4052 if (local_description()) {
4053 mutable_local_description()->RemoveCandidates(candidates);
4054 }
4055 OnIceCandidatesRemoved(candidates);
4056}
4057
4058void PeerConnection::OnTransportControllerDtlsHandshakeError(
4059 rtc::SSLHandshakeError error) {
4060 if (metrics_observer()) {
4061 metrics_observer()->IncrementEnumCounter(
4062 webrtc::kEnumCounterDtlsHandshakeError, static_cast<int>(error),
4063 static_cast<int>(rtc::SSLHandshakeError::MAX_VALUE));
4064 }
4065}
4066
Steve Antoned10bd92017-12-05 10:52:59 -08004067void PeerConnection::EnableSending() {
4068 for (auto transceiver : transceivers_) {
4069 cricket::BaseChannel* channel = transceiver->internal()->channel();
4070 if (channel && !channel->enabled()) {
4071 channel->Enable(true);
4072 }
Steve Anton75737c02017-11-06 10:37:17 -08004073 }
4074
Steve Anton4171afb2017-11-20 10:20:22 -08004075 if (rtp_data_channel_ && !rtp_data_channel_->enabled()) {
Steve Anton75737c02017-11-06 10:37:17 -08004076 rtp_data_channel_->Enable(true);
Steve Anton4171afb2017-11-20 10:20:22 -08004077 }
Steve Anton75737c02017-11-06 10:37:17 -08004078}
4079
4080// Returns the media index for a local ice candidate given the content name.
4081bool PeerConnection::GetLocalCandidateMediaIndex(
4082 const std::string& content_name,
4083 int* sdp_mline_index) {
4084 if (!local_description() || !sdp_mline_index) {
4085 return false;
4086 }
4087
4088 bool content_found = false;
4089 const ContentInfos& contents = local_description()->description()->contents();
4090 for (size_t index = 0; index < contents.size(); ++index) {
4091 if (contents[index].name == content_name) {
4092 *sdp_mline_index = static_cast<int>(index);
4093 content_found = true;
4094 break;
4095 }
4096 }
4097 return content_found;
4098}
4099
4100bool PeerConnection::UseCandidatesInSessionDescription(
4101 const SessionDescriptionInterface* remote_desc) {
4102 if (!remote_desc) {
4103 return true;
4104 }
4105 bool ret = true;
4106
4107 for (size_t m = 0; m < remote_desc->number_of_mediasections(); ++m) {
4108 const IceCandidateCollection* candidates = remote_desc->candidates(m);
4109 for (size_t n = 0; n < candidates->count(); ++n) {
4110 const IceCandidateInterface* candidate = candidates->at(n);
4111 bool valid = false;
4112 if (!ReadyToUseRemoteCandidate(candidate, remote_desc, &valid)) {
4113 if (valid) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004114 RTC_LOG(LS_INFO)
4115 << "UseCandidatesInSessionDescription: Not ready to use "
4116 << "candidate.";
Steve Anton75737c02017-11-06 10:37:17 -08004117 }
4118 continue;
4119 }
4120 ret = UseCandidate(candidate);
4121 if (!ret) {
4122 break;
4123 }
4124 }
4125 }
4126 return ret;
4127}
4128
4129bool PeerConnection::UseCandidate(const IceCandidateInterface* candidate) {
4130 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
4131 size_t remote_content_size =
4132 remote_description()->description()->contents().size();
4133 if (mediacontent_index >= remote_content_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004134 RTC_LOG(LS_ERROR) << "UseCandidate: Invalid candidate media index.";
Steve Anton75737c02017-11-06 10:37:17 -08004135 return false;
4136 }
4137
4138 cricket::ContentInfo content =
4139 remote_description()->description()->contents()[mediacontent_index];
4140 std::vector<cricket::Candidate> candidates;
4141 candidates.push_back(candidate->candidate());
4142 // Invoking BaseSession method to handle remote candidates.
4143 std::string error;
4144 if (transport_controller_->AddRemoteCandidates(content.name, candidates,
4145 &error)) {
4146 // Candidates successfully submitted for checking.
4147 if (ice_connection_state_ == PeerConnectionInterface::kIceConnectionNew ||
4148 ice_connection_state_ ==
4149 PeerConnectionInterface::kIceConnectionDisconnected) {
4150 // If state is New, then the session has just gotten its first remote ICE
4151 // candidates, so go to Checking.
4152 // If state is Disconnected, the session is re-using old candidates or
4153 // receiving additional ones, so go to Checking.
4154 // If state is Connected, stay Connected.
4155 // TODO(bemasc): If state is Connected, and the new candidates are for a
4156 // newly added transport, then the state actually _should_ move to
4157 // checking. Add a way to distinguish that case.
4158 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
4159 }
4160 // TODO(bemasc): If state is Completed, go back to Connected.
4161 } else {
4162 if (!error.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004163 RTC_LOG(LS_WARNING) << error;
Steve Anton75737c02017-11-06 10:37:17 -08004164 }
4165 }
4166 return true;
4167}
4168
4169void PeerConnection::RemoveUnusedChannels(const SessionDescription* desc) {
Steve Anton75737c02017-11-06 10:37:17 -08004170 // Destroy video channel first since it may have a pointer to the
4171 // voice channel.
4172 const cricket::ContentInfo* video_info = cricket::GetFirstVideoContent(desc);
Steve Anton6fec8802017-12-04 10:37:29 -08004173 if (!video_info || video_info->rejected) {
4174 DestroyTransceiverChannel(GetVideoTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08004175 }
4176
Steve Anton6fec8802017-12-04 10:37:29 -08004177 const cricket::ContentInfo* audio_info = cricket::GetFirstAudioContent(desc);
4178 if (!audio_info || audio_info->rejected) {
4179 DestroyTransceiverChannel(GetAudioTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08004180 }
4181
4182 const cricket::ContentInfo* data_info = cricket::GetFirstDataContent(desc);
4183 if (!data_info || data_info->rejected) {
Steve Anton6fec8802017-12-04 10:37:29 -08004184 DestroyDataChannel();
Steve Anton75737c02017-11-06 10:37:17 -08004185 }
4186}
4187
Steve Antoneda6ccd2017-12-04 10:21:55 -08004188std::string PeerConnection::GetTransportNameForMediaSection(
4189 const std::string& mid,
4190 const cricket::ContentGroup* bundle_group) const {
4191 if (!bundle_group) {
4192 return mid;
Steve Anton75737c02017-11-06 10:37:17 -08004193 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08004194 const std::string* first_content_name = bundle_group->FirstContentName();
Steve Anton75737c02017-11-06 10:37:17 -08004195 if (!first_content_name) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004196 RTC_LOG(LS_WARNING) << "Tried to BUNDLE with no contents.";
Steve Antoneda6ccd2017-12-04 10:21:55 -08004197 return mid;
Steve Anton75737c02017-11-06 10:37:17 -08004198 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08004199 if (!bundle_group->HasContentName(mid)) {
4200 RTC_LOG(LS_WARNING) << mid << " is not part of any bundle group";
4201 return mid;
Steve Anton75737c02017-11-06 10:37:17 -08004202 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08004203 RTC_LOG(LS_INFO) << "Bundling " << mid << " on " << *first_content_name;
4204 return *first_content_name;
Steve Anton75737c02017-11-06 10:37:17 -08004205}
4206
Steve Anton8a006912017-12-04 15:25:56 -08004207RTCError PeerConnection::CreateChannels(const SessionDescription* desc) {
Steve Antoneda6ccd2017-12-04 10:21:55 -08004208 RTC_DCHECK(desc);
4209
Steve Anton75737c02017-11-06 10:37:17 -08004210 const cricket::ContentGroup* bundle_group = nullptr;
4211 if (configuration_.bundle_policy ==
4212 PeerConnectionInterface::kBundlePolicyMaxBundle) {
4213 bundle_group = desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
4214 if (!bundle_group) {
Steve Anton8a006912017-12-04 15:25:56 -08004215 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
4216 "max-bundle configured but session description "
4217 "has no BUNDLE group");
Steve Anton75737c02017-11-06 10:37:17 -08004218 }
4219 }
4220
Steve Antoneda6ccd2017-12-04 10:21:55 -08004221 // Creating the media channels and transport proxies.
4222 const cricket::ContentInfo* voice = cricket::GetFirstAudioContent(desc);
4223 if (voice && !voice->rejected &&
4224 !GetAudioTransceiver()->internal()->channel()) {
4225 cricket::VoiceChannel* voice_channel = CreateVoiceChannel(
4226 voice->name,
4227 GetTransportNameForMediaSection(voice->name, bundle_group));
4228 if (!voice_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08004229 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
4230 "Failed to create voice channel.");
Steve Antoneda6ccd2017-12-04 10:21:55 -08004231 }
4232 GetAudioTransceiver()->internal()->SetChannel(voice_channel);
4233 }
4234
Steve Anton75737c02017-11-06 10:37:17 -08004235 const cricket::ContentInfo* video = cricket::GetFirstVideoContent(desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08004236 if (video && !video->rejected &&
4237 !GetVideoTransceiver()->internal()->channel()) {
4238 cricket::VideoChannel* video_channel = CreateVideoChannel(
4239 video->name,
4240 GetTransportNameForMediaSection(video->name, bundle_group));
4241 if (!video_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08004242 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
4243 "Failed to create video channel.");
Steve Anton75737c02017-11-06 10:37:17 -08004244 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08004245 GetVideoTransceiver()->internal()->SetChannel(video_channel);
Steve Anton75737c02017-11-06 10:37:17 -08004246 }
4247
4248 const cricket::ContentInfo* data = cricket::GetFirstDataContent(desc);
4249 if (data_channel_type_ != cricket::DCT_NONE && data && !data->rejected &&
4250 !rtp_data_channel_ && !sctp_transport_) {
Steve Antoneda6ccd2017-12-04 10:21:55 -08004251 if (!CreateDataChannel(data->name, GetTransportNameForMediaSection(
4252 data->name, bundle_group))) {
Steve Anton8a006912017-12-04 15:25:56 -08004253 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
4254 "Failed to create data channel.");
Steve Anton75737c02017-11-06 10:37:17 -08004255 }
4256 }
4257
Steve Anton8a006912017-12-04 15:25:56 -08004258 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08004259}
4260
Steve Anton4171afb2017-11-20 10:20:22 -08004261// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08004262cricket::VoiceChannel* PeerConnection::CreateVoiceChannel(
4263 const std::string& mid,
4264 const std::string& transport_name) {
Steve Anton75737c02017-11-06 10:37:17 -08004265 cricket::DtlsTransportInternal* rtp_dtls_transport =
4266 transport_controller_->CreateDtlsTransport(
4267 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4268 cricket::DtlsTransportInternal* rtcp_dtls_transport = nullptr;
4269 if (configuration_.rtcp_mux_policy !=
4270 PeerConnectionInterface::kRtcpMuxPolicyRequire) {
4271 rtcp_dtls_transport = transport_controller_->CreateDtlsTransport(
4272 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
4273 }
4274
4275 cricket::VoiceChannel* voice_channel = channel_manager()->CreateVoiceChannel(
4276 call_.get(), configuration_.media_config, rtp_dtls_transport,
Steve Antoneda6ccd2017-12-04 10:21:55 -08004277 rtcp_dtls_transport, signaling_thread(), mid, SrtpRequired(),
4278 audio_options_);
Steve Anton75737c02017-11-06 10:37:17 -08004279 if (!voice_channel) {
4280 transport_controller_->DestroyDtlsTransport(
4281 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4282 if (rtcp_dtls_transport) {
4283 transport_controller_->DestroyDtlsTransport(
4284 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
4285 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08004286 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08004287 }
Steve Anton75737c02017-11-06 10:37:17 -08004288 voice_channel->SignalRtcpMuxFullyActive.connect(
4289 this, &PeerConnection::DestroyRtcpTransport_n);
4290 voice_channel->SignalDtlsSrtpSetupFailure.connect(
4291 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08004292 voice_channel->SignalSentPacket.connect(this,
4293 &PeerConnection::OnSentPacket_w);
Steve Anton4171afb2017-11-20 10:20:22 -08004294
Steve Antoneda6ccd2017-12-04 10:21:55 -08004295 return voice_channel;
Steve Anton75737c02017-11-06 10:37:17 -08004296}
4297
Steve Anton4171afb2017-11-20 10:20:22 -08004298// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08004299cricket::VideoChannel* PeerConnection::CreateVideoChannel(
4300 const std::string& mid,
4301 const std::string& transport_name) {
Steve Anton75737c02017-11-06 10:37:17 -08004302 cricket::DtlsTransportInternal* rtp_dtls_transport =
4303 transport_controller_->CreateDtlsTransport(
4304 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4305 cricket::DtlsTransportInternal* rtcp_dtls_transport = nullptr;
4306 if (configuration_.rtcp_mux_policy !=
4307 PeerConnectionInterface::kRtcpMuxPolicyRequire) {
4308 rtcp_dtls_transport = transport_controller_->CreateDtlsTransport(
4309 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
4310 }
4311
4312 cricket::VideoChannel* video_channel = channel_manager()->CreateVideoChannel(
4313 call_.get(), configuration_.media_config, rtp_dtls_transport,
Steve Antoneda6ccd2017-12-04 10:21:55 -08004314 rtcp_dtls_transport, signaling_thread(), mid, SrtpRequired(),
4315 video_options_);
Steve Anton75737c02017-11-06 10:37:17 -08004316
4317 if (!video_channel) {
4318 transport_controller_->DestroyDtlsTransport(
4319 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4320 if (rtcp_dtls_transport) {
4321 transport_controller_->DestroyDtlsTransport(
4322 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
4323 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08004324 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08004325 }
Steve Anton75737c02017-11-06 10:37:17 -08004326 video_channel->SignalRtcpMuxFullyActive.connect(
4327 this, &PeerConnection::DestroyRtcpTransport_n);
4328 video_channel->SignalDtlsSrtpSetupFailure.connect(
4329 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08004330 video_channel->SignalSentPacket.connect(this,
4331 &PeerConnection::OnSentPacket_w);
Steve Anton4171afb2017-11-20 10:20:22 -08004332
Steve Antoneda6ccd2017-12-04 10:21:55 -08004333 return video_channel;
Steve Anton75737c02017-11-06 10:37:17 -08004334}
4335
Steve Antoneda6ccd2017-12-04 10:21:55 -08004336bool PeerConnection::CreateDataChannel(const std::string& mid,
4337 const std::string& transport_name) {
Steve Anton75737c02017-11-06 10:37:17 -08004338 bool sctp = (data_channel_type_ == cricket::DCT_SCTP);
4339 if (sctp) {
4340 if (!sctp_factory_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004341 RTC_LOG(LS_ERROR)
Steve Anton75737c02017-11-06 10:37:17 -08004342 << "Trying to create SCTP transport, but didn't compile with "
4343 "SCTP support (HAVE_SCTP)";
4344 return false;
4345 }
4346 if (!network_thread()->Invoke<bool>(
4347 RTC_FROM_HERE, rtc::Bind(&PeerConnection::CreateSctpTransport_n,
Steve Antoneda6ccd2017-12-04 10:21:55 -08004348 this, mid, transport_name))) {
Steve Anton75737c02017-11-06 10:37:17 -08004349 return false;
4350 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08004351 for (const auto& channel : sctp_data_channels_) {
4352 channel->OnTransportChannelCreated();
4353 }
Steve Anton75737c02017-11-06 10:37:17 -08004354 } else {
Steve Anton75737c02017-11-06 10:37:17 -08004355 cricket::DtlsTransportInternal* rtp_dtls_transport =
4356 transport_controller_->CreateDtlsTransport(
4357 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4358 cricket::DtlsTransportInternal* rtcp_dtls_transport = nullptr;
4359 if (configuration_.rtcp_mux_policy !=
4360 PeerConnectionInterface::kRtcpMuxPolicyRequire) {
4361 rtcp_dtls_transport = transport_controller_->CreateDtlsTransport(
4362 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
4363 }
4364
4365 rtp_data_channel_ = channel_manager()->CreateRtpDataChannel(
4366 configuration_.media_config, rtp_dtls_transport, rtcp_dtls_transport,
Steve Antoneda6ccd2017-12-04 10:21:55 -08004367 signaling_thread(), mid, SrtpRequired());
Steve Anton75737c02017-11-06 10:37:17 -08004368
4369 if (!rtp_data_channel_) {
4370 transport_controller_->DestroyDtlsTransport(
4371 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4372 if (rtcp_dtls_transport) {
4373 transport_controller_->DestroyDtlsTransport(
4374 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
4375 }
4376 return false;
4377 }
4378
4379 rtp_data_channel_->SignalRtcpMuxFullyActive.connect(
4380 this, &PeerConnection::DestroyRtcpTransport_n);
4381 rtp_data_channel_->SignalDtlsSrtpSetupFailure.connect(
4382 this, &PeerConnection::OnDtlsSrtpSetupFailure);
4383 rtp_data_channel_->SignalSentPacket.connect(
4384 this, &PeerConnection::OnSentPacket_w);
4385 }
4386
Steve Anton75737c02017-11-06 10:37:17 -08004387 return true;
4388}
4389
4390Call::Stats PeerConnection::GetCallStats() {
4391 if (!worker_thread()->IsCurrent()) {
4392 return worker_thread()->Invoke<Call::Stats>(
4393 RTC_FROM_HERE, rtc::Bind(&PeerConnection::GetCallStats, this));
4394 }
4395 if (call_) {
4396 return call_->GetStats();
4397 } else {
4398 return Call::Stats();
4399 }
4400}
4401
4402std::unique_ptr<SessionStats> PeerConnection::GetSessionStats_n(
4403 const ChannelNamePairs& channel_name_pairs) {
4404 RTC_DCHECK(network_thread()->IsCurrent());
4405 std::unique_ptr<SessionStats> session_stats(new SessionStats());
4406 for (const auto channel_name_pair :
4407 {&channel_name_pairs.voice, &channel_name_pairs.video,
4408 &channel_name_pairs.data}) {
4409 if (*channel_name_pair) {
4410 cricket::TransportStats transport_stats;
4411 if (!transport_controller_->GetStats((*channel_name_pair)->transport_name,
4412 &transport_stats)) {
4413 return nullptr;
4414 }
4415 session_stats->proxy_to_transport[(*channel_name_pair)->content_name] =
4416 (*channel_name_pair)->transport_name;
4417 session_stats->transport_stats[(*channel_name_pair)->transport_name] =
4418 std::move(transport_stats);
4419 }
4420 }
4421 return session_stats;
4422}
4423
4424bool PeerConnection::CreateSctpTransport_n(const std::string& content_name,
4425 const std::string& transport_name) {
4426 RTC_DCHECK(network_thread()->IsCurrent());
4427 RTC_DCHECK(sctp_factory_);
4428 cricket::DtlsTransportInternal* tc =
4429 transport_controller_->CreateDtlsTransport_n(
4430 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4431 sctp_transport_ = sctp_factory_->CreateSctpTransport(tc);
4432 RTC_DCHECK(sctp_transport_);
4433 sctp_invoker_.reset(new rtc::AsyncInvoker());
4434 sctp_transport_->SignalReadyToSendData.connect(
4435 this, &PeerConnection::OnSctpTransportReadyToSendData_n);
4436 sctp_transport_->SignalDataReceived.connect(
4437 this, &PeerConnection::OnSctpTransportDataReceived_n);
4438 sctp_transport_->SignalStreamClosedRemotely.connect(
4439 this, &PeerConnection::OnSctpStreamClosedRemotely_n);
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004440 sctp_transport_name_ = transport_name;
4441 sctp_content_name_ = content_name;
Steve Anton75737c02017-11-06 10:37:17 -08004442 return true;
4443}
4444
4445void PeerConnection::ChangeSctpTransport_n(const std::string& transport_name) {
4446 RTC_DCHECK(network_thread()->IsCurrent());
4447 RTC_DCHECK(sctp_transport_);
4448 RTC_DCHECK(sctp_transport_name_);
4449 std::string old_sctp_transport_name = *sctp_transport_name_;
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004450 sctp_transport_name_ = transport_name;
Steve Anton75737c02017-11-06 10:37:17 -08004451 cricket::DtlsTransportInternal* tc =
4452 transport_controller_->CreateDtlsTransport_n(
4453 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4454 sctp_transport_->SetTransportChannel(tc);
4455 transport_controller_->DestroyDtlsTransport_n(
4456 old_sctp_transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4457}
4458
4459void PeerConnection::DestroySctpTransport_n() {
4460 RTC_DCHECK(network_thread()->IsCurrent());
4461 sctp_transport_.reset(nullptr);
4462 sctp_content_name_.reset();
4463 sctp_transport_name_.reset();
4464 sctp_invoker_.reset(nullptr);
4465 sctp_ready_to_send_data_ = false;
4466}
4467
4468void PeerConnection::OnSctpTransportReadyToSendData_n() {
4469 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
4470 RTC_DCHECK(network_thread()->IsCurrent());
4471 // Note: Cannot use rtc::Bind here because it will grab a reference to
4472 // PeerConnection and potentially cause PeerConnection to live longer than
4473 // expected. It is safe not to grab a reference since the sctp_invoker_ will
4474 // be destroyed before PeerConnection is destroyed, and at that point all
4475 // pending tasks will be cleared.
4476 sctp_invoker_->AsyncInvoke<void>(RTC_FROM_HERE, signaling_thread(), [this] {
4477 OnSctpTransportReadyToSendData_s(true);
4478 });
4479}
4480
4481void PeerConnection::OnSctpTransportReadyToSendData_s(bool ready) {
4482 RTC_DCHECK(signaling_thread()->IsCurrent());
4483 sctp_ready_to_send_data_ = ready;
4484 SignalSctpReadyToSendData(ready);
4485}
4486
4487void PeerConnection::OnSctpTransportDataReceived_n(
4488 const cricket::ReceiveDataParams& params,
4489 const rtc::CopyOnWriteBuffer& payload) {
4490 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
4491 RTC_DCHECK(network_thread()->IsCurrent());
4492 // Note: Cannot use rtc::Bind here because it will grab a reference to
4493 // PeerConnection and potentially cause PeerConnection to live longer than
4494 // expected. It is safe not to grab a reference since the sctp_invoker_ will
4495 // be destroyed before PeerConnection is destroyed, and at that point all
4496 // pending tasks will be cleared.
4497 sctp_invoker_->AsyncInvoke<void>(
4498 RTC_FROM_HERE, signaling_thread(), [this, params, payload] {
4499 OnSctpTransportDataReceived_s(params, payload);
4500 });
4501}
4502
4503void PeerConnection::OnSctpTransportDataReceived_s(
4504 const cricket::ReceiveDataParams& params,
4505 const rtc::CopyOnWriteBuffer& payload) {
4506 RTC_DCHECK(signaling_thread()->IsCurrent());
4507 if (params.type == cricket::DMT_CONTROL && IsOpenMessage(payload)) {
4508 // Received OPEN message; parse and signal that a new data channel should
4509 // be created.
4510 std::string label;
4511 InternalDataChannelInit config;
4512 config.id = params.ssrc;
4513 if (!ParseDataChannelOpenMessage(payload, &label, &config)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004514 RTC_LOG(LS_WARNING) << "Failed to parse the OPEN message for sid "
4515 << params.ssrc;
Steve Anton75737c02017-11-06 10:37:17 -08004516 return;
4517 }
4518 config.open_handshake_role = InternalDataChannelInit::kAcker;
4519 OnDataChannelOpenMessage(label, config);
4520 } else {
4521 // Otherwise just forward the signal.
4522 SignalSctpDataReceived(params, payload);
4523 }
4524}
4525
4526void PeerConnection::OnSctpStreamClosedRemotely_n(int sid) {
4527 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
4528 RTC_DCHECK(network_thread()->IsCurrent());
4529 sctp_invoker_->AsyncInvoke<void>(
4530 RTC_FROM_HERE, signaling_thread(),
4531 rtc::Bind(&sigslot::signal1<int>::operator(),
4532 &SignalSctpStreamClosedRemotely, sid));
4533}
4534
4535// Returns false if bundle is enabled and rtcp_mux is disabled.
4536bool PeerConnection::ValidateBundleSettings(const SessionDescription* desc) {
4537 bool bundle_enabled = desc->HasGroup(cricket::GROUP_TYPE_BUNDLE);
4538 if (!bundle_enabled)
4539 return true;
4540
4541 const cricket::ContentGroup* bundle_group =
4542 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
4543 RTC_DCHECK(bundle_group != NULL);
4544
4545 const cricket::ContentInfos& contents = desc->contents();
4546 for (cricket::ContentInfos::const_iterator citer = contents.begin();
4547 citer != contents.end(); ++citer) {
4548 const cricket::ContentInfo* content = (&*citer);
4549 RTC_DCHECK(content != NULL);
4550 if (bundle_group->HasContentName(content->name) && !content->rejected &&
4551 content->type == cricket::NS_JINGLE_RTP) {
4552 if (!HasRtcpMuxEnabled(content))
4553 return false;
4554 }
4555 }
4556 // RTCP-MUX is enabled in all the contents.
4557 return true;
4558}
4559
4560bool PeerConnection::HasRtcpMuxEnabled(const cricket::ContentInfo* content) {
4561 const cricket::MediaContentDescription* description =
4562 static_cast<cricket::MediaContentDescription*>(content->description);
4563 return description->rtcp_mux();
4564}
4565
Steve Anton8a006912017-12-04 15:25:56 -08004566RTCError PeerConnection::ValidateSessionDescription(
Steve Anton75737c02017-11-06 10:37:17 -08004567 const SessionDescriptionInterface* sdesc,
Steve Anton8a006912017-12-04 15:25:56 -08004568 cricket::ContentSource source) {
Steve Antonf8470812017-12-04 10:46:21 -08004569 if (session_error() != SessionError::kNone) {
Steve Anton8a006912017-12-04 15:25:56 -08004570 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
Steve Anton75737c02017-11-06 10:37:17 -08004571 }
4572
4573 if (!sdesc || !sdesc->description()) {
Steve Anton8a006912017-12-04 15:25:56 -08004574 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidSdp);
Steve Anton75737c02017-11-06 10:37:17 -08004575 }
4576
Steve Anton3828c062017-12-06 10:34:51 -08004577 SdpType type = sdesc->GetType();
4578 if ((source == cricket::CS_LOCAL && !ExpectSetLocalDescription(type)) ||
4579 (source == cricket::CS_REMOTE && !ExpectSetRemoteDescription(type))) {
Steve Anton8a006912017-12-04 15:25:56 -08004580 LOG_AND_RETURN_ERROR(
4581 RTCErrorType::INVALID_PARAMETER,
4582 "Called in wrong state: " + GetSignalingStateString(signaling_state()));
Steve Anton75737c02017-11-06 10:37:17 -08004583 }
4584
4585 // Verify crypto settings.
4586 std::string crypto_error;
Steve Anton8a006912017-12-04 15:25:56 -08004587 if (webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED ||
4588 dtls_enabled_) {
4589 RTCError crypto_error = VerifyCrypto(sdesc->description(), dtls_enabled_);
4590 if (!crypto_error.ok()) {
4591 return crypto_error;
4592 }
Steve Anton75737c02017-11-06 10:37:17 -08004593 }
4594
4595 // Verify ice-ufrag and ice-pwd.
4596 if (!VerifyIceUfragPwdPresent(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08004597 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
4598 kSdpWithoutIceUfragPwd);
Steve Anton75737c02017-11-06 10:37:17 -08004599 }
4600
4601 if (!ValidateBundleSettings(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08004602 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
4603 kBundleWithoutRtcpMux);
Steve Anton75737c02017-11-06 10:37:17 -08004604 }
4605
4606 // TODO(skvlad): When the local rtcp-mux policy is Require, reject any
4607 // m-lines that do not rtcp-mux enabled.
4608
4609 // Verify m-lines in Answer when compared against Offer.
Steve Anton3828c062017-12-06 10:34:51 -08004610 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Anton75737c02017-11-06 10:37:17 -08004611 const cricket::SessionDescription* offer_desc =
4612 (source == cricket::CS_LOCAL) ? remote_description()->description()
4613 : local_description()->description();
4614 if (!MediaSectionsHaveSameCount(offer_desc, sdesc->description()) ||
4615 !MediaSectionsInSameOrder(offer_desc, sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08004616 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
4617 kMlineMismatchInAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08004618 }
4619 } else {
4620 const cricket::SessionDescription* current_desc = nullptr;
4621 if (source == cricket::CS_LOCAL && local_description()) {
4622 current_desc = local_description()->description();
4623 } else if (source == cricket::CS_REMOTE && remote_description()) {
4624 current_desc = remote_description()->description();
4625 }
4626 // The re-offers should respect the order of m= sections in current
4627 // description. See RFC3264 Section 8 paragraph 4 for more details.
4628 if (current_desc &&
4629 !MediaSectionsInSameOrder(current_desc, sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08004630 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
4631 kMlineMismatchInSubsequentOffer);
Steve Anton75737c02017-11-06 10:37:17 -08004632 }
4633 }
4634
Steve Anton8a006912017-12-04 15:25:56 -08004635 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08004636}
4637
Steve Anton3828c062017-12-06 10:34:51 -08004638bool PeerConnection::ExpectSetLocalDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08004639 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08004640 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08004641 return (state == PeerConnectionInterface::kStable) ||
4642 (state == PeerConnectionInterface::kHaveLocalOffer);
Steve Anton20393062017-12-04 16:24:52 -08004643 } else {
Steve Anton3828c062017-12-06 10:34:51 -08004644 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08004645 return (state == PeerConnectionInterface::kHaveRemoteOffer) ||
4646 (state == PeerConnectionInterface::kHaveLocalPrAnswer);
4647 }
4648}
4649
Steve Anton3828c062017-12-06 10:34:51 -08004650bool PeerConnection::ExpectSetRemoteDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08004651 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08004652 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08004653 return (state == PeerConnectionInterface::kStable) ||
4654 (state == PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton20393062017-12-04 16:24:52 -08004655 } else {
Steve Anton3828c062017-12-06 10:34:51 -08004656 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08004657 return (state == PeerConnectionInterface::kHaveLocalOffer) ||
4658 (state == PeerConnectionInterface::kHaveRemotePrAnswer);
4659 }
4660}
4661
Steve Antonf8470812017-12-04 10:46:21 -08004662const char* PeerConnection::SessionErrorToString(SessionError error) const {
4663 switch (error) {
4664 case SessionError::kNone:
4665 return "ERROR_NONE";
4666 case SessionError::kContent:
4667 return "ERROR_CONTENT";
4668 case SessionError::kTransport:
4669 return "ERROR_TRANSPORT";
4670 }
4671 RTC_NOTREACHED();
4672 return "";
4673}
4674
Steve Anton75737c02017-11-06 10:37:17 -08004675std::string PeerConnection::GetSessionErrorMsg() {
4676 std::ostringstream desc;
Steve Antonf8470812017-12-04 10:46:21 -08004677 desc << kSessionError << SessionErrorToString(session_error()) << ". ";
4678 desc << kSessionErrorDesc << session_error_desc() << ".";
Steve Anton75737c02017-11-06 10:37:17 -08004679 return desc.str();
4680}
4681
4682// We need to check the local/remote description for the Transport instead of
4683// the session, because a new Transport added during renegotiation may have
4684// them unset while the session has them set from the previous negotiation.
4685// Not doing so may trigger the auto generation of transport description and
4686// mess up DTLS identity information, ICE credential, etc.
4687bool PeerConnection::ReadyToUseRemoteCandidate(
4688 const IceCandidateInterface* candidate,
4689 const SessionDescriptionInterface* remote_desc,
4690 bool* valid) {
4691 *valid = true;
4692
4693 const SessionDescriptionInterface* current_remote_desc =
4694 remote_desc ? remote_desc : remote_description();
4695
4696 if (!current_remote_desc) {
4697 return false;
4698 }
4699
4700 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
4701 size_t remote_content_size =
4702 current_remote_desc->description()->contents().size();
4703 if (mediacontent_index >= remote_content_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004704 RTC_LOG(LS_ERROR)
4705 << "ReadyToUseRemoteCandidate: Invalid candidate media index "
4706 << mediacontent_index;
Steve Anton75737c02017-11-06 10:37:17 -08004707
4708 *valid = false;
4709 return false;
4710 }
4711
4712 cricket::ContentInfo content =
4713 current_remote_desc->description()->contents()[mediacontent_index];
4714
4715 const std::string transport_name = GetTransportName(content.name);
4716 if (transport_name.empty()) {
4717 return false;
4718 }
4719 return transport_controller_->ReadyForRemoteCandidates(transport_name);
4720}
4721
4722bool PeerConnection::SrtpRequired() const {
4723 return dtls_enabled_ ||
4724 webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED;
4725}
4726
4727void PeerConnection::OnTransportControllerGatheringState(
4728 cricket::IceGatheringState state) {
4729 RTC_DCHECK(signaling_thread()->IsCurrent());
4730 if (state == cricket::kIceGatheringGathering) {
4731 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringGathering);
4732 } else if (state == cricket::kIceGatheringComplete) {
4733 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringComplete);
4734 }
4735}
4736
4737void PeerConnection::ReportTransportStats() {
4738 // Use a set so we don't report the same stats twice if two channels share
4739 // a transport.
4740 std::set<std::string> transport_names;
4741 if (voice_channel()) {
4742 transport_names.insert(voice_channel()->transport_name());
4743 }
4744 if (video_channel()) {
4745 transport_names.insert(video_channel()->transport_name());
4746 }
4747 if (rtp_data_channel()) {
4748 transport_names.insert(rtp_data_channel()->transport_name());
4749 }
4750 if (sctp_transport_name_) {
4751 transport_names.insert(*sctp_transport_name_);
4752 }
4753 for (const auto& name : transport_names) {
4754 cricket::TransportStats stats;
4755 if (transport_controller_->GetStats(name, &stats)) {
4756 ReportBestConnectionState(stats);
4757 ReportNegotiatedCiphers(stats);
4758 }
4759 }
4760}
4761// Walk through the ConnectionInfos to gather best connection usage
4762// for IPv4 and IPv6.
4763void PeerConnection::ReportBestConnectionState(
4764 const cricket::TransportStats& stats) {
4765 RTC_DCHECK(metrics_observer());
4766 for (cricket::TransportChannelStatsList::const_iterator it =
4767 stats.channel_stats.begin();
4768 it != stats.channel_stats.end(); ++it) {
4769 for (cricket::ConnectionInfos::const_iterator it_info =
4770 it->connection_infos.begin();
4771 it_info != it->connection_infos.end(); ++it_info) {
4772 if (!it_info->best_connection) {
4773 continue;
4774 }
4775
4776 PeerConnectionEnumCounterType type = kPeerConnectionEnumCounterMax;
4777 const cricket::Candidate& local = it_info->local_candidate;
4778 const cricket::Candidate& remote = it_info->remote_candidate;
4779
4780 // Increment the counter for IceCandidatePairType.
4781 if (local.protocol() == cricket::TCP_PROTOCOL_NAME ||
4782 (local.type() == RELAY_PORT_TYPE &&
4783 local.relay_protocol() == cricket::TCP_PROTOCOL_NAME)) {
4784 type = kEnumCounterIceCandidatePairTypeTcp;
4785 } else if (local.protocol() == cricket::UDP_PROTOCOL_NAME) {
4786 type = kEnumCounterIceCandidatePairTypeUdp;
4787 } else {
4788 RTC_CHECK(0);
4789 }
4790 metrics_observer()->IncrementEnumCounter(
4791 type, GetIceCandidatePairCounter(local, remote),
4792 kIceCandidatePairMax);
4793
4794 // Increment the counter for IP type.
4795 if (local.address().family() == AF_INET) {
4796 metrics_observer()->IncrementEnumCounter(
4797 kEnumCounterAddressFamily, kBestConnections_IPv4,
4798 kPeerConnectionAddressFamilyCounter_Max);
4799
4800 } else if (local.address().family() == AF_INET6) {
4801 metrics_observer()->IncrementEnumCounter(
4802 kEnumCounterAddressFamily, kBestConnections_IPv6,
4803 kPeerConnectionAddressFamilyCounter_Max);
4804 } else {
4805 RTC_CHECK(0);
4806 }
4807
4808 return;
4809 }
4810 }
4811}
4812
4813void PeerConnection::ReportNegotiatedCiphers(
4814 const cricket::TransportStats& stats) {
4815 RTC_DCHECK(metrics_observer());
4816 if (!dtls_enabled_ || stats.channel_stats.empty()) {
4817 return;
4818 }
4819
4820 int srtp_crypto_suite = stats.channel_stats[0].srtp_crypto_suite;
4821 int ssl_cipher_suite = stats.channel_stats[0].ssl_cipher_suite;
4822 if (srtp_crypto_suite == rtc::SRTP_INVALID_CRYPTO_SUITE &&
4823 ssl_cipher_suite == rtc::TLS_NULL_WITH_NULL_NULL) {
4824 return;
4825 }
4826
4827 PeerConnectionEnumCounterType srtp_counter_type;
4828 PeerConnectionEnumCounterType ssl_counter_type;
4829 if (stats.transport_name == cricket::CN_AUDIO) {
4830 srtp_counter_type = kEnumCounterAudioSrtpCipher;
4831 ssl_counter_type = kEnumCounterAudioSslCipher;
4832 } else if (stats.transport_name == cricket::CN_VIDEO) {
4833 srtp_counter_type = kEnumCounterVideoSrtpCipher;
4834 ssl_counter_type = kEnumCounterVideoSslCipher;
4835 } else if (stats.transport_name == cricket::CN_DATA) {
4836 srtp_counter_type = kEnumCounterDataSrtpCipher;
4837 ssl_counter_type = kEnumCounterDataSslCipher;
4838 } else {
4839 RTC_NOTREACHED();
4840 return;
4841 }
4842
4843 if (srtp_crypto_suite != rtc::SRTP_INVALID_CRYPTO_SUITE) {
4844 metrics_observer()->IncrementSparseEnumCounter(srtp_counter_type,
4845 srtp_crypto_suite);
4846 }
4847 if (ssl_cipher_suite != rtc::TLS_NULL_WITH_NULL_NULL) {
4848 metrics_observer()->IncrementSparseEnumCounter(ssl_counter_type,
4849 ssl_cipher_suite);
4850 }
4851}
4852
4853void PeerConnection::OnSentPacket_w(const rtc::SentPacket& sent_packet) {
4854 RTC_DCHECK(worker_thread()->IsCurrent());
4855 RTC_DCHECK(call_);
4856 call_->OnSentPacket(sent_packet);
4857}
4858
4859const std::string PeerConnection::GetTransportName(
4860 const std::string& content_name) {
4861 cricket::BaseChannel* channel = GetChannel(content_name);
Steve Anton6fec8802017-12-04 10:37:29 -08004862 if (channel) {
4863 return channel->transport_name();
Steve Anton75737c02017-11-06 10:37:17 -08004864 }
Steve Anton6fec8802017-12-04 10:37:29 -08004865 if (sctp_transport_) {
4866 RTC_DCHECK(sctp_content_name_);
4867 RTC_DCHECK(sctp_transport_name_);
4868 if (content_name == *sctp_content_name_) {
4869 return *sctp_transport_name_;
4870 }
4871 }
4872 // Return an empty string if failed to retrieve the transport name.
4873 return "";
Steve Anton75737c02017-11-06 10:37:17 -08004874}
4875
4876void PeerConnection::DestroyRtcpTransport_n(const std::string& transport_name) {
4877 RTC_DCHECK(network_thread()->IsCurrent());
4878 transport_controller_->DestroyDtlsTransport_n(
4879 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
4880}
4881
Steve Anton6fec8802017-12-04 10:37:29 -08004882void PeerConnection::DestroyTransceiverChannel(
4883 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
4884 transceiver) {
4885 RTC_DCHECK(transceiver);
Steve Anton75737c02017-11-06 10:37:17 -08004886
Steve Anton6fec8802017-12-04 10:37:29 -08004887 cricket::BaseChannel* channel = transceiver->internal()->channel();
4888 if (channel) {
4889 transceiver->internal()->SetChannel(nullptr);
4890 DestroyBaseChannel(channel);
Steve Anton75737c02017-11-06 10:37:17 -08004891 }
4892}
4893
4894void PeerConnection::DestroyDataChannel() {
Steve Anton6fec8802017-12-04 10:37:29 -08004895 if (rtp_data_channel_) {
4896 OnDataChannelDestroyed();
4897 DestroyBaseChannel(rtp_data_channel_);
4898 rtp_data_channel_ = nullptr;
4899 }
4900
4901 // Note: Cannot use rtc::Bind to create a functor to invoke because it will
4902 // grab a reference to this PeerConnection. If this is called from the
4903 // PeerConnection destructor, the RefCountedObject vtable will have already
4904 // been destroyed (since it is a subclass of PeerConnection) and using
4905 // rtc::Bind will cause "Pure virtual function called" error to appear.
4906
4907 if (sctp_transport_) {
4908 OnDataChannelDestroyed();
4909 network_thread()->Invoke<void>(RTC_FROM_HERE,
4910 [this] { DestroySctpTransport_n(); });
4911 }
4912}
4913
4914void PeerConnection::DestroyBaseChannel(cricket::BaseChannel* channel) {
4915 RTC_DCHECK(channel);
4916 RTC_DCHECK(channel->rtp_dtls_transport());
4917
4918 // Need to cache these before destroying the base channel so that we do not
4919 // access uninitialized memory.
4920 const std::string transport_name =
4921 channel->rtp_dtls_transport()->transport_name();
4922 const bool need_to_delete_rtcp = (channel->rtcp_dtls_transport() != nullptr);
4923
4924 switch (channel->media_type()) {
4925 case cricket::MEDIA_TYPE_AUDIO:
4926 channel_manager()->DestroyVoiceChannel(
4927 static_cast<cricket::VoiceChannel*>(channel));
4928 break;
4929 case cricket::MEDIA_TYPE_VIDEO:
4930 channel_manager()->DestroyVideoChannel(
4931 static_cast<cricket::VideoChannel*>(channel));
4932 break;
4933 case cricket::MEDIA_TYPE_DATA:
4934 channel_manager()->DestroyRtpDataChannel(
4935 static_cast<cricket::RtpDataChannel*>(channel));
4936 break;
4937 default:
4938 RTC_NOTREACHED() << "Unknown media type: " << channel->media_type();
4939 break;
4940 }
4941
4942 // |channel| can no longer be used.
4943
Steve Anton75737c02017-11-06 10:37:17 -08004944 transport_controller_->DestroyDtlsTransport(
4945 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4946 if (need_to_delete_rtcp) {
4947 transport_controller_->DestroyDtlsTransport(
4948 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
4949 }
4950}
4951
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004952} // namespace webrtc