blob: 5a21146490e3715a969ece1255f3ffff4266bc76 [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;
Steve Anton5adfafd2017-12-20 16:34:00 -080057using cricket::MediaProtocolType;
Steve Anton75737c02017-11-06 10:37:17 -080058using cricket::TransportInfo;
59
60using cricket::LOCAL_PORT_TYPE;
61using cricket::STUN_PORT_TYPE;
62using cricket::RELAY_PORT_TYPE;
63using cricket::PRFLX_PORT_TYPE;
64
Steve Antonba818672017-11-06 10:21:57 -080065namespace webrtc {
66
Steve Anton75737c02017-11-06 10:37:17 -080067// Error messages
68const char kBundleWithoutRtcpMux[] =
69 "rtcp-mux must be enabled when BUNDLE "
70 "is enabled.";
Steve Anton75737c02017-11-06 10:37:17 -080071const char kInvalidCandidates[] = "Description contains invalid candidates.";
72const char kInvalidSdp[] = "Invalid session description.";
73const char kMlineMismatchInAnswer[] =
74 "The order of m-lines in answer doesn't match order in offer. Rejecting "
75 "answer.";
76const char kMlineMismatchInSubsequentOffer[] =
77 "The order of m-lines in subsequent offer doesn't match order from "
78 "previous offer/answer.";
Steve Anton75737c02017-11-06 10:37:17 -080079const char kSdpWithoutDtlsFingerprint[] =
80 "Called with SDP without DTLS fingerprint.";
81const char kSdpWithoutSdesCrypto[] = "Called with SDP without SDES crypto.";
82const char kSdpWithoutIceUfragPwd[] =
83 "Called with SDP without ice-ufrag and ice-pwd.";
84const char kSessionError[] = "Session error code: ";
85const char kSessionErrorDesc[] = "Session error description: ";
86const char kDtlsSrtpSetupFailureRtp[] =
87 "Couldn't set up DTLS-SRTP on RTP channel.";
88const char kDtlsSrtpSetupFailureRtcp[] =
89 "Couldn't set up DTLS-SRTP on RTCP channel.";
90const char kEnableBundleFailed[] = "Failed to enable BUNDLE.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +000091
Steve Anton75737c02017-11-06 10:37:17 -080092namespace {
henrike@webrtc.org28e20752013-07-10 00:45:36 +000093
deadbeefab9b2d12015-10-14 11:33:11 -070094static const char kDefaultStreamLabel[] = "default";
Steve Anton4171afb2017-11-20 10:20:22 -080095static const char kDefaultAudioSenderId[] = "defaulta0";
96static const char kDefaultVideoSenderId[] = "defaultv0";
deadbeefab9b2d12015-10-14 11:33:11 -070097
zhihuang8f65cdf2016-05-06 18:40:30 -070098// The length of RTCP CNAMEs.
99static const int kRtcpCnameLength = 16;
100
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000101enum {
wu@webrtc.org91053e72013-08-10 07:18:04 +0000102 MSG_SET_SESSIONDESCRIPTION_SUCCESS = 0,
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000103 MSG_SET_SESSIONDESCRIPTION_FAILED,
deadbeefab9b2d12015-10-14 11:33:11 -0700104 MSG_CREATE_SESSIONDESCRIPTION_FAILED,
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000105 MSG_GETSTATS,
deadbeefbd292462015-12-14 18:15:29 -0800106 MSG_FREE_DATACHANNELS,
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000107};
108
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000109struct SetSessionDescriptionMsg : public rtc::MessageData {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000110 explicit SetSessionDescriptionMsg(
111 webrtc::SetSessionDescriptionObserver* observer)
112 : observer(observer) {
113 }
114
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000115 rtc::scoped_refptr<webrtc::SetSessionDescriptionObserver> observer;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000116 std::string error;
117};
118
deadbeefab9b2d12015-10-14 11:33:11 -0700119struct CreateSessionDescriptionMsg : public rtc::MessageData {
120 explicit CreateSessionDescriptionMsg(
121 webrtc::CreateSessionDescriptionObserver* observer)
122 : observer(observer) {}
123
124 rtc::scoped_refptr<webrtc::CreateSessionDescriptionObserver> observer;
125 std::string error;
126};
127
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000128struct GetStatsMsg : public rtc::MessageData {
tommi@webrtc.org5b06b062014-08-15 08:38:30 +0000129 GetStatsMsg(webrtc::StatsObserver* observer,
130 webrtc::MediaStreamTrackInterface* track)
131 : observer(observer), track(track) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000132 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000133 rtc::scoped_refptr<webrtc::StatsObserver> observer;
tommi@webrtc.org5b06b062014-08-15 08:38:30 +0000134 rtc::scoped_refptr<webrtc::MediaStreamTrackInterface> track;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000135};
136
deadbeefab9b2d12015-10-14 11:33:11 -0700137// Check if we can send |new_stream| on a PeerConnection.
138bool CanAddLocalMediaStream(webrtc::StreamCollectionInterface* current_streams,
139 webrtc::MediaStreamInterface* new_stream) {
140 if (!new_stream || !current_streams) {
141 return false;
142 }
143 if (current_streams->find(new_stream->label()) != nullptr) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100144 RTC_LOG(LS_ERROR) << "MediaStream with label " << new_stream->label()
145 << " is already added.";
deadbeefab9b2d12015-10-14 11:33:11 -0700146 return false;
147 }
148 return true;
149}
150
deadbeef5e97fb52015-10-15 12:49:08 -0700151// If the direction is "recvonly" or "inactive", treat the description
152// as containing no streams.
153// See: https://code.google.com/p/webrtc/issues/detail?id=5054
154std::vector<cricket::StreamParams> GetActiveStreams(
155 const cricket::MediaContentDescription* desc) {
Steve Anton4e70a722017-11-28 14:57:10 -0800156 return RtpTransceiverDirectionHasSend(desc->direction())
deadbeef5e97fb52015-10-15 12:49:08 -0700157 ? desc->streams()
158 : std::vector<cricket::StreamParams>();
159}
160
deadbeefab9b2d12015-10-14 11:33:11 -0700161bool IsValidOfferToReceiveMedia(int value) {
162 typedef PeerConnectionInterface::RTCOfferAnswerOptions Options;
163 return (value >= Options::kUndefined) &&
164 (value <= Options::kMaxOfferToReceiveMedia);
165}
166
zhihuang1c378ed2017-08-17 14:10:50 -0700167// Add options to |[audio/video]_media_description_options| from |senders|.
168void AddRtpSenderOptions(
deadbeefa601f5c2016-06-06 14:27:39 -0700169 const std::vector<rtc::scoped_refptr<
170 RtpSenderProxyWithInternal<RtpSenderInternal>>>& senders,
zhihuang1c378ed2017-08-17 14:10:50 -0700171 cricket::MediaDescriptionOptions* audio_media_description_options,
172 cricket::MediaDescriptionOptions* video_media_description_options) {
olka3c747662017-08-17 06:50:32 -0700173 for (const auto& sender : senders) {
zhihuang1c378ed2017-08-17 14:10:50 -0700174 if (sender->media_type() == cricket::MEDIA_TYPE_AUDIO) {
175 if (audio_media_description_options) {
176 audio_media_description_options->AddAudioSender(
Steve Anton8ffb9c32017-08-31 15:45:38 -0700177 sender->id(), sender->internal()->stream_ids());
zhihuang1c378ed2017-08-17 14:10:50 -0700178 }
179 } else {
180 RTC_DCHECK(sender->media_type() == cricket::MEDIA_TYPE_VIDEO);
181 if (video_media_description_options) {
182 video_media_description_options->AddVideoSender(
Steve Anton8ffb9c32017-08-31 15:45:38 -0700183 sender->id(), sender->internal()->stream_ids(), 1);
zhihuang1c378ed2017-08-17 14:10:50 -0700184 }
185 }
zhihuanga77e6bb2017-08-14 18:17:48 -0700186 }
zhihuang1c378ed2017-08-17 14:10:50 -0700187}
olka3c747662017-08-17 06:50:32 -0700188
zhihuang1c378ed2017-08-17 14:10:50 -0700189// Add options to |session_options| from |rtp_data_channels|.
190void AddRtpDataChannelOptions(
191 const std::map<std::string, rtc::scoped_refptr<DataChannel>>&
192 rtp_data_channels,
193 cricket::MediaDescriptionOptions* data_media_description_options) {
194 if (!data_media_description_options) {
195 return;
196 }
deadbeefab9b2d12015-10-14 11:33:11 -0700197 // Check for data channels.
198 for (const auto& kv : rtp_data_channels) {
199 const DataChannel* channel = kv.second;
200 if (channel->state() == DataChannel::kConnecting ||
201 channel->state() == DataChannel::kOpen) {
zhihuang1c378ed2017-08-17 14:10:50 -0700202 // Legacy RTP data channels are signaled with the track/stream ID set to
203 // the data channel's label.
204 data_media_description_options->AddRtpDataChannel(channel->label(),
205 channel->label());
deadbeefab9b2d12015-10-14 11:33:11 -0700206 }
207 }
208}
209
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700210uint32_t ConvertIceTransportTypeToCandidateFilter(
211 PeerConnectionInterface::IceTransportsType type) {
212 switch (type) {
213 case PeerConnectionInterface::kNone:
214 return cricket::CF_NONE;
215 case PeerConnectionInterface::kRelay:
216 return cricket::CF_RELAY;
217 case PeerConnectionInterface::kNoHost:
218 return (cricket::CF_ALL & ~cricket::CF_HOST);
219 case PeerConnectionInterface::kAll:
220 return cricket::CF_ALL;
221 default:
nissec80e7412017-01-11 05:56:46 -0800222 RTC_NOTREACHED();
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700223 }
224 return cricket::CF_NONE;
225}
226
deadbeef293e9262017-01-11 12:28:30 -0800227// Helper to set an error and return from a method.
228bool SafeSetError(webrtc::RTCErrorType type, webrtc::RTCError* error) {
229 if (error) {
230 error->set_type(type);
231 }
232 return type == webrtc::RTCErrorType::NONE;
233}
234
Steve Anton038834f2017-07-14 15:59:59 -0700235bool SafeSetError(webrtc::RTCError error, webrtc::RTCError* error_out) {
236 if (error_out) {
237 *error_out = std::move(error);
238 }
239 return error.ok();
240}
241
Steve Antonba818672017-11-06 10:21:57 -0800242std::string GetSignalingStateString(
243 PeerConnectionInterface::SignalingState state) {
244 switch (state) {
245 case PeerConnectionInterface::kStable:
246 return "kStable";
247 case PeerConnectionInterface::kHaveLocalOffer:
248 return "kHaveLocalOffer";
249 case PeerConnectionInterface::kHaveLocalPrAnswer:
250 return "kHavePrAnswer";
251 case PeerConnectionInterface::kHaveRemoteOffer:
252 return "kHaveRemoteOffer";
253 case PeerConnectionInterface::kHaveRemotePrAnswer:
254 return "kHaveRemotePrAnswer";
255 case PeerConnectionInterface::kClosed:
256 return "kClosed";
257 }
258 RTC_NOTREACHED();
259 return "";
260}
deadbeef0a6c4ca2015-10-06 11:38:28 -0700261
Steve Anton75737c02017-11-06 10:37:17 -0800262IceCandidatePairType GetIceCandidatePairCounter(
263 const cricket::Candidate& local,
264 const cricket::Candidate& remote) {
265 const auto& l = local.type();
266 const auto& r = remote.type();
267 const auto& host = LOCAL_PORT_TYPE;
268 const auto& srflx = STUN_PORT_TYPE;
269 const auto& relay = RELAY_PORT_TYPE;
270 const auto& prflx = PRFLX_PORT_TYPE;
271 if (l == host && r == host) {
272 bool local_private = IPIsPrivate(local.address().ipaddr());
273 bool remote_private = IPIsPrivate(remote.address().ipaddr());
274 if (local_private) {
275 if (remote_private) {
276 return kIceCandidatePairHostPrivateHostPrivate;
277 } else {
278 return kIceCandidatePairHostPrivateHostPublic;
279 }
280 } else {
281 if (remote_private) {
282 return kIceCandidatePairHostPublicHostPrivate;
283 } else {
284 return kIceCandidatePairHostPublicHostPublic;
285 }
286 }
287 }
288 if (l == host && r == srflx)
289 return kIceCandidatePairHostSrflx;
290 if (l == host && r == relay)
291 return kIceCandidatePairHostRelay;
292 if (l == host && r == prflx)
293 return kIceCandidatePairHostPrflx;
294 if (l == srflx && r == host)
295 return kIceCandidatePairSrflxHost;
296 if (l == srflx && r == srflx)
297 return kIceCandidatePairSrflxSrflx;
298 if (l == srflx && r == relay)
299 return kIceCandidatePairSrflxRelay;
300 if (l == srflx && r == prflx)
301 return kIceCandidatePairSrflxPrflx;
302 if (l == relay && r == host)
303 return kIceCandidatePairRelayHost;
304 if (l == relay && r == srflx)
305 return kIceCandidatePairRelaySrflx;
306 if (l == relay && r == relay)
307 return kIceCandidatePairRelayRelay;
308 if (l == relay && r == prflx)
309 return kIceCandidatePairRelayPrflx;
310 if (l == prflx && r == host)
311 return kIceCandidatePairPrflxHost;
312 if (l == prflx && r == srflx)
313 return kIceCandidatePairPrflxSrflx;
314 if (l == prflx && r == relay)
315 return kIceCandidatePairPrflxRelay;
316 return kIceCandidatePairMax;
317}
318
319// Verify that the order of media sections in |new_desc| matches
320// |existing_desc|. The number of m= sections in |new_desc| should be no less
321// than |existing_desc|.
322bool MediaSectionsInSameOrder(const SessionDescription* existing_desc,
323 const SessionDescription* new_desc) {
324 if (!existing_desc || !new_desc) {
325 return false;
326 }
327
328 if (existing_desc->contents().size() > new_desc->contents().size()) {
329 return false;
330 }
331
332 for (size_t i = 0; i < existing_desc->contents().size(); ++i) {
333 if (new_desc->contents()[i].name != existing_desc->contents()[i].name) {
334 return false;
335 }
336 const MediaContentDescription* new_desc_mdesc =
Steve Antonb1c1de12017-12-21 15:14:30 -0800337 new_desc->contents()[i].media_description();
Steve Anton75737c02017-11-06 10:37:17 -0800338 const MediaContentDescription* existing_desc_mdesc =
Steve Antonb1c1de12017-12-21 15:14:30 -0800339 existing_desc->contents()[i].media_description();
Steve Anton75737c02017-11-06 10:37:17 -0800340 if (new_desc_mdesc->type() != existing_desc_mdesc->type()) {
341 return false;
342 }
343 }
344 return true;
345}
346
347bool MediaSectionsHaveSameCount(const SessionDescription* desc1,
348 const SessionDescription* desc2) {
349 if (!desc1 || !desc2) {
350 return false;
351 }
352 return desc1->contents().size() == desc2->contents().size();
353}
354
355// Checks that each non-rejected content has SDES crypto keys or a DTLS
356// fingerprint, unless it's in a BUNDLE group, in which case only the
357// BUNDLE-tag section (first media section/description in the BUNDLE group)
358// needs a ufrag and pwd. Mismatches, such as replying with a DTLS fingerprint
359// to SDES keys, will be caught in JsepTransport negotiation, and backstopped
360// by Channel's |srtp_required| check.
Steve Anton8a006912017-12-04 15:25:56 -0800361RTCError VerifyCrypto(const SessionDescription* desc, bool dtls_enabled) {
Steve Anton75737c02017-11-06 10:37:17 -0800362 const cricket::ContentGroup* bundle =
363 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton8a006912017-12-04 15:25:56 -0800364 for (const cricket::ContentInfo& content_info : desc->contents()) {
365 if (content_info.rejected) {
Steve Anton75737c02017-11-06 10:37:17 -0800366 continue;
367 }
Steve Anton8a006912017-12-04 15:25:56 -0800368 const std::string& mid = content_info.name;
369 if (bundle && bundle->HasContentName(mid) &&
370 mid != *(bundle->FirstContentName())) {
Steve Anton75737c02017-11-06 10:37:17 -0800371 // This isn't the first media section in the BUNDLE group, so it's not
372 // required to have crypto attributes, since only the crypto attributes
373 // from the first section actually get used.
374 continue;
375 }
376
377 // If the content isn't rejected or bundled into another m= section, crypto
378 // must be present.
Steve Antonb1c1de12017-12-21 15:14:30 -0800379 const MediaContentDescription* media = content_info.media_description();
Steve Anton8a006912017-12-04 15:25:56 -0800380 const TransportInfo* tinfo = desc->GetTransportInfoByName(mid);
Steve Anton75737c02017-11-06 10:37:17 -0800381 if (!media || !tinfo) {
382 // Something is not right.
Steve Anton8a006912017-12-04 15:25:56 -0800383 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidSdp);
Steve Anton75737c02017-11-06 10:37:17 -0800384 }
385 if (dtls_enabled) {
386 if (!tinfo->description.identity_fingerprint) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100387 RTC_LOG(LS_WARNING)
388 << "Session description must have DTLS fingerprint if "
389 "DTLS enabled.";
Steve Anton8a006912017-12-04 15:25:56 -0800390 return RTCError(RTCErrorType::INVALID_PARAMETER,
391 kSdpWithoutDtlsFingerprint);
Steve Anton75737c02017-11-06 10:37:17 -0800392 }
393 } else {
394 if (media->cryptos().empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100395 RTC_LOG(LS_WARNING)
Steve Anton75737c02017-11-06 10:37:17 -0800396 << "Session description must have SDES when DTLS disabled.";
Steve Anton8a006912017-12-04 15:25:56 -0800397 return RTCError(RTCErrorType::INVALID_PARAMETER, kSdpWithoutSdesCrypto);
Steve Anton75737c02017-11-06 10:37:17 -0800398 }
399 }
400 }
Steve Anton8a006912017-12-04 15:25:56 -0800401 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -0800402}
403
404// Checks that each non-rejected content has ice-ufrag and ice-pwd set, unless
405// it's in a BUNDLE group, in which case only the BUNDLE-tag section (first
406// media section/description in the BUNDLE group) needs a ufrag and pwd.
407bool VerifyIceUfragPwdPresent(const SessionDescription* desc) {
408 const cricket::ContentGroup* bundle =
409 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton8a006912017-12-04 15:25:56 -0800410 for (const cricket::ContentInfo& content_info : desc->contents()) {
411 if (content_info.rejected) {
Steve Anton75737c02017-11-06 10:37:17 -0800412 continue;
413 }
Steve Anton8a006912017-12-04 15:25:56 -0800414 const std::string& mid = content_info.name;
415 if (bundle && bundle->HasContentName(mid) &&
416 mid != *(bundle->FirstContentName())) {
Steve Anton75737c02017-11-06 10:37:17 -0800417 // This isn't the first media section in the BUNDLE group, so it's not
418 // required to have ufrag/password, since only the ufrag/password from
419 // the first section actually get used.
420 continue;
421 }
422
423 // If the content isn't rejected or bundled into another m= section,
424 // ice-ufrag and ice-pwd must be present.
Steve Anton8a006912017-12-04 15:25:56 -0800425 const TransportInfo* tinfo = desc->GetTransportInfoByName(mid);
Steve Anton75737c02017-11-06 10:37:17 -0800426 if (!tinfo) {
427 // Something is not right.
Mirko Bonadei675513b2017-11-09 11:09:25 +0100428 RTC_LOG(LS_ERROR) << kInvalidSdp;
Steve Anton75737c02017-11-06 10:37:17 -0800429 return false;
430 }
431 if (tinfo->description.ice_ufrag.empty() ||
432 tinfo->description.ice_pwd.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100433 RTC_LOG(LS_ERROR) << "Session description must have ice ufrag and pwd.";
Steve Anton75737c02017-11-06 10:37:17 -0800434 return false;
435 }
436 }
437 return true;
438}
439
440bool GetTrackIdBySsrc(const SessionDescription* session_description,
441 uint32_t ssrc,
442 std::string* track_id) {
443 RTC_DCHECK(track_id != NULL);
444
Steve Antonb1c1de12017-12-21 15:14:30 -0800445 const cricket::AudioContentDescription* audio_desc =
446 cricket::GetFirstAudioContentDescription(session_description);
447 if (audio_desc) {
448 const auto* found = cricket::GetStreamBySsrc(audio_desc->streams(), ssrc);
Steve Anton75737c02017-11-06 10:37:17 -0800449 if (found) {
450 *track_id = found->id;
451 return true;
452 }
453 }
454
Steve Antonb1c1de12017-12-21 15:14:30 -0800455 const cricket::VideoContentDescription* video_desc =
456 cricket::GetFirstVideoContentDescription(session_description);
457 if (video_desc) {
458 const auto* found = cricket::GetStreamBySsrc(video_desc->streams(), ssrc);
Steve Anton75737c02017-11-06 10:37:17 -0800459 if (found) {
460 *track_id = found->id;
461 return true;
462 }
463 }
464 return false;
465}
466
467// Get the SCTP port out of a SessionDescription.
468// Return -1 if not found.
469int GetSctpPort(const SessionDescription* session_description) {
Steve Antonb1c1de12017-12-21 15:14:30 -0800470 const cricket::DataContentDescription* data_desc =
471 GetFirstDataContentDescription(session_description);
472 RTC_DCHECK(data_desc);
473 if (!data_desc) {
Steve Anton75737c02017-11-06 10:37:17 -0800474 return -1;
475 }
Steve Anton75737c02017-11-06 10:37:17 -0800476 std::string value;
477 cricket::DataCodec match_pattern(cricket::kGoogleSctpDataCodecPlType,
478 cricket::kGoogleSctpDataCodecName);
Steve Antonb1c1de12017-12-21 15:14:30 -0800479 for (const cricket::DataCodec& codec : data_desc->codecs()) {
Steve Anton75737c02017-11-06 10:37:17 -0800480 if (!codec.Matches(match_pattern)) {
481 continue;
482 }
483 if (codec.GetParam(cricket::kCodecParamPort, &value)) {
484 return rtc::FromString<int>(value);
485 }
486 }
487 return -1;
488}
489
Steve Anton75737c02017-11-06 10:37:17 -0800490// Returns true if |new_desc| requests an ICE restart (i.e., new ufrag/pwd).
491bool CheckForRemoteIceRestart(const SessionDescriptionInterface* old_desc,
492 const SessionDescriptionInterface* new_desc,
493 const std::string& content_name) {
494 if (!old_desc) {
495 return false;
496 }
497 const SessionDescription* new_sd = new_desc->description();
498 const SessionDescription* old_sd = old_desc->description();
499 const ContentInfo* cinfo = new_sd->GetContentByName(content_name);
500 if (!cinfo || cinfo->rejected) {
501 return false;
502 }
503 // If the content isn't rejected, check if ufrag and password has changed.
504 const cricket::TransportDescription* new_transport_desc =
505 new_sd->GetTransportDescriptionByName(content_name);
506 const cricket::TransportDescription* old_transport_desc =
507 old_sd->GetTransportDescriptionByName(content_name);
508 if (!new_transport_desc || !old_transport_desc) {
509 // No transport description exists. This is not an ICE restart.
510 return false;
511 }
512 if (cricket::IceCredentialsChanged(
513 old_transport_desc->ice_ufrag, old_transport_desc->ice_pwd,
514 new_transport_desc->ice_ufrag, new_transport_desc->ice_pwd)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100515 RTC_LOG(LS_INFO) << "Remote peer requests ICE restart for " << content_name
516 << ".";
Steve Anton75737c02017-11-06 10:37:17 -0800517 return true;
518 }
519 return false;
520}
521
522} // namespace
523
Henrik Boström31638672017-11-23 17:48:32 +0100524// Upon completion, posts a task to execute the callback of the
525// SetSessionDescriptionObserver asynchronously on the same thread. At this
526// point, the state of the peer connection might no longer reflect the effects
527// of the SetRemoteDescription operation, as the peer connection could have been
528// modified during the post.
529// TODO(hbos): Remove this class once we remove the version of
530// PeerConnectionInterface::SetRemoteDescription() that takes a
531// SetSessionDescriptionObserver as an argument.
532class PeerConnection::SetRemoteDescriptionObserverAdapter
533 : public rtc::RefCountedObject<SetRemoteDescriptionObserverInterface> {
534 public:
535 SetRemoteDescriptionObserverAdapter(
536 rtc::scoped_refptr<PeerConnection> pc,
537 rtc::scoped_refptr<SetSessionDescriptionObserver> wrapper)
538 : pc_(std::move(pc)), wrapper_(std::move(wrapper)) {}
539
540 // SetRemoteDescriptionObserverInterface implementation.
541 void OnSetRemoteDescriptionComplete(RTCError error) override {
542 if (error.ok())
543 pc_->PostSetSessionDescriptionSuccess(wrapper_);
544 else
545 pc_->PostSetSessionDescriptionFailure(wrapper_, error.message());
546 }
547
548 private:
549 rtc::scoped_refptr<PeerConnection> pc_;
550 rtc::scoped_refptr<SetSessionDescriptionObserver> wrapper_;
551};
552
deadbeef293e9262017-01-11 12:28:30 -0800553bool PeerConnectionInterface::RTCConfiguration::operator==(
554 const PeerConnectionInterface::RTCConfiguration& o) const {
555 // This static_assert prevents us from accidentally breaking operator==.
Steve Anton300bf8e2017-07-14 10:13:10 -0700556 // Note: Order matters! Fields must be ordered the same as RTCConfiguration.
deadbeef293e9262017-01-11 12:28:30 -0800557 struct stuff_being_tested_for_equality {
Magnus Jedvert3beb2072017-07-14 14:23:56 +0000558 IceServers servers;
Steve Anton300bf8e2017-07-14 10:13:10 -0700559 IceTransportsType type;
deadbeef293e9262017-01-11 12:28:30 -0800560 BundlePolicy bundle_policy;
561 RtcpMuxPolicy rtcp_mux_policy;
Steve Anton300bf8e2017-07-14 10:13:10 -0700562 std::vector<rtc::scoped_refptr<rtc::RTCCertificate>> certificates;
563 int ice_candidate_pool_size;
564 bool disable_ipv6;
565 bool disable_ipv6_on_wifi;
deadbeefd21eab32017-07-26 16:50:11 -0700566 int max_ipv6_networks;
Steve Anton300bf8e2017-07-14 10:13:10 -0700567 bool enable_rtp_data_channel;
568 rtc::Optional<int> screencast_min_bitrate;
569 rtc::Optional<bool> combined_audio_video_bwe;
570 rtc::Optional<bool> enable_dtls_srtp;
deadbeef293e9262017-01-11 12:28:30 -0800571 TcpCandidatePolicy tcp_candidate_policy;
572 CandidateNetworkPolicy candidate_network_policy;
573 int audio_jitter_buffer_max_packets;
574 bool audio_jitter_buffer_fast_accelerate;
575 int ice_connection_receiving_timeout;
576 int ice_backup_candidate_pair_ping_interval;
577 ContinualGatheringPolicy continual_gathering_policy;
deadbeef293e9262017-01-11 12:28:30 -0800578 bool prioritize_most_likely_ice_candidate_pairs;
579 struct cricket::MediaConfig media_config;
deadbeef293e9262017-01-11 12:28:30 -0800580 bool prune_turn_ports;
581 bool presume_writable_when_fully_relayed;
582 bool enable_ice_renomination;
583 bool redetermine_role_on_ice_restart;
skvlad51072462017-02-02 11:50:14 -0800584 rtc::Optional<int> ice_check_min_interval;
Steve Anton300bf8e2017-07-14 10:13:10 -0700585 rtc::Optional<rtc::IntervalRange> ice_regather_interval_range;
Jonas Orelandbdcee282017-10-10 14:01:40 +0200586 webrtc::TurnCustomizer* turn_customizer;
Steve Anton79e79602017-11-20 10:25:56 -0800587 SdpSemantics sdp_semantics;
deadbeef293e9262017-01-11 12:28:30 -0800588 };
589 static_assert(sizeof(stuff_being_tested_for_equality) == sizeof(*this),
590 "Did you add something to RTCConfiguration and forget to "
591 "update operator==?");
592 return type == o.type && servers == o.servers &&
593 bundle_policy == o.bundle_policy &&
594 rtcp_mux_policy == o.rtcp_mux_policy &&
595 tcp_candidate_policy == o.tcp_candidate_policy &&
596 candidate_network_policy == o.candidate_network_policy &&
597 audio_jitter_buffer_max_packets == o.audio_jitter_buffer_max_packets &&
598 audio_jitter_buffer_fast_accelerate ==
599 o.audio_jitter_buffer_fast_accelerate &&
600 ice_connection_receiving_timeout ==
601 o.ice_connection_receiving_timeout &&
602 ice_backup_candidate_pair_ping_interval ==
603 o.ice_backup_candidate_pair_ping_interval &&
604 continual_gathering_policy == o.continual_gathering_policy &&
605 certificates == o.certificates &&
606 prioritize_most_likely_ice_candidate_pairs ==
607 o.prioritize_most_likely_ice_candidate_pairs &&
608 media_config == o.media_config && disable_ipv6 == o.disable_ipv6 &&
zhihuangb09b3f92017-03-07 14:40:51 -0800609 disable_ipv6_on_wifi == o.disable_ipv6_on_wifi &&
deadbeefd21eab32017-07-26 16:50:11 -0700610 max_ipv6_networks == o.max_ipv6_networks &&
deadbeef293e9262017-01-11 12:28:30 -0800611 enable_rtp_data_channel == o.enable_rtp_data_channel &&
deadbeef293e9262017-01-11 12:28:30 -0800612 screencast_min_bitrate == o.screencast_min_bitrate &&
613 combined_audio_video_bwe == o.combined_audio_video_bwe &&
614 enable_dtls_srtp == o.enable_dtls_srtp &&
615 ice_candidate_pool_size == o.ice_candidate_pool_size &&
616 prune_turn_ports == o.prune_turn_ports &&
617 presume_writable_when_fully_relayed ==
618 o.presume_writable_when_fully_relayed &&
619 enable_ice_renomination == o.enable_ice_renomination &&
skvlad51072462017-02-02 11:50:14 -0800620 redetermine_role_on_ice_restart == o.redetermine_role_on_ice_restart &&
Steve Anton300bf8e2017-07-14 10:13:10 -0700621 ice_check_min_interval == o.ice_check_min_interval &&
Jonas Orelandbdcee282017-10-10 14:01:40 +0200622 ice_regather_interval_range == o.ice_regather_interval_range &&
Steve Anton79e79602017-11-20 10:25:56 -0800623 turn_customizer == o.turn_customizer &&
624 sdp_semantics == o.sdp_semantics;
deadbeef293e9262017-01-11 12:28:30 -0800625}
626
627bool PeerConnectionInterface::RTCConfiguration::operator!=(
628 const PeerConnectionInterface::RTCConfiguration& o) const {
629 return !(*this == o);
deadbeef3edec7c2016-12-10 11:44:26 -0800630}
631
zhihuang8f65cdf2016-05-06 18:40:30 -0700632// Generate a RTCP CNAME when a PeerConnection is created.
633std::string GenerateRtcpCname() {
634 std::string cname;
635 if (!rtc::CreateRandomString(kRtcpCnameLength, &cname)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100636 RTC_LOG(LS_ERROR) << "Failed to generate CNAME.";
nisseeb4ca4e2017-01-12 02:24:27 -0800637 RTC_NOTREACHED();
zhihuang8f65cdf2016-05-06 18:40:30 -0700638 }
639 return cname;
640}
641
zhihuang1c378ed2017-08-17 14:10:50 -0700642bool ValidateOfferAnswerOptions(
643 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options) {
644 return IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_audio) &&
645 IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_video);
olka3c747662017-08-17 06:50:32 -0700646}
647
zhihuang1c378ed2017-08-17 14:10:50 -0700648// From |rtc_options|, fill parts of |session_options| shared by all generated
649// m= sections (in other words, nothing that involves a map/array).
650void ExtractSharedMediaSessionOptions(
651 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options,
652 cricket::MediaSessionOptions* session_options) {
653 session_options->vad_enabled = rtc_options.voice_activity_detection;
654 session_options->bundle_enabled = rtc_options.use_rtp_mux;
655}
zhihuanga77e6bb2017-08-14 18:17:48 -0700656
zhihuang1c378ed2017-08-17 14:10:50 -0700657bool ConvertConstraintsToOfferAnswerOptions(
658 const MediaConstraintsInterface* constraints,
659 PeerConnectionInterface::RTCOfferAnswerOptions* offer_answer_options) {
olka3c747662017-08-17 06:50:32 -0700660 if (!constraints) {
661 return true;
662 }
zhihuang1c378ed2017-08-17 14:10:50 -0700663
664 bool value = false;
665 size_t mandatory_constraints_satisfied = 0;
666
667 if (FindConstraint(constraints,
668 MediaConstraintsInterface::kOfferToReceiveAudio, &value,
669 &mandatory_constraints_satisfied)) {
670 offer_answer_options->offer_to_receive_audio =
671 value ? PeerConnectionInterface::RTCOfferAnswerOptions::
672 kOfferToReceiveMediaTrue
673 : 0;
674 }
675
676 if (FindConstraint(constraints,
677 MediaConstraintsInterface::kOfferToReceiveVideo, &value,
678 &mandatory_constraints_satisfied)) {
679 offer_answer_options->offer_to_receive_video =
680 value ? PeerConnectionInterface::RTCOfferAnswerOptions::
681 kOfferToReceiveMediaTrue
682 : 0;
683 }
684 if (FindConstraint(constraints,
685 MediaConstraintsInterface::kVoiceActivityDetection, &value,
686 &mandatory_constraints_satisfied)) {
687 offer_answer_options->voice_activity_detection = value;
688 }
689 if (FindConstraint(constraints, MediaConstraintsInterface::kUseRtpMux, &value,
690 &mandatory_constraints_satisfied)) {
691 offer_answer_options->use_rtp_mux = value;
692 }
693 if (FindConstraint(constraints, MediaConstraintsInterface::kIceRestart,
694 &value, &mandatory_constraints_satisfied)) {
695 offer_answer_options->ice_restart = value;
696 }
697
deadbeefab9b2d12015-10-14 11:33:11 -0700698 return mandatory_constraints_satisfied == constraints->GetMandatory().size();
699}
700
zhihuang38ede132017-06-15 12:52:32 -0700701PeerConnection::PeerConnection(PeerConnectionFactory* factory,
702 std::unique_ptr<RtcEventLog> event_log,
703 std::unique_ptr<Call> call)
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000704 : factory_(factory),
zhihuang38ede132017-06-15 12:52:32 -0700705 event_log_(std::move(event_log)),
zhihuang8f65cdf2016-05-06 18:40:30 -0700706 rtcp_cname_(GenerateRtcpCname()),
deadbeefab9b2d12015-10-14 11:33:11 -0700707 local_streams_(StreamCollection::Create()),
zhihuang38ede132017-06-15 12:52:32 -0700708 remote_streams_(StreamCollection::Create()),
709 call_(std::move(call)) {}
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000710
711PeerConnection::~PeerConnection() {
Peter Boström1a9d6152015-12-08 22:15:17 +0100712 TRACE_EVENT0("webrtc", "PeerConnection::~PeerConnection");
Steve Anton4171afb2017-11-20 10:20:22 -0800713 RTC_DCHECK_RUN_ON(signaling_thread());
714
Steve Anton8af21862017-12-15 11:20:13 -0800715 // Need to stop transceivers before destroying the stats collector because
716 // AudioRtpSender has a reference to the StatsCollector it will update when
717 // stopping.
718 for (auto transceiver : transceivers_) {
719 transceiver->Stop();
720 }
Steve Anton4171afb2017-11-20 10:20:22 -0800721
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700722 stats_.reset(nullptr);
hbosb78306a2016-12-19 05:06:57 -0800723 if (stats_collector_) {
724 stats_collector_->WaitForPendingRequest();
725 stats_collector_ = nullptr;
726 }
Steve Anton75737c02017-11-06 10:37:17 -0800727
Steve Anton8af21862017-12-15 11:20:13 -0800728 // Don't destroy BaseChannels until after stats has been cleaned up so that
729 // the last stats request can still read from the channels.
730 DestroyAllChannels();
731
Mirko Bonadei675513b2017-11-09 11:09:25 +0100732 RTC_LOG(LS_INFO) << "Session: " << session_id() << " is destroyed.";
Steve Anton75737c02017-11-06 10:37:17 -0800733
734 webrtc_session_desc_factory_.reset();
735 sctp_invoker_.reset();
736 sctp_factory_.reset();
737 transport_controller_.reset();
738
deadbeef91dd5672016-05-18 16:55:30 -0700739 // port_allocator_ lives on the network thread and should be destroyed there.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700740 network_thread()->Invoke<void>(RTC_FROM_HERE,
nisseeaabdf62017-05-05 02:23:02 -0700741 [this] { port_allocator_.reset(); });
eladalon248fd4f2017-09-06 05:18:15 -0700742 // call_ and event_log_ must be destroyed on the worker thread.
Steve Anton978b8762017-09-29 12:15:02 -0700743 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
eladalon248fd4f2017-09-06 05:18:15 -0700744 call_.reset();
745 event_log_.reset();
746 });
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000747}
748
Steve Anton8af21862017-12-15 11:20:13 -0800749void PeerConnection::DestroyAllChannels() {
Steve Anton3fe1b152017-12-12 10:20:08 -0800750 // Destroy video channels first since they may have a pointer to a voice
751 // channel.
752 for (auto transceiver : transceivers_) {
753 if (transceiver->internal()->media_type() == cricket::MEDIA_TYPE_VIDEO) {
754 DestroyTransceiverChannel(transceiver);
755 }
756 }
757 for (auto transceiver : transceivers_) {
758 if (transceiver->internal()->media_type() == cricket::MEDIA_TYPE_AUDIO) {
759 DestroyTransceiverChannel(transceiver);
760 }
761 }
762 DestroyDataChannel();
763}
764
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000765bool PeerConnection::Initialize(
buildbot@webrtc.org41451d42014-05-03 05:39:45 +0000766 const PeerConnectionInterface::RTCConfiguration& configuration,
kwibergd1fe2812016-04-27 06:47:29 -0700767 std::unique_ptr<cricket::PortAllocator> allocator,
Henrik Boströmd03c23b2016-06-01 11:44:18 +0200768 std::unique_ptr<rtc::RTCCertificateGeneratorInterface> cert_generator,
deadbeef653b8e02015-11-11 12:55:10 -0800769 PeerConnectionObserver* observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100770 TRACE_EVENT0("webrtc", "PeerConnection::Initialize");
Steve Anton038834f2017-07-14 15:59:59 -0700771
772 RTCError config_error = ValidateConfiguration(configuration);
773 if (!config_error.ok()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100774 RTC_LOG(LS_ERROR) << "Invalid configuration: " << config_error.message();
Steve Anton038834f2017-07-14 15:59:59 -0700775 return false;
776 }
777
deadbeef293e9262017-01-11 12:28:30 -0800778 if (!allocator) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100779 RTC_LOG(LS_ERROR)
780 << "PeerConnection initialized without a PortAllocator? "
781 << "This shouldn't happen if using PeerConnectionFactory.";
deadbeef293e9262017-01-11 12:28:30 -0800782 return false;
783 }
Jonas Orelandbdcee282017-10-10 14:01:40 +0200784
deadbeef653b8e02015-11-11 12:55:10 -0800785 if (!observer) {
deadbeef293e9262017-01-11 12:28:30 -0800786 // TODO(deadbeef): Why do we do this?
Mirko Bonadei675513b2017-11-09 11:09:25 +0100787 RTC_LOG(LS_ERROR) << "PeerConnection initialized without a "
788 << "PeerConnectionObserver";
deadbeef653b8e02015-11-11 12:55:10 -0800789 return false;
790 }
pthatcher@webrtc.org877ac762015-02-04 22:03:09 +0000791 observer_ = observer;
kwiberg0eb15ed2015-12-17 03:04:15 -0800792 port_allocator_ = std::move(allocator);
deadbeef653b8e02015-11-11 12:55:10 -0800793
deadbeef91dd5672016-05-18 16:55:30 -0700794 // The port allocator lives on the network thread and should be initialized
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700795 // there.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700796 if (!network_thread()->Invoke<bool>(
797 RTC_FROM_HERE, rtc::Bind(&PeerConnection::InitializePortAllocator_n,
798 this, configuration))) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000799 return false;
800 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000801
Steve Anton75737c02017-11-06 10:37:17 -0800802 // RFC 3264: The numeric value of the session id and version in the
803 // o line MUST be representable with a "64 bit signed integer".
804 // Due to this constraint session id |session_id_| is max limited to
805 // LLONG_MAX.
806 session_id_ = rtc::ToString(rtc::CreateRandomId64() & LLONG_MAX);
807 transport_controller_.reset(factory_->CreateTransportController(
808 port_allocator_.get(), configuration.redetermine_role_on_ice_restart));
809 transport_controller_->SetIceRole(cricket::ICEROLE_CONTROLLED);
810 transport_controller_->SignalConnectionState.connect(
811 this, &PeerConnection::OnTransportControllerConnectionState);
812 transport_controller_->SignalGatheringState.connect(
813 this, &PeerConnection::OnTransportControllerGatheringState);
814 transport_controller_->SignalCandidatesGathered.connect(
815 this, &PeerConnection::OnTransportControllerCandidatesGathered);
816 transport_controller_->SignalCandidatesRemoved.connect(
817 this, &PeerConnection::OnTransportControllerCandidatesRemoved);
818 transport_controller_->SignalDtlsHandshakeError.connect(
819 this, &PeerConnection::OnTransportControllerDtlsHandshakeError);
820
821 sctp_factory_ = factory_->CreateSctpTransportInternalFactory();
zhihuang29ff8442016-07-27 11:07:25 -0700822
deadbeefab9b2d12015-10-14 11:33:11 -0700823 stats_.reset(new StatsCollector(this));
hbos74e1a4f2016-09-15 23:33:01 -0700824 stats_collector_ = RTCStatsCollector::Create(this);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000825
Steve Antonba818672017-11-06 10:21:57 -0800826 configuration_ = configuration;
827
Steve Anton75737c02017-11-06 10:37:17 -0800828 const PeerConnectionFactoryInterface::Options& options = factory_->options();
829
830 transport_controller_->SetSslMaxProtocolVersion(options.ssl_max_version);
831
832 // Obtain a certificate from RTCConfiguration if any were provided (optional).
833 rtc::scoped_refptr<rtc::RTCCertificate> certificate;
834 if (!configuration.certificates.empty()) {
835 // TODO(hbos,torbjorng): Decide on certificate-selection strategy instead of
836 // just picking the first one. The decision should be made based on the DTLS
837 // handshake. The DTLS negotiations need to know about all certificates.
838 certificate = configuration.certificates[0];
839 }
840
Steve Antond25da372017-11-06 14:50:29 -0800841 transport_controller_->SetIceConfig(ParseIceConfig(configuration));
Steve Anton75737c02017-11-06 10:37:17 -0800842
843 if (options.disable_encryption) {
844 dtls_enabled_ = false;
845 } else {
846 // Enable DTLS by default if we have an identity store or a certificate.
847 dtls_enabled_ = (cert_generator || certificate);
848 // |configuration| can override the default |dtls_enabled_| value.
849 if (configuration.enable_dtls_srtp) {
850 dtls_enabled_ = *(configuration.enable_dtls_srtp);
851 }
852 }
853
854 // Enable creation of RTP data channels if the kEnableRtpDataChannels is set.
855 // It takes precendence over the disable_sctp_data_channels
856 // PeerConnectionFactoryInterface::Options.
857 if (configuration.enable_rtp_data_channel) {
858 data_channel_type_ = cricket::DCT_RTP;
859 } else {
860 // DTLS has to be enabled to use SCTP.
861 if (!options.disable_sctp_data_channels && dtls_enabled_) {
862 data_channel_type_ = cricket::DCT_SCTP;
863 }
864 }
865
866 video_options_.screencast_min_bitrate_kbps =
867 configuration.screencast_min_bitrate;
868 audio_options_.combined_audio_video_bwe =
869 configuration.combined_audio_video_bwe;
870
871 audio_options_.audio_jitter_buffer_max_packets =
Oskar Sundbom9b28a032017-11-16 10:53:30 +0100872 configuration.audio_jitter_buffer_max_packets;
Steve Anton75737c02017-11-06 10:37:17 -0800873
874 audio_options_.audio_jitter_buffer_fast_accelerate =
Oskar Sundbom9b28a032017-11-16 10:53:30 +0100875 configuration.audio_jitter_buffer_fast_accelerate;
Steve Anton75737c02017-11-06 10:37:17 -0800876
877 // Whether the certificate generator/certificate is null or not determines
878 // what PeerConnectionDescriptionFactory will do, so make sure that we give it
879 // the right instructions by clearing the variables if needed.
880 if (!dtls_enabled_) {
881 cert_generator.reset();
882 certificate = nullptr;
883 } else if (certificate) {
884 // Favor generated certificate over the certificate generator.
885 cert_generator.reset();
886 }
887
888 webrtc_session_desc_factory_.reset(new WebRtcSessionDescriptionFactory(
889 signaling_thread(), channel_manager(), this, session_id(),
890 std::move(cert_generator), certificate));
891 webrtc_session_desc_factory_->SignalCertificateReady.connect(
892 this, &PeerConnection::OnCertificateReady);
893
894 if (options.disable_encryption) {
895 webrtc_session_desc_factory_->SetSdesPolicy(cricket::SEC_DISABLED);
896 }
897
898 webrtc_session_desc_factory_->set_enable_encrypted_rtp_header_extensions(
899 options.crypto_options.enable_encrypted_rtp_header_extensions);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000900
Steve Anton4171afb2017-11-20 10:20:22 -0800901 // Add default audio/video transceivers for Plan B SDP.
902 if (!IsUnifiedPlan()) {
903 transceivers_.push_back(
904 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
905 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_AUDIO)));
906 transceivers_.push_back(
907 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
908 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_VIDEO)));
909 }
910
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000911 return true;
912}
913
Steve Anton038834f2017-07-14 15:59:59 -0700914RTCError PeerConnection::ValidateConfiguration(
915 const RTCConfiguration& config) const {
916 if (config.ice_regather_interval_range &&
917 config.continual_gathering_policy == GATHER_ONCE) {
918 return RTCError(RTCErrorType::INVALID_PARAMETER,
919 "ice_regather_interval_range specified but continual "
920 "gathering policy is GATHER_ONCE");
921 }
922 return RTCError::OK();
923}
924
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000925rtc::scoped_refptr<StreamCollectionInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000926PeerConnection::local_streams() {
deadbeefab9b2d12015-10-14 11:33:11 -0700927 return local_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000928}
929
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000930rtc::scoped_refptr<StreamCollectionInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000931PeerConnection::remote_streams() {
deadbeefab9b2d12015-10-14 11:33:11 -0700932 return remote_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000933}
934
perkj@webrtc.orgc2dd5ee2014-11-04 11:31:29 +0000935bool PeerConnection::AddStream(MediaStreamInterface* local_stream) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100936 TRACE_EVENT0("webrtc", "PeerConnection::AddStream");
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000937 if (IsClosed()) {
938 return false;
939 }
deadbeefab9b2d12015-10-14 11:33:11 -0700940 if (!CanAddLocalMediaStream(local_streams_, local_stream)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000941 return false;
942 }
deadbeefab9b2d12015-10-14 11:33:11 -0700943
944 local_streams_->AddStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -0800945 MediaStreamObserver* observer = new MediaStreamObserver(local_stream);
946 observer->SignalAudioTrackAdded.connect(this,
947 &PeerConnection::OnAudioTrackAdded);
948 observer->SignalAudioTrackRemoved.connect(
949 this, &PeerConnection::OnAudioTrackRemoved);
950 observer->SignalVideoTrackAdded.connect(this,
951 &PeerConnection::OnVideoTrackAdded);
952 observer->SignalVideoTrackRemoved.connect(
953 this, &PeerConnection::OnVideoTrackRemoved);
kwibergd1fe2812016-04-27 06:47:29 -0700954 stream_observers_.push_back(std::unique_ptr<MediaStreamObserver>(observer));
deadbeefab9b2d12015-10-14 11:33:11 -0700955
deadbeefab9b2d12015-10-14 11:33:11 -0700956 for (const auto& track : local_stream->GetAudioTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -0700957 AddAudioTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -0700958 }
959 for (const auto& track : local_stream->GetVideoTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -0700960 AddVideoTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -0700961 }
962
tommi@webrtc.org03505bc2014-07-14 20:15:26 +0000963 stats_->AddStream(local_stream);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000964 observer_->OnRenegotiationNeeded();
965 return true;
966}
967
968void PeerConnection::RemoveStream(MediaStreamInterface* local_stream) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100969 TRACE_EVENT0("webrtc", "PeerConnection::RemoveStream");
korniltsev.anatolyec390b52017-07-24 17:00:25 -0700970 if (!IsClosed()) {
971 for (const auto& track : local_stream->GetAudioTracks()) {
972 RemoveAudioTrack(track.get(), local_stream);
973 }
974 for (const auto& track : local_stream->GetVideoTracks()) {
975 RemoveVideoTrack(track.get(), local_stream);
976 }
deadbeefab9b2d12015-10-14 11:33:11 -0700977 }
deadbeefab9b2d12015-10-14 11:33:11 -0700978 local_streams_->RemoveStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -0800979 stream_observers_.erase(
980 std::remove_if(
981 stream_observers_.begin(), stream_observers_.end(),
kwibergd1fe2812016-04-27 06:47:29 -0700982 [local_stream](const std::unique_ptr<MediaStreamObserver>& observer) {
deadbeefeb459812015-12-15 19:24:43 -0800983 return observer->stream()->label().compare(local_stream->label()) ==
984 0;
985 }),
986 stream_observers_.end());
deadbeefab9b2d12015-10-14 11:33:11 -0700987
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000988 if (IsClosed()) {
989 return;
990 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000991 observer_->OnRenegotiationNeeded();
992}
993
deadbeefe1f9d832016-01-14 15:35:42 -0800994rtc::scoped_refptr<RtpSenderInterface> PeerConnection::AddTrack(
995 MediaStreamTrackInterface* track,
996 std::vector<MediaStreamInterface*> streams) {
997 TRACE_EVENT0("webrtc", "PeerConnection::AddTrack");
Steve Antonf9381f02017-12-14 10:23:57 -0800998 std::vector<std::string> stream_labels;
999 for (auto* stream : streams) {
1000 if (!stream) {
1001 RTC_LOG(LS_ERROR) << "Stream list has null element.";
1002 return nullptr;
1003 }
1004 stream_labels.push_back(stream->label());
1005 }
1006 auto sender_or_error = AddTrackWithStreamLabels(track, stream_labels);
1007 if (!sender_or_error.ok()) {
deadbeefe1f9d832016-01-14 15:35:42 -08001008 return nullptr;
1009 }
Steve Antonf9381f02017-12-14 10:23:57 -08001010 return sender_or_error.MoveValue();
1011}
1012
1013RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>>
1014PeerConnection::AddTrackWithStreamLabels(
1015 rtc::scoped_refptr<MediaStreamTrackInterface> track,
1016 const std::vector<std::string>& stream_labels) {
1017 TRACE_EVENT0("webrtc", "PeerConnection::AddTrackWithStreamLabels");
1018 if (!track) {
1019 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "Track is null.");
1020 }
1021 if (!(track->kind() == MediaStreamTrackInterface::kAudioKind ||
1022 track->kind() == MediaStreamTrackInterface::kVideoKind)) {
1023 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1024 "Track has invalid kind: " + track->kind());
1025 }
1026 // TODO(bugs.webrtc.org/7932): Support adding a track to multiple streams.
1027 if (stream_labels.size() > 1u) {
1028 LOG_AND_RETURN_ERROR(
1029 RTCErrorType::UNSUPPORTED_OPERATION,
1030 "AddTrack with more than one stream is not currently supported.");
1031 }
1032 if (IsClosed()) {
1033 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
1034 "PeerConnection is closed.");
deadbeefe1f9d832016-01-14 15:35:42 -08001035 }
Steve Anton4171afb2017-11-20 10:20:22 -08001036 if (FindSenderForTrack(track)) {
Steve Antonf9381f02017-12-14 10:23:57 -08001037 LOG_AND_RETURN_ERROR(
1038 RTCErrorType::INVALID_PARAMETER,
1039 "Sender already exists for track " + track->id() + ".");
deadbeefe1f9d832016-01-14 15:35:42 -08001040 }
Steve Antonf9381f02017-12-14 10:23:57 -08001041 // TODO(bugs.webrtc.org/7933): MediaSession expects the sender to have exactly
1042 // one stream. AddTrackInternal will return an error if there is more than one
1043 // stream, but if the caller specifies none then we need to generate a random
1044 // stream label.
1045 std::vector<std::string> adjusted_stream_labels = stream_labels;
1046 if (stream_labels.empty()) {
1047 adjusted_stream_labels.push_back(rtc::CreateRandomUuid());
1048 }
1049 RTC_DCHECK_EQ(1, adjusted_stream_labels.size());
1050 auto sender_or_error =
1051 (IsUnifiedPlan() ? AddTrackUnifiedPlan(track, adjusted_stream_labels)
1052 : AddTrackPlanB(track, adjusted_stream_labels));
1053 if (sender_or_error.ok()) {
1054 observer_->OnRenegotiationNeeded();
1055 }
1056 return sender_or_error;
1057}
deadbeefe1f9d832016-01-14 15:35:42 -08001058
Steve Antonf9381f02017-12-14 10:23:57 -08001059RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>>
1060PeerConnection::AddTrackPlanB(
1061 rtc::scoped_refptr<MediaStreamTrackInterface> track,
1062 const std::vector<std::string>& stream_labels) {
deadbeefe1f9d832016-01-14 15:35:42 -08001063 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
Steve Antonf9381f02017-12-14 10:23:57 -08001064 auto new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
deadbeefe1f9d832016-01-14 15:35:42 -08001065 signaling_thread(),
Steve Antonf9381f02017-12-14 10:23:57 -08001066 new AudioRtpSender(static_cast<AudioTrackInterface*>(track.get()),
Steve Anton75737c02017-11-06 10:37:17 -08001067 voice_channel(), stats_.get()));
Steve Anton4171afb2017-11-20 10:20:22 -08001068 GetAudioTransceiver()->internal()->AddSender(new_sender);
Steve Antonf9381f02017-12-14 10:23:57 -08001069 new_sender->internal()->set_stream_ids(stream_labels);
Steve Anton4171afb2017-11-20 10:20:22 -08001070 const RtpSenderInfo* sender_info =
1071 FindSenderInfo(local_audio_sender_infos_,
1072 new_sender->internal()->stream_id(), track->id());
1073 if (sender_info) {
1074 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -08001075 }
Steve Antonf9381f02017-12-14 10:23:57 -08001076 return rtc::scoped_refptr<RtpSenderInterface>(new_sender);
1077 } else {
1078 RTC_DCHECK_EQ(MediaStreamTrackInterface::kVideoKind, track->kind());
1079 auto new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
deadbeefe1f9d832016-01-14 15:35:42 -08001080 signaling_thread(),
Steve Antonf9381f02017-12-14 10:23:57 -08001081 new VideoRtpSender(static_cast<VideoTrackInterface*>(track.get()),
Steve Anton75737c02017-11-06 10:37:17 -08001082 video_channel()));
Steve Anton4171afb2017-11-20 10:20:22 -08001083 GetVideoTransceiver()->internal()->AddSender(new_sender);
Steve Antonf9381f02017-12-14 10:23:57 -08001084 new_sender->internal()->set_stream_ids(stream_labels);
Steve Anton4171afb2017-11-20 10:20:22 -08001085 const RtpSenderInfo* sender_info =
1086 FindSenderInfo(local_video_sender_infos_,
1087 new_sender->internal()->stream_id(), track->id());
1088 if (sender_info) {
1089 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -08001090 }
Steve Antonf9381f02017-12-14 10:23:57 -08001091 return rtc::scoped_refptr<RtpSenderInterface>(new_sender);
deadbeefe1f9d832016-01-14 15:35:42 -08001092 }
Steve Antonf9381f02017-12-14 10:23:57 -08001093}
deadbeefe1f9d832016-01-14 15:35:42 -08001094
Steve Antonf9381f02017-12-14 10:23:57 -08001095RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>>
1096PeerConnection::AddTrackUnifiedPlan(
1097 rtc::scoped_refptr<MediaStreamTrackInterface> track,
1098 const std::vector<std::string>& stream_labels) {
1099 auto transceiver = FindFirstTransceiverForAddedTrack(track);
1100 if (transceiver) {
1101 if (transceiver->direction() == RtpTransceiverDirection::kRecvOnly) {
1102 transceiver->SetDirection(RtpTransceiverDirection::kSendRecv);
1103 } else if (transceiver->direction() == RtpTransceiverDirection::kInactive) {
1104 transceiver->SetDirection(RtpTransceiverDirection::kSendOnly);
1105 }
1106 } else {
1107 cricket::MediaType media_type =
1108 (track->kind() == MediaStreamTrackInterface::kAudioKind
1109 ? cricket::MEDIA_TYPE_AUDIO
1110 : cricket::MEDIA_TYPE_VIDEO);
1111 transceiver = CreateTransceiver(media_type);
1112 transceiver->internal()->set_created_by_addtrack(true);
1113 transceiver->SetDirection(RtpTransceiverDirection::kSendRecv);
1114 }
1115 transceiver->sender()->SetTrack(track);
1116 transceiver->internal()->sender_internal()->set_stream_ids(stream_labels);
1117 return transceiver->sender();
1118}
1119
1120rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1121PeerConnection::FindFirstTransceiverForAddedTrack(
1122 rtc::scoped_refptr<MediaStreamTrackInterface> track) {
1123 RTC_DCHECK(track);
1124 for (auto transceiver : transceivers_) {
1125 if (!transceiver->sender()->track() &&
1126 cricket::MediaTypeToString(transceiver->internal()->media_type()) ==
1127 track->kind() &&
1128 !transceiver->internal()->has_ever_been_used_to_send()) {
1129 return transceiver;
1130 }
1131 }
1132 return nullptr;
deadbeefe1f9d832016-01-14 15:35:42 -08001133}
1134
1135bool PeerConnection::RemoveTrack(RtpSenderInterface* sender) {
1136 TRACE_EVENT0("webrtc", "PeerConnection::RemoveTrack");
Steve Antonf9381f02017-12-14 10:23:57 -08001137 return RemoveTrackInternal(sender).ok();
1138}
1139
1140RTCError PeerConnection::RemoveTrackInternal(
1141 rtc::scoped_refptr<RtpSenderInterface> sender) {
1142 if (!sender) {
1143 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "Sender is null.");
1144 }
deadbeefe1f9d832016-01-14 15:35:42 -08001145 if (IsClosed()) {
Steve Antonf9381f02017-12-14 10:23:57 -08001146 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
1147 "PeerConnection is closed.");
deadbeefe1f9d832016-01-14 15:35:42 -08001148 }
Steve Antonf9381f02017-12-14 10:23:57 -08001149 if (IsUnifiedPlan()) {
1150 auto transceiver = FindTransceiverBySender(sender);
1151 if (!transceiver || !sender->track()) {
1152 return RTCError::OK();
1153 }
1154 sender->SetTrack(nullptr);
1155 if (transceiver->direction() == RtpTransceiverDirection::kSendRecv) {
1156 transceiver->internal()->SetDirection(RtpTransceiverDirection::kRecvOnly);
1157 } else if (transceiver->direction() == RtpTransceiverDirection::kSendOnly) {
1158 transceiver->internal()->SetDirection(RtpTransceiverDirection::kInactive);
1159 }
Steve Anton4171afb2017-11-20 10:20:22 -08001160 } else {
Steve Antonf9381f02017-12-14 10:23:57 -08001161 bool removed;
1162 if (sender->media_type() == cricket::MEDIA_TYPE_AUDIO) {
1163 removed = GetAudioTransceiver()->internal()->RemoveSender(sender);
1164 } else {
1165 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, sender->media_type());
1166 removed = GetVideoTransceiver()->internal()->RemoveSender(sender);
1167 }
1168 if (!removed) {
1169 LOG_AND_RETURN_ERROR(
1170 RTCErrorType::INVALID_PARAMETER,
1171 "Couldn't find sender " + sender->id() + " to remove.");
1172 }
Steve Anton4171afb2017-11-20 10:20:22 -08001173 }
deadbeefe1f9d832016-01-14 15:35:42 -08001174 observer_->OnRenegotiationNeeded();
Steve Antonf9381f02017-12-14 10:23:57 -08001175 return RTCError::OK();
1176}
1177
1178rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1179PeerConnection::FindTransceiverBySender(
1180 rtc::scoped_refptr<RtpSenderInterface> sender) {
1181 for (auto transceiver : transceivers_) {
1182 if (transceiver->sender() == sender) {
1183 return transceiver;
1184 }
1185 }
1186 return nullptr;
deadbeefe1f9d832016-01-14 15:35:42 -08001187}
1188
Steve Anton9158ef62017-11-27 13:01:52 -08001189RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1190PeerConnection::AddTransceiver(
1191 rtc::scoped_refptr<MediaStreamTrackInterface> track) {
1192 return AddTransceiver(track, RtpTransceiverInit());
1193}
1194
1195RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1196PeerConnection::AddTransceiver(
1197 rtc::scoped_refptr<MediaStreamTrackInterface> track,
1198 const RtpTransceiverInit& init) {
1199 if (!IsUnifiedPlan()) {
1200 LOG_AND_RETURN_ERROR(
1201 RTCErrorType::INTERNAL_ERROR,
1202 "AddTransceiver only supported when Unified Plan is enabled.");
1203 }
1204 if (!track) {
1205 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "track is null");
1206 }
1207 cricket::MediaType media_type;
1208 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
1209 media_type = cricket::MEDIA_TYPE_AUDIO;
1210 } else if (track->kind() == MediaStreamTrackInterface::kVideoKind) {
1211 media_type = cricket::MEDIA_TYPE_VIDEO;
1212 } else {
1213 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1214 "Track kind is not audio or video");
1215 }
1216 return AddTransceiver(media_type, track, init);
1217}
1218
1219RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1220PeerConnection::AddTransceiver(cricket::MediaType media_type) {
1221 return AddTransceiver(media_type, RtpTransceiverInit());
1222}
1223
1224RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1225PeerConnection::AddTransceiver(cricket::MediaType media_type,
1226 const RtpTransceiverInit& init) {
1227 if (!IsUnifiedPlan()) {
1228 LOG_AND_RETURN_ERROR(
1229 RTCErrorType::INTERNAL_ERROR,
1230 "AddTransceiver only supported when Unified Plan is enabled.");
1231 }
1232 if (!(media_type == cricket::MEDIA_TYPE_AUDIO ||
1233 media_type == cricket::MEDIA_TYPE_VIDEO)) {
1234 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1235 "media type is not audio or video");
1236 }
1237 return AddTransceiver(media_type, nullptr, init);
1238}
1239
1240RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1241PeerConnection::AddTransceiver(
1242 cricket::MediaType media_type,
1243 rtc::scoped_refptr<MediaStreamTrackInterface> track,
1244 const RtpTransceiverInit& init) {
1245 RTC_DCHECK((media_type == cricket::MEDIA_TYPE_AUDIO ||
1246 media_type == cricket::MEDIA_TYPE_VIDEO));
1247 if (track) {
1248 RTC_DCHECK_EQ(media_type,
1249 (track->kind() == MediaStreamTrackInterface::kAudioKind
1250 ? cricket::MEDIA_TYPE_AUDIO
1251 : cricket::MEDIA_TYPE_VIDEO));
1252 }
1253
1254 // TODO(bugs.webrtc.org/7600): Verify init.
1255
Steve Antonf9381f02017-12-14 10:23:57 -08001256 auto transceiver = CreateTransceiver(media_type);
1257 transceiver->SetDirection(init.direction);
1258 if (track) {
1259 transceiver->sender()->SetTrack(track);
1260 }
1261
1262 observer_->OnRenegotiationNeeded();
1263
1264 return rtc::scoped_refptr<RtpTransceiverInterface>(transceiver);
1265}
1266
1267rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1268PeerConnection::CreateTransceiver(cricket::MediaType media_type) {
Steve Anton9158ef62017-11-27 13:01:52 -08001269 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> sender;
1270 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1271 receiver;
1272 std::string receiver_id = rtc::CreateRandomUuid();
Steve Antonf9381f02017-12-14 10:23:57 -08001273 // TODO(bugs.webrtc.org/7600): Initializing the sender/receiver with a null
1274 // channel prevents users from calling SetParameters on them, which is needed
1275 // to be in compliance with the spec.
Steve Anton9158ef62017-11-27 13:01:52 -08001276 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
1277 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
1278 signaling_thread(), new AudioRtpSender(nullptr, stats_.get()));
1279 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
1280 signaling_thread(), new AudioRtpReceiver(receiver_id, {}, 0, nullptr));
1281 } else {
1282 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, media_type);
1283 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
1284 signaling_thread(), new VideoRtpSender(nullptr));
1285 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
1286 signaling_thread(),
1287 new VideoRtpReceiver(receiver_id, {}, worker_thread(), 0, nullptr));
1288 }
Steve Anton9158ef62017-11-27 13:01:52 -08001289 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1290 transceiver = RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1291 signaling_thread(), new RtpTransceiver(sender, receiver));
Steve Anton9158ef62017-11-27 13:01:52 -08001292 transceivers_.push_back(transceiver);
Steve Antonf9381f02017-12-14 10:23:57 -08001293 return transceiver;
Steve Anton9158ef62017-11-27 13:01:52 -08001294}
1295
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001296rtc::scoped_refptr<DtmfSenderInterface> PeerConnection::CreateDtmfSender(
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001297 AudioTrackInterface* track) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001298 TRACE_EVENT0("webrtc", "PeerConnection::CreateDtmfSender");
zhihuang29ff8442016-07-27 11:07:25 -07001299 if (IsClosed()) {
1300 return nullptr;
1301 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001302 if (!track) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001303 RTC_LOG(LS_ERROR) << "CreateDtmfSender - track is NULL.";
deadbeef20cb0c12017-02-01 20:27:00 -08001304 return nullptr;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001305 }
Steve Anton4171afb2017-11-20 10:20:22 -08001306 auto track_sender = FindSenderForTrack(track);
1307 if (!track_sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001308 RTC_LOG(LS_ERROR) << "CreateDtmfSender called with a non-added track.";
deadbeef20cb0c12017-02-01 20:27:00 -08001309 return nullptr;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001310 }
1311
Steve Anton4171afb2017-11-20 10:20:22 -08001312 return track_sender->GetDtmfSender();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001313}
1314
deadbeeffac06552015-11-25 11:26:01 -08001315rtc::scoped_refptr<RtpSenderInterface> PeerConnection::CreateSender(
deadbeefbd7d8f72015-12-18 16:58:44 -08001316 const std::string& kind,
1317 const std::string& stream_id) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001318 TRACE_EVENT0("webrtc", "PeerConnection::CreateSender");
zhihuang29ff8442016-07-27 11:07:25 -07001319 if (IsClosed()) {
1320 return nullptr;
1321 }
Steve Anton4171afb2017-11-20 10:20:22 -08001322
1323 // TODO(steveanton): Move construction of the RtpSenders to RtpTransceiver.
deadbeefa601f5c2016-06-06 14:27:39 -07001324 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender;
deadbeeffac06552015-11-25 11:26:01 -08001325 if (kind == MediaStreamTrackInterface::kAudioKind) {
deadbeefa601f5c2016-06-06 14:27:39 -07001326 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton75737c02017-11-06 10:37:17 -08001327 signaling_thread(), new AudioRtpSender(voice_channel(), stats_.get()));
Steve Anton4171afb2017-11-20 10:20:22 -08001328 GetAudioTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 11:26:01 -08001329 } else if (kind == MediaStreamTrackInterface::kVideoKind) {
deadbeefa601f5c2016-06-06 14:27:39 -07001330 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton75737c02017-11-06 10:37:17 -08001331 signaling_thread(), new VideoRtpSender(video_channel()));
Steve Anton4171afb2017-11-20 10:20:22 -08001332 GetVideoTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 11:26:01 -08001333 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001334 RTC_LOG(LS_ERROR) << "CreateSender called with invalid kind: " << kind;
Steve Anton4171afb2017-11-20 10:20:22 -08001335 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08001336 }
Steve Anton4171afb2017-11-20 10:20:22 -08001337
deadbeefbd7d8f72015-12-18 16:58:44 -08001338 if (!stream_id.empty()) {
deadbeefa601f5c2016-06-06 14:27:39 -07001339 new_sender->internal()->set_stream_id(stream_id);
deadbeefbd7d8f72015-12-18 16:58:44 -08001340 }
Steve Anton4171afb2017-11-20 10:20:22 -08001341
deadbeefe1f9d832016-01-14 15:35:42 -08001342 return new_sender;
deadbeeffac06552015-11-25 11:26:01 -08001343}
1344
deadbeef70ab1a12015-09-28 16:53:55 -07001345std::vector<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::GetSenders()
1346 const {
deadbeefa601f5c2016-06-06 14:27:39 -07001347 std::vector<rtc::scoped_refptr<RtpSenderInterface>> ret;
Steve Anton4171afb2017-11-20 10:20:22 -08001348 for (auto sender : GetSendersInternal()) {
1349 ret.push_back(sender);
deadbeefa601f5c2016-06-06 14:27:39 -07001350 }
1351 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -07001352}
1353
Steve Anton4171afb2017-11-20 10:20:22 -08001354std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1355PeerConnection::GetSendersInternal() const {
1356 std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1357 all_senders;
1358 for (auto transceiver : transceivers_) {
1359 auto senders = transceiver->internal()->senders();
1360 all_senders.insert(all_senders.end(), senders.begin(), senders.end());
1361 }
1362 return all_senders;
1363}
1364
deadbeef70ab1a12015-09-28 16:53:55 -07001365std::vector<rtc::scoped_refptr<RtpReceiverInterface>>
1366PeerConnection::GetReceivers() const {
deadbeefa601f5c2016-06-06 14:27:39 -07001367 std::vector<rtc::scoped_refptr<RtpReceiverInterface>> ret;
Steve Anton4171afb2017-11-20 10:20:22 -08001368 for (const auto& receiver : GetReceiversInternal()) {
1369 ret.push_back(receiver);
deadbeefa601f5c2016-06-06 14:27:39 -07001370 }
1371 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -07001372}
1373
Steve Anton4171afb2017-11-20 10:20:22 -08001374std::vector<
1375 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1376PeerConnection::GetReceiversInternal() const {
1377 std::vector<
1378 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1379 all_receivers;
1380 for (auto transceiver : transceivers_) {
1381 auto receivers = transceiver->internal()->receivers();
1382 all_receivers.insert(all_receivers.end(), receivers.begin(),
1383 receivers.end());
1384 }
1385 return all_receivers;
1386}
1387
Steve Anton9158ef62017-11-27 13:01:52 -08001388std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
1389PeerConnection::GetTransceivers() const {
1390 RTC_DCHECK(IsUnifiedPlan());
1391 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> all_transceivers;
1392 for (auto transceiver : transceivers_) {
1393 all_transceivers.push_back(transceiver);
1394 }
1395 return all_transceivers;
1396}
1397
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001398bool PeerConnection::GetStats(StatsObserver* observer,
wu@webrtc.orgb9a088b2014-02-13 23:18:49 +00001399 MediaStreamTrackInterface* track,
1400 StatsOutputLevel level) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001401 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
deadbeef0a6c4ca2015-10-06 11:38:28 -07001402 RTC_DCHECK(signaling_thread()->IsCurrent());
nisse7ce109a2017-01-31 00:57:56 -08001403 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001404 RTC_LOG(LS_ERROR) << "GetStats - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001405 return false;
1406 }
1407
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001408 stats_->UpdateStats(level);
zhihuange9e94c32016-11-04 11:38:15 -07001409 // The StatsCollector is used to tell if a track is valid because it may
1410 // remember tracks that the PeerConnection previously removed.
1411 if (track && !stats_->IsValidTrack(track->id())) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001412 RTC_LOG(LS_WARNING) << "GetStats is called with an invalid track: "
1413 << track->id();
zhihuange9e94c32016-11-04 11:38:15 -07001414 return false;
1415 }
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001416 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_GETSTATS,
tommi@webrtc.org5b06b062014-08-15 08:38:30 +00001417 new GetStatsMsg(observer, track));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001418 return true;
1419}
1420
hbos74e1a4f2016-09-15 23:33:01 -07001421void PeerConnection::GetStats(RTCStatsCollectorCallback* callback) {
1422 RTC_DCHECK(stats_collector_);
1423 stats_collector_->GetStatsReport(callback);
1424}
1425
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001426PeerConnectionInterface::SignalingState PeerConnection::signaling_state() {
1427 return signaling_state_;
1428}
1429
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001430PeerConnectionInterface::IceConnectionState
1431PeerConnection::ice_connection_state() {
1432 return ice_connection_state_;
1433}
1434
1435PeerConnectionInterface::IceGatheringState
1436PeerConnection::ice_gathering_state() {
1437 return ice_gathering_state_;
1438}
1439
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001440rtc::scoped_refptr<DataChannelInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001441PeerConnection::CreateDataChannel(
1442 const std::string& label,
1443 const DataChannelInit* config) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001444 TRACE_EVENT0("webrtc", "PeerConnection::CreateDataChannel");
zhihuang9763d562016-08-05 11:14:50 -07001445
deadbeefab9b2d12015-10-14 11:33:11 -07001446 bool first_datachannel = !HasDataChannels();
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001447
kwibergd1fe2812016-04-27 06:47:29 -07001448 std::unique_ptr<InternalDataChannelInit> internal_config;
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00001449 if (config) {
1450 internal_config.reset(new InternalDataChannelInit(*config));
1451 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001452 rtc::scoped_refptr<DataChannelInterface> channel(
deadbeefab9b2d12015-10-14 11:33:11 -07001453 InternalCreateDataChannel(label, internal_config.get()));
1454 if (!channel.get()) {
1455 return nullptr;
1456 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001457
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001458 // Trigger the onRenegotiationNeeded event for every new RTP DataChannel, or
1459 // the first SCTP DataChannel.
Steve Anton75737c02017-11-06 10:37:17 -08001460 if (data_channel_type() == cricket::DCT_RTP || first_datachannel) {
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001461 observer_->OnRenegotiationNeeded();
1462 }
wu@webrtc.org91053e72013-08-10 07:18:04 +00001463
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001464 return DataChannelProxy::Create(signaling_thread(), channel.get());
1465}
1466
1467void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
1468 const MediaConstraintsInterface* constraints) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001469 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
Steve Anton8d3444d2017-10-20 15:30:51 -07001470
zhihuang1c378ed2017-08-17 14:10:50 -07001471 PeerConnectionInterface::RTCOfferAnswerOptions offer_answer_options;
1472 // Always create an offer even if |ConvertConstraintsToOfferAnswerOptions|
1473 // returns false for now. Because |ConvertConstraintsToOfferAnswerOptions|
1474 // compares the mandatory fields parsed with the mandatory fields added in the
1475 // |constraints| and some downstream applications might create offers with
1476 // mandatory fields which would not be parsed in the helper method. For
1477 // example, in Chromium/remoting, |kEnableDtlsSrtp| is added to the
1478 // |constraints| as a mandatory field but it is not parsed.
1479 ConvertConstraintsToOfferAnswerOptions(constraints, &offer_answer_options);
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001480
zhihuang1c378ed2017-08-17 14:10:50 -07001481 CreateOffer(observer, offer_answer_options);
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001482}
1483
1484void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
1485 const RTCOfferAnswerOptions& options) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001486 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
Steve Anton8d3444d2017-10-20 15:30:51 -07001487
nisse7ce109a2017-01-31 00:57:56 -08001488 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001489 RTC_LOG(LS_ERROR) << "CreateOffer - observer is NULL.";
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001490 return;
1491 }
deadbeefab9b2d12015-10-14 11:33:11 -07001492
Steve Anton8d3444d2017-10-20 15:30:51 -07001493 if (IsClosed()) {
1494 std::string error = "CreateOffer called when PeerConnection is closed.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001495 RTC_LOG(LS_ERROR) << error;
Steve Anton8d3444d2017-10-20 15:30:51 -07001496 PostCreateSessionDescriptionFailure(observer, error);
1497 return;
1498 }
1499
zhihuang1c378ed2017-08-17 14:10:50 -07001500 if (!ValidateOfferAnswerOptions(options)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001501 std::string error = "CreateOffer called with invalid options.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001502 RTC_LOG(LS_ERROR) << error;
deadbeefab9b2d12015-10-14 11:33:11 -07001503 PostCreateSessionDescriptionFailure(observer, error);
1504 return;
1505 }
1506
zhihuang1c378ed2017-08-17 14:10:50 -07001507 cricket::MediaSessionOptions session_options;
1508 GetOptionsForOffer(options, &session_options);
Steve Antond25da372017-11-06 14:50:29 -08001509 webrtc_session_desc_factory_->CreateOffer(observer, options, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001510}
1511
1512void PeerConnection::CreateAnswer(
1513 CreateSessionDescriptionObserver* observer,
1514 const MediaConstraintsInterface* constraints) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001515 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
Steve Anton8d3444d2017-10-20 15:30:51 -07001516
nisse7ce109a2017-01-31 00:57:56 -08001517 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001518 RTC_LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001519 return;
1520 }
deadbeefab9b2d12015-10-14 11:33:11 -07001521
zhihuang1c378ed2017-08-17 14:10:50 -07001522 PeerConnectionInterface::RTCOfferAnswerOptions offer_answer_options;
1523 if (!ConvertConstraintsToOfferAnswerOptions(constraints,
1524 &offer_answer_options)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001525 std::string error = "CreateAnswer called with invalid constraints.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001526 RTC_LOG(LS_ERROR) << error;
deadbeefab9b2d12015-10-14 11:33:11 -07001527 PostCreateSessionDescriptionFailure(observer, error);
1528 return;
1529 }
1530
Steve Anton8d3444d2017-10-20 15:30:51 -07001531 CreateAnswer(observer, offer_answer_options);
htaa2a49d92016-03-04 02:51:39 -08001532}
1533
1534void PeerConnection::CreateAnswer(CreateSessionDescriptionObserver* observer,
1535 const RTCOfferAnswerOptions& options) {
1536 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
nisse7ce109a2017-01-31 00:57:56 -08001537 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001538 RTC_LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
htaa2a49d92016-03-04 02:51:39 -08001539 return;
1540 }
1541
Steve Anton8d3444d2017-10-20 15:30:51 -07001542 if (IsClosed()) {
1543 std::string error = "CreateAnswer called when PeerConnection is closed.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001544 RTC_LOG(LS_ERROR) << error;
Steve Anton8d3444d2017-10-20 15:30:51 -07001545 PostCreateSessionDescriptionFailure(observer, error);
1546 return;
1547 }
1548
Steve Anton75737c02017-11-06 10:37:17 -08001549 if (remote_description() &&
Steve Antona3a92c22017-12-07 10:27:41 -08001550 remote_description()->GetType() != SdpType::kOffer) {
Steve Anton8d3444d2017-10-20 15:30:51 -07001551 std::string error = "CreateAnswer called without remote offer.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001552 RTC_LOG(LS_ERROR) << error;
Steve Anton8d3444d2017-10-20 15:30:51 -07001553 PostCreateSessionDescriptionFailure(observer, error);
1554 return;
1555 }
1556
htaa2a49d92016-03-04 02:51:39 -08001557 cricket::MediaSessionOptions session_options;
zhihuang1c378ed2017-08-17 14:10:50 -07001558 GetOptionsForAnswer(options, &session_options);
htaa2a49d92016-03-04 02:51:39 -08001559
Steve Antond25da372017-11-06 14:50:29 -08001560 webrtc_session_desc_factory_->CreateAnswer(observer, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001561}
1562
1563void PeerConnection::SetLocalDescription(
1564 SetSessionDescriptionObserver* observer,
1565 SessionDescriptionInterface* desc) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001566 TRACE_EVENT0("webrtc", "PeerConnection::SetLocalDescription");
Steve Anton8a006912017-12-04 15:25:56 -08001567
nisse7ce109a2017-01-31 00:57:56 -08001568 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001569 RTC_LOG(LS_ERROR) << "SetLocalDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001570 return;
1571 }
Steve Anton8a006912017-12-04 15:25:56 -08001572
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001573 if (!desc) {
1574 PostSetSessionDescriptionFailure(observer, "SessionDescription is NULL.");
1575 return;
1576 }
Steve Anton8d3444d2017-10-20 15:30:51 -07001577
Steve Antona3a92c22017-12-07 10:27:41 -08001578 SdpType type = desc->GetType();
Steve Anton8d3444d2017-10-20 15:30:51 -07001579
Steve Anton8a006912017-12-04 15:25:56 -08001580 RTCError error = ApplyLocalDescription(rtc::WrapUnique(desc));
1581 // |desc| may be destroyed at this point.
1582
1583 if (!error.ok()) {
Steve Antona3a92c22017-12-07 10:27:41 -08001584 std::ostringstream oss;
1585 oss << "Failed to set local " << SdpTypeToString(type)
1586 << " sdp: " << error.message();
1587 std::string error_message = oss.str();
Steve Anton8a006912017-12-04 15:25:56 -08001588 RTC_LOG(LS_ERROR) << error_message << " (" << error.type() << ")";
1589 PostSetSessionDescriptionFailure(observer, std::move(error_message));
Steve Anton8d3444d2017-10-20 15:30:51 -07001590 return;
1591 }
Steve Anton8a006912017-12-04 15:25:56 -08001592 RTC_DCHECK(local_description());
1593
1594 PostSetSessionDescriptionSuccess(observer);
1595
1596 // According to JSEP, after setLocalDescription, changing the candidate pool
1597 // size is not allowed, and changing the set of ICE servers will not result
1598 // in new candidates being gathered.
1599 port_allocator_->FreezeCandidatePool();
1600
1601 // MaybeStartGathering needs to be called after posting
1602 // MSG_SET_SESSIONDESCRIPTION_SUCCESS, so that we don't signal any candidates
1603 // before signaling that SetLocalDescription completed.
1604 transport_controller_->MaybeStartGathering();
1605
Steve Antona3a92c22017-12-07 10:27:41 -08001606 if (local_description()->GetType() == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08001607 // TODO(deadbeef): We already had to hop to the network thread for
1608 // MaybeStartGathering...
1609 network_thread()->Invoke<void>(
1610 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
1611 port_allocator_.get()));
1612 }
1613}
1614
1615RTCError PeerConnection::ApplyLocalDescription(
1616 std::unique_ptr<SessionDescriptionInterface> desc) {
1617 RTC_DCHECK_RUN_ON(signaling_thread());
1618 RTC_DCHECK(desc);
1619
1620 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_LOCAL);
1621 if (!error.ok()) {
1622 return error;
1623 }
Steve Anton8d3444d2017-10-20 15:30:51 -07001624
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001625 // Update stats here so that we have the most recent stats for tracks and
1626 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001627 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 15:25:56 -08001628
1629 // Update the initial_offerer flag if this session is the initial_offerer.
Steve Anton3828c062017-12-06 10:34:51 -08001630 SdpType type = desc->GetType();
Steve Anton8a006912017-12-04 15:25:56 -08001631 if (!initial_offerer_.has_value()) {
Steve Anton3828c062017-12-06 10:34:51 -08001632 initial_offerer_.emplace(type == SdpType::kOffer);
Steve Anton8a006912017-12-04 15:25:56 -08001633 if (*initial_offerer_) {
1634 transport_controller_->SetIceRole(cricket::ICEROLE_CONTROLLING);
1635 } else {
1636 transport_controller_->SetIceRole(cricket::ICEROLE_CONTROLLED);
1637 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001638 }
Steve Anton8a006912017-12-04 15:25:56 -08001639
Steve Anton3828c062017-12-06 10:34:51 -08001640 if (type == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08001641 current_local_description_ = std::move(desc);
1642 pending_local_description_ = nullptr;
1643 current_remote_description_ = std::move(pending_remote_description_);
1644 } else {
1645 pending_local_description_ = std::move(desc);
1646 }
1647 // The session description to apply now must be accessed by
1648 // |local_description()|.
Henrik Boströmfdb92012017-11-09 19:55:44 +01001649 RTC_DCHECK(local_description());
deadbeefab9b2d12015-10-14 11:33:11 -07001650
Steve Anton8a006912017-12-04 15:25:56 -08001651 // Transport and Media channels will be created only when offer is set.
Steve Anton3828c062017-12-06 10:34:51 -08001652 if (type == SdpType::kOffer) {
Steve Anton8a006912017-12-04 15:25:56 -08001653 // TODO(mallinath) - Handle CreateChannel failure, as new local description
1654 // is applied. Restore back to old description.
1655 RTCError error = CreateChannels(local_description()->description());
1656 if (!error.ok()) {
1657 return error;
1658 }
1659 }
1660
1661 // Remove unused channels if MediaContentDescription is rejected.
1662 RemoveUnusedChannels(local_description()->description());
1663
Steve Anton3828c062017-12-06 10:34:51 -08001664 error = UpdateSessionState(type, cricket::CS_LOCAL);
Steve Anton8a006912017-12-04 15:25:56 -08001665 if (!error.ok()) {
1666 return error;
1667 }
1668 if (remote_description()) {
1669 // Now that we have a local description, we can push down remote candidates.
1670 UseCandidatesInSessionDescription(remote_description());
1671 }
1672
1673 pending_ice_restarts_.clear();
1674 if (session_error() != SessionError::kNone) {
1675 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
1676 }
1677
deadbeefab9b2d12015-10-14 11:33:11 -07001678 // If setting the description decided our SSL role, allocate any necessary
1679 // SCTP sids.
1680 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08001681 if (data_channel_type() == cricket::DCT_SCTP && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001682 AllocateSctpSids(role);
1683 }
1684
1685 // Update state and SSRC of local MediaStreams and DataChannels based on the
1686 // local session description.
1687 const cricket::ContentInfo* audio_content =
Henrik Boströmfdb92012017-11-09 19:55:44 +01001688 GetFirstAudioContent(local_description()->description());
deadbeefab9b2d12015-10-14 11:33:11 -07001689 if (audio_content) {
deadbeeffaac4972015-11-12 15:33:07 -08001690 if (audio_content->rejected) {
Steve Anton4171afb2017-11-20 10:20:22 -08001691 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
deadbeeffaac4972015-11-12 15:33:07 -08001692 } else {
1693 const cricket::AudioContentDescription* audio_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08001694 audio_content->media_description()->as_audio();
Steve Anton4171afb2017-11-20 10:20:22 -08001695 UpdateLocalSenders(audio_desc->streams(), audio_desc->type());
deadbeeffaac4972015-11-12 15:33:07 -08001696 }
deadbeefab9b2d12015-10-14 11:33:11 -07001697 }
1698
1699 const cricket::ContentInfo* video_content =
Henrik Boströmfdb92012017-11-09 19:55:44 +01001700 GetFirstVideoContent(local_description()->description());
deadbeefab9b2d12015-10-14 11:33:11 -07001701 if (video_content) {
deadbeeffaac4972015-11-12 15:33:07 -08001702 if (video_content->rejected) {
Steve Anton4171afb2017-11-20 10:20:22 -08001703 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
deadbeeffaac4972015-11-12 15:33:07 -08001704 } else {
1705 const cricket::VideoContentDescription* video_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08001706 video_content->media_description()->as_video();
Steve Anton4171afb2017-11-20 10:20:22 -08001707 UpdateLocalSenders(video_desc->streams(), video_desc->type());
deadbeeffaac4972015-11-12 15:33:07 -08001708 }
deadbeefab9b2d12015-10-14 11:33:11 -07001709 }
1710
1711 const cricket::ContentInfo* data_content =
Henrik Boströmfdb92012017-11-09 19:55:44 +01001712 GetFirstDataContent(local_description()->description());
deadbeefab9b2d12015-10-14 11:33:11 -07001713 if (data_content) {
1714 const cricket::DataContentDescription* data_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08001715 data_content->media_description()->as_data();
deadbeefab9b2d12015-10-14 11:33:11 -07001716 if (rtc::starts_with(data_desc->protocol().data(),
1717 cricket::kMediaProtocolRtpPrefix)) {
1718 UpdateLocalRtpDataChannels(data_desc->streams());
1719 }
1720 }
1721
Steve Anton8a006912017-12-04 15:25:56 -08001722 return RTCError::OK();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001723}
1724
1725void PeerConnection::SetRemoteDescription(
Henrik Boströma4ecf552017-11-23 14:17:07 +00001726 SetSessionDescriptionObserver* observer,
1727 SessionDescriptionInterface* desc) {
Henrik Boström31638672017-11-23 17:48:32 +01001728 SetRemoteDescription(
1729 std::unique_ptr<SessionDescriptionInterface>(desc),
1730 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface>(
1731 new SetRemoteDescriptionObserverAdapter(this, observer)));
1732}
1733
1734void PeerConnection::SetRemoteDescription(
1735 std::unique_ptr<SessionDescriptionInterface> desc,
1736 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface> observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001737 TRACE_EVENT0("webrtc", "PeerConnection::SetRemoteDescription");
Steve Anton8a006912017-12-04 15:25:56 -08001738
nisse7ce109a2017-01-31 00:57:56 -08001739 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001740 RTC_LOG(LS_ERROR) << "SetRemoteDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001741 return;
1742 }
Steve Anton8a006912017-12-04 15:25:56 -08001743
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001744 if (!desc) {
Henrik Boström31638672017-11-23 17:48:32 +01001745 observer->OnSetRemoteDescriptionComplete(RTCError(
Steve Anton8a006912017-12-04 15:25:56 -08001746 RTCErrorType::INVALID_PARAMETER, "SessionDescription is NULL."));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001747 return;
1748 }
Steve Anton8d3444d2017-10-20 15:30:51 -07001749
Steve Antona3a92c22017-12-07 10:27:41 -08001750 const SdpType type = desc->GetType();
Steve Anton8a006912017-12-04 15:25:56 -08001751
1752 RTCError error = ApplyRemoteDescription(std::move(desc));
1753 // |desc| may be destroyed at this point.
1754
1755 if (!error.ok()) {
Steve Antona3a92c22017-12-07 10:27:41 -08001756 std::ostringstream oss;
1757 oss << "Failed to set remote " << SdpTypeToString(type)
1758 << " sdp: " << error.message();
1759 std::string error_message = oss.str();
Steve Anton8a006912017-12-04 15:25:56 -08001760 RTC_LOG(LS_ERROR) << error_message << " (" << error.type() << ")";
Henrik Boström31638672017-11-23 17:48:32 +01001761 observer->OnSetRemoteDescriptionComplete(
Steve Anton8a006912017-12-04 15:25:56 -08001762 RTCError(error.type(), std::move(error_message)));
Steve Anton8d3444d2017-10-20 15:30:51 -07001763 return;
1764 }
1765
Steve Antona3a92c22017-12-07 10:27:41 -08001766 if (remote_description()->GetType() == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08001767 // TODO(deadbeef): We already had to hop to the network thread for
1768 // MaybeStartGathering...
1769 network_thread()->Invoke<void>(
1770 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
1771 port_allocator_.get()));
1772 }
1773
1774 observer->OnSetRemoteDescriptionComplete(RTCError::OK());
1775}
1776
1777RTCError PeerConnection::ApplyRemoteDescription(
1778 std::unique_ptr<SessionDescriptionInterface> desc) {
1779 RTC_DCHECK_RUN_ON(signaling_thread());
1780 RTC_DCHECK(desc);
1781
1782 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_REMOTE);
1783 if (!error.ok()) {
1784 return error;
1785 }
1786
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001787 // Update stats here so that we have the most recent stats for tracks and
1788 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001789 stats_->UpdateStats(kStatsOutputLevelStandard);
Henrik Boström31638672017-11-23 17:48:32 +01001790 // Takes the ownership of |desc|. On success, remote_description() is updated
1791 // to reflect the description that was passed in.
Steve Anton8a006912017-12-04 15:25:56 -08001792
1793 const SessionDescriptionInterface* old_remote_description =
1794 remote_description();
1795 // Grab ownership of the description being replaced for the remainder of this
1796 // method, since it's used below as |old_remote_description|.
1797 std::unique_ptr<SessionDescriptionInterface> replaced_remote_description;
Steve Anton3828c062017-12-06 10:34:51 -08001798 SdpType type = desc->GetType();
1799 if (type == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08001800 replaced_remote_description = pending_remote_description_
1801 ? std::move(pending_remote_description_)
1802 : std::move(current_remote_description_);
1803 current_remote_description_ = std::move(desc);
1804 pending_remote_description_ = nullptr;
1805 current_local_description_ = std::move(pending_local_description_);
1806 } else {
1807 replaced_remote_description = std::move(pending_remote_description_);
1808 pending_remote_description_ = std::move(desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001809 }
Steve Anton8a006912017-12-04 15:25:56 -08001810 // The session description to apply now must be accessed by
1811 // |remote_description()|.
Henrik Boströmfdb92012017-11-09 19:55:44 +01001812 RTC_DCHECK(remote_description());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001813
Steve Anton8a006912017-12-04 15:25:56 -08001814 // Transport and Media channels will be created only when offer is set.
Steve Anton3828c062017-12-06 10:34:51 -08001815 if (type == SdpType::kOffer) {
Steve Anton8a006912017-12-04 15:25:56 -08001816 // TODO(mallinath) - Handle CreateChannel failure, as new local description
1817 // is applied. Restore back to old description.
1818 RTCError error = CreateChannels(remote_description()->description());
1819 if (!error.ok()) {
1820 return error;
1821 }
1822 }
1823
1824 // Remove unused channels if MediaContentDescription is rejected.
1825 RemoveUnusedChannels(remote_description()->description());
1826
1827 // NOTE: Candidates allocation will be initiated only when SetLocalDescription
1828 // is called.
Steve Anton3828c062017-12-06 10:34:51 -08001829 error = UpdateSessionState(type, cricket::CS_REMOTE);
Steve Anton8a006912017-12-04 15:25:56 -08001830 if (!error.ok()) {
1831 return error;
1832 }
1833
1834 if (local_description() &&
1835 !UseCandidatesInSessionDescription(remote_description())) {
1836 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidCandidates);
1837 }
1838
1839 if (old_remote_description) {
1840 for (const cricket::ContentInfo& content :
1841 old_remote_description->description()->contents()) {
1842 // Check if this new SessionDescription contains new ICE ufrag and
1843 // password that indicates the remote peer requests an ICE restart.
1844 // TODO(deadbeef): When we start storing both the current and pending
1845 // remote description, this should reset pending_ice_restarts and compare
1846 // against the current description.
1847 if (CheckForRemoteIceRestart(old_remote_description, remote_description(),
1848 content.name)) {
Steve Anton3828c062017-12-06 10:34:51 -08001849 if (type == SdpType::kOffer) {
Steve Anton8a006912017-12-04 15:25:56 -08001850 pending_ice_restarts_.insert(content.name);
1851 }
1852 } else {
1853 // We retain all received candidates only if ICE is not restarted.
1854 // When ICE is restarted, all previous candidates belong to an old
1855 // generation and should not be kept.
1856 // TODO(deadbeef): This goes against the W3C spec which says the remote
1857 // description should only contain candidates from the last set remote
1858 // description plus any candidates added since then. We should remove
1859 // this once we're sure it won't break anything.
1860 WebRtcSessionDescriptionFactory::CopyCandidatesFromSessionDescription(
1861 old_remote_description, content.name, mutable_remote_description());
1862 }
1863 }
1864 }
1865
1866 if (session_error() != SessionError::kNone) {
1867 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
1868 }
1869
1870 // Set the the ICE connection state to connecting since the connection may
1871 // become writable with peer reflexive candidates before any remote candidate
1872 // is signaled.
1873 // TODO(pthatcher): This is a short-term solution for crbug/446908. A real fix
1874 // is to have a new signal the indicates a change in checking state from the
1875 // transport and expose a new checking() member from transport that can be
1876 // read to determine the current checking state. The existing SignalConnecting
1877 // actually means "gathering candidates", so cannot be be used here.
Steve Antona3a92c22017-12-07 10:27:41 -08001878 if (remote_description()->GetType() != SdpType::kOffer &&
Steve Anton8a006912017-12-04 15:25:56 -08001879 ice_connection_state() == PeerConnectionInterface::kIceConnectionNew) {
1880 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
1881 }
1882
deadbeefab9b2d12015-10-14 11:33:11 -07001883 // If setting the description decided our SSL role, allocate any necessary
1884 // SCTP sids.
1885 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08001886 if (data_channel_type() == cricket::DCT_SCTP && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001887 AllocateSctpSids(role);
1888 }
1889
Henrik Boströmfdb92012017-11-09 19:55:44 +01001890 const cricket::ContentInfo* audio_content =
1891 GetFirstAudioContent(remote_description()->description());
1892 const cricket::ContentInfo* video_content =
1893 GetFirstVideoContent(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08001894 const cricket::AudioContentDescription* audio_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01001895 GetFirstAudioContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08001896 const cricket::VideoContentDescription* video_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01001897 GetFirstVideoContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08001898 const cricket::DataContentDescription* data_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01001899 GetFirstDataContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08001900
1901 // Check if the descriptions include streams, just in case the peer supports
1902 // MSID, but doesn't indicate so with "a=msid-semantic".
Henrik Boströmfdb92012017-11-09 19:55:44 +01001903 if (remote_description()->description()->msid_supported() ||
deadbeefbda7e0b2015-12-08 17:13:40 -08001904 (audio_desc && !audio_desc->streams().empty()) ||
1905 (video_desc && !video_desc->streams().empty())) {
1906 remote_peer_supports_msid_ = true;
1907 }
deadbeefab9b2d12015-10-14 11:33:11 -07001908
1909 // We wait to signal new streams until we finish processing the description,
1910 // since only at that point will new streams have all their tracks.
1911 rtc::scoped_refptr<StreamCollection> new_streams(StreamCollection::Create());
1912
Steve Anton8d3444d2017-10-20 15:30:51 -07001913 // TODO(steveanton): When removing RTP senders/receivers in response to a
1914 // rejected media section, there is some cleanup logic that expects the voice/
1915 // video channel to still be set. But in this method the voice/video channel
Steve Anton75737c02017-11-06 10:37:17 -08001916 // would have been destroyed by the SetRemoteDescription caller above so the
Steve Anton4171afb2017-11-20 10:20:22 -08001917 // cleanup that relies on them fails to run. The RemoveSenders calls should be
Steve Anton75737c02017-11-06 10:37:17 -08001918 // moved to right before the DestroyChannel calls to fix this.
Steve Anton8d3444d2017-10-20 15:30:51 -07001919
deadbeefab9b2d12015-10-14 11:33:11 -07001920 // Find all audio rtp streams and create corresponding remote AudioTracks
1921 // and MediaStreams.
deadbeefab9b2d12015-10-14 11:33:11 -07001922 if (audio_content) {
deadbeeffaac4972015-11-12 15:33:07 -08001923 if (audio_content->rejected) {
Steve Anton4171afb2017-11-20 10:20:22 -08001924 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
deadbeeffaac4972015-11-12 15:33:07 -08001925 } else {
deadbeefbda7e0b2015-12-08 17:13:40 -08001926 bool default_audio_track_needed =
1927 !remote_peer_supports_msid_ &&
Steve Anton4e70a722017-11-28 14:57:10 -08001928 RtpTransceiverDirectionHasSend(audio_desc->direction());
Steve Anton4171afb2017-11-20 10:20:22 -08001929 UpdateRemoteSendersList(GetActiveStreams(audio_desc),
deadbeefbda7e0b2015-12-08 17:13:40 -08001930 default_audio_track_needed, audio_desc->type(),
deadbeeffaac4972015-11-12 15:33:07 -08001931 new_streams);
deadbeeffaac4972015-11-12 15:33:07 -08001932 }
deadbeefab9b2d12015-10-14 11:33:11 -07001933 }
1934
1935 // Find all video rtp streams and create corresponding remote VideoTracks
1936 // and MediaStreams.
deadbeefab9b2d12015-10-14 11:33:11 -07001937 if (video_content) {
deadbeeffaac4972015-11-12 15:33:07 -08001938 if (video_content->rejected) {
Steve Anton4171afb2017-11-20 10:20:22 -08001939 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
deadbeeffaac4972015-11-12 15:33:07 -08001940 } else {
deadbeefbda7e0b2015-12-08 17:13:40 -08001941 bool default_video_track_needed =
1942 !remote_peer_supports_msid_ &&
Steve Anton4e70a722017-11-28 14:57:10 -08001943 RtpTransceiverDirectionHasSend(video_desc->direction());
Steve Anton4171afb2017-11-20 10:20:22 -08001944 UpdateRemoteSendersList(GetActiveStreams(video_desc),
deadbeefbda7e0b2015-12-08 17:13:40 -08001945 default_video_track_needed, video_desc->type(),
deadbeeffaac4972015-11-12 15:33:07 -08001946 new_streams);
deadbeeffaac4972015-11-12 15:33:07 -08001947 }
deadbeefab9b2d12015-10-14 11:33:11 -07001948 }
1949
1950 // Update the DataChannels with the information from the remote peer.
deadbeefbda7e0b2015-12-08 17:13:40 -08001951 if (data_desc) {
1952 if (rtc::starts_with(data_desc->protocol().data(),
deadbeefab9b2d12015-10-14 11:33:11 -07001953 cricket::kMediaProtocolRtpPrefix)) {
deadbeefbda7e0b2015-12-08 17:13:40 -08001954 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
deadbeefab9b2d12015-10-14 11:33:11 -07001955 }
1956 }
1957
1958 // Iterate new_streams and notify the observer about new MediaStreams.
1959 for (size_t i = 0; i < new_streams->count(); ++i) {
1960 MediaStreamInterface* new_stream = new_streams->at(i);
1961 stats_->AddStream(new_stream);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07001962 observer_->OnAddStream(
1963 rtc::scoped_refptr<MediaStreamInterface>(new_stream));
deadbeefab9b2d12015-10-14 11:33:11 -07001964 }
1965
deadbeefbda7e0b2015-12-08 17:13:40 -08001966 UpdateEndedRemoteMediaStreams();
deadbeefab9b2d12015-10-14 11:33:11 -07001967
Steve Anton8a006912017-12-04 15:25:56 -08001968 return RTCError::OK();
deadbeeffc648b62015-10-13 16:42:33 -07001969}
1970
Steve Antoned10bd92017-12-05 10:52:59 -08001971const cricket::ContentInfo* PeerConnection::FindMediaSectionForTransceiver(
1972 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1973 transceiver,
1974 const SessionDescriptionInterface* sdesc) const {
1975 RTC_DCHECK(transceiver);
1976 RTC_DCHECK(sdesc);
1977 if (IsUnifiedPlan()) {
1978 if (!transceiver->internal()->mid()) {
1979 // This transceiver is not associated with a media section yet.
1980 return nullptr;
1981 }
1982 return sdesc->description()->GetContentByName(
1983 *transceiver->internal()->mid());
1984 } else {
1985 // Plan B only allows at most one audio and one video section, so use the
1986 // first media section of that type.
1987 return cricket::GetFirstMediaContent(sdesc->description()->contents(),
1988 transceiver->internal()->media_type());
1989 }
1990}
1991
deadbeef46c73892016-11-16 19:42:04 -08001992PeerConnectionInterface::RTCConfiguration PeerConnection::GetConfiguration() {
1993 return configuration_;
1994}
1995
deadbeef293e9262017-01-11 12:28:30 -08001996bool PeerConnection::SetConfiguration(const RTCConfiguration& configuration,
1997 RTCError* error) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001998 TRACE_EVENT0("webrtc", "PeerConnection::SetConfiguration");
deadbeef6de92f92016-12-12 18:49:32 -08001999
Steve Anton75737c02017-11-06 10:37:17 -08002000 if (local_description() && configuration.ice_candidate_pool_size !=
2001 configuration_.ice_candidate_pool_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002002 RTC_LOG(LS_ERROR) << "Can't change candidate pool size after calling "
2003 "SetLocalDescription.";
deadbeef293e9262017-01-11 12:28:30 -08002004 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00002005 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002006
deadbeef293e9262017-01-11 12:28:30 -08002007 // The simplest (and most future-compatible) way to tell if the config was
2008 // modified in an invalid way is to copy each property we do support
2009 // modifying, then use operator==. There are far more properties we don't
2010 // support modifying than those we do, and more could be added.
2011 RTCConfiguration modified_config = configuration_;
2012 modified_config.servers = configuration.servers;
2013 modified_config.type = configuration.type;
2014 modified_config.ice_candidate_pool_size =
2015 configuration.ice_candidate_pool_size;
2016 modified_config.prune_turn_ports = configuration.prune_turn_ports;
skvladd1f5fda2017-02-03 16:54:05 -08002017 modified_config.ice_check_min_interval = configuration.ice_check_min_interval;
Jonas Orelandbdcee282017-10-10 14:01:40 +02002018 modified_config.turn_customizer = configuration.turn_customizer;
deadbeef293e9262017-01-11 12:28:30 -08002019 if (configuration != modified_config) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002020 RTC_LOG(LS_ERROR) << "Modifying the configuration in an unsupported way.";
deadbeef293e9262017-01-11 12:28:30 -08002021 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
2022 }
2023
Steve Anton038834f2017-07-14 15:59:59 -07002024 // Validate the modified configuration.
2025 RTCError validate_error = ValidateConfiguration(modified_config);
2026 if (!validate_error.ok()) {
2027 return SafeSetError(std::move(validate_error), error);
2028 }
2029
deadbeef293e9262017-01-11 12:28:30 -08002030 // Note that this isn't possible through chromium, since it's an unsigned
2031 // short in WebIDL.
2032 if (configuration.ice_candidate_pool_size < 0 ||
2033 configuration.ice_candidate_pool_size > UINT16_MAX) {
2034 return SafeSetError(RTCErrorType::INVALID_RANGE, error);
2035 }
2036
2037 // Parse ICE servers before hopping to network thread.
2038 cricket::ServerAddresses stun_servers;
2039 std::vector<cricket::RelayServerConfig> turn_servers;
2040 RTCErrorType parse_error =
2041 ParseIceServers(configuration.servers, &stun_servers, &turn_servers);
2042 if (parse_error != RTCErrorType::NONE) {
2043 return SafeSetError(parse_error, error);
2044 }
2045
2046 // In theory this shouldn't fail.
2047 if (!network_thread()->Invoke<bool>(
2048 RTC_FROM_HERE,
2049 rtc::Bind(&PeerConnection::ReconfigurePortAllocator_n, this,
2050 stun_servers, turn_servers, modified_config.type,
2051 modified_config.ice_candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02002052 modified_config.prune_turn_ports,
2053 modified_config.turn_customizer))) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002054 RTC_LOG(LS_ERROR) << "Failed to apply configuration to PortAllocator.";
deadbeef293e9262017-01-11 12:28:30 -08002055 return SafeSetError(RTCErrorType::INTERNAL_ERROR, error);
2056 }
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07002057
deadbeefd1a38b52016-12-10 13:15:33 -08002058 // As described in JSEP, calling setConfiguration with new ICE servers or
2059 // candidate policy must set a "needs-ice-restart" bit so that the next offer
2060 // triggers an ICE restart which will pick up the changes.
deadbeef293e9262017-01-11 12:28:30 -08002061 if (modified_config.servers != configuration_.servers ||
2062 modified_config.type != configuration_.type ||
2063 modified_config.prune_turn_ports != configuration_.prune_turn_ports) {
Steve Antond25da372017-11-06 14:50:29 -08002064 transport_controller_->SetNeedsIceRestartFlag();
deadbeefd1a38b52016-12-10 13:15:33 -08002065 }
skvladd1f5fda2017-02-03 16:54:05 -08002066
2067 if (modified_config.ice_check_min_interval !=
2068 configuration_.ice_check_min_interval) {
Steve Antond25da372017-11-06 14:50:29 -08002069 transport_controller_->SetIceConfig(ParseIceConfig(modified_config));
skvladd1f5fda2017-02-03 16:54:05 -08002070 }
2071
deadbeef293e9262017-01-11 12:28:30 -08002072 configuration_ = modified_config;
2073 return SafeSetError(RTCErrorType::NONE, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00002074}
2075
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002076bool PeerConnection::AddIceCandidate(
2077 const IceCandidateInterface* ice_candidate) {
Peter Boström1a9d6152015-12-08 22:15:17 +01002078 TRACE_EVENT0("webrtc", "PeerConnection::AddIceCandidate");
zhihuang29ff8442016-07-27 11:07:25 -07002079 if (IsClosed()) {
2080 return false;
2081 }
Steve Antond25da372017-11-06 14:50:29 -08002082
2083 if (!remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002084 RTC_LOG(LS_ERROR) << "ProcessIceMessage: ICE candidates can't be added "
2085 << "without any remote session description.";
Steve Antond25da372017-11-06 14:50:29 -08002086 return false;
2087 }
2088
2089 if (!ice_candidate) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002090 RTC_LOG(LS_ERROR) << "ProcessIceMessage: Candidate is NULL.";
Steve Antond25da372017-11-06 14:50:29 -08002091 return false;
2092 }
2093
2094 bool valid = false;
2095 bool ready = ReadyToUseRemoteCandidate(ice_candidate, nullptr, &valid);
2096 if (!valid) {
2097 return false;
2098 }
2099
2100 // Add this candidate to the remote session description.
2101 if (!mutable_remote_description()->AddCandidate(ice_candidate)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002102 RTC_LOG(LS_ERROR) << "ProcessIceMessage: Candidate cannot be used.";
Steve Antond25da372017-11-06 14:50:29 -08002103 return false;
2104 }
2105
2106 if (ready) {
2107 return UseCandidate(ice_candidate);
2108 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002109 RTC_LOG(LS_INFO) << "ProcessIceMessage: Not ready to use candidate.";
Steve Antond25da372017-11-06 14:50:29 -08002110 return true;
2111 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002112}
2113
Honghai Zhang7fb69db2016-03-14 11:59:18 -07002114bool PeerConnection::RemoveIceCandidates(
2115 const std::vector<cricket::Candidate>& candidates) {
2116 TRACE_EVENT0("webrtc", "PeerConnection::RemoveIceCandidates");
Steve Antond25da372017-11-06 14:50:29 -08002117 if (!remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002118 RTC_LOG(LS_ERROR) << "RemoveRemoteIceCandidates: ICE candidates can't be "
2119 << "removed without any remote session description.";
Steve Antond25da372017-11-06 14:50:29 -08002120 return false;
2121 }
2122
2123 if (candidates.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002124 RTC_LOG(LS_ERROR) << "RemoveRemoteIceCandidates: candidates are empty.";
Steve Antond25da372017-11-06 14:50:29 -08002125 return false;
2126 }
2127
2128 size_t number_removed =
2129 mutable_remote_description()->RemoveCandidates(candidates);
2130 if (number_removed != candidates.size()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002131 RTC_LOG(LS_ERROR)
2132 << "RemoveRemoteIceCandidates: Failed to remove candidates. "
2133 << "Requested " << candidates.size() << " but only " << number_removed
2134 << " are removed.";
Steve Antond25da372017-11-06 14:50:29 -08002135 }
2136
2137 // Remove the candidates from the transport controller.
2138 std::string error;
2139 bool res = transport_controller_->RemoveRemoteCandidates(candidates, &error);
2140 if (!res && !error.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002141 RTC_LOG(LS_ERROR) << "Error when removing remote candidates: " << error;
Steve Antond25da372017-11-06 14:50:29 -08002142 }
2143 return true;
Honghai Zhang7fb69db2016-03-14 11:59:18 -07002144}
2145
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00002146void PeerConnection::RegisterUMAObserver(UMAObserver* observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +01002147 TRACE_EVENT0("webrtc", "PeerConnection::RegisterUmaObserver");
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00002148 uma_observer_ = observer;
guoweis@webrtc.org7169afd2014-12-04 17:59:29 +00002149
Steve Anton75737c02017-11-06 10:37:17 -08002150 if (transport_controller()) {
2151 transport_controller()->SetMetricsObserver(uma_observer_);
guoweis@webrtc.org7169afd2014-12-04 17:59:29 +00002152 }
2153
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00002154 // Send information about IPv4/IPv6 status.
deadbeef293e9262017-01-11 12:28:30 -08002155 if (uma_observer_) {
Honghai Zhangd93f50c2016-10-05 11:47:22 -07002156 port_allocator_->SetMetricsObserver(uma_observer_);
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00002157 if (port_allocator_->flags() & cricket::PORTALLOCATOR_ENABLE_IPV6) {
Guo-wei Shiehdfbe6792015-09-03 17:12:07 -07002158 uma_observer_->IncrementEnumCounter(
2159 kEnumCounterAddressFamily, kPeerConnection_IPv6,
2160 kPeerConnectionAddressFamilyCounter_Max);
mallinath@webrtc.orgb445f262014-05-23 22:19:37 +00002161 } else {
Guo-wei Shiehdfbe6792015-09-03 17:12:07 -07002162 uma_observer_->IncrementEnumCounter(
2163 kEnumCounterAddressFamily, kPeerConnection_IPv4,
2164 kPeerConnectionAddressFamilyCounter_Max);
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00002165 }
2166 }
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00002167}
2168
zstein4b979802017-06-02 14:37:37 -07002169RTCError PeerConnection::SetBitrate(const BitrateParameters& bitrate) {
Steve Anton978b8762017-09-29 12:15:02 -07002170 if (!worker_thread()->IsCurrent()) {
2171 return worker_thread()->Invoke<RTCError>(
zstein4b979802017-06-02 14:37:37 -07002172 RTC_FROM_HERE, rtc::Bind(&PeerConnection::SetBitrate, this, bitrate));
2173 }
2174
2175 const bool has_min = static_cast<bool>(bitrate.min_bitrate_bps);
2176 const bool has_current = static_cast<bool>(bitrate.current_bitrate_bps);
2177 const bool has_max = static_cast<bool>(bitrate.max_bitrate_bps);
2178 if (has_min && *bitrate.min_bitrate_bps < 0) {
2179 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2180 "min_bitrate_bps <= 0");
2181 }
2182 if (has_current) {
2183 if (has_min && *bitrate.current_bitrate_bps < *bitrate.min_bitrate_bps) {
2184 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2185 "current_bitrate_bps < min_bitrate_bps");
2186 } else if (*bitrate.current_bitrate_bps < 0) {
2187 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2188 "curent_bitrate_bps < 0");
2189 }
2190 }
2191 if (has_max) {
2192 if (has_current &&
2193 *bitrate.max_bitrate_bps < *bitrate.current_bitrate_bps) {
2194 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2195 "max_bitrate_bps < current_bitrate_bps");
2196 } else if (has_min && *bitrate.max_bitrate_bps < *bitrate.min_bitrate_bps) {
2197 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2198 "max_bitrate_bps < min_bitrate_bps");
2199 } else if (*bitrate.max_bitrate_bps < 0) {
2200 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2201 "max_bitrate_bps < 0");
2202 }
2203 }
2204
2205 Call::Config::BitrateConfigMask mask;
2206 mask.min_bitrate_bps = bitrate.min_bitrate_bps;
2207 mask.start_bitrate_bps = bitrate.current_bitrate_bps;
2208 mask.max_bitrate_bps = bitrate.max_bitrate_bps;
2209
2210 RTC_DCHECK(call_.get());
2211 call_->SetBitrateConfigMask(mask);
2212
2213 return RTCError::OK();
2214}
2215
Alex Narest78609d52017-10-20 10:37:47 +02002216void PeerConnection::SetBitrateAllocationStrategy(
2217 std::unique_ptr<rtc::BitrateAllocationStrategy>
2218 bitrate_allocation_strategy) {
2219 rtc::Thread* worker_thread = factory_->worker_thread();
2220 if (!worker_thread->IsCurrent()) {
2221 rtc::BitrateAllocationStrategy* strategy_raw =
2222 bitrate_allocation_strategy.release();
2223 auto functor = [this, strategy_raw]() {
2224 call_->SetBitrateAllocationStrategy(
2225 rtc::WrapUnique<rtc::BitrateAllocationStrategy>(strategy_raw));
2226 };
2227 worker_thread->Invoke<void>(RTC_FROM_HERE, functor);
2228 return;
2229 }
2230 RTC_DCHECK(call_.get());
2231 call_->SetBitrateAllocationStrategy(std::move(bitrate_allocation_strategy));
2232}
2233
henrika5f6bf242017-11-01 11:06:56 +01002234void PeerConnection::SetAudioPlayout(bool playout) {
2235 if (!worker_thread()->IsCurrent()) {
2236 worker_thread()->Invoke<void>(
2237 RTC_FROM_HERE,
2238 rtc::Bind(&PeerConnection::SetAudioPlayout, this, playout));
2239 return;
2240 }
2241 auto audio_state =
2242 factory_->channel_manager()->media_engine()->GetAudioState();
2243 audio_state->SetPlayout(playout);
2244}
2245
2246void PeerConnection::SetAudioRecording(bool recording) {
2247 if (!worker_thread()->IsCurrent()) {
2248 worker_thread()->Invoke<void>(
2249 RTC_FROM_HERE,
2250 rtc::Bind(&PeerConnection::SetAudioRecording, this, recording));
2251 return;
2252 }
2253 auto audio_state =
2254 factory_->channel_manager()->media_engine()->GetAudioState();
2255 audio_state->SetRecording(recording);
2256}
2257
Steve Anton8c0f7a72017-10-03 10:03:10 -07002258std::unique_ptr<rtc::SSLCertificate>
2259PeerConnection::GetRemoteAudioSSLCertificate() {
Steve Anton75737c02017-11-06 10:37:17 -08002260 if (!voice_channel()) {
Steve Anton8c0f7a72017-10-03 10:03:10 -07002261 return nullptr;
2262 }
Steve Anton75737c02017-11-06 10:37:17 -08002263 return GetRemoteSSLCertificate(voice_channel()->transport_name());
Steve Anton8c0f7a72017-10-03 10:03:10 -07002264}
2265
ivoc14d5dbe2016-07-04 07:06:55 -07002266bool PeerConnection::StartRtcEventLog(rtc::PlatformFile file,
2267 int64_t max_size_bytes) {
Elad Alon99c3fe52017-10-13 16:29:40 +02002268 // TODO(eladalon): It would be better to not allow negative values into PC.
2269 const size_t max_size = (max_size_bytes < 0)
2270 ? RtcEventLog::kUnlimitedOutput
2271 : rtc::saturated_cast<size_t>(max_size_bytes);
2272 return StartRtcEventLog(
Bjorn Tereliusde939432017-11-20 17:38:14 +01002273 rtc::MakeUnique<RtcEventLogOutputFile>(file, max_size),
2274 webrtc::RtcEventLog::kImmediateOutput);
Elad Alon99c3fe52017-10-13 16:29:40 +02002275}
2276
Bjorn Tereliusde939432017-11-20 17:38:14 +01002277bool PeerConnection::StartRtcEventLog(std::unique_ptr<RtcEventLogOutput> output,
2278 int64_t output_period_ms) {
Karl Wibergd6b48192017-10-16 23:01:06 +02002279 // TODO(eladalon): In C++14, this can be done with a lambda.
2280 struct Functor {
Bjorn Tereliusde939432017-11-20 17:38:14 +01002281 bool operator()() {
2282 return pc->StartRtcEventLog_w(std::move(output), output_period_ms);
2283 }
Karl Wibergd6b48192017-10-16 23:01:06 +02002284 PeerConnection* const pc;
2285 std::unique_ptr<RtcEventLogOutput> output;
Bjorn Tereliusde939432017-11-20 17:38:14 +01002286 const int64_t output_period_ms;
Elad Alon99c3fe52017-10-13 16:29:40 +02002287 };
Bjorn Tereliusde939432017-11-20 17:38:14 +01002288 return worker_thread()->Invoke<bool>(
2289 RTC_FROM_HERE, Functor{this, std::move(output), output_period_ms});
ivoc14d5dbe2016-07-04 07:06:55 -07002290}
2291
2292void PeerConnection::StopRtcEventLog() {
Steve Anton978b8762017-09-29 12:15:02 -07002293 worker_thread()->Invoke<void>(
ivoc14d5dbe2016-07-04 07:06:55 -07002294 RTC_FROM_HERE, rtc::Bind(&PeerConnection::StopRtcEventLog_w, this));
2295}
2296
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002297const SessionDescriptionInterface* PeerConnection::local_description() const {
Steve Anton75737c02017-11-06 10:37:17 -08002298 return pending_local_description_ ? pending_local_description_.get()
2299 : current_local_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002300}
2301
2302const SessionDescriptionInterface* PeerConnection::remote_description() const {
Steve Anton75737c02017-11-06 10:37:17 -08002303 return pending_remote_description_ ? pending_remote_description_.get()
2304 : current_remote_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002305}
2306
deadbeeffe4a8a42016-12-20 17:56:17 -08002307const SessionDescriptionInterface* PeerConnection::current_local_description()
2308 const {
Steve Anton75737c02017-11-06 10:37:17 -08002309 return current_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08002310}
2311
2312const SessionDescriptionInterface* PeerConnection::current_remote_description()
2313 const {
Steve Anton75737c02017-11-06 10:37:17 -08002314 return current_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08002315}
2316
2317const SessionDescriptionInterface* PeerConnection::pending_local_description()
2318 const {
Steve Anton75737c02017-11-06 10:37:17 -08002319 return pending_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08002320}
2321
2322const SessionDescriptionInterface* PeerConnection::pending_remote_description()
2323 const {
Steve Anton75737c02017-11-06 10:37:17 -08002324 return pending_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08002325}
2326
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002327void PeerConnection::Close() {
Peter Boström1a9d6152015-12-08 22:15:17 +01002328 TRACE_EVENT0("webrtc", "PeerConnection::Close");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002329 // Update stats here so that we have the most recent stats for tracks and
2330 // streams before the channels are closed.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00002331 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002332
Steve Anton75737c02017-11-06 10:37:17 -08002333 ChangeSignalingState(PeerConnectionInterface::kClosed);
Steve Anton3fe1b152017-12-12 10:20:08 -08002334
Steve Anton8af21862017-12-15 11:20:13 -08002335 for (auto transceiver : transceivers_) {
2336 transceiver->Stop();
2337 }
2338 DestroyAllChannels();
Steve Anton75737c02017-11-06 10:37:17 -08002339
deadbeef42a42632017-03-10 15:18:00 -08002340 network_thread()->Invoke<void>(
2341 RTC_FROM_HERE,
2342 rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
2343 port_allocator_.get()));
nisseeaabdf62017-05-05 02:23:02 -07002344
Steve Anton978b8762017-09-29 12:15:02 -07002345 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
eladalon248fd4f2017-09-06 05:18:15 -07002346 call_.reset();
2347 // The event log must outlive call (and any other object that uses it).
2348 event_log_.reset();
2349 });
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002350}
2351
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002352void PeerConnection::OnMessage(rtc::Message* msg) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002353 switch (msg->message_id) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002354 case MSG_SET_SESSIONDESCRIPTION_SUCCESS: {
2355 SetSessionDescriptionMsg* param =
2356 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
2357 param->observer->OnSuccess();
2358 delete param;
2359 break;
2360 }
2361 case MSG_SET_SESSIONDESCRIPTION_FAILED: {
2362 SetSessionDescriptionMsg* param =
2363 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
2364 param->observer->OnFailure(param->error);
2365 delete param;
2366 break;
2367 }
deadbeefab9b2d12015-10-14 11:33:11 -07002368 case MSG_CREATE_SESSIONDESCRIPTION_FAILED: {
2369 CreateSessionDescriptionMsg* param =
2370 static_cast<CreateSessionDescriptionMsg*>(msg->pdata);
2371 param->observer->OnFailure(param->error);
2372 delete param;
2373 break;
2374 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002375 case MSG_GETSTATS: {
2376 GetStatsMsg* param = static_cast<GetStatsMsg*>(msg->pdata);
nissee8abe3e2017-01-18 05:00:34 -08002377 StatsReports reports;
2378 stats_->GetStats(param->track, &reports);
2379 param->observer->OnComplete(reports);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002380 delete param;
2381 break;
2382 }
deadbeefbd292462015-12-14 18:15:29 -08002383 case MSG_FREE_DATACHANNELS: {
2384 sctp_data_channels_to_free_.clear();
2385 break;
2386 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002387 default:
nisseeb4ca4e2017-01-12 02:24:27 -08002388 RTC_NOTREACHED() << "Not implemented";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002389 break;
2390 }
2391}
2392
Steve Anton4171afb2017-11-20 10:20:22 -08002393void PeerConnection::CreateAudioReceiver(
2394 MediaStreamInterface* stream,
2395 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01002396 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
2397 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
zhihuang81c3a032016-11-17 12:06:24 -08002398 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
2399 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
deadbeefe814a0d2017-02-25 18:15:09 -08002400 signaling_thread(),
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01002401 new AudioRtpReceiver(remote_sender_info.sender_id, streams,
Steve Anton4171afb2017-11-20 10:20:22 -08002402 remote_sender_info.first_ssrc, voice_channel()));
deadbeefe814a0d2017-02-25 18:15:09 -08002403 stream->AddTrack(
2404 static_cast<AudioTrackInterface*>(receiver->internal()->track().get()));
Steve Anton4171afb2017-11-20 10:20:22 -08002405 GetAudioTransceiver()->internal()->AddReceiver(receiver);
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01002406 observer_->OnAddTrack(receiver, std::move(streams));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002407}
2408
Steve Anton4171afb2017-11-20 10:20:22 -08002409void PeerConnection::CreateVideoReceiver(
2410 MediaStreamInterface* stream,
2411 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01002412 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
2413 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
zhihuang81c3a032016-11-17 12:06:24 -08002414 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
2415 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
Steve Anton4171afb2017-11-20 10:20:22 -08002416 signaling_thread(),
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01002417 new VideoRtpReceiver(remote_sender_info.sender_id, streams,
2418 worker_thread(), remote_sender_info.first_ssrc,
2419 video_channel()));
deadbeefe814a0d2017-02-25 18:15:09 -08002420 stream->AddTrack(
2421 static_cast<VideoTrackInterface*>(receiver->internal()->track().get()));
Steve Anton4171afb2017-11-20 10:20:22 -08002422 GetVideoTransceiver()->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
deadbeef70ab1a12015-09-28 16:53:55 -07002426// TODO(deadbeef): Keep RtpReceivers around even if track goes away in remote
2427// description.
Henrik Boström933d8b02017-10-10 10:05:16 -07002428rtc::scoped_refptr<RtpReceiverInterface> PeerConnection::RemoveAndStopReceiver(
Steve Anton4171afb2017-11-20 10:20:22 -08002429 const RtpSenderInfo& remote_sender_info) {
2430 auto receiver = FindReceiverById(remote_sender_info.sender_id);
2431 if (!receiver) {
2432 RTC_LOG(LS_WARNING) << "RtpReceiver for track with id "
2433 << remote_sender_info.sender_id << " doesn't exist.";
Henrik Boström933d8b02017-10-10 10:05:16 -07002434 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07002435 }
Steve Anton4171afb2017-11-20 10:20:22 -08002436 if (receiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
2437 GetAudioTransceiver()->internal()->RemoveReceiver(receiver);
2438 } else {
2439 GetVideoTransceiver()->internal()->RemoveReceiver(receiver);
2440 }
Henrik Boström933d8b02017-10-10 10:05:16 -07002441 return receiver;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002442}
2443
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002444void PeerConnection::AddAudioTrack(AudioTrackInterface* track,
2445 MediaStreamInterface* stream) {
2446 RTC_DCHECK(!IsClosed());
2447 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08002448 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002449 // We already have a sender for this track, so just change the stream_id
2450 // so that it's correct in the next call to CreateOffer.
Steve Anton4171afb2017-11-20 10:20:22 -08002451 sender->internal()->set_stream_id(stream->label());
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002452 return;
2453 }
2454
2455 // Normal case; we've never seen this track before.
2456 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender =
2457 RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
2458 signaling_thread(),
Steve Anton75737c02017-11-06 10:37:17 -08002459 new AudioRtpSender(track, {stream->label()}, voice_channel(),
2460 stats_.get()));
Steve Anton4171afb2017-11-20 10:20:22 -08002461 GetAudioTransceiver()->internal()->AddSender(new_sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002462 // If the sender has already been configured in SDP, we call SetSsrc,
2463 // which will connect the sender to the underlying transport. This can
2464 // occur if a local session description that contains the ID of the sender
2465 // is set before AddStream is called. It can also occur if the local
2466 // session description is not changed and RemoveStream is called, and
2467 // later AddStream is called again with the same stream.
Steve Anton4171afb2017-11-20 10:20:22 -08002468 const RtpSenderInfo* sender_info =
2469 FindSenderInfo(local_audio_sender_infos_, stream->label(), track->id());
2470 if (sender_info) {
2471 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002472 }
2473}
2474
2475// TODO(deadbeef): Don't destroy RtpSenders here; they should be kept around
2476// indefinitely, when we have unified plan SDP.
2477void PeerConnection::RemoveAudioTrack(AudioTrackInterface* track,
2478 MediaStreamInterface* stream) {
2479 RTC_DCHECK(!IsClosed());
2480 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08002481 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002482 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
2483 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002484 return;
2485 }
Steve Anton4171afb2017-11-20 10:20:22 -08002486 GetAudioTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002487}
2488
2489void PeerConnection::AddVideoTrack(VideoTrackInterface* track,
2490 MediaStreamInterface* stream) {
2491 RTC_DCHECK(!IsClosed());
2492 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08002493 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002494 // We already have a sender for this track, so just change the stream_id
2495 // so that it's correct in the next call to CreateOffer.
Steve Anton4171afb2017-11-20 10:20:22 -08002496 sender->internal()->set_stream_id(stream->label());
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002497 return;
2498 }
2499
2500 // Normal case; we've never seen this track before.
2501 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender =
2502 RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton75737c02017-11-06 10:37:17 -08002503 signaling_thread(),
2504 new VideoRtpSender(track, {stream->label()}, video_channel()));
Steve Anton4171afb2017-11-20 10:20:22 -08002505 GetVideoTransceiver()->internal()->AddSender(new_sender);
2506 const RtpSenderInfo* sender_info =
2507 FindSenderInfo(local_video_sender_infos_, stream->label(), track->id());
2508 if (sender_info) {
2509 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002510 }
2511}
2512
2513void PeerConnection::RemoveVideoTrack(VideoTrackInterface* track,
2514 MediaStreamInterface* stream) {
2515 RTC_DCHECK(!IsClosed());
2516 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08002517 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002518 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
2519 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002520 return;
2521 }
Steve Anton4171afb2017-11-20 10:20:22 -08002522 GetVideoTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002523}
2524
Steve Antonba818672017-11-06 10:21:57 -08002525void PeerConnection::SetIceConnectionState(IceConnectionState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07002526 RTC_DCHECK(signaling_thread()->IsCurrent());
Steve Antonba818672017-11-06 10:21:57 -08002527 if (ice_connection_state_ == new_state) {
2528 return;
2529 }
2530
deadbeefcbecd352015-09-23 11:50:27 -07002531 // After transitioning to "closed", ignore any additional states from
Steve Antonba818672017-11-06 10:21:57 -08002532 // TransportController (such as "disconnected").
deadbeefab9b2d12015-10-14 11:33:11 -07002533 if (IsClosed()) {
deadbeefcbecd352015-09-23 11:50:27 -07002534 return;
2535 }
Steve Antonba818672017-11-06 10:21:57 -08002536
Mirko Bonadei675513b2017-11-09 11:09:25 +01002537 RTC_LOG(LS_INFO) << "Changing IceConnectionState " << ice_connection_state_
2538 << " => " << new_state;
Steve Antonba818672017-11-06 10:21:57 -08002539 RTC_DCHECK(ice_connection_state_ !=
2540 PeerConnectionInterface::kIceConnectionClosed);
2541
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002542 ice_connection_state_ = new_state;
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00002543 observer_->OnIceConnectionChange(ice_connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002544}
2545
2546void PeerConnection::OnIceGatheringChange(
2547 PeerConnectionInterface::IceGatheringState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07002548 RTC_DCHECK(signaling_thread()->IsCurrent());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002549 if (IsClosed()) {
2550 return;
2551 }
2552 ice_gathering_state_ = new_state;
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00002553 observer_->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002554}
2555
jbauch81bf7b02017-03-25 08:31:12 -07002556void PeerConnection::OnIceCandidate(
2557 std::unique_ptr<IceCandidateInterface> candidate) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07002558 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07002559 if (IsClosed()) {
2560 return;
2561 }
jbauch81bf7b02017-03-25 08:31:12 -07002562 observer_->OnIceCandidate(candidate.get());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002563}
2564
Honghai Zhang7fb69db2016-03-14 11:59:18 -07002565void PeerConnection::OnIceCandidatesRemoved(
2566 const std::vector<cricket::Candidate>& candidates) {
2567 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07002568 if (IsClosed()) {
2569 return;
2570 }
Honghai Zhang7fb69db2016-03-14 11:59:18 -07002571 observer_->OnIceCandidatesRemoved(candidates);
2572}
2573
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002574void PeerConnection::ChangeSignalingState(
2575 PeerConnectionInterface::SignalingState signaling_state) {
Steve Antonba818672017-11-06 10:21:57 -08002576 RTC_DCHECK(signaling_thread()->IsCurrent());
2577 if (signaling_state_ == signaling_state) {
2578 return;
2579 }
Mirko Bonadei675513b2017-11-09 11:09:25 +01002580 RTC_LOG(LS_INFO) << "Session: " << session_id() << " Old state: "
2581 << GetSignalingStateString(signaling_state_)
2582 << " New state: "
2583 << GetSignalingStateString(signaling_state);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002584 signaling_state_ = signaling_state;
2585 if (signaling_state == kClosed) {
2586 ice_connection_state_ = kIceConnectionClosed;
2587 observer_->OnIceConnectionChange(ice_connection_state_);
2588 if (ice_gathering_state_ != kIceGatheringComplete) {
2589 ice_gathering_state_ = kIceGatheringComplete;
2590 observer_->OnIceGatheringChange(ice_gathering_state_);
2591 }
2592 }
2593 observer_->OnSignalingChange(signaling_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002594}
2595
deadbeefeb459812015-12-15 19:24:43 -08002596void PeerConnection::OnAudioTrackAdded(AudioTrackInterface* track,
2597 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07002598 if (IsClosed()) {
2599 return;
2600 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002601 AddAudioTrack(track, stream);
2602 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08002603}
2604
deadbeefeb459812015-12-15 19:24:43 -08002605void PeerConnection::OnAudioTrackRemoved(AudioTrackInterface* track,
2606 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07002607 if (IsClosed()) {
2608 return;
2609 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002610 RemoveAudioTrack(track, stream);
2611 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08002612}
2613
2614void PeerConnection::OnVideoTrackAdded(VideoTrackInterface* track,
2615 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07002616 if (IsClosed()) {
2617 return;
2618 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002619 AddVideoTrack(track, stream);
2620 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08002621}
2622
2623void PeerConnection::OnVideoTrackRemoved(VideoTrackInterface* track,
2624 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07002625 if (IsClosed()) {
2626 return;
2627 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002628 RemoveVideoTrack(track, stream);
2629 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08002630}
2631
Henrik Boström31638672017-11-23 17:48:32 +01002632void PeerConnection::PostSetSessionDescriptionSuccess(
2633 SetSessionDescriptionObserver* observer) {
2634 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
2635 signaling_thread()->Post(RTC_FROM_HERE, this,
2636 MSG_SET_SESSIONDESCRIPTION_SUCCESS, msg);
2637}
2638
deadbeefab9b2d12015-10-14 11:33:11 -07002639void PeerConnection::PostSetSessionDescriptionFailure(
2640 SetSessionDescriptionObserver* observer,
2641 const std::string& error) {
2642 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
2643 msg->error = error;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07002644 signaling_thread()->Post(RTC_FROM_HERE, this,
2645 MSG_SET_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07002646}
2647
2648void PeerConnection::PostCreateSessionDescriptionFailure(
2649 CreateSessionDescriptionObserver* observer,
2650 const std::string& error) {
2651 CreateSessionDescriptionMsg* msg = new CreateSessionDescriptionMsg(observer);
2652 msg->error = error;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07002653 signaling_thread()->Post(RTC_FROM_HERE, this,
2654 MSG_CREATE_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07002655}
2656
zhihuang1c378ed2017-08-17 14:10:50 -07002657void PeerConnection::GetOptionsForOffer(
deadbeefab9b2d12015-10-14 11:33:11 -07002658 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options,
2659 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07002660 ExtractSharedMediaSessionOptions(rtc_options, session_options);
2661
2662 // Figure out transceiver directional preferences.
2663 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
2664 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
2665
2666 // By default, generate sendrecv/recvonly m= sections.
2667 bool recv_audio = true;
2668 bool recv_video = true;
2669
2670 // By default, only offer a new m= section if we have media to send with it.
2671 bool offer_new_audio_description = send_audio;
2672 bool offer_new_video_description = send_video;
2673 bool offer_new_data_description = HasDataChannels();
2674
2675 // The "offer_to_receive_X" options allow those defaults to be overridden.
2676 if (rtc_options.offer_to_receive_audio != RTCOfferAnswerOptions::kUndefined) {
2677 recv_audio = (rtc_options.offer_to_receive_audio > 0);
2678 offer_new_audio_description =
2679 offer_new_audio_description || (rtc_options.offer_to_receive_audio > 0);
2680 }
2681 if (rtc_options.offer_to_receive_video != RTCOfferAnswerOptions::kUndefined) {
2682 recv_video = (rtc_options.offer_to_receive_video > 0);
2683 offer_new_video_description =
2684 offer_new_video_description || (rtc_options.offer_to_receive_video > 0);
2685 }
2686
2687 rtc::Optional<size_t> audio_index;
2688 rtc::Optional<size_t> video_index;
2689 rtc::Optional<size_t> data_index;
2690 // If a current description exists, generate m= sections in the same order,
2691 // using the first audio/video/data section that appears and rejecting
2692 // extraneous ones.
Steve Anton75737c02017-11-06 10:37:17 -08002693 if (local_description()) {
zhihuang1c378ed2017-08-17 14:10:50 -07002694 GenerateMediaDescriptionOptions(
Steve Anton75737c02017-11-06 10:37:17 -08002695 local_description(),
Steve Anton1d03a752017-11-27 14:30:09 -08002696 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
2697 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
2698 &audio_index, &video_index, &data_index, session_options);
deadbeefab9b2d12015-10-14 11:33:11 -07002699 }
2700
zhihuang1c378ed2017-08-17 14:10:50 -07002701 // Add audio/video/data m= sections to the end if needed.
2702 if (!audio_index && offer_new_audio_description) {
2703 session_options->media_description_options.push_back(
2704 cricket::MediaDescriptionOptions(
2705 cricket::MEDIA_TYPE_AUDIO, cricket::CN_AUDIO,
Steve Anton1d03a752017-11-27 14:30:09 -08002706 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
2707 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01002708 audio_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07002709 }
zhihuang1c378ed2017-08-17 14:10:50 -07002710 if (!video_index && offer_new_video_description) {
2711 session_options->media_description_options.push_back(
2712 cricket::MediaDescriptionOptions(
2713 cricket::MEDIA_TYPE_VIDEO, cricket::CN_VIDEO,
Steve Anton1d03a752017-11-27 14:30:09 -08002714 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
2715 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01002716 video_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07002717 }
zhihuang1c378ed2017-08-17 14:10:50 -07002718 if (!data_index && offer_new_data_description) {
2719 session_options->media_description_options.push_back(
2720 cricket::MediaDescriptionOptions(
2721 cricket::MEDIA_TYPE_DATA, cricket::CN_DATA,
Steve Anton1d03a752017-11-27 14:30:09 -08002722 RtpTransceiverDirection::kSendRecv, false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01002723 data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07002724 }
2725
2726 cricket::MediaDescriptionOptions* audio_media_description_options =
2727 !audio_index ? nullptr
2728 : &session_options->media_description_options[*audio_index];
2729 cricket::MediaDescriptionOptions* video_media_description_options =
2730 !video_index ? nullptr
2731 : &session_options->media_description_options[*video_index];
2732 cricket::MediaDescriptionOptions* data_media_description_options =
2733 !data_index ? nullptr
2734 : &session_options->media_description_options[*data_index];
2735
2736 // Apply ICE restart flag and renomination flag.
2737 for (auto& options : session_options->media_description_options) {
2738 options.transport_options.ice_restart = rtc_options.ice_restart;
2739 options.transport_options.enable_ice_renomination =
2740 configuration_.enable_ice_renomination;
2741 }
2742
Steve Anton4171afb2017-11-20 10:20:22 -08002743 AddRtpSenderOptions(GetSendersInternal(), audio_media_description_options,
zhihuang1c378ed2017-08-17 14:10:50 -07002744 video_media_description_options);
2745 AddRtpDataChannelOptions(rtp_data_channels_, data_media_description_options);
deadbeefc80741f2015-10-22 13:14:45 -07002746
zhihuang9763d562016-08-05 11:14:50 -07002747 // Intentionally unset the data channel type for RTP data channel with the
2748 // second condition. Otherwise the RTP data channels would be successfully
2749 // negotiated by default and the unit tests in WebRtcDataBrowserTest will fail
2750 // when building with chromium. We want to leave RTP data channels broken, so
2751 // people won't try to use them.
Steve Anton75737c02017-11-06 10:37:17 -08002752 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
2753 session_options->data_channel_type = data_channel_type();
deadbeefab9b2d12015-10-14 11:33:11 -07002754 }
zhihuang8f65cdf2016-05-06 18:40:30 -07002755
2756 session_options->rtcp_cname = rtcp_cname_;
jbauchcb560652016-08-04 05:20:32 -07002757 session_options->crypto_options = factory_->options().crypto_options;
deadbeefab9b2d12015-10-14 11:33:11 -07002758}
2759
zhihuang1c378ed2017-08-17 14:10:50 -07002760void PeerConnection::GetOptionsForAnswer(
2761 const RTCOfferAnswerOptions& rtc_options,
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07002762 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07002763 ExtractSharedMediaSessionOptions(rtc_options, session_options);
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07002764
zhihuang1c378ed2017-08-17 14:10:50 -07002765 // Figure out transceiver directional preferences.
2766 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
2767 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
2768
2769 // By default, generate sendrecv/recvonly m= sections. The direction is also
2770 // restricted by the direction in the offer.
2771 bool recv_audio = true;
2772 bool recv_video = true;
2773
2774 // The "offer_to_receive_X" options allow those defaults to be overridden.
2775 if (rtc_options.offer_to_receive_audio != RTCOfferAnswerOptions::kUndefined) {
2776 recv_audio = (rtc_options.offer_to_receive_audio > 0);
deadbeef0ed85b22016-02-23 17:24:52 -08002777 }
zhihuang1c378ed2017-08-17 14:10:50 -07002778 if (rtc_options.offer_to_receive_video != RTCOfferAnswerOptions::kUndefined) {
2779 recv_video = (rtc_options.offer_to_receive_video > 0);
2780 }
2781
2782 rtc::Optional<size_t> audio_index;
2783 rtc::Optional<size_t> video_index;
2784 rtc::Optional<size_t> data_index;
Steve Anton75737c02017-11-06 10:37:17 -08002785 if (remote_description()) {
zhihuang141aacb2017-08-29 13:23:53 -07002786 // The pending remote description should be an offer.
Steve Antona3a92c22017-12-07 10:27:41 -08002787 RTC_DCHECK(remote_description()->GetType() == SdpType::kOffer);
zhihuang141aacb2017-08-29 13:23:53 -07002788 // Generate m= sections that match those in the offer.
2789 // Note that mediasession.cc will handle intersection our preferred
2790 // direction with the offered direction.
2791 GenerateMediaDescriptionOptions(
Steve Anton75737c02017-11-06 10:37:17 -08002792 remote_description(),
Steve Anton1d03a752017-11-27 14:30:09 -08002793 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
2794 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
2795 &audio_index, &video_index, &data_index, session_options);
zhihuang141aacb2017-08-29 13:23:53 -07002796 }
zhihuang1c378ed2017-08-17 14:10:50 -07002797
2798 cricket::MediaDescriptionOptions* audio_media_description_options =
2799 !audio_index ? nullptr
2800 : &session_options->media_description_options[*audio_index];
2801 cricket::MediaDescriptionOptions* video_media_description_options =
2802 !video_index ? nullptr
2803 : &session_options->media_description_options[*video_index];
2804 cricket::MediaDescriptionOptions* data_media_description_options =
2805 !data_index ? nullptr
2806 : &session_options->media_description_options[*data_index];
2807
2808 // Apply ICE renomination flag.
2809 for (auto& options : session_options->media_description_options) {
2810 options.transport_options.enable_ice_renomination =
2811 configuration_.enable_ice_renomination;
2812 }
2813
Steve Anton4171afb2017-11-20 10:20:22 -08002814 AddRtpSenderOptions(GetSendersInternal(), audio_media_description_options,
zhihuang1c378ed2017-08-17 14:10:50 -07002815 video_media_description_options);
2816 AddRtpDataChannelOptions(rtp_data_channels_, data_media_description_options);
2817
zhihuang9763d562016-08-05 11:14:50 -07002818 // Intentionally unset the data channel type for RTP data channel. Otherwise
2819 // the RTP data channels would be successfully negotiated by default and the
2820 // unit tests in WebRtcDataBrowserTest will fail when building with chromium.
2821 // We want to leave RTP data channels broken, so people won't try to use them.
Steve Anton75737c02017-11-06 10:37:17 -08002822 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
2823 session_options->data_channel_type = data_channel_type();
deadbeef907abe42016-08-04 12:22:18 -07002824 }
zhihuangaf388472016-11-02 16:49:48 -07002825
zhihuang1c378ed2017-08-17 14:10:50 -07002826 session_options->rtcp_cname = rtcp_cname_;
jbauchcb560652016-08-04 05:20:32 -07002827 session_options->crypto_options = factory_->options().crypto_options;
htaa2a49d92016-03-04 02:51:39 -08002828}
2829
zhihuang1c378ed2017-08-17 14:10:50 -07002830void PeerConnection::GenerateMediaDescriptionOptions(
2831 const SessionDescriptionInterface* session_desc,
Steve Anton1d03a752017-11-27 14:30:09 -08002832 RtpTransceiverDirection audio_direction,
2833 RtpTransceiverDirection video_direction,
zhihuang1c378ed2017-08-17 14:10:50 -07002834 rtc::Optional<size_t>* audio_index,
2835 rtc::Optional<size_t>* video_index,
2836 rtc::Optional<size_t>* data_index,
htaa2a49d92016-03-04 02:51:39 -08002837 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07002838 for (const cricket::ContentInfo& content :
2839 session_desc->description()->contents()) {
2840 if (IsAudioContent(&content)) {
2841 // If we already have an audio m= section, reject this extra one.
2842 if (*audio_index) {
2843 session_options->media_description_options.push_back(
2844 cricket::MediaDescriptionOptions(
2845 cricket::MEDIA_TYPE_AUDIO, content.name,
Steve Anton1d03a752017-11-27 14:30:09 -08002846 RtpTransceiverDirection::kInactive, true));
zhihuang1c378ed2017-08-17 14:10:50 -07002847 } else {
2848 session_options->media_description_options.push_back(
2849 cricket::MediaDescriptionOptions(
2850 cricket::MEDIA_TYPE_AUDIO, content.name, audio_direction,
Steve Anton1d03a752017-11-27 14:30:09 -08002851 audio_direction == RtpTransceiverDirection::kInactive));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01002852 *audio_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07002853 }
2854 } else if (IsVideoContent(&content)) {
2855 // If we already have an video m= section, reject this extra one.
2856 if (*video_index) {
2857 session_options->media_description_options.push_back(
2858 cricket::MediaDescriptionOptions(
2859 cricket::MEDIA_TYPE_VIDEO, content.name,
Steve Anton1d03a752017-11-27 14:30:09 -08002860 RtpTransceiverDirection::kInactive, true));
zhihuang1c378ed2017-08-17 14:10:50 -07002861 } else {
2862 session_options->media_description_options.push_back(
2863 cricket::MediaDescriptionOptions(
2864 cricket::MEDIA_TYPE_VIDEO, content.name, video_direction,
Steve Anton1d03a752017-11-27 14:30:09 -08002865 video_direction == RtpTransceiverDirection::kInactive));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01002866 *video_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07002867 }
2868 } else {
2869 RTC_DCHECK(IsDataContent(&content));
2870 // If we already have an data m= section, reject this extra one.
2871 if (*data_index) {
2872 session_options->media_description_options.push_back(
2873 cricket::MediaDescriptionOptions(
2874 cricket::MEDIA_TYPE_DATA, content.name,
Steve Anton1d03a752017-11-27 14:30:09 -08002875 RtpTransceiverDirection::kInactive, true));
zhihuang1c378ed2017-08-17 14:10:50 -07002876 } else {
2877 session_options->media_description_options.push_back(
2878 cricket::MediaDescriptionOptions(
2879 cricket::MEDIA_TYPE_DATA, content.name,
2880 // Direction for data sections is meaningless, but legacy
2881 // endpoints might expect sendrecv.
Steve Anton1d03a752017-11-27 14:30:09 -08002882 RtpTransceiverDirection::kSendRecv, false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01002883 *data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07002884 }
2885 }
htaa2a49d92016-03-04 02:51:39 -08002886 }
deadbeefab9b2d12015-10-14 11:33:11 -07002887}
2888
Steve Anton4171afb2017-11-20 10:20:22 -08002889void PeerConnection::RemoveSenders(cricket::MediaType media_type) {
2890 UpdateLocalSenders(std::vector<cricket::StreamParams>(), media_type);
2891 UpdateRemoteSendersList(std::vector<cricket::StreamParams>(), false,
deadbeefbda7e0b2015-12-08 17:13:40 -08002892 media_type, nullptr);
deadbeeffaac4972015-11-12 15:33:07 -08002893}
2894
Steve Anton4171afb2017-11-20 10:20:22 -08002895void PeerConnection::UpdateRemoteSendersList(
deadbeefab9b2d12015-10-14 11:33:11 -07002896 const cricket::StreamParamsVec& streams,
Steve Anton4171afb2017-11-20 10:20:22 -08002897 bool default_sender_needed,
deadbeefab9b2d12015-10-14 11:33:11 -07002898 cricket::MediaType media_type,
2899 StreamCollection* new_streams) {
Steve Anton4171afb2017-11-20 10:20:22 -08002900 std::vector<RtpSenderInfo>* current_senders =
2901 GetRemoteSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07002902
Steve Anton4171afb2017-11-20 10:20:22 -08002903 // Find removed senders. I.e., senders where the sender id or ssrc don't match
deadbeeffac06552015-11-25 11:26:01 -08002904 // the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08002905 for (auto sender_it = current_senders->begin();
2906 sender_it != current_senders->end();
2907 /* incremented manually */) {
2908 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07002909 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08002910 cricket::GetStreamBySsrc(streams, info.first_ssrc);
2911 bool sender_exists = params && params->id == info.sender_id;
deadbeefbda7e0b2015-12-08 17:13:40 -08002912 // If this is a default track, and we still need it, don't remove it.
Steve Anton4171afb2017-11-20 10:20:22 -08002913 if ((info.stream_label == kDefaultStreamLabel && default_sender_needed) ||
2914 sender_exists) {
2915 ++sender_it;
deadbeefbda7e0b2015-12-08 17:13:40 -08002916 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08002917 OnRemoteSenderRemoved(info, media_type);
2918 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07002919 }
2920 }
2921
Steve Anton4171afb2017-11-20 10:20:22 -08002922 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07002923 for (const cricket::StreamParams& params : streams) {
2924 // The sync_label is the MediaStream label and the |stream.id| is the
Steve Anton4171afb2017-11-20 10:20:22 -08002925 // sender id.
deadbeefab9b2d12015-10-14 11:33:11 -07002926 const std::string& stream_label = params.sync_label;
Steve Anton4171afb2017-11-20 10:20:22 -08002927 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07002928 uint32_t ssrc = params.first_ssrc();
2929
2930 rtc::scoped_refptr<MediaStreamInterface> stream =
2931 remote_streams_->find(stream_label);
2932 if (!stream) {
2933 // This is a new MediaStream. Create a new remote MediaStream.
perkjd61bf802016-03-24 03:16:19 -07002934 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
2935 MediaStream::Create(stream_label));
deadbeefab9b2d12015-10-14 11:33:11 -07002936 remote_streams_->AddStream(stream);
2937 new_streams->AddStream(stream);
2938 }
2939
Steve Anton4171afb2017-11-20 10:20:22 -08002940 const RtpSenderInfo* sender_info =
2941 FindSenderInfo(*current_senders, stream_label, sender_id);
2942 if (!sender_info) {
2943 current_senders->push_back(RtpSenderInfo(stream_label, sender_id, ssrc));
2944 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07002945 }
2946 }
deadbeefbda7e0b2015-12-08 17:13:40 -08002947
Steve Anton4171afb2017-11-20 10:20:22 -08002948 // Add default sender if necessary.
2949 if (default_sender_needed) {
deadbeefbda7e0b2015-12-08 17:13:40 -08002950 rtc::scoped_refptr<MediaStreamInterface> default_stream =
2951 remote_streams_->find(kDefaultStreamLabel);
2952 if (!default_stream) {
2953 // Create the new default MediaStream.
perkjd61bf802016-03-24 03:16:19 -07002954 default_stream = MediaStreamProxy::Create(
2955 rtc::Thread::Current(), MediaStream::Create(kDefaultStreamLabel));
deadbeefbda7e0b2015-12-08 17:13:40 -08002956 remote_streams_->AddStream(default_stream);
2957 new_streams->AddStream(default_stream);
2958 }
Steve Anton4171afb2017-11-20 10:20:22 -08002959 std::string default_sender_id = (media_type == cricket::MEDIA_TYPE_AUDIO)
2960 ? kDefaultAudioSenderId
2961 : kDefaultVideoSenderId;
2962 const RtpSenderInfo* default_sender_info = FindSenderInfo(
2963 *current_senders, kDefaultStreamLabel, default_sender_id);
2964 if (!default_sender_info) {
2965 current_senders->push_back(
2966 RtpSenderInfo(kDefaultStreamLabel, default_sender_id, 0));
2967 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefbda7e0b2015-12-08 17:13:40 -08002968 }
2969 }
deadbeefab9b2d12015-10-14 11:33:11 -07002970}
2971
Steve Anton4171afb2017-11-20 10:20:22 -08002972void PeerConnection::OnRemoteSenderAdded(const RtpSenderInfo& sender_info,
2973 cricket::MediaType media_type) {
2974 MediaStreamInterface* stream =
2975 remote_streams_->find(sender_info.stream_label);
deadbeefab9b2d12015-10-14 11:33:11 -07002976
2977 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 10:20:22 -08002978 CreateAudioReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07002979 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 10:20:22 -08002980 CreateVideoReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07002981 } else {
nisseeb4ca4e2017-01-12 02:24:27 -08002982 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07002983 }
2984}
2985
Steve Anton4171afb2017-11-20 10:20:22 -08002986void PeerConnection::OnRemoteSenderRemoved(const RtpSenderInfo& sender_info,
2987 cricket::MediaType media_type) {
2988 MediaStreamInterface* stream =
2989 remote_streams_->find(sender_info.stream_label);
deadbeefab9b2d12015-10-14 11:33:11 -07002990
Henrik Boström933d8b02017-10-10 10:05:16 -07002991 rtc::scoped_refptr<RtpReceiverInterface> receiver;
deadbeefab9b2d12015-10-14 11:33:11 -07002992 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
perkjd61bf802016-03-24 03:16:19 -07002993 // When the MediaEngine audio channel is destroyed, the RemoteAudioSource
2994 // will be notified which will end the AudioRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08002995 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07002996 rtc::scoped_refptr<AudioTrackInterface> audio_track =
Steve Anton4171afb2017-11-20 10:20:22 -08002997 stream->FindAudioTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07002998 if (audio_track) {
deadbeefab9b2d12015-10-14 11:33:11 -07002999 stream->RemoveTrack(audio_track);
deadbeefab9b2d12015-10-14 11:33:11 -07003000 }
3001 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
perkjd61bf802016-03-24 03:16:19 -07003002 // Stopping or destroying a VideoRtpReceiver will end the
3003 // VideoRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08003004 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07003005 rtc::scoped_refptr<VideoTrackInterface> video_track =
Steve Anton4171afb2017-11-20 10:20:22 -08003006 stream->FindVideoTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07003007 if (video_track) {
perkjd61bf802016-03-24 03:16:19 -07003008 // There's no guarantee the track is still available, e.g. the track may
3009 // have been removed from the stream by an application.
deadbeefab9b2d12015-10-14 11:33:11 -07003010 stream->RemoveTrack(video_track);
deadbeefab9b2d12015-10-14 11:33:11 -07003011 }
3012 } else {
nisseede5da42017-01-12 05:15:36 -08003013 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07003014 }
Henrik Boström933d8b02017-10-10 10:05:16 -07003015 if (receiver) {
3016 observer_->OnRemoveTrack(receiver);
3017 }
deadbeefab9b2d12015-10-14 11:33:11 -07003018}
3019
3020void PeerConnection::UpdateEndedRemoteMediaStreams() {
3021 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams_to_remove;
3022 for (size_t i = 0; i < remote_streams_->count(); ++i) {
3023 MediaStreamInterface* stream = remote_streams_->at(i);
3024 if (stream->GetAudioTracks().empty() && stream->GetVideoTracks().empty()) {
3025 streams_to_remove.push_back(stream);
3026 }
3027 }
3028
Taylor Brandstetter98cde262016-05-31 13:02:21 -07003029 for (auto& stream : streams_to_remove) {
deadbeefab9b2d12015-10-14 11:33:11 -07003030 remote_streams_->RemoveStream(stream);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07003031 observer_->OnRemoveStream(std::move(stream));
deadbeefab9b2d12015-10-14 11:33:11 -07003032 }
3033}
3034
Steve Anton4171afb2017-11-20 10:20:22 -08003035void PeerConnection::UpdateLocalSenders(
deadbeefab9b2d12015-10-14 11:33:11 -07003036 const std::vector<cricket::StreamParams>& streams,
3037 cricket::MediaType media_type) {
Steve Anton4171afb2017-11-20 10:20:22 -08003038 std::vector<RtpSenderInfo>* current_senders = GetLocalSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07003039
3040 // Find removed tracks. I.e., tracks where the track id, stream label or ssrc
3041 // don't match the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08003042 for (auto sender_it = current_senders->begin();
3043 sender_it != current_senders->end();
3044 /* incremented manually */) {
3045 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07003046 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08003047 cricket::GetStreamBySsrc(streams, info.first_ssrc);
3048 if (!params || params->id != info.sender_id ||
deadbeefab9b2d12015-10-14 11:33:11 -07003049 params->sync_label != info.stream_label) {
Steve Anton4171afb2017-11-20 10:20:22 -08003050 OnLocalSenderRemoved(info, media_type);
3051 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07003052 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08003053 ++sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07003054 }
3055 }
3056
Steve Anton4171afb2017-11-20 10:20:22 -08003057 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07003058 for (const cricket::StreamParams& params : streams) {
3059 // The sync_label is the MediaStream label and the |stream.id| is the
Steve Anton4171afb2017-11-20 10:20:22 -08003060 // sender id.
deadbeefab9b2d12015-10-14 11:33:11 -07003061 const std::string& stream_label = params.sync_label;
Steve Anton4171afb2017-11-20 10:20:22 -08003062 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07003063 uint32_t ssrc = params.first_ssrc();
Steve Anton4171afb2017-11-20 10:20:22 -08003064 const RtpSenderInfo* sender_info =
3065 FindSenderInfo(*current_senders, stream_label, sender_id);
3066 if (!sender_info) {
3067 current_senders->push_back(RtpSenderInfo(stream_label, sender_id, ssrc));
3068 OnLocalSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07003069 }
3070 }
3071}
3072
Steve Anton4171afb2017-11-20 10:20:22 -08003073void PeerConnection::OnLocalSenderAdded(const RtpSenderInfo& sender_info,
3074 cricket::MediaType media_type) {
3075 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08003076 if (!sender) {
Steve Anton4171afb2017-11-20 10:20:22 -08003077 RTC_LOG(LS_WARNING) << "An unknown RtpSender with id "
3078 << sender_info.sender_id
Mirko Bonadei675513b2017-11-09 11:09:25 +01003079 << " has been configured in the local description.";
deadbeefab9b2d12015-10-14 11:33:11 -07003080 return;
3081 }
3082
deadbeeffac06552015-11-25 11:26:01 -08003083 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003084 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
3085 << " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08003086 return;
deadbeefab9b2d12015-10-14 11:33:11 -07003087 }
deadbeeffac06552015-11-25 11:26:01 -08003088
Steve Anton4171afb2017-11-20 10:20:22 -08003089 sender->internal()->set_stream_id(sender_info.stream_label);
3090 sender->internal()->SetSsrc(sender_info.first_ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07003091}
3092
Steve Anton4171afb2017-11-20 10:20:22 -08003093void PeerConnection::OnLocalSenderRemoved(const RtpSenderInfo& sender_info,
3094 cricket::MediaType media_type) {
3095 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08003096 if (!sender) {
3097 // This is the normal case. I.e., RemoveStream has been called and the
deadbeefab9b2d12015-10-14 11:33:11 -07003098 // SessionDescriptions has been renegotiated.
3099 return;
3100 }
deadbeeffac06552015-11-25 11:26:01 -08003101
3102 // A sender has been removed from the SessionDescription but it's still
3103 // associated with the PeerConnection. This only occurs if the SDP doesn't
3104 // match with the calls to CreateSender, AddStream and RemoveStream.
3105 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003106 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
3107 << " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08003108 return;
deadbeefab9b2d12015-10-14 11:33:11 -07003109 }
deadbeeffac06552015-11-25 11:26:01 -08003110
Steve Anton4171afb2017-11-20 10:20:22 -08003111 sender->internal()->SetSsrc(0);
deadbeefab9b2d12015-10-14 11:33:11 -07003112}
3113
3114void PeerConnection::UpdateLocalRtpDataChannels(
3115 const cricket::StreamParamsVec& streams) {
3116 std::vector<std::string> existing_channels;
3117
3118 // Find new and active data channels.
3119 for (const cricket::StreamParams& params : streams) {
3120 // |it->sync_label| is actually the data channel label. The reason is that
3121 // we use the same naming of data channels as we do for
3122 // MediaStreams and Tracks.
3123 // For MediaStreams, the sync_label is the MediaStream label and the
3124 // track label is the same as |streamid|.
3125 const std::string& channel_label = params.sync_label;
3126 auto data_channel_it = rtp_data_channels_.find(channel_label);
nisse7ce109a2017-01-31 00:57:56 -08003127 if (data_channel_it == rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003128 RTC_LOG(LS_ERROR) << "channel label not found";
deadbeefab9b2d12015-10-14 11:33:11 -07003129 continue;
3130 }
3131 // Set the SSRC the data channel should use for sending.
3132 data_channel_it->second->SetSendSsrc(params.first_ssrc());
3133 existing_channels.push_back(data_channel_it->first);
3134 }
3135
3136 UpdateClosingRtpDataChannels(existing_channels, true);
3137}
3138
3139void PeerConnection::UpdateRemoteRtpDataChannels(
3140 const cricket::StreamParamsVec& streams) {
3141 std::vector<std::string> existing_channels;
3142
3143 // Find new and active data channels.
3144 for (const cricket::StreamParams& params : streams) {
3145 // The data channel label is either the mslabel or the SSRC if the mslabel
3146 // does not exist. Ex a=ssrc:444330170 mslabel:test1.
3147 std::string label = params.sync_label.empty()
3148 ? rtc::ToString(params.first_ssrc())
3149 : params.sync_label;
3150 auto data_channel_it = rtp_data_channels_.find(label);
3151 if (data_channel_it == rtp_data_channels_.end()) {
3152 // This is a new data channel.
3153 CreateRemoteRtpDataChannel(label, params.first_ssrc());
3154 } else {
3155 data_channel_it->second->SetReceiveSsrc(params.first_ssrc());
3156 }
3157 existing_channels.push_back(label);
3158 }
3159
3160 UpdateClosingRtpDataChannels(existing_channels, false);
3161}
3162
3163void PeerConnection::UpdateClosingRtpDataChannels(
3164 const std::vector<std::string>& active_channels,
3165 bool is_local_update) {
3166 auto it = rtp_data_channels_.begin();
3167 while (it != rtp_data_channels_.end()) {
3168 DataChannel* data_channel = it->second;
3169 if (std::find(active_channels.begin(), active_channels.end(),
3170 data_channel->label()) != active_channels.end()) {
3171 ++it;
3172 continue;
3173 }
3174
3175 if (is_local_update) {
3176 data_channel->SetSendSsrc(0);
3177 } else {
3178 data_channel->RemotePeerRequestClose();
3179 }
3180
3181 if (data_channel->state() == DataChannel::kClosed) {
3182 rtp_data_channels_.erase(it);
3183 it = rtp_data_channels_.begin();
3184 } else {
3185 ++it;
3186 }
3187 }
3188}
3189
3190void PeerConnection::CreateRemoteRtpDataChannel(const std::string& label,
3191 uint32_t remote_ssrc) {
3192 rtc::scoped_refptr<DataChannel> channel(
3193 InternalCreateDataChannel(label, nullptr));
3194 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003195 RTC_LOG(LS_WARNING) << "Remote peer requested a DataChannel but"
3196 << "CreateDataChannel failed.";
deadbeefab9b2d12015-10-14 11:33:11 -07003197 return;
3198 }
3199 channel->SetReceiveSsrc(remote_ssrc);
deadbeefa601f5c2016-06-06 14:27:39 -07003200 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
3201 DataChannelProxy::Create(signaling_thread(), channel);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07003202 observer_->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07003203}
3204
3205rtc::scoped_refptr<DataChannel> PeerConnection::InternalCreateDataChannel(
3206 const std::string& label,
3207 const InternalDataChannelInit* config) {
3208 if (IsClosed()) {
3209 return nullptr;
3210 }
Steve Anton75737c02017-11-06 10:37:17 -08003211 if (data_channel_type() == cricket::DCT_NONE) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003212 RTC_LOG(LS_ERROR)
deadbeefab9b2d12015-10-14 11:33:11 -07003213 << "InternalCreateDataChannel: Data is not supported in this call.";
3214 return nullptr;
3215 }
3216 InternalDataChannelInit new_config =
3217 config ? (*config) : InternalDataChannelInit();
Steve Anton75737c02017-11-06 10:37:17 -08003218 if (data_channel_type() == cricket::DCT_SCTP) {
deadbeefab9b2d12015-10-14 11:33:11 -07003219 if (new_config.id < 0) {
3220 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08003221 if ((GetSctpSslRole(&role)) &&
deadbeefab9b2d12015-10-14 11:33:11 -07003222 !sid_allocator_.AllocateSid(role, &new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003223 RTC_LOG(LS_ERROR)
3224 << "No id can be allocated for the SCTP data channel.";
deadbeefab9b2d12015-10-14 11:33:11 -07003225 return nullptr;
3226 }
3227 } else if (!sid_allocator_.ReserveSid(new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003228 RTC_LOG(LS_ERROR) << "Failed to create a SCTP data channel "
3229 << "because the id is already in use or out of range.";
deadbeefab9b2d12015-10-14 11:33:11 -07003230 return nullptr;
3231 }
3232 }
3233
Steve Anton75737c02017-11-06 10:37:17 -08003234 rtc::scoped_refptr<DataChannel> channel(
3235 DataChannel::Create(this, data_channel_type(), label, new_config));
deadbeefab9b2d12015-10-14 11:33:11 -07003236 if (!channel) {
3237 sid_allocator_.ReleaseSid(new_config.id);
3238 return nullptr;
3239 }
3240
3241 if (channel->data_channel_type() == cricket::DCT_RTP) {
3242 if (rtp_data_channels_.find(channel->label()) != rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003243 RTC_LOG(LS_ERROR) << "DataChannel with label " << channel->label()
3244 << " already exists.";
deadbeefab9b2d12015-10-14 11:33:11 -07003245 return nullptr;
3246 }
3247 rtp_data_channels_[channel->label()] = channel;
3248 } else {
3249 RTC_DCHECK(channel->data_channel_type() == cricket::DCT_SCTP);
3250 sctp_data_channels_.push_back(channel);
3251 channel->SignalClosed.connect(this,
3252 &PeerConnection::OnSctpDataChannelClosed);
3253 }
3254
hbos82ebe022016-11-14 01:41:09 -08003255 SignalDataChannelCreated(channel.get());
deadbeefab9b2d12015-10-14 11:33:11 -07003256 return channel;
3257}
3258
3259bool PeerConnection::HasDataChannels() const {
3260 return !rtp_data_channels_.empty() || !sctp_data_channels_.empty();
3261}
3262
3263void PeerConnection::AllocateSctpSids(rtc::SSLRole role) {
3264 for (const auto& channel : sctp_data_channels_) {
3265 if (channel->id() < 0) {
3266 int sid;
3267 if (!sid_allocator_.AllocateSid(role, &sid)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003268 RTC_LOG(LS_ERROR) << "Failed to allocate SCTP sid.";
deadbeefab9b2d12015-10-14 11:33:11 -07003269 continue;
3270 }
3271 channel->SetSctpSid(sid);
3272 }
3273 }
3274}
3275
3276void PeerConnection::OnSctpDataChannelClosed(DataChannel* channel) {
deadbeefbd292462015-12-14 18:15:29 -08003277 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeefab9b2d12015-10-14 11:33:11 -07003278 for (auto it = sctp_data_channels_.begin(); it != sctp_data_channels_.end();
3279 ++it) {
3280 if (it->get() == channel) {
3281 if (channel->id() >= 0) {
3282 sid_allocator_.ReleaseSid(channel->id());
3283 }
deadbeefbd292462015-12-14 18:15:29 -08003284 // Since this method is triggered by a signal from the DataChannel,
3285 // we can't free it directly here; we need to free it asynchronously.
3286 sctp_data_channels_to_free_.push_back(*it);
deadbeefab9b2d12015-10-14 11:33:11 -07003287 sctp_data_channels_.erase(it);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07003288 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_FREE_DATACHANNELS,
3289 nullptr);
deadbeefab9b2d12015-10-14 11:33:11 -07003290 return;
3291 }
3292 }
3293}
3294
deadbeefab9b2d12015-10-14 11:33:11 -07003295void PeerConnection::OnDataChannelDestroyed() {
3296 // Use a temporary copy of the RTP/SCTP DataChannel list because the
3297 // DataChannel may callback to us and try to modify the list.
3298 std::map<std::string, rtc::scoped_refptr<DataChannel>> temp_rtp_dcs;
3299 temp_rtp_dcs.swap(rtp_data_channels_);
3300 for (const auto& kv : temp_rtp_dcs) {
3301 kv.second->OnTransportChannelDestroyed();
3302 }
3303
3304 std::vector<rtc::scoped_refptr<DataChannel>> temp_sctp_dcs;
3305 temp_sctp_dcs.swap(sctp_data_channels_);
3306 for (const auto& channel : temp_sctp_dcs) {
3307 channel->OnTransportChannelDestroyed();
3308 }
3309}
3310
3311void PeerConnection::OnDataChannelOpenMessage(
3312 const std::string& label,
3313 const InternalDataChannelInit& config) {
3314 rtc::scoped_refptr<DataChannel> channel(
3315 InternalCreateDataChannel(label, &config));
3316 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003317 RTC_LOG(LS_ERROR) << "Failed to create DataChannel from the OPEN message.";
deadbeefab9b2d12015-10-14 11:33:11 -07003318 return;
3319 }
3320
deadbeefa601f5c2016-06-06 14:27:39 -07003321 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
3322 DataChannelProxy::Create(signaling_thread(), channel);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07003323 observer_->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07003324}
3325
Steve Anton4171afb2017-11-20 10:20:22 -08003326rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3327PeerConnection::GetAudioTransceiver() const {
3328 // This method only works with Plan B SDP, where there is a single
3329 // audio/video transceiver.
3330 RTC_DCHECK(!IsUnifiedPlan());
3331 for (auto transceiver : transceivers_) {
3332 if (transceiver->internal()->media_type() == cricket::MEDIA_TYPE_AUDIO) {
3333 return transceiver;
3334 }
3335 }
3336 RTC_NOTREACHED();
3337 return nullptr;
3338}
3339
3340rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3341PeerConnection::GetVideoTransceiver() const {
3342 // This method only works with Plan B SDP, where there is a single
3343 // audio/video transceiver.
3344 RTC_DCHECK(!IsUnifiedPlan());
3345 for (auto transceiver : transceivers_) {
3346 if (transceiver->internal()->media_type() == cricket::MEDIA_TYPE_VIDEO) {
3347 return transceiver;
3348 }
3349 }
3350 RTC_NOTREACHED();
3351 return nullptr;
3352}
3353
3354// TODO(bugs.webrtc.org/7600): Remove this when multiple transceivers with
3355// individual transceiver directions are supported.
zhihuang1c378ed2017-08-17 14:10:50 -07003356bool PeerConnection::HasRtpSender(cricket::MediaType type) const {
Steve Anton4171afb2017-11-20 10:20:22 -08003357 switch (type) {
3358 case cricket::MEDIA_TYPE_AUDIO:
3359 return !GetAudioTransceiver()->internal()->senders().empty();
3360 case cricket::MEDIA_TYPE_VIDEO:
3361 return !GetVideoTransceiver()->internal()->senders().empty();
3362 case cricket::MEDIA_TYPE_DATA:
3363 return false;
3364 }
3365 RTC_NOTREACHED();
3366 return false;
zhihuang1c378ed2017-08-17 14:10:50 -07003367}
3368
Steve Anton4171afb2017-11-20 10:20:22 -08003369rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
3370PeerConnection::FindSenderForTrack(MediaStreamTrackInterface* track) const {
3371 for (auto transceiver : transceivers_) {
3372 for (auto sender : transceiver->internal()->senders()) {
3373 if (sender->track() == track) {
3374 return sender;
3375 }
3376 }
3377 }
3378 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08003379}
3380
Steve Anton4171afb2017-11-20 10:20:22 -08003381rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
3382PeerConnection::FindSenderById(const std::string& sender_id) const {
3383 for (auto transceiver : transceivers_) {
3384 for (auto sender : transceiver->internal()->senders()) {
3385 if (sender->id() == sender_id) {
3386 return sender;
3387 }
3388 }
3389 }
3390 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07003391}
3392
Steve Anton4171afb2017-11-20 10:20:22 -08003393rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
3394PeerConnection::FindReceiverById(const std::string& receiver_id) const {
3395 for (auto transceiver : transceivers_) {
3396 for (auto receiver : transceiver->internal()->receivers()) {
3397 if (receiver->id() == receiver_id) {
3398 return receiver;
3399 }
3400 }
3401 }
3402 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07003403}
3404
Steve Anton4171afb2017-11-20 10:20:22 -08003405std::vector<PeerConnection::RtpSenderInfo>*
3406PeerConnection::GetRemoteSenderInfos(cricket::MediaType media_type) {
3407 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
3408 media_type == cricket::MEDIA_TYPE_VIDEO);
3409 return (media_type == cricket::MEDIA_TYPE_AUDIO)
3410 ? &remote_audio_sender_infos_
3411 : &remote_video_sender_infos_;
3412}
3413
3414std::vector<PeerConnection::RtpSenderInfo>* PeerConnection::GetLocalSenderInfos(
deadbeefab9b2d12015-10-14 11:33:11 -07003415 cricket::MediaType media_type) {
3416 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
3417 media_type == cricket::MEDIA_TYPE_VIDEO);
Steve Anton4171afb2017-11-20 10:20:22 -08003418 return (media_type == cricket::MEDIA_TYPE_AUDIO) ? &local_audio_sender_infos_
3419 : &local_video_sender_infos_;
deadbeefab9b2d12015-10-14 11:33:11 -07003420}
3421
Steve Anton4171afb2017-11-20 10:20:22 -08003422const PeerConnection::RtpSenderInfo* PeerConnection::FindSenderInfo(
3423 const std::vector<PeerConnection::RtpSenderInfo>& infos,
deadbeefab9b2d12015-10-14 11:33:11 -07003424 const std::string& stream_label,
Steve Anton4171afb2017-11-20 10:20:22 -08003425 const std::string sender_id) const {
3426 for (const RtpSenderInfo& sender_info : infos) {
3427 if (sender_info.stream_label == stream_label &&
3428 sender_info.sender_id == sender_id) {
3429 return &sender_info;
deadbeefab9b2d12015-10-14 11:33:11 -07003430 }
3431 }
3432 return nullptr;
3433}
3434
3435DataChannel* PeerConnection::FindDataChannelBySid(int sid) const {
3436 for (const auto& channel : sctp_data_channels_) {
3437 if (channel->id() == sid) {
3438 return channel;
3439 }
3440 }
3441 return nullptr;
3442}
3443
deadbeef91dd5672016-05-18 16:55:30 -07003444bool PeerConnection::InitializePortAllocator_n(
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003445 const RTCConfiguration& configuration) {
3446 cricket::ServerAddresses stun_servers;
3447 std::vector<cricket::RelayServerConfig> turn_servers;
deadbeef293e9262017-01-11 12:28:30 -08003448 if (ParseIceServers(configuration.servers, &stun_servers, &turn_servers) !=
3449 RTCErrorType::NONE) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003450 return false;
3451 }
3452
Taylor Brandstetterf8e65772016-06-27 17:20:15 -07003453 port_allocator_->Initialize();
3454
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003455 // To handle both internal and externally created port allocator, we will
3456 // enable BUNDLE here.
3457 int portallocator_flags = port_allocator_->flags();
3458 portallocator_flags |= cricket::PORTALLOCATOR_ENABLE_SHARED_SOCKET |
zhihuangb09b3f92017-03-07 14:40:51 -08003459 cricket::PORTALLOCATOR_ENABLE_IPV6 |
3460 cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI;
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003461 // If the disable-IPv6 flag was specified, we'll not override it
3462 // by experiment.
3463 if (configuration.disable_ipv6) {
3464 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
sprangc1b57a12017-02-28 08:50:47 -08003465 } else if (webrtc::field_trial::FindFullName("WebRTC-IPv6Default")
3466 .find("Disabled") == 0) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003467 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
3468 }
3469
zhihuangb09b3f92017-03-07 14:40:51 -08003470 if (configuration.disable_ipv6_on_wifi) {
3471 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI);
Mirko Bonadei675513b2017-11-09 11:09:25 +01003472 RTC_LOG(LS_INFO) << "IPv6 candidates on Wi-Fi are disabled.";
zhihuangb09b3f92017-03-07 14:40:51 -08003473 }
3474
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003475 if (configuration.tcp_candidate_policy == kTcpCandidatePolicyDisabled) {
3476 portallocator_flags |= cricket::PORTALLOCATOR_DISABLE_TCP;
Mirko Bonadei675513b2017-11-09 11:09:25 +01003477 RTC_LOG(LS_INFO) << "TCP candidates are disabled.";
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003478 }
3479
honghaiz60347052016-05-31 18:29:12 -07003480 if (configuration.candidate_network_policy ==
3481 kCandidateNetworkPolicyLowCost) {
3482 portallocator_flags |= cricket::PORTALLOCATOR_DISABLE_COSTLY_NETWORKS;
Mirko Bonadei675513b2017-11-09 11:09:25 +01003483 RTC_LOG(LS_INFO) << "Do not gather candidates on high-cost networks";
honghaiz60347052016-05-31 18:29:12 -07003484 }
3485
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003486 port_allocator_->set_flags(portallocator_flags);
3487 // No step delay is used while allocating ports.
3488 port_allocator_->set_step_delay(cricket::kMinimumStepDelay);
3489 port_allocator_->set_candidate_filter(
3490 ConvertIceTransportTypeToCandidateFilter(configuration.type));
deadbeefd21eab32017-07-26 16:50:11 -07003491 port_allocator_->set_max_ipv6_networks(configuration.max_ipv6_networks);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003492
3493 // Call this last since it may create pooled allocator sessions using the
3494 // properties set above.
3495 port_allocator_->SetConfiguration(stun_servers, turn_servers,
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -07003496 configuration.ice_candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02003497 configuration.prune_turn_ports,
3498 configuration.turn_customizer);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003499 return true;
3500}
3501
deadbeef91dd5672016-05-18 16:55:30 -07003502bool PeerConnection::ReconfigurePortAllocator_n(
deadbeef293e9262017-01-11 12:28:30 -08003503 const cricket::ServerAddresses& stun_servers,
3504 const std::vector<cricket::RelayServerConfig>& turn_servers,
3505 IceTransportsType type,
3506 int candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02003507 bool prune_turn_ports,
3508 webrtc::TurnCustomizer* turn_customizer) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003509 port_allocator_->set_candidate_filter(
deadbeef293e9262017-01-11 12:28:30 -08003510 ConvertIceTransportTypeToCandidateFilter(type));
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003511 // Call this last since it may create pooled allocator sessions using the
3512 // candidate filter set above.
deadbeef6de92f92016-12-12 18:49:32 -08003513 return port_allocator_->SetConfiguration(
Jonas Orelandbdcee282017-10-10 14:01:40 +02003514 stun_servers, turn_servers, candidate_pool_size, prune_turn_ports,
3515 turn_customizer);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003516}
3517
Steve Antonba818672017-11-06 10:21:57 -08003518cricket::ChannelManager* PeerConnection::channel_manager() const {
3519 return factory_->channel_manager();
3520}
3521
3522MetricsObserverInterface* PeerConnection::metrics_observer() const {
3523 return uma_observer_;
3524}
3525
Elad Alon99c3fe52017-10-13 16:29:40 +02003526bool PeerConnection::StartRtcEventLog_w(
Bjorn Tereliusde939432017-11-20 17:38:14 +01003527 std::unique_ptr<RtcEventLogOutput> output,
3528 int64_t output_period_ms) {
zhihuang77985012017-02-07 15:45:16 -08003529 if (!event_log_) {
3530 return false;
3531 }
Bjorn Tereliusde939432017-11-20 17:38:14 +01003532 return event_log_->StartLogging(std::move(output), output_period_ms);
ivoc14d5dbe2016-07-04 07:06:55 -07003533}
3534
3535void PeerConnection::StopRtcEventLog_w() {
zhihuang77985012017-02-07 15:45:16 -08003536 if (event_log_) {
3537 event_log_->StopLogging();
3538 }
ivoc14d5dbe2016-07-04 07:06:55 -07003539}
nisseeaabdf62017-05-05 02:23:02 -07003540
Steve Anton75737c02017-11-06 10:37:17 -08003541cricket::BaseChannel* PeerConnection::GetChannel(
3542 const std::string& content_name) {
3543 if (voice_channel() && voice_channel()->content_name() == content_name) {
3544 return voice_channel();
3545 }
3546 if (video_channel() && video_channel()->content_name() == content_name) {
3547 return video_channel();
3548 }
3549 if (rtp_data_channel() &&
3550 rtp_data_channel()->content_name() == content_name) {
3551 return rtp_data_channel();
3552 }
3553 return nullptr;
3554}
3555
3556bool PeerConnection::GetSctpSslRole(rtc::SSLRole* role) {
3557 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003558 RTC_LOG(LS_INFO)
3559 << "Local and Remote descriptions must be applied to get the "
3560 << "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08003561 return false;
3562 }
3563 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003564 RTC_LOG(LS_INFO) << "Non-rejected SCTP m= section is needed to get the "
3565 << "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08003566 return false;
3567 }
3568
3569 return transport_controller_->GetSslRole(*sctp_transport_name_, role);
3570}
3571
3572bool PeerConnection::GetSslRole(const std::string& content_name,
3573 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 session.";
Steve Anton75737c02017-11-06 10:37:17 -08003578 return false;
3579 }
3580
3581 return transport_controller_->GetSslRole(GetTransportName(content_name),
3582 role);
3583}
3584
Steve Anton75737c02017-11-06 10:37:17 -08003585// TODO(steveanton): Eventually it'd be nice to store the channels as a single
3586// vector of BaseChannel pointers instead of separate voice and video channel
3587// vectors. At that point, this will become a simple getter.
3588std::vector<cricket::BaseChannel*> PeerConnection::Channels() const {
3589 std::vector<cricket::BaseChannel*> channels;
Steve Anton4171afb2017-11-20 10:20:22 -08003590 if (voice_channel()) {
3591 channels.push_back(voice_channel());
3592 }
3593 if (video_channel()) {
3594 channels.push_back(video_channel());
3595 }
Steve Anton75737c02017-11-06 10:37:17 -08003596 if (rtp_data_channel_) {
3597 channels.push_back(rtp_data_channel_);
3598 }
3599 return channels;
3600}
3601
Steve Antonf8470812017-12-04 10:46:21 -08003602void PeerConnection::SetSessionError(SessionError error,
3603 const std::string& error_desc) {
3604 RTC_DCHECK_RUN_ON(signaling_thread());
3605 if (error != session_error_) {
3606 session_error_ = error;
3607 session_error_desc_ = error_desc;
Steve Anton75737c02017-11-06 10:37:17 -08003608 }
3609}
3610
Steve Anton3828c062017-12-06 10:34:51 -08003611RTCError PeerConnection::UpdateSessionState(SdpType type,
Steve Anton8a006912017-12-04 15:25:56 -08003612 cricket::ContentSource source) {
3613 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08003614
3615 // If there's already a pending error then no state transition should happen.
3616 // But all call-sites should be verifying this before calling us!
Steve Antonf8470812017-12-04 10:46:21 -08003617 RTC_DCHECK(session_error() == SessionError::kNone);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08003618
3619 // If this is an answer then we know whether to BUNDLE or not. If both the
3620 // local and remote side have agreed to BUNDLE, go ahead and enable it.
Steve Anton3828c062017-12-06 10:34:51 -08003621 if (type == SdpType::kAnswer) {
Steve Anton75737c02017-11-06 10:37:17 -08003622 const cricket::ContentGroup* local_bundle =
3623 local_description()->description()->GetGroupByName(
3624 cricket::GROUP_TYPE_BUNDLE);
3625 const cricket::ContentGroup* remote_bundle =
3626 remote_description()->description()->GetGroupByName(
3627 cricket::GROUP_TYPE_BUNDLE);
3628 if (local_bundle && remote_bundle) {
3629 // The answerer decides the transport to bundle on.
3630 const cricket::ContentGroup* answer_bundle =
3631 (source == cricket::CS_LOCAL ? local_bundle : remote_bundle);
3632 if (!EnableBundle(*answer_bundle)) {
Steve Anton8a006912017-12-04 15:25:56 -08003633 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3634 kEnableBundleFailed);
Steve Anton75737c02017-11-06 10:37:17 -08003635 }
3636 }
Steve Anton75737c02017-11-06 10:37:17 -08003637 }
Steve Anton6d6a2ae2017-12-04 17:19:47 -08003638
3639 // Only push down the transport description after potentially enabling BUNDLE;
3640 // we don't want to push down a description on a transport about to be
3641 // destroyed.
Steve Anton3828c062017-12-06 10:34:51 -08003642 RTCError error = PushdownTransportDescription(source, type);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08003643 if (!error.ok()) {
3644 return error;
3645 }
3646
3647 // If this is answer-ish we're ready to let media flow.
Steve Anton3828c062017-12-06 10:34:51 -08003648 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Antoned10bd92017-12-05 10:52:59 -08003649 EnableSending();
Steve Anton6d6a2ae2017-12-04 17:19:47 -08003650 }
3651
3652 // Update the signaling state according to the specified state machine (see
3653 // https://w3c.github.io/webrtc-pc/#rtcsignalingstate-enum).
Steve Anton3828c062017-12-06 10:34:51 -08003654 if (type == SdpType::kOffer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08003655 ChangeSignalingState(source == cricket::CS_LOCAL
3656 ? PeerConnectionInterface::kHaveLocalOffer
3657 : PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton3828c062017-12-06 10:34:51 -08003658 } else if (type == SdpType::kPrAnswer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08003659 ChangeSignalingState(source == cricket::CS_LOCAL
3660 ? PeerConnectionInterface::kHaveLocalPrAnswer
3661 : PeerConnectionInterface::kHaveRemotePrAnswer);
3662 } else {
Steve Anton3828c062017-12-06 10:34:51 -08003663 RTC_DCHECK(type == SdpType::kAnswer);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08003664 ChangeSignalingState(PeerConnectionInterface::kStable);
3665 }
3666
3667 // Update internal objects according to the session description's media
3668 // descriptions.
Steve Anton3828c062017-12-06 10:34:51 -08003669 error = PushdownMediaDescription(type, source);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08003670 if (!error.ok()) {
3671 SetSessionError(SessionError::kContent, error.message());
3672 }
3673 if (session_error() != SessionError::kNone) {
3674 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
3675 }
3676
Steve Anton8a006912017-12-04 15:25:56 -08003677 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08003678}
3679
Steve Anton8a006912017-12-04 15:25:56 -08003680RTCError PeerConnection::PushdownMediaDescription(
Steve Anton3828c062017-12-06 10:34:51 -08003681 SdpType type,
Steve Anton8a006912017-12-04 15:25:56 -08003682 cricket::ContentSource source) {
Steve Antoned10bd92017-12-05 10:52:59 -08003683 const SessionDescriptionInterface* sdesc =
3684 (source == cricket::CS_LOCAL ? local_description()
3685 : remote_description());
Steve Anton75737c02017-11-06 10:37:17 -08003686 RTC_DCHECK(sdesc);
Steve Antoned10bd92017-12-05 10:52:59 -08003687
3688 // Push down the new SDP media section for each audio/video transceiver.
3689 for (auto transceiver : transceivers_) {
Steve Anton75737c02017-11-06 10:37:17 -08003690 const ContentInfo* content_info =
Steve Antoned10bd92017-12-05 10:52:59 -08003691 FindMediaSectionForTransceiver(transceiver, sdesc);
3692 cricket::BaseChannel* channel = transceiver->internal()->channel();
3693 if (!channel || !content_info || content_info->rejected) {
Steve Anton75737c02017-11-06 10:37:17 -08003694 continue;
3695 }
3696 const MediaContentDescription* content_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08003697 content_info->media_description();
Steve Antoned10bd92017-12-05 10:52:59 -08003698 if (!content_desc) {
3699 continue;
3700 }
3701 std::string error;
3702 bool success =
3703 (source == cricket::CS_LOCAL)
Steve Anton3828c062017-12-06 10:34:51 -08003704 ? channel->SetLocalContent(content_desc, type, &error)
3705 : channel->SetRemoteContent(content_desc, type, &error);
Steve Antoned10bd92017-12-05 10:52:59 -08003706 if (!success) {
3707 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, std::move(error));
3708 }
3709 }
3710
3711 // If using the RtpDataChannel, push down the new SDP section for it too.
3712 if (rtp_data_channel_) {
3713 const ContentInfo* data_content =
3714 cricket::GetFirstDataContent(sdesc->description());
3715 if (data_content && !data_content->rejected) {
3716 const MediaContentDescription* data_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08003717 data_content->media_description();
Steve Antoned10bd92017-12-05 10:52:59 -08003718 if (data_desc) {
3719 std::string error;
3720 bool success =
3721 (source == cricket::CS_LOCAL)
Steve Anton3828c062017-12-06 10:34:51 -08003722 ? rtp_data_channel_->SetLocalContent(data_desc, type, &error)
3723 : rtp_data_channel_->SetRemoteContent(data_desc, type,
Steve Antoned10bd92017-12-05 10:52:59 -08003724 &error);
3725 if (!success) {
3726 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3727 std::move(error));
3728 }
Steve Anton75737c02017-11-06 10:37:17 -08003729 }
3730 }
3731 }
Steve Antoned10bd92017-12-05 10:52:59 -08003732
Steve Anton75737c02017-11-06 10:37:17 -08003733 // Need complete offer/answer with an SCTP m= section before starting SCTP,
3734 // according to https://tools.ietf.org/html/draft-ietf-mmusic-sctp-sdp-19
3735 if (sctp_transport_ && local_description() && remote_description() &&
3736 cricket::GetFirstDataContent(local_description()->description()) &&
3737 cricket::GetFirstDataContent(remote_description()->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08003738 bool success = network_thread()->Invoke<bool>(
Steve Anton75737c02017-11-06 10:37:17 -08003739 RTC_FROM_HERE,
3740 rtc::Bind(&PeerConnection::PushdownSctpParameters_n, this, source));
Steve Anton8a006912017-12-04 15:25:56 -08003741 if (!success) {
3742 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
3743 "Failed to push down SCTP parameters.");
3744 }
Steve Anton75737c02017-11-06 10:37:17 -08003745 }
Steve Antoned10bd92017-12-05 10:52:59 -08003746
Steve Anton8a006912017-12-04 15:25:56 -08003747 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08003748}
3749
3750bool PeerConnection::PushdownSctpParameters_n(cricket::ContentSource source) {
3751 RTC_DCHECK(network_thread()->IsCurrent());
3752 RTC_DCHECK(local_description());
3753 RTC_DCHECK(remote_description());
3754 // Apply the SCTP port (which is hidden inside a DataCodec structure...)
3755 // When we support "max-message-size", that would also be pushed down here.
3756 return sctp_transport_->Start(
3757 GetSctpPort(local_description()->description()),
3758 GetSctpPort(remote_description()->description()));
3759}
3760
Steve Anton8a006912017-12-04 15:25:56 -08003761RTCError PeerConnection::PushdownTransportDescription(
3762 cricket::ContentSource source,
Steve Anton3828c062017-12-06 10:34:51 -08003763 SdpType type) {
Steve Anton8a006912017-12-04 15:25:56 -08003764 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08003765
Steve Anton8a006912017-12-04 15:25:56 -08003766 const SessionDescriptionInterface* sdesc =
3767 (source == cricket::CS_LOCAL ? local_description()
3768 : remote_description());
3769 RTC_DCHECK(sdesc);
3770 for (const cricket::TransportInfo& tinfo :
3771 sdesc->description()->transport_infos()) {
3772 std::string error;
3773 bool success;
3774 if (source == cricket::CS_LOCAL) {
3775 success = transport_controller_->SetLocalTransportDescription(
Steve Anton3828c062017-12-06 10:34:51 -08003776 tinfo.content_name, tinfo.description, type, &error);
Steve Anton8a006912017-12-04 15:25:56 -08003777 } else {
3778 success = transport_controller_->SetRemoteTransportDescription(
Steve Anton3828c062017-12-06 10:34:51 -08003779 tinfo.content_name, tinfo.description, type, &error);
Steve Anton8a006912017-12-04 15:25:56 -08003780 }
3781 if (!success) {
3782 LOG_AND_RETURN_ERROR(
3783 RTCErrorType::INVALID_PARAMETER,
3784 "Failed to push down transport description: " + error);
Steve Anton75737c02017-11-06 10:37:17 -08003785 }
3786 }
3787
Steve Anton8a006912017-12-04 15:25:56 -08003788 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08003789}
3790
3791bool PeerConnection::GetTransportDescription(
3792 const SessionDescription* description,
3793 const std::string& content_name,
3794 cricket::TransportDescription* tdesc) {
3795 if (!description || !tdesc) {
3796 return false;
3797 }
3798 const TransportInfo* transport_info =
3799 description->GetTransportInfoByName(content_name);
3800 if (!transport_info) {
3801 return false;
3802 }
3803 *tdesc = transport_info->description;
3804 return true;
3805}
3806
3807bool PeerConnection::EnableBundle(const cricket::ContentGroup& bundle) {
3808 const std::string* first_content_name = bundle.FirstContentName();
3809 if (!first_content_name) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003810 RTC_LOG(LS_WARNING) << "Tried to BUNDLE with no contents.";
Steve Anton75737c02017-11-06 10:37:17 -08003811 return false;
3812 }
3813 const std::string& transport_name = *first_content_name;
3814
3815 auto maybe_set_transport = [this, bundle,
3816 transport_name](cricket::BaseChannel* ch) {
3817 if (!ch || !bundle.HasContentName(ch->content_name())) {
Steve Antoned10bd92017-12-05 10:52:59 -08003818 return;
Steve Anton75737c02017-11-06 10:37:17 -08003819 }
3820
3821 std::string old_transport_name = ch->transport_name();
3822 if (old_transport_name == transport_name) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003823 RTC_LOG(LS_INFO) << "BUNDLE already enabled for " << ch->content_name()
3824 << " on " << transport_name << ".";
Steve Antoned10bd92017-12-05 10:52:59 -08003825 return;
Steve Anton75737c02017-11-06 10:37:17 -08003826 }
3827
3828 cricket::DtlsTransportInternal* rtp_dtls_transport =
3829 transport_controller_->CreateDtlsTransport(
3830 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
3831 bool need_rtcp = (ch->rtcp_dtls_transport() != nullptr);
3832 cricket::DtlsTransportInternal* rtcp_dtls_transport = nullptr;
3833 if (need_rtcp) {
3834 rtcp_dtls_transport = transport_controller_->CreateDtlsTransport(
3835 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
3836 }
3837
3838 ch->SetTransports(rtp_dtls_transport, rtcp_dtls_transport);
Mirko Bonadei675513b2017-11-09 11:09:25 +01003839 RTC_LOG(LS_INFO) << "Enabled BUNDLE for " << ch->content_name() << " on "
3840 << transport_name << ".";
Steve Anton75737c02017-11-06 10:37:17 -08003841 transport_controller_->DestroyDtlsTransport(
3842 old_transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
3843 // If the channel needs rtcp, it means that the channel used to have a
3844 // rtcp transport which needs to be deleted now.
3845 if (need_rtcp) {
3846 transport_controller_->DestroyDtlsTransport(
3847 old_transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
3848 }
Steve Anton75737c02017-11-06 10:37:17 -08003849 };
3850
Steve Antoned10bd92017-12-05 10:52:59 -08003851 for (auto transceiver : transceivers_) {
3852 maybe_set_transport(transceiver->internal()->channel());
Steve Anton75737c02017-11-06 10:37:17 -08003853 }
Steve Antoned10bd92017-12-05 10:52:59 -08003854 maybe_set_transport(rtp_data_channel_);
3855
Steve Anton75737c02017-11-06 10:37:17 -08003856 // For SCTP, transport creation/deletion happens here instead of in the
3857 // object itself.
3858 if (sctp_transport_) {
3859 RTC_DCHECK(sctp_transport_name_);
3860 RTC_DCHECK(sctp_content_name_);
3861 if (transport_name != *sctp_transport_name_ &&
3862 bundle.HasContentName(*sctp_content_name_)) {
3863 network_thread()->Invoke<void>(
3864 RTC_FROM_HERE, rtc::Bind(&PeerConnection::ChangeSctpTransport_n, this,
3865 transport_name));
3866 }
3867 }
3868
3869 return true;
3870}
3871
Steve Anton75737c02017-11-06 10:37:17 -08003872cricket::IceConfig PeerConnection::ParseIceConfig(
3873 const PeerConnectionInterface::RTCConfiguration& config) const {
3874 cricket::ContinualGatheringPolicy gathering_policy;
3875 // TODO(honghaiz): Add the third continual gathering policy in
3876 // PeerConnectionInterface and map it to GATHER_CONTINUALLY_AND_RECOVER.
3877 switch (config.continual_gathering_policy) {
3878 case PeerConnectionInterface::GATHER_ONCE:
3879 gathering_policy = cricket::GATHER_ONCE;
3880 break;
3881 case PeerConnectionInterface::GATHER_CONTINUALLY:
3882 gathering_policy = cricket::GATHER_CONTINUALLY;
3883 break;
3884 default:
3885 RTC_NOTREACHED();
3886 gathering_policy = cricket::GATHER_ONCE;
3887 }
3888 cricket::IceConfig ice_config;
3889 ice_config.receiving_timeout = config.ice_connection_receiving_timeout;
3890 ice_config.prioritize_most_likely_candidate_pairs =
3891 config.prioritize_most_likely_ice_candidate_pairs;
3892 ice_config.backup_connection_ping_interval =
3893 config.ice_backup_candidate_pair_ping_interval;
3894 ice_config.continual_gathering_policy = gathering_policy;
3895 ice_config.presume_writable_when_fully_relayed =
3896 config.presume_writable_when_fully_relayed;
3897 ice_config.ice_check_min_interval = config.ice_check_min_interval;
3898 ice_config.regather_all_networks_interval_range =
3899 config.ice_regather_interval_range;
3900 return ice_config;
3901}
3902
Steve Anton75737c02017-11-06 10:37:17 -08003903bool PeerConnection::GetLocalTrackIdBySsrc(uint32_t ssrc,
3904 std::string* track_id) {
3905 if (!local_description()) {
3906 return false;
3907 }
3908 return webrtc::GetTrackIdBySsrc(local_description()->description(), ssrc,
3909 track_id);
3910}
3911
3912bool PeerConnection::GetRemoteTrackIdBySsrc(uint32_t ssrc,
3913 std::string* track_id) {
3914 if (!remote_description()) {
3915 return false;
3916 }
3917 return webrtc::GetTrackIdBySsrc(remote_description()->description(), ssrc,
3918 track_id);
3919}
3920
3921bool PeerConnection::SendData(const cricket::SendDataParams& params,
3922 const rtc::CopyOnWriteBuffer& payload,
3923 cricket::SendDataResult* result) {
3924 if (!rtp_data_channel_ && !sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003925 RTC_LOG(LS_ERROR) << "SendData called when rtp_data_channel_ "
3926 << "and sctp_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08003927 return false;
3928 }
3929 return rtp_data_channel_
3930 ? rtp_data_channel_->SendData(params, payload, result)
3931 : network_thread()->Invoke<bool>(
3932 RTC_FROM_HERE,
3933 Bind(&cricket::SctpTransportInternal::SendData,
3934 sctp_transport_.get(), params, payload, result));
3935}
3936
3937bool PeerConnection::ConnectDataChannel(DataChannel* webrtc_data_channel) {
3938 if (!rtp_data_channel_ && !sctp_transport_) {
3939 // Don't log an error here, because DataChannels are expected to call
3940 // ConnectDataChannel in this state. It's the only way to initially tell
3941 // whether or not the underlying transport is ready.
3942 return false;
3943 }
3944 if (rtp_data_channel_) {
3945 rtp_data_channel_->SignalReadyToSendData.connect(
3946 webrtc_data_channel, &DataChannel::OnChannelReady);
3947 rtp_data_channel_->SignalDataReceived.connect(webrtc_data_channel,
3948 &DataChannel::OnDataReceived);
3949 } else {
3950 SignalSctpReadyToSendData.connect(webrtc_data_channel,
3951 &DataChannel::OnChannelReady);
3952 SignalSctpDataReceived.connect(webrtc_data_channel,
3953 &DataChannel::OnDataReceived);
3954 SignalSctpStreamClosedRemotely.connect(
3955 webrtc_data_channel, &DataChannel::OnStreamClosedRemotely);
3956 }
3957 return true;
3958}
3959
3960void PeerConnection::DisconnectDataChannel(DataChannel* webrtc_data_channel) {
3961 if (!rtp_data_channel_ && !sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003962 RTC_LOG(LS_ERROR)
3963 << "DisconnectDataChannel called when rtp_data_channel_ and "
3964 "sctp_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08003965 return;
3966 }
3967 if (rtp_data_channel_) {
3968 rtp_data_channel_->SignalReadyToSendData.disconnect(webrtc_data_channel);
3969 rtp_data_channel_->SignalDataReceived.disconnect(webrtc_data_channel);
3970 } else {
3971 SignalSctpReadyToSendData.disconnect(webrtc_data_channel);
3972 SignalSctpDataReceived.disconnect(webrtc_data_channel);
3973 SignalSctpStreamClosedRemotely.disconnect(webrtc_data_channel);
3974 }
3975}
3976
3977void PeerConnection::AddSctpDataStream(int sid) {
3978 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003979 RTC_LOG(LS_ERROR)
3980 << "AddSctpDataStream called when sctp_transport_ is NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08003981 return;
3982 }
3983 network_thread()->Invoke<void>(
3984 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::OpenStream,
3985 sctp_transport_.get(), sid));
3986}
3987
3988void PeerConnection::RemoveSctpDataStream(int sid) {
3989 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003990 RTC_LOG(LS_ERROR) << "RemoveSctpDataStream called when sctp_transport_ is "
3991 << "NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08003992 return;
3993 }
3994 network_thread()->Invoke<void>(
3995 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::ResetStream,
3996 sctp_transport_.get(), sid));
3997}
3998
3999bool PeerConnection::ReadyToSendData() const {
4000 return (rtp_data_channel_ && rtp_data_channel_->ready_to_send_data()) ||
4001 sctp_ready_to_send_data_;
4002}
4003
4004std::unique_ptr<SessionStats> PeerConnection::GetSessionStats_s() {
4005 RTC_DCHECK(signaling_thread()->IsCurrent());
4006 ChannelNamePairs channel_name_pairs;
4007 if (voice_channel()) {
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004008 channel_name_pairs.voice = ChannelNamePair(
4009 voice_channel()->content_name(), voice_channel()->transport_name());
Steve Anton75737c02017-11-06 10:37:17 -08004010 }
4011 if (video_channel()) {
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004012 channel_name_pairs.video = ChannelNamePair(
4013 video_channel()->content_name(), video_channel()->transport_name());
Steve Anton75737c02017-11-06 10:37:17 -08004014 }
4015 if (rtp_data_channel()) {
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004016 channel_name_pairs.data =
Steve Anton75737c02017-11-06 10:37:17 -08004017 ChannelNamePair(rtp_data_channel()->content_name(),
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004018 rtp_data_channel()->transport_name());
Steve Anton75737c02017-11-06 10:37:17 -08004019 }
4020 if (sctp_transport_) {
4021 RTC_DCHECK(sctp_content_name_);
4022 RTC_DCHECK(sctp_transport_name_);
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004023 channel_name_pairs.data =
4024 ChannelNamePair(*sctp_content_name_, *sctp_transport_name_);
Steve Anton75737c02017-11-06 10:37:17 -08004025 }
4026 return GetSessionStats(channel_name_pairs);
4027}
4028
4029std::unique_ptr<SessionStats> PeerConnection::GetSessionStats(
4030 const ChannelNamePairs& channel_name_pairs) {
4031 if (network_thread()->IsCurrent()) {
4032 return GetSessionStats_n(channel_name_pairs);
4033 }
4034 return network_thread()->Invoke<std::unique_ptr<SessionStats>>(
4035 RTC_FROM_HERE,
4036 rtc::Bind(&PeerConnection::GetSessionStats_n, this, channel_name_pairs));
4037}
4038
4039bool PeerConnection::GetLocalCertificate(
4040 const std::string& transport_name,
4041 rtc::scoped_refptr<rtc::RTCCertificate>* certificate) {
4042 return transport_controller_->GetLocalCertificate(transport_name,
4043 certificate);
4044}
4045
4046std::unique_ptr<rtc::SSLCertificate> PeerConnection::GetRemoteSSLCertificate(
4047 const std::string& transport_name) {
4048 return transport_controller_->GetRemoteSSLCertificate(transport_name);
4049}
4050
4051cricket::DataChannelType PeerConnection::data_channel_type() const {
4052 return data_channel_type_;
4053}
4054
4055bool PeerConnection::IceRestartPending(const std::string& content_name) const {
4056 return pending_ice_restarts_.find(content_name) !=
4057 pending_ice_restarts_.end();
4058}
4059
Steve Anton75737c02017-11-06 10:37:17 -08004060bool PeerConnection::NeedsIceRestart(const std::string& content_name) const {
4061 return transport_controller_->NeedsIceRestart(content_name);
4062}
4063
4064void PeerConnection::OnCertificateReady(
4065 const rtc::scoped_refptr<rtc::RTCCertificate>& certificate) {
4066 transport_controller_->SetLocalCertificate(certificate);
4067}
4068
4069void PeerConnection::OnDtlsSrtpSetupFailure(cricket::BaseChannel*, bool rtcp) {
Steve Antonf8470812017-12-04 10:46:21 -08004070 SetSessionError(SessionError::kTransport,
4071 rtcp ? kDtlsSrtpSetupFailureRtcp : kDtlsSrtpSetupFailureRtp);
Steve Anton75737c02017-11-06 10:37:17 -08004072}
4073
4074void PeerConnection::OnTransportControllerConnectionState(
4075 cricket::IceConnectionState state) {
4076 switch (state) {
4077 case cricket::kIceConnectionConnecting:
4078 // If the current state is Connected or Completed, then there were
4079 // writable channels but now there are not, so the next state must
4080 // be Disconnected.
4081 // kIceConnectionConnecting is currently used as the default,
4082 // un-connected state by the TransportController, so its only use is
4083 // detecting disconnections.
4084 if (ice_connection_state_ ==
4085 PeerConnectionInterface::kIceConnectionConnected ||
4086 ice_connection_state_ ==
4087 PeerConnectionInterface::kIceConnectionCompleted) {
4088 SetIceConnectionState(
4089 PeerConnectionInterface::kIceConnectionDisconnected);
4090 }
4091 break;
4092 case cricket::kIceConnectionFailed:
4093 SetIceConnectionState(PeerConnectionInterface::kIceConnectionFailed);
4094 break;
4095 case cricket::kIceConnectionConnected:
Mirko Bonadei675513b2017-11-09 11:09:25 +01004096 RTC_LOG(LS_INFO) << "Changing to ICE connected state because "
4097 << "all transports are writable.";
Steve Anton75737c02017-11-06 10:37:17 -08004098 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
4099 break;
4100 case cricket::kIceConnectionCompleted:
Mirko Bonadei675513b2017-11-09 11:09:25 +01004101 RTC_LOG(LS_INFO) << "Changing to ICE completed state because "
4102 << "all transports are complete.";
Steve Anton75737c02017-11-06 10:37:17 -08004103 if (ice_connection_state_ !=
4104 PeerConnectionInterface::kIceConnectionConnected) {
4105 // If jumping directly from "checking" to "connected",
4106 // signal "connected" first.
4107 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
4108 }
4109 SetIceConnectionState(PeerConnectionInterface::kIceConnectionCompleted);
4110 if (metrics_observer()) {
4111 ReportTransportStats();
4112 }
4113 break;
4114 default:
4115 RTC_NOTREACHED();
4116 }
4117}
4118
4119void PeerConnection::OnTransportControllerCandidatesGathered(
4120 const std::string& transport_name,
4121 const cricket::Candidates& candidates) {
4122 RTC_DCHECK(signaling_thread()->IsCurrent());
4123 int sdp_mline_index;
4124 if (!GetLocalCandidateMediaIndex(transport_name, &sdp_mline_index)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004125 RTC_LOG(LS_ERROR)
4126 << "OnTransportControllerCandidatesGathered: content name "
4127 << transport_name << " not found";
Steve Anton75737c02017-11-06 10:37:17 -08004128 return;
4129 }
4130
4131 for (cricket::Candidates::const_iterator citer = candidates.begin();
4132 citer != candidates.end(); ++citer) {
4133 // Use transport_name as the candidate media id.
4134 std::unique_ptr<JsepIceCandidate> candidate(
4135 new JsepIceCandidate(transport_name, sdp_mline_index, *citer));
4136 if (local_description()) {
4137 mutable_local_description()->AddCandidate(candidate.get());
4138 }
4139 OnIceCandidate(std::move(candidate));
4140 }
4141}
4142
4143void PeerConnection::OnTransportControllerCandidatesRemoved(
4144 const std::vector<cricket::Candidate>& candidates) {
4145 RTC_DCHECK(signaling_thread()->IsCurrent());
4146 // Sanity check.
4147 for (const cricket::Candidate& candidate : candidates) {
4148 if (candidate.transport_name().empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004149 RTC_LOG(LS_ERROR) << "OnTransportControllerCandidatesRemoved: "
4150 << "empty content name in candidate "
4151 << candidate.ToString();
Steve Anton75737c02017-11-06 10:37:17 -08004152 return;
4153 }
4154 }
4155
4156 if (local_description()) {
4157 mutable_local_description()->RemoveCandidates(candidates);
4158 }
4159 OnIceCandidatesRemoved(candidates);
4160}
4161
4162void PeerConnection::OnTransportControllerDtlsHandshakeError(
4163 rtc::SSLHandshakeError error) {
4164 if (metrics_observer()) {
4165 metrics_observer()->IncrementEnumCounter(
4166 webrtc::kEnumCounterDtlsHandshakeError, static_cast<int>(error),
4167 static_cast<int>(rtc::SSLHandshakeError::MAX_VALUE));
4168 }
4169}
4170
Steve Antoned10bd92017-12-05 10:52:59 -08004171void PeerConnection::EnableSending() {
4172 for (auto transceiver : transceivers_) {
4173 cricket::BaseChannel* channel = transceiver->internal()->channel();
4174 if (channel && !channel->enabled()) {
4175 channel->Enable(true);
4176 }
Steve Anton75737c02017-11-06 10:37:17 -08004177 }
4178
Steve Anton4171afb2017-11-20 10:20:22 -08004179 if (rtp_data_channel_ && !rtp_data_channel_->enabled()) {
Steve Anton75737c02017-11-06 10:37:17 -08004180 rtp_data_channel_->Enable(true);
Steve Anton4171afb2017-11-20 10:20:22 -08004181 }
Steve Anton75737c02017-11-06 10:37:17 -08004182}
4183
4184// Returns the media index for a local ice candidate given the content name.
4185bool PeerConnection::GetLocalCandidateMediaIndex(
4186 const std::string& content_name,
4187 int* sdp_mline_index) {
4188 if (!local_description() || !sdp_mline_index) {
4189 return false;
4190 }
4191
4192 bool content_found = false;
4193 const ContentInfos& contents = local_description()->description()->contents();
4194 for (size_t index = 0; index < contents.size(); ++index) {
4195 if (contents[index].name == content_name) {
4196 *sdp_mline_index = static_cast<int>(index);
4197 content_found = true;
4198 break;
4199 }
4200 }
4201 return content_found;
4202}
4203
4204bool PeerConnection::UseCandidatesInSessionDescription(
4205 const SessionDescriptionInterface* remote_desc) {
4206 if (!remote_desc) {
4207 return true;
4208 }
4209 bool ret = true;
4210
4211 for (size_t m = 0; m < remote_desc->number_of_mediasections(); ++m) {
4212 const IceCandidateCollection* candidates = remote_desc->candidates(m);
4213 for (size_t n = 0; n < candidates->count(); ++n) {
4214 const IceCandidateInterface* candidate = candidates->at(n);
4215 bool valid = false;
4216 if (!ReadyToUseRemoteCandidate(candidate, remote_desc, &valid)) {
4217 if (valid) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004218 RTC_LOG(LS_INFO)
4219 << "UseCandidatesInSessionDescription: Not ready to use "
4220 << "candidate.";
Steve Anton75737c02017-11-06 10:37:17 -08004221 }
4222 continue;
4223 }
4224 ret = UseCandidate(candidate);
4225 if (!ret) {
4226 break;
4227 }
4228 }
4229 }
4230 return ret;
4231}
4232
4233bool PeerConnection::UseCandidate(const IceCandidateInterface* candidate) {
4234 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
4235 size_t remote_content_size =
4236 remote_description()->description()->contents().size();
4237 if (mediacontent_index >= remote_content_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004238 RTC_LOG(LS_ERROR) << "UseCandidate: Invalid candidate media index.";
Steve Anton75737c02017-11-06 10:37:17 -08004239 return false;
4240 }
4241
4242 cricket::ContentInfo content =
4243 remote_description()->description()->contents()[mediacontent_index];
4244 std::vector<cricket::Candidate> candidates;
4245 candidates.push_back(candidate->candidate());
4246 // Invoking BaseSession method to handle remote candidates.
4247 std::string error;
4248 if (transport_controller_->AddRemoteCandidates(content.name, candidates,
4249 &error)) {
4250 // Candidates successfully submitted for checking.
4251 if (ice_connection_state_ == PeerConnectionInterface::kIceConnectionNew ||
4252 ice_connection_state_ ==
4253 PeerConnectionInterface::kIceConnectionDisconnected) {
4254 // If state is New, then the session has just gotten its first remote ICE
4255 // candidates, so go to Checking.
4256 // If state is Disconnected, the session is re-using old candidates or
4257 // receiving additional ones, so go to Checking.
4258 // If state is Connected, stay Connected.
4259 // TODO(bemasc): If state is Connected, and the new candidates are for a
4260 // newly added transport, then the state actually _should_ move to
4261 // checking. Add a way to distinguish that case.
4262 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
4263 }
4264 // TODO(bemasc): If state is Completed, go back to Connected.
4265 } else {
4266 if (!error.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004267 RTC_LOG(LS_WARNING) << error;
Steve Anton75737c02017-11-06 10:37:17 -08004268 }
4269 }
4270 return true;
4271}
4272
4273void PeerConnection::RemoveUnusedChannels(const SessionDescription* desc) {
Steve Anton75737c02017-11-06 10:37:17 -08004274 // Destroy video channel first since it may have a pointer to the
4275 // voice channel.
4276 const cricket::ContentInfo* video_info = cricket::GetFirstVideoContent(desc);
Steve Anton6fec8802017-12-04 10:37:29 -08004277 if (!video_info || video_info->rejected) {
4278 DestroyTransceiverChannel(GetVideoTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08004279 }
4280
Steve Anton6fec8802017-12-04 10:37:29 -08004281 const cricket::ContentInfo* audio_info = cricket::GetFirstAudioContent(desc);
4282 if (!audio_info || audio_info->rejected) {
4283 DestroyTransceiverChannel(GetAudioTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08004284 }
4285
4286 const cricket::ContentInfo* data_info = cricket::GetFirstDataContent(desc);
4287 if (!data_info || data_info->rejected) {
Steve Anton6fec8802017-12-04 10:37:29 -08004288 DestroyDataChannel();
Steve Anton75737c02017-11-06 10:37:17 -08004289 }
4290}
4291
Steve Antoneda6ccd2017-12-04 10:21:55 -08004292std::string PeerConnection::GetTransportNameForMediaSection(
4293 const std::string& mid,
4294 const cricket::ContentGroup* bundle_group) const {
4295 if (!bundle_group) {
4296 return mid;
Steve Anton75737c02017-11-06 10:37:17 -08004297 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08004298 const std::string* first_content_name = bundle_group->FirstContentName();
Steve Anton75737c02017-11-06 10:37:17 -08004299 if (!first_content_name) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004300 RTC_LOG(LS_WARNING) << "Tried to BUNDLE with no contents.";
Steve Antoneda6ccd2017-12-04 10:21:55 -08004301 return mid;
Steve Anton75737c02017-11-06 10:37:17 -08004302 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08004303 if (!bundle_group->HasContentName(mid)) {
4304 RTC_LOG(LS_WARNING) << mid << " is not part of any bundle group";
4305 return mid;
Steve Anton75737c02017-11-06 10:37:17 -08004306 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08004307 RTC_LOG(LS_INFO) << "Bundling " << mid << " on " << *first_content_name;
4308 return *first_content_name;
Steve Anton75737c02017-11-06 10:37:17 -08004309}
4310
Steve Anton8a006912017-12-04 15:25:56 -08004311RTCError PeerConnection::CreateChannels(const SessionDescription* desc) {
Steve Antoneda6ccd2017-12-04 10:21:55 -08004312 RTC_DCHECK(desc);
4313
Steve Anton75737c02017-11-06 10:37:17 -08004314 const cricket::ContentGroup* bundle_group = nullptr;
4315 if (configuration_.bundle_policy ==
4316 PeerConnectionInterface::kBundlePolicyMaxBundle) {
4317 bundle_group = desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
4318 if (!bundle_group) {
Steve Anton8a006912017-12-04 15:25:56 -08004319 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
4320 "max-bundle configured but session description "
4321 "has no BUNDLE group");
Steve Anton75737c02017-11-06 10:37:17 -08004322 }
4323 }
4324
Steve Antoneda6ccd2017-12-04 10:21:55 -08004325 // Creating the media channels and transport proxies.
4326 const cricket::ContentInfo* voice = cricket::GetFirstAudioContent(desc);
4327 if (voice && !voice->rejected &&
4328 !GetAudioTransceiver()->internal()->channel()) {
4329 cricket::VoiceChannel* voice_channel = CreateVoiceChannel(
4330 voice->name,
4331 GetTransportNameForMediaSection(voice->name, bundle_group));
4332 if (!voice_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08004333 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
4334 "Failed to create voice channel.");
Steve Antoneda6ccd2017-12-04 10:21:55 -08004335 }
4336 GetAudioTransceiver()->internal()->SetChannel(voice_channel);
4337 }
4338
Steve Anton75737c02017-11-06 10:37:17 -08004339 const cricket::ContentInfo* video = cricket::GetFirstVideoContent(desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08004340 if (video && !video->rejected &&
4341 !GetVideoTransceiver()->internal()->channel()) {
4342 cricket::VideoChannel* video_channel = CreateVideoChannel(
4343 video->name,
4344 GetTransportNameForMediaSection(video->name, bundle_group));
4345 if (!video_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08004346 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
4347 "Failed to create video channel.");
Steve Anton75737c02017-11-06 10:37:17 -08004348 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08004349 GetVideoTransceiver()->internal()->SetChannel(video_channel);
Steve Anton75737c02017-11-06 10:37:17 -08004350 }
4351
4352 const cricket::ContentInfo* data = cricket::GetFirstDataContent(desc);
4353 if (data_channel_type_ != cricket::DCT_NONE && data && !data->rejected &&
4354 !rtp_data_channel_ && !sctp_transport_) {
Steve Antoneda6ccd2017-12-04 10:21:55 -08004355 if (!CreateDataChannel(data->name, GetTransportNameForMediaSection(
4356 data->name, bundle_group))) {
Steve Anton8a006912017-12-04 15:25:56 -08004357 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
4358 "Failed to create data channel.");
Steve Anton75737c02017-11-06 10:37:17 -08004359 }
4360 }
4361
Steve Anton8a006912017-12-04 15:25:56 -08004362 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08004363}
4364
Steve Anton4171afb2017-11-20 10:20:22 -08004365// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08004366cricket::VoiceChannel* PeerConnection::CreateVoiceChannel(
4367 const std::string& mid,
4368 const std::string& transport_name) {
Steve Anton75737c02017-11-06 10:37:17 -08004369 cricket::DtlsTransportInternal* rtp_dtls_transport =
4370 transport_controller_->CreateDtlsTransport(
4371 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4372 cricket::DtlsTransportInternal* rtcp_dtls_transport = nullptr;
4373 if (configuration_.rtcp_mux_policy !=
4374 PeerConnectionInterface::kRtcpMuxPolicyRequire) {
4375 rtcp_dtls_transport = transport_controller_->CreateDtlsTransport(
4376 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
4377 }
4378
4379 cricket::VoiceChannel* voice_channel = channel_manager()->CreateVoiceChannel(
4380 call_.get(), configuration_.media_config, rtp_dtls_transport,
Steve Antoneda6ccd2017-12-04 10:21:55 -08004381 rtcp_dtls_transport, signaling_thread(), mid, SrtpRequired(),
4382 audio_options_);
Steve Anton75737c02017-11-06 10:37:17 -08004383 if (!voice_channel) {
4384 transport_controller_->DestroyDtlsTransport(
4385 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4386 if (rtcp_dtls_transport) {
4387 transport_controller_->DestroyDtlsTransport(
4388 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
4389 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08004390 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08004391 }
Steve Anton75737c02017-11-06 10:37:17 -08004392 voice_channel->SignalRtcpMuxFullyActive.connect(
4393 this, &PeerConnection::DestroyRtcpTransport_n);
4394 voice_channel->SignalDtlsSrtpSetupFailure.connect(
4395 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08004396 voice_channel->SignalSentPacket.connect(this,
4397 &PeerConnection::OnSentPacket_w);
Steve Anton4171afb2017-11-20 10:20:22 -08004398
Steve Antoneda6ccd2017-12-04 10:21:55 -08004399 return voice_channel;
Steve Anton75737c02017-11-06 10:37:17 -08004400}
4401
Steve Anton4171afb2017-11-20 10:20:22 -08004402// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08004403cricket::VideoChannel* PeerConnection::CreateVideoChannel(
4404 const std::string& mid,
4405 const std::string& transport_name) {
Steve Anton75737c02017-11-06 10:37:17 -08004406 cricket::DtlsTransportInternal* rtp_dtls_transport =
4407 transport_controller_->CreateDtlsTransport(
4408 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4409 cricket::DtlsTransportInternal* rtcp_dtls_transport = nullptr;
4410 if (configuration_.rtcp_mux_policy !=
4411 PeerConnectionInterface::kRtcpMuxPolicyRequire) {
4412 rtcp_dtls_transport = transport_controller_->CreateDtlsTransport(
4413 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
4414 }
4415
4416 cricket::VideoChannel* video_channel = channel_manager()->CreateVideoChannel(
4417 call_.get(), configuration_.media_config, rtp_dtls_transport,
Steve Antoneda6ccd2017-12-04 10:21:55 -08004418 rtcp_dtls_transport, signaling_thread(), mid, SrtpRequired(),
4419 video_options_);
Steve Anton75737c02017-11-06 10:37:17 -08004420
4421 if (!video_channel) {
4422 transport_controller_->DestroyDtlsTransport(
4423 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4424 if (rtcp_dtls_transport) {
4425 transport_controller_->DestroyDtlsTransport(
4426 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
4427 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08004428 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08004429 }
Steve Anton75737c02017-11-06 10:37:17 -08004430 video_channel->SignalRtcpMuxFullyActive.connect(
4431 this, &PeerConnection::DestroyRtcpTransport_n);
4432 video_channel->SignalDtlsSrtpSetupFailure.connect(
4433 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08004434 video_channel->SignalSentPacket.connect(this,
4435 &PeerConnection::OnSentPacket_w);
Steve Anton4171afb2017-11-20 10:20:22 -08004436
Steve Antoneda6ccd2017-12-04 10:21:55 -08004437 return video_channel;
Steve Anton75737c02017-11-06 10:37:17 -08004438}
4439
Steve Antoneda6ccd2017-12-04 10:21:55 -08004440bool PeerConnection::CreateDataChannel(const std::string& mid,
4441 const std::string& transport_name) {
Steve Anton75737c02017-11-06 10:37:17 -08004442 bool sctp = (data_channel_type_ == cricket::DCT_SCTP);
4443 if (sctp) {
4444 if (!sctp_factory_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004445 RTC_LOG(LS_ERROR)
Steve Anton75737c02017-11-06 10:37:17 -08004446 << "Trying to create SCTP transport, but didn't compile with "
4447 "SCTP support (HAVE_SCTP)";
4448 return false;
4449 }
4450 if (!network_thread()->Invoke<bool>(
4451 RTC_FROM_HERE, rtc::Bind(&PeerConnection::CreateSctpTransport_n,
Steve Antoneda6ccd2017-12-04 10:21:55 -08004452 this, mid, transport_name))) {
Steve Anton75737c02017-11-06 10:37:17 -08004453 return false;
4454 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08004455 for (const auto& channel : sctp_data_channels_) {
4456 channel->OnTransportChannelCreated();
4457 }
Steve Anton75737c02017-11-06 10:37:17 -08004458 } else {
Steve Anton75737c02017-11-06 10:37:17 -08004459 cricket::DtlsTransportInternal* rtp_dtls_transport =
4460 transport_controller_->CreateDtlsTransport(
4461 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4462 cricket::DtlsTransportInternal* rtcp_dtls_transport = nullptr;
4463 if (configuration_.rtcp_mux_policy !=
4464 PeerConnectionInterface::kRtcpMuxPolicyRequire) {
4465 rtcp_dtls_transport = transport_controller_->CreateDtlsTransport(
4466 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
4467 }
4468
4469 rtp_data_channel_ = channel_manager()->CreateRtpDataChannel(
4470 configuration_.media_config, rtp_dtls_transport, rtcp_dtls_transport,
Steve Antoneda6ccd2017-12-04 10:21:55 -08004471 signaling_thread(), mid, SrtpRequired());
Steve Anton75737c02017-11-06 10:37:17 -08004472
4473 if (!rtp_data_channel_) {
4474 transport_controller_->DestroyDtlsTransport(
4475 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4476 if (rtcp_dtls_transport) {
4477 transport_controller_->DestroyDtlsTransport(
4478 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
4479 }
4480 return false;
4481 }
4482
4483 rtp_data_channel_->SignalRtcpMuxFullyActive.connect(
4484 this, &PeerConnection::DestroyRtcpTransport_n);
4485 rtp_data_channel_->SignalDtlsSrtpSetupFailure.connect(
4486 this, &PeerConnection::OnDtlsSrtpSetupFailure);
4487 rtp_data_channel_->SignalSentPacket.connect(
4488 this, &PeerConnection::OnSentPacket_w);
4489 }
4490
Steve Anton75737c02017-11-06 10:37:17 -08004491 return true;
4492}
4493
4494Call::Stats PeerConnection::GetCallStats() {
4495 if (!worker_thread()->IsCurrent()) {
4496 return worker_thread()->Invoke<Call::Stats>(
4497 RTC_FROM_HERE, rtc::Bind(&PeerConnection::GetCallStats, this));
4498 }
4499 if (call_) {
4500 return call_->GetStats();
4501 } else {
4502 return Call::Stats();
4503 }
4504}
4505
4506std::unique_ptr<SessionStats> PeerConnection::GetSessionStats_n(
4507 const ChannelNamePairs& channel_name_pairs) {
4508 RTC_DCHECK(network_thread()->IsCurrent());
4509 std::unique_ptr<SessionStats> session_stats(new SessionStats());
4510 for (const auto channel_name_pair :
4511 {&channel_name_pairs.voice, &channel_name_pairs.video,
4512 &channel_name_pairs.data}) {
4513 if (*channel_name_pair) {
4514 cricket::TransportStats transport_stats;
4515 if (!transport_controller_->GetStats((*channel_name_pair)->transport_name,
4516 &transport_stats)) {
4517 return nullptr;
4518 }
Steve Anton75737c02017-11-06 10:37:17 -08004519 session_stats->transport_stats[(*channel_name_pair)->transport_name] =
4520 std::move(transport_stats);
4521 }
4522 }
4523 return session_stats;
4524}
4525
4526bool PeerConnection::CreateSctpTransport_n(const std::string& content_name,
4527 const std::string& transport_name) {
4528 RTC_DCHECK(network_thread()->IsCurrent());
4529 RTC_DCHECK(sctp_factory_);
4530 cricket::DtlsTransportInternal* tc =
4531 transport_controller_->CreateDtlsTransport_n(
4532 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4533 sctp_transport_ = sctp_factory_->CreateSctpTransport(tc);
4534 RTC_DCHECK(sctp_transport_);
4535 sctp_invoker_.reset(new rtc::AsyncInvoker());
4536 sctp_transport_->SignalReadyToSendData.connect(
4537 this, &PeerConnection::OnSctpTransportReadyToSendData_n);
4538 sctp_transport_->SignalDataReceived.connect(
4539 this, &PeerConnection::OnSctpTransportDataReceived_n);
4540 sctp_transport_->SignalStreamClosedRemotely.connect(
4541 this, &PeerConnection::OnSctpStreamClosedRemotely_n);
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004542 sctp_transport_name_ = transport_name;
4543 sctp_content_name_ = content_name;
Steve Anton75737c02017-11-06 10:37:17 -08004544 return true;
4545}
4546
4547void PeerConnection::ChangeSctpTransport_n(const std::string& transport_name) {
4548 RTC_DCHECK(network_thread()->IsCurrent());
4549 RTC_DCHECK(sctp_transport_);
4550 RTC_DCHECK(sctp_transport_name_);
4551 std::string old_sctp_transport_name = *sctp_transport_name_;
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004552 sctp_transport_name_ = transport_name;
Steve Anton75737c02017-11-06 10:37:17 -08004553 cricket::DtlsTransportInternal* tc =
4554 transport_controller_->CreateDtlsTransport_n(
4555 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4556 sctp_transport_->SetTransportChannel(tc);
4557 transport_controller_->DestroyDtlsTransport_n(
4558 old_sctp_transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4559}
4560
4561void PeerConnection::DestroySctpTransport_n() {
4562 RTC_DCHECK(network_thread()->IsCurrent());
4563 sctp_transport_.reset(nullptr);
4564 sctp_content_name_.reset();
4565 sctp_transport_name_.reset();
4566 sctp_invoker_.reset(nullptr);
4567 sctp_ready_to_send_data_ = false;
4568}
4569
4570void PeerConnection::OnSctpTransportReadyToSendData_n() {
4571 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
4572 RTC_DCHECK(network_thread()->IsCurrent());
4573 // Note: Cannot use rtc::Bind here because it will grab a reference to
4574 // PeerConnection and potentially cause PeerConnection to live longer than
4575 // expected. It is safe not to grab a reference since the sctp_invoker_ will
4576 // be destroyed before PeerConnection is destroyed, and at that point all
4577 // pending tasks will be cleared.
4578 sctp_invoker_->AsyncInvoke<void>(RTC_FROM_HERE, signaling_thread(), [this] {
4579 OnSctpTransportReadyToSendData_s(true);
4580 });
4581}
4582
4583void PeerConnection::OnSctpTransportReadyToSendData_s(bool ready) {
4584 RTC_DCHECK(signaling_thread()->IsCurrent());
4585 sctp_ready_to_send_data_ = ready;
4586 SignalSctpReadyToSendData(ready);
4587}
4588
4589void PeerConnection::OnSctpTransportDataReceived_n(
4590 const cricket::ReceiveDataParams& params,
4591 const rtc::CopyOnWriteBuffer& payload) {
4592 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
4593 RTC_DCHECK(network_thread()->IsCurrent());
4594 // Note: Cannot use rtc::Bind here because it will grab a reference to
4595 // PeerConnection and potentially cause PeerConnection to live longer than
4596 // expected. It is safe not to grab a reference since the sctp_invoker_ will
4597 // be destroyed before PeerConnection is destroyed, and at that point all
4598 // pending tasks will be cleared.
4599 sctp_invoker_->AsyncInvoke<void>(
4600 RTC_FROM_HERE, signaling_thread(), [this, params, payload] {
4601 OnSctpTransportDataReceived_s(params, payload);
4602 });
4603}
4604
4605void PeerConnection::OnSctpTransportDataReceived_s(
4606 const cricket::ReceiveDataParams& params,
4607 const rtc::CopyOnWriteBuffer& payload) {
4608 RTC_DCHECK(signaling_thread()->IsCurrent());
4609 if (params.type == cricket::DMT_CONTROL && IsOpenMessage(payload)) {
4610 // Received OPEN message; parse and signal that a new data channel should
4611 // be created.
4612 std::string label;
4613 InternalDataChannelInit config;
4614 config.id = params.ssrc;
4615 if (!ParseDataChannelOpenMessage(payload, &label, &config)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004616 RTC_LOG(LS_WARNING) << "Failed to parse the OPEN message for sid "
4617 << params.ssrc;
Steve Anton75737c02017-11-06 10:37:17 -08004618 return;
4619 }
4620 config.open_handshake_role = InternalDataChannelInit::kAcker;
4621 OnDataChannelOpenMessage(label, config);
4622 } else {
4623 // Otherwise just forward the signal.
4624 SignalSctpDataReceived(params, payload);
4625 }
4626}
4627
4628void PeerConnection::OnSctpStreamClosedRemotely_n(int sid) {
4629 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
4630 RTC_DCHECK(network_thread()->IsCurrent());
4631 sctp_invoker_->AsyncInvoke<void>(
4632 RTC_FROM_HERE, signaling_thread(),
4633 rtc::Bind(&sigslot::signal1<int>::operator(),
4634 &SignalSctpStreamClosedRemotely, sid));
4635}
4636
4637// Returns false if bundle is enabled and rtcp_mux is disabled.
4638bool PeerConnection::ValidateBundleSettings(const SessionDescription* desc) {
4639 bool bundle_enabled = desc->HasGroup(cricket::GROUP_TYPE_BUNDLE);
4640 if (!bundle_enabled)
4641 return true;
4642
4643 const cricket::ContentGroup* bundle_group =
4644 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
4645 RTC_DCHECK(bundle_group != NULL);
4646
4647 const cricket::ContentInfos& contents = desc->contents();
4648 for (cricket::ContentInfos::const_iterator citer = contents.begin();
4649 citer != contents.end(); ++citer) {
4650 const cricket::ContentInfo* content = (&*citer);
4651 RTC_DCHECK(content != NULL);
4652 if (bundle_group->HasContentName(content->name) && !content->rejected &&
Steve Anton5adfafd2017-12-20 16:34:00 -08004653 content->type == MediaProtocolType::kRtp) {
Steve Anton75737c02017-11-06 10:37:17 -08004654 if (!HasRtcpMuxEnabled(content))
4655 return false;
4656 }
4657 }
4658 // RTCP-MUX is enabled in all the contents.
4659 return true;
4660}
4661
4662bool PeerConnection::HasRtcpMuxEnabled(const cricket::ContentInfo* content) {
Steve Antonb1c1de12017-12-21 15:14:30 -08004663 return content->media_description()->rtcp_mux();
Steve Anton75737c02017-11-06 10:37:17 -08004664}
4665
Steve Anton8a006912017-12-04 15:25:56 -08004666RTCError PeerConnection::ValidateSessionDescription(
Steve Anton75737c02017-11-06 10:37:17 -08004667 const SessionDescriptionInterface* sdesc,
Steve Anton8a006912017-12-04 15:25:56 -08004668 cricket::ContentSource source) {
Steve Antonf8470812017-12-04 10:46:21 -08004669 if (session_error() != SessionError::kNone) {
Steve Anton8a006912017-12-04 15:25:56 -08004670 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
Steve Anton75737c02017-11-06 10:37:17 -08004671 }
4672
4673 if (!sdesc || !sdesc->description()) {
Steve Anton8a006912017-12-04 15:25:56 -08004674 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidSdp);
Steve Anton75737c02017-11-06 10:37:17 -08004675 }
4676
Steve Anton3828c062017-12-06 10:34:51 -08004677 SdpType type = sdesc->GetType();
4678 if ((source == cricket::CS_LOCAL && !ExpectSetLocalDescription(type)) ||
4679 (source == cricket::CS_REMOTE && !ExpectSetRemoteDescription(type))) {
Steve Anton8a006912017-12-04 15:25:56 -08004680 LOG_AND_RETURN_ERROR(
4681 RTCErrorType::INVALID_PARAMETER,
4682 "Called in wrong state: " + GetSignalingStateString(signaling_state()));
Steve Anton75737c02017-11-06 10:37:17 -08004683 }
4684
4685 // Verify crypto settings.
4686 std::string crypto_error;
Steve Anton8a006912017-12-04 15:25:56 -08004687 if (webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED ||
4688 dtls_enabled_) {
4689 RTCError crypto_error = VerifyCrypto(sdesc->description(), dtls_enabled_);
4690 if (!crypto_error.ok()) {
4691 return crypto_error;
4692 }
Steve Anton75737c02017-11-06 10:37:17 -08004693 }
4694
4695 // Verify ice-ufrag and ice-pwd.
4696 if (!VerifyIceUfragPwdPresent(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08004697 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
4698 kSdpWithoutIceUfragPwd);
Steve Anton75737c02017-11-06 10:37:17 -08004699 }
4700
4701 if (!ValidateBundleSettings(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08004702 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
4703 kBundleWithoutRtcpMux);
Steve Anton75737c02017-11-06 10:37:17 -08004704 }
4705
4706 // TODO(skvlad): When the local rtcp-mux policy is Require, reject any
4707 // m-lines that do not rtcp-mux enabled.
4708
4709 // Verify m-lines in Answer when compared against Offer.
Steve Anton3828c062017-12-06 10:34:51 -08004710 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Anton75737c02017-11-06 10:37:17 -08004711 const cricket::SessionDescription* offer_desc =
4712 (source == cricket::CS_LOCAL) ? remote_description()->description()
4713 : local_description()->description();
4714 if (!MediaSectionsHaveSameCount(offer_desc, sdesc->description()) ||
4715 !MediaSectionsInSameOrder(offer_desc, sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08004716 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
4717 kMlineMismatchInAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08004718 }
4719 } else {
4720 const cricket::SessionDescription* current_desc = nullptr;
4721 if (source == cricket::CS_LOCAL && local_description()) {
4722 current_desc = local_description()->description();
4723 } else if (source == cricket::CS_REMOTE && remote_description()) {
4724 current_desc = remote_description()->description();
4725 }
4726 // The re-offers should respect the order of m= sections in current
4727 // description. See RFC3264 Section 8 paragraph 4 for more details.
4728 if (current_desc &&
4729 !MediaSectionsInSameOrder(current_desc, sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08004730 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
4731 kMlineMismatchInSubsequentOffer);
Steve Anton75737c02017-11-06 10:37:17 -08004732 }
4733 }
4734
Steve Anton8a006912017-12-04 15:25:56 -08004735 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08004736}
4737
Steve Anton3828c062017-12-06 10:34:51 -08004738bool PeerConnection::ExpectSetLocalDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08004739 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08004740 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08004741 return (state == PeerConnectionInterface::kStable) ||
4742 (state == PeerConnectionInterface::kHaveLocalOffer);
Steve Anton20393062017-12-04 16:24:52 -08004743 } else {
Steve Anton3828c062017-12-06 10:34:51 -08004744 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08004745 return (state == PeerConnectionInterface::kHaveRemoteOffer) ||
4746 (state == PeerConnectionInterface::kHaveLocalPrAnswer);
4747 }
4748}
4749
Steve Anton3828c062017-12-06 10:34:51 -08004750bool PeerConnection::ExpectSetRemoteDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08004751 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08004752 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08004753 return (state == PeerConnectionInterface::kStable) ||
4754 (state == PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton20393062017-12-04 16:24:52 -08004755 } else {
Steve Anton3828c062017-12-06 10:34:51 -08004756 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08004757 return (state == PeerConnectionInterface::kHaveLocalOffer) ||
4758 (state == PeerConnectionInterface::kHaveRemotePrAnswer);
4759 }
4760}
4761
Steve Antonf8470812017-12-04 10:46:21 -08004762const char* PeerConnection::SessionErrorToString(SessionError error) const {
4763 switch (error) {
4764 case SessionError::kNone:
4765 return "ERROR_NONE";
4766 case SessionError::kContent:
4767 return "ERROR_CONTENT";
4768 case SessionError::kTransport:
4769 return "ERROR_TRANSPORT";
4770 }
4771 RTC_NOTREACHED();
4772 return "";
4773}
4774
Steve Anton75737c02017-11-06 10:37:17 -08004775std::string PeerConnection::GetSessionErrorMsg() {
4776 std::ostringstream desc;
Steve Antonf8470812017-12-04 10:46:21 -08004777 desc << kSessionError << SessionErrorToString(session_error()) << ". ";
4778 desc << kSessionErrorDesc << session_error_desc() << ".";
Steve Anton75737c02017-11-06 10:37:17 -08004779 return desc.str();
4780}
4781
4782// We need to check the local/remote description for the Transport instead of
4783// the session, because a new Transport added during renegotiation may have
4784// them unset while the session has them set from the previous negotiation.
4785// Not doing so may trigger the auto generation of transport description and
4786// mess up DTLS identity information, ICE credential, etc.
4787bool PeerConnection::ReadyToUseRemoteCandidate(
4788 const IceCandidateInterface* candidate,
4789 const SessionDescriptionInterface* remote_desc,
4790 bool* valid) {
4791 *valid = true;
4792
4793 const SessionDescriptionInterface* current_remote_desc =
4794 remote_desc ? remote_desc : remote_description();
4795
4796 if (!current_remote_desc) {
4797 return false;
4798 }
4799
4800 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
4801 size_t remote_content_size =
4802 current_remote_desc->description()->contents().size();
4803 if (mediacontent_index >= remote_content_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004804 RTC_LOG(LS_ERROR)
4805 << "ReadyToUseRemoteCandidate: Invalid candidate media index "
4806 << mediacontent_index;
Steve Anton75737c02017-11-06 10:37:17 -08004807
4808 *valid = false;
4809 return false;
4810 }
4811
4812 cricket::ContentInfo content =
4813 current_remote_desc->description()->contents()[mediacontent_index];
4814
4815 const std::string transport_name = GetTransportName(content.name);
4816 if (transport_name.empty()) {
4817 return false;
4818 }
4819 return transport_controller_->ReadyForRemoteCandidates(transport_name);
4820}
4821
4822bool PeerConnection::SrtpRequired() const {
4823 return dtls_enabled_ ||
4824 webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED;
4825}
4826
4827void PeerConnection::OnTransportControllerGatheringState(
4828 cricket::IceGatheringState state) {
4829 RTC_DCHECK(signaling_thread()->IsCurrent());
4830 if (state == cricket::kIceGatheringGathering) {
4831 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringGathering);
4832 } else if (state == cricket::kIceGatheringComplete) {
4833 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringComplete);
4834 }
4835}
4836
4837void PeerConnection::ReportTransportStats() {
4838 // Use a set so we don't report the same stats twice if two channels share
4839 // a transport.
4840 std::set<std::string> transport_names;
4841 if (voice_channel()) {
4842 transport_names.insert(voice_channel()->transport_name());
4843 }
4844 if (video_channel()) {
4845 transport_names.insert(video_channel()->transport_name());
4846 }
4847 if (rtp_data_channel()) {
4848 transport_names.insert(rtp_data_channel()->transport_name());
4849 }
4850 if (sctp_transport_name_) {
4851 transport_names.insert(*sctp_transport_name_);
4852 }
4853 for (const auto& name : transport_names) {
4854 cricket::TransportStats stats;
4855 if (transport_controller_->GetStats(name, &stats)) {
4856 ReportBestConnectionState(stats);
4857 ReportNegotiatedCiphers(stats);
4858 }
4859 }
4860}
4861// Walk through the ConnectionInfos to gather best connection usage
4862// for IPv4 and IPv6.
4863void PeerConnection::ReportBestConnectionState(
4864 const cricket::TransportStats& stats) {
4865 RTC_DCHECK(metrics_observer());
4866 for (cricket::TransportChannelStatsList::const_iterator it =
4867 stats.channel_stats.begin();
4868 it != stats.channel_stats.end(); ++it) {
4869 for (cricket::ConnectionInfos::const_iterator it_info =
4870 it->connection_infos.begin();
4871 it_info != it->connection_infos.end(); ++it_info) {
4872 if (!it_info->best_connection) {
4873 continue;
4874 }
4875
4876 PeerConnectionEnumCounterType type = kPeerConnectionEnumCounterMax;
4877 const cricket::Candidate& local = it_info->local_candidate;
4878 const cricket::Candidate& remote = it_info->remote_candidate;
4879
4880 // Increment the counter for IceCandidatePairType.
4881 if (local.protocol() == cricket::TCP_PROTOCOL_NAME ||
4882 (local.type() == RELAY_PORT_TYPE &&
4883 local.relay_protocol() == cricket::TCP_PROTOCOL_NAME)) {
4884 type = kEnumCounterIceCandidatePairTypeTcp;
4885 } else if (local.protocol() == cricket::UDP_PROTOCOL_NAME) {
4886 type = kEnumCounterIceCandidatePairTypeUdp;
4887 } else {
4888 RTC_CHECK(0);
4889 }
4890 metrics_observer()->IncrementEnumCounter(
4891 type, GetIceCandidatePairCounter(local, remote),
4892 kIceCandidatePairMax);
4893
4894 // Increment the counter for IP type.
4895 if (local.address().family() == AF_INET) {
4896 metrics_observer()->IncrementEnumCounter(
4897 kEnumCounterAddressFamily, kBestConnections_IPv4,
4898 kPeerConnectionAddressFamilyCounter_Max);
4899
4900 } else if (local.address().family() == AF_INET6) {
4901 metrics_observer()->IncrementEnumCounter(
4902 kEnumCounterAddressFamily, kBestConnections_IPv6,
4903 kPeerConnectionAddressFamilyCounter_Max);
4904 } else {
4905 RTC_CHECK(0);
4906 }
4907
4908 return;
4909 }
4910 }
4911}
4912
4913void PeerConnection::ReportNegotiatedCiphers(
4914 const cricket::TransportStats& stats) {
4915 RTC_DCHECK(metrics_observer());
4916 if (!dtls_enabled_ || stats.channel_stats.empty()) {
4917 return;
4918 }
4919
4920 int srtp_crypto_suite = stats.channel_stats[0].srtp_crypto_suite;
4921 int ssl_cipher_suite = stats.channel_stats[0].ssl_cipher_suite;
4922 if (srtp_crypto_suite == rtc::SRTP_INVALID_CRYPTO_SUITE &&
4923 ssl_cipher_suite == rtc::TLS_NULL_WITH_NULL_NULL) {
4924 return;
4925 }
4926
4927 PeerConnectionEnumCounterType srtp_counter_type;
4928 PeerConnectionEnumCounterType ssl_counter_type;
4929 if (stats.transport_name == cricket::CN_AUDIO) {
4930 srtp_counter_type = kEnumCounterAudioSrtpCipher;
4931 ssl_counter_type = kEnumCounterAudioSslCipher;
4932 } else if (stats.transport_name == cricket::CN_VIDEO) {
4933 srtp_counter_type = kEnumCounterVideoSrtpCipher;
4934 ssl_counter_type = kEnumCounterVideoSslCipher;
4935 } else if (stats.transport_name == cricket::CN_DATA) {
4936 srtp_counter_type = kEnumCounterDataSrtpCipher;
4937 ssl_counter_type = kEnumCounterDataSslCipher;
4938 } else {
4939 RTC_NOTREACHED();
4940 return;
4941 }
4942
4943 if (srtp_crypto_suite != rtc::SRTP_INVALID_CRYPTO_SUITE) {
4944 metrics_observer()->IncrementSparseEnumCounter(srtp_counter_type,
4945 srtp_crypto_suite);
4946 }
4947 if (ssl_cipher_suite != rtc::TLS_NULL_WITH_NULL_NULL) {
4948 metrics_observer()->IncrementSparseEnumCounter(ssl_counter_type,
4949 ssl_cipher_suite);
4950 }
4951}
4952
4953void PeerConnection::OnSentPacket_w(const rtc::SentPacket& sent_packet) {
4954 RTC_DCHECK(worker_thread()->IsCurrent());
4955 RTC_DCHECK(call_);
4956 call_->OnSentPacket(sent_packet);
4957}
4958
4959const std::string PeerConnection::GetTransportName(
4960 const std::string& content_name) {
4961 cricket::BaseChannel* channel = GetChannel(content_name);
Steve Anton6fec8802017-12-04 10:37:29 -08004962 if (channel) {
4963 return channel->transport_name();
Steve Anton75737c02017-11-06 10:37:17 -08004964 }
Steve Anton6fec8802017-12-04 10:37:29 -08004965 if (sctp_transport_) {
4966 RTC_DCHECK(sctp_content_name_);
4967 RTC_DCHECK(sctp_transport_name_);
4968 if (content_name == *sctp_content_name_) {
4969 return *sctp_transport_name_;
4970 }
4971 }
4972 // Return an empty string if failed to retrieve the transport name.
4973 return "";
Steve Anton75737c02017-11-06 10:37:17 -08004974}
4975
4976void PeerConnection::DestroyRtcpTransport_n(const std::string& transport_name) {
4977 RTC_DCHECK(network_thread()->IsCurrent());
4978 transport_controller_->DestroyDtlsTransport_n(
4979 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
4980}
4981
Steve Anton6fec8802017-12-04 10:37:29 -08004982void PeerConnection::DestroyTransceiverChannel(
4983 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
4984 transceiver) {
4985 RTC_DCHECK(transceiver);
Steve Anton75737c02017-11-06 10:37:17 -08004986
Steve Anton6fec8802017-12-04 10:37:29 -08004987 cricket::BaseChannel* channel = transceiver->internal()->channel();
4988 if (channel) {
4989 transceiver->internal()->SetChannel(nullptr);
4990 DestroyBaseChannel(channel);
Steve Anton75737c02017-11-06 10:37:17 -08004991 }
4992}
4993
4994void PeerConnection::DestroyDataChannel() {
Steve Anton6fec8802017-12-04 10:37:29 -08004995 if (rtp_data_channel_) {
4996 OnDataChannelDestroyed();
4997 DestroyBaseChannel(rtp_data_channel_);
4998 rtp_data_channel_ = nullptr;
4999 }
5000
5001 // Note: Cannot use rtc::Bind to create a functor to invoke because it will
5002 // grab a reference to this PeerConnection. If this is called from the
5003 // PeerConnection destructor, the RefCountedObject vtable will have already
5004 // been destroyed (since it is a subclass of PeerConnection) and using
5005 // rtc::Bind will cause "Pure virtual function called" error to appear.
5006
5007 if (sctp_transport_) {
5008 OnDataChannelDestroyed();
5009 network_thread()->Invoke<void>(RTC_FROM_HERE,
5010 [this] { DestroySctpTransport_n(); });
5011 }
5012}
5013
5014void PeerConnection::DestroyBaseChannel(cricket::BaseChannel* channel) {
5015 RTC_DCHECK(channel);
5016 RTC_DCHECK(channel->rtp_dtls_transport());
5017
5018 // Need to cache these before destroying the base channel so that we do not
5019 // access uninitialized memory.
5020 const std::string transport_name =
5021 channel->rtp_dtls_transport()->transport_name();
5022 const bool need_to_delete_rtcp = (channel->rtcp_dtls_transport() != nullptr);
5023
5024 switch (channel->media_type()) {
5025 case cricket::MEDIA_TYPE_AUDIO:
5026 channel_manager()->DestroyVoiceChannel(
5027 static_cast<cricket::VoiceChannel*>(channel));
5028 break;
5029 case cricket::MEDIA_TYPE_VIDEO:
5030 channel_manager()->DestroyVideoChannel(
5031 static_cast<cricket::VideoChannel*>(channel));
5032 break;
5033 case cricket::MEDIA_TYPE_DATA:
5034 channel_manager()->DestroyRtpDataChannel(
5035 static_cast<cricket::RtpDataChannel*>(channel));
5036 break;
5037 default:
5038 RTC_NOTREACHED() << "Unknown media type: " << channel->media_type();
5039 break;
5040 }
5041
5042 // |channel| can no longer be used.
5043
Steve Anton75737c02017-11-06 10:37:17 -08005044 transport_controller_->DestroyDtlsTransport(
5045 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5046 if (need_to_delete_rtcp) {
5047 transport_controller_->DestroyDtlsTransport(
5048 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
5049 }
5050}
5051
henrike@webrtc.org28e20752013-07-10 00:45:36 +00005052} // namespace webrtc