blob: c9e25909e26de26e99547081cb26c56f4cf7d5cb [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 =
337 static_cast<const MediaContentDescription*>(
338 new_desc->contents()[i].description);
339 const MediaContentDescription* existing_desc_mdesc =
340 static_cast<const MediaContentDescription*>(
341 existing_desc->contents()[i].description);
342 if (new_desc_mdesc->type() != existing_desc_mdesc->type()) {
343 return false;
344 }
345 }
346 return true;
347}
348
349bool MediaSectionsHaveSameCount(const SessionDescription* desc1,
350 const SessionDescription* desc2) {
351 if (!desc1 || !desc2) {
352 return false;
353 }
354 return desc1->contents().size() == desc2->contents().size();
355}
356
357// Checks that each non-rejected content has SDES crypto keys or a DTLS
358// fingerprint, unless it's in a BUNDLE group, in which case only the
359// BUNDLE-tag section (first media section/description in the BUNDLE group)
360// needs a ufrag and pwd. Mismatches, such as replying with a DTLS fingerprint
361// to SDES keys, will be caught in JsepTransport negotiation, and backstopped
362// by Channel's |srtp_required| check.
Steve Anton8a006912017-12-04 15:25:56 -0800363RTCError VerifyCrypto(const SessionDescription* desc, bool dtls_enabled) {
Steve Anton75737c02017-11-06 10:37:17 -0800364 const cricket::ContentGroup* bundle =
365 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton8a006912017-12-04 15:25:56 -0800366 for (const cricket::ContentInfo& content_info : desc->contents()) {
367 if (content_info.rejected) {
Steve Anton75737c02017-11-06 10:37:17 -0800368 continue;
369 }
Steve Anton8a006912017-12-04 15:25:56 -0800370 const std::string& mid = content_info.name;
371 if (bundle && bundle->HasContentName(mid) &&
372 mid != *(bundle->FirstContentName())) {
Steve Anton75737c02017-11-06 10:37:17 -0800373 // This isn't the first media section in the BUNDLE group, so it's not
374 // required to have crypto attributes, since only the crypto attributes
375 // from the first section actually get used.
376 continue;
377 }
378
379 // If the content isn't rejected or bundled into another m= section, crypto
380 // must be present.
381 const MediaContentDescription* media =
Steve Anton8a006912017-12-04 15:25:56 -0800382 static_cast<const MediaContentDescription*>(content_info.description);
383 const TransportInfo* tinfo = desc->GetTransportInfoByName(mid);
Steve Anton75737c02017-11-06 10:37:17 -0800384 if (!media || !tinfo) {
385 // Something is not right.
Steve Anton8a006912017-12-04 15:25:56 -0800386 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidSdp);
Steve Anton75737c02017-11-06 10:37:17 -0800387 }
388 if (dtls_enabled) {
389 if (!tinfo->description.identity_fingerprint) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100390 RTC_LOG(LS_WARNING)
391 << "Session description must have DTLS fingerprint if "
392 "DTLS enabled.";
Steve Anton8a006912017-12-04 15:25:56 -0800393 return RTCError(RTCErrorType::INVALID_PARAMETER,
394 kSdpWithoutDtlsFingerprint);
Steve Anton75737c02017-11-06 10:37:17 -0800395 }
396 } else {
397 if (media->cryptos().empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100398 RTC_LOG(LS_WARNING)
Steve Anton75737c02017-11-06 10:37:17 -0800399 << "Session description must have SDES when DTLS disabled.";
Steve Anton8a006912017-12-04 15:25:56 -0800400 return RTCError(RTCErrorType::INVALID_PARAMETER, kSdpWithoutSdesCrypto);
Steve Anton75737c02017-11-06 10:37:17 -0800401 }
402 }
403 }
Steve Anton8a006912017-12-04 15:25:56 -0800404 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -0800405}
406
407// Checks that each non-rejected content has ice-ufrag and ice-pwd set, unless
408// it's in a BUNDLE group, in which case only the BUNDLE-tag section (first
409// media section/description in the BUNDLE group) needs a ufrag and pwd.
410bool VerifyIceUfragPwdPresent(const SessionDescription* desc) {
411 const cricket::ContentGroup* bundle =
412 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton8a006912017-12-04 15:25:56 -0800413 for (const cricket::ContentInfo& content_info : desc->contents()) {
414 if (content_info.rejected) {
Steve Anton75737c02017-11-06 10:37:17 -0800415 continue;
416 }
Steve Anton8a006912017-12-04 15:25:56 -0800417 const std::string& mid = content_info.name;
418 if (bundle && bundle->HasContentName(mid) &&
419 mid != *(bundle->FirstContentName())) {
Steve Anton75737c02017-11-06 10:37:17 -0800420 // This isn't the first media section in the BUNDLE group, so it's not
421 // required to have ufrag/password, since only the ufrag/password from
422 // the first section actually get used.
423 continue;
424 }
425
426 // If the content isn't rejected or bundled into another m= section,
427 // ice-ufrag and ice-pwd must be present.
Steve Anton8a006912017-12-04 15:25:56 -0800428 const TransportInfo* tinfo = desc->GetTransportInfoByName(mid);
Steve Anton75737c02017-11-06 10:37:17 -0800429 if (!tinfo) {
430 // Something is not right.
Mirko Bonadei675513b2017-11-09 11:09:25 +0100431 RTC_LOG(LS_ERROR) << kInvalidSdp;
Steve Anton75737c02017-11-06 10:37:17 -0800432 return false;
433 }
434 if (tinfo->description.ice_ufrag.empty() ||
435 tinfo->description.ice_pwd.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100436 RTC_LOG(LS_ERROR) << "Session description must have ice ufrag and pwd.";
Steve Anton75737c02017-11-06 10:37:17 -0800437 return false;
438 }
439 }
440 return true;
441}
442
443bool GetTrackIdBySsrc(const SessionDescription* session_description,
444 uint32_t ssrc,
445 std::string* track_id) {
446 RTC_DCHECK(track_id != NULL);
447
448 const cricket::ContentInfo* audio_info =
449 cricket::GetFirstAudioContent(session_description);
450 if (audio_info) {
451 const cricket::MediaContentDescription* audio_content =
452 static_cast<const cricket::MediaContentDescription*>(
453 audio_info->description);
454
455 const auto* found =
456 cricket::GetStreamBySsrc(audio_content->streams(), ssrc);
457 if (found) {
458 *track_id = found->id;
459 return true;
460 }
461 }
462
463 const cricket::ContentInfo* video_info =
464 cricket::GetFirstVideoContent(session_description);
465 if (video_info) {
466 const cricket::MediaContentDescription* video_content =
467 static_cast<const cricket::MediaContentDescription*>(
468 video_info->description);
469
470 const auto* found =
471 cricket::GetStreamBySsrc(video_content->streams(), ssrc);
472 if (found) {
473 *track_id = found->id;
474 return true;
475 }
476 }
477 return false;
478}
479
480// Get the SCTP port out of a SessionDescription.
481// Return -1 if not found.
482int GetSctpPort(const SessionDescription* session_description) {
483 const ContentInfo* content_info = GetFirstDataContent(session_description);
484 RTC_DCHECK(content_info);
485 if (!content_info) {
486 return -1;
487 }
488 const cricket::DataContentDescription* data =
489 static_cast<const cricket::DataContentDescription*>(
490 (content_info->description));
491 std::string value;
492 cricket::DataCodec match_pattern(cricket::kGoogleSctpDataCodecPlType,
493 cricket::kGoogleSctpDataCodecName);
494 for (const cricket::DataCodec& codec : data->codecs()) {
495 if (!codec.Matches(match_pattern)) {
496 continue;
497 }
498 if (codec.GetParam(cricket::kCodecParamPort, &value)) {
499 return rtc::FromString<int>(value);
500 }
501 }
502 return -1;
503}
504
Steve Anton75737c02017-11-06 10:37:17 -0800505// Returns true if |new_desc| requests an ICE restart (i.e., new ufrag/pwd).
506bool CheckForRemoteIceRestart(const SessionDescriptionInterface* old_desc,
507 const SessionDescriptionInterface* new_desc,
508 const std::string& content_name) {
509 if (!old_desc) {
510 return false;
511 }
512 const SessionDescription* new_sd = new_desc->description();
513 const SessionDescription* old_sd = old_desc->description();
514 const ContentInfo* cinfo = new_sd->GetContentByName(content_name);
515 if (!cinfo || cinfo->rejected) {
516 return false;
517 }
518 // If the content isn't rejected, check if ufrag and password has changed.
519 const cricket::TransportDescription* new_transport_desc =
520 new_sd->GetTransportDescriptionByName(content_name);
521 const cricket::TransportDescription* old_transport_desc =
522 old_sd->GetTransportDescriptionByName(content_name);
523 if (!new_transport_desc || !old_transport_desc) {
524 // No transport description exists. This is not an ICE restart.
525 return false;
526 }
527 if (cricket::IceCredentialsChanged(
528 old_transport_desc->ice_ufrag, old_transport_desc->ice_pwd,
529 new_transport_desc->ice_ufrag, new_transport_desc->ice_pwd)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100530 RTC_LOG(LS_INFO) << "Remote peer requests ICE restart for " << content_name
531 << ".";
Steve Anton75737c02017-11-06 10:37:17 -0800532 return true;
533 }
534 return false;
535}
536
537} // namespace
538
Henrik Boström31638672017-11-23 17:48:32 +0100539// Upon completion, posts a task to execute the callback of the
540// SetSessionDescriptionObserver asynchronously on the same thread. At this
541// point, the state of the peer connection might no longer reflect the effects
542// of the SetRemoteDescription operation, as the peer connection could have been
543// modified during the post.
544// TODO(hbos): Remove this class once we remove the version of
545// PeerConnectionInterface::SetRemoteDescription() that takes a
546// SetSessionDescriptionObserver as an argument.
547class PeerConnection::SetRemoteDescriptionObserverAdapter
548 : public rtc::RefCountedObject<SetRemoteDescriptionObserverInterface> {
549 public:
550 SetRemoteDescriptionObserverAdapter(
551 rtc::scoped_refptr<PeerConnection> pc,
552 rtc::scoped_refptr<SetSessionDescriptionObserver> wrapper)
553 : pc_(std::move(pc)), wrapper_(std::move(wrapper)) {}
554
555 // SetRemoteDescriptionObserverInterface implementation.
556 void OnSetRemoteDescriptionComplete(RTCError error) override {
557 if (error.ok())
558 pc_->PostSetSessionDescriptionSuccess(wrapper_);
559 else
560 pc_->PostSetSessionDescriptionFailure(wrapper_, error.message());
561 }
562
563 private:
564 rtc::scoped_refptr<PeerConnection> pc_;
565 rtc::scoped_refptr<SetSessionDescriptionObserver> wrapper_;
566};
567
deadbeef293e9262017-01-11 12:28:30 -0800568bool PeerConnectionInterface::RTCConfiguration::operator==(
569 const PeerConnectionInterface::RTCConfiguration& o) const {
570 // This static_assert prevents us from accidentally breaking operator==.
Steve Anton300bf8e2017-07-14 10:13:10 -0700571 // Note: Order matters! Fields must be ordered the same as RTCConfiguration.
deadbeef293e9262017-01-11 12:28:30 -0800572 struct stuff_being_tested_for_equality {
Magnus Jedvert3beb2072017-07-14 14:23:56 +0000573 IceServers servers;
Steve Anton300bf8e2017-07-14 10:13:10 -0700574 IceTransportsType type;
deadbeef293e9262017-01-11 12:28:30 -0800575 BundlePolicy bundle_policy;
576 RtcpMuxPolicy rtcp_mux_policy;
Steve Anton300bf8e2017-07-14 10:13:10 -0700577 std::vector<rtc::scoped_refptr<rtc::RTCCertificate>> certificates;
578 int ice_candidate_pool_size;
579 bool disable_ipv6;
580 bool disable_ipv6_on_wifi;
deadbeefd21eab32017-07-26 16:50:11 -0700581 int max_ipv6_networks;
Steve Anton300bf8e2017-07-14 10:13:10 -0700582 bool enable_rtp_data_channel;
583 rtc::Optional<int> screencast_min_bitrate;
584 rtc::Optional<bool> combined_audio_video_bwe;
585 rtc::Optional<bool> enable_dtls_srtp;
deadbeef293e9262017-01-11 12:28:30 -0800586 TcpCandidatePolicy tcp_candidate_policy;
587 CandidateNetworkPolicy candidate_network_policy;
588 int audio_jitter_buffer_max_packets;
589 bool audio_jitter_buffer_fast_accelerate;
590 int ice_connection_receiving_timeout;
591 int ice_backup_candidate_pair_ping_interval;
592 ContinualGatheringPolicy continual_gathering_policy;
deadbeef293e9262017-01-11 12:28:30 -0800593 bool prioritize_most_likely_ice_candidate_pairs;
594 struct cricket::MediaConfig media_config;
deadbeef293e9262017-01-11 12:28:30 -0800595 bool prune_turn_ports;
596 bool presume_writable_when_fully_relayed;
597 bool enable_ice_renomination;
598 bool redetermine_role_on_ice_restart;
skvlad51072462017-02-02 11:50:14 -0800599 rtc::Optional<int> ice_check_min_interval;
Steve Anton300bf8e2017-07-14 10:13:10 -0700600 rtc::Optional<rtc::IntervalRange> ice_regather_interval_range;
Jonas Orelandbdcee282017-10-10 14:01:40 +0200601 webrtc::TurnCustomizer* turn_customizer;
Steve Anton79e79602017-11-20 10:25:56 -0800602 SdpSemantics sdp_semantics;
deadbeef293e9262017-01-11 12:28:30 -0800603 };
604 static_assert(sizeof(stuff_being_tested_for_equality) == sizeof(*this),
605 "Did you add something to RTCConfiguration and forget to "
606 "update operator==?");
607 return type == o.type && servers == o.servers &&
608 bundle_policy == o.bundle_policy &&
609 rtcp_mux_policy == o.rtcp_mux_policy &&
610 tcp_candidate_policy == o.tcp_candidate_policy &&
611 candidate_network_policy == o.candidate_network_policy &&
612 audio_jitter_buffer_max_packets == o.audio_jitter_buffer_max_packets &&
613 audio_jitter_buffer_fast_accelerate ==
614 o.audio_jitter_buffer_fast_accelerate &&
615 ice_connection_receiving_timeout ==
616 o.ice_connection_receiving_timeout &&
617 ice_backup_candidate_pair_ping_interval ==
618 o.ice_backup_candidate_pair_ping_interval &&
619 continual_gathering_policy == o.continual_gathering_policy &&
620 certificates == o.certificates &&
621 prioritize_most_likely_ice_candidate_pairs ==
622 o.prioritize_most_likely_ice_candidate_pairs &&
623 media_config == o.media_config && disable_ipv6 == o.disable_ipv6 &&
zhihuangb09b3f92017-03-07 14:40:51 -0800624 disable_ipv6_on_wifi == o.disable_ipv6_on_wifi &&
deadbeefd21eab32017-07-26 16:50:11 -0700625 max_ipv6_networks == o.max_ipv6_networks &&
deadbeef293e9262017-01-11 12:28:30 -0800626 enable_rtp_data_channel == o.enable_rtp_data_channel &&
deadbeef293e9262017-01-11 12:28:30 -0800627 screencast_min_bitrate == o.screencast_min_bitrate &&
628 combined_audio_video_bwe == o.combined_audio_video_bwe &&
629 enable_dtls_srtp == o.enable_dtls_srtp &&
630 ice_candidate_pool_size == o.ice_candidate_pool_size &&
631 prune_turn_ports == o.prune_turn_ports &&
632 presume_writable_when_fully_relayed ==
633 o.presume_writable_when_fully_relayed &&
634 enable_ice_renomination == o.enable_ice_renomination &&
skvlad51072462017-02-02 11:50:14 -0800635 redetermine_role_on_ice_restart == o.redetermine_role_on_ice_restart &&
Steve Anton300bf8e2017-07-14 10:13:10 -0700636 ice_check_min_interval == o.ice_check_min_interval &&
Jonas Orelandbdcee282017-10-10 14:01:40 +0200637 ice_regather_interval_range == o.ice_regather_interval_range &&
Steve Anton79e79602017-11-20 10:25:56 -0800638 turn_customizer == o.turn_customizer &&
639 sdp_semantics == o.sdp_semantics;
deadbeef293e9262017-01-11 12:28:30 -0800640}
641
642bool PeerConnectionInterface::RTCConfiguration::operator!=(
643 const PeerConnectionInterface::RTCConfiguration& o) const {
644 return !(*this == o);
deadbeef3edec7c2016-12-10 11:44:26 -0800645}
646
zhihuang8f65cdf2016-05-06 18:40:30 -0700647// Generate a RTCP CNAME when a PeerConnection is created.
648std::string GenerateRtcpCname() {
649 std::string cname;
650 if (!rtc::CreateRandomString(kRtcpCnameLength, &cname)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100651 RTC_LOG(LS_ERROR) << "Failed to generate CNAME.";
nisseeb4ca4e2017-01-12 02:24:27 -0800652 RTC_NOTREACHED();
zhihuang8f65cdf2016-05-06 18:40:30 -0700653 }
654 return cname;
655}
656
zhihuang1c378ed2017-08-17 14:10:50 -0700657bool ValidateOfferAnswerOptions(
658 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options) {
659 return IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_audio) &&
660 IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_video);
olka3c747662017-08-17 06:50:32 -0700661}
662
zhihuang1c378ed2017-08-17 14:10:50 -0700663// From |rtc_options|, fill parts of |session_options| shared by all generated
664// m= sections (in other words, nothing that involves a map/array).
665void ExtractSharedMediaSessionOptions(
666 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options,
667 cricket::MediaSessionOptions* session_options) {
668 session_options->vad_enabled = rtc_options.voice_activity_detection;
669 session_options->bundle_enabled = rtc_options.use_rtp_mux;
670}
zhihuanga77e6bb2017-08-14 18:17:48 -0700671
zhihuang1c378ed2017-08-17 14:10:50 -0700672bool ConvertConstraintsToOfferAnswerOptions(
673 const MediaConstraintsInterface* constraints,
674 PeerConnectionInterface::RTCOfferAnswerOptions* offer_answer_options) {
olka3c747662017-08-17 06:50:32 -0700675 if (!constraints) {
676 return true;
677 }
zhihuang1c378ed2017-08-17 14:10:50 -0700678
679 bool value = false;
680 size_t mandatory_constraints_satisfied = 0;
681
682 if (FindConstraint(constraints,
683 MediaConstraintsInterface::kOfferToReceiveAudio, &value,
684 &mandatory_constraints_satisfied)) {
685 offer_answer_options->offer_to_receive_audio =
686 value ? PeerConnectionInterface::RTCOfferAnswerOptions::
687 kOfferToReceiveMediaTrue
688 : 0;
689 }
690
691 if (FindConstraint(constraints,
692 MediaConstraintsInterface::kOfferToReceiveVideo, &value,
693 &mandatory_constraints_satisfied)) {
694 offer_answer_options->offer_to_receive_video =
695 value ? PeerConnectionInterface::RTCOfferAnswerOptions::
696 kOfferToReceiveMediaTrue
697 : 0;
698 }
699 if (FindConstraint(constraints,
700 MediaConstraintsInterface::kVoiceActivityDetection, &value,
701 &mandatory_constraints_satisfied)) {
702 offer_answer_options->voice_activity_detection = value;
703 }
704 if (FindConstraint(constraints, MediaConstraintsInterface::kUseRtpMux, &value,
705 &mandatory_constraints_satisfied)) {
706 offer_answer_options->use_rtp_mux = value;
707 }
708 if (FindConstraint(constraints, MediaConstraintsInterface::kIceRestart,
709 &value, &mandatory_constraints_satisfied)) {
710 offer_answer_options->ice_restart = value;
711 }
712
deadbeefab9b2d12015-10-14 11:33:11 -0700713 return mandatory_constraints_satisfied == constraints->GetMandatory().size();
714}
715
zhihuang38ede132017-06-15 12:52:32 -0700716PeerConnection::PeerConnection(PeerConnectionFactory* factory,
717 std::unique_ptr<RtcEventLog> event_log,
718 std::unique_ptr<Call> call)
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000719 : factory_(factory),
zhihuang38ede132017-06-15 12:52:32 -0700720 event_log_(std::move(event_log)),
zhihuang8f65cdf2016-05-06 18:40:30 -0700721 rtcp_cname_(GenerateRtcpCname()),
deadbeefab9b2d12015-10-14 11:33:11 -0700722 local_streams_(StreamCollection::Create()),
zhihuang38ede132017-06-15 12:52:32 -0700723 remote_streams_(StreamCollection::Create()),
724 call_(std::move(call)) {}
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000725
726PeerConnection::~PeerConnection() {
Peter Boström1a9d6152015-12-08 22:15:17 +0100727 TRACE_EVENT0("webrtc", "PeerConnection::~PeerConnection");
Steve Anton4171afb2017-11-20 10:20:22 -0800728 RTC_DCHECK_RUN_ON(signaling_thread());
729
Steve Anton8af21862017-12-15 11:20:13 -0800730 // Need to stop transceivers before destroying the stats collector because
731 // AudioRtpSender has a reference to the StatsCollector it will update when
732 // stopping.
733 for (auto transceiver : transceivers_) {
734 transceiver->Stop();
735 }
Steve Anton4171afb2017-11-20 10:20:22 -0800736
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700737 stats_.reset(nullptr);
hbosb78306a2016-12-19 05:06:57 -0800738 if (stats_collector_) {
739 stats_collector_->WaitForPendingRequest();
740 stats_collector_ = nullptr;
741 }
Steve Anton75737c02017-11-06 10:37:17 -0800742
Steve Anton8af21862017-12-15 11:20:13 -0800743 // Don't destroy BaseChannels until after stats has been cleaned up so that
744 // the last stats request can still read from the channels.
745 DestroyAllChannels();
746
Mirko Bonadei675513b2017-11-09 11:09:25 +0100747 RTC_LOG(LS_INFO) << "Session: " << session_id() << " is destroyed.";
Steve Anton75737c02017-11-06 10:37:17 -0800748
749 webrtc_session_desc_factory_.reset();
750 sctp_invoker_.reset();
751 sctp_factory_.reset();
752 transport_controller_.reset();
753
deadbeef91dd5672016-05-18 16:55:30 -0700754 // port_allocator_ lives on the network thread and should be destroyed there.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700755 network_thread()->Invoke<void>(RTC_FROM_HERE,
nisseeaabdf62017-05-05 02:23:02 -0700756 [this] { port_allocator_.reset(); });
eladalon248fd4f2017-09-06 05:18:15 -0700757 // call_ and event_log_ must be destroyed on the worker thread.
Steve Anton978b8762017-09-29 12:15:02 -0700758 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
eladalon248fd4f2017-09-06 05:18:15 -0700759 call_.reset();
760 event_log_.reset();
761 });
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000762}
763
Steve Anton8af21862017-12-15 11:20:13 -0800764void PeerConnection::DestroyAllChannels() {
Steve Anton3fe1b152017-12-12 10:20:08 -0800765 // Destroy video channels first since they may have a pointer to a voice
766 // channel.
767 for (auto transceiver : transceivers_) {
768 if (transceiver->internal()->media_type() == cricket::MEDIA_TYPE_VIDEO) {
769 DestroyTransceiverChannel(transceiver);
770 }
771 }
772 for (auto transceiver : transceivers_) {
773 if (transceiver->internal()->media_type() == cricket::MEDIA_TYPE_AUDIO) {
774 DestroyTransceiverChannel(transceiver);
775 }
776 }
777 DestroyDataChannel();
778}
779
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000780bool PeerConnection::Initialize(
buildbot@webrtc.org41451d42014-05-03 05:39:45 +0000781 const PeerConnectionInterface::RTCConfiguration& configuration,
kwibergd1fe2812016-04-27 06:47:29 -0700782 std::unique_ptr<cricket::PortAllocator> allocator,
Henrik Boströmd03c23b2016-06-01 11:44:18 +0200783 std::unique_ptr<rtc::RTCCertificateGeneratorInterface> cert_generator,
deadbeef653b8e02015-11-11 12:55:10 -0800784 PeerConnectionObserver* observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100785 TRACE_EVENT0("webrtc", "PeerConnection::Initialize");
Steve Anton038834f2017-07-14 15:59:59 -0700786
787 RTCError config_error = ValidateConfiguration(configuration);
788 if (!config_error.ok()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100789 RTC_LOG(LS_ERROR) << "Invalid configuration: " << config_error.message();
Steve Anton038834f2017-07-14 15:59:59 -0700790 return false;
791 }
792
deadbeef293e9262017-01-11 12:28:30 -0800793 if (!allocator) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100794 RTC_LOG(LS_ERROR)
795 << "PeerConnection initialized without a PortAllocator? "
796 << "This shouldn't happen if using PeerConnectionFactory.";
deadbeef293e9262017-01-11 12:28:30 -0800797 return false;
798 }
Jonas Orelandbdcee282017-10-10 14:01:40 +0200799
deadbeef653b8e02015-11-11 12:55:10 -0800800 if (!observer) {
deadbeef293e9262017-01-11 12:28:30 -0800801 // TODO(deadbeef): Why do we do this?
Mirko Bonadei675513b2017-11-09 11:09:25 +0100802 RTC_LOG(LS_ERROR) << "PeerConnection initialized without a "
803 << "PeerConnectionObserver";
deadbeef653b8e02015-11-11 12:55:10 -0800804 return false;
805 }
pthatcher@webrtc.org877ac762015-02-04 22:03:09 +0000806 observer_ = observer;
kwiberg0eb15ed2015-12-17 03:04:15 -0800807 port_allocator_ = std::move(allocator);
deadbeef653b8e02015-11-11 12:55:10 -0800808
deadbeef91dd5672016-05-18 16:55:30 -0700809 // The port allocator lives on the network thread and should be initialized
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700810 // there.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700811 if (!network_thread()->Invoke<bool>(
812 RTC_FROM_HERE, rtc::Bind(&PeerConnection::InitializePortAllocator_n,
813 this, configuration))) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000814 return false;
815 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000816
Steve Anton75737c02017-11-06 10:37:17 -0800817 // RFC 3264: The numeric value of the session id and version in the
818 // o line MUST be representable with a "64 bit signed integer".
819 // Due to this constraint session id |session_id_| is max limited to
820 // LLONG_MAX.
821 session_id_ = rtc::ToString(rtc::CreateRandomId64() & LLONG_MAX);
822 transport_controller_.reset(factory_->CreateTransportController(
823 port_allocator_.get(), configuration.redetermine_role_on_ice_restart));
824 transport_controller_->SetIceRole(cricket::ICEROLE_CONTROLLED);
825 transport_controller_->SignalConnectionState.connect(
826 this, &PeerConnection::OnTransportControllerConnectionState);
827 transport_controller_->SignalGatheringState.connect(
828 this, &PeerConnection::OnTransportControllerGatheringState);
829 transport_controller_->SignalCandidatesGathered.connect(
830 this, &PeerConnection::OnTransportControllerCandidatesGathered);
831 transport_controller_->SignalCandidatesRemoved.connect(
832 this, &PeerConnection::OnTransportControllerCandidatesRemoved);
833 transport_controller_->SignalDtlsHandshakeError.connect(
834 this, &PeerConnection::OnTransportControllerDtlsHandshakeError);
835
836 sctp_factory_ = factory_->CreateSctpTransportInternalFactory();
zhihuang29ff8442016-07-27 11:07:25 -0700837
deadbeefab9b2d12015-10-14 11:33:11 -0700838 stats_.reset(new StatsCollector(this));
hbos74e1a4f2016-09-15 23:33:01 -0700839 stats_collector_ = RTCStatsCollector::Create(this);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000840
Steve Antonba818672017-11-06 10:21:57 -0800841 configuration_ = configuration;
842
Steve Anton75737c02017-11-06 10:37:17 -0800843 const PeerConnectionFactoryInterface::Options& options = factory_->options();
844
845 transport_controller_->SetSslMaxProtocolVersion(options.ssl_max_version);
846
847 // Obtain a certificate from RTCConfiguration if any were provided (optional).
848 rtc::scoped_refptr<rtc::RTCCertificate> certificate;
849 if (!configuration.certificates.empty()) {
850 // TODO(hbos,torbjorng): Decide on certificate-selection strategy instead of
851 // just picking the first one. The decision should be made based on the DTLS
852 // handshake. The DTLS negotiations need to know about all certificates.
853 certificate = configuration.certificates[0];
854 }
855
Steve Antond25da372017-11-06 14:50:29 -0800856 transport_controller_->SetIceConfig(ParseIceConfig(configuration));
Steve Anton75737c02017-11-06 10:37:17 -0800857
858 if (options.disable_encryption) {
859 dtls_enabled_ = false;
860 } else {
861 // Enable DTLS by default if we have an identity store or a certificate.
862 dtls_enabled_ = (cert_generator || certificate);
863 // |configuration| can override the default |dtls_enabled_| value.
864 if (configuration.enable_dtls_srtp) {
865 dtls_enabled_ = *(configuration.enable_dtls_srtp);
866 }
867 }
868
869 // Enable creation of RTP data channels if the kEnableRtpDataChannels is set.
870 // It takes precendence over the disable_sctp_data_channels
871 // PeerConnectionFactoryInterface::Options.
872 if (configuration.enable_rtp_data_channel) {
873 data_channel_type_ = cricket::DCT_RTP;
874 } else {
875 // DTLS has to be enabled to use SCTP.
876 if (!options.disable_sctp_data_channels && dtls_enabled_) {
877 data_channel_type_ = cricket::DCT_SCTP;
878 }
879 }
880
881 video_options_.screencast_min_bitrate_kbps =
882 configuration.screencast_min_bitrate;
883 audio_options_.combined_audio_video_bwe =
884 configuration.combined_audio_video_bwe;
885
886 audio_options_.audio_jitter_buffer_max_packets =
Oskar Sundbom9b28a032017-11-16 10:53:30 +0100887 configuration.audio_jitter_buffer_max_packets;
Steve Anton75737c02017-11-06 10:37:17 -0800888
889 audio_options_.audio_jitter_buffer_fast_accelerate =
Oskar Sundbom9b28a032017-11-16 10:53:30 +0100890 configuration.audio_jitter_buffer_fast_accelerate;
Steve Anton75737c02017-11-06 10:37:17 -0800891
892 // Whether the certificate generator/certificate is null or not determines
893 // what PeerConnectionDescriptionFactory will do, so make sure that we give it
894 // the right instructions by clearing the variables if needed.
895 if (!dtls_enabled_) {
896 cert_generator.reset();
897 certificate = nullptr;
898 } else if (certificate) {
899 // Favor generated certificate over the certificate generator.
900 cert_generator.reset();
901 }
902
903 webrtc_session_desc_factory_.reset(new WebRtcSessionDescriptionFactory(
904 signaling_thread(), channel_manager(), this, session_id(),
905 std::move(cert_generator), certificate));
906 webrtc_session_desc_factory_->SignalCertificateReady.connect(
907 this, &PeerConnection::OnCertificateReady);
908
909 if (options.disable_encryption) {
910 webrtc_session_desc_factory_->SetSdesPolicy(cricket::SEC_DISABLED);
911 }
912
913 webrtc_session_desc_factory_->set_enable_encrypted_rtp_header_extensions(
914 options.crypto_options.enable_encrypted_rtp_header_extensions);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000915
Steve Anton4171afb2017-11-20 10:20:22 -0800916 // Add default audio/video transceivers for Plan B SDP.
917 if (!IsUnifiedPlan()) {
918 transceivers_.push_back(
919 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
920 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_AUDIO)));
921 transceivers_.push_back(
922 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
923 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_VIDEO)));
924 }
925
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000926 return true;
927}
928
Steve Anton038834f2017-07-14 15:59:59 -0700929RTCError PeerConnection::ValidateConfiguration(
930 const RTCConfiguration& config) const {
931 if (config.ice_regather_interval_range &&
932 config.continual_gathering_policy == GATHER_ONCE) {
933 return RTCError(RTCErrorType::INVALID_PARAMETER,
934 "ice_regather_interval_range specified but continual "
935 "gathering policy is GATHER_ONCE");
936 }
937 return RTCError::OK();
938}
939
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000940rtc::scoped_refptr<StreamCollectionInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000941PeerConnection::local_streams() {
deadbeefab9b2d12015-10-14 11:33:11 -0700942 return local_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000943}
944
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000945rtc::scoped_refptr<StreamCollectionInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000946PeerConnection::remote_streams() {
deadbeefab9b2d12015-10-14 11:33:11 -0700947 return remote_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000948}
949
perkj@webrtc.orgc2dd5ee2014-11-04 11:31:29 +0000950bool PeerConnection::AddStream(MediaStreamInterface* local_stream) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100951 TRACE_EVENT0("webrtc", "PeerConnection::AddStream");
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000952 if (IsClosed()) {
953 return false;
954 }
deadbeefab9b2d12015-10-14 11:33:11 -0700955 if (!CanAddLocalMediaStream(local_streams_, local_stream)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000956 return false;
957 }
deadbeefab9b2d12015-10-14 11:33:11 -0700958
959 local_streams_->AddStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -0800960 MediaStreamObserver* observer = new MediaStreamObserver(local_stream);
961 observer->SignalAudioTrackAdded.connect(this,
962 &PeerConnection::OnAudioTrackAdded);
963 observer->SignalAudioTrackRemoved.connect(
964 this, &PeerConnection::OnAudioTrackRemoved);
965 observer->SignalVideoTrackAdded.connect(this,
966 &PeerConnection::OnVideoTrackAdded);
967 observer->SignalVideoTrackRemoved.connect(
968 this, &PeerConnection::OnVideoTrackRemoved);
kwibergd1fe2812016-04-27 06:47:29 -0700969 stream_observers_.push_back(std::unique_ptr<MediaStreamObserver>(observer));
deadbeefab9b2d12015-10-14 11:33:11 -0700970
deadbeefab9b2d12015-10-14 11:33:11 -0700971 for (const auto& track : local_stream->GetAudioTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -0700972 AddAudioTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -0700973 }
974 for (const auto& track : local_stream->GetVideoTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -0700975 AddVideoTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -0700976 }
977
tommi@webrtc.org03505bc2014-07-14 20:15:26 +0000978 stats_->AddStream(local_stream);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000979 observer_->OnRenegotiationNeeded();
980 return true;
981}
982
983void PeerConnection::RemoveStream(MediaStreamInterface* local_stream) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100984 TRACE_EVENT0("webrtc", "PeerConnection::RemoveStream");
korniltsev.anatolyec390b52017-07-24 17:00:25 -0700985 if (!IsClosed()) {
986 for (const auto& track : local_stream->GetAudioTracks()) {
987 RemoveAudioTrack(track.get(), local_stream);
988 }
989 for (const auto& track : local_stream->GetVideoTracks()) {
990 RemoveVideoTrack(track.get(), local_stream);
991 }
deadbeefab9b2d12015-10-14 11:33:11 -0700992 }
deadbeefab9b2d12015-10-14 11:33:11 -0700993 local_streams_->RemoveStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -0800994 stream_observers_.erase(
995 std::remove_if(
996 stream_observers_.begin(), stream_observers_.end(),
kwibergd1fe2812016-04-27 06:47:29 -0700997 [local_stream](const std::unique_ptr<MediaStreamObserver>& observer) {
deadbeefeb459812015-12-15 19:24:43 -0800998 return observer->stream()->label().compare(local_stream->label()) ==
999 0;
1000 }),
1001 stream_observers_.end());
deadbeefab9b2d12015-10-14 11:33:11 -07001002
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001003 if (IsClosed()) {
1004 return;
1005 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001006 observer_->OnRenegotiationNeeded();
1007}
1008
deadbeefe1f9d832016-01-14 15:35:42 -08001009rtc::scoped_refptr<RtpSenderInterface> PeerConnection::AddTrack(
1010 MediaStreamTrackInterface* track,
1011 std::vector<MediaStreamInterface*> streams) {
1012 TRACE_EVENT0("webrtc", "PeerConnection::AddTrack");
Steve Antonf9381f02017-12-14 10:23:57 -08001013 std::vector<std::string> stream_labels;
1014 for (auto* stream : streams) {
1015 if (!stream) {
1016 RTC_LOG(LS_ERROR) << "Stream list has null element.";
1017 return nullptr;
1018 }
1019 stream_labels.push_back(stream->label());
1020 }
1021 auto sender_or_error = AddTrackWithStreamLabels(track, stream_labels);
1022 if (!sender_or_error.ok()) {
deadbeefe1f9d832016-01-14 15:35:42 -08001023 return nullptr;
1024 }
Steve Antonf9381f02017-12-14 10:23:57 -08001025 return sender_or_error.MoveValue();
1026}
1027
1028RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>>
1029PeerConnection::AddTrackWithStreamLabels(
1030 rtc::scoped_refptr<MediaStreamTrackInterface> track,
1031 const std::vector<std::string>& stream_labels) {
1032 TRACE_EVENT0("webrtc", "PeerConnection::AddTrackWithStreamLabels");
1033 if (!track) {
1034 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "Track is null.");
1035 }
1036 if (!(track->kind() == MediaStreamTrackInterface::kAudioKind ||
1037 track->kind() == MediaStreamTrackInterface::kVideoKind)) {
1038 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1039 "Track has invalid kind: " + track->kind());
1040 }
1041 // TODO(bugs.webrtc.org/7932): Support adding a track to multiple streams.
1042 if (stream_labels.size() > 1u) {
1043 LOG_AND_RETURN_ERROR(
1044 RTCErrorType::UNSUPPORTED_OPERATION,
1045 "AddTrack with more than one stream is not currently supported.");
1046 }
1047 if (IsClosed()) {
1048 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
1049 "PeerConnection is closed.");
deadbeefe1f9d832016-01-14 15:35:42 -08001050 }
Steve Anton4171afb2017-11-20 10:20:22 -08001051 if (FindSenderForTrack(track)) {
Steve Antonf9381f02017-12-14 10:23:57 -08001052 LOG_AND_RETURN_ERROR(
1053 RTCErrorType::INVALID_PARAMETER,
1054 "Sender already exists for track " + track->id() + ".");
deadbeefe1f9d832016-01-14 15:35:42 -08001055 }
Steve Antonf9381f02017-12-14 10:23:57 -08001056 // TODO(bugs.webrtc.org/7933): MediaSession expects the sender to have exactly
1057 // one stream. AddTrackInternal will return an error if there is more than one
1058 // stream, but if the caller specifies none then we need to generate a random
1059 // stream label.
1060 std::vector<std::string> adjusted_stream_labels = stream_labels;
1061 if (stream_labels.empty()) {
1062 adjusted_stream_labels.push_back(rtc::CreateRandomUuid());
1063 }
1064 RTC_DCHECK_EQ(1, adjusted_stream_labels.size());
1065 auto sender_or_error =
1066 (IsUnifiedPlan() ? AddTrackUnifiedPlan(track, adjusted_stream_labels)
1067 : AddTrackPlanB(track, adjusted_stream_labels));
1068 if (sender_or_error.ok()) {
1069 observer_->OnRenegotiationNeeded();
1070 }
1071 return sender_or_error;
1072}
deadbeefe1f9d832016-01-14 15:35:42 -08001073
Steve Antonf9381f02017-12-14 10:23:57 -08001074RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>>
1075PeerConnection::AddTrackPlanB(
1076 rtc::scoped_refptr<MediaStreamTrackInterface> track,
1077 const std::vector<std::string>& stream_labels) {
deadbeefe1f9d832016-01-14 15:35:42 -08001078 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
Steve Antonf9381f02017-12-14 10:23:57 -08001079 auto new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
deadbeefe1f9d832016-01-14 15:35:42 -08001080 signaling_thread(),
Steve Antonf9381f02017-12-14 10:23:57 -08001081 new AudioRtpSender(static_cast<AudioTrackInterface*>(track.get()),
Steve Anton75737c02017-11-06 10:37:17 -08001082 voice_channel(), stats_.get()));
Steve Anton4171afb2017-11-20 10:20:22 -08001083 GetAudioTransceiver()->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_audio_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);
1092 } else {
1093 RTC_DCHECK_EQ(MediaStreamTrackInterface::kVideoKind, track->kind());
1094 auto new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
deadbeefe1f9d832016-01-14 15:35:42 -08001095 signaling_thread(),
Steve Antonf9381f02017-12-14 10:23:57 -08001096 new VideoRtpSender(static_cast<VideoTrackInterface*>(track.get()),
Steve Anton75737c02017-11-06 10:37:17 -08001097 video_channel()));
Steve Anton4171afb2017-11-20 10:20:22 -08001098 GetVideoTransceiver()->internal()->AddSender(new_sender);
Steve Antonf9381f02017-12-14 10:23:57 -08001099 new_sender->internal()->set_stream_ids(stream_labels);
Steve Anton4171afb2017-11-20 10:20:22 -08001100 const RtpSenderInfo* sender_info =
1101 FindSenderInfo(local_video_sender_infos_,
1102 new_sender->internal()->stream_id(), track->id());
1103 if (sender_info) {
1104 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -08001105 }
Steve Antonf9381f02017-12-14 10:23:57 -08001106 return rtc::scoped_refptr<RtpSenderInterface>(new_sender);
deadbeefe1f9d832016-01-14 15:35:42 -08001107 }
Steve Antonf9381f02017-12-14 10:23:57 -08001108}
deadbeefe1f9d832016-01-14 15:35:42 -08001109
Steve Antonf9381f02017-12-14 10:23:57 -08001110RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>>
1111PeerConnection::AddTrackUnifiedPlan(
1112 rtc::scoped_refptr<MediaStreamTrackInterface> track,
1113 const std::vector<std::string>& stream_labels) {
1114 auto transceiver = FindFirstTransceiverForAddedTrack(track);
1115 if (transceiver) {
1116 if (transceiver->direction() == RtpTransceiverDirection::kRecvOnly) {
1117 transceiver->SetDirection(RtpTransceiverDirection::kSendRecv);
1118 } else if (transceiver->direction() == RtpTransceiverDirection::kInactive) {
1119 transceiver->SetDirection(RtpTransceiverDirection::kSendOnly);
1120 }
1121 } else {
1122 cricket::MediaType media_type =
1123 (track->kind() == MediaStreamTrackInterface::kAudioKind
1124 ? cricket::MEDIA_TYPE_AUDIO
1125 : cricket::MEDIA_TYPE_VIDEO);
1126 transceiver = CreateTransceiver(media_type);
1127 transceiver->internal()->set_created_by_addtrack(true);
1128 transceiver->SetDirection(RtpTransceiverDirection::kSendRecv);
1129 }
1130 transceiver->sender()->SetTrack(track);
1131 transceiver->internal()->sender_internal()->set_stream_ids(stream_labels);
1132 return transceiver->sender();
1133}
1134
1135rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1136PeerConnection::FindFirstTransceiverForAddedTrack(
1137 rtc::scoped_refptr<MediaStreamTrackInterface> track) {
1138 RTC_DCHECK(track);
1139 for (auto transceiver : transceivers_) {
1140 if (!transceiver->sender()->track() &&
1141 cricket::MediaTypeToString(transceiver->internal()->media_type()) ==
1142 track->kind() &&
1143 !transceiver->internal()->has_ever_been_used_to_send()) {
1144 return transceiver;
1145 }
1146 }
1147 return nullptr;
deadbeefe1f9d832016-01-14 15:35:42 -08001148}
1149
1150bool PeerConnection::RemoveTrack(RtpSenderInterface* sender) {
1151 TRACE_EVENT0("webrtc", "PeerConnection::RemoveTrack");
Steve Antonf9381f02017-12-14 10:23:57 -08001152 return RemoveTrackInternal(sender).ok();
1153}
1154
1155RTCError PeerConnection::RemoveTrackInternal(
1156 rtc::scoped_refptr<RtpSenderInterface> sender) {
1157 if (!sender) {
1158 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "Sender is null.");
1159 }
deadbeefe1f9d832016-01-14 15:35:42 -08001160 if (IsClosed()) {
Steve Antonf9381f02017-12-14 10:23:57 -08001161 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
1162 "PeerConnection is closed.");
deadbeefe1f9d832016-01-14 15:35:42 -08001163 }
Steve Antonf9381f02017-12-14 10:23:57 -08001164 if (IsUnifiedPlan()) {
1165 auto transceiver = FindTransceiverBySender(sender);
1166 if (!transceiver || !sender->track()) {
1167 return RTCError::OK();
1168 }
1169 sender->SetTrack(nullptr);
1170 if (transceiver->direction() == RtpTransceiverDirection::kSendRecv) {
1171 transceiver->internal()->SetDirection(RtpTransceiverDirection::kRecvOnly);
1172 } else if (transceiver->direction() == RtpTransceiverDirection::kSendOnly) {
1173 transceiver->internal()->SetDirection(RtpTransceiverDirection::kInactive);
1174 }
Steve Anton4171afb2017-11-20 10:20:22 -08001175 } else {
Steve Antonf9381f02017-12-14 10:23:57 -08001176 bool removed;
1177 if (sender->media_type() == cricket::MEDIA_TYPE_AUDIO) {
1178 removed = GetAudioTransceiver()->internal()->RemoveSender(sender);
1179 } else {
1180 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, sender->media_type());
1181 removed = GetVideoTransceiver()->internal()->RemoveSender(sender);
1182 }
1183 if (!removed) {
1184 LOG_AND_RETURN_ERROR(
1185 RTCErrorType::INVALID_PARAMETER,
1186 "Couldn't find sender " + sender->id() + " to remove.");
1187 }
Steve Anton4171afb2017-11-20 10:20:22 -08001188 }
deadbeefe1f9d832016-01-14 15:35:42 -08001189 observer_->OnRenegotiationNeeded();
Steve Antonf9381f02017-12-14 10:23:57 -08001190 return RTCError::OK();
1191}
1192
1193rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1194PeerConnection::FindTransceiverBySender(
1195 rtc::scoped_refptr<RtpSenderInterface> sender) {
1196 for (auto transceiver : transceivers_) {
1197 if (transceiver->sender() == sender) {
1198 return transceiver;
1199 }
1200 }
1201 return nullptr;
deadbeefe1f9d832016-01-14 15:35:42 -08001202}
1203
Steve Anton9158ef62017-11-27 13:01:52 -08001204RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1205PeerConnection::AddTransceiver(
1206 rtc::scoped_refptr<MediaStreamTrackInterface> track) {
1207 return AddTransceiver(track, RtpTransceiverInit());
1208}
1209
1210RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1211PeerConnection::AddTransceiver(
1212 rtc::scoped_refptr<MediaStreamTrackInterface> track,
1213 const RtpTransceiverInit& init) {
1214 if (!IsUnifiedPlan()) {
1215 LOG_AND_RETURN_ERROR(
1216 RTCErrorType::INTERNAL_ERROR,
1217 "AddTransceiver only supported when Unified Plan is enabled.");
1218 }
1219 if (!track) {
1220 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "track is null");
1221 }
1222 cricket::MediaType media_type;
1223 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
1224 media_type = cricket::MEDIA_TYPE_AUDIO;
1225 } else if (track->kind() == MediaStreamTrackInterface::kVideoKind) {
1226 media_type = cricket::MEDIA_TYPE_VIDEO;
1227 } else {
1228 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1229 "Track kind is not audio or video");
1230 }
1231 return AddTransceiver(media_type, track, init);
1232}
1233
1234RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1235PeerConnection::AddTransceiver(cricket::MediaType media_type) {
1236 return AddTransceiver(media_type, RtpTransceiverInit());
1237}
1238
1239RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1240PeerConnection::AddTransceiver(cricket::MediaType media_type,
1241 const RtpTransceiverInit& init) {
1242 if (!IsUnifiedPlan()) {
1243 LOG_AND_RETURN_ERROR(
1244 RTCErrorType::INTERNAL_ERROR,
1245 "AddTransceiver only supported when Unified Plan is enabled.");
1246 }
1247 if (!(media_type == cricket::MEDIA_TYPE_AUDIO ||
1248 media_type == cricket::MEDIA_TYPE_VIDEO)) {
1249 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1250 "media type is not audio or video");
1251 }
1252 return AddTransceiver(media_type, nullptr, init);
1253}
1254
1255RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1256PeerConnection::AddTransceiver(
1257 cricket::MediaType media_type,
1258 rtc::scoped_refptr<MediaStreamTrackInterface> track,
1259 const RtpTransceiverInit& init) {
1260 RTC_DCHECK((media_type == cricket::MEDIA_TYPE_AUDIO ||
1261 media_type == cricket::MEDIA_TYPE_VIDEO));
1262 if (track) {
1263 RTC_DCHECK_EQ(media_type,
1264 (track->kind() == MediaStreamTrackInterface::kAudioKind
1265 ? cricket::MEDIA_TYPE_AUDIO
1266 : cricket::MEDIA_TYPE_VIDEO));
1267 }
1268
1269 // TODO(bugs.webrtc.org/7600): Verify init.
1270
Steve Antonf9381f02017-12-14 10:23:57 -08001271 auto transceiver = CreateTransceiver(media_type);
1272 transceiver->SetDirection(init.direction);
1273 if (track) {
1274 transceiver->sender()->SetTrack(track);
1275 }
1276
1277 observer_->OnRenegotiationNeeded();
1278
1279 return rtc::scoped_refptr<RtpTransceiverInterface>(transceiver);
1280}
1281
1282rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1283PeerConnection::CreateTransceiver(cricket::MediaType media_type) {
Steve Anton9158ef62017-11-27 13:01:52 -08001284 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> sender;
1285 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1286 receiver;
1287 std::string receiver_id = rtc::CreateRandomUuid();
Steve Antonf9381f02017-12-14 10:23:57 -08001288 // TODO(bugs.webrtc.org/7600): Initializing the sender/receiver with a null
1289 // channel prevents users from calling SetParameters on them, which is needed
1290 // to be in compliance with the spec.
Steve Anton9158ef62017-11-27 13:01:52 -08001291 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
1292 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
1293 signaling_thread(), new AudioRtpSender(nullptr, stats_.get()));
1294 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
1295 signaling_thread(), new AudioRtpReceiver(receiver_id, {}, 0, nullptr));
1296 } else {
1297 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, media_type);
1298 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
1299 signaling_thread(), new VideoRtpSender(nullptr));
1300 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
1301 signaling_thread(),
1302 new VideoRtpReceiver(receiver_id, {}, worker_thread(), 0, nullptr));
1303 }
Steve Anton9158ef62017-11-27 13:01:52 -08001304 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1305 transceiver = RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1306 signaling_thread(), new RtpTransceiver(sender, receiver));
Steve Anton9158ef62017-11-27 13:01:52 -08001307 transceivers_.push_back(transceiver);
Steve Antonf9381f02017-12-14 10:23:57 -08001308 return transceiver;
Steve Anton9158ef62017-11-27 13:01:52 -08001309}
1310
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001311rtc::scoped_refptr<DtmfSenderInterface> PeerConnection::CreateDtmfSender(
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001312 AudioTrackInterface* track) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001313 TRACE_EVENT0("webrtc", "PeerConnection::CreateDtmfSender");
zhihuang29ff8442016-07-27 11:07:25 -07001314 if (IsClosed()) {
1315 return nullptr;
1316 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001317 if (!track) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001318 RTC_LOG(LS_ERROR) << "CreateDtmfSender - track is NULL.";
deadbeef20cb0c12017-02-01 20:27:00 -08001319 return nullptr;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001320 }
Steve Anton4171afb2017-11-20 10:20:22 -08001321 auto track_sender = FindSenderForTrack(track);
1322 if (!track_sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001323 RTC_LOG(LS_ERROR) << "CreateDtmfSender called with a non-added track.";
deadbeef20cb0c12017-02-01 20:27:00 -08001324 return nullptr;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001325 }
1326
Steve Anton4171afb2017-11-20 10:20:22 -08001327 return track_sender->GetDtmfSender();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001328}
1329
deadbeeffac06552015-11-25 11:26:01 -08001330rtc::scoped_refptr<RtpSenderInterface> PeerConnection::CreateSender(
deadbeefbd7d8f72015-12-18 16:58:44 -08001331 const std::string& kind,
1332 const std::string& stream_id) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001333 TRACE_EVENT0("webrtc", "PeerConnection::CreateSender");
zhihuang29ff8442016-07-27 11:07:25 -07001334 if (IsClosed()) {
1335 return nullptr;
1336 }
Steve Anton4171afb2017-11-20 10:20:22 -08001337
1338 // TODO(steveanton): Move construction of the RtpSenders to RtpTransceiver.
deadbeefa601f5c2016-06-06 14:27:39 -07001339 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender;
deadbeeffac06552015-11-25 11:26:01 -08001340 if (kind == MediaStreamTrackInterface::kAudioKind) {
deadbeefa601f5c2016-06-06 14:27:39 -07001341 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton75737c02017-11-06 10:37:17 -08001342 signaling_thread(), new AudioRtpSender(voice_channel(), stats_.get()));
Steve Anton4171afb2017-11-20 10:20:22 -08001343 GetAudioTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 11:26:01 -08001344 } else if (kind == MediaStreamTrackInterface::kVideoKind) {
deadbeefa601f5c2016-06-06 14:27:39 -07001345 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton75737c02017-11-06 10:37:17 -08001346 signaling_thread(), new VideoRtpSender(video_channel()));
Steve Anton4171afb2017-11-20 10:20:22 -08001347 GetVideoTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 11:26:01 -08001348 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001349 RTC_LOG(LS_ERROR) << "CreateSender called with invalid kind: " << kind;
Steve Anton4171afb2017-11-20 10:20:22 -08001350 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08001351 }
Steve Anton4171afb2017-11-20 10:20:22 -08001352
deadbeefbd7d8f72015-12-18 16:58:44 -08001353 if (!stream_id.empty()) {
deadbeefa601f5c2016-06-06 14:27:39 -07001354 new_sender->internal()->set_stream_id(stream_id);
deadbeefbd7d8f72015-12-18 16:58:44 -08001355 }
Steve Anton4171afb2017-11-20 10:20:22 -08001356
deadbeefe1f9d832016-01-14 15:35:42 -08001357 return new_sender;
deadbeeffac06552015-11-25 11:26:01 -08001358}
1359
deadbeef70ab1a12015-09-28 16:53:55 -07001360std::vector<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::GetSenders()
1361 const {
deadbeefa601f5c2016-06-06 14:27:39 -07001362 std::vector<rtc::scoped_refptr<RtpSenderInterface>> ret;
Steve Anton4171afb2017-11-20 10:20:22 -08001363 for (auto sender : GetSendersInternal()) {
1364 ret.push_back(sender);
deadbeefa601f5c2016-06-06 14:27:39 -07001365 }
1366 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -07001367}
1368
Steve Anton4171afb2017-11-20 10:20:22 -08001369std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1370PeerConnection::GetSendersInternal() const {
1371 std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1372 all_senders;
1373 for (auto transceiver : transceivers_) {
1374 auto senders = transceiver->internal()->senders();
1375 all_senders.insert(all_senders.end(), senders.begin(), senders.end());
1376 }
1377 return all_senders;
1378}
1379
deadbeef70ab1a12015-09-28 16:53:55 -07001380std::vector<rtc::scoped_refptr<RtpReceiverInterface>>
1381PeerConnection::GetReceivers() const {
deadbeefa601f5c2016-06-06 14:27:39 -07001382 std::vector<rtc::scoped_refptr<RtpReceiverInterface>> ret;
Steve Anton4171afb2017-11-20 10:20:22 -08001383 for (const auto& receiver : GetReceiversInternal()) {
1384 ret.push_back(receiver);
deadbeefa601f5c2016-06-06 14:27:39 -07001385 }
1386 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -07001387}
1388
Steve Anton4171afb2017-11-20 10:20:22 -08001389std::vector<
1390 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1391PeerConnection::GetReceiversInternal() const {
1392 std::vector<
1393 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1394 all_receivers;
1395 for (auto transceiver : transceivers_) {
1396 auto receivers = transceiver->internal()->receivers();
1397 all_receivers.insert(all_receivers.end(), receivers.begin(),
1398 receivers.end());
1399 }
1400 return all_receivers;
1401}
1402
Steve Anton9158ef62017-11-27 13:01:52 -08001403std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
1404PeerConnection::GetTransceivers() const {
1405 RTC_DCHECK(IsUnifiedPlan());
1406 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> all_transceivers;
1407 for (auto transceiver : transceivers_) {
1408 all_transceivers.push_back(transceiver);
1409 }
1410 return all_transceivers;
1411}
1412
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001413bool PeerConnection::GetStats(StatsObserver* observer,
wu@webrtc.orgb9a088b2014-02-13 23:18:49 +00001414 MediaStreamTrackInterface* track,
1415 StatsOutputLevel level) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001416 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
deadbeef0a6c4ca2015-10-06 11:38:28 -07001417 RTC_DCHECK(signaling_thread()->IsCurrent());
nisse7ce109a2017-01-31 00:57:56 -08001418 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001419 RTC_LOG(LS_ERROR) << "GetStats - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001420 return false;
1421 }
1422
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001423 stats_->UpdateStats(level);
zhihuange9e94c32016-11-04 11:38:15 -07001424 // The StatsCollector is used to tell if a track is valid because it may
1425 // remember tracks that the PeerConnection previously removed.
1426 if (track && !stats_->IsValidTrack(track->id())) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001427 RTC_LOG(LS_WARNING) << "GetStats is called with an invalid track: "
1428 << track->id();
zhihuange9e94c32016-11-04 11:38:15 -07001429 return false;
1430 }
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001431 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_GETSTATS,
tommi@webrtc.org5b06b062014-08-15 08:38:30 +00001432 new GetStatsMsg(observer, track));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001433 return true;
1434}
1435
hbos74e1a4f2016-09-15 23:33:01 -07001436void PeerConnection::GetStats(RTCStatsCollectorCallback* callback) {
1437 RTC_DCHECK(stats_collector_);
1438 stats_collector_->GetStatsReport(callback);
1439}
1440
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001441PeerConnectionInterface::SignalingState PeerConnection::signaling_state() {
1442 return signaling_state_;
1443}
1444
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001445PeerConnectionInterface::IceConnectionState
1446PeerConnection::ice_connection_state() {
1447 return ice_connection_state_;
1448}
1449
1450PeerConnectionInterface::IceGatheringState
1451PeerConnection::ice_gathering_state() {
1452 return ice_gathering_state_;
1453}
1454
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001455rtc::scoped_refptr<DataChannelInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001456PeerConnection::CreateDataChannel(
1457 const std::string& label,
1458 const DataChannelInit* config) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001459 TRACE_EVENT0("webrtc", "PeerConnection::CreateDataChannel");
zhihuang9763d562016-08-05 11:14:50 -07001460
deadbeefab9b2d12015-10-14 11:33:11 -07001461 bool first_datachannel = !HasDataChannels();
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001462
kwibergd1fe2812016-04-27 06:47:29 -07001463 std::unique_ptr<InternalDataChannelInit> internal_config;
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00001464 if (config) {
1465 internal_config.reset(new InternalDataChannelInit(*config));
1466 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001467 rtc::scoped_refptr<DataChannelInterface> channel(
deadbeefab9b2d12015-10-14 11:33:11 -07001468 InternalCreateDataChannel(label, internal_config.get()));
1469 if (!channel.get()) {
1470 return nullptr;
1471 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001472
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001473 // Trigger the onRenegotiationNeeded event for every new RTP DataChannel, or
1474 // the first SCTP DataChannel.
Steve Anton75737c02017-11-06 10:37:17 -08001475 if (data_channel_type() == cricket::DCT_RTP || first_datachannel) {
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001476 observer_->OnRenegotiationNeeded();
1477 }
wu@webrtc.org91053e72013-08-10 07:18:04 +00001478
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001479 return DataChannelProxy::Create(signaling_thread(), channel.get());
1480}
1481
1482void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
1483 const MediaConstraintsInterface* constraints) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001484 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
Steve Anton8d3444d2017-10-20 15:30:51 -07001485
zhihuang1c378ed2017-08-17 14:10:50 -07001486 PeerConnectionInterface::RTCOfferAnswerOptions offer_answer_options;
1487 // Always create an offer even if |ConvertConstraintsToOfferAnswerOptions|
1488 // returns false for now. Because |ConvertConstraintsToOfferAnswerOptions|
1489 // compares the mandatory fields parsed with the mandatory fields added in the
1490 // |constraints| and some downstream applications might create offers with
1491 // mandatory fields which would not be parsed in the helper method. For
1492 // example, in Chromium/remoting, |kEnableDtlsSrtp| is added to the
1493 // |constraints| as a mandatory field but it is not parsed.
1494 ConvertConstraintsToOfferAnswerOptions(constraints, &offer_answer_options);
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001495
zhihuang1c378ed2017-08-17 14:10:50 -07001496 CreateOffer(observer, offer_answer_options);
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001497}
1498
1499void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
1500 const RTCOfferAnswerOptions& options) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001501 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
Steve Anton8d3444d2017-10-20 15:30:51 -07001502
nisse7ce109a2017-01-31 00:57:56 -08001503 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001504 RTC_LOG(LS_ERROR) << "CreateOffer - observer is NULL.";
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001505 return;
1506 }
deadbeefab9b2d12015-10-14 11:33:11 -07001507
Steve Anton8d3444d2017-10-20 15:30:51 -07001508 if (IsClosed()) {
1509 std::string error = "CreateOffer called when PeerConnection is closed.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001510 RTC_LOG(LS_ERROR) << error;
Steve Anton8d3444d2017-10-20 15:30:51 -07001511 PostCreateSessionDescriptionFailure(observer, error);
1512 return;
1513 }
1514
zhihuang1c378ed2017-08-17 14:10:50 -07001515 if (!ValidateOfferAnswerOptions(options)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001516 std::string error = "CreateOffer called with invalid options.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001517 RTC_LOG(LS_ERROR) << error;
deadbeefab9b2d12015-10-14 11:33:11 -07001518 PostCreateSessionDescriptionFailure(observer, error);
1519 return;
1520 }
1521
zhihuang1c378ed2017-08-17 14:10:50 -07001522 cricket::MediaSessionOptions session_options;
1523 GetOptionsForOffer(options, &session_options);
Steve Antond25da372017-11-06 14:50:29 -08001524 webrtc_session_desc_factory_->CreateOffer(observer, options, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001525}
1526
1527void PeerConnection::CreateAnswer(
1528 CreateSessionDescriptionObserver* observer,
1529 const MediaConstraintsInterface* constraints) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001530 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
Steve Anton8d3444d2017-10-20 15:30:51 -07001531
nisse7ce109a2017-01-31 00:57:56 -08001532 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001533 RTC_LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001534 return;
1535 }
deadbeefab9b2d12015-10-14 11:33:11 -07001536
zhihuang1c378ed2017-08-17 14:10:50 -07001537 PeerConnectionInterface::RTCOfferAnswerOptions offer_answer_options;
1538 if (!ConvertConstraintsToOfferAnswerOptions(constraints,
1539 &offer_answer_options)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001540 std::string error = "CreateAnswer called with invalid constraints.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001541 RTC_LOG(LS_ERROR) << error;
deadbeefab9b2d12015-10-14 11:33:11 -07001542 PostCreateSessionDescriptionFailure(observer, error);
1543 return;
1544 }
1545
Steve Anton8d3444d2017-10-20 15:30:51 -07001546 CreateAnswer(observer, offer_answer_options);
htaa2a49d92016-03-04 02:51:39 -08001547}
1548
1549void PeerConnection::CreateAnswer(CreateSessionDescriptionObserver* observer,
1550 const RTCOfferAnswerOptions& options) {
1551 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
nisse7ce109a2017-01-31 00:57:56 -08001552 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001553 RTC_LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
htaa2a49d92016-03-04 02:51:39 -08001554 return;
1555 }
1556
Steve Anton8d3444d2017-10-20 15:30:51 -07001557 if (IsClosed()) {
1558 std::string error = "CreateAnswer called when PeerConnection is closed.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001559 RTC_LOG(LS_ERROR) << error;
Steve Anton8d3444d2017-10-20 15:30:51 -07001560 PostCreateSessionDescriptionFailure(observer, error);
1561 return;
1562 }
1563
Steve Anton75737c02017-11-06 10:37:17 -08001564 if (remote_description() &&
Steve Antona3a92c22017-12-07 10:27:41 -08001565 remote_description()->GetType() != SdpType::kOffer) {
Steve Anton8d3444d2017-10-20 15:30:51 -07001566 std::string error = "CreateAnswer called without remote offer.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001567 RTC_LOG(LS_ERROR) << error;
Steve Anton8d3444d2017-10-20 15:30:51 -07001568 PostCreateSessionDescriptionFailure(observer, error);
1569 return;
1570 }
1571
htaa2a49d92016-03-04 02:51:39 -08001572 cricket::MediaSessionOptions session_options;
zhihuang1c378ed2017-08-17 14:10:50 -07001573 GetOptionsForAnswer(options, &session_options);
htaa2a49d92016-03-04 02:51:39 -08001574
Steve Antond25da372017-11-06 14:50:29 -08001575 webrtc_session_desc_factory_->CreateAnswer(observer, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001576}
1577
1578void PeerConnection::SetLocalDescription(
1579 SetSessionDescriptionObserver* observer,
1580 SessionDescriptionInterface* desc) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001581 TRACE_EVENT0("webrtc", "PeerConnection::SetLocalDescription");
Steve Anton8a006912017-12-04 15:25:56 -08001582
nisse7ce109a2017-01-31 00:57:56 -08001583 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001584 RTC_LOG(LS_ERROR) << "SetLocalDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001585 return;
1586 }
Steve Anton8a006912017-12-04 15:25:56 -08001587
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001588 if (!desc) {
1589 PostSetSessionDescriptionFailure(observer, "SessionDescription is NULL.");
1590 return;
1591 }
Steve Anton8d3444d2017-10-20 15:30:51 -07001592
Steve Antona3a92c22017-12-07 10:27:41 -08001593 SdpType type = desc->GetType();
Steve Anton8d3444d2017-10-20 15:30:51 -07001594
Steve Anton8a006912017-12-04 15:25:56 -08001595 RTCError error = ApplyLocalDescription(rtc::WrapUnique(desc));
1596 // |desc| may be destroyed at this point.
1597
1598 if (!error.ok()) {
Steve Antona3a92c22017-12-07 10:27:41 -08001599 std::ostringstream oss;
1600 oss << "Failed to set local " << SdpTypeToString(type)
1601 << " sdp: " << error.message();
1602 std::string error_message = oss.str();
Steve Anton8a006912017-12-04 15:25:56 -08001603 RTC_LOG(LS_ERROR) << error_message << " (" << error.type() << ")";
1604 PostSetSessionDescriptionFailure(observer, std::move(error_message));
Steve Anton8d3444d2017-10-20 15:30:51 -07001605 return;
1606 }
Steve Anton8a006912017-12-04 15:25:56 -08001607 RTC_DCHECK(local_description());
1608
1609 PostSetSessionDescriptionSuccess(observer);
1610
1611 // According to JSEP, after setLocalDescription, changing the candidate pool
1612 // size is not allowed, and changing the set of ICE servers will not result
1613 // in new candidates being gathered.
1614 port_allocator_->FreezeCandidatePool();
1615
1616 // MaybeStartGathering needs to be called after posting
1617 // MSG_SET_SESSIONDESCRIPTION_SUCCESS, so that we don't signal any candidates
1618 // before signaling that SetLocalDescription completed.
1619 transport_controller_->MaybeStartGathering();
1620
Steve Antona3a92c22017-12-07 10:27:41 -08001621 if (local_description()->GetType() == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08001622 // TODO(deadbeef): We already had to hop to the network thread for
1623 // MaybeStartGathering...
1624 network_thread()->Invoke<void>(
1625 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
1626 port_allocator_.get()));
1627 }
1628}
1629
1630RTCError PeerConnection::ApplyLocalDescription(
1631 std::unique_ptr<SessionDescriptionInterface> desc) {
1632 RTC_DCHECK_RUN_ON(signaling_thread());
1633 RTC_DCHECK(desc);
1634
1635 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_LOCAL);
1636 if (!error.ok()) {
1637 return error;
1638 }
Steve Anton8d3444d2017-10-20 15:30:51 -07001639
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001640 // Update stats here so that we have the most recent stats for tracks and
1641 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001642 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 15:25:56 -08001643
1644 // Update the initial_offerer flag if this session is the initial_offerer.
Steve Anton3828c062017-12-06 10:34:51 -08001645 SdpType type = desc->GetType();
Steve Anton8a006912017-12-04 15:25:56 -08001646 if (!initial_offerer_.has_value()) {
Steve Anton3828c062017-12-06 10:34:51 -08001647 initial_offerer_.emplace(type == SdpType::kOffer);
Steve Anton8a006912017-12-04 15:25:56 -08001648 if (*initial_offerer_) {
1649 transport_controller_->SetIceRole(cricket::ICEROLE_CONTROLLING);
1650 } else {
1651 transport_controller_->SetIceRole(cricket::ICEROLE_CONTROLLED);
1652 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001653 }
Steve Anton8a006912017-12-04 15:25:56 -08001654
Steve Anton3828c062017-12-06 10:34:51 -08001655 if (type == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08001656 current_local_description_ = std::move(desc);
1657 pending_local_description_ = nullptr;
1658 current_remote_description_ = std::move(pending_remote_description_);
1659 } else {
1660 pending_local_description_ = std::move(desc);
1661 }
1662 // The session description to apply now must be accessed by
1663 // |local_description()|.
Henrik Boströmfdb92012017-11-09 19:55:44 +01001664 RTC_DCHECK(local_description());
deadbeefab9b2d12015-10-14 11:33:11 -07001665
Steve Anton8a006912017-12-04 15:25:56 -08001666 // Transport and Media channels will be created only when offer is set.
Steve Anton3828c062017-12-06 10:34:51 -08001667 if (type == SdpType::kOffer) {
Steve Anton8a006912017-12-04 15:25:56 -08001668 // TODO(mallinath) - Handle CreateChannel failure, as new local description
1669 // is applied. Restore back to old description.
1670 RTCError error = CreateChannels(local_description()->description());
1671 if (!error.ok()) {
1672 return error;
1673 }
1674 }
1675
1676 // Remove unused channels if MediaContentDescription is rejected.
1677 RemoveUnusedChannels(local_description()->description());
1678
Steve Anton3828c062017-12-06 10:34:51 -08001679 error = UpdateSessionState(type, cricket::CS_LOCAL);
Steve Anton8a006912017-12-04 15:25:56 -08001680 if (!error.ok()) {
1681 return error;
1682 }
1683 if (remote_description()) {
1684 // Now that we have a local description, we can push down remote candidates.
1685 UseCandidatesInSessionDescription(remote_description());
1686 }
1687
1688 pending_ice_restarts_.clear();
1689 if (session_error() != SessionError::kNone) {
1690 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
1691 }
1692
deadbeefab9b2d12015-10-14 11:33:11 -07001693 // If setting the description decided our SSL role, allocate any necessary
1694 // SCTP sids.
1695 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08001696 if (data_channel_type() == cricket::DCT_SCTP && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001697 AllocateSctpSids(role);
1698 }
1699
1700 // Update state and SSRC of local MediaStreams and DataChannels based on the
1701 // local session description.
1702 const cricket::ContentInfo* audio_content =
Henrik Boströmfdb92012017-11-09 19:55:44 +01001703 GetFirstAudioContent(local_description()->description());
deadbeefab9b2d12015-10-14 11:33:11 -07001704 if (audio_content) {
deadbeeffaac4972015-11-12 15:33:07 -08001705 if (audio_content->rejected) {
Steve Anton4171afb2017-11-20 10:20:22 -08001706 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
deadbeeffaac4972015-11-12 15:33:07 -08001707 } else {
1708 const cricket::AudioContentDescription* audio_desc =
1709 static_cast<const cricket::AudioContentDescription*>(
1710 audio_content->description);
Steve Anton4171afb2017-11-20 10:20:22 -08001711 UpdateLocalSenders(audio_desc->streams(), audio_desc->type());
deadbeeffaac4972015-11-12 15:33:07 -08001712 }
deadbeefab9b2d12015-10-14 11:33:11 -07001713 }
1714
1715 const cricket::ContentInfo* video_content =
Henrik Boströmfdb92012017-11-09 19:55:44 +01001716 GetFirstVideoContent(local_description()->description());
deadbeefab9b2d12015-10-14 11:33:11 -07001717 if (video_content) {
deadbeeffaac4972015-11-12 15:33:07 -08001718 if (video_content->rejected) {
Steve Anton4171afb2017-11-20 10:20:22 -08001719 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
deadbeeffaac4972015-11-12 15:33:07 -08001720 } else {
1721 const cricket::VideoContentDescription* video_desc =
1722 static_cast<const cricket::VideoContentDescription*>(
1723 video_content->description);
Steve Anton4171afb2017-11-20 10:20:22 -08001724 UpdateLocalSenders(video_desc->streams(), video_desc->type());
deadbeeffaac4972015-11-12 15:33:07 -08001725 }
deadbeefab9b2d12015-10-14 11:33:11 -07001726 }
1727
1728 const cricket::ContentInfo* data_content =
Henrik Boströmfdb92012017-11-09 19:55:44 +01001729 GetFirstDataContent(local_description()->description());
deadbeefab9b2d12015-10-14 11:33:11 -07001730 if (data_content) {
1731 const cricket::DataContentDescription* data_desc =
1732 static_cast<const cricket::DataContentDescription*>(
1733 data_content->description);
1734 if (rtc::starts_with(data_desc->protocol().data(),
1735 cricket::kMediaProtocolRtpPrefix)) {
1736 UpdateLocalRtpDataChannels(data_desc->streams());
1737 }
1738 }
1739
Steve Anton8a006912017-12-04 15:25:56 -08001740 return RTCError::OK();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001741}
1742
1743void PeerConnection::SetRemoteDescription(
Henrik Boströma4ecf552017-11-23 14:17:07 +00001744 SetSessionDescriptionObserver* observer,
1745 SessionDescriptionInterface* desc) {
Henrik Boström31638672017-11-23 17:48:32 +01001746 SetRemoteDescription(
1747 std::unique_ptr<SessionDescriptionInterface>(desc),
1748 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface>(
1749 new SetRemoteDescriptionObserverAdapter(this, observer)));
1750}
1751
1752void PeerConnection::SetRemoteDescription(
1753 std::unique_ptr<SessionDescriptionInterface> desc,
1754 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface> observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001755 TRACE_EVENT0("webrtc", "PeerConnection::SetRemoteDescription");
Steve Anton8a006912017-12-04 15:25:56 -08001756
nisse7ce109a2017-01-31 00:57:56 -08001757 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001758 RTC_LOG(LS_ERROR) << "SetRemoteDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001759 return;
1760 }
Steve Anton8a006912017-12-04 15:25:56 -08001761
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001762 if (!desc) {
Henrik Boström31638672017-11-23 17:48:32 +01001763 observer->OnSetRemoteDescriptionComplete(RTCError(
Steve Anton8a006912017-12-04 15:25:56 -08001764 RTCErrorType::INVALID_PARAMETER, "SessionDescription is NULL."));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001765 return;
1766 }
Steve Anton8d3444d2017-10-20 15:30:51 -07001767
Steve Antona3a92c22017-12-07 10:27:41 -08001768 const SdpType type = desc->GetType();
Steve Anton8a006912017-12-04 15:25:56 -08001769
1770 RTCError error = ApplyRemoteDescription(std::move(desc));
1771 // |desc| may be destroyed at this point.
1772
1773 if (!error.ok()) {
Steve Antona3a92c22017-12-07 10:27:41 -08001774 std::ostringstream oss;
1775 oss << "Failed to set remote " << SdpTypeToString(type)
1776 << " sdp: " << error.message();
1777 std::string error_message = oss.str();
Steve Anton8a006912017-12-04 15:25:56 -08001778 RTC_LOG(LS_ERROR) << error_message << " (" << error.type() << ")";
Henrik Boström31638672017-11-23 17:48:32 +01001779 observer->OnSetRemoteDescriptionComplete(
Steve Anton8a006912017-12-04 15:25:56 -08001780 RTCError(error.type(), std::move(error_message)));
Steve Anton8d3444d2017-10-20 15:30:51 -07001781 return;
1782 }
1783
Steve Antona3a92c22017-12-07 10:27:41 -08001784 if (remote_description()->GetType() == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08001785 // TODO(deadbeef): We already had to hop to the network thread for
1786 // MaybeStartGathering...
1787 network_thread()->Invoke<void>(
1788 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
1789 port_allocator_.get()));
1790 }
1791
1792 observer->OnSetRemoteDescriptionComplete(RTCError::OK());
1793}
1794
1795RTCError PeerConnection::ApplyRemoteDescription(
1796 std::unique_ptr<SessionDescriptionInterface> desc) {
1797 RTC_DCHECK_RUN_ON(signaling_thread());
1798 RTC_DCHECK(desc);
1799
1800 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_REMOTE);
1801 if (!error.ok()) {
1802 return error;
1803 }
1804
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001805 // Update stats here so that we have the most recent stats for tracks and
1806 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001807 stats_->UpdateStats(kStatsOutputLevelStandard);
Henrik Boström31638672017-11-23 17:48:32 +01001808 // Takes the ownership of |desc|. On success, remote_description() is updated
1809 // to reflect the description that was passed in.
Steve Anton8a006912017-12-04 15:25:56 -08001810
1811 const SessionDescriptionInterface* old_remote_description =
1812 remote_description();
1813 // Grab ownership of the description being replaced for the remainder of this
1814 // method, since it's used below as |old_remote_description|.
1815 std::unique_ptr<SessionDescriptionInterface> replaced_remote_description;
Steve Anton3828c062017-12-06 10:34:51 -08001816 SdpType type = desc->GetType();
1817 if (type == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08001818 replaced_remote_description = pending_remote_description_
1819 ? std::move(pending_remote_description_)
1820 : std::move(current_remote_description_);
1821 current_remote_description_ = std::move(desc);
1822 pending_remote_description_ = nullptr;
1823 current_local_description_ = std::move(pending_local_description_);
1824 } else {
1825 replaced_remote_description = std::move(pending_remote_description_);
1826 pending_remote_description_ = std::move(desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001827 }
Steve Anton8a006912017-12-04 15:25:56 -08001828 // The session description to apply now must be accessed by
1829 // |remote_description()|.
Henrik Boströmfdb92012017-11-09 19:55:44 +01001830 RTC_DCHECK(remote_description());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001831
Steve Anton8a006912017-12-04 15:25:56 -08001832 // Transport and Media channels will be created only when offer is set.
Steve Anton3828c062017-12-06 10:34:51 -08001833 if (type == SdpType::kOffer) {
Steve Anton8a006912017-12-04 15:25:56 -08001834 // TODO(mallinath) - Handle CreateChannel failure, as new local description
1835 // is applied. Restore back to old description.
1836 RTCError error = CreateChannels(remote_description()->description());
1837 if (!error.ok()) {
1838 return error;
1839 }
1840 }
1841
1842 // Remove unused channels if MediaContentDescription is rejected.
1843 RemoveUnusedChannels(remote_description()->description());
1844
1845 // NOTE: Candidates allocation will be initiated only when SetLocalDescription
1846 // is called.
Steve Anton3828c062017-12-06 10:34:51 -08001847 error = UpdateSessionState(type, cricket::CS_REMOTE);
Steve Anton8a006912017-12-04 15:25:56 -08001848 if (!error.ok()) {
1849 return error;
1850 }
1851
1852 if (local_description() &&
1853 !UseCandidatesInSessionDescription(remote_description())) {
1854 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidCandidates);
1855 }
1856
1857 if (old_remote_description) {
1858 for (const cricket::ContentInfo& content :
1859 old_remote_description->description()->contents()) {
1860 // Check if this new SessionDescription contains new ICE ufrag and
1861 // password that indicates the remote peer requests an ICE restart.
1862 // TODO(deadbeef): When we start storing both the current and pending
1863 // remote description, this should reset pending_ice_restarts and compare
1864 // against the current description.
1865 if (CheckForRemoteIceRestart(old_remote_description, remote_description(),
1866 content.name)) {
Steve Anton3828c062017-12-06 10:34:51 -08001867 if (type == SdpType::kOffer) {
Steve Anton8a006912017-12-04 15:25:56 -08001868 pending_ice_restarts_.insert(content.name);
1869 }
1870 } else {
1871 // We retain all received candidates only if ICE is not restarted.
1872 // When ICE is restarted, all previous candidates belong to an old
1873 // generation and should not be kept.
1874 // TODO(deadbeef): This goes against the W3C spec which says the remote
1875 // description should only contain candidates from the last set remote
1876 // description plus any candidates added since then. We should remove
1877 // this once we're sure it won't break anything.
1878 WebRtcSessionDescriptionFactory::CopyCandidatesFromSessionDescription(
1879 old_remote_description, content.name, mutable_remote_description());
1880 }
1881 }
1882 }
1883
1884 if (session_error() != SessionError::kNone) {
1885 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
1886 }
1887
1888 // Set the the ICE connection state to connecting since the connection may
1889 // become writable with peer reflexive candidates before any remote candidate
1890 // is signaled.
1891 // TODO(pthatcher): This is a short-term solution for crbug/446908. A real fix
1892 // is to have a new signal the indicates a change in checking state from the
1893 // transport and expose a new checking() member from transport that can be
1894 // read to determine the current checking state. The existing SignalConnecting
1895 // actually means "gathering candidates", so cannot be be used here.
Steve Antona3a92c22017-12-07 10:27:41 -08001896 if (remote_description()->GetType() != SdpType::kOffer &&
Steve Anton8a006912017-12-04 15:25:56 -08001897 ice_connection_state() == PeerConnectionInterface::kIceConnectionNew) {
1898 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
1899 }
1900
deadbeefab9b2d12015-10-14 11:33:11 -07001901 // If setting the description decided our SSL role, allocate any necessary
1902 // SCTP sids.
1903 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08001904 if (data_channel_type() == cricket::DCT_SCTP && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001905 AllocateSctpSids(role);
1906 }
1907
Henrik Boströmfdb92012017-11-09 19:55:44 +01001908 const cricket::ContentInfo* audio_content =
1909 GetFirstAudioContent(remote_description()->description());
1910 const cricket::ContentInfo* video_content =
1911 GetFirstVideoContent(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08001912 const cricket::AudioContentDescription* audio_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01001913 GetFirstAudioContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08001914 const cricket::VideoContentDescription* video_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01001915 GetFirstVideoContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08001916 const cricket::DataContentDescription* data_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01001917 GetFirstDataContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08001918
1919 // Check if the descriptions include streams, just in case the peer supports
1920 // MSID, but doesn't indicate so with "a=msid-semantic".
Henrik Boströmfdb92012017-11-09 19:55:44 +01001921 if (remote_description()->description()->msid_supported() ||
deadbeefbda7e0b2015-12-08 17:13:40 -08001922 (audio_desc && !audio_desc->streams().empty()) ||
1923 (video_desc && !video_desc->streams().empty())) {
1924 remote_peer_supports_msid_ = true;
1925 }
deadbeefab9b2d12015-10-14 11:33:11 -07001926
1927 // We wait to signal new streams until we finish processing the description,
1928 // since only at that point will new streams have all their tracks.
1929 rtc::scoped_refptr<StreamCollection> new_streams(StreamCollection::Create());
1930
Steve Anton8d3444d2017-10-20 15:30:51 -07001931 // TODO(steveanton): When removing RTP senders/receivers in response to a
1932 // rejected media section, there is some cleanup logic that expects the voice/
1933 // video channel to still be set. But in this method the voice/video channel
Steve Anton75737c02017-11-06 10:37:17 -08001934 // would have been destroyed by the SetRemoteDescription caller above so the
Steve Anton4171afb2017-11-20 10:20:22 -08001935 // cleanup that relies on them fails to run. The RemoveSenders calls should be
Steve Anton75737c02017-11-06 10:37:17 -08001936 // moved to right before the DestroyChannel calls to fix this.
Steve Anton8d3444d2017-10-20 15:30:51 -07001937
deadbeefab9b2d12015-10-14 11:33:11 -07001938 // Find all audio rtp streams and create corresponding remote AudioTracks
1939 // and MediaStreams.
deadbeefab9b2d12015-10-14 11:33:11 -07001940 if (audio_content) {
deadbeeffaac4972015-11-12 15:33:07 -08001941 if (audio_content->rejected) {
Steve Anton4171afb2017-11-20 10:20:22 -08001942 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
deadbeeffaac4972015-11-12 15:33:07 -08001943 } else {
deadbeefbda7e0b2015-12-08 17:13:40 -08001944 bool default_audio_track_needed =
1945 !remote_peer_supports_msid_ &&
Steve Anton4e70a722017-11-28 14:57:10 -08001946 RtpTransceiverDirectionHasSend(audio_desc->direction());
Steve Anton4171afb2017-11-20 10:20:22 -08001947 UpdateRemoteSendersList(GetActiveStreams(audio_desc),
deadbeefbda7e0b2015-12-08 17:13:40 -08001948 default_audio_track_needed, audio_desc->type(),
deadbeeffaac4972015-11-12 15:33:07 -08001949 new_streams);
deadbeeffaac4972015-11-12 15:33:07 -08001950 }
deadbeefab9b2d12015-10-14 11:33:11 -07001951 }
1952
1953 // Find all video rtp streams and create corresponding remote VideoTracks
1954 // and MediaStreams.
deadbeefab9b2d12015-10-14 11:33:11 -07001955 if (video_content) {
deadbeeffaac4972015-11-12 15:33:07 -08001956 if (video_content->rejected) {
Steve Anton4171afb2017-11-20 10:20:22 -08001957 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
deadbeeffaac4972015-11-12 15:33:07 -08001958 } else {
deadbeefbda7e0b2015-12-08 17:13:40 -08001959 bool default_video_track_needed =
1960 !remote_peer_supports_msid_ &&
Steve Anton4e70a722017-11-28 14:57:10 -08001961 RtpTransceiverDirectionHasSend(video_desc->direction());
Steve Anton4171afb2017-11-20 10:20:22 -08001962 UpdateRemoteSendersList(GetActiveStreams(video_desc),
deadbeefbda7e0b2015-12-08 17:13:40 -08001963 default_video_track_needed, video_desc->type(),
deadbeeffaac4972015-11-12 15:33:07 -08001964 new_streams);
deadbeeffaac4972015-11-12 15:33:07 -08001965 }
deadbeefab9b2d12015-10-14 11:33:11 -07001966 }
1967
1968 // Update the DataChannels with the information from the remote peer.
deadbeefbda7e0b2015-12-08 17:13:40 -08001969 if (data_desc) {
1970 if (rtc::starts_with(data_desc->protocol().data(),
deadbeefab9b2d12015-10-14 11:33:11 -07001971 cricket::kMediaProtocolRtpPrefix)) {
deadbeefbda7e0b2015-12-08 17:13:40 -08001972 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
deadbeefab9b2d12015-10-14 11:33:11 -07001973 }
1974 }
1975
1976 // Iterate new_streams and notify the observer about new MediaStreams.
1977 for (size_t i = 0; i < new_streams->count(); ++i) {
1978 MediaStreamInterface* new_stream = new_streams->at(i);
1979 stats_->AddStream(new_stream);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07001980 observer_->OnAddStream(
1981 rtc::scoped_refptr<MediaStreamInterface>(new_stream));
deadbeefab9b2d12015-10-14 11:33:11 -07001982 }
1983
deadbeefbda7e0b2015-12-08 17:13:40 -08001984 UpdateEndedRemoteMediaStreams();
deadbeefab9b2d12015-10-14 11:33:11 -07001985
Steve Anton8a006912017-12-04 15:25:56 -08001986 return RTCError::OK();
deadbeeffc648b62015-10-13 16:42:33 -07001987}
1988
Steve Antoned10bd92017-12-05 10:52:59 -08001989const cricket::ContentInfo* PeerConnection::FindMediaSectionForTransceiver(
1990 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1991 transceiver,
1992 const SessionDescriptionInterface* sdesc) const {
1993 RTC_DCHECK(transceiver);
1994 RTC_DCHECK(sdesc);
1995 if (IsUnifiedPlan()) {
1996 if (!transceiver->internal()->mid()) {
1997 // This transceiver is not associated with a media section yet.
1998 return nullptr;
1999 }
2000 return sdesc->description()->GetContentByName(
2001 *transceiver->internal()->mid());
2002 } else {
2003 // Plan B only allows at most one audio and one video section, so use the
2004 // first media section of that type.
2005 return cricket::GetFirstMediaContent(sdesc->description()->contents(),
2006 transceiver->internal()->media_type());
2007 }
2008}
2009
deadbeef46c73892016-11-16 19:42:04 -08002010PeerConnectionInterface::RTCConfiguration PeerConnection::GetConfiguration() {
2011 return configuration_;
2012}
2013
deadbeef293e9262017-01-11 12:28:30 -08002014bool PeerConnection::SetConfiguration(const RTCConfiguration& configuration,
2015 RTCError* error) {
Peter Boström1a9d6152015-12-08 22:15:17 +01002016 TRACE_EVENT0("webrtc", "PeerConnection::SetConfiguration");
deadbeef6de92f92016-12-12 18:49:32 -08002017
Steve Anton75737c02017-11-06 10:37:17 -08002018 if (local_description() && configuration.ice_candidate_pool_size !=
2019 configuration_.ice_candidate_pool_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002020 RTC_LOG(LS_ERROR) << "Can't change candidate pool size after calling "
2021 "SetLocalDescription.";
deadbeef293e9262017-01-11 12:28:30 -08002022 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00002023 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002024
deadbeef293e9262017-01-11 12:28:30 -08002025 // The simplest (and most future-compatible) way to tell if the config was
2026 // modified in an invalid way is to copy each property we do support
2027 // modifying, then use operator==. There are far more properties we don't
2028 // support modifying than those we do, and more could be added.
2029 RTCConfiguration modified_config = configuration_;
2030 modified_config.servers = configuration.servers;
2031 modified_config.type = configuration.type;
2032 modified_config.ice_candidate_pool_size =
2033 configuration.ice_candidate_pool_size;
2034 modified_config.prune_turn_ports = configuration.prune_turn_ports;
skvladd1f5fda2017-02-03 16:54:05 -08002035 modified_config.ice_check_min_interval = configuration.ice_check_min_interval;
Jonas Orelandbdcee282017-10-10 14:01:40 +02002036 modified_config.turn_customizer = configuration.turn_customizer;
deadbeef293e9262017-01-11 12:28:30 -08002037 if (configuration != modified_config) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002038 RTC_LOG(LS_ERROR) << "Modifying the configuration in an unsupported way.";
deadbeef293e9262017-01-11 12:28:30 -08002039 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
2040 }
2041
Steve Anton038834f2017-07-14 15:59:59 -07002042 // Validate the modified configuration.
2043 RTCError validate_error = ValidateConfiguration(modified_config);
2044 if (!validate_error.ok()) {
2045 return SafeSetError(std::move(validate_error), error);
2046 }
2047
deadbeef293e9262017-01-11 12:28:30 -08002048 // Note that this isn't possible through chromium, since it's an unsigned
2049 // short in WebIDL.
2050 if (configuration.ice_candidate_pool_size < 0 ||
2051 configuration.ice_candidate_pool_size > UINT16_MAX) {
2052 return SafeSetError(RTCErrorType::INVALID_RANGE, error);
2053 }
2054
2055 // Parse ICE servers before hopping to network thread.
2056 cricket::ServerAddresses stun_servers;
2057 std::vector<cricket::RelayServerConfig> turn_servers;
2058 RTCErrorType parse_error =
2059 ParseIceServers(configuration.servers, &stun_servers, &turn_servers);
2060 if (parse_error != RTCErrorType::NONE) {
2061 return SafeSetError(parse_error, error);
2062 }
2063
2064 // In theory this shouldn't fail.
2065 if (!network_thread()->Invoke<bool>(
2066 RTC_FROM_HERE,
2067 rtc::Bind(&PeerConnection::ReconfigurePortAllocator_n, this,
2068 stun_servers, turn_servers, modified_config.type,
2069 modified_config.ice_candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02002070 modified_config.prune_turn_ports,
2071 modified_config.turn_customizer))) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002072 RTC_LOG(LS_ERROR) << "Failed to apply configuration to PortAllocator.";
deadbeef293e9262017-01-11 12:28:30 -08002073 return SafeSetError(RTCErrorType::INTERNAL_ERROR, error);
2074 }
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07002075
deadbeefd1a38b52016-12-10 13:15:33 -08002076 // As described in JSEP, calling setConfiguration with new ICE servers or
2077 // candidate policy must set a "needs-ice-restart" bit so that the next offer
2078 // triggers an ICE restart which will pick up the changes.
deadbeef293e9262017-01-11 12:28:30 -08002079 if (modified_config.servers != configuration_.servers ||
2080 modified_config.type != configuration_.type ||
2081 modified_config.prune_turn_ports != configuration_.prune_turn_ports) {
Steve Antond25da372017-11-06 14:50:29 -08002082 transport_controller_->SetNeedsIceRestartFlag();
deadbeefd1a38b52016-12-10 13:15:33 -08002083 }
skvladd1f5fda2017-02-03 16:54:05 -08002084
2085 if (modified_config.ice_check_min_interval !=
2086 configuration_.ice_check_min_interval) {
Steve Antond25da372017-11-06 14:50:29 -08002087 transport_controller_->SetIceConfig(ParseIceConfig(modified_config));
skvladd1f5fda2017-02-03 16:54:05 -08002088 }
2089
deadbeef293e9262017-01-11 12:28:30 -08002090 configuration_ = modified_config;
2091 return SafeSetError(RTCErrorType::NONE, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00002092}
2093
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002094bool PeerConnection::AddIceCandidate(
2095 const IceCandidateInterface* ice_candidate) {
Peter Boström1a9d6152015-12-08 22:15:17 +01002096 TRACE_EVENT0("webrtc", "PeerConnection::AddIceCandidate");
zhihuang29ff8442016-07-27 11:07:25 -07002097 if (IsClosed()) {
2098 return false;
2099 }
Steve Antond25da372017-11-06 14:50:29 -08002100
2101 if (!remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002102 RTC_LOG(LS_ERROR) << "ProcessIceMessage: ICE candidates can't be added "
2103 << "without any remote session description.";
Steve Antond25da372017-11-06 14:50:29 -08002104 return false;
2105 }
2106
2107 if (!ice_candidate) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002108 RTC_LOG(LS_ERROR) << "ProcessIceMessage: Candidate is NULL.";
Steve Antond25da372017-11-06 14:50:29 -08002109 return false;
2110 }
2111
2112 bool valid = false;
2113 bool ready = ReadyToUseRemoteCandidate(ice_candidate, nullptr, &valid);
2114 if (!valid) {
2115 return false;
2116 }
2117
2118 // Add this candidate to the remote session description.
2119 if (!mutable_remote_description()->AddCandidate(ice_candidate)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002120 RTC_LOG(LS_ERROR) << "ProcessIceMessage: Candidate cannot be used.";
Steve Antond25da372017-11-06 14:50:29 -08002121 return false;
2122 }
2123
2124 if (ready) {
2125 return UseCandidate(ice_candidate);
2126 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002127 RTC_LOG(LS_INFO) << "ProcessIceMessage: Not ready to use candidate.";
Steve Antond25da372017-11-06 14:50:29 -08002128 return true;
2129 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002130}
2131
Honghai Zhang7fb69db2016-03-14 11:59:18 -07002132bool PeerConnection::RemoveIceCandidates(
2133 const std::vector<cricket::Candidate>& candidates) {
2134 TRACE_EVENT0("webrtc", "PeerConnection::RemoveIceCandidates");
Steve Antond25da372017-11-06 14:50:29 -08002135 if (!remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002136 RTC_LOG(LS_ERROR) << "RemoveRemoteIceCandidates: ICE candidates can't be "
2137 << "removed without any remote session description.";
Steve Antond25da372017-11-06 14:50:29 -08002138 return false;
2139 }
2140
2141 if (candidates.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002142 RTC_LOG(LS_ERROR) << "RemoveRemoteIceCandidates: candidates are empty.";
Steve Antond25da372017-11-06 14:50:29 -08002143 return false;
2144 }
2145
2146 size_t number_removed =
2147 mutable_remote_description()->RemoveCandidates(candidates);
2148 if (number_removed != candidates.size()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002149 RTC_LOG(LS_ERROR)
2150 << "RemoveRemoteIceCandidates: Failed to remove candidates. "
2151 << "Requested " << candidates.size() << " but only " << number_removed
2152 << " are removed.";
Steve Antond25da372017-11-06 14:50:29 -08002153 }
2154
2155 // Remove the candidates from the transport controller.
2156 std::string error;
2157 bool res = transport_controller_->RemoveRemoteCandidates(candidates, &error);
2158 if (!res && !error.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002159 RTC_LOG(LS_ERROR) << "Error when removing remote candidates: " << error;
Steve Antond25da372017-11-06 14:50:29 -08002160 }
2161 return true;
Honghai Zhang7fb69db2016-03-14 11:59:18 -07002162}
2163
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00002164void PeerConnection::RegisterUMAObserver(UMAObserver* observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +01002165 TRACE_EVENT0("webrtc", "PeerConnection::RegisterUmaObserver");
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00002166 uma_observer_ = observer;
guoweis@webrtc.org7169afd2014-12-04 17:59:29 +00002167
Steve Anton75737c02017-11-06 10:37:17 -08002168 if (transport_controller()) {
2169 transport_controller()->SetMetricsObserver(uma_observer_);
guoweis@webrtc.org7169afd2014-12-04 17:59:29 +00002170 }
2171
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00002172 // Send information about IPv4/IPv6 status.
deadbeef293e9262017-01-11 12:28:30 -08002173 if (uma_observer_) {
Honghai Zhangd93f50c2016-10-05 11:47:22 -07002174 port_allocator_->SetMetricsObserver(uma_observer_);
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00002175 if (port_allocator_->flags() & cricket::PORTALLOCATOR_ENABLE_IPV6) {
Guo-wei Shiehdfbe6792015-09-03 17:12:07 -07002176 uma_observer_->IncrementEnumCounter(
2177 kEnumCounterAddressFamily, kPeerConnection_IPv6,
2178 kPeerConnectionAddressFamilyCounter_Max);
mallinath@webrtc.orgb445f262014-05-23 22:19:37 +00002179 } else {
Guo-wei Shiehdfbe6792015-09-03 17:12:07 -07002180 uma_observer_->IncrementEnumCounter(
2181 kEnumCounterAddressFamily, kPeerConnection_IPv4,
2182 kPeerConnectionAddressFamilyCounter_Max);
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00002183 }
2184 }
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00002185}
2186
zstein4b979802017-06-02 14:37:37 -07002187RTCError PeerConnection::SetBitrate(const BitrateParameters& bitrate) {
Steve Anton978b8762017-09-29 12:15:02 -07002188 if (!worker_thread()->IsCurrent()) {
2189 return worker_thread()->Invoke<RTCError>(
zstein4b979802017-06-02 14:37:37 -07002190 RTC_FROM_HERE, rtc::Bind(&PeerConnection::SetBitrate, this, bitrate));
2191 }
2192
2193 const bool has_min = static_cast<bool>(bitrate.min_bitrate_bps);
2194 const bool has_current = static_cast<bool>(bitrate.current_bitrate_bps);
2195 const bool has_max = static_cast<bool>(bitrate.max_bitrate_bps);
2196 if (has_min && *bitrate.min_bitrate_bps < 0) {
2197 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2198 "min_bitrate_bps <= 0");
2199 }
2200 if (has_current) {
2201 if (has_min && *bitrate.current_bitrate_bps < *bitrate.min_bitrate_bps) {
2202 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2203 "current_bitrate_bps < min_bitrate_bps");
2204 } else if (*bitrate.current_bitrate_bps < 0) {
2205 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2206 "curent_bitrate_bps < 0");
2207 }
2208 }
2209 if (has_max) {
2210 if (has_current &&
2211 *bitrate.max_bitrate_bps < *bitrate.current_bitrate_bps) {
2212 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2213 "max_bitrate_bps < current_bitrate_bps");
2214 } else if (has_min && *bitrate.max_bitrate_bps < *bitrate.min_bitrate_bps) {
2215 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2216 "max_bitrate_bps < min_bitrate_bps");
2217 } else if (*bitrate.max_bitrate_bps < 0) {
2218 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2219 "max_bitrate_bps < 0");
2220 }
2221 }
2222
2223 Call::Config::BitrateConfigMask mask;
2224 mask.min_bitrate_bps = bitrate.min_bitrate_bps;
2225 mask.start_bitrate_bps = bitrate.current_bitrate_bps;
2226 mask.max_bitrate_bps = bitrate.max_bitrate_bps;
2227
2228 RTC_DCHECK(call_.get());
2229 call_->SetBitrateConfigMask(mask);
2230
2231 return RTCError::OK();
2232}
2233
Alex Narest78609d52017-10-20 10:37:47 +02002234void PeerConnection::SetBitrateAllocationStrategy(
2235 std::unique_ptr<rtc::BitrateAllocationStrategy>
2236 bitrate_allocation_strategy) {
2237 rtc::Thread* worker_thread = factory_->worker_thread();
2238 if (!worker_thread->IsCurrent()) {
2239 rtc::BitrateAllocationStrategy* strategy_raw =
2240 bitrate_allocation_strategy.release();
2241 auto functor = [this, strategy_raw]() {
2242 call_->SetBitrateAllocationStrategy(
2243 rtc::WrapUnique<rtc::BitrateAllocationStrategy>(strategy_raw));
2244 };
2245 worker_thread->Invoke<void>(RTC_FROM_HERE, functor);
2246 return;
2247 }
2248 RTC_DCHECK(call_.get());
2249 call_->SetBitrateAllocationStrategy(std::move(bitrate_allocation_strategy));
2250}
2251
henrika5f6bf242017-11-01 11:06:56 +01002252void PeerConnection::SetAudioPlayout(bool playout) {
2253 if (!worker_thread()->IsCurrent()) {
2254 worker_thread()->Invoke<void>(
2255 RTC_FROM_HERE,
2256 rtc::Bind(&PeerConnection::SetAudioPlayout, this, playout));
2257 return;
2258 }
2259 auto audio_state =
2260 factory_->channel_manager()->media_engine()->GetAudioState();
2261 audio_state->SetPlayout(playout);
2262}
2263
2264void PeerConnection::SetAudioRecording(bool recording) {
2265 if (!worker_thread()->IsCurrent()) {
2266 worker_thread()->Invoke<void>(
2267 RTC_FROM_HERE,
2268 rtc::Bind(&PeerConnection::SetAudioRecording, this, recording));
2269 return;
2270 }
2271 auto audio_state =
2272 factory_->channel_manager()->media_engine()->GetAudioState();
2273 audio_state->SetRecording(recording);
2274}
2275
Steve Anton8c0f7a72017-10-03 10:03:10 -07002276std::unique_ptr<rtc::SSLCertificate>
2277PeerConnection::GetRemoteAudioSSLCertificate() {
Steve Anton75737c02017-11-06 10:37:17 -08002278 if (!voice_channel()) {
Steve Anton8c0f7a72017-10-03 10:03:10 -07002279 return nullptr;
2280 }
Steve Anton75737c02017-11-06 10:37:17 -08002281 return GetRemoteSSLCertificate(voice_channel()->transport_name());
Steve Anton8c0f7a72017-10-03 10:03:10 -07002282}
2283
ivoc14d5dbe2016-07-04 07:06:55 -07002284bool PeerConnection::StartRtcEventLog(rtc::PlatformFile file,
2285 int64_t max_size_bytes) {
Elad Alon99c3fe52017-10-13 16:29:40 +02002286 // TODO(eladalon): It would be better to not allow negative values into PC.
2287 const size_t max_size = (max_size_bytes < 0)
2288 ? RtcEventLog::kUnlimitedOutput
2289 : rtc::saturated_cast<size_t>(max_size_bytes);
2290 return StartRtcEventLog(
Bjorn Tereliusde939432017-11-20 17:38:14 +01002291 rtc::MakeUnique<RtcEventLogOutputFile>(file, max_size),
2292 webrtc::RtcEventLog::kImmediateOutput);
Elad Alon99c3fe52017-10-13 16:29:40 +02002293}
2294
Bjorn Tereliusde939432017-11-20 17:38:14 +01002295bool PeerConnection::StartRtcEventLog(std::unique_ptr<RtcEventLogOutput> output,
2296 int64_t output_period_ms) {
Karl Wibergd6b48192017-10-16 23:01:06 +02002297 // TODO(eladalon): In C++14, this can be done with a lambda.
2298 struct Functor {
Bjorn Tereliusde939432017-11-20 17:38:14 +01002299 bool operator()() {
2300 return pc->StartRtcEventLog_w(std::move(output), output_period_ms);
2301 }
Karl Wibergd6b48192017-10-16 23:01:06 +02002302 PeerConnection* const pc;
2303 std::unique_ptr<RtcEventLogOutput> output;
Bjorn Tereliusde939432017-11-20 17:38:14 +01002304 const int64_t output_period_ms;
Elad Alon99c3fe52017-10-13 16:29:40 +02002305 };
Bjorn Tereliusde939432017-11-20 17:38:14 +01002306 return worker_thread()->Invoke<bool>(
2307 RTC_FROM_HERE, Functor{this, std::move(output), output_period_ms});
ivoc14d5dbe2016-07-04 07:06:55 -07002308}
2309
2310void PeerConnection::StopRtcEventLog() {
Steve Anton978b8762017-09-29 12:15:02 -07002311 worker_thread()->Invoke<void>(
ivoc14d5dbe2016-07-04 07:06:55 -07002312 RTC_FROM_HERE, rtc::Bind(&PeerConnection::StopRtcEventLog_w, this));
2313}
2314
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002315const SessionDescriptionInterface* PeerConnection::local_description() const {
Steve Anton75737c02017-11-06 10:37:17 -08002316 return pending_local_description_ ? pending_local_description_.get()
2317 : current_local_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002318}
2319
2320const SessionDescriptionInterface* PeerConnection::remote_description() const {
Steve Anton75737c02017-11-06 10:37:17 -08002321 return pending_remote_description_ ? pending_remote_description_.get()
2322 : current_remote_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002323}
2324
deadbeeffe4a8a42016-12-20 17:56:17 -08002325const SessionDescriptionInterface* PeerConnection::current_local_description()
2326 const {
Steve Anton75737c02017-11-06 10:37:17 -08002327 return current_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08002328}
2329
2330const SessionDescriptionInterface* PeerConnection::current_remote_description()
2331 const {
Steve Anton75737c02017-11-06 10:37:17 -08002332 return current_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08002333}
2334
2335const SessionDescriptionInterface* PeerConnection::pending_local_description()
2336 const {
Steve Anton75737c02017-11-06 10:37:17 -08002337 return pending_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08002338}
2339
2340const SessionDescriptionInterface* PeerConnection::pending_remote_description()
2341 const {
Steve Anton75737c02017-11-06 10:37:17 -08002342 return pending_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08002343}
2344
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002345void PeerConnection::Close() {
Peter Boström1a9d6152015-12-08 22:15:17 +01002346 TRACE_EVENT0("webrtc", "PeerConnection::Close");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002347 // Update stats here so that we have the most recent stats for tracks and
2348 // streams before the channels are closed.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00002349 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002350
Steve Anton75737c02017-11-06 10:37:17 -08002351 ChangeSignalingState(PeerConnectionInterface::kClosed);
Steve Anton3fe1b152017-12-12 10:20:08 -08002352
Steve Anton8af21862017-12-15 11:20:13 -08002353 for (auto transceiver : transceivers_) {
2354 transceiver->Stop();
2355 }
2356 DestroyAllChannels();
Steve Anton75737c02017-11-06 10:37:17 -08002357
deadbeef42a42632017-03-10 15:18:00 -08002358 network_thread()->Invoke<void>(
2359 RTC_FROM_HERE,
2360 rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
2361 port_allocator_.get()));
nisseeaabdf62017-05-05 02:23:02 -07002362
Steve Anton978b8762017-09-29 12:15:02 -07002363 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
eladalon248fd4f2017-09-06 05:18:15 -07002364 call_.reset();
2365 // The event log must outlive call (and any other object that uses it).
2366 event_log_.reset();
2367 });
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002368}
2369
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002370void PeerConnection::OnMessage(rtc::Message* msg) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002371 switch (msg->message_id) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002372 case MSG_SET_SESSIONDESCRIPTION_SUCCESS: {
2373 SetSessionDescriptionMsg* param =
2374 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
2375 param->observer->OnSuccess();
2376 delete param;
2377 break;
2378 }
2379 case MSG_SET_SESSIONDESCRIPTION_FAILED: {
2380 SetSessionDescriptionMsg* param =
2381 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
2382 param->observer->OnFailure(param->error);
2383 delete param;
2384 break;
2385 }
deadbeefab9b2d12015-10-14 11:33:11 -07002386 case MSG_CREATE_SESSIONDESCRIPTION_FAILED: {
2387 CreateSessionDescriptionMsg* param =
2388 static_cast<CreateSessionDescriptionMsg*>(msg->pdata);
2389 param->observer->OnFailure(param->error);
2390 delete param;
2391 break;
2392 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002393 case MSG_GETSTATS: {
2394 GetStatsMsg* param = static_cast<GetStatsMsg*>(msg->pdata);
nissee8abe3e2017-01-18 05:00:34 -08002395 StatsReports reports;
2396 stats_->GetStats(param->track, &reports);
2397 param->observer->OnComplete(reports);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002398 delete param;
2399 break;
2400 }
deadbeefbd292462015-12-14 18:15:29 -08002401 case MSG_FREE_DATACHANNELS: {
2402 sctp_data_channels_to_free_.clear();
2403 break;
2404 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002405 default:
nisseeb4ca4e2017-01-12 02:24:27 -08002406 RTC_NOTREACHED() << "Not implemented";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002407 break;
2408 }
2409}
2410
Steve Anton4171afb2017-11-20 10:20:22 -08002411void PeerConnection::CreateAudioReceiver(
2412 MediaStreamInterface* stream,
2413 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01002414 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
2415 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
zhihuang81c3a032016-11-17 12:06:24 -08002416 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
2417 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
deadbeefe814a0d2017-02-25 18:15:09 -08002418 signaling_thread(),
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01002419 new AudioRtpReceiver(remote_sender_info.sender_id, streams,
Steve Anton4171afb2017-11-20 10:20:22 -08002420 remote_sender_info.first_ssrc, voice_channel()));
deadbeefe814a0d2017-02-25 18:15:09 -08002421 stream->AddTrack(
2422 static_cast<AudioTrackInterface*>(receiver->internal()->track().get()));
Steve Anton4171afb2017-11-20 10:20:22 -08002423 GetAudioTransceiver()->internal()->AddReceiver(receiver);
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01002424 observer_->OnAddTrack(receiver, std::move(streams));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002425}
2426
Steve Anton4171afb2017-11-20 10:20:22 -08002427void PeerConnection::CreateVideoReceiver(
2428 MediaStreamInterface* stream,
2429 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01002430 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
2431 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
zhihuang81c3a032016-11-17 12:06:24 -08002432 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
2433 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
Steve Anton4171afb2017-11-20 10:20:22 -08002434 signaling_thread(),
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01002435 new VideoRtpReceiver(remote_sender_info.sender_id, streams,
2436 worker_thread(), remote_sender_info.first_ssrc,
2437 video_channel()));
deadbeefe814a0d2017-02-25 18:15:09 -08002438 stream->AddTrack(
2439 static_cast<VideoTrackInterface*>(receiver->internal()->track().get()));
Steve Anton4171afb2017-11-20 10:20:22 -08002440 GetVideoTransceiver()->internal()->AddReceiver(receiver);
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01002441 observer_->OnAddTrack(receiver, std::move(streams));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002442}
2443
deadbeef70ab1a12015-09-28 16:53:55 -07002444// TODO(deadbeef): Keep RtpReceivers around even if track goes away in remote
2445// description.
Henrik Boström933d8b02017-10-10 10:05:16 -07002446rtc::scoped_refptr<RtpReceiverInterface> PeerConnection::RemoveAndStopReceiver(
Steve Anton4171afb2017-11-20 10:20:22 -08002447 const RtpSenderInfo& remote_sender_info) {
2448 auto receiver = FindReceiverById(remote_sender_info.sender_id);
2449 if (!receiver) {
2450 RTC_LOG(LS_WARNING) << "RtpReceiver for track with id "
2451 << remote_sender_info.sender_id << " doesn't exist.";
Henrik Boström933d8b02017-10-10 10:05:16 -07002452 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07002453 }
Steve Anton4171afb2017-11-20 10:20:22 -08002454 if (receiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
2455 GetAudioTransceiver()->internal()->RemoveReceiver(receiver);
2456 } else {
2457 GetVideoTransceiver()->internal()->RemoveReceiver(receiver);
2458 }
Henrik Boström933d8b02017-10-10 10:05:16 -07002459 return receiver;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002460}
2461
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002462void PeerConnection::AddAudioTrack(AudioTrackInterface* track,
2463 MediaStreamInterface* stream) {
2464 RTC_DCHECK(!IsClosed());
2465 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08002466 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002467 // We already have a sender for this track, so just change the stream_id
2468 // so that it's correct in the next call to CreateOffer.
Steve Anton4171afb2017-11-20 10:20:22 -08002469 sender->internal()->set_stream_id(stream->label());
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002470 return;
2471 }
2472
2473 // Normal case; we've never seen this track before.
2474 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender =
2475 RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
2476 signaling_thread(),
Steve Anton75737c02017-11-06 10:37:17 -08002477 new AudioRtpSender(track, {stream->label()}, voice_channel(),
2478 stats_.get()));
Steve Anton4171afb2017-11-20 10:20:22 -08002479 GetAudioTransceiver()->internal()->AddSender(new_sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002480 // If the sender has already been configured in SDP, we call SetSsrc,
2481 // which will connect the sender to the underlying transport. This can
2482 // occur if a local session description that contains the ID of the sender
2483 // is set before AddStream is called. It can also occur if the local
2484 // session description is not changed and RemoveStream is called, and
2485 // later AddStream is called again with the same stream.
Steve Anton4171afb2017-11-20 10:20:22 -08002486 const RtpSenderInfo* sender_info =
2487 FindSenderInfo(local_audio_sender_infos_, stream->label(), track->id());
2488 if (sender_info) {
2489 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002490 }
2491}
2492
2493// TODO(deadbeef): Don't destroy RtpSenders here; they should be kept around
2494// indefinitely, when we have unified plan SDP.
2495void PeerConnection::RemoveAudioTrack(AudioTrackInterface* track,
2496 MediaStreamInterface* stream) {
2497 RTC_DCHECK(!IsClosed());
2498 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08002499 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002500 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
2501 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002502 return;
2503 }
Steve Anton4171afb2017-11-20 10:20:22 -08002504 GetAudioTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002505}
2506
2507void PeerConnection::AddVideoTrack(VideoTrackInterface* track,
2508 MediaStreamInterface* stream) {
2509 RTC_DCHECK(!IsClosed());
2510 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08002511 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002512 // We already have a sender for this track, so just change the stream_id
2513 // so that it's correct in the next call to CreateOffer.
Steve Anton4171afb2017-11-20 10:20:22 -08002514 sender->internal()->set_stream_id(stream->label());
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002515 return;
2516 }
2517
2518 // Normal case; we've never seen this track before.
2519 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender =
2520 RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton75737c02017-11-06 10:37:17 -08002521 signaling_thread(),
2522 new VideoRtpSender(track, {stream->label()}, video_channel()));
Steve Anton4171afb2017-11-20 10:20:22 -08002523 GetVideoTransceiver()->internal()->AddSender(new_sender);
2524 const RtpSenderInfo* sender_info =
2525 FindSenderInfo(local_video_sender_infos_, stream->label(), track->id());
2526 if (sender_info) {
2527 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002528 }
2529}
2530
2531void PeerConnection::RemoveVideoTrack(VideoTrackInterface* track,
2532 MediaStreamInterface* stream) {
2533 RTC_DCHECK(!IsClosed());
2534 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08002535 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002536 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
2537 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002538 return;
2539 }
Steve Anton4171afb2017-11-20 10:20:22 -08002540 GetVideoTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002541}
2542
Steve Antonba818672017-11-06 10:21:57 -08002543void PeerConnection::SetIceConnectionState(IceConnectionState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07002544 RTC_DCHECK(signaling_thread()->IsCurrent());
Steve Antonba818672017-11-06 10:21:57 -08002545 if (ice_connection_state_ == new_state) {
2546 return;
2547 }
2548
deadbeefcbecd352015-09-23 11:50:27 -07002549 // After transitioning to "closed", ignore any additional states from
Steve Antonba818672017-11-06 10:21:57 -08002550 // TransportController (such as "disconnected").
deadbeefab9b2d12015-10-14 11:33:11 -07002551 if (IsClosed()) {
deadbeefcbecd352015-09-23 11:50:27 -07002552 return;
2553 }
Steve Antonba818672017-11-06 10:21:57 -08002554
Mirko Bonadei675513b2017-11-09 11:09:25 +01002555 RTC_LOG(LS_INFO) << "Changing IceConnectionState " << ice_connection_state_
2556 << " => " << new_state;
Steve Antonba818672017-11-06 10:21:57 -08002557 RTC_DCHECK(ice_connection_state_ !=
2558 PeerConnectionInterface::kIceConnectionClosed);
2559
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002560 ice_connection_state_ = new_state;
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00002561 observer_->OnIceConnectionChange(ice_connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002562}
2563
2564void PeerConnection::OnIceGatheringChange(
2565 PeerConnectionInterface::IceGatheringState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07002566 RTC_DCHECK(signaling_thread()->IsCurrent());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002567 if (IsClosed()) {
2568 return;
2569 }
2570 ice_gathering_state_ = new_state;
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00002571 observer_->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002572}
2573
jbauch81bf7b02017-03-25 08:31:12 -07002574void PeerConnection::OnIceCandidate(
2575 std::unique_ptr<IceCandidateInterface> candidate) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07002576 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07002577 if (IsClosed()) {
2578 return;
2579 }
jbauch81bf7b02017-03-25 08:31:12 -07002580 observer_->OnIceCandidate(candidate.get());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002581}
2582
Honghai Zhang7fb69db2016-03-14 11:59:18 -07002583void PeerConnection::OnIceCandidatesRemoved(
2584 const std::vector<cricket::Candidate>& candidates) {
2585 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07002586 if (IsClosed()) {
2587 return;
2588 }
Honghai Zhang7fb69db2016-03-14 11:59:18 -07002589 observer_->OnIceCandidatesRemoved(candidates);
2590}
2591
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002592void PeerConnection::ChangeSignalingState(
2593 PeerConnectionInterface::SignalingState signaling_state) {
Steve Antonba818672017-11-06 10:21:57 -08002594 RTC_DCHECK(signaling_thread()->IsCurrent());
2595 if (signaling_state_ == signaling_state) {
2596 return;
2597 }
Mirko Bonadei675513b2017-11-09 11:09:25 +01002598 RTC_LOG(LS_INFO) << "Session: " << session_id() << " Old state: "
2599 << GetSignalingStateString(signaling_state_)
2600 << " New state: "
2601 << GetSignalingStateString(signaling_state);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002602 signaling_state_ = signaling_state;
2603 if (signaling_state == kClosed) {
2604 ice_connection_state_ = kIceConnectionClosed;
2605 observer_->OnIceConnectionChange(ice_connection_state_);
2606 if (ice_gathering_state_ != kIceGatheringComplete) {
2607 ice_gathering_state_ = kIceGatheringComplete;
2608 observer_->OnIceGatheringChange(ice_gathering_state_);
2609 }
2610 }
2611 observer_->OnSignalingChange(signaling_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002612}
2613
deadbeefeb459812015-12-15 19:24:43 -08002614void PeerConnection::OnAudioTrackAdded(AudioTrackInterface* track,
2615 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07002616 if (IsClosed()) {
2617 return;
2618 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002619 AddAudioTrack(track, stream);
2620 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08002621}
2622
deadbeefeb459812015-12-15 19:24:43 -08002623void PeerConnection::OnAudioTrackRemoved(AudioTrackInterface* track,
2624 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07002625 if (IsClosed()) {
2626 return;
2627 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002628 RemoveAudioTrack(track, stream);
2629 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08002630}
2631
2632void PeerConnection::OnVideoTrackAdded(VideoTrackInterface* track,
2633 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07002634 if (IsClosed()) {
2635 return;
2636 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002637 AddVideoTrack(track, stream);
2638 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08002639}
2640
2641void PeerConnection::OnVideoTrackRemoved(VideoTrackInterface* track,
2642 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07002643 if (IsClosed()) {
2644 return;
2645 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002646 RemoveVideoTrack(track, stream);
2647 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08002648}
2649
Henrik Boström31638672017-11-23 17:48:32 +01002650void PeerConnection::PostSetSessionDescriptionSuccess(
2651 SetSessionDescriptionObserver* observer) {
2652 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
2653 signaling_thread()->Post(RTC_FROM_HERE, this,
2654 MSG_SET_SESSIONDESCRIPTION_SUCCESS, msg);
2655}
2656
deadbeefab9b2d12015-10-14 11:33:11 -07002657void PeerConnection::PostSetSessionDescriptionFailure(
2658 SetSessionDescriptionObserver* observer,
2659 const std::string& error) {
2660 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
2661 msg->error = error;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07002662 signaling_thread()->Post(RTC_FROM_HERE, this,
2663 MSG_SET_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07002664}
2665
2666void PeerConnection::PostCreateSessionDescriptionFailure(
2667 CreateSessionDescriptionObserver* observer,
2668 const std::string& error) {
2669 CreateSessionDescriptionMsg* msg = new CreateSessionDescriptionMsg(observer);
2670 msg->error = error;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07002671 signaling_thread()->Post(RTC_FROM_HERE, this,
2672 MSG_CREATE_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07002673}
2674
zhihuang1c378ed2017-08-17 14:10:50 -07002675void PeerConnection::GetOptionsForOffer(
deadbeefab9b2d12015-10-14 11:33:11 -07002676 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options,
2677 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07002678 ExtractSharedMediaSessionOptions(rtc_options, session_options);
2679
2680 // Figure out transceiver directional preferences.
2681 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
2682 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
2683
2684 // By default, generate sendrecv/recvonly m= sections.
2685 bool recv_audio = true;
2686 bool recv_video = true;
2687
2688 // By default, only offer a new m= section if we have media to send with it.
2689 bool offer_new_audio_description = send_audio;
2690 bool offer_new_video_description = send_video;
2691 bool offer_new_data_description = HasDataChannels();
2692
2693 // The "offer_to_receive_X" options allow those defaults to be overridden.
2694 if (rtc_options.offer_to_receive_audio != RTCOfferAnswerOptions::kUndefined) {
2695 recv_audio = (rtc_options.offer_to_receive_audio > 0);
2696 offer_new_audio_description =
2697 offer_new_audio_description || (rtc_options.offer_to_receive_audio > 0);
2698 }
2699 if (rtc_options.offer_to_receive_video != RTCOfferAnswerOptions::kUndefined) {
2700 recv_video = (rtc_options.offer_to_receive_video > 0);
2701 offer_new_video_description =
2702 offer_new_video_description || (rtc_options.offer_to_receive_video > 0);
2703 }
2704
2705 rtc::Optional<size_t> audio_index;
2706 rtc::Optional<size_t> video_index;
2707 rtc::Optional<size_t> data_index;
2708 // If a current description exists, generate m= sections in the same order,
2709 // using the first audio/video/data section that appears and rejecting
2710 // extraneous ones.
Steve Anton75737c02017-11-06 10:37:17 -08002711 if (local_description()) {
zhihuang1c378ed2017-08-17 14:10:50 -07002712 GenerateMediaDescriptionOptions(
Steve Anton75737c02017-11-06 10:37:17 -08002713 local_description(),
Steve Anton1d03a752017-11-27 14:30:09 -08002714 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
2715 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
2716 &audio_index, &video_index, &data_index, session_options);
deadbeefab9b2d12015-10-14 11:33:11 -07002717 }
2718
zhihuang1c378ed2017-08-17 14:10:50 -07002719 // Add audio/video/data m= sections to the end if needed.
2720 if (!audio_index && offer_new_audio_description) {
2721 session_options->media_description_options.push_back(
2722 cricket::MediaDescriptionOptions(
2723 cricket::MEDIA_TYPE_AUDIO, cricket::CN_AUDIO,
Steve Anton1d03a752017-11-27 14:30:09 -08002724 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
2725 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01002726 audio_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07002727 }
zhihuang1c378ed2017-08-17 14:10:50 -07002728 if (!video_index && offer_new_video_description) {
2729 session_options->media_description_options.push_back(
2730 cricket::MediaDescriptionOptions(
2731 cricket::MEDIA_TYPE_VIDEO, cricket::CN_VIDEO,
Steve Anton1d03a752017-11-27 14:30:09 -08002732 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
2733 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01002734 video_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07002735 }
zhihuang1c378ed2017-08-17 14:10:50 -07002736 if (!data_index && offer_new_data_description) {
2737 session_options->media_description_options.push_back(
2738 cricket::MediaDescriptionOptions(
2739 cricket::MEDIA_TYPE_DATA, cricket::CN_DATA,
Steve Anton1d03a752017-11-27 14:30:09 -08002740 RtpTransceiverDirection::kSendRecv, false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01002741 data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07002742 }
2743
2744 cricket::MediaDescriptionOptions* audio_media_description_options =
2745 !audio_index ? nullptr
2746 : &session_options->media_description_options[*audio_index];
2747 cricket::MediaDescriptionOptions* video_media_description_options =
2748 !video_index ? nullptr
2749 : &session_options->media_description_options[*video_index];
2750 cricket::MediaDescriptionOptions* data_media_description_options =
2751 !data_index ? nullptr
2752 : &session_options->media_description_options[*data_index];
2753
2754 // Apply ICE restart flag and renomination flag.
2755 for (auto& options : session_options->media_description_options) {
2756 options.transport_options.ice_restart = rtc_options.ice_restart;
2757 options.transport_options.enable_ice_renomination =
2758 configuration_.enable_ice_renomination;
2759 }
2760
Steve Anton4171afb2017-11-20 10:20:22 -08002761 AddRtpSenderOptions(GetSendersInternal(), audio_media_description_options,
zhihuang1c378ed2017-08-17 14:10:50 -07002762 video_media_description_options);
2763 AddRtpDataChannelOptions(rtp_data_channels_, data_media_description_options);
deadbeefc80741f2015-10-22 13:14:45 -07002764
zhihuang9763d562016-08-05 11:14:50 -07002765 // Intentionally unset the data channel type for RTP data channel with the
2766 // second condition. Otherwise the RTP data channels would be successfully
2767 // negotiated by default and the unit tests in WebRtcDataBrowserTest will fail
2768 // when building with chromium. We want to leave RTP data channels broken, so
2769 // people won't try to use them.
Steve Anton75737c02017-11-06 10:37:17 -08002770 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
2771 session_options->data_channel_type = data_channel_type();
deadbeefab9b2d12015-10-14 11:33:11 -07002772 }
zhihuang8f65cdf2016-05-06 18:40:30 -07002773
2774 session_options->rtcp_cname = rtcp_cname_;
jbauchcb560652016-08-04 05:20:32 -07002775 session_options->crypto_options = factory_->options().crypto_options;
deadbeefab9b2d12015-10-14 11:33:11 -07002776}
2777
zhihuang1c378ed2017-08-17 14:10:50 -07002778void PeerConnection::GetOptionsForAnswer(
2779 const RTCOfferAnswerOptions& rtc_options,
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07002780 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07002781 ExtractSharedMediaSessionOptions(rtc_options, session_options);
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07002782
zhihuang1c378ed2017-08-17 14:10:50 -07002783 // Figure out transceiver directional preferences.
2784 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
2785 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
2786
2787 // By default, generate sendrecv/recvonly m= sections. The direction is also
2788 // restricted by the direction in the offer.
2789 bool recv_audio = true;
2790 bool recv_video = true;
2791
2792 // The "offer_to_receive_X" options allow those defaults to be overridden.
2793 if (rtc_options.offer_to_receive_audio != RTCOfferAnswerOptions::kUndefined) {
2794 recv_audio = (rtc_options.offer_to_receive_audio > 0);
deadbeef0ed85b22016-02-23 17:24:52 -08002795 }
zhihuang1c378ed2017-08-17 14:10:50 -07002796 if (rtc_options.offer_to_receive_video != RTCOfferAnswerOptions::kUndefined) {
2797 recv_video = (rtc_options.offer_to_receive_video > 0);
2798 }
2799
2800 rtc::Optional<size_t> audio_index;
2801 rtc::Optional<size_t> video_index;
2802 rtc::Optional<size_t> data_index;
Steve Anton75737c02017-11-06 10:37:17 -08002803 if (remote_description()) {
zhihuang141aacb2017-08-29 13:23:53 -07002804 // The pending remote description should be an offer.
Steve Antona3a92c22017-12-07 10:27:41 -08002805 RTC_DCHECK(remote_description()->GetType() == SdpType::kOffer);
zhihuang141aacb2017-08-29 13:23:53 -07002806 // Generate m= sections that match those in the offer.
2807 // Note that mediasession.cc will handle intersection our preferred
2808 // direction with the offered direction.
2809 GenerateMediaDescriptionOptions(
Steve Anton75737c02017-11-06 10:37:17 -08002810 remote_description(),
Steve Anton1d03a752017-11-27 14:30:09 -08002811 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
2812 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
2813 &audio_index, &video_index, &data_index, session_options);
zhihuang141aacb2017-08-29 13:23:53 -07002814 }
zhihuang1c378ed2017-08-17 14:10:50 -07002815
2816 cricket::MediaDescriptionOptions* audio_media_description_options =
2817 !audio_index ? nullptr
2818 : &session_options->media_description_options[*audio_index];
2819 cricket::MediaDescriptionOptions* video_media_description_options =
2820 !video_index ? nullptr
2821 : &session_options->media_description_options[*video_index];
2822 cricket::MediaDescriptionOptions* data_media_description_options =
2823 !data_index ? nullptr
2824 : &session_options->media_description_options[*data_index];
2825
2826 // Apply ICE renomination flag.
2827 for (auto& options : session_options->media_description_options) {
2828 options.transport_options.enable_ice_renomination =
2829 configuration_.enable_ice_renomination;
2830 }
2831
Steve Anton4171afb2017-11-20 10:20:22 -08002832 AddRtpSenderOptions(GetSendersInternal(), audio_media_description_options,
zhihuang1c378ed2017-08-17 14:10:50 -07002833 video_media_description_options);
2834 AddRtpDataChannelOptions(rtp_data_channels_, data_media_description_options);
2835
zhihuang9763d562016-08-05 11:14:50 -07002836 // Intentionally unset the data channel type for RTP data channel. Otherwise
2837 // the RTP data channels would be successfully negotiated by default and the
2838 // unit tests in WebRtcDataBrowserTest will fail when building with chromium.
2839 // We want to leave RTP data channels broken, so people won't try to use them.
Steve Anton75737c02017-11-06 10:37:17 -08002840 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
2841 session_options->data_channel_type = data_channel_type();
deadbeef907abe42016-08-04 12:22:18 -07002842 }
zhihuangaf388472016-11-02 16:49:48 -07002843
zhihuang1c378ed2017-08-17 14:10:50 -07002844 session_options->rtcp_cname = rtcp_cname_;
jbauchcb560652016-08-04 05:20:32 -07002845 session_options->crypto_options = factory_->options().crypto_options;
htaa2a49d92016-03-04 02:51:39 -08002846}
2847
zhihuang1c378ed2017-08-17 14:10:50 -07002848void PeerConnection::GenerateMediaDescriptionOptions(
2849 const SessionDescriptionInterface* session_desc,
Steve Anton1d03a752017-11-27 14:30:09 -08002850 RtpTransceiverDirection audio_direction,
2851 RtpTransceiverDirection video_direction,
zhihuang1c378ed2017-08-17 14:10:50 -07002852 rtc::Optional<size_t>* audio_index,
2853 rtc::Optional<size_t>* video_index,
2854 rtc::Optional<size_t>* data_index,
htaa2a49d92016-03-04 02:51:39 -08002855 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07002856 for (const cricket::ContentInfo& content :
2857 session_desc->description()->contents()) {
2858 if (IsAudioContent(&content)) {
2859 // If we already have an audio m= section, reject this extra one.
2860 if (*audio_index) {
2861 session_options->media_description_options.push_back(
2862 cricket::MediaDescriptionOptions(
2863 cricket::MEDIA_TYPE_AUDIO, content.name,
Steve Anton1d03a752017-11-27 14:30:09 -08002864 RtpTransceiverDirection::kInactive, true));
zhihuang1c378ed2017-08-17 14:10:50 -07002865 } else {
2866 session_options->media_description_options.push_back(
2867 cricket::MediaDescriptionOptions(
2868 cricket::MEDIA_TYPE_AUDIO, content.name, audio_direction,
Steve Anton1d03a752017-11-27 14:30:09 -08002869 audio_direction == RtpTransceiverDirection::kInactive));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01002870 *audio_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07002871 }
2872 } else if (IsVideoContent(&content)) {
2873 // If we already have an video m= section, reject this extra one.
2874 if (*video_index) {
2875 session_options->media_description_options.push_back(
2876 cricket::MediaDescriptionOptions(
2877 cricket::MEDIA_TYPE_VIDEO, content.name,
Steve Anton1d03a752017-11-27 14:30:09 -08002878 RtpTransceiverDirection::kInactive, true));
zhihuang1c378ed2017-08-17 14:10:50 -07002879 } else {
2880 session_options->media_description_options.push_back(
2881 cricket::MediaDescriptionOptions(
2882 cricket::MEDIA_TYPE_VIDEO, content.name, video_direction,
Steve Anton1d03a752017-11-27 14:30:09 -08002883 video_direction == RtpTransceiverDirection::kInactive));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01002884 *video_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07002885 }
2886 } else {
2887 RTC_DCHECK(IsDataContent(&content));
2888 // If we already have an data m= section, reject this extra one.
2889 if (*data_index) {
2890 session_options->media_description_options.push_back(
2891 cricket::MediaDescriptionOptions(
2892 cricket::MEDIA_TYPE_DATA, content.name,
Steve Anton1d03a752017-11-27 14:30:09 -08002893 RtpTransceiverDirection::kInactive, true));
zhihuang1c378ed2017-08-17 14:10:50 -07002894 } else {
2895 session_options->media_description_options.push_back(
2896 cricket::MediaDescriptionOptions(
2897 cricket::MEDIA_TYPE_DATA, content.name,
2898 // Direction for data sections is meaningless, but legacy
2899 // endpoints might expect sendrecv.
Steve Anton1d03a752017-11-27 14:30:09 -08002900 RtpTransceiverDirection::kSendRecv, false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01002901 *data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07002902 }
2903 }
htaa2a49d92016-03-04 02:51:39 -08002904 }
deadbeefab9b2d12015-10-14 11:33:11 -07002905}
2906
Steve Anton4171afb2017-11-20 10:20:22 -08002907void PeerConnection::RemoveSenders(cricket::MediaType media_type) {
2908 UpdateLocalSenders(std::vector<cricket::StreamParams>(), media_type);
2909 UpdateRemoteSendersList(std::vector<cricket::StreamParams>(), false,
deadbeefbda7e0b2015-12-08 17:13:40 -08002910 media_type, nullptr);
deadbeeffaac4972015-11-12 15:33:07 -08002911}
2912
Steve Anton4171afb2017-11-20 10:20:22 -08002913void PeerConnection::UpdateRemoteSendersList(
deadbeefab9b2d12015-10-14 11:33:11 -07002914 const cricket::StreamParamsVec& streams,
Steve Anton4171afb2017-11-20 10:20:22 -08002915 bool default_sender_needed,
deadbeefab9b2d12015-10-14 11:33:11 -07002916 cricket::MediaType media_type,
2917 StreamCollection* new_streams) {
Steve Anton4171afb2017-11-20 10:20:22 -08002918 std::vector<RtpSenderInfo>* current_senders =
2919 GetRemoteSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07002920
Steve Anton4171afb2017-11-20 10:20:22 -08002921 // Find removed senders. I.e., senders where the sender id or ssrc don't match
deadbeeffac06552015-11-25 11:26:01 -08002922 // the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08002923 for (auto sender_it = current_senders->begin();
2924 sender_it != current_senders->end();
2925 /* incremented manually */) {
2926 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07002927 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08002928 cricket::GetStreamBySsrc(streams, info.first_ssrc);
2929 bool sender_exists = params && params->id == info.sender_id;
deadbeefbda7e0b2015-12-08 17:13:40 -08002930 // If this is a default track, and we still need it, don't remove it.
Steve Anton4171afb2017-11-20 10:20:22 -08002931 if ((info.stream_label == kDefaultStreamLabel && default_sender_needed) ||
2932 sender_exists) {
2933 ++sender_it;
deadbeefbda7e0b2015-12-08 17:13:40 -08002934 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08002935 OnRemoteSenderRemoved(info, media_type);
2936 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07002937 }
2938 }
2939
Steve Anton4171afb2017-11-20 10:20:22 -08002940 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07002941 for (const cricket::StreamParams& params : streams) {
2942 // The sync_label is the MediaStream label and the |stream.id| is the
Steve Anton4171afb2017-11-20 10:20:22 -08002943 // sender id.
deadbeefab9b2d12015-10-14 11:33:11 -07002944 const std::string& stream_label = params.sync_label;
Steve Anton4171afb2017-11-20 10:20:22 -08002945 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07002946 uint32_t ssrc = params.first_ssrc();
2947
2948 rtc::scoped_refptr<MediaStreamInterface> stream =
2949 remote_streams_->find(stream_label);
2950 if (!stream) {
2951 // This is a new MediaStream. Create a new remote MediaStream.
perkjd61bf802016-03-24 03:16:19 -07002952 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
2953 MediaStream::Create(stream_label));
deadbeefab9b2d12015-10-14 11:33:11 -07002954 remote_streams_->AddStream(stream);
2955 new_streams->AddStream(stream);
2956 }
2957
Steve Anton4171afb2017-11-20 10:20:22 -08002958 const RtpSenderInfo* sender_info =
2959 FindSenderInfo(*current_senders, stream_label, sender_id);
2960 if (!sender_info) {
2961 current_senders->push_back(RtpSenderInfo(stream_label, sender_id, ssrc));
2962 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07002963 }
2964 }
deadbeefbda7e0b2015-12-08 17:13:40 -08002965
Steve Anton4171afb2017-11-20 10:20:22 -08002966 // Add default sender if necessary.
2967 if (default_sender_needed) {
deadbeefbda7e0b2015-12-08 17:13:40 -08002968 rtc::scoped_refptr<MediaStreamInterface> default_stream =
2969 remote_streams_->find(kDefaultStreamLabel);
2970 if (!default_stream) {
2971 // Create the new default MediaStream.
perkjd61bf802016-03-24 03:16:19 -07002972 default_stream = MediaStreamProxy::Create(
2973 rtc::Thread::Current(), MediaStream::Create(kDefaultStreamLabel));
deadbeefbda7e0b2015-12-08 17:13:40 -08002974 remote_streams_->AddStream(default_stream);
2975 new_streams->AddStream(default_stream);
2976 }
Steve Anton4171afb2017-11-20 10:20:22 -08002977 std::string default_sender_id = (media_type == cricket::MEDIA_TYPE_AUDIO)
2978 ? kDefaultAudioSenderId
2979 : kDefaultVideoSenderId;
2980 const RtpSenderInfo* default_sender_info = FindSenderInfo(
2981 *current_senders, kDefaultStreamLabel, default_sender_id);
2982 if (!default_sender_info) {
2983 current_senders->push_back(
2984 RtpSenderInfo(kDefaultStreamLabel, default_sender_id, 0));
2985 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefbda7e0b2015-12-08 17:13:40 -08002986 }
2987 }
deadbeefab9b2d12015-10-14 11:33:11 -07002988}
2989
Steve Anton4171afb2017-11-20 10:20:22 -08002990void PeerConnection::OnRemoteSenderAdded(const RtpSenderInfo& sender_info,
2991 cricket::MediaType media_type) {
2992 MediaStreamInterface* stream =
2993 remote_streams_->find(sender_info.stream_label);
deadbeefab9b2d12015-10-14 11:33:11 -07002994
2995 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 10:20:22 -08002996 CreateAudioReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07002997 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 10:20:22 -08002998 CreateVideoReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07002999 } else {
nisseeb4ca4e2017-01-12 02:24:27 -08003000 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07003001 }
3002}
3003
Steve Anton4171afb2017-11-20 10:20:22 -08003004void PeerConnection::OnRemoteSenderRemoved(const RtpSenderInfo& sender_info,
3005 cricket::MediaType media_type) {
3006 MediaStreamInterface* stream =
3007 remote_streams_->find(sender_info.stream_label);
deadbeefab9b2d12015-10-14 11:33:11 -07003008
Henrik Boström933d8b02017-10-10 10:05:16 -07003009 rtc::scoped_refptr<RtpReceiverInterface> receiver;
deadbeefab9b2d12015-10-14 11:33:11 -07003010 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
perkjd61bf802016-03-24 03:16:19 -07003011 // When the MediaEngine audio channel is destroyed, the RemoteAudioSource
3012 // will be notified which will end the AudioRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08003013 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07003014 rtc::scoped_refptr<AudioTrackInterface> audio_track =
Steve Anton4171afb2017-11-20 10:20:22 -08003015 stream->FindAudioTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07003016 if (audio_track) {
deadbeefab9b2d12015-10-14 11:33:11 -07003017 stream->RemoveTrack(audio_track);
deadbeefab9b2d12015-10-14 11:33:11 -07003018 }
3019 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
perkjd61bf802016-03-24 03:16:19 -07003020 // Stopping or destroying a VideoRtpReceiver will end the
3021 // VideoRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08003022 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07003023 rtc::scoped_refptr<VideoTrackInterface> video_track =
Steve Anton4171afb2017-11-20 10:20:22 -08003024 stream->FindVideoTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07003025 if (video_track) {
perkjd61bf802016-03-24 03:16:19 -07003026 // There's no guarantee the track is still available, e.g. the track may
3027 // have been removed from the stream by an application.
deadbeefab9b2d12015-10-14 11:33:11 -07003028 stream->RemoveTrack(video_track);
deadbeefab9b2d12015-10-14 11:33:11 -07003029 }
3030 } else {
nisseede5da42017-01-12 05:15:36 -08003031 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07003032 }
Henrik Boström933d8b02017-10-10 10:05:16 -07003033 if (receiver) {
3034 observer_->OnRemoveTrack(receiver);
3035 }
deadbeefab9b2d12015-10-14 11:33:11 -07003036}
3037
3038void PeerConnection::UpdateEndedRemoteMediaStreams() {
3039 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams_to_remove;
3040 for (size_t i = 0; i < remote_streams_->count(); ++i) {
3041 MediaStreamInterface* stream = remote_streams_->at(i);
3042 if (stream->GetAudioTracks().empty() && stream->GetVideoTracks().empty()) {
3043 streams_to_remove.push_back(stream);
3044 }
3045 }
3046
Taylor Brandstetter98cde262016-05-31 13:02:21 -07003047 for (auto& stream : streams_to_remove) {
deadbeefab9b2d12015-10-14 11:33:11 -07003048 remote_streams_->RemoveStream(stream);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07003049 observer_->OnRemoveStream(std::move(stream));
deadbeefab9b2d12015-10-14 11:33:11 -07003050 }
3051}
3052
Steve Anton4171afb2017-11-20 10:20:22 -08003053void PeerConnection::UpdateLocalSenders(
deadbeefab9b2d12015-10-14 11:33:11 -07003054 const std::vector<cricket::StreamParams>& streams,
3055 cricket::MediaType media_type) {
Steve Anton4171afb2017-11-20 10:20:22 -08003056 std::vector<RtpSenderInfo>* current_senders = GetLocalSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07003057
3058 // Find removed tracks. I.e., tracks where the track id, stream label or ssrc
3059 // don't match the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08003060 for (auto sender_it = current_senders->begin();
3061 sender_it != current_senders->end();
3062 /* incremented manually */) {
3063 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07003064 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08003065 cricket::GetStreamBySsrc(streams, info.first_ssrc);
3066 if (!params || params->id != info.sender_id ||
deadbeefab9b2d12015-10-14 11:33:11 -07003067 params->sync_label != info.stream_label) {
Steve Anton4171afb2017-11-20 10:20:22 -08003068 OnLocalSenderRemoved(info, media_type);
3069 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07003070 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08003071 ++sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07003072 }
3073 }
3074
Steve Anton4171afb2017-11-20 10:20:22 -08003075 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07003076 for (const cricket::StreamParams& params : streams) {
3077 // The sync_label is the MediaStream label and the |stream.id| is the
Steve Anton4171afb2017-11-20 10:20:22 -08003078 // sender id.
deadbeefab9b2d12015-10-14 11:33:11 -07003079 const std::string& stream_label = params.sync_label;
Steve Anton4171afb2017-11-20 10:20:22 -08003080 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07003081 uint32_t ssrc = params.first_ssrc();
Steve Anton4171afb2017-11-20 10:20:22 -08003082 const RtpSenderInfo* sender_info =
3083 FindSenderInfo(*current_senders, stream_label, sender_id);
3084 if (!sender_info) {
3085 current_senders->push_back(RtpSenderInfo(stream_label, sender_id, ssrc));
3086 OnLocalSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07003087 }
3088 }
3089}
3090
Steve Anton4171afb2017-11-20 10:20:22 -08003091void PeerConnection::OnLocalSenderAdded(const RtpSenderInfo& sender_info,
3092 cricket::MediaType media_type) {
3093 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08003094 if (!sender) {
Steve Anton4171afb2017-11-20 10:20:22 -08003095 RTC_LOG(LS_WARNING) << "An unknown RtpSender with id "
3096 << sender_info.sender_id
Mirko Bonadei675513b2017-11-09 11:09:25 +01003097 << " has been configured in the local description.";
deadbeefab9b2d12015-10-14 11:33:11 -07003098 return;
3099 }
3100
deadbeeffac06552015-11-25 11:26:01 -08003101 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003102 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
3103 << " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08003104 return;
deadbeefab9b2d12015-10-14 11:33:11 -07003105 }
deadbeeffac06552015-11-25 11:26:01 -08003106
Steve Anton4171afb2017-11-20 10:20:22 -08003107 sender->internal()->set_stream_id(sender_info.stream_label);
3108 sender->internal()->SetSsrc(sender_info.first_ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07003109}
3110
Steve Anton4171afb2017-11-20 10:20:22 -08003111void PeerConnection::OnLocalSenderRemoved(const RtpSenderInfo& sender_info,
3112 cricket::MediaType media_type) {
3113 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08003114 if (!sender) {
3115 // This is the normal case. I.e., RemoveStream has been called and the
deadbeefab9b2d12015-10-14 11:33:11 -07003116 // SessionDescriptions has been renegotiated.
3117 return;
3118 }
deadbeeffac06552015-11-25 11:26:01 -08003119
3120 // A sender has been removed from the SessionDescription but it's still
3121 // associated with the PeerConnection. This only occurs if the SDP doesn't
3122 // match with the calls to CreateSender, AddStream and RemoveStream.
3123 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003124 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
3125 << " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08003126 return;
deadbeefab9b2d12015-10-14 11:33:11 -07003127 }
deadbeeffac06552015-11-25 11:26:01 -08003128
Steve Anton4171afb2017-11-20 10:20:22 -08003129 sender->internal()->SetSsrc(0);
deadbeefab9b2d12015-10-14 11:33:11 -07003130}
3131
3132void PeerConnection::UpdateLocalRtpDataChannels(
3133 const cricket::StreamParamsVec& streams) {
3134 std::vector<std::string> existing_channels;
3135
3136 // Find new and active data channels.
3137 for (const cricket::StreamParams& params : streams) {
3138 // |it->sync_label| is actually the data channel label. The reason is that
3139 // we use the same naming of data channels as we do for
3140 // MediaStreams and Tracks.
3141 // For MediaStreams, the sync_label is the MediaStream label and the
3142 // track label is the same as |streamid|.
3143 const std::string& channel_label = params.sync_label;
3144 auto data_channel_it = rtp_data_channels_.find(channel_label);
nisse7ce109a2017-01-31 00:57:56 -08003145 if (data_channel_it == rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003146 RTC_LOG(LS_ERROR) << "channel label not found";
deadbeefab9b2d12015-10-14 11:33:11 -07003147 continue;
3148 }
3149 // Set the SSRC the data channel should use for sending.
3150 data_channel_it->second->SetSendSsrc(params.first_ssrc());
3151 existing_channels.push_back(data_channel_it->first);
3152 }
3153
3154 UpdateClosingRtpDataChannels(existing_channels, true);
3155}
3156
3157void PeerConnection::UpdateRemoteRtpDataChannels(
3158 const cricket::StreamParamsVec& streams) {
3159 std::vector<std::string> existing_channels;
3160
3161 // Find new and active data channels.
3162 for (const cricket::StreamParams& params : streams) {
3163 // The data channel label is either the mslabel or the SSRC if the mslabel
3164 // does not exist. Ex a=ssrc:444330170 mslabel:test1.
3165 std::string label = params.sync_label.empty()
3166 ? rtc::ToString(params.first_ssrc())
3167 : params.sync_label;
3168 auto data_channel_it = rtp_data_channels_.find(label);
3169 if (data_channel_it == rtp_data_channels_.end()) {
3170 // This is a new data channel.
3171 CreateRemoteRtpDataChannel(label, params.first_ssrc());
3172 } else {
3173 data_channel_it->second->SetReceiveSsrc(params.first_ssrc());
3174 }
3175 existing_channels.push_back(label);
3176 }
3177
3178 UpdateClosingRtpDataChannels(existing_channels, false);
3179}
3180
3181void PeerConnection::UpdateClosingRtpDataChannels(
3182 const std::vector<std::string>& active_channels,
3183 bool is_local_update) {
3184 auto it = rtp_data_channels_.begin();
3185 while (it != rtp_data_channels_.end()) {
3186 DataChannel* data_channel = it->second;
3187 if (std::find(active_channels.begin(), active_channels.end(),
3188 data_channel->label()) != active_channels.end()) {
3189 ++it;
3190 continue;
3191 }
3192
3193 if (is_local_update) {
3194 data_channel->SetSendSsrc(0);
3195 } else {
3196 data_channel->RemotePeerRequestClose();
3197 }
3198
3199 if (data_channel->state() == DataChannel::kClosed) {
3200 rtp_data_channels_.erase(it);
3201 it = rtp_data_channels_.begin();
3202 } else {
3203 ++it;
3204 }
3205 }
3206}
3207
3208void PeerConnection::CreateRemoteRtpDataChannel(const std::string& label,
3209 uint32_t remote_ssrc) {
3210 rtc::scoped_refptr<DataChannel> channel(
3211 InternalCreateDataChannel(label, nullptr));
3212 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003213 RTC_LOG(LS_WARNING) << "Remote peer requested a DataChannel but"
3214 << "CreateDataChannel failed.";
deadbeefab9b2d12015-10-14 11:33:11 -07003215 return;
3216 }
3217 channel->SetReceiveSsrc(remote_ssrc);
deadbeefa601f5c2016-06-06 14:27:39 -07003218 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
3219 DataChannelProxy::Create(signaling_thread(), channel);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07003220 observer_->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07003221}
3222
3223rtc::scoped_refptr<DataChannel> PeerConnection::InternalCreateDataChannel(
3224 const std::string& label,
3225 const InternalDataChannelInit* config) {
3226 if (IsClosed()) {
3227 return nullptr;
3228 }
Steve Anton75737c02017-11-06 10:37:17 -08003229 if (data_channel_type() == cricket::DCT_NONE) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003230 RTC_LOG(LS_ERROR)
deadbeefab9b2d12015-10-14 11:33:11 -07003231 << "InternalCreateDataChannel: Data is not supported in this call.";
3232 return nullptr;
3233 }
3234 InternalDataChannelInit new_config =
3235 config ? (*config) : InternalDataChannelInit();
Steve Anton75737c02017-11-06 10:37:17 -08003236 if (data_channel_type() == cricket::DCT_SCTP) {
deadbeefab9b2d12015-10-14 11:33:11 -07003237 if (new_config.id < 0) {
3238 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08003239 if ((GetSctpSslRole(&role)) &&
deadbeefab9b2d12015-10-14 11:33:11 -07003240 !sid_allocator_.AllocateSid(role, &new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003241 RTC_LOG(LS_ERROR)
3242 << "No id can be allocated for the SCTP data channel.";
deadbeefab9b2d12015-10-14 11:33:11 -07003243 return nullptr;
3244 }
3245 } else if (!sid_allocator_.ReserveSid(new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003246 RTC_LOG(LS_ERROR) << "Failed to create a SCTP data channel "
3247 << "because the id is already in use or out of range.";
deadbeefab9b2d12015-10-14 11:33:11 -07003248 return nullptr;
3249 }
3250 }
3251
Steve Anton75737c02017-11-06 10:37:17 -08003252 rtc::scoped_refptr<DataChannel> channel(
3253 DataChannel::Create(this, data_channel_type(), label, new_config));
deadbeefab9b2d12015-10-14 11:33:11 -07003254 if (!channel) {
3255 sid_allocator_.ReleaseSid(new_config.id);
3256 return nullptr;
3257 }
3258
3259 if (channel->data_channel_type() == cricket::DCT_RTP) {
3260 if (rtp_data_channels_.find(channel->label()) != rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003261 RTC_LOG(LS_ERROR) << "DataChannel with label " << channel->label()
3262 << " already exists.";
deadbeefab9b2d12015-10-14 11:33:11 -07003263 return nullptr;
3264 }
3265 rtp_data_channels_[channel->label()] = channel;
3266 } else {
3267 RTC_DCHECK(channel->data_channel_type() == cricket::DCT_SCTP);
3268 sctp_data_channels_.push_back(channel);
3269 channel->SignalClosed.connect(this,
3270 &PeerConnection::OnSctpDataChannelClosed);
3271 }
3272
hbos82ebe022016-11-14 01:41:09 -08003273 SignalDataChannelCreated(channel.get());
deadbeefab9b2d12015-10-14 11:33:11 -07003274 return channel;
3275}
3276
3277bool PeerConnection::HasDataChannels() const {
3278 return !rtp_data_channels_.empty() || !sctp_data_channels_.empty();
3279}
3280
3281void PeerConnection::AllocateSctpSids(rtc::SSLRole role) {
3282 for (const auto& channel : sctp_data_channels_) {
3283 if (channel->id() < 0) {
3284 int sid;
3285 if (!sid_allocator_.AllocateSid(role, &sid)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003286 RTC_LOG(LS_ERROR) << "Failed to allocate SCTP sid.";
deadbeefab9b2d12015-10-14 11:33:11 -07003287 continue;
3288 }
3289 channel->SetSctpSid(sid);
3290 }
3291 }
3292}
3293
3294void PeerConnection::OnSctpDataChannelClosed(DataChannel* channel) {
deadbeefbd292462015-12-14 18:15:29 -08003295 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeefab9b2d12015-10-14 11:33:11 -07003296 for (auto it = sctp_data_channels_.begin(); it != sctp_data_channels_.end();
3297 ++it) {
3298 if (it->get() == channel) {
3299 if (channel->id() >= 0) {
3300 sid_allocator_.ReleaseSid(channel->id());
3301 }
deadbeefbd292462015-12-14 18:15:29 -08003302 // Since this method is triggered by a signal from the DataChannel,
3303 // we can't free it directly here; we need to free it asynchronously.
3304 sctp_data_channels_to_free_.push_back(*it);
deadbeefab9b2d12015-10-14 11:33:11 -07003305 sctp_data_channels_.erase(it);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07003306 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_FREE_DATACHANNELS,
3307 nullptr);
deadbeefab9b2d12015-10-14 11:33:11 -07003308 return;
3309 }
3310 }
3311}
3312
deadbeefab9b2d12015-10-14 11:33:11 -07003313void PeerConnection::OnDataChannelDestroyed() {
3314 // Use a temporary copy of the RTP/SCTP DataChannel list because the
3315 // DataChannel may callback to us and try to modify the list.
3316 std::map<std::string, rtc::scoped_refptr<DataChannel>> temp_rtp_dcs;
3317 temp_rtp_dcs.swap(rtp_data_channels_);
3318 for (const auto& kv : temp_rtp_dcs) {
3319 kv.second->OnTransportChannelDestroyed();
3320 }
3321
3322 std::vector<rtc::scoped_refptr<DataChannel>> temp_sctp_dcs;
3323 temp_sctp_dcs.swap(sctp_data_channels_);
3324 for (const auto& channel : temp_sctp_dcs) {
3325 channel->OnTransportChannelDestroyed();
3326 }
3327}
3328
3329void PeerConnection::OnDataChannelOpenMessage(
3330 const std::string& label,
3331 const InternalDataChannelInit& config) {
3332 rtc::scoped_refptr<DataChannel> channel(
3333 InternalCreateDataChannel(label, &config));
3334 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003335 RTC_LOG(LS_ERROR) << "Failed to create DataChannel from the OPEN message.";
deadbeefab9b2d12015-10-14 11:33:11 -07003336 return;
3337 }
3338
deadbeefa601f5c2016-06-06 14:27:39 -07003339 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
3340 DataChannelProxy::Create(signaling_thread(), channel);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07003341 observer_->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07003342}
3343
Steve Anton4171afb2017-11-20 10:20:22 -08003344rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3345PeerConnection::GetAudioTransceiver() const {
3346 // This method only works with Plan B SDP, where there is a single
3347 // audio/video transceiver.
3348 RTC_DCHECK(!IsUnifiedPlan());
3349 for (auto transceiver : transceivers_) {
3350 if (transceiver->internal()->media_type() == cricket::MEDIA_TYPE_AUDIO) {
3351 return transceiver;
3352 }
3353 }
3354 RTC_NOTREACHED();
3355 return nullptr;
3356}
3357
3358rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3359PeerConnection::GetVideoTransceiver() const {
3360 // This method only works with Plan B SDP, where there is a single
3361 // audio/video transceiver.
3362 RTC_DCHECK(!IsUnifiedPlan());
3363 for (auto transceiver : transceivers_) {
3364 if (transceiver->internal()->media_type() == cricket::MEDIA_TYPE_VIDEO) {
3365 return transceiver;
3366 }
3367 }
3368 RTC_NOTREACHED();
3369 return nullptr;
3370}
3371
3372// TODO(bugs.webrtc.org/7600): Remove this when multiple transceivers with
3373// individual transceiver directions are supported.
zhihuang1c378ed2017-08-17 14:10:50 -07003374bool PeerConnection::HasRtpSender(cricket::MediaType type) const {
Steve Anton4171afb2017-11-20 10:20:22 -08003375 switch (type) {
3376 case cricket::MEDIA_TYPE_AUDIO:
3377 return !GetAudioTransceiver()->internal()->senders().empty();
3378 case cricket::MEDIA_TYPE_VIDEO:
3379 return !GetVideoTransceiver()->internal()->senders().empty();
3380 case cricket::MEDIA_TYPE_DATA:
3381 return false;
3382 }
3383 RTC_NOTREACHED();
3384 return false;
zhihuang1c378ed2017-08-17 14:10:50 -07003385}
3386
Steve Anton4171afb2017-11-20 10:20:22 -08003387rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
3388PeerConnection::FindSenderForTrack(MediaStreamTrackInterface* track) const {
3389 for (auto transceiver : transceivers_) {
3390 for (auto sender : transceiver->internal()->senders()) {
3391 if (sender->track() == track) {
3392 return sender;
3393 }
3394 }
3395 }
3396 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08003397}
3398
Steve Anton4171afb2017-11-20 10:20:22 -08003399rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
3400PeerConnection::FindSenderById(const std::string& sender_id) const {
3401 for (auto transceiver : transceivers_) {
3402 for (auto sender : transceiver->internal()->senders()) {
3403 if (sender->id() == sender_id) {
3404 return sender;
3405 }
3406 }
3407 }
3408 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07003409}
3410
Steve Anton4171afb2017-11-20 10:20:22 -08003411rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
3412PeerConnection::FindReceiverById(const std::string& receiver_id) const {
3413 for (auto transceiver : transceivers_) {
3414 for (auto receiver : transceiver->internal()->receivers()) {
3415 if (receiver->id() == receiver_id) {
3416 return receiver;
3417 }
3418 }
3419 }
3420 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07003421}
3422
Steve Anton4171afb2017-11-20 10:20:22 -08003423std::vector<PeerConnection::RtpSenderInfo>*
3424PeerConnection::GetRemoteSenderInfos(cricket::MediaType media_type) {
3425 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
3426 media_type == cricket::MEDIA_TYPE_VIDEO);
3427 return (media_type == cricket::MEDIA_TYPE_AUDIO)
3428 ? &remote_audio_sender_infos_
3429 : &remote_video_sender_infos_;
3430}
3431
3432std::vector<PeerConnection::RtpSenderInfo>* PeerConnection::GetLocalSenderInfos(
deadbeefab9b2d12015-10-14 11:33:11 -07003433 cricket::MediaType media_type) {
3434 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
3435 media_type == cricket::MEDIA_TYPE_VIDEO);
Steve Anton4171afb2017-11-20 10:20:22 -08003436 return (media_type == cricket::MEDIA_TYPE_AUDIO) ? &local_audio_sender_infos_
3437 : &local_video_sender_infos_;
deadbeefab9b2d12015-10-14 11:33:11 -07003438}
3439
Steve Anton4171afb2017-11-20 10:20:22 -08003440const PeerConnection::RtpSenderInfo* PeerConnection::FindSenderInfo(
3441 const std::vector<PeerConnection::RtpSenderInfo>& infos,
deadbeefab9b2d12015-10-14 11:33:11 -07003442 const std::string& stream_label,
Steve Anton4171afb2017-11-20 10:20:22 -08003443 const std::string sender_id) const {
3444 for (const RtpSenderInfo& sender_info : infos) {
3445 if (sender_info.stream_label == stream_label &&
3446 sender_info.sender_id == sender_id) {
3447 return &sender_info;
deadbeefab9b2d12015-10-14 11:33:11 -07003448 }
3449 }
3450 return nullptr;
3451}
3452
3453DataChannel* PeerConnection::FindDataChannelBySid(int sid) const {
3454 for (const auto& channel : sctp_data_channels_) {
3455 if (channel->id() == sid) {
3456 return channel;
3457 }
3458 }
3459 return nullptr;
3460}
3461
deadbeef91dd5672016-05-18 16:55:30 -07003462bool PeerConnection::InitializePortAllocator_n(
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003463 const RTCConfiguration& configuration) {
3464 cricket::ServerAddresses stun_servers;
3465 std::vector<cricket::RelayServerConfig> turn_servers;
deadbeef293e9262017-01-11 12:28:30 -08003466 if (ParseIceServers(configuration.servers, &stun_servers, &turn_servers) !=
3467 RTCErrorType::NONE) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003468 return false;
3469 }
3470
Taylor Brandstetterf8e65772016-06-27 17:20:15 -07003471 port_allocator_->Initialize();
3472
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003473 // To handle both internal and externally created port allocator, we will
3474 // enable BUNDLE here.
3475 int portallocator_flags = port_allocator_->flags();
3476 portallocator_flags |= cricket::PORTALLOCATOR_ENABLE_SHARED_SOCKET |
zhihuangb09b3f92017-03-07 14:40:51 -08003477 cricket::PORTALLOCATOR_ENABLE_IPV6 |
3478 cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI;
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003479 // If the disable-IPv6 flag was specified, we'll not override it
3480 // by experiment.
3481 if (configuration.disable_ipv6) {
3482 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
sprangc1b57a12017-02-28 08:50:47 -08003483 } else if (webrtc::field_trial::FindFullName("WebRTC-IPv6Default")
3484 .find("Disabled") == 0) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003485 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
3486 }
3487
zhihuangb09b3f92017-03-07 14:40:51 -08003488 if (configuration.disable_ipv6_on_wifi) {
3489 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI);
Mirko Bonadei675513b2017-11-09 11:09:25 +01003490 RTC_LOG(LS_INFO) << "IPv6 candidates on Wi-Fi are disabled.";
zhihuangb09b3f92017-03-07 14:40:51 -08003491 }
3492
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003493 if (configuration.tcp_candidate_policy == kTcpCandidatePolicyDisabled) {
3494 portallocator_flags |= cricket::PORTALLOCATOR_DISABLE_TCP;
Mirko Bonadei675513b2017-11-09 11:09:25 +01003495 RTC_LOG(LS_INFO) << "TCP candidates are disabled.";
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003496 }
3497
honghaiz60347052016-05-31 18:29:12 -07003498 if (configuration.candidate_network_policy ==
3499 kCandidateNetworkPolicyLowCost) {
3500 portallocator_flags |= cricket::PORTALLOCATOR_DISABLE_COSTLY_NETWORKS;
Mirko Bonadei675513b2017-11-09 11:09:25 +01003501 RTC_LOG(LS_INFO) << "Do not gather candidates on high-cost networks";
honghaiz60347052016-05-31 18:29:12 -07003502 }
3503
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003504 port_allocator_->set_flags(portallocator_flags);
3505 // No step delay is used while allocating ports.
3506 port_allocator_->set_step_delay(cricket::kMinimumStepDelay);
3507 port_allocator_->set_candidate_filter(
3508 ConvertIceTransportTypeToCandidateFilter(configuration.type));
deadbeefd21eab32017-07-26 16:50:11 -07003509 port_allocator_->set_max_ipv6_networks(configuration.max_ipv6_networks);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003510
3511 // Call this last since it may create pooled allocator sessions using the
3512 // properties set above.
3513 port_allocator_->SetConfiguration(stun_servers, turn_servers,
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -07003514 configuration.ice_candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02003515 configuration.prune_turn_ports,
3516 configuration.turn_customizer);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003517 return true;
3518}
3519
deadbeef91dd5672016-05-18 16:55:30 -07003520bool PeerConnection::ReconfigurePortAllocator_n(
deadbeef293e9262017-01-11 12:28:30 -08003521 const cricket::ServerAddresses& stun_servers,
3522 const std::vector<cricket::RelayServerConfig>& turn_servers,
3523 IceTransportsType type,
3524 int candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02003525 bool prune_turn_ports,
3526 webrtc::TurnCustomizer* turn_customizer) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003527 port_allocator_->set_candidate_filter(
deadbeef293e9262017-01-11 12:28:30 -08003528 ConvertIceTransportTypeToCandidateFilter(type));
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003529 // Call this last since it may create pooled allocator sessions using the
3530 // candidate filter set above.
deadbeef6de92f92016-12-12 18:49:32 -08003531 return port_allocator_->SetConfiguration(
Jonas Orelandbdcee282017-10-10 14:01:40 +02003532 stun_servers, turn_servers, candidate_pool_size, prune_turn_ports,
3533 turn_customizer);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003534}
3535
Steve Antonba818672017-11-06 10:21:57 -08003536cricket::ChannelManager* PeerConnection::channel_manager() const {
3537 return factory_->channel_manager();
3538}
3539
3540MetricsObserverInterface* PeerConnection::metrics_observer() const {
3541 return uma_observer_;
3542}
3543
Elad Alon99c3fe52017-10-13 16:29:40 +02003544bool PeerConnection::StartRtcEventLog_w(
Bjorn Tereliusde939432017-11-20 17:38:14 +01003545 std::unique_ptr<RtcEventLogOutput> output,
3546 int64_t output_period_ms) {
zhihuang77985012017-02-07 15:45:16 -08003547 if (!event_log_) {
3548 return false;
3549 }
Bjorn Tereliusde939432017-11-20 17:38:14 +01003550 return event_log_->StartLogging(std::move(output), output_period_ms);
ivoc14d5dbe2016-07-04 07:06:55 -07003551}
3552
3553void PeerConnection::StopRtcEventLog_w() {
zhihuang77985012017-02-07 15:45:16 -08003554 if (event_log_) {
3555 event_log_->StopLogging();
3556 }
ivoc14d5dbe2016-07-04 07:06:55 -07003557}
nisseeaabdf62017-05-05 02:23:02 -07003558
Steve Anton75737c02017-11-06 10:37:17 -08003559cricket::BaseChannel* PeerConnection::GetChannel(
3560 const std::string& content_name) {
3561 if (voice_channel() && voice_channel()->content_name() == content_name) {
3562 return voice_channel();
3563 }
3564 if (video_channel() && video_channel()->content_name() == content_name) {
3565 return video_channel();
3566 }
3567 if (rtp_data_channel() &&
3568 rtp_data_channel()->content_name() == content_name) {
3569 return rtp_data_channel();
3570 }
3571 return nullptr;
3572}
3573
3574bool PeerConnection::GetSctpSslRole(rtc::SSLRole* role) {
3575 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003576 RTC_LOG(LS_INFO)
3577 << "Local and Remote descriptions must be applied to get the "
3578 << "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08003579 return false;
3580 }
3581 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003582 RTC_LOG(LS_INFO) << "Non-rejected SCTP m= section is needed to get the "
3583 << "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08003584 return false;
3585 }
3586
3587 return transport_controller_->GetSslRole(*sctp_transport_name_, role);
3588}
3589
3590bool PeerConnection::GetSslRole(const std::string& content_name,
3591 rtc::SSLRole* role) {
3592 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003593 RTC_LOG(LS_INFO)
3594 << "Local and Remote descriptions must be applied to get the "
3595 << "SSL Role of the session.";
Steve Anton75737c02017-11-06 10:37:17 -08003596 return false;
3597 }
3598
3599 return transport_controller_->GetSslRole(GetTransportName(content_name),
3600 role);
3601}
3602
Steve Anton75737c02017-11-06 10:37:17 -08003603// TODO(steveanton): Eventually it'd be nice to store the channels as a single
3604// vector of BaseChannel pointers instead of separate voice and video channel
3605// vectors. At that point, this will become a simple getter.
3606std::vector<cricket::BaseChannel*> PeerConnection::Channels() const {
3607 std::vector<cricket::BaseChannel*> channels;
Steve Anton4171afb2017-11-20 10:20:22 -08003608 if (voice_channel()) {
3609 channels.push_back(voice_channel());
3610 }
3611 if (video_channel()) {
3612 channels.push_back(video_channel());
3613 }
Steve Anton75737c02017-11-06 10:37:17 -08003614 if (rtp_data_channel_) {
3615 channels.push_back(rtp_data_channel_);
3616 }
3617 return channels;
3618}
3619
Steve Antonf8470812017-12-04 10:46:21 -08003620void PeerConnection::SetSessionError(SessionError error,
3621 const std::string& error_desc) {
3622 RTC_DCHECK_RUN_ON(signaling_thread());
3623 if (error != session_error_) {
3624 session_error_ = error;
3625 session_error_desc_ = error_desc;
Steve Anton75737c02017-11-06 10:37:17 -08003626 }
3627}
3628
Steve Anton3828c062017-12-06 10:34:51 -08003629RTCError PeerConnection::UpdateSessionState(SdpType type,
Steve Anton8a006912017-12-04 15:25:56 -08003630 cricket::ContentSource source) {
3631 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08003632
3633 // If there's already a pending error then no state transition should happen.
3634 // But all call-sites should be verifying this before calling us!
Steve Antonf8470812017-12-04 10:46:21 -08003635 RTC_DCHECK(session_error() == SessionError::kNone);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08003636
3637 // If this is an answer then we know whether to BUNDLE or not. If both the
3638 // local and remote side have agreed to BUNDLE, go ahead and enable it.
Steve Anton3828c062017-12-06 10:34:51 -08003639 if (type == SdpType::kAnswer) {
Steve Anton75737c02017-11-06 10:37:17 -08003640 const cricket::ContentGroup* local_bundle =
3641 local_description()->description()->GetGroupByName(
3642 cricket::GROUP_TYPE_BUNDLE);
3643 const cricket::ContentGroup* remote_bundle =
3644 remote_description()->description()->GetGroupByName(
3645 cricket::GROUP_TYPE_BUNDLE);
3646 if (local_bundle && remote_bundle) {
3647 // The answerer decides the transport to bundle on.
3648 const cricket::ContentGroup* answer_bundle =
3649 (source == cricket::CS_LOCAL ? local_bundle : remote_bundle);
3650 if (!EnableBundle(*answer_bundle)) {
Steve Anton8a006912017-12-04 15:25:56 -08003651 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3652 kEnableBundleFailed);
Steve Anton75737c02017-11-06 10:37:17 -08003653 }
3654 }
Steve Anton75737c02017-11-06 10:37:17 -08003655 }
Steve Anton6d6a2ae2017-12-04 17:19:47 -08003656
3657 // Only push down the transport description after potentially enabling BUNDLE;
3658 // we don't want to push down a description on a transport about to be
3659 // destroyed.
Steve Anton3828c062017-12-06 10:34:51 -08003660 RTCError error = PushdownTransportDescription(source, type);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08003661 if (!error.ok()) {
3662 return error;
3663 }
3664
3665 // If this is answer-ish we're ready to let media flow.
Steve Anton3828c062017-12-06 10:34:51 -08003666 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Antoned10bd92017-12-05 10:52:59 -08003667 EnableSending();
Steve Anton6d6a2ae2017-12-04 17:19:47 -08003668 }
3669
3670 // Update the signaling state according to the specified state machine (see
3671 // https://w3c.github.io/webrtc-pc/#rtcsignalingstate-enum).
Steve Anton3828c062017-12-06 10:34:51 -08003672 if (type == SdpType::kOffer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08003673 ChangeSignalingState(source == cricket::CS_LOCAL
3674 ? PeerConnectionInterface::kHaveLocalOffer
3675 : PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton3828c062017-12-06 10:34:51 -08003676 } else if (type == SdpType::kPrAnswer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08003677 ChangeSignalingState(source == cricket::CS_LOCAL
3678 ? PeerConnectionInterface::kHaveLocalPrAnswer
3679 : PeerConnectionInterface::kHaveRemotePrAnswer);
3680 } else {
Steve Anton3828c062017-12-06 10:34:51 -08003681 RTC_DCHECK(type == SdpType::kAnswer);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08003682 ChangeSignalingState(PeerConnectionInterface::kStable);
3683 }
3684
3685 // Update internal objects according to the session description's media
3686 // descriptions.
Steve Anton3828c062017-12-06 10:34:51 -08003687 error = PushdownMediaDescription(type, source);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08003688 if (!error.ok()) {
3689 SetSessionError(SessionError::kContent, error.message());
3690 }
3691 if (session_error() != SessionError::kNone) {
3692 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
3693 }
3694
Steve Anton8a006912017-12-04 15:25:56 -08003695 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08003696}
3697
Steve Anton8a006912017-12-04 15:25:56 -08003698RTCError PeerConnection::PushdownMediaDescription(
Steve Anton3828c062017-12-06 10:34:51 -08003699 SdpType type,
Steve Anton8a006912017-12-04 15:25:56 -08003700 cricket::ContentSource source) {
Steve Antoned10bd92017-12-05 10:52:59 -08003701 const SessionDescriptionInterface* sdesc =
3702 (source == cricket::CS_LOCAL ? local_description()
3703 : remote_description());
Steve Anton75737c02017-11-06 10:37:17 -08003704 RTC_DCHECK(sdesc);
Steve Antoned10bd92017-12-05 10:52:59 -08003705
3706 // Push down the new SDP media section for each audio/video transceiver.
3707 for (auto transceiver : transceivers_) {
Steve Anton75737c02017-11-06 10:37:17 -08003708 const ContentInfo* content_info =
Steve Antoned10bd92017-12-05 10:52:59 -08003709 FindMediaSectionForTransceiver(transceiver, sdesc);
3710 cricket::BaseChannel* channel = transceiver->internal()->channel();
3711 if (!channel || !content_info || content_info->rejected) {
Steve Anton75737c02017-11-06 10:37:17 -08003712 continue;
3713 }
3714 const MediaContentDescription* content_desc =
3715 static_cast<const MediaContentDescription*>(content_info->description);
Steve Antoned10bd92017-12-05 10:52:59 -08003716 if (!content_desc) {
3717 continue;
3718 }
3719 std::string error;
3720 bool success =
3721 (source == cricket::CS_LOCAL)
Steve Anton3828c062017-12-06 10:34:51 -08003722 ? channel->SetLocalContent(content_desc, type, &error)
3723 : channel->SetRemoteContent(content_desc, type, &error);
Steve Antoned10bd92017-12-05 10:52:59 -08003724 if (!success) {
3725 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, std::move(error));
3726 }
3727 }
3728
3729 // If using the RtpDataChannel, push down the new SDP section for it too.
3730 if (rtp_data_channel_) {
3731 const ContentInfo* data_content =
3732 cricket::GetFirstDataContent(sdesc->description());
3733 if (data_content && !data_content->rejected) {
3734 const MediaContentDescription* data_desc =
3735 static_cast<const MediaContentDescription*>(
3736 data_content->description);
3737 if (data_desc) {
3738 std::string error;
3739 bool success =
3740 (source == cricket::CS_LOCAL)
Steve Anton3828c062017-12-06 10:34:51 -08003741 ? rtp_data_channel_->SetLocalContent(data_desc, type, &error)
3742 : rtp_data_channel_->SetRemoteContent(data_desc, type,
Steve Antoned10bd92017-12-05 10:52:59 -08003743 &error);
3744 if (!success) {
3745 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3746 std::move(error));
3747 }
Steve Anton75737c02017-11-06 10:37:17 -08003748 }
3749 }
3750 }
Steve Antoned10bd92017-12-05 10:52:59 -08003751
Steve Anton75737c02017-11-06 10:37:17 -08003752 // Need complete offer/answer with an SCTP m= section before starting SCTP,
3753 // according to https://tools.ietf.org/html/draft-ietf-mmusic-sctp-sdp-19
3754 if (sctp_transport_ && local_description() && remote_description() &&
3755 cricket::GetFirstDataContent(local_description()->description()) &&
3756 cricket::GetFirstDataContent(remote_description()->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08003757 bool success = network_thread()->Invoke<bool>(
Steve Anton75737c02017-11-06 10:37:17 -08003758 RTC_FROM_HERE,
3759 rtc::Bind(&PeerConnection::PushdownSctpParameters_n, this, source));
Steve Anton8a006912017-12-04 15:25:56 -08003760 if (!success) {
3761 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
3762 "Failed to push down SCTP parameters.");
3763 }
Steve Anton75737c02017-11-06 10:37:17 -08003764 }
Steve Antoned10bd92017-12-05 10:52:59 -08003765
Steve Anton8a006912017-12-04 15:25:56 -08003766 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08003767}
3768
3769bool PeerConnection::PushdownSctpParameters_n(cricket::ContentSource source) {
3770 RTC_DCHECK(network_thread()->IsCurrent());
3771 RTC_DCHECK(local_description());
3772 RTC_DCHECK(remote_description());
3773 // Apply the SCTP port (which is hidden inside a DataCodec structure...)
3774 // When we support "max-message-size", that would also be pushed down here.
3775 return sctp_transport_->Start(
3776 GetSctpPort(local_description()->description()),
3777 GetSctpPort(remote_description()->description()));
3778}
3779
Steve Anton8a006912017-12-04 15:25:56 -08003780RTCError PeerConnection::PushdownTransportDescription(
3781 cricket::ContentSource source,
Steve Anton3828c062017-12-06 10:34:51 -08003782 SdpType type) {
Steve Anton8a006912017-12-04 15:25:56 -08003783 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08003784
Steve Anton8a006912017-12-04 15:25:56 -08003785 const SessionDescriptionInterface* sdesc =
3786 (source == cricket::CS_LOCAL ? local_description()
3787 : remote_description());
3788 RTC_DCHECK(sdesc);
3789 for (const cricket::TransportInfo& tinfo :
3790 sdesc->description()->transport_infos()) {
3791 std::string error;
3792 bool success;
3793 if (source == cricket::CS_LOCAL) {
3794 success = transport_controller_->SetLocalTransportDescription(
Steve Anton3828c062017-12-06 10:34:51 -08003795 tinfo.content_name, tinfo.description, type, &error);
Steve Anton8a006912017-12-04 15:25:56 -08003796 } else {
3797 success = transport_controller_->SetRemoteTransportDescription(
Steve Anton3828c062017-12-06 10:34:51 -08003798 tinfo.content_name, tinfo.description, type, &error);
Steve Anton8a006912017-12-04 15:25:56 -08003799 }
3800 if (!success) {
3801 LOG_AND_RETURN_ERROR(
3802 RTCErrorType::INVALID_PARAMETER,
3803 "Failed to push down transport description: " + error);
Steve Anton75737c02017-11-06 10:37:17 -08003804 }
3805 }
3806
Steve Anton8a006912017-12-04 15:25:56 -08003807 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08003808}
3809
3810bool PeerConnection::GetTransportDescription(
3811 const SessionDescription* description,
3812 const std::string& content_name,
3813 cricket::TransportDescription* tdesc) {
3814 if (!description || !tdesc) {
3815 return false;
3816 }
3817 const TransportInfo* transport_info =
3818 description->GetTransportInfoByName(content_name);
3819 if (!transport_info) {
3820 return false;
3821 }
3822 *tdesc = transport_info->description;
3823 return true;
3824}
3825
3826bool PeerConnection::EnableBundle(const cricket::ContentGroup& bundle) {
3827 const std::string* first_content_name = bundle.FirstContentName();
3828 if (!first_content_name) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003829 RTC_LOG(LS_WARNING) << "Tried to BUNDLE with no contents.";
Steve Anton75737c02017-11-06 10:37:17 -08003830 return false;
3831 }
3832 const std::string& transport_name = *first_content_name;
3833
3834 auto maybe_set_transport = [this, bundle,
3835 transport_name](cricket::BaseChannel* ch) {
3836 if (!ch || !bundle.HasContentName(ch->content_name())) {
Steve Antoned10bd92017-12-05 10:52:59 -08003837 return;
Steve Anton75737c02017-11-06 10:37:17 -08003838 }
3839
3840 std::string old_transport_name = ch->transport_name();
3841 if (old_transport_name == transport_name) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003842 RTC_LOG(LS_INFO) << "BUNDLE already enabled for " << ch->content_name()
3843 << " on " << transport_name << ".";
Steve Antoned10bd92017-12-05 10:52:59 -08003844 return;
Steve Anton75737c02017-11-06 10:37:17 -08003845 }
3846
3847 cricket::DtlsTransportInternal* rtp_dtls_transport =
3848 transport_controller_->CreateDtlsTransport(
3849 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
3850 bool need_rtcp = (ch->rtcp_dtls_transport() != nullptr);
3851 cricket::DtlsTransportInternal* rtcp_dtls_transport = nullptr;
3852 if (need_rtcp) {
3853 rtcp_dtls_transport = transport_controller_->CreateDtlsTransport(
3854 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
3855 }
3856
3857 ch->SetTransports(rtp_dtls_transport, rtcp_dtls_transport);
Mirko Bonadei675513b2017-11-09 11:09:25 +01003858 RTC_LOG(LS_INFO) << "Enabled BUNDLE for " << ch->content_name() << " on "
3859 << transport_name << ".";
Steve Anton75737c02017-11-06 10:37:17 -08003860 transport_controller_->DestroyDtlsTransport(
3861 old_transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
3862 // If the channel needs rtcp, it means that the channel used to have a
3863 // rtcp transport which needs to be deleted now.
3864 if (need_rtcp) {
3865 transport_controller_->DestroyDtlsTransport(
3866 old_transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
3867 }
Steve Anton75737c02017-11-06 10:37:17 -08003868 };
3869
Steve Antoned10bd92017-12-05 10:52:59 -08003870 for (auto transceiver : transceivers_) {
3871 maybe_set_transport(transceiver->internal()->channel());
Steve Anton75737c02017-11-06 10:37:17 -08003872 }
Steve Antoned10bd92017-12-05 10:52:59 -08003873 maybe_set_transport(rtp_data_channel_);
3874
Steve Anton75737c02017-11-06 10:37:17 -08003875 // For SCTP, transport creation/deletion happens here instead of in the
3876 // object itself.
3877 if (sctp_transport_) {
3878 RTC_DCHECK(sctp_transport_name_);
3879 RTC_DCHECK(sctp_content_name_);
3880 if (transport_name != *sctp_transport_name_ &&
3881 bundle.HasContentName(*sctp_content_name_)) {
3882 network_thread()->Invoke<void>(
3883 RTC_FROM_HERE, rtc::Bind(&PeerConnection::ChangeSctpTransport_n, this,
3884 transport_name));
3885 }
3886 }
3887
3888 return true;
3889}
3890
Steve Anton75737c02017-11-06 10:37:17 -08003891cricket::IceConfig PeerConnection::ParseIceConfig(
3892 const PeerConnectionInterface::RTCConfiguration& config) const {
3893 cricket::ContinualGatheringPolicy gathering_policy;
3894 // TODO(honghaiz): Add the third continual gathering policy in
3895 // PeerConnectionInterface and map it to GATHER_CONTINUALLY_AND_RECOVER.
3896 switch (config.continual_gathering_policy) {
3897 case PeerConnectionInterface::GATHER_ONCE:
3898 gathering_policy = cricket::GATHER_ONCE;
3899 break;
3900 case PeerConnectionInterface::GATHER_CONTINUALLY:
3901 gathering_policy = cricket::GATHER_CONTINUALLY;
3902 break;
3903 default:
3904 RTC_NOTREACHED();
3905 gathering_policy = cricket::GATHER_ONCE;
3906 }
3907 cricket::IceConfig ice_config;
3908 ice_config.receiving_timeout = config.ice_connection_receiving_timeout;
3909 ice_config.prioritize_most_likely_candidate_pairs =
3910 config.prioritize_most_likely_ice_candidate_pairs;
3911 ice_config.backup_connection_ping_interval =
3912 config.ice_backup_candidate_pair_ping_interval;
3913 ice_config.continual_gathering_policy = gathering_policy;
3914 ice_config.presume_writable_when_fully_relayed =
3915 config.presume_writable_when_fully_relayed;
3916 ice_config.ice_check_min_interval = config.ice_check_min_interval;
3917 ice_config.regather_all_networks_interval_range =
3918 config.ice_regather_interval_range;
3919 return ice_config;
3920}
3921
Steve Anton75737c02017-11-06 10:37:17 -08003922bool PeerConnection::GetLocalTrackIdBySsrc(uint32_t ssrc,
3923 std::string* track_id) {
3924 if (!local_description()) {
3925 return false;
3926 }
3927 return webrtc::GetTrackIdBySsrc(local_description()->description(), ssrc,
3928 track_id);
3929}
3930
3931bool PeerConnection::GetRemoteTrackIdBySsrc(uint32_t ssrc,
3932 std::string* track_id) {
3933 if (!remote_description()) {
3934 return false;
3935 }
3936 return webrtc::GetTrackIdBySsrc(remote_description()->description(), ssrc,
3937 track_id);
3938}
3939
3940bool PeerConnection::SendData(const cricket::SendDataParams& params,
3941 const rtc::CopyOnWriteBuffer& payload,
3942 cricket::SendDataResult* result) {
3943 if (!rtp_data_channel_ && !sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003944 RTC_LOG(LS_ERROR) << "SendData called when rtp_data_channel_ "
3945 << "and sctp_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08003946 return false;
3947 }
3948 return rtp_data_channel_
3949 ? rtp_data_channel_->SendData(params, payload, result)
3950 : network_thread()->Invoke<bool>(
3951 RTC_FROM_HERE,
3952 Bind(&cricket::SctpTransportInternal::SendData,
3953 sctp_transport_.get(), params, payload, result));
3954}
3955
3956bool PeerConnection::ConnectDataChannel(DataChannel* webrtc_data_channel) {
3957 if (!rtp_data_channel_ && !sctp_transport_) {
3958 // Don't log an error here, because DataChannels are expected to call
3959 // ConnectDataChannel in this state. It's the only way to initially tell
3960 // whether or not the underlying transport is ready.
3961 return false;
3962 }
3963 if (rtp_data_channel_) {
3964 rtp_data_channel_->SignalReadyToSendData.connect(
3965 webrtc_data_channel, &DataChannel::OnChannelReady);
3966 rtp_data_channel_->SignalDataReceived.connect(webrtc_data_channel,
3967 &DataChannel::OnDataReceived);
3968 } else {
3969 SignalSctpReadyToSendData.connect(webrtc_data_channel,
3970 &DataChannel::OnChannelReady);
3971 SignalSctpDataReceived.connect(webrtc_data_channel,
3972 &DataChannel::OnDataReceived);
3973 SignalSctpStreamClosedRemotely.connect(
3974 webrtc_data_channel, &DataChannel::OnStreamClosedRemotely);
3975 }
3976 return true;
3977}
3978
3979void PeerConnection::DisconnectDataChannel(DataChannel* webrtc_data_channel) {
3980 if (!rtp_data_channel_ && !sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003981 RTC_LOG(LS_ERROR)
3982 << "DisconnectDataChannel called when rtp_data_channel_ and "
3983 "sctp_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08003984 return;
3985 }
3986 if (rtp_data_channel_) {
3987 rtp_data_channel_->SignalReadyToSendData.disconnect(webrtc_data_channel);
3988 rtp_data_channel_->SignalDataReceived.disconnect(webrtc_data_channel);
3989 } else {
3990 SignalSctpReadyToSendData.disconnect(webrtc_data_channel);
3991 SignalSctpDataReceived.disconnect(webrtc_data_channel);
3992 SignalSctpStreamClosedRemotely.disconnect(webrtc_data_channel);
3993 }
3994}
3995
3996void PeerConnection::AddSctpDataStream(int sid) {
3997 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003998 RTC_LOG(LS_ERROR)
3999 << "AddSctpDataStream called when sctp_transport_ is NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08004000 return;
4001 }
4002 network_thread()->Invoke<void>(
4003 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::OpenStream,
4004 sctp_transport_.get(), sid));
4005}
4006
4007void PeerConnection::RemoveSctpDataStream(int sid) {
4008 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004009 RTC_LOG(LS_ERROR) << "RemoveSctpDataStream called when sctp_transport_ is "
4010 << "NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08004011 return;
4012 }
4013 network_thread()->Invoke<void>(
4014 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::ResetStream,
4015 sctp_transport_.get(), sid));
4016}
4017
4018bool PeerConnection::ReadyToSendData() const {
4019 return (rtp_data_channel_ && rtp_data_channel_->ready_to_send_data()) ||
4020 sctp_ready_to_send_data_;
4021}
4022
4023std::unique_ptr<SessionStats> PeerConnection::GetSessionStats_s() {
4024 RTC_DCHECK(signaling_thread()->IsCurrent());
4025 ChannelNamePairs channel_name_pairs;
4026 if (voice_channel()) {
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004027 channel_name_pairs.voice = ChannelNamePair(
4028 voice_channel()->content_name(), voice_channel()->transport_name());
Steve Anton75737c02017-11-06 10:37:17 -08004029 }
4030 if (video_channel()) {
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004031 channel_name_pairs.video = ChannelNamePair(
4032 video_channel()->content_name(), video_channel()->transport_name());
Steve Anton75737c02017-11-06 10:37:17 -08004033 }
4034 if (rtp_data_channel()) {
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004035 channel_name_pairs.data =
Steve Anton75737c02017-11-06 10:37:17 -08004036 ChannelNamePair(rtp_data_channel()->content_name(),
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004037 rtp_data_channel()->transport_name());
Steve Anton75737c02017-11-06 10:37:17 -08004038 }
4039 if (sctp_transport_) {
4040 RTC_DCHECK(sctp_content_name_);
4041 RTC_DCHECK(sctp_transport_name_);
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004042 channel_name_pairs.data =
4043 ChannelNamePair(*sctp_content_name_, *sctp_transport_name_);
Steve Anton75737c02017-11-06 10:37:17 -08004044 }
4045 return GetSessionStats(channel_name_pairs);
4046}
4047
4048std::unique_ptr<SessionStats> PeerConnection::GetSessionStats(
4049 const ChannelNamePairs& channel_name_pairs) {
4050 if (network_thread()->IsCurrent()) {
4051 return GetSessionStats_n(channel_name_pairs);
4052 }
4053 return network_thread()->Invoke<std::unique_ptr<SessionStats>>(
4054 RTC_FROM_HERE,
4055 rtc::Bind(&PeerConnection::GetSessionStats_n, this, channel_name_pairs));
4056}
4057
4058bool PeerConnection::GetLocalCertificate(
4059 const std::string& transport_name,
4060 rtc::scoped_refptr<rtc::RTCCertificate>* certificate) {
4061 return transport_controller_->GetLocalCertificate(transport_name,
4062 certificate);
4063}
4064
4065std::unique_ptr<rtc::SSLCertificate> PeerConnection::GetRemoteSSLCertificate(
4066 const std::string& transport_name) {
4067 return transport_controller_->GetRemoteSSLCertificate(transport_name);
4068}
4069
4070cricket::DataChannelType PeerConnection::data_channel_type() const {
4071 return data_channel_type_;
4072}
4073
4074bool PeerConnection::IceRestartPending(const std::string& content_name) const {
4075 return pending_ice_restarts_.find(content_name) !=
4076 pending_ice_restarts_.end();
4077}
4078
Steve Anton75737c02017-11-06 10:37:17 -08004079bool PeerConnection::NeedsIceRestart(const std::string& content_name) const {
4080 return transport_controller_->NeedsIceRestart(content_name);
4081}
4082
4083void PeerConnection::OnCertificateReady(
4084 const rtc::scoped_refptr<rtc::RTCCertificate>& certificate) {
4085 transport_controller_->SetLocalCertificate(certificate);
4086}
4087
4088void PeerConnection::OnDtlsSrtpSetupFailure(cricket::BaseChannel*, bool rtcp) {
Steve Antonf8470812017-12-04 10:46:21 -08004089 SetSessionError(SessionError::kTransport,
4090 rtcp ? kDtlsSrtpSetupFailureRtcp : kDtlsSrtpSetupFailureRtp);
Steve Anton75737c02017-11-06 10:37:17 -08004091}
4092
4093void PeerConnection::OnTransportControllerConnectionState(
4094 cricket::IceConnectionState state) {
4095 switch (state) {
4096 case cricket::kIceConnectionConnecting:
4097 // If the current state is Connected or Completed, then there were
4098 // writable channels but now there are not, so the next state must
4099 // be Disconnected.
4100 // kIceConnectionConnecting is currently used as the default,
4101 // un-connected state by the TransportController, so its only use is
4102 // detecting disconnections.
4103 if (ice_connection_state_ ==
4104 PeerConnectionInterface::kIceConnectionConnected ||
4105 ice_connection_state_ ==
4106 PeerConnectionInterface::kIceConnectionCompleted) {
4107 SetIceConnectionState(
4108 PeerConnectionInterface::kIceConnectionDisconnected);
4109 }
4110 break;
4111 case cricket::kIceConnectionFailed:
4112 SetIceConnectionState(PeerConnectionInterface::kIceConnectionFailed);
4113 break;
4114 case cricket::kIceConnectionConnected:
Mirko Bonadei675513b2017-11-09 11:09:25 +01004115 RTC_LOG(LS_INFO) << "Changing to ICE connected state because "
4116 << "all transports are writable.";
Steve Anton75737c02017-11-06 10:37:17 -08004117 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
4118 break;
4119 case cricket::kIceConnectionCompleted:
Mirko Bonadei675513b2017-11-09 11:09:25 +01004120 RTC_LOG(LS_INFO) << "Changing to ICE completed state because "
4121 << "all transports are complete.";
Steve Anton75737c02017-11-06 10:37:17 -08004122 if (ice_connection_state_ !=
4123 PeerConnectionInterface::kIceConnectionConnected) {
4124 // If jumping directly from "checking" to "connected",
4125 // signal "connected" first.
4126 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
4127 }
4128 SetIceConnectionState(PeerConnectionInterface::kIceConnectionCompleted);
4129 if (metrics_observer()) {
4130 ReportTransportStats();
4131 }
4132 break;
4133 default:
4134 RTC_NOTREACHED();
4135 }
4136}
4137
4138void PeerConnection::OnTransportControllerCandidatesGathered(
4139 const std::string& transport_name,
4140 const cricket::Candidates& candidates) {
4141 RTC_DCHECK(signaling_thread()->IsCurrent());
4142 int sdp_mline_index;
4143 if (!GetLocalCandidateMediaIndex(transport_name, &sdp_mline_index)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004144 RTC_LOG(LS_ERROR)
4145 << "OnTransportControllerCandidatesGathered: content name "
4146 << transport_name << " not found";
Steve Anton75737c02017-11-06 10:37:17 -08004147 return;
4148 }
4149
4150 for (cricket::Candidates::const_iterator citer = candidates.begin();
4151 citer != candidates.end(); ++citer) {
4152 // Use transport_name as the candidate media id.
4153 std::unique_ptr<JsepIceCandidate> candidate(
4154 new JsepIceCandidate(transport_name, sdp_mline_index, *citer));
4155 if (local_description()) {
4156 mutable_local_description()->AddCandidate(candidate.get());
4157 }
4158 OnIceCandidate(std::move(candidate));
4159 }
4160}
4161
4162void PeerConnection::OnTransportControllerCandidatesRemoved(
4163 const std::vector<cricket::Candidate>& candidates) {
4164 RTC_DCHECK(signaling_thread()->IsCurrent());
4165 // Sanity check.
4166 for (const cricket::Candidate& candidate : candidates) {
4167 if (candidate.transport_name().empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004168 RTC_LOG(LS_ERROR) << "OnTransportControllerCandidatesRemoved: "
4169 << "empty content name in candidate "
4170 << candidate.ToString();
Steve Anton75737c02017-11-06 10:37:17 -08004171 return;
4172 }
4173 }
4174
4175 if (local_description()) {
4176 mutable_local_description()->RemoveCandidates(candidates);
4177 }
4178 OnIceCandidatesRemoved(candidates);
4179}
4180
4181void PeerConnection::OnTransportControllerDtlsHandshakeError(
4182 rtc::SSLHandshakeError error) {
4183 if (metrics_observer()) {
4184 metrics_observer()->IncrementEnumCounter(
4185 webrtc::kEnumCounterDtlsHandshakeError, static_cast<int>(error),
4186 static_cast<int>(rtc::SSLHandshakeError::MAX_VALUE));
4187 }
4188}
4189
Steve Antoned10bd92017-12-05 10:52:59 -08004190void PeerConnection::EnableSending() {
4191 for (auto transceiver : transceivers_) {
4192 cricket::BaseChannel* channel = transceiver->internal()->channel();
4193 if (channel && !channel->enabled()) {
4194 channel->Enable(true);
4195 }
Steve Anton75737c02017-11-06 10:37:17 -08004196 }
4197
Steve Anton4171afb2017-11-20 10:20:22 -08004198 if (rtp_data_channel_ && !rtp_data_channel_->enabled()) {
Steve Anton75737c02017-11-06 10:37:17 -08004199 rtp_data_channel_->Enable(true);
Steve Anton4171afb2017-11-20 10:20:22 -08004200 }
Steve Anton75737c02017-11-06 10:37:17 -08004201}
4202
4203// Returns the media index for a local ice candidate given the content name.
4204bool PeerConnection::GetLocalCandidateMediaIndex(
4205 const std::string& content_name,
4206 int* sdp_mline_index) {
4207 if (!local_description() || !sdp_mline_index) {
4208 return false;
4209 }
4210
4211 bool content_found = false;
4212 const ContentInfos& contents = local_description()->description()->contents();
4213 for (size_t index = 0; index < contents.size(); ++index) {
4214 if (contents[index].name == content_name) {
4215 *sdp_mline_index = static_cast<int>(index);
4216 content_found = true;
4217 break;
4218 }
4219 }
4220 return content_found;
4221}
4222
4223bool PeerConnection::UseCandidatesInSessionDescription(
4224 const SessionDescriptionInterface* remote_desc) {
4225 if (!remote_desc) {
4226 return true;
4227 }
4228 bool ret = true;
4229
4230 for (size_t m = 0; m < remote_desc->number_of_mediasections(); ++m) {
4231 const IceCandidateCollection* candidates = remote_desc->candidates(m);
4232 for (size_t n = 0; n < candidates->count(); ++n) {
4233 const IceCandidateInterface* candidate = candidates->at(n);
4234 bool valid = false;
4235 if (!ReadyToUseRemoteCandidate(candidate, remote_desc, &valid)) {
4236 if (valid) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004237 RTC_LOG(LS_INFO)
4238 << "UseCandidatesInSessionDescription: Not ready to use "
4239 << "candidate.";
Steve Anton75737c02017-11-06 10:37:17 -08004240 }
4241 continue;
4242 }
4243 ret = UseCandidate(candidate);
4244 if (!ret) {
4245 break;
4246 }
4247 }
4248 }
4249 return ret;
4250}
4251
4252bool PeerConnection::UseCandidate(const IceCandidateInterface* candidate) {
4253 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
4254 size_t remote_content_size =
4255 remote_description()->description()->contents().size();
4256 if (mediacontent_index >= remote_content_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004257 RTC_LOG(LS_ERROR) << "UseCandidate: Invalid candidate media index.";
Steve Anton75737c02017-11-06 10:37:17 -08004258 return false;
4259 }
4260
4261 cricket::ContentInfo content =
4262 remote_description()->description()->contents()[mediacontent_index];
4263 std::vector<cricket::Candidate> candidates;
4264 candidates.push_back(candidate->candidate());
4265 // Invoking BaseSession method to handle remote candidates.
4266 std::string error;
4267 if (transport_controller_->AddRemoteCandidates(content.name, candidates,
4268 &error)) {
4269 // Candidates successfully submitted for checking.
4270 if (ice_connection_state_ == PeerConnectionInterface::kIceConnectionNew ||
4271 ice_connection_state_ ==
4272 PeerConnectionInterface::kIceConnectionDisconnected) {
4273 // If state is New, then the session has just gotten its first remote ICE
4274 // candidates, so go to Checking.
4275 // If state is Disconnected, the session is re-using old candidates or
4276 // receiving additional ones, so go to Checking.
4277 // If state is Connected, stay Connected.
4278 // TODO(bemasc): If state is Connected, and the new candidates are for a
4279 // newly added transport, then the state actually _should_ move to
4280 // checking. Add a way to distinguish that case.
4281 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
4282 }
4283 // TODO(bemasc): If state is Completed, go back to Connected.
4284 } else {
4285 if (!error.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004286 RTC_LOG(LS_WARNING) << error;
Steve Anton75737c02017-11-06 10:37:17 -08004287 }
4288 }
4289 return true;
4290}
4291
4292void PeerConnection::RemoveUnusedChannels(const SessionDescription* desc) {
Steve Anton75737c02017-11-06 10:37:17 -08004293 // Destroy video channel first since it may have a pointer to the
4294 // voice channel.
4295 const cricket::ContentInfo* video_info = cricket::GetFirstVideoContent(desc);
Steve Anton6fec8802017-12-04 10:37:29 -08004296 if (!video_info || video_info->rejected) {
4297 DestroyTransceiverChannel(GetVideoTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08004298 }
4299
Steve Anton6fec8802017-12-04 10:37:29 -08004300 const cricket::ContentInfo* audio_info = cricket::GetFirstAudioContent(desc);
4301 if (!audio_info || audio_info->rejected) {
4302 DestroyTransceiverChannel(GetAudioTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08004303 }
4304
4305 const cricket::ContentInfo* data_info = cricket::GetFirstDataContent(desc);
4306 if (!data_info || data_info->rejected) {
Steve Anton6fec8802017-12-04 10:37:29 -08004307 DestroyDataChannel();
Steve Anton75737c02017-11-06 10:37:17 -08004308 }
4309}
4310
Steve Antoneda6ccd2017-12-04 10:21:55 -08004311std::string PeerConnection::GetTransportNameForMediaSection(
4312 const std::string& mid,
4313 const cricket::ContentGroup* bundle_group) const {
4314 if (!bundle_group) {
4315 return mid;
Steve Anton75737c02017-11-06 10:37:17 -08004316 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08004317 const std::string* first_content_name = bundle_group->FirstContentName();
Steve Anton75737c02017-11-06 10:37:17 -08004318 if (!first_content_name) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004319 RTC_LOG(LS_WARNING) << "Tried to BUNDLE with no contents.";
Steve Antoneda6ccd2017-12-04 10:21:55 -08004320 return mid;
Steve Anton75737c02017-11-06 10:37:17 -08004321 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08004322 if (!bundle_group->HasContentName(mid)) {
4323 RTC_LOG(LS_WARNING) << mid << " is not part of any bundle group";
4324 return mid;
Steve Anton75737c02017-11-06 10:37:17 -08004325 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08004326 RTC_LOG(LS_INFO) << "Bundling " << mid << " on " << *first_content_name;
4327 return *first_content_name;
Steve Anton75737c02017-11-06 10:37:17 -08004328}
4329
Steve Anton8a006912017-12-04 15:25:56 -08004330RTCError PeerConnection::CreateChannels(const SessionDescription* desc) {
Steve Antoneda6ccd2017-12-04 10:21:55 -08004331 RTC_DCHECK(desc);
4332
Steve Anton75737c02017-11-06 10:37:17 -08004333 const cricket::ContentGroup* bundle_group = nullptr;
4334 if (configuration_.bundle_policy ==
4335 PeerConnectionInterface::kBundlePolicyMaxBundle) {
4336 bundle_group = desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
4337 if (!bundle_group) {
Steve Anton8a006912017-12-04 15:25:56 -08004338 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
4339 "max-bundle configured but session description "
4340 "has no BUNDLE group");
Steve Anton75737c02017-11-06 10:37:17 -08004341 }
4342 }
4343
Steve Antoneda6ccd2017-12-04 10:21:55 -08004344 // Creating the media channels and transport proxies.
4345 const cricket::ContentInfo* voice = cricket::GetFirstAudioContent(desc);
4346 if (voice && !voice->rejected &&
4347 !GetAudioTransceiver()->internal()->channel()) {
4348 cricket::VoiceChannel* voice_channel = CreateVoiceChannel(
4349 voice->name,
4350 GetTransportNameForMediaSection(voice->name, bundle_group));
4351 if (!voice_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08004352 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
4353 "Failed to create voice channel.");
Steve Antoneda6ccd2017-12-04 10:21:55 -08004354 }
4355 GetAudioTransceiver()->internal()->SetChannel(voice_channel);
4356 }
4357
Steve Anton75737c02017-11-06 10:37:17 -08004358 const cricket::ContentInfo* video = cricket::GetFirstVideoContent(desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08004359 if (video && !video->rejected &&
4360 !GetVideoTransceiver()->internal()->channel()) {
4361 cricket::VideoChannel* video_channel = CreateVideoChannel(
4362 video->name,
4363 GetTransportNameForMediaSection(video->name, bundle_group));
4364 if (!video_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08004365 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
4366 "Failed to create video channel.");
Steve Anton75737c02017-11-06 10:37:17 -08004367 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08004368 GetVideoTransceiver()->internal()->SetChannel(video_channel);
Steve Anton75737c02017-11-06 10:37:17 -08004369 }
4370
4371 const cricket::ContentInfo* data = cricket::GetFirstDataContent(desc);
4372 if (data_channel_type_ != cricket::DCT_NONE && data && !data->rejected &&
4373 !rtp_data_channel_ && !sctp_transport_) {
Steve Antoneda6ccd2017-12-04 10:21:55 -08004374 if (!CreateDataChannel(data->name, GetTransportNameForMediaSection(
4375 data->name, bundle_group))) {
Steve Anton8a006912017-12-04 15:25:56 -08004376 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
4377 "Failed to create data channel.");
Steve Anton75737c02017-11-06 10:37:17 -08004378 }
4379 }
4380
Steve Anton8a006912017-12-04 15:25:56 -08004381 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08004382}
4383
Steve Anton4171afb2017-11-20 10:20:22 -08004384// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08004385cricket::VoiceChannel* PeerConnection::CreateVoiceChannel(
4386 const std::string& mid,
4387 const std::string& transport_name) {
Steve Anton75737c02017-11-06 10:37:17 -08004388 cricket::DtlsTransportInternal* rtp_dtls_transport =
4389 transport_controller_->CreateDtlsTransport(
4390 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4391 cricket::DtlsTransportInternal* rtcp_dtls_transport = nullptr;
4392 if (configuration_.rtcp_mux_policy !=
4393 PeerConnectionInterface::kRtcpMuxPolicyRequire) {
4394 rtcp_dtls_transport = transport_controller_->CreateDtlsTransport(
4395 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
4396 }
4397
4398 cricket::VoiceChannel* voice_channel = channel_manager()->CreateVoiceChannel(
4399 call_.get(), configuration_.media_config, rtp_dtls_transport,
Steve Antoneda6ccd2017-12-04 10:21:55 -08004400 rtcp_dtls_transport, signaling_thread(), mid, SrtpRequired(),
4401 audio_options_);
Steve Anton75737c02017-11-06 10:37:17 -08004402 if (!voice_channel) {
4403 transport_controller_->DestroyDtlsTransport(
4404 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4405 if (rtcp_dtls_transport) {
4406 transport_controller_->DestroyDtlsTransport(
4407 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
4408 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08004409 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08004410 }
Steve Anton75737c02017-11-06 10:37:17 -08004411 voice_channel->SignalRtcpMuxFullyActive.connect(
4412 this, &PeerConnection::DestroyRtcpTransport_n);
4413 voice_channel->SignalDtlsSrtpSetupFailure.connect(
4414 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08004415 voice_channel->SignalSentPacket.connect(this,
4416 &PeerConnection::OnSentPacket_w);
Steve Anton4171afb2017-11-20 10:20:22 -08004417
Steve Antoneda6ccd2017-12-04 10:21:55 -08004418 return voice_channel;
Steve Anton75737c02017-11-06 10:37:17 -08004419}
4420
Steve Anton4171afb2017-11-20 10:20:22 -08004421// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08004422cricket::VideoChannel* PeerConnection::CreateVideoChannel(
4423 const std::string& mid,
4424 const std::string& transport_name) {
Steve Anton75737c02017-11-06 10:37:17 -08004425 cricket::DtlsTransportInternal* rtp_dtls_transport =
4426 transport_controller_->CreateDtlsTransport(
4427 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4428 cricket::DtlsTransportInternal* rtcp_dtls_transport = nullptr;
4429 if (configuration_.rtcp_mux_policy !=
4430 PeerConnectionInterface::kRtcpMuxPolicyRequire) {
4431 rtcp_dtls_transport = transport_controller_->CreateDtlsTransport(
4432 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
4433 }
4434
4435 cricket::VideoChannel* video_channel = channel_manager()->CreateVideoChannel(
4436 call_.get(), configuration_.media_config, rtp_dtls_transport,
Steve Antoneda6ccd2017-12-04 10:21:55 -08004437 rtcp_dtls_transport, signaling_thread(), mid, SrtpRequired(),
4438 video_options_);
Steve Anton75737c02017-11-06 10:37:17 -08004439
4440 if (!video_channel) {
4441 transport_controller_->DestroyDtlsTransport(
4442 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4443 if (rtcp_dtls_transport) {
4444 transport_controller_->DestroyDtlsTransport(
4445 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
4446 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08004447 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08004448 }
Steve Anton75737c02017-11-06 10:37:17 -08004449 video_channel->SignalRtcpMuxFullyActive.connect(
4450 this, &PeerConnection::DestroyRtcpTransport_n);
4451 video_channel->SignalDtlsSrtpSetupFailure.connect(
4452 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08004453 video_channel->SignalSentPacket.connect(this,
4454 &PeerConnection::OnSentPacket_w);
Steve Anton4171afb2017-11-20 10:20:22 -08004455
Steve Antoneda6ccd2017-12-04 10:21:55 -08004456 return video_channel;
Steve Anton75737c02017-11-06 10:37:17 -08004457}
4458
Steve Antoneda6ccd2017-12-04 10:21:55 -08004459bool PeerConnection::CreateDataChannel(const std::string& mid,
4460 const std::string& transport_name) {
Steve Anton75737c02017-11-06 10:37:17 -08004461 bool sctp = (data_channel_type_ == cricket::DCT_SCTP);
4462 if (sctp) {
4463 if (!sctp_factory_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004464 RTC_LOG(LS_ERROR)
Steve Anton75737c02017-11-06 10:37:17 -08004465 << "Trying to create SCTP transport, but didn't compile with "
4466 "SCTP support (HAVE_SCTP)";
4467 return false;
4468 }
4469 if (!network_thread()->Invoke<bool>(
4470 RTC_FROM_HERE, rtc::Bind(&PeerConnection::CreateSctpTransport_n,
Steve Antoneda6ccd2017-12-04 10:21:55 -08004471 this, mid, transport_name))) {
Steve Anton75737c02017-11-06 10:37:17 -08004472 return false;
4473 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08004474 for (const auto& channel : sctp_data_channels_) {
4475 channel->OnTransportChannelCreated();
4476 }
Steve Anton75737c02017-11-06 10:37:17 -08004477 } else {
Steve Anton75737c02017-11-06 10:37:17 -08004478 cricket::DtlsTransportInternal* rtp_dtls_transport =
4479 transport_controller_->CreateDtlsTransport(
4480 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4481 cricket::DtlsTransportInternal* rtcp_dtls_transport = nullptr;
4482 if (configuration_.rtcp_mux_policy !=
4483 PeerConnectionInterface::kRtcpMuxPolicyRequire) {
4484 rtcp_dtls_transport = transport_controller_->CreateDtlsTransport(
4485 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
4486 }
4487
4488 rtp_data_channel_ = channel_manager()->CreateRtpDataChannel(
4489 configuration_.media_config, rtp_dtls_transport, rtcp_dtls_transport,
Steve Antoneda6ccd2017-12-04 10:21:55 -08004490 signaling_thread(), mid, SrtpRequired());
Steve Anton75737c02017-11-06 10:37:17 -08004491
4492 if (!rtp_data_channel_) {
4493 transport_controller_->DestroyDtlsTransport(
4494 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4495 if (rtcp_dtls_transport) {
4496 transport_controller_->DestroyDtlsTransport(
4497 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
4498 }
4499 return false;
4500 }
4501
4502 rtp_data_channel_->SignalRtcpMuxFullyActive.connect(
4503 this, &PeerConnection::DestroyRtcpTransport_n);
4504 rtp_data_channel_->SignalDtlsSrtpSetupFailure.connect(
4505 this, &PeerConnection::OnDtlsSrtpSetupFailure);
4506 rtp_data_channel_->SignalSentPacket.connect(
4507 this, &PeerConnection::OnSentPacket_w);
4508 }
4509
Steve Anton75737c02017-11-06 10:37:17 -08004510 return true;
4511}
4512
4513Call::Stats PeerConnection::GetCallStats() {
4514 if (!worker_thread()->IsCurrent()) {
4515 return worker_thread()->Invoke<Call::Stats>(
4516 RTC_FROM_HERE, rtc::Bind(&PeerConnection::GetCallStats, this));
4517 }
4518 if (call_) {
4519 return call_->GetStats();
4520 } else {
4521 return Call::Stats();
4522 }
4523}
4524
4525std::unique_ptr<SessionStats> PeerConnection::GetSessionStats_n(
4526 const ChannelNamePairs& channel_name_pairs) {
4527 RTC_DCHECK(network_thread()->IsCurrent());
4528 std::unique_ptr<SessionStats> session_stats(new SessionStats());
4529 for (const auto channel_name_pair :
4530 {&channel_name_pairs.voice, &channel_name_pairs.video,
4531 &channel_name_pairs.data}) {
4532 if (*channel_name_pair) {
4533 cricket::TransportStats transport_stats;
4534 if (!transport_controller_->GetStats((*channel_name_pair)->transport_name,
4535 &transport_stats)) {
4536 return nullptr;
4537 }
Steve Anton75737c02017-11-06 10:37:17 -08004538 session_stats->transport_stats[(*channel_name_pair)->transport_name] =
4539 std::move(transport_stats);
4540 }
4541 }
4542 return session_stats;
4543}
4544
4545bool PeerConnection::CreateSctpTransport_n(const std::string& content_name,
4546 const std::string& transport_name) {
4547 RTC_DCHECK(network_thread()->IsCurrent());
4548 RTC_DCHECK(sctp_factory_);
4549 cricket::DtlsTransportInternal* tc =
4550 transport_controller_->CreateDtlsTransport_n(
4551 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4552 sctp_transport_ = sctp_factory_->CreateSctpTransport(tc);
4553 RTC_DCHECK(sctp_transport_);
4554 sctp_invoker_.reset(new rtc::AsyncInvoker());
4555 sctp_transport_->SignalReadyToSendData.connect(
4556 this, &PeerConnection::OnSctpTransportReadyToSendData_n);
4557 sctp_transport_->SignalDataReceived.connect(
4558 this, &PeerConnection::OnSctpTransportDataReceived_n);
4559 sctp_transport_->SignalStreamClosedRemotely.connect(
4560 this, &PeerConnection::OnSctpStreamClosedRemotely_n);
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004561 sctp_transport_name_ = transport_name;
4562 sctp_content_name_ = content_name;
Steve Anton75737c02017-11-06 10:37:17 -08004563 return true;
4564}
4565
4566void PeerConnection::ChangeSctpTransport_n(const std::string& transport_name) {
4567 RTC_DCHECK(network_thread()->IsCurrent());
4568 RTC_DCHECK(sctp_transport_);
4569 RTC_DCHECK(sctp_transport_name_);
4570 std::string old_sctp_transport_name = *sctp_transport_name_;
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004571 sctp_transport_name_ = transport_name;
Steve Anton75737c02017-11-06 10:37:17 -08004572 cricket::DtlsTransportInternal* tc =
4573 transport_controller_->CreateDtlsTransport_n(
4574 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4575 sctp_transport_->SetTransportChannel(tc);
4576 transport_controller_->DestroyDtlsTransport_n(
4577 old_sctp_transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4578}
4579
4580void PeerConnection::DestroySctpTransport_n() {
4581 RTC_DCHECK(network_thread()->IsCurrent());
4582 sctp_transport_.reset(nullptr);
4583 sctp_content_name_.reset();
4584 sctp_transport_name_.reset();
4585 sctp_invoker_.reset(nullptr);
4586 sctp_ready_to_send_data_ = false;
4587}
4588
4589void PeerConnection::OnSctpTransportReadyToSendData_n() {
4590 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
4591 RTC_DCHECK(network_thread()->IsCurrent());
4592 // Note: Cannot use rtc::Bind here because it will grab a reference to
4593 // PeerConnection and potentially cause PeerConnection to live longer than
4594 // expected. It is safe not to grab a reference since the sctp_invoker_ will
4595 // be destroyed before PeerConnection is destroyed, and at that point all
4596 // pending tasks will be cleared.
4597 sctp_invoker_->AsyncInvoke<void>(RTC_FROM_HERE, signaling_thread(), [this] {
4598 OnSctpTransportReadyToSendData_s(true);
4599 });
4600}
4601
4602void PeerConnection::OnSctpTransportReadyToSendData_s(bool ready) {
4603 RTC_DCHECK(signaling_thread()->IsCurrent());
4604 sctp_ready_to_send_data_ = ready;
4605 SignalSctpReadyToSendData(ready);
4606}
4607
4608void PeerConnection::OnSctpTransportDataReceived_n(
4609 const cricket::ReceiveDataParams& params,
4610 const rtc::CopyOnWriteBuffer& payload) {
4611 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
4612 RTC_DCHECK(network_thread()->IsCurrent());
4613 // Note: Cannot use rtc::Bind here because it will grab a reference to
4614 // PeerConnection and potentially cause PeerConnection to live longer than
4615 // expected. It is safe not to grab a reference since the sctp_invoker_ will
4616 // be destroyed before PeerConnection is destroyed, and at that point all
4617 // pending tasks will be cleared.
4618 sctp_invoker_->AsyncInvoke<void>(
4619 RTC_FROM_HERE, signaling_thread(), [this, params, payload] {
4620 OnSctpTransportDataReceived_s(params, payload);
4621 });
4622}
4623
4624void PeerConnection::OnSctpTransportDataReceived_s(
4625 const cricket::ReceiveDataParams& params,
4626 const rtc::CopyOnWriteBuffer& payload) {
4627 RTC_DCHECK(signaling_thread()->IsCurrent());
4628 if (params.type == cricket::DMT_CONTROL && IsOpenMessage(payload)) {
4629 // Received OPEN message; parse and signal that a new data channel should
4630 // be created.
4631 std::string label;
4632 InternalDataChannelInit config;
4633 config.id = params.ssrc;
4634 if (!ParseDataChannelOpenMessage(payload, &label, &config)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004635 RTC_LOG(LS_WARNING) << "Failed to parse the OPEN message for sid "
4636 << params.ssrc;
Steve Anton75737c02017-11-06 10:37:17 -08004637 return;
4638 }
4639 config.open_handshake_role = InternalDataChannelInit::kAcker;
4640 OnDataChannelOpenMessage(label, config);
4641 } else {
4642 // Otherwise just forward the signal.
4643 SignalSctpDataReceived(params, payload);
4644 }
4645}
4646
4647void PeerConnection::OnSctpStreamClosedRemotely_n(int sid) {
4648 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
4649 RTC_DCHECK(network_thread()->IsCurrent());
4650 sctp_invoker_->AsyncInvoke<void>(
4651 RTC_FROM_HERE, signaling_thread(),
4652 rtc::Bind(&sigslot::signal1<int>::operator(),
4653 &SignalSctpStreamClosedRemotely, sid));
4654}
4655
4656// Returns false if bundle is enabled and rtcp_mux is disabled.
4657bool PeerConnection::ValidateBundleSettings(const SessionDescription* desc) {
4658 bool bundle_enabled = desc->HasGroup(cricket::GROUP_TYPE_BUNDLE);
4659 if (!bundle_enabled)
4660 return true;
4661
4662 const cricket::ContentGroup* bundle_group =
4663 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
4664 RTC_DCHECK(bundle_group != NULL);
4665
4666 const cricket::ContentInfos& contents = desc->contents();
4667 for (cricket::ContentInfos::const_iterator citer = contents.begin();
4668 citer != contents.end(); ++citer) {
4669 const cricket::ContentInfo* content = (&*citer);
4670 RTC_DCHECK(content != NULL);
4671 if (bundle_group->HasContentName(content->name) && !content->rejected &&
Steve Anton5adfafd2017-12-20 16:34:00 -08004672 content->type == MediaProtocolType::kRtp) {
Steve Anton75737c02017-11-06 10:37:17 -08004673 if (!HasRtcpMuxEnabled(content))
4674 return false;
4675 }
4676 }
4677 // RTCP-MUX is enabled in all the contents.
4678 return true;
4679}
4680
4681bool PeerConnection::HasRtcpMuxEnabled(const cricket::ContentInfo* content) {
4682 const cricket::MediaContentDescription* description =
4683 static_cast<cricket::MediaContentDescription*>(content->description);
4684 return description->rtcp_mux();
4685}
4686
Steve Anton8a006912017-12-04 15:25:56 -08004687RTCError PeerConnection::ValidateSessionDescription(
Steve Anton75737c02017-11-06 10:37:17 -08004688 const SessionDescriptionInterface* sdesc,
Steve Anton8a006912017-12-04 15:25:56 -08004689 cricket::ContentSource source) {
Steve Antonf8470812017-12-04 10:46:21 -08004690 if (session_error() != SessionError::kNone) {
Steve Anton8a006912017-12-04 15:25:56 -08004691 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
Steve Anton75737c02017-11-06 10:37:17 -08004692 }
4693
4694 if (!sdesc || !sdesc->description()) {
Steve Anton8a006912017-12-04 15:25:56 -08004695 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidSdp);
Steve Anton75737c02017-11-06 10:37:17 -08004696 }
4697
Steve Anton3828c062017-12-06 10:34:51 -08004698 SdpType type = sdesc->GetType();
4699 if ((source == cricket::CS_LOCAL && !ExpectSetLocalDescription(type)) ||
4700 (source == cricket::CS_REMOTE && !ExpectSetRemoteDescription(type))) {
Steve Anton8a006912017-12-04 15:25:56 -08004701 LOG_AND_RETURN_ERROR(
4702 RTCErrorType::INVALID_PARAMETER,
4703 "Called in wrong state: " + GetSignalingStateString(signaling_state()));
Steve Anton75737c02017-11-06 10:37:17 -08004704 }
4705
4706 // Verify crypto settings.
4707 std::string crypto_error;
Steve Anton8a006912017-12-04 15:25:56 -08004708 if (webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED ||
4709 dtls_enabled_) {
4710 RTCError crypto_error = VerifyCrypto(sdesc->description(), dtls_enabled_);
4711 if (!crypto_error.ok()) {
4712 return crypto_error;
4713 }
Steve Anton75737c02017-11-06 10:37:17 -08004714 }
4715
4716 // Verify ice-ufrag and ice-pwd.
4717 if (!VerifyIceUfragPwdPresent(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08004718 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
4719 kSdpWithoutIceUfragPwd);
Steve Anton75737c02017-11-06 10:37:17 -08004720 }
4721
4722 if (!ValidateBundleSettings(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08004723 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
4724 kBundleWithoutRtcpMux);
Steve Anton75737c02017-11-06 10:37:17 -08004725 }
4726
4727 // TODO(skvlad): When the local rtcp-mux policy is Require, reject any
4728 // m-lines that do not rtcp-mux enabled.
4729
4730 // Verify m-lines in Answer when compared against Offer.
Steve Anton3828c062017-12-06 10:34:51 -08004731 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Anton75737c02017-11-06 10:37:17 -08004732 const cricket::SessionDescription* offer_desc =
4733 (source == cricket::CS_LOCAL) ? remote_description()->description()
4734 : local_description()->description();
4735 if (!MediaSectionsHaveSameCount(offer_desc, sdesc->description()) ||
4736 !MediaSectionsInSameOrder(offer_desc, sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08004737 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
4738 kMlineMismatchInAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08004739 }
4740 } else {
4741 const cricket::SessionDescription* current_desc = nullptr;
4742 if (source == cricket::CS_LOCAL && local_description()) {
4743 current_desc = local_description()->description();
4744 } else if (source == cricket::CS_REMOTE && remote_description()) {
4745 current_desc = remote_description()->description();
4746 }
4747 // The re-offers should respect the order of m= sections in current
4748 // description. See RFC3264 Section 8 paragraph 4 for more details.
4749 if (current_desc &&
4750 !MediaSectionsInSameOrder(current_desc, sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08004751 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
4752 kMlineMismatchInSubsequentOffer);
Steve Anton75737c02017-11-06 10:37:17 -08004753 }
4754 }
4755
Steve Anton8a006912017-12-04 15:25:56 -08004756 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08004757}
4758
Steve Anton3828c062017-12-06 10:34:51 -08004759bool PeerConnection::ExpectSetLocalDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08004760 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08004761 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08004762 return (state == PeerConnectionInterface::kStable) ||
4763 (state == PeerConnectionInterface::kHaveLocalOffer);
Steve Anton20393062017-12-04 16:24:52 -08004764 } else {
Steve Anton3828c062017-12-06 10:34:51 -08004765 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08004766 return (state == PeerConnectionInterface::kHaveRemoteOffer) ||
4767 (state == PeerConnectionInterface::kHaveLocalPrAnswer);
4768 }
4769}
4770
Steve Anton3828c062017-12-06 10:34:51 -08004771bool PeerConnection::ExpectSetRemoteDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08004772 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08004773 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08004774 return (state == PeerConnectionInterface::kStable) ||
4775 (state == PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton20393062017-12-04 16:24:52 -08004776 } else {
Steve Anton3828c062017-12-06 10:34:51 -08004777 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08004778 return (state == PeerConnectionInterface::kHaveLocalOffer) ||
4779 (state == PeerConnectionInterface::kHaveRemotePrAnswer);
4780 }
4781}
4782
Steve Antonf8470812017-12-04 10:46:21 -08004783const char* PeerConnection::SessionErrorToString(SessionError error) const {
4784 switch (error) {
4785 case SessionError::kNone:
4786 return "ERROR_NONE";
4787 case SessionError::kContent:
4788 return "ERROR_CONTENT";
4789 case SessionError::kTransport:
4790 return "ERROR_TRANSPORT";
4791 }
4792 RTC_NOTREACHED();
4793 return "";
4794}
4795
Steve Anton75737c02017-11-06 10:37:17 -08004796std::string PeerConnection::GetSessionErrorMsg() {
4797 std::ostringstream desc;
Steve Antonf8470812017-12-04 10:46:21 -08004798 desc << kSessionError << SessionErrorToString(session_error()) << ". ";
4799 desc << kSessionErrorDesc << session_error_desc() << ".";
Steve Anton75737c02017-11-06 10:37:17 -08004800 return desc.str();
4801}
4802
4803// We need to check the local/remote description for the Transport instead of
4804// the session, because a new Transport added during renegotiation may have
4805// them unset while the session has them set from the previous negotiation.
4806// Not doing so may trigger the auto generation of transport description and
4807// mess up DTLS identity information, ICE credential, etc.
4808bool PeerConnection::ReadyToUseRemoteCandidate(
4809 const IceCandidateInterface* candidate,
4810 const SessionDescriptionInterface* remote_desc,
4811 bool* valid) {
4812 *valid = true;
4813
4814 const SessionDescriptionInterface* current_remote_desc =
4815 remote_desc ? remote_desc : remote_description();
4816
4817 if (!current_remote_desc) {
4818 return false;
4819 }
4820
4821 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
4822 size_t remote_content_size =
4823 current_remote_desc->description()->contents().size();
4824 if (mediacontent_index >= remote_content_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004825 RTC_LOG(LS_ERROR)
4826 << "ReadyToUseRemoteCandidate: Invalid candidate media index "
4827 << mediacontent_index;
Steve Anton75737c02017-11-06 10:37:17 -08004828
4829 *valid = false;
4830 return false;
4831 }
4832
4833 cricket::ContentInfo content =
4834 current_remote_desc->description()->contents()[mediacontent_index];
4835
4836 const std::string transport_name = GetTransportName(content.name);
4837 if (transport_name.empty()) {
4838 return false;
4839 }
4840 return transport_controller_->ReadyForRemoteCandidates(transport_name);
4841}
4842
4843bool PeerConnection::SrtpRequired() const {
4844 return dtls_enabled_ ||
4845 webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED;
4846}
4847
4848void PeerConnection::OnTransportControllerGatheringState(
4849 cricket::IceGatheringState state) {
4850 RTC_DCHECK(signaling_thread()->IsCurrent());
4851 if (state == cricket::kIceGatheringGathering) {
4852 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringGathering);
4853 } else if (state == cricket::kIceGatheringComplete) {
4854 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringComplete);
4855 }
4856}
4857
4858void PeerConnection::ReportTransportStats() {
4859 // Use a set so we don't report the same stats twice if two channels share
4860 // a transport.
4861 std::set<std::string> transport_names;
4862 if (voice_channel()) {
4863 transport_names.insert(voice_channel()->transport_name());
4864 }
4865 if (video_channel()) {
4866 transport_names.insert(video_channel()->transport_name());
4867 }
4868 if (rtp_data_channel()) {
4869 transport_names.insert(rtp_data_channel()->transport_name());
4870 }
4871 if (sctp_transport_name_) {
4872 transport_names.insert(*sctp_transport_name_);
4873 }
4874 for (const auto& name : transport_names) {
4875 cricket::TransportStats stats;
4876 if (transport_controller_->GetStats(name, &stats)) {
4877 ReportBestConnectionState(stats);
4878 ReportNegotiatedCiphers(stats);
4879 }
4880 }
4881}
4882// Walk through the ConnectionInfos to gather best connection usage
4883// for IPv4 and IPv6.
4884void PeerConnection::ReportBestConnectionState(
4885 const cricket::TransportStats& stats) {
4886 RTC_DCHECK(metrics_observer());
4887 for (cricket::TransportChannelStatsList::const_iterator it =
4888 stats.channel_stats.begin();
4889 it != stats.channel_stats.end(); ++it) {
4890 for (cricket::ConnectionInfos::const_iterator it_info =
4891 it->connection_infos.begin();
4892 it_info != it->connection_infos.end(); ++it_info) {
4893 if (!it_info->best_connection) {
4894 continue;
4895 }
4896
4897 PeerConnectionEnumCounterType type = kPeerConnectionEnumCounterMax;
4898 const cricket::Candidate& local = it_info->local_candidate;
4899 const cricket::Candidate& remote = it_info->remote_candidate;
4900
4901 // Increment the counter for IceCandidatePairType.
4902 if (local.protocol() == cricket::TCP_PROTOCOL_NAME ||
4903 (local.type() == RELAY_PORT_TYPE &&
4904 local.relay_protocol() == cricket::TCP_PROTOCOL_NAME)) {
4905 type = kEnumCounterIceCandidatePairTypeTcp;
4906 } else if (local.protocol() == cricket::UDP_PROTOCOL_NAME) {
4907 type = kEnumCounterIceCandidatePairTypeUdp;
4908 } else {
4909 RTC_CHECK(0);
4910 }
4911 metrics_observer()->IncrementEnumCounter(
4912 type, GetIceCandidatePairCounter(local, remote),
4913 kIceCandidatePairMax);
4914
4915 // Increment the counter for IP type.
4916 if (local.address().family() == AF_INET) {
4917 metrics_observer()->IncrementEnumCounter(
4918 kEnumCounterAddressFamily, kBestConnections_IPv4,
4919 kPeerConnectionAddressFamilyCounter_Max);
4920
4921 } else if (local.address().family() == AF_INET6) {
4922 metrics_observer()->IncrementEnumCounter(
4923 kEnumCounterAddressFamily, kBestConnections_IPv6,
4924 kPeerConnectionAddressFamilyCounter_Max);
4925 } else {
4926 RTC_CHECK(0);
4927 }
4928
4929 return;
4930 }
4931 }
4932}
4933
4934void PeerConnection::ReportNegotiatedCiphers(
4935 const cricket::TransportStats& stats) {
4936 RTC_DCHECK(metrics_observer());
4937 if (!dtls_enabled_ || stats.channel_stats.empty()) {
4938 return;
4939 }
4940
4941 int srtp_crypto_suite = stats.channel_stats[0].srtp_crypto_suite;
4942 int ssl_cipher_suite = stats.channel_stats[0].ssl_cipher_suite;
4943 if (srtp_crypto_suite == rtc::SRTP_INVALID_CRYPTO_SUITE &&
4944 ssl_cipher_suite == rtc::TLS_NULL_WITH_NULL_NULL) {
4945 return;
4946 }
4947
4948 PeerConnectionEnumCounterType srtp_counter_type;
4949 PeerConnectionEnumCounterType ssl_counter_type;
4950 if (stats.transport_name == cricket::CN_AUDIO) {
4951 srtp_counter_type = kEnumCounterAudioSrtpCipher;
4952 ssl_counter_type = kEnumCounterAudioSslCipher;
4953 } else if (stats.transport_name == cricket::CN_VIDEO) {
4954 srtp_counter_type = kEnumCounterVideoSrtpCipher;
4955 ssl_counter_type = kEnumCounterVideoSslCipher;
4956 } else if (stats.transport_name == cricket::CN_DATA) {
4957 srtp_counter_type = kEnumCounterDataSrtpCipher;
4958 ssl_counter_type = kEnumCounterDataSslCipher;
4959 } else {
4960 RTC_NOTREACHED();
4961 return;
4962 }
4963
4964 if (srtp_crypto_suite != rtc::SRTP_INVALID_CRYPTO_SUITE) {
4965 metrics_observer()->IncrementSparseEnumCounter(srtp_counter_type,
4966 srtp_crypto_suite);
4967 }
4968 if (ssl_cipher_suite != rtc::TLS_NULL_WITH_NULL_NULL) {
4969 metrics_observer()->IncrementSparseEnumCounter(ssl_counter_type,
4970 ssl_cipher_suite);
4971 }
4972}
4973
4974void PeerConnection::OnSentPacket_w(const rtc::SentPacket& sent_packet) {
4975 RTC_DCHECK(worker_thread()->IsCurrent());
4976 RTC_DCHECK(call_);
4977 call_->OnSentPacket(sent_packet);
4978}
4979
4980const std::string PeerConnection::GetTransportName(
4981 const std::string& content_name) {
4982 cricket::BaseChannel* channel = GetChannel(content_name);
Steve Anton6fec8802017-12-04 10:37:29 -08004983 if (channel) {
4984 return channel->transport_name();
Steve Anton75737c02017-11-06 10:37:17 -08004985 }
Steve Anton6fec8802017-12-04 10:37:29 -08004986 if (sctp_transport_) {
4987 RTC_DCHECK(sctp_content_name_);
4988 RTC_DCHECK(sctp_transport_name_);
4989 if (content_name == *sctp_content_name_) {
4990 return *sctp_transport_name_;
4991 }
4992 }
4993 // Return an empty string if failed to retrieve the transport name.
4994 return "";
Steve Anton75737c02017-11-06 10:37:17 -08004995}
4996
4997void PeerConnection::DestroyRtcpTransport_n(const std::string& transport_name) {
4998 RTC_DCHECK(network_thread()->IsCurrent());
4999 transport_controller_->DestroyDtlsTransport_n(
5000 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
5001}
5002
Steve Anton6fec8802017-12-04 10:37:29 -08005003void PeerConnection::DestroyTransceiverChannel(
5004 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
5005 transceiver) {
5006 RTC_DCHECK(transceiver);
Steve Anton75737c02017-11-06 10:37:17 -08005007
Steve Anton6fec8802017-12-04 10:37:29 -08005008 cricket::BaseChannel* channel = transceiver->internal()->channel();
5009 if (channel) {
5010 transceiver->internal()->SetChannel(nullptr);
5011 DestroyBaseChannel(channel);
Steve Anton75737c02017-11-06 10:37:17 -08005012 }
5013}
5014
5015void PeerConnection::DestroyDataChannel() {
Steve Anton6fec8802017-12-04 10:37:29 -08005016 if (rtp_data_channel_) {
5017 OnDataChannelDestroyed();
5018 DestroyBaseChannel(rtp_data_channel_);
5019 rtp_data_channel_ = nullptr;
5020 }
5021
5022 // Note: Cannot use rtc::Bind to create a functor to invoke because it will
5023 // grab a reference to this PeerConnection. If this is called from the
5024 // PeerConnection destructor, the RefCountedObject vtable will have already
5025 // been destroyed (since it is a subclass of PeerConnection) and using
5026 // rtc::Bind will cause "Pure virtual function called" error to appear.
5027
5028 if (sctp_transport_) {
5029 OnDataChannelDestroyed();
5030 network_thread()->Invoke<void>(RTC_FROM_HERE,
5031 [this] { DestroySctpTransport_n(); });
5032 }
5033}
5034
5035void PeerConnection::DestroyBaseChannel(cricket::BaseChannel* channel) {
5036 RTC_DCHECK(channel);
5037 RTC_DCHECK(channel->rtp_dtls_transport());
5038
5039 // Need to cache these before destroying the base channel so that we do not
5040 // access uninitialized memory.
5041 const std::string transport_name =
5042 channel->rtp_dtls_transport()->transport_name();
5043 const bool need_to_delete_rtcp = (channel->rtcp_dtls_transport() != nullptr);
5044
5045 switch (channel->media_type()) {
5046 case cricket::MEDIA_TYPE_AUDIO:
5047 channel_manager()->DestroyVoiceChannel(
5048 static_cast<cricket::VoiceChannel*>(channel));
5049 break;
5050 case cricket::MEDIA_TYPE_VIDEO:
5051 channel_manager()->DestroyVideoChannel(
5052 static_cast<cricket::VideoChannel*>(channel));
5053 break;
5054 case cricket::MEDIA_TYPE_DATA:
5055 channel_manager()->DestroyRtpDataChannel(
5056 static_cast<cricket::RtpDataChannel*>(channel));
5057 break;
5058 default:
5059 RTC_NOTREACHED() << "Unknown media type: " << channel->media_type();
5060 break;
5061 }
5062
5063 // |channel| can no longer be used.
5064
Steve Anton75737c02017-11-06 10:37:17 -08005065 transport_controller_->DestroyDtlsTransport(
5066 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5067 if (need_to_delete_rtcp) {
5068 transport_controller_->DestroyDtlsTransport(
5069 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
5070 }
5071}
5072
henrike@webrtc.org28e20752013-07-10 00:45:36 +00005073} // namespace webrtc