blob: 49ab979e409221b38e76a060919fc519bdbca875 [file] [log] [blame]
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001/*
kjellanderb24317b2016-02-10 07:54:43 -08002 * Copyright 2012 The WebRTC project authors. All Rights Reserved.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003 *
kjellanderb24317b2016-02-10 07:54:43 -08004 * Use of this source code is governed by a BSD-style license
5 * that can be found in the LICENSE file in the root of the source
6 * tree. An additional intellectual property rights grant can be found
7 * in the file PATENTS. All contributing project authors may
8 * be found in the AUTHORS file in the root of the source tree.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00009 */
10
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020011#include "pc/peerconnection.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000012
deadbeefeb459812015-12-15 19:24:43 -080013#include <algorithm>
Steve Anton75737c02017-11-06 10:37:17 -080014#include <set>
kwiberg0eb15ed2015-12-17 03:04:15 -080015#include <utility>
16#include <vector>
henrike@webrtc.org28e20752013-07-10 00:45:36 +000017
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020018#include "api/jsepicecandidate.h"
19#include "api/jsepsessiondescription.h"
20#include "api/mediaconstraintsinterface.h"
21#include "api/mediastreamproxy.h"
22#include "api/mediastreamtrackproxy.h"
23#include "call/call.h"
Elad Alon83ccca12017-10-04 13:18:26 +020024#include "logging/rtc_event_log/output/rtc_event_log_output_file.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020025#include "logging/rtc_event_log/rtc_event_log.h"
26#include "media/sctp/sctptransport.h"
27#include "pc/audiotrack.h"
Steve Anton75737c02017-11-06 10:37:17 -080028#include "pc/channel.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020029#include "pc/channelmanager.h"
30#include "pc/dtmfsender.h"
31#include "pc/mediastream.h"
32#include "pc/mediastreamobserver.h"
33#include "pc/remoteaudiosource.h"
Steve Anton1d03a752017-11-27 14:30:09 -080034#include "pc/rtpmediautils.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020035#include "pc/rtpreceiver.h"
36#include "pc/rtpsender.h"
Steve Anton75737c02017-11-06 10:37:17 -080037#include "pc/sctputils.h"
Steve Antona3a92c22017-12-07 10:27:41 -080038#include "pc/sdputils.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020039#include "pc/streamcollection.h"
40#include "pc/videocapturertracksource.h"
41#include "pc/videotrack.h"
42#include "rtc_base/bind.h"
43#include "rtc_base/checks.h"
44#include "rtc_base/logging.h"
Karl Wiberge40468b2017-11-22 10:42:26 +010045#include "rtc_base/numerics/safe_conversions.h"
Elad Alon83ccca12017-10-04 13:18:26 +020046#include "rtc_base/ptr_util.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020047#include "rtc_base/stringencode.h"
48#include "rtc_base/stringutils.h"
49#include "rtc_base/trace_event.h"
50#include "system_wrappers/include/clock.h"
51#include "system_wrappers/include/field_trial.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000052
Steve Anton75737c02017-11-06 10:37:17 -080053using cricket::ContentInfo;
54using cricket::ContentInfos;
55using cricket::MediaContentDescription;
56using cricket::SessionDescription;
57using cricket::TransportInfo;
58
59using cricket::LOCAL_PORT_TYPE;
60using cricket::STUN_PORT_TYPE;
61using cricket::RELAY_PORT_TYPE;
62using cricket::PRFLX_PORT_TYPE;
63
Steve Antonba818672017-11-06 10:21:57 -080064namespace webrtc {
65
Steve Anton75737c02017-11-06 10:37:17 -080066// Error messages
67const char kBundleWithoutRtcpMux[] =
68 "rtcp-mux must be enabled when BUNDLE "
69 "is enabled.";
Steve Anton75737c02017-11-06 10:37:17 -080070const char kInvalidCandidates[] = "Description contains invalid candidates.";
71const char kInvalidSdp[] = "Invalid session description.";
72const char kMlineMismatchInAnswer[] =
73 "The order of m-lines in answer doesn't match order in offer. Rejecting "
74 "answer.";
75const char kMlineMismatchInSubsequentOffer[] =
76 "The order of m-lines in subsequent offer doesn't match order from "
77 "previous offer/answer.";
Steve Anton75737c02017-11-06 10:37:17 -080078const char kSdpWithoutDtlsFingerprint[] =
79 "Called with SDP without DTLS fingerprint.";
80const char kSdpWithoutSdesCrypto[] = "Called with SDP without SDES crypto.";
81const char kSdpWithoutIceUfragPwd[] =
82 "Called with SDP without ice-ufrag and ice-pwd.";
83const char kSessionError[] = "Session error code: ";
84const char kSessionErrorDesc[] = "Session error description: ";
85const char kDtlsSrtpSetupFailureRtp[] =
86 "Couldn't set up DTLS-SRTP on RTP channel.";
87const char kDtlsSrtpSetupFailureRtcp[] =
88 "Couldn't set up DTLS-SRTP on RTCP channel.";
89const char kEnableBundleFailed[] = "Failed to enable BUNDLE.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +000090
Steve Anton75737c02017-11-06 10:37:17 -080091namespace {
henrike@webrtc.org28e20752013-07-10 00:45:36 +000092
deadbeefab9b2d12015-10-14 11:33:11 -070093static const char kDefaultStreamLabel[] = "default";
Steve Anton4171afb2017-11-20 10:20:22 -080094static const char kDefaultAudioSenderId[] = "defaulta0";
95static const char kDefaultVideoSenderId[] = "defaultv0";
deadbeefab9b2d12015-10-14 11:33:11 -070096
zhihuang8f65cdf2016-05-06 18:40:30 -070097// The length of RTCP CNAMEs.
98static const int kRtcpCnameLength = 16;
99
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000100enum {
wu@webrtc.org91053e72013-08-10 07:18:04 +0000101 MSG_SET_SESSIONDESCRIPTION_SUCCESS = 0,
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000102 MSG_SET_SESSIONDESCRIPTION_FAILED,
deadbeefab9b2d12015-10-14 11:33:11 -0700103 MSG_CREATE_SESSIONDESCRIPTION_FAILED,
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000104 MSG_GETSTATS,
deadbeefbd292462015-12-14 18:15:29 -0800105 MSG_FREE_DATACHANNELS,
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000106};
107
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000108struct SetSessionDescriptionMsg : public rtc::MessageData {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000109 explicit SetSessionDescriptionMsg(
110 webrtc::SetSessionDescriptionObserver* observer)
111 : observer(observer) {
112 }
113
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000114 rtc::scoped_refptr<webrtc::SetSessionDescriptionObserver> observer;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000115 std::string error;
116};
117
deadbeefab9b2d12015-10-14 11:33:11 -0700118struct CreateSessionDescriptionMsg : public rtc::MessageData {
119 explicit CreateSessionDescriptionMsg(
120 webrtc::CreateSessionDescriptionObserver* observer)
121 : observer(observer) {}
122
123 rtc::scoped_refptr<webrtc::CreateSessionDescriptionObserver> observer;
124 std::string error;
125};
126
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000127struct GetStatsMsg : public rtc::MessageData {
tommi@webrtc.org5b06b062014-08-15 08:38:30 +0000128 GetStatsMsg(webrtc::StatsObserver* observer,
129 webrtc::MediaStreamTrackInterface* track)
130 : observer(observer), track(track) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000131 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000132 rtc::scoped_refptr<webrtc::StatsObserver> observer;
tommi@webrtc.org5b06b062014-08-15 08:38:30 +0000133 rtc::scoped_refptr<webrtc::MediaStreamTrackInterface> track;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000134};
135
deadbeefab9b2d12015-10-14 11:33:11 -0700136// Check if we can send |new_stream| on a PeerConnection.
137bool CanAddLocalMediaStream(webrtc::StreamCollectionInterface* current_streams,
138 webrtc::MediaStreamInterface* new_stream) {
139 if (!new_stream || !current_streams) {
140 return false;
141 }
142 if (current_streams->find(new_stream->label()) != nullptr) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100143 RTC_LOG(LS_ERROR) << "MediaStream with label " << new_stream->label()
144 << " is already added.";
deadbeefab9b2d12015-10-14 11:33:11 -0700145 return false;
146 }
147 return true;
148}
149
deadbeef5e97fb52015-10-15 12:49:08 -0700150// If the direction is "recvonly" or "inactive", treat the description
151// as containing no streams.
152// See: https://code.google.com/p/webrtc/issues/detail?id=5054
153std::vector<cricket::StreamParams> GetActiveStreams(
154 const cricket::MediaContentDescription* desc) {
Steve Anton4e70a722017-11-28 14:57:10 -0800155 return RtpTransceiverDirectionHasSend(desc->direction())
deadbeef5e97fb52015-10-15 12:49:08 -0700156 ? desc->streams()
157 : std::vector<cricket::StreamParams>();
158}
159
deadbeefab9b2d12015-10-14 11:33:11 -0700160bool IsValidOfferToReceiveMedia(int value) {
161 typedef PeerConnectionInterface::RTCOfferAnswerOptions Options;
162 return (value >= Options::kUndefined) &&
163 (value <= Options::kMaxOfferToReceiveMedia);
164}
165
zhihuang1c378ed2017-08-17 14:10:50 -0700166// Add options to |[audio/video]_media_description_options| from |senders|.
167void AddRtpSenderOptions(
deadbeefa601f5c2016-06-06 14:27:39 -0700168 const std::vector<rtc::scoped_refptr<
169 RtpSenderProxyWithInternal<RtpSenderInternal>>>& senders,
zhihuang1c378ed2017-08-17 14:10:50 -0700170 cricket::MediaDescriptionOptions* audio_media_description_options,
171 cricket::MediaDescriptionOptions* video_media_description_options) {
olka3c747662017-08-17 06:50:32 -0700172 for (const auto& sender : senders) {
zhihuang1c378ed2017-08-17 14:10:50 -0700173 if (sender->media_type() == cricket::MEDIA_TYPE_AUDIO) {
174 if (audio_media_description_options) {
175 audio_media_description_options->AddAudioSender(
Steve Anton8ffb9c32017-08-31 15:45:38 -0700176 sender->id(), sender->internal()->stream_ids());
zhihuang1c378ed2017-08-17 14:10:50 -0700177 }
178 } else {
179 RTC_DCHECK(sender->media_type() == cricket::MEDIA_TYPE_VIDEO);
180 if (video_media_description_options) {
181 video_media_description_options->AddVideoSender(
Steve Anton8ffb9c32017-08-31 15:45:38 -0700182 sender->id(), sender->internal()->stream_ids(), 1);
zhihuang1c378ed2017-08-17 14:10:50 -0700183 }
184 }
zhihuanga77e6bb2017-08-14 18:17:48 -0700185 }
zhihuang1c378ed2017-08-17 14:10:50 -0700186}
olka3c747662017-08-17 06:50:32 -0700187
zhihuang1c378ed2017-08-17 14:10:50 -0700188// Add options to |session_options| from |rtp_data_channels|.
189void AddRtpDataChannelOptions(
190 const std::map<std::string, rtc::scoped_refptr<DataChannel>>&
191 rtp_data_channels,
192 cricket::MediaDescriptionOptions* data_media_description_options) {
193 if (!data_media_description_options) {
194 return;
195 }
deadbeefab9b2d12015-10-14 11:33:11 -0700196 // Check for data channels.
197 for (const auto& kv : rtp_data_channels) {
198 const DataChannel* channel = kv.second;
199 if (channel->state() == DataChannel::kConnecting ||
200 channel->state() == DataChannel::kOpen) {
zhihuang1c378ed2017-08-17 14:10:50 -0700201 // Legacy RTP data channels are signaled with the track/stream ID set to
202 // the data channel's label.
203 data_media_description_options->AddRtpDataChannel(channel->label(),
204 channel->label());
deadbeefab9b2d12015-10-14 11:33:11 -0700205 }
206 }
207}
208
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700209uint32_t ConvertIceTransportTypeToCandidateFilter(
210 PeerConnectionInterface::IceTransportsType type) {
211 switch (type) {
212 case PeerConnectionInterface::kNone:
213 return cricket::CF_NONE;
214 case PeerConnectionInterface::kRelay:
215 return cricket::CF_RELAY;
216 case PeerConnectionInterface::kNoHost:
217 return (cricket::CF_ALL & ~cricket::CF_HOST);
218 case PeerConnectionInterface::kAll:
219 return cricket::CF_ALL;
220 default:
nissec80e7412017-01-11 05:56:46 -0800221 RTC_NOTREACHED();
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700222 }
223 return cricket::CF_NONE;
224}
225
deadbeef293e9262017-01-11 12:28:30 -0800226// Helper to set an error and return from a method.
227bool SafeSetError(webrtc::RTCErrorType type, webrtc::RTCError* error) {
228 if (error) {
229 error->set_type(type);
230 }
231 return type == webrtc::RTCErrorType::NONE;
232}
233
Steve Anton038834f2017-07-14 15:59:59 -0700234bool SafeSetError(webrtc::RTCError error, webrtc::RTCError* error_out) {
235 if (error_out) {
236 *error_out = std::move(error);
237 }
238 return error.ok();
239}
240
Steve Antonba818672017-11-06 10:21:57 -0800241std::string GetSignalingStateString(
242 PeerConnectionInterface::SignalingState state) {
243 switch (state) {
244 case PeerConnectionInterface::kStable:
245 return "kStable";
246 case PeerConnectionInterface::kHaveLocalOffer:
247 return "kHaveLocalOffer";
248 case PeerConnectionInterface::kHaveLocalPrAnswer:
249 return "kHavePrAnswer";
250 case PeerConnectionInterface::kHaveRemoteOffer:
251 return "kHaveRemoteOffer";
252 case PeerConnectionInterface::kHaveRemotePrAnswer:
253 return "kHaveRemotePrAnswer";
254 case PeerConnectionInterface::kClosed:
255 return "kClosed";
256 }
257 RTC_NOTREACHED();
258 return "";
259}
deadbeef0a6c4ca2015-10-06 11:38:28 -0700260
Steve Anton75737c02017-11-06 10:37:17 -0800261IceCandidatePairType GetIceCandidatePairCounter(
262 const cricket::Candidate& local,
263 const cricket::Candidate& remote) {
264 const auto& l = local.type();
265 const auto& r = remote.type();
266 const auto& host = LOCAL_PORT_TYPE;
267 const auto& srflx = STUN_PORT_TYPE;
268 const auto& relay = RELAY_PORT_TYPE;
269 const auto& prflx = PRFLX_PORT_TYPE;
270 if (l == host && r == host) {
271 bool local_private = IPIsPrivate(local.address().ipaddr());
272 bool remote_private = IPIsPrivate(remote.address().ipaddr());
273 if (local_private) {
274 if (remote_private) {
275 return kIceCandidatePairHostPrivateHostPrivate;
276 } else {
277 return kIceCandidatePairHostPrivateHostPublic;
278 }
279 } else {
280 if (remote_private) {
281 return kIceCandidatePairHostPublicHostPrivate;
282 } else {
283 return kIceCandidatePairHostPublicHostPublic;
284 }
285 }
286 }
287 if (l == host && r == srflx)
288 return kIceCandidatePairHostSrflx;
289 if (l == host && r == relay)
290 return kIceCandidatePairHostRelay;
291 if (l == host && r == prflx)
292 return kIceCandidatePairHostPrflx;
293 if (l == srflx && r == host)
294 return kIceCandidatePairSrflxHost;
295 if (l == srflx && r == srflx)
296 return kIceCandidatePairSrflxSrflx;
297 if (l == srflx && r == relay)
298 return kIceCandidatePairSrflxRelay;
299 if (l == srflx && r == prflx)
300 return kIceCandidatePairSrflxPrflx;
301 if (l == relay && r == host)
302 return kIceCandidatePairRelayHost;
303 if (l == relay && r == srflx)
304 return kIceCandidatePairRelaySrflx;
305 if (l == relay && r == relay)
306 return kIceCandidatePairRelayRelay;
307 if (l == relay && r == prflx)
308 return kIceCandidatePairRelayPrflx;
309 if (l == prflx && r == host)
310 return kIceCandidatePairPrflxHost;
311 if (l == prflx && r == srflx)
312 return kIceCandidatePairPrflxSrflx;
313 if (l == prflx && r == relay)
314 return kIceCandidatePairPrflxRelay;
315 return kIceCandidatePairMax;
316}
317
318// Verify that the order of media sections in |new_desc| matches
319// |existing_desc|. The number of m= sections in |new_desc| should be no less
320// than |existing_desc|.
321bool MediaSectionsInSameOrder(const SessionDescription* existing_desc,
322 const SessionDescription* new_desc) {
323 if (!existing_desc || !new_desc) {
324 return false;
325 }
326
327 if (existing_desc->contents().size() > new_desc->contents().size()) {
328 return false;
329 }
330
331 for (size_t i = 0; i < existing_desc->contents().size(); ++i) {
332 if (new_desc->contents()[i].name != existing_desc->contents()[i].name) {
333 return false;
334 }
335 const MediaContentDescription* new_desc_mdesc =
336 static_cast<const MediaContentDescription*>(
337 new_desc->contents()[i].description);
338 const MediaContentDescription* existing_desc_mdesc =
339 static_cast<const MediaContentDescription*>(
340 existing_desc->contents()[i].description);
341 if (new_desc_mdesc->type() != existing_desc_mdesc->type()) {
342 return false;
343 }
344 }
345 return true;
346}
347
348bool MediaSectionsHaveSameCount(const SessionDescription* desc1,
349 const SessionDescription* desc2) {
350 if (!desc1 || !desc2) {
351 return false;
352 }
353 return desc1->contents().size() == desc2->contents().size();
354}
355
356// Checks that each non-rejected content has SDES crypto keys or a DTLS
357// fingerprint, unless it's in a BUNDLE group, in which case only the
358// BUNDLE-tag section (first media section/description in the BUNDLE group)
359// needs a ufrag and pwd. Mismatches, such as replying with a DTLS fingerprint
360// to SDES keys, will be caught in JsepTransport negotiation, and backstopped
361// by Channel's |srtp_required| check.
Steve Anton8a006912017-12-04 15:25:56 -0800362RTCError VerifyCrypto(const SessionDescription* desc, bool dtls_enabled) {
Steve Anton75737c02017-11-06 10:37:17 -0800363 const cricket::ContentGroup* bundle =
364 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton8a006912017-12-04 15:25:56 -0800365 for (const cricket::ContentInfo& content_info : desc->contents()) {
366 if (content_info.rejected) {
Steve Anton75737c02017-11-06 10:37:17 -0800367 continue;
368 }
Steve Anton8a006912017-12-04 15:25:56 -0800369 const std::string& mid = content_info.name;
370 if (bundle && bundle->HasContentName(mid) &&
371 mid != *(bundle->FirstContentName())) {
Steve Anton75737c02017-11-06 10:37:17 -0800372 // This isn't the first media section in the BUNDLE group, so it's not
373 // required to have crypto attributes, since only the crypto attributes
374 // from the first section actually get used.
375 continue;
376 }
377
378 // If the content isn't rejected or bundled into another m= section, crypto
379 // must be present.
380 const MediaContentDescription* media =
Steve Anton8a006912017-12-04 15:25:56 -0800381 static_cast<const MediaContentDescription*>(content_info.description);
382 const TransportInfo* tinfo = desc->GetTransportInfoByName(mid);
Steve Anton75737c02017-11-06 10:37:17 -0800383 if (!media || !tinfo) {
384 // Something is not right.
Steve Anton8a006912017-12-04 15:25:56 -0800385 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidSdp);
Steve Anton75737c02017-11-06 10:37:17 -0800386 }
387 if (dtls_enabled) {
388 if (!tinfo->description.identity_fingerprint) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100389 RTC_LOG(LS_WARNING)
390 << "Session description must have DTLS fingerprint if "
391 "DTLS enabled.";
Steve Anton8a006912017-12-04 15:25:56 -0800392 return RTCError(RTCErrorType::INVALID_PARAMETER,
393 kSdpWithoutDtlsFingerprint);
Steve Anton75737c02017-11-06 10:37:17 -0800394 }
395 } else {
396 if (media->cryptos().empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100397 RTC_LOG(LS_WARNING)
Steve Anton75737c02017-11-06 10:37:17 -0800398 << "Session description must have SDES when DTLS disabled.";
Steve Anton8a006912017-12-04 15:25:56 -0800399 return RTCError(RTCErrorType::INVALID_PARAMETER, kSdpWithoutSdesCrypto);
Steve Anton75737c02017-11-06 10:37:17 -0800400 }
401 }
402 }
Steve Anton8a006912017-12-04 15:25:56 -0800403 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -0800404}
405
406// Checks that each non-rejected content has ice-ufrag and ice-pwd set, unless
407// it's in a BUNDLE group, in which case only the BUNDLE-tag section (first
408// media section/description in the BUNDLE group) needs a ufrag and pwd.
409bool VerifyIceUfragPwdPresent(const SessionDescription* desc) {
410 const cricket::ContentGroup* bundle =
411 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton8a006912017-12-04 15:25:56 -0800412 for (const cricket::ContentInfo& content_info : desc->contents()) {
413 if (content_info.rejected) {
Steve Anton75737c02017-11-06 10:37:17 -0800414 continue;
415 }
Steve Anton8a006912017-12-04 15:25:56 -0800416 const std::string& mid = content_info.name;
417 if (bundle && bundle->HasContentName(mid) &&
418 mid != *(bundle->FirstContentName())) {
Steve Anton75737c02017-11-06 10:37:17 -0800419 // This isn't the first media section in the BUNDLE group, so it's not
420 // required to have ufrag/password, since only the ufrag/password from
421 // the first section actually get used.
422 continue;
423 }
424
425 // If the content isn't rejected or bundled into another m= section,
426 // ice-ufrag and ice-pwd must be present.
Steve Anton8a006912017-12-04 15:25:56 -0800427 const TransportInfo* tinfo = desc->GetTransportInfoByName(mid);
Steve Anton75737c02017-11-06 10:37:17 -0800428 if (!tinfo) {
429 // Something is not right.
Mirko Bonadei675513b2017-11-09 11:09:25 +0100430 RTC_LOG(LS_ERROR) << kInvalidSdp;
Steve Anton75737c02017-11-06 10:37:17 -0800431 return false;
432 }
433 if (tinfo->description.ice_ufrag.empty() ||
434 tinfo->description.ice_pwd.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100435 RTC_LOG(LS_ERROR) << "Session description must have ice ufrag and pwd.";
Steve Anton75737c02017-11-06 10:37:17 -0800436 return false;
437 }
438 }
439 return true;
440}
441
442bool GetTrackIdBySsrc(const SessionDescription* session_description,
443 uint32_t ssrc,
444 std::string* track_id) {
445 RTC_DCHECK(track_id != NULL);
446
447 const cricket::ContentInfo* audio_info =
448 cricket::GetFirstAudioContent(session_description);
449 if (audio_info) {
450 const cricket::MediaContentDescription* audio_content =
451 static_cast<const cricket::MediaContentDescription*>(
452 audio_info->description);
453
454 const auto* found =
455 cricket::GetStreamBySsrc(audio_content->streams(), ssrc);
456 if (found) {
457 *track_id = found->id;
458 return true;
459 }
460 }
461
462 const cricket::ContentInfo* video_info =
463 cricket::GetFirstVideoContent(session_description);
464 if (video_info) {
465 const cricket::MediaContentDescription* video_content =
466 static_cast<const cricket::MediaContentDescription*>(
467 video_info->description);
468
469 const auto* found =
470 cricket::GetStreamBySsrc(video_content->streams(), ssrc);
471 if (found) {
472 *track_id = found->id;
473 return true;
474 }
475 }
476 return false;
477}
478
479// Get the SCTP port out of a SessionDescription.
480// Return -1 if not found.
481int GetSctpPort(const SessionDescription* session_description) {
482 const ContentInfo* content_info = GetFirstDataContent(session_description);
483 RTC_DCHECK(content_info);
484 if (!content_info) {
485 return -1;
486 }
487 const cricket::DataContentDescription* data =
488 static_cast<const cricket::DataContentDescription*>(
489 (content_info->description));
490 std::string value;
491 cricket::DataCodec match_pattern(cricket::kGoogleSctpDataCodecPlType,
492 cricket::kGoogleSctpDataCodecName);
493 for (const cricket::DataCodec& codec : data->codecs()) {
494 if (!codec.Matches(match_pattern)) {
495 continue;
496 }
497 if (codec.GetParam(cricket::kCodecParamPort, &value)) {
498 return rtc::FromString<int>(value);
499 }
500 }
501 return -1;
502}
503
Steve Anton75737c02017-11-06 10:37:17 -0800504// Returns true if |new_desc| requests an ICE restart (i.e., new ufrag/pwd).
505bool CheckForRemoteIceRestart(const SessionDescriptionInterface* old_desc,
506 const SessionDescriptionInterface* new_desc,
507 const std::string& content_name) {
508 if (!old_desc) {
509 return false;
510 }
511 const SessionDescription* new_sd = new_desc->description();
512 const SessionDescription* old_sd = old_desc->description();
513 const ContentInfo* cinfo = new_sd->GetContentByName(content_name);
514 if (!cinfo || cinfo->rejected) {
515 return false;
516 }
517 // If the content isn't rejected, check if ufrag and password has changed.
518 const cricket::TransportDescription* new_transport_desc =
519 new_sd->GetTransportDescriptionByName(content_name);
520 const cricket::TransportDescription* old_transport_desc =
521 old_sd->GetTransportDescriptionByName(content_name);
522 if (!new_transport_desc || !old_transport_desc) {
523 // No transport description exists. This is not an ICE restart.
524 return false;
525 }
526 if (cricket::IceCredentialsChanged(
527 old_transport_desc->ice_ufrag, old_transport_desc->ice_pwd,
528 new_transport_desc->ice_ufrag, new_transport_desc->ice_pwd)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100529 RTC_LOG(LS_INFO) << "Remote peer requests ICE restart for " << content_name
530 << ".";
Steve Anton75737c02017-11-06 10:37:17 -0800531 return true;
532 }
533 return false;
534}
535
536} // namespace
537
Henrik Boström31638672017-11-23 17:48:32 +0100538// Upon completion, posts a task to execute the callback of the
539// SetSessionDescriptionObserver asynchronously on the same thread. At this
540// point, the state of the peer connection might no longer reflect the effects
541// of the SetRemoteDescription operation, as the peer connection could have been
542// modified during the post.
543// TODO(hbos): Remove this class once we remove the version of
544// PeerConnectionInterface::SetRemoteDescription() that takes a
545// SetSessionDescriptionObserver as an argument.
546class PeerConnection::SetRemoteDescriptionObserverAdapter
547 : public rtc::RefCountedObject<SetRemoteDescriptionObserverInterface> {
548 public:
549 SetRemoteDescriptionObserverAdapter(
550 rtc::scoped_refptr<PeerConnection> pc,
551 rtc::scoped_refptr<SetSessionDescriptionObserver> wrapper)
552 : pc_(std::move(pc)), wrapper_(std::move(wrapper)) {}
553
554 // SetRemoteDescriptionObserverInterface implementation.
555 void OnSetRemoteDescriptionComplete(RTCError error) override {
556 if (error.ok())
557 pc_->PostSetSessionDescriptionSuccess(wrapper_);
558 else
559 pc_->PostSetSessionDescriptionFailure(wrapper_, error.message());
560 }
561
562 private:
563 rtc::scoped_refptr<PeerConnection> pc_;
564 rtc::scoped_refptr<SetSessionDescriptionObserver> wrapper_;
565};
566
deadbeef293e9262017-01-11 12:28:30 -0800567bool PeerConnectionInterface::RTCConfiguration::operator==(
568 const PeerConnectionInterface::RTCConfiguration& o) const {
569 // This static_assert prevents us from accidentally breaking operator==.
Steve Anton300bf8e2017-07-14 10:13:10 -0700570 // Note: Order matters! Fields must be ordered the same as RTCConfiguration.
deadbeef293e9262017-01-11 12:28:30 -0800571 struct stuff_being_tested_for_equality {
Magnus Jedvert3beb2072017-07-14 14:23:56 +0000572 IceServers servers;
Steve Anton300bf8e2017-07-14 10:13:10 -0700573 IceTransportsType type;
deadbeef293e9262017-01-11 12:28:30 -0800574 BundlePolicy bundle_policy;
575 RtcpMuxPolicy rtcp_mux_policy;
Steve Anton300bf8e2017-07-14 10:13:10 -0700576 std::vector<rtc::scoped_refptr<rtc::RTCCertificate>> certificates;
577 int ice_candidate_pool_size;
578 bool disable_ipv6;
579 bool disable_ipv6_on_wifi;
deadbeefd21eab32017-07-26 16:50:11 -0700580 int max_ipv6_networks;
Steve Anton300bf8e2017-07-14 10:13:10 -0700581 bool enable_rtp_data_channel;
582 rtc::Optional<int> screencast_min_bitrate;
583 rtc::Optional<bool> combined_audio_video_bwe;
584 rtc::Optional<bool> enable_dtls_srtp;
deadbeef293e9262017-01-11 12:28:30 -0800585 TcpCandidatePolicy tcp_candidate_policy;
586 CandidateNetworkPolicy candidate_network_policy;
587 int audio_jitter_buffer_max_packets;
588 bool audio_jitter_buffer_fast_accelerate;
589 int ice_connection_receiving_timeout;
590 int ice_backup_candidate_pair_ping_interval;
591 ContinualGatheringPolicy continual_gathering_policy;
deadbeef293e9262017-01-11 12:28:30 -0800592 bool prioritize_most_likely_ice_candidate_pairs;
593 struct cricket::MediaConfig media_config;
deadbeef293e9262017-01-11 12:28:30 -0800594 bool prune_turn_ports;
595 bool presume_writable_when_fully_relayed;
596 bool enable_ice_renomination;
597 bool redetermine_role_on_ice_restart;
skvlad51072462017-02-02 11:50:14 -0800598 rtc::Optional<int> ice_check_min_interval;
Steve Anton300bf8e2017-07-14 10:13:10 -0700599 rtc::Optional<rtc::IntervalRange> ice_regather_interval_range;
Jonas Orelandbdcee282017-10-10 14:01:40 +0200600 webrtc::TurnCustomizer* turn_customizer;
Steve Anton79e79602017-11-20 10:25:56 -0800601 SdpSemantics sdp_semantics;
deadbeef293e9262017-01-11 12:28:30 -0800602 };
603 static_assert(sizeof(stuff_being_tested_for_equality) == sizeof(*this),
604 "Did you add something to RTCConfiguration and forget to "
605 "update operator==?");
606 return type == o.type && servers == o.servers &&
607 bundle_policy == o.bundle_policy &&
608 rtcp_mux_policy == o.rtcp_mux_policy &&
609 tcp_candidate_policy == o.tcp_candidate_policy &&
610 candidate_network_policy == o.candidate_network_policy &&
611 audio_jitter_buffer_max_packets == o.audio_jitter_buffer_max_packets &&
612 audio_jitter_buffer_fast_accelerate ==
613 o.audio_jitter_buffer_fast_accelerate &&
614 ice_connection_receiving_timeout ==
615 o.ice_connection_receiving_timeout &&
616 ice_backup_candidate_pair_ping_interval ==
617 o.ice_backup_candidate_pair_ping_interval &&
618 continual_gathering_policy == o.continual_gathering_policy &&
619 certificates == o.certificates &&
620 prioritize_most_likely_ice_candidate_pairs ==
621 o.prioritize_most_likely_ice_candidate_pairs &&
622 media_config == o.media_config && disable_ipv6 == o.disable_ipv6 &&
zhihuangb09b3f92017-03-07 14:40:51 -0800623 disable_ipv6_on_wifi == o.disable_ipv6_on_wifi &&
deadbeefd21eab32017-07-26 16:50:11 -0700624 max_ipv6_networks == o.max_ipv6_networks &&
deadbeef293e9262017-01-11 12:28:30 -0800625 enable_rtp_data_channel == o.enable_rtp_data_channel &&
deadbeef293e9262017-01-11 12:28:30 -0800626 screencast_min_bitrate == o.screencast_min_bitrate &&
627 combined_audio_video_bwe == o.combined_audio_video_bwe &&
628 enable_dtls_srtp == o.enable_dtls_srtp &&
629 ice_candidate_pool_size == o.ice_candidate_pool_size &&
630 prune_turn_ports == o.prune_turn_ports &&
631 presume_writable_when_fully_relayed ==
632 o.presume_writable_when_fully_relayed &&
633 enable_ice_renomination == o.enable_ice_renomination &&
skvlad51072462017-02-02 11:50:14 -0800634 redetermine_role_on_ice_restart == o.redetermine_role_on_ice_restart &&
Steve Anton300bf8e2017-07-14 10:13:10 -0700635 ice_check_min_interval == o.ice_check_min_interval &&
Jonas Orelandbdcee282017-10-10 14:01:40 +0200636 ice_regather_interval_range == o.ice_regather_interval_range &&
Steve Anton79e79602017-11-20 10:25:56 -0800637 turn_customizer == o.turn_customizer &&
638 sdp_semantics == o.sdp_semantics;
deadbeef293e9262017-01-11 12:28:30 -0800639}
640
641bool PeerConnectionInterface::RTCConfiguration::operator!=(
642 const PeerConnectionInterface::RTCConfiguration& o) const {
643 return !(*this == o);
deadbeef3edec7c2016-12-10 11:44:26 -0800644}
645
zhihuang8f65cdf2016-05-06 18:40:30 -0700646// Generate a RTCP CNAME when a PeerConnection is created.
647std::string GenerateRtcpCname() {
648 std::string cname;
649 if (!rtc::CreateRandomString(kRtcpCnameLength, &cname)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100650 RTC_LOG(LS_ERROR) << "Failed to generate CNAME.";
nisseeb4ca4e2017-01-12 02:24:27 -0800651 RTC_NOTREACHED();
zhihuang8f65cdf2016-05-06 18:40:30 -0700652 }
653 return cname;
654}
655
zhihuang1c378ed2017-08-17 14:10:50 -0700656bool ValidateOfferAnswerOptions(
657 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options) {
658 return IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_audio) &&
659 IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_video);
olka3c747662017-08-17 06:50:32 -0700660}
661
zhihuang1c378ed2017-08-17 14:10:50 -0700662// From |rtc_options|, fill parts of |session_options| shared by all generated
663// m= sections (in other words, nothing that involves a map/array).
664void ExtractSharedMediaSessionOptions(
665 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options,
666 cricket::MediaSessionOptions* session_options) {
667 session_options->vad_enabled = rtc_options.voice_activity_detection;
668 session_options->bundle_enabled = rtc_options.use_rtp_mux;
669}
zhihuanga77e6bb2017-08-14 18:17:48 -0700670
zhihuang1c378ed2017-08-17 14:10:50 -0700671bool ConvertConstraintsToOfferAnswerOptions(
672 const MediaConstraintsInterface* constraints,
673 PeerConnectionInterface::RTCOfferAnswerOptions* offer_answer_options) {
olka3c747662017-08-17 06:50:32 -0700674 if (!constraints) {
675 return true;
676 }
zhihuang1c378ed2017-08-17 14:10:50 -0700677
678 bool value = false;
679 size_t mandatory_constraints_satisfied = 0;
680
681 if (FindConstraint(constraints,
682 MediaConstraintsInterface::kOfferToReceiveAudio, &value,
683 &mandatory_constraints_satisfied)) {
684 offer_answer_options->offer_to_receive_audio =
685 value ? PeerConnectionInterface::RTCOfferAnswerOptions::
686 kOfferToReceiveMediaTrue
687 : 0;
688 }
689
690 if (FindConstraint(constraints,
691 MediaConstraintsInterface::kOfferToReceiveVideo, &value,
692 &mandatory_constraints_satisfied)) {
693 offer_answer_options->offer_to_receive_video =
694 value ? PeerConnectionInterface::RTCOfferAnswerOptions::
695 kOfferToReceiveMediaTrue
696 : 0;
697 }
698 if (FindConstraint(constraints,
699 MediaConstraintsInterface::kVoiceActivityDetection, &value,
700 &mandatory_constraints_satisfied)) {
701 offer_answer_options->voice_activity_detection = value;
702 }
703 if (FindConstraint(constraints, MediaConstraintsInterface::kUseRtpMux, &value,
704 &mandatory_constraints_satisfied)) {
705 offer_answer_options->use_rtp_mux = value;
706 }
707 if (FindConstraint(constraints, MediaConstraintsInterface::kIceRestart,
708 &value, &mandatory_constraints_satisfied)) {
709 offer_answer_options->ice_restart = value;
710 }
711
deadbeefab9b2d12015-10-14 11:33:11 -0700712 return mandatory_constraints_satisfied == constraints->GetMandatory().size();
713}
714
zhihuang38ede132017-06-15 12:52:32 -0700715PeerConnection::PeerConnection(PeerConnectionFactory* factory,
716 std::unique_ptr<RtcEventLog> event_log,
717 std::unique_ptr<Call> call)
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000718 : factory_(factory),
zhihuang38ede132017-06-15 12:52:32 -0700719 event_log_(std::move(event_log)),
zhihuang8f65cdf2016-05-06 18:40:30 -0700720 rtcp_cname_(GenerateRtcpCname()),
deadbeefab9b2d12015-10-14 11:33:11 -0700721 local_streams_(StreamCollection::Create()),
zhihuang38ede132017-06-15 12:52:32 -0700722 remote_streams_(StreamCollection::Create()),
723 call_(std::move(call)) {}
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000724
725PeerConnection::~PeerConnection() {
Peter Boström1a9d6152015-12-08 22:15:17 +0100726 TRACE_EVENT0("webrtc", "PeerConnection::~PeerConnection");
Steve Anton4171afb2017-11-20 10:20:22 -0800727 RTC_DCHECK_RUN_ON(signaling_thread());
728
Steve Anton3fe1b152017-12-12 10:20:08 -0800729 StopAndDestroyChannels();
Steve Anton4171afb2017-11-20 10:20:22 -0800730
Steve Anton3fe1b152017-12-12 10:20:08 -0800731 // Destroy stats after stopping all transceivers because the senders/receivers
732 // will update the stats collector before stopping.
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700733 stats_.reset(nullptr);
hbosb78306a2016-12-19 05:06:57 -0800734 if (stats_collector_) {
735 stats_collector_->WaitForPendingRequest();
736 stats_collector_ = nullptr;
737 }
Steve Anton75737c02017-11-06 10:37:17 -0800738
Mirko Bonadei675513b2017-11-09 11:09:25 +0100739 RTC_LOG(LS_INFO) << "Session: " << session_id() << " is destroyed.";
Steve Anton75737c02017-11-06 10:37:17 -0800740
741 webrtc_session_desc_factory_.reset();
742 sctp_invoker_.reset();
743 sctp_factory_.reset();
744 transport_controller_.reset();
745
deadbeef91dd5672016-05-18 16:55:30 -0700746 // port_allocator_ lives on the network thread and should be destroyed there.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700747 network_thread()->Invoke<void>(RTC_FROM_HERE,
nisseeaabdf62017-05-05 02:23:02 -0700748 [this] { port_allocator_.reset(); });
eladalon248fd4f2017-09-06 05:18:15 -0700749 // call_ and event_log_ must be destroyed on the worker thread.
Steve Anton978b8762017-09-29 12:15:02 -0700750 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
eladalon248fd4f2017-09-06 05:18:15 -0700751 call_.reset();
752 event_log_.reset();
753 });
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000754}
755
Steve Anton3fe1b152017-12-12 10:20:08 -0800756void PeerConnection::StopAndDestroyChannels() {
757 for (auto transceiver : transceivers_) {
758 transceiver->Stop();
759 }
760 // Destroy video channels first since they may have a pointer to a voice
761 // channel.
762 for (auto transceiver : transceivers_) {
763 if (transceiver->internal()->media_type() == cricket::MEDIA_TYPE_VIDEO) {
764 DestroyTransceiverChannel(transceiver);
765 }
766 }
767 for (auto transceiver : transceivers_) {
768 if (transceiver->internal()->media_type() == cricket::MEDIA_TYPE_AUDIO) {
769 DestroyTransceiverChannel(transceiver);
770 }
771 }
772 DestroyDataChannel();
773}
774
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000775bool PeerConnection::Initialize(
buildbot@webrtc.org41451d42014-05-03 05:39:45 +0000776 const PeerConnectionInterface::RTCConfiguration& configuration,
kwibergd1fe2812016-04-27 06:47:29 -0700777 std::unique_ptr<cricket::PortAllocator> allocator,
Henrik Boströmd03c23b2016-06-01 11:44:18 +0200778 std::unique_ptr<rtc::RTCCertificateGeneratorInterface> cert_generator,
deadbeef653b8e02015-11-11 12:55:10 -0800779 PeerConnectionObserver* observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100780 TRACE_EVENT0("webrtc", "PeerConnection::Initialize");
Steve Anton038834f2017-07-14 15:59:59 -0700781
782 RTCError config_error = ValidateConfiguration(configuration);
783 if (!config_error.ok()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100784 RTC_LOG(LS_ERROR) << "Invalid configuration: " << config_error.message();
Steve Anton038834f2017-07-14 15:59:59 -0700785 return false;
786 }
787
deadbeef293e9262017-01-11 12:28:30 -0800788 if (!allocator) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100789 RTC_LOG(LS_ERROR)
790 << "PeerConnection initialized without a PortAllocator? "
791 << "This shouldn't happen if using PeerConnectionFactory.";
deadbeef293e9262017-01-11 12:28:30 -0800792 return false;
793 }
Jonas Orelandbdcee282017-10-10 14:01:40 +0200794
deadbeef653b8e02015-11-11 12:55:10 -0800795 if (!observer) {
deadbeef293e9262017-01-11 12:28:30 -0800796 // TODO(deadbeef): Why do we do this?
Mirko Bonadei675513b2017-11-09 11:09:25 +0100797 RTC_LOG(LS_ERROR) << "PeerConnection initialized without a "
798 << "PeerConnectionObserver";
deadbeef653b8e02015-11-11 12:55:10 -0800799 return false;
800 }
pthatcher@webrtc.org877ac762015-02-04 22:03:09 +0000801 observer_ = observer;
kwiberg0eb15ed2015-12-17 03:04:15 -0800802 port_allocator_ = std::move(allocator);
deadbeef653b8e02015-11-11 12:55:10 -0800803
deadbeef91dd5672016-05-18 16:55:30 -0700804 // The port allocator lives on the network thread and should be initialized
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700805 // there.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700806 if (!network_thread()->Invoke<bool>(
807 RTC_FROM_HERE, rtc::Bind(&PeerConnection::InitializePortAllocator_n,
808 this, configuration))) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000809 return false;
810 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000811
Steve Anton75737c02017-11-06 10:37:17 -0800812 // RFC 3264: The numeric value of the session id and version in the
813 // o line MUST be representable with a "64 bit signed integer".
814 // Due to this constraint session id |session_id_| is max limited to
815 // LLONG_MAX.
816 session_id_ = rtc::ToString(rtc::CreateRandomId64() & LLONG_MAX);
817 transport_controller_.reset(factory_->CreateTransportController(
818 port_allocator_.get(), configuration.redetermine_role_on_ice_restart));
819 transport_controller_->SetIceRole(cricket::ICEROLE_CONTROLLED);
820 transport_controller_->SignalConnectionState.connect(
821 this, &PeerConnection::OnTransportControllerConnectionState);
822 transport_controller_->SignalGatheringState.connect(
823 this, &PeerConnection::OnTransportControllerGatheringState);
824 transport_controller_->SignalCandidatesGathered.connect(
825 this, &PeerConnection::OnTransportControllerCandidatesGathered);
826 transport_controller_->SignalCandidatesRemoved.connect(
827 this, &PeerConnection::OnTransportControllerCandidatesRemoved);
828 transport_controller_->SignalDtlsHandshakeError.connect(
829 this, &PeerConnection::OnTransportControllerDtlsHandshakeError);
830
831 sctp_factory_ = factory_->CreateSctpTransportInternalFactory();
zhihuang29ff8442016-07-27 11:07:25 -0700832
deadbeefab9b2d12015-10-14 11:33:11 -0700833 stats_.reset(new StatsCollector(this));
hbos74e1a4f2016-09-15 23:33:01 -0700834 stats_collector_ = RTCStatsCollector::Create(this);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000835
Steve Antonba818672017-11-06 10:21:57 -0800836 configuration_ = configuration;
837
Steve Anton75737c02017-11-06 10:37:17 -0800838 const PeerConnectionFactoryInterface::Options& options = factory_->options();
839
840 transport_controller_->SetSslMaxProtocolVersion(options.ssl_max_version);
841
842 // Obtain a certificate from RTCConfiguration if any were provided (optional).
843 rtc::scoped_refptr<rtc::RTCCertificate> certificate;
844 if (!configuration.certificates.empty()) {
845 // TODO(hbos,torbjorng): Decide on certificate-selection strategy instead of
846 // just picking the first one. The decision should be made based on the DTLS
847 // handshake. The DTLS negotiations need to know about all certificates.
848 certificate = configuration.certificates[0];
849 }
850
Steve Antond25da372017-11-06 14:50:29 -0800851 transport_controller_->SetIceConfig(ParseIceConfig(configuration));
Steve Anton75737c02017-11-06 10:37:17 -0800852
853 if (options.disable_encryption) {
854 dtls_enabled_ = false;
855 } else {
856 // Enable DTLS by default if we have an identity store or a certificate.
857 dtls_enabled_ = (cert_generator || certificate);
858 // |configuration| can override the default |dtls_enabled_| value.
859 if (configuration.enable_dtls_srtp) {
860 dtls_enabled_ = *(configuration.enable_dtls_srtp);
861 }
862 }
863
864 // Enable creation of RTP data channels if the kEnableRtpDataChannels is set.
865 // It takes precendence over the disable_sctp_data_channels
866 // PeerConnectionFactoryInterface::Options.
867 if (configuration.enable_rtp_data_channel) {
868 data_channel_type_ = cricket::DCT_RTP;
869 } else {
870 // DTLS has to be enabled to use SCTP.
871 if (!options.disable_sctp_data_channels && dtls_enabled_) {
872 data_channel_type_ = cricket::DCT_SCTP;
873 }
874 }
875
876 video_options_.screencast_min_bitrate_kbps =
877 configuration.screencast_min_bitrate;
878 audio_options_.combined_audio_video_bwe =
879 configuration.combined_audio_video_bwe;
880
881 audio_options_.audio_jitter_buffer_max_packets =
Oskar Sundbom9b28a032017-11-16 10:53:30 +0100882 configuration.audio_jitter_buffer_max_packets;
Steve Anton75737c02017-11-06 10:37:17 -0800883
884 audio_options_.audio_jitter_buffer_fast_accelerate =
Oskar Sundbom9b28a032017-11-16 10:53:30 +0100885 configuration.audio_jitter_buffer_fast_accelerate;
Steve Anton75737c02017-11-06 10:37:17 -0800886
887 // Whether the certificate generator/certificate is null or not determines
888 // what PeerConnectionDescriptionFactory will do, so make sure that we give it
889 // the right instructions by clearing the variables if needed.
890 if (!dtls_enabled_) {
891 cert_generator.reset();
892 certificate = nullptr;
893 } else if (certificate) {
894 // Favor generated certificate over the certificate generator.
895 cert_generator.reset();
896 }
897
898 webrtc_session_desc_factory_.reset(new WebRtcSessionDescriptionFactory(
899 signaling_thread(), channel_manager(), this, session_id(),
900 std::move(cert_generator), certificate));
901 webrtc_session_desc_factory_->SignalCertificateReady.connect(
902 this, &PeerConnection::OnCertificateReady);
903
904 if (options.disable_encryption) {
905 webrtc_session_desc_factory_->SetSdesPolicy(cricket::SEC_DISABLED);
906 }
907
908 webrtc_session_desc_factory_->set_enable_encrypted_rtp_header_extensions(
909 options.crypto_options.enable_encrypted_rtp_header_extensions);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000910
Steve Anton4171afb2017-11-20 10:20:22 -0800911 // Add default audio/video transceivers for Plan B SDP.
912 if (!IsUnifiedPlan()) {
913 transceivers_.push_back(
914 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
915 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_AUDIO)));
916 transceivers_.push_back(
917 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
918 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_VIDEO)));
919 }
920
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000921 return true;
922}
923
Steve Anton038834f2017-07-14 15:59:59 -0700924RTCError PeerConnection::ValidateConfiguration(
925 const RTCConfiguration& config) const {
926 if (config.ice_regather_interval_range &&
927 config.continual_gathering_policy == GATHER_ONCE) {
928 return RTCError(RTCErrorType::INVALID_PARAMETER,
929 "ice_regather_interval_range specified but continual "
930 "gathering policy is GATHER_ONCE");
931 }
932 return RTCError::OK();
933}
934
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000935rtc::scoped_refptr<StreamCollectionInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000936PeerConnection::local_streams() {
deadbeefab9b2d12015-10-14 11:33:11 -0700937 return local_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000938}
939
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000940rtc::scoped_refptr<StreamCollectionInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000941PeerConnection::remote_streams() {
deadbeefab9b2d12015-10-14 11:33:11 -0700942 return remote_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000943}
944
perkj@webrtc.orgc2dd5ee2014-11-04 11:31:29 +0000945bool PeerConnection::AddStream(MediaStreamInterface* local_stream) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100946 TRACE_EVENT0("webrtc", "PeerConnection::AddStream");
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000947 if (IsClosed()) {
948 return false;
949 }
deadbeefab9b2d12015-10-14 11:33:11 -0700950 if (!CanAddLocalMediaStream(local_streams_, local_stream)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000951 return false;
952 }
deadbeefab9b2d12015-10-14 11:33:11 -0700953
954 local_streams_->AddStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -0800955 MediaStreamObserver* observer = new MediaStreamObserver(local_stream);
956 observer->SignalAudioTrackAdded.connect(this,
957 &PeerConnection::OnAudioTrackAdded);
958 observer->SignalAudioTrackRemoved.connect(
959 this, &PeerConnection::OnAudioTrackRemoved);
960 observer->SignalVideoTrackAdded.connect(this,
961 &PeerConnection::OnVideoTrackAdded);
962 observer->SignalVideoTrackRemoved.connect(
963 this, &PeerConnection::OnVideoTrackRemoved);
kwibergd1fe2812016-04-27 06:47:29 -0700964 stream_observers_.push_back(std::unique_ptr<MediaStreamObserver>(observer));
deadbeefab9b2d12015-10-14 11:33:11 -0700965
deadbeefab9b2d12015-10-14 11:33:11 -0700966 for (const auto& track : local_stream->GetAudioTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -0700967 AddAudioTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -0700968 }
969 for (const auto& track : local_stream->GetVideoTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -0700970 AddVideoTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -0700971 }
972
tommi@webrtc.org03505bc2014-07-14 20:15:26 +0000973 stats_->AddStream(local_stream);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000974 observer_->OnRenegotiationNeeded();
975 return true;
976}
977
978void PeerConnection::RemoveStream(MediaStreamInterface* local_stream) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100979 TRACE_EVENT0("webrtc", "PeerConnection::RemoveStream");
korniltsev.anatolyec390b52017-07-24 17:00:25 -0700980 if (!IsClosed()) {
981 for (const auto& track : local_stream->GetAudioTracks()) {
982 RemoveAudioTrack(track.get(), local_stream);
983 }
984 for (const auto& track : local_stream->GetVideoTracks()) {
985 RemoveVideoTrack(track.get(), local_stream);
986 }
deadbeefab9b2d12015-10-14 11:33:11 -0700987 }
deadbeefab9b2d12015-10-14 11:33:11 -0700988 local_streams_->RemoveStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -0800989 stream_observers_.erase(
990 std::remove_if(
991 stream_observers_.begin(), stream_observers_.end(),
kwibergd1fe2812016-04-27 06:47:29 -0700992 [local_stream](const std::unique_ptr<MediaStreamObserver>& observer) {
deadbeefeb459812015-12-15 19:24:43 -0800993 return observer->stream()->label().compare(local_stream->label()) ==
994 0;
995 }),
996 stream_observers_.end());
deadbeefab9b2d12015-10-14 11:33:11 -0700997
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000998 if (IsClosed()) {
999 return;
1000 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001001 observer_->OnRenegotiationNeeded();
1002}
1003
deadbeefe1f9d832016-01-14 15:35:42 -08001004rtc::scoped_refptr<RtpSenderInterface> PeerConnection::AddTrack(
1005 MediaStreamTrackInterface* track,
1006 std::vector<MediaStreamInterface*> streams) {
1007 TRACE_EVENT0("webrtc", "PeerConnection::AddTrack");
Steve Antonf9381f02017-12-14 10:23:57 -08001008 std::vector<std::string> stream_labels;
1009 for (auto* stream : streams) {
1010 if (!stream) {
1011 RTC_LOG(LS_ERROR) << "Stream list has null element.";
1012 return nullptr;
1013 }
1014 stream_labels.push_back(stream->label());
1015 }
1016 auto sender_or_error = AddTrackWithStreamLabels(track, stream_labels);
1017 if (!sender_or_error.ok()) {
deadbeefe1f9d832016-01-14 15:35:42 -08001018 return nullptr;
1019 }
Steve Antonf9381f02017-12-14 10:23:57 -08001020 return sender_or_error.MoveValue();
1021}
1022
1023RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>>
1024PeerConnection::AddTrackWithStreamLabels(
1025 rtc::scoped_refptr<MediaStreamTrackInterface> track,
1026 const std::vector<std::string>& stream_labels) {
1027 TRACE_EVENT0("webrtc", "PeerConnection::AddTrackWithStreamLabels");
1028 if (!track) {
1029 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "Track is null.");
1030 }
1031 if (!(track->kind() == MediaStreamTrackInterface::kAudioKind ||
1032 track->kind() == MediaStreamTrackInterface::kVideoKind)) {
1033 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1034 "Track has invalid kind: " + track->kind());
1035 }
1036 // TODO(bugs.webrtc.org/7932): Support adding a track to multiple streams.
1037 if (stream_labels.size() > 1u) {
1038 LOG_AND_RETURN_ERROR(
1039 RTCErrorType::UNSUPPORTED_OPERATION,
1040 "AddTrack with more than one stream is not currently supported.");
1041 }
1042 if (IsClosed()) {
1043 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
1044 "PeerConnection is closed.");
deadbeefe1f9d832016-01-14 15:35:42 -08001045 }
Steve Anton4171afb2017-11-20 10:20:22 -08001046 if (FindSenderForTrack(track)) {
Steve Antonf9381f02017-12-14 10:23:57 -08001047 LOG_AND_RETURN_ERROR(
1048 RTCErrorType::INVALID_PARAMETER,
1049 "Sender already exists for track " + track->id() + ".");
deadbeefe1f9d832016-01-14 15:35:42 -08001050 }
Steve Antonf9381f02017-12-14 10:23:57 -08001051 // TODO(bugs.webrtc.org/7933): MediaSession expects the sender to have exactly
1052 // one stream. AddTrackInternal will return an error if there is more than one
1053 // stream, but if the caller specifies none then we need to generate a random
1054 // stream label.
1055 std::vector<std::string> adjusted_stream_labels = stream_labels;
1056 if (stream_labels.empty()) {
1057 adjusted_stream_labels.push_back(rtc::CreateRandomUuid());
1058 }
1059 RTC_DCHECK_EQ(1, adjusted_stream_labels.size());
1060 auto sender_or_error =
1061 (IsUnifiedPlan() ? AddTrackUnifiedPlan(track, adjusted_stream_labels)
1062 : AddTrackPlanB(track, adjusted_stream_labels));
1063 if (sender_or_error.ok()) {
1064 observer_->OnRenegotiationNeeded();
1065 }
1066 return sender_or_error;
1067}
deadbeefe1f9d832016-01-14 15:35:42 -08001068
Steve Antonf9381f02017-12-14 10:23:57 -08001069RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>>
1070PeerConnection::AddTrackPlanB(
1071 rtc::scoped_refptr<MediaStreamTrackInterface> track,
1072 const std::vector<std::string>& stream_labels) {
deadbeefe1f9d832016-01-14 15:35:42 -08001073 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
Steve Antonf9381f02017-12-14 10:23:57 -08001074 auto new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
deadbeefe1f9d832016-01-14 15:35:42 -08001075 signaling_thread(),
Steve Antonf9381f02017-12-14 10:23:57 -08001076 new AudioRtpSender(static_cast<AudioTrackInterface*>(track.get()),
Steve Anton75737c02017-11-06 10:37:17 -08001077 voice_channel(), stats_.get()));
Steve Anton4171afb2017-11-20 10:20:22 -08001078 GetAudioTransceiver()->internal()->AddSender(new_sender);
Steve Antonf9381f02017-12-14 10:23:57 -08001079 new_sender->internal()->set_stream_ids(stream_labels);
Steve Anton4171afb2017-11-20 10:20:22 -08001080 const RtpSenderInfo* sender_info =
1081 FindSenderInfo(local_audio_sender_infos_,
1082 new_sender->internal()->stream_id(), track->id());
1083 if (sender_info) {
1084 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -08001085 }
Steve Antonf9381f02017-12-14 10:23:57 -08001086 return rtc::scoped_refptr<RtpSenderInterface>(new_sender);
1087 } else {
1088 RTC_DCHECK_EQ(MediaStreamTrackInterface::kVideoKind, track->kind());
1089 auto new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
deadbeefe1f9d832016-01-14 15:35:42 -08001090 signaling_thread(),
Steve Antonf9381f02017-12-14 10:23:57 -08001091 new VideoRtpSender(static_cast<VideoTrackInterface*>(track.get()),
Steve Anton75737c02017-11-06 10:37:17 -08001092 video_channel()));
Steve Anton4171afb2017-11-20 10:20:22 -08001093 GetVideoTransceiver()->internal()->AddSender(new_sender);
Steve Antonf9381f02017-12-14 10:23:57 -08001094 new_sender->internal()->set_stream_ids(stream_labels);
Steve Anton4171afb2017-11-20 10:20:22 -08001095 const RtpSenderInfo* sender_info =
1096 FindSenderInfo(local_video_sender_infos_,
1097 new_sender->internal()->stream_id(), track->id());
1098 if (sender_info) {
1099 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -08001100 }
Steve Antonf9381f02017-12-14 10:23:57 -08001101 return rtc::scoped_refptr<RtpSenderInterface>(new_sender);
deadbeefe1f9d832016-01-14 15:35:42 -08001102 }
Steve Antonf9381f02017-12-14 10:23:57 -08001103}
deadbeefe1f9d832016-01-14 15:35:42 -08001104
Steve Antonf9381f02017-12-14 10:23:57 -08001105RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>>
1106PeerConnection::AddTrackUnifiedPlan(
1107 rtc::scoped_refptr<MediaStreamTrackInterface> track,
1108 const std::vector<std::string>& stream_labels) {
1109 auto transceiver = FindFirstTransceiverForAddedTrack(track);
1110 if (transceiver) {
1111 if (transceiver->direction() == RtpTransceiverDirection::kRecvOnly) {
1112 transceiver->SetDirection(RtpTransceiverDirection::kSendRecv);
1113 } else if (transceiver->direction() == RtpTransceiverDirection::kInactive) {
1114 transceiver->SetDirection(RtpTransceiverDirection::kSendOnly);
1115 }
1116 } else {
1117 cricket::MediaType media_type =
1118 (track->kind() == MediaStreamTrackInterface::kAudioKind
1119 ? cricket::MEDIA_TYPE_AUDIO
1120 : cricket::MEDIA_TYPE_VIDEO);
1121 transceiver = CreateTransceiver(media_type);
1122 transceiver->internal()->set_created_by_addtrack(true);
1123 transceiver->SetDirection(RtpTransceiverDirection::kSendRecv);
1124 }
1125 transceiver->sender()->SetTrack(track);
1126 transceiver->internal()->sender_internal()->set_stream_ids(stream_labels);
1127 return transceiver->sender();
1128}
1129
1130rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1131PeerConnection::FindFirstTransceiverForAddedTrack(
1132 rtc::scoped_refptr<MediaStreamTrackInterface> track) {
1133 RTC_DCHECK(track);
1134 for (auto transceiver : transceivers_) {
1135 if (!transceiver->sender()->track() &&
1136 cricket::MediaTypeToString(transceiver->internal()->media_type()) ==
1137 track->kind() &&
1138 !transceiver->internal()->has_ever_been_used_to_send()) {
1139 return transceiver;
1140 }
1141 }
1142 return nullptr;
deadbeefe1f9d832016-01-14 15:35:42 -08001143}
1144
1145bool PeerConnection::RemoveTrack(RtpSenderInterface* sender) {
1146 TRACE_EVENT0("webrtc", "PeerConnection::RemoveTrack");
Steve Antonf9381f02017-12-14 10:23:57 -08001147 return RemoveTrackInternal(sender).ok();
1148}
1149
1150RTCError PeerConnection::RemoveTrackInternal(
1151 rtc::scoped_refptr<RtpSenderInterface> sender) {
1152 if (!sender) {
1153 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "Sender is null.");
1154 }
deadbeefe1f9d832016-01-14 15:35:42 -08001155 if (IsClosed()) {
Steve Antonf9381f02017-12-14 10:23:57 -08001156 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
1157 "PeerConnection is closed.");
deadbeefe1f9d832016-01-14 15:35:42 -08001158 }
Steve Antonf9381f02017-12-14 10:23:57 -08001159 if (IsUnifiedPlan()) {
1160 auto transceiver = FindTransceiverBySender(sender);
1161 if (!transceiver || !sender->track()) {
1162 return RTCError::OK();
1163 }
1164 sender->SetTrack(nullptr);
1165 if (transceiver->direction() == RtpTransceiverDirection::kSendRecv) {
1166 transceiver->internal()->SetDirection(RtpTransceiverDirection::kRecvOnly);
1167 } else if (transceiver->direction() == RtpTransceiverDirection::kSendOnly) {
1168 transceiver->internal()->SetDirection(RtpTransceiverDirection::kInactive);
1169 }
Steve Anton4171afb2017-11-20 10:20:22 -08001170 } else {
Steve Antonf9381f02017-12-14 10:23:57 -08001171 bool removed;
1172 if (sender->media_type() == cricket::MEDIA_TYPE_AUDIO) {
1173 removed = GetAudioTransceiver()->internal()->RemoveSender(sender);
1174 } else {
1175 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, sender->media_type());
1176 removed = GetVideoTransceiver()->internal()->RemoveSender(sender);
1177 }
1178 if (!removed) {
1179 LOG_AND_RETURN_ERROR(
1180 RTCErrorType::INVALID_PARAMETER,
1181 "Couldn't find sender " + sender->id() + " to remove.");
1182 }
Steve Anton4171afb2017-11-20 10:20:22 -08001183 }
deadbeefe1f9d832016-01-14 15:35:42 -08001184 observer_->OnRenegotiationNeeded();
Steve Antonf9381f02017-12-14 10:23:57 -08001185 return RTCError::OK();
1186}
1187
1188rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1189PeerConnection::FindTransceiverBySender(
1190 rtc::scoped_refptr<RtpSenderInterface> sender) {
1191 for (auto transceiver : transceivers_) {
1192 if (transceiver->sender() == sender) {
1193 return transceiver;
1194 }
1195 }
1196 return nullptr;
deadbeefe1f9d832016-01-14 15:35:42 -08001197}
1198
Steve Anton9158ef62017-11-27 13:01:52 -08001199RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1200PeerConnection::AddTransceiver(
1201 rtc::scoped_refptr<MediaStreamTrackInterface> track) {
1202 return AddTransceiver(track, RtpTransceiverInit());
1203}
1204
1205RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1206PeerConnection::AddTransceiver(
1207 rtc::scoped_refptr<MediaStreamTrackInterface> track,
1208 const RtpTransceiverInit& init) {
1209 if (!IsUnifiedPlan()) {
1210 LOG_AND_RETURN_ERROR(
1211 RTCErrorType::INTERNAL_ERROR,
1212 "AddTransceiver only supported when Unified Plan is enabled.");
1213 }
1214 if (!track) {
1215 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "track is null");
1216 }
1217 cricket::MediaType media_type;
1218 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
1219 media_type = cricket::MEDIA_TYPE_AUDIO;
1220 } else if (track->kind() == MediaStreamTrackInterface::kVideoKind) {
1221 media_type = cricket::MEDIA_TYPE_VIDEO;
1222 } else {
1223 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1224 "Track kind is not audio or video");
1225 }
1226 return AddTransceiver(media_type, track, init);
1227}
1228
1229RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1230PeerConnection::AddTransceiver(cricket::MediaType media_type) {
1231 return AddTransceiver(media_type, RtpTransceiverInit());
1232}
1233
1234RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1235PeerConnection::AddTransceiver(cricket::MediaType media_type,
1236 const RtpTransceiverInit& init) {
1237 if (!IsUnifiedPlan()) {
1238 LOG_AND_RETURN_ERROR(
1239 RTCErrorType::INTERNAL_ERROR,
1240 "AddTransceiver only supported when Unified Plan is enabled.");
1241 }
1242 if (!(media_type == cricket::MEDIA_TYPE_AUDIO ||
1243 media_type == cricket::MEDIA_TYPE_VIDEO)) {
1244 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1245 "media type is not audio or video");
1246 }
1247 return AddTransceiver(media_type, nullptr, init);
1248}
1249
1250RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1251PeerConnection::AddTransceiver(
1252 cricket::MediaType media_type,
1253 rtc::scoped_refptr<MediaStreamTrackInterface> track,
1254 const RtpTransceiverInit& init) {
1255 RTC_DCHECK((media_type == cricket::MEDIA_TYPE_AUDIO ||
1256 media_type == cricket::MEDIA_TYPE_VIDEO));
1257 if (track) {
1258 RTC_DCHECK_EQ(media_type,
1259 (track->kind() == MediaStreamTrackInterface::kAudioKind
1260 ? cricket::MEDIA_TYPE_AUDIO
1261 : cricket::MEDIA_TYPE_VIDEO));
1262 }
1263
1264 // TODO(bugs.webrtc.org/7600): Verify init.
1265
Steve Antonf9381f02017-12-14 10:23:57 -08001266 auto transceiver = CreateTransceiver(media_type);
1267 transceiver->SetDirection(init.direction);
1268 if (track) {
1269 transceiver->sender()->SetTrack(track);
1270 }
1271
1272 observer_->OnRenegotiationNeeded();
1273
1274 return rtc::scoped_refptr<RtpTransceiverInterface>(transceiver);
1275}
1276
1277rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1278PeerConnection::CreateTransceiver(cricket::MediaType media_type) {
Steve Anton9158ef62017-11-27 13:01:52 -08001279 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> sender;
1280 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1281 receiver;
1282 std::string receiver_id = rtc::CreateRandomUuid();
Steve Antonf9381f02017-12-14 10:23:57 -08001283 // TODO(bugs.webrtc.org/7600): Initializing the sender/receiver with a null
1284 // channel prevents users from calling SetParameters on them, which is needed
1285 // to be in compliance with the spec.
Steve Anton9158ef62017-11-27 13:01:52 -08001286 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
1287 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
1288 signaling_thread(), new AudioRtpSender(nullptr, stats_.get()));
1289 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
1290 signaling_thread(), new AudioRtpReceiver(receiver_id, {}, 0, nullptr));
1291 } else {
1292 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, media_type);
1293 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
1294 signaling_thread(), new VideoRtpSender(nullptr));
1295 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
1296 signaling_thread(),
1297 new VideoRtpReceiver(receiver_id, {}, worker_thread(), 0, nullptr));
1298 }
Steve Anton9158ef62017-11-27 13:01:52 -08001299 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1300 transceiver = RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1301 signaling_thread(), new RtpTransceiver(sender, receiver));
Steve Anton9158ef62017-11-27 13:01:52 -08001302 transceivers_.push_back(transceiver);
Steve Antonf9381f02017-12-14 10:23:57 -08001303 return transceiver;
Steve Anton9158ef62017-11-27 13:01:52 -08001304}
1305
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001306rtc::scoped_refptr<DtmfSenderInterface> PeerConnection::CreateDtmfSender(
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001307 AudioTrackInterface* track) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001308 TRACE_EVENT0("webrtc", "PeerConnection::CreateDtmfSender");
zhihuang29ff8442016-07-27 11:07:25 -07001309 if (IsClosed()) {
1310 return nullptr;
1311 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001312 if (!track) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001313 RTC_LOG(LS_ERROR) << "CreateDtmfSender - track is NULL.";
deadbeef20cb0c12017-02-01 20:27:00 -08001314 return nullptr;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001315 }
Steve Anton4171afb2017-11-20 10:20:22 -08001316 auto track_sender = FindSenderForTrack(track);
1317 if (!track_sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001318 RTC_LOG(LS_ERROR) << "CreateDtmfSender called with a non-added track.";
deadbeef20cb0c12017-02-01 20:27:00 -08001319 return nullptr;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001320 }
1321
Steve Anton4171afb2017-11-20 10:20:22 -08001322 return track_sender->GetDtmfSender();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001323}
1324
deadbeeffac06552015-11-25 11:26:01 -08001325rtc::scoped_refptr<RtpSenderInterface> PeerConnection::CreateSender(
deadbeefbd7d8f72015-12-18 16:58:44 -08001326 const std::string& kind,
1327 const std::string& stream_id) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001328 TRACE_EVENT0("webrtc", "PeerConnection::CreateSender");
zhihuang29ff8442016-07-27 11:07:25 -07001329 if (IsClosed()) {
1330 return nullptr;
1331 }
Steve Anton4171afb2017-11-20 10:20:22 -08001332
1333 // TODO(steveanton): Move construction of the RtpSenders to RtpTransceiver.
deadbeefa601f5c2016-06-06 14:27:39 -07001334 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender;
deadbeeffac06552015-11-25 11:26:01 -08001335 if (kind == MediaStreamTrackInterface::kAudioKind) {
deadbeefa601f5c2016-06-06 14:27:39 -07001336 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton75737c02017-11-06 10:37:17 -08001337 signaling_thread(), new AudioRtpSender(voice_channel(), stats_.get()));
Steve Anton4171afb2017-11-20 10:20:22 -08001338 GetAudioTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 11:26:01 -08001339 } else if (kind == MediaStreamTrackInterface::kVideoKind) {
deadbeefa601f5c2016-06-06 14:27:39 -07001340 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton75737c02017-11-06 10:37:17 -08001341 signaling_thread(), new VideoRtpSender(video_channel()));
Steve Anton4171afb2017-11-20 10:20:22 -08001342 GetVideoTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 11:26:01 -08001343 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001344 RTC_LOG(LS_ERROR) << "CreateSender called with invalid kind: " << kind;
Steve Anton4171afb2017-11-20 10:20:22 -08001345 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08001346 }
Steve Anton4171afb2017-11-20 10:20:22 -08001347
deadbeefbd7d8f72015-12-18 16:58:44 -08001348 if (!stream_id.empty()) {
deadbeefa601f5c2016-06-06 14:27:39 -07001349 new_sender->internal()->set_stream_id(stream_id);
deadbeefbd7d8f72015-12-18 16:58:44 -08001350 }
Steve Anton4171afb2017-11-20 10:20:22 -08001351
deadbeefe1f9d832016-01-14 15:35:42 -08001352 return new_sender;
deadbeeffac06552015-11-25 11:26:01 -08001353}
1354
deadbeef70ab1a12015-09-28 16:53:55 -07001355std::vector<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::GetSenders()
1356 const {
deadbeefa601f5c2016-06-06 14:27:39 -07001357 std::vector<rtc::scoped_refptr<RtpSenderInterface>> ret;
Steve Anton4171afb2017-11-20 10:20:22 -08001358 for (auto sender : GetSendersInternal()) {
1359 ret.push_back(sender);
deadbeefa601f5c2016-06-06 14:27:39 -07001360 }
1361 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -07001362}
1363
Steve Anton4171afb2017-11-20 10:20:22 -08001364std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1365PeerConnection::GetSendersInternal() const {
1366 std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1367 all_senders;
1368 for (auto transceiver : transceivers_) {
1369 auto senders = transceiver->internal()->senders();
1370 all_senders.insert(all_senders.end(), senders.begin(), senders.end());
1371 }
1372 return all_senders;
1373}
1374
deadbeef70ab1a12015-09-28 16:53:55 -07001375std::vector<rtc::scoped_refptr<RtpReceiverInterface>>
1376PeerConnection::GetReceivers() const {
deadbeefa601f5c2016-06-06 14:27:39 -07001377 std::vector<rtc::scoped_refptr<RtpReceiverInterface>> ret;
Steve Anton4171afb2017-11-20 10:20:22 -08001378 for (const auto& receiver : GetReceiversInternal()) {
1379 ret.push_back(receiver);
deadbeefa601f5c2016-06-06 14:27:39 -07001380 }
1381 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -07001382}
1383
Steve Anton4171afb2017-11-20 10:20:22 -08001384std::vector<
1385 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1386PeerConnection::GetReceiversInternal() const {
1387 std::vector<
1388 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1389 all_receivers;
1390 for (auto transceiver : transceivers_) {
1391 auto receivers = transceiver->internal()->receivers();
1392 all_receivers.insert(all_receivers.end(), receivers.begin(),
1393 receivers.end());
1394 }
1395 return all_receivers;
1396}
1397
Steve Anton9158ef62017-11-27 13:01:52 -08001398std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
1399PeerConnection::GetTransceivers() const {
1400 RTC_DCHECK(IsUnifiedPlan());
1401 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> all_transceivers;
1402 for (auto transceiver : transceivers_) {
1403 all_transceivers.push_back(transceiver);
1404 }
1405 return all_transceivers;
1406}
1407
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001408bool PeerConnection::GetStats(StatsObserver* observer,
wu@webrtc.orgb9a088b2014-02-13 23:18:49 +00001409 MediaStreamTrackInterface* track,
1410 StatsOutputLevel level) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001411 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
deadbeef0a6c4ca2015-10-06 11:38:28 -07001412 RTC_DCHECK(signaling_thread()->IsCurrent());
nisse7ce109a2017-01-31 00:57:56 -08001413 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001414 RTC_LOG(LS_ERROR) << "GetStats - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001415 return false;
1416 }
1417
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001418 stats_->UpdateStats(level);
zhihuange9e94c32016-11-04 11:38:15 -07001419 // The StatsCollector is used to tell if a track is valid because it may
1420 // remember tracks that the PeerConnection previously removed.
1421 if (track && !stats_->IsValidTrack(track->id())) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001422 RTC_LOG(LS_WARNING) << "GetStats is called with an invalid track: "
1423 << track->id();
zhihuange9e94c32016-11-04 11:38:15 -07001424 return false;
1425 }
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001426 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_GETSTATS,
tommi@webrtc.org5b06b062014-08-15 08:38:30 +00001427 new GetStatsMsg(observer, track));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001428 return true;
1429}
1430
hbos74e1a4f2016-09-15 23:33:01 -07001431void PeerConnection::GetStats(RTCStatsCollectorCallback* callback) {
1432 RTC_DCHECK(stats_collector_);
1433 stats_collector_->GetStatsReport(callback);
1434}
1435
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001436PeerConnectionInterface::SignalingState PeerConnection::signaling_state() {
1437 return signaling_state_;
1438}
1439
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001440PeerConnectionInterface::IceConnectionState
1441PeerConnection::ice_connection_state() {
1442 return ice_connection_state_;
1443}
1444
1445PeerConnectionInterface::IceGatheringState
1446PeerConnection::ice_gathering_state() {
1447 return ice_gathering_state_;
1448}
1449
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001450rtc::scoped_refptr<DataChannelInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001451PeerConnection::CreateDataChannel(
1452 const std::string& label,
1453 const DataChannelInit* config) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001454 TRACE_EVENT0("webrtc", "PeerConnection::CreateDataChannel");
zhihuang9763d562016-08-05 11:14:50 -07001455
deadbeefab9b2d12015-10-14 11:33:11 -07001456 bool first_datachannel = !HasDataChannels();
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001457
kwibergd1fe2812016-04-27 06:47:29 -07001458 std::unique_ptr<InternalDataChannelInit> internal_config;
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00001459 if (config) {
1460 internal_config.reset(new InternalDataChannelInit(*config));
1461 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001462 rtc::scoped_refptr<DataChannelInterface> channel(
deadbeefab9b2d12015-10-14 11:33:11 -07001463 InternalCreateDataChannel(label, internal_config.get()));
1464 if (!channel.get()) {
1465 return nullptr;
1466 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001467
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001468 // Trigger the onRenegotiationNeeded event for every new RTP DataChannel, or
1469 // the first SCTP DataChannel.
Steve Anton75737c02017-11-06 10:37:17 -08001470 if (data_channel_type() == cricket::DCT_RTP || first_datachannel) {
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001471 observer_->OnRenegotiationNeeded();
1472 }
wu@webrtc.org91053e72013-08-10 07:18:04 +00001473
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001474 return DataChannelProxy::Create(signaling_thread(), channel.get());
1475}
1476
1477void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
1478 const MediaConstraintsInterface* constraints) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001479 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
Steve Anton8d3444d2017-10-20 15:30:51 -07001480
zhihuang1c378ed2017-08-17 14:10:50 -07001481 PeerConnectionInterface::RTCOfferAnswerOptions offer_answer_options;
1482 // Always create an offer even if |ConvertConstraintsToOfferAnswerOptions|
1483 // returns false for now. Because |ConvertConstraintsToOfferAnswerOptions|
1484 // compares the mandatory fields parsed with the mandatory fields added in the
1485 // |constraints| and some downstream applications might create offers with
1486 // mandatory fields which would not be parsed in the helper method. For
1487 // example, in Chromium/remoting, |kEnableDtlsSrtp| is added to the
1488 // |constraints| as a mandatory field but it is not parsed.
1489 ConvertConstraintsToOfferAnswerOptions(constraints, &offer_answer_options);
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001490
zhihuang1c378ed2017-08-17 14:10:50 -07001491 CreateOffer(observer, offer_answer_options);
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001492}
1493
1494void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
1495 const RTCOfferAnswerOptions& options) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001496 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
Steve Anton8d3444d2017-10-20 15:30:51 -07001497
nisse7ce109a2017-01-31 00:57:56 -08001498 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001499 RTC_LOG(LS_ERROR) << "CreateOffer - observer is NULL.";
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001500 return;
1501 }
deadbeefab9b2d12015-10-14 11:33:11 -07001502
Steve Anton8d3444d2017-10-20 15:30:51 -07001503 if (IsClosed()) {
1504 std::string error = "CreateOffer called when PeerConnection is closed.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001505 RTC_LOG(LS_ERROR) << error;
Steve Anton8d3444d2017-10-20 15:30:51 -07001506 PostCreateSessionDescriptionFailure(observer, error);
1507 return;
1508 }
1509
zhihuang1c378ed2017-08-17 14:10:50 -07001510 if (!ValidateOfferAnswerOptions(options)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001511 std::string error = "CreateOffer called with invalid options.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001512 RTC_LOG(LS_ERROR) << error;
deadbeefab9b2d12015-10-14 11:33:11 -07001513 PostCreateSessionDescriptionFailure(observer, error);
1514 return;
1515 }
1516
zhihuang1c378ed2017-08-17 14:10:50 -07001517 cricket::MediaSessionOptions session_options;
1518 GetOptionsForOffer(options, &session_options);
Steve Antond25da372017-11-06 14:50:29 -08001519 webrtc_session_desc_factory_->CreateOffer(observer, options, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001520}
1521
1522void PeerConnection::CreateAnswer(
1523 CreateSessionDescriptionObserver* observer,
1524 const MediaConstraintsInterface* constraints) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001525 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
Steve Anton8d3444d2017-10-20 15:30:51 -07001526
nisse7ce109a2017-01-31 00:57:56 -08001527 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001528 RTC_LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001529 return;
1530 }
deadbeefab9b2d12015-10-14 11:33:11 -07001531
zhihuang1c378ed2017-08-17 14:10:50 -07001532 PeerConnectionInterface::RTCOfferAnswerOptions offer_answer_options;
1533 if (!ConvertConstraintsToOfferAnswerOptions(constraints,
1534 &offer_answer_options)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001535 std::string error = "CreateAnswer called with invalid constraints.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001536 RTC_LOG(LS_ERROR) << error;
deadbeefab9b2d12015-10-14 11:33:11 -07001537 PostCreateSessionDescriptionFailure(observer, error);
1538 return;
1539 }
1540
Steve Anton8d3444d2017-10-20 15:30:51 -07001541 CreateAnswer(observer, offer_answer_options);
htaa2a49d92016-03-04 02:51:39 -08001542}
1543
1544void PeerConnection::CreateAnswer(CreateSessionDescriptionObserver* observer,
1545 const RTCOfferAnswerOptions& options) {
1546 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
nisse7ce109a2017-01-31 00:57:56 -08001547 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001548 RTC_LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
htaa2a49d92016-03-04 02:51:39 -08001549 return;
1550 }
1551
Steve Anton8d3444d2017-10-20 15:30:51 -07001552 if (IsClosed()) {
1553 std::string error = "CreateAnswer called when PeerConnection is closed.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001554 RTC_LOG(LS_ERROR) << error;
Steve Anton8d3444d2017-10-20 15:30:51 -07001555 PostCreateSessionDescriptionFailure(observer, error);
1556 return;
1557 }
1558
Steve Anton75737c02017-11-06 10:37:17 -08001559 if (remote_description() &&
Steve Antona3a92c22017-12-07 10:27:41 -08001560 remote_description()->GetType() != SdpType::kOffer) {
Steve Anton8d3444d2017-10-20 15:30:51 -07001561 std::string error = "CreateAnswer called without remote offer.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001562 RTC_LOG(LS_ERROR) << error;
Steve Anton8d3444d2017-10-20 15:30:51 -07001563 PostCreateSessionDescriptionFailure(observer, error);
1564 return;
1565 }
1566
htaa2a49d92016-03-04 02:51:39 -08001567 cricket::MediaSessionOptions session_options;
zhihuang1c378ed2017-08-17 14:10:50 -07001568 GetOptionsForAnswer(options, &session_options);
htaa2a49d92016-03-04 02:51:39 -08001569
Steve Antond25da372017-11-06 14:50:29 -08001570 webrtc_session_desc_factory_->CreateAnswer(observer, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001571}
1572
1573void PeerConnection::SetLocalDescription(
1574 SetSessionDescriptionObserver* observer,
1575 SessionDescriptionInterface* desc) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001576 TRACE_EVENT0("webrtc", "PeerConnection::SetLocalDescription");
Steve Anton8a006912017-12-04 15:25:56 -08001577
nisse7ce109a2017-01-31 00:57:56 -08001578 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001579 RTC_LOG(LS_ERROR) << "SetLocalDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001580 return;
1581 }
Steve Anton8a006912017-12-04 15:25:56 -08001582
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001583 if (!desc) {
1584 PostSetSessionDescriptionFailure(observer, "SessionDescription is NULL.");
1585 return;
1586 }
Steve Anton8d3444d2017-10-20 15:30:51 -07001587
Steve Antona3a92c22017-12-07 10:27:41 -08001588 SdpType type = desc->GetType();
Steve Anton8d3444d2017-10-20 15:30:51 -07001589
Steve Anton8a006912017-12-04 15:25:56 -08001590 RTCError error = ApplyLocalDescription(rtc::WrapUnique(desc));
1591 // |desc| may be destroyed at this point.
1592
1593 if (!error.ok()) {
Steve Antona3a92c22017-12-07 10:27:41 -08001594 std::ostringstream oss;
1595 oss << "Failed to set local " << SdpTypeToString(type)
1596 << " sdp: " << error.message();
1597 std::string error_message = oss.str();
Steve Anton8a006912017-12-04 15:25:56 -08001598 RTC_LOG(LS_ERROR) << error_message << " (" << error.type() << ")";
1599 PostSetSessionDescriptionFailure(observer, std::move(error_message));
Steve Anton8d3444d2017-10-20 15:30:51 -07001600 return;
1601 }
Steve Anton8a006912017-12-04 15:25:56 -08001602 RTC_DCHECK(local_description());
1603
1604 PostSetSessionDescriptionSuccess(observer);
1605
1606 // According to JSEP, after setLocalDescription, changing the candidate pool
1607 // size is not allowed, and changing the set of ICE servers will not result
1608 // in new candidates being gathered.
1609 port_allocator_->FreezeCandidatePool();
1610
1611 // MaybeStartGathering needs to be called after posting
1612 // MSG_SET_SESSIONDESCRIPTION_SUCCESS, so that we don't signal any candidates
1613 // before signaling that SetLocalDescription completed.
1614 transport_controller_->MaybeStartGathering();
1615
Steve Antona3a92c22017-12-07 10:27:41 -08001616 if (local_description()->GetType() == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08001617 // TODO(deadbeef): We already had to hop to the network thread for
1618 // MaybeStartGathering...
1619 network_thread()->Invoke<void>(
1620 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
1621 port_allocator_.get()));
1622 }
1623}
1624
1625RTCError PeerConnection::ApplyLocalDescription(
1626 std::unique_ptr<SessionDescriptionInterface> desc) {
1627 RTC_DCHECK_RUN_ON(signaling_thread());
1628 RTC_DCHECK(desc);
1629
1630 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_LOCAL);
1631 if (!error.ok()) {
1632 return error;
1633 }
Steve Anton8d3444d2017-10-20 15:30:51 -07001634
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001635 // Update stats here so that we have the most recent stats for tracks and
1636 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001637 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 15:25:56 -08001638
1639 // Update the initial_offerer flag if this session is the initial_offerer.
Steve Anton3828c062017-12-06 10:34:51 -08001640 SdpType type = desc->GetType();
Steve Anton8a006912017-12-04 15:25:56 -08001641 if (!initial_offerer_.has_value()) {
Steve Anton3828c062017-12-06 10:34:51 -08001642 initial_offerer_.emplace(type == SdpType::kOffer);
Steve Anton8a006912017-12-04 15:25:56 -08001643 if (*initial_offerer_) {
1644 transport_controller_->SetIceRole(cricket::ICEROLE_CONTROLLING);
1645 } else {
1646 transport_controller_->SetIceRole(cricket::ICEROLE_CONTROLLED);
1647 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001648 }
Steve Anton8a006912017-12-04 15:25:56 -08001649
Steve Anton3828c062017-12-06 10:34:51 -08001650 if (type == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08001651 current_local_description_ = std::move(desc);
1652 pending_local_description_ = nullptr;
1653 current_remote_description_ = std::move(pending_remote_description_);
1654 } else {
1655 pending_local_description_ = std::move(desc);
1656 }
1657 // The session description to apply now must be accessed by
1658 // |local_description()|.
Henrik Boströmfdb92012017-11-09 19:55:44 +01001659 RTC_DCHECK(local_description());
deadbeefab9b2d12015-10-14 11:33:11 -07001660
Steve Anton8a006912017-12-04 15:25:56 -08001661 // Transport and Media channels will be created only when offer is set.
Steve Anton3828c062017-12-06 10:34:51 -08001662 if (type == SdpType::kOffer) {
Steve Anton8a006912017-12-04 15:25:56 -08001663 // TODO(mallinath) - Handle CreateChannel failure, as new local description
1664 // is applied. Restore back to old description.
1665 RTCError error = CreateChannels(local_description()->description());
1666 if (!error.ok()) {
1667 return error;
1668 }
1669 }
1670
1671 // Remove unused channels if MediaContentDescription is rejected.
1672 RemoveUnusedChannels(local_description()->description());
1673
Steve Anton3828c062017-12-06 10:34:51 -08001674 error = UpdateSessionState(type, cricket::CS_LOCAL);
Steve Anton8a006912017-12-04 15:25:56 -08001675 if (!error.ok()) {
1676 return error;
1677 }
1678 if (remote_description()) {
1679 // Now that we have a local description, we can push down remote candidates.
1680 UseCandidatesInSessionDescription(remote_description());
1681 }
1682
1683 pending_ice_restarts_.clear();
1684 if (session_error() != SessionError::kNone) {
1685 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
1686 }
1687
deadbeefab9b2d12015-10-14 11:33:11 -07001688 // If setting the description decided our SSL role, allocate any necessary
1689 // SCTP sids.
1690 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08001691 if (data_channel_type() == cricket::DCT_SCTP && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001692 AllocateSctpSids(role);
1693 }
1694
1695 // Update state and SSRC of local MediaStreams and DataChannels based on the
1696 // local session description.
1697 const cricket::ContentInfo* audio_content =
Henrik Boströmfdb92012017-11-09 19:55:44 +01001698 GetFirstAudioContent(local_description()->description());
deadbeefab9b2d12015-10-14 11:33:11 -07001699 if (audio_content) {
deadbeeffaac4972015-11-12 15:33:07 -08001700 if (audio_content->rejected) {
Steve Anton4171afb2017-11-20 10:20:22 -08001701 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
deadbeeffaac4972015-11-12 15:33:07 -08001702 } else {
1703 const cricket::AudioContentDescription* audio_desc =
1704 static_cast<const cricket::AudioContentDescription*>(
1705 audio_content->description);
Steve Anton4171afb2017-11-20 10:20:22 -08001706 UpdateLocalSenders(audio_desc->streams(), audio_desc->type());
deadbeeffaac4972015-11-12 15:33:07 -08001707 }
deadbeefab9b2d12015-10-14 11:33:11 -07001708 }
1709
1710 const cricket::ContentInfo* video_content =
Henrik Boströmfdb92012017-11-09 19:55:44 +01001711 GetFirstVideoContent(local_description()->description());
deadbeefab9b2d12015-10-14 11:33:11 -07001712 if (video_content) {
deadbeeffaac4972015-11-12 15:33:07 -08001713 if (video_content->rejected) {
Steve Anton4171afb2017-11-20 10:20:22 -08001714 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
deadbeeffaac4972015-11-12 15:33:07 -08001715 } else {
1716 const cricket::VideoContentDescription* video_desc =
1717 static_cast<const cricket::VideoContentDescription*>(
1718 video_content->description);
Steve Anton4171afb2017-11-20 10:20:22 -08001719 UpdateLocalSenders(video_desc->streams(), video_desc->type());
deadbeeffaac4972015-11-12 15:33:07 -08001720 }
deadbeefab9b2d12015-10-14 11:33:11 -07001721 }
1722
1723 const cricket::ContentInfo* data_content =
Henrik Boströmfdb92012017-11-09 19:55:44 +01001724 GetFirstDataContent(local_description()->description());
deadbeefab9b2d12015-10-14 11:33:11 -07001725 if (data_content) {
1726 const cricket::DataContentDescription* data_desc =
1727 static_cast<const cricket::DataContentDescription*>(
1728 data_content->description);
1729 if (rtc::starts_with(data_desc->protocol().data(),
1730 cricket::kMediaProtocolRtpPrefix)) {
1731 UpdateLocalRtpDataChannels(data_desc->streams());
1732 }
1733 }
1734
Steve Anton8a006912017-12-04 15:25:56 -08001735 return RTCError::OK();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001736}
1737
1738void PeerConnection::SetRemoteDescription(
Henrik Boströma4ecf552017-11-23 14:17:07 +00001739 SetSessionDescriptionObserver* observer,
1740 SessionDescriptionInterface* desc) {
Henrik Boström31638672017-11-23 17:48:32 +01001741 SetRemoteDescription(
1742 std::unique_ptr<SessionDescriptionInterface>(desc),
1743 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface>(
1744 new SetRemoteDescriptionObserverAdapter(this, observer)));
1745}
1746
1747void PeerConnection::SetRemoteDescription(
1748 std::unique_ptr<SessionDescriptionInterface> desc,
1749 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface> observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001750 TRACE_EVENT0("webrtc", "PeerConnection::SetRemoteDescription");
Steve Anton8a006912017-12-04 15:25:56 -08001751
nisse7ce109a2017-01-31 00:57:56 -08001752 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001753 RTC_LOG(LS_ERROR) << "SetRemoteDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001754 return;
1755 }
Steve Anton8a006912017-12-04 15:25:56 -08001756
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001757 if (!desc) {
Henrik Boström31638672017-11-23 17:48:32 +01001758 observer->OnSetRemoteDescriptionComplete(RTCError(
Steve Anton8a006912017-12-04 15:25:56 -08001759 RTCErrorType::INVALID_PARAMETER, "SessionDescription is NULL."));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001760 return;
1761 }
Steve Anton8d3444d2017-10-20 15:30:51 -07001762
Steve Antona3a92c22017-12-07 10:27:41 -08001763 const SdpType type = desc->GetType();
Steve Anton8a006912017-12-04 15:25:56 -08001764
1765 RTCError error = ApplyRemoteDescription(std::move(desc));
1766 // |desc| may be destroyed at this point.
1767
1768 if (!error.ok()) {
Steve Antona3a92c22017-12-07 10:27:41 -08001769 std::ostringstream oss;
1770 oss << "Failed to set remote " << SdpTypeToString(type)
1771 << " sdp: " << error.message();
1772 std::string error_message = oss.str();
Steve Anton8a006912017-12-04 15:25:56 -08001773 RTC_LOG(LS_ERROR) << error_message << " (" << error.type() << ")";
Henrik Boström31638672017-11-23 17:48:32 +01001774 observer->OnSetRemoteDescriptionComplete(
Steve Anton8a006912017-12-04 15:25:56 -08001775 RTCError(error.type(), std::move(error_message)));
Steve Anton8d3444d2017-10-20 15:30:51 -07001776 return;
1777 }
1778
Steve Antona3a92c22017-12-07 10:27:41 -08001779 if (remote_description()->GetType() == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08001780 // TODO(deadbeef): We already had to hop to the network thread for
1781 // MaybeStartGathering...
1782 network_thread()->Invoke<void>(
1783 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
1784 port_allocator_.get()));
1785 }
1786
1787 observer->OnSetRemoteDescriptionComplete(RTCError::OK());
1788}
1789
1790RTCError PeerConnection::ApplyRemoteDescription(
1791 std::unique_ptr<SessionDescriptionInterface> desc) {
1792 RTC_DCHECK_RUN_ON(signaling_thread());
1793 RTC_DCHECK(desc);
1794
1795 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_REMOTE);
1796 if (!error.ok()) {
1797 return error;
1798 }
1799
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001800 // Update stats here so that we have the most recent stats for tracks and
1801 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001802 stats_->UpdateStats(kStatsOutputLevelStandard);
Henrik Boström31638672017-11-23 17:48:32 +01001803 // Takes the ownership of |desc|. On success, remote_description() is updated
1804 // to reflect the description that was passed in.
Steve Anton8a006912017-12-04 15:25:56 -08001805
1806 const SessionDescriptionInterface* old_remote_description =
1807 remote_description();
1808 // Grab ownership of the description being replaced for the remainder of this
1809 // method, since it's used below as |old_remote_description|.
1810 std::unique_ptr<SessionDescriptionInterface> replaced_remote_description;
Steve Anton3828c062017-12-06 10:34:51 -08001811 SdpType type = desc->GetType();
1812 if (type == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08001813 replaced_remote_description = pending_remote_description_
1814 ? std::move(pending_remote_description_)
1815 : std::move(current_remote_description_);
1816 current_remote_description_ = std::move(desc);
1817 pending_remote_description_ = nullptr;
1818 current_local_description_ = std::move(pending_local_description_);
1819 } else {
1820 replaced_remote_description = std::move(pending_remote_description_);
1821 pending_remote_description_ = std::move(desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001822 }
Steve Anton8a006912017-12-04 15:25:56 -08001823 // The session description to apply now must be accessed by
1824 // |remote_description()|.
Henrik Boströmfdb92012017-11-09 19:55:44 +01001825 RTC_DCHECK(remote_description());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001826
Steve Anton8a006912017-12-04 15:25:56 -08001827 // Transport and Media channels will be created only when offer is set.
Steve Anton3828c062017-12-06 10:34:51 -08001828 if (type == SdpType::kOffer) {
Steve Anton8a006912017-12-04 15:25:56 -08001829 // TODO(mallinath) - Handle CreateChannel failure, as new local description
1830 // is applied. Restore back to old description.
1831 RTCError error = CreateChannels(remote_description()->description());
1832 if (!error.ok()) {
1833 return error;
1834 }
1835 }
1836
1837 // Remove unused channels if MediaContentDescription is rejected.
1838 RemoveUnusedChannels(remote_description()->description());
1839
1840 // NOTE: Candidates allocation will be initiated only when SetLocalDescription
1841 // is called.
Steve Anton3828c062017-12-06 10:34:51 -08001842 error = UpdateSessionState(type, cricket::CS_REMOTE);
Steve Anton8a006912017-12-04 15:25:56 -08001843 if (!error.ok()) {
1844 return error;
1845 }
1846
1847 if (local_description() &&
1848 !UseCandidatesInSessionDescription(remote_description())) {
1849 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidCandidates);
1850 }
1851
1852 if (old_remote_description) {
1853 for (const cricket::ContentInfo& content :
1854 old_remote_description->description()->contents()) {
1855 // Check if this new SessionDescription contains new ICE ufrag and
1856 // password that indicates the remote peer requests an ICE restart.
1857 // TODO(deadbeef): When we start storing both the current and pending
1858 // remote description, this should reset pending_ice_restarts and compare
1859 // against the current description.
1860 if (CheckForRemoteIceRestart(old_remote_description, remote_description(),
1861 content.name)) {
Steve Anton3828c062017-12-06 10:34:51 -08001862 if (type == SdpType::kOffer) {
Steve Anton8a006912017-12-04 15:25:56 -08001863 pending_ice_restarts_.insert(content.name);
1864 }
1865 } else {
1866 // We retain all received candidates only if ICE is not restarted.
1867 // When ICE is restarted, all previous candidates belong to an old
1868 // generation and should not be kept.
1869 // TODO(deadbeef): This goes against the W3C spec which says the remote
1870 // description should only contain candidates from the last set remote
1871 // description plus any candidates added since then. We should remove
1872 // this once we're sure it won't break anything.
1873 WebRtcSessionDescriptionFactory::CopyCandidatesFromSessionDescription(
1874 old_remote_description, content.name, mutable_remote_description());
1875 }
1876 }
1877 }
1878
1879 if (session_error() != SessionError::kNone) {
1880 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
1881 }
1882
1883 // Set the the ICE connection state to connecting since the connection may
1884 // become writable with peer reflexive candidates before any remote candidate
1885 // is signaled.
1886 // TODO(pthatcher): This is a short-term solution for crbug/446908. A real fix
1887 // is to have a new signal the indicates a change in checking state from the
1888 // transport and expose a new checking() member from transport that can be
1889 // read to determine the current checking state. The existing SignalConnecting
1890 // actually means "gathering candidates", so cannot be be used here.
Steve Antona3a92c22017-12-07 10:27:41 -08001891 if (remote_description()->GetType() != SdpType::kOffer &&
Steve Anton8a006912017-12-04 15:25:56 -08001892 ice_connection_state() == PeerConnectionInterface::kIceConnectionNew) {
1893 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
1894 }
1895
deadbeefab9b2d12015-10-14 11:33:11 -07001896 // If setting the description decided our SSL role, allocate any necessary
1897 // SCTP sids.
1898 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08001899 if (data_channel_type() == cricket::DCT_SCTP && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001900 AllocateSctpSids(role);
1901 }
1902
Henrik Boströmfdb92012017-11-09 19:55:44 +01001903 const cricket::ContentInfo* audio_content =
1904 GetFirstAudioContent(remote_description()->description());
1905 const cricket::ContentInfo* video_content =
1906 GetFirstVideoContent(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08001907 const cricket::AudioContentDescription* audio_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01001908 GetFirstAudioContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08001909 const cricket::VideoContentDescription* video_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01001910 GetFirstVideoContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08001911 const cricket::DataContentDescription* data_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01001912 GetFirstDataContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08001913
1914 // Check if the descriptions include streams, just in case the peer supports
1915 // MSID, but doesn't indicate so with "a=msid-semantic".
Henrik Boströmfdb92012017-11-09 19:55:44 +01001916 if (remote_description()->description()->msid_supported() ||
deadbeefbda7e0b2015-12-08 17:13:40 -08001917 (audio_desc && !audio_desc->streams().empty()) ||
1918 (video_desc && !video_desc->streams().empty())) {
1919 remote_peer_supports_msid_ = true;
1920 }
deadbeefab9b2d12015-10-14 11:33:11 -07001921
1922 // We wait to signal new streams until we finish processing the description,
1923 // since only at that point will new streams have all their tracks.
1924 rtc::scoped_refptr<StreamCollection> new_streams(StreamCollection::Create());
1925
Steve Anton8d3444d2017-10-20 15:30:51 -07001926 // TODO(steveanton): When removing RTP senders/receivers in response to a
1927 // rejected media section, there is some cleanup logic that expects the voice/
1928 // video channel to still be set. But in this method the voice/video channel
Steve Anton75737c02017-11-06 10:37:17 -08001929 // would have been destroyed by the SetRemoteDescription caller above so the
Steve Anton4171afb2017-11-20 10:20:22 -08001930 // cleanup that relies on them fails to run. The RemoveSenders calls should be
Steve Anton75737c02017-11-06 10:37:17 -08001931 // moved to right before the DestroyChannel calls to fix this.
Steve Anton8d3444d2017-10-20 15:30:51 -07001932
deadbeefab9b2d12015-10-14 11:33:11 -07001933 // Find all audio rtp streams and create corresponding remote AudioTracks
1934 // and MediaStreams.
deadbeefab9b2d12015-10-14 11:33:11 -07001935 if (audio_content) {
deadbeeffaac4972015-11-12 15:33:07 -08001936 if (audio_content->rejected) {
Steve Anton4171afb2017-11-20 10:20:22 -08001937 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
deadbeeffaac4972015-11-12 15:33:07 -08001938 } else {
deadbeefbda7e0b2015-12-08 17:13:40 -08001939 bool default_audio_track_needed =
1940 !remote_peer_supports_msid_ &&
Steve Anton4e70a722017-11-28 14:57:10 -08001941 RtpTransceiverDirectionHasSend(audio_desc->direction());
Steve Anton4171afb2017-11-20 10:20:22 -08001942 UpdateRemoteSendersList(GetActiveStreams(audio_desc),
deadbeefbda7e0b2015-12-08 17:13:40 -08001943 default_audio_track_needed, audio_desc->type(),
deadbeeffaac4972015-11-12 15:33:07 -08001944 new_streams);
deadbeeffaac4972015-11-12 15:33:07 -08001945 }
deadbeefab9b2d12015-10-14 11:33:11 -07001946 }
1947
1948 // Find all video rtp streams and create corresponding remote VideoTracks
1949 // and MediaStreams.
deadbeefab9b2d12015-10-14 11:33:11 -07001950 if (video_content) {
deadbeeffaac4972015-11-12 15:33:07 -08001951 if (video_content->rejected) {
Steve Anton4171afb2017-11-20 10:20:22 -08001952 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
deadbeeffaac4972015-11-12 15:33:07 -08001953 } else {
deadbeefbda7e0b2015-12-08 17:13:40 -08001954 bool default_video_track_needed =
1955 !remote_peer_supports_msid_ &&
Steve Anton4e70a722017-11-28 14:57:10 -08001956 RtpTransceiverDirectionHasSend(video_desc->direction());
Steve Anton4171afb2017-11-20 10:20:22 -08001957 UpdateRemoteSendersList(GetActiveStreams(video_desc),
deadbeefbda7e0b2015-12-08 17:13:40 -08001958 default_video_track_needed, video_desc->type(),
deadbeeffaac4972015-11-12 15:33:07 -08001959 new_streams);
deadbeeffaac4972015-11-12 15:33:07 -08001960 }
deadbeefab9b2d12015-10-14 11:33:11 -07001961 }
1962
1963 // Update the DataChannels with the information from the remote peer.
deadbeefbda7e0b2015-12-08 17:13:40 -08001964 if (data_desc) {
1965 if (rtc::starts_with(data_desc->protocol().data(),
deadbeefab9b2d12015-10-14 11:33:11 -07001966 cricket::kMediaProtocolRtpPrefix)) {
deadbeefbda7e0b2015-12-08 17:13:40 -08001967 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
deadbeefab9b2d12015-10-14 11:33:11 -07001968 }
1969 }
1970
1971 // Iterate new_streams and notify the observer about new MediaStreams.
1972 for (size_t i = 0; i < new_streams->count(); ++i) {
1973 MediaStreamInterface* new_stream = new_streams->at(i);
1974 stats_->AddStream(new_stream);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07001975 observer_->OnAddStream(
1976 rtc::scoped_refptr<MediaStreamInterface>(new_stream));
deadbeefab9b2d12015-10-14 11:33:11 -07001977 }
1978
deadbeefbda7e0b2015-12-08 17:13:40 -08001979 UpdateEndedRemoteMediaStreams();
deadbeefab9b2d12015-10-14 11:33:11 -07001980
Steve Anton8a006912017-12-04 15:25:56 -08001981 return RTCError::OK();
deadbeeffc648b62015-10-13 16:42:33 -07001982}
1983
Steve Antoned10bd92017-12-05 10:52:59 -08001984const cricket::ContentInfo* PeerConnection::FindMediaSectionForTransceiver(
1985 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1986 transceiver,
1987 const SessionDescriptionInterface* sdesc) const {
1988 RTC_DCHECK(transceiver);
1989 RTC_DCHECK(sdesc);
1990 if (IsUnifiedPlan()) {
1991 if (!transceiver->internal()->mid()) {
1992 // This transceiver is not associated with a media section yet.
1993 return nullptr;
1994 }
1995 return sdesc->description()->GetContentByName(
1996 *transceiver->internal()->mid());
1997 } else {
1998 // Plan B only allows at most one audio and one video section, so use the
1999 // first media section of that type.
2000 return cricket::GetFirstMediaContent(sdesc->description()->contents(),
2001 transceiver->internal()->media_type());
2002 }
2003}
2004
deadbeef46c73892016-11-16 19:42:04 -08002005PeerConnectionInterface::RTCConfiguration PeerConnection::GetConfiguration() {
2006 return configuration_;
2007}
2008
deadbeef293e9262017-01-11 12:28:30 -08002009bool PeerConnection::SetConfiguration(const RTCConfiguration& configuration,
2010 RTCError* error) {
Peter Boström1a9d6152015-12-08 22:15:17 +01002011 TRACE_EVENT0("webrtc", "PeerConnection::SetConfiguration");
deadbeef6de92f92016-12-12 18:49:32 -08002012
Steve Anton75737c02017-11-06 10:37:17 -08002013 if (local_description() && configuration.ice_candidate_pool_size !=
2014 configuration_.ice_candidate_pool_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002015 RTC_LOG(LS_ERROR) << "Can't change candidate pool size after calling "
2016 "SetLocalDescription.";
deadbeef293e9262017-01-11 12:28:30 -08002017 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00002018 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002019
deadbeef293e9262017-01-11 12:28:30 -08002020 // The simplest (and most future-compatible) way to tell if the config was
2021 // modified in an invalid way is to copy each property we do support
2022 // modifying, then use operator==. There are far more properties we don't
2023 // support modifying than those we do, and more could be added.
2024 RTCConfiguration modified_config = configuration_;
2025 modified_config.servers = configuration.servers;
2026 modified_config.type = configuration.type;
2027 modified_config.ice_candidate_pool_size =
2028 configuration.ice_candidate_pool_size;
2029 modified_config.prune_turn_ports = configuration.prune_turn_ports;
skvladd1f5fda2017-02-03 16:54:05 -08002030 modified_config.ice_check_min_interval = configuration.ice_check_min_interval;
Jonas Orelandbdcee282017-10-10 14:01:40 +02002031 modified_config.turn_customizer = configuration.turn_customizer;
deadbeef293e9262017-01-11 12:28:30 -08002032 if (configuration != modified_config) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002033 RTC_LOG(LS_ERROR) << "Modifying the configuration in an unsupported way.";
deadbeef293e9262017-01-11 12:28:30 -08002034 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
2035 }
2036
Steve Anton038834f2017-07-14 15:59:59 -07002037 // Validate the modified configuration.
2038 RTCError validate_error = ValidateConfiguration(modified_config);
2039 if (!validate_error.ok()) {
2040 return SafeSetError(std::move(validate_error), error);
2041 }
2042
deadbeef293e9262017-01-11 12:28:30 -08002043 // Note that this isn't possible through chromium, since it's an unsigned
2044 // short in WebIDL.
2045 if (configuration.ice_candidate_pool_size < 0 ||
2046 configuration.ice_candidate_pool_size > UINT16_MAX) {
2047 return SafeSetError(RTCErrorType::INVALID_RANGE, error);
2048 }
2049
2050 // Parse ICE servers before hopping to network thread.
2051 cricket::ServerAddresses stun_servers;
2052 std::vector<cricket::RelayServerConfig> turn_servers;
2053 RTCErrorType parse_error =
2054 ParseIceServers(configuration.servers, &stun_servers, &turn_servers);
2055 if (parse_error != RTCErrorType::NONE) {
2056 return SafeSetError(parse_error, error);
2057 }
2058
2059 // In theory this shouldn't fail.
2060 if (!network_thread()->Invoke<bool>(
2061 RTC_FROM_HERE,
2062 rtc::Bind(&PeerConnection::ReconfigurePortAllocator_n, this,
2063 stun_servers, turn_servers, modified_config.type,
2064 modified_config.ice_candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02002065 modified_config.prune_turn_ports,
2066 modified_config.turn_customizer))) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002067 RTC_LOG(LS_ERROR) << "Failed to apply configuration to PortAllocator.";
deadbeef293e9262017-01-11 12:28:30 -08002068 return SafeSetError(RTCErrorType::INTERNAL_ERROR, error);
2069 }
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07002070
deadbeefd1a38b52016-12-10 13:15:33 -08002071 // As described in JSEP, calling setConfiguration with new ICE servers or
2072 // candidate policy must set a "needs-ice-restart" bit so that the next offer
2073 // triggers an ICE restart which will pick up the changes.
deadbeef293e9262017-01-11 12:28:30 -08002074 if (modified_config.servers != configuration_.servers ||
2075 modified_config.type != configuration_.type ||
2076 modified_config.prune_turn_ports != configuration_.prune_turn_ports) {
Steve Antond25da372017-11-06 14:50:29 -08002077 transport_controller_->SetNeedsIceRestartFlag();
deadbeefd1a38b52016-12-10 13:15:33 -08002078 }
skvladd1f5fda2017-02-03 16:54:05 -08002079
2080 if (modified_config.ice_check_min_interval !=
2081 configuration_.ice_check_min_interval) {
Steve Antond25da372017-11-06 14:50:29 -08002082 transport_controller_->SetIceConfig(ParseIceConfig(modified_config));
skvladd1f5fda2017-02-03 16:54:05 -08002083 }
2084
deadbeef293e9262017-01-11 12:28:30 -08002085 configuration_ = modified_config;
2086 return SafeSetError(RTCErrorType::NONE, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00002087}
2088
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002089bool PeerConnection::AddIceCandidate(
2090 const IceCandidateInterface* ice_candidate) {
Peter Boström1a9d6152015-12-08 22:15:17 +01002091 TRACE_EVENT0("webrtc", "PeerConnection::AddIceCandidate");
zhihuang29ff8442016-07-27 11:07:25 -07002092 if (IsClosed()) {
2093 return false;
2094 }
Steve Antond25da372017-11-06 14:50:29 -08002095
2096 if (!remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002097 RTC_LOG(LS_ERROR) << "ProcessIceMessage: ICE candidates can't be added "
2098 << "without any remote session description.";
Steve Antond25da372017-11-06 14:50:29 -08002099 return false;
2100 }
2101
2102 if (!ice_candidate) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002103 RTC_LOG(LS_ERROR) << "ProcessIceMessage: Candidate is NULL.";
Steve Antond25da372017-11-06 14:50:29 -08002104 return false;
2105 }
2106
2107 bool valid = false;
2108 bool ready = ReadyToUseRemoteCandidate(ice_candidate, nullptr, &valid);
2109 if (!valid) {
2110 return false;
2111 }
2112
2113 // Add this candidate to the remote session description.
2114 if (!mutable_remote_description()->AddCandidate(ice_candidate)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002115 RTC_LOG(LS_ERROR) << "ProcessIceMessage: Candidate cannot be used.";
Steve Antond25da372017-11-06 14:50:29 -08002116 return false;
2117 }
2118
2119 if (ready) {
2120 return UseCandidate(ice_candidate);
2121 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002122 RTC_LOG(LS_INFO) << "ProcessIceMessage: Not ready to use candidate.";
Steve Antond25da372017-11-06 14:50:29 -08002123 return true;
2124 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002125}
2126
Honghai Zhang7fb69db2016-03-14 11:59:18 -07002127bool PeerConnection::RemoveIceCandidates(
2128 const std::vector<cricket::Candidate>& candidates) {
2129 TRACE_EVENT0("webrtc", "PeerConnection::RemoveIceCandidates");
Steve Antond25da372017-11-06 14:50:29 -08002130 if (!remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002131 RTC_LOG(LS_ERROR) << "RemoveRemoteIceCandidates: ICE candidates can't be "
2132 << "removed without any remote session description.";
Steve Antond25da372017-11-06 14:50:29 -08002133 return false;
2134 }
2135
2136 if (candidates.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002137 RTC_LOG(LS_ERROR) << "RemoveRemoteIceCandidates: candidates are empty.";
Steve Antond25da372017-11-06 14:50:29 -08002138 return false;
2139 }
2140
2141 size_t number_removed =
2142 mutable_remote_description()->RemoveCandidates(candidates);
2143 if (number_removed != candidates.size()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002144 RTC_LOG(LS_ERROR)
2145 << "RemoveRemoteIceCandidates: Failed to remove candidates. "
2146 << "Requested " << candidates.size() << " but only " << number_removed
2147 << " are removed.";
Steve Antond25da372017-11-06 14:50:29 -08002148 }
2149
2150 // Remove the candidates from the transport controller.
2151 std::string error;
2152 bool res = transport_controller_->RemoveRemoteCandidates(candidates, &error);
2153 if (!res && !error.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002154 RTC_LOG(LS_ERROR) << "Error when removing remote candidates: " << error;
Steve Antond25da372017-11-06 14:50:29 -08002155 }
2156 return true;
Honghai Zhang7fb69db2016-03-14 11:59:18 -07002157}
2158
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00002159void PeerConnection::RegisterUMAObserver(UMAObserver* observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +01002160 TRACE_EVENT0("webrtc", "PeerConnection::RegisterUmaObserver");
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00002161 uma_observer_ = observer;
guoweis@webrtc.org7169afd2014-12-04 17:59:29 +00002162
Steve Anton75737c02017-11-06 10:37:17 -08002163 if (transport_controller()) {
2164 transport_controller()->SetMetricsObserver(uma_observer_);
guoweis@webrtc.org7169afd2014-12-04 17:59:29 +00002165 }
2166
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00002167 // Send information about IPv4/IPv6 status.
deadbeef293e9262017-01-11 12:28:30 -08002168 if (uma_observer_) {
Honghai Zhangd93f50c2016-10-05 11:47:22 -07002169 port_allocator_->SetMetricsObserver(uma_observer_);
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00002170 if (port_allocator_->flags() & cricket::PORTALLOCATOR_ENABLE_IPV6) {
Guo-wei Shiehdfbe6792015-09-03 17:12:07 -07002171 uma_observer_->IncrementEnumCounter(
2172 kEnumCounterAddressFamily, kPeerConnection_IPv6,
2173 kPeerConnectionAddressFamilyCounter_Max);
mallinath@webrtc.orgb445f262014-05-23 22:19:37 +00002174 } else {
Guo-wei Shiehdfbe6792015-09-03 17:12:07 -07002175 uma_observer_->IncrementEnumCounter(
2176 kEnumCounterAddressFamily, kPeerConnection_IPv4,
2177 kPeerConnectionAddressFamilyCounter_Max);
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00002178 }
2179 }
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00002180}
2181
zstein4b979802017-06-02 14:37:37 -07002182RTCError PeerConnection::SetBitrate(const BitrateParameters& bitrate) {
Steve Anton978b8762017-09-29 12:15:02 -07002183 if (!worker_thread()->IsCurrent()) {
2184 return worker_thread()->Invoke<RTCError>(
zstein4b979802017-06-02 14:37:37 -07002185 RTC_FROM_HERE, rtc::Bind(&PeerConnection::SetBitrate, this, bitrate));
2186 }
2187
2188 const bool has_min = static_cast<bool>(bitrate.min_bitrate_bps);
2189 const bool has_current = static_cast<bool>(bitrate.current_bitrate_bps);
2190 const bool has_max = static_cast<bool>(bitrate.max_bitrate_bps);
2191 if (has_min && *bitrate.min_bitrate_bps < 0) {
2192 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2193 "min_bitrate_bps <= 0");
2194 }
2195 if (has_current) {
2196 if (has_min && *bitrate.current_bitrate_bps < *bitrate.min_bitrate_bps) {
2197 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2198 "current_bitrate_bps < min_bitrate_bps");
2199 } else if (*bitrate.current_bitrate_bps < 0) {
2200 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2201 "curent_bitrate_bps < 0");
2202 }
2203 }
2204 if (has_max) {
2205 if (has_current &&
2206 *bitrate.max_bitrate_bps < *bitrate.current_bitrate_bps) {
2207 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2208 "max_bitrate_bps < current_bitrate_bps");
2209 } else if (has_min && *bitrate.max_bitrate_bps < *bitrate.min_bitrate_bps) {
2210 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2211 "max_bitrate_bps < min_bitrate_bps");
2212 } else if (*bitrate.max_bitrate_bps < 0) {
2213 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2214 "max_bitrate_bps < 0");
2215 }
2216 }
2217
2218 Call::Config::BitrateConfigMask mask;
2219 mask.min_bitrate_bps = bitrate.min_bitrate_bps;
2220 mask.start_bitrate_bps = bitrate.current_bitrate_bps;
2221 mask.max_bitrate_bps = bitrate.max_bitrate_bps;
2222
2223 RTC_DCHECK(call_.get());
2224 call_->SetBitrateConfigMask(mask);
2225
2226 return RTCError::OK();
2227}
2228
Alex Narest78609d52017-10-20 10:37:47 +02002229void PeerConnection::SetBitrateAllocationStrategy(
2230 std::unique_ptr<rtc::BitrateAllocationStrategy>
2231 bitrate_allocation_strategy) {
2232 rtc::Thread* worker_thread = factory_->worker_thread();
2233 if (!worker_thread->IsCurrent()) {
2234 rtc::BitrateAllocationStrategy* strategy_raw =
2235 bitrate_allocation_strategy.release();
2236 auto functor = [this, strategy_raw]() {
2237 call_->SetBitrateAllocationStrategy(
2238 rtc::WrapUnique<rtc::BitrateAllocationStrategy>(strategy_raw));
2239 };
2240 worker_thread->Invoke<void>(RTC_FROM_HERE, functor);
2241 return;
2242 }
2243 RTC_DCHECK(call_.get());
2244 call_->SetBitrateAllocationStrategy(std::move(bitrate_allocation_strategy));
2245}
2246
henrika5f6bf242017-11-01 11:06:56 +01002247void PeerConnection::SetAudioPlayout(bool playout) {
2248 if (!worker_thread()->IsCurrent()) {
2249 worker_thread()->Invoke<void>(
2250 RTC_FROM_HERE,
2251 rtc::Bind(&PeerConnection::SetAudioPlayout, this, playout));
2252 return;
2253 }
2254 auto audio_state =
2255 factory_->channel_manager()->media_engine()->GetAudioState();
2256 audio_state->SetPlayout(playout);
2257}
2258
2259void PeerConnection::SetAudioRecording(bool recording) {
2260 if (!worker_thread()->IsCurrent()) {
2261 worker_thread()->Invoke<void>(
2262 RTC_FROM_HERE,
2263 rtc::Bind(&PeerConnection::SetAudioRecording, this, recording));
2264 return;
2265 }
2266 auto audio_state =
2267 factory_->channel_manager()->media_engine()->GetAudioState();
2268 audio_state->SetRecording(recording);
2269}
2270
Steve Anton8c0f7a72017-10-03 10:03:10 -07002271std::unique_ptr<rtc::SSLCertificate>
2272PeerConnection::GetRemoteAudioSSLCertificate() {
Steve Anton75737c02017-11-06 10:37:17 -08002273 if (!voice_channel()) {
Steve Anton8c0f7a72017-10-03 10:03:10 -07002274 return nullptr;
2275 }
Steve Anton75737c02017-11-06 10:37:17 -08002276 return GetRemoteSSLCertificate(voice_channel()->transport_name());
Steve Anton8c0f7a72017-10-03 10:03:10 -07002277}
2278
ivoc14d5dbe2016-07-04 07:06:55 -07002279bool PeerConnection::StartRtcEventLog(rtc::PlatformFile file,
2280 int64_t max_size_bytes) {
Elad Alon99c3fe52017-10-13 16:29:40 +02002281 // TODO(eladalon): It would be better to not allow negative values into PC.
2282 const size_t max_size = (max_size_bytes < 0)
2283 ? RtcEventLog::kUnlimitedOutput
2284 : rtc::saturated_cast<size_t>(max_size_bytes);
2285 return StartRtcEventLog(
Bjorn Tereliusde939432017-11-20 17:38:14 +01002286 rtc::MakeUnique<RtcEventLogOutputFile>(file, max_size),
2287 webrtc::RtcEventLog::kImmediateOutput);
Elad Alon99c3fe52017-10-13 16:29:40 +02002288}
2289
Bjorn Tereliusde939432017-11-20 17:38:14 +01002290bool PeerConnection::StartRtcEventLog(std::unique_ptr<RtcEventLogOutput> output,
2291 int64_t output_period_ms) {
Karl Wibergd6b48192017-10-16 23:01:06 +02002292 // TODO(eladalon): In C++14, this can be done with a lambda.
2293 struct Functor {
Bjorn Tereliusde939432017-11-20 17:38:14 +01002294 bool operator()() {
2295 return pc->StartRtcEventLog_w(std::move(output), output_period_ms);
2296 }
Karl Wibergd6b48192017-10-16 23:01:06 +02002297 PeerConnection* const pc;
2298 std::unique_ptr<RtcEventLogOutput> output;
Bjorn Tereliusde939432017-11-20 17:38:14 +01002299 const int64_t output_period_ms;
Elad Alon99c3fe52017-10-13 16:29:40 +02002300 };
Bjorn Tereliusde939432017-11-20 17:38:14 +01002301 return worker_thread()->Invoke<bool>(
2302 RTC_FROM_HERE, Functor{this, std::move(output), output_period_ms});
ivoc14d5dbe2016-07-04 07:06:55 -07002303}
2304
2305void PeerConnection::StopRtcEventLog() {
Steve Anton978b8762017-09-29 12:15:02 -07002306 worker_thread()->Invoke<void>(
ivoc14d5dbe2016-07-04 07:06:55 -07002307 RTC_FROM_HERE, rtc::Bind(&PeerConnection::StopRtcEventLog_w, this));
2308}
2309
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002310const SessionDescriptionInterface* PeerConnection::local_description() const {
Steve Anton75737c02017-11-06 10:37:17 -08002311 return pending_local_description_ ? pending_local_description_.get()
2312 : current_local_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002313}
2314
2315const SessionDescriptionInterface* PeerConnection::remote_description() const {
Steve Anton75737c02017-11-06 10:37:17 -08002316 return pending_remote_description_ ? pending_remote_description_.get()
2317 : current_remote_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002318}
2319
deadbeeffe4a8a42016-12-20 17:56:17 -08002320const SessionDescriptionInterface* PeerConnection::current_local_description()
2321 const {
Steve Anton75737c02017-11-06 10:37:17 -08002322 return current_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08002323}
2324
2325const SessionDescriptionInterface* PeerConnection::current_remote_description()
2326 const {
Steve Anton75737c02017-11-06 10:37:17 -08002327 return current_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08002328}
2329
2330const SessionDescriptionInterface* PeerConnection::pending_local_description()
2331 const {
Steve Anton75737c02017-11-06 10:37:17 -08002332 return pending_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08002333}
2334
2335const SessionDescriptionInterface* PeerConnection::pending_remote_description()
2336 const {
Steve Anton75737c02017-11-06 10:37:17 -08002337 return pending_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08002338}
2339
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002340void PeerConnection::Close() {
Peter Boström1a9d6152015-12-08 22:15:17 +01002341 TRACE_EVENT0("webrtc", "PeerConnection::Close");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002342 // Update stats here so that we have the most recent stats for tracks and
2343 // streams before the channels are closed.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00002344 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002345
Steve Anton75737c02017-11-06 10:37:17 -08002346 ChangeSignalingState(PeerConnectionInterface::kClosed);
Steve Anton3fe1b152017-12-12 10:20:08 -08002347
2348 StopAndDestroyChannels();
Steve Anton75737c02017-11-06 10:37:17 -08002349
deadbeef42a42632017-03-10 15:18:00 -08002350 network_thread()->Invoke<void>(
2351 RTC_FROM_HERE,
2352 rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
2353 port_allocator_.get()));
nisseeaabdf62017-05-05 02:23:02 -07002354
Steve Anton978b8762017-09-29 12:15:02 -07002355 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
eladalon248fd4f2017-09-06 05:18:15 -07002356 call_.reset();
2357 // The event log must outlive call (and any other object that uses it).
2358 event_log_.reset();
2359 });
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002360}
2361
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002362void PeerConnection::OnMessage(rtc::Message* msg) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002363 switch (msg->message_id) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002364 case MSG_SET_SESSIONDESCRIPTION_SUCCESS: {
2365 SetSessionDescriptionMsg* param =
2366 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
2367 param->observer->OnSuccess();
2368 delete param;
2369 break;
2370 }
2371 case MSG_SET_SESSIONDESCRIPTION_FAILED: {
2372 SetSessionDescriptionMsg* param =
2373 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
2374 param->observer->OnFailure(param->error);
2375 delete param;
2376 break;
2377 }
deadbeefab9b2d12015-10-14 11:33:11 -07002378 case MSG_CREATE_SESSIONDESCRIPTION_FAILED: {
2379 CreateSessionDescriptionMsg* param =
2380 static_cast<CreateSessionDescriptionMsg*>(msg->pdata);
2381 param->observer->OnFailure(param->error);
2382 delete param;
2383 break;
2384 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002385 case MSG_GETSTATS: {
2386 GetStatsMsg* param = static_cast<GetStatsMsg*>(msg->pdata);
nissee8abe3e2017-01-18 05:00:34 -08002387 StatsReports reports;
2388 stats_->GetStats(param->track, &reports);
2389 param->observer->OnComplete(reports);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002390 delete param;
2391 break;
2392 }
deadbeefbd292462015-12-14 18:15:29 -08002393 case MSG_FREE_DATACHANNELS: {
2394 sctp_data_channels_to_free_.clear();
2395 break;
2396 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002397 default:
nisseeb4ca4e2017-01-12 02:24:27 -08002398 RTC_NOTREACHED() << "Not implemented";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002399 break;
2400 }
2401}
2402
Steve Anton4171afb2017-11-20 10:20:22 -08002403void PeerConnection::CreateAudioReceiver(
2404 MediaStreamInterface* stream,
2405 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01002406 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
2407 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
zhihuang81c3a032016-11-17 12:06:24 -08002408 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
2409 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
deadbeefe814a0d2017-02-25 18:15:09 -08002410 signaling_thread(),
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01002411 new AudioRtpReceiver(remote_sender_info.sender_id, streams,
Steve Anton4171afb2017-11-20 10:20:22 -08002412 remote_sender_info.first_ssrc, voice_channel()));
deadbeefe814a0d2017-02-25 18:15:09 -08002413 stream->AddTrack(
2414 static_cast<AudioTrackInterface*>(receiver->internal()->track().get()));
Steve Anton4171afb2017-11-20 10:20:22 -08002415 GetAudioTransceiver()->internal()->AddReceiver(receiver);
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01002416 observer_->OnAddTrack(receiver, std::move(streams));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002417}
2418
Steve Anton4171afb2017-11-20 10:20:22 -08002419void PeerConnection::CreateVideoReceiver(
2420 MediaStreamInterface* stream,
2421 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01002422 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
2423 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
zhihuang81c3a032016-11-17 12:06:24 -08002424 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
2425 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
Steve Anton4171afb2017-11-20 10:20:22 -08002426 signaling_thread(),
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01002427 new VideoRtpReceiver(remote_sender_info.sender_id, streams,
2428 worker_thread(), remote_sender_info.first_ssrc,
2429 video_channel()));
deadbeefe814a0d2017-02-25 18:15:09 -08002430 stream->AddTrack(
2431 static_cast<VideoTrackInterface*>(receiver->internal()->track().get()));
Steve Anton4171afb2017-11-20 10:20:22 -08002432 GetVideoTransceiver()->internal()->AddReceiver(receiver);
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01002433 observer_->OnAddTrack(receiver, std::move(streams));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002434}
2435
deadbeef70ab1a12015-09-28 16:53:55 -07002436// TODO(deadbeef): Keep RtpReceivers around even if track goes away in remote
2437// description.
Henrik Boström933d8b02017-10-10 10:05:16 -07002438rtc::scoped_refptr<RtpReceiverInterface> PeerConnection::RemoveAndStopReceiver(
Steve Anton4171afb2017-11-20 10:20:22 -08002439 const RtpSenderInfo& remote_sender_info) {
2440 auto receiver = FindReceiverById(remote_sender_info.sender_id);
2441 if (!receiver) {
2442 RTC_LOG(LS_WARNING) << "RtpReceiver for track with id "
2443 << remote_sender_info.sender_id << " doesn't exist.";
Henrik Boström933d8b02017-10-10 10:05:16 -07002444 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07002445 }
Steve Anton4171afb2017-11-20 10:20:22 -08002446 if (receiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
2447 GetAudioTransceiver()->internal()->RemoveReceiver(receiver);
2448 } else {
2449 GetVideoTransceiver()->internal()->RemoveReceiver(receiver);
2450 }
Henrik Boström933d8b02017-10-10 10:05:16 -07002451 return receiver;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002452}
2453
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002454void PeerConnection::AddAudioTrack(AudioTrackInterface* track,
2455 MediaStreamInterface* stream) {
2456 RTC_DCHECK(!IsClosed());
2457 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08002458 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002459 // We already have a sender for this track, so just change the stream_id
2460 // so that it's correct in the next call to CreateOffer.
Steve Anton4171afb2017-11-20 10:20:22 -08002461 sender->internal()->set_stream_id(stream->label());
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002462 return;
2463 }
2464
2465 // Normal case; we've never seen this track before.
2466 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender =
2467 RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
2468 signaling_thread(),
Steve Anton75737c02017-11-06 10:37:17 -08002469 new AudioRtpSender(track, {stream->label()}, voice_channel(),
2470 stats_.get()));
Steve Anton4171afb2017-11-20 10:20:22 -08002471 GetAudioTransceiver()->internal()->AddSender(new_sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002472 // If the sender has already been configured in SDP, we call SetSsrc,
2473 // which will connect the sender to the underlying transport. This can
2474 // occur if a local session description that contains the ID of the sender
2475 // is set before AddStream is called. It can also occur if the local
2476 // session description is not changed and RemoveStream is called, and
2477 // later AddStream is called again with the same stream.
Steve Anton4171afb2017-11-20 10:20:22 -08002478 const RtpSenderInfo* sender_info =
2479 FindSenderInfo(local_audio_sender_infos_, stream->label(), track->id());
2480 if (sender_info) {
2481 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002482 }
2483}
2484
2485// TODO(deadbeef): Don't destroy RtpSenders here; they should be kept around
2486// indefinitely, when we have unified plan SDP.
2487void PeerConnection::RemoveAudioTrack(AudioTrackInterface* track,
2488 MediaStreamInterface* stream) {
2489 RTC_DCHECK(!IsClosed());
2490 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08002491 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002492 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
2493 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002494 return;
2495 }
Steve Anton4171afb2017-11-20 10:20:22 -08002496 GetAudioTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002497}
2498
2499void PeerConnection::AddVideoTrack(VideoTrackInterface* track,
2500 MediaStreamInterface* stream) {
2501 RTC_DCHECK(!IsClosed());
2502 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08002503 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002504 // We already have a sender for this track, so just change the stream_id
2505 // so that it's correct in the next call to CreateOffer.
Steve Anton4171afb2017-11-20 10:20:22 -08002506 sender->internal()->set_stream_id(stream->label());
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002507 return;
2508 }
2509
2510 // Normal case; we've never seen this track before.
2511 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender =
2512 RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton75737c02017-11-06 10:37:17 -08002513 signaling_thread(),
2514 new VideoRtpSender(track, {stream->label()}, video_channel()));
Steve Anton4171afb2017-11-20 10:20:22 -08002515 GetVideoTransceiver()->internal()->AddSender(new_sender);
2516 const RtpSenderInfo* sender_info =
2517 FindSenderInfo(local_video_sender_infos_, stream->label(), track->id());
2518 if (sender_info) {
2519 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002520 }
2521}
2522
2523void PeerConnection::RemoveVideoTrack(VideoTrackInterface* track,
2524 MediaStreamInterface* stream) {
2525 RTC_DCHECK(!IsClosed());
2526 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08002527 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002528 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
2529 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002530 return;
2531 }
Steve Anton4171afb2017-11-20 10:20:22 -08002532 GetVideoTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002533}
2534
Steve Antonba818672017-11-06 10:21:57 -08002535void PeerConnection::SetIceConnectionState(IceConnectionState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07002536 RTC_DCHECK(signaling_thread()->IsCurrent());
Steve Antonba818672017-11-06 10:21:57 -08002537 if (ice_connection_state_ == new_state) {
2538 return;
2539 }
2540
deadbeefcbecd352015-09-23 11:50:27 -07002541 // After transitioning to "closed", ignore any additional states from
Steve Antonba818672017-11-06 10:21:57 -08002542 // TransportController (such as "disconnected").
deadbeefab9b2d12015-10-14 11:33:11 -07002543 if (IsClosed()) {
deadbeefcbecd352015-09-23 11:50:27 -07002544 return;
2545 }
Steve Antonba818672017-11-06 10:21:57 -08002546
Mirko Bonadei675513b2017-11-09 11:09:25 +01002547 RTC_LOG(LS_INFO) << "Changing IceConnectionState " << ice_connection_state_
2548 << " => " << new_state;
Steve Antonba818672017-11-06 10:21:57 -08002549 RTC_DCHECK(ice_connection_state_ !=
2550 PeerConnectionInterface::kIceConnectionClosed);
2551
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002552 ice_connection_state_ = new_state;
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00002553 observer_->OnIceConnectionChange(ice_connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002554}
2555
2556void PeerConnection::OnIceGatheringChange(
2557 PeerConnectionInterface::IceGatheringState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07002558 RTC_DCHECK(signaling_thread()->IsCurrent());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002559 if (IsClosed()) {
2560 return;
2561 }
2562 ice_gathering_state_ = new_state;
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00002563 observer_->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002564}
2565
jbauch81bf7b02017-03-25 08:31:12 -07002566void PeerConnection::OnIceCandidate(
2567 std::unique_ptr<IceCandidateInterface> candidate) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07002568 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07002569 if (IsClosed()) {
2570 return;
2571 }
jbauch81bf7b02017-03-25 08:31:12 -07002572 observer_->OnIceCandidate(candidate.get());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002573}
2574
Honghai Zhang7fb69db2016-03-14 11:59:18 -07002575void PeerConnection::OnIceCandidatesRemoved(
2576 const std::vector<cricket::Candidate>& candidates) {
2577 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07002578 if (IsClosed()) {
2579 return;
2580 }
Honghai Zhang7fb69db2016-03-14 11:59:18 -07002581 observer_->OnIceCandidatesRemoved(candidates);
2582}
2583
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002584void PeerConnection::ChangeSignalingState(
2585 PeerConnectionInterface::SignalingState signaling_state) {
Steve Antonba818672017-11-06 10:21:57 -08002586 RTC_DCHECK(signaling_thread()->IsCurrent());
2587 if (signaling_state_ == signaling_state) {
2588 return;
2589 }
Mirko Bonadei675513b2017-11-09 11:09:25 +01002590 RTC_LOG(LS_INFO) << "Session: " << session_id() << " Old state: "
2591 << GetSignalingStateString(signaling_state_)
2592 << " New state: "
2593 << GetSignalingStateString(signaling_state);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002594 signaling_state_ = signaling_state;
2595 if (signaling_state == kClosed) {
2596 ice_connection_state_ = kIceConnectionClosed;
2597 observer_->OnIceConnectionChange(ice_connection_state_);
2598 if (ice_gathering_state_ != kIceGatheringComplete) {
2599 ice_gathering_state_ = kIceGatheringComplete;
2600 observer_->OnIceGatheringChange(ice_gathering_state_);
2601 }
2602 }
2603 observer_->OnSignalingChange(signaling_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002604}
2605
deadbeefeb459812015-12-15 19:24:43 -08002606void PeerConnection::OnAudioTrackAdded(AudioTrackInterface* track,
2607 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07002608 if (IsClosed()) {
2609 return;
2610 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002611 AddAudioTrack(track, stream);
2612 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08002613}
2614
deadbeefeb459812015-12-15 19:24:43 -08002615void PeerConnection::OnAudioTrackRemoved(AudioTrackInterface* track,
2616 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07002617 if (IsClosed()) {
2618 return;
2619 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002620 RemoveAudioTrack(track, stream);
2621 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08002622}
2623
2624void PeerConnection::OnVideoTrackAdded(VideoTrackInterface* track,
2625 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07002626 if (IsClosed()) {
2627 return;
2628 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002629 AddVideoTrack(track, stream);
2630 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08002631}
2632
2633void PeerConnection::OnVideoTrackRemoved(VideoTrackInterface* track,
2634 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07002635 if (IsClosed()) {
2636 return;
2637 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002638 RemoveVideoTrack(track, stream);
2639 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08002640}
2641
Henrik Boström31638672017-11-23 17:48:32 +01002642void PeerConnection::PostSetSessionDescriptionSuccess(
2643 SetSessionDescriptionObserver* observer) {
2644 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
2645 signaling_thread()->Post(RTC_FROM_HERE, this,
2646 MSG_SET_SESSIONDESCRIPTION_SUCCESS, msg);
2647}
2648
deadbeefab9b2d12015-10-14 11:33:11 -07002649void PeerConnection::PostSetSessionDescriptionFailure(
2650 SetSessionDescriptionObserver* observer,
2651 const std::string& error) {
2652 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
2653 msg->error = error;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07002654 signaling_thread()->Post(RTC_FROM_HERE, this,
2655 MSG_SET_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07002656}
2657
2658void PeerConnection::PostCreateSessionDescriptionFailure(
2659 CreateSessionDescriptionObserver* observer,
2660 const std::string& error) {
2661 CreateSessionDescriptionMsg* msg = new CreateSessionDescriptionMsg(observer);
2662 msg->error = error;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07002663 signaling_thread()->Post(RTC_FROM_HERE, this,
2664 MSG_CREATE_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07002665}
2666
zhihuang1c378ed2017-08-17 14:10:50 -07002667void PeerConnection::GetOptionsForOffer(
deadbeefab9b2d12015-10-14 11:33:11 -07002668 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options,
2669 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07002670 ExtractSharedMediaSessionOptions(rtc_options, session_options);
2671
2672 // Figure out transceiver directional preferences.
2673 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
2674 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
2675
2676 // By default, generate sendrecv/recvonly m= sections.
2677 bool recv_audio = true;
2678 bool recv_video = true;
2679
2680 // By default, only offer a new m= section if we have media to send with it.
2681 bool offer_new_audio_description = send_audio;
2682 bool offer_new_video_description = send_video;
2683 bool offer_new_data_description = HasDataChannels();
2684
2685 // The "offer_to_receive_X" options allow those defaults to be overridden.
2686 if (rtc_options.offer_to_receive_audio != RTCOfferAnswerOptions::kUndefined) {
2687 recv_audio = (rtc_options.offer_to_receive_audio > 0);
2688 offer_new_audio_description =
2689 offer_new_audio_description || (rtc_options.offer_to_receive_audio > 0);
2690 }
2691 if (rtc_options.offer_to_receive_video != RTCOfferAnswerOptions::kUndefined) {
2692 recv_video = (rtc_options.offer_to_receive_video > 0);
2693 offer_new_video_description =
2694 offer_new_video_description || (rtc_options.offer_to_receive_video > 0);
2695 }
2696
2697 rtc::Optional<size_t> audio_index;
2698 rtc::Optional<size_t> video_index;
2699 rtc::Optional<size_t> data_index;
2700 // If a current description exists, generate m= sections in the same order,
2701 // using the first audio/video/data section that appears and rejecting
2702 // extraneous ones.
Steve Anton75737c02017-11-06 10:37:17 -08002703 if (local_description()) {
zhihuang1c378ed2017-08-17 14:10:50 -07002704 GenerateMediaDescriptionOptions(
Steve Anton75737c02017-11-06 10:37:17 -08002705 local_description(),
Steve Anton1d03a752017-11-27 14:30:09 -08002706 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
2707 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
2708 &audio_index, &video_index, &data_index, session_options);
deadbeefab9b2d12015-10-14 11:33:11 -07002709 }
2710
zhihuang1c378ed2017-08-17 14:10:50 -07002711 // Add audio/video/data m= sections to the end if needed.
2712 if (!audio_index && offer_new_audio_description) {
2713 session_options->media_description_options.push_back(
2714 cricket::MediaDescriptionOptions(
2715 cricket::MEDIA_TYPE_AUDIO, cricket::CN_AUDIO,
Steve Anton1d03a752017-11-27 14:30:09 -08002716 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
2717 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01002718 audio_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07002719 }
zhihuang1c378ed2017-08-17 14:10:50 -07002720 if (!video_index && offer_new_video_description) {
2721 session_options->media_description_options.push_back(
2722 cricket::MediaDescriptionOptions(
2723 cricket::MEDIA_TYPE_VIDEO, cricket::CN_VIDEO,
Steve Anton1d03a752017-11-27 14:30:09 -08002724 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
2725 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01002726 video_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07002727 }
zhihuang1c378ed2017-08-17 14:10:50 -07002728 if (!data_index && offer_new_data_description) {
2729 session_options->media_description_options.push_back(
2730 cricket::MediaDescriptionOptions(
2731 cricket::MEDIA_TYPE_DATA, cricket::CN_DATA,
Steve Anton1d03a752017-11-27 14:30:09 -08002732 RtpTransceiverDirection::kSendRecv, false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01002733 data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07002734 }
2735
2736 cricket::MediaDescriptionOptions* audio_media_description_options =
2737 !audio_index ? nullptr
2738 : &session_options->media_description_options[*audio_index];
2739 cricket::MediaDescriptionOptions* video_media_description_options =
2740 !video_index ? nullptr
2741 : &session_options->media_description_options[*video_index];
2742 cricket::MediaDescriptionOptions* data_media_description_options =
2743 !data_index ? nullptr
2744 : &session_options->media_description_options[*data_index];
2745
2746 // Apply ICE restart flag and renomination flag.
2747 for (auto& options : session_options->media_description_options) {
2748 options.transport_options.ice_restart = rtc_options.ice_restart;
2749 options.transport_options.enable_ice_renomination =
2750 configuration_.enable_ice_renomination;
2751 }
2752
Steve Anton4171afb2017-11-20 10:20:22 -08002753 AddRtpSenderOptions(GetSendersInternal(), audio_media_description_options,
zhihuang1c378ed2017-08-17 14:10:50 -07002754 video_media_description_options);
2755 AddRtpDataChannelOptions(rtp_data_channels_, data_media_description_options);
deadbeefc80741f2015-10-22 13:14:45 -07002756
zhihuang9763d562016-08-05 11:14:50 -07002757 // Intentionally unset the data channel type for RTP data channel with the
2758 // second condition. Otherwise the RTP data channels would be successfully
2759 // negotiated by default and the unit tests in WebRtcDataBrowserTest will fail
2760 // when building with chromium. We want to leave RTP data channels broken, so
2761 // people won't try to use them.
Steve Anton75737c02017-11-06 10:37:17 -08002762 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
2763 session_options->data_channel_type = data_channel_type();
deadbeefab9b2d12015-10-14 11:33:11 -07002764 }
zhihuang8f65cdf2016-05-06 18:40:30 -07002765
2766 session_options->rtcp_cname = rtcp_cname_;
jbauchcb560652016-08-04 05:20:32 -07002767 session_options->crypto_options = factory_->options().crypto_options;
deadbeefab9b2d12015-10-14 11:33:11 -07002768}
2769
zhihuang1c378ed2017-08-17 14:10:50 -07002770void PeerConnection::GetOptionsForAnswer(
2771 const RTCOfferAnswerOptions& rtc_options,
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07002772 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07002773 ExtractSharedMediaSessionOptions(rtc_options, session_options);
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07002774
zhihuang1c378ed2017-08-17 14:10:50 -07002775 // Figure out transceiver directional preferences.
2776 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
2777 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
2778
2779 // By default, generate sendrecv/recvonly m= sections. The direction is also
2780 // restricted by the direction in the offer.
2781 bool recv_audio = true;
2782 bool recv_video = true;
2783
2784 // The "offer_to_receive_X" options allow those defaults to be overridden.
2785 if (rtc_options.offer_to_receive_audio != RTCOfferAnswerOptions::kUndefined) {
2786 recv_audio = (rtc_options.offer_to_receive_audio > 0);
deadbeef0ed85b22016-02-23 17:24:52 -08002787 }
zhihuang1c378ed2017-08-17 14:10:50 -07002788 if (rtc_options.offer_to_receive_video != RTCOfferAnswerOptions::kUndefined) {
2789 recv_video = (rtc_options.offer_to_receive_video > 0);
2790 }
2791
2792 rtc::Optional<size_t> audio_index;
2793 rtc::Optional<size_t> video_index;
2794 rtc::Optional<size_t> data_index;
Steve Anton75737c02017-11-06 10:37:17 -08002795 if (remote_description()) {
zhihuang141aacb2017-08-29 13:23:53 -07002796 // The pending remote description should be an offer.
Steve Antona3a92c22017-12-07 10:27:41 -08002797 RTC_DCHECK(remote_description()->GetType() == SdpType::kOffer);
zhihuang141aacb2017-08-29 13:23:53 -07002798 // Generate m= sections that match those in the offer.
2799 // Note that mediasession.cc will handle intersection our preferred
2800 // direction with the offered direction.
2801 GenerateMediaDescriptionOptions(
Steve Anton75737c02017-11-06 10:37:17 -08002802 remote_description(),
Steve Anton1d03a752017-11-27 14:30:09 -08002803 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
2804 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
2805 &audio_index, &video_index, &data_index, session_options);
zhihuang141aacb2017-08-29 13:23:53 -07002806 }
zhihuang1c378ed2017-08-17 14:10:50 -07002807
2808 cricket::MediaDescriptionOptions* audio_media_description_options =
2809 !audio_index ? nullptr
2810 : &session_options->media_description_options[*audio_index];
2811 cricket::MediaDescriptionOptions* video_media_description_options =
2812 !video_index ? nullptr
2813 : &session_options->media_description_options[*video_index];
2814 cricket::MediaDescriptionOptions* data_media_description_options =
2815 !data_index ? nullptr
2816 : &session_options->media_description_options[*data_index];
2817
2818 // Apply ICE renomination flag.
2819 for (auto& options : session_options->media_description_options) {
2820 options.transport_options.enable_ice_renomination =
2821 configuration_.enable_ice_renomination;
2822 }
2823
Steve Anton4171afb2017-11-20 10:20:22 -08002824 AddRtpSenderOptions(GetSendersInternal(), audio_media_description_options,
zhihuang1c378ed2017-08-17 14:10:50 -07002825 video_media_description_options);
2826 AddRtpDataChannelOptions(rtp_data_channels_, data_media_description_options);
2827
zhihuang9763d562016-08-05 11:14:50 -07002828 // Intentionally unset the data channel type for RTP data channel. Otherwise
2829 // the RTP data channels would be successfully negotiated by default and the
2830 // unit tests in WebRtcDataBrowserTest will fail when building with chromium.
2831 // We want to leave RTP data channels broken, so people won't try to use them.
Steve Anton75737c02017-11-06 10:37:17 -08002832 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
2833 session_options->data_channel_type = data_channel_type();
deadbeef907abe42016-08-04 12:22:18 -07002834 }
zhihuangaf388472016-11-02 16:49:48 -07002835
zhihuang1c378ed2017-08-17 14:10:50 -07002836 session_options->rtcp_cname = rtcp_cname_;
jbauchcb560652016-08-04 05:20:32 -07002837 session_options->crypto_options = factory_->options().crypto_options;
htaa2a49d92016-03-04 02:51:39 -08002838}
2839
zhihuang1c378ed2017-08-17 14:10:50 -07002840void PeerConnection::GenerateMediaDescriptionOptions(
2841 const SessionDescriptionInterface* session_desc,
Steve Anton1d03a752017-11-27 14:30:09 -08002842 RtpTransceiverDirection audio_direction,
2843 RtpTransceiverDirection video_direction,
zhihuang1c378ed2017-08-17 14:10:50 -07002844 rtc::Optional<size_t>* audio_index,
2845 rtc::Optional<size_t>* video_index,
2846 rtc::Optional<size_t>* data_index,
htaa2a49d92016-03-04 02:51:39 -08002847 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07002848 for (const cricket::ContentInfo& content :
2849 session_desc->description()->contents()) {
2850 if (IsAudioContent(&content)) {
2851 // If we already have an audio m= section, reject this extra one.
2852 if (*audio_index) {
2853 session_options->media_description_options.push_back(
2854 cricket::MediaDescriptionOptions(
2855 cricket::MEDIA_TYPE_AUDIO, content.name,
Steve Anton1d03a752017-11-27 14:30:09 -08002856 RtpTransceiverDirection::kInactive, true));
zhihuang1c378ed2017-08-17 14:10:50 -07002857 } else {
2858 session_options->media_description_options.push_back(
2859 cricket::MediaDescriptionOptions(
2860 cricket::MEDIA_TYPE_AUDIO, content.name, audio_direction,
Steve Anton1d03a752017-11-27 14:30:09 -08002861 audio_direction == RtpTransceiverDirection::kInactive));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01002862 *audio_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07002863 }
2864 } else if (IsVideoContent(&content)) {
2865 // If we already have an video m= section, reject this extra one.
2866 if (*video_index) {
2867 session_options->media_description_options.push_back(
2868 cricket::MediaDescriptionOptions(
2869 cricket::MEDIA_TYPE_VIDEO, content.name,
Steve Anton1d03a752017-11-27 14:30:09 -08002870 RtpTransceiverDirection::kInactive, true));
zhihuang1c378ed2017-08-17 14:10:50 -07002871 } else {
2872 session_options->media_description_options.push_back(
2873 cricket::MediaDescriptionOptions(
2874 cricket::MEDIA_TYPE_VIDEO, content.name, video_direction,
Steve Anton1d03a752017-11-27 14:30:09 -08002875 video_direction == RtpTransceiverDirection::kInactive));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01002876 *video_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07002877 }
2878 } else {
2879 RTC_DCHECK(IsDataContent(&content));
2880 // If we already have an data m= section, reject this extra one.
2881 if (*data_index) {
2882 session_options->media_description_options.push_back(
2883 cricket::MediaDescriptionOptions(
2884 cricket::MEDIA_TYPE_DATA, content.name,
Steve Anton1d03a752017-11-27 14:30:09 -08002885 RtpTransceiverDirection::kInactive, true));
zhihuang1c378ed2017-08-17 14:10:50 -07002886 } else {
2887 session_options->media_description_options.push_back(
2888 cricket::MediaDescriptionOptions(
2889 cricket::MEDIA_TYPE_DATA, content.name,
2890 // Direction for data sections is meaningless, but legacy
2891 // endpoints might expect sendrecv.
Steve Anton1d03a752017-11-27 14:30:09 -08002892 RtpTransceiverDirection::kSendRecv, false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01002893 *data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07002894 }
2895 }
htaa2a49d92016-03-04 02:51:39 -08002896 }
deadbeefab9b2d12015-10-14 11:33:11 -07002897}
2898
Steve Anton4171afb2017-11-20 10:20:22 -08002899void PeerConnection::RemoveSenders(cricket::MediaType media_type) {
2900 UpdateLocalSenders(std::vector<cricket::StreamParams>(), media_type);
2901 UpdateRemoteSendersList(std::vector<cricket::StreamParams>(), false,
deadbeefbda7e0b2015-12-08 17:13:40 -08002902 media_type, nullptr);
deadbeeffaac4972015-11-12 15:33:07 -08002903}
2904
Steve Anton4171afb2017-11-20 10:20:22 -08002905void PeerConnection::UpdateRemoteSendersList(
deadbeefab9b2d12015-10-14 11:33:11 -07002906 const cricket::StreamParamsVec& streams,
Steve Anton4171afb2017-11-20 10:20:22 -08002907 bool default_sender_needed,
deadbeefab9b2d12015-10-14 11:33:11 -07002908 cricket::MediaType media_type,
2909 StreamCollection* new_streams) {
Steve Anton4171afb2017-11-20 10:20:22 -08002910 std::vector<RtpSenderInfo>* current_senders =
2911 GetRemoteSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07002912
Steve Anton4171afb2017-11-20 10:20:22 -08002913 // Find removed senders. I.e., senders where the sender id or ssrc don't match
deadbeeffac06552015-11-25 11:26:01 -08002914 // the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08002915 for (auto sender_it = current_senders->begin();
2916 sender_it != current_senders->end();
2917 /* incremented manually */) {
2918 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07002919 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08002920 cricket::GetStreamBySsrc(streams, info.first_ssrc);
2921 bool sender_exists = params && params->id == info.sender_id;
deadbeefbda7e0b2015-12-08 17:13:40 -08002922 // If this is a default track, and we still need it, don't remove it.
Steve Anton4171afb2017-11-20 10:20:22 -08002923 if ((info.stream_label == kDefaultStreamLabel && default_sender_needed) ||
2924 sender_exists) {
2925 ++sender_it;
deadbeefbda7e0b2015-12-08 17:13:40 -08002926 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08002927 OnRemoteSenderRemoved(info, media_type);
2928 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07002929 }
2930 }
2931
Steve Anton4171afb2017-11-20 10:20:22 -08002932 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07002933 for (const cricket::StreamParams& params : streams) {
2934 // The sync_label is the MediaStream label and the |stream.id| is the
Steve Anton4171afb2017-11-20 10:20:22 -08002935 // sender id.
deadbeefab9b2d12015-10-14 11:33:11 -07002936 const std::string& stream_label = params.sync_label;
Steve Anton4171afb2017-11-20 10:20:22 -08002937 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07002938 uint32_t ssrc = params.first_ssrc();
2939
2940 rtc::scoped_refptr<MediaStreamInterface> stream =
2941 remote_streams_->find(stream_label);
2942 if (!stream) {
2943 // This is a new MediaStream. Create a new remote MediaStream.
perkjd61bf802016-03-24 03:16:19 -07002944 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
2945 MediaStream::Create(stream_label));
deadbeefab9b2d12015-10-14 11:33:11 -07002946 remote_streams_->AddStream(stream);
2947 new_streams->AddStream(stream);
2948 }
2949
Steve Anton4171afb2017-11-20 10:20:22 -08002950 const RtpSenderInfo* sender_info =
2951 FindSenderInfo(*current_senders, stream_label, sender_id);
2952 if (!sender_info) {
2953 current_senders->push_back(RtpSenderInfo(stream_label, sender_id, ssrc));
2954 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07002955 }
2956 }
deadbeefbda7e0b2015-12-08 17:13:40 -08002957
Steve Anton4171afb2017-11-20 10:20:22 -08002958 // Add default sender if necessary.
2959 if (default_sender_needed) {
deadbeefbda7e0b2015-12-08 17:13:40 -08002960 rtc::scoped_refptr<MediaStreamInterface> default_stream =
2961 remote_streams_->find(kDefaultStreamLabel);
2962 if (!default_stream) {
2963 // Create the new default MediaStream.
perkjd61bf802016-03-24 03:16:19 -07002964 default_stream = MediaStreamProxy::Create(
2965 rtc::Thread::Current(), MediaStream::Create(kDefaultStreamLabel));
deadbeefbda7e0b2015-12-08 17:13:40 -08002966 remote_streams_->AddStream(default_stream);
2967 new_streams->AddStream(default_stream);
2968 }
Steve Anton4171afb2017-11-20 10:20:22 -08002969 std::string default_sender_id = (media_type == cricket::MEDIA_TYPE_AUDIO)
2970 ? kDefaultAudioSenderId
2971 : kDefaultVideoSenderId;
2972 const RtpSenderInfo* default_sender_info = FindSenderInfo(
2973 *current_senders, kDefaultStreamLabel, default_sender_id);
2974 if (!default_sender_info) {
2975 current_senders->push_back(
2976 RtpSenderInfo(kDefaultStreamLabel, default_sender_id, 0));
2977 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefbda7e0b2015-12-08 17:13:40 -08002978 }
2979 }
deadbeefab9b2d12015-10-14 11:33:11 -07002980}
2981
Steve Anton4171afb2017-11-20 10:20:22 -08002982void PeerConnection::OnRemoteSenderAdded(const RtpSenderInfo& sender_info,
2983 cricket::MediaType media_type) {
2984 MediaStreamInterface* stream =
2985 remote_streams_->find(sender_info.stream_label);
deadbeefab9b2d12015-10-14 11:33:11 -07002986
2987 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 10:20:22 -08002988 CreateAudioReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07002989 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 10:20:22 -08002990 CreateVideoReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07002991 } else {
nisseeb4ca4e2017-01-12 02:24:27 -08002992 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07002993 }
2994}
2995
Steve Anton4171afb2017-11-20 10:20:22 -08002996void PeerConnection::OnRemoteSenderRemoved(const RtpSenderInfo& sender_info,
2997 cricket::MediaType media_type) {
2998 MediaStreamInterface* stream =
2999 remote_streams_->find(sender_info.stream_label);
deadbeefab9b2d12015-10-14 11:33:11 -07003000
Henrik Boström933d8b02017-10-10 10:05:16 -07003001 rtc::scoped_refptr<RtpReceiverInterface> receiver;
deadbeefab9b2d12015-10-14 11:33:11 -07003002 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
perkjd61bf802016-03-24 03:16:19 -07003003 // When the MediaEngine audio channel is destroyed, the RemoteAudioSource
3004 // will be notified which will end the AudioRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08003005 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07003006 rtc::scoped_refptr<AudioTrackInterface> audio_track =
Steve Anton4171afb2017-11-20 10:20:22 -08003007 stream->FindAudioTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07003008 if (audio_track) {
deadbeefab9b2d12015-10-14 11:33:11 -07003009 stream->RemoveTrack(audio_track);
deadbeefab9b2d12015-10-14 11:33:11 -07003010 }
3011 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
perkjd61bf802016-03-24 03:16:19 -07003012 // Stopping or destroying a VideoRtpReceiver will end the
3013 // VideoRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08003014 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07003015 rtc::scoped_refptr<VideoTrackInterface> video_track =
Steve Anton4171afb2017-11-20 10:20:22 -08003016 stream->FindVideoTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07003017 if (video_track) {
perkjd61bf802016-03-24 03:16:19 -07003018 // There's no guarantee the track is still available, e.g. the track may
3019 // have been removed from the stream by an application.
deadbeefab9b2d12015-10-14 11:33:11 -07003020 stream->RemoveTrack(video_track);
deadbeefab9b2d12015-10-14 11:33:11 -07003021 }
3022 } else {
nisseede5da42017-01-12 05:15:36 -08003023 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07003024 }
Henrik Boström933d8b02017-10-10 10:05:16 -07003025 if (receiver) {
3026 observer_->OnRemoveTrack(receiver);
3027 }
deadbeefab9b2d12015-10-14 11:33:11 -07003028}
3029
3030void PeerConnection::UpdateEndedRemoteMediaStreams() {
3031 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams_to_remove;
3032 for (size_t i = 0; i < remote_streams_->count(); ++i) {
3033 MediaStreamInterface* stream = remote_streams_->at(i);
3034 if (stream->GetAudioTracks().empty() && stream->GetVideoTracks().empty()) {
3035 streams_to_remove.push_back(stream);
3036 }
3037 }
3038
Taylor Brandstetter98cde262016-05-31 13:02:21 -07003039 for (auto& stream : streams_to_remove) {
deadbeefab9b2d12015-10-14 11:33:11 -07003040 remote_streams_->RemoveStream(stream);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07003041 observer_->OnRemoveStream(std::move(stream));
deadbeefab9b2d12015-10-14 11:33:11 -07003042 }
3043}
3044
Steve Anton4171afb2017-11-20 10:20:22 -08003045void PeerConnection::UpdateLocalSenders(
deadbeefab9b2d12015-10-14 11:33:11 -07003046 const std::vector<cricket::StreamParams>& streams,
3047 cricket::MediaType media_type) {
Steve Anton4171afb2017-11-20 10:20:22 -08003048 std::vector<RtpSenderInfo>* current_senders = GetLocalSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07003049
3050 // Find removed tracks. I.e., tracks where the track id, stream label or ssrc
3051 // don't match the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08003052 for (auto sender_it = current_senders->begin();
3053 sender_it != current_senders->end();
3054 /* incremented manually */) {
3055 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07003056 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08003057 cricket::GetStreamBySsrc(streams, info.first_ssrc);
3058 if (!params || params->id != info.sender_id ||
deadbeefab9b2d12015-10-14 11:33:11 -07003059 params->sync_label != info.stream_label) {
Steve Anton4171afb2017-11-20 10:20:22 -08003060 OnLocalSenderRemoved(info, media_type);
3061 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07003062 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08003063 ++sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07003064 }
3065 }
3066
Steve Anton4171afb2017-11-20 10:20:22 -08003067 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07003068 for (const cricket::StreamParams& params : streams) {
3069 // The sync_label is the MediaStream label and the |stream.id| is the
Steve Anton4171afb2017-11-20 10:20:22 -08003070 // sender id.
deadbeefab9b2d12015-10-14 11:33:11 -07003071 const std::string& stream_label = params.sync_label;
Steve Anton4171afb2017-11-20 10:20:22 -08003072 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07003073 uint32_t ssrc = params.first_ssrc();
Steve Anton4171afb2017-11-20 10:20:22 -08003074 const RtpSenderInfo* sender_info =
3075 FindSenderInfo(*current_senders, stream_label, sender_id);
3076 if (!sender_info) {
3077 current_senders->push_back(RtpSenderInfo(stream_label, sender_id, ssrc));
3078 OnLocalSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07003079 }
3080 }
3081}
3082
Steve Anton4171afb2017-11-20 10:20:22 -08003083void PeerConnection::OnLocalSenderAdded(const RtpSenderInfo& sender_info,
3084 cricket::MediaType media_type) {
3085 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08003086 if (!sender) {
Steve Anton4171afb2017-11-20 10:20:22 -08003087 RTC_LOG(LS_WARNING) << "An unknown RtpSender with id "
3088 << sender_info.sender_id
Mirko Bonadei675513b2017-11-09 11:09:25 +01003089 << " has been configured in the local description.";
deadbeefab9b2d12015-10-14 11:33:11 -07003090 return;
3091 }
3092
deadbeeffac06552015-11-25 11:26:01 -08003093 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003094 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
3095 << " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08003096 return;
deadbeefab9b2d12015-10-14 11:33:11 -07003097 }
deadbeeffac06552015-11-25 11:26:01 -08003098
Steve Anton4171afb2017-11-20 10:20:22 -08003099 sender->internal()->set_stream_id(sender_info.stream_label);
3100 sender->internal()->SetSsrc(sender_info.first_ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07003101}
3102
Steve Anton4171afb2017-11-20 10:20:22 -08003103void PeerConnection::OnLocalSenderRemoved(const RtpSenderInfo& sender_info,
3104 cricket::MediaType media_type) {
3105 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08003106 if (!sender) {
3107 // This is the normal case. I.e., RemoveStream has been called and the
deadbeefab9b2d12015-10-14 11:33:11 -07003108 // SessionDescriptions has been renegotiated.
3109 return;
3110 }
deadbeeffac06552015-11-25 11:26:01 -08003111
3112 // A sender has been removed from the SessionDescription but it's still
3113 // associated with the PeerConnection. This only occurs if the SDP doesn't
3114 // match with the calls to CreateSender, AddStream and RemoveStream.
3115 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003116 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
3117 << " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08003118 return;
deadbeefab9b2d12015-10-14 11:33:11 -07003119 }
deadbeeffac06552015-11-25 11:26:01 -08003120
Steve Anton4171afb2017-11-20 10:20:22 -08003121 sender->internal()->SetSsrc(0);
deadbeefab9b2d12015-10-14 11:33:11 -07003122}
3123
3124void PeerConnection::UpdateLocalRtpDataChannels(
3125 const cricket::StreamParamsVec& streams) {
3126 std::vector<std::string> existing_channels;
3127
3128 // Find new and active data channels.
3129 for (const cricket::StreamParams& params : streams) {
3130 // |it->sync_label| is actually the data channel label. The reason is that
3131 // we use the same naming of data channels as we do for
3132 // MediaStreams and Tracks.
3133 // For MediaStreams, the sync_label is the MediaStream label and the
3134 // track label is the same as |streamid|.
3135 const std::string& channel_label = params.sync_label;
3136 auto data_channel_it = rtp_data_channels_.find(channel_label);
nisse7ce109a2017-01-31 00:57:56 -08003137 if (data_channel_it == rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003138 RTC_LOG(LS_ERROR) << "channel label not found";
deadbeefab9b2d12015-10-14 11:33:11 -07003139 continue;
3140 }
3141 // Set the SSRC the data channel should use for sending.
3142 data_channel_it->second->SetSendSsrc(params.first_ssrc());
3143 existing_channels.push_back(data_channel_it->first);
3144 }
3145
3146 UpdateClosingRtpDataChannels(existing_channels, true);
3147}
3148
3149void PeerConnection::UpdateRemoteRtpDataChannels(
3150 const cricket::StreamParamsVec& streams) {
3151 std::vector<std::string> existing_channels;
3152
3153 // Find new and active data channels.
3154 for (const cricket::StreamParams& params : streams) {
3155 // The data channel label is either the mslabel or the SSRC if the mslabel
3156 // does not exist. Ex a=ssrc:444330170 mslabel:test1.
3157 std::string label = params.sync_label.empty()
3158 ? rtc::ToString(params.first_ssrc())
3159 : params.sync_label;
3160 auto data_channel_it = rtp_data_channels_.find(label);
3161 if (data_channel_it == rtp_data_channels_.end()) {
3162 // This is a new data channel.
3163 CreateRemoteRtpDataChannel(label, params.first_ssrc());
3164 } else {
3165 data_channel_it->second->SetReceiveSsrc(params.first_ssrc());
3166 }
3167 existing_channels.push_back(label);
3168 }
3169
3170 UpdateClosingRtpDataChannels(existing_channels, false);
3171}
3172
3173void PeerConnection::UpdateClosingRtpDataChannels(
3174 const std::vector<std::string>& active_channels,
3175 bool is_local_update) {
3176 auto it = rtp_data_channels_.begin();
3177 while (it != rtp_data_channels_.end()) {
3178 DataChannel* data_channel = it->second;
3179 if (std::find(active_channels.begin(), active_channels.end(),
3180 data_channel->label()) != active_channels.end()) {
3181 ++it;
3182 continue;
3183 }
3184
3185 if (is_local_update) {
3186 data_channel->SetSendSsrc(0);
3187 } else {
3188 data_channel->RemotePeerRequestClose();
3189 }
3190
3191 if (data_channel->state() == DataChannel::kClosed) {
3192 rtp_data_channels_.erase(it);
3193 it = rtp_data_channels_.begin();
3194 } else {
3195 ++it;
3196 }
3197 }
3198}
3199
3200void PeerConnection::CreateRemoteRtpDataChannel(const std::string& label,
3201 uint32_t remote_ssrc) {
3202 rtc::scoped_refptr<DataChannel> channel(
3203 InternalCreateDataChannel(label, nullptr));
3204 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003205 RTC_LOG(LS_WARNING) << "Remote peer requested a DataChannel but"
3206 << "CreateDataChannel failed.";
deadbeefab9b2d12015-10-14 11:33:11 -07003207 return;
3208 }
3209 channel->SetReceiveSsrc(remote_ssrc);
deadbeefa601f5c2016-06-06 14:27:39 -07003210 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
3211 DataChannelProxy::Create(signaling_thread(), channel);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07003212 observer_->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07003213}
3214
3215rtc::scoped_refptr<DataChannel> PeerConnection::InternalCreateDataChannel(
3216 const std::string& label,
3217 const InternalDataChannelInit* config) {
3218 if (IsClosed()) {
3219 return nullptr;
3220 }
Steve Anton75737c02017-11-06 10:37:17 -08003221 if (data_channel_type() == cricket::DCT_NONE) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003222 RTC_LOG(LS_ERROR)
deadbeefab9b2d12015-10-14 11:33:11 -07003223 << "InternalCreateDataChannel: Data is not supported in this call.";
3224 return nullptr;
3225 }
3226 InternalDataChannelInit new_config =
3227 config ? (*config) : InternalDataChannelInit();
Steve Anton75737c02017-11-06 10:37:17 -08003228 if (data_channel_type() == cricket::DCT_SCTP) {
deadbeefab9b2d12015-10-14 11:33:11 -07003229 if (new_config.id < 0) {
3230 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08003231 if ((GetSctpSslRole(&role)) &&
deadbeefab9b2d12015-10-14 11:33:11 -07003232 !sid_allocator_.AllocateSid(role, &new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003233 RTC_LOG(LS_ERROR)
3234 << "No id can be allocated for the SCTP data channel.";
deadbeefab9b2d12015-10-14 11:33:11 -07003235 return nullptr;
3236 }
3237 } else if (!sid_allocator_.ReserveSid(new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003238 RTC_LOG(LS_ERROR) << "Failed to create a SCTP data channel "
3239 << "because the id is already in use or out of range.";
deadbeefab9b2d12015-10-14 11:33:11 -07003240 return nullptr;
3241 }
3242 }
3243
Steve Anton75737c02017-11-06 10:37:17 -08003244 rtc::scoped_refptr<DataChannel> channel(
3245 DataChannel::Create(this, data_channel_type(), label, new_config));
deadbeefab9b2d12015-10-14 11:33:11 -07003246 if (!channel) {
3247 sid_allocator_.ReleaseSid(new_config.id);
3248 return nullptr;
3249 }
3250
3251 if (channel->data_channel_type() == cricket::DCT_RTP) {
3252 if (rtp_data_channels_.find(channel->label()) != rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003253 RTC_LOG(LS_ERROR) << "DataChannel with label " << channel->label()
3254 << " already exists.";
deadbeefab9b2d12015-10-14 11:33:11 -07003255 return nullptr;
3256 }
3257 rtp_data_channels_[channel->label()] = channel;
3258 } else {
3259 RTC_DCHECK(channel->data_channel_type() == cricket::DCT_SCTP);
3260 sctp_data_channels_.push_back(channel);
3261 channel->SignalClosed.connect(this,
3262 &PeerConnection::OnSctpDataChannelClosed);
3263 }
3264
hbos82ebe022016-11-14 01:41:09 -08003265 SignalDataChannelCreated(channel.get());
deadbeefab9b2d12015-10-14 11:33:11 -07003266 return channel;
3267}
3268
3269bool PeerConnection::HasDataChannels() const {
3270 return !rtp_data_channels_.empty() || !sctp_data_channels_.empty();
3271}
3272
3273void PeerConnection::AllocateSctpSids(rtc::SSLRole role) {
3274 for (const auto& channel : sctp_data_channels_) {
3275 if (channel->id() < 0) {
3276 int sid;
3277 if (!sid_allocator_.AllocateSid(role, &sid)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003278 RTC_LOG(LS_ERROR) << "Failed to allocate SCTP sid.";
deadbeefab9b2d12015-10-14 11:33:11 -07003279 continue;
3280 }
3281 channel->SetSctpSid(sid);
3282 }
3283 }
3284}
3285
3286void PeerConnection::OnSctpDataChannelClosed(DataChannel* channel) {
deadbeefbd292462015-12-14 18:15:29 -08003287 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeefab9b2d12015-10-14 11:33:11 -07003288 for (auto it = sctp_data_channels_.begin(); it != sctp_data_channels_.end();
3289 ++it) {
3290 if (it->get() == channel) {
3291 if (channel->id() >= 0) {
3292 sid_allocator_.ReleaseSid(channel->id());
3293 }
deadbeefbd292462015-12-14 18:15:29 -08003294 // Since this method is triggered by a signal from the DataChannel,
3295 // we can't free it directly here; we need to free it asynchronously.
3296 sctp_data_channels_to_free_.push_back(*it);
deadbeefab9b2d12015-10-14 11:33:11 -07003297 sctp_data_channels_.erase(it);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07003298 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_FREE_DATACHANNELS,
3299 nullptr);
deadbeefab9b2d12015-10-14 11:33:11 -07003300 return;
3301 }
3302 }
3303}
3304
deadbeefab9b2d12015-10-14 11:33:11 -07003305void PeerConnection::OnDataChannelDestroyed() {
3306 // Use a temporary copy of the RTP/SCTP DataChannel list because the
3307 // DataChannel may callback to us and try to modify the list.
3308 std::map<std::string, rtc::scoped_refptr<DataChannel>> temp_rtp_dcs;
3309 temp_rtp_dcs.swap(rtp_data_channels_);
3310 for (const auto& kv : temp_rtp_dcs) {
3311 kv.second->OnTransportChannelDestroyed();
3312 }
3313
3314 std::vector<rtc::scoped_refptr<DataChannel>> temp_sctp_dcs;
3315 temp_sctp_dcs.swap(sctp_data_channels_);
3316 for (const auto& channel : temp_sctp_dcs) {
3317 channel->OnTransportChannelDestroyed();
3318 }
3319}
3320
3321void PeerConnection::OnDataChannelOpenMessage(
3322 const std::string& label,
3323 const InternalDataChannelInit& config) {
3324 rtc::scoped_refptr<DataChannel> channel(
3325 InternalCreateDataChannel(label, &config));
3326 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003327 RTC_LOG(LS_ERROR) << "Failed to create DataChannel from the OPEN message.";
deadbeefab9b2d12015-10-14 11:33:11 -07003328 return;
3329 }
3330
deadbeefa601f5c2016-06-06 14:27:39 -07003331 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
3332 DataChannelProxy::Create(signaling_thread(), channel);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07003333 observer_->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07003334}
3335
Steve Anton4171afb2017-11-20 10:20:22 -08003336rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3337PeerConnection::GetAudioTransceiver() const {
3338 // This method only works with Plan B SDP, where there is a single
3339 // audio/video transceiver.
3340 RTC_DCHECK(!IsUnifiedPlan());
3341 for (auto transceiver : transceivers_) {
3342 if (transceiver->internal()->media_type() == cricket::MEDIA_TYPE_AUDIO) {
3343 return transceiver;
3344 }
3345 }
3346 RTC_NOTREACHED();
3347 return nullptr;
3348}
3349
3350rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3351PeerConnection::GetVideoTransceiver() const {
3352 // This method only works with Plan B SDP, where there is a single
3353 // audio/video transceiver.
3354 RTC_DCHECK(!IsUnifiedPlan());
3355 for (auto transceiver : transceivers_) {
3356 if (transceiver->internal()->media_type() == cricket::MEDIA_TYPE_VIDEO) {
3357 return transceiver;
3358 }
3359 }
3360 RTC_NOTREACHED();
3361 return nullptr;
3362}
3363
3364// TODO(bugs.webrtc.org/7600): Remove this when multiple transceivers with
3365// individual transceiver directions are supported.
zhihuang1c378ed2017-08-17 14:10:50 -07003366bool PeerConnection::HasRtpSender(cricket::MediaType type) const {
Steve Anton4171afb2017-11-20 10:20:22 -08003367 switch (type) {
3368 case cricket::MEDIA_TYPE_AUDIO:
3369 return !GetAudioTransceiver()->internal()->senders().empty();
3370 case cricket::MEDIA_TYPE_VIDEO:
3371 return !GetVideoTransceiver()->internal()->senders().empty();
3372 case cricket::MEDIA_TYPE_DATA:
3373 return false;
3374 }
3375 RTC_NOTREACHED();
3376 return false;
zhihuang1c378ed2017-08-17 14:10:50 -07003377}
3378
Steve Anton4171afb2017-11-20 10:20:22 -08003379rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
3380PeerConnection::FindSenderForTrack(MediaStreamTrackInterface* track) const {
3381 for (auto transceiver : transceivers_) {
3382 for (auto sender : transceiver->internal()->senders()) {
3383 if (sender->track() == track) {
3384 return sender;
3385 }
3386 }
3387 }
3388 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08003389}
3390
Steve Anton4171afb2017-11-20 10:20:22 -08003391rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
3392PeerConnection::FindSenderById(const std::string& sender_id) const {
3393 for (auto transceiver : transceivers_) {
3394 for (auto sender : transceiver->internal()->senders()) {
3395 if (sender->id() == sender_id) {
3396 return sender;
3397 }
3398 }
3399 }
3400 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07003401}
3402
Steve Anton4171afb2017-11-20 10:20:22 -08003403rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
3404PeerConnection::FindReceiverById(const std::string& receiver_id) const {
3405 for (auto transceiver : transceivers_) {
3406 for (auto receiver : transceiver->internal()->receivers()) {
3407 if (receiver->id() == receiver_id) {
3408 return receiver;
3409 }
3410 }
3411 }
3412 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07003413}
3414
Steve Anton4171afb2017-11-20 10:20:22 -08003415std::vector<PeerConnection::RtpSenderInfo>*
3416PeerConnection::GetRemoteSenderInfos(cricket::MediaType media_type) {
3417 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
3418 media_type == cricket::MEDIA_TYPE_VIDEO);
3419 return (media_type == cricket::MEDIA_TYPE_AUDIO)
3420 ? &remote_audio_sender_infos_
3421 : &remote_video_sender_infos_;
3422}
3423
3424std::vector<PeerConnection::RtpSenderInfo>* PeerConnection::GetLocalSenderInfos(
deadbeefab9b2d12015-10-14 11:33:11 -07003425 cricket::MediaType media_type) {
3426 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
3427 media_type == cricket::MEDIA_TYPE_VIDEO);
Steve Anton4171afb2017-11-20 10:20:22 -08003428 return (media_type == cricket::MEDIA_TYPE_AUDIO) ? &local_audio_sender_infos_
3429 : &local_video_sender_infos_;
deadbeefab9b2d12015-10-14 11:33:11 -07003430}
3431
Steve Anton4171afb2017-11-20 10:20:22 -08003432const PeerConnection::RtpSenderInfo* PeerConnection::FindSenderInfo(
3433 const std::vector<PeerConnection::RtpSenderInfo>& infos,
deadbeefab9b2d12015-10-14 11:33:11 -07003434 const std::string& stream_label,
Steve Anton4171afb2017-11-20 10:20:22 -08003435 const std::string sender_id) const {
3436 for (const RtpSenderInfo& sender_info : infos) {
3437 if (sender_info.stream_label == stream_label &&
3438 sender_info.sender_id == sender_id) {
3439 return &sender_info;
deadbeefab9b2d12015-10-14 11:33:11 -07003440 }
3441 }
3442 return nullptr;
3443}
3444
3445DataChannel* PeerConnection::FindDataChannelBySid(int sid) const {
3446 for (const auto& channel : sctp_data_channels_) {
3447 if (channel->id() == sid) {
3448 return channel;
3449 }
3450 }
3451 return nullptr;
3452}
3453
deadbeef91dd5672016-05-18 16:55:30 -07003454bool PeerConnection::InitializePortAllocator_n(
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003455 const RTCConfiguration& configuration) {
3456 cricket::ServerAddresses stun_servers;
3457 std::vector<cricket::RelayServerConfig> turn_servers;
deadbeef293e9262017-01-11 12:28:30 -08003458 if (ParseIceServers(configuration.servers, &stun_servers, &turn_servers) !=
3459 RTCErrorType::NONE) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003460 return false;
3461 }
3462
Taylor Brandstetterf8e65772016-06-27 17:20:15 -07003463 port_allocator_->Initialize();
3464
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003465 // To handle both internal and externally created port allocator, we will
3466 // enable BUNDLE here.
3467 int portallocator_flags = port_allocator_->flags();
3468 portallocator_flags |= cricket::PORTALLOCATOR_ENABLE_SHARED_SOCKET |
zhihuangb09b3f92017-03-07 14:40:51 -08003469 cricket::PORTALLOCATOR_ENABLE_IPV6 |
3470 cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI;
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003471 // If the disable-IPv6 flag was specified, we'll not override it
3472 // by experiment.
3473 if (configuration.disable_ipv6) {
3474 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
sprangc1b57a12017-02-28 08:50:47 -08003475 } else if (webrtc::field_trial::FindFullName("WebRTC-IPv6Default")
3476 .find("Disabled") == 0) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003477 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
3478 }
3479
zhihuangb09b3f92017-03-07 14:40:51 -08003480 if (configuration.disable_ipv6_on_wifi) {
3481 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI);
Mirko Bonadei675513b2017-11-09 11:09:25 +01003482 RTC_LOG(LS_INFO) << "IPv6 candidates on Wi-Fi are disabled.";
zhihuangb09b3f92017-03-07 14:40:51 -08003483 }
3484
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003485 if (configuration.tcp_candidate_policy == kTcpCandidatePolicyDisabled) {
3486 portallocator_flags |= cricket::PORTALLOCATOR_DISABLE_TCP;
Mirko Bonadei675513b2017-11-09 11:09:25 +01003487 RTC_LOG(LS_INFO) << "TCP candidates are disabled.";
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003488 }
3489
honghaiz60347052016-05-31 18:29:12 -07003490 if (configuration.candidate_network_policy ==
3491 kCandidateNetworkPolicyLowCost) {
3492 portallocator_flags |= cricket::PORTALLOCATOR_DISABLE_COSTLY_NETWORKS;
Mirko Bonadei675513b2017-11-09 11:09:25 +01003493 RTC_LOG(LS_INFO) << "Do not gather candidates on high-cost networks";
honghaiz60347052016-05-31 18:29:12 -07003494 }
3495
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003496 port_allocator_->set_flags(portallocator_flags);
3497 // No step delay is used while allocating ports.
3498 port_allocator_->set_step_delay(cricket::kMinimumStepDelay);
3499 port_allocator_->set_candidate_filter(
3500 ConvertIceTransportTypeToCandidateFilter(configuration.type));
deadbeefd21eab32017-07-26 16:50:11 -07003501 port_allocator_->set_max_ipv6_networks(configuration.max_ipv6_networks);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003502
3503 // Call this last since it may create pooled allocator sessions using the
3504 // properties set above.
3505 port_allocator_->SetConfiguration(stun_servers, turn_servers,
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -07003506 configuration.ice_candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02003507 configuration.prune_turn_ports,
3508 configuration.turn_customizer);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003509 return true;
3510}
3511
deadbeef91dd5672016-05-18 16:55:30 -07003512bool PeerConnection::ReconfigurePortAllocator_n(
deadbeef293e9262017-01-11 12:28:30 -08003513 const cricket::ServerAddresses& stun_servers,
3514 const std::vector<cricket::RelayServerConfig>& turn_servers,
3515 IceTransportsType type,
3516 int candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02003517 bool prune_turn_ports,
3518 webrtc::TurnCustomizer* turn_customizer) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003519 port_allocator_->set_candidate_filter(
deadbeef293e9262017-01-11 12:28:30 -08003520 ConvertIceTransportTypeToCandidateFilter(type));
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003521 // Call this last since it may create pooled allocator sessions using the
3522 // candidate filter set above.
deadbeef6de92f92016-12-12 18:49:32 -08003523 return port_allocator_->SetConfiguration(
Jonas Orelandbdcee282017-10-10 14:01:40 +02003524 stun_servers, turn_servers, candidate_pool_size, prune_turn_ports,
3525 turn_customizer);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003526}
3527
Steve Antonba818672017-11-06 10:21:57 -08003528cricket::ChannelManager* PeerConnection::channel_manager() const {
3529 return factory_->channel_manager();
3530}
3531
3532MetricsObserverInterface* PeerConnection::metrics_observer() const {
3533 return uma_observer_;
3534}
3535
Elad Alon99c3fe52017-10-13 16:29:40 +02003536bool PeerConnection::StartRtcEventLog_w(
Bjorn Tereliusde939432017-11-20 17:38:14 +01003537 std::unique_ptr<RtcEventLogOutput> output,
3538 int64_t output_period_ms) {
zhihuang77985012017-02-07 15:45:16 -08003539 if (!event_log_) {
3540 return false;
3541 }
Bjorn Tereliusde939432017-11-20 17:38:14 +01003542 return event_log_->StartLogging(std::move(output), output_period_ms);
ivoc14d5dbe2016-07-04 07:06:55 -07003543}
3544
3545void PeerConnection::StopRtcEventLog_w() {
zhihuang77985012017-02-07 15:45:16 -08003546 if (event_log_) {
3547 event_log_->StopLogging();
3548 }
ivoc14d5dbe2016-07-04 07:06:55 -07003549}
nisseeaabdf62017-05-05 02:23:02 -07003550
Steve Anton75737c02017-11-06 10:37:17 -08003551cricket::BaseChannel* PeerConnection::GetChannel(
3552 const std::string& content_name) {
3553 if (voice_channel() && voice_channel()->content_name() == content_name) {
3554 return voice_channel();
3555 }
3556 if (video_channel() && video_channel()->content_name() == content_name) {
3557 return video_channel();
3558 }
3559 if (rtp_data_channel() &&
3560 rtp_data_channel()->content_name() == content_name) {
3561 return rtp_data_channel();
3562 }
3563 return nullptr;
3564}
3565
3566bool PeerConnection::GetSctpSslRole(rtc::SSLRole* role) {
3567 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003568 RTC_LOG(LS_INFO)
3569 << "Local and Remote descriptions must be applied to get the "
3570 << "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08003571 return false;
3572 }
3573 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003574 RTC_LOG(LS_INFO) << "Non-rejected SCTP m= section is needed to get the "
3575 << "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08003576 return false;
3577 }
3578
3579 return transport_controller_->GetSslRole(*sctp_transport_name_, role);
3580}
3581
3582bool PeerConnection::GetSslRole(const std::string& content_name,
3583 rtc::SSLRole* role) {
3584 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003585 RTC_LOG(LS_INFO)
3586 << "Local and Remote descriptions must be applied to get the "
3587 << "SSL Role of the session.";
Steve Anton75737c02017-11-06 10:37:17 -08003588 return false;
3589 }
3590
3591 return transport_controller_->GetSslRole(GetTransportName(content_name),
3592 role);
3593}
3594
Steve Anton75737c02017-11-06 10:37:17 -08003595// TODO(steveanton): Eventually it'd be nice to store the channels as a single
3596// vector of BaseChannel pointers instead of separate voice and video channel
3597// vectors. At that point, this will become a simple getter.
3598std::vector<cricket::BaseChannel*> PeerConnection::Channels() const {
3599 std::vector<cricket::BaseChannel*> channels;
Steve Anton4171afb2017-11-20 10:20:22 -08003600 if (voice_channel()) {
3601 channels.push_back(voice_channel());
3602 }
3603 if (video_channel()) {
3604 channels.push_back(video_channel());
3605 }
Steve Anton75737c02017-11-06 10:37:17 -08003606 if (rtp_data_channel_) {
3607 channels.push_back(rtp_data_channel_);
3608 }
3609 return channels;
3610}
3611
Steve Antonf8470812017-12-04 10:46:21 -08003612void PeerConnection::SetSessionError(SessionError error,
3613 const std::string& error_desc) {
3614 RTC_DCHECK_RUN_ON(signaling_thread());
3615 if (error != session_error_) {
3616 session_error_ = error;
3617 session_error_desc_ = error_desc;
Steve Anton75737c02017-11-06 10:37:17 -08003618 }
3619}
3620
Steve Anton3828c062017-12-06 10:34:51 -08003621RTCError PeerConnection::UpdateSessionState(SdpType type,
Steve Anton8a006912017-12-04 15:25:56 -08003622 cricket::ContentSource source) {
3623 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08003624
3625 // If there's already a pending error then no state transition should happen.
3626 // But all call-sites should be verifying this before calling us!
Steve Antonf8470812017-12-04 10:46:21 -08003627 RTC_DCHECK(session_error() == SessionError::kNone);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08003628
3629 // If this is an answer then we know whether to BUNDLE or not. If both the
3630 // local and remote side have agreed to BUNDLE, go ahead and enable it.
Steve Anton3828c062017-12-06 10:34:51 -08003631 if (type == SdpType::kAnswer) {
Steve Anton75737c02017-11-06 10:37:17 -08003632 const cricket::ContentGroup* local_bundle =
3633 local_description()->description()->GetGroupByName(
3634 cricket::GROUP_TYPE_BUNDLE);
3635 const cricket::ContentGroup* remote_bundle =
3636 remote_description()->description()->GetGroupByName(
3637 cricket::GROUP_TYPE_BUNDLE);
3638 if (local_bundle && remote_bundle) {
3639 // The answerer decides the transport to bundle on.
3640 const cricket::ContentGroup* answer_bundle =
3641 (source == cricket::CS_LOCAL ? local_bundle : remote_bundle);
3642 if (!EnableBundle(*answer_bundle)) {
Steve Anton8a006912017-12-04 15:25:56 -08003643 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3644 kEnableBundleFailed);
Steve Anton75737c02017-11-06 10:37:17 -08003645 }
3646 }
Steve Anton75737c02017-11-06 10:37:17 -08003647 }
Steve Anton6d6a2ae2017-12-04 17:19:47 -08003648
3649 // Only push down the transport description after potentially enabling BUNDLE;
3650 // we don't want to push down a description on a transport about to be
3651 // destroyed.
Steve Anton3828c062017-12-06 10:34:51 -08003652 RTCError error = PushdownTransportDescription(source, type);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08003653 if (!error.ok()) {
3654 return error;
3655 }
3656
3657 // If this is answer-ish we're ready to let media flow.
Steve Anton3828c062017-12-06 10:34:51 -08003658 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Antoned10bd92017-12-05 10:52:59 -08003659 EnableSending();
Steve Anton6d6a2ae2017-12-04 17:19:47 -08003660 }
3661
3662 // Update the signaling state according to the specified state machine (see
3663 // https://w3c.github.io/webrtc-pc/#rtcsignalingstate-enum).
Steve Anton3828c062017-12-06 10:34:51 -08003664 if (type == SdpType::kOffer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08003665 ChangeSignalingState(source == cricket::CS_LOCAL
3666 ? PeerConnectionInterface::kHaveLocalOffer
3667 : PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton3828c062017-12-06 10:34:51 -08003668 } else if (type == SdpType::kPrAnswer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08003669 ChangeSignalingState(source == cricket::CS_LOCAL
3670 ? PeerConnectionInterface::kHaveLocalPrAnswer
3671 : PeerConnectionInterface::kHaveRemotePrAnswer);
3672 } else {
Steve Anton3828c062017-12-06 10:34:51 -08003673 RTC_DCHECK(type == SdpType::kAnswer);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08003674 ChangeSignalingState(PeerConnectionInterface::kStable);
3675 }
3676
3677 // Update internal objects according to the session description's media
3678 // descriptions.
Steve Anton3828c062017-12-06 10:34:51 -08003679 error = PushdownMediaDescription(type, source);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08003680 if (!error.ok()) {
3681 SetSessionError(SessionError::kContent, error.message());
3682 }
3683 if (session_error() != SessionError::kNone) {
3684 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
3685 }
3686
Steve Anton8a006912017-12-04 15:25:56 -08003687 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08003688}
3689
Steve Anton8a006912017-12-04 15:25:56 -08003690RTCError PeerConnection::PushdownMediaDescription(
Steve Anton3828c062017-12-06 10:34:51 -08003691 SdpType type,
Steve Anton8a006912017-12-04 15:25:56 -08003692 cricket::ContentSource source) {
Steve Antoned10bd92017-12-05 10:52:59 -08003693 const SessionDescriptionInterface* sdesc =
3694 (source == cricket::CS_LOCAL ? local_description()
3695 : remote_description());
Steve Anton75737c02017-11-06 10:37:17 -08003696 RTC_DCHECK(sdesc);
Steve Antoned10bd92017-12-05 10:52:59 -08003697
3698 // Push down the new SDP media section for each audio/video transceiver.
3699 for (auto transceiver : transceivers_) {
Steve Anton75737c02017-11-06 10:37:17 -08003700 const ContentInfo* content_info =
Steve Antoned10bd92017-12-05 10:52:59 -08003701 FindMediaSectionForTransceiver(transceiver, sdesc);
3702 cricket::BaseChannel* channel = transceiver->internal()->channel();
3703 if (!channel || !content_info || content_info->rejected) {
Steve Anton75737c02017-11-06 10:37:17 -08003704 continue;
3705 }
3706 const MediaContentDescription* content_desc =
3707 static_cast<const MediaContentDescription*>(content_info->description);
Steve Antoned10bd92017-12-05 10:52:59 -08003708 if (!content_desc) {
3709 continue;
3710 }
3711 std::string error;
3712 bool success =
3713 (source == cricket::CS_LOCAL)
Steve Anton3828c062017-12-06 10:34:51 -08003714 ? channel->SetLocalContent(content_desc, type, &error)
3715 : channel->SetRemoteContent(content_desc, type, &error);
Steve Antoned10bd92017-12-05 10:52:59 -08003716 if (!success) {
3717 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, std::move(error));
3718 }
3719 }
3720
3721 // If using the RtpDataChannel, push down the new SDP section for it too.
3722 if (rtp_data_channel_) {
3723 const ContentInfo* data_content =
3724 cricket::GetFirstDataContent(sdesc->description());
3725 if (data_content && !data_content->rejected) {
3726 const MediaContentDescription* data_desc =
3727 static_cast<const MediaContentDescription*>(
3728 data_content->description);
3729 if (data_desc) {
3730 std::string error;
3731 bool success =
3732 (source == cricket::CS_LOCAL)
Steve Anton3828c062017-12-06 10:34:51 -08003733 ? rtp_data_channel_->SetLocalContent(data_desc, type, &error)
3734 : rtp_data_channel_->SetRemoteContent(data_desc, type,
Steve Antoned10bd92017-12-05 10:52:59 -08003735 &error);
3736 if (!success) {
3737 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3738 std::move(error));
3739 }
Steve Anton75737c02017-11-06 10:37:17 -08003740 }
3741 }
3742 }
Steve Antoned10bd92017-12-05 10:52:59 -08003743
Steve Anton75737c02017-11-06 10:37:17 -08003744 // Need complete offer/answer with an SCTP m= section before starting SCTP,
3745 // according to https://tools.ietf.org/html/draft-ietf-mmusic-sctp-sdp-19
3746 if (sctp_transport_ && local_description() && remote_description() &&
3747 cricket::GetFirstDataContent(local_description()->description()) &&
3748 cricket::GetFirstDataContent(remote_description()->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08003749 bool success = network_thread()->Invoke<bool>(
Steve Anton75737c02017-11-06 10:37:17 -08003750 RTC_FROM_HERE,
3751 rtc::Bind(&PeerConnection::PushdownSctpParameters_n, this, source));
Steve Anton8a006912017-12-04 15:25:56 -08003752 if (!success) {
3753 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
3754 "Failed to push down SCTP parameters.");
3755 }
Steve Anton75737c02017-11-06 10:37:17 -08003756 }
Steve Antoned10bd92017-12-05 10:52:59 -08003757
Steve Anton8a006912017-12-04 15:25:56 -08003758 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08003759}
3760
3761bool PeerConnection::PushdownSctpParameters_n(cricket::ContentSource source) {
3762 RTC_DCHECK(network_thread()->IsCurrent());
3763 RTC_DCHECK(local_description());
3764 RTC_DCHECK(remote_description());
3765 // Apply the SCTP port (which is hidden inside a DataCodec structure...)
3766 // When we support "max-message-size", that would also be pushed down here.
3767 return sctp_transport_->Start(
3768 GetSctpPort(local_description()->description()),
3769 GetSctpPort(remote_description()->description()));
3770}
3771
Steve Anton8a006912017-12-04 15:25:56 -08003772RTCError PeerConnection::PushdownTransportDescription(
3773 cricket::ContentSource source,
Steve Anton3828c062017-12-06 10:34:51 -08003774 SdpType type) {
Steve Anton8a006912017-12-04 15:25:56 -08003775 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08003776
Steve Anton8a006912017-12-04 15:25:56 -08003777 const SessionDescriptionInterface* sdesc =
3778 (source == cricket::CS_LOCAL ? local_description()
3779 : remote_description());
3780 RTC_DCHECK(sdesc);
3781 for (const cricket::TransportInfo& tinfo :
3782 sdesc->description()->transport_infos()) {
3783 std::string error;
3784 bool success;
3785 if (source == cricket::CS_LOCAL) {
3786 success = transport_controller_->SetLocalTransportDescription(
Steve Anton3828c062017-12-06 10:34:51 -08003787 tinfo.content_name, tinfo.description, type, &error);
Steve Anton8a006912017-12-04 15:25:56 -08003788 } else {
3789 success = transport_controller_->SetRemoteTransportDescription(
Steve Anton3828c062017-12-06 10:34:51 -08003790 tinfo.content_name, tinfo.description, type, &error);
Steve Anton8a006912017-12-04 15:25:56 -08003791 }
3792 if (!success) {
3793 LOG_AND_RETURN_ERROR(
3794 RTCErrorType::INVALID_PARAMETER,
3795 "Failed to push down transport description: " + error);
Steve Anton75737c02017-11-06 10:37:17 -08003796 }
3797 }
3798
Steve Anton8a006912017-12-04 15:25:56 -08003799 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08003800}
3801
3802bool PeerConnection::GetTransportDescription(
3803 const SessionDescription* description,
3804 const std::string& content_name,
3805 cricket::TransportDescription* tdesc) {
3806 if (!description || !tdesc) {
3807 return false;
3808 }
3809 const TransportInfo* transport_info =
3810 description->GetTransportInfoByName(content_name);
3811 if (!transport_info) {
3812 return false;
3813 }
3814 *tdesc = transport_info->description;
3815 return true;
3816}
3817
3818bool PeerConnection::EnableBundle(const cricket::ContentGroup& bundle) {
3819 const std::string* first_content_name = bundle.FirstContentName();
3820 if (!first_content_name) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003821 RTC_LOG(LS_WARNING) << "Tried to BUNDLE with no contents.";
Steve Anton75737c02017-11-06 10:37:17 -08003822 return false;
3823 }
3824 const std::string& transport_name = *first_content_name;
3825
3826 auto maybe_set_transport = [this, bundle,
3827 transport_name](cricket::BaseChannel* ch) {
3828 if (!ch || !bundle.HasContentName(ch->content_name())) {
Steve Antoned10bd92017-12-05 10:52:59 -08003829 return;
Steve Anton75737c02017-11-06 10:37:17 -08003830 }
3831
3832 std::string old_transport_name = ch->transport_name();
3833 if (old_transport_name == transport_name) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003834 RTC_LOG(LS_INFO) << "BUNDLE already enabled for " << ch->content_name()
3835 << " on " << transport_name << ".";
Steve Antoned10bd92017-12-05 10:52:59 -08003836 return;
Steve Anton75737c02017-11-06 10:37:17 -08003837 }
3838
3839 cricket::DtlsTransportInternal* rtp_dtls_transport =
3840 transport_controller_->CreateDtlsTransport(
3841 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
3842 bool need_rtcp = (ch->rtcp_dtls_transport() != nullptr);
3843 cricket::DtlsTransportInternal* rtcp_dtls_transport = nullptr;
3844 if (need_rtcp) {
3845 rtcp_dtls_transport = transport_controller_->CreateDtlsTransport(
3846 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
3847 }
3848
3849 ch->SetTransports(rtp_dtls_transport, rtcp_dtls_transport);
Mirko Bonadei675513b2017-11-09 11:09:25 +01003850 RTC_LOG(LS_INFO) << "Enabled BUNDLE for " << ch->content_name() << " on "
3851 << transport_name << ".";
Steve Anton75737c02017-11-06 10:37:17 -08003852 transport_controller_->DestroyDtlsTransport(
3853 old_transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
3854 // If the channel needs rtcp, it means that the channel used to have a
3855 // rtcp transport which needs to be deleted now.
3856 if (need_rtcp) {
3857 transport_controller_->DestroyDtlsTransport(
3858 old_transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
3859 }
Steve Anton75737c02017-11-06 10:37:17 -08003860 };
3861
Steve Antoned10bd92017-12-05 10:52:59 -08003862 for (auto transceiver : transceivers_) {
3863 maybe_set_transport(transceiver->internal()->channel());
Steve Anton75737c02017-11-06 10:37:17 -08003864 }
Steve Antoned10bd92017-12-05 10:52:59 -08003865 maybe_set_transport(rtp_data_channel_);
3866
Steve Anton75737c02017-11-06 10:37:17 -08003867 // For SCTP, transport creation/deletion happens here instead of in the
3868 // object itself.
3869 if (sctp_transport_) {
3870 RTC_DCHECK(sctp_transport_name_);
3871 RTC_DCHECK(sctp_content_name_);
3872 if (transport_name != *sctp_transport_name_ &&
3873 bundle.HasContentName(*sctp_content_name_)) {
3874 network_thread()->Invoke<void>(
3875 RTC_FROM_HERE, rtc::Bind(&PeerConnection::ChangeSctpTransport_n, this,
3876 transport_name));
3877 }
3878 }
3879
3880 return true;
3881}
3882
Steve Anton75737c02017-11-06 10:37:17 -08003883cricket::IceConfig PeerConnection::ParseIceConfig(
3884 const PeerConnectionInterface::RTCConfiguration& config) const {
3885 cricket::ContinualGatheringPolicy gathering_policy;
3886 // TODO(honghaiz): Add the third continual gathering policy in
3887 // PeerConnectionInterface and map it to GATHER_CONTINUALLY_AND_RECOVER.
3888 switch (config.continual_gathering_policy) {
3889 case PeerConnectionInterface::GATHER_ONCE:
3890 gathering_policy = cricket::GATHER_ONCE;
3891 break;
3892 case PeerConnectionInterface::GATHER_CONTINUALLY:
3893 gathering_policy = cricket::GATHER_CONTINUALLY;
3894 break;
3895 default:
3896 RTC_NOTREACHED();
3897 gathering_policy = cricket::GATHER_ONCE;
3898 }
3899 cricket::IceConfig ice_config;
3900 ice_config.receiving_timeout = config.ice_connection_receiving_timeout;
3901 ice_config.prioritize_most_likely_candidate_pairs =
3902 config.prioritize_most_likely_ice_candidate_pairs;
3903 ice_config.backup_connection_ping_interval =
3904 config.ice_backup_candidate_pair_ping_interval;
3905 ice_config.continual_gathering_policy = gathering_policy;
3906 ice_config.presume_writable_when_fully_relayed =
3907 config.presume_writable_when_fully_relayed;
3908 ice_config.ice_check_min_interval = config.ice_check_min_interval;
3909 ice_config.regather_all_networks_interval_range =
3910 config.ice_regather_interval_range;
3911 return ice_config;
3912}
3913
Steve Anton75737c02017-11-06 10:37:17 -08003914bool PeerConnection::GetLocalTrackIdBySsrc(uint32_t ssrc,
3915 std::string* track_id) {
3916 if (!local_description()) {
3917 return false;
3918 }
3919 return webrtc::GetTrackIdBySsrc(local_description()->description(), ssrc,
3920 track_id);
3921}
3922
3923bool PeerConnection::GetRemoteTrackIdBySsrc(uint32_t ssrc,
3924 std::string* track_id) {
3925 if (!remote_description()) {
3926 return false;
3927 }
3928 return webrtc::GetTrackIdBySsrc(remote_description()->description(), ssrc,
3929 track_id);
3930}
3931
3932bool PeerConnection::SendData(const cricket::SendDataParams& params,
3933 const rtc::CopyOnWriteBuffer& payload,
3934 cricket::SendDataResult* result) {
3935 if (!rtp_data_channel_ && !sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003936 RTC_LOG(LS_ERROR) << "SendData called when rtp_data_channel_ "
3937 << "and sctp_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08003938 return false;
3939 }
3940 return rtp_data_channel_
3941 ? rtp_data_channel_->SendData(params, payload, result)
3942 : network_thread()->Invoke<bool>(
3943 RTC_FROM_HERE,
3944 Bind(&cricket::SctpTransportInternal::SendData,
3945 sctp_transport_.get(), params, payload, result));
3946}
3947
3948bool PeerConnection::ConnectDataChannel(DataChannel* webrtc_data_channel) {
3949 if (!rtp_data_channel_ && !sctp_transport_) {
3950 // Don't log an error here, because DataChannels are expected to call
3951 // ConnectDataChannel in this state. It's the only way to initially tell
3952 // whether or not the underlying transport is ready.
3953 return false;
3954 }
3955 if (rtp_data_channel_) {
3956 rtp_data_channel_->SignalReadyToSendData.connect(
3957 webrtc_data_channel, &DataChannel::OnChannelReady);
3958 rtp_data_channel_->SignalDataReceived.connect(webrtc_data_channel,
3959 &DataChannel::OnDataReceived);
3960 } else {
3961 SignalSctpReadyToSendData.connect(webrtc_data_channel,
3962 &DataChannel::OnChannelReady);
3963 SignalSctpDataReceived.connect(webrtc_data_channel,
3964 &DataChannel::OnDataReceived);
3965 SignalSctpStreamClosedRemotely.connect(
3966 webrtc_data_channel, &DataChannel::OnStreamClosedRemotely);
3967 }
3968 return true;
3969}
3970
3971void PeerConnection::DisconnectDataChannel(DataChannel* webrtc_data_channel) {
3972 if (!rtp_data_channel_ && !sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003973 RTC_LOG(LS_ERROR)
3974 << "DisconnectDataChannel called when rtp_data_channel_ and "
3975 "sctp_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08003976 return;
3977 }
3978 if (rtp_data_channel_) {
3979 rtp_data_channel_->SignalReadyToSendData.disconnect(webrtc_data_channel);
3980 rtp_data_channel_->SignalDataReceived.disconnect(webrtc_data_channel);
3981 } else {
3982 SignalSctpReadyToSendData.disconnect(webrtc_data_channel);
3983 SignalSctpDataReceived.disconnect(webrtc_data_channel);
3984 SignalSctpStreamClosedRemotely.disconnect(webrtc_data_channel);
3985 }
3986}
3987
3988void PeerConnection::AddSctpDataStream(int sid) {
3989 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003990 RTC_LOG(LS_ERROR)
3991 << "AddSctpDataStream called when sctp_transport_ is NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08003992 return;
3993 }
3994 network_thread()->Invoke<void>(
3995 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::OpenStream,
3996 sctp_transport_.get(), sid));
3997}
3998
3999void PeerConnection::RemoveSctpDataStream(int sid) {
4000 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004001 RTC_LOG(LS_ERROR) << "RemoveSctpDataStream called when sctp_transport_ is "
4002 << "NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08004003 return;
4004 }
4005 network_thread()->Invoke<void>(
4006 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::ResetStream,
4007 sctp_transport_.get(), sid));
4008}
4009
4010bool PeerConnection::ReadyToSendData() const {
4011 return (rtp_data_channel_ && rtp_data_channel_->ready_to_send_data()) ||
4012 sctp_ready_to_send_data_;
4013}
4014
4015std::unique_ptr<SessionStats> PeerConnection::GetSessionStats_s() {
4016 RTC_DCHECK(signaling_thread()->IsCurrent());
4017 ChannelNamePairs channel_name_pairs;
4018 if (voice_channel()) {
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004019 channel_name_pairs.voice = ChannelNamePair(
4020 voice_channel()->content_name(), voice_channel()->transport_name());
Steve Anton75737c02017-11-06 10:37:17 -08004021 }
4022 if (video_channel()) {
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004023 channel_name_pairs.video = ChannelNamePair(
4024 video_channel()->content_name(), video_channel()->transport_name());
Steve Anton75737c02017-11-06 10:37:17 -08004025 }
4026 if (rtp_data_channel()) {
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004027 channel_name_pairs.data =
Steve Anton75737c02017-11-06 10:37:17 -08004028 ChannelNamePair(rtp_data_channel()->content_name(),
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004029 rtp_data_channel()->transport_name());
Steve Anton75737c02017-11-06 10:37:17 -08004030 }
4031 if (sctp_transport_) {
4032 RTC_DCHECK(sctp_content_name_);
4033 RTC_DCHECK(sctp_transport_name_);
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004034 channel_name_pairs.data =
4035 ChannelNamePair(*sctp_content_name_, *sctp_transport_name_);
Steve Anton75737c02017-11-06 10:37:17 -08004036 }
4037 return GetSessionStats(channel_name_pairs);
4038}
4039
4040std::unique_ptr<SessionStats> PeerConnection::GetSessionStats(
4041 const ChannelNamePairs& channel_name_pairs) {
4042 if (network_thread()->IsCurrent()) {
4043 return GetSessionStats_n(channel_name_pairs);
4044 }
4045 return network_thread()->Invoke<std::unique_ptr<SessionStats>>(
4046 RTC_FROM_HERE,
4047 rtc::Bind(&PeerConnection::GetSessionStats_n, this, channel_name_pairs));
4048}
4049
4050bool PeerConnection::GetLocalCertificate(
4051 const std::string& transport_name,
4052 rtc::scoped_refptr<rtc::RTCCertificate>* certificate) {
4053 return transport_controller_->GetLocalCertificate(transport_name,
4054 certificate);
4055}
4056
4057std::unique_ptr<rtc::SSLCertificate> PeerConnection::GetRemoteSSLCertificate(
4058 const std::string& transport_name) {
4059 return transport_controller_->GetRemoteSSLCertificate(transport_name);
4060}
4061
4062cricket::DataChannelType PeerConnection::data_channel_type() const {
4063 return data_channel_type_;
4064}
4065
4066bool PeerConnection::IceRestartPending(const std::string& content_name) const {
4067 return pending_ice_restarts_.find(content_name) !=
4068 pending_ice_restarts_.end();
4069}
4070
Steve Anton75737c02017-11-06 10:37:17 -08004071bool PeerConnection::NeedsIceRestart(const std::string& content_name) const {
4072 return transport_controller_->NeedsIceRestart(content_name);
4073}
4074
4075void PeerConnection::OnCertificateReady(
4076 const rtc::scoped_refptr<rtc::RTCCertificate>& certificate) {
4077 transport_controller_->SetLocalCertificate(certificate);
4078}
4079
4080void PeerConnection::OnDtlsSrtpSetupFailure(cricket::BaseChannel*, bool rtcp) {
Steve Antonf8470812017-12-04 10:46:21 -08004081 SetSessionError(SessionError::kTransport,
4082 rtcp ? kDtlsSrtpSetupFailureRtcp : kDtlsSrtpSetupFailureRtp);
Steve Anton75737c02017-11-06 10:37:17 -08004083}
4084
4085void PeerConnection::OnTransportControllerConnectionState(
4086 cricket::IceConnectionState state) {
4087 switch (state) {
4088 case cricket::kIceConnectionConnecting:
4089 // If the current state is Connected or Completed, then there were
4090 // writable channels but now there are not, so the next state must
4091 // be Disconnected.
4092 // kIceConnectionConnecting is currently used as the default,
4093 // un-connected state by the TransportController, so its only use is
4094 // detecting disconnections.
4095 if (ice_connection_state_ ==
4096 PeerConnectionInterface::kIceConnectionConnected ||
4097 ice_connection_state_ ==
4098 PeerConnectionInterface::kIceConnectionCompleted) {
4099 SetIceConnectionState(
4100 PeerConnectionInterface::kIceConnectionDisconnected);
4101 }
4102 break;
4103 case cricket::kIceConnectionFailed:
4104 SetIceConnectionState(PeerConnectionInterface::kIceConnectionFailed);
4105 break;
4106 case cricket::kIceConnectionConnected:
Mirko Bonadei675513b2017-11-09 11:09:25 +01004107 RTC_LOG(LS_INFO) << "Changing to ICE connected state because "
4108 << "all transports are writable.";
Steve Anton75737c02017-11-06 10:37:17 -08004109 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
4110 break;
4111 case cricket::kIceConnectionCompleted:
Mirko Bonadei675513b2017-11-09 11:09:25 +01004112 RTC_LOG(LS_INFO) << "Changing to ICE completed state because "
4113 << "all transports are complete.";
Steve Anton75737c02017-11-06 10:37:17 -08004114 if (ice_connection_state_ !=
4115 PeerConnectionInterface::kIceConnectionConnected) {
4116 // If jumping directly from "checking" to "connected",
4117 // signal "connected" first.
4118 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
4119 }
4120 SetIceConnectionState(PeerConnectionInterface::kIceConnectionCompleted);
4121 if (metrics_observer()) {
4122 ReportTransportStats();
4123 }
4124 break;
4125 default:
4126 RTC_NOTREACHED();
4127 }
4128}
4129
4130void PeerConnection::OnTransportControllerCandidatesGathered(
4131 const std::string& transport_name,
4132 const cricket::Candidates& candidates) {
4133 RTC_DCHECK(signaling_thread()->IsCurrent());
4134 int sdp_mline_index;
4135 if (!GetLocalCandidateMediaIndex(transport_name, &sdp_mline_index)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004136 RTC_LOG(LS_ERROR)
4137 << "OnTransportControllerCandidatesGathered: content name "
4138 << transport_name << " not found";
Steve Anton75737c02017-11-06 10:37:17 -08004139 return;
4140 }
4141
4142 for (cricket::Candidates::const_iterator citer = candidates.begin();
4143 citer != candidates.end(); ++citer) {
4144 // Use transport_name as the candidate media id.
4145 std::unique_ptr<JsepIceCandidate> candidate(
4146 new JsepIceCandidate(transport_name, sdp_mline_index, *citer));
4147 if (local_description()) {
4148 mutable_local_description()->AddCandidate(candidate.get());
4149 }
4150 OnIceCandidate(std::move(candidate));
4151 }
4152}
4153
4154void PeerConnection::OnTransportControllerCandidatesRemoved(
4155 const std::vector<cricket::Candidate>& candidates) {
4156 RTC_DCHECK(signaling_thread()->IsCurrent());
4157 // Sanity check.
4158 for (const cricket::Candidate& candidate : candidates) {
4159 if (candidate.transport_name().empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004160 RTC_LOG(LS_ERROR) << "OnTransportControllerCandidatesRemoved: "
4161 << "empty content name in candidate "
4162 << candidate.ToString();
Steve Anton75737c02017-11-06 10:37:17 -08004163 return;
4164 }
4165 }
4166
4167 if (local_description()) {
4168 mutable_local_description()->RemoveCandidates(candidates);
4169 }
4170 OnIceCandidatesRemoved(candidates);
4171}
4172
4173void PeerConnection::OnTransportControllerDtlsHandshakeError(
4174 rtc::SSLHandshakeError error) {
4175 if (metrics_observer()) {
4176 metrics_observer()->IncrementEnumCounter(
4177 webrtc::kEnumCounterDtlsHandshakeError, static_cast<int>(error),
4178 static_cast<int>(rtc::SSLHandshakeError::MAX_VALUE));
4179 }
4180}
4181
Steve Antoned10bd92017-12-05 10:52:59 -08004182void PeerConnection::EnableSending() {
4183 for (auto transceiver : transceivers_) {
4184 cricket::BaseChannel* channel = transceiver->internal()->channel();
4185 if (channel && !channel->enabled()) {
4186 channel->Enable(true);
4187 }
Steve Anton75737c02017-11-06 10:37:17 -08004188 }
4189
Steve Anton4171afb2017-11-20 10:20:22 -08004190 if (rtp_data_channel_ && !rtp_data_channel_->enabled()) {
Steve Anton75737c02017-11-06 10:37:17 -08004191 rtp_data_channel_->Enable(true);
Steve Anton4171afb2017-11-20 10:20:22 -08004192 }
Steve Anton75737c02017-11-06 10:37:17 -08004193}
4194
4195// Returns the media index for a local ice candidate given the content name.
4196bool PeerConnection::GetLocalCandidateMediaIndex(
4197 const std::string& content_name,
4198 int* sdp_mline_index) {
4199 if (!local_description() || !sdp_mline_index) {
4200 return false;
4201 }
4202
4203 bool content_found = false;
4204 const ContentInfos& contents = local_description()->description()->contents();
4205 for (size_t index = 0; index < contents.size(); ++index) {
4206 if (contents[index].name == content_name) {
4207 *sdp_mline_index = static_cast<int>(index);
4208 content_found = true;
4209 break;
4210 }
4211 }
4212 return content_found;
4213}
4214
4215bool PeerConnection::UseCandidatesInSessionDescription(
4216 const SessionDescriptionInterface* remote_desc) {
4217 if (!remote_desc) {
4218 return true;
4219 }
4220 bool ret = true;
4221
4222 for (size_t m = 0; m < remote_desc->number_of_mediasections(); ++m) {
4223 const IceCandidateCollection* candidates = remote_desc->candidates(m);
4224 for (size_t n = 0; n < candidates->count(); ++n) {
4225 const IceCandidateInterface* candidate = candidates->at(n);
4226 bool valid = false;
4227 if (!ReadyToUseRemoteCandidate(candidate, remote_desc, &valid)) {
4228 if (valid) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004229 RTC_LOG(LS_INFO)
4230 << "UseCandidatesInSessionDescription: Not ready to use "
4231 << "candidate.";
Steve Anton75737c02017-11-06 10:37:17 -08004232 }
4233 continue;
4234 }
4235 ret = UseCandidate(candidate);
4236 if (!ret) {
4237 break;
4238 }
4239 }
4240 }
4241 return ret;
4242}
4243
4244bool PeerConnection::UseCandidate(const IceCandidateInterface* candidate) {
4245 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
4246 size_t remote_content_size =
4247 remote_description()->description()->contents().size();
4248 if (mediacontent_index >= remote_content_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004249 RTC_LOG(LS_ERROR) << "UseCandidate: Invalid candidate media index.";
Steve Anton75737c02017-11-06 10:37:17 -08004250 return false;
4251 }
4252
4253 cricket::ContentInfo content =
4254 remote_description()->description()->contents()[mediacontent_index];
4255 std::vector<cricket::Candidate> candidates;
4256 candidates.push_back(candidate->candidate());
4257 // Invoking BaseSession method to handle remote candidates.
4258 std::string error;
4259 if (transport_controller_->AddRemoteCandidates(content.name, candidates,
4260 &error)) {
4261 // Candidates successfully submitted for checking.
4262 if (ice_connection_state_ == PeerConnectionInterface::kIceConnectionNew ||
4263 ice_connection_state_ ==
4264 PeerConnectionInterface::kIceConnectionDisconnected) {
4265 // If state is New, then the session has just gotten its first remote ICE
4266 // candidates, so go to Checking.
4267 // If state is Disconnected, the session is re-using old candidates or
4268 // receiving additional ones, so go to Checking.
4269 // If state is Connected, stay Connected.
4270 // TODO(bemasc): If state is Connected, and the new candidates are for a
4271 // newly added transport, then the state actually _should_ move to
4272 // checking. Add a way to distinguish that case.
4273 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
4274 }
4275 // TODO(bemasc): If state is Completed, go back to Connected.
4276 } else {
4277 if (!error.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004278 RTC_LOG(LS_WARNING) << error;
Steve Anton75737c02017-11-06 10:37:17 -08004279 }
4280 }
4281 return true;
4282}
4283
4284void PeerConnection::RemoveUnusedChannels(const SessionDescription* desc) {
Steve Anton75737c02017-11-06 10:37:17 -08004285 // Destroy video channel first since it may have a pointer to the
4286 // voice channel.
4287 const cricket::ContentInfo* video_info = cricket::GetFirstVideoContent(desc);
Steve Anton6fec8802017-12-04 10:37:29 -08004288 if (!video_info || video_info->rejected) {
4289 DestroyTransceiverChannel(GetVideoTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08004290 }
4291
Steve Anton6fec8802017-12-04 10:37:29 -08004292 const cricket::ContentInfo* audio_info = cricket::GetFirstAudioContent(desc);
4293 if (!audio_info || audio_info->rejected) {
4294 DestroyTransceiverChannel(GetAudioTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08004295 }
4296
4297 const cricket::ContentInfo* data_info = cricket::GetFirstDataContent(desc);
4298 if (!data_info || data_info->rejected) {
Steve Anton6fec8802017-12-04 10:37:29 -08004299 DestroyDataChannel();
Steve Anton75737c02017-11-06 10:37:17 -08004300 }
4301}
4302
Steve Antoneda6ccd2017-12-04 10:21:55 -08004303std::string PeerConnection::GetTransportNameForMediaSection(
4304 const std::string& mid,
4305 const cricket::ContentGroup* bundle_group) const {
4306 if (!bundle_group) {
4307 return mid;
Steve Anton75737c02017-11-06 10:37:17 -08004308 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08004309 const std::string* first_content_name = bundle_group->FirstContentName();
Steve Anton75737c02017-11-06 10:37:17 -08004310 if (!first_content_name) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004311 RTC_LOG(LS_WARNING) << "Tried to BUNDLE with no contents.";
Steve Antoneda6ccd2017-12-04 10:21:55 -08004312 return mid;
Steve Anton75737c02017-11-06 10:37:17 -08004313 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08004314 if (!bundle_group->HasContentName(mid)) {
4315 RTC_LOG(LS_WARNING) << mid << " is not part of any bundle group";
4316 return mid;
Steve Anton75737c02017-11-06 10:37:17 -08004317 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08004318 RTC_LOG(LS_INFO) << "Bundling " << mid << " on " << *first_content_name;
4319 return *first_content_name;
Steve Anton75737c02017-11-06 10:37:17 -08004320}
4321
Steve Anton8a006912017-12-04 15:25:56 -08004322RTCError PeerConnection::CreateChannels(const SessionDescription* desc) {
Steve Antoneda6ccd2017-12-04 10:21:55 -08004323 RTC_DCHECK(desc);
4324
Steve Anton75737c02017-11-06 10:37:17 -08004325 const cricket::ContentGroup* bundle_group = nullptr;
4326 if (configuration_.bundle_policy ==
4327 PeerConnectionInterface::kBundlePolicyMaxBundle) {
4328 bundle_group = desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
4329 if (!bundle_group) {
Steve Anton8a006912017-12-04 15:25:56 -08004330 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
4331 "max-bundle configured but session description "
4332 "has no BUNDLE group");
Steve Anton75737c02017-11-06 10:37:17 -08004333 }
4334 }
4335
Steve Antoneda6ccd2017-12-04 10:21:55 -08004336 // Creating the media channels and transport proxies.
4337 const cricket::ContentInfo* voice = cricket::GetFirstAudioContent(desc);
4338 if (voice && !voice->rejected &&
4339 !GetAudioTransceiver()->internal()->channel()) {
4340 cricket::VoiceChannel* voice_channel = CreateVoiceChannel(
4341 voice->name,
4342 GetTransportNameForMediaSection(voice->name, bundle_group));
4343 if (!voice_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08004344 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
4345 "Failed to create voice channel.");
Steve Antoneda6ccd2017-12-04 10:21:55 -08004346 }
4347 GetAudioTransceiver()->internal()->SetChannel(voice_channel);
4348 }
4349
Steve Anton75737c02017-11-06 10:37:17 -08004350 const cricket::ContentInfo* video = cricket::GetFirstVideoContent(desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08004351 if (video && !video->rejected &&
4352 !GetVideoTransceiver()->internal()->channel()) {
4353 cricket::VideoChannel* video_channel = CreateVideoChannel(
4354 video->name,
4355 GetTransportNameForMediaSection(video->name, bundle_group));
4356 if (!video_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08004357 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
4358 "Failed to create video channel.");
Steve Anton75737c02017-11-06 10:37:17 -08004359 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08004360 GetVideoTransceiver()->internal()->SetChannel(video_channel);
Steve Anton75737c02017-11-06 10:37:17 -08004361 }
4362
4363 const cricket::ContentInfo* data = cricket::GetFirstDataContent(desc);
4364 if (data_channel_type_ != cricket::DCT_NONE && data && !data->rejected &&
4365 !rtp_data_channel_ && !sctp_transport_) {
Steve Antoneda6ccd2017-12-04 10:21:55 -08004366 if (!CreateDataChannel(data->name, GetTransportNameForMediaSection(
4367 data->name, bundle_group))) {
Steve Anton8a006912017-12-04 15:25:56 -08004368 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
4369 "Failed to create data channel.");
Steve Anton75737c02017-11-06 10:37:17 -08004370 }
4371 }
4372
Steve Anton8a006912017-12-04 15:25:56 -08004373 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08004374}
4375
Steve Anton4171afb2017-11-20 10:20:22 -08004376// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08004377cricket::VoiceChannel* PeerConnection::CreateVoiceChannel(
4378 const std::string& mid,
4379 const std::string& transport_name) {
Steve Anton75737c02017-11-06 10:37:17 -08004380 cricket::DtlsTransportInternal* rtp_dtls_transport =
4381 transport_controller_->CreateDtlsTransport(
4382 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4383 cricket::DtlsTransportInternal* rtcp_dtls_transport = nullptr;
4384 if (configuration_.rtcp_mux_policy !=
4385 PeerConnectionInterface::kRtcpMuxPolicyRequire) {
4386 rtcp_dtls_transport = transport_controller_->CreateDtlsTransport(
4387 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
4388 }
4389
4390 cricket::VoiceChannel* voice_channel = channel_manager()->CreateVoiceChannel(
4391 call_.get(), configuration_.media_config, rtp_dtls_transport,
Steve Antoneda6ccd2017-12-04 10:21:55 -08004392 rtcp_dtls_transport, signaling_thread(), mid, SrtpRequired(),
4393 audio_options_);
Steve Anton75737c02017-11-06 10:37:17 -08004394 if (!voice_channel) {
4395 transport_controller_->DestroyDtlsTransport(
4396 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4397 if (rtcp_dtls_transport) {
4398 transport_controller_->DestroyDtlsTransport(
4399 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
4400 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08004401 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08004402 }
Steve Anton75737c02017-11-06 10:37:17 -08004403 voice_channel->SignalRtcpMuxFullyActive.connect(
4404 this, &PeerConnection::DestroyRtcpTransport_n);
4405 voice_channel->SignalDtlsSrtpSetupFailure.connect(
4406 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08004407 voice_channel->SignalSentPacket.connect(this,
4408 &PeerConnection::OnSentPacket_w);
Steve Anton4171afb2017-11-20 10:20:22 -08004409
Steve Antoneda6ccd2017-12-04 10:21:55 -08004410 return voice_channel;
Steve Anton75737c02017-11-06 10:37:17 -08004411}
4412
Steve Anton4171afb2017-11-20 10:20:22 -08004413// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08004414cricket::VideoChannel* PeerConnection::CreateVideoChannel(
4415 const std::string& mid,
4416 const std::string& transport_name) {
Steve Anton75737c02017-11-06 10:37:17 -08004417 cricket::DtlsTransportInternal* rtp_dtls_transport =
4418 transport_controller_->CreateDtlsTransport(
4419 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4420 cricket::DtlsTransportInternal* rtcp_dtls_transport = nullptr;
4421 if (configuration_.rtcp_mux_policy !=
4422 PeerConnectionInterface::kRtcpMuxPolicyRequire) {
4423 rtcp_dtls_transport = transport_controller_->CreateDtlsTransport(
4424 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
4425 }
4426
4427 cricket::VideoChannel* video_channel = channel_manager()->CreateVideoChannel(
4428 call_.get(), configuration_.media_config, rtp_dtls_transport,
Steve Antoneda6ccd2017-12-04 10:21:55 -08004429 rtcp_dtls_transport, signaling_thread(), mid, SrtpRequired(),
4430 video_options_);
Steve Anton75737c02017-11-06 10:37:17 -08004431
4432 if (!video_channel) {
4433 transport_controller_->DestroyDtlsTransport(
4434 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4435 if (rtcp_dtls_transport) {
4436 transport_controller_->DestroyDtlsTransport(
4437 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
4438 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08004439 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08004440 }
Steve Anton75737c02017-11-06 10:37:17 -08004441 video_channel->SignalRtcpMuxFullyActive.connect(
4442 this, &PeerConnection::DestroyRtcpTransport_n);
4443 video_channel->SignalDtlsSrtpSetupFailure.connect(
4444 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08004445 video_channel->SignalSentPacket.connect(this,
4446 &PeerConnection::OnSentPacket_w);
Steve Anton4171afb2017-11-20 10:20:22 -08004447
Steve Antoneda6ccd2017-12-04 10:21:55 -08004448 return video_channel;
Steve Anton75737c02017-11-06 10:37:17 -08004449}
4450
Steve Antoneda6ccd2017-12-04 10:21:55 -08004451bool PeerConnection::CreateDataChannel(const std::string& mid,
4452 const std::string& transport_name) {
Steve Anton75737c02017-11-06 10:37:17 -08004453 bool sctp = (data_channel_type_ == cricket::DCT_SCTP);
4454 if (sctp) {
4455 if (!sctp_factory_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004456 RTC_LOG(LS_ERROR)
Steve Anton75737c02017-11-06 10:37:17 -08004457 << "Trying to create SCTP transport, but didn't compile with "
4458 "SCTP support (HAVE_SCTP)";
4459 return false;
4460 }
4461 if (!network_thread()->Invoke<bool>(
4462 RTC_FROM_HERE, rtc::Bind(&PeerConnection::CreateSctpTransport_n,
Steve Antoneda6ccd2017-12-04 10:21:55 -08004463 this, mid, transport_name))) {
Steve Anton75737c02017-11-06 10:37:17 -08004464 return false;
4465 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08004466 for (const auto& channel : sctp_data_channels_) {
4467 channel->OnTransportChannelCreated();
4468 }
Steve Anton75737c02017-11-06 10:37:17 -08004469 } else {
Steve Anton75737c02017-11-06 10:37:17 -08004470 cricket::DtlsTransportInternal* rtp_dtls_transport =
4471 transport_controller_->CreateDtlsTransport(
4472 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4473 cricket::DtlsTransportInternal* rtcp_dtls_transport = nullptr;
4474 if (configuration_.rtcp_mux_policy !=
4475 PeerConnectionInterface::kRtcpMuxPolicyRequire) {
4476 rtcp_dtls_transport = transport_controller_->CreateDtlsTransport(
4477 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
4478 }
4479
4480 rtp_data_channel_ = channel_manager()->CreateRtpDataChannel(
4481 configuration_.media_config, rtp_dtls_transport, rtcp_dtls_transport,
Steve Antoneda6ccd2017-12-04 10:21:55 -08004482 signaling_thread(), mid, SrtpRequired());
Steve Anton75737c02017-11-06 10:37:17 -08004483
4484 if (!rtp_data_channel_) {
4485 transport_controller_->DestroyDtlsTransport(
4486 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4487 if (rtcp_dtls_transport) {
4488 transport_controller_->DestroyDtlsTransport(
4489 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
4490 }
4491 return false;
4492 }
4493
4494 rtp_data_channel_->SignalRtcpMuxFullyActive.connect(
4495 this, &PeerConnection::DestroyRtcpTransport_n);
4496 rtp_data_channel_->SignalDtlsSrtpSetupFailure.connect(
4497 this, &PeerConnection::OnDtlsSrtpSetupFailure);
4498 rtp_data_channel_->SignalSentPacket.connect(
4499 this, &PeerConnection::OnSentPacket_w);
4500 }
4501
Steve Anton75737c02017-11-06 10:37:17 -08004502 return true;
4503}
4504
4505Call::Stats PeerConnection::GetCallStats() {
4506 if (!worker_thread()->IsCurrent()) {
4507 return worker_thread()->Invoke<Call::Stats>(
4508 RTC_FROM_HERE, rtc::Bind(&PeerConnection::GetCallStats, this));
4509 }
4510 if (call_) {
4511 return call_->GetStats();
4512 } else {
4513 return Call::Stats();
4514 }
4515}
4516
4517std::unique_ptr<SessionStats> PeerConnection::GetSessionStats_n(
4518 const ChannelNamePairs& channel_name_pairs) {
4519 RTC_DCHECK(network_thread()->IsCurrent());
4520 std::unique_ptr<SessionStats> session_stats(new SessionStats());
4521 for (const auto channel_name_pair :
4522 {&channel_name_pairs.voice, &channel_name_pairs.video,
4523 &channel_name_pairs.data}) {
4524 if (*channel_name_pair) {
4525 cricket::TransportStats transport_stats;
4526 if (!transport_controller_->GetStats((*channel_name_pair)->transport_name,
4527 &transport_stats)) {
4528 return nullptr;
4529 }
4530 session_stats->proxy_to_transport[(*channel_name_pair)->content_name] =
4531 (*channel_name_pair)->transport_name;
4532 session_stats->transport_stats[(*channel_name_pair)->transport_name] =
4533 std::move(transport_stats);
4534 }
4535 }
4536 return session_stats;
4537}
4538
4539bool PeerConnection::CreateSctpTransport_n(const std::string& content_name,
4540 const std::string& transport_name) {
4541 RTC_DCHECK(network_thread()->IsCurrent());
4542 RTC_DCHECK(sctp_factory_);
4543 cricket::DtlsTransportInternal* tc =
4544 transport_controller_->CreateDtlsTransport_n(
4545 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4546 sctp_transport_ = sctp_factory_->CreateSctpTransport(tc);
4547 RTC_DCHECK(sctp_transport_);
4548 sctp_invoker_.reset(new rtc::AsyncInvoker());
4549 sctp_transport_->SignalReadyToSendData.connect(
4550 this, &PeerConnection::OnSctpTransportReadyToSendData_n);
4551 sctp_transport_->SignalDataReceived.connect(
4552 this, &PeerConnection::OnSctpTransportDataReceived_n);
4553 sctp_transport_->SignalStreamClosedRemotely.connect(
4554 this, &PeerConnection::OnSctpStreamClosedRemotely_n);
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004555 sctp_transport_name_ = transport_name;
4556 sctp_content_name_ = content_name;
Steve Anton75737c02017-11-06 10:37:17 -08004557 return true;
4558}
4559
4560void PeerConnection::ChangeSctpTransport_n(const std::string& transport_name) {
4561 RTC_DCHECK(network_thread()->IsCurrent());
4562 RTC_DCHECK(sctp_transport_);
4563 RTC_DCHECK(sctp_transport_name_);
4564 std::string old_sctp_transport_name = *sctp_transport_name_;
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004565 sctp_transport_name_ = transport_name;
Steve Anton75737c02017-11-06 10:37:17 -08004566 cricket::DtlsTransportInternal* tc =
4567 transport_controller_->CreateDtlsTransport_n(
4568 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4569 sctp_transport_->SetTransportChannel(tc);
4570 transport_controller_->DestroyDtlsTransport_n(
4571 old_sctp_transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4572}
4573
4574void PeerConnection::DestroySctpTransport_n() {
4575 RTC_DCHECK(network_thread()->IsCurrent());
4576 sctp_transport_.reset(nullptr);
4577 sctp_content_name_.reset();
4578 sctp_transport_name_.reset();
4579 sctp_invoker_.reset(nullptr);
4580 sctp_ready_to_send_data_ = false;
4581}
4582
4583void PeerConnection::OnSctpTransportReadyToSendData_n() {
4584 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
4585 RTC_DCHECK(network_thread()->IsCurrent());
4586 // Note: Cannot use rtc::Bind here because it will grab a reference to
4587 // PeerConnection and potentially cause PeerConnection to live longer than
4588 // expected. It is safe not to grab a reference since the sctp_invoker_ will
4589 // be destroyed before PeerConnection is destroyed, and at that point all
4590 // pending tasks will be cleared.
4591 sctp_invoker_->AsyncInvoke<void>(RTC_FROM_HERE, signaling_thread(), [this] {
4592 OnSctpTransportReadyToSendData_s(true);
4593 });
4594}
4595
4596void PeerConnection::OnSctpTransportReadyToSendData_s(bool ready) {
4597 RTC_DCHECK(signaling_thread()->IsCurrent());
4598 sctp_ready_to_send_data_ = ready;
4599 SignalSctpReadyToSendData(ready);
4600}
4601
4602void PeerConnection::OnSctpTransportDataReceived_n(
4603 const cricket::ReceiveDataParams& params,
4604 const rtc::CopyOnWriteBuffer& payload) {
4605 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
4606 RTC_DCHECK(network_thread()->IsCurrent());
4607 // Note: Cannot use rtc::Bind here because it will grab a reference to
4608 // PeerConnection and potentially cause PeerConnection to live longer than
4609 // expected. It is safe not to grab a reference since the sctp_invoker_ will
4610 // be destroyed before PeerConnection is destroyed, and at that point all
4611 // pending tasks will be cleared.
4612 sctp_invoker_->AsyncInvoke<void>(
4613 RTC_FROM_HERE, signaling_thread(), [this, params, payload] {
4614 OnSctpTransportDataReceived_s(params, payload);
4615 });
4616}
4617
4618void PeerConnection::OnSctpTransportDataReceived_s(
4619 const cricket::ReceiveDataParams& params,
4620 const rtc::CopyOnWriteBuffer& payload) {
4621 RTC_DCHECK(signaling_thread()->IsCurrent());
4622 if (params.type == cricket::DMT_CONTROL && IsOpenMessage(payload)) {
4623 // Received OPEN message; parse and signal that a new data channel should
4624 // be created.
4625 std::string label;
4626 InternalDataChannelInit config;
4627 config.id = params.ssrc;
4628 if (!ParseDataChannelOpenMessage(payload, &label, &config)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004629 RTC_LOG(LS_WARNING) << "Failed to parse the OPEN message for sid "
4630 << params.ssrc;
Steve Anton75737c02017-11-06 10:37:17 -08004631 return;
4632 }
4633 config.open_handshake_role = InternalDataChannelInit::kAcker;
4634 OnDataChannelOpenMessage(label, config);
4635 } else {
4636 // Otherwise just forward the signal.
4637 SignalSctpDataReceived(params, payload);
4638 }
4639}
4640
4641void PeerConnection::OnSctpStreamClosedRemotely_n(int sid) {
4642 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
4643 RTC_DCHECK(network_thread()->IsCurrent());
4644 sctp_invoker_->AsyncInvoke<void>(
4645 RTC_FROM_HERE, signaling_thread(),
4646 rtc::Bind(&sigslot::signal1<int>::operator(),
4647 &SignalSctpStreamClosedRemotely, sid));
4648}
4649
4650// Returns false if bundle is enabled and rtcp_mux is disabled.
4651bool PeerConnection::ValidateBundleSettings(const SessionDescription* desc) {
4652 bool bundle_enabled = desc->HasGroup(cricket::GROUP_TYPE_BUNDLE);
4653 if (!bundle_enabled)
4654 return true;
4655
4656 const cricket::ContentGroup* bundle_group =
4657 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
4658 RTC_DCHECK(bundle_group != NULL);
4659
4660 const cricket::ContentInfos& contents = desc->contents();
4661 for (cricket::ContentInfos::const_iterator citer = contents.begin();
4662 citer != contents.end(); ++citer) {
4663 const cricket::ContentInfo* content = (&*citer);
4664 RTC_DCHECK(content != NULL);
4665 if (bundle_group->HasContentName(content->name) && !content->rejected &&
4666 content->type == cricket::NS_JINGLE_RTP) {
4667 if (!HasRtcpMuxEnabled(content))
4668 return false;
4669 }
4670 }
4671 // RTCP-MUX is enabled in all the contents.
4672 return true;
4673}
4674
4675bool PeerConnection::HasRtcpMuxEnabled(const cricket::ContentInfo* content) {
4676 const cricket::MediaContentDescription* description =
4677 static_cast<cricket::MediaContentDescription*>(content->description);
4678 return description->rtcp_mux();
4679}
4680
Steve Anton8a006912017-12-04 15:25:56 -08004681RTCError PeerConnection::ValidateSessionDescription(
Steve Anton75737c02017-11-06 10:37:17 -08004682 const SessionDescriptionInterface* sdesc,
Steve Anton8a006912017-12-04 15:25:56 -08004683 cricket::ContentSource source) {
Steve Antonf8470812017-12-04 10:46:21 -08004684 if (session_error() != SessionError::kNone) {
Steve Anton8a006912017-12-04 15:25:56 -08004685 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
Steve Anton75737c02017-11-06 10:37:17 -08004686 }
4687
4688 if (!sdesc || !sdesc->description()) {
Steve Anton8a006912017-12-04 15:25:56 -08004689 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidSdp);
Steve Anton75737c02017-11-06 10:37:17 -08004690 }
4691
Steve Anton3828c062017-12-06 10:34:51 -08004692 SdpType type = sdesc->GetType();
4693 if ((source == cricket::CS_LOCAL && !ExpectSetLocalDescription(type)) ||
4694 (source == cricket::CS_REMOTE && !ExpectSetRemoteDescription(type))) {
Steve Anton8a006912017-12-04 15:25:56 -08004695 LOG_AND_RETURN_ERROR(
4696 RTCErrorType::INVALID_PARAMETER,
4697 "Called in wrong state: " + GetSignalingStateString(signaling_state()));
Steve Anton75737c02017-11-06 10:37:17 -08004698 }
4699
4700 // Verify crypto settings.
4701 std::string crypto_error;
Steve Anton8a006912017-12-04 15:25:56 -08004702 if (webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED ||
4703 dtls_enabled_) {
4704 RTCError crypto_error = VerifyCrypto(sdesc->description(), dtls_enabled_);
4705 if (!crypto_error.ok()) {
4706 return crypto_error;
4707 }
Steve Anton75737c02017-11-06 10:37:17 -08004708 }
4709
4710 // Verify ice-ufrag and ice-pwd.
4711 if (!VerifyIceUfragPwdPresent(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08004712 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
4713 kSdpWithoutIceUfragPwd);
Steve Anton75737c02017-11-06 10:37:17 -08004714 }
4715
4716 if (!ValidateBundleSettings(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08004717 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
4718 kBundleWithoutRtcpMux);
Steve Anton75737c02017-11-06 10:37:17 -08004719 }
4720
4721 // TODO(skvlad): When the local rtcp-mux policy is Require, reject any
4722 // m-lines that do not rtcp-mux enabled.
4723
4724 // Verify m-lines in Answer when compared against Offer.
Steve Anton3828c062017-12-06 10:34:51 -08004725 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Anton75737c02017-11-06 10:37:17 -08004726 const cricket::SessionDescription* offer_desc =
4727 (source == cricket::CS_LOCAL) ? remote_description()->description()
4728 : local_description()->description();
4729 if (!MediaSectionsHaveSameCount(offer_desc, sdesc->description()) ||
4730 !MediaSectionsInSameOrder(offer_desc, sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08004731 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
4732 kMlineMismatchInAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08004733 }
4734 } else {
4735 const cricket::SessionDescription* current_desc = nullptr;
4736 if (source == cricket::CS_LOCAL && local_description()) {
4737 current_desc = local_description()->description();
4738 } else if (source == cricket::CS_REMOTE && remote_description()) {
4739 current_desc = remote_description()->description();
4740 }
4741 // The re-offers should respect the order of m= sections in current
4742 // description. See RFC3264 Section 8 paragraph 4 for more details.
4743 if (current_desc &&
4744 !MediaSectionsInSameOrder(current_desc, sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08004745 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
4746 kMlineMismatchInSubsequentOffer);
Steve Anton75737c02017-11-06 10:37:17 -08004747 }
4748 }
4749
Steve Anton8a006912017-12-04 15:25:56 -08004750 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08004751}
4752
Steve Anton3828c062017-12-06 10:34:51 -08004753bool PeerConnection::ExpectSetLocalDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08004754 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08004755 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08004756 return (state == PeerConnectionInterface::kStable) ||
4757 (state == PeerConnectionInterface::kHaveLocalOffer);
Steve Anton20393062017-12-04 16:24:52 -08004758 } else {
Steve Anton3828c062017-12-06 10:34:51 -08004759 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08004760 return (state == PeerConnectionInterface::kHaveRemoteOffer) ||
4761 (state == PeerConnectionInterface::kHaveLocalPrAnswer);
4762 }
4763}
4764
Steve Anton3828c062017-12-06 10:34:51 -08004765bool PeerConnection::ExpectSetRemoteDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08004766 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08004767 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08004768 return (state == PeerConnectionInterface::kStable) ||
4769 (state == PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton20393062017-12-04 16:24:52 -08004770 } else {
Steve Anton3828c062017-12-06 10:34:51 -08004771 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08004772 return (state == PeerConnectionInterface::kHaveLocalOffer) ||
4773 (state == PeerConnectionInterface::kHaveRemotePrAnswer);
4774 }
4775}
4776
Steve Antonf8470812017-12-04 10:46:21 -08004777const char* PeerConnection::SessionErrorToString(SessionError error) const {
4778 switch (error) {
4779 case SessionError::kNone:
4780 return "ERROR_NONE";
4781 case SessionError::kContent:
4782 return "ERROR_CONTENT";
4783 case SessionError::kTransport:
4784 return "ERROR_TRANSPORT";
4785 }
4786 RTC_NOTREACHED();
4787 return "";
4788}
4789
Steve Anton75737c02017-11-06 10:37:17 -08004790std::string PeerConnection::GetSessionErrorMsg() {
4791 std::ostringstream desc;
Steve Antonf8470812017-12-04 10:46:21 -08004792 desc << kSessionError << SessionErrorToString(session_error()) << ". ";
4793 desc << kSessionErrorDesc << session_error_desc() << ".";
Steve Anton75737c02017-11-06 10:37:17 -08004794 return desc.str();
4795}
4796
4797// We need to check the local/remote description for the Transport instead of
4798// the session, because a new Transport added during renegotiation may have
4799// them unset while the session has them set from the previous negotiation.
4800// Not doing so may trigger the auto generation of transport description and
4801// mess up DTLS identity information, ICE credential, etc.
4802bool PeerConnection::ReadyToUseRemoteCandidate(
4803 const IceCandidateInterface* candidate,
4804 const SessionDescriptionInterface* remote_desc,
4805 bool* valid) {
4806 *valid = true;
4807
4808 const SessionDescriptionInterface* current_remote_desc =
4809 remote_desc ? remote_desc : remote_description();
4810
4811 if (!current_remote_desc) {
4812 return false;
4813 }
4814
4815 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
4816 size_t remote_content_size =
4817 current_remote_desc->description()->contents().size();
4818 if (mediacontent_index >= remote_content_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004819 RTC_LOG(LS_ERROR)
4820 << "ReadyToUseRemoteCandidate: Invalid candidate media index "
4821 << mediacontent_index;
Steve Anton75737c02017-11-06 10:37:17 -08004822
4823 *valid = false;
4824 return false;
4825 }
4826
4827 cricket::ContentInfo content =
4828 current_remote_desc->description()->contents()[mediacontent_index];
4829
4830 const std::string transport_name = GetTransportName(content.name);
4831 if (transport_name.empty()) {
4832 return false;
4833 }
4834 return transport_controller_->ReadyForRemoteCandidates(transport_name);
4835}
4836
4837bool PeerConnection::SrtpRequired() const {
4838 return dtls_enabled_ ||
4839 webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED;
4840}
4841
4842void PeerConnection::OnTransportControllerGatheringState(
4843 cricket::IceGatheringState state) {
4844 RTC_DCHECK(signaling_thread()->IsCurrent());
4845 if (state == cricket::kIceGatheringGathering) {
4846 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringGathering);
4847 } else if (state == cricket::kIceGatheringComplete) {
4848 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringComplete);
4849 }
4850}
4851
4852void PeerConnection::ReportTransportStats() {
4853 // Use a set so we don't report the same stats twice if two channels share
4854 // a transport.
4855 std::set<std::string> transport_names;
4856 if (voice_channel()) {
4857 transport_names.insert(voice_channel()->transport_name());
4858 }
4859 if (video_channel()) {
4860 transport_names.insert(video_channel()->transport_name());
4861 }
4862 if (rtp_data_channel()) {
4863 transport_names.insert(rtp_data_channel()->transport_name());
4864 }
4865 if (sctp_transport_name_) {
4866 transport_names.insert(*sctp_transport_name_);
4867 }
4868 for (const auto& name : transport_names) {
4869 cricket::TransportStats stats;
4870 if (transport_controller_->GetStats(name, &stats)) {
4871 ReportBestConnectionState(stats);
4872 ReportNegotiatedCiphers(stats);
4873 }
4874 }
4875}
4876// Walk through the ConnectionInfos to gather best connection usage
4877// for IPv4 and IPv6.
4878void PeerConnection::ReportBestConnectionState(
4879 const cricket::TransportStats& stats) {
4880 RTC_DCHECK(metrics_observer());
4881 for (cricket::TransportChannelStatsList::const_iterator it =
4882 stats.channel_stats.begin();
4883 it != stats.channel_stats.end(); ++it) {
4884 for (cricket::ConnectionInfos::const_iterator it_info =
4885 it->connection_infos.begin();
4886 it_info != it->connection_infos.end(); ++it_info) {
4887 if (!it_info->best_connection) {
4888 continue;
4889 }
4890
4891 PeerConnectionEnumCounterType type = kPeerConnectionEnumCounterMax;
4892 const cricket::Candidate& local = it_info->local_candidate;
4893 const cricket::Candidate& remote = it_info->remote_candidate;
4894
4895 // Increment the counter for IceCandidatePairType.
4896 if (local.protocol() == cricket::TCP_PROTOCOL_NAME ||
4897 (local.type() == RELAY_PORT_TYPE &&
4898 local.relay_protocol() == cricket::TCP_PROTOCOL_NAME)) {
4899 type = kEnumCounterIceCandidatePairTypeTcp;
4900 } else if (local.protocol() == cricket::UDP_PROTOCOL_NAME) {
4901 type = kEnumCounterIceCandidatePairTypeUdp;
4902 } else {
4903 RTC_CHECK(0);
4904 }
4905 metrics_observer()->IncrementEnumCounter(
4906 type, GetIceCandidatePairCounter(local, remote),
4907 kIceCandidatePairMax);
4908
4909 // Increment the counter for IP type.
4910 if (local.address().family() == AF_INET) {
4911 metrics_observer()->IncrementEnumCounter(
4912 kEnumCounterAddressFamily, kBestConnections_IPv4,
4913 kPeerConnectionAddressFamilyCounter_Max);
4914
4915 } else if (local.address().family() == AF_INET6) {
4916 metrics_observer()->IncrementEnumCounter(
4917 kEnumCounterAddressFamily, kBestConnections_IPv6,
4918 kPeerConnectionAddressFamilyCounter_Max);
4919 } else {
4920 RTC_CHECK(0);
4921 }
4922
4923 return;
4924 }
4925 }
4926}
4927
4928void PeerConnection::ReportNegotiatedCiphers(
4929 const cricket::TransportStats& stats) {
4930 RTC_DCHECK(metrics_observer());
4931 if (!dtls_enabled_ || stats.channel_stats.empty()) {
4932 return;
4933 }
4934
4935 int srtp_crypto_suite = stats.channel_stats[0].srtp_crypto_suite;
4936 int ssl_cipher_suite = stats.channel_stats[0].ssl_cipher_suite;
4937 if (srtp_crypto_suite == rtc::SRTP_INVALID_CRYPTO_SUITE &&
4938 ssl_cipher_suite == rtc::TLS_NULL_WITH_NULL_NULL) {
4939 return;
4940 }
4941
4942 PeerConnectionEnumCounterType srtp_counter_type;
4943 PeerConnectionEnumCounterType ssl_counter_type;
4944 if (stats.transport_name == cricket::CN_AUDIO) {
4945 srtp_counter_type = kEnumCounterAudioSrtpCipher;
4946 ssl_counter_type = kEnumCounterAudioSslCipher;
4947 } else if (stats.transport_name == cricket::CN_VIDEO) {
4948 srtp_counter_type = kEnumCounterVideoSrtpCipher;
4949 ssl_counter_type = kEnumCounterVideoSslCipher;
4950 } else if (stats.transport_name == cricket::CN_DATA) {
4951 srtp_counter_type = kEnumCounterDataSrtpCipher;
4952 ssl_counter_type = kEnumCounterDataSslCipher;
4953 } else {
4954 RTC_NOTREACHED();
4955 return;
4956 }
4957
4958 if (srtp_crypto_suite != rtc::SRTP_INVALID_CRYPTO_SUITE) {
4959 metrics_observer()->IncrementSparseEnumCounter(srtp_counter_type,
4960 srtp_crypto_suite);
4961 }
4962 if (ssl_cipher_suite != rtc::TLS_NULL_WITH_NULL_NULL) {
4963 metrics_observer()->IncrementSparseEnumCounter(ssl_counter_type,
4964 ssl_cipher_suite);
4965 }
4966}
4967
4968void PeerConnection::OnSentPacket_w(const rtc::SentPacket& sent_packet) {
4969 RTC_DCHECK(worker_thread()->IsCurrent());
4970 RTC_DCHECK(call_);
4971 call_->OnSentPacket(sent_packet);
4972}
4973
4974const std::string PeerConnection::GetTransportName(
4975 const std::string& content_name) {
4976 cricket::BaseChannel* channel = GetChannel(content_name);
Steve Anton6fec8802017-12-04 10:37:29 -08004977 if (channel) {
4978 return channel->transport_name();
Steve Anton75737c02017-11-06 10:37:17 -08004979 }
Steve Anton6fec8802017-12-04 10:37:29 -08004980 if (sctp_transport_) {
4981 RTC_DCHECK(sctp_content_name_);
4982 RTC_DCHECK(sctp_transport_name_);
4983 if (content_name == *sctp_content_name_) {
4984 return *sctp_transport_name_;
4985 }
4986 }
4987 // Return an empty string if failed to retrieve the transport name.
4988 return "";
Steve Anton75737c02017-11-06 10:37:17 -08004989}
4990
4991void PeerConnection::DestroyRtcpTransport_n(const std::string& transport_name) {
4992 RTC_DCHECK(network_thread()->IsCurrent());
4993 transport_controller_->DestroyDtlsTransport_n(
4994 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
4995}
4996
Steve Anton6fec8802017-12-04 10:37:29 -08004997void PeerConnection::DestroyTransceiverChannel(
4998 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
4999 transceiver) {
5000 RTC_DCHECK(transceiver);
Steve Anton75737c02017-11-06 10:37:17 -08005001
Steve Anton6fec8802017-12-04 10:37:29 -08005002 cricket::BaseChannel* channel = transceiver->internal()->channel();
5003 if (channel) {
5004 transceiver->internal()->SetChannel(nullptr);
5005 DestroyBaseChannel(channel);
Steve Anton75737c02017-11-06 10:37:17 -08005006 }
5007}
5008
5009void PeerConnection::DestroyDataChannel() {
Steve Anton6fec8802017-12-04 10:37:29 -08005010 if (rtp_data_channel_) {
5011 OnDataChannelDestroyed();
5012 DestroyBaseChannel(rtp_data_channel_);
5013 rtp_data_channel_ = nullptr;
5014 }
5015
5016 // Note: Cannot use rtc::Bind to create a functor to invoke because it will
5017 // grab a reference to this PeerConnection. If this is called from the
5018 // PeerConnection destructor, the RefCountedObject vtable will have already
5019 // been destroyed (since it is a subclass of PeerConnection) and using
5020 // rtc::Bind will cause "Pure virtual function called" error to appear.
5021
5022 if (sctp_transport_) {
5023 OnDataChannelDestroyed();
5024 network_thread()->Invoke<void>(RTC_FROM_HERE,
5025 [this] { DestroySctpTransport_n(); });
5026 }
5027}
5028
5029void PeerConnection::DestroyBaseChannel(cricket::BaseChannel* channel) {
5030 RTC_DCHECK(channel);
5031 RTC_DCHECK(channel->rtp_dtls_transport());
5032
5033 // Need to cache these before destroying the base channel so that we do not
5034 // access uninitialized memory.
5035 const std::string transport_name =
5036 channel->rtp_dtls_transport()->transport_name();
5037 const bool need_to_delete_rtcp = (channel->rtcp_dtls_transport() != nullptr);
5038
5039 switch (channel->media_type()) {
5040 case cricket::MEDIA_TYPE_AUDIO:
5041 channel_manager()->DestroyVoiceChannel(
5042 static_cast<cricket::VoiceChannel*>(channel));
5043 break;
5044 case cricket::MEDIA_TYPE_VIDEO:
5045 channel_manager()->DestroyVideoChannel(
5046 static_cast<cricket::VideoChannel*>(channel));
5047 break;
5048 case cricket::MEDIA_TYPE_DATA:
5049 channel_manager()->DestroyRtpDataChannel(
5050 static_cast<cricket::RtpDataChannel*>(channel));
5051 break;
5052 default:
5053 RTC_NOTREACHED() << "Unknown media type: " << channel->media_type();
5054 break;
5055 }
5056
5057 // |channel| can no longer be used.
5058
Steve Anton75737c02017-11-06 10:37:17 -08005059 transport_controller_->DestroyDtlsTransport(
5060 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5061 if (need_to_delete_rtcp) {
5062 transport_controller_->DestroyDtlsTransport(
5063 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
5064 }
5065}
5066
henrike@webrtc.org28e20752013-07-10 00:45:36 +00005067} // namespace webrtc