blob: 6420596608c1313219818095254c883cec1bcf50 [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 Anton8af21862017-12-15 11:20:13 -0800729 // Need to stop transceivers before destroying the stats collector because
730 // AudioRtpSender has a reference to the StatsCollector it will update when
731 // stopping.
732 for (auto transceiver : transceivers_) {
733 transceiver->Stop();
734 }
Steve Anton4171afb2017-11-20 10:20:22 -0800735
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700736 stats_.reset(nullptr);
hbosb78306a2016-12-19 05:06:57 -0800737 if (stats_collector_) {
738 stats_collector_->WaitForPendingRequest();
739 stats_collector_ = nullptr;
740 }
Steve Anton75737c02017-11-06 10:37:17 -0800741
Steve Anton8af21862017-12-15 11:20:13 -0800742 // Don't destroy BaseChannels until after stats has been cleaned up so that
743 // the last stats request can still read from the channels.
744 DestroyAllChannels();
745
Mirko Bonadei675513b2017-11-09 11:09:25 +0100746 RTC_LOG(LS_INFO) << "Session: " << session_id() << " is destroyed.";
Steve Anton75737c02017-11-06 10:37:17 -0800747
748 webrtc_session_desc_factory_.reset();
749 sctp_invoker_.reset();
750 sctp_factory_.reset();
751 transport_controller_.reset();
752
deadbeef91dd5672016-05-18 16:55:30 -0700753 // port_allocator_ lives on the network thread and should be destroyed there.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700754 network_thread()->Invoke<void>(RTC_FROM_HERE,
nisseeaabdf62017-05-05 02:23:02 -0700755 [this] { port_allocator_.reset(); });
eladalon248fd4f2017-09-06 05:18:15 -0700756 // call_ and event_log_ must be destroyed on the worker thread.
Steve Anton978b8762017-09-29 12:15:02 -0700757 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
eladalon248fd4f2017-09-06 05:18:15 -0700758 call_.reset();
759 event_log_.reset();
760 });
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000761}
762
Steve Anton8af21862017-12-15 11:20:13 -0800763void PeerConnection::DestroyAllChannels() {
Steve Anton3fe1b152017-12-12 10:20:08 -0800764 // Destroy video channels first since they may have a pointer to a voice
765 // channel.
766 for (auto transceiver : transceivers_) {
767 if (transceiver->internal()->media_type() == cricket::MEDIA_TYPE_VIDEO) {
768 DestroyTransceiverChannel(transceiver);
769 }
770 }
771 for (auto transceiver : transceivers_) {
772 if (transceiver->internal()->media_type() == cricket::MEDIA_TYPE_AUDIO) {
773 DestroyTransceiverChannel(transceiver);
774 }
775 }
776 DestroyDataChannel();
777}
778
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000779bool PeerConnection::Initialize(
buildbot@webrtc.org41451d42014-05-03 05:39:45 +0000780 const PeerConnectionInterface::RTCConfiguration& configuration,
kwibergd1fe2812016-04-27 06:47:29 -0700781 std::unique_ptr<cricket::PortAllocator> allocator,
Henrik Boströmd03c23b2016-06-01 11:44:18 +0200782 std::unique_ptr<rtc::RTCCertificateGeneratorInterface> cert_generator,
deadbeef653b8e02015-11-11 12:55:10 -0800783 PeerConnectionObserver* observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100784 TRACE_EVENT0("webrtc", "PeerConnection::Initialize");
Steve Anton038834f2017-07-14 15:59:59 -0700785
786 RTCError config_error = ValidateConfiguration(configuration);
787 if (!config_error.ok()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100788 RTC_LOG(LS_ERROR) << "Invalid configuration: " << config_error.message();
Steve Anton038834f2017-07-14 15:59:59 -0700789 return false;
790 }
791
deadbeef293e9262017-01-11 12:28:30 -0800792 if (!allocator) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100793 RTC_LOG(LS_ERROR)
794 << "PeerConnection initialized without a PortAllocator? "
795 << "This shouldn't happen if using PeerConnectionFactory.";
deadbeef293e9262017-01-11 12:28:30 -0800796 return false;
797 }
Jonas Orelandbdcee282017-10-10 14:01:40 +0200798
deadbeef653b8e02015-11-11 12:55:10 -0800799 if (!observer) {
deadbeef293e9262017-01-11 12:28:30 -0800800 // TODO(deadbeef): Why do we do this?
Mirko Bonadei675513b2017-11-09 11:09:25 +0100801 RTC_LOG(LS_ERROR) << "PeerConnection initialized without a "
802 << "PeerConnectionObserver";
deadbeef653b8e02015-11-11 12:55:10 -0800803 return false;
804 }
pthatcher@webrtc.org877ac762015-02-04 22:03:09 +0000805 observer_ = observer;
kwiberg0eb15ed2015-12-17 03:04:15 -0800806 port_allocator_ = std::move(allocator);
deadbeef653b8e02015-11-11 12:55:10 -0800807
deadbeef91dd5672016-05-18 16:55:30 -0700808 // The port allocator lives on the network thread and should be initialized
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700809 // there.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700810 if (!network_thread()->Invoke<bool>(
811 RTC_FROM_HERE, rtc::Bind(&PeerConnection::InitializePortAllocator_n,
812 this, configuration))) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000813 return false;
814 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000815
Steve Anton75737c02017-11-06 10:37:17 -0800816 // RFC 3264: The numeric value of the session id and version in the
817 // o line MUST be representable with a "64 bit signed integer".
818 // Due to this constraint session id |session_id_| is max limited to
819 // LLONG_MAX.
820 session_id_ = rtc::ToString(rtc::CreateRandomId64() & LLONG_MAX);
821 transport_controller_.reset(factory_->CreateTransportController(
822 port_allocator_.get(), configuration.redetermine_role_on_ice_restart));
823 transport_controller_->SetIceRole(cricket::ICEROLE_CONTROLLED);
824 transport_controller_->SignalConnectionState.connect(
825 this, &PeerConnection::OnTransportControllerConnectionState);
826 transport_controller_->SignalGatheringState.connect(
827 this, &PeerConnection::OnTransportControllerGatheringState);
828 transport_controller_->SignalCandidatesGathered.connect(
829 this, &PeerConnection::OnTransportControllerCandidatesGathered);
830 transport_controller_->SignalCandidatesRemoved.connect(
831 this, &PeerConnection::OnTransportControllerCandidatesRemoved);
832 transport_controller_->SignalDtlsHandshakeError.connect(
833 this, &PeerConnection::OnTransportControllerDtlsHandshakeError);
834
835 sctp_factory_ = factory_->CreateSctpTransportInternalFactory();
zhihuang29ff8442016-07-27 11:07:25 -0700836
deadbeefab9b2d12015-10-14 11:33:11 -0700837 stats_.reset(new StatsCollector(this));
hbos74e1a4f2016-09-15 23:33:01 -0700838 stats_collector_ = RTCStatsCollector::Create(this);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000839
Steve Antonba818672017-11-06 10:21:57 -0800840 configuration_ = configuration;
841
Steve Anton75737c02017-11-06 10:37:17 -0800842 const PeerConnectionFactoryInterface::Options& options = factory_->options();
843
844 transport_controller_->SetSslMaxProtocolVersion(options.ssl_max_version);
845
846 // Obtain a certificate from RTCConfiguration if any were provided (optional).
847 rtc::scoped_refptr<rtc::RTCCertificate> certificate;
848 if (!configuration.certificates.empty()) {
849 // TODO(hbos,torbjorng): Decide on certificate-selection strategy instead of
850 // just picking the first one. The decision should be made based on the DTLS
851 // handshake. The DTLS negotiations need to know about all certificates.
852 certificate = configuration.certificates[0];
853 }
854
Steve Antond25da372017-11-06 14:50:29 -0800855 transport_controller_->SetIceConfig(ParseIceConfig(configuration));
Steve Anton75737c02017-11-06 10:37:17 -0800856
857 if (options.disable_encryption) {
858 dtls_enabled_ = false;
859 } else {
860 // Enable DTLS by default if we have an identity store or a certificate.
861 dtls_enabled_ = (cert_generator || certificate);
862 // |configuration| can override the default |dtls_enabled_| value.
863 if (configuration.enable_dtls_srtp) {
864 dtls_enabled_ = *(configuration.enable_dtls_srtp);
865 }
866 }
867
868 // Enable creation of RTP data channels if the kEnableRtpDataChannels is set.
869 // It takes precendence over the disable_sctp_data_channels
870 // PeerConnectionFactoryInterface::Options.
871 if (configuration.enable_rtp_data_channel) {
872 data_channel_type_ = cricket::DCT_RTP;
873 } else {
874 // DTLS has to be enabled to use SCTP.
875 if (!options.disable_sctp_data_channels && dtls_enabled_) {
876 data_channel_type_ = cricket::DCT_SCTP;
877 }
878 }
879
880 video_options_.screencast_min_bitrate_kbps =
881 configuration.screencast_min_bitrate;
882 audio_options_.combined_audio_video_bwe =
883 configuration.combined_audio_video_bwe;
884
885 audio_options_.audio_jitter_buffer_max_packets =
Oskar Sundbom9b28a032017-11-16 10:53:30 +0100886 configuration.audio_jitter_buffer_max_packets;
Steve Anton75737c02017-11-06 10:37:17 -0800887
888 audio_options_.audio_jitter_buffer_fast_accelerate =
Oskar Sundbom9b28a032017-11-16 10:53:30 +0100889 configuration.audio_jitter_buffer_fast_accelerate;
Steve Anton75737c02017-11-06 10:37:17 -0800890
891 // Whether the certificate generator/certificate is null or not determines
892 // what PeerConnectionDescriptionFactory will do, so make sure that we give it
893 // the right instructions by clearing the variables if needed.
894 if (!dtls_enabled_) {
895 cert_generator.reset();
896 certificate = nullptr;
897 } else if (certificate) {
898 // Favor generated certificate over the certificate generator.
899 cert_generator.reset();
900 }
901
902 webrtc_session_desc_factory_.reset(new WebRtcSessionDescriptionFactory(
903 signaling_thread(), channel_manager(), this, session_id(),
904 std::move(cert_generator), certificate));
905 webrtc_session_desc_factory_->SignalCertificateReady.connect(
906 this, &PeerConnection::OnCertificateReady);
907
908 if (options.disable_encryption) {
909 webrtc_session_desc_factory_->SetSdesPolicy(cricket::SEC_DISABLED);
910 }
911
912 webrtc_session_desc_factory_->set_enable_encrypted_rtp_header_extensions(
913 options.crypto_options.enable_encrypted_rtp_header_extensions);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000914
Steve Anton4171afb2017-11-20 10:20:22 -0800915 // Add default audio/video transceivers for Plan B SDP.
916 if (!IsUnifiedPlan()) {
917 transceivers_.push_back(
918 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
919 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_AUDIO)));
920 transceivers_.push_back(
921 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
922 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_VIDEO)));
923 }
924
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000925 return true;
926}
927
Steve Anton038834f2017-07-14 15:59:59 -0700928RTCError PeerConnection::ValidateConfiguration(
929 const RTCConfiguration& config) const {
930 if (config.ice_regather_interval_range &&
931 config.continual_gathering_policy == GATHER_ONCE) {
932 return RTCError(RTCErrorType::INVALID_PARAMETER,
933 "ice_regather_interval_range specified but continual "
934 "gathering policy is GATHER_ONCE");
935 }
936 return RTCError::OK();
937}
938
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000939rtc::scoped_refptr<StreamCollectionInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000940PeerConnection::local_streams() {
deadbeefab9b2d12015-10-14 11:33:11 -0700941 return local_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000942}
943
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000944rtc::scoped_refptr<StreamCollectionInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000945PeerConnection::remote_streams() {
deadbeefab9b2d12015-10-14 11:33:11 -0700946 return remote_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000947}
948
perkj@webrtc.orgc2dd5ee2014-11-04 11:31:29 +0000949bool PeerConnection::AddStream(MediaStreamInterface* local_stream) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100950 TRACE_EVENT0("webrtc", "PeerConnection::AddStream");
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000951 if (IsClosed()) {
952 return false;
953 }
deadbeefab9b2d12015-10-14 11:33:11 -0700954 if (!CanAddLocalMediaStream(local_streams_, local_stream)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000955 return false;
956 }
deadbeefab9b2d12015-10-14 11:33:11 -0700957
958 local_streams_->AddStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -0800959 MediaStreamObserver* observer = new MediaStreamObserver(local_stream);
960 observer->SignalAudioTrackAdded.connect(this,
961 &PeerConnection::OnAudioTrackAdded);
962 observer->SignalAudioTrackRemoved.connect(
963 this, &PeerConnection::OnAudioTrackRemoved);
964 observer->SignalVideoTrackAdded.connect(this,
965 &PeerConnection::OnVideoTrackAdded);
966 observer->SignalVideoTrackRemoved.connect(
967 this, &PeerConnection::OnVideoTrackRemoved);
kwibergd1fe2812016-04-27 06:47:29 -0700968 stream_observers_.push_back(std::unique_ptr<MediaStreamObserver>(observer));
deadbeefab9b2d12015-10-14 11:33:11 -0700969
deadbeefab9b2d12015-10-14 11:33:11 -0700970 for (const auto& track : local_stream->GetAudioTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -0700971 AddAudioTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -0700972 }
973 for (const auto& track : local_stream->GetVideoTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -0700974 AddVideoTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -0700975 }
976
tommi@webrtc.org03505bc2014-07-14 20:15:26 +0000977 stats_->AddStream(local_stream);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000978 observer_->OnRenegotiationNeeded();
979 return true;
980}
981
982void PeerConnection::RemoveStream(MediaStreamInterface* local_stream) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100983 TRACE_EVENT0("webrtc", "PeerConnection::RemoveStream");
korniltsev.anatolyec390b52017-07-24 17:00:25 -0700984 if (!IsClosed()) {
985 for (const auto& track : local_stream->GetAudioTracks()) {
986 RemoveAudioTrack(track.get(), local_stream);
987 }
988 for (const auto& track : local_stream->GetVideoTracks()) {
989 RemoveVideoTrack(track.get(), local_stream);
990 }
deadbeefab9b2d12015-10-14 11:33:11 -0700991 }
deadbeefab9b2d12015-10-14 11:33:11 -0700992 local_streams_->RemoveStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -0800993 stream_observers_.erase(
994 std::remove_if(
995 stream_observers_.begin(), stream_observers_.end(),
kwibergd1fe2812016-04-27 06:47:29 -0700996 [local_stream](const std::unique_ptr<MediaStreamObserver>& observer) {
deadbeefeb459812015-12-15 19:24:43 -0800997 return observer->stream()->label().compare(local_stream->label()) ==
998 0;
999 }),
1000 stream_observers_.end());
deadbeefab9b2d12015-10-14 11:33:11 -07001001
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001002 if (IsClosed()) {
1003 return;
1004 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001005 observer_->OnRenegotiationNeeded();
1006}
1007
deadbeefe1f9d832016-01-14 15:35:42 -08001008rtc::scoped_refptr<RtpSenderInterface> PeerConnection::AddTrack(
1009 MediaStreamTrackInterface* track,
1010 std::vector<MediaStreamInterface*> streams) {
1011 TRACE_EVENT0("webrtc", "PeerConnection::AddTrack");
Steve Antonf9381f02017-12-14 10:23:57 -08001012 std::vector<std::string> stream_labels;
1013 for (auto* stream : streams) {
1014 if (!stream) {
1015 RTC_LOG(LS_ERROR) << "Stream list has null element.";
1016 return nullptr;
1017 }
1018 stream_labels.push_back(stream->label());
1019 }
1020 auto sender_or_error = AddTrackWithStreamLabels(track, stream_labels);
1021 if (!sender_or_error.ok()) {
deadbeefe1f9d832016-01-14 15:35:42 -08001022 return nullptr;
1023 }
Steve Antonf9381f02017-12-14 10:23:57 -08001024 return sender_or_error.MoveValue();
1025}
1026
1027RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>>
1028PeerConnection::AddTrackWithStreamLabels(
1029 rtc::scoped_refptr<MediaStreamTrackInterface> track,
1030 const std::vector<std::string>& stream_labels) {
1031 TRACE_EVENT0("webrtc", "PeerConnection::AddTrackWithStreamLabels");
1032 if (!track) {
1033 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "Track is null.");
1034 }
1035 if (!(track->kind() == MediaStreamTrackInterface::kAudioKind ||
1036 track->kind() == MediaStreamTrackInterface::kVideoKind)) {
1037 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1038 "Track has invalid kind: " + track->kind());
1039 }
1040 // TODO(bugs.webrtc.org/7932): Support adding a track to multiple streams.
1041 if (stream_labels.size() > 1u) {
1042 LOG_AND_RETURN_ERROR(
1043 RTCErrorType::UNSUPPORTED_OPERATION,
1044 "AddTrack with more than one stream is not currently supported.");
1045 }
1046 if (IsClosed()) {
1047 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
1048 "PeerConnection is closed.");
deadbeefe1f9d832016-01-14 15:35:42 -08001049 }
Steve Anton4171afb2017-11-20 10:20:22 -08001050 if (FindSenderForTrack(track)) {
Steve Antonf9381f02017-12-14 10:23:57 -08001051 LOG_AND_RETURN_ERROR(
1052 RTCErrorType::INVALID_PARAMETER,
1053 "Sender already exists for track " + track->id() + ".");
deadbeefe1f9d832016-01-14 15:35:42 -08001054 }
Steve Antonf9381f02017-12-14 10:23:57 -08001055 // TODO(bugs.webrtc.org/7933): MediaSession expects the sender to have exactly
1056 // one stream. AddTrackInternal will return an error if there is more than one
1057 // stream, but if the caller specifies none then we need to generate a random
1058 // stream label.
1059 std::vector<std::string> adjusted_stream_labels = stream_labels;
1060 if (stream_labels.empty()) {
1061 adjusted_stream_labels.push_back(rtc::CreateRandomUuid());
1062 }
1063 RTC_DCHECK_EQ(1, adjusted_stream_labels.size());
1064 auto sender_or_error =
1065 (IsUnifiedPlan() ? AddTrackUnifiedPlan(track, adjusted_stream_labels)
1066 : AddTrackPlanB(track, adjusted_stream_labels));
1067 if (sender_or_error.ok()) {
1068 observer_->OnRenegotiationNeeded();
1069 }
1070 return sender_or_error;
1071}
deadbeefe1f9d832016-01-14 15:35:42 -08001072
Steve Antonf9381f02017-12-14 10:23:57 -08001073RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>>
1074PeerConnection::AddTrackPlanB(
1075 rtc::scoped_refptr<MediaStreamTrackInterface> track,
1076 const std::vector<std::string>& stream_labels) {
deadbeefe1f9d832016-01-14 15:35:42 -08001077 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
Steve Antonf9381f02017-12-14 10:23:57 -08001078 auto new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
deadbeefe1f9d832016-01-14 15:35:42 -08001079 signaling_thread(),
Steve Antonf9381f02017-12-14 10:23:57 -08001080 new AudioRtpSender(static_cast<AudioTrackInterface*>(track.get()),
Steve Anton75737c02017-11-06 10:37:17 -08001081 voice_channel(), stats_.get()));
Steve Anton4171afb2017-11-20 10:20:22 -08001082 GetAudioTransceiver()->internal()->AddSender(new_sender);
Steve Antonf9381f02017-12-14 10:23:57 -08001083 new_sender->internal()->set_stream_ids(stream_labels);
Steve Anton4171afb2017-11-20 10:20:22 -08001084 const RtpSenderInfo* sender_info =
1085 FindSenderInfo(local_audio_sender_infos_,
1086 new_sender->internal()->stream_id(), track->id());
1087 if (sender_info) {
1088 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -08001089 }
Steve Antonf9381f02017-12-14 10:23:57 -08001090 return rtc::scoped_refptr<RtpSenderInterface>(new_sender);
1091 } else {
1092 RTC_DCHECK_EQ(MediaStreamTrackInterface::kVideoKind, track->kind());
1093 auto new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
deadbeefe1f9d832016-01-14 15:35:42 -08001094 signaling_thread(),
Steve Antonf9381f02017-12-14 10:23:57 -08001095 new VideoRtpSender(static_cast<VideoTrackInterface*>(track.get()),
Steve Anton75737c02017-11-06 10:37:17 -08001096 video_channel()));
Steve Anton4171afb2017-11-20 10:20:22 -08001097 GetVideoTransceiver()->internal()->AddSender(new_sender);
Steve Antonf9381f02017-12-14 10:23:57 -08001098 new_sender->internal()->set_stream_ids(stream_labels);
Steve Anton4171afb2017-11-20 10:20:22 -08001099 const RtpSenderInfo* sender_info =
1100 FindSenderInfo(local_video_sender_infos_,
1101 new_sender->internal()->stream_id(), track->id());
1102 if (sender_info) {
1103 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -08001104 }
Steve Antonf9381f02017-12-14 10:23:57 -08001105 return rtc::scoped_refptr<RtpSenderInterface>(new_sender);
deadbeefe1f9d832016-01-14 15:35:42 -08001106 }
Steve Antonf9381f02017-12-14 10:23:57 -08001107}
deadbeefe1f9d832016-01-14 15:35:42 -08001108
Steve Antonf9381f02017-12-14 10:23:57 -08001109RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>>
1110PeerConnection::AddTrackUnifiedPlan(
1111 rtc::scoped_refptr<MediaStreamTrackInterface> track,
1112 const std::vector<std::string>& stream_labels) {
1113 auto transceiver = FindFirstTransceiverForAddedTrack(track);
1114 if (transceiver) {
1115 if (transceiver->direction() == RtpTransceiverDirection::kRecvOnly) {
1116 transceiver->SetDirection(RtpTransceiverDirection::kSendRecv);
1117 } else if (transceiver->direction() == RtpTransceiverDirection::kInactive) {
1118 transceiver->SetDirection(RtpTransceiverDirection::kSendOnly);
1119 }
1120 } else {
1121 cricket::MediaType media_type =
1122 (track->kind() == MediaStreamTrackInterface::kAudioKind
1123 ? cricket::MEDIA_TYPE_AUDIO
1124 : cricket::MEDIA_TYPE_VIDEO);
1125 transceiver = CreateTransceiver(media_type);
1126 transceiver->internal()->set_created_by_addtrack(true);
1127 transceiver->SetDirection(RtpTransceiverDirection::kSendRecv);
1128 }
1129 transceiver->sender()->SetTrack(track);
1130 transceiver->internal()->sender_internal()->set_stream_ids(stream_labels);
1131 return transceiver->sender();
1132}
1133
1134rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1135PeerConnection::FindFirstTransceiverForAddedTrack(
1136 rtc::scoped_refptr<MediaStreamTrackInterface> track) {
1137 RTC_DCHECK(track);
1138 for (auto transceiver : transceivers_) {
1139 if (!transceiver->sender()->track() &&
1140 cricket::MediaTypeToString(transceiver->internal()->media_type()) ==
1141 track->kind() &&
1142 !transceiver->internal()->has_ever_been_used_to_send()) {
1143 return transceiver;
1144 }
1145 }
1146 return nullptr;
deadbeefe1f9d832016-01-14 15:35:42 -08001147}
1148
1149bool PeerConnection::RemoveTrack(RtpSenderInterface* sender) {
1150 TRACE_EVENT0("webrtc", "PeerConnection::RemoveTrack");
Steve Antonf9381f02017-12-14 10:23:57 -08001151 return RemoveTrackInternal(sender).ok();
1152}
1153
1154RTCError PeerConnection::RemoveTrackInternal(
1155 rtc::scoped_refptr<RtpSenderInterface> sender) {
1156 if (!sender) {
1157 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "Sender is null.");
1158 }
deadbeefe1f9d832016-01-14 15:35:42 -08001159 if (IsClosed()) {
Steve Antonf9381f02017-12-14 10:23:57 -08001160 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
1161 "PeerConnection is closed.");
deadbeefe1f9d832016-01-14 15:35:42 -08001162 }
Steve Antonf9381f02017-12-14 10:23:57 -08001163 if (IsUnifiedPlan()) {
1164 auto transceiver = FindTransceiverBySender(sender);
1165 if (!transceiver || !sender->track()) {
1166 return RTCError::OK();
1167 }
1168 sender->SetTrack(nullptr);
1169 if (transceiver->direction() == RtpTransceiverDirection::kSendRecv) {
1170 transceiver->internal()->SetDirection(RtpTransceiverDirection::kRecvOnly);
1171 } else if (transceiver->direction() == RtpTransceiverDirection::kSendOnly) {
1172 transceiver->internal()->SetDirection(RtpTransceiverDirection::kInactive);
1173 }
Steve Anton4171afb2017-11-20 10:20:22 -08001174 } else {
Steve Antonf9381f02017-12-14 10:23:57 -08001175 bool removed;
1176 if (sender->media_type() == cricket::MEDIA_TYPE_AUDIO) {
1177 removed = GetAudioTransceiver()->internal()->RemoveSender(sender);
1178 } else {
1179 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, sender->media_type());
1180 removed = GetVideoTransceiver()->internal()->RemoveSender(sender);
1181 }
1182 if (!removed) {
1183 LOG_AND_RETURN_ERROR(
1184 RTCErrorType::INVALID_PARAMETER,
1185 "Couldn't find sender " + sender->id() + " to remove.");
1186 }
Steve Anton4171afb2017-11-20 10:20:22 -08001187 }
deadbeefe1f9d832016-01-14 15:35:42 -08001188 observer_->OnRenegotiationNeeded();
Steve Antonf9381f02017-12-14 10:23:57 -08001189 return RTCError::OK();
1190}
1191
1192rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1193PeerConnection::FindTransceiverBySender(
1194 rtc::scoped_refptr<RtpSenderInterface> sender) {
1195 for (auto transceiver : transceivers_) {
1196 if (transceiver->sender() == sender) {
1197 return transceiver;
1198 }
1199 }
1200 return nullptr;
deadbeefe1f9d832016-01-14 15:35:42 -08001201}
1202
Steve Anton9158ef62017-11-27 13:01:52 -08001203RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1204PeerConnection::AddTransceiver(
1205 rtc::scoped_refptr<MediaStreamTrackInterface> track) {
1206 return AddTransceiver(track, RtpTransceiverInit());
1207}
1208
1209RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1210PeerConnection::AddTransceiver(
1211 rtc::scoped_refptr<MediaStreamTrackInterface> track,
1212 const RtpTransceiverInit& init) {
1213 if (!IsUnifiedPlan()) {
1214 LOG_AND_RETURN_ERROR(
1215 RTCErrorType::INTERNAL_ERROR,
1216 "AddTransceiver only supported when Unified Plan is enabled.");
1217 }
1218 if (!track) {
1219 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "track is null");
1220 }
1221 cricket::MediaType media_type;
1222 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
1223 media_type = cricket::MEDIA_TYPE_AUDIO;
1224 } else if (track->kind() == MediaStreamTrackInterface::kVideoKind) {
1225 media_type = cricket::MEDIA_TYPE_VIDEO;
1226 } else {
1227 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1228 "Track kind is not audio or video");
1229 }
1230 return AddTransceiver(media_type, track, init);
1231}
1232
1233RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1234PeerConnection::AddTransceiver(cricket::MediaType media_type) {
1235 return AddTransceiver(media_type, RtpTransceiverInit());
1236}
1237
1238RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1239PeerConnection::AddTransceiver(cricket::MediaType media_type,
1240 const RtpTransceiverInit& init) {
1241 if (!IsUnifiedPlan()) {
1242 LOG_AND_RETURN_ERROR(
1243 RTCErrorType::INTERNAL_ERROR,
1244 "AddTransceiver only supported when Unified Plan is enabled.");
1245 }
1246 if (!(media_type == cricket::MEDIA_TYPE_AUDIO ||
1247 media_type == cricket::MEDIA_TYPE_VIDEO)) {
1248 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1249 "media type is not audio or video");
1250 }
1251 return AddTransceiver(media_type, nullptr, init);
1252}
1253
1254RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1255PeerConnection::AddTransceiver(
1256 cricket::MediaType media_type,
1257 rtc::scoped_refptr<MediaStreamTrackInterface> track,
1258 const RtpTransceiverInit& init) {
1259 RTC_DCHECK((media_type == cricket::MEDIA_TYPE_AUDIO ||
1260 media_type == cricket::MEDIA_TYPE_VIDEO));
1261 if (track) {
1262 RTC_DCHECK_EQ(media_type,
1263 (track->kind() == MediaStreamTrackInterface::kAudioKind
1264 ? cricket::MEDIA_TYPE_AUDIO
1265 : cricket::MEDIA_TYPE_VIDEO));
1266 }
1267
1268 // TODO(bugs.webrtc.org/7600): Verify init.
1269
Steve Antonf9381f02017-12-14 10:23:57 -08001270 auto transceiver = CreateTransceiver(media_type);
1271 transceiver->SetDirection(init.direction);
1272 if (track) {
1273 transceiver->sender()->SetTrack(track);
1274 }
1275
1276 observer_->OnRenegotiationNeeded();
1277
1278 return rtc::scoped_refptr<RtpTransceiverInterface>(transceiver);
1279}
1280
1281rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1282PeerConnection::CreateTransceiver(cricket::MediaType media_type) {
Steve Anton9158ef62017-11-27 13:01:52 -08001283 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> sender;
1284 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1285 receiver;
1286 std::string receiver_id = rtc::CreateRandomUuid();
Steve Antonf9381f02017-12-14 10:23:57 -08001287 // TODO(bugs.webrtc.org/7600): Initializing the sender/receiver with a null
1288 // channel prevents users from calling SetParameters on them, which is needed
1289 // to be in compliance with the spec.
Steve Anton9158ef62017-11-27 13:01:52 -08001290 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
1291 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
1292 signaling_thread(), new AudioRtpSender(nullptr, stats_.get()));
1293 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
1294 signaling_thread(), new AudioRtpReceiver(receiver_id, {}, 0, nullptr));
1295 } else {
1296 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, media_type);
1297 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
1298 signaling_thread(), new VideoRtpSender(nullptr));
1299 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
1300 signaling_thread(),
1301 new VideoRtpReceiver(receiver_id, {}, worker_thread(), 0, nullptr));
1302 }
Steve Anton9158ef62017-11-27 13:01:52 -08001303 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1304 transceiver = RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1305 signaling_thread(), new RtpTransceiver(sender, receiver));
Steve Anton9158ef62017-11-27 13:01:52 -08001306 transceivers_.push_back(transceiver);
Steve Antonf9381f02017-12-14 10:23:57 -08001307 return transceiver;
Steve Anton9158ef62017-11-27 13:01:52 -08001308}
1309
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001310rtc::scoped_refptr<DtmfSenderInterface> PeerConnection::CreateDtmfSender(
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001311 AudioTrackInterface* track) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001312 TRACE_EVENT0("webrtc", "PeerConnection::CreateDtmfSender");
zhihuang29ff8442016-07-27 11:07:25 -07001313 if (IsClosed()) {
1314 return nullptr;
1315 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001316 if (!track) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001317 RTC_LOG(LS_ERROR) << "CreateDtmfSender - track is NULL.";
deadbeef20cb0c12017-02-01 20:27:00 -08001318 return nullptr;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001319 }
Steve Anton4171afb2017-11-20 10:20:22 -08001320 auto track_sender = FindSenderForTrack(track);
1321 if (!track_sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001322 RTC_LOG(LS_ERROR) << "CreateDtmfSender called with a non-added track.";
deadbeef20cb0c12017-02-01 20:27:00 -08001323 return nullptr;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001324 }
1325
Steve Anton4171afb2017-11-20 10:20:22 -08001326 return track_sender->GetDtmfSender();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001327}
1328
deadbeeffac06552015-11-25 11:26:01 -08001329rtc::scoped_refptr<RtpSenderInterface> PeerConnection::CreateSender(
deadbeefbd7d8f72015-12-18 16:58:44 -08001330 const std::string& kind,
1331 const std::string& stream_id) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001332 TRACE_EVENT0("webrtc", "PeerConnection::CreateSender");
zhihuang29ff8442016-07-27 11:07:25 -07001333 if (IsClosed()) {
1334 return nullptr;
1335 }
Steve Anton4171afb2017-11-20 10:20:22 -08001336
1337 // TODO(steveanton): Move construction of the RtpSenders to RtpTransceiver.
deadbeefa601f5c2016-06-06 14:27:39 -07001338 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender;
deadbeeffac06552015-11-25 11:26:01 -08001339 if (kind == MediaStreamTrackInterface::kAudioKind) {
deadbeefa601f5c2016-06-06 14:27:39 -07001340 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton75737c02017-11-06 10:37:17 -08001341 signaling_thread(), new AudioRtpSender(voice_channel(), stats_.get()));
Steve Anton4171afb2017-11-20 10:20:22 -08001342 GetAudioTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 11:26:01 -08001343 } else if (kind == MediaStreamTrackInterface::kVideoKind) {
deadbeefa601f5c2016-06-06 14:27:39 -07001344 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton75737c02017-11-06 10:37:17 -08001345 signaling_thread(), new VideoRtpSender(video_channel()));
Steve Anton4171afb2017-11-20 10:20:22 -08001346 GetVideoTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 11:26:01 -08001347 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001348 RTC_LOG(LS_ERROR) << "CreateSender called with invalid kind: " << kind;
Steve Anton4171afb2017-11-20 10:20:22 -08001349 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08001350 }
Steve Anton4171afb2017-11-20 10:20:22 -08001351
deadbeefbd7d8f72015-12-18 16:58:44 -08001352 if (!stream_id.empty()) {
deadbeefa601f5c2016-06-06 14:27:39 -07001353 new_sender->internal()->set_stream_id(stream_id);
deadbeefbd7d8f72015-12-18 16:58:44 -08001354 }
Steve Anton4171afb2017-11-20 10:20:22 -08001355
deadbeefe1f9d832016-01-14 15:35:42 -08001356 return new_sender;
deadbeeffac06552015-11-25 11:26:01 -08001357}
1358
deadbeef70ab1a12015-09-28 16:53:55 -07001359std::vector<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::GetSenders()
1360 const {
deadbeefa601f5c2016-06-06 14:27:39 -07001361 std::vector<rtc::scoped_refptr<RtpSenderInterface>> ret;
Steve Anton4171afb2017-11-20 10:20:22 -08001362 for (auto sender : GetSendersInternal()) {
1363 ret.push_back(sender);
deadbeefa601f5c2016-06-06 14:27:39 -07001364 }
1365 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -07001366}
1367
Steve Anton4171afb2017-11-20 10:20:22 -08001368std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1369PeerConnection::GetSendersInternal() const {
1370 std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1371 all_senders;
1372 for (auto transceiver : transceivers_) {
1373 auto senders = transceiver->internal()->senders();
1374 all_senders.insert(all_senders.end(), senders.begin(), senders.end());
1375 }
1376 return all_senders;
1377}
1378
deadbeef70ab1a12015-09-28 16:53:55 -07001379std::vector<rtc::scoped_refptr<RtpReceiverInterface>>
1380PeerConnection::GetReceivers() const {
deadbeefa601f5c2016-06-06 14:27:39 -07001381 std::vector<rtc::scoped_refptr<RtpReceiverInterface>> ret;
Steve Anton4171afb2017-11-20 10:20:22 -08001382 for (const auto& receiver : GetReceiversInternal()) {
1383 ret.push_back(receiver);
deadbeefa601f5c2016-06-06 14:27:39 -07001384 }
1385 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -07001386}
1387
Steve Anton4171afb2017-11-20 10:20:22 -08001388std::vector<
1389 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1390PeerConnection::GetReceiversInternal() const {
1391 std::vector<
1392 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1393 all_receivers;
1394 for (auto transceiver : transceivers_) {
1395 auto receivers = transceiver->internal()->receivers();
1396 all_receivers.insert(all_receivers.end(), receivers.begin(),
1397 receivers.end());
1398 }
1399 return all_receivers;
1400}
1401
Steve Anton9158ef62017-11-27 13:01:52 -08001402std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
1403PeerConnection::GetTransceivers() const {
1404 RTC_DCHECK(IsUnifiedPlan());
1405 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> all_transceivers;
1406 for (auto transceiver : transceivers_) {
1407 all_transceivers.push_back(transceiver);
1408 }
1409 return all_transceivers;
1410}
1411
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001412bool PeerConnection::GetStats(StatsObserver* observer,
wu@webrtc.orgb9a088b2014-02-13 23:18:49 +00001413 MediaStreamTrackInterface* track,
1414 StatsOutputLevel level) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001415 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
deadbeef0a6c4ca2015-10-06 11:38:28 -07001416 RTC_DCHECK(signaling_thread()->IsCurrent());
nisse7ce109a2017-01-31 00:57:56 -08001417 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001418 RTC_LOG(LS_ERROR) << "GetStats - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001419 return false;
1420 }
1421
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001422 stats_->UpdateStats(level);
zhihuange9e94c32016-11-04 11:38:15 -07001423 // The StatsCollector is used to tell if a track is valid because it may
1424 // remember tracks that the PeerConnection previously removed.
1425 if (track && !stats_->IsValidTrack(track->id())) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001426 RTC_LOG(LS_WARNING) << "GetStats is called with an invalid track: "
1427 << track->id();
zhihuange9e94c32016-11-04 11:38:15 -07001428 return false;
1429 }
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001430 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_GETSTATS,
tommi@webrtc.org5b06b062014-08-15 08:38:30 +00001431 new GetStatsMsg(observer, track));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001432 return true;
1433}
1434
hbos74e1a4f2016-09-15 23:33:01 -07001435void PeerConnection::GetStats(RTCStatsCollectorCallback* callback) {
1436 RTC_DCHECK(stats_collector_);
1437 stats_collector_->GetStatsReport(callback);
1438}
1439
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001440PeerConnectionInterface::SignalingState PeerConnection::signaling_state() {
1441 return signaling_state_;
1442}
1443
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001444PeerConnectionInterface::IceConnectionState
1445PeerConnection::ice_connection_state() {
1446 return ice_connection_state_;
1447}
1448
1449PeerConnectionInterface::IceGatheringState
1450PeerConnection::ice_gathering_state() {
1451 return ice_gathering_state_;
1452}
1453
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001454rtc::scoped_refptr<DataChannelInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001455PeerConnection::CreateDataChannel(
1456 const std::string& label,
1457 const DataChannelInit* config) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001458 TRACE_EVENT0("webrtc", "PeerConnection::CreateDataChannel");
zhihuang9763d562016-08-05 11:14:50 -07001459
deadbeefab9b2d12015-10-14 11:33:11 -07001460 bool first_datachannel = !HasDataChannels();
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001461
kwibergd1fe2812016-04-27 06:47:29 -07001462 std::unique_ptr<InternalDataChannelInit> internal_config;
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00001463 if (config) {
1464 internal_config.reset(new InternalDataChannelInit(*config));
1465 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001466 rtc::scoped_refptr<DataChannelInterface> channel(
deadbeefab9b2d12015-10-14 11:33:11 -07001467 InternalCreateDataChannel(label, internal_config.get()));
1468 if (!channel.get()) {
1469 return nullptr;
1470 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001471
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001472 // Trigger the onRenegotiationNeeded event for every new RTP DataChannel, or
1473 // the first SCTP DataChannel.
Steve Anton75737c02017-11-06 10:37:17 -08001474 if (data_channel_type() == cricket::DCT_RTP || first_datachannel) {
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001475 observer_->OnRenegotiationNeeded();
1476 }
wu@webrtc.org91053e72013-08-10 07:18:04 +00001477
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001478 return DataChannelProxy::Create(signaling_thread(), channel.get());
1479}
1480
1481void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
1482 const MediaConstraintsInterface* constraints) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001483 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
Steve Anton8d3444d2017-10-20 15:30:51 -07001484
zhihuang1c378ed2017-08-17 14:10:50 -07001485 PeerConnectionInterface::RTCOfferAnswerOptions offer_answer_options;
1486 // Always create an offer even if |ConvertConstraintsToOfferAnswerOptions|
1487 // returns false for now. Because |ConvertConstraintsToOfferAnswerOptions|
1488 // compares the mandatory fields parsed with the mandatory fields added in the
1489 // |constraints| and some downstream applications might create offers with
1490 // mandatory fields which would not be parsed in the helper method. For
1491 // example, in Chromium/remoting, |kEnableDtlsSrtp| is added to the
1492 // |constraints| as a mandatory field but it is not parsed.
1493 ConvertConstraintsToOfferAnswerOptions(constraints, &offer_answer_options);
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001494
zhihuang1c378ed2017-08-17 14:10:50 -07001495 CreateOffer(observer, offer_answer_options);
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001496}
1497
1498void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
1499 const RTCOfferAnswerOptions& options) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001500 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
Steve Anton8d3444d2017-10-20 15:30:51 -07001501
nisse7ce109a2017-01-31 00:57:56 -08001502 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001503 RTC_LOG(LS_ERROR) << "CreateOffer - observer is NULL.";
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001504 return;
1505 }
deadbeefab9b2d12015-10-14 11:33:11 -07001506
Steve Anton8d3444d2017-10-20 15:30:51 -07001507 if (IsClosed()) {
1508 std::string error = "CreateOffer called when PeerConnection is closed.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001509 RTC_LOG(LS_ERROR) << error;
Steve Anton8d3444d2017-10-20 15:30:51 -07001510 PostCreateSessionDescriptionFailure(observer, error);
1511 return;
1512 }
1513
zhihuang1c378ed2017-08-17 14:10:50 -07001514 if (!ValidateOfferAnswerOptions(options)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001515 std::string error = "CreateOffer called with invalid options.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001516 RTC_LOG(LS_ERROR) << error;
deadbeefab9b2d12015-10-14 11:33:11 -07001517 PostCreateSessionDescriptionFailure(observer, error);
1518 return;
1519 }
1520
zhihuang1c378ed2017-08-17 14:10:50 -07001521 cricket::MediaSessionOptions session_options;
1522 GetOptionsForOffer(options, &session_options);
Steve Antond25da372017-11-06 14:50:29 -08001523 webrtc_session_desc_factory_->CreateOffer(observer, options, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001524}
1525
1526void PeerConnection::CreateAnswer(
1527 CreateSessionDescriptionObserver* observer,
1528 const MediaConstraintsInterface* constraints) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001529 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
Steve Anton8d3444d2017-10-20 15:30:51 -07001530
nisse7ce109a2017-01-31 00:57:56 -08001531 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001532 RTC_LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001533 return;
1534 }
deadbeefab9b2d12015-10-14 11:33:11 -07001535
zhihuang1c378ed2017-08-17 14:10:50 -07001536 PeerConnectionInterface::RTCOfferAnswerOptions offer_answer_options;
1537 if (!ConvertConstraintsToOfferAnswerOptions(constraints,
1538 &offer_answer_options)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001539 std::string error = "CreateAnswer called with invalid constraints.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001540 RTC_LOG(LS_ERROR) << error;
deadbeefab9b2d12015-10-14 11:33:11 -07001541 PostCreateSessionDescriptionFailure(observer, error);
1542 return;
1543 }
1544
Steve Anton8d3444d2017-10-20 15:30:51 -07001545 CreateAnswer(observer, offer_answer_options);
htaa2a49d92016-03-04 02:51:39 -08001546}
1547
1548void PeerConnection::CreateAnswer(CreateSessionDescriptionObserver* observer,
1549 const RTCOfferAnswerOptions& options) {
1550 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
nisse7ce109a2017-01-31 00:57:56 -08001551 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001552 RTC_LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
htaa2a49d92016-03-04 02:51:39 -08001553 return;
1554 }
1555
Steve Anton8d3444d2017-10-20 15:30:51 -07001556 if (IsClosed()) {
1557 std::string error = "CreateAnswer called when PeerConnection is closed.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001558 RTC_LOG(LS_ERROR) << error;
Steve Anton8d3444d2017-10-20 15:30:51 -07001559 PostCreateSessionDescriptionFailure(observer, error);
1560 return;
1561 }
1562
Steve Anton75737c02017-11-06 10:37:17 -08001563 if (remote_description() &&
Steve Antona3a92c22017-12-07 10:27:41 -08001564 remote_description()->GetType() != SdpType::kOffer) {
Steve Anton8d3444d2017-10-20 15:30:51 -07001565 std::string error = "CreateAnswer called without remote offer.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001566 RTC_LOG(LS_ERROR) << error;
Steve Anton8d3444d2017-10-20 15:30:51 -07001567 PostCreateSessionDescriptionFailure(observer, error);
1568 return;
1569 }
1570
htaa2a49d92016-03-04 02:51:39 -08001571 cricket::MediaSessionOptions session_options;
zhihuang1c378ed2017-08-17 14:10:50 -07001572 GetOptionsForAnswer(options, &session_options);
htaa2a49d92016-03-04 02:51:39 -08001573
Steve Antond25da372017-11-06 14:50:29 -08001574 webrtc_session_desc_factory_->CreateAnswer(observer, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001575}
1576
1577void PeerConnection::SetLocalDescription(
1578 SetSessionDescriptionObserver* observer,
1579 SessionDescriptionInterface* desc) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001580 TRACE_EVENT0("webrtc", "PeerConnection::SetLocalDescription");
Steve Anton8a006912017-12-04 15:25:56 -08001581
nisse7ce109a2017-01-31 00:57:56 -08001582 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001583 RTC_LOG(LS_ERROR) << "SetLocalDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001584 return;
1585 }
Steve Anton8a006912017-12-04 15:25:56 -08001586
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001587 if (!desc) {
1588 PostSetSessionDescriptionFailure(observer, "SessionDescription is NULL.");
1589 return;
1590 }
Steve Anton8d3444d2017-10-20 15:30:51 -07001591
Steve Antona3a92c22017-12-07 10:27:41 -08001592 SdpType type = desc->GetType();
Steve Anton8d3444d2017-10-20 15:30:51 -07001593
Steve Anton8a006912017-12-04 15:25:56 -08001594 RTCError error = ApplyLocalDescription(rtc::WrapUnique(desc));
1595 // |desc| may be destroyed at this point.
1596
1597 if (!error.ok()) {
Steve Antona3a92c22017-12-07 10:27:41 -08001598 std::ostringstream oss;
1599 oss << "Failed to set local " << SdpTypeToString(type)
1600 << " sdp: " << error.message();
1601 std::string error_message = oss.str();
Steve Anton8a006912017-12-04 15:25:56 -08001602 RTC_LOG(LS_ERROR) << error_message << " (" << error.type() << ")";
1603 PostSetSessionDescriptionFailure(observer, std::move(error_message));
Steve Anton8d3444d2017-10-20 15:30:51 -07001604 return;
1605 }
Steve Anton8a006912017-12-04 15:25:56 -08001606 RTC_DCHECK(local_description());
1607
1608 PostSetSessionDescriptionSuccess(observer);
1609
1610 // According to JSEP, after setLocalDescription, changing the candidate pool
1611 // size is not allowed, and changing the set of ICE servers will not result
1612 // in new candidates being gathered.
1613 port_allocator_->FreezeCandidatePool();
1614
1615 // MaybeStartGathering needs to be called after posting
1616 // MSG_SET_SESSIONDESCRIPTION_SUCCESS, so that we don't signal any candidates
1617 // before signaling that SetLocalDescription completed.
1618 transport_controller_->MaybeStartGathering();
1619
Steve Antona3a92c22017-12-07 10:27:41 -08001620 if (local_description()->GetType() == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08001621 // TODO(deadbeef): We already had to hop to the network thread for
1622 // MaybeStartGathering...
1623 network_thread()->Invoke<void>(
1624 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
1625 port_allocator_.get()));
1626 }
1627}
1628
1629RTCError PeerConnection::ApplyLocalDescription(
1630 std::unique_ptr<SessionDescriptionInterface> desc) {
1631 RTC_DCHECK_RUN_ON(signaling_thread());
1632 RTC_DCHECK(desc);
1633
1634 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_LOCAL);
1635 if (!error.ok()) {
1636 return error;
1637 }
Steve Anton8d3444d2017-10-20 15:30:51 -07001638
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001639 // Update stats here so that we have the most recent stats for tracks and
1640 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001641 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 15:25:56 -08001642
1643 // Update the initial_offerer flag if this session is the initial_offerer.
Steve Anton3828c062017-12-06 10:34:51 -08001644 SdpType type = desc->GetType();
Steve Anton8a006912017-12-04 15:25:56 -08001645 if (!initial_offerer_.has_value()) {
Steve Anton3828c062017-12-06 10:34:51 -08001646 initial_offerer_.emplace(type == SdpType::kOffer);
Steve Anton8a006912017-12-04 15:25:56 -08001647 if (*initial_offerer_) {
1648 transport_controller_->SetIceRole(cricket::ICEROLE_CONTROLLING);
1649 } else {
1650 transport_controller_->SetIceRole(cricket::ICEROLE_CONTROLLED);
1651 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001652 }
Steve Anton8a006912017-12-04 15:25:56 -08001653
Steve Anton3828c062017-12-06 10:34:51 -08001654 if (type == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08001655 current_local_description_ = std::move(desc);
1656 pending_local_description_ = nullptr;
1657 current_remote_description_ = std::move(pending_remote_description_);
1658 } else {
1659 pending_local_description_ = std::move(desc);
1660 }
1661 // The session description to apply now must be accessed by
1662 // |local_description()|.
Henrik Boströmfdb92012017-11-09 19:55:44 +01001663 RTC_DCHECK(local_description());
deadbeefab9b2d12015-10-14 11:33:11 -07001664
Steve Anton8a006912017-12-04 15:25:56 -08001665 // Transport and Media channels will be created only when offer is set.
Steve Anton3828c062017-12-06 10:34:51 -08001666 if (type == SdpType::kOffer) {
Steve Anton8a006912017-12-04 15:25:56 -08001667 // TODO(mallinath) - Handle CreateChannel failure, as new local description
1668 // is applied. Restore back to old description.
1669 RTCError error = CreateChannels(local_description()->description());
1670 if (!error.ok()) {
1671 return error;
1672 }
1673 }
1674
1675 // Remove unused channels if MediaContentDescription is rejected.
1676 RemoveUnusedChannels(local_description()->description());
1677
Steve Anton3828c062017-12-06 10:34:51 -08001678 error = UpdateSessionState(type, cricket::CS_LOCAL);
Steve Anton8a006912017-12-04 15:25:56 -08001679 if (!error.ok()) {
1680 return error;
1681 }
1682 if (remote_description()) {
1683 // Now that we have a local description, we can push down remote candidates.
1684 UseCandidatesInSessionDescription(remote_description());
1685 }
1686
1687 pending_ice_restarts_.clear();
1688 if (session_error() != SessionError::kNone) {
1689 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
1690 }
1691
deadbeefab9b2d12015-10-14 11:33:11 -07001692 // If setting the description decided our SSL role, allocate any necessary
1693 // SCTP sids.
1694 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08001695 if (data_channel_type() == cricket::DCT_SCTP && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001696 AllocateSctpSids(role);
1697 }
1698
1699 // Update state and SSRC of local MediaStreams and DataChannels based on the
1700 // local session description.
1701 const cricket::ContentInfo* audio_content =
Henrik Boströmfdb92012017-11-09 19:55:44 +01001702 GetFirstAudioContent(local_description()->description());
deadbeefab9b2d12015-10-14 11:33:11 -07001703 if (audio_content) {
deadbeeffaac4972015-11-12 15:33:07 -08001704 if (audio_content->rejected) {
Steve Anton4171afb2017-11-20 10:20:22 -08001705 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
deadbeeffaac4972015-11-12 15:33:07 -08001706 } else {
1707 const cricket::AudioContentDescription* audio_desc =
1708 static_cast<const cricket::AudioContentDescription*>(
1709 audio_content->description);
Steve Anton4171afb2017-11-20 10:20:22 -08001710 UpdateLocalSenders(audio_desc->streams(), audio_desc->type());
deadbeeffaac4972015-11-12 15:33:07 -08001711 }
deadbeefab9b2d12015-10-14 11:33:11 -07001712 }
1713
1714 const cricket::ContentInfo* video_content =
Henrik Boströmfdb92012017-11-09 19:55:44 +01001715 GetFirstVideoContent(local_description()->description());
deadbeefab9b2d12015-10-14 11:33:11 -07001716 if (video_content) {
deadbeeffaac4972015-11-12 15:33:07 -08001717 if (video_content->rejected) {
Steve Anton4171afb2017-11-20 10:20:22 -08001718 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
deadbeeffaac4972015-11-12 15:33:07 -08001719 } else {
1720 const cricket::VideoContentDescription* video_desc =
1721 static_cast<const cricket::VideoContentDescription*>(
1722 video_content->description);
Steve Anton4171afb2017-11-20 10:20:22 -08001723 UpdateLocalSenders(video_desc->streams(), video_desc->type());
deadbeeffaac4972015-11-12 15:33:07 -08001724 }
deadbeefab9b2d12015-10-14 11:33:11 -07001725 }
1726
1727 const cricket::ContentInfo* data_content =
Henrik Boströmfdb92012017-11-09 19:55:44 +01001728 GetFirstDataContent(local_description()->description());
deadbeefab9b2d12015-10-14 11:33:11 -07001729 if (data_content) {
1730 const cricket::DataContentDescription* data_desc =
1731 static_cast<const cricket::DataContentDescription*>(
1732 data_content->description);
1733 if (rtc::starts_with(data_desc->protocol().data(),
1734 cricket::kMediaProtocolRtpPrefix)) {
1735 UpdateLocalRtpDataChannels(data_desc->streams());
1736 }
1737 }
1738
Steve Anton8a006912017-12-04 15:25:56 -08001739 return RTCError::OK();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001740}
1741
1742void PeerConnection::SetRemoteDescription(
Henrik Boströma4ecf552017-11-23 14:17:07 +00001743 SetSessionDescriptionObserver* observer,
1744 SessionDescriptionInterface* desc) {
Henrik Boström31638672017-11-23 17:48:32 +01001745 SetRemoteDescription(
1746 std::unique_ptr<SessionDescriptionInterface>(desc),
1747 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface>(
1748 new SetRemoteDescriptionObserverAdapter(this, observer)));
1749}
1750
1751void PeerConnection::SetRemoteDescription(
1752 std::unique_ptr<SessionDescriptionInterface> desc,
1753 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface> observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001754 TRACE_EVENT0("webrtc", "PeerConnection::SetRemoteDescription");
Steve Anton8a006912017-12-04 15:25:56 -08001755
nisse7ce109a2017-01-31 00:57:56 -08001756 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001757 RTC_LOG(LS_ERROR) << "SetRemoteDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001758 return;
1759 }
Steve Anton8a006912017-12-04 15:25:56 -08001760
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001761 if (!desc) {
Henrik Boström31638672017-11-23 17:48:32 +01001762 observer->OnSetRemoteDescriptionComplete(RTCError(
Steve Anton8a006912017-12-04 15:25:56 -08001763 RTCErrorType::INVALID_PARAMETER, "SessionDescription is NULL."));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001764 return;
1765 }
Steve Anton8d3444d2017-10-20 15:30:51 -07001766
Steve Antona3a92c22017-12-07 10:27:41 -08001767 const SdpType type = desc->GetType();
Steve Anton8a006912017-12-04 15:25:56 -08001768
1769 RTCError error = ApplyRemoteDescription(std::move(desc));
1770 // |desc| may be destroyed at this point.
1771
1772 if (!error.ok()) {
Steve Antona3a92c22017-12-07 10:27:41 -08001773 std::ostringstream oss;
1774 oss << "Failed to set remote " << SdpTypeToString(type)
1775 << " sdp: " << error.message();
1776 std::string error_message = oss.str();
Steve Anton8a006912017-12-04 15:25:56 -08001777 RTC_LOG(LS_ERROR) << error_message << " (" << error.type() << ")";
Henrik Boström31638672017-11-23 17:48:32 +01001778 observer->OnSetRemoteDescriptionComplete(
Steve Anton8a006912017-12-04 15:25:56 -08001779 RTCError(error.type(), std::move(error_message)));
Steve Anton8d3444d2017-10-20 15:30:51 -07001780 return;
1781 }
1782
Steve Antona3a92c22017-12-07 10:27:41 -08001783 if (remote_description()->GetType() == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08001784 // TODO(deadbeef): We already had to hop to the network thread for
1785 // MaybeStartGathering...
1786 network_thread()->Invoke<void>(
1787 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
1788 port_allocator_.get()));
1789 }
1790
1791 observer->OnSetRemoteDescriptionComplete(RTCError::OK());
1792}
1793
1794RTCError PeerConnection::ApplyRemoteDescription(
1795 std::unique_ptr<SessionDescriptionInterface> desc) {
1796 RTC_DCHECK_RUN_ON(signaling_thread());
1797 RTC_DCHECK(desc);
1798
1799 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_REMOTE);
1800 if (!error.ok()) {
1801 return error;
1802 }
1803
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001804 // Update stats here so that we have the most recent stats for tracks and
1805 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001806 stats_->UpdateStats(kStatsOutputLevelStandard);
Henrik Boström31638672017-11-23 17:48:32 +01001807 // Takes the ownership of |desc|. On success, remote_description() is updated
1808 // to reflect the description that was passed in.
Steve Anton8a006912017-12-04 15:25:56 -08001809
1810 const SessionDescriptionInterface* old_remote_description =
1811 remote_description();
1812 // Grab ownership of the description being replaced for the remainder of this
1813 // method, since it's used below as |old_remote_description|.
1814 std::unique_ptr<SessionDescriptionInterface> replaced_remote_description;
Steve Anton3828c062017-12-06 10:34:51 -08001815 SdpType type = desc->GetType();
1816 if (type == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08001817 replaced_remote_description = pending_remote_description_
1818 ? std::move(pending_remote_description_)
1819 : std::move(current_remote_description_);
1820 current_remote_description_ = std::move(desc);
1821 pending_remote_description_ = nullptr;
1822 current_local_description_ = std::move(pending_local_description_);
1823 } else {
1824 replaced_remote_description = std::move(pending_remote_description_);
1825 pending_remote_description_ = std::move(desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001826 }
Steve Anton8a006912017-12-04 15:25:56 -08001827 // The session description to apply now must be accessed by
1828 // |remote_description()|.
Henrik Boströmfdb92012017-11-09 19:55:44 +01001829 RTC_DCHECK(remote_description());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001830
Steve Anton8a006912017-12-04 15:25:56 -08001831 // Transport and Media channels will be created only when offer is set.
Steve Anton3828c062017-12-06 10:34:51 -08001832 if (type == SdpType::kOffer) {
Steve Anton8a006912017-12-04 15:25:56 -08001833 // TODO(mallinath) - Handle CreateChannel failure, as new local description
1834 // is applied. Restore back to old description.
1835 RTCError error = CreateChannels(remote_description()->description());
1836 if (!error.ok()) {
1837 return error;
1838 }
1839 }
1840
1841 // Remove unused channels if MediaContentDescription is rejected.
1842 RemoveUnusedChannels(remote_description()->description());
1843
1844 // NOTE: Candidates allocation will be initiated only when SetLocalDescription
1845 // is called.
Steve Anton3828c062017-12-06 10:34:51 -08001846 error = UpdateSessionState(type, cricket::CS_REMOTE);
Steve Anton8a006912017-12-04 15:25:56 -08001847 if (!error.ok()) {
1848 return error;
1849 }
1850
1851 if (local_description() &&
1852 !UseCandidatesInSessionDescription(remote_description())) {
1853 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidCandidates);
1854 }
1855
1856 if (old_remote_description) {
1857 for (const cricket::ContentInfo& content :
1858 old_remote_description->description()->contents()) {
1859 // Check if this new SessionDescription contains new ICE ufrag and
1860 // password that indicates the remote peer requests an ICE restart.
1861 // TODO(deadbeef): When we start storing both the current and pending
1862 // remote description, this should reset pending_ice_restarts and compare
1863 // against the current description.
1864 if (CheckForRemoteIceRestart(old_remote_description, remote_description(),
1865 content.name)) {
Steve Anton3828c062017-12-06 10:34:51 -08001866 if (type == SdpType::kOffer) {
Steve Anton8a006912017-12-04 15:25:56 -08001867 pending_ice_restarts_.insert(content.name);
1868 }
1869 } else {
1870 // We retain all received candidates only if ICE is not restarted.
1871 // When ICE is restarted, all previous candidates belong to an old
1872 // generation and should not be kept.
1873 // TODO(deadbeef): This goes against the W3C spec which says the remote
1874 // description should only contain candidates from the last set remote
1875 // description plus any candidates added since then. We should remove
1876 // this once we're sure it won't break anything.
1877 WebRtcSessionDescriptionFactory::CopyCandidatesFromSessionDescription(
1878 old_remote_description, content.name, mutable_remote_description());
1879 }
1880 }
1881 }
1882
1883 if (session_error() != SessionError::kNone) {
1884 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
1885 }
1886
1887 // Set the the ICE connection state to connecting since the connection may
1888 // become writable with peer reflexive candidates before any remote candidate
1889 // is signaled.
1890 // TODO(pthatcher): This is a short-term solution for crbug/446908. A real fix
1891 // is to have a new signal the indicates a change in checking state from the
1892 // transport and expose a new checking() member from transport that can be
1893 // read to determine the current checking state. The existing SignalConnecting
1894 // actually means "gathering candidates", so cannot be be used here.
Steve Antona3a92c22017-12-07 10:27:41 -08001895 if (remote_description()->GetType() != SdpType::kOffer &&
Steve Anton8a006912017-12-04 15:25:56 -08001896 ice_connection_state() == PeerConnectionInterface::kIceConnectionNew) {
1897 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
1898 }
1899
deadbeefab9b2d12015-10-14 11:33:11 -07001900 // If setting the description decided our SSL role, allocate any necessary
1901 // SCTP sids.
1902 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08001903 if (data_channel_type() == cricket::DCT_SCTP && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001904 AllocateSctpSids(role);
1905 }
1906
Henrik Boströmfdb92012017-11-09 19:55:44 +01001907 const cricket::ContentInfo* audio_content =
1908 GetFirstAudioContent(remote_description()->description());
1909 const cricket::ContentInfo* video_content =
1910 GetFirstVideoContent(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08001911 const cricket::AudioContentDescription* audio_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01001912 GetFirstAudioContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08001913 const cricket::VideoContentDescription* video_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01001914 GetFirstVideoContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08001915 const cricket::DataContentDescription* data_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01001916 GetFirstDataContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08001917
1918 // Check if the descriptions include streams, just in case the peer supports
1919 // MSID, but doesn't indicate so with "a=msid-semantic".
Henrik Boströmfdb92012017-11-09 19:55:44 +01001920 if (remote_description()->description()->msid_supported() ||
deadbeefbda7e0b2015-12-08 17:13:40 -08001921 (audio_desc && !audio_desc->streams().empty()) ||
1922 (video_desc && !video_desc->streams().empty())) {
1923 remote_peer_supports_msid_ = true;
1924 }
deadbeefab9b2d12015-10-14 11:33:11 -07001925
1926 // We wait to signal new streams until we finish processing the description,
1927 // since only at that point will new streams have all their tracks.
1928 rtc::scoped_refptr<StreamCollection> new_streams(StreamCollection::Create());
1929
Steve Anton8d3444d2017-10-20 15:30:51 -07001930 // TODO(steveanton): When removing RTP senders/receivers in response to a
1931 // rejected media section, there is some cleanup logic that expects the voice/
1932 // video channel to still be set. But in this method the voice/video channel
Steve Anton75737c02017-11-06 10:37:17 -08001933 // would have been destroyed by the SetRemoteDescription caller above so the
Steve Anton4171afb2017-11-20 10:20:22 -08001934 // cleanup that relies on them fails to run. The RemoveSenders calls should be
Steve Anton75737c02017-11-06 10:37:17 -08001935 // moved to right before the DestroyChannel calls to fix this.
Steve Anton8d3444d2017-10-20 15:30:51 -07001936
deadbeefab9b2d12015-10-14 11:33:11 -07001937 // Find all audio rtp streams and create corresponding remote AudioTracks
1938 // and MediaStreams.
deadbeefab9b2d12015-10-14 11:33:11 -07001939 if (audio_content) {
deadbeeffaac4972015-11-12 15:33:07 -08001940 if (audio_content->rejected) {
Steve Anton4171afb2017-11-20 10:20:22 -08001941 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
deadbeeffaac4972015-11-12 15:33:07 -08001942 } else {
deadbeefbda7e0b2015-12-08 17:13:40 -08001943 bool default_audio_track_needed =
1944 !remote_peer_supports_msid_ &&
Steve Anton4e70a722017-11-28 14:57:10 -08001945 RtpTransceiverDirectionHasSend(audio_desc->direction());
Steve Anton4171afb2017-11-20 10:20:22 -08001946 UpdateRemoteSendersList(GetActiveStreams(audio_desc),
deadbeefbda7e0b2015-12-08 17:13:40 -08001947 default_audio_track_needed, audio_desc->type(),
deadbeeffaac4972015-11-12 15:33:07 -08001948 new_streams);
deadbeeffaac4972015-11-12 15:33:07 -08001949 }
deadbeefab9b2d12015-10-14 11:33:11 -07001950 }
1951
1952 // Find all video rtp streams and create corresponding remote VideoTracks
1953 // and MediaStreams.
deadbeefab9b2d12015-10-14 11:33:11 -07001954 if (video_content) {
deadbeeffaac4972015-11-12 15:33:07 -08001955 if (video_content->rejected) {
Steve Anton4171afb2017-11-20 10:20:22 -08001956 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
deadbeeffaac4972015-11-12 15:33:07 -08001957 } else {
deadbeefbda7e0b2015-12-08 17:13:40 -08001958 bool default_video_track_needed =
1959 !remote_peer_supports_msid_ &&
Steve Anton4e70a722017-11-28 14:57:10 -08001960 RtpTransceiverDirectionHasSend(video_desc->direction());
Steve Anton4171afb2017-11-20 10:20:22 -08001961 UpdateRemoteSendersList(GetActiveStreams(video_desc),
deadbeefbda7e0b2015-12-08 17:13:40 -08001962 default_video_track_needed, video_desc->type(),
deadbeeffaac4972015-11-12 15:33:07 -08001963 new_streams);
deadbeeffaac4972015-11-12 15:33:07 -08001964 }
deadbeefab9b2d12015-10-14 11:33:11 -07001965 }
1966
1967 // Update the DataChannels with the information from the remote peer.
deadbeefbda7e0b2015-12-08 17:13:40 -08001968 if (data_desc) {
1969 if (rtc::starts_with(data_desc->protocol().data(),
deadbeefab9b2d12015-10-14 11:33:11 -07001970 cricket::kMediaProtocolRtpPrefix)) {
deadbeefbda7e0b2015-12-08 17:13:40 -08001971 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
deadbeefab9b2d12015-10-14 11:33:11 -07001972 }
1973 }
1974
1975 // Iterate new_streams and notify the observer about new MediaStreams.
1976 for (size_t i = 0; i < new_streams->count(); ++i) {
1977 MediaStreamInterface* new_stream = new_streams->at(i);
1978 stats_->AddStream(new_stream);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07001979 observer_->OnAddStream(
1980 rtc::scoped_refptr<MediaStreamInterface>(new_stream));
deadbeefab9b2d12015-10-14 11:33:11 -07001981 }
1982
deadbeefbda7e0b2015-12-08 17:13:40 -08001983 UpdateEndedRemoteMediaStreams();
deadbeefab9b2d12015-10-14 11:33:11 -07001984
Steve Anton8a006912017-12-04 15:25:56 -08001985 return RTCError::OK();
deadbeeffc648b62015-10-13 16:42:33 -07001986}
1987
Steve Antoned10bd92017-12-05 10:52:59 -08001988const cricket::ContentInfo* PeerConnection::FindMediaSectionForTransceiver(
1989 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1990 transceiver,
1991 const SessionDescriptionInterface* sdesc) const {
1992 RTC_DCHECK(transceiver);
1993 RTC_DCHECK(sdesc);
1994 if (IsUnifiedPlan()) {
1995 if (!transceiver->internal()->mid()) {
1996 // This transceiver is not associated with a media section yet.
1997 return nullptr;
1998 }
1999 return sdesc->description()->GetContentByName(
2000 *transceiver->internal()->mid());
2001 } else {
2002 // Plan B only allows at most one audio and one video section, so use the
2003 // first media section of that type.
2004 return cricket::GetFirstMediaContent(sdesc->description()->contents(),
2005 transceiver->internal()->media_type());
2006 }
2007}
2008
deadbeef46c73892016-11-16 19:42:04 -08002009PeerConnectionInterface::RTCConfiguration PeerConnection::GetConfiguration() {
2010 return configuration_;
2011}
2012
deadbeef293e9262017-01-11 12:28:30 -08002013bool PeerConnection::SetConfiguration(const RTCConfiguration& configuration,
2014 RTCError* error) {
Peter Boström1a9d6152015-12-08 22:15:17 +01002015 TRACE_EVENT0("webrtc", "PeerConnection::SetConfiguration");
deadbeef6de92f92016-12-12 18:49:32 -08002016
Steve Anton75737c02017-11-06 10:37:17 -08002017 if (local_description() && configuration.ice_candidate_pool_size !=
2018 configuration_.ice_candidate_pool_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002019 RTC_LOG(LS_ERROR) << "Can't change candidate pool size after calling "
2020 "SetLocalDescription.";
deadbeef293e9262017-01-11 12:28:30 -08002021 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00002022 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002023
deadbeef293e9262017-01-11 12:28:30 -08002024 // The simplest (and most future-compatible) way to tell if the config was
2025 // modified in an invalid way is to copy each property we do support
2026 // modifying, then use operator==. There are far more properties we don't
2027 // support modifying than those we do, and more could be added.
2028 RTCConfiguration modified_config = configuration_;
2029 modified_config.servers = configuration.servers;
2030 modified_config.type = configuration.type;
2031 modified_config.ice_candidate_pool_size =
2032 configuration.ice_candidate_pool_size;
2033 modified_config.prune_turn_ports = configuration.prune_turn_ports;
skvladd1f5fda2017-02-03 16:54:05 -08002034 modified_config.ice_check_min_interval = configuration.ice_check_min_interval;
Jonas Orelandbdcee282017-10-10 14:01:40 +02002035 modified_config.turn_customizer = configuration.turn_customizer;
deadbeef293e9262017-01-11 12:28:30 -08002036 if (configuration != modified_config) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002037 RTC_LOG(LS_ERROR) << "Modifying the configuration in an unsupported way.";
deadbeef293e9262017-01-11 12:28:30 -08002038 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
2039 }
2040
Steve Anton038834f2017-07-14 15:59:59 -07002041 // Validate the modified configuration.
2042 RTCError validate_error = ValidateConfiguration(modified_config);
2043 if (!validate_error.ok()) {
2044 return SafeSetError(std::move(validate_error), error);
2045 }
2046
deadbeef293e9262017-01-11 12:28:30 -08002047 // Note that this isn't possible through chromium, since it's an unsigned
2048 // short in WebIDL.
2049 if (configuration.ice_candidate_pool_size < 0 ||
2050 configuration.ice_candidate_pool_size > UINT16_MAX) {
2051 return SafeSetError(RTCErrorType::INVALID_RANGE, error);
2052 }
2053
2054 // Parse ICE servers before hopping to network thread.
2055 cricket::ServerAddresses stun_servers;
2056 std::vector<cricket::RelayServerConfig> turn_servers;
2057 RTCErrorType parse_error =
2058 ParseIceServers(configuration.servers, &stun_servers, &turn_servers);
2059 if (parse_error != RTCErrorType::NONE) {
2060 return SafeSetError(parse_error, error);
2061 }
2062
2063 // In theory this shouldn't fail.
2064 if (!network_thread()->Invoke<bool>(
2065 RTC_FROM_HERE,
2066 rtc::Bind(&PeerConnection::ReconfigurePortAllocator_n, this,
2067 stun_servers, turn_servers, modified_config.type,
2068 modified_config.ice_candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02002069 modified_config.prune_turn_ports,
2070 modified_config.turn_customizer))) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002071 RTC_LOG(LS_ERROR) << "Failed to apply configuration to PortAllocator.";
deadbeef293e9262017-01-11 12:28:30 -08002072 return SafeSetError(RTCErrorType::INTERNAL_ERROR, error);
2073 }
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07002074
deadbeefd1a38b52016-12-10 13:15:33 -08002075 // As described in JSEP, calling setConfiguration with new ICE servers or
2076 // candidate policy must set a "needs-ice-restart" bit so that the next offer
2077 // triggers an ICE restart which will pick up the changes.
deadbeef293e9262017-01-11 12:28:30 -08002078 if (modified_config.servers != configuration_.servers ||
2079 modified_config.type != configuration_.type ||
2080 modified_config.prune_turn_ports != configuration_.prune_turn_ports) {
Steve Antond25da372017-11-06 14:50:29 -08002081 transport_controller_->SetNeedsIceRestartFlag();
deadbeefd1a38b52016-12-10 13:15:33 -08002082 }
skvladd1f5fda2017-02-03 16:54:05 -08002083
2084 if (modified_config.ice_check_min_interval !=
2085 configuration_.ice_check_min_interval) {
Steve Antond25da372017-11-06 14:50:29 -08002086 transport_controller_->SetIceConfig(ParseIceConfig(modified_config));
skvladd1f5fda2017-02-03 16:54:05 -08002087 }
2088
deadbeef293e9262017-01-11 12:28:30 -08002089 configuration_ = modified_config;
2090 return SafeSetError(RTCErrorType::NONE, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00002091}
2092
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002093bool PeerConnection::AddIceCandidate(
2094 const IceCandidateInterface* ice_candidate) {
Peter Boström1a9d6152015-12-08 22:15:17 +01002095 TRACE_EVENT0("webrtc", "PeerConnection::AddIceCandidate");
zhihuang29ff8442016-07-27 11:07:25 -07002096 if (IsClosed()) {
2097 return false;
2098 }
Steve Antond25da372017-11-06 14:50:29 -08002099
2100 if (!remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002101 RTC_LOG(LS_ERROR) << "ProcessIceMessage: ICE candidates can't be added "
2102 << "without any remote session description.";
Steve Antond25da372017-11-06 14:50:29 -08002103 return false;
2104 }
2105
2106 if (!ice_candidate) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002107 RTC_LOG(LS_ERROR) << "ProcessIceMessage: Candidate is NULL.";
Steve Antond25da372017-11-06 14:50:29 -08002108 return false;
2109 }
2110
2111 bool valid = false;
2112 bool ready = ReadyToUseRemoteCandidate(ice_candidate, nullptr, &valid);
2113 if (!valid) {
2114 return false;
2115 }
2116
2117 // Add this candidate to the remote session description.
2118 if (!mutable_remote_description()->AddCandidate(ice_candidate)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002119 RTC_LOG(LS_ERROR) << "ProcessIceMessage: Candidate cannot be used.";
Steve Antond25da372017-11-06 14:50:29 -08002120 return false;
2121 }
2122
2123 if (ready) {
2124 return UseCandidate(ice_candidate);
2125 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002126 RTC_LOG(LS_INFO) << "ProcessIceMessage: Not ready to use candidate.";
Steve Antond25da372017-11-06 14:50:29 -08002127 return true;
2128 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002129}
2130
Honghai Zhang7fb69db2016-03-14 11:59:18 -07002131bool PeerConnection::RemoveIceCandidates(
2132 const std::vector<cricket::Candidate>& candidates) {
2133 TRACE_EVENT0("webrtc", "PeerConnection::RemoveIceCandidates");
Steve Antond25da372017-11-06 14:50:29 -08002134 if (!remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002135 RTC_LOG(LS_ERROR) << "RemoveRemoteIceCandidates: ICE candidates can't be "
2136 << "removed without any remote session description.";
Steve Antond25da372017-11-06 14:50:29 -08002137 return false;
2138 }
2139
2140 if (candidates.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002141 RTC_LOG(LS_ERROR) << "RemoveRemoteIceCandidates: candidates are empty.";
Steve Antond25da372017-11-06 14:50:29 -08002142 return false;
2143 }
2144
2145 size_t number_removed =
2146 mutable_remote_description()->RemoveCandidates(candidates);
2147 if (number_removed != candidates.size()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002148 RTC_LOG(LS_ERROR)
2149 << "RemoveRemoteIceCandidates: Failed to remove candidates. "
2150 << "Requested " << candidates.size() << " but only " << number_removed
2151 << " are removed.";
Steve Antond25da372017-11-06 14:50:29 -08002152 }
2153
2154 // Remove the candidates from the transport controller.
2155 std::string error;
2156 bool res = transport_controller_->RemoveRemoteCandidates(candidates, &error);
2157 if (!res && !error.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002158 RTC_LOG(LS_ERROR) << "Error when removing remote candidates: " << error;
Steve Antond25da372017-11-06 14:50:29 -08002159 }
2160 return true;
Honghai Zhang7fb69db2016-03-14 11:59:18 -07002161}
2162
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00002163void PeerConnection::RegisterUMAObserver(UMAObserver* observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +01002164 TRACE_EVENT0("webrtc", "PeerConnection::RegisterUmaObserver");
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00002165 uma_observer_ = observer;
guoweis@webrtc.org7169afd2014-12-04 17:59:29 +00002166
Steve Anton75737c02017-11-06 10:37:17 -08002167 if (transport_controller()) {
2168 transport_controller()->SetMetricsObserver(uma_observer_);
guoweis@webrtc.org7169afd2014-12-04 17:59:29 +00002169 }
2170
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00002171 // Send information about IPv4/IPv6 status.
deadbeef293e9262017-01-11 12:28:30 -08002172 if (uma_observer_) {
Honghai Zhangd93f50c2016-10-05 11:47:22 -07002173 port_allocator_->SetMetricsObserver(uma_observer_);
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00002174 if (port_allocator_->flags() & cricket::PORTALLOCATOR_ENABLE_IPV6) {
Guo-wei Shiehdfbe6792015-09-03 17:12:07 -07002175 uma_observer_->IncrementEnumCounter(
2176 kEnumCounterAddressFamily, kPeerConnection_IPv6,
2177 kPeerConnectionAddressFamilyCounter_Max);
mallinath@webrtc.orgb445f262014-05-23 22:19:37 +00002178 } else {
Guo-wei Shiehdfbe6792015-09-03 17:12:07 -07002179 uma_observer_->IncrementEnumCounter(
2180 kEnumCounterAddressFamily, kPeerConnection_IPv4,
2181 kPeerConnectionAddressFamilyCounter_Max);
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00002182 }
2183 }
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00002184}
2185
zstein4b979802017-06-02 14:37:37 -07002186RTCError PeerConnection::SetBitrate(const BitrateParameters& bitrate) {
Steve Anton978b8762017-09-29 12:15:02 -07002187 if (!worker_thread()->IsCurrent()) {
2188 return worker_thread()->Invoke<RTCError>(
zstein4b979802017-06-02 14:37:37 -07002189 RTC_FROM_HERE, rtc::Bind(&PeerConnection::SetBitrate, this, bitrate));
2190 }
2191
2192 const bool has_min = static_cast<bool>(bitrate.min_bitrate_bps);
2193 const bool has_current = static_cast<bool>(bitrate.current_bitrate_bps);
2194 const bool has_max = static_cast<bool>(bitrate.max_bitrate_bps);
2195 if (has_min && *bitrate.min_bitrate_bps < 0) {
2196 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2197 "min_bitrate_bps <= 0");
2198 }
2199 if (has_current) {
2200 if (has_min && *bitrate.current_bitrate_bps < *bitrate.min_bitrate_bps) {
2201 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2202 "current_bitrate_bps < min_bitrate_bps");
2203 } else if (*bitrate.current_bitrate_bps < 0) {
2204 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2205 "curent_bitrate_bps < 0");
2206 }
2207 }
2208 if (has_max) {
2209 if (has_current &&
2210 *bitrate.max_bitrate_bps < *bitrate.current_bitrate_bps) {
2211 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2212 "max_bitrate_bps < current_bitrate_bps");
2213 } else if (has_min && *bitrate.max_bitrate_bps < *bitrate.min_bitrate_bps) {
2214 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2215 "max_bitrate_bps < min_bitrate_bps");
2216 } else if (*bitrate.max_bitrate_bps < 0) {
2217 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2218 "max_bitrate_bps < 0");
2219 }
2220 }
2221
2222 Call::Config::BitrateConfigMask mask;
2223 mask.min_bitrate_bps = bitrate.min_bitrate_bps;
2224 mask.start_bitrate_bps = bitrate.current_bitrate_bps;
2225 mask.max_bitrate_bps = bitrate.max_bitrate_bps;
2226
2227 RTC_DCHECK(call_.get());
2228 call_->SetBitrateConfigMask(mask);
2229
2230 return RTCError::OK();
2231}
2232
Alex Narest78609d52017-10-20 10:37:47 +02002233void PeerConnection::SetBitrateAllocationStrategy(
2234 std::unique_ptr<rtc::BitrateAllocationStrategy>
2235 bitrate_allocation_strategy) {
2236 rtc::Thread* worker_thread = factory_->worker_thread();
2237 if (!worker_thread->IsCurrent()) {
2238 rtc::BitrateAllocationStrategy* strategy_raw =
2239 bitrate_allocation_strategy.release();
2240 auto functor = [this, strategy_raw]() {
2241 call_->SetBitrateAllocationStrategy(
2242 rtc::WrapUnique<rtc::BitrateAllocationStrategy>(strategy_raw));
2243 };
2244 worker_thread->Invoke<void>(RTC_FROM_HERE, functor);
2245 return;
2246 }
2247 RTC_DCHECK(call_.get());
2248 call_->SetBitrateAllocationStrategy(std::move(bitrate_allocation_strategy));
2249}
2250
henrika5f6bf242017-11-01 11:06:56 +01002251void PeerConnection::SetAudioPlayout(bool playout) {
2252 if (!worker_thread()->IsCurrent()) {
2253 worker_thread()->Invoke<void>(
2254 RTC_FROM_HERE,
2255 rtc::Bind(&PeerConnection::SetAudioPlayout, this, playout));
2256 return;
2257 }
2258 auto audio_state =
2259 factory_->channel_manager()->media_engine()->GetAudioState();
2260 audio_state->SetPlayout(playout);
2261}
2262
2263void PeerConnection::SetAudioRecording(bool recording) {
2264 if (!worker_thread()->IsCurrent()) {
2265 worker_thread()->Invoke<void>(
2266 RTC_FROM_HERE,
2267 rtc::Bind(&PeerConnection::SetAudioRecording, this, recording));
2268 return;
2269 }
2270 auto audio_state =
2271 factory_->channel_manager()->media_engine()->GetAudioState();
2272 audio_state->SetRecording(recording);
2273}
2274
Steve Anton8c0f7a72017-10-03 10:03:10 -07002275std::unique_ptr<rtc::SSLCertificate>
2276PeerConnection::GetRemoteAudioSSLCertificate() {
Steve Anton75737c02017-11-06 10:37:17 -08002277 if (!voice_channel()) {
Steve Anton8c0f7a72017-10-03 10:03:10 -07002278 return nullptr;
2279 }
Steve Anton75737c02017-11-06 10:37:17 -08002280 return GetRemoteSSLCertificate(voice_channel()->transport_name());
Steve Anton8c0f7a72017-10-03 10:03:10 -07002281}
2282
ivoc14d5dbe2016-07-04 07:06:55 -07002283bool PeerConnection::StartRtcEventLog(rtc::PlatformFile file,
2284 int64_t max_size_bytes) {
Elad Alon99c3fe52017-10-13 16:29:40 +02002285 // TODO(eladalon): It would be better to not allow negative values into PC.
2286 const size_t max_size = (max_size_bytes < 0)
2287 ? RtcEventLog::kUnlimitedOutput
2288 : rtc::saturated_cast<size_t>(max_size_bytes);
2289 return StartRtcEventLog(
Bjorn Tereliusde939432017-11-20 17:38:14 +01002290 rtc::MakeUnique<RtcEventLogOutputFile>(file, max_size),
2291 webrtc::RtcEventLog::kImmediateOutput);
Elad Alon99c3fe52017-10-13 16:29:40 +02002292}
2293
Bjorn Tereliusde939432017-11-20 17:38:14 +01002294bool PeerConnection::StartRtcEventLog(std::unique_ptr<RtcEventLogOutput> output,
2295 int64_t output_period_ms) {
Karl Wibergd6b48192017-10-16 23:01:06 +02002296 // TODO(eladalon): In C++14, this can be done with a lambda.
2297 struct Functor {
Bjorn Tereliusde939432017-11-20 17:38:14 +01002298 bool operator()() {
2299 return pc->StartRtcEventLog_w(std::move(output), output_period_ms);
2300 }
Karl Wibergd6b48192017-10-16 23:01:06 +02002301 PeerConnection* const pc;
2302 std::unique_ptr<RtcEventLogOutput> output;
Bjorn Tereliusde939432017-11-20 17:38:14 +01002303 const int64_t output_period_ms;
Elad Alon99c3fe52017-10-13 16:29:40 +02002304 };
Bjorn Tereliusde939432017-11-20 17:38:14 +01002305 return worker_thread()->Invoke<bool>(
2306 RTC_FROM_HERE, Functor{this, std::move(output), output_period_ms});
ivoc14d5dbe2016-07-04 07:06:55 -07002307}
2308
2309void PeerConnection::StopRtcEventLog() {
Steve Anton978b8762017-09-29 12:15:02 -07002310 worker_thread()->Invoke<void>(
ivoc14d5dbe2016-07-04 07:06:55 -07002311 RTC_FROM_HERE, rtc::Bind(&PeerConnection::StopRtcEventLog_w, this));
2312}
2313
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002314const SessionDescriptionInterface* PeerConnection::local_description() const {
Steve Anton75737c02017-11-06 10:37:17 -08002315 return pending_local_description_ ? pending_local_description_.get()
2316 : current_local_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002317}
2318
2319const SessionDescriptionInterface* PeerConnection::remote_description() const {
Steve Anton75737c02017-11-06 10:37:17 -08002320 return pending_remote_description_ ? pending_remote_description_.get()
2321 : current_remote_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002322}
2323
deadbeeffe4a8a42016-12-20 17:56:17 -08002324const SessionDescriptionInterface* PeerConnection::current_local_description()
2325 const {
Steve Anton75737c02017-11-06 10:37:17 -08002326 return current_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08002327}
2328
2329const SessionDescriptionInterface* PeerConnection::current_remote_description()
2330 const {
Steve Anton75737c02017-11-06 10:37:17 -08002331 return current_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08002332}
2333
2334const SessionDescriptionInterface* PeerConnection::pending_local_description()
2335 const {
Steve Anton75737c02017-11-06 10:37:17 -08002336 return pending_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08002337}
2338
2339const SessionDescriptionInterface* PeerConnection::pending_remote_description()
2340 const {
Steve Anton75737c02017-11-06 10:37:17 -08002341 return pending_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08002342}
2343
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002344void PeerConnection::Close() {
Peter Boström1a9d6152015-12-08 22:15:17 +01002345 TRACE_EVENT0("webrtc", "PeerConnection::Close");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002346 // Update stats here so that we have the most recent stats for tracks and
2347 // streams before the channels are closed.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00002348 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002349
Steve Anton75737c02017-11-06 10:37:17 -08002350 ChangeSignalingState(PeerConnectionInterface::kClosed);
Steve Anton3fe1b152017-12-12 10:20:08 -08002351
Steve Anton8af21862017-12-15 11:20:13 -08002352 for (auto transceiver : transceivers_) {
2353 transceiver->Stop();
2354 }
2355 DestroyAllChannels();
Steve Anton75737c02017-11-06 10:37:17 -08002356
deadbeef42a42632017-03-10 15:18:00 -08002357 network_thread()->Invoke<void>(
2358 RTC_FROM_HERE,
2359 rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
2360 port_allocator_.get()));
nisseeaabdf62017-05-05 02:23:02 -07002361
Steve Anton978b8762017-09-29 12:15:02 -07002362 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
eladalon248fd4f2017-09-06 05:18:15 -07002363 call_.reset();
2364 // The event log must outlive call (and any other object that uses it).
2365 event_log_.reset();
2366 });
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002367}
2368
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002369void PeerConnection::OnMessage(rtc::Message* msg) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002370 switch (msg->message_id) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002371 case MSG_SET_SESSIONDESCRIPTION_SUCCESS: {
2372 SetSessionDescriptionMsg* param =
2373 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
2374 param->observer->OnSuccess();
2375 delete param;
2376 break;
2377 }
2378 case MSG_SET_SESSIONDESCRIPTION_FAILED: {
2379 SetSessionDescriptionMsg* param =
2380 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
2381 param->observer->OnFailure(param->error);
2382 delete param;
2383 break;
2384 }
deadbeefab9b2d12015-10-14 11:33:11 -07002385 case MSG_CREATE_SESSIONDESCRIPTION_FAILED: {
2386 CreateSessionDescriptionMsg* param =
2387 static_cast<CreateSessionDescriptionMsg*>(msg->pdata);
2388 param->observer->OnFailure(param->error);
2389 delete param;
2390 break;
2391 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002392 case MSG_GETSTATS: {
2393 GetStatsMsg* param = static_cast<GetStatsMsg*>(msg->pdata);
nissee8abe3e2017-01-18 05:00:34 -08002394 StatsReports reports;
2395 stats_->GetStats(param->track, &reports);
2396 param->observer->OnComplete(reports);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002397 delete param;
2398 break;
2399 }
deadbeefbd292462015-12-14 18:15:29 -08002400 case MSG_FREE_DATACHANNELS: {
2401 sctp_data_channels_to_free_.clear();
2402 break;
2403 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002404 default:
nisseeb4ca4e2017-01-12 02:24:27 -08002405 RTC_NOTREACHED() << "Not implemented";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002406 break;
2407 }
2408}
2409
Steve Anton4171afb2017-11-20 10:20:22 -08002410void PeerConnection::CreateAudioReceiver(
2411 MediaStreamInterface* stream,
2412 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01002413 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
2414 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
zhihuang81c3a032016-11-17 12:06:24 -08002415 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
2416 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
deadbeefe814a0d2017-02-25 18:15:09 -08002417 signaling_thread(),
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01002418 new AudioRtpReceiver(remote_sender_info.sender_id, streams,
Steve Anton4171afb2017-11-20 10:20:22 -08002419 remote_sender_info.first_ssrc, voice_channel()));
deadbeefe814a0d2017-02-25 18:15:09 -08002420 stream->AddTrack(
2421 static_cast<AudioTrackInterface*>(receiver->internal()->track().get()));
Steve Anton4171afb2017-11-20 10:20:22 -08002422 GetAudioTransceiver()->internal()->AddReceiver(receiver);
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01002423 observer_->OnAddTrack(receiver, std::move(streams));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002424}
2425
Steve Anton4171afb2017-11-20 10:20:22 -08002426void PeerConnection::CreateVideoReceiver(
2427 MediaStreamInterface* stream,
2428 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01002429 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
2430 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
zhihuang81c3a032016-11-17 12:06:24 -08002431 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
2432 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
Steve Anton4171afb2017-11-20 10:20:22 -08002433 signaling_thread(),
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01002434 new VideoRtpReceiver(remote_sender_info.sender_id, streams,
2435 worker_thread(), remote_sender_info.first_ssrc,
2436 video_channel()));
deadbeefe814a0d2017-02-25 18:15:09 -08002437 stream->AddTrack(
2438 static_cast<VideoTrackInterface*>(receiver->internal()->track().get()));
Steve Anton4171afb2017-11-20 10:20:22 -08002439 GetVideoTransceiver()->internal()->AddReceiver(receiver);
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01002440 observer_->OnAddTrack(receiver, std::move(streams));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002441}
2442
deadbeef70ab1a12015-09-28 16:53:55 -07002443// TODO(deadbeef): Keep RtpReceivers around even if track goes away in remote
2444// description.
Henrik Boström933d8b02017-10-10 10:05:16 -07002445rtc::scoped_refptr<RtpReceiverInterface> PeerConnection::RemoveAndStopReceiver(
Steve Anton4171afb2017-11-20 10:20:22 -08002446 const RtpSenderInfo& remote_sender_info) {
2447 auto receiver = FindReceiverById(remote_sender_info.sender_id);
2448 if (!receiver) {
2449 RTC_LOG(LS_WARNING) << "RtpReceiver for track with id "
2450 << remote_sender_info.sender_id << " doesn't exist.";
Henrik Boström933d8b02017-10-10 10:05:16 -07002451 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07002452 }
Steve Anton4171afb2017-11-20 10:20:22 -08002453 if (receiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
2454 GetAudioTransceiver()->internal()->RemoveReceiver(receiver);
2455 } else {
2456 GetVideoTransceiver()->internal()->RemoveReceiver(receiver);
2457 }
Henrik Boström933d8b02017-10-10 10:05:16 -07002458 return receiver;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002459}
2460
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002461void PeerConnection::AddAudioTrack(AudioTrackInterface* track,
2462 MediaStreamInterface* stream) {
2463 RTC_DCHECK(!IsClosed());
2464 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08002465 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002466 // We already have a sender for this track, so just change the stream_id
2467 // so that it's correct in the next call to CreateOffer.
Steve Anton4171afb2017-11-20 10:20:22 -08002468 sender->internal()->set_stream_id(stream->label());
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002469 return;
2470 }
2471
2472 // Normal case; we've never seen this track before.
2473 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender =
2474 RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
2475 signaling_thread(),
Steve Anton75737c02017-11-06 10:37:17 -08002476 new AudioRtpSender(track, {stream->label()}, voice_channel(),
2477 stats_.get()));
Steve Anton4171afb2017-11-20 10:20:22 -08002478 GetAudioTransceiver()->internal()->AddSender(new_sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002479 // If the sender has already been configured in SDP, we call SetSsrc,
2480 // which will connect the sender to the underlying transport. This can
2481 // occur if a local session description that contains the ID of the sender
2482 // is set before AddStream is called. It can also occur if the local
2483 // session description is not changed and RemoveStream is called, and
2484 // later AddStream is called again with the same stream.
Steve Anton4171afb2017-11-20 10:20:22 -08002485 const RtpSenderInfo* sender_info =
2486 FindSenderInfo(local_audio_sender_infos_, stream->label(), track->id());
2487 if (sender_info) {
2488 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002489 }
2490}
2491
2492// TODO(deadbeef): Don't destroy RtpSenders here; they should be kept around
2493// indefinitely, when we have unified plan SDP.
2494void PeerConnection::RemoveAudioTrack(AudioTrackInterface* track,
2495 MediaStreamInterface* stream) {
2496 RTC_DCHECK(!IsClosed());
2497 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08002498 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002499 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
2500 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002501 return;
2502 }
Steve Anton4171afb2017-11-20 10:20:22 -08002503 GetAudioTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002504}
2505
2506void PeerConnection::AddVideoTrack(VideoTrackInterface* track,
2507 MediaStreamInterface* stream) {
2508 RTC_DCHECK(!IsClosed());
2509 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08002510 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002511 // We already have a sender for this track, so just change the stream_id
2512 // so that it's correct in the next call to CreateOffer.
Steve Anton4171afb2017-11-20 10:20:22 -08002513 sender->internal()->set_stream_id(stream->label());
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002514 return;
2515 }
2516
2517 // Normal case; we've never seen this track before.
2518 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender =
2519 RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton75737c02017-11-06 10:37:17 -08002520 signaling_thread(),
2521 new VideoRtpSender(track, {stream->label()}, video_channel()));
Steve Anton4171afb2017-11-20 10:20:22 -08002522 GetVideoTransceiver()->internal()->AddSender(new_sender);
2523 const RtpSenderInfo* sender_info =
2524 FindSenderInfo(local_video_sender_infos_, stream->label(), track->id());
2525 if (sender_info) {
2526 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002527 }
2528}
2529
2530void PeerConnection::RemoveVideoTrack(VideoTrackInterface* track,
2531 MediaStreamInterface* stream) {
2532 RTC_DCHECK(!IsClosed());
2533 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08002534 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002535 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
2536 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002537 return;
2538 }
Steve Anton4171afb2017-11-20 10:20:22 -08002539 GetVideoTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002540}
2541
Steve Antonba818672017-11-06 10:21:57 -08002542void PeerConnection::SetIceConnectionState(IceConnectionState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07002543 RTC_DCHECK(signaling_thread()->IsCurrent());
Steve Antonba818672017-11-06 10:21:57 -08002544 if (ice_connection_state_ == new_state) {
2545 return;
2546 }
2547
deadbeefcbecd352015-09-23 11:50:27 -07002548 // After transitioning to "closed", ignore any additional states from
Steve Antonba818672017-11-06 10:21:57 -08002549 // TransportController (such as "disconnected").
deadbeefab9b2d12015-10-14 11:33:11 -07002550 if (IsClosed()) {
deadbeefcbecd352015-09-23 11:50:27 -07002551 return;
2552 }
Steve Antonba818672017-11-06 10:21:57 -08002553
Mirko Bonadei675513b2017-11-09 11:09:25 +01002554 RTC_LOG(LS_INFO) << "Changing IceConnectionState " << ice_connection_state_
2555 << " => " << new_state;
Steve Antonba818672017-11-06 10:21:57 -08002556 RTC_DCHECK(ice_connection_state_ !=
2557 PeerConnectionInterface::kIceConnectionClosed);
2558
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002559 ice_connection_state_ = new_state;
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00002560 observer_->OnIceConnectionChange(ice_connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002561}
2562
2563void PeerConnection::OnIceGatheringChange(
2564 PeerConnectionInterface::IceGatheringState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07002565 RTC_DCHECK(signaling_thread()->IsCurrent());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002566 if (IsClosed()) {
2567 return;
2568 }
2569 ice_gathering_state_ = new_state;
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00002570 observer_->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002571}
2572
jbauch81bf7b02017-03-25 08:31:12 -07002573void PeerConnection::OnIceCandidate(
2574 std::unique_ptr<IceCandidateInterface> candidate) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07002575 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07002576 if (IsClosed()) {
2577 return;
2578 }
jbauch81bf7b02017-03-25 08:31:12 -07002579 observer_->OnIceCandidate(candidate.get());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002580}
2581
Honghai Zhang7fb69db2016-03-14 11:59:18 -07002582void PeerConnection::OnIceCandidatesRemoved(
2583 const std::vector<cricket::Candidate>& candidates) {
2584 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07002585 if (IsClosed()) {
2586 return;
2587 }
Honghai Zhang7fb69db2016-03-14 11:59:18 -07002588 observer_->OnIceCandidatesRemoved(candidates);
2589}
2590
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002591void PeerConnection::ChangeSignalingState(
2592 PeerConnectionInterface::SignalingState signaling_state) {
Steve Antonba818672017-11-06 10:21:57 -08002593 RTC_DCHECK(signaling_thread()->IsCurrent());
2594 if (signaling_state_ == signaling_state) {
2595 return;
2596 }
Mirko Bonadei675513b2017-11-09 11:09:25 +01002597 RTC_LOG(LS_INFO) << "Session: " << session_id() << " Old state: "
2598 << GetSignalingStateString(signaling_state_)
2599 << " New state: "
2600 << GetSignalingStateString(signaling_state);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002601 signaling_state_ = signaling_state;
2602 if (signaling_state == kClosed) {
2603 ice_connection_state_ = kIceConnectionClosed;
2604 observer_->OnIceConnectionChange(ice_connection_state_);
2605 if (ice_gathering_state_ != kIceGatheringComplete) {
2606 ice_gathering_state_ = kIceGatheringComplete;
2607 observer_->OnIceGatheringChange(ice_gathering_state_);
2608 }
2609 }
2610 observer_->OnSignalingChange(signaling_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002611}
2612
deadbeefeb459812015-12-15 19:24:43 -08002613void PeerConnection::OnAudioTrackAdded(AudioTrackInterface* track,
2614 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07002615 if (IsClosed()) {
2616 return;
2617 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002618 AddAudioTrack(track, stream);
2619 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08002620}
2621
deadbeefeb459812015-12-15 19:24:43 -08002622void PeerConnection::OnAudioTrackRemoved(AudioTrackInterface* track,
2623 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07002624 if (IsClosed()) {
2625 return;
2626 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002627 RemoveAudioTrack(track, stream);
2628 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08002629}
2630
2631void PeerConnection::OnVideoTrackAdded(VideoTrackInterface* track,
2632 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07002633 if (IsClosed()) {
2634 return;
2635 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002636 AddVideoTrack(track, stream);
2637 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08002638}
2639
2640void PeerConnection::OnVideoTrackRemoved(VideoTrackInterface* track,
2641 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07002642 if (IsClosed()) {
2643 return;
2644 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002645 RemoveVideoTrack(track, stream);
2646 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08002647}
2648
Henrik Boström31638672017-11-23 17:48:32 +01002649void PeerConnection::PostSetSessionDescriptionSuccess(
2650 SetSessionDescriptionObserver* observer) {
2651 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
2652 signaling_thread()->Post(RTC_FROM_HERE, this,
2653 MSG_SET_SESSIONDESCRIPTION_SUCCESS, msg);
2654}
2655
deadbeefab9b2d12015-10-14 11:33:11 -07002656void PeerConnection::PostSetSessionDescriptionFailure(
2657 SetSessionDescriptionObserver* observer,
2658 const std::string& error) {
2659 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
2660 msg->error = error;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07002661 signaling_thread()->Post(RTC_FROM_HERE, this,
2662 MSG_SET_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07002663}
2664
2665void PeerConnection::PostCreateSessionDescriptionFailure(
2666 CreateSessionDescriptionObserver* observer,
2667 const std::string& error) {
2668 CreateSessionDescriptionMsg* msg = new CreateSessionDescriptionMsg(observer);
2669 msg->error = error;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07002670 signaling_thread()->Post(RTC_FROM_HERE, this,
2671 MSG_CREATE_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07002672}
2673
zhihuang1c378ed2017-08-17 14:10:50 -07002674void PeerConnection::GetOptionsForOffer(
deadbeefab9b2d12015-10-14 11:33:11 -07002675 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options,
2676 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07002677 ExtractSharedMediaSessionOptions(rtc_options, session_options);
2678
2679 // Figure out transceiver directional preferences.
2680 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
2681 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
2682
2683 // By default, generate sendrecv/recvonly m= sections.
2684 bool recv_audio = true;
2685 bool recv_video = true;
2686
2687 // By default, only offer a new m= section if we have media to send with it.
2688 bool offer_new_audio_description = send_audio;
2689 bool offer_new_video_description = send_video;
2690 bool offer_new_data_description = HasDataChannels();
2691
2692 // The "offer_to_receive_X" options allow those defaults to be overridden.
2693 if (rtc_options.offer_to_receive_audio != RTCOfferAnswerOptions::kUndefined) {
2694 recv_audio = (rtc_options.offer_to_receive_audio > 0);
2695 offer_new_audio_description =
2696 offer_new_audio_description || (rtc_options.offer_to_receive_audio > 0);
2697 }
2698 if (rtc_options.offer_to_receive_video != RTCOfferAnswerOptions::kUndefined) {
2699 recv_video = (rtc_options.offer_to_receive_video > 0);
2700 offer_new_video_description =
2701 offer_new_video_description || (rtc_options.offer_to_receive_video > 0);
2702 }
2703
2704 rtc::Optional<size_t> audio_index;
2705 rtc::Optional<size_t> video_index;
2706 rtc::Optional<size_t> data_index;
2707 // If a current description exists, generate m= sections in the same order,
2708 // using the first audio/video/data section that appears and rejecting
2709 // extraneous ones.
Steve Anton75737c02017-11-06 10:37:17 -08002710 if (local_description()) {
zhihuang1c378ed2017-08-17 14:10:50 -07002711 GenerateMediaDescriptionOptions(
Steve Anton75737c02017-11-06 10:37:17 -08002712 local_description(),
Steve Anton1d03a752017-11-27 14:30:09 -08002713 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
2714 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
2715 &audio_index, &video_index, &data_index, session_options);
deadbeefab9b2d12015-10-14 11:33:11 -07002716 }
2717
zhihuang1c378ed2017-08-17 14:10:50 -07002718 // Add audio/video/data m= sections to the end if needed.
2719 if (!audio_index && offer_new_audio_description) {
2720 session_options->media_description_options.push_back(
2721 cricket::MediaDescriptionOptions(
2722 cricket::MEDIA_TYPE_AUDIO, cricket::CN_AUDIO,
Steve Anton1d03a752017-11-27 14:30:09 -08002723 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
2724 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01002725 audio_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07002726 }
zhihuang1c378ed2017-08-17 14:10:50 -07002727 if (!video_index && offer_new_video_description) {
2728 session_options->media_description_options.push_back(
2729 cricket::MediaDescriptionOptions(
2730 cricket::MEDIA_TYPE_VIDEO, cricket::CN_VIDEO,
Steve Anton1d03a752017-11-27 14:30:09 -08002731 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
2732 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01002733 video_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07002734 }
zhihuang1c378ed2017-08-17 14:10:50 -07002735 if (!data_index && offer_new_data_description) {
2736 session_options->media_description_options.push_back(
2737 cricket::MediaDescriptionOptions(
2738 cricket::MEDIA_TYPE_DATA, cricket::CN_DATA,
Steve Anton1d03a752017-11-27 14:30:09 -08002739 RtpTransceiverDirection::kSendRecv, false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01002740 data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07002741 }
2742
2743 cricket::MediaDescriptionOptions* audio_media_description_options =
2744 !audio_index ? nullptr
2745 : &session_options->media_description_options[*audio_index];
2746 cricket::MediaDescriptionOptions* video_media_description_options =
2747 !video_index ? nullptr
2748 : &session_options->media_description_options[*video_index];
2749 cricket::MediaDescriptionOptions* data_media_description_options =
2750 !data_index ? nullptr
2751 : &session_options->media_description_options[*data_index];
2752
2753 // Apply ICE restart flag and renomination flag.
2754 for (auto& options : session_options->media_description_options) {
2755 options.transport_options.ice_restart = rtc_options.ice_restart;
2756 options.transport_options.enable_ice_renomination =
2757 configuration_.enable_ice_renomination;
2758 }
2759
Steve Anton4171afb2017-11-20 10:20:22 -08002760 AddRtpSenderOptions(GetSendersInternal(), audio_media_description_options,
zhihuang1c378ed2017-08-17 14:10:50 -07002761 video_media_description_options);
2762 AddRtpDataChannelOptions(rtp_data_channels_, data_media_description_options);
deadbeefc80741f2015-10-22 13:14:45 -07002763
zhihuang9763d562016-08-05 11:14:50 -07002764 // Intentionally unset the data channel type for RTP data channel with the
2765 // second condition. Otherwise the RTP data channels would be successfully
2766 // negotiated by default and the unit tests in WebRtcDataBrowserTest will fail
2767 // when building with chromium. We want to leave RTP data channels broken, so
2768 // people won't try to use them.
Steve Anton75737c02017-11-06 10:37:17 -08002769 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
2770 session_options->data_channel_type = data_channel_type();
deadbeefab9b2d12015-10-14 11:33:11 -07002771 }
zhihuang8f65cdf2016-05-06 18:40:30 -07002772
2773 session_options->rtcp_cname = rtcp_cname_;
jbauchcb560652016-08-04 05:20:32 -07002774 session_options->crypto_options = factory_->options().crypto_options;
deadbeefab9b2d12015-10-14 11:33:11 -07002775}
2776
zhihuang1c378ed2017-08-17 14:10:50 -07002777void PeerConnection::GetOptionsForAnswer(
2778 const RTCOfferAnswerOptions& rtc_options,
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07002779 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07002780 ExtractSharedMediaSessionOptions(rtc_options, session_options);
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07002781
zhihuang1c378ed2017-08-17 14:10:50 -07002782 // Figure out transceiver directional preferences.
2783 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
2784 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
2785
2786 // By default, generate sendrecv/recvonly m= sections. The direction is also
2787 // restricted by the direction in the offer.
2788 bool recv_audio = true;
2789 bool recv_video = true;
2790
2791 // The "offer_to_receive_X" options allow those defaults to be overridden.
2792 if (rtc_options.offer_to_receive_audio != RTCOfferAnswerOptions::kUndefined) {
2793 recv_audio = (rtc_options.offer_to_receive_audio > 0);
deadbeef0ed85b22016-02-23 17:24:52 -08002794 }
zhihuang1c378ed2017-08-17 14:10:50 -07002795 if (rtc_options.offer_to_receive_video != RTCOfferAnswerOptions::kUndefined) {
2796 recv_video = (rtc_options.offer_to_receive_video > 0);
2797 }
2798
2799 rtc::Optional<size_t> audio_index;
2800 rtc::Optional<size_t> video_index;
2801 rtc::Optional<size_t> data_index;
Steve Anton75737c02017-11-06 10:37:17 -08002802 if (remote_description()) {
zhihuang141aacb2017-08-29 13:23:53 -07002803 // The pending remote description should be an offer.
Steve Antona3a92c22017-12-07 10:27:41 -08002804 RTC_DCHECK(remote_description()->GetType() == SdpType::kOffer);
zhihuang141aacb2017-08-29 13:23:53 -07002805 // Generate m= sections that match those in the offer.
2806 // Note that mediasession.cc will handle intersection our preferred
2807 // direction with the offered direction.
2808 GenerateMediaDescriptionOptions(
Steve Anton75737c02017-11-06 10:37:17 -08002809 remote_description(),
Steve Anton1d03a752017-11-27 14:30:09 -08002810 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
2811 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
2812 &audio_index, &video_index, &data_index, session_options);
zhihuang141aacb2017-08-29 13:23:53 -07002813 }
zhihuang1c378ed2017-08-17 14:10:50 -07002814
2815 cricket::MediaDescriptionOptions* audio_media_description_options =
2816 !audio_index ? nullptr
2817 : &session_options->media_description_options[*audio_index];
2818 cricket::MediaDescriptionOptions* video_media_description_options =
2819 !video_index ? nullptr
2820 : &session_options->media_description_options[*video_index];
2821 cricket::MediaDescriptionOptions* data_media_description_options =
2822 !data_index ? nullptr
2823 : &session_options->media_description_options[*data_index];
2824
2825 // Apply ICE renomination flag.
2826 for (auto& options : session_options->media_description_options) {
2827 options.transport_options.enable_ice_renomination =
2828 configuration_.enable_ice_renomination;
2829 }
2830
Steve Anton4171afb2017-11-20 10:20:22 -08002831 AddRtpSenderOptions(GetSendersInternal(), audio_media_description_options,
zhihuang1c378ed2017-08-17 14:10:50 -07002832 video_media_description_options);
2833 AddRtpDataChannelOptions(rtp_data_channels_, data_media_description_options);
2834
zhihuang9763d562016-08-05 11:14:50 -07002835 // Intentionally unset the data channel type for RTP data channel. Otherwise
2836 // the RTP data channels would be successfully negotiated by default and the
2837 // unit tests in WebRtcDataBrowserTest will fail when building with chromium.
2838 // We want to leave RTP data channels broken, so people won't try to use them.
Steve Anton75737c02017-11-06 10:37:17 -08002839 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
2840 session_options->data_channel_type = data_channel_type();
deadbeef907abe42016-08-04 12:22:18 -07002841 }
zhihuangaf388472016-11-02 16:49:48 -07002842
zhihuang1c378ed2017-08-17 14:10:50 -07002843 session_options->rtcp_cname = rtcp_cname_;
jbauchcb560652016-08-04 05:20:32 -07002844 session_options->crypto_options = factory_->options().crypto_options;
htaa2a49d92016-03-04 02:51:39 -08002845}
2846
zhihuang1c378ed2017-08-17 14:10:50 -07002847void PeerConnection::GenerateMediaDescriptionOptions(
2848 const SessionDescriptionInterface* session_desc,
Steve Anton1d03a752017-11-27 14:30:09 -08002849 RtpTransceiverDirection audio_direction,
2850 RtpTransceiverDirection video_direction,
zhihuang1c378ed2017-08-17 14:10:50 -07002851 rtc::Optional<size_t>* audio_index,
2852 rtc::Optional<size_t>* video_index,
2853 rtc::Optional<size_t>* data_index,
htaa2a49d92016-03-04 02:51:39 -08002854 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07002855 for (const cricket::ContentInfo& content :
2856 session_desc->description()->contents()) {
2857 if (IsAudioContent(&content)) {
2858 // If we already have an audio m= section, reject this extra one.
2859 if (*audio_index) {
2860 session_options->media_description_options.push_back(
2861 cricket::MediaDescriptionOptions(
2862 cricket::MEDIA_TYPE_AUDIO, content.name,
Steve Anton1d03a752017-11-27 14:30:09 -08002863 RtpTransceiverDirection::kInactive, true));
zhihuang1c378ed2017-08-17 14:10:50 -07002864 } else {
2865 session_options->media_description_options.push_back(
2866 cricket::MediaDescriptionOptions(
2867 cricket::MEDIA_TYPE_AUDIO, content.name, audio_direction,
Steve Anton1d03a752017-11-27 14:30:09 -08002868 audio_direction == RtpTransceiverDirection::kInactive));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01002869 *audio_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07002870 }
2871 } else if (IsVideoContent(&content)) {
2872 // If we already have an video m= section, reject this extra one.
2873 if (*video_index) {
2874 session_options->media_description_options.push_back(
2875 cricket::MediaDescriptionOptions(
2876 cricket::MEDIA_TYPE_VIDEO, content.name,
Steve Anton1d03a752017-11-27 14:30:09 -08002877 RtpTransceiverDirection::kInactive, true));
zhihuang1c378ed2017-08-17 14:10:50 -07002878 } else {
2879 session_options->media_description_options.push_back(
2880 cricket::MediaDescriptionOptions(
2881 cricket::MEDIA_TYPE_VIDEO, content.name, video_direction,
Steve Anton1d03a752017-11-27 14:30:09 -08002882 video_direction == RtpTransceiverDirection::kInactive));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01002883 *video_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07002884 }
2885 } else {
2886 RTC_DCHECK(IsDataContent(&content));
2887 // If we already have an data m= section, reject this extra one.
2888 if (*data_index) {
2889 session_options->media_description_options.push_back(
2890 cricket::MediaDescriptionOptions(
2891 cricket::MEDIA_TYPE_DATA, content.name,
Steve Anton1d03a752017-11-27 14:30:09 -08002892 RtpTransceiverDirection::kInactive, true));
zhihuang1c378ed2017-08-17 14:10:50 -07002893 } else {
2894 session_options->media_description_options.push_back(
2895 cricket::MediaDescriptionOptions(
2896 cricket::MEDIA_TYPE_DATA, content.name,
2897 // Direction for data sections is meaningless, but legacy
2898 // endpoints might expect sendrecv.
Steve Anton1d03a752017-11-27 14:30:09 -08002899 RtpTransceiverDirection::kSendRecv, false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01002900 *data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07002901 }
2902 }
htaa2a49d92016-03-04 02:51:39 -08002903 }
deadbeefab9b2d12015-10-14 11:33:11 -07002904}
2905
Steve Anton4171afb2017-11-20 10:20:22 -08002906void PeerConnection::RemoveSenders(cricket::MediaType media_type) {
2907 UpdateLocalSenders(std::vector<cricket::StreamParams>(), media_type);
2908 UpdateRemoteSendersList(std::vector<cricket::StreamParams>(), false,
deadbeefbda7e0b2015-12-08 17:13:40 -08002909 media_type, nullptr);
deadbeeffaac4972015-11-12 15:33:07 -08002910}
2911
Steve Anton4171afb2017-11-20 10:20:22 -08002912void PeerConnection::UpdateRemoteSendersList(
deadbeefab9b2d12015-10-14 11:33:11 -07002913 const cricket::StreamParamsVec& streams,
Steve Anton4171afb2017-11-20 10:20:22 -08002914 bool default_sender_needed,
deadbeefab9b2d12015-10-14 11:33:11 -07002915 cricket::MediaType media_type,
2916 StreamCollection* new_streams) {
Steve Anton4171afb2017-11-20 10:20:22 -08002917 std::vector<RtpSenderInfo>* current_senders =
2918 GetRemoteSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07002919
Steve Anton4171afb2017-11-20 10:20:22 -08002920 // Find removed senders. I.e., senders where the sender id or ssrc don't match
deadbeeffac06552015-11-25 11:26:01 -08002921 // the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08002922 for (auto sender_it = current_senders->begin();
2923 sender_it != current_senders->end();
2924 /* incremented manually */) {
2925 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07002926 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08002927 cricket::GetStreamBySsrc(streams, info.first_ssrc);
2928 bool sender_exists = params && params->id == info.sender_id;
deadbeefbda7e0b2015-12-08 17:13:40 -08002929 // If this is a default track, and we still need it, don't remove it.
Steve Anton4171afb2017-11-20 10:20:22 -08002930 if ((info.stream_label == kDefaultStreamLabel && default_sender_needed) ||
2931 sender_exists) {
2932 ++sender_it;
deadbeefbda7e0b2015-12-08 17:13:40 -08002933 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08002934 OnRemoteSenderRemoved(info, media_type);
2935 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07002936 }
2937 }
2938
Steve Anton4171afb2017-11-20 10:20:22 -08002939 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07002940 for (const cricket::StreamParams& params : streams) {
2941 // The sync_label is the MediaStream label and the |stream.id| is the
Steve Anton4171afb2017-11-20 10:20:22 -08002942 // sender id.
deadbeefab9b2d12015-10-14 11:33:11 -07002943 const std::string& stream_label = params.sync_label;
Steve Anton4171afb2017-11-20 10:20:22 -08002944 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07002945 uint32_t ssrc = params.first_ssrc();
2946
2947 rtc::scoped_refptr<MediaStreamInterface> stream =
2948 remote_streams_->find(stream_label);
2949 if (!stream) {
2950 // This is a new MediaStream. Create a new remote MediaStream.
perkjd61bf802016-03-24 03:16:19 -07002951 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
2952 MediaStream::Create(stream_label));
deadbeefab9b2d12015-10-14 11:33:11 -07002953 remote_streams_->AddStream(stream);
2954 new_streams->AddStream(stream);
2955 }
2956
Steve Anton4171afb2017-11-20 10:20:22 -08002957 const RtpSenderInfo* sender_info =
2958 FindSenderInfo(*current_senders, stream_label, sender_id);
2959 if (!sender_info) {
2960 current_senders->push_back(RtpSenderInfo(stream_label, sender_id, ssrc));
2961 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07002962 }
2963 }
deadbeefbda7e0b2015-12-08 17:13:40 -08002964
Steve Anton4171afb2017-11-20 10:20:22 -08002965 // Add default sender if necessary.
2966 if (default_sender_needed) {
deadbeefbda7e0b2015-12-08 17:13:40 -08002967 rtc::scoped_refptr<MediaStreamInterface> default_stream =
2968 remote_streams_->find(kDefaultStreamLabel);
2969 if (!default_stream) {
2970 // Create the new default MediaStream.
perkjd61bf802016-03-24 03:16:19 -07002971 default_stream = MediaStreamProxy::Create(
2972 rtc::Thread::Current(), MediaStream::Create(kDefaultStreamLabel));
deadbeefbda7e0b2015-12-08 17:13:40 -08002973 remote_streams_->AddStream(default_stream);
2974 new_streams->AddStream(default_stream);
2975 }
Steve Anton4171afb2017-11-20 10:20:22 -08002976 std::string default_sender_id = (media_type == cricket::MEDIA_TYPE_AUDIO)
2977 ? kDefaultAudioSenderId
2978 : kDefaultVideoSenderId;
2979 const RtpSenderInfo* default_sender_info = FindSenderInfo(
2980 *current_senders, kDefaultStreamLabel, default_sender_id);
2981 if (!default_sender_info) {
2982 current_senders->push_back(
2983 RtpSenderInfo(kDefaultStreamLabel, default_sender_id, 0));
2984 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefbda7e0b2015-12-08 17:13:40 -08002985 }
2986 }
deadbeefab9b2d12015-10-14 11:33:11 -07002987}
2988
Steve Anton4171afb2017-11-20 10:20:22 -08002989void PeerConnection::OnRemoteSenderAdded(const RtpSenderInfo& sender_info,
2990 cricket::MediaType media_type) {
2991 MediaStreamInterface* stream =
2992 remote_streams_->find(sender_info.stream_label);
deadbeefab9b2d12015-10-14 11:33:11 -07002993
2994 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 10:20:22 -08002995 CreateAudioReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07002996 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 10:20:22 -08002997 CreateVideoReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07002998 } else {
nisseeb4ca4e2017-01-12 02:24:27 -08002999 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07003000 }
3001}
3002
Steve Anton4171afb2017-11-20 10:20:22 -08003003void PeerConnection::OnRemoteSenderRemoved(const RtpSenderInfo& sender_info,
3004 cricket::MediaType media_type) {
3005 MediaStreamInterface* stream =
3006 remote_streams_->find(sender_info.stream_label);
deadbeefab9b2d12015-10-14 11:33:11 -07003007
Henrik Boström933d8b02017-10-10 10:05:16 -07003008 rtc::scoped_refptr<RtpReceiverInterface> receiver;
deadbeefab9b2d12015-10-14 11:33:11 -07003009 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
perkjd61bf802016-03-24 03:16:19 -07003010 // When the MediaEngine audio channel is destroyed, the RemoteAudioSource
3011 // will be notified which will end the AudioRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08003012 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07003013 rtc::scoped_refptr<AudioTrackInterface> audio_track =
Steve Anton4171afb2017-11-20 10:20:22 -08003014 stream->FindAudioTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07003015 if (audio_track) {
deadbeefab9b2d12015-10-14 11:33:11 -07003016 stream->RemoveTrack(audio_track);
deadbeefab9b2d12015-10-14 11:33:11 -07003017 }
3018 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
perkjd61bf802016-03-24 03:16:19 -07003019 // Stopping or destroying a VideoRtpReceiver will end the
3020 // VideoRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08003021 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07003022 rtc::scoped_refptr<VideoTrackInterface> video_track =
Steve Anton4171afb2017-11-20 10:20:22 -08003023 stream->FindVideoTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07003024 if (video_track) {
perkjd61bf802016-03-24 03:16:19 -07003025 // There's no guarantee the track is still available, e.g. the track may
3026 // have been removed from the stream by an application.
deadbeefab9b2d12015-10-14 11:33:11 -07003027 stream->RemoveTrack(video_track);
deadbeefab9b2d12015-10-14 11:33:11 -07003028 }
3029 } else {
nisseede5da42017-01-12 05:15:36 -08003030 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07003031 }
Henrik Boström933d8b02017-10-10 10:05:16 -07003032 if (receiver) {
3033 observer_->OnRemoveTrack(receiver);
3034 }
deadbeefab9b2d12015-10-14 11:33:11 -07003035}
3036
3037void PeerConnection::UpdateEndedRemoteMediaStreams() {
3038 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams_to_remove;
3039 for (size_t i = 0; i < remote_streams_->count(); ++i) {
3040 MediaStreamInterface* stream = remote_streams_->at(i);
3041 if (stream->GetAudioTracks().empty() && stream->GetVideoTracks().empty()) {
3042 streams_to_remove.push_back(stream);
3043 }
3044 }
3045
Taylor Brandstetter98cde262016-05-31 13:02:21 -07003046 for (auto& stream : streams_to_remove) {
deadbeefab9b2d12015-10-14 11:33:11 -07003047 remote_streams_->RemoveStream(stream);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07003048 observer_->OnRemoveStream(std::move(stream));
deadbeefab9b2d12015-10-14 11:33:11 -07003049 }
3050}
3051
Steve Anton4171afb2017-11-20 10:20:22 -08003052void PeerConnection::UpdateLocalSenders(
deadbeefab9b2d12015-10-14 11:33:11 -07003053 const std::vector<cricket::StreamParams>& streams,
3054 cricket::MediaType media_type) {
Steve Anton4171afb2017-11-20 10:20:22 -08003055 std::vector<RtpSenderInfo>* current_senders = GetLocalSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07003056
3057 // Find removed tracks. I.e., tracks where the track id, stream label or ssrc
3058 // don't match the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08003059 for (auto sender_it = current_senders->begin();
3060 sender_it != current_senders->end();
3061 /* incremented manually */) {
3062 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07003063 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08003064 cricket::GetStreamBySsrc(streams, info.first_ssrc);
3065 if (!params || params->id != info.sender_id ||
deadbeefab9b2d12015-10-14 11:33:11 -07003066 params->sync_label != info.stream_label) {
Steve Anton4171afb2017-11-20 10:20:22 -08003067 OnLocalSenderRemoved(info, media_type);
3068 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07003069 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08003070 ++sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07003071 }
3072 }
3073
Steve Anton4171afb2017-11-20 10:20:22 -08003074 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07003075 for (const cricket::StreamParams& params : streams) {
3076 // The sync_label is the MediaStream label and the |stream.id| is the
Steve Anton4171afb2017-11-20 10:20:22 -08003077 // sender id.
deadbeefab9b2d12015-10-14 11:33:11 -07003078 const std::string& stream_label = params.sync_label;
Steve Anton4171afb2017-11-20 10:20:22 -08003079 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07003080 uint32_t ssrc = params.first_ssrc();
Steve Anton4171afb2017-11-20 10:20:22 -08003081 const RtpSenderInfo* sender_info =
3082 FindSenderInfo(*current_senders, stream_label, sender_id);
3083 if (!sender_info) {
3084 current_senders->push_back(RtpSenderInfo(stream_label, sender_id, ssrc));
3085 OnLocalSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07003086 }
3087 }
3088}
3089
Steve Anton4171afb2017-11-20 10:20:22 -08003090void PeerConnection::OnLocalSenderAdded(const RtpSenderInfo& sender_info,
3091 cricket::MediaType media_type) {
3092 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08003093 if (!sender) {
Steve Anton4171afb2017-11-20 10:20:22 -08003094 RTC_LOG(LS_WARNING) << "An unknown RtpSender with id "
3095 << sender_info.sender_id
Mirko Bonadei675513b2017-11-09 11:09:25 +01003096 << " has been configured in the local description.";
deadbeefab9b2d12015-10-14 11:33:11 -07003097 return;
3098 }
3099
deadbeeffac06552015-11-25 11:26:01 -08003100 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003101 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
3102 << " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08003103 return;
deadbeefab9b2d12015-10-14 11:33:11 -07003104 }
deadbeeffac06552015-11-25 11:26:01 -08003105
Steve Anton4171afb2017-11-20 10:20:22 -08003106 sender->internal()->set_stream_id(sender_info.stream_label);
3107 sender->internal()->SetSsrc(sender_info.first_ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07003108}
3109
Steve Anton4171afb2017-11-20 10:20:22 -08003110void PeerConnection::OnLocalSenderRemoved(const RtpSenderInfo& sender_info,
3111 cricket::MediaType media_type) {
3112 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08003113 if (!sender) {
3114 // This is the normal case. I.e., RemoveStream has been called and the
deadbeefab9b2d12015-10-14 11:33:11 -07003115 // SessionDescriptions has been renegotiated.
3116 return;
3117 }
deadbeeffac06552015-11-25 11:26:01 -08003118
3119 // A sender has been removed from the SessionDescription but it's still
3120 // associated with the PeerConnection. This only occurs if the SDP doesn't
3121 // match with the calls to CreateSender, AddStream and RemoveStream.
3122 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003123 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
3124 << " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08003125 return;
deadbeefab9b2d12015-10-14 11:33:11 -07003126 }
deadbeeffac06552015-11-25 11:26:01 -08003127
Steve Anton4171afb2017-11-20 10:20:22 -08003128 sender->internal()->SetSsrc(0);
deadbeefab9b2d12015-10-14 11:33:11 -07003129}
3130
3131void PeerConnection::UpdateLocalRtpDataChannels(
3132 const cricket::StreamParamsVec& streams) {
3133 std::vector<std::string> existing_channels;
3134
3135 // Find new and active data channels.
3136 for (const cricket::StreamParams& params : streams) {
3137 // |it->sync_label| is actually the data channel label. The reason is that
3138 // we use the same naming of data channels as we do for
3139 // MediaStreams and Tracks.
3140 // For MediaStreams, the sync_label is the MediaStream label and the
3141 // track label is the same as |streamid|.
3142 const std::string& channel_label = params.sync_label;
3143 auto data_channel_it = rtp_data_channels_.find(channel_label);
nisse7ce109a2017-01-31 00:57:56 -08003144 if (data_channel_it == rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003145 RTC_LOG(LS_ERROR) << "channel label not found";
deadbeefab9b2d12015-10-14 11:33:11 -07003146 continue;
3147 }
3148 // Set the SSRC the data channel should use for sending.
3149 data_channel_it->second->SetSendSsrc(params.first_ssrc());
3150 existing_channels.push_back(data_channel_it->first);
3151 }
3152
3153 UpdateClosingRtpDataChannels(existing_channels, true);
3154}
3155
3156void PeerConnection::UpdateRemoteRtpDataChannels(
3157 const cricket::StreamParamsVec& streams) {
3158 std::vector<std::string> existing_channels;
3159
3160 // Find new and active data channels.
3161 for (const cricket::StreamParams& params : streams) {
3162 // The data channel label is either the mslabel or the SSRC if the mslabel
3163 // does not exist. Ex a=ssrc:444330170 mslabel:test1.
3164 std::string label = params.sync_label.empty()
3165 ? rtc::ToString(params.first_ssrc())
3166 : params.sync_label;
3167 auto data_channel_it = rtp_data_channels_.find(label);
3168 if (data_channel_it == rtp_data_channels_.end()) {
3169 // This is a new data channel.
3170 CreateRemoteRtpDataChannel(label, params.first_ssrc());
3171 } else {
3172 data_channel_it->second->SetReceiveSsrc(params.first_ssrc());
3173 }
3174 existing_channels.push_back(label);
3175 }
3176
3177 UpdateClosingRtpDataChannels(existing_channels, false);
3178}
3179
3180void PeerConnection::UpdateClosingRtpDataChannels(
3181 const std::vector<std::string>& active_channels,
3182 bool is_local_update) {
3183 auto it = rtp_data_channels_.begin();
3184 while (it != rtp_data_channels_.end()) {
3185 DataChannel* data_channel = it->second;
3186 if (std::find(active_channels.begin(), active_channels.end(),
3187 data_channel->label()) != active_channels.end()) {
3188 ++it;
3189 continue;
3190 }
3191
3192 if (is_local_update) {
3193 data_channel->SetSendSsrc(0);
3194 } else {
3195 data_channel->RemotePeerRequestClose();
3196 }
3197
3198 if (data_channel->state() == DataChannel::kClosed) {
3199 rtp_data_channels_.erase(it);
3200 it = rtp_data_channels_.begin();
3201 } else {
3202 ++it;
3203 }
3204 }
3205}
3206
3207void PeerConnection::CreateRemoteRtpDataChannel(const std::string& label,
3208 uint32_t remote_ssrc) {
3209 rtc::scoped_refptr<DataChannel> channel(
3210 InternalCreateDataChannel(label, nullptr));
3211 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003212 RTC_LOG(LS_WARNING) << "Remote peer requested a DataChannel but"
3213 << "CreateDataChannel failed.";
deadbeefab9b2d12015-10-14 11:33:11 -07003214 return;
3215 }
3216 channel->SetReceiveSsrc(remote_ssrc);
deadbeefa601f5c2016-06-06 14:27:39 -07003217 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
3218 DataChannelProxy::Create(signaling_thread(), channel);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07003219 observer_->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07003220}
3221
3222rtc::scoped_refptr<DataChannel> PeerConnection::InternalCreateDataChannel(
3223 const std::string& label,
3224 const InternalDataChannelInit* config) {
3225 if (IsClosed()) {
3226 return nullptr;
3227 }
Steve Anton75737c02017-11-06 10:37:17 -08003228 if (data_channel_type() == cricket::DCT_NONE) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003229 RTC_LOG(LS_ERROR)
deadbeefab9b2d12015-10-14 11:33:11 -07003230 << "InternalCreateDataChannel: Data is not supported in this call.";
3231 return nullptr;
3232 }
3233 InternalDataChannelInit new_config =
3234 config ? (*config) : InternalDataChannelInit();
Steve Anton75737c02017-11-06 10:37:17 -08003235 if (data_channel_type() == cricket::DCT_SCTP) {
deadbeefab9b2d12015-10-14 11:33:11 -07003236 if (new_config.id < 0) {
3237 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08003238 if ((GetSctpSslRole(&role)) &&
deadbeefab9b2d12015-10-14 11:33:11 -07003239 !sid_allocator_.AllocateSid(role, &new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003240 RTC_LOG(LS_ERROR)
3241 << "No id can be allocated for the SCTP data channel.";
deadbeefab9b2d12015-10-14 11:33:11 -07003242 return nullptr;
3243 }
3244 } else if (!sid_allocator_.ReserveSid(new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003245 RTC_LOG(LS_ERROR) << "Failed to create a SCTP data channel "
3246 << "because the id is already in use or out of range.";
deadbeefab9b2d12015-10-14 11:33:11 -07003247 return nullptr;
3248 }
3249 }
3250
Steve Anton75737c02017-11-06 10:37:17 -08003251 rtc::scoped_refptr<DataChannel> channel(
3252 DataChannel::Create(this, data_channel_type(), label, new_config));
deadbeefab9b2d12015-10-14 11:33:11 -07003253 if (!channel) {
3254 sid_allocator_.ReleaseSid(new_config.id);
3255 return nullptr;
3256 }
3257
3258 if (channel->data_channel_type() == cricket::DCT_RTP) {
3259 if (rtp_data_channels_.find(channel->label()) != rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003260 RTC_LOG(LS_ERROR) << "DataChannel with label " << channel->label()
3261 << " already exists.";
deadbeefab9b2d12015-10-14 11:33:11 -07003262 return nullptr;
3263 }
3264 rtp_data_channels_[channel->label()] = channel;
3265 } else {
3266 RTC_DCHECK(channel->data_channel_type() == cricket::DCT_SCTP);
3267 sctp_data_channels_.push_back(channel);
3268 channel->SignalClosed.connect(this,
3269 &PeerConnection::OnSctpDataChannelClosed);
3270 }
3271
hbos82ebe022016-11-14 01:41:09 -08003272 SignalDataChannelCreated(channel.get());
deadbeefab9b2d12015-10-14 11:33:11 -07003273 return channel;
3274}
3275
3276bool PeerConnection::HasDataChannels() const {
3277 return !rtp_data_channels_.empty() || !sctp_data_channels_.empty();
3278}
3279
3280void PeerConnection::AllocateSctpSids(rtc::SSLRole role) {
3281 for (const auto& channel : sctp_data_channels_) {
3282 if (channel->id() < 0) {
3283 int sid;
3284 if (!sid_allocator_.AllocateSid(role, &sid)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003285 RTC_LOG(LS_ERROR) << "Failed to allocate SCTP sid.";
deadbeefab9b2d12015-10-14 11:33:11 -07003286 continue;
3287 }
3288 channel->SetSctpSid(sid);
3289 }
3290 }
3291}
3292
3293void PeerConnection::OnSctpDataChannelClosed(DataChannel* channel) {
deadbeefbd292462015-12-14 18:15:29 -08003294 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeefab9b2d12015-10-14 11:33:11 -07003295 for (auto it = sctp_data_channels_.begin(); it != sctp_data_channels_.end();
3296 ++it) {
3297 if (it->get() == channel) {
3298 if (channel->id() >= 0) {
3299 sid_allocator_.ReleaseSid(channel->id());
3300 }
deadbeefbd292462015-12-14 18:15:29 -08003301 // Since this method is triggered by a signal from the DataChannel,
3302 // we can't free it directly here; we need to free it asynchronously.
3303 sctp_data_channels_to_free_.push_back(*it);
deadbeefab9b2d12015-10-14 11:33:11 -07003304 sctp_data_channels_.erase(it);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07003305 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_FREE_DATACHANNELS,
3306 nullptr);
deadbeefab9b2d12015-10-14 11:33:11 -07003307 return;
3308 }
3309 }
3310}
3311
deadbeefab9b2d12015-10-14 11:33:11 -07003312void PeerConnection::OnDataChannelDestroyed() {
3313 // Use a temporary copy of the RTP/SCTP DataChannel list because the
3314 // DataChannel may callback to us and try to modify the list.
3315 std::map<std::string, rtc::scoped_refptr<DataChannel>> temp_rtp_dcs;
3316 temp_rtp_dcs.swap(rtp_data_channels_);
3317 for (const auto& kv : temp_rtp_dcs) {
3318 kv.second->OnTransportChannelDestroyed();
3319 }
3320
3321 std::vector<rtc::scoped_refptr<DataChannel>> temp_sctp_dcs;
3322 temp_sctp_dcs.swap(sctp_data_channels_);
3323 for (const auto& channel : temp_sctp_dcs) {
3324 channel->OnTransportChannelDestroyed();
3325 }
3326}
3327
3328void PeerConnection::OnDataChannelOpenMessage(
3329 const std::string& label,
3330 const InternalDataChannelInit& config) {
3331 rtc::scoped_refptr<DataChannel> channel(
3332 InternalCreateDataChannel(label, &config));
3333 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003334 RTC_LOG(LS_ERROR) << "Failed to create DataChannel from the OPEN message.";
deadbeefab9b2d12015-10-14 11:33:11 -07003335 return;
3336 }
3337
deadbeefa601f5c2016-06-06 14:27:39 -07003338 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
3339 DataChannelProxy::Create(signaling_thread(), channel);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07003340 observer_->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07003341}
3342
Steve Anton4171afb2017-11-20 10:20:22 -08003343rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3344PeerConnection::GetAudioTransceiver() const {
3345 // This method only works with Plan B SDP, where there is a single
3346 // audio/video transceiver.
3347 RTC_DCHECK(!IsUnifiedPlan());
3348 for (auto transceiver : transceivers_) {
3349 if (transceiver->internal()->media_type() == cricket::MEDIA_TYPE_AUDIO) {
3350 return transceiver;
3351 }
3352 }
3353 RTC_NOTREACHED();
3354 return nullptr;
3355}
3356
3357rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3358PeerConnection::GetVideoTransceiver() const {
3359 // This method only works with Plan B SDP, where there is a single
3360 // audio/video transceiver.
3361 RTC_DCHECK(!IsUnifiedPlan());
3362 for (auto transceiver : transceivers_) {
3363 if (transceiver->internal()->media_type() == cricket::MEDIA_TYPE_VIDEO) {
3364 return transceiver;
3365 }
3366 }
3367 RTC_NOTREACHED();
3368 return nullptr;
3369}
3370
3371// TODO(bugs.webrtc.org/7600): Remove this when multiple transceivers with
3372// individual transceiver directions are supported.
zhihuang1c378ed2017-08-17 14:10:50 -07003373bool PeerConnection::HasRtpSender(cricket::MediaType type) const {
Steve Anton4171afb2017-11-20 10:20:22 -08003374 switch (type) {
3375 case cricket::MEDIA_TYPE_AUDIO:
3376 return !GetAudioTransceiver()->internal()->senders().empty();
3377 case cricket::MEDIA_TYPE_VIDEO:
3378 return !GetVideoTransceiver()->internal()->senders().empty();
3379 case cricket::MEDIA_TYPE_DATA:
3380 return false;
3381 }
3382 RTC_NOTREACHED();
3383 return false;
zhihuang1c378ed2017-08-17 14:10:50 -07003384}
3385
Steve Anton4171afb2017-11-20 10:20:22 -08003386rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
3387PeerConnection::FindSenderForTrack(MediaStreamTrackInterface* track) const {
3388 for (auto transceiver : transceivers_) {
3389 for (auto sender : transceiver->internal()->senders()) {
3390 if (sender->track() == track) {
3391 return sender;
3392 }
3393 }
3394 }
3395 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08003396}
3397
Steve Anton4171afb2017-11-20 10:20:22 -08003398rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
3399PeerConnection::FindSenderById(const std::string& sender_id) const {
3400 for (auto transceiver : transceivers_) {
3401 for (auto sender : transceiver->internal()->senders()) {
3402 if (sender->id() == sender_id) {
3403 return sender;
3404 }
3405 }
3406 }
3407 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07003408}
3409
Steve Anton4171afb2017-11-20 10:20:22 -08003410rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
3411PeerConnection::FindReceiverById(const std::string& receiver_id) const {
3412 for (auto transceiver : transceivers_) {
3413 for (auto receiver : transceiver->internal()->receivers()) {
3414 if (receiver->id() == receiver_id) {
3415 return receiver;
3416 }
3417 }
3418 }
3419 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07003420}
3421
Steve Anton4171afb2017-11-20 10:20:22 -08003422std::vector<PeerConnection::RtpSenderInfo>*
3423PeerConnection::GetRemoteSenderInfos(cricket::MediaType media_type) {
3424 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
3425 media_type == cricket::MEDIA_TYPE_VIDEO);
3426 return (media_type == cricket::MEDIA_TYPE_AUDIO)
3427 ? &remote_audio_sender_infos_
3428 : &remote_video_sender_infos_;
3429}
3430
3431std::vector<PeerConnection::RtpSenderInfo>* PeerConnection::GetLocalSenderInfos(
deadbeefab9b2d12015-10-14 11:33:11 -07003432 cricket::MediaType media_type) {
3433 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
3434 media_type == cricket::MEDIA_TYPE_VIDEO);
Steve Anton4171afb2017-11-20 10:20:22 -08003435 return (media_type == cricket::MEDIA_TYPE_AUDIO) ? &local_audio_sender_infos_
3436 : &local_video_sender_infos_;
deadbeefab9b2d12015-10-14 11:33:11 -07003437}
3438
Steve Anton4171afb2017-11-20 10:20:22 -08003439const PeerConnection::RtpSenderInfo* PeerConnection::FindSenderInfo(
3440 const std::vector<PeerConnection::RtpSenderInfo>& infos,
deadbeefab9b2d12015-10-14 11:33:11 -07003441 const std::string& stream_label,
Steve Anton4171afb2017-11-20 10:20:22 -08003442 const std::string sender_id) const {
3443 for (const RtpSenderInfo& sender_info : infos) {
3444 if (sender_info.stream_label == stream_label &&
3445 sender_info.sender_id == sender_id) {
3446 return &sender_info;
deadbeefab9b2d12015-10-14 11:33:11 -07003447 }
3448 }
3449 return nullptr;
3450}
3451
3452DataChannel* PeerConnection::FindDataChannelBySid(int sid) const {
3453 for (const auto& channel : sctp_data_channels_) {
3454 if (channel->id() == sid) {
3455 return channel;
3456 }
3457 }
3458 return nullptr;
3459}
3460
deadbeef91dd5672016-05-18 16:55:30 -07003461bool PeerConnection::InitializePortAllocator_n(
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003462 const RTCConfiguration& configuration) {
3463 cricket::ServerAddresses stun_servers;
3464 std::vector<cricket::RelayServerConfig> turn_servers;
deadbeef293e9262017-01-11 12:28:30 -08003465 if (ParseIceServers(configuration.servers, &stun_servers, &turn_servers) !=
3466 RTCErrorType::NONE) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003467 return false;
3468 }
3469
Taylor Brandstetterf8e65772016-06-27 17:20:15 -07003470 port_allocator_->Initialize();
3471
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003472 // To handle both internal and externally created port allocator, we will
3473 // enable BUNDLE here.
3474 int portallocator_flags = port_allocator_->flags();
3475 portallocator_flags |= cricket::PORTALLOCATOR_ENABLE_SHARED_SOCKET |
zhihuangb09b3f92017-03-07 14:40:51 -08003476 cricket::PORTALLOCATOR_ENABLE_IPV6 |
3477 cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI;
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003478 // If the disable-IPv6 flag was specified, we'll not override it
3479 // by experiment.
3480 if (configuration.disable_ipv6) {
3481 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
sprangc1b57a12017-02-28 08:50:47 -08003482 } else if (webrtc::field_trial::FindFullName("WebRTC-IPv6Default")
3483 .find("Disabled") == 0) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003484 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
3485 }
3486
zhihuangb09b3f92017-03-07 14:40:51 -08003487 if (configuration.disable_ipv6_on_wifi) {
3488 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI);
Mirko Bonadei675513b2017-11-09 11:09:25 +01003489 RTC_LOG(LS_INFO) << "IPv6 candidates on Wi-Fi are disabled.";
zhihuangb09b3f92017-03-07 14:40:51 -08003490 }
3491
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003492 if (configuration.tcp_candidate_policy == kTcpCandidatePolicyDisabled) {
3493 portallocator_flags |= cricket::PORTALLOCATOR_DISABLE_TCP;
Mirko Bonadei675513b2017-11-09 11:09:25 +01003494 RTC_LOG(LS_INFO) << "TCP candidates are disabled.";
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003495 }
3496
honghaiz60347052016-05-31 18:29:12 -07003497 if (configuration.candidate_network_policy ==
3498 kCandidateNetworkPolicyLowCost) {
3499 portallocator_flags |= cricket::PORTALLOCATOR_DISABLE_COSTLY_NETWORKS;
Mirko Bonadei675513b2017-11-09 11:09:25 +01003500 RTC_LOG(LS_INFO) << "Do not gather candidates on high-cost networks";
honghaiz60347052016-05-31 18:29:12 -07003501 }
3502
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003503 port_allocator_->set_flags(portallocator_flags);
3504 // No step delay is used while allocating ports.
3505 port_allocator_->set_step_delay(cricket::kMinimumStepDelay);
3506 port_allocator_->set_candidate_filter(
3507 ConvertIceTransportTypeToCandidateFilter(configuration.type));
deadbeefd21eab32017-07-26 16:50:11 -07003508 port_allocator_->set_max_ipv6_networks(configuration.max_ipv6_networks);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003509
3510 // Call this last since it may create pooled allocator sessions using the
3511 // properties set above.
3512 port_allocator_->SetConfiguration(stun_servers, turn_servers,
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -07003513 configuration.ice_candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02003514 configuration.prune_turn_ports,
3515 configuration.turn_customizer);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003516 return true;
3517}
3518
deadbeef91dd5672016-05-18 16:55:30 -07003519bool PeerConnection::ReconfigurePortAllocator_n(
deadbeef293e9262017-01-11 12:28:30 -08003520 const cricket::ServerAddresses& stun_servers,
3521 const std::vector<cricket::RelayServerConfig>& turn_servers,
3522 IceTransportsType type,
3523 int candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02003524 bool prune_turn_ports,
3525 webrtc::TurnCustomizer* turn_customizer) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003526 port_allocator_->set_candidate_filter(
deadbeef293e9262017-01-11 12:28:30 -08003527 ConvertIceTransportTypeToCandidateFilter(type));
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003528 // Call this last since it may create pooled allocator sessions using the
3529 // candidate filter set above.
deadbeef6de92f92016-12-12 18:49:32 -08003530 return port_allocator_->SetConfiguration(
Jonas Orelandbdcee282017-10-10 14:01:40 +02003531 stun_servers, turn_servers, candidate_pool_size, prune_turn_ports,
3532 turn_customizer);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003533}
3534
Steve Antonba818672017-11-06 10:21:57 -08003535cricket::ChannelManager* PeerConnection::channel_manager() const {
3536 return factory_->channel_manager();
3537}
3538
3539MetricsObserverInterface* PeerConnection::metrics_observer() const {
3540 return uma_observer_;
3541}
3542
Elad Alon99c3fe52017-10-13 16:29:40 +02003543bool PeerConnection::StartRtcEventLog_w(
Bjorn Tereliusde939432017-11-20 17:38:14 +01003544 std::unique_ptr<RtcEventLogOutput> output,
3545 int64_t output_period_ms) {
zhihuang77985012017-02-07 15:45:16 -08003546 if (!event_log_) {
3547 return false;
3548 }
Bjorn Tereliusde939432017-11-20 17:38:14 +01003549 return event_log_->StartLogging(std::move(output), output_period_ms);
ivoc14d5dbe2016-07-04 07:06:55 -07003550}
3551
3552void PeerConnection::StopRtcEventLog_w() {
zhihuang77985012017-02-07 15:45:16 -08003553 if (event_log_) {
3554 event_log_->StopLogging();
3555 }
ivoc14d5dbe2016-07-04 07:06:55 -07003556}
nisseeaabdf62017-05-05 02:23:02 -07003557
Steve Anton75737c02017-11-06 10:37:17 -08003558cricket::BaseChannel* PeerConnection::GetChannel(
3559 const std::string& content_name) {
3560 if (voice_channel() && voice_channel()->content_name() == content_name) {
3561 return voice_channel();
3562 }
3563 if (video_channel() && video_channel()->content_name() == content_name) {
3564 return video_channel();
3565 }
3566 if (rtp_data_channel() &&
3567 rtp_data_channel()->content_name() == content_name) {
3568 return rtp_data_channel();
3569 }
3570 return nullptr;
3571}
3572
3573bool PeerConnection::GetSctpSslRole(rtc::SSLRole* role) {
3574 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003575 RTC_LOG(LS_INFO)
3576 << "Local and Remote descriptions must be applied to get the "
3577 << "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08003578 return false;
3579 }
3580 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003581 RTC_LOG(LS_INFO) << "Non-rejected SCTP m= section is needed to get the "
3582 << "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08003583 return false;
3584 }
3585
3586 return transport_controller_->GetSslRole(*sctp_transport_name_, role);
3587}
3588
3589bool PeerConnection::GetSslRole(const std::string& content_name,
3590 rtc::SSLRole* role) {
3591 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003592 RTC_LOG(LS_INFO)
3593 << "Local and Remote descriptions must be applied to get the "
3594 << "SSL Role of the session.";
Steve Anton75737c02017-11-06 10:37:17 -08003595 return false;
3596 }
3597
3598 return transport_controller_->GetSslRole(GetTransportName(content_name),
3599 role);
3600}
3601
Steve Anton75737c02017-11-06 10:37:17 -08003602// TODO(steveanton): Eventually it'd be nice to store the channels as a single
3603// vector of BaseChannel pointers instead of separate voice and video channel
3604// vectors. At that point, this will become a simple getter.
3605std::vector<cricket::BaseChannel*> PeerConnection::Channels() const {
3606 std::vector<cricket::BaseChannel*> channels;
Steve Anton4171afb2017-11-20 10:20:22 -08003607 if (voice_channel()) {
3608 channels.push_back(voice_channel());
3609 }
3610 if (video_channel()) {
3611 channels.push_back(video_channel());
3612 }
Steve Anton75737c02017-11-06 10:37:17 -08003613 if (rtp_data_channel_) {
3614 channels.push_back(rtp_data_channel_);
3615 }
3616 return channels;
3617}
3618
Steve Antonf8470812017-12-04 10:46:21 -08003619void PeerConnection::SetSessionError(SessionError error,
3620 const std::string& error_desc) {
3621 RTC_DCHECK_RUN_ON(signaling_thread());
3622 if (error != session_error_) {
3623 session_error_ = error;
3624 session_error_desc_ = error_desc;
Steve Anton75737c02017-11-06 10:37:17 -08003625 }
3626}
3627
Steve Anton3828c062017-12-06 10:34:51 -08003628RTCError PeerConnection::UpdateSessionState(SdpType type,
Steve Anton8a006912017-12-04 15:25:56 -08003629 cricket::ContentSource source) {
3630 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08003631
3632 // If there's already a pending error then no state transition should happen.
3633 // But all call-sites should be verifying this before calling us!
Steve Antonf8470812017-12-04 10:46:21 -08003634 RTC_DCHECK(session_error() == SessionError::kNone);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08003635
3636 // If this is an answer then we know whether to BUNDLE or not. If both the
3637 // local and remote side have agreed to BUNDLE, go ahead and enable it.
Steve Anton3828c062017-12-06 10:34:51 -08003638 if (type == SdpType::kAnswer) {
Steve Anton75737c02017-11-06 10:37:17 -08003639 const cricket::ContentGroup* local_bundle =
3640 local_description()->description()->GetGroupByName(
3641 cricket::GROUP_TYPE_BUNDLE);
3642 const cricket::ContentGroup* remote_bundle =
3643 remote_description()->description()->GetGroupByName(
3644 cricket::GROUP_TYPE_BUNDLE);
3645 if (local_bundle && remote_bundle) {
3646 // The answerer decides the transport to bundle on.
3647 const cricket::ContentGroup* answer_bundle =
3648 (source == cricket::CS_LOCAL ? local_bundle : remote_bundle);
3649 if (!EnableBundle(*answer_bundle)) {
Steve Anton8a006912017-12-04 15:25:56 -08003650 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3651 kEnableBundleFailed);
Steve Anton75737c02017-11-06 10:37:17 -08003652 }
3653 }
Steve Anton75737c02017-11-06 10:37:17 -08003654 }
Steve Anton6d6a2ae2017-12-04 17:19:47 -08003655
3656 // Only push down the transport description after potentially enabling BUNDLE;
3657 // we don't want to push down a description on a transport about to be
3658 // destroyed.
Steve Anton3828c062017-12-06 10:34:51 -08003659 RTCError error = PushdownTransportDescription(source, type);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08003660 if (!error.ok()) {
3661 return error;
3662 }
3663
3664 // If this is answer-ish we're ready to let media flow.
Steve Anton3828c062017-12-06 10:34:51 -08003665 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Antoned10bd92017-12-05 10:52:59 -08003666 EnableSending();
Steve Anton6d6a2ae2017-12-04 17:19:47 -08003667 }
3668
3669 // Update the signaling state according to the specified state machine (see
3670 // https://w3c.github.io/webrtc-pc/#rtcsignalingstate-enum).
Steve Anton3828c062017-12-06 10:34:51 -08003671 if (type == SdpType::kOffer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08003672 ChangeSignalingState(source == cricket::CS_LOCAL
3673 ? PeerConnectionInterface::kHaveLocalOffer
3674 : PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton3828c062017-12-06 10:34:51 -08003675 } else if (type == SdpType::kPrAnswer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08003676 ChangeSignalingState(source == cricket::CS_LOCAL
3677 ? PeerConnectionInterface::kHaveLocalPrAnswer
3678 : PeerConnectionInterface::kHaveRemotePrAnswer);
3679 } else {
Steve Anton3828c062017-12-06 10:34:51 -08003680 RTC_DCHECK(type == SdpType::kAnswer);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08003681 ChangeSignalingState(PeerConnectionInterface::kStable);
3682 }
3683
3684 // Update internal objects according to the session description's media
3685 // descriptions.
Steve Anton3828c062017-12-06 10:34:51 -08003686 error = PushdownMediaDescription(type, source);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08003687 if (!error.ok()) {
3688 SetSessionError(SessionError::kContent, error.message());
3689 }
3690 if (session_error() != SessionError::kNone) {
3691 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
3692 }
3693
Steve Anton8a006912017-12-04 15:25:56 -08003694 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08003695}
3696
Steve Anton8a006912017-12-04 15:25:56 -08003697RTCError PeerConnection::PushdownMediaDescription(
Steve Anton3828c062017-12-06 10:34:51 -08003698 SdpType type,
Steve Anton8a006912017-12-04 15:25:56 -08003699 cricket::ContentSource source) {
Steve Antoned10bd92017-12-05 10:52:59 -08003700 const SessionDescriptionInterface* sdesc =
3701 (source == cricket::CS_LOCAL ? local_description()
3702 : remote_description());
Steve Anton75737c02017-11-06 10:37:17 -08003703 RTC_DCHECK(sdesc);
Steve Antoned10bd92017-12-05 10:52:59 -08003704
3705 // Push down the new SDP media section for each audio/video transceiver.
3706 for (auto transceiver : transceivers_) {
Steve Anton75737c02017-11-06 10:37:17 -08003707 const ContentInfo* content_info =
Steve Antoned10bd92017-12-05 10:52:59 -08003708 FindMediaSectionForTransceiver(transceiver, sdesc);
3709 cricket::BaseChannel* channel = transceiver->internal()->channel();
3710 if (!channel || !content_info || content_info->rejected) {
Steve Anton75737c02017-11-06 10:37:17 -08003711 continue;
3712 }
3713 const MediaContentDescription* content_desc =
3714 static_cast<const MediaContentDescription*>(content_info->description);
Steve Antoned10bd92017-12-05 10:52:59 -08003715 if (!content_desc) {
3716 continue;
3717 }
3718 std::string error;
3719 bool success =
3720 (source == cricket::CS_LOCAL)
Steve Anton3828c062017-12-06 10:34:51 -08003721 ? channel->SetLocalContent(content_desc, type, &error)
3722 : channel->SetRemoteContent(content_desc, type, &error);
Steve Antoned10bd92017-12-05 10:52:59 -08003723 if (!success) {
3724 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, std::move(error));
3725 }
3726 }
3727
3728 // If using the RtpDataChannel, push down the new SDP section for it too.
3729 if (rtp_data_channel_) {
3730 const ContentInfo* data_content =
3731 cricket::GetFirstDataContent(sdesc->description());
3732 if (data_content && !data_content->rejected) {
3733 const MediaContentDescription* data_desc =
3734 static_cast<const MediaContentDescription*>(
3735 data_content->description);
3736 if (data_desc) {
3737 std::string error;
3738 bool success =
3739 (source == cricket::CS_LOCAL)
Steve Anton3828c062017-12-06 10:34:51 -08003740 ? rtp_data_channel_->SetLocalContent(data_desc, type, &error)
3741 : rtp_data_channel_->SetRemoteContent(data_desc, type,
Steve Antoned10bd92017-12-05 10:52:59 -08003742 &error);
3743 if (!success) {
3744 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3745 std::move(error));
3746 }
Steve Anton75737c02017-11-06 10:37:17 -08003747 }
3748 }
3749 }
Steve Antoned10bd92017-12-05 10:52:59 -08003750
Steve Anton75737c02017-11-06 10:37:17 -08003751 // Need complete offer/answer with an SCTP m= section before starting SCTP,
3752 // according to https://tools.ietf.org/html/draft-ietf-mmusic-sctp-sdp-19
3753 if (sctp_transport_ && local_description() && remote_description() &&
3754 cricket::GetFirstDataContent(local_description()->description()) &&
3755 cricket::GetFirstDataContent(remote_description()->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08003756 bool success = network_thread()->Invoke<bool>(
Steve Anton75737c02017-11-06 10:37:17 -08003757 RTC_FROM_HERE,
3758 rtc::Bind(&PeerConnection::PushdownSctpParameters_n, this, source));
Steve Anton8a006912017-12-04 15:25:56 -08003759 if (!success) {
3760 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
3761 "Failed to push down SCTP parameters.");
3762 }
Steve Anton75737c02017-11-06 10:37:17 -08003763 }
Steve Antoned10bd92017-12-05 10:52:59 -08003764
Steve Anton8a006912017-12-04 15:25:56 -08003765 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08003766}
3767
3768bool PeerConnection::PushdownSctpParameters_n(cricket::ContentSource source) {
3769 RTC_DCHECK(network_thread()->IsCurrent());
3770 RTC_DCHECK(local_description());
3771 RTC_DCHECK(remote_description());
3772 // Apply the SCTP port (which is hidden inside a DataCodec structure...)
3773 // When we support "max-message-size", that would also be pushed down here.
3774 return sctp_transport_->Start(
3775 GetSctpPort(local_description()->description()),
3776 GetSctpPort(remote_description()->description()));
3777}
3778
Steve Anton8a006912017-12-04 15:25:56 -08003779RTCError PeerConnection::PushdownTransportDescription(
3780 cricket::ContentSource source,
Steve Anton3828c062017-12-06 10:34:51 -08003781 SdpType type) {
Steve Anton8a006912017-12-04 15:25:56 -08003782 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08003783
Steve Anton8a006912017-12-04 15:25:56 -08003784 const SessionDescriptionInterface* sdesc =
3785 (source == cricket::CS_LOCAL ? local_description()
3786 : remote_description());
3787 RTC_DCHECK(sdesc);
3788 for (const cricket::TransportInfo& tinfo :
3789 sdesc->description()->transport_infos()) {
3790 std::string error;
3791 bool success;
3792 if (source == cricket::CS_LOCAL) {
3793 success = transport_controller_->SetLocalTransportDescription(
Steve Anton3828c062017-12-06 10:34:51 -08003794 tinfo.content_name, tinfo.description, type, &error);
Steve Anton8a006912017-12-04 15:25:56 -08003795 } else {
3796 success = transport_controller_->SetRemoteTransportDescription(
Steve Anton3828c062017-12-06 10:34:51 -08003797 tinfo.content_name, tinfo.description, type, &error);
Steve Anton8a006912017-12-04 15:25:56 -08003798 }
3799 if (!success) {
3800 LOG_AND_RETURN_ERROR(
3801 RTCErrorType::INVALID_PARAMETER,
3802 "Failed to push down transport description: " + error);
Steve Anton75737c02017-11-06 10:37:17 -08003803 }
3804 }
3805
Steve Anton8a006912017-12-04 15:25:56 -08003806 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08003807}
3808
3809bool PeerConnection::GetTransportDescription(
3810 const SessionDescription* description,
3811 const std::string& content_name,
3812 cricket::TransportDescription* tdesc) {
3813 if (!description || !tdesc) {
3814 return false;
3815 }
3816 const TransportInfo* transport_info =
3817 description->GetTransportInfoByName(content_name);
3818 if (!transport_info) {
3819 return false;
3820 }
3821 *tdesc = transport_info->description;
3822 return true;
3823}
3824
3825bool PeerConnection::EnableBundle(const cricket::ContentGroup& bundle) {
3826 const std::string* first_content_name = bundle.FirstContentName();
3827 if (!first_content_name) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003828 RTC_LOG(LS_WARNING) << "Tried to BUNDLE with no contents.";
Steve Anton75737c02017-11-06 10:37:17 -08003829 return false;
3830 }
3831 const std::string& transport_name = *first_content_name;
3832
3833 auto maybe_set_transport = [this, bundle,
3834 transport_name](cricket::BaseChannel* ch) {
3835 if (!ch || !bundle.HasContentName(ch->content_name())) {
Steve Antoned10bd92017-12-05 10:52:59 -08003836 return;
Steve Anton75737c02017-11-06 10:37:17 -08003837 }
3838
3839 std::string old_transport_name = ch->transport_name();
3840 if (old_transport_name == transport_name) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003841 RTC_LOG(LS_INFO) << "BUNDLE already enabled for " << ch->content_name()
3842 << " on " << transport_name << ".";
Steve Antoned10bd92017-12-05 10:52:59 -08003843 return;
Steve Anton75737c02017-11-06 10:37:17 -08003844 }
3845
3846 cricket::DtlsTransportInternal* rtp_dtls_transport =
3847 transport_controller_->CreateDtlsTransport(
3848 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
3849 bool need_rtcp = (ch->rtcp_dtls_transport() != nullptr);
3850 cricket::DtlsTransportInternal* rtcp_dtls_transport = nullptr;
3851 if (need_rtcp) {
3852 rtcp_dtls_transport = transport_controller_->CreateDtlsTransport(
3853 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
3854 }
3855
3856 ch->SetTransports(rtp_dtls_transport, rtcp_dtls_transport);
Mirko Bonadei675513b2017-11-09 11:09:25 +01003857 RTC_LOG(LS_INFO) << "Enabled BUNDLE for " << ch->content_name() << " on "
3858 << transport_name << ".";
Steve Anton75737c02017-11-06 10:37:17 -08003859 transport_controller_->DestroyDtlsTransport(
3860 old_transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
3861 // If the channel needs rtcp, it means that the channel used to have a
3862 // rtcp transport which needs to be deleted now.
3863 if (need_rtcp) {
3864 transport_controller_->DestroyDtlsTransport(
3865 old_transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
3866 }
Steve Anton75737c02017-11-06 10:37:17 -08003867 };
3868
Steve Antoned10bd92017-12-05 10:52:59 -08003869 for (auto transceiver : transceivers_) {
3870 maybe_set_transport(transceiver->internal()->channel());
Steve Anton75737c02017-11-06 10:37:17 -08003871 }
Steve Antoned10bd92017-12-05 10:52:59 -08003872 maybe_set_transport(rtp_data_channel_);
3873
Steve Anton75737c02017-11-06 10:37:17 -08003874 // For SCTP, transport creation/deletion happens here instead of in the
3875 // object itself.
3876 if (sctp_transport_) {
3877 RTC_DCHECK(sctp_transport_name_);
3878 RTC_DCHECK(sctp_content_name_);
3879 if (transport_name != *sctp_transport_name_ &&
3880 bundle.HasContentName(*sctp_content_name_)) {
3881 network_thread()->Invoke<void>(
3882 RTC_FROM_HERE, rtc::Bind(&PeerConnection::ChangeSctpTransport_n, this,
3883 transport_name));
3884 }
3885 }
3886
3887 return true;
3888}
3889
Steve Anton75737c02017-11-06 10:37:17 -08003890cricket::IceConfig PeerConnection::ParseIceConfig(
3891 const PeerConnectionInterface::RTCConfiguration& config) const {
3892 cricket::ContinualGatheringPolicy gathering_policy;
3893 // TODO(honghaiz): Add the third continual gathering policy in
3894 // PeerConnectionInterface and map it to GATHER_CONTINUALLY_AND_RECOVER.
3895 switch (config.continual_gathering_policy) {
3896 case PeerConnectionInterface::GATHER_ONCE:
3897 gathering_policy = cricket::GATHER_ONCE;
3898 break;
3899 case PeerConnectionInterface::GATHER_CONTINUALLY:
3900 gathering_policy = cricket::GATHER_CONTINUALLY;
3901 break;
3902 default:
3903 RTC_NOTREACHED();
3904 gathering_policy = cricket::GATHER_ONCE;
3905 }
3906 cricket::IceConfig ice_config;
3907 ice_config.receiving_timeout = config.ice_connection_receiving_timeout;
3908 ice_config.prioritize_most_likely_candidate_pairs =
3909 config.prioritize_most_likely_ice_candidate_pairs;
3910 ice_config.backup_connection_ping_interval =
3911 config.ice_backup_candidate_pair_ping_interval;
3912 ice_config.continual_gathering_policy = gathering_policy;
3913 ice_config.presume_writable_when_fully_relayed =
3914 config.presume_writable_when_fully_relayed;
3915 ice_config.ice_check_min_interval = config.ice_check_min_interval;
3916 ice_config.regather_all_networks_interval_range =
3917 config.ice_regather_interval_range;
3918 return ice_config;
3919}
3920
Steve Anton75737c02017-11-06 10:37:17 -08003921bool PeerConnection::GetLocalTrackIdBySsrc(uint32_t ssrc,
3922 std::string* track_id) {
3923 if (!local_description()) {
3924 return false;
3925 }
3926 return webrtc::GetTrackIdBySsrc(local_description()->description(), ssrc,
3927 track_id);
3928}
3929
3930bool PeerConnection::GetRemoteTrackIdBySsrc(uint32_t ssrc,
3931 std::string* track_id) {
3932 if (!remote_description()) {
3933 return false;
3934 }
3935 return webrtc::GetTrackIdBySsrc(remote_description()->description(), ssrc,
3936 track_id);
3937}
3938
3939bool PeerConnection::SendData(const cricket::SendDataParams& params,
3940 const rtc::CopyOnWriteBuffer& payload,
3941 cricket::SendDataResult* result) {
3942 if (!rtp_data_channel_ && !sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003943 RTC_LOG(LS_ERROR) << "SendData called when rtp_data_channel_ "
3944 << "and sctp_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08003945 return false;
3946 }
3947 return rtp_data_channel_
3948 ? rtp_data_channel_->SendData(params, payload, result)
3949 : network_thread()->Invoke<bool>(
3950 RTC_FROM_HERE,
3951 Bind(&cricket::SctpTransportInternal::SendData,
3952 sctp_transport_.get(), params, payload, result));
3953}
3954
3955bool PeerConnection::ConnectDataChannel(DataChannel* webrtc_data_channel) {
3956 if (!rtp_data_channel_ && !sctp_transport_) {
3957 // Don't log an error here, because DataChannels are expected to call
3958 // ConnectDataChannel in this state. It's the only way to initially tell
3959 // whether or not the underlying transport is ready.
3960 return false;
3961 }
3962 if (rtp_data_channel_) {
3963 rtp_data_channel_->SignalReadyToSendData.connect(
3964 webrtc_data_channel, &DataChannel::OnChannelReady);
3965 rtp_data_channel_->SignalDataReceived.connect(webrtc_data_channel,
3966 &DataChannel::OnDataReceived);
3967 } else {
3968 SignalSctpReadyToSendData.connect(webrtc_data_channel,
3969 &DataChannel::OnChannelReady);
3970 SignalSctpDataReceived.connect(webrtc_data_channel,
3971 &DataChannel::OnDataReceived);
3972 SignalSctpStreamClosedRemotely.connect(
3973 webrtc_data_channel, &DataChannel::OnStreamClosedRemotely);
3974 }
3975 return true;
3976}
3977
3978void PeerConnection::DisconnectDataChannel(DataChannel* webrtc_data_channel) {
3979 if (!rtp_data_channel_ && !sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003980 RTC_LOG(LS_ERROR)
3981 << "DisconnectDataChannel called when rtp_data_channel_ and "
3982 "sctp_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08003983 return;
3984 }
3985 if (rtp_data_channel_) {
3986 rtp_data_channel_->SignalReadyToSendData.disconnect(webrtc_data_channel);
3987 rtp_data_channel_->SignalDataReceived.disconnect(webrtc_data_channel);
3988 } else {
3989 SignalSctpReadyToSendData.disconnect(webrtc_data_channel);
3990 SignalSctpDataReceived.disconnect(webrtc_data_channel);
3991 SignalSctpStreamClosedRemotely.disconnect(webrtc_data_channel);
3992 }
3993}
3994
3995void PeerConnection::AddSctpDataStream(int sid) {
3996 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003997 RTC_LOG(LS_ERROR)
3998 << "AddSctpDataStream called when sctp_transport_ is NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08003999 return;
4000 }
4001 network_thread()->Invoke<void>(
4002 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::OpenStream,
4003 sctp_transport_.get(), sid));
4004}
4005
4006void PeerConnection::RemoveSctpDataStream(int sid) {
4007 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004008 RTC_LOG(LS_ERROR) << "RemoveSctpDataStream called when sctp_transport_ is "
4009 << "NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08004010 return;
4011 }
4012 network_thread()->Invoke<void>(
4013 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::ResetStream,
4014 sctp_transport_.get(), sid));
4015}
4016
4017bool PeerConnection::ReadyToSendData() const {
4018 return (rtp_data_channel_ && rtp_data_channel_->ready_to_send_data()) ||
4019 sctp_ready_to_send_data_;
4020}
4021
4022std::unique_ptr<SessionStats> PeerConnection::GetSessionStats_s() {
4023 RTC_DCHECK(signaling_thread()->IsCurrent());
4024 ChannelNamePairs channel_name_pairs;
4025 if (voice_channel()) {
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004026 channel_name_pairs.voice = ChannelNamePair(
4027 voice_channel()->content_name(), voice_channel()->transport_name());
Steve Anton75737c02017-11-06 10:37:17 -08004028 }
4029 if (video_channel()) {
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004030 channel_name_pairs.video = ChannelNamePair(
4031 video_channel()->content_name(), video_channel()->transport_name());
Steve Anton75737c02017-11-06 10:37:17 -08004032 }
4033 if (rtp_data_channel()) {
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004034 channel_name_pairs.data =
Steve Anton75737c02017-11-06 10:37:17 -08004035 ChannelNamePair(rtp_data_channel()->content_name(),
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004036 rtp_data_channel()->transport_name());
Steve Anton75737c02017-11-06 10:37:17 -08004037 }
4038 if (sctp_transport_) {
4039 RTC_DCHECK(sctp_content_name_);
4040 RTC_DCHECK(sctp_transport_name_);
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004041 channel_name_pairs.data =
4042 ChannelNamePair(*sctp_content_name_, *sctp_transport_name_);
Steve Anton75737c02017-11-06 10:37:17 -08004043 }
4044 return GetSessionStats(channel_name_pairs);
4045}
4046
4047std::unique_ptr<SessionStats> PeerConnection::GetSessionStats(
4048 const ChannelNamePairs& channel_name_pairs) {
4049 if (network_thread()->IsCurrent()) {
4050 return GetSessionStats_n(channel_name_pairs);
4051 }
4052 return network_thread()->Invoke<std::unique_ptr<SessionStats>>(
4053 RTC_FROM_HERE,
4054 rtc::Bind(&PeerConnection::GetSessionStats_n, this, channel_name_pairs));
4055}
4056
4057bool PeerConnection::GetLocalCertificate(
4058 const std::string& transport_name,
4059 rtc::scoped_refptr<rtc::RTCCertificate>* certificate) {
4060 return transport_controller_->GetLocalCertificate(transport_name,
4061 certificate);
4062}
4063
4064std::unique_ptr<rtc::SSLCertificate> PeerConnection::GetRemoteSSLCertificate(
4065 const std::string& transport_name) {
4066 return transport_controller_->GetRemoteSSLCertificate(transport_name);
4067}
4068
4069cricket::DataChannelType PeerConnection::data_channel_type() const {
4070 return data_channel_type_;
4071}
4072
4073bool PeerConnection::IceRestartPending(const std::string& content_name) const {
4074 return pending_ice_restarts_.find(content_name) !=
4075 pending_ice_restarts_.end();
4076}
4077
Steve Anton75737c02017-11-06 10:37:17 -08004078bool PeerConnection::NeedsIceRestart(const std::string& content_name) const {
4079 return transport_controller_->NeedsIceRestart(content_name);
4080}
4081
4082void PeerConnection::OnCertificateReady(
4083 const rtc::scoped_refptr<rtc::RTCCertificate>& certificate) {
4084 transport_controller_->SetLocalCertificate(certificate);
4085}
4086
4087void PeerConnection::OnDtlsSrtpSetupFailure(cricket::BaseChannel*, bool rtcp) {
Steve Antonf8470812017-12-04 10:46:21 -08004088 SetSessionError(SessionError::kTransport,
4089 rtcp ? kDtlsSrtpSetupFailureRtcp : kDtlsSrtpSetupFailureRtp);
Steve Anton75737c02017-11-06 10:37:17 -08004090}
4091
4092void PeerConnection::OnTransportControllerConnectionState(
4093 cricket::IceConnectionState state) {
4094 switch (state) {
4095 case cricket::kIceConnectionConnecting:
4096 // If the current state is Connected or Completed, then there were
4097 // writable channels but now there are not, so the next state must
4098 // be Disconnected.
4099 // kIceConnectionConnecting is currently used as the default,
4100 // un-connected state by the TransportController, so its only use is
4101 // detecting disconnections.
4102 if (ice_connection_state_ ==
4103 PeerConnectionInterface::kIceConnectionConnected ||
4104 ice_connection_state_ ==
4105 PeerConnectionInterface::kIceConnectionCompleted) {
4106 SetIceConnectionState(
4107 PeerConnectionInterface::kIceConnectionDisconnected);
4108 }
4109 break;
4110 case cricket::kIceConnectionFailed:
4111 SetIceConnectionState(PeerConnectionInterface::kIceConnectionFailed);
4112 break;
4113 case cricket::kIceConnectionConnected:
Mirko Bonadei675513b2017-11-09 11:09:25 +01004114 RTC_LOG(LS_INFO) << "Changing to ICE connected state because "
4115 << "all transports are writable.";
Steve Anton75737c02017-11-06 10:37:17 -08004116 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
4117 break;
4118 case cricket::kIceConnectionCompleted:
Mirko Bonadei675513b2017-11-09 11:09:25 +01004119 RTC_LOG(LS_INFO) << "Changing to ICE completed state because "
4120 << "all transports are complete.";
Steve Anton75737c02017-11-06 10:37:17 -08004121 if (ice_connection_state_ !=
4122 PeerConnectionInterface::kIceConnectionConnected) {
4123 // If jumping directly from "checking" to "connected",
4124 // signal "connected" first.
4125 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
4126 }
4127 SetIceConnectionState(PeerConnectionInterface::kIceConnectionCompleted);
4128 if (metrics_observer()) {
4129 ReportTransportStats();
4130 }
4131 break;
4132 default:
4133 RTC_NOTREACHED();
4134 }
4135}
4136
4137void PeerConnection::OnTransportControllerCandidatesGathered(
4138 const std::string& transport_name,
4139 const cricket::Candidates& candidates) {
4140 RTC_DCHECK(signaling_thread()->IsCurrent());
4141 int sdp_mline_index;
4142 if (!GetLocalCandidateMediaIndex(transport_name, &sdp_mline_index)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004143 RTC_LOG(LS_ERROR)
4144 << "OnTransportControllerCandidatesGathered: content name "
4145 << transport_name << " not found";
Steve Anton75737c02017-11-06 10:37:17 -08004146 return;
4147 }
4148
4149 for (cricket::Candidates::const_iterator citer = candidates.begin();
4150 citer != candidates.end(); ++citer) {
4151 // Use transport_name as the candidate media id.
4152 std::unique_ptr<JsepIceCandidate> candidate(
4153 new JsepIceCandidate(transport_name, sdp_mline_index, *citer));
4154 if (local_description()) {
4155 mutable_local_description()->AddCandidate(candidate.get());
4156 }
4157 OnIceCandidate(std::move(candidate));
4158 }
4159}
4160
4161void PeerConnection::OnTransportControllerCandidatesRemoved(
4162 const std::vector<cricket::Candidate>& candidates) {
4163 RTC_DCHECK(signaling_thread()->IsCurrent());
4164 // Sanity check.
4165 for (const cricket::Candidate& candidate : candidates) {
4166 if (candidate.transport_name().empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004167 RTC_LOG(LS_ERROR) << "OnTransportControllerCandidatesRemoved: "
4168 << "empty content name in candidate "
4169 << candidate.ToString();
Steve Anton75737c02017-11-06 10:37:17 -08004170 return;
4171 }
4172 }
4173
4174 if (local_description()) {
4175 mutable_local_description()->RemoveCandidates(candidates);
4176 }
4177 OnIceCandidatesRemoved(candidates);
4178}
4179
4180void PeerConnection::OnTransportControllerDtlsHandshakeError(
4181 rtc::SSLHandshakeError error) {
4182 if (metrics_observer()) {
4183 metrics_observer()->IncrementEnumCounter(
4184 webrtc::kEnumCounterDtlsHandshakeError, static_cast<int>(error),
4185 static_cast<int>(rtc::SSLHandshakeError::MAX_VALUE));
4186 }
4187}
4188
Steve Antoned10bd92017-12-05 10:52:59 -08004189void PeerConnection::EnableSending() {
4190 for (auto transceiver : transceivers_) {
4191 cricket::BaseChannel* channel = transceiver->internal()->channel();
4192 if (channel && !channel->enabled()) {
4193 channel->Enable(true);
4194 }
Steve Anton75737c02017-11-06 10:37:17 -08004195 }
4196
Steve Anton4171afb2017-11-20 10:20:22 -08004197 if (rtp_data_channel_ && !rtp_data_channel_->enabled()) {
Steve Anton75737c02017-11-06 10:37:17 -08004198 rtp_data_channel_->Enable(true);
Steve Anton4171afb2017-11-20 10:20:22 -08004199 }
Steve Anton75737c02017-11-06 10:37:17 -08004200}
4201
4202// Returns the media index for a local ice candidate given the content name.
4203bool PeerConnection::GetLocalCandidateMediaIndex(
4204 const std::string& content_name,
4205 int* sdp_mline_index) {
4206 if (!local_description() || !sdp_mline_index) {
4207 return false;
4208 }
4209
4210 bool content_found = false;
4211 const ContentInfos& contents = local_description()->description()->contents();
4212 for (size_t index = 0; index < contents.size(); ++index) {
4213 if (contents[index].name == content_name) {
4214 *sdp_mline_index = static_cast<int>(index);
4215 content_found = true;
4216 break;
4217 }
4218 }
4219 return content_found;
4220}
4221
4222bool PeerConnection::UseCandidatesInSessionDescription(
4223 const SessionDescriptionInterface* remote_desc) {
4224 if (!remote_desc) {
4225 return true;
4226 }
4227 bool ret = true;
4228
4229 for (size_t m = 0; m < remote_desc->number_of_mediasections(); ++m) {
4230 const IceCandidateCollection* candidates = remote_desc->candidates(m);
4231 for (size_t n = 0; n < candidates->count(); ++n) {
4232 const IceCandidateInterface* candidate = candidates->at(n);
4233 bool valid = false;
4234 if (!ReadyToUseRemoteCandidate(candidate, remote_desc, &valid)) {
4235 if (valid) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004236 RTC_LOG(LS_INFO)
4237 << "UseCandidatesInSessionDescription: Not ready to use "
4238 << "candidate.";
Steve Anton75737c02017-11-06 10:37:17 -08004239 }
4240 continue;
4241 }
4242 ret = UseCandidate(candidate);
4243 if (!ret) {
4244 break;
4245 }
4246 }
4247 }
4248 return ret;
4249}
4250
4251bool PeerConnection::UseCandidate(const IceCandidateInterface* candidate) {
4252 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
4253 size_t remote_content_size =
4254 remote_description()->description()->contents().size();
4255 if (mediacontent_index >= remote_content_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004256 RTC_LOG(LS_ERROR) << "UseCandidate: Invalid candidate media index.";
Steve Anton75737c02017-11-06 10:37:17 -08004257 return false;
4258 }
4259
4260 cricket::ContentInfo content =
4261 remote_description()->description()->contents()[mediacontent_index];
4262 std::vector<cricket::Candidate> candidates;
4263 candidates.push_back(candidate->candidate());
4264 // Invoking BaseSession method to handle remote candidates.
4265 std::string error;
4266 if (transport_controller_->AddRemoteCandidates(content.name, candidates,
4267 &error)) {
4268 // Candidates successfully submitted for checking.
4269 if (ice_connection_state_ == PeerConnectionInterface::kIceConnectionNew ||
4270 ice_connection_state_ ==
4271 PeerConnectionInterface::kIceConnectionDisconnected) {
4272 // If state is New, then the session has just gotten its first remote ICE
4273 // candidates, so go to Checking.
4274 // If state is Disconnected, the session is re-using old candidates or
4275 // receiving additional ones, so go to Checking.
4276 // If state is Connected, stay Connected.
4277 // TODO(bemasc): If state is Connected, and the new candidates are for a
4278 // newly added transport, then the state actually _should_ move to
4279 // checking. Add a way to distinguish that case.
4280 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
4281 }
4282 // TODO(bemasc): If state is Completed, go back to Connected.
4283 } else {
4284 if (!error.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004285 RTC_LOG(LS_WARNING) << error;
Steve Anton75737c02017-11-06 10:37:17 -08004286 }
4287 }
4288 return true;
4289}
4290
4291void PeerConnection::RemoveUnusedChannels(const SessionDescription* desc) {
Steve Anton75737c02017-11-06 10:37:17 -08004292 // Destroy video channel first since it may have a pointer to the
4293 // voice channel.
4294 const cricket::ContentInfo* video_info = cricket::GetFirstVideoContent(desc);
Steve Anton6fec8802017-12-04 10:37:29 -08004295 if (!video_info || video_info->rejected) {
4296 DestroyTransceiverChannel(GetVideoTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08004297 }
4298
Steve Anton6fec8802017-12-04 10:37:29 -08004299 const cricket::ContentInfo* audio_info = cricket::GetFirstAudioContent(desc);
4300 if (!audio_info || audio_info->rejected) {
4301 DestroyTransceiverChannel(GetAudioTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08004302 }
4303
4304 const cricket::ContentInfo* data_info = cricket::GetFirstDataContent(desc);
4305 if (!data_info || data_info->rejected) {
Steve Anton6fec8802017-12-04 10:37:29 -08004306 DestroyDataChannel();
Steve Anton75737c02017-11-06 10:37:17 -08004307 }
4308}
4309
Steve Antoneda6ccd2017-12-04 10:21:55 -08004310std::string PeerConnection::GetTransportNameForMediaSection(
4311 const std::string& mid,
4312 const cricket::ContentGroup* bundle_group) const {
4313 if (!bundle_group) {
4314 return mid;
Steve Anton75737c02017-11-06 10:37:17 -08004315 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08004316 const std::string* first_content_name = bundle_group->FirstContentName();
Steve Anton75737c02017-11-06 10:37:17 -08004317 if (!first_content_name) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004318 RTC_LOG(LS_WARNING) << "Tried to BUNDLE with no contents.";
Steve Antoneda6ccd2017-12-04 10:21:55 -08004319 return mid;
Steve Anton75737c02017-11-06 10:37:17 -08004320 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08004321 if (!bundle_group->HasContentName(mid)) {
4322 RTC_LOG(LS_WARNING) << mid << " is not part of any bundle group";
4323 return mid;
Steve Anton75737c02017-11-06 10:37:17 -08004324 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08004325 RTC_LOG(LS_INFO) << "Bundling " << mid << " on " << *first_content_name;
4326 return *first_content_name;
Steve Anton75737c02017-11-06 10:37:17 -08004327}
4328
Steve Anton8a006912017-12-04 15:25:56 -08004329RTCError PeerConnection::CreateChannels(const SessionDescription* desc) {
Steve Antoneda6ccd2017-12-04 10:21:55 -08004330 RTC_DCHECK(desc);
4331
Steve Anton75737c02017-11-06 10:37:17 -08004332 const cricket::ContentGroup* bundle_group = nullptr;
4333 if (configuration_.bundle_policy ==
4334 PeerConnectionInterface::kBundlePolicyMaxBundle) {
4335 bundle_group = desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
4336 if (!bundle_group) {
Steve Anton8a006912017-12-04 15:25:56 -08004337 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
4338 "max-bundle configured but session description "
4339 "has no BUNDLE group");
Steve Anton75737c02017-11-06 10:37:17 -08004340 }
4341 }
4342
Steve Antoneda6ccd2017-12-04 10:21:55 -08004343 // Creating the media channels and transport proxies.
4344 const cricket::ContentInfo* voice = cricket::GetFirstAudioContent(desc);
4345 if (voice && !voice->rejected &&
4346 !GetAudioTransceiver()->internal()->channel()) {
4347 cricket::VoiceChannel* voice_channel = CreateVoiceChannel(
4348 voice->name,
4349 GetTransportNameForMediaSection(voice->name, bundle_group));
4350 if (!voice_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08004351 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
4352 "Failed to create voice channel.");
Steve Antoneda6ccd2017-12-04 10:21:55 -08004353 }
4354 GetAudioTransceiver()->internal()->SetChannel(voice_channel);
4355 }
4356
Steve Anton75737c02017-11-06 10:37:17 -08004357 const cricket::ContentInfo* video = cricket::GetFirstVideoContent(desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08004358 if (video && !video->rejected &&
4359 !GetVideoTransceiver()->internal()->channel()) {
4360 cricket::VideoChannel* video_channel = CreateVideoChannel(
4361 video->name,
4362 GetTransportNameForMediaSection(video->name, bundle_group));
4363 if (!video_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08004364 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
4365 "Failed to create video channel.");
Steve Anton75737c02017-11-06 10:37:17 -08004366 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08004367 GetVideoTransceiver()->internal()->SetChannel(video_channel);
Steve Anton75737c02017-11-06 10:37:17 -08004368 }
4369
4370 const cricket::ContentInfo* data = cricket::GetFirstDataContent(desc);
4371 if (data_channel_type_ != cricket::DCT_NONE && data && !data->rejected &&
4372 !rtp_data_channel_ && !sctp_transport_) {
Steve Antoneda6ccd2017-12-04 10:21:55 -08004373 if (!CreateDataChannel(data->name, GetTransportNameForMediaSection(
4374 data->name, bundle_group))) {
Steve Anton8a006912017-12-04 15:25:56 -08004375 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
4376 "Failed to create data channel.");
Steve Anton75737c02017-11-06 10:37:17 -08004377 }
4378 }
4379
Steve Anton8a006912017-12-04 15:25:56 -08004380 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08004381}
4382
Steve Anton4171afb2017-11-20 10:20:22 -08004383// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08004384cricket::VoiceChannel* PeerConnection::CreateVoiceChannel(
4385 const std::string& mid,
4386 const std::string& transport_name) {
Steve Anton75737c02017-11-06 10:37:17 -08004387 cricket::DtlsTransportInternal* rtp_dtls_transport =
4388 transport_controller_->CreateDtlsTransport(
4389 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4390 cricket::DtlsTransportInternal* rtcp_dtls_transport = nullptr;
4391 if (configuration_.rtcp_mux_policy !=
4392 PeerConnectionInterface::kRtcpMuxPolicyRequire) {
4393 rtcp_dtls_transport = transport_controller_->CreateDtlsTransport(
4394 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
4395 }
4396
4397 cricket::VoiceChannel* voice_channel = channel_manager()->CreateVoiceChannel(
4398 call_.get(), configuration_.media_config, rtp_dtls_transport,
Steve Antoneda6ccd2017-12-04 10:21:55 -08004399 rtcp_dtls_transport, signaling_thread(), mid, SrtpRequired(),
4400 audio_options_);
Steve Anton75737c02017-11-06 10:37:17 -08004401 if (!voice_channel) {
4402 transport_controller_->DestroyDtlsTransport(
4403 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4404 if (rtcp_dtls_transport) {
4405 transport_controller_->DestroyDtlsTransport(
4406 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
4407 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08004408 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08004409 }
Steve Anton75737c02017-11-06 10:37:17 -08004410 voice_channel->SignalRtcpMuxFullyActive.connect(
4411 this, &PeerConnection::DestroyRtcpTransport_n);
4412 voice_channel->SignalDtlsSrtpSetupFailure.connect(
4413 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08004414 voice_channel->SignalSentPacket.connect(this,
4415 &PeerConnection::OnSentPacket_w);
Steve Anton4171afb2017-11-20 10:20:22 -08004416
Steve Antoneda6ccd2017-12-04 10:21:55 -08004417 return voice_channel;
Steve Anton75737c02017-11-06 10:37:17 -08004418}
4419
Steve Anton4171afb2017-11-20 10:20:22 -08004420// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08004421cricket::VideoChannel* PeerConnection::CreateVideoChannel(
4422 const std::string& mid,
4423 const std::string& transport_name) {
Steve Anton75737c02017-11-06 10:37:17 -08004424 cricket::DtlsTransportInternal* rtp_dtls_transport =
4425 transport_controller_->CreateDtlsTransport(
4426 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4427 cricket::DtlsTransportInternal* rtcp_dtls_transport = nullptr;
4428 if (configuration_.rtcp_mux_policy !=
4429 PeerConnectionInterface::kRtcpMuxPolicyRequire) {
4430 rtcp_dtls_transport = transport_controller_->CreateDtlsTransport(
4431 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
4432 }
4433
4434 cricket::VideoChannel* video_channel = channel_manager()->CreateVideoChannel(
4435 call_.get(), configuration_.media_config, rtp_dtls_transport,
Steve Antoneda6ccd2017-12-04 10:21:55 -08004436 rtcp_dtls_transport, signaling_thread(), mid, SrtpRequired(),
4437 video_options_);
Steve Anton75737c02017-11-06 10:37:17 -08004438
4439 if (!video_channel) {
4440 transport_controller_->DestroyDtlsTransport(
4441 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4442 if (rtcp_dtls_transport) {
4443 transport_controller_->DestroyDtlsTransport(
4444 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
4445 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08004446 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08004447 }
Steve Anton75737c02017-11-06 10:37:17 -08004448 video_channel->SignalRtcpMuxFullyActive.connect(
4449 this, &PeerConnection::DestroyRtcpTransport_n);
4450 video_channel->SignalDtlsSrtpSetupFailure.connect(
4451 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08004452 video_channel->SignalSentPacket.connect(this,
4453 &PeerConnection::OnSentPacket_w);
Steve Anton4171afb2017-11-20 10:20:22 -08004454
Steve Antoneda6ccd2017-12-04 10:21:55 -08004455 return video_channel;
Steve Anton75737c02017-11-06 10:37:17 -08004456}
4457
Steve Antoneda6ccd2017-12-04 10:21:55 -08004458bool PeerConnection::CreateDataChannel(const std::string& mid,
4459 const std::string& transport_name) {
Steve Anton75737c02017-11-06 10:37:17 -08004460 bool sctp = (data_channel_type_ == cricket::DCT_SCTP);
4461 if (sctp) {
4462 if (!sctp_factory_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004463 RTC_LOG(LS_ERROR)
Steve Anton75737c02017-11-06 10:37:17 -08004464 << "Trying to create SCTP transport, but didn't compile with "
4465 "SCTP support (HAVE_SCTP)";
4466 return false;
4467 }
4468 if (!network_thread()->Invoke<bool>(
4469 RTC_FROM_HERE, rtc::Bind(&PeerConnection::CreateSctpTransport_n,
Steve Antoneda6ccd2017-12-04 10:21:55 -08004470 this, mid, transport_name))) {
Steve Anton75737c02017-11-06 10:37:17 -08004471 return false;
4472 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08004473 for (const auto& channel : sctp_data_channels_) {
4474 channel->OnTransportChannelCreated();
4475 }
Steve Anton75737c02017-11-06 10:37:17 -08004476 } else {
Steve Anton75737c02017-11-06 10:37:17 -08004477 cricket::DtlsTransportInternal* rtp_dtls_transport =
4478 transport_controller_->CreateDtlsTransport(
4479 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4480 cricket::DtlsTransportInternal* rtcp_dtls_transport = nullptr;
4481 if (configuration_.rtcp_mux_policy !=
4482 PeerConnectionInterface::kRtcpMuxPolicyRequire) {
4483 rtcp_dtls_transport = transport_controller_->CreateDtlsTransport(
4484 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
4485 }
4486
4487 rtp_data_channel_ = channel_manager()->CreateRtpDataChannel(
4488 configuration_.media_config, rtp_dtls_transport, rtcp_dtls_transport,
Steve Antoneda6ccd2017-12-04 10:21:55 -08004489 signaling_thread(), mid, SrtpRequired());
Steve Anton75737c02017-11-06 10:37:17 -08004490
4491 if (!rtp_data_channel_) {
4492 transport_controller_->DestroyDtlsTransport(
4493 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4494 if (rtcp_dtls_transport) {
4495 transport_controller_->DestroyDtlsTransport(
4496 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
4497 }
4498 return false;
4499 }
4500
4501 rtp_data_channel_->SignalRtcpMuxFullyActive.connect(
4502 this, &PeerConnection::DestroyRtcpTransport_n);
4503 rtp_data_channel_->SignalDtlsSrtpSetupFailure.connect(
4504 this, &PeerConnection::OnDtlsSrtpSetupFailure);
4505 rtp_data_channel_->SignalSentPacket.connect(
4506 this, &PeerConnection::OnSentPacket_w);
4507 }
4508
Steve Anton75737c02017-11-06 10:37:17 -08004509 return true;
4510}
4511
4512Call::Stats PeerConnection::GetCallStats() {
4513 if (!worker_thread()->IsCurrent()) {
4514 return worker_thread()->Invoke<Call::Stats>(
4515 RTC_FROM_HERE, rtc::Bind(&PeerConnection::GetCallStats, this));
4516 }
4517 if (call_) {
4518 return call_->GetStats();
4519 } else {
4520 return Call::Stats();
4521 }
4522}
4523
4524std::unique_ptr<SessionStats> PeerConnection::GetSessionStats_n(
4525 const ChannelNamePairs& channel_name_pairs) {
4526 RTC_DCHECK(network_thread()->IsCurrent());
4527 std::unique_ptr<SessionStats> session_stats(new SessionStats());
4528 for (const auto channel_name_pair :
4529 {&channel_name_pairs.voice, &channel_name_pairs.video,
4530 &channel_name_pairs.data}) {
4531 if (*channel_name_pair) {
4532 cricket::TransportStats transport_stats;
4533 if (!transport_controller_->GetStats((*channel_name_pair)->transport_name,
4534 &transport_stats)) {
4535 return nullptr;
4536 }
4537 session_stats->proxy_to_transport[(*channel_name_pair)->content_name] =
4538 (*channel_name_pair)->transport_name;
4539 session_stats->transport_stats[(*channel_name_pair)->transport_name] =
4540 std::move(transport_stats);
4541 }
4542 }
4543 return session_stats;
4544}
4545
4546bool PeerConnection::CreateSctpTransport_n(const std::string& content_name,
4547 const std::string& transport_name) {
4548 RTC_DCHECK(network_thread()->IsCurrent());
4549 RTC_DCHECK(sctp_factory_);
4550 cricket::DtlsTransportInternal* tc =
4551 transport_controller_->CreateDtlsTransport_n(
4552 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4553 sctp_transport_ = sctp_factory_->CreateSctpTransport(tc);
4554 RTC_DCHECK(sctp_transport_);
4555 sctp_invoker_.reset(new rtc::AsyncInvoker());
4556 sctp_transport_->SignalReadyToSendData.connect(
4557 this, &PeerConnection::OnSctpTransportReadyToSendData_n);
4558 sctp_transport_->SignalDataReceived.connect(
4559 this, &PeerConnection::OnSctpTransportDataReceived_n);
4560 sctp_transport_->SignalStreamClosedRemotely.connect(
4561 this, &PeerConnection::OnSctpStreamClosedRemotely_n);
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004562 sctp_transport_name_ = transport_name;
4563 sctp_content_name_ = content_name;
Steve Anton75737c02017-11-06 10:37:17 -08004564 return true;
4565}
4566
4567void PeerConnection::ChangeSctpTransport_n(const std::string& transport_name) {
4568 RTC_DCHECK(network_thread()->IsCurrent());
4569 RTC_DCHECK(sctp_transport_);
4570 RTC_DCHECK(sctp_transport_name_);
4571 std::string old_sctp_transport_name = *sctp_transport_name_;
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004572 sctp_transport_name_ = transport_name;
Steve Anton75737c02017-11-06 10:37:17 -08004573 cricket::DtlsTransportInternal* tc =
4574 transport_controller_->CreateDtlsTransport_n(
4575 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4576 sctp_transport_->SetTransportChannel(tc);
4577 transport_controller_->DestroyDtlsTransport_n(
4578 old_sctp_transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4579}
4580
4581void PeerConnection::DestroySctpTransport_n() {
4582 RTC_DCHECK(network_thread()->IsCurrent());
4583 sctp_transport_.reset(nullptr);
4584 sctp_content_name_.reset();
4585 sctp_transport_name_.reset();
4586 sctp_invoker_.reset(nullptr);
4587 sctp_ready_to_send_data_ = false;
4588}
4589
4590void PeerConnection::OnSctpTransportReadyToSendData_n() {
4591 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
4592 RTC_DCHECK(network_thread()->IsCurrent());
4593 // Note: Cannot use rtc::Bind here because it will grab a reference to
4594 // PeerConnection and potentially cause PeerConnection to live longer than
4595 // expected. It is safe not to grab a reference since the sctp_invoker_ will
4596 // be destroyed before PeerConnection is destroyed, and at that point all
4597 // pending tasks will be cleared.
4598 sctp_invoker_->AsyncInvoke<void>(RTC_FROM_HERE, signaling_thread(), [this] {
4599 OnSctpTransportReadyToSendData_s(true);
4600 });
4601}
4602
4603void PeerConnection::OnSctpTransportReadyToSendData_s(bool ready) {
4604 RTC_DCHECK(signaling_thread()->IsCurrent());
4605 sctp_ready_to_send_data_ = ready;
4606 SignalSctpReadyToSendData(ready);
4607}
4608
4609void PeerConnection::OnSctpTransportDataReceived_n(
4610 const cricket::ReceiveDataParams& params,
4611 const rtc::CopyOnWriteBuffer& payload) {
4612 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
4613 RTC_DCHECK(network_thread()->IsCurrent());
4614 // Note: Cannot use rtc::Bind here because it will grab a reference to
4615 // PeerConnection and potentially cause PeerConnection to live longer than
4616 // expected. It is safe not to grab a reference since the sctp_invoker_ will
4617 // be destroyed before PeerConnection is destroyed, and at that point all
4618 // pending tasks will be cleared.
4619 sctp_invoker_->AsyncInvoke<void>(
4620 RTC_FROM_HERE, signaling_thread(), [this, params, payload] {
4621 OnSctpTransportDataReceived_s(params, payload);
4622 });
4623}
4624
4625void PeerConnection::OnSctpTransportDataReceived_s(
4626 const cricket::ReceiveDataParams& params,
4627 const rtc::CopyOnWriteBuffer& payload) {
4628 RTC_DCHECK(signaling_thread()->IsCurrent());
4629 if (params.type == cricket::DMT_CONTROL && IsOpenMessage(payload)) {
4630 // Received OPEN message; parse and signal that a new data channel should
4631 // be created.
4632 std::string label;
4633 InternalDataChannelInit config;
4634 config.id = params.ssrc;
4635 if (!ParseDataChannelOpenMessage(payload, &label, &config)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004636 RTC_LOG(LS_WARNING) << "Failed to parse the OPEN message for sid "
4637 << params.ssrc;
Steve Anton75737c02017-11-06 10:37:17 -08004638 return;
4639 }
4640 config.open_handshake_role = InternalDataChannelInit::kAcker;
4641 OnDataChannelOpenMessage(label, config);
4642 } else {
4643 // Otherwise just forward the signal.
4644 SignalSctpDataReceived(params, payload);
4645 }
4646}
4647
4648void PeerConnection::OnSctpStreamClosedRemotely_n(int sid) {
4649 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
4650 RTC_DCHECK(network_thread()->IsCurrent());
4651 sctp_invoker_->AsyncInvoke<void>(
4652 RTC_FROM_HERE, signaling_thread(),
4653 rtc::Bind(&sigslot::signal1<int>::operator(),
4654 &SignalSctpStreamClosedRemotely, sid));
4655}
4656
4657// Returns false if bundle is enabled and rtcp_mux is disabled.
4658bool PeerConnection::ValidateBundleSettings(const SessionDescription* desc) {
4659 bool bundle_enabled = desc->HasGroup(cricket::GROUP_TYPE_BUNDLE);
4660 if (!bundle_enabled)
4661 return true;
4662
4663 const cricket::ContentGroup* bundle_group =
4664 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
4665 RTC_DCHECK(bundle_group != NULL);
4666
4667 const cricket::ContentInfos& contents = desc->contents();
4668 for (cricket::ContentInfos::const_iterator citer = contents.begin();
4669 citer != contents.end(); ++citer) {
4670 const cricket::ContentInfo* content = (&*citer);
4671 RTC_DCHECK(content != NULL);
4672 if (bundle_group->HasContentName(content->name) && !content->rejected &&
4673 content->type == cricket::NS_JINGLE_RTP) {
4674 if (!HasRtcpMuxEnabled(content))
4675 return false;
4676 }
4677 }
4678 // RTCP-MUX is enabled in all the contents.
4679 return true;
4680}
4681
4682bool PeerConnection::HasRtcpMuxEnabled(const cricket::ContentInfo* content) {
4683 const cricket::MediaContentDescription* description =
4684 static_cast<cricket::MediaContentDescription*>(content->description);
4685 return description->rtcp_mux();
4686}
4687
Steve Anton8a006912017-12-04 15:25:56 -08004688RTCError PeerConnection::ValidateSessionDescription(
Steve Anton75737c02017-11-06 10:37:17 -08004689 const SessionDescriptionInterface* sdesc,
Steve Anton8a006912017-12-04 15:25:56 -08004690 cricket::ContentSource source) {
Steve Antonf8470812017-12-04 10:46:21 -08004691 if (session_error() != SessionError::kNone) {
Steve Anton8a006912017-12-04 15:25:56 -08004692 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
Steve Anton75737c02017-11-06 10:37:17 -08004693 }
4694
4695 if (!sdesc || !sdesc->description()) {
Steve Anton8a006912017-12-04 15:25:56 -08004696 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidSdp);
Steve Anton75737c02017-11-06 10:37:17 -08004697 }
4698
Steve Anton3828c062017-12-06 10:34:51 -08004699 SdpType type = sdesc->GetType();
4700 if ((source == cricket::CS_LOCAL && !ExpectSetLocalDescription(type)) ||
4701 (source == cricket::CS_REMOTE && !ExpectSetRemoteDescription(type))) {
Steve Anton8a006912017-12-04 15:25:56 -08004702 LOG_AND_RETURN_ERROR(
4703 RTCErrorType::INVALID_PARAMETER,
4704 "Called in wrong state: " + GetSignalingStateString(signaling_state()));
Steve Anton75737c02017-11-06 10:37:17 -08004705 }
4706
4707 // Verify crypto settings.
4708 std::string crypto_error;
Steve Anton8a006912017-12-04 15:25:56 -08004709 if (webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED ||
4710 dtls_enabled_) {
4711 RTCError crypto_error = VerifyCrypto(sdesc->description(), dtls_enabled_);
4712 if (!crypto_error.ok()) {
4713 return crypto_error;
4714 }
Steve Anton75737c02017-11-06 10:37:17 -08004715 }
4716
4717 // Verify ice-ufrag and ice-pwd.
4718 if (!VerifyIceUfragPwdPresent(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08004719 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
4720 kSdpWithoutIceUfragPwd);
Steve Anton75737c02017-11-06 10:37:17 -08004721 }
4722
4723 if (!ValidateBundleSettings(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08004724 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
4725 kBundleWithoutRtcpMux);
Steve Anton75737c02017-11-06 10:37:17 -08004726 }
4727
4728 // TODO(skvlad): When the local rtcp-mux policy is Require, reject any
4729 // m-lines that do not rtcp-mux enabled.
4730
4731 // Verify m-lines in Answer when compared against Offer.
Steve Anton3828c062017-12-06 10:34:51 -08004732 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Anton75737c02017-11-06 10:37:17 -08004733 const cricket::SessionDescription* offer_desc =
4734 (source == cricket::CS_LOCAL) ? remote_description()->description()
4735 : local_description()->description();
4736 if (!MediaSectionsHaveSameCount(offer_desc, sdesc->description()) ||
4737 !MediaSectionsInSameOrder(offer_desc, sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08004738 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
4739 kMlineMismatchInAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08004740 }
4741 } else {
4742 const cricket::SessionDescription* current_desc = nullptr;
4743 if (source == cricket::CS_LOCAL && local_description()) {
4744 current_desc = local_description()->description();
4745 } else if (source == cricket::CS_REMOTE && remote_description()) {
4746 current_desc = remote_description()->description();
4747 }
4748 // The re-offers should respect the order of m= sections in current
4749 // description. See RFC3264 Section 8 paragraph 4 for more details.
4750 if (current_desc &&
4751 !MediaSectionsInSameOrder(current_desc, sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08004752 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
4753 kMlineMismatchInSubsequentOffer);
Steve Anton75737c02017-11-06 10:37:17 -08004754 }
4755 }
4756
Steve Anton8a006912017-12-04 15:25:56 -08004757 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08004758}
4759
Steve Anton3828c062017-12-06 10:34:51 -08004760bool PeerConnection::ExpectSetLocalDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08004761 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08004762 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08004763 return (state == PeerConnectionInterface::kStable) ||
4764 (state == PeerConnectionInterface::kHaveLocalOffer);
Steve Anton20393062017-12-04 16:24:52 -08004765 } else {
Steve Anton3828c062017-12-06 10:34:51 -08004766 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08004767 return (state == PeerConnectionInterface::kHaveRemoteOffer) ||
4768 (state == PeerConnectionInterface::kHaveLocalPrAnswer);
4769 }
4770}
4771
Steve Anton3828c062017-12-06 10:34:51 -08004772bool PeerConnection::ExpectSetRemoteDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08004773 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08004774 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08004775 return (state == PeerConnectionInterface::kStable) ||
4776 (state == PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton20393062017-12-04 16:24:52 -08004777 } else {
Steve Anton3828c062017-12-06 10:34:51 -08004778 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08004779 return (state == PeerConnectionInterface::kHaveLocalOffer) ||
4780 (state == PeerConnectionInterface::kHaveRemotePrAnswer);
4781 }
4782}
4783
Steve Antonf8470812017-12-04 10:46:21 -08004784const char* PeerConnection::SessionErrorToString(SessionError error) const {
4785 switch (error) {
4786 case SessionError::kNone:
4787 return "ERROR_NONE";
4788 case SessionError::kContent:
4789 return "ERROR_CONTENT";
4790 case SessionError::kTransport:
4791 return "ERROR_TRANSPORT";
4792 }
4793 RTC_NOTREACHED();
4794 return "";
4795}
4796
Steve Anton75737c02017-11-06 10:37:17 -08004797std::string PeerConnection::GetSessionErrorMsg() {
4798 std::ostringstream desc;
Steve Antonf8470812017-12-04 10:46:21 -08004799 desc << kSessionError << SessionErrorToString(session_error()) << ". ";
4800 desc << kSessionErrorDesc << session_error_desc() << ".";
Steve Anton75737c02017-11-06 10:37:17 -08004801 return desc.str();
4802}
4803
4804// We need to check the local/remote description for the Transport instead of
4805// the session, because a new Transport added during renegotiation may have
4806// them unset while the session has them set from the previous negotiation.
4807// Not doing so may trigger the auto generation of transport description and
4808// mess up DTLS identity information, ICE credential, etc.
4809bool PeerConnection::ReadyToUseRemoteCandidate(
4810 const IceCandidateInterface* candidate,
4811 const SessionDescriptionInterface* remote_desc,
4812 bool* valid) {
4813 *valid = true;
4814
4815 const SessionDescriptionInterface* current_remote_desc =
4816 remote_desc ? remote_desc : remote_description();
4817
4818 if (!current_remote_desc) {
4819 return false;
4820 }
4821
4822 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
4823 size_t remote_content_size =
4824 current_remote_desc->description()->contents().size();
4825 if (mediacontent_index >= remote_content_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004826 RTC_LOG(LS_ERROR)
4827 << "ReadyToUseRemoteCandidate: Invalid candidate media index "
4828 << mediacontent_index;
Steve Anton75737c02017-11-06 10:37:17 -08004829
4830 *valid = false;
4831 return false;
4832 }
4833
4834 cricket::ContentInfo content =
4835 current_remote_desc->description()->contents()[mediacontent_index];
4836
4837 const std::string transport_name = GetTransportName(content.name);
4838 if (transport_name.empty()) {
4839 return false;
4840 }
4841 return transport_controller_->ReadyForRemoteCandidates(transport_name);
4842}
4843
4844bool PeerConnection::SrtpRequired() const {
4845 return dtls_enabled_ ||
4846 webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED;
4847}
4848
4849void PeerConnection::OnTransportControllerGatheringState(
4850 cricket::IceGatheringState state) {
4851 RTC_DCHECK(signaling_thread()->IsCurrent());
4852 if (state == cricket::kIceGatheringGathering) {
4853 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringGathering);
4854 } else if (state == cricket::kIceGatheringComplete) {
4855 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringComplete);
4856 }
4857}
4858
4859void PeerConnection::ReportTransportStats() {
4860 // Use a set so we don't report the same stats twice if two channels share
4861 // a transport.
4862 std::set<std::string> transport_names;
4863 if (voice_channel()) {
4864 transport_names.insert(voice_channel()->transport_name());
4865 }
4866 if (video_channel()) {
4867 transport_names.insert(video_channel()->transport_name());
4868 }
4869 if (rtp_data_channel()) {
4870 transport_names.insert(rtp_data_channel()->transport_name());
4871 }
4872 if (sctp_transport_name_) {
4873 transport_names.insert(*sctp_transport_name_);
4874 }
4875 for (const auto& name : transport_names) {
4876 cricket::TransportStats stats;
4877 if (transport_controller_->GetStats(name, &stats)) {
4878 ReportBestConnectionState(stats);
4879 ReportNegotiatedCiphers(stats);
4880 }
4881 }
4882}
4883// Walk through the ConnectionInfos to gather best connection usage
4884// for IPv4 and IPv6.
4885void PeerConnection::ReportBestConnectionState(
4886 const cricket::TransportStats& stats) {
4887 RTC_DCHECK(metrics_observer());
4888 for (cricket::TransportChannelStatsList::const_iterator it =
4889 stats.channel_stats.begin();
4890 it != stats.channel_stats.end(); ++it) {
4891 for (cricket::ConnectionInfos::const_iterator it_info =
4892 it->connection_infos.begin();
4893 it_info != it->connection_infos.end(); ++it_info) {
4894 if (!it_info->best_connection) {
4895 continue;
4896 }
4897
4898 PeerConnectionEnumCounterType type = kPeerConnectionEnumCounterMax;
4899 const cricket::Candidate& local = it_info->local_candidate;
4900 const cricket::Candidate& remote = it_info->remote_candidate;
4901
4902 // Increment the counter for IceCandidatePairType.
4903 if (local.protocol() == cricket::TCP_PROTOCOL_NAME ||
4904 (local.type() == RELAY_PORT_TYPE &&
4905 local.relay_protocol() == cricket::TCP_PROTOCOL_NAME)) {
4906 type = kEnumCounterIceCandidatePairTypeTcp;
4907 } else if (local.protocol() == cricket::UDP_PROTOCOL_NAME) {
4908 type = kEnumCounterIceCandidatePairTypeUdp;
4909 } else {
4910 RTC_CHECK(0);
4911 }
4912 metrics_observer()->IncrementEnumCounter(
4913 type, GetIceCandidatePairCounter(local, remote),
4914 kIceCandidatePairMax);
4915
4916 // Increment the counter for IP type.
4917 if (local.address().family() == AF_INET) {
4918 metrics_observer()->IncrementEnumCounter(
4919 kEnumCounterAddressFamily, kBestConnections_IPv4,
4920 kPeerConnectionAddressFamilyCounter_Max);
4921
4922 } else if (local.address().family() == AF_INET6) {
4923 metrics_observer()->IncrementEnumCounter(
4924 kEnumCounterAddressFamily, kBestConnections_IPv6,
4925 kPeerConnectionAddressFamilyCounter_Max);
4926 } else {
4927 RTC_CHECK(0);
4928 }
4929
4930 return;
4931 }
4932 }
4933}
4934
4935void PeerConnection::ReportNegotiatedCiphers(
4936 const cricket::TransportStats& stats) {
4937 RTC_DCHECK(metrics_observer());
4938 if (!dtls_enabled_ || stats.channel_stats.empty()) {
4939 return;
4940 }
4941
4942 int srtp_crypto_suite = stats.channel_stats[0].srtp_crypto_suite;
4943 int ssl_cipher_suite = stats.channel_stats[0].ssl_cipher_suite;
4944 if (srtp_crypto_suite == rtc::SRTP_INVALID_CRYPTO_SUITE &&
4945 ssl_cipher_suite == rtc::TLS_NULL_WITH_NULL_NULL) {
4946 return;
4947 }
4948
4949 PeerConnectionEnumCounterType srtp_counter_type;
4950 PeerConnectionEnumCounterType ssl_counter_type;
4951 if (stats.transport_name == cricket::CN_AUDIO) {
4952 srtp_counter_type = kEnumCounterAudioSrtpCipher;
4953 ssl_counter_type = kEnumCounterAudioSslCipher;
4954 } else if (stats.transport_name == cricket::CN_VIDEO) {
4955 srtp_counter_type = kEnumCounterVideoSrtpCipher;
4956 ssl_counter_type = kEnumCounterVideoSslCipher;
4957 } else if (stats.transport_name == cricket::CN_DATA) {
4958 srtp_counter_type = kEnumCounterDataSrtpCipher;
4959 ssl_counter_type = kEnumCounterDataSslCipher;
4960 } else {
4961 RTC_NOTREACHED();
4962 return;
4963 }
4964
4965 if (srtp_crypto_suite != rtc::SRTP_INVALID_CRYPTO_SUITE) {
4966 metrics_observer()->IncrementSparseEnumCounter(srtp_counter_type,
4967 srtp_crypto_suite);
4968 }
4969 if (ssl_cipher_suite != rtc::TLS_NULL_WITH_NULL_NULL) {
4970 metrics_observer()->IncrementSparseEnumCounter(ssl_counter_type,
4971 ssl_cipher_suite);
4972 }
4973}
4974
4975void PeerConnection::OnSentPacket_w(const rtc::SentPacket& sent_packet) {
4976 RTC_DCHECK(worker_thread()->IsCurrent());
4977 RTC_DCHECK(call_);
4978 call_->OnSentPacket(sent_packet);
4979}
4980
4981const std::string PeerConnection::GetTransportName(
4982 const std::string& content_name) {
4983 cricket::BaseChannel* channel = GetChannel(content_name);
Steve Anton6fec8802017-12-04 10:37:29 -08004984 if (channel) {
4985 return channel->transport_name();
Steve Anton75737c02017-11-06 10:37:17 -08004986 }
Steve Anton6fec8802017-12-04 10:37:29 -08004987 if (sctp_transport_) {
4988 RTC_DCHECK(sctp_content_name_);
4989 RTC_DCHECK(sctp_transport_name_);
4990 if (content_name == *sctp_content_name_) {
4991 return *sctp_transport_name_;
4992 }
4993 }
4994 // Return an empty string if failed to retrieve the transport name.
4995 return "";
Steve Anton75737c02017-11-06 10:37:17 -08004996}
4997
4998void PeerConnection::DestroyRtcpTransport_n(const std::string& transport_name) {
4999 RTC_DCHECK(network_thread()->IsCurrent());
5000 transport_controller_->DestroyDtlsTransport_n(
5001 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
5002}
5003
Steve Anton6fec8802017-12-04 10:37:29 -08005004void PeerConnection::DestroyTransceiverChannel(
5005 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
5006 transceiver) {
5007 RTC_DCHECK(transceiver);
Steve Anton75737c02017-11-06 10:37:17 -08005008
Steve Anton6fec8802017-12-04 10:37:29 -08005009 cricket::BaseChannel* channel = transceiver->internal()->channel();
5010 if (channel) {
5011 transceiver->internal()->SetChannel(nullptr);
5012 DestroyBaseChannel(channel);
Steve Anton75737c02017-11-06 10:37:17 -08005013 }
5014}
5015
5016void PeerConnection::DestroyDataChannel() {
Steve Anton6fec8802017-12-04 10:37:29 -08005017 if (rtp_data_channel_) {
5018 OnDataChannelDestroyed();
5019 DestroyBaseChannel(rtp_data_channel_);
5020 rtp_data_channel_ = nullptr;
5021 }
5022
5023 // Note: Cannot use rtc::Bind to create a functor to invoke because it will
5024 // grab a reference to this PeerConnection. If this is called from the
5025 // PeerConnection destructor, the RefCountedObject vtable will have already
5026 // been destroyed (since it is a subclass of PeerConnection) and using
5027 // rtc::Bind will cause "Pure virtual function called" error to appear.
5028
5029 if (sctp_transport_) {
5030 OnDataChannelDestroyed();
5031 network_thread()->Invoke<void>(RTC_FROM_HERE,
5032 [this] { DestroySctpTransport_n(); });
5033 }
5034}
5035
5036void PeerConnection::DestroyBaseChannel(cricket::BaseChannel* channel) {
5037 RTC_DCHECK(channel);
5038 RTC_DCHECK(channel->rtp_dtls_transport());
5039
5040 // Need to cache these before destroying the base channel so that we do not
5041 // access uninitialized memory.
5042 const std::string transport_name =
5043 channel->rtp_dtls_transport()->transport_name();
5044 const bool need_to_delete_rtcp = (channel->rtcp_dtls_transport() != nullptr);
5045
5046 switch (channel->media_type()) {
5047 case cricket::MEDIA_TYPE_AUDIO:
5048 channel_manager()->DestroyVoiceChannel(
5049 static_cast<cricket::VoiceChannel*>(channel));
5050 break;
5051 case cricket::MEDIA_TYPE_VIDEO:
5052 channel_manager()->DestroyVideoChannel(
5053 static_cast<cricket::VideoChannel*>(channel));
5054 break;
5055 case cricket::MEDIA_TYPE_DATA:
5056 channel_manager()->DestroyRtpDataChannel(
5057 static_cast<cricket::RtpDataChannel*>(channel));
5058 break;
5059 default:
5060 RTC_NOTREACHED() << "Unknown media type: " << channel->media_type();
5061 break;
5062 }
5063
5064 // |channel| can no longer be used.
5065
Steve Anton75737c02017-11-06 10:37:17 -08005066 transport_controller_->DestroyDtlsTransport(
5067 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5068 if (need_to_delete_rtcp) {
5069 transport_controller_->DestroyDtlsTransport(
5070 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
5071 }
5072}
5073
henrike@webrtc.org28e20752013-07-10 00:45:36 +00005074} // namespace webrtc