blob: 78fcf1d6662610e5ba889f6c2ef338fef6d737e2 [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 Antondcc3c022017-12-22 16:02:54 -080014#include <queue>
Steve Anton75737c02017-11-06 10:37:17 -080015#include <set>
kwiberg0eb15ed2015-12-17 03:04:15 -080016#include <utility>
17#include <vector>
henrike@webrtc.org28e20752013-07-10 00:45:36 +000018
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020019#include "api/jsepicecandidate.h"
20#include "api/jsepsessiondescription.h"
21#include "api/mediaconstraintsinterface.h"
22#include "api/mediastreamproxy.h"
23#include "api/mediastreamtrackproxy.h"
24#include "call/call.h"
Elad Alon83ccca12017-10-04 13:18:26 +020025#include "logging/rtc_event_log/output/rtc_event_log_output_file.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020026#include "logging/rtc_event_log/rtc_event_log.h"
27#include "media/sctp/sctptransport.h"
28#include "pc/audiotrack.h"
Steve Anton75737c02017-11-06 10:37:17 -080029#include "pc/channel.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020030#include "pc/channelmanager.h"
31#include "pc/dtmfsender.h"
32#include "pc/mediastream.h"
33#include "pc/mediastreamobserver.h"
34#include "pc/remoteaudiosource.h"
Steve Anton1d03a752017-11-27 14:30:09 -080035#include "pc/rtpmediautils.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020036#include "pc/rtpreceiver.h"
37#include "pc/rtpsender.h"
Steve Anton75737c02017-11-06 10:37:17 -080038#include "pc/sctputils.h"
Steve Antona3a92c22017-12-07 10:27:41 -080039#include "pc/sdputils.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020040#include "pc/streamcollection.h"
41#include "pc/videocapturertracksource.h"
42#include "pc/videotrack.h"
43#include "rtc_base/bind.h"
44#include "rtc_base/checks.h"
45#include "rtc_base/logging.h"
Karl Wiberge40468b2017-11-22 10:42:26 +010046#include "rtc_base/numerics/safe_conversions.h"
Elad Alon83ccca12017-10-04 13:18:26 +020047#include "rtc_base/ptr_util.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020048#include "rtc_base/stringencode.h"
49#include "rtc_base/stringutils.h"
50#include "rtc_base/trace_event.h"
51#include "system_wrappers/include/clock.h"
52#include "system_wrappers/include/field_trial.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000053
Steve Anton75737c02017-11-06 10:37:17 -080054using cricket::ContentInfo;
55using cricket::ContentInfos;
56using cricket::MediaContentDescription;
57using cricket::SessionDescription;
Steve Anton5adfafd2017-12-20 16:34:00 -080058using cricket::MediaProtocolType;
Steve Anton75737c02017-11-06 10:37:17 -080059using cricket::TransportInfo;
60
61using cricket::LOCAL_PORT_TYPE;
62using cricket::STUN_PORT_TYPE;
63using cricket::RELAY_PORT_TYPE;
64using cricket::PRFLX_PORT_TYPE;
65
Steve Antonba818672017-11-06 10:21:57 -080066namespace webrtc {
67
Steve Anton75737c02017-11-06 10:37:17 -080068// Error messages
69const char kBundleWithoutRtcpMux[] =
70 "rtcp-mux must be enabled when BUNDLE "
71 "is enabled.";
Steve Anton75737c02017-11-06 10:37:17 -080072const char kInvalidCandidates[] = "Description contains invalid candidates.";
73const char kInvalidSdp[] = "Invalid session description.";
74const char kMlineMismatchInAnswer[] =
75 "The order of m-lines in answer doesn't match order in offer. Rejecting "
76 "answer.";
77const char kMlineMismatchInSubsequentOffer[] =
78 "The order of m-lines in subsequent offer doesn't match order from "
79 "previous offer/answer.";
Steve Anton75737c02017-11-06 10:37:17 -080080const char kSdpWithoutDtlsFingerprint[] =
81 "Called with SDP without DTLS fingerprint.";
82const char kSdpWithoutSdesCrypto[] = "Called with SDP without SDES crypto.";
83const char kSdpWithoutIceUfragPwd[] =
84 "Called with SDP without ice-ufrag and ice-pwd.";
85const char kSessionError[] = "Session error code: ";
86const char kSessionErrorDesc[] = "Session error description: ";
87const char kDtlsSrtpSetupFailureRtp[] =
88 "Couldn't set up DTLS-SRTP on RTP channel.";
89const char kDtlsSrtpSetupFailureRtcp[] =
90 "Couldn't set up DTLS-SRTP on RTCP channel.";
91const char kEnableBundleFailed[] = "Failed to enable BUNDLE.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +000092
Steve Anton75737c02017-11-06 10:37:17 -080093namespace {
henrike@webrtc.org28e20752013-07-10 00:45:36 +000094
deadbeefab9b2d12015-10-14 11:33:11 -070095static const char kDefaultStreamLabel[] = "default";
Steve Anton4171afb2017-11-20 10:20:22 -080096static const char kDefaultAudioSenderId[] = "defaulta0";
97static const char kDefaultVideoSenderId[] = "defaultv0";
deadbeefab9b2d12015-10-14 11:33:11 -070098
zhihuang8f65cdf2016-05-06 18:40:30 -070099// The length of RTCP CNAMEs.
100static const int kRtcpCnameLength = 16;
101
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000102enum {
wu@webrtc.org91053e72013-08-10 07:18:04 +0000103 MSG_SET_SESSIONDESCRIPTION_SUCCESS = 0,
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000104 MSG_SET_SESSIONDESCRIPTION_FAILED,
deadbeefab9b2d12015-10-14 11:33:11 -0700105 MSG_CREATE_SESSIONDESCRIPTION_FAILED,
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000106 MSG_GETSTATS,
deadbeefbd292462015-12-14 18:15:29 -0800107 MSG_FREE_DATACHANNELS,
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000108};
109
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000110struct SetSessionDescriptionMsg : public rtc::MessageData {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000111 explicit SetSessionDescriptionMsg(
112 webrtc::SetSessionDescriptionObserver* observer)
113 : observer(observer) {
114 }
115
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000116 rtc::scoped_refptr<webrtc::SetSessionDescriptionObserver> observer;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000117 std::string error;
118};
119
deadbeefab9b2d12015-10-14 11:33:11 -0700120struct CreateSessionDescriptionMsg : public rtc::MessageData {
121 explicit CreateSessionDescriptionMsg(
122 webrtc::CreateSessionDescriptionObserver* observer)
123 : observer(observer) {}
124
125 rtc::scoped_refptr<webrtc::CreateSessionDescriptionObserver> observer;
126 std::string error;
127};
128
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000129struct GetStatsMsg : public rtc::MessageData {
tommi@webrtc.org5b06b062014-08-15 08:38:30 +0000130 GetStatsMsg(webrtc::StatsObserver* observer,
131 webrtc::MediaStreamTrackInterface* track)
132 : observer(observer), track(track) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000133 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000134 rtc::scoped_refptr<webrtc::StatsObserver> observer;
tommi@webrtc.org5b06b062014-08-15 08:38:30 +0000135 rtc::scoped_refptr<webrtc::MediaStreamTrackInterface> track;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000136};
137
deadbeefab9b2d12015-10-14 11:33:11 -0700138// Check if we can send |new_stream| on a PeerConnection.
139bool CanAddLocalMediaStream(webrtc::StreamCollectionInterface* current_streams,
140 webrtc::MediaStreamInterface* new_stream) {
141 if (!new_stream || !current_streams) {
142 return false;
143 }
144 if (current_streams->find(new_stream->label()) != nullptr) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100145 RTC_LOG(LS_ERROR) << "MediaStream with label " << new_stream->label()
146 << " is already added.";
deadbeefab9b2d12015-10-14 11:33:11 -0700147 return false;
148 }
149 return true;
150}
151
deadbeef5e97fb52015-10-15 12:49:08 -0700152// If the direction is "recvonly" or "inactive", treat the description
153// as containing no streams.
154// See: https://code.google.com/p/webrtc/issues/detail?id=5054
155std::vector<cricket::StreamParams> GetActiveStreams(
156 const cricket::MediaContentDescription* desc) {
Steve Anton4e70a722017-11-28 14:57:10 -0800157 return RtpTransceiverDirectionHasSend(desc->direction())
deadbeef5e97fb52015-10-15 12:49:08 -0700158 ? desc->streams()
159 : std::vector<cricket::StreamParams>();
160}
161
deadbeefab9b2d12015-10-14 11:33:11 -0700162bool IsValidOfferToReceiveMedia(int value) {
163 typedef PeerConnectionInterface::RTCOfferAnswerOptions Options;
164 return (value >= Options::kUndefined) &&
165 (value <= Options::kMaxOfferToReceiveMedia);
166}
167
zhihuang1c378ed2017-08-17 14:10:50 -0700168// Add options to |[audio/video]_media_description_options| from |senders|.
169void AddRtpSenderOptions(
deadbeefa601f5c2016-06-06 14:27:39 -0700170 const std::vector<rtc::scoped_refptr<
171 RtpSenderProxyWithInternal<RtpSenderInternal>>>& senders,
zhihuang1c378ed2017-08-17 14:10:50 -0700172 cricket::MediaDescriptionOptions* audio_media_description_options,
173 cricket::MediaDescriptionOptions* video_media_description_options) {
olka3c747662017-08-17 06:50:32 -0700174 for (const auto& sender : senders) {
zhihuang1c378ed2017-08-17 14:10:50 -0700175 if (sender->media_type() == cricket::MEDIA_TYPE_AUDIO) {
176 if (audio_media_description_options) {
177 audio_media_description_options->AddAudioSender(
Steve Anton8ffb9c32017-08-31 15:45:38 -0700178 sender->id(), sender->internal()->stream_ids());
zhihuang1c378ed2017-08-17 14:10:50 -0700179 }
180 } else {
181 RTC_DCHECK(sender->media_type() == cricket::MEDIA_TYPE_VIDEO);
182 if (video_media_description_options) {
183 video_media_description_options->AddVideoSender(
Steve Anton8ffb9c32017-08-31 15:45:38 -0700184 sender->id(), sender->internal()->stream_ids(), 1);
zhihuang1c378ed2017-08-17 14:10:50 -0700185 }
186 }
zhihuanga77e6bb2017-08-14 18:17:48 -0700187 }
zhihuang1c378ed2017-08-17 14:10:50 -0700188}
olka3c747662017-08-17 06:50:32 -0700189
zhihuang1c378ed2017-08-17 14:10:50 -0700190// Add options to |session_options| from |rtp_data_channels|.
191void AddRtpDataChannelOptions(
192 const std::map<std::string, rtc::scoped_refptr<DataChannel>>&
193 rtp_data_channels,
194 cricket::MediaDescriptionOptions* data_media_description_options) {
195 if (!data_media_description_options) {
196 return;
197 }
deadbeefab9b2d12015-10-14 11:33:11 -0700198 // Check for data channels.
199 for (const auto& kv : rtp_data_channels) {
200 const DataChannel* channel = kv.second;
201 if (channel->state() == DataChannel::kConnecting ||
202 channel->state() == DataChannel::kOpen) {
zhihuang1c378ed2017-08-17 14:10:50 -0700203 // Legacy RTP data channels are signaled with the track/stream ID set to
204 // the data channel's label.
205 data_media_description_options->AddRtpDataChannel(channel->label(),
206 channel->label());
deadbeefab9b2d12015-10-14 11:33:11 -0700207 }
208 }
209}
210
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700211uint32_t ConvertIceTransportTypeToCandidateFilter(
212 PeerConnectionInterface::IceTransportsType type) {
213 switch (type) {
214 case PeerConnectionInterface::kNone:
215 return cricket::CF_NONE;
216 case PeerConnectionInterface::kRelay:
217 return cricket::CF_RELAY;
218 case PeerConnectionInterface::kNoHost:
219 return (cricket::CF_ALL & ~cricket::CF_HOST);
220 case PeerConnectionInterface::kAll:
221 return cricket::CF_ALL;
222 default:
nissec80e7412017-01-11 05:56:46 -0800223 RTC_NOTREACHED();
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700224 }
225 return cricket::CF_NONE;
226}
227
deadbeef293e9262017-01-11 12:28:30 -0800228// Helper to set an error and return from a method.
229bool SafeSetError(webrtc::RTCErrorType type, webrtc::RTCError* error) {
230 if (error) {
231 error->set_type(type);
232 }
233 return type == webrtc::RTCErrorType::NONE;
234}
235
Steve Anton038834f2017-07-14 15:59:59 -0700236bool SafeSetError(webrtc::RTCError error, webrtc::RTCError* error_out) {
237 if (error_out) {
238 *error_out = std::move(error);
239 }
240 return error.ok();
241}
242
Steve Antonba818672017-11-06 10:21:57 -0800243std::string GetSignalingStateString(
244 PeerConnectionInterface::SignalingState state) {
245 switch (state) {
246 case PeerConnectionInterface::kStable:
247 return "kStable";
248 case PeerConnectionInterface::kHaveLocalOffer:
249 return "kHaveLocalOffer";
250 case PeerConnectionInterface::kHaveLocalPrAnswer:
251 return "kHavePrAnswer";
252 case PeerConnectionInterface::kHaveRemoteOffer:
253 return "kHaveRemoteOffer";
254 case PeerConnectionInterface::kHaveRemotePrAnswer:
255 return "kHaveRemotePrAnswer";
256 case PeerConnectionInterface::kClosed:
257 return "kClosed";
258 }
259 RTC_NOTREACHED();
260 return "";
261}
deadbeef0a6c4ca2015-10-06 11:38:28 -0700262
Steve Anton75737c02017-11-06 10:37:17 -0800263IceCandidatePairType GetIceCandidatePairCounter(
264 const cricket::Candidate& local,
265 const cricket::Candidate& remote) {
266 const auto& l = local.type();
267 const auto& r = remote.type();
268 const auto& host = LOCAL_PORT_TYPE;
269 const auto& srflx = STUN_PORT_TYPE;
270 const auto& relay = RELAY_PORT_TYPE;
271 const auto& prflx = PRFLX_PORT_TYPE;
272 if (l == host && r == host) {
273 bool local_private = IPIsPrivate(local.address().ipaddr());
274 bool remote_private = IPIsPrivate(remote.address().ipaddr());
275 if (local_private) {
276 if (remote_private) {
277 return kIceCandidatePairHostPrivateHostPrivate;
278 } else {
279 return kIceCandidatePairHostPrivateHostPublic;
280 }
281 } else {
282 if (remote_private) {
283 return kIceCandidatePairHostPublicHostPrivate;
284 } else {
285 return kIceCandidatePairHostPublicHostPublic;
286 }
287 }
288 }
289 if (l == host && r == srflx)
290 return kIceCandidatePairHostSrflx;
291 if (l == host && r == relay)
292 return kIceCandidatePairHostRelay;
293 if (l == host && r == prflx)
294 return kIceCandidatePairHostPrflx;
295 if (l == srflx && r == host)
296 return kIceCandidatePairSrflxHost;
297 if (l == srflx && r == srflx)
298 return kIceCandidatePairSrflxSrflx;
299 if (l == srflx && r == relay)
300 return kIceCandidatePairSrflxRelay;
301 if (l == srflx && r == prflx)
302 return kIceCandidatePairSrflxPrflx;
303 if (l == relay && r == host)
304 return kIceCandidatePairRelayHost;
305 if (l == relay && r == srflx)
306 return kIceCandidatePairRelaySrflx;
307 if (l == relay && r == relay)
308 return kIceCandidatePairRelayRelay;
309 if (l == relay && r == prflx)
310 return kIceCandidatePairRelayPrflx;
311 if (l == prflx && r == host)
312 return kIceCandidatePairPrflxHost;
313 if (l == prflx && r == srflx)
314 return kIceCandidatePairPrflxSrflx;
315 if (l == prflx && r == relay)
316 return kIceCandidatePairPrflxRelay;
317 return kIceCandidatePairMax;
318}
319
320// Verify that the order of media sections in |new_desc| matches
321// |existing_desc|. The number of m= sections in |new_desc| should be no less
322// than |existing_desc|.
323bool MediaSectionsInSameOrder(const SessionDescription* existing_desc,
324 const SessionDescription* new_desc) {
325 if (!existing_desc || !new_desc) {
326 return false;
327 }
328
329 if (existing_desc->contents().size() > new_desc->contents().size()) {
330 return false;
331 }
332
333 for (size_t i = 0; i < existing_desc->contents().size(); ++i) {
Steve Antondcc3c022017-12-22 16:02:54 -0800334 if (existing_desc->contents()[i].rejected) {
335 // If the media section can be recycled, it's valid for the MID and media
336 // type to change.
337 continue;
338 }
Steve Anton75737c02017-11-06 10:37:17 -0800339 if (new_desc->contents()[i].name != existing_desc->contents()[i].name) {
340 return false;
341 }
342 const MediaContentDescription* new_desc_mdesc =
Steve Antonb1c1de12017-12-21 15:14:30 -0800343 new_desc->contents()[i].media_description();
Steve Anton75737c02017-11-06 10:37:17 -0800344 const MediaContentDescription* existing_desc_mdesc =
Steve Antonb1c1de12017-12-21 15:14:30 -0800345 existing_desc->contents()[i].media_description();
Steve Anton75737c02017-11-06 10:37:17 -0800346 if (new_desc_mdesc->type() != existing_desc_mdesc->type()) {
347 return false;
348 }
349 }
350 return true;
351}
352
353bool MediaSectionsHaveSameCount(const SessionDescription* desc1,
354 const SessionDescription* desc2) {
355 if (!desc1 || !desc2) {
356 return false;
357 }
358 return desc1->contents().size() == desc2->contents().size();
359}
360
361// Checks that each non-rejected content has SDES crypto keys or a DTLS
362// fingerprint, unless it's in a BUNDLE group, in which case only the
363// BUNDLE-tag section (first media section/description in the BUNDLE group)
364// needs a ufrag and pwd. Mismatches, such as replying with a DTLS fingerprint
365// to SDES keys, will be caught in JsepTransport negotiation, and backstopped
366// by Channel's |srtp_required| check.
Steve Anton8a006912017-12-04 15:25:56 -0800367RTCError VerifyCrypto(const SessionDescription* desc, bool dtls_enabled) {
Steve Anton75737c02017-11-06 10:37:17 -0800368 const cricket::ContentGroup* bundle =
369 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton8a006912017-12-04 15:25:56 -0800370 for (const cricket::ContentInfo& content_info : desc->contents()) {
371 if (content_info.rejected) {
Steve Anton75737c02017-11-06 10:37:17 -0800372 continue;
373 }
Steve Anton8a006912017-12-04 15:25:56 -0800374 const std::string& mid = content_info.name;
375 if (bundle && bundle->HasContentName(mid) &&
376 mid != *(bundle->FirstContentName())) {
Steve Anton75737c02017-11-06 10:37:17 -0800377 // This isn't the first media section in the BUNDLE group, so it's not
378 // required to have crypto attributes, since only the crypto attributes
379 // from the first section actually get used.
380 continue;
381 }
382
383 // If the content isn't rejected or bundled into another m= section, crypto
384 // must be present.
Steve Antonb1c1de12017-12-21 15:14:30 -0800385 const MediaContentDescription* media = content_info.media_description();
Steve Anton8a006912017-12-04 15:25:56 -0800386 const TransportInfo* tinfo = desc->GetTransportInfoByName(mid);
Steve Anton75737c02017-11-06 10:37:17 -0800387 if (!media || !tinfo) {
388 // Something is not right.
Steve Anton8a006912017-12-04 15:25:56 -0800389 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidSdp);
Steve Anton75737c02017-11-06 10:37:17 -0800390 }
391 if (dtls_enabled) {
392 if (!tinfo->description.identity_fingerprint) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100393 RTC_LOG(LS_WARNING)
394 << "Session description must have DTLS fingerprint if "
395 "DTLS enabled.";
Steve Anton8a006912017-12-04 15:25:56 -0800396 return RTCError(RTCErrorType::INVALID_PARAMETER,
397 kSdpWithoutDtlsFingerprint);
Steve Anton75737c02017-11-06 10:37:17 -0800398 }
399 } else {
400 if (media->cryptos().empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100401 RTC_LOG(LS_WARNING)
Steve Anton75737c02017-11-06 10:37:17 -0800402 << "Session description must have SDES when DTLS disabled.";
Steve Anton8a006912017-12-04 15:25:56 -0800403 return RTCError(RTCErrorType::INVALID_PARAMETER, kSdpWithoutSdesCrypto);
Steve Anton75737c02017-11-06 10:37:17 -0800404 }
405 }
406 }
Steve Anton8a006912017-12-04 15:25:56 -0800407 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -0800408}
409
410// Checks that each non-rejected content has ice-ufrag and ice-pwd set, unless
411// it's in a BUNDLE group, in which case only the BUNDLE-tag section (first
412// media section/description in the BUNDLE group) needs a ufrag and pwd.
413bool VerifyIceUfragPwdPresent(const SessionDescription* desc) {
414 const cricket::ContentGroup* bundle =
415 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton8a006912017-12-04 15:25:56 -0800416 for (const cricket::ContentInfo& content_info : desc->contents()) {
417 if (content_info.rejected) {
Steve Anton75737c02017-11-06 10:37:17 -0800418 continue;
419 }
Steve Anton8a006912017-12-04 15:25:56 -0800420 const std::string& mid = content_info.name;
421 if (bundle && bundle->HasContentName(mid) &&
422 mid != *(bundle->FirstContentName())) {
Steve Anton75737c02017-11-06 10:37:17 -0800423 // This isn't the first media section in the BUNDLE group, so it's not
424 // required to have ufrag/password, since only the ufrag/password from
425 // the first section actually get used.
426 continue;
427 }
428
429 // If the content isn't rejected or bundled into another m= section,
430 // ice-ufrag and ice-pwd must be present.
Steve Anton8a006912017-12-04 15:25:56 -0800431 const TransportInfo* tinfo = desc->GetTransportInfoByName(mid);
Steve Anton75737c02017-11-06 10:37:17 -0800432 if (!tinfo) {
433 // Something is not right.
Mirko Bonadei675513b2017-11-09 11:09:25 +0100434 RTC_LOG(LS_ERROR) << kInvalidSdp;
Steve Anton75737c02017-11-06 10:37:17 -0800435 return false;
436 }
437 if (tinfo->description.ice_ufrag.empty() ||
438 tinfo->description.ice_pwd.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100439 RTC_LOG(LS_ERROR) << "Session description must have ice ufrag and pwd.";
Steve Anton75737c02017-11-06 10:37:17 -0800440 return false;
441 }
442 }
443 return true;
444}
445
446bool GetTrackIdBySsrc(const SessionDescription* session_description,
447 uint32_t ssrc,
448 std::string* track_id) {
449 RTC_DCHECK(track_id != NULL);
450
Steve Antonb1c1de12017-12-21 15:14:30 -0800451 const cricket::AudioContentDescription* audio_desc =
452 cricket::GetFirstAudioContentDescription(session_description);
453 if (audio_desc) {
454 const auto* found = cricket::GetStreamBySsrc(audio_desc->streams(), ssrc);
Steve Anton75737c02017-11-06 10:37:17 -0800455 if (found) {
456 *track_id = found->id;
457 return true;
458 }
459 }
460
Steve Antonb1c1de12017-12-21 15:14:30 -0800461 const cricket::VideoContentDescription* video_desc =
462 cricket::GetFirstVideoContentDescription(session_description);
463 if (video_desc) {
464 const auto* found = cricket::GetStreamBySsrc(video_desc->streams(), ssrc);
Steve Anton75737c02017-11-06 10:37:17 -0800465 if (found) {
466 *track_id = found->id;
467 return true;
468 }
469 }
470 return false;
471}
472
473// Get the SCTP port out of a SessionDescription.
474// Return -1 if not found.
475int GetSctpPort(const SessionDescription* session_description) {
Steve Antonb1c1de12017-12-21 15:14:30 -0800476 const cricket::DataContentDescription* data_desc =
477 GetFirstDataContentDescription(session_description);
478 RTC_DCHECK(data_desc);
479 if (!data_desc) {
Steve Anton75737c02017-11-06 10:37:17 -0800480 return -1;
481 }
Steve Anton75737c02017-11-06 10:37:17 -0800482 std::string value;
483 cricket::DataCodec match_pattern(cricket::kGoogleSctpDataCodecPlType,
484 cricket::kGoogleSctpDataCodecName);
Steve Antonb1c1de12017-12-21 15:14:30 -0800485 for (const cricket::DataCodec& codec : data_desc->codecs()) {
Steve Anton75737c02017-11-06 10:37:17 -0800486 if (!codec.Matches(match_pattern)) {
487 continue;
488 }
489 if (codec.GetParam(cricket::kCodecParamPort, &value)) {
490 return rtc::FromString<int>(value);
491 }
492 }
493 return -1;
494}
495
Steve Anton75737c02017-11-06 10:37:17 -0800496// Returns true if |new_desc| requests an ICE restart (i.e., new ufrag/pwd).
497bool CheckForRemoteIceRestart(const SessionDescriptionInterface* old_desc,
498 const SessionDescriptionInterface* new_desc,
499 const std::string& content_name) {
500 if (!old_desc) {
501 return false;
502 }
503 const SessionDescription* new_sd = new_desc->description();
504 const SessionDescription* old_sd = old_desc->description();
505 const ContentInfo* cinfo = new_sd->GetContentByName(content_name);
506 if (!cinfo || cinfo->rejected) {
507 return false;
508 }
509 // If the content isn't rejected, check if ufrag and password has changed.
510 const cricket::TransportDescription* new_transport_desc =
511 new_sd->GetTransportDescriptionByName(content_name);
512 const cricket::TransportDescription* old_transport_desc =
513 old_sd->GetTransportDescriptionByName(content_name);
514 if (!new_transport_desc || !old_transport_desc) {
515 // No transport description exists. This is not an ICE restart.
516 return false;
517 }
518 if (cricket::IceCredentialsChanged(
519 old_transport_desc->ice_ufrag, old_transport_desc->ice_pwd,
520 new_transport_desc->ice_ufrag, new_transport_desc->ice_pwd)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100521 RTC_LOG(LS_INFO) << "Remote peer requests ICE restart for " << content_name
522 << ".";
Steve Anton75737c02017-11-06 10:37:17 -0800523 return true;
524 }
525 return false;
526}
527
528} // namespace
529
Henrik Boström31638672017-11-23 17:48:32 +0100530// Upon completion, posts a task to execute the callback of the
531// SetSessionDescriptionObserver asynchronously on the same thread. At this
532// point, the state of the peer connection might no longer reflect the effects
533// of the SetRemoteDescription operation, as the peer connection could have been
534// modified during the post.
535// TODO(hbos): Remove this class once we remove the version of
536// PeerConnectionInterface::SetRemoteDescription() that takes a
537// SetSessionDescriptionObserver as an argument.
538class PeerConnection::SetRemoteDescriptionObserverAdapter
539 : public rtc::RefCountedObject<SetRemoteDescriptionObserverInterface> {
540 public:
541 SetRemoteDescriptionObserverAdapter(
542 rtc::scoped_refptr<PeerConnection> pc,
543 rtc::scoped_refptr<SetSessionDescriptionObserver> wrapper)
544 : pc_(std::move(pc)), wrapper_(std::move(wrapper)) {}
545
546 // SetRemoteDescriptionObserverInterface implementation.
547 void OnSetRemoteDescriptionComplete(RTCError error) override {
548 if (error.ok())
549 pc_->PostSetSessionDescriptionSuccess(wrapper_);
550 else
551 pc_->PostSetSessionDescriptionFailure(wrapper_, error.message());
552 }
553
554 private:
555 rtc::scoped_refptr<PeerConnection> pc_;
556 rtc::scoped_refptr<SetSessionDescriptionObserver> wrapper_;
557};
558
deadbeef293e9262017-01-11 12:28:30 -0800559bool PeerConnectionInterface::RTCConfiguration::operator==(
560 const PeerConnectionInterface::RTCConfiguration& o) const {
561 // This static_assert prevents us from accidentally breaking operator==.
Steve Anton300bf8e2017-07-14 10:13:10 -0700562 // Note: Order matters! Fields must be ordered the same as RTCConfiguration.
deadbeef293e9262017-01-11 12:28:30 -0800563 struct stuff_being_tested_for_equality {
Magnus Jedvert3beb2072017-07-14 14:23:56 +0000564 IceServers servers;
Steve Anton300bf8e2017-07-14 10:13:10 -0700565 IceTransportsType type;
deadbeef293e9262017-01-11 12:28:30 -0800566 BundlePolicy bundle_policy;
567 RtcpMuxPolicy rtcp_mux_policy;
Steve Anton300bf8e2017-07-14 10:13:10 -0700568 std::vector<rtc::scoped_refptr<rtc::RTCCertificate>> certificates;
569 int ice_candidate_pool_size;
570 bool disable_ipv6;
571 bool disable_ipv6_on_wifi;
deadbeefd21eab32017-07-26 16:50:11 -0700572 int max_ipv6_networks;
Steve Anton300bf8e2017-07-14 10:13:10 -0700573 bool enable_rtp_data_channel;
574 rtc::Optional<int> screencast_min_bitrate;
575 rtc::Optional<bool> combined_audio_video_bwe;
576 rtc::Optional<bool> enable_dtls_srtp;
deadbeef293e9262017-01-11 12:28:30 -0800577 TcpCandidatePolicy tcp_candidate_policy;
578 CandidateNetworkPolicy candidate_network_policy;
579 int audio_jitter_buffer_max_packets;
580 bool audio_jitter_buffer_fast_accelerate;
581 int ice_connection_receiving_timeout;
582 int ice_backup_candidate_pair_ping_interval;
583 ContinualGatheringPolicy continual_gathering_policy;
deadbeef293e9262017-01-11 12:28:30 -0800584 bool prioritize_most_likely_ice_candidate_pairs;
585 struct cricket::MediaConfig media_config;
deadbeef293e9262017-01-11 12:28:30 -0800586 bool prune_turn_ports;
587 bool presume_writable_when_fully_relayed;
588 bool enable_ice_renomination;
589 bool redetermine_role_on_ice_restart;
skvlad51072462017-02-02 11:50:14 -0800590 rtc::Optional<int> ice_check_min_interval;
Steve Anton300bf8e2017-07-14 10:13:10 -0700591 rtc::Optional<rtc::IntervalRange> ice_regather_interval_range;
Jonas Orelandbdcee282017-10-10 14:01:40 +0200592 webrtc::TurnCustomizer* turn_customizer;
Steve Anton79e79602017-11-20 10:25:56 -0800593 SdpSemantics sdp_semantics;
deadbeef293e9262017-01-11 12:28:30 -0800594 };
595 static_assert(sizeof(stuff_being_tested_for_equality) == sizeof(*this),
596 "Did you add something to RTCConfiguration and forget to "
597 "update operator==?");
598 return type == o.type && servers == o.servers &&
599 bundle_policy == o.bundle_policy &&
600 rtcp_mux_policy == o.rtcp_mux_policy &&
601 tcp_candidate_policy == o.tcp_candidate_policy &&
602 candidate_network_policy == o.candidate_network_policy &&
603 audio_jitter_buffer_max_packets == o.audio_jitter_buffer_max_packets &&
604 audio_jitter_buffer_fast_accelerate ==
605 o.audio_jitter_buffer_fast_accelerate &&
606 ice_connection_receiving_timeout ==
607 o.ice_connection_receiving_timeout &&
608 ice_backup_candidate_pair_ping_interval ==
609 o.ice_backup_candidate_pair_ping_interval &&
610 continual_gathering_policy == o.continual_gathering_policy &&
611 certificates == o.certificates &&
612 prioritize_most_likely_ice_candidate_pairs ==
613 o.prioritize_most_likely_ice_candidate_pairs &&
614 media_config == o.media_config && disable_ipv6 == o.disable_ipv6 &&
zhihuangb09b3f92017-03-07 14:40:51 -0800615 disable_ipv6_on_wifi == o.disable_ipv6_on_wifi &&
deadbeefd21eab32017-07-26 16:50:11 -0700616 max_ipv6_networks == o.max_ipv6_networks &&
deadbeef293e9262017-01-11 12:28:30 -0800617 enable_rtp_data_channel == o.enable_rtp_data_channel &&
deadbeef293e9262017-01-11 12:28:30 -0800618 screencast_min_bitrate == o.screencast_min_bitrate &&
619 combined_audio_video_bwe == o.combined_audio_video_bwe &&
620 enable_dtls_srtp == o.enable_dtls_srtp &&
621 ice_candidate_pool_size == o.ice_candidate_pool_size &&
622 prune_turn_ports == o.prune_turn_ports &&
623 presume_writable_when_fully_relayed ==
624 o.presume_writable_when_fully_relayed &&
625 enable_ice_renomination == o.enable_ice_renomination &&
skvlad51072462017-02-02 11:50:14 -0800626 redetermine_role_on_ice_restart == o.redetermine_role_on_ice_restart &&
Steve Anton300bf8e2017-07-14 10:13:10 -0700627 ice_check_min_interval == o.ice_check_min_interval &&
Jonas Orelandbdcee282017-10-10 14:01:40 +0200628 ice_regather_interval_range == o.ice_regather_interval_range &&
Steve Anton79e79602017-11-20 10:25:56 -0800629 turn_customizer == o.turn_customizer &&
630 sdp_semantics == o.sdp_semantics;
deadbeef293e9262017-01-11 12:28:30 -0800631}
632
633bool PeerConnectionInterface::RTCConfiguration::operator!=(
634 const PeerConnectionInterface::RTCConfiguration& o) const {
635 return !(*this == o);
deadbeef3edec7c2016-12-10 11:44:26 -0800636}
637
zhihuang8f65cdf2016-05-06 18:40:30 -0700638// Generate a RTCP CNAME when a PeerConnection is created.
639std::string GenerateRtcpCname() {
640 std::string cname;
641 if (!rtc::CreateRandomString(kRtcpCnameLength, &cname)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100642 RTC_LOG(LS_ERROR) << "Failed to generate CNAME.";
nisseeb4ca4e2017-01-12 02:24:27 -0800643 RTC_NOTREACHED();
zhihuang8f65cdf2016-05-06 18:40:30 -0700644 }
645 return cname;
646}
647
zhihuang1c378ed2017-08-17 14:10:50 -0700648bool ValidateOfferAnswerOptions(
649 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options) {
650 return IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_audio) &&
651 IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_video);
olka3c747662017-08-17 06:50:32 -0700652}
653
zhihuang1c378ed2017-08-17 14:10:50 -0700654// From |rtc_options|, fill parts of |session_options| shared by all generated
655// m= sections (in other words, nothing that involves a map/array).
656void ExtractSharedMediaSessionOptions(
657 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options,
658 cricket::MediaSessionOptions* session_options) {
659 session_options->vad_enabled = rtc_options.voice_activity_detection;
660 session_options->bundle_enabled = rtc_options.use_rtp_mux;
661}
zhihuanga77e6bb2017-08-14 18:17:48 -0700662
zhihuang1c378ed2017-08-17 14:10:50 -0700663bool ConvertConstraintsToOfferAnswerOptions(
664 const MediaConstraintsInterface* constraints,
665 PeerConnectionInterface::RTCOfferAnswerOptions* offer_answer_options) {
olka3c747662017-08-17 06:50:32 -0700666 if (!constraints) {
667 return true;
668 }
zhihuang1c378ed2017-08-17 14:10:50 -0700669
670 bool value = false;
671 size_t mandatory_constraints_satisfied = 0;
672
673 if (FindConstraint(constraints,
674 MediaConstraintsInterface::kOfferToReceiveAudio, &value,
675 &mandatory_constraints_satisfied)) {
676 offer_answer_options->offer_to_receive_audio =
677 value ? PeerConnectionInterface::RTCOfferAnswerOptions::
678 kOfferToReceiveMediaTrue
679 : 0;
680 }
681
682 if (FindConstraint(constraints,
683 MediaConstraintsInterface::kOfferToReceiveVideo, &value,
684 &mandatory_constraints_satisfied)) {
685 offer_answer_options->offer_to_receive_video =
686 value ? PeerConnectionInterface::RTCOfferAnswerOptions::
687 kOfferToReceiveMediaTrue
688 : 0;
689 }
690 if (FindConstraint(constraints,
691 MediaConstraintsInterface::kVoiceActivityDetection, &value,
692 &mandatory_constraints_satisfied)) {
693 offer_answer_options->voice_activity_detection = value;
694 }
695 if (FindConstraint(constraints, MediaConstraintsInterface::kUseRtpMux, &value,
696 &mandatory_constraints_satisfied)) {
697 offer_answer_options->use_rtp_mux = value;
698 }
699 if (FindConstraint(constraints, MediaConstraintsInterface::kIceRestart,
700 &value, &mandatory_constraints_satisfied)) {
701 offer_answer_options->ice_restart = value;
702 }
703
deadbeefab9b2d12015-10-14 11:33:11 -0700704 return mandatory_constraints_satisfied == constraints->GetMandatory().size();
705}
706
zhihuang38ede132017-06-15 12:52:32 -0700707PeerConnection::PeerConnection(PeerConnectionFactory* factory,
708 std::unique_ptr<RtcEventLog> event_log,
709 std::unique_ptr<Call> call)
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000710 : factory_(factory),
zhihuang38ede132017-06-15 12:52:32 -0700711 event_log_(std::move(event_log)),
zhihuang8f65cdf2016-05-06 18:40:30 -0700712 rtcp_cname_(GenerateRtcpCname()),
deadbeefab9b2d12015-10-14 11:33:11 -0700713 local_streams_(StreamCollection::Create()),
zhihuang38ede132017-06-15 12:52:32 -0700714 remote_streams_(StreamCollection::Create()),
715 call_(std::move(call)) {}
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000716
717PeerConnection::~PeerConnection() {
Peter Boström1a9d6152015-12-08 22:15:17 +0100718 TRACE_EVENT0("webrtc", "PeerConnection::~PeerConnection");
Steve Anton4171afb2017-11-20 10:20:22 -0800719 RTC_DCHECK_RUN_ON(signaling_thread());
720
Steve Anton8af21862017-12-15 11:20:13 -0800721 // Need to stop transceivers before destroying the stats collector because
722 // AudioRtpSender has a reference to the StatsCollector it will update when
723 // stopping.
724 for (auto transceiver : transceivers_) {
725 transceiver->Stop();
726 }
Steve Anton4171afb2017-11-20 10:20:22 -0800727
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700728 stats_.reset(nullptr);
hbosb78306a2016-12-19 05:06:57 -0800729 if (stats_collector_) {
730 stats_collector_->WaitForPendingRequest();
731 stats_collector_ = nullptr;
732 }
Steve Anton75737c02017-11-06 10:37:17 -0800733
Steve Anton8af21862017-12-15 11:20:13 -0800734 // Don't destroy BaseChannels until after stats has been cleaned up so that
735 // the last stats request can still read from the channels.
736 DestroyAllChannels();
737
Mirko Bonadei675513b2017-11-09 11:09:25 +0100738 RTC_LOG(LS_INFO) << "Session: " << session_id() << " is destroyed.";
Steve Anton75737c02017-11-06 10:37:17 -0800739
740 webrtc_session_desc_factory_.reset();
741 sctp_invoker_.reset();
742 sctp_factory_.reset();
743 transport_controller_.reset();
744
deadbeef91dd5672016-05-18 16:55:30 -0700745 // port_allocator_ lives on the network thread and should be destroyed there.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700746 network_thread()->Invoke<void>(RTC_FROM_HERE,
nisseeaabdf62017-05-05 02:23:02 -0700747 [this] { port_allocator_.reset(); });
eladalon248fd4f2017-09-06 05:18:15 -0700748 // call_ and event_log_ must be destroyed on the worker thread.
Steve Anton978b8762017-09-29 12:15:02 -0700749 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
eladalon248fd4f2017-09-06 05:18:15 -0700750 call_.reset();
751 event_log_.reset();
752 });
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000753}
754
Steve Anton8af21862017-12-15 11:20:13 -0800755void PeerConnection::DestroyAllChannels() {
Steve Anton3fe1b152017-12-12 10:20:08 -0800756 // Destroy video channels first since they may have a pointer to a voice
757 // channel.
758 for (auto transceiver : transceivers_) {
759 if (transceiver->internal()->media_type() == cricket::MEDIA_TYPE_VIDEO) {
760 DestroyTransceiverChannel(transceiver);
761 }
762 }
763 for (auto transceiver : transceivers_) {
764 if (transceiver->internal()->media_type() == cricket::MEDIA_TYPE_AUDIO) {
765 DestroyTransceiverChannel(transceiver);
766 }
767 }
768 DestroyDataChannel();
769}
770
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000771bool PeerConnection::Initialize(
buildbot@webrtc.org41451d42014-05-03 05:39:45 +0000772 const PeerConnectionInterface::RTCConfiguration& configuration,
kwibergd1fe2812016-04-27 06:47:29 -0700773 std::unique_ptr<cricket::PortAllocator> allocator,
Henrik Boströmd03c23b2016-06-01 11:44:18 +0200774 std::unique_ptr<rtc::RTCCertificateGeneratorInterface> cert_generator,
deadbeef653b8e02015-11-11 12:55:10 -0800775 PeerConnectionObserver* observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100776 TRACE_EVENT0("webrtc", "PeerConnection::Initialize");
Steve Anton038834f2017-07-14 15:59:59 -0700777
778 RTCError config_error = ValidateConfiguration(configuration);
779 if (!config_error.ok()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100780 RTC_LOG(LS_ERROR) << "Invalid configuration: " << config_error.message();
Steve Anton038834f2017-07-14 15:59:59 -0700781 return false;
782 }
783
deadbeef293e9262017-01-11 12:28:30 -0800784 if (!allocator) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100785 RTC_LOG(LS_ERROR)
786 << "PeerConnection initialized without a PortAllocator? "
787 << "This shouldn't happen if using PeerConnectionFactory.";
deadbeef293e9262017-01-11 12:28:30 -0800788 return false;
789 }
Jonas Orelandbdcee282017-10-10 14:01:40 +0200790
deadbeef653b8e02015-11-11 12:55:10 -0800791 if (!observer) {
deadbeef293e9262017-01-11 12:28:30 -0800792 // TODO(deadbeef): Why do we do this?
Mirko Bonadei675513b2017-11-09 11:09:25 +0100793 RTC_LOG(LS_ERROR) << "PeerConnection initialized without a "
794 << "PeerConnectionObserver";
deadbeef653b8e02015-11-11 12:55:10 -0800795 return false;
796 }
pthatcher@webrtc.org877ac762015-02-04 22:03:09 +0000797 observer_ = observer;
kwiberg0eb15ed2015-12-17 03:04:15 -0800798 port_allocator_ = std::move(allocator);
deadbeef653b8e02015-11-11 12:55:10 -0800799
deadbeef91dd5672016-05-18 16:55:30 -0700800 // The port allocator lives on the network thread and should be initialized
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700801 // there.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700802 if (!network_thread()->Invoke<bool>(
803 RTC_FROM_HERE, rtc::Bind(&PeerConnection::InitializePortAllocator_n,
804 this, configuration))) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000805 return false;
806 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000807
Steve Anton75737c02017-11-06 10:37:17 -0800808 // RFC 3264: The numeric value of the session id and version in the
809 // o line MUST be representable with a "64 bit signed integer".
810 // Due to this constraint session id |session_id_| is max limited to
811 // LLONG_MAX.
812 session_id_ = rtc::ToString(rtc::CreateRandomId64() & LLONG_MAX);
813 transport_controller_.reset(factory_->CreateTransportController(
814 port_allocator_.get(), configuration.redetermine_role_on_ice_restart));
815 transport_controller_->SetIceRole(cricket::ICEROLE_CONTROLLED);
816 transport_controller_->SignalConnectionState.connect(
817 this, &PeerConnection::OnTransportControllerConnectionState);
818 transport_controller_->SignalGatheringState.connect(
819 this, &PeerConnection::OnTransportControllerGatheringState);
820 transport_controller_->SignalCandidatesGathered.connect(
821 this, &PeerConnection::OnTransportControllerCandidatesGathered);
822 transport_controller_->SignalCandidatesRemoved.connect(
823 this, &PeerConnection::OnTransportControllerCandidatesRemoved);
824 transport_controller_->SignalDtlsHandshakeError.connect(
825 this, &PeerConnection::OnTransportControllerDtlsHandshakeError);
826
827 sctp_factory_ = factory_->CreateSctpTransportInternalFactory();
zhihuang29ff8442016-07-27 11:07:25 -0700828
deadbeefab9b2d12015-10-14 11:33:11 -0700829 stats_.reset(new StatsCollector(this));
hbos74e1a4f2016-09-15 23:33:01 -0700830 stats_collector_ = RTCStatsCollector::Create(this);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000831
Steve Antonba818672017-11-06 10:21:57 -0800832 configuration_ = configuration;
833
Steve Anton75737c02017-11-06 10:37:17 -0800834 const PeerConnectionFactoryInterface::Options& options = factory_->options();
835
836 transport_controller_->SetSslMaxProtocolVersion(options.ssl_max_version);
837
838 // Obtain a certificate from RTCConfiguration if any were provided (optional).
839 rtc::scoped_refptr<rtc::RTCCertificate> certificate;
840 if (!configuration.certificates.empty()) {
841 // TODO(hbos,torbjorng): Decide on certificate-selection strategy instead of
842 // just picking the first one. The decision should be made based on the DTLS
843 // handshake. The DTLS negotiations need to know about all certificates.
844 certificate = configuration.certificates[0];
845 }
846
Steve Antond25da372017-11-06 14:50:29 -0800847 transport_controller_->SetIceConfig(ParseIceConfig(configuration));
Steve Anton75737c02017-11-06 10:37:17 -0800848
849 if (options.disable_encryption) {
850 dtls_enabled_ = false;
851 } else {
852 // Enable DTLS by default if we have an identity store or a certificate.
853 dtls_enabled_ = (cert_generator || certificate);
854 // |configuration| can override the default |dtls_enabled_| value.
855 if (configuration.enable_dtls_srtp) {
856 dtls_enabled_ = *(configuration.enable_dtls_srtp);
857 }
858 }
859
860 // Enable creation of RTP data channels if the kEnableRtpDataChannels is set.
861 // It takes precendence over the disable_sctp_data_channels
862 // PeerConnectionFactoryInterface::Options.
863 if (configuration.enable_rtp_data_channel) {
864 data_channel_type_ = cricket::DCT_RTP;
865 } else {
866 // DTLS has to be enabled to use SCTP.
867 if (!options.disable_sctp_data_channels && dtls_enabled_) {
868 data_channel_type_ = cricket::DCT_SCTP;
869 }
870 }
871
872 video_options_.screencast_min_bitrate_kbps =
873 configuration.screencast_min_bitrate;
874 audio_options_.combined_audio_video_bwe =
875 configuration.combined_audio_video_bwe;
876
877 audio_options_.audio_jitter_buffer_max_packets =
Oskar Sundbom9b28a032017-11-16 10:53:30 +0100878 configuration.audio_jitter_buffer_max_packets;
Steve Anton75737c02017-11-06 10:37:17 -0800879
880 audio_options_.audio_jitter_buffer_fast_accelerate =
Oskar Sundbom9b28a032017-11-16 10:53:30 +0100881 configuration.audio_jitter_buffer_fast_accelerate;
Steve Anton75737c02017-11-06 10:37:17 -0800882
883 // Whether the certificate generator/certificate is null or not determines
884 // what PeerConnectionDescriptionFactory will do, so make sure that we give it
885 // the right instructions by clearing the variables if needed.
886 if (!dtls_enabled_) {
887 cert_generator.reset();
888 certificate = nullptr;
889 } else if (certificate) {
890 // Favor generated certificate over the certificate generator.
891 cert_generator.reset();
892 }
893
894 webrtc_session_desc_factory_.reset(new WebRtcSessionDescriptionFactory(
895 signaling_thread(), channel_manager(), this, session_id(),
896 std::move(cert_generator), certificate));
897 webrtc_session_desc_factory_->SignalCertificateReady.connect(
898 this, &PeerConnection::OnCertificateReady);
899
900 if (options.disable_encryption) {
901 webrtc_session_desc_factory_->SetSdesPolicy(cricket::SEC_DISABLED);
902 }
903
904 webrtc_session_desc_factory_->set_enable_encrypted_rtp_header_extensions(
905 options.crypto_options.enable_encrypted_rtp_header_extensions);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000906
Steve Anton4171afb2017-11-20 10:20:22 -0800907 // Add default audio/video transceivers for Plan B SDP.
908 if (!IsUnifiedPlan()) {
909 transceivers_.push_back(
910 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
911 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_AUDIO)));
912 transceivers_.push_back(
913 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
914 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_VIDEO)));
915 }
916
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000917 return true;
918}
919
Steve Anton038834f2017-07-14 15:59:59 -0700920RTCError PeerConnection::ValidateConfiguration(
921 const RTCConfiguration& config) const {
922 if (config.ice_regather_interval_range &&
923 config.continual_gathering_policy == GATHER_ONCE) {
924 return RTCError(RTCErrorType::INVALID_PARAMETER,
925 "ice_regather_interval_range specified but continual "
926 "gathering policy is GATHER_ONCE");
927 }
928 return RTCError::OK();
929}
930
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000931rtc::scoped_refptr<StreamCollectionInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000932PeerConnection::local_streams() {
deadbeefab9b2d12015-10-14 11:33:11 -0700933 return local_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000934}
935
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000936rtc::scoped_refptr<StreamCollectionInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000937PeerConnection::remote_streams() {
deadbeefab9b2d12015-10-14 11:33:11 -0700938 return remote_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000939}
940
perkj@webrtc.orgc2dd5ee2014-11-04 11:31:29 +0000941bool PeerConnection::AddStream(MediaStreamInterface* local_stream) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100942 TRACE_EVENT0("webrtc", "PeerConnection::AddStream");
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000943 if (IsClosed()) {
944 return false;
945 }
deadbeefab9b2d12015-10-14 11:33:11 -0700946 if (!CanAddLocalMediaStream(local_streams_, local_stream)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000947 return false;
948 }
deadbeefab9b2d12015-10-14 11:33:11 -0700949
950 local_streams_->AddStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -0800951 MediaStreamObserver* observer = new MediaStreamObserver(local_stream);
952 observer->SignalAudioTrackAdded.connect(this,
953 &PeerConnection::OnAudioTrackAdded);
954 observer->SignalAudioTrackRemoved.connect(
955 this, &PeerConnection::OnAudioTrackRemoved);
956 observer->SignalVideoTrackAdded.connect(this,
957 &PeerConnection::OnVideoTrackAdded);
958 observer->SignalVideoTrackRemoved.connect(
959 this, &PeerConnection::OnVideoTrackRemoved);
kwibergd1fe2812016-04-27 06:47:29 -0700960 stream_observers_.push_back(std::unique_ptr<MediaStreamObserver>(observer));
deadbeefab9b2d12015-10-14 11:33:11 -0700961
deadbeefab9b2d12015-10-14 11:33:11 -0700962 for (const auto& track : local_stream->GetAudioTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -0700963 AddAudioTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -0700964 }
965 for (const auto& track : local_stream->GetVideoTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -0700966 AddVideoTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -0700967 }
968
tommi@webrtc.org03505bc2014-07-14 20:15:26 +0000969 stats_->AddStream(local_stream);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000970 observer_->OnRenegotiationNeeded();
971 return true;
972}
973
974void PeerConnection::RemoveStream(MediaStreamInterface* local_stream) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100975 TRACE_EVENT0("webrtc", "PeerConnection::RemoveStream");
korniltsev.anatolyec390b52017-07-24 17:00:25 -0700976 if (!IsClosed()) {
977 for (const auto& track : local_stream->GetAudioTracks()) {
978 RemoveAudioTrack(track.get(), local_stream);
979 }
980 for (const auto& track : local_stream->GetVideoTracks()) {
981 RemoveVideoTrack(track.get(), local_stream);
982 }
deadbeefab9b2d12015-10-14 11:33:11 -0700983 }
deadbeefab9b2d12015-10-14 11:33:11 -0700984 local_streams_->RemoveStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -0800985 stream_observers_.erase(
986 std::remove_if(
987 stream_observers_.begin(), stream_observers_.end(),
kwibergd1fe2812016-04-27 06:47:29 -0700988 [local_stream](const std::unique_ptr<MediaStreamObserver>& observer) {
deadbeefeb459812015-12-15 19:24:43 -0800989 return observer->stream()->label().compare(local_stream->label()) ==
990 0;
991 }),
992 stream_observers_.end());
deadbeefab9b2d12015-10-14 11:33:11 -0700993
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000994 if (IsClosed()) {
995 return;
996 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000997 observer_->OnRenegotiationNeeded();
998}
999
deadbeefe1f9d832016-01-14 15:35:42 -08001000rtc::scoped_refptr<RtpSenderInterface> PeerConnection::AddTrack(
1001 MediaStreamTrackInterface* track,
1002 std::vector<MediaStreamInterface*> streams) {
1003 TRACE_EVENT0("webrtc", "PeerConnection::AddTrack");
Steve Antonf9381f02017-12-14 10:23:57 -08001004 std::vector<std::string> stream_labels;
1005 for (auto* stream : streams) {
1006 if (!stream) {
1007 RTC_LOG(LS_ERROR) << "Stream list has null element.";
1008 return nullptr;
1009 }
1010 stream_labels.push_back(stream->label());
1011 }
1012 auto sender_or_error = AddTrackWithStreamLabels(track, stream_labels);
1013 if (!sender_or_error.ok()) {
deadbeefe1f9d832016-01-14 15:35:42 -08001014 return nullptr;
1015 }
Steve Antonf9381f02017-12-14 10:23:57 -08001016 return sender_or_error.MoveValue();
1017}
1018
1019RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>>
1020PeerConnection::AddTrackWithStreamLabels(
1021 rtc::scoped_refptr<MediaStreamTrackInterface> track,
1022 const std::vector<std::string>& stream_labels) {
1023 TRACE_EVENT0("webrtc", "PeerConnection::AddTrackWithStreamLabels");
1024 if (!track) {
1025 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "Track is null.");
1026 }
1027 if (!(track->kind() == MediaStreamTrackInterface::kAudioKind ||
1028 track->kind() == MediaStreamTrackInterface::kVideoKind)) {
1029 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1030 "Track has invalid kind: " + track->kind());
1031 }
1032 // TODO(bugs.webrtc.org/7932): Support adding a track to multiple streams.
1033 if (stream_labels.size() > 1u) {
1034 LOG_AND_RETURN_ERROR(
1035 RTCErrorType::UNSUPPORTED_OPERATION,
1036 "AddTrack with more than one stream is not currently supported.");
1037 }
1038 if (IsClosed()) {
1039 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
1040 "PeerConnection is closed.");
deadbeefe1f9d832016-01-14 15:35:42 -08001041 }
Steve Anton4171afb2017-11-20 10:20:22 -08001042 if (FindSenderForTrack(track)) {
Steve Antonf9381f02017-12-14 10:23:57 -08001043 LOG_AND_RETURN_ERROR(
1044 RTCErrorType::INVALID_PARAMETER,
1045 "Sender already exists for track " + track->id() + ".");
deadbeefe1f9d832016-01-14 15:35:42 -08001046 }
Steve Antonf9381f02017-12-14 10:23:57 -08001047 // TODO(bugs.webrtc.org/7933): MediaSession expects the sender to have exactly
1048 // one stream. AddTrackInternal will return an error if there is more than one
1049 // stream, but if the caller specifies none then we need to generate a random
1050 // stream label.
1051 std::vector<std::string> adjusted_stream_labels = stream_labels;
1052 if (stream_labels.empty()) {
1053 adjusted_stream_labels.push_back(rtc::CreateRandomUuid());
1054 }
1055 RTC_DCHECK_EQ(1, adjusted_stream_labels.size());
1056 auto sender_or_error =
1057 (IsUnifiedPlan() ? AddTrackUnifiedPlan(track, adjusted_stream_labels)
1058 : AddTrackPlanB(track, adjusted_stream_labels));
1059 if (sender_or_error.ok()) {
1060 observer_->OnRenegotiationNeeded();
Steve Anton43a723a2018-01-04 15:48:17 -08001061 stats_->AddTrack(track);
Steve Antonf9381f02017-12-14 10:23:57 -08001062 }
1063 return sender_or_error;
1064}
deadbeefe1f9d832016-01-14 15:35:42 -08001065
Steve Antonf9381f02017-12-14 10:23:57 -08001066RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>>
1067PeerConnection::AddTrackPlanB(
1068 rtc::scoped_refptr<MediaStreamTrackInterface> track,
1069 const std::vector<std::string>& stream_labels) {
deadbeefe1f9d832016-01-14 15:35:42 -08001070 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
Steve Antonf9381f02017-12-14 10:23:57 -08001071 auto new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
deadbeefe1f9d832016-01-14 15:35:42 -08001072 signaling_thread(),
Steve Antonf9381f02017-12-14 10:23:57 -08001073 new AudioRtpSender(static_cast<AudioTrackInterface*>(track.get()),
Steve Anton75737c02017-11-06 10:37:17 -08001074 voice_channel(), stats_.get()));
Steve Anton4171afb2017-11-20 10:20:22 -08001075 GetAudioTransceiver()->internal()->AddSender(new_sender);
Steve Antonf9381f02017-12-14 10:23:57 -08001076 new_sender->internal()->set_stream_ids(stream_labels);
Steve Anton4171afb2017-11-20 10:20:22 -08001077 const RtpSenderInfo* sender_info =
1078 FindSenderInfo(local_audio_sender_infos_,
1079 new_sender->internal()->stream_id(), track->id());
1080 if (sender_info) {
1081 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -08001082 }
Steve Antonf9381f02017-12-14 10:23:57 -08001083 return rtc::scoped_refptr<RtpSenderInterface>(new_sender);
1084 } else {
1085 RTC_DCHECK_EQ(MediaStreamTrackInterface::kVideoKind, track->kind());
1086 auto new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
deadbeefe1f9d832016-01-14 15:35:42 -08001087 signaling_thread(),
Steve Antonf9381f02017-12-14 10:23:57 -08001088 new VideoRtpSender(static_cast<VideoTrackInterface*>(track.get()),
Steve Anton75737c02017-11-06 10:37:17 -08001089 video_channel()));
Steve Anton4171afb2017-11-20 10:20:22 -08001090 GetVideoTransceiver()->internal()->AddSender(new_sender);
Steve Antonf9381f02017-12-14 10:23:57 -08001091 new_sender->internal()->set_stream_ids(stream_labels);
Steve Anton4171afb2017-11-20 10:20:22 -08001092 const RtpSenderInfo* sender_info =
1093 FindSenderInfo(local_video_sender_infos_,
1094 new_sender->internal()->stream_id(), track->id());
1095 if (sender_info) {
1096 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -08001097 }
Steve Antonf9381f02017-12-14 10:23:57 -08001098 return rtc::scoped_refptr<RtpSenderInterface>(new_sender);
deadbeefe1f9d832016-01-14 15:35:42 -08001099 }
Steve Antonf9381f02017-12-14 10:23:57 -08001100}
deadbeefe1f9d832016-01-14 15:35:42 -08001101
Steve Antonf9381f02017-12-14 10:23:57 -08001102RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>>
1103PeerConnection::AddTrackUnifiedPlan(
1104 rtc::scoped_refptr<MediaStreamTrackInterface> track,
1105 const std::vector<std::string>& stream_labels) {
1106 auto transceiver = FindFirstTransceiverForAddedTrack(track);
1107 if (transceiver) {
1108 if (transceiver->direction() == RtpTransceiverDirection::kRecvOnly) {
1109 transceiver->SetDirection(RtpTransceiverDirection::kSendRecv);
1110 } else if (transceiver->direction() == RtpTransceiverDirection::kInactive) {
1111 transceiver->SetDirection(RtpTransceiverDirection::kSendOnly);
1112 }
1113 } else {
1114 cricket::MediaType media_type =
1115 (track->kind() == MediaStreamTrackInterface::kAudioKind
1116 ? cricket::MEDIA_TYPE_AUDIO
1117 : cricket::MEDIA_TYPE_VIDEO);
1118 transceiver = CreateTransceiver(media_type);
1119 transceiver->internal()->set_created_by_addtrack(true);
1120 transceiver->SetDirection(RtpTransceiverDirection::kSendRecv);
1121 }
1122 transceiver->sender()->SetTrack(track);
1123 transceiver->internal()->sender_internal()->set_stream_ids(stream_labels);
1124 return transceiver->sender();
1125}
1126
1127rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1128PeerConnection::FindFirstTransceiverForAddedTrack(
1129 rtc::scoped_refptr<MediaStreamTrackInterface> track) {
1130 RTC_DCHECK(track);
1131 for (auto transceiver : transceivers_) {
1132 if (!transceiver->sender()->track() &&
1133 cricket::MediaTypeToString(transceiver->internal()->media_type()) ==
1134 track->kind() &&
1135 !transceiver->internal()->has_ever_been_used_to_send()) {
1136 return transceiver;
1137 }
1138 }
1139 return nullptr;
deadbeefe1f9d832016-01-14 15:35:42 -08001140}
1141
1142bool PeerConnection::RemoveTrack(RtpSenderInterface* sender) {
1143 TRACE_EVENT0("webrtc", "PeerConnection::RemoveTrack");
Steve Antonf9381f02017-12-14 10:23:57 -08001144 return RemoveTrackInternal(sender).ok();
1145}
1146
1147RTCError PeerConnection::RemoveTrackInternal(
1148 rtc::scoped_refptr<RtpSenderInterface> sender) {
1149 if (!sender) {
1150 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "Sender is null.");
1151 }
deadbeefe1f9d832016-01-14 15:35:42 -08001152 if (IsClosed()) {
Steve Antonf9381f02017-12-14 10:23:57 -08001153 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
1154 "PeerConnection is closed.");
deadbeefe1f9d832016-01-14 15:35:42 -08001155 }
Steve Antonf9381f02017-12-14 10:23:57 -08001156 if (IsUnifiedPlan()) {
1157 auto transceiver = FindTransceiverBySender(sender);
1158 if (!transceiver || !sender->track()) {
1159 return RTCError::OK();
1160 }
1161 sender->SetTrack(nullptr);
1162 if (transceiver->direction() == RtpTransceiverDirection::kSendRecv) {
1163 transceiver->internal()->SetDirection(RtpTransceiverDirection::kRecvOnly);
1164 } else if (transceiver->direction() == RtpTransceiverDirection::kSendOnly) {
1165 transceiver->internal()->SetDirection(RtpTransceiverDirection::kInactive);
1166 }
Steve Anton4171afb2017-11-20 10:20:22 -08001167 } else {
Steve Antonf9381f02017-12-14 10:23:57 -08001168 bool removed;
1169 if (sender->media_type() == cricket::MEDIA_TYPE_AUDIO) {
1170 removed = GetAudioTransceiver()->internal()->RemoveSender(sender);
1171 } else {
1172 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, sender->media_type());
1173 removed = GetVideoTransceiver()->internal()->RemoveSender(sender);
1174 }
1175 if (!removed) {
1176 LOG_AND_RETURN_ERROR(
1177 RTCErrorType::INVALID_PARAMETER,
1178 "Couldn't find sender " + sender->id() + " to remove.");
1179 }
Steve Anton4171afb2017-11-20 10:20:22 -08001180 }
deadbeefe1f9d832016-01-14 15:35:42 -08001181 observer_->OnRenegotiationNeeded();
Steve Antonf9381f02017-12-14 10:23:57 -08001182 return RTCError::OK();
1183}
1184
1185rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1186PeerConnection::FindTransceiverBySender(
1187 rtc::scoped_refptr<RtpSenderInterface> sender) {
1188 for (auto transceiver : transceivers_) {
1189 if (transceiver->sender() == sender) {
1190 return transceiver;
1191 }
1192 }
1193 return nullptr;
deadbeefe1f9d832016-01-14 15:35:42 -08001194}
1195
Steve Anton9158ef62017-11-27 13:01:52 -08001196RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1197PeerConnection::AddTransceiver(
1198 rtc::scoped_refptr<MediaStreamTrackInterface> track) {
1199 return AddTransceiver(track, RtpTransceiverInit());
1200}
1201
1202RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1203PeerConnection::AddTransceiver(
1204 rtc::scoped_refptr<MediaStreamTrackInterface> track,
1205 const RtpTransceiverInit& init) {
1206 if (!IsUnifiedPlan()) {
1207 LOG_AND_RETURN_ERROR(
1208 RTCErrorType::INTERNAL_ERROR,
1209 "AddTransceiver only supported when Unified Plan is enabled.");
1210 }
1211 if (!track) {
1212 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "track is null");
1213 }
1214 cricket::MediaType media_type;
1215 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
1216 media_type = cricket::MEDIA_TYPE_AUDIO;
1217 } else if (track->kind() == MediaStreamTrackInterface::kVideoKind) {
1218 media_type = cricket::MEDIA_TYPE_VIDEO;
1219 } else {
1220 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1221 "Track kind is not audio or video");
1222 }
1223 return AddTransceiver(media_type, track, init);
1224}
1225
1226RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1227PeerConnection::AddTransceiver(cricket::MediaType media_type) {
1228 return AddTransceiver(media_type, RtpTransceiverInit());
1229}
1230
1231RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1232PeerConnection::AddTransceiver(cricket::MediaType media_type,
1233 const RtpTransceiverInit& init) {
1234 if (!IsUnifiedPlan()) {
1235 LOG_AND_RETURN_ERROR(
1236 RTCErrorType::INTERNAL_ERROR,
1237 "AddTransceiver only supported when Unified Plan is enabled.");
1238 }
1239 if (!(media_type == cricket::MEDIA_TYPE_AUDIO ||
1240 media_type == cricket::MEDIA_TYPE_VIDEO)) {
1241 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1242 "media type is not audio or video");
1243 }
1244 return AddTransceiver(media_type, nullptr, init);
1245}
1246
1247RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1248PeerConnection::AddTransceiver(
1249 cricket::MediaType media_type,
1250 rtc::scoped_refptr<MediaStreamTrackInterface> track,
1251 const RtpTransceiverInit& init) {
1252 RTC_DCHECK((media_type == cricket::MEDIA_TYPE_AUDIO ||
1253 media_type == cricket::MEDIA_TYPE_VIDEO));
1254 if (track) {
1255 RTC_DCHECK_EQ(media_type,
1256 (track->kind() == MediaStreamTrackInterface::kAudioKind
1257 ? cricket::MEDIA_TYPE_AUDIO
1258 : cricket::MEDIA_TYPE_VIDEO));
1259 }
1260
1261 // TODO(bugs.webrtc.org/7600): Verify init.
1262
Steve Antonf9381f02017-12-14 10:23:57 -08001263 auto transceiver = CreateTransceiver(media_type);
1264 transceiver->SetDirection(init.direction);
1265 if (track) {
1266 transceiver->sender()->SetTrack(track);
1267 }
1268
1269 observer_->OnRenegotiationNeeded();
1270
1271 return rtc::scoped_refptr<RtpTransceiverInterface>(transceiver);
1272}
1273
1274rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1275PeerConnection::CreateTransceiver(cricket::MediaType media_type) {
Steve Anton9158ef62017-11-27 13:01:52 -08001276 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> sender;
1277 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1278 receiver;
1279 std::string receiver_id = rtc::CreateRandomUuid();
Steve Antonf9381f02017-12-14 10:23:57 -08001280 // TODO(bugs.webrtc.org/7600): Initializing the sender/receiver with a null
1281 // channel prevents users from calling SetParameters on them, which is needed
1282 // to be in compliance with the spec.
Steve Anton9158ef62017-11-27 13:01:52 -08001283 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
1284 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
1285 signaling_thread(), new AudioRtpSender(nullptr, stats_.get()));
1286 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
1287 signaling_thread(), new AudioRtpReceiver(receiver_id, {}, 0, nullptr));
1288 } else {
1289 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, media_type);
1290 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
1291 signaling_thread(), new VideoRtpSender(nullptr));
1292 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
1293 signaling_thread(),
1294 new VideoRtpReceiver(receiver_id, {}, worker_thread(), 0, nullptr));
1295 }
Steve Anton9158ef62017-11-27 13:01:52 -08001296 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1297 transceiver = RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1298 signaling_thread(), new RtpTransceiver(sender, receiver));
Steve Anton9158ef62017-11-27 13:01:52 -08001299 transceivers_.push_back(transceiver);
Steve Antonf9381f02017-12-14 10:23:57 -08001300 return transceiver;
Steve Anton9158ef62017-11-27 13:01:52 -08001301}
1302
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001303rtc::scoped_refptr<DtmfSenderInterface> PeerConnection::CreateDtmfSender(
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001304 AudioTrackInterface* track) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001305 TRACE_EVENT0("webrtc", "PeerConnection::CreateDtmfSender");
zhihuang29ff8442016-07-27 11:07:25 -07001306 if (IsClosed()) {
1307 return nullptr;
1308 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001309 if (!track) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001310 RTC_LOG(LS_ERROR) << "CreateDtmfSender - track is NULL.";
deadbeef20cb0c12017-02-01 20:27:00 -08001311 return nullptr;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001312 }
Steve Anton4171afb2017-11-20 10:20:22 -08001313 auto track_sender = FindSenderForTrack(track);
1314 if (!track_sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001315 RTC_LOG(LS_ERROR) << "CreateDtmfSender called with a non-added track.";
deadbeef20cb0c12017-02-01 20:27:00 -08001316 return nullptr;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001317 }
1318
Steve Anton4171afb2017-11-20 10:20:22 -08001319 return track_sender->GetDtmfSender();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001320}
1321
deadbeeffac06552015-11-25 11:26:01 -08001322rtc::scoped_refptr<RtpSenderInterface> PeerConnection::CreateSender(
deadbeefbd7d8f72015-12-18 16:58:44 -08001323 const std::string& kind,
1324 const std::string& stream_id) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001325 TRACE_EVENT0("webrtc", "PeerConnection::CreateSender");
zhihuang29ff8442016-07-27 11:07:25 -07001326 if (IsClosed()) {
1327 return nullptr;
1328 }
Steve Anton4171afb2017-11-20 10:20:22 -08001329
1330 // TODO(steveanton): Move construction of the RtpSenders to RtpTransceiver.
deadbeefa601f5c2016-06-06 14:27:39 -07001331 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender;
deadbeeffac06552015-11-25 11:26:01 -08001332 if (kind == MediaStreamTrackInterface::kAudioKind) {
deadbeefa601f5c2016-06-06 14:27:39 -07001333 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton75737c02017-11-06 10:37:17 -08001334 signaling_thread(), new AudioRtpSender(voice_channel(), stats_.get()));
Steve Anton4171afb2017-11-20 10:20:22 -08001335 GetAudioTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 11:26:01 -08001336 } else if (kind == MediaStreamTrackInterface::kVideoKind) {
deadbeefa601f5c2016-06-06 14:27:39 -07001337 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton75737c02017-11-06 10:37:17 -08001338 signaling_thread(), new VideoRtpSender(video_channel()));
Steve Anton4171afb2017-11-20 10:20:22 -08001339 GetVideoTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 11:26:01 -08001340 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001341 RTC_LOG(LS_ERROR) << "CreateSender called with invalid kind: " << kind;
Steve Anton4171afb2017-11-20 10:20:22 -08001342 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08001343 }
Steve Anton4171afb2017-11-20 10:20:22 -08001344
deadbeefbd7d8f72015-12-18 16:58:44 -08001345 if (!stream_id.empty()) {
deadbeefa601f5c2016-06-06 14:27:39 -07001346 new_sender->internal()->set_stream_id(stream_id);
deadbeefbd7d8f72015-12-18 16:58:44 -08001347 }
Steve Anton4171afb2017-11-20 10:20:22 -08001348
deadbeefe1f9d832016-01-14 15:35:42 -08001349 return new_sender;
deadbeeffac06552015-11-25 11:26:01 -08001350}
1351
deadbeef70ab1a12015-09-28 16:53:55 -07001352std::vector<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::GetSenders()
1353 const {
deadbeefa601f5c2016-06-06 14:27:39 -07001354 std::vector<rtc::scoped_refptr<RtpSenderInterface>> ret;
Steve Anton4171afb2017-11-20 10:20:22 -08001355 for (auto sender : GetSendersInternal()) {
1356 ret.push_back(sender);
deadbeefa601f5c2016-06-06 14:27:39 -07001357 }
1358 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -07001359}
1360
Steve Anton4171afb2017-11-20 10:20:22 -08001361std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1362PeerConnection::GetSendersInternal() const {
1363 std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1364 all_senders;
1365 for (auto transceiver : transceivers_) {
1366 auto senders = transceiver->internal()->senders();
1367 all_senders.insert(all_senders.end(), senders.begin(), senders.end());
1368 }
1369 return all_senders;
1370}
1371
deadbeef70ab1a12015-09-28 16:53:55 -07001372std::vector<rtc::scoped_refptr<RtpReceiverInterface>>
1373PeerConnection::GetReceivers() const {
deadbeefa601f5c2016-06-06 14:27:39 -07001374 std::vector<rtc::scoped_refptr<RtpReceiverInterface>> ret;
Steve Anton4171afb2017-11-20 10:20:22 -08001375 for (const auto& receiver : GetReceiversInternal()) {
1376 ret.push_back(receiver);
deadbeefa601f5c2016-06-06 14:27:39 -07001377 }
1378 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -07001379}
1380
Steve Anton4171afb2017-11-20 10:20:22 -08001381std::vector<
1382 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1383PeerConnection::GetReceiversInternal() const {
1384 std::vector<
1385 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1386 all_receivers;
1387 for (auto transceiver : transceivers_) {
1388 auto receivers = transceiver->internal()->receivers();
1389 all_receivers.insert(all_receivers.end(), receivers.begin(),
1390 receivers.end());
1391 }
1392 return all_receivers;
1393}
1394
Steve Anton9158ef62017-11-27 13:01:52 -08001395std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
1396PeerConnection::GetTransceivers() const {
1397 RTC_DCHECK(IsUnifiedPlan());
1398 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> all_transceivers;
1399 for (auto transceiver : transceivers_) {
1400 all_transceivers.push_back(transceiver);
1401 }
1402 return all_transceivers;
1403}
1404
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001405bool PeerConnection::GetStats(StatsObserver* observer,
wu@webrtc.orgb9a088b2014-02-13 23:18:49 +00001406 MediaStreamTrackInterface* track,
1407 StatsOutputLevel level) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001408 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
deadbeef0a6c4ca2015-10-06 11:38:28 -07001409 RTC_DCHECK(signaling_thread()->IsCurrent());
nisse7ce109a2017-01-31 00:57:56 -08001410 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001411 RTC_LOG(LS_ERROR) << "GetStats - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001412 return false;
1413 }
1414
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001415 stats_->UpdateStats(level);
zhihuange9e94c32016-11-04 11:38:15 -07001416 // The StatsCollector is used to tell if a track is valid because it may
1417 // remember tracks that the PeerConnection previously removed.
1418 if (track && !stats_->IsValidTrack(track->id())) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001419 RTC_LOG(LS_WARNING) << "GetStats is called with an invalid track: "
1420 << track->id();
zhihuange9e94c32016-11-04 11:38:15 -07001421 return false;
1422 }
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001423 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_GETSTATS,
tommi@webrtc.org5b06b062014-08-15 08:38:30 +00001424 new GetStatsMsg(observer, track));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001425 return true;
1426}
1427
hbos74e1a4f2016-09-15 23:33:01 -07001428void PeerConnection::GetStats(RTCStatsCollectorCallback* callback) {
1429 RTC_DCHECK(stats_collector_);
1430 stats_collector_->GetStatsReport(callback);
1431}
1432
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001433PeerConnectionInterface::SignalingState PeerConnection::signaling_state() {
1434 return signaling_state_;
1435}
1436
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001437PeerConnectionInterface::IceConnectionState
1438PeerConnection::ice_connection_state() {
1439 return ice_connection_state_;
1440}
1441
1442PeerConnectionInterface::IceGatheringState
1443PeerConnection::ice_gathering_state() {
1444 return ice_gathering_state_;
1445}
1446
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001447rtc::scoped_refptr<DataChannelInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001448PeerConnection::CreateDataChannel(
1449 const std::string& label,
1450 const DataChannelInit* config) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001451 TRACE_EVENT0("webrtc", "PeerConnection::CreateDataChannel");
zhihuang9763d562016-08-05 11:14:50 -07001452
deadbeefab9b2d12015-10-14 11:33:11 -07001453 bool first_datachannel = !HasDataChannels();
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001454
kwibergd1fe2812016-04-27 06:47:29 -07001455 std::unique_ptr<InternalDataChannelInit> internal_config;
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00001456 if (config) {
1457 internal_config.reset(new InternalDataChannelInit(*config));
1458 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001459 rtc::scoped_refptr<DataChannelInterface> channel(
deadbeefab9b2d12015-10-14 11:33:11 -07001460 InternalCreateDataChannel(label, internal_config.get()));
1461 if (!channel.get()) {
1462 return nullptr;
1463 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001464
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001465 // Trigger the onRenegotiationNeeded event for every new RTP DataChannel, or
1466 // the first SCTP DataChannel.
Steve Anton75737c02017-11-06 10:37:17 -08001467 if (data_channel_type() == cricket::DCT_RTP || first_datachannel) {
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001468 observer_->OnRenegotiationNeeded();
1469 }
wu@webrtc.org91053e72013-08-10 07:18:04 +00001470
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001471 return DataChannelProxy::Create(signaling_thread(), channel.get());
1472}
1473
1474void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
1475 const MediaConstraintsInterface* constraints) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001476 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
Steve Anton8d3444d2017-10-20 15:30:51 -07001477
zhihuang1c378ed2017-08-17 14:10:50 -07001478 PeerConnectionInterface::RTCOfferAnswerOptions offer_answer_options;
1479 // Always create an offer even if |ConvertConstraintsToOfferAnswerOptions|
1480 // returns false for now. Because |ConvertConstraintsToOfferAnswerOptions|
1481 // compares the mandatory fields parsed with the mandatory fields added in the
1482 // |constraints| and some downstream applications might create offers with
1483 // mandatory fields which would not be parsed in the helper method. For
1484 // example, in Chromium/remoting, |kEnableDtlsSrtp| is added to the
1485 // |constraints| as a mandatory field but it is not parsed.
1486 ConvertConstraintsToOfferAnswerOptions(constraints, &offer_answer_options);
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001487
zhihuang1c378ed2017-08-17 14:10:50 -07001488 CreateOffer(observer, offer_answer_options);
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001489}
1490
1491void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
1492 const RTCOfferAnswerOptions& options) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001493 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
Steve Anton8d3444d2017-10-20 15:30:51 -07001494
nisse7ce109a2017-01-31 00:57:56 -08001495 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001496 RTC_LOG(LS_ERROR) << "CreateOffer - observer is NULL.";
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001497 return;
1498 }
deadbeefab9b2d12015-10-14 11:33:11 -07001499
Steve Anton8d3444d2017-10-20 15:30:51 -07001500 if (IsClosed()) {
1501 std::string error = "CreateOffer called when PeerConnection is closed.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001502 RTC_LOG(LS_ERROR) << error;
Steve Anton8d3444d2017-10-20 15:30:51 -07001503 PostCreateSessionDescriptionFailure(observer, error);
1504 return;
1505 }
1506
zhihuang1c378ed2017-08-17 14:10:50 -07001507 if (!ValidateOfferAnswerOptions(options)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001508 std::string error = "CreateOffer called with invalid options.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001509 RTC_LOG(LS_ERROR) << error;
deadbeefab9b2d12015-10-14 11:33:11 -07001510 PostCreateSessionDescriptionFailure(observer, error);
1511 return;
1512 }
1513
zhihuang1c378ed2017-08-17 14:10:50 -07001514 cricket::MediaSessionOptions session_options;
1515 GetOptionsForOffer(options, &session_options);
Steve Antond25da372017-11-06 14:50:29 -08001516 webrtc_session_desc_factory_->CreateOffer(observer, options, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001517}
1518
1519void PeerConnection::CreateAnswer(
1520 CreateSessionDescriptionObserver* observer,
1521 const MediaConstraintsInterface* constraints) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001522 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
Steve Anton8d3444d2017-10-20 15:30:51 -07001523
nisse7ce109a2017-01-31 00:57:56 -08001524 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001525 RTC_LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001526 return;
1527 }
deadbeefab9b2d12015-10-14 11:33:11 -07001528
zhihuang1c378ed2017-08-17 14:10:50 -07001529 PeerConnectionInterface::RTCOfferAnswerOptions offer_answer_options;
1530 if (!ConvertConstraintsToOfferAnswerOptions(constraints,
1531 &offer_answer_options)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001532 std::string error = "CreateAnswer called with invalid constraints.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001533 RTC_LOG(LS_ERROR) << error;
deadbeefab9b2d12015-10-14 11:33:11 -07001534 PostCreateSessionDescriptionFailure(observer, error);
1535 return;
1536 }
1537
Steve Anton8d3444d2017-10-20 15:30:51 -07001538 CreateAnswer(observer, offer_answer_options);
htaa2a49d92016-03-04 02:51:39 -08001539}
1540
1541void PeerConnection::CreateAnswer(CreateSessionDescriptionObserver* observer,
1542 const RTCOfferAnswerOptions& options) {
1543 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
nisse7ce109a2017-01-31 00:57:56 -08001544 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001545 RTC_LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
htaa2a49d92016-03-04 02:51:39 -08001546 return;
1547 }
1548
Steve Anton8d3444d2017-10-20 15:30:51 -07001549 if (IsClosed()) {
1550 std::string error = "CreateAnswer called when PeerConnection is closed.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001551 RTC_LOG(LS_ERROR) << error;
Steve Anton8d3444d2017-10-20 15:30:51 -07001552 PostCreateSessionDescriptionFailure(observer, error);
1553 return;
1554 }
1555
Steve Anton75737c02017-11-06 10:37:17 -08001556 if (remote_description() &&
Steve Antona3a92c22017-12-07 10:27:41 -08001557 remote_description()->GetType() != SdpType::kOffer) {
Steve Anton8d3444d2017-10-20 15:30:51 -07001558 std::string error = "CreateAnswer called without remote offer.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001559 RTC_LOG(LS_ERROR) << error;
Steve Anton8d3444d2017-10-20 15:30:51 -07001560 PostCreateSessionDescriptionFailure(observer, error);
1561 return;
1562 }
1563
htaa2a49d92016-03-04 02:51:39 -08001564 cricket::MediaSessionOptions session_options;
zhihuang1c378ed2017-08-17 14:10:50 -07001565 GetOptionsForAnswer(options, &session_options);
htaa2a49d92016-03-04 02:51:39 -08001566
Steve Antond25da372017-11-06 14:50:29 -08001567 webrtc_session_desc_factory_->CreateAnswer(observer, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001568}
1569
1570void PeerConnection::SetLocalDescription(
1571 SetSessionDescriptionObserver* observer,
1572 SessionDescriptionInterface* desc) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001573 TRACE_EVENT0("webrtc", "PeerConnection::SetLocalDescription");
Steve Anton8a006912017-12-04 15:25:56 -08001574
nisse7ce109a2017-01-31 00:57:56 -08001575 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001576 RTC_LOG(LS_ERROR) << "SetLocalDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001577 return;
1578 }
Steve Anton8a006912017-12-04 15:25:56 -08001579
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001580 if (!desc) {
1581 PostSetSessionDescriptionFailure(observer, "SessionDescription is NULL.");
1582 return;
1583 }
Steve Anton8d3444d2017-10-20 15:30:51 -07001584
Steve Antona3a92c22017-12-07 10:27:41 -08001585 SdpType type = desc->GetType();
Steve Anton8d3444d2017-10-20 15:30:51 -07001586
Steve Anton8a006912017-12-04 15:25:56 -08001587 RTCError error = ApplyLocalDescription(rtc::WrapUnique(desc));
1588 // |desc| may be destroyed at this point.
1589
1590 if (!error.ok()) {
Steve Antona3a92c22017-12-07 10:27:41 -08001591 std::ostringstream oss;
1592 oss << "Failed to set local " << SdpTypeToString(type)
1593 << " sdp: " << error.message();
1594 std::string error_message = oss.str();
Steve Anton8a006912017-12-04 15:25:56 -08001595 RTC_LOG(LS_ERROR) << error_message << " (" << error.type() << ")";
1596 PostSetSessionDescriptionFailure(observer, std::move(error_message));
Steve Anton8d3444d2017-10-20 15:30:51 -07001597 return;
1598 }
Steve Anton8a006912017-12-04 15:25:56 -08001599 RTC_DCHECK(local_description());
1600
1601 PostSetSessionDescriptionSuccess(observer);
1602
1603 // According to JSEP, after setLocalDescription, changing the candidate pool
1604 // size is not allowed, and changing the set of ICE servers will not result
1605 // in new candidates being gathered.
1606 port_allocator_->FreezeCandidatePool();
1607
1608 // MaybeStartGathering needs to be called after posting
1609 // MSG_SET_SESSIONDESCRIPTION_SUCCESS, so that we don't signal any candidates
1610 // before signaling that SetLocalDescription completed.
1611 transport_controller_->MaybeStartGathering();
1612
Steve Antona3a92c22017-12-07 10:27:41 -08001613 if (local_description()->GetType() == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08001614 // TODO(deadbeef): We already had to hop to the network thread for
1615 // MaybeStartGathering...
1616 network_thread()->Invoke<void>(
1617 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
1618 port_allocator_.get()));
1619 }
1620}
1621
1622RTCError PeerConnection::ApplyLocalDescription(
1623 std::unique_ptr<SessionDescriptionInterface> desc) {
1624 RTC_DCHECK_RUN_ON(signaling_thread());
1625 RTC_DCHECK(desc);
1626
1627 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_LOCAL);
1628 if (!error.ok()) {
1629 return error;
1630 }
Steve Anton8d3444d2017-10-20 15:30:51 -07001631
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001632 // Update stats here so that we have the most recent stats for tracks and
1633 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001634 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 15:25:56 -08001635
1636 // Update the initial_offerer flag if this session is the initial_offerer.
Steve Anton3828c062017-12-06 10:34:51 -08001637 SdpType type = desc->GetType();
Steve Anton8a006912017-12-04 15:25:56 -08001638 if (!initial_offerer_.has_value()) {
Steve Anton3828c062017-12-06 10:34:51 -08001639 initial_offerer_.emplace(type == SdpType::kOffer);
Steve Anton8a006912017-12-04 15:25:56 -08001640 if (*initial_offerer_) {
1641 transport_controller_->SetIceRole(cricket::ICEROLE_CONTROLLING);
1642 } else {
1643 transport_controller_->SetIceRole(cricket::ICEROLE_CONTROLLED);
1644 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001645 }
Steve Anton8a006912017-12-04 15:25:56 -08001646
Steve Antondcc3c022017-12-22 16:02:54 -08001647 // Take a reference to the old local description since it's used below to
1648 // compare against the new local description. When setting the new local
1649 // description, grab ownership of the replaced session description in case it
1650 // is the same as |old_local_description|, to keep it alive for the duration
1651 // of the method.
1652 const SessionDescriptionInterface* old_local_description =
1653 local_description();
1654 std::unique_ptr<SessionDescriptionInterface> replaced_local_description;
Steve Anton3828c062017-12-06 10:34:51 -08001655 if (type == SdpType::kAnswer) {
Steve Antondcc3c022017-12-22 16:02:54 -08001656 replaced_local_description = pending_local_description_
1657 ? std::move(pending_local_description_)
1658 : std::move(current_local_description_);
Steve Anton8a006912017-12-04 15:25:56 -08001659 current_local_description_ = std::move(desc);
1660 pending_local_description_ = nullptr;
1661 current_remote_description_ = std::move(pending_remote_description_);
1662 } else {
Steve Antondcc3c022017-12-22 16:02:54 -08001663 replaced_local_description = std::move(pending_local_description_);
Steve Anton8a006912017-12-04 15:25:56 -08001664 pending_local_description_ = std::move(desc);
1665 }
1666 // The session description to apply now must be accessed by
1667 // |local_description()|.
Henrik Boströmfdb92012017-11-09 19:55:44 +01001668 RTC_DCHECK(local_description());
deadbeefab9b2d12015-10-14 11:33:11 -07001669
Steve Antondcc3c022017-12-22 16:02:54 -08001670 if (IsUnifiedPlan()) {
1671 RTCError error = UpdateTransceiversAndDataChannels(
1672 cricket::CS_LOCAL, old_local_description, *local_description());
Steve Anton8a006912017-12-04 15:25:56 -08001673 if (!error.ok()) {
1674 return error;
1675 }
Steve Antondcc3c022017-12-22 16:02:54 -08001676 for (auto transceiver : transceivers_) {
1677 const ContentInfo* content =
1678 FindMediaSectionForTransceiver(transceiver, local_description());
1679 if (!content) {
1680 continue;
1681 }
1682 const MediaContentDescription* media_desc = content->media_description();
1683 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
1684 transceiver->internal()->set_current_direction(media_desc->direction());
1685 }
1686 if (content->rejected && !transceiver->stopped()) {
1687 transceiver->Stop();
1688 }
1689 }
1690 } else {
1691 // Transport and Media channels will be created only when offer is set.
1692 if (type == SdpType::kOffer) {
1693 // TODO(bugs.webrtc.org/4676) - Handle CreateChannel failure, as new local
1694 // description is applied. Restore back to old description.
1695 RTCError error = CreateChannels(*local_description()->description());
1696 if (!error.ok()) {
1697 return error;
1698 }
1699 }
Steve Anton8a006912017-12-04 15:25:56 -08001700
Steve Antondcc3c022017-12-22 16:02:54 -08001701 // Remove unused channels if MediaContentDescription is rejected.
1702 RemoveUnusedChannels(local_description()->description());
1703 }
Steve Anton8a006912017-12-04 15:25:56 -08001704
Steve Anton3828c062017-12-06 10:34:51 -08001705 error = UpdateSessionState(type, cricket::CS_LOCAL);
Steve Anton8a006912017-12-04 15:25:56 -08001706 if (!error.ok()) {
1707 return error;
1708 }
Steve Antondcc3c022017-12-22 16:02:54 -08001709
Steve Anton8a006912017-12-04 15:25:56 -08001710 if (remote_description()) {
1711 // Now that we have a local description, we can push down remote candidates.
1712 UseCandidatesInSessionDescription(remote_description());
1713 }
1714
1715 pending_ice_restarts_.clear();
1716 if (session_error() != SessionError::kNone) {
1717 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
1718 }
1719
deadbeefab9b2d12015-10-14 11:33:11 -07001720 // If setting the description decided our SSL role, allocate any necessary
1721 // SCTP sids.
1722 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08001723 if (data_channel_type() == cricket::DCT_SCTP && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001724 AllocateSctpSids(role);
1725 }
1726
Steve Antondcc3c022017-12-22 16:02:54 -08001727 if (!IsUnifiedPlan()) {
1728 // Update state and SSRC of local MediaStreams and DataChannels based on the
1729 // local session description.
1730 const cricket::ContentInfo* audio_content =
1731 GetFirstAudioContent(local_description()->description());
1732 if (audio_content) {
1733 if (audio_content->rejected) {
1734 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
1735 } else {
1736 const cricket::AudioContentDescription* audio_desc =
1737 audio_content->media_description()->as_audio();
1738 UpdateLocalSenders(audio_desc->streams(), audio_desc->type());
1739 }
deadbeeffaac4972015-11-12 15:33:07 -08001740 }
deadbeefab9b2d12015-10-14 11:33:11 -07001741
Steve Antondcc3c022017-12-22 16:02:54 -08001742 const cricket::ContentInfo* video_content =
1743 GetFirstVideoContent(local_description()->description());
1744 if (video_content) {
1745 if (video_content->rejected) {
1746 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
1747 } else {
1748 const cricket::VideoContentDescription* video_desc =
1749 video_content->media_description()->as_video();
1750 UpdateLocalSenders(video_desc->streams(), video_desc->type());
1751 }
deadbeeffaac4972015-11-12 15:33:07 -08001752 }
deadbeefab9b2d12015-10-14 11:33:11 -07001753 }
1754
1755 const cricket::ContentInfo* data_content =
Henrik Boströmfdb92012017-11-09 19:55:44 +01001756 GetFirstDataContent(local_description()->description());
deadbeefab9b2d12015-10-14 11:33:11 -07001757 if (data_content) {
1758 const cricket::DataContentDescription* data_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08001759 data_content->media_description()->as_data();
deadbeefab9b2d12015-10-14 11:33:11 -07001760 if (rtc::starts_with(data_desc->protocol().data(),
1761 cricket::kMediaProtocolRtpPrefix)) {
1762 UpdateLocalRtpDataChannels(data_desc->streams());
1763 }
1764 }
1765
Steve Anton8a006912017-12-04 15:25:56 -08001766 return RTCError::OK();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001767}
1768
1769void PeerConnection::SetRemoteDescription(
Henrik Boströma4ecf552017-11-23 14:17:07 +00001770 SetSessionDescriptionObserver* observer,
1771 SessionDescriptionInterface* desc) {
Henrik Boström31638672017-11-23 17:48:32 +01001772 SetRemoteDescription(
1773 std::unique_ptr<SessionDescriptionInterface>(desc),
1774 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface>(
1775 new SetRemoteDescriptionObserverAdapter(this, observer)));
1776}
1777
1778void PeerConnection::SetRemoteDescription(
1779 std::unique_ptr<SessionDescriptionInterface> desc,
1780 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface> observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001781 TRACE_EVENT0("webrtc", "PeerConnection::SetRemoteDescription");
Steve Anton8a006912017-12-04 15:25:56 -08001782
nisse7ce109a2017-01-31 00:57:56 -08001783 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001784 RTC_LOG(LS_ERROR) << "SetRemoteDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001785 return;
1786 }
Steve Anton8a006912017-12-04 15:25:56 -08001787
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001788 if (!desc) {
Henrik Boström31638672017-11-23 17:48:32 +01001789 observer->OnSetRemoteDescriptionComplete(RTCError(
Steve Anton8a006912017-12-04 15:25:56 -08001790 RTCErrorType::INVALID_PARAMETER, "SessionDescription is NULL."));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001791 return;
1792 }
Steve Anton8d3444d2017-10-20 15:30:51 -07001793
Steve Antona3a92c22017-12-07 10:27:41 -08001794 const SdpType type = desc->GetType();
Steve Anton8a006912017-12-04 15:25:56 -08001795
1796 RTCError error = ApplyRemoteDescription(std::move(desc));
1797 // |desc| may be destroyed at this point.
1798
1799 if (!error.ok()) {
Steve Antona3a92c22017-12-07 10:27:41 -08001800 std::ostringstream oss;
1801 oss << "Failed to set remote " << SdpTypeToString(type)
1802 << " sdp: " << error.message();
1803 std::string error_message = oss.str();
Steve Anton8a006912017-12-04 15:25:56 -08001804 RTC_LOG(LS_ERROR) << error_message << " (" << error.type() << ")";
Henrik Boström31638672017-11-23 17:48:32 +01001805 observer->OnSetRemoteDescriptionComplete(
Steve Anton8a006912017-12-04 15:25:56 -08001806 RTCError(error.type(), std::move(error_message)));
Steve Anton8d3444d2017-10-20 15:30:51 -07001807 return;
1808 }
1809
Steve Antona3a92c22017-12-07 10:27:41 -08001810 if (remote_description()->GetType() == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08001811 // TODO(deadbeef): We already had to hop to the network thread for
1812 // MaybeStartGathering...
1813 network_thread()->Invoke<void>(
1814 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
1815 port_allocator_.get()));
1816 }
1817
1818 observer->OnSetRemoteDescriptionComplete(RTCError::OK());
1819}
1820
1821RTCError PeerConnection::ApplyRemoteDescription(
1822 std::unique_ptr<SessionDescriptionInterface> desc) {
1823 RTC_DCHECK_RUN_ON(signaling_thread());
1824 RTC_DCHECK(desc);
1825
1826 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_REMOTE);
1827 if (!error.ok()) {
1828 return error;
1829 }
1830
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001831 // Update stats here so that we have the most recent stats for tracks and
1832 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001833 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 15:25:56 -08001834
Steve Antondcc3c022017-12-22 16:02:54 -08001835 // Take a reference to the old remote description since it's used below to
1836 // compare against the new remote description. When setting the new remote
1837 // description, grab ownership of the replaced session description in case it
1838 // is the same as |old_remote_description|, to keep it alive for the duration
1839 // of the method.
Steve Anton8a006912017-12-04 15:25:56 -08001840 const SessionDescriptionInterface* old_remote_description =
1841 remote_description();
Steve Anton8a006912017-12-04 15:25:56 -08001842 std::unique_ptr<SessionDescriptionInterface> replaced_remote_description;
Steve Anton3828c062017-12-06 10:34:51 -08001843 SdpType type = desc->GetType();
1844 if (type == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08001845 replaced_remote_description = pending_remote_description_
1846 ? std::move(pending_remote_description_)
1847 : std::move(current_remote_description_);
1848 current_remote_description_ = std::move(desc);
1849 pending_remote_description_ = nullptr;
1850 current_local_description_ = std::move(pending_local_description_);
1851 } else {
1852 replaced_remote_description = std::move(pending_remote_description_);
1853 pending_remote_description_ = std::move(desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001854 }
Steve Anton8a006912017-12-04 15:25:56 -08001855 // The session description to apply now must be accessed by
1856 // |remote_description()|.
Henrik Boströmfdb92012017-11-09 19:55:44 +01001857 RTC_DCHECK(remote_description());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001858
Steve Anton8a006912017-12-04 15:25:56 -08001859 // Transport and Media channels will be created only when offer is set.
Steve Antondcc3c022017-12-22 16:02:54 -08001860 if (IsUnifiedPlan()) {
1861 RTCError error = UpdateTransceiversAndDataChannels(
1862 cricket::CS_REMOTE, old_remote_description, *remote_description());
Steve Anton8a006912017-12-04 15:25:56 -08001863 if (!error.ok()) {
1864 return error;
1865 }
Steve Antondcc3c022017-12-22 16:02:54 -08001866 } else {
1867 if (type == SdpType::kOffer) {
1868 // TODO(bugs.webrtc.org/4676) - Handle CreateChannel failure, as new local
1869 // description is applied. Restore back to old description.
1870 RTCError error = CreateChannels(*remote_description()->description());
1871 if (!error.ok()) {
1872 return error;
1873 }
1874 }
Steve Anton8a006912017-12-04 15:25:56 -08001875
Steve Antondcc3c022017-12-22 16:02:54 -08001876 // Remove unused channels if MediaContentDescription is rejected.
1877 RemoveUnusedChannels(remote_description()->description());
1878 }
Steve Anton8a006912017-12-04 15:25:56 -08001879
1880 // NOTE: Candidates allocation will be initiated only when SetLocalDescription
1881 // is called.
Steve Anton3828c062017-12-06 10:34:51 -08001882 error = UpdateSessionState(type, cricket::CS_REMOTE);
Steve Anton8a006912017-12-04 15:25:56 -08001883 if (!error.ok()) {
1884 return error;
1885 }
1886
1887 if (local_description() &&
1888 !UseCandidatesInSessionDescription(remote_description())) {
1889 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidCandidates);
1890 }
1891
1892 if (old_remote_description) {
1893 for (const cricket::ContentInfo& content :
1894 old_remote_description->description()->contents()) {
1895 // Check if this new SessionDescription contains new ICE ufrag and
1896 // password that indicates the remote peer requests an ICE restart.
1897 // TODO(deadbeef): When we start storing both the current and pending
1898 // remote description, this should reset pending_ice_restarts and compare
1899 // against the current description.
1900 if (CheckForRemoteIceRestart(old_remote_description, remote_description(),
1901 content.name)) {
Steve Anton3828c062017-12-06 10:34:51 -08001902 if (type == SdpType::kOffer) {
Steve Anton8a006912017-12-04 15:25:56 -08001903 pending_ice_restarts_.insert(content.name);
1904 }
1905 } else {
1906 // We retain all received candidates only if ICE is not restarted.
1907 // When ICE is restarted, all previous candidates belong to an old
1908 // generation and should not be kept.
1909 // TODO(deadbeef): This goes against the W3C spec which says the remote
1910 // description should only contain candidates from the last set remote
1911 // description plus any candidates added since then. We should remove
1912 // this once we're sure it won't break anything.
1913 WebRtcSessionDescriptionFactory::CopyCandidatesFromSessionDescription(
1914 old_remote_description, content.name, mutable_remote_description());
1915 }
1916 }
1917 }
1918
1919 if (session_error() != SessionError::kNone) {
1920 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
1921 }
1922
1923 // Set the the ICE connection state to connecting since the connection may
1924 // become writable with peer reflexive candidates before any remote candidate
1925 // is signaled.
1926 // TODO(pthatcher): This is a short-term solution for crbug/446908. A real fix
1927 // is to have a new signal the indicates a change in checking state from the
1928 // transport and expose a new checking() member from transport that can be
1929 // read to determine the current checking state. The existing SignalConnecting
1930 // actually means "gathering candidates", so cannot be be used here.
Steve Antona3a92c22017-12-07 10:27:41 -08001931 if (remote_description()->GetType() != SdpType::kOffer &&
Steve Anton8a006912017-12-04 15:25:56 -08001932 ice_connection_state() == PeerConnectionInterface::kIceConnectionNew) {
1933 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
1934 }
1935
deadbeefab9b2d12015-10-14 11:33:11 -07001936 // If setting the description decided our SSL role, allocate any necessary
1937 // SCTP sids.
1938 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08001939 if (data_channel_type() == cricket::DCT_SCTP && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001940 AllocateSctpSids(role);
1941 }
1942
Steve Antondcc3c022017-12-22 16:02:54 -08001943 if (IsUnifiedPlan()) {
1944 for (auto transceiver : transceivers_) {
1945 const ContentInfo* content =
1946 FindMediaSectionForTransceiver(transceiver, remote_description());
1947 if (!content) {
1948 continue;
1949 }
1950 const MediaContentDescription* media_desc = content->media_description();
1951 RtpTransceiverDirection local_direction =
1952 RtpTransceiverDirectionReversed(media_desc->direction());
1953 // From the WebRTC specification, steps 2.2.8.5/6 of section 4.4.1.6 "Set
1954 // the RTCSessionDescription: If direction is sendrecv or recvonly, and
1955 // transceiver's current direction is neither sendrecv nor recvonly,
1956 // process the addition of a remote track for the media description.
1957 if (RtpTransceiverDirectionHasRecv(local_direction) &&
1958 (!transceiver->current_direction() ||
1959 !RtpTransceiverDirectionHasRecv(
1960 *transceiver->current_direction()))) {
1961 // TODO(bugs.webrtc.org/7600): Process the addition of a remote track.
1962 }
1963 // If direction is sendonly or inactive, and transceiver's current
1964 // direction is neither sendonly nor inactive, process the removal of a
1965 // remote track for the media description.
1966 if (!RtpTransceiverDirectionHasRecv(local_direction) &&
1967 (!transceiver->current_direction() ||
1968 RtpTransceiverDirectionHasRecv(*transceiver->current_direction()))) {
1969 // TODO(bugs.webrtc.org/7600): Process the removal of a remote track.
1970 }
1971 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
1972 transceiver->internal()->set_current_direction(local_direction);
1973 }
1974 if (content->rejected && !transceiver->stopped()) {
1975 transceiver->Stop();
1976 }
1977 }
1978 }
1979
Henrik Boströmfdb92012017-11-09 19:55:44 +01001980 const cricket::ContentInfo* audio_content =
1981 GetFirstAudioContent(remote_description()->description());
1982 const cricket::ContentInfo* video_content =
1983 GetFirstVideoContent(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08001984 const cricket::AudioContentDescription* audio_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01001985 GetFirstAudioContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08001986 const cricket::VideoContentDescription* video_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01001987 GetFirstVideoContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08001988 const cricket::DataContentDescription* data_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01001989 GetFirstDataContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08001990
1991 // Check if the descriptions include streams, just in case the peer supports
1992 // MSID, but doesn't indicate so with "a=msid-semantic".
Henrik Boströmfdb92012017-11-09 19:55:44 +01001993 if (remote_description()->description()->msid_supported() ||
deadbeefbda7e0b2015-12-08 17:13:40 -08001994 (audio_desc && !audio_desc->streams().empty()) ||
1995 (video_desc && !video_desc->streams().empty())) {
1996 remote_peer_supports_msid_ = true;
1997 }
deadbeefab9b2d12015-10-14 11:33:11 -07001998
1999 // We wait to signal new streams until we finish processing the description,
2000 // since only at that point will new streams have all their tracks.
2001 rtc::scoped_refptr<StreamCollection> new_streams(StreamCollection::Create());
2002
Steve Antondcc3c022017-12-22 16:02:54 -08002003 if (!IsUnifiedPlan()) {
2004 // TODO(steveanton): When removing RTP senders/receivers in response to a
2005 // rejected media section, there is some cleanup logic that expects the
2006 // voice/ video channel to still be set. But in this method the voice/video
2007 // channel would have been destroyed by the SetRemoteDescription caller
2008 // above so the cleanup that relies on them fails to run. The RemoveSenders
2009 // calls should be moved to right before the DestroyChannel calls to fix
2010 // this.
Steve Anton8d3444d2017-10-20 15:30:51 -07002011
Steve Antondcc3c022017-12-22 16:02:54 -08002012 // Find all audio rtp streams and create corresponding remote AudioTracks
2013 // and MediaStreams.
2014 if (audio_content) {
2015 if (audio_content->rejected) {
2016 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
2017 } else {
2018 bool default_audio_track_needed =
2019 !remote_peer_supports_msid_ &&
2020 RtpTransceiverDirectionHasSend(audio_desc->direction());
2021 UpdateRemoteSendersList(GetActiveStreams(audio_desc),
2022 default_audio_track_needed, audio_desc->type(),
2023 new_streams);
2024 }
deadbeeffaac4972015-11-12 15:33:07 -08002025 }
deadbeefab9b2d12015-10-14 11:33:11 -07002026
Steve Antondcc3c022017-12-22 16:02:54 -08002027 // Find all video rtp streams and create corresponding remote VideoTracks
2028 // and MediaStreams.
2029 if (video_content) {
2030 if (video_content->rejected) {
2031 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
2032 } else {
2033 bool default_video_track_needed =
2034 !remote_peer_supports_msid_ &&
2035 RtpTransceiverDirectionHasSend(video_desc->direction());
2036 UpdateRemoteSendersList(GetActiveStreams(video_desc),
2037 default_video_track_needed, video_desc->type(),
2038 new_streams);
2039 }
deadbeeffaac4972015-11-12 15:33:07 -08002040 }
deadbeefab9b2d12015-10-14 11:33:11 -07002041
Steve Antondcc3c022017-12-22 16:02:54 -08002042 // Update the DataChannels with the information from the remote peer.
2043 if (data_desc) {
2044 if (rtc::starts_with(data_desc->protocol().data(),
2045 cricket::kMediaProtocolRtpPrefix)) {
2046 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
2047 }
deadbeefab9b2d12015-10-14 11:33:11 -07002048 }
deadbeefab9b2d12015-10-14 11:33:11 -07002049
Steve Antondcc3c022017-12-22 16:02:54 -08002050 // Iterate new_streams and notify the observer about new MediaStreams.
2051 for (size_t i = 0; i < new_streams->count(); ++i) {
2052 MediaStreamInterface* new_stream = new_streams->at(i);
2053 stats_->AddStream(new_stream);
2054 observer_->OnAddStream(
2055 rtc::scoped_refptr<MediaStreamInterface>(new_stream));
2056 }
deadbeefab9b2d12015-10-14 11:33:11 -07002057
Steve Antondcc3c022017-12-22 16:02:54 -08002058 UpdateEndedRemoteMediaStreams();
2059 }
deadbeefab9b2d12015-10-14 11:33:11 -07002060
Steve Anton8a006912017-12-04 15:25:56 -08002061 return RTCError::OK();
deadbeeffc648b62015-10-13 16:42:33 -07002062}
2063
Steve Antondcc3c022017-12-22 16:02:54 -08002064RTCError PeerConnection::UpdateTransceiversAndDataChannels(
2065 cricket::ContentSource source,
2066 const SessionDescriptionInterface* old_session,
2067 const SessionDescriptionInterface& new_session) {
2068 RTC_DCHECK(IsUnifiedPlan());
2069
2070 auto bundle_group_or_error = GetEarlyBundleGroup(*new_session.description());
2071 if (!bundle_group_or_error.ok()) {
2072 return bundle_group_or_error.MoveError();
2073 }
2074 const cricket::ContentGroup* bundle_group = bundle_group_or_error.MoveValue();
2075
2076 const ContentInfos& old_contents =
2077 (old_session ? old_session->description()->contents() : ContentInfos());
2078 const ContentInfos& new_contents = new_session.description()->contents();
2079
2080 for (size_t i = 0; i < new_contents.size(); ++i) {
2081 const cricket::ContentInfo& new_content = new_contents[i];
2082 const cricket::ContentInfo* old_content =
2083 (i < old_contents.size() ? &old_contents[i] : nullptr);
2084 cricket::MediaType media_type = new_content.media_description()->type();
2085 seen_mids_.insert(new_content.name);
2086 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
2087 media_type == cricket::MEDIA_TYPE_VIDEO) {
2088 auto transceiver_or_error =
2089 AssociateTransceiver(source, i, new_content, old_content);
2090 if (!transceiver_or_error.ok()) {
2091 return transceiver_or_error.MoveError();
2092 }
2093 auto transceiver = transceiver_or_error.MoveValue();
2094 if (source == cricket::CS_LOCAL && transceiver->stopped()) {
2095 continue;
2096 }
2097 RTCError error =
2098 UpdateTransceiverChannel(transceiver, new_content, bundle_group);
2099 if (!error.ok()) {
2100 return error;
2101 }
2102 } else if (media_type == cricket::MEDIA_TYPE_DATA) {
Steve Antonfa2260d2017-12-28 16:38:23 -08002103 if (GetDataMid() && new_content.name != *GetDataMid()) {
2104 // Ignore all but the first data section.
2105 continue;
2106 }
2107 RTCError error = UpdateDataChannel(source, new_content, bundle_group);
2108 if (!error.ok()) {
2109 return error;
2110 }
Steve Antondcc3c022017-12-22 16:02:54 -08002111 } else {
2112 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
2113 "Unknown section type.");
2114 }
2115 }
2116
2117 return RTCError::OK();
2118}
2119
2120RTCError PeerConnection::UpdateTransceiverChannel(
2121 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2122 transceiver,
2123 const cricket::ContentInfo& content,
2124 const cricket::ContentGroup* bundle_group) {
2125 RTC_DCHECK(IsUnifiedPlan());
2126 RTC_DCHECK(transceiver);
2127 cricket::BaseChannel* channel = transceiver->internal()->channel();
2128 if (content.rejected) {
2129 if (channel) {
2130 transceiver->internal()->SetChannel(nullptr);
2131 DestroyBaseChannel(channel);
2132 }
2133 } else {
2134 if (!channel) {
2135 if (transceiver->internal()->media_type() == cricket::MEDIA_TYPE_AUDIO) {
2136 channel = CreateVoiceChannel(
2137 content.name,
2138 GetTransportNameForMediaSection(content.name, bundle_group));
2139 } else {
2140 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO,
2141 transceiver->internal()->media_type());
2142 channel = CreateVideoChannel(
2143 content.name,
2144 GetTransportNameForMediaSection(content.name, bundle_group));
2145 }
2146 if (!channel) {
2147 LOG_AND_RETURN_ERROR(
2148 RTCErrorType::INTERNAL_ERROR,
2149 "Failed to create channel for mid=" + content.name);
2150 }
2151 transceiver->internal()->SetChannel(channel);
2152 }
2153 }
2154 return RTCError::OK();
2155}
2156
Steve Antonfa2260d2017-12-28 16:38:23 -08002157RTCError PeerConnection::UpdateDataChannel(
2158 cricket::ContentSource source,
2159 const cricket::ContentInfo& content,
2160 const cricket::ContentGroup* bundle_group) {
2161 if (data_channel_type_ == cricket::DCT_NONE) {
2162 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2163 "Data channels are not supported.");
2164 }
2165 if (content.rejected) {
2166 DestroyDataChannel();
2167 } else {
2168 if (!rtp_data_channel_ && !sctp_transport_) {
2169 if (!CreateDataChannel(content.name, GetTransportNameForMediaSection(
2170 content.name, bundle_group))) {
2171 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
2172 "Failed to create data channel.");
2173 }
2174 }
2175 if (source == cricket::CS_REMOTE) {
2176 const MediaContentDescription* data_desc = content.media_description();
2177 if (data_desc && cricket::IsRtpProtocol(data_desc->protocol())) {
2178 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
2179 }
2180 }
2181 }
2182 return RTCError::OK();
2183}
2184
Steve Antondcc3c022017-12-22 16:02:54 -08002185RTCErrorOr<rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
2186PeerConnection::AssociateTransceiver(cricket::ContentSource source,
2187 size_t mline_index,
2188 const ContentInfo& content,
2189 const ContentInfo* old_content) {
2190 RTC_DCHECK(IsUnifiedPlan());
2191 // If the m= section is being recycled (rejected in previous remote
2192 // description, not rejected in current description), dissociate the currently
2193 // associated RtpTransceiver by setting its mid property to null, and discard
2194 // the mapping between the transceiver and its m= section index.
2195 if (old_content && old_content->rejected && !content.rejected) {
2196 auto old_transceiver = GetAssociatedTransceiver(old_content->name);
2197 if (old_transceiver) {
2198 old_transceiver->internal()->set_mid(rtc::nullopt);
2199 old_transceiver->internal()->set_mline_index(rtc::nullopt);
2200 }
2201 }
2202 const MediaContentDescription* media_desc = content.media_description();
2203 auto transceiver = GetAssociatedTransceiver(content.name);
2204 if (source == cricket::CS_LOCAL) {
2205 // Find the RtpTransceiver that corresponds to this m= section, using the
2206 // mapping between transceivers and m= section indices established when
2207 // creating the offer.
2208 if (!transceiver) {
2209 transceiver = GetTransceiverByMLineIndex(mline_index);
2210 }
2211 if (!transceiver) {
2212 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2213 "Unknown transceiver");
2214 }
2215 } else {
2216 RTC_DCHECK_EQ(source, cricket::CS_REMOTE);
2217 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers
2218 // of the same type...
2219 if (!transceiver &&
2220 RtpTransceiverDirectionHasRecv(media_desc->direction())) {
2221 transceiver = FindAvailableTransceiverToReceive(media_desc->type());
2222 }
2223 // If no RtpTransceiver was found in the previous step, create one with a
2224 // recvonly direction.
2225 if (!transceiver) {
2226 transceiver = CreateTransceiver(media_desc->type());
2227 transceiver->internal()->set_direction(
2228 RtpTransceiverDirection::kRecvOnly);
2229 }
2230 }
2231 RTC_DCHECK(transceiver);
2232 if (transceiver->internal()->media_type() != media_desc->type()) {
2233 LOG_AND_RETURN_ERROR(
2234 RTCErrorType::INVALID_PARAMETER,
2235 "Transceiver type does not match media description type.");
2236 }
2237 // Associate the found or created RtpTransceiver with the m= section by
2238 // setting the value of the RtpTransceiver's mid property to the MID of the m=
2239 // section, and establish a mapping between the transceiver and the index of
2240 // the m= section.
2241 transceiver->internal()->set_mid(content.name);
2242 transceiver->internal()->set_mline_index(mline_index);
2243 return std::move(transceiver);
2244}
2245
2246rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2247PeerConnection::GetAssociatedTransceiver(const std::string& mid) const {
2248 RTC_DCHECK(IsUnifiedPlan());
2249 for (auto transceiver : transceivers_) {
2250 if (transceiver->mid() == mid) {
2251 return transceiver;
2252 }
2253 }
2254 return nullptr;
2255}
2256
2257rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2258PeerConnection::GetTransceiverByMLineIndex(size_t mline_index) const {
2259 RTC_DCHECK(IsUnifiedPlan());
2260 for (auto transceiver : transceivers_) {
2261 if (transceiver->internal()->mline_index() == mline_index) {
2262 return transceiver;
2263 }
2264 }
2265 return nullptr;
2266}
2267
2268rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2269PeerConnection::FindAvailableTransceiverToReceive(
2270 cricket::MediaType media_type) const {
2271 RTC_DCHECK(IsUnifiedPlan());
2272 // From JSEP section 5.10 (Applying a Remote Description):
2273 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers of
2274 // the same type that were added to the PeerConnection by addTrack and are not
2275 // associated with any m= section and are not stopped, find the first such
2276 // RtpTransceiver.
2277 for (auto transceiver : transceivers_) {
2278 if (transceiver->internal()->media_type() == media_type &&
2279 transceiver->internal()->created_by_addtrack() && !transceiver->mid() &&
2280 !transceiver->stopped()) {
2281 return transceiver;
2282 }
2283 }
2284 return nullptr;
2285}
2286
Steve Antoned10bd92017-12-05 10:52:59 -08002287const cricket::ContentInfo* PeerConnection::FindMediaSectionForTransceiver(
2288 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2289 transceiver,
2290 const SessionDescriptionInterface* sdesc) const {
2291 RTC_DCHECK(transceiver);
2292 RTC_DCHECK(sdesc);
2293 if (IsUnifiedPlan()) {
2294 if (!transceiver->internal()->mid()) {
2295 // This transceiver is not associated with a media section yet.
2296 return nullptr;
2297 }
2298 return sdesc->description()->GetContentByName(
2299 *transceiver->internal()->mid());
2300 } else {
2301 // Plan B only allows at most one audio and one video section, so use the
2302 // first media section of that type.
2303 return cricket::GetFirstMediaContent(sdesc->description()->contents(),
2304 transceiver->internal()->media_type());
2305 }
2306}
2307
deadbeef46c73892016-11-16 19:42:04 -08002308PeerConnectionInterface::RTCConfiguration PeerConnection::GetConfiguration() {
2309 return configuration_;
2310}
2311
deadbeef293e9262017-01-11 12:28:30 -08002312bool PeerConnection::SetConfiguration(const RTCConfiguration& configuration,
2313 RTCError* error) {
Peter Boström1a9d6152015-12-08 22:15:17 +01002314 TRACE_EVENT0("webrtc", "PeerConnection::SetConfiguration");
deadbeef6de92f92016-12-12 18:49:32 -08002315
Steve Anton75737c02017-11-06 10:37:17 -08002316 if (local_description() && configuration.ice_candidate_pool_size !=
2317 configuration_.ice_candidate_pool_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002318 RTC_LOG(LS_ERROR) << "Can't change candidate pool size after calling "
2319 "SetLocalDescription.";
deadbeef293e9262017-01-11 12:28:30 -08002320 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00002321 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002322
deadbeef293e9262017-01-11 12:28:30 -08002323 // The simplest (and most future-compatible) way to tell if the config was
2324 // modified in an invalid way is to copy each property we do support
2325 // modifying, then use operator==. There are far more properties we don't
2326 // support modifying than those we do, and more could be added.
2327 RTCConfiguration modified_config = configuration_;
2328 modified_config.servers = configuration.servers;
2329 modified_config.type = configuration.type;
2330 modified_config.ice_candidate_pool_size =
2331 configuration.ice_candidate_pool_size;
2332 modified_config.prune_turn_ports = configuration.prune_turn_ports;
skvladd1f5fda2017-02-03 16:54:05 -08002333 modified_config.ice_check_min_interval = configuration.ice_check_min_interval;
Jonas Orelandbdcee282017-10-10 14:01:40 +02002334 modified_config.turn_customizer = configuration.turn_customizer;
deadbeef293e9262017-01-11 12:28:30 -08002335 if (configuration != modified_config) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002336 RTC_LOG(LS_ERROR) << "Modifying the configuration in an unsupported way.";
deadbeef293e9262017-01-11 12:28:30 -08002337 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
2338 }
2339
Steve Anton038834f2017-07-14 15:59:59 -07002340 // Validate the modified configuration.
2341 RTCError validate_error = ValidateConfiguration(modified_config);
2342 if (!validate_error.ok()) {
2343 return SafeSetError(std::move(validate_error), error);
2344 }
2345
deadbeef293e9262017-01-11 12:28:30 -08002346 // Note that this isn't possible through chromium, since it's an unsigned
2347 // short in WebIDL.
2348 if (configuration.ice_candidate_pool_size < 0 ||
2349 configuration.ice_candidate_pool_size > UINT16_MAX) {
2350 return SafeSetError(RTCErrorType::INVALID_RANGE, error);
2351 }
2352
2353 // Parse ICE servers before hopping to network thread.
2354 cricket::ServerAddresses stun_servers;
2355 std::vector<cricket::RelayServerConfig> turn_servers;
2356 RTCErrorType parse_error =
2357 ParseIceServers(configuration.servers, &stun_servers, &turn_servers);
2358 if (parse_error != RTCErrorType::NONE) {
2359 return SafeSetError(parse_error, error);
2360 }
2361
2362 // In theory this shouldn't fail.
2363 if (!network_thread()->Invoke<bool>(
2364 RTC_FROM_HERE,
2365 rtc::Bind(&PeerConnection::ReconfigurePortAllocator_n, this,
2366 stun_servers, turn_servers, modified_config.type,
2367 modified_config.ice_candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02002368 modified_config.prune_turn_ports,
2369 modified_config.turn_customizer))) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002370 RTC_LOG(LS_ERROR) << "Failed to apply configuration to PortAllocator.";
deadbeef293e9262017-01-11 12:28:30 -08002371 return SafeSetError(RTCErrorType::INTERNAL_ERROR, error);
2372 }
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07002373
deadbeefd1a38b52016-12-10 13:15:33 -08002374 // As described in JSEP, calling setConfiguration with new ICE servers or
2375 // candidate policy must set a "needs-ice-restart" bit so that the next offer
2376 // triggers an ICE restart which will pick up the changes.
deadbeef293e9262017-01-11 12:28:30 -08002377 if (modified_config.servers != configuration_.servers ||
2378 modified_config.type != configuration_.type ||
2379 modified_config.prune_turn_ports != configuration_.prune_turn_ports) {
Steve Antond25da372017-11-06 14:50:29 -08002380 transport_controller_->SetNeedsIceRestartFlag();
deadbeefd1a38b52016-12-10 13:15:33 -08002381 }
skvladd1f5fda2017-02-03 16:54:05 -08002382
2383 if (modified_config.ice_check_min_interval !=
2384 configuration_.ice_check_min_interval) {
Steve Antond25da372017-11-06 14:50:29 -08002385 transport_controller_->SetIceConfig(ParseIceConfig(modified_config));
skvladd1f5fda2017-02-03 16:54:05 -08002386 }
2387
deadbeef293e9262017-01-11 12:28:30 -08002388 configuration_ = modified_config;
2389 return SafeSetError(RTCErrorType::NONE, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00002390}
2391
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002392bool PeerConnection::AddIceCandidate(
2393 const IceCandidateInterface* ice_candidate) {
Peter Boström1a9d6152015-12-08 22:15:17 +01002394 TRACE_EVENT0("webrtc", "PeerConnection::AddIceCandidate");
zhihuang29ff8442016-07-27 11:07:25 -07002395 if (IsClosed()) {
2396 return false;
2397 }
Steve Antond25da372017-11-06 14:50:29 -08002398
2399 if (!remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002400 RTC_LOG(LS_ERROR) << "ProcessIceMessage: ICE candidates can't be added "
2401 << "without any remote session description.";
Steve Antond25da372017-11-06 14:50:29 -08002402 return false;
2403 }
2404
2405 if (!ice_candidate) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002406 RTC_LOG(LS_ERROR) << "ProcessIceMessage: Candidate is NULL.";
Steve Antond25da372017-11-06 14:50:29 -08002407 return false;
2408 }
2409
2410 bool valid = false;
2411 bool ready = ReadyToUseRemoteCandidate(ice_candidate, nullptr, &valid);
2412 if (!valid) {
2413 return false;
2414 }
2415
2416 // Add this candidate to the remote session description.
2417 if (!mutable_remote_description()->AddCandidate(ice_candidate)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002418 RTC_LOG(LS_ERROR) << "ProcessIceMessage: Candidate cannot be used.";
Steve Antond25da372017-11-06 14:50:29 -08002419 return false;
2420 }
2421
2422 if (ready) {
2423 return UseCandidate(ice_candidate);
2424 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002425 RTC_LOG(LS_INFO) << "ProcessIceMessage: Not ready to use candidate.";
Steve Antond25da372017-11-06 14:50:29 -08002426 return true;
2427 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002428}
2429
Honghai Zhang7fb69db2016-03-14 11:59:18 -07002430bool PeerConnection::RemoveIceCandidates(
2431 const std::vector<cricket::Candidate>& candidates) {
2432 TRACE_EVENT0("webrtc", "PeerConnection::RemoveIceCandidates");
Steve Antond25da372017-11-06 14:50:29 -08002433 if (!remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002434 RTC_LOG(LS_ERROR) << "RemoveRemoteIceCandidates: ICE candidates can't be "
2435 << "removed without any remote session description.";
Steve Antond25da372017-11-06 14:50:29 -08002436 return false;
2437 }
2438
2439 if (candidates.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002440 RTC_LOG(LS_ERROR) << "RemoveRemoteIceCandidates: candidates are empty.";
Steve Antond25da372017-11-06 14:50:29 -08002441 return false;
2442 }
2443
2444 size_t number_removed =
2445 mutable_remote_description()->RemoveCandidates(candidates);
2446 if (number_removed != candidates.size()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002447 RTC_LOG(LS_ERROR)
2448 << "RemoveRemoteIceCandidates: Failed to remove candidates. "
2449 << "Requested " << candidates.size() << " but only " << number_removed
2450 << " are removed.";
Steve Antond25da372017-11-06 14:50:29 -08002451 }
2452
2453 // Remove the candidates from the transport controller.
2454 std::string error;
2455 bool res = transport_controller_->RemoveRemoteCandidates(candidates, &error);
2456 if (!res && !error.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002457 RTC_LOG(LS_ERROR) << "Error when removing remote candidates: " << error;
Steve Antond25da372017-11-06 14:50:29 -08002458 }
2459 return true;
Honghai Zhang7fb69db2016-03-14 11:59:18 -07002460}
2461
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00002462void PeerConnection::RegisterUMAObserver(UMAObserver* observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +01002463 TRACE_EVENT0("webrtc", "PeerConnection::RegisterUmaObserver");
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00002464 uma_observer_ = observer;
guoweis@webrtc.org7169afd2014-12-04 17:59:29 +00002465
Steve Anton75737c02017-11-06 10:37:17 -08002466 if (transport_controller()) {
2467 transport_controller()->SetMetricsObserver(uma_observer_);
guoweis@webrtc.org7169afd2014-12-04 17:59:29 +00002468 }
2469
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00002470 // Send information about IPv4/IPv6 status.
deadbeef293e9262017-01-11 12:28:30 -08002471 if (uma_observer_) {
Honghai Zhangd93f50c2016-10-05 11:47:22 -07002472 port_allocator_->SetMetricsObserver(uma_observer_);
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00002473 if (port_allocator_->flags() & cricket::PORTALLOCATOR_ENABLE_IPV6) {
Guo-wei Shiehdfbe6792015-09-03 17:12:07 -07002474 uma_observer_->IncrementEnumCounter(
2475 kEnumCounterAddressFamily, kPeerConnection_IPv6,
2476 kPeerConnectionAddressFamilyCounter_Max);
mallinath@webrtc.orgb445f262014-05-23 22:19:37 +00002477 } else {
Guo-wei Shiehdfbe6792015-09-03 17:12:07 -07002478 uma_observer_->IncrementEnumCounter(
2479 kEnumCounterAddressFamily, kPeerConnection_IPv4,
2480 kPeerConnectionAddressFamilyCounter_Max);
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00002481 }
2482 }
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00002483}
2484
zstein4b979802017-06-02 14:37:37 -07002485RTCError PeerConnection::SetBitrate(const BitrateParameters& bitrate) {
Steve Anton978b8762017-09-29 12:15:02 -07002486 if (!worker_thread()->IsCurrent()) {
2487 return worker_thread()->Invoke<RTCError>(
zstein4b979802017-06-02 14:37:37 -07002488 RTC_FROM_HERE, rtc::Bind(&PeerConnection::SetBitrate, this, bitrate));
2489 }
2490
2491 const bool has_min = static_cast<bool>(bitrate.min_bitrate_bps);
2492 const bool has_current = static_cast<bool>(bitrate.current_bitrate_bps);
2493 const bool has_max = static_cast<bool>(bitrate.max_bitrate_bps);
2494 if (has_min && *bitrate.min_bitrate_bps < 0) {
2495 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2496 "min_bitrate_bps <= 0");
2497 }
2498 if (has_current) {
2499 if (has_min && *bitrate.current_bitrate_bps < *bitrate.min_bitrate_bps) {
2500 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2501 "current_bitrate_bps < min_bitrate_bps");
2502 } else if (*bitrate.current_bitrate_bps < 0) {
2503 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2504 "curent_bitrate_bps < 0");
2505 }
2506 }
2507 if (has_max) {
2508 if (has_current &&
2509 *bitrate.max_bitrate_bps < *bitrate.current_bitrate_bps) {
2510 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2511 "max_bitrate_bps < current_bitrate_bps");
2512 } else if (has_min && *bitrate.max_bitrate_bps < *bitrate.min_bitrate_bps) {
2513 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2514 "max_bitrate_bps < min_bitrate_bps");
2515 } else if (*bitrate.max_bitrate_bps < 0) {
2516 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2517 "max_bitrate_bps < 0");
2518 }
2519 }
2520
2521 Call::Config::BitrateConfigMask mask;
2522 mask.min_bitrate_bps = bitrate.min_bitrate_bps;
2523 mask.start_bitrate_bps = bitrate.current_bitrate_bps;
2524 mask.max_bitrate_bps = bitrate.max_bitrate_bps;
2525
2526 RTC_DCHECK(call_.get());
2527 call_->SetBitrateConfigMask(mask);
2528
2529 return RTCError::OK();
2530}
2531
Alex Narest78609d52017-10-20 10:37:47 +02002532void PeerConnection::SetBitrateAllocationStrategy(
2533 std::unique_ptr<rtc::BitrateAllocationStrategy>
2534 bitrate_allocation_strategy) {
2535 rtc::Thread* worker_thread = factory_->worker_thread();
2536 if (!worker_thread->IsCurrent()) {
2537 rtc::BitrateAllocationStrategy* strategy_raw =
2538 bitrate_allocation_strategy.release();
2539 auto functor = [this, strategy_raw]() {
2540 call_->SetBitrateAllocationStrategy(
2541 rtc::WrapUnique<rtc::BitrateAllocationStrategy>(strategy_raw));
2542 };
2543 worker_thread->Invoke<void>(RTC_FROM_HERE, functor);
2544 return;
2545 }
2546 RTC_DCHECK(call_.get());
2547 call_->SetBitrateAllocationStrategy(std::move(bitrate_allocation_strategy));
2548}
2549
henrika5f6bf242017-11-01 11:06:56 +01002550void PeerConnection::SetAudioPlayout(bool playout) {
2551 if (!worker_thread()->IsCurrent()) {
2552 worker_thread()->Invoke<void>(
2553 RTC_FROM_HERE,
2554 rtc::Bind(&PeerConnection::SetAudioPlayout, this, playout));
2555 return;
2556 }
2557 auto audio_state =
2558 factory_->channel_manager()->media_engine()->GetAudioState();
2559 audio_state->SetPlayout(playout);
2560}
2561
2562void PeerConnection::SetAudioRecording(bool recording) {
2563 if (!worker_thread()->IsCurrent()) {
2564 worker_thread()->Invoke<void>(
2565 RTC_FROM_HERE,
2566 rtc::Bind(&PeerConnection::SetAudioRecording, this, recording));
2567 return;
2568 }
2569 auto audio_state =
2570 factory_->channel_manager()->media_engine()->GetAudioState();
2571 audio_state->SetRecording(recording);
2572}
2573
Steve Anton8c0f7a72017-10-03 10:03:10 -07002574std::unique_ptr<rtc::SSLCertificate>
2575PeerConnection::GetRemoteAudioSSLCertificate() {
Steve Anton75737c02017-11-06 10:37:17 -08002576 if (!voice_channel()) {
Steve Anton8c0f7a72017-10-03 10:03:10 -07002577 return nullptr;
2578 }
Steve Anton75737c02017-11-06 10:37:17 -08002579 return GetRemoteSSLCertificate(voice_channel()->transport_name());
Steve Anton8c0f7a72017-10-03 10:03:10 -07002580}
2581
ivoc14d5dbe2016-07-04 07:06:55 -07002582bool PeerConnection::StartRtcEventLog(rtc::PlatformFile file,
2583 int64_t max_size_bytes) {
Elad Alon99c3fe52017-10-13 16:29:40 +02002584 // TODO(eladalon): It would be better to not allow negative values into PC.
2585 const size_t max_size = (max_size_bytes < 0)
2586 ? RtcEventLog::kUnlimitedOutput
2587 : rtc::saturated_cast<size_t>(max_size_bytes);
2588 return StartRtcEventLog(
Bjorn Tereliusde939432017-11-20 17:38:14 +01002589 rtc::MakeUnique<RtcEventLogOutputFile>(file, max_size),
2590 webrtc::RtcEventLog::kImmediateOutput);
Elad Alon99c3fe52017-10-13 16:29:40 +02002591}
2592
Bjorn Tereliusde939432017-11-20 17:38:14 +01002593bool PeerConnection::StartRtcEventLog(std::unique_ptr<RtcEventLogOutput> output,
2594 int64_t output_period_ms) {
Karl Wibergd6b48192017-10-16 23:01:06 +02002595 // TODO(eladalon): In C++14, this can be done with a lambda.
2596 struct Functor {
Bjorn Tereliusde939432017-11-20 17:38:14 +01002597 bool operator()() {
2598 return pc->StartRtcEventLog_w(std::move(output), output_period_ms);
2599 }
Karl Wibergd6b48192017-10-16 23:01:06 +02002600 PeerConnection* const pc;
2601 std::unique_ptr<RtcEventLogOutput> output;
Bjorn Tereliusde939432017-11-20 17:38:14 +01002602 const int64_t output_period_ms;
Elad Alon99c3fe52017-10-13 16:29:40 +02002603 };
Bjorn Tereliusde939432017-11-20 17:38:14 +01002604 return worker_thread()->Invoke<bool>(
2605 RTC_FROM_HERE, Functor{this, std::move(output), output_period_ms});
ivoc14d5dbe2016-07-04 07:06:55 -07002606}
2607
2608void PeerConnection::StopRtcEventLog() {
Steve Anton978b8762017-09-29 12:15:02 -07002609 worker_thread()->Invoke<void>(
ivoc14d5dbe2016-07-04 07:06:55 -07002610 RTC_FROM_HERE, rtc::Bind(&PeerConnection::StopRtcEventLog_w, this));
2611}
2612
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002613const SessionDescriptionInterface* PeerConnection::local_description() const {
Steve Anton75737c02017-11-06 10:37:17 -08002614 return pending_local_description_ ? pending_local_description_.get()
2615 : current_local_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002616}
2617
2618const SessionDescriptionInterface* PeerConnection::remote_description() const {
Steve Anton75737c02017-11-06 10:37:17 -08002619 return pending_remote_description_ ? pending_remote_description_.get()
2620 : current_remote_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002621}
2622
deadbeeffe4a8a42016-12-20 17:56:17 -08002623const SessionDescriptionInterface* PeerConnection::current_local_description()
2624 const {
Steve Anton75737c02017-11-06 10:37:17 -08002625 return current_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08002626}
2627
2628const SessionDescriptionInterface* PeerConnection::current_remote_description()
2629 const {
Steve Anton75737c02017-11-06 10:37:17 -08002630 return current_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08002631}
2632
2633const SessionDescriptionInterface* PeerConnection::pending_local_description()
2634 const {
Steve Anton75737c02017-11-06 10:37:17 -08002635 return pending_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08002636}
2637
2638const SessionDescriptionInterface* PeerConnection::pending_remote_description()
2639 const {
Steve Anton75737c02017-11-06 10:37:17 -08002640 return pending_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08002641}
2642
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002643void PeerConnection::Close() {
Peter Boström1a9d6152015-12-08 22:15:17 +01002644 TRACE_EVENT0("webrtc", "PeerConnection::Close");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002645 // Update stats here so that we have the most recent stats for tracks and
2646 // streams before the channels are closed.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00002647 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002648
Steve Anton75737c02017-11-06 10:37:17 -08002649 ChangeSignalingState(PeerConnectionInterface::kClosed);
Steve Anton3fe1b152017-12-12 10:20:08 -08002650
Steve Anton8af21862017-12-15 11:20:13 -08002651 for (auto transceiver : transceivers_) {
2652 transceiver->Stop();
2653 }
2654 DestroyAllChannels();
Steve Anton75737c02017-11-06 10:37:17 -08002655
deadbeef42a42632017-03-10 15:18:00 -08002656 network_thread()->Invoke<void>(
2657 RTC_FROM_HERE,
2658 rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
2659 port_allocator_.get()));
nisseeaabdf62017-05-05 02:23:02 -07002660
Steve Anton978b8762017-09-29 12:15:02 -07002661 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
eladalon248fd4f2017-09-06 05:18:15 -07002662 call_.reset();
2663 // The event log must outlive call (and any other object that uses it).
2664 event_log_.reset();
2665 });
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002666}
2667
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002668void PeerConnection::OnMessage(rtc::Message* msg) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002669 switch (msg->message_id) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002670 case MSG_SET_SESSIONDESCRIPTION_SUCCESS: {
2671 SetSessionDescriptionMsg* param =
2672 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
2673 param->observer->OnSuccess();
2674 delete param;
2675 break;
2676 }
2677 case MSG_SET_SESSIONDESCRIPTION_FAILED: {
2678 SetSessionDescriptionMsg* param =
2679 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
2680 param->observer->OnFailure(param->error);
2681 delete param;
2682 break;
2683 }
deadbeefab9b2d12015-10-14 11:33:11 -07002684 case MSG_CREATE_SESSIONDESCRIPTION_FAILED: {
2685 CreateSessionDescriptionMsg* param =
2686 static_cast<CreateSessionDescriptionMsg*>(msg->pdata);
2687 param->observer->OnFailure(param->error);
2688 delete param;
2689 break;
2690 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002691 case MSG_GETSTATS: {
2692 GetStatsMsg* param = static_cast<GetStatsMsg*>(msg->pdata);
nissee8abe3e2017-01-18 05:00:34 -08002693 StatsReports reports;
2694 stats_->GetStats(param->track, &reports);
2695 param->observer->OnComplete(reports);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002696 delete param;
2697 break;
2698 }
deadbeefbd292462015-12-14 18:15:29 -08002699 case MSG_FREE_DATACHANNELS: {
2700 sctp_data_channels_to_free_.clear();
2701 break;
2702 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002703 default:
nisseeb4ca4e2017-01-12 02:24:27 -08002704 RTC_NOTREACHED() << "Not implemented";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002705 break;
2706 }
2707}
2708
Steve Anton4171afb2017-11-20 10:20:22 -08002709void PeerConnection::CreateAudioReceiver(
2710 MediaStreamInterface* stream,
2711 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01002712 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
2713 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
zhihuang81c3a032016-11-17 12:06:24 -08002714 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
2715 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
deadbeefe814a0d2017-02-25 18:15:09 -08002716 signaling_thread(),
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01002717 new AudioRtpReceiver(remote_sender_info.sender_id, streams,
Steve Anton4171afb2017-11-20 10:20:22 -08002718 remote_sender_info.first_ssrc, voice_channel()));
deadbeefe814a0d2017-02-25 18:15:09 -08002719 stream->AddTrack(
2720 static_cast<AudioTrackInterface*>(receiver->internal()->track().get()));
Steve Anton4171afb2017-11-20 10:20:22 -08002721 GetAudioTransceiver()->internal()->AddReceiver(receiver);
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01002722 observer_->OnAddTrack(receiver, std::move(streams));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002723}
2724
Steve Anton4171afb2017-11-20 10:20:22 -08002725void PeerConnection::CreateVideoReceiver(
2726 MediaStreamInterface* stream,
2727 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01002728 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
2729 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
zhihuang81c3a032016-11-17 12:06:24 -08002730 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
2731 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
Steve Anton4171afb2017-11-20 10:20:22 -08002732 signaling_thread(),
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01002733 new VideoRtpReceiver(remote_sender_info.sender_id, streams,
2734 worker_thread(), remote_sender_info.first_ssrc,
2735 video_channel()));
deadbeefe814a0d2017-02-25 18:15:09 -08002736 stream->AddTrack(
2737 static_cast<VideoTrackInterface*>(receiver->internal()->track().get()));
Steve Anton4171afb2017-11-20 10:20:22 -08002738 GetVideoTransceiver()->internal()->AddReceiver(receiver);
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01002739 observer_->OnAddTrack(receiver, std::move(streams));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002740}
2741
deadbeef70ab1a12015-09-28 16:53:55 -07002742// TODO(deadbeef): Keep RtpReceivers around even if track goes away in remote
2743// description.
Henrik Boström933d8b02017-10-10 10:05:16 -07002744rtc::scoped_refptr<RtpReceiverInterface> PeerConnection::RemoveAndStopReceiver(
Steve Anton4171afb2017-11-20 10:20:22 -08002745 const RtpSenderInfo& remote_sender_info) {
2746 auto receiver = FindReceiverById(remote_sender_info.sender_id);
2747 if (!receiver) {
2748 RTC_LOG(LS_WARNING) << "RtpReceiver for track with id "
2749 << remote_sender_info.sender_id << " doesn't exist.";
Henrik Boström933d8b02017-10-10 10:05:16 -07002750 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07002751 }
Steve Anton4171afb2017-11-20 10:20:22 -08002752 if (receiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
2753 GetAudioTransceiver()->internal()->RemoveReceiver(receiver);
2754 } else {
2755 GetVideoTransceiver()->internal()->RemoveReceiver(receiver);
2756 }
Henrik Boström933d8b02017-10-10 10:05:16 -07002757 return receiver;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002758}
2759
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002760void PeerConnection::AddAudioTrack(AudioTrackInterface* track,
2761 MediaStreamInterface* stream) {
2762 RTC_DCHECK(!IsClosed());
2763 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08002764 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002765 // We already have a sender for this track, so just change the stream_id
2766 // so that it's correct in the next call to CreateOffer.
Steve Anton4171afb2017-11-20 10:20:22 -08002767 sender->internal()->set_stream_id(stream->label());
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002768 return;
2769 }
2770
2771 // Normal case; we've never seen this track before.
2772 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender =
2773 RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
2774 signaling_thread(),
Steve Anton75737c02017-11-06 10:37:17 -08002775 new AudioRtpSender(track, {stream->label()}, voice_channel(),
2776 stats_.get()));
Steve Anton4171afb2017-11-20 10:20:22 -08002777 GetAudioTransceiver()->internal()->AddSender(new_sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002778 // If the sender has already been configured in SDP, we call SetSsrc,
2779 // which will connect the sender to the underlying transport. This can
2780 // occur if a local session description that contains the ID of the sender
2781 // is set before AddStream is called. It can also occur if the local
2782 // session description is not changed and RemoveStream is called, and
2783 // later AddStream is called again with the same stream.
Steve Anton4171afb2017-11-20 10:20:22 -08002784 const RtpSenderInfo* sender_info =
2785 FindSenderInfo(local_audio_sender_infos_, stream->label(), track->id());
2786 if (sender_info) {
2787 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002788 }
2789}
2790
2791// TODO(deadbeef): Don't destroy RtpSenders here; they should be kept around
2792// indefinitely, when we have unified plan SDP.
2793void PeerConnection::RemoveAudioTrack(AudioTrackInterface* track,
2794 MediaStreamInterface* stream) {
2795 RTC_DCHECK(!IsClosed());
2796 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08002797 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002798 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
2799 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002800 return;
2801 }
Steve Anton4171afb2017-11-20 10:20:22 -08002802 GetAudioTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002803}
2804
2805void PeerConnection::AddVideoTrack(VideoTrackInterface* track,
2806 MediaStreamInterface* stream) {
2807 RTC_DCHECK(!IsClosed());
2808 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08002809 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002810 // We already have a sender for this track, so just change the stream_id
2811 // so that it's correct in the next call to CreateOffer.
Steve Anton4171afb2017-11-20 10:20:22 -08002812 sender->internal()->set_stream_id(stream->label());
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002813 return;
2814 }
2815
2816 // Normal case; we've never seen this track before.
2817 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender =
2818 RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton75737c02017-11-06 10:37:17 -08002819 signaling_thread(),
2820 new VideoRtpSender(track, {stream->label()}, video_channel()));
Steve Anton4171afb2017-11-20 10:20:22 -08002821 GetVideoTransceiver()->internal()->AddSender(new_sender);
2822 const RtpSenderInfo* sender_info =
2823 FindSenderInfo(local_video_sender_infos_, stream->label(), track->id());
2824 if (sender_info) {
2825 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002826 }
2827}
2828
2829void PeerConnection::RemoveVideoTrack(VideoTrackInterface* track,
2830 MediaStreamInterface* stream) {
2831 RTC_DCHECK(!IsClosed());
2832 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08002833 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002834 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
2835 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002836 return;
2837 }
Steve Anton4171afb2017-11-20 10:20:22 -08002838 GetVideoTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002839}
2840
Steve Antonba818672017-11-06 10:21:57 -08002841void PeerConnection::SetIceConnectionState(IceConnectionState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07002842 RTC_DCHECK(signaling_thread()->IsCurrent());
Steve Antonba818672017-11-06 10:21:57 -08002843 if (ice_connection_state_ == new_state) {
2844 return;
2845 }
2846
deadbeefcbecd352015-09-23 11:50:27 -07002847 // After transitioning to "closed", ignore any additional states from
Steve Antonba818672017-11-06 10:21:57 -08002848 // TransportController (such as "disconnected").
deadbeefab9b2d12015-10-14 11:33:11 -07002849 if (IsClosed()) {
deadbeefcbecd352015-09-23 11:50:27 -07002850 return;
2851 }
Steve Antonba818672017-11-06 10:21:57 -08002852
Mirko Bonadei675513b2017-11-09 11:09:25 +01002853 RTC_LOG(LS_INFO) << "Changing IceConnectionState " << ice_connection_state_
2854 << " => " << new_state;
Steve Antonba818672017-11-06 10:21:57 -08002855 RTC_DCHECK(ice_connection_state_ !=
2856 PeerConnectionInterface::kIceConnectionClosed);
2857
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002858 ice_connection_state_ = new_state;
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00002859 observer_->OnIceConnectionChange(ice_connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002860}
2861
2862void PeerConnection::OnIceGatheringChange(
2863 PeerConnectionInterface::IceGatheringState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07002864 RTC_DCHECK(signaling_thread()->IsCurrent());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002865 if (IsClosed()) {
2866 return;
2867 }
2868 ice_gathering_state_ = new_state;
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00002869 observer_->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002870}
2871
jbauch81bf7b02017-03-25 08:31:12 -07002872void PeerConnection::OnIceCandidate(
2873 std::unique_ptr<IceCandidateInterface> candidate) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07002874 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07002875 if (IsClosed()) {
2876 return;
2877 }
jbauch81bf7b02017-03-25 08:31:12 -07002878 observer_->OnIceCandidate(candidate.get());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002879}
2880
Honghai Zhang7fb69db2016-03-14 11:59:18 -07002881void PeerConnection::OnIceCandidatesRemoved(
2882 const std::vector<cricket::Candidate>& candidates) {
2883 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07002884 if (IsClosed()) {
2885 return;
2886 }
Honghai Zhang7fb69db2016-03-14 11:59:18 -07002887 observer_->OnIceCandidatesRemoved(candidates);
2888}
2889
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002890void PeerConnection::ChangeSignalingState(
2891 PeerConnectionInterface::SignalingState signaling_state) {
Steve Antonba818672017-11-06 10:21:57 -08002892 RTC_DCHECK(signaling_thread()->IsCurrent());
2893 if (signaling_state_ == signaling_state) {
2894 return;
2895 }
Mirko Bonadei675513b2017-11-09 11:09:25 +01002896 RTC_LOG(LS_INFO) << "Session: " << session_id() << " Old state: "
2897 << GetSignalingStateString(signaling_state_)
2898 << " New state: "
2899 << GetSignalingStateString(signaling_state);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002900 signaling_state_ = signaling_state;
2901 if (signaling_state == kClosed) {
2902 ice_connection_state_ = kIceConnectionClosed;
2903 observer_->OnIceConnectionChange(ice_connection_state_);
2904 if (ice_gathering_state_ != kIceGatheringComplete) {
2905 ice_gathering_state_ = kIceGatheringComplete;
2906 observer_->OnIceGatheringChange(ice_gathering_state_);
2907 }
2908 }
2909 observer_->OnSignalingChange(signaling_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002910}
2911
deadbeefeb459812015-12-15 19:24:43 -08002912void PeerConnection::OnAudioTrackAdded(AudioTrackInterface* track,
2913 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07002914 if (IsClosed()) {
2915 return;
2916 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002917 AddAudioTrack(track, stream);
2918 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08002919}
2920
deadbeefeb459812015-12-15 19:24:43 -08002921void PeerConnection::OnAudioTrackRemoved(AudioTrackInterface* track,
2922 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07002923 if (IsClosed()) {
2924 return;
2925 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002926 RemoveAudioTrack(track, stream);
2927 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08002928}
2929
2930void PeerConnection::OnVideoTrackAdded(VideoTrackInterface* track,
2931 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07002932 if (IsClosed()) {
2933 return;
2934 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002935 AddVideoTrack(track, stream);
2936 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08002937}
2938
2939void PeerConnection::OnVideoTrackRemoved(VideoTrackInterface* track,
2940 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07002941 if (IsClosed()) {
2942 return;
2943 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002944 RemoveVideoTrack(track, stream);
2945 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08002946}
2947
Henrik Boström31638672017-11-23 17:48:32 +01002948void PeerConnection::PostSetSessionDescriptionSuccess(
2949 SetSessionDescriptionObserver* observer) {
2950 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
2951 signaling_thread()->Post(RTC_FROM_HERE, this,
2952 MSG_SET_SESSIONDESCRIPTION_SUCCESS, msg);
2953}
2954
deadbeefab9b2d12015-10-14 11:33:11 -07002955void PeerConnection::PostSetSessionDescriptionFailure(
2956 SetSessionDescriptionObserver* observer,
2957 const std::string& error) {
2958 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
2959 msg->error = error;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07002960 signaling_thread()->Post(RTC_FROM_HERE, this,
2961 MSG_SET_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07002962}
2963
2964void PeerConnection::PostCreateSessionDescriptionFailure(
2965 CreateSessionDescriptionObserver* observer,
2966 const std::string& error) {
2967 CreateSessionDescriptionMsg* msg = new CreateSessionDescriptionMsg(observer);
2968 msg->error = error;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07002969 signaling_thread()->Post(RTC_FROM_HERE, this,
2970 MSG_CREATE_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07002971}
2972
zhihuang1c378ed2017-08-17 14:10:50 -07002973void PeerConnection::GetOptionsForOffer(
Steve Antondcc3c022017-12-22 16:02:54 -08002974 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
deadbeefab9b2d12015-10-14 11:33:11 -07002975 cricket::MediaSessionOptions* session_options) {
Steve Antondcc3c022017-12-22 16:02:54 -08002976 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
zhihuang1c378ed2017-08-17 14:10:50 -07002977
Steve Antondcc3c022017-12-22 16:02:54 -08002978 if (IsUnifiedPlan()) {
2979 GetOptionsForUnifiedPlanOffer(offer_answer_options, session_options);
2980 } else {
2981 GetOptionsForPlanBOffer(offer_answer_options, session_options);
2982 }
2983
Steve Antonfa2260d2017-12-28 16:38:23 -08002984 // Intentionally unset the data channel type for RTP data channel with the
2985 // second condition. Otherwise the RTP data channels would be successfully
2986 // negotiated by default and the unit tests in WebRtcDataBrowserTest will fail
2987 // when building with chromium. We want to leave RTP data channels broken, so
2988 // people won't try to use them.
2989 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
2990 session_options->data_channel_type = data_channel_type();
2991 }
2992
Steve Antondcc3c022017-12-22 16:02:54 -08002993 // Apply ICE restart flag and renomination flag.
2994 for (auto& options : session_options->media_description_options) {
2995 options.transport_options.ice_restart = offer_answer_options.ice_restart;
2996 options.transport_options.enable_ice_renomination =
2997 configuration_.enable_ice_renomination;
2998 }
2999
3000 session_options->rtcp_cname = rtcp_cname_;
3001 session_options->crypto_options = factory_->options().crypto_options;
3002}
3003
3004void PeerConnection::GetOptionsForPlanBOffer(
3005 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
3006 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07003007 // Figure out transceiver directional preferences.
3008 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
3009 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
3010
3011 // By default, generate sendrecv/recvonly m= sections.
3012 bool recv_audio = true;
3013 bool recv_video = true;
3014
3015 // By default, only offer a new m= section if we have media to send with it.
3016 bool offer_new_audio_description = send_audio;
3017 bool offer_new_video_description = send_video;
3018 bool offer_new_data_description = HasDataChannels();
3019
3020 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-22 16:02:54 -08003021 if (offer_answer_options.offer_to_receive_audio !=
3022 RTCOfferAnswerOptions::kUndefined) {
3023 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003024 offer_new_audio_description =
Steve Antondcc3c022017-12-22 16:02:54 -08003025 offer_new_audio_description ||
3026 (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003027 }
Steve Antondcc3c022017-12-22 16:02:54 -08003028 if (offer_answer_options.offer_to_receive_video !=
3029 RTCOfferAnswerOptions::kUndefined) {
3030 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003031 offer_new_video_description =
Steve Antondcc3c022017-12-22 16:02:54 -08003032 offer_new_video_description ||
3033 (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003034 }
3035
3036 rtc::Optional<size_t> audio_index;
3037 rtc::Optional<size_t> video_index;
3038 rtc::Optional<size_t> data_index;
3039 // If a current description exists, generate m= sections in the same order,
3040 // using the first audio/video/data section that appears and rejecting
3041 // extraneous ones.
Steve Anton75737c02017-11-06 10:37:17 -08003042 if (local_description()) {
zhihuang1c378ed2017-08-17 14:10:50 -07003043 GenerateMediaDescriptionOptions(
Steve Anton75737c02017-11-06 10:37:17 -08003044 local_description(),
Steve Anton1d03a752017-11-27 14:30:09 -08003045 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
3046 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
3047 &audio_index, &video_index, &data_index, session_options);
deadbeefab9b2d12015-10-14 11:33:11 -07003048 }
3049
zhihuang1c378ed2017-08-17 14:10:50 -07003050 // Add audio/video/data m= sections to the end if needed.
3051 if (!audio_index && offer_new_audio_description) {
3052 session_options->media_description_options.push_back(
3053 cricket::MediaDescriptionOptions(
3054 cricket::MEDIA_TYPE_AUDIO, cricket::CN_AUDIO,
Steve Anton1d03a752017-11-27 14:30:09 -08003055 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
3056 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003057 audio_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07003058 }
zhihuang1c378ed2017-08-17 14:10:50 -07003059 if (!video_index && offer_new_video_description) {
3060 session_options->media_description_options.push_back(
3061 cricket::MediaDescriptionOptions(
3062 cricket::MEDIA_TYPE_VIDEO, cricket::CN_VIDEO,
Steve Anton1d03a752017-11-27 14:30:09 -08003063 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
3064 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003065 video_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07003066 }
zhihuang1c378ed2017-08-17 14:10:50 -07003067 if (!data_index && offer_new_data_description) {
3068 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08003069 GetMediaDescriptionOptionsForActiveData(cricket::CN_DATA));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003070 data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07003071 }
3072
3073 cricket::MediaDescriptionOptions* audio_media_description_options =
3074 !audio_index ? nullptr
3075 : &session_options->media_description_options[*audio_index];
3076 cricket::MediaDescriptionOptions* video_media_description_options =
3077 !video_index ? nullptr
3078 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 14:10:50 -07003079
Steve Anton4171afb2017-11-20 10:20:22 -08003080 AddRtpSenderOptions(GetSendersInternal(), audio_media_description_options,
zhihuang1c378ed2017-08-17 14:10:50 -07003081 video_media_description_options);
Steve Antondcc3c022017-12-22 16:02:54 -08003082}
3083
3084// Find a new MID that is not already in |used_mids|, then add it to |used_mids|
3085// and return a reference to it.
3086// Generated MIDs should be no more than 3 bytes long to take up less space in
3087// the RTP packet.
3088static const std::string& AllocateMid(std::set<std::string>* used_mids) {
3089 RTC_DCHECK(used_mids);
3090 // We're boring: just generate MIDs 0, 1, 2, ...
3091 size_t i = 0;
3092 std::set<std::string>::iterator it;
3093 bool inserted;
3094 do {
3095 std::string mid = rtc::ToString(i++);
3096 auto insert_result = used_mids->insert(mid);
3097 it = insert_result.first;
3098 inserted = insert_result.second;
3099 } while (!inserted);
3100 return *it;
3101}
3102
3103static cricket::MediaDescriptionOptions
3104GetMediaDescriptionOptionsForTransceiver(
3105 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3106 transceiver,
3107 const std::string& mid) {
3108 cricket::MediaDescriptionOptions media_description_options(
3109 transceiver->internal()->media_type(), mid, transceiver->direction(),
3110 transceiver->stopped());
3111 cricket::SenderOptions sender_options;
3112 sender_options.track_id = transceiver->sender()->id();
3113 sender_options.stream_ids = transceiver->sender()->stream_ids();
3114 // TODO(bugs.webrtc.org/7600): Set num_sim_layers to the number of encodings
3115 // set in the RTP parameters when the transceiver was added.
3116 sender_options.num_sim_layers = 1;
3117 media_description_options.sender_options.push_back(sender_options);
3118 return media_description_options;
3119}
3120
3121void PeerConnection::GetOptionsForUnifiedPlanOffer(
3122 const RTCOfferAnswerOptions& offer_answer_options,
3123 cricket::MediaSessionOptions* session_options) {
3124 // Rules for generating an offer are dictated by JSEP sections 5.2.1 (Initial
3125 // Offers) and 5.2.2 (Subsequent Offers).
3126 RTC_DCHECK_EQ(session_options->media_description_options.size(), 0);
3127 const ContentInfos& local_contents =
3128 (local_description() ? local_description()->description()->contents()
3129 : ContentInfos());
3130 const ContentInfos& remote_contents =
3131 (remote_description() ? remote_description()->description()->contents()
3132 : ContentInfos());
3133 // The mline indices that can be recycled. New transceivers should reuse these
3134 // slots first.
3135 std::queue<size_t> recycleable_mline_indices;
3136 // Track the MIDs used in previous offer/answer exchanges and the current
3137 // offer so that new, unique MIDs are generated.
3138 std::set<std::string> used_mids = seen_mids_;
3139 // First, go through each media section that exists in either the local or
3140 // remote description and generate a media section in this offer for the
3141 // associated transceiver. If a media section can be recycled, generate a
3142 // default, rejected media section here that can be later overwritten.
3143 for (size_t i = 0;
3144 i < std::max(local_contents.size(), remote_contents.size()); ++i) {
3145 // Either |local_content| or |remote_content| is non-null.
3146 const ContentInfo* local_content =
3147 (i < local_contents.size() ? &local_contents[i] : nullptr);
3148 const ContentInfo* remote_content =
3149 (i < remote_contents.size() ? &remote_contents[i] : nullptr);
3150 bool had_been_rejected = (local_content && local_content->rejected) ||
3151 (remote_content && remote_content->rejected);
3152 const std::string& mid =
3153 (local_content ? local_content->name : remote_content->name);
3154 cricket::MediaType media_type =
3155 (local_content ? local_content->media_description()->type()
3156 : remote_content->media_description()->type());
3157 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
3158 media_type == cricket::MEDIA_TYPE_VIDEO) {
3159 auto transceiver = GetAssociatedTransceiver(mid);
3160 RTC_CHECK(transceiver);
3161 // A media section is considered eligible for recycling if it is marked as
3162 // rejected in either the local or remote description.
3163 if (had_been_rejected) {
3164 session_options->media_description_options.push_back(
3165 cricket::MediaDescriptionOptions(
3166 transceiver->internal()->media_type(), mid,
3167 RtpTransceiverDirection::kInactive,
3168 /*stopped=*/true));
3169 recycleable_mline_indices.push(i);
3170 } else {
3171 session_options->media_description_options.push_back(
3172 GetMediaDescriptionOptionsForTransceiver(transceiver, mid));
3173 // CreateOffer shouldn't really cause any state changes in
3174 // PeerConnection, but we need a way to match new transceivers to new
3175 // media sections in SetLocalDescription and JSEP specifies this is done
3176 // by recording the index of the media section generated for the
3177 // transceiver in the offer.
3178 transceiver->internal()->set_mline_index(i);
3179 }
3180 } else {
3181 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antonfa2260d2017-12-28 16:38:23 -08003182 RTC_CHECK(GetDataMid());
3183 if (had_been_rejected || mid != *GetDataMid()) {
3184 session_options->media_description_options.push_back(
3185 GetMediaDescriptionOptionsForRejectedData(mid));
3186 } else {
3187 session_options->media_description_options.push_back(
3188 GetMediaDescriptionOptionsForActiveData(mid));
3189 }
Steve Antondcc3c022017-12-22 16:02:54 -08003190 }
3191 }
3192 // Next, look for transceivers that are newly added (that is, are not stopped
3193 // and not associated). Reuse media sections marked as recyclable first,
3194 // otherwise append to the end of the offer. New media sections should be
3195 // added in the order they were added to the PeerConnection.
3196 for (auto transceiver : transceivers_) {
3197 if (transceiver->mid() || transceiver->stopped()) {
3198 continue;
3199 }
3200 size_t mline_index;
3201 if (!recycleable_mline_indices.empty()) {
3202 mline_index = recycleable_mline_indices.front();
3203 recycleable_mline_indices.pop();
3204 session_options->media_description_options[mline_index] =
3205 GetMediaDescriptionOptionsForTransceiver(transceiver,
3206 AllocateMid(&used_mids));
3207 } else {
3208 mline_index = session_options->media_description_options.size();
3209 session_options->media_description_options.push_back(
3210 GetMediaDescriptionOptionsForTransceiver(transceiver,
3211 AllocateMid(&used_mids)));
3212 }
3213 // See comment above for why CreateOffer changes the transceiver's state.
3214 transceiver->internal()->set_mline_index(mline_index);
3215 }
Steve Antonfa2260d2017-12-28 16:38:23 -08003216 // Lastly, add a m-section if we have local data channels and an m section
3217 // does not already exist.
3218 if (!GetDataMid() && HasDataChannels()) {
3219 session_options->media_description_options.push_back(
3220 GetMediaDescriptionOptionsForActiveData(AllocateMid(&used_mids)));
3221 }
Steve Antondcc3c022017-12-22 16:02:54 -08003222}
3223
3224void PeerConnection::GetOptionsForAnswer(
3225 const RTCOfferAnswerOptions& offer_answer_options,
3226 cricket::MediaSessionOptions* session_options) {
3227 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
3228
3229 if (IsUnifiedPlan()) {
3230 GetOptionsForUnifiedPlanAnswer(offer_answer_options, session_options);
3231 } else {
3232 GetOptionsForPlanBAnswer(offer_answer_options, session_options);
3233 }
3234
Steve Antonfa2260d2017-12-28 16:38:23 -08003235 // Intentionally unset the data channel type for RTP data channel. Otherwise
3236 // the RTP data channels would be successfully negotiated by default and the
3237 // unit tests in WebRtcDataBrowserTest will fail when building with chromium.
3238 // We want to leave RTP data channels broken, so people won't try to use them.
3239 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
3240 session_options->data_channel_type = data_channel_type();
3241 }
3242
Steve Antondcc3c022017-12-22 16:02:54 -08003243 // Apply ICE renomination flag.
3244 for (auto& options : session_options->media_description_options) {
3245 options.transport_options.enable_ice_renomination =
3246 configuration_.enable_ice_renomination;
3247 }
zhihuang8f65cdf2016-05-06 18:40:30 -07003248
3249 session_options->rtcp_cname = rtcp_cname_;
jbauchcb560652016-08-04 05:20:32 -07003250 session_options->crypto_options = factory_->options().crypto_options;
deadbeefab9b2d12015-10-14 11:33:11 -07003251}
3252
Steve Antondcc3c022017-12-22 16:02:54 -08003253void PeerConnection::GetOptionsForPlanBAnswer(
3254 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07003255 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07003256 // Figure out transceiver directional preferences.
3257 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
3258 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
3259
3260 // By default, generate sendrecv/recvonly m= sections. The direction is also
3261 // restricted by the direction in the offer.
3262 bool recv_audio = true;
3263 bool recv_video = true;
3264
3265 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-22 16:02:54 -08003266 if (offer_answer_options.offer_to_receive_audio !=
3267 RTCOfferAnswerOptions::kUndefined) {
3268 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
deadbeef0ed85b22016-02-23 17:24:52 -08003269 }
Steve Antondcc3c022017-12-22 16:02:54 -08003270 if (offer_answer_options.offer_to_receive_video !=
3271 RTCOfferAnswerOptions::kUndefined) {
3272 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003273 }
3274
3275 rtc::Optional<size_t> audio_index;
3276 rtc::Optional<size_t> video_index;
3277 rtc::Optional<size_t> data_index;
Steve Anton75737c02017-11-06 10:37:17 -08003278 if (remote_description()) {
zhihuang141aacb2017-08-29 13:23:53 -07003279 // The pending remote description should be an offer.
Steve Antona3a92c22017-12-07 10:27:41 -08003280 RTC_DCHECK(remote_description()->GetType() == SdpType::kOffer);
zhihuang141aacb2017-08-29 13:23:53 -07003281 // Generate m= sections that match those in the offer.
3282 // Note that mediasession.cc will handle intersection our preferred
3283 // direction with the offered direction.
3284 GenerateMediaDescriptionOptions(
Steve Anton75737c02017-11-06 10:37:17 -08003285 remote_description(),
Steve Anton1d03a752017-11-27 14:30:09 -08003286 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
3287 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
3288 &audio_index, &video_index, &data_index, session_options);
zhihuang141aacb2017-08-29 13:23:53 -07003289 }
zhihuang1c378ed2017-08-17 14:10:50 -07003290
3291 cricket::MediaDescriptionOptions* audio_media_description_options =
3292 !audio_index ? nullptr
3293 : &session_options->media_description_options[*audio_index];
3294 cricket::MediaDescriptionOptions* video_media_description_options =
3295 !video_index ? nullptr
3296 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 14:10:50 -07003297
Steve Anton4171afb2017-11-20 10:20:22 -08003298 AddRtpSenderOptions(GetSendersInternal(), audio_media_description_options,
zhihuang1c378ed2017-08-17 14:10:50 -07003299 video_media_description_options);
Steve Antondcc3c022017-12-22 16:02:54 -08003300}
zhihuangaf388472016-11-02 16:49:48 -07003301
Steve Antondcc3c022017-12-22 16:02:54 -08003302void PeerConnection::GetOptionsForUnifiedPlanAnswer(
3303 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
3304 cricket::MediaSessionOptions* session_options) {
3305 // Rules for generating an answer are dictated by JSEP sections 5.3.1 (Initial
3306 // Answers) and 5.3.2 (Subsequent Answers).
3307 RTC_DCHECK(remote_description());
3308 RTC_DCHECK(remote_description()->GetType() == SdpType::kOffer);
3309 for (const ContentInfo& content :
3310 remote_description()->description()->contents()) {
3311 cricket::MediaType media_type = content.media_description()->type();
3312 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
3313 media_type == cricket::MEDIA_TYPE_VIDEO) {
3314 auto transceiver = GetAssociatedTransceiver(content.name);
3315 RTC_CHECK(transceiver);
3316 session_options->media_description_options.push_back(
3317 GetMediaDescriptionOptionsForTransceiver(transceiver, content.name));
3318 } else {
3319 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antonfa2260d2017-12-28 16:38:23 -08003320 RTC_CHECK(GetDataMid());
3321 // Always reject a data section if it has already been rejected.
3322 // Additionally, reject all data sections except for the first one.
3323 if (content.rejected || content.name != *GetDataMid()) {
3324 session_options->media_description_options.push_back(
3325 GetMediaDescriptionOptionsForRejectedData(content.name));
3326 } else {
3327 session_options->media_description_options.push_back(
3328 GetMediaDescriptionOptionsForActiveData(content.name));
3329 }
Steve Antondcc3c022017-12-22 16:02:54 -08003330 }
3331 }
htaa2a49d92016-03-04 02:51:39 -08003332}
3333
zhihuang1c378ed2017-08-17 14:10:50 -07003334void PeerConnection::GenerateMediaDescriptionOptions(
3335 const SessionDescriptionInterface* session_desc,
Steve Anton1d03a752017-11-27 14:30:09 -08003336 RtpTransceiverDirection audio_direction,
3337 RtpTransceiverDirection video_direction,
zhihuang1c378ed2017-08-17 14:10:50 -07003338 rtc::Optional<size_t>* audio_index,
3339 rtc::Optional<size_t>* video_index,
3340 rtc::Optional<size_t>* data_index,
htaa2a49d92016-03-04 02:51:39 -08003341 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07003342 for (const cricket::ContentInfo& content :
3343 session_desc->description()->contents()) {
3344 if (IsAudioContent(&content)) {
3345 // If we already have an audio m= section, reject this extra one.
3346 if (*audio_index) {
3347 session_options->media_description_options.push_back(
3348 cricket::MediaDescriptionOptions(
3349 cricket::MEDIA_TYPE_AUDIO, content.name,
Steve Anton1d03a752017-11-27 14:30:09 -08003350 RtpTransceiverDirection::kInactive, true));
zhihuang1c378ed2017-08-17 14:10:50 -07003351 } else {
3352 session_options->media_description_options.push_back(
3353 cricket::MediaDescriptionOptions(
3354 cricket::MEDIA_TYPE_AUDIO, content.name, audio_direction,
Steve Anton1d03a752017-11-27 14:30:09 -08003355 audio_direction == RtpTransceiverDirection::kInactive));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003356 *audio_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07003357 }
3358 } else if (IsVideoContent(&content)) {
3359 // If we already have an video m= section, reject this extra one.
3360 if (*video_index) {
3361 session_options->media_description_options.push_back(
3362 cricket::MediaDescriptionOptions(
3363 cricket::MEDIA_TYPE_VIDEO, content.name,
Steve Anton1d03a752017-11-27 14:30:09 -08003364 RtpTransceiverDirection::kInactive, true));
zhihuang1c378ed2017-08-17 14:10:50 -07003365 } else {
3366 session_options->media_description_options.push_back(
3367 cricket::MediaDescriptionOptions(
3368 cricket::MEDIA_TYPE_VIDEO, content.name, video_direction,
Steve Anton1d03a752017-11-27 14:30:09 -08003369 video_direction == RtpTransceiverDirection::kInactive));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003370 *video_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07003371 }
3372 } else {
3373 RTC_DCHECK(IsDataContent(&content));
3374 // If we already have an data m= section, reject this extra one.
3375 if (*data_index) {
3376 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08003377 GetMediaDescriptionOptionsForRejectedData(content.name));
zhihuang1c378ed2017-08-17 14:10:50 -07003378 } else {
3379 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08003380 GetMediaDescriptionOptionsForActiveData(content.name));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003381 *data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07003382 }
3383 }
htaa2a49d92016-03-04 02:51:39 -08003384 }
deadbeefab9b2d12015-10-14 11:33:11 -07003385}
3386
Steve Antonfa2260d2017-12-28 16:38:23 -08003387cricket::MediaDescriptionOptions
3388PeerConnection::GetMediaDescriptionOptionsForActiveData(
3389 const std::string& mid) const {
3390 // Direction for data sections is meaningless, but legacy endpoints might
3391 // expect sendrecv.
3392 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
3393 RtpTransceiverDirection::kSendRecv,
3394 /*stopped=*/false);
3395 AddRtpDataChannelOptions(rtp_data_channels_, &options);
3396 return options;
3397}
3398
3399cricket::MediaDescriptionOptions
3400PeerConnection::GetMediaDescriptionOptionsForRejectedData(
3401 const std::string& mid) const {
3402 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
3403 RtpTransceiverDirection::kInactive,
3404 /*stopped=*/true);
3405 AddRtpDataChannelOptions(rtp_data_channels_, &options);
3406 return options;
3407}
3408
3409rtc::Optional<std::string> PeerConnection::GetDataMid() const {
3410 switch (data_channel_type_) {
3411 case cricket::DCT_RTP:
3412 if (!rtp_data_channel_) {
3413 return rtc::nullopt;
3414 }
3415 return rtp_data_channel_->content_name();
3416 case cricket::DCT_SCTP:
3417 return sctp_content_name_;
3418 default:
3419 return rtc::nullopt;
3420 }
3421}
3422
Steve Anton4171afb2017-11-20 10:20:22 -08003423void PeerConnection::RemoveSenders(cricket::MediaType media_type) {
3424 UpdateLocalSenders(std::vector<cricket::StreamParams>(), media_type);
3425 UpdateRemoteSendersList(std::vector<cricket::StreamParams>(), false,
deadbeefbda7e0b2015-12-08 17:13:40 -08003426 media_type, nullptr);
deadbeeffaac4972015-11-12 15:33:07 -08003427}
3428
Steve Anton4171afb2017-11-20 10:20:22 -08003429void PeerConnection::UpdateRemoteSendersList(
deadbeefab9b2d12015-10-14 11:33:11 -07003430 const cricket::StreamParamsVec& streams,
Steve Anton4171afb2017-11-20 10:20:22 -08003431 bool default_sender_needed,
deadbeefab9b2d12015-10-14 11:33:11 -07003432 cricket::MediaType media_type,
3433 StreamCollection* new_streams) {
Steve Anton4171afb2017-11-20 10:20:22 -08003434 std::vector<RtpSenderInfo>* current_senders =
3435 GetRemoteSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07003436
Steve Anton4171afb2017-11-20 10:20:22 -08003437 // Find removed senders. I.e., senders where the sender id or ssrc don't match
deadbeeffac06552015-11-25 11:26:01 -08003438 // the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08003439 for (auto sender_it = current_senders->begin();
3440 sender_it != current_senders->end();
3441 /* incremented manually */) {
3442 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07003443 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08003444 cricket::GetStreamBySsrc(streams, info.first_ssrc);
3445 bool sender_exists = params && params->id == info.sender_id;
deadbeefbda7e0b2015-12-08 17:13:40 -08003446 // If this is a default track, and we still need it, don't remove it.
Steve Anton4171afb2017-11-20 10:20:22 -08003447 if ((info.stream_label == kDefaultStreamLabel && default_sender_needed) ||
3448 sender_exists) {
3449 ++sender_it;
deadbeefbda7e0b2015-12-08 17:13:40 -08003450 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08003451 OnRemoteSenderRemoved(info, media_type);
3452 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07003453 }
3454 }
3455
Steve Anton4171afb2017-11-20 10:20:22 -08003456 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07003457 for (const cricket::StreamParams& params : streams) {
3458 // The sync_label is the MediaStream label and the |stream.id| is the
Steve Anton4171afb2017-11-20 10:20:22 -08003459 // sender id.
deadbeefab9b2d12015-10-14 11:33:11 -07003460 const std::string& stream_label = params.sync_label;
Steve Anton4171afb2017-11-20 10:20:22 -08003461 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07003462 uint32_t ssrc = params.first_ssrc();
3463
3464 rtc::scoped_refptr<MediaStreamInterface> stream =
3465 remote_streams_->find(stream_label);
3466 if (!stream) {
3467 // This is a new MediaStream. Create a new remote MediaStream.
perkjd61bf802016-03-24 03:16:19 -07003468 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
3469 MediaStream::Create(stream_label));
deadbeefab9b2d12015-10-14 11:33:11 -07003470 remote_streams_->AddStream(stream);
3471 new_streams->AddStream(stream);
3472 }
3473
Steve Anton4171afb2017-11-20 10:20:22 -08003474 const RtpSenderInfo* sender_info =
3475 FindSenderInfo(*current_senders, stream_label, sender_id);
3476 if (!sender_info) {
3477 current_senders->push_back(RtpSenderInfo(stream_label, sender_id, ssrc));
3478 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07003479 }
3480 }
deadbeefbda7e0b2015-12-08 17:13:40 -08003481
Steve Anton4171afb2017-11-20 10:20:22 -08003482 // Add default sender if necessary.
3483 if (default_sender_needed) {
deadbeefbda7e0b2015-12-08 17:13:40 -08003484 rtc::scoped_refptr<MediaStreamInterface> default_stream =
3485 remote_streams_->find(kDefaultStreamLabel);
3486 if (!default_stream) {
3487 // Create the new default MediaStream.
perkjd61bf802016-03-24 03:16:19 -07003488 default_stream = MediaStreamProxy::Create(
3489 rtc::Thread::Current(), MediaStream::Create(kDefaultStreamLabel));
deadbeefbda7e0b2015-12-08 17:13:40 -08003490 remote_streams_->AddStream(default_stream);
3491 new_streams->AddStream(default_stream);
3492 }
Steve Anton4171afb2017-11-20 10:20:22 -08003493 std::string default_sender_id = (media_type == cricket::MEDIA_TYPE_AUDIO)
3494 ? kDefaultAudioSenderId
3495 : kDefaultVideoSenderId;
3496 const RtpSenderInfo* default_sender_info = FindSenderInfo(
3497 *current_senders, kDefaultStreamLabel, default_sender_id);
3498 if (!default_sender_info) {
3499 current_senders->push_back(
3500 RtpSenderInfo(kDefaultStreamLabel, default_sender_id, 0));
3501 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefbda7e0b2015-12-08 17:13:40 -08003502 }
3503 }
deadbeefab9b2d12015-10-14 11:33:11 -07003504}
3505
Steve Anton4171afb2017-11-20 10:20:22 -08003506void PeerConnection::OnRemoteSenderAdded(const RtpSenderInfo& sender_info,
3507 cricket::MediaType media_type) {
3508 MediaStreamInterface* stream =
3509 remote_streams_->find(sender_info.stream_label);
deadbeefab9b2d12015-10-14 11:33:11 -07003510
3511 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 10:20:22 -08003512 CreateAudioReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07003513 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 10:20:22 -08003514 CreateVideoReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07003515 } else {
nisseeb4ca4e2017-01-12 02:24:27 -08003516 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07003517 }
3518}
3519
Steve Anton4171afb2017-11-20 10:20:22 -08003520void PeerConnection::OnRemoteSenderRemoved(const RtpSenderInfo& sender_info,
3521 cricket::MediaType media_type) {
3522 MediaStreamInterface* stream =
3523 remote_streams_->find(sender_info.stream_label);
deadbeefab9b2d12015-10-14 11:33:11 -07003524
Henrik Boström933d8b02017-10-10 10:05:16 -07003525 rtc::scoped_refptr<RtpReceiverInterface> receiver;
deadbeefab9b2d12015-10-14 11:33:11 -07003526 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
perkjd61bf802016-03-24 03:16:19 -07003527 // When the MediaEngine audio channel is destroyed, the RemoteAudioSource
3528 // will be notified which will end the AudioRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08003529 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07003530 rtc::scoped_refptr<AudioTrackInterface> audio_track =
Steve Anton4171afb2017-11-20 10:20:22 -08003531 stream->FindAudioTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07003532 if (audio_track) {
deadbeefab9b2d12015-10-14 11:33:11 -07003533 stream->RemoveTrack(audio_track);
deadbeefab9b2d12015-10-14 11:33:11 -07003534 }
3535 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
perkjd61bf802016-03-24 03:16:19 -07003536 // Stopping or destroying a VideoRtpReceiver will end the
3537 // VideoRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08003538 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07003539 rtc::scoped_refptr<VideoTrackInterface> video_track =
Steve Anton4171afb2017-11-20 10:20:22 -08003540 stream->FindVideoTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07003541 if (video_track) {
perkjd61bf802016-03-24 03:16:19 -07003542 // There's no guarantee the track is still available, e.g. the track may
3543 // have been removed from the stream by an application.
deadbeefab9b2d12015-10-14 11:33:11 -07003544 stream->RemoveTrack(video_track);
deadbeefab9b2d12015-10-14 11:33:11 -07003545 }
3546 } else {
nisseede5da42017-01-12 05:15:36 -08003547 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07003548 }
Henrik Boström933d8b02017-10-10 10:05:16 -07003549 if (receiver) {
3550 observer_->OnRemoveTrack(receiver);
3551 }
deadbeefab9b2d12015-10-14 11:33:11 -07003552}
3553
3554void PeerConnection::UpdateEndedRemoteMediaStreams() {
3555 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams_to_remove;
3556 for (size_t i = 0; i < remote_streams_->count(); ++i) {
3557 MediaStreamInterface* stream = remote_streams_->at(i);
3558 if (stream->GetAudioTracks().empty() && stream->GetVideoTracks().empty()) {
3559 streams_to_remove.push_back(stream);
3560 }
3561 }
3562
Taylor Brandstetter98cde262016-05-31 13:02:21 -07003563 for (auto& stream : streams_to_remove) {
deadbeefab9b2d12015-10-14 11:33:11 -07003564 remote_streams_->RemoveStream(stream);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07003565 observer_->OnRemoveStream(std::move(stream));
deadbeefab9b2d12015-10-14 11:33:11 -07003566 }
3567}
3568
Steve Anton4171afb2017-11-20 10:20:22 -08003569void PeerConnection::UpdateLocalSenders(
deadbeefab9b2d12015-10-14 11:33:11 -07003570 const std::vector<cricket::StreamParams>& streams,
3571 cricket::MediaType media_type) {
Steve Anton4171afb2017-11-20 10:20:22 -08003572 std::vector<RtpSenderInfo>* current_senders = GetLocalSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07003573
3574 // Find removed tracks. I.e., tracks where the track id, stream label or ssrc
3575 // don't match the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08003576 for (auto sender_it = current_senders->begin();
3577 sender_it != current_senders->end();
3578 /* incremented manually */) {
3579 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07003580 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08003581 cricket::GetStreamBySsrc(streams, info.first_ssrc);
3582 if (!params || params->id != info.sender_id ||
deadbeefab9b2d12015-10-14 11:33:11 -07003583 params->sync_label != info.stream_label) {
Steve Anton4171afb2017-11-20 10:20:22 -08003584 OnLocalSenderRemoved(info, media_type);
3585 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07003586 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08003587 ++sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07003588 }
3589 }
3590
Steve Anton4171afb2017-11-20 10:20:22 -08003591 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07003592 for (const cricket::StreamParams& params : streams) {
3593 // The sync_label is the MediaStream label and the |stream.id| is the
Steve Anton4171afb2017-11-20 10:20:22 -08003594 // sender id.
deadbeefab9b2d12015-10-14 11:33:11 -07003595 const std::string& stream_label = params.sync_label;
Steve Anton4171afb2017-11-20 10:20:22 -08003596 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07003597 uint32_t ssrc = params.first_ssrc();
Steve Anton4171afb2017-11-20 10:20:22 -08003598 const RtpSenderInfo* sender_info =
3599 FindSenderInfo(*current_senders, stream_label, sender_id);
3600 if (!sender_info) {
3601 current_senders->push_back(RtpSenderInfo(stream_label, sender_id, ssrc));
3602 OnLocalSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07003603 }
3604 }
3605}
3606
Steve Anton4171afb2017-11-20 10:20:22 -08003607void PeerConnection::OnLocalSenderAdded(const RtpSenderInfo& sender_info,
3608 cricket::MediaType media_type) {
3609 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08003610 if (!sender) {
Steve Anton4171afb2017-11-20 10:20:22 -08003611 RTC_LOG(LS_WARNING) << "An unknown RtpSender with id "
3612 << sender_info.sender_id
Mirko Bonadei675513b2017-11-09 11:09:25 +01003613 << " has been configured in the local description.";
deadbeefab9b2d12015-10-14 11:33:11 -07003614 return;
3615 }
3616
deadbeeffac06552015-11-25 11:26:01 -08003617 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003618 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
3619 << " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08003620 return;
deadbeefab9b2d12015-10-14 11:33:11 -07003621 }
deadbeeffac06552015-11-25 11:26:01 -08003622
Steve Anton4171afb2017-11-20 10:20:22 -08003623 sender->internal()->set_stream_id(sender_info.stream_label);
3624 sender->internal()->SetSsrc(sender_info.first_ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07003625}
3626
Steve Anton4171afb2017-11-20 10:20:22 -08003627void PeerConnection::OnLocalSenderRemoved(const RtpSenderInfo& sender_info,
3628 cricket::MediaType media_type) {
3629 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08003630 if (!sender) {
3631 // This is the normal case. I.e., RemoveStream has been called and the
deadbeefab9b2d12015-10-14 11:33:11 -07003632 // SessionDescriptions has been renegotiated.
3633 return;
3634 }
deadbeeffac06552015-11-25 11:26:01 -08003635
3636 // A sender has been removed from the SessionDescription but it's still
3637 // associated with the PeerConnection. This only occurs if the SDP doesn't
3638 // match with the calls to CreateSender, AddStream and RemoveStream.
3639 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003640 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
3641 << " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08003642 return;
deadbeefab9b2d12015-10-14 11:33:11 -07003643 }
deadbeeffac06552015-11-25 11:26:01 -08003644
Steve Anton4171afb2017-11-20 10:20:22 -08003645 sender->internal()->SetSsrc(0);
deadbeefab9b2d12015-10-14 11:33:11 -07003646}
3647
3648void PeerConnection::UpdateLocalRtpDataChannels(
3649 const cricket::StreamParamsVec& streams) {
3650 std::vector<std::string> existing_channels;
3651
3652 // Find new and active data channels.
3653 for (const cricket::StreamParams& params : streams) {
3654 // |it->sync_label| is actually the data channel label. The reason is that
3655 // we use the same naming of data channels as we do for
3656 // MediaStreams and Tracks.
3657 // For MediaStreams, the sync_label is the MediaStream label and the
3658 // track label is the same as |streamid|.
3659 const std::string& channel_label = params.sync_label;
3660 auto data_channel_it = rtp_data_channels_.find(channel_label);
nisse7ce109a2017-01-31 00:57:56 -08003661 if (data_channel_it == rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003662 RTC_LOG(LS_ERROR) << "channel label not found";
deadbeefab9b2d12015-10-14 11:33:11 -07003663 continue;
3664 }
3665 // Set the SSRC the data channel should use for sending.
3666 data_channel_it->second->SetSendSsrc(params.first_ssrc());
3667 existing_channels.push_back(data_channel_it->first);
3668 }
3669
3670 UpdateClosingRtpDataChannels(existing_channels, true);
3671}
3672
3673void PeerConnection::UpdateRemoteRtpDataChannels(
3674 const cricket::StreamParamsVec& streams) {
3675 std::vector<std::string> existing_channels;
3676
3677 // Find new and active data channels.
3678 for (const cricket::StreamParams& params : streams) {
3679 // The data channel label is either the mslabel or the SSRC if the mslabel
3680 // does not exist. Ex a=ssrc:444330170 mslabel:test1.
3681 std::string label = params.sync_label.empty()
3682 ? rtc::ToString(params.first_ssrc())
3683 : params.sync_label;
3684 auto data_channel_it = rtp_data_channels_.find(label);
3685 if (data_channel_it == rtp_data_channels_.end()) {
3686 // This is a new data channel.
3687 CreateRemoteRtpDataChannel(label, params.first_ssrc());
3688 } else {
3689 data_channel_it->second->SetReceiveSsrc(params.first_ssrc());
3690 }
3691 existing_channels.push_back(label);
3692 }
3693
3694 UpdateClosingRtpDataChannels(existing_channels, false);
3695}
3696
3697void PeerConnection::UpdateClosingRtpDataChannels(
3698 const std::vector<std::string>& active_channels,
3699 bool is_local_update) {
3700 auto it = rtp_data_channels_.begin();
3701 while (it != rtp_data_channels_.end()) {
3702 DataChannel* data_channel = it->second;
3703 if (std::find(active_channels.begin(), active_channels.end(),
3704 data_channel->label()) != active_channels.end()) {
3705 ++it;
3706 continue;
3707 }
3708
3709 if (is_local_update) {
3710 data_channel->SetSendSsrc(0);
3711 } else {
3712 data_channel->RemotePeerRequestClose();
3713 }
3714
3715 if (data_channel->state() == DataChannel::kClosed) {
3716 rtp_data_channels_.erase(it);
3717 it = rtp_data_channels_.begin();
3718 } else {
3719 ++it;
3720 }
3721 }
3722}
3723
3724void PeerConnection::CreateRemoteRtpDataChannel(const std::string& label,
3725 uint32_t remote_ssrc) {
3726 rtc::scoped_refptr<DataChannel> channel(
3727 InternalCreateDataChannel(label, nullptr));
3728 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003729 RTC_LOG(LS_WARNING) << "Remote peer requested a DataChannel but"
3730 << "CreateDataChannel failed.";
deadbeefab9b2d12015-10-14 11:33:11 -07003731 return;
3732 }
3733 channel->SetReceiveSsrc(remote_ssrc);
deadbeefa601f5c2016-06-06 14:27:39 -07003734 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
3735 DataChannelProxy::Create(signaling_thread(), channel);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07003736 observer_->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07003737}
3738
3739rtc::scoped_refptr<DataChannel> PeerConnection::InternalCreateDataChannel(
3740 const std::string& label,
3741 const InternalDataChannelInit* config) {
3742 if (IsClosed()) {
3743 return nullptr;
3744 }
Steve Anton75737c02017-11-06 10:37:17 -08003745 if (data_channel_type() == cricket::DCT_NONE) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003746 RTC_LOG(LS_ERROR)
deadbeefab9b2d12015-10-14 11:33:11 -07003747 << "InternalCreateDataChannel: Data is not supported in this call.";
3748 return nullptr;
3749 }
3750 InternalDataChannelInit new_config =
3751 config ? (*config) : InternalDataChannelInit();
Steve Anton75737c02017-11-06 10:37:17 -08003752 if (data_channel_type() == cricket::DCT_SCTP) {
deadbeefab9b2d12015-10-14 11:33:11 -07003753 if (new_config.id < 0) {
3754 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08003755 if ((GetSctpSslRole(&role)) &&
deadbeefab9b2d12015-10-14 11:33:11 -07003756 !sid_allocator_.AllocateSid(role, &new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003757 RTC_LOG(LS_ERROR)
3758 << "No id can be allocated for the SCTP data channel.";
deadbeefab9b2d12015-10-14 11:33:11 -07003759 return nullptr;
3760 }
3761 } else if (!sid_allocator_.ReserveSid(new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003762 RTC_LOG(LS_ERROR) << "Failed to create a SCTP data channel "
3763 << "because the id is already in use or out of range.";
deadbeefab9b2d12015-10-14 11:33:11 -07003764 return nullptr;
3765 }
3766 }
3767
Steve Anton75737c02017-11-06 10:37:17 -08003768 rtc::scoped_refptr<DataChannel> channel(
3769 DataChannel::Create(this, data_channel_type(), label, new_config));
deadbeefab9b2d12015-10-14 11:33:11 -07003770 if (!channel) {
3771 sid_allocator_.ReleaseSid(new_config.id);
3772 return nullptr;
3773 }
3774
3775 if (channel->data_channel_type() == cricket::DCT_RTP) {
3776 if (rtp_data_channels_.find(channel->label()) != rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003777 RTC_LOG(LS_ERROR) << "DataChannel with label " << channel->label()
3778 << " already exists.";
deadbeefab9b2d12015-10-14 11:33:11 -07003779 return nullptr;
3780 }
3781 rtp_data_channels_[channel->label()] = channel;
3782 } else {
3783 RTC_DCHECK(channel->data_channel_type() == cricket::DCT_SCTP);
3784 sctp_data_channels_.push_back(channel);
3785 channel->SignalClosed.connect(this,
3786 &PeerConnection::OnSctpDataChannelClosed);
3787 }
3788
hbos82ebe022016-11-14 01:41:09 -08003789 SignalDataChannelCreated(channel.get());
deadbeefab9b2d12015-10-14 11:33:11 -07003790 return channel;
3791}
3792
3793bool PeerConnection::HasDataChannels() const {
3794 return !rtp_data_channels_.empty() || !sctp_data_channels_.empty();
3795}
3796
3797void PeerConnection::AllocateSctpSids(rtc::SSLRole role) {
3798 for (const auto& channel : sctp_data_channels_) {
3799 if (channel->id() < 0) {
3800 int sid;
3801 if (!sid_allocator_.AllocateSid(role, &sid)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003802 RTC_LOG(LS_ERROR) << "Failed to allocate SCTP sid.";
deadbeefab9b2d12015-10-14 11:33:11 -07003803 continue;
3804 }
3805 channel->SetSctpSid(sid);
3806 }
3807 }
3808}
3809
3810void PeerConnection::OnSctpDataChannelClosed(DataChannel* channel) {
deadbeefbd292462015-12-14 18:15:29 -08003811 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeefab9b2d12015-10-14 11:33:11 -07003812 for (auto it = sctp_data_channels_.begin(); it != sctp_data_channels_.end();
3813 ++it) {
3814 if (it->get() == channel) {
3815 if (channel->id() >= 0) {
3816 sid_allocator_.ReleaseSid(channel->id());
3817 }
deadbeefbd292462015-12-14 18:15:29 -08003818 // Since this method is triggered by a signal from the DataChannel,
3819 // we can't free it directly here; we need to free it asynchronously.
3820 sctp_data_channels_to_free_.push_back(*it);
deadbeefab9b2d12015-10-14 11:33:11 -07003821 sctp_data_channels_.erase(it);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07003822 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_FREE_DATACHANNELS,
3823 nullptr);
deadbeefab9b2d12015-10-14 11:33:11 -07003824 return;
3825 }
3826 }
3827}
3828
deadbeefab9b2d12015-10-14 11:33:11 -07003829void PeerConnection::OnDataChannelDestroyed() {
3830 // Use a temporary copy of the RTP/SCTP DataChannel list because the
3831 // DataChannel may callback to us and try to modify the list.
3832 std::map<std::string, rtc::scoped_refptr<DataChannel>> temp_rtp_dcs;
3833 temp_rtp_dcs.swap(rtp_data_channels_);
3834 for (const auto& kv : temp_rtp_dcs) {
3835 kv.second->OnTransportChannelDestroyed();
3836 }
3837
3838 std::vector<rtc::scoped_refptr<DataChannel>> temp_sctp_dcs;
3839 temp_sctp_dcs.swap(sctp_data_channels_);
3840 for (const auto& channel : temp_sctp_dcs) {
3841 channel->OnTransportChannelDestroyed();
3842 }
3843}
3844
3845void PeerConnection::OnDataChannelOpenMessage(
3846 const std::string& label,
3847 const InternalDataChannelInit& config) {
3848 rtc::scoped_refptr<DataChannel> channel(
3849 InternalCreateDataChannel(label, &config));
3850 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003851 RTC_LOG(LS_ERROR) << "Failed to create DataChannel from the OPEN message.";
deadbeefab9b2d12015-10-14 11:33:11 -07003852 return;
3853 }
3854
deadbeefa601f5c2016-06-06 14:27:39 -07003855 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
3856 DataChannelProxy::Create(signaling_thread(), channel);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07003857 observer_->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07003858}
3859
Steve Anton4171afb2017-11-20 10:20:22 -08003860rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3861PeerConnection::GetAudioTransceiver() const {
3862 // This method only works with Plan B SDP, where there is a single
3863 // audio/video transceiver.
3864 RTC_DCHECK(!IsUnifiedPlan());
3865 for (auto transceiver : transceivers_) {
3866 if (transceiver->internal()->media_type() == cricket::MEDIA_TYPE_AUDIO) {
3867 return transceiver;
3868 }
3869 }
3870 RTC_NOTREACHED();
3871 return nullptr;
3872}
3873
3874rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3875PeerConnection::GetVideoTransceiver() const {
3876 // This method only works with Plan B SDP, where there is a single
3877 // audio/video transceiver.
3878 RTC_DCHECK(!IsUnifiedPlan());
3879 for (auto transceiver : transceivers_) {
3880 if (transceiver->internal()->media_type() == cricket::MEDIA_TYPE_VIDEO) {
3881 return transceiver;
3882 }
3883 }
3884 RTC_NOTREACHED();
3885 return nullptr;
3886}
3887
3888// TODO(bugs.webrtc.org/7600): Remove this when multiple transceivers with
3889// individual transceiver directions are supported.
zhihuang1c378ed2017-08-17 14:10:50 -07003890bool PeerConnection::HasRtpSender(cricket::MediaType type) const {
Steve Anton4171afb2017-11-20 10:20:22 -08003891 switch (type) {
3892 case cricket::MEDIA_TYPE_AUDIO:
3893 return !GetAudioTransceiver()->internal()->senders().empty();
3894 case cricket::MEDIA_TYPE_VIDEO:
3895 return !GetVideoTransceiver()->internal()->senders().empty();
3896 case cricket::MEDIA_TYPE_DATA:
3897 return false;
3898 }
3899 RTC_NOTREACHED();
3900 return false;
zhihuang1c378ed2017-08-17 14:10:50 -07003901}
3902
Steve Anton4171afb2017-11-20 10:20:22 -08003903rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
3904PeerConnection::FindSenderForTrack(MediaStreamTrackInterface* track) const {
3905 for (auto transceiver : transceivers_) {
3906 for (auto sender : transceiver->internal()->senders()) {
3907 if (sender->track() == track) {
3908 return sender;
3909 }
3910 }
3911 }
3912 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08003913}
3914
Steve Anton4171afb2017-11-20 10:20:22 -08003915rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
3916PeerConnection::FindSenderById(const std::string& sender_id) const {
3917 for (auto transceiver : transceivers_) {
3918 for (auto sender : transceiver->internal()->senders()) {
3919 if (sender->id() == sender_id) {
3920 return sender;
3921 }
3922 }
3923 }
3924 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07003925}
3926
Steve Anton4171afb2017-11-20 10:20:22 -08003927rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
3928PeerConnection::FindReceiverById(const std::string& receiver_id) const {
3929 for (auto transceiver : transceivers_) {
3930 for (auto receiver : transceiver->internal()->receivers()) {
3931 if (receiver->id() == receiver_id) {
3932 return receiver;
3933 }
3934 }
3935 }
3936 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07003937}
3938
Steve Anton4171afb2017-11-20 10:20:22 -08003939std::vector<PeerConnection::RtpSenderInfo>*
3940PeerConnection::GetRemoteSenderInfos(cricket::MediaType media_type) {
3941 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
3942 media_type == cricket::MEDIA_TYPE_VIDEO);
3943 return (media_type == cricket::MEDIA_TYPE_AUDIO)
3944 ? &remote_audio_sender_infos_
3945 : &remote_video_sender_infos_;
3946}
3947
3948std::vector<PeerConnection::RtpSenderInfo>* PeerConnection::GetLocalSenderInfos(
deadbeefab9b2d12015-10-14 11:33:11 -07003949 cricket::MediaType media_type) {
3950 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
3951 media_type == cricket::MEDIA_TYPE_VIDEO);
Steve Anton4171afb2017-11-20 10:20:22 -08003952 return (media_type == cricket::MEDIA_TYPE_AUDIO) ? &local_audio_sender_infos_
3953 : &local_video_sender_infos_;
deadbeefab9b2d12015-10-14 11:33:11 -07003954}
3955
Steve Anton4171afb2017-11-20 10:20:22 -08003956const PeerConnection::RtpSenderInfo* PeerConnection::FindSenderInfo(
3957 const std::vector<PeerConnection::RtpSenderInfo>& infos,
deadbeefab9b2d12015-10-14 11:33:11 -07003958 const std::string& stream_label,
Steve Anton4171afb2017-11-20 10:20:22 -08003959 const std::string sender_id) const {
3960 for (const RtpSenderInfo& sender_info : infos) {
3961 if (sender_info.stream_label == stream_label &&
3962 sender_info.sender_id == sender_id) {
3963 return &sender_info;
deadbeefab9b2d12015-10-14 11:33:11 -07003964 }
3965 }
3966 return nullptr;
3967}
3968
3969DataChannel* PeerConnection::FindDataChannelBySid(int sid) const {
3970 for (const auto& channel : sctp_data_channels_) {
3971 if (channel->id() == sid) {
3972 return channel;
3973 }
3974 }
3975 return nullptr;
3976}
3977
deadbeef91dd5672016-05-18 16:55:30 -07003978bool PeerConnection::InitializePortAllocator_n(
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003979 const RTCConfiguration& configuration) {
3980 cricket::ServerAddresses stun_servers;
3981 std::vector<cricket::RelayServerConfig> turn_servers;
deadbeef293e9262017-01-11 12:28:30 -08003982 if (ParseIceServers(configuration.servers, &stun_servers, &turn_servers) !=
3983 RTCErrorType::NONE) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003984 return false;
3985 }
3986
Taylor Brandstetterf8e65772016-06-27 17:20:15 -07003987 port_allocator_->Initialize();
3988
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003989 // To handle both internal and externally created port allocator, we will
3990 // enable BUNDLE here.
3991 int portallocator_flags = port_allocator_->flags();
3992 portallocator_flags |= cricket::PORTALLOCATOR_ENABLE_SHARED_SOCKET |
zhihuangb09b3f92017-03-07 14:40:51 -08003993 cricket::PORTALLOCATOR_ENABLE_IPV6 |
3994 cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI;
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003995 // If the disable-IPv6 flag was specified, we'll not override it
3996 // by experiment.
3997 if (configuration.disable_ipv6) {
3998 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
sprangc1b57a12017-02-28 08:50:47 -08003999 } else if (webrtc::field_trial::FindFullName("WebRTC-IPv6Default")
4000 .find("Disabled") == 0) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004001 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
4002 }
4003
zhihuangb09b3f92017-03-07 14:40:51 -08004004 if (configuration.disable_ipv6_on_wifi) {
4005 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI);
Mirko Bonadei675513b2017-11-09 11:09:25 +01004006 RTC_LOG(LS_INFO) << "IPv6 candidates on Wi-Fi are disabled.";
zhihuangb09b3f92017-03-07 14:40:51 -08004007 }
4008
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004009 if (configuration.tcp_candidate_policy == kTcpCandidatePolicyDisabled) {
4010 portallocator_flags |= cricket::PORTALLOCATOR_DISABLE_TCP;
Mirko Bonadei675513b2017-11-09 11:09:25 +01004011 RTC_LOG(LS_INFO) << "TCP candidates are disabled.";
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004012 }
4013
honghaiz60347052016-05-31 18:29:12 -07004014 if (configuration.candidate_network_policy ==
4015 kCandidateNetworkPolicyLowCost) {
4016 portallocator_flags |= cricket::PORTALLOCATOR_DISABLE_COSTLY_NETWORKS;
Mirko Bonadei675513b2017-11-09 11:09:25 +01004017 RTC_LOG(LS_INFO) << "Do not gather candidates on high-cost networks";
honghaiz60347052016-05-31 18:29:12 -07004018 }
4019
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004020 port_allocator_->set_flags(portallocator_flags);
4021 // No step delay is used while allocating ports.
4022 port_allocator_->set_step_delay(cricket::kMinimumStepDelay);
4023 port_allocator_->set_candidate_filter(
4024 ConvertIceTransportTypeToCandidateFilter(configuration.type));
deadbeefd21eab32017-07-26 16:50:11 -07004025 port_allocator_->set_max_ipv6_networks(configuration.max_ipv6_networks);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004026
4027 // Call this last since it may create pooled allocator sessions using the
4028 // properties set above.
4029 port_allocator_->SetConfiguration(stun_servers, turn_servers,
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -07004030 configuration.ice_candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02004031 configuration.prune_turn_ports,
4032 configuration.turn_customizer);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004033 return true;
4034}
4035
deadbeef91dd5672016-05-18 16:55:30 -07004036bool PeerConnection::ReconfigurePortAllocator_n(
deadbeef293e9262017-01-11 12:28:30 -08004037 const cricket::ServerAddresses& stun_servers,
4038 const std::vector<cricket::RelayServerConfig>& turn_servers,
4039 IceTransportsType type,
4040 int candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02004041 bool prune_turn_ports,
4042 webrtc::TurnCustomizer* turn_customizer) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004043 port_allocator_->set_candidate_filter(
deadbeef293e9262017-01-11 12:28:30 -08004044 ConvertIceTransportTypeToCandidateFilter(type));
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004045 // Call this last since it may create pooled allocator sessions using the
4046 // candidate filter set above.
deadbeef6de92f92016-12-12 18:49:32 -08004047 return port_allocator_->SetConfiguration(
Jonas Orelandbdcee282017-10-10 14:01:40 +02004048 stun_servers, turn_servers, candidate_pool_size, prune_turn_ports,
4049 turn_customizer);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004050}
4051
Steve Antonba818672017-11-06 10:21:57 -08004052cricket::ChannelManager* PeerConnection::channel_manager() const {
4053 return factory_->channel_manager();
4054}
4055
4056MetricsObserverInterface* PeerConnection::metrics_observer() const {
4057 return uma_observer_;
4058}
4059
Elad Alon99c3fe52017-10-13 16:29:40 +02004060bool PeerConnection::StartRtcEventLog_w(
Bjorn Tereliusde939432017-11-20 17:38:14 +01004061 std::unique_ptr<RtcEventLogOutput> output,
4062 int64_t output_period_ms) {
zhihuang77985012017-02-07 15:45:16 -08004063 if (!event_log_) {
4064 return false;
4065 }
Bjorn Tereliusde939432017-11-20 17:38:14 +01004066 return event_log_->StartLogging(std::move(output), output_period_ms);
ivoc14d5dbe2016-07-04 07:06:55 -07004067}
4068
4069void PeerConnection::StopRtcEventLog_w() {
zhihuang77985012017-02-07 15:45:16 -08004070 if (event_log_) {
4071 event_log_->StopLogging();
4072 }
ivoc14d5dbe2016-07-04 07:06:55 -07004073}
nisseeaabdf62017-05-05 02:23:02 -07004074
Steve Anton75737c02017-11-06 10:37:17 -08004075cricket::BaseChannel* PeerConnection::GetChannel(
4076 const std::string& content_name) {
Steve Antondcc3c022017-12-22 16:02:54 -08004077 for (auto transceiver : transceivers_) {
4078 cricket::BaseChannel* channel = transceiver->internal()->channel();
4079 if (channel && channel->content_name() == content_name) {
4080 return channel;
4081 }
Steve Anton75737c02017-11-06 10:37:17 -08004082 }
4083 if (rtp_data_channel() &&
4084 rtp_data_channel()->content_name() == content_name) {
4085 return rtp_data_channel();
4086 }
4087 return nullptr;
4088}
4089
4090bool PeerConnection::GetSctpSslRole(rtc::SSLRole* role) {
4091 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004092 RTC_LOG(LS_INFO)
4093 << "Local and Remote descriptions must be applied to get the "
4094 << "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08004095 return false;
4096 }
4097 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004098 RTC_LOG(LS_INFO) << "Non-rejected SCTP m= section is needed to get the "
4099 << "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08004100 return false;
4101 }
4102
4103 return transport_controller_->GetSslRole(*sctp_transport_name_, role);
4104}
4105
4106bool PeerConnection::GetSslRole(const std::string& content_name,
4107 rtc::SSLRole* role) {
4108 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004109 RTC_LOG(LS_INFO)
4110 << "Local and Remote descriptions must be applied to get the "
4111 << "SSL Role of the session.";
Steve Anton75737c02017-11-06 10:37:17 -08004112 return false;
4113 }
4114
4115 return transport_controller_->GetSslRole(GetTransportName(content_name),
4116 role);
4117}
4118
Steve Anton75737c02017-11-06 10:37:17 -08004119// TODO(steveanton): Eventually it'd be nice to store the channels as a single
4120// vector of BaseChannel pointers instead of separate voice and video channel
4121// vectors. At that point, this will become a simple getter.
4122std::vector<cricket::BaseChannel*> PeerConnection::Channels() const {
4123 std::vector<cricket::BaseChannel*> channels;
Steve Anton4171afb2017-11-20 10:20:22 -08004124 if (voice_channel()) {
4125 channels.push_back(voice_channel());
4126 }
4127 if (video_channel()) {
4128 channels.push_back(video_channel());
4129 }
Steve Anton75737c02017-11-06 10:37:17 -08004130 if (rtp_data_channel_) {
4131 channels.push_back(rtp_data_channel_);
4132 }
4133 return channels;
4134}
4135
Steve Antonf8470812017-12-04 10:46:21 -08004136void PeerConnection::SetSessionError(SessionError error,
4137 const std::string& error_desc) {
4138 RTC_DCHECK_RUN_ON(signaling_thread());
4139 if (error != session_error_) {
4140 session_error_ = error;
4141 session_error_desc_ = error_desc;
Steve Anton75737c02017-11-06 10:37:17 -08004142 }
4143}
4144
Steve Anton3828c062017-12-06 10:34:51 -08004145RTCError PeerConnection::UpdateSessionState(SdpType type,
Steve Anton8a006912017-12-04 15:25:56 -08004146 cricket::ContentSource source) {
4147 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08004148
4149 // If there's already a pending error then no state transition should happen.
4150 // But all call-sites should be verifying this before calling us!
Steve Antonf8470812017-12-04 10:46:21 -08004151 RTC_DCHECK(session_error() == SessionError::kNone);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004152
4153 // If this is an answer then we know whether to BUNDLE or not. If both the
4154 // local and remote side have agreed to BUNDLE, go ahead and enable it.
Steve Anton3828c062017-12-06 10:34:51 -08004155 if (type == SdpType::kAnswer) {
Steve Anton75737c02017-11-06 10:37:17 -08004156 const cricket::ContentGroup* local_bundle =
4157 local_description()->description()->GetGroupByName(
4158 cricket::GROUP_TYPE_BUNDLE);
4159 const cricket::ContentGroup* remote_bundle =
4160 remote_description()->description()->GetGroupByName(
4161 cricket::GROUP_TYPE_BUNDLE);
4162 if (local_bundle && remote_bundle) {
4163 // The answerer decides the transport to bundle on.
4164 const cricket::ContentGroup* answer_bundle =
4165 (source == cricket::CS_LOCAL ? local_bundle : remote_bundle);
4166 if (!EnableBundle(*answer_bundle)) {
Steve Anton8a006912017-12-04 15:25:56 -08004167 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
4168 kEnableBundleFailed);
Steve Anton75737c02017-11-06 10:37:17 -08004169 }
4170 }
Steve Anton75737c02017-11-06 10:37:17 -08004171 }
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004172
4173 // Only push down the transport description after potentially enabling BUNDLE;
4174 // we don't want to push down a description on a transport about to be
4175 // destroyed.
Steve Anton3828c062017-12-06 10:34:51 -08004176 RTCError error = PushdownTransportDescription(source, type);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004177 if (!error.ok()) {
4178 return error;
4179 }
4180
4181 // If this is answer-ish we're ready to let media flow.
Steve Anton3828c062017-12-06 10:34:51 -08004182 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Antoned10bd92017-12-05 10:52:59 -08004183 EnableSending();
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004184 }
4185
4186 // Update the signaling state according to the specified state machine (see
4187 // https://w3c.github.io/webrtc-pc/#rtcsignalingstate-enum).
Steve Anton3828c062017-12-06 10:34:51 -08004188 if (type == SdpType::kOffer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004189 ChangeSignalingState(source == cricket::CS_LOCAL
4190 ? PeerConnectionInterface::kHaveLocalOffer
4191 : PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton3828c062017-12-06 10:34:51 -08004192 } else if (type == SdpType::kPrAnswer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004193 ChangeSignalingState(source == cricket::CS_LOCAL
4194 ? PeerConnectionInterface::kHaveLocalPrAnswer
4195 : PeerConnectionInterface::kHaveRemotePrAnswer);
4196 } else {
Steve Anton3828c062017-12-06 10:34:51 -08004197 RTC_DCHECK(type == SdpType::kAnswer);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004198 ChangeSignalingState(PeerConnectionInterface::kStable);
4199 }
4200
4201 // Update internal objects according to the session description's media
4202 // descriptions.
Steve Anton3828c062017-12-06 10:34:51 -08004203 error = PushdownMediaDescription(type, source);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004204 if (!error.ok()) {
4205 SetSessionError(SessionError::kContent, error.message());
4206 }
4207 if (session_error() != SessionError::kNone) {
4208 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
4209 }
4210
Steve Anton8a006912017-12-04 15:25:56 -08004211 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08004212}
4213
Steve Anton8a006912017-12-04 15:25:56 -08004214RTCError PeerConnection::PushdownMediaDescription(
Steve Anton3828c062017-12-06 10:34:51 -08004215 SdpType type,
Steve Anton8a006912017-12-04 15:25:56 -08004216 cricket::ContentSource source) {
Steve Antoned10bd92017-12-05 10:52:59 -08004217 const SessionDescriptionInterface* sdesc =
4218 (source == cricket::CS_LOCAL ? local_description()
4219 : remote_description());
Steve Anton75737c02017-11-06 10:37:17 -08004220 RTC_DCHECK(sdesc);
Steve Antoned10bd92017-12-05 10:52:59 -08004221
4222 // Push down the new SDP media section for each audio/video transceiver.
4223 for (auto transceiver : transceivers_) {
Steve Anton75737c02017-11-06 10:37:17 -08004224 const ContentInfo* content_info =
Steve Antoned10bd92017-12-05 10:52:59 -08004225 FindMediaSectionForTransceiver(transceiver, sdesc);
4226 cricket::BaseChannel* channel = transceiver->internal()->channel();
4227 if (!channel || !content_info || content_info->rejected) {
Steve Anton75737c02017-11-06 10:37:17 -08004228 continue;
4229 }
4230 const MediaContentDescription* content_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08004231 content_info->media_description();
Steve Antoned10bd92017-12-05 10:52:59 -08004232 if (!content_desc) {
4233 continue;
4234 }
4235 std::string error;
4236 bool success =
4237 (source == cricket::CS_LOCAL)
Steve Anton3828c062017-12-06 10:34:51 -08004238 ? channel->SetLocalContent(content_desc, type, &error)
4239 : channel->SetRemoteContent(content_desc, type, &error);
Steve Antoned10bd92017-12-05 10:52:59 -08004240 if (!success) {
4241 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, std::move(error));
4242 }
4243 }
4244
4245 // If using the RtpDataChannel, push down the new SDP section for it too.
4246 if (rtp_data_channel_) {
4247 const ContentInfo* data_content =
4248 cricket::GetFirstDataContent(sdesc->description());
4249 if (data_content && !data_content->rejected) {
4250 const MediaContentDescription* data_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08004251 data_content->media_description();
Steve Antoned10bd92017-12-05 10:52:59 -08004252 if (data_desc) {
4253 std::string error;
4254 bool success =
4255 (source == cricket::CS_LOCAL)
Steve Anton3828c062017-12-06 10:34:51 -08004256 ? rtp_data_channel_->SetLocalContent(data_desc, type, &error)
4257 : rtp_data_channel_->SetRemoteContent(data_desc, type,
Steve Antoned10bd92017-12-05 10:52:59 -08004258 &error);
4259 if (!success) {
4260 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
4261 std::move(error));
4262 }
Steve Anton75737c02017-11-06 10:37:17 -08004263 }
4264 }
4265 }
Steve Antoned10bd92017-12-05 10:52:59 -08004266
Steve Anton75737c02017-11-06 10:37:17 -08004267 // Need complete offer/answer with an SCTP m= section before starting SCTP,
4268 // according to https://tools.ietf.org/html/draft-ietf-mmusic-sctp-sdp-19
4269 if (sctp_transport_ && local_description() && remote_description() &&
4270 cricket::GetFirstDataContent(local_description()->description()) &&
4271 cricket::GetFirstDataContent(remote_description()->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08004272 bool success = network_thread()->Invoke<bool>(
Steve Anton75737c02017-11-06 10:37:17 -08004273 RTC_FROM_HERE,
4274 rtc::Bind(&PeerConnection::PushdownSctpParameters_n, this, source));
Steve Anton8a006912017-12-04 15:25:56 -08004275 if (!success) {
4276 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
4277 "Failed to push down SCTP parameters.");
4278 }
Steve Anton75737c02017-11-06 10:37:17 -08004279 }
Steve Antoned10bd92017-12-05 10:52:59 -08004280
Steve Anton8a006912017-12-04 15:25:56 -08004281 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08004282}
4283
4284bool PeerConnection::PushdownSctpParameters_n(cricket::ContentSource source) {
4285 RTC_DCHECK(network_thread()->IsCurrent());
4286 RTC_DCHECK(local_description());
4287 RTC_DCHECK(remote_description());
4288 // Apply the SCTP port (which is hidden inside a DataCodec structure...)
4289 // When we support "max-message-size", that would also be pushed down here.
4290 return sctp_transport_->Start(
4291 GetSctpPort(local_description()->description()),
4292 GetSctpPort(remote_description()->description()));
4293}
4294
Steve Anton8a006912017-12-04 15:25:56 -08004295RTCError PeerConnection::PushdownTransportDescription(
4296 cricket::ContentSource source,
Steve Anton3828c062017-12-06 10:34:51 -08004297 SdpType type) {
Steve Anton8a006912017-12-04 15:25:56 -08004298 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08004299
Steve Anton8a006912017-12-04 15:25:56 -08004300 const SessionDescriptionInterface* sdesc =
4301 (source == cricket::CS_LOCAL ? local_description()
4302 : remote_description());
4303 RTC_DCHECK(sdesc);
4304 for (const cricket::TransportInfo& tinfo :
4305 sdesc->description()->transport_infos()) {
4306 std::string error;
4307 bool success;
4308 if (source == cricket::CS_LOCAL) {
4309 success = transport_controller_->SetLocalTransportDescription(
Steve Anton3828c062017-12-06 10:34:51 -08004310 tinfo.content_name, tinfo.description, type, &error);
Steve Anton8a006912017-12-04 15:25:56 -08004311 } else {
4312 success = transport_controller_->SetRemoteTransportDescription(
Steve Anton3828c062017-12-06 10:34:51 -08004313 tinfo.content_name, tinfo.description, type, &error);
Steve Anton8a006912017-12-04 15:25:56 -08004314 }
4315 if (!success) {
Steve Antondcc3c022017-12-22 16:02:54 -08004316 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
4317 "Failed to push down transport description for " +
4318 tinfo.content_name + ": " + error);
Steve Anton75737c02017-11-06 10:37:17 -08004319 }
4320 }
4321
Steve Anton8a006912017-12-04 15:25:56 -08004322 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08004323}
4324
4325bool PeerConnection::GetTransportDescription(
4326 const SessionDescription* description,
4327 const std::string& content_name,
4328 cricket::TransportDescription* tdesc) {
4329 if (!description || !tdesc) {
4330 return false;
4331 }
4332 const TransportInfo* transport_info =
4333 description->GetTransportInfoByName(content_name);
4334 if (!transport_info) {
4335 return false;
4336 }
4337 *tdesc = transport_info->description;
4338 return true;
4339}
4340
4341bool PeerConnection::EnableBundle(const cricket::ContentGroup& bundle) {
4342 const std::string* first_content_name = bundle.FirstContentName();
4343 if (!first_content_name) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004344 RTC_LOG(LS_WARNING) << "Tried to BUNDLE with no contents.";
Steve Anton75737c02017-11-06 10:37:17 -08004345 return false;
4346 }
4347 const std::string& transport_name = *first_content_name;
4348
4349 auto maybe_set_transport = [this, bundle,
4350 transport_name](cricket::BaseChannel* ch) {
4351 if (!ch || !bundle.HasContentName(ch->content_name())) {
Steve Antoned10bd92017-12-05 10:52:59 -08004352 return;
Steve Anton75737c02017-11-06 10:37:17 -08004353 }
4354
4355 std::string old_transport_name = ch->transport_name();
4356 if (old_transport_name == transport_name) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004357 RTC_LOG(LS_INFO) << "BUNDLE already enabled for " << ch->content_name()
4358 << " on " << transport_name << ".";
Steve Antoned10bd92017-12-05 10:52:59 -08004359 return;
Steve Anton75737c02017-11-06 10:37:17 -08004360 }
4361
4362 cricket::DtlsTransportInternal* rtp_dtls_transport =
4363 transport_controller_->CreateDtlsTransport(
4364 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4365 bool need_rtcp = (ch->rtcp_dtls_transport() != nullptr);
4366 cricket::DtlsTransportInternal* rtcp_dtls_transport = nullptr;
4367 if (need_rtcp) {
4368 rtcp_dtls_transport = transport_controller_->CreateDtlsTransport(
4369 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
4370 }
4371
4372 ch->SetTransports(rtp_dtls_transport, rtcp_dtls_transport);
Mirko Bonadei675513b2017-11-09 11:09:25 +01004373 RTC_LOG(LS_INFO) << "Enabled BUNDLE for " << ch->content_name() << " on "
4374 << transport_name << ".";
Steve Anton75737c02017-11-06 10:37:17 -08004375 transport_controller_->DestroyDtlsTransport(
4376 old_transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4377 // If the channel needs rtcp, it means that the channel used to have a
4378 // rtcp transport which needs to be deleted now.
4379 if (need_rtcp) {
4380 transport_controller_->DestroyDtlsTransport(
4381 old_transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
4382 }
Steve Anton75737c02017-11-06 10:37:17 -08004383 };
4384
Steve Antoned10bd92017-12-05 10:52:59 -08004385 for (auto transceiver : transceivers_) {
4386 maybe_set_transport(transceiver->internal()->channel());
Steve Anton75737c02017-11-06 10:37:17 -08004387 }
Steve Antoned10bd92017-12-05 10:52:59 -08004388 maybe_set_transport(rtp_data_channel_);
4389
Steve Anton75737c02017-11-06 10:37:17 -08004390 // For SCTP, transport creation/deletion happens here instead of in the
4391 // object itself.
4392 if (sctp_transport_) {
4393 RTC_DCHECK(sctp_transport_name_);
4394 RTC_DCHECK(sctp_content_name_);
4395 if (transport_name != *sctp_transport_name_ &&
4396 bundle.HasContentName(*sctp_content_name_)) {
4397 network_thread()->Invoke<void>(
4398 RTC_FROM_HERE, rtc::Bind(&PeerConnection::ChangeSctpTransport_n, this,
4399 transport_name));
4400 }
4401 }
4402
4403 return true;
4404}
4405
Steve Anton75737c02017-11-06 10:37:17 -08004406cricket::IceConfig PeerConnection::ParseIceConfig(
4407 const PeerConnectionInterface::RTCConfiguration& config) const {
4408 cricket::ContinualGatheringPolicy gathering_policy;
4409 // TODO(honghaiz): Add the third continual gathering policy in
4410 // PeerConnectionInterface and map it to GATHER_CONTINUALLY_AND_RECOVER.
4411 switch (config.continual_gathering_policy) {
4412 case PeerConnectionInterface::GATHER_ONCE:
4413 gathering_policy = cricket::GATHER_ONCE;
4414 break;
4415 case PeerConnectionInterface::GATHER_CONTINUALLY:
4416 gathering_policy = cricket::GATHER_CONTINUALLY;
4417 break;
4418 default:
4419 RTC_NOTREACHED();
4420 gathering_policy = cricket::GATHER_ONCE;
4421 }
4422 cricket::IceConfig ice_config;
4423 ice_config.receiving_timeout = config.ice_connection_receiving_timeout;
4424 ice_config.prioritize_most_likely_candidate_pairs =
4425 config.prioritize_most_likely_ice_candidate_pairs;
4426 ice_config.backup_connection_ping_interval =
4427 config.ice_backup_candidate_pair_ping_interval;
4428 ice_config.continual_gathering_policy = gathering_policy;
4429 ice_config.presume_writable_when_fully_relayed =
4430 config.presume_writable_when_fully_relayed;
4431 ice_config.ice_check_min_interval = config.ice_check_min_interval;
4432 ice_config.regather_all_networks_interval_range =
4433 config.ice_regather_interval_range;
4434 return ice_config;
4435}
4436
Steve Anton75737c02017-11-06 10:37:17 -08004437bool PeerConnection::GetLocalTrackIdBySsrc(uint32_t ssrc,
4438 std::string* track_id) {
4439 if (!local_description()) {
4440 return false;
4441 }
4442 return webrtc::GetTrackIdBySsrc(local_description()->description(), ssrc,
4443 track_id);
4444}
4445
4446bool PeerConnection::GetRemoteTrackIdBySsrc(uint32_t ssrc,
4447 std::string* track_id) {
4448 if (!remote_description()) {
4449 return false;
4450 }
4451 return webrtc::GetTrackIdBySsrc(remote_description()->description(), ssrc,
4452 track_id);
4453}
4454
4455bool PeerConnection::SendData(const cricket::SendDataParams& params,
4456 const rtc::CopyOnWriteBuffer& payload,
4457 cricket::SendDataResult* result) {
4458 if (!rtp_data_channel_ && !sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004459 RTC_LOG(LS_ERROR) << "SendData called when rtp_data_channel_ "
4460 << "and sctp_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08004461 return false;
4462 }
4463 return rtp_data_channel_
4464 ? rtp_data_channel_->SendData(params, payload, result)
4465 : network_thread()->Invoke<bool>(
4466 RTC_FROM_HERE,
4467 Bind(&cricket::SctpTransportInternal::SendData,
4468 sctp_transport_.get(), params, payload, result));
4469}
4470
4471bool PeerConnection::ConnectDataChannel(DataChannel* webrtc_data_channel) {
4472 if (!rtp_data_channel_ && !sctp_transport_) {
4473 // Don't log an error here, because DataChannels are expected to call
4474 // ConnectDataChannel in this state. It's the only way to initially tell
4475 // whether or not the underlying transport is ready.
4476 return false;
4477 }
4478 if (rtp_data_channel_) {
4479 rtp_data_channel_->SignalReadyToSendData.connect(
4480 webrtc_data_channel, &DataChannel::OnChannelReady);
4481 rtp_data_channel_->SignalDataReceived.connect(webrtc_data_channel,
4482 &DataChannel::OnDataReceived);
4483 } else {
4484 SignalSctpReadyToSendData.connect(webrtc_data_channel,
4485 &DataChannel::OnChannelReady);
4486 SignalSctpDataReceived.connect(webrtc_data_channel,
4487 &DataChannel::OnDataReceived);
4488 SignalSctpStreamClosedRemotely.connect(
4489 webrtc_data_channel, &DataChannel::OnStreamClosedRemotely);
4490 }
4491 return true;
4492}
4493
4494void PeerConnection::DisconnectDataChannel(DataChannel* webrtc_data_channel) {
4495 if (!rtp_data_channel_ && !sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004496 RTC_LOG(LS_ERROR)
4497 << "DisconnectDataChannel called when rtp_data_channel_ and "
4498 "sctp_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08004499 return;
4500 }
4501 if (rtp_data_channel_) {
4502 rtp_data_channel_->SignalReadyToSendData.disconnect(webrtc_data_channel);
4503 rtp_data_channel_->SignalDataReceived.disconnect(webrtc_data_channel);
4504 } else {
4505 SignalSctpReadyToSendData.disconnect(webrtc_data_channel);
4506 SignalSctpDataReceived.disconnect(webrtc_data_channel);
4507 SignalSctpStreamClosedRemotely.disconnect(webrtc_data_channel);
4508 }
4509}
4510
4511void PeerConnection::AddSctpDataStream(int sid) {
4512 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004513 RTC_LOG(LS_ERROR)
4514 << "AddSctpDataStream called when sctp_transport_ is NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08004515 return;
4516 }
4517 network_thread()->Invoke<void>(
4518 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::OpenStream,
4519 sctp_transport_.get(), sid));
4520}
4521
4522void PeerConnection::RemoveSctpDataStream(int sid) {
4523 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004524 RTC_LOG(LS_ERROR) << "RemoveSctpDataStream called when sctp_transport_ is "
4525 << "NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08004526 return;
4527 }
4528 network_thread()->Invoke<void>(
4529 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::ResetStream,
4530 sctp_transport_.get(), sid));
4531}
4532
4533bool PeerConnection::ReadyToSendData() const {
4534 return (rtp_data_channel_ && rtp_data_channel_->ready_to_send_data()) ||
4535 sctp_ready_to_send_data_;
4536}
4537
4538std::unique_ptr<SessionStats> PeerConnection::GetSessionStats_s() {
4539 RTC_DCHECK(signaling_thread()->IsCurrent());
4540 ChannelNamePairs channel_name_pairs;
4541 if (voice_channel()) {
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004542 channel_name_pairs.voice = ChannelNamePair(
4543 voice_channel()->content_name(), voice_channel()->transport_name());
Steve Anton75737c02017-11-06 10:37:17 -08004544 }
4545 if (video_channel()) {
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004546 channel_name_pairs.video = ChannelNamePair(
4547 video_channel()->content_name(), video_channel()->transport_name());
Steve Anton75737c02017-11-06 10:37:17 -08004548 }
4549 if (rtp_data_channel()) {
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004550 channel_name_pairs.data =
Steve Anton75737c02017-11-06 10:37:17 -08004551 ChannelNamePair(rtp_data_channel()->content_name(),
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004552 rtp_data_channel()->transport_name());
Steve Anton75737c02017-11-06 10:37:17 -08004553 }
4554 if (sctp_transport_) {
4555 RTC_DCHECK(sctp_content_name_);
4556 RTC_DCHECK(sctp_transport_name_);
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004557 channel_name_pairs.data =
4558 ChannelNamePair(*sctp_content_name_, *sctp_transport_name_);
Steve Anton75737c02017-11-06 10:37:17 -08004559 }
4560 return GetSessionStats(channel_name_pairs);
4561}
4562
4563std::unique_ptr<SessionStats> PeerConnection::GetSessionStats(
4564 const ChannelNamePairs& channel_name_pairs) {
4565 if (network_thread()->IsCurrent()) {
4566 return GetSessionStats_n(channel_name_pairs);
4567 }
4568 return network_thread()->Invoke<std::unique_ptr<SessionStats>>(
4569 RTC_FROM_HERE,
4570 rtc::Bind(&PeerConnection::GetSessionStats_n, this, channel_name_pairs));
4571}
4572
4573bool PeerConnection::GetLocalCertificate(
4574 const std::string& transport_name,
4575 rtc::scoped_refptr<rtc::RTCCertificate>* certificate) {
4576 return transport_controller_->GetLocalCertificate(transport_name,
4577 certificate);
4578}
4579
4580std::unique_ptr<rtc::SSLCertificate> PeerConnection::GetRemoteSSLCertificate(
4581 const std::string& transport_name) {
4582 return transport_controller_->GetRemoteSSLCertificate(transport_name);
4583}
4584
4585cricket::DataChannelType PeerConnection::data_channel_type() const {
4586 return data_channel_type_;
4587}
4588
4589bool PeerConnection::IceRestartPending(const std::string& content_name) const {
4590 return pending_ice_restarts_.find(content_name) !=
4591 pending_ice_restarts_.end();
4592}
4593
Steve Anton75737c02017-11-06 10:37:17 -08004594bool PeerConnection::NeedsIceRestart(const std::string& content_name) const {
4595 return transport_controller_->NeedsIceRestart(content_name);
4596}
4597
4598void PeerConnection::OnCertificateReady(
4599 const rtc::scoped_refptr<rtc::RTCCertificate>& certificate) {
4600 transport_controller_->SetLocalCertificate(certificate);
4601}
4602
4603void PeerConnection::OnDtlsSrtpSetupFailure(cricket::BaseChannel*, bool rtcp) {
Steve Antonf8470812017-12-04 10:46:21 -08004604 SetSessionError(SessionError::kTransport,
4605 rtcp ? kDtlsSrtpSetupFailureRtcp : kDtlsSrtpSetupFailureRtp);
Steve Anton75737c02017-11-06 10:37:17 -08004606}
4607
4608void PeerConnection::OnTransportControllerConnectionState(
4609 cricket::IceConnectionState state) {
4610 switch (state) {
4611 case cricket::kIceConnectionConnecting:
4612 // If the current state is Connected or Completed, then there were
4613 // writable channels but now there are not, so the next state must
4614 // be Disconnected.
4615 // kIceConnectionConnecting is currently used as the default,
4616 // un-connected state by the TransportController, so its only use is
4617 // detecting disconnections.
4618 if (ice_connection_state_ ==
4619 PeerConnectionInterface::kIceConnectionConnected ||
4620 ice_connection_state_ ==
4621 PeerConnectionInterface::kIceConnectionCompleted) {
4622 SetIceConnectionState(
4623 PeerConnectionInterface::kIceConnectionDisconnected);
4624 }
4625 break;
4626 case cricket::kIceConnectionFailed:
4627 SetIceConnectionState(PeerConnectionInterface::kIceConnectionFailed);
4628 break;
4629 case cricket::kIceConnectionConnected:
Mirko Bonadei675513b2017-11-09 11:09:25 +01004630 RTC_LOG(LS_INFO) << "Changing to ICE connected state because "
4631 << "all transports are writable.";
Steve Anton75737c02017-11-06 10:37:17 -08004632 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
4633 break;
4634 case cricket::kIceConnectionCompleted:
Mirko Bonadei675513b2017-11-09 11:09:25 +01004635 RTC_LOG(LS_INFO) << "Changing to ICE completed state because "
4636 << "all transports are complete.";
Steve Anton75737c02017-11-06 10:37:17 -08004637 if (ice_connection_state_ !=
4638 PeerConnectionInterface::kIceConnectionConnected) {
4639 // If jumping directly from "checking" to "connected",
4640 // signal "connected" first.
4641 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
4642 }
4643 SetIceConnectionState(PeerConnectionInterface::kIceConnectionCompleted);
4644 if (metrics_observer()) {
4645 ReportTransportStats();
4646 }
4647 break;
4648 default:
4649 RTC_NOTREACHED();
4650 }
4651}
4652
4653void PeerConnection::OnTransportControllerCandidatesGathered(
4654 const std::string& transport_name,
4655 const cricket::Candidates& candidates) {
4656 RTC_DCHECK(signaling_thread()->IsCurrent());
4657 int sdp_mline_index;
4658 if (!GetLocalCandidateMediaIndex(transport_name, &sdp_mline_index)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004659 RTC_LOG(LS_ERROR)
4660 << "OnTransportControllerCandidatesGathered: content name "
4661 << transport_name << " not found";
Steve Anton75737c02017-11-06 10:37:17 -08004662 return;
4663 }
4664
4665 for (cricket::Candidates::const_iterator citer = candidates.begin();
4666 citer != candidates.end(); ++citer) {
4667 // Use transport_name as the candidate media id.
4668 std::unique_ptr<JsepIceCandidate> candidate(
4669 new JsepIceCandidate(transport_name, sdp_mline_index, *citer));
4670 if (local_description()) {
4671 mutable_local_description()->AddCandidate(candidate.get());
4672 }
4673 OnIceCandidate(std::move(candidate));
4674 }
4675}
4676
4677void PeerConnection::OnTransportControllerCandidatesRemoved(
4678 const std::vector<cricket::Candidate>& candidates) {
4679 RTC_DCHECK(signaling_thread()->IsCurrent());
4680 // Sanity check.
4681 for (const cricket::Candidate& candidate : candidates) {
4682 if (candidate.transport_name().empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004683 RTC_LOG(LS_ERROR) << "OnTransportControllerCandidatesRemoved: "
4684 << "empty content name in candidate "
4685 << candidate.ToString();
Steve Anton75737c02017-11-06 10:37:17 -08004686 return;
4687 }
4688 }
4689
4690 if (local_description()) {
4691 mutable_local_description()->RemoveCandidates(candidates);
4692 }
4693 OnIceCandidatesRemoved(candidates);
4694}
4695
4696void PeerConnection::OnTransportControllerDtlsHandshakeError(
4697 rtc::SSLHandshakeError error) {
4698 if (metrics_observer()) {
4699 metrics_observer()->IncrementEnumCounter(
4700 webrtc::kEnumCounterDtlsHandshakeError, static_cast<int>(error),
4701 static_cast<int>(rtc::SSLHandshakeError::MAX_VALUE));
4702 }
4703}
4704
Steve Antoned10bd92017-12-05 10:52:59 -08004705void PeerConnection::EnableSending() {
4706 for (auto transceiver : transceivers_) {
4707 cricket::BaseChannel* channel = transceiver->internal()->channel();
4708 if (channel && !channel->enabled()) {
4709 channel->Enable(true);
4710 }
Steve Anton75737c02017-11-06 10:37:17 -08004711 }
4712
Steve Anton4171afb2017-11-20 10:20:22 -08004713 if (rtp_data_channel_ && !rtp_data_channel_->enabled()) {
Steve Anton75737c02017-11-06 10:37:17 -08004714 rtp_data_channel_->Enable(true);
Steve Anton4171afb2017-11-20 10:20:22 -08004715 }
Steve Anton75737c02017-11-06 10:37:17 -08004716}
4717
4718// Returns the media index for a local ice candidate given the content name.
4719bool PeerConnection::GetLocalCandidateMediaIndex(
4720 const std::string& content_name,
4721 int* sdp_mline_index) {
4722 if (!local_description() || !sdp_mline_index) {
4723 return false;
4724 }
4725
4726 bool content_found = false;
4727 const ContentInfos& contents = local_description()->description()->contents();
4728 for (size_t index = 0; index < contents.size(); ++index) {
4729 if (contents[index].name == content_name) {
4730 *sdp_mline_index = static_cast<int>(index);
4731 content_found = true;
4732 break;
4733 }
4734 }
4735 return content_found;
4736}
4737
4738bool PeerConnection::UseCandidatesInSessionDescription(
4739 const SessionDescriptionInterface* remote_desc) {
4740 if (!remote_desc) {
4741 return true;
4742 }
4743 bool ret = true;
4744
4745 for (size_t m = 0; m < remote_desc->number_of_mediasections(); ++m) {
4746 const IceCandidateCollection* candidates = remote_desc->candidates(m);
4747 for (size_t n = 0; n < candidates->count(); ++n) {
4748 const IceCandidateInterface* candidate = candidates->at(n);
4749 bool valid = false;
4750 if (!ReadyToUseRemoteCandidate(candidate, remote_desc, &valid)) {
4751 if (valid) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004752 RTC_LOG(LS_INFO)
4753 << "UseCandidatesInSessionDescription: Not ready to use "
4754 << "candidate.";
Steve Anton75737c02017-11-06 10:37:17 -08004755 }
4756 continue;
4757 }
4758 ret = UseCandidate(candidate);
4759 if (!ret) {
4760 break;
4761 }
4762 }
4763 }
4764 return ret;
4765}
4766
4767bool PeerConnection::UseCandidate(const IceCandidateInterface* candidate) {
4768 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
4769 size_t remote_content_size =
4770 remote_description()->description()->contents().size();
4771 if (mediacontent_index >= remote_content_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004772 RTC_LOG(LS_ERROR) << "UseCandidate: Invalid candidate media index.";
Steve Anton75737c02017-11-06 10:37:17 -08004773 return false;
4774 }
4775
4776 cricket::ContentInfo content =
4777 remote_description()->description()->contents()[mediacontent_index];
4778 std::vector<cricket::Candidate> candidates;
4779 candidates.push_back(candidate->candidate());
4780 // Invoking BaseSession method to handle remote candidates.
4781 std::string error;
4782 if (transport_controller_->AddRemoteCandidates(content.name, candidates,
4783 &error)) {
4784 // Candidates successfully submitted for checking.
4785 if (ice_connection_state_ == PeerConnectionInterface::kIceConnectionNew ||
4786 ice_connection_state_ ==
4787 PeerConnectionInterface::kIceConnectionDisconnected) {
4788 // If state is New, then the session has just gotten its first remote ICE
4789 // candidates, so go to Checking.
4790 // If state is Disconnected, the session is re-using old candidates or
4791 // receiving additional ones, so go to Checking.
4792 // If state is Connected, stay Connected.
4793 // TODO(bemasc): If state is Connected, and the new candidates are for a
4794 // newly added transport, then the state actually _should_ move to
4795 // checking. Add a way to distinguish that case.
4796 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
4797 }
4798 // TODO(bemasc): If state is Completed, go back to Connected.
4799 } else {
4800 if (!error.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004801 RTC_LOG(LS_WARNING) << error;
Steve Anton75737c02017-11-06 10:37:17 -08004802 }
4803 }
4804 return true;
4805}
4806
4807void PeerConnection::RemoveUnusedChannels(const SessionDescription* desc) {
Steve Anton75737c02017-11-06 10:37:17 -08004808 // Destroy video channel first since it may have a pointer to the
4809 // voice channel.
4810 const cricket::ContentInfo* video_info = cricket::GetFirstVideoContent(desc);
Steve Anton6fec8802017-12-04 10:37:29 -08004811 if (!video_info || video_info->rejected) {
4812 DestroyTransceiverChannel(GetVideoTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08004813 }
4814
Steve Anton6fec8802017-12-04 10:37:29 -08004815 const cricket::ContentInfo* audio_info = cricket::GetFirstAudioContent(desc);
4816 if (!audio_info || audio_info->rejected) {
4817 DestroyTransceiverChannel(GetAudioTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08004818 }
4819
4820 const cricket::ContentInfo* data_info = cricket::GetFirstDataContent(desc);
4821 if (!data_info || data_info->rejected) {
Steve Anton6fec8802017-12-04 10:37:29 -08004822 DestroyDataChannel();
Steve Anton75737c02017-11-06 10:37:17 -08004823 }
4824}
4825
Steve Antoneda6ccd2017-12-04 10:21:55 -08004826std::string PeerConnection::GetTransportNameForMediaSection(
4827 const std::string& mid,
4828 const cricket::ContentGroup* bundle_group) const {
4829 if (!bundle_group) {
4830 return mid;
Steve Anton75737c02017-11-06 10:37:17 -08004831 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08004832 const std::string* first_content_name = bundle_group->FirstContentName();
Steve Anton75737c02017-11-06 10:37:17 -08004833 if (!first_content_name) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004834 RTC_LOG(LS_WARNING) << "Tried to BUNDLE with no contents.";
Steve Antoneda6ccd2017-12-04 10:21:55 -08004835 return mid;
Steve Anton75737c02017-11-06 10:37:17 -08004836 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08004837 if (!bundle_group->HasContentName(mid)) {
4838 RTC_LOG(LS_WARNING) << mid << " is not part of any bundle group";
4839 return mid;
Steve Anton75737c02017-11-06 10:37:17 -08004840 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08004841 RTC_LOG(LS_INFO) << "Bundling " << mid << " on " << *first_content_name;
4842 return *first_content_name;
Steve Anton75737c02017-11-06 10:37:17 -08004843}
4844
Steve Antondcc3c022017-12-22 16:02:54 -08004845RTCErrorOr<const cricket::ContentGroup*> PeerConnection::GetEarlyBundleGroup(
4846 const SessionDescription& desc) const {
Steve Anton75737c02017-11-06 10:37:17 -08004847 const cricket::ContentGroup* bundle_group = nullptr;
4848 if (configuration_.bundle_policy ==
4849 PeerConnectionInterface::kBundlePolicyMaxBundle) {
Steve Antondcc3c022017-12-22 16:02:54 -08004850 bundle_group = desc.GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton75737c02017-11-06 10:37:17 -08004851 if (!bundle_group) {
Steve Anton8a006912017-12-04 15:25:56 -08004852 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
4853 "max-bundle configured but session description "
4854 "has no BUNDLE group");
Steve Anton75737c02017-11-06 10:37:17 -08004855 }
4856 }
Steve Antondcc3c022017-12-22 16:02:54 -08004857 return std::move(bundle_group);
4858}
4859
4860RTCError PeerConnection::CreateChannels(const SessionDescription& desc) {
4861 auto bundle_group_or_error = GetEarlyBundleGroup(desc);
4862 if (!bundle_group_or_error.ok()) {
4863 return bundle_group_or_error.MoveError();
4864 }
4865 const cricket::ContentGroup* bundle_group = bundle_group_or_error.MoveValue();
Steve Anton75737c02017-11-06 10:37:17 -08004866
Steve Antoneda6ccd2017-12-04 10:21:55 -08004867 // Creating the media channels and transport proxies.
Steve Antondcc3c022017-12-22 16:02:54 -08004868 const cricket::ContentInfo* voice = cricket::GetFirstAudioContent(&desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08004869 if (voice && !voice->rejected &&
4870 !GetAudioTransceiver()->internal()->channel()) {
4871 cricket::VoiceChannel* voice_channel = CreateVoiceChannel(
4872 voice->name,
4873 GetTransportNameForMediaSection(voice->name, bundle_group));
4874 if (!voice_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08004875 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
4876 "Failed to create voice channel.");
Steve Antoneda6ccd2017-12-04 10:21:55 -08004877 }
4878 GetAudioTransceiver()->internal()->SetChannel(voice_channel);
4879 }
4880
Steve Antondcc3c022017-12-22 16:02:54 -08004881 const cricket::ContentInfo* video = cricket::GetFirstVideoContent(&desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08004882 if (video && !video->rejected &&
4883 !GetVideoTransceiver()->internal()->channel()) {
4884 cricket::VideoChannel* video_channel = CreateVideoChannel(
4885 video->name,
4886 GetTransportNameForMediaSection(video->name, bundle_group));
4887 if (!video_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08004888 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
4889 "Failed to create video channel.");
Steve Anton75737c02017-11-06 10:37:17 -08004890 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08004891 GetVideoTransceiver()->internal()->SetChannel(video_channel);
Steve Anton75737c02017-11-06 10:37:17 -08004892 }
4893
Steve Antondcc3c022017-12-22 16:02:54 -08004894 const cricket::ContentInfo* data = cricket::GetFirstDataContent(&desc);
Steve Anton75737c02017-11-06 10:37:17 -08004895 if (data_channel_type_ != cricket::DCT_NONE && data && !data->rejected &&
4896 !rtp_data_channel_ && !sctp_transport_) {
Steve Antoneda6ccd2017-12-04 10:21:55 -08004897 if (!CreateDataChannel(data->name, GetTransportNameForMediaSection(
4898 data->name, bundle_group))) {
Steve Anton8a006912017-12-04 15:25:56 -08004899 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
4900 "Failed to create data channel.");
Steve Anton75737c02017-11-06 10:37:17 -08004901 }
4902 }
4903
Steve Anton8a006912017-12-04 15:25:56 -08004904 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08004905}
4906
Steve Anton4171afb2017-11-20 10:20:22 -08004907// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08004908cricket::VoiceChannel* PeerConnection::CreateVoiceChannel(
4909 const std::string& mid,
4910 const std::string& transport_name) {
Steve Anton75737c02017-11-06 10:37:17 -08004911 cricket::DtlsTransportInternal* rtp_dtls_transport =
4912 transport_controller_->CreateDtlsTransport(
4913 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4914 cricket::DtlsTransportInternal* rtcp_dtls_transport = nullptr;
4915 if (configuration_.rtcp_mux_policy !=
4916 PeerConnectionInterface::kRtcpMuxPolicyRequire) {
4917 rtcp_dtls_transport = transport_controller_->CreateDtlsTransport(
4918 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
4919 }
4920
4921 cricket::VoiceChannel* voice_channel = channel_manager()->CreateVoiceChannel(
4922 call_.get(), configuration_.media_config, rtp_dtls_transport,
Steve Antoneda6ccd2017-12-04 10:21:55 -08004923 rtcp_dtls_transport, signaling_thread(), mid, SrtpRequired(),
4924 audio_options_);
Steve Anton75737c02017-11-06 10:37:17 -08004925 if (!voice_channel) {
4926 transport_controller_->DestroyDtlsTransport(
4927 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4928 if (rtcp_dtls_transport) {
4929 transport_controller_->DestroyDtlsTransport(
4930 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
4931 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08004932 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08004933 }
Steve Anton75737c02017-11-06 10:37:17 -08004934 voice_channel->SignalRtcpMuxFullyActive.connect(
4935 this, &PeerConnection::DestroyRtcpTransport_n);
4936 voice_channel->SignalDtlsSrtpSetupFailure.connect(
4937 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08004938 voice_channel->SignalSentPacket.connect(this,
4939 &PeerConnection::OnSentPacket_w);
Steve Anton4171afb2017-11-20 10:20:22 -08004940
Steve Antoneda6ccd2017-12-04 10:21:55 -08004941 return voice_channel;
Steve Anton75737c02017-11-06 10:37:17 -08004942}
4943
Steve Anton4171afb2017-11-20 10:20:22 -08004944// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08004945cricket::VideoChannel* PeerConnection::CreateVideoChannel(
4946 const std::string& mid,
4947 const std::string& transport_name) {
Steve Anton75737c02017-11-06 10:37:17 -08004948 cricket::DtlsTransportInternal* rtp_dtls_transport =
4949 transport_controller_->CreateDtlsTransport(
4950 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4951 cricket::DtlsTransportInternal* rtcp_dtls_transport = nullptr;
4952 if (configuration_.rtcp_mux_policy !=
4953 PeerConnectionInterface::kRtcpMuxPolicyRequire) {
4954 rtcp_dtls_transport = transport_controller_->CreateDtlsTransport(
4955 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
4956 }
4957
4958 cricket::VideoChannel* video_channel = channel_manager()->CreateVideoChannel(
4959 call_.get(), configuration_.media_config, rtp_dtls_transport,
Steve Antoneda6ccd2017-12-04 10:21:55 -08004960 rtcp_dtls_transport, signaling_thread(), mid, SrtpRequired(),
4961 video_options_);
Steve Anton75737c02017-11-06 10:37:17 -08004962
4963 if (!video_channel) {
4964 transport_controller_->DestroyDtlsTransport(
4965 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4966 if (rtcp_dtls_transport) {
4967 transport_controller_->DestroyDtlsTransport(
4968 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
4969 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08004970 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08004971 }
Steve Anton75737c02017-11-06 10:37:17 -08004972 video_channel->SignalRtcpMuxFullyActive.connect(
4973 this, &PeerConnection::DestroyRtcpTransport_n);
4974 video_channel->SignalDtlsSrtpSetupFailure.connect(
4975 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08004976 video_channel->SignalSentPacket.connect(this,
4977 &PeerConnection::OnSentPacket_w);
Steve Anton4171afb2017-11-20 10:20:22 -08004978
Steve Antoneda6ccd2017-12-04 10:21:55 -08004979 return video_channel;
Steve Anton75737c02017-11-06 10:37:17 -08004980}
4981
Steve Antoneda6ccd2017-12-04 10:21:55 -08004982bool PeerConnection::CreateDataChannel(const std::string& mid,
4983 const std::string& transport_name) {
Steve Anton75737c02017-11-06 10:37:17 -08004984 bool sctp = (data_channel_type_ == cricket::DCT_SCTP);
4985 if (sctp) {
4986 if (!sctp_factory_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004987 RTC_LOG(LS_ERROR)
Steve Anton75737c02017-11-06 10:37:17 -08004988 << "Trying to create SCTP transport, but didn't compile with "
4989 "SCTP support (HAVE_SCTP)";
4990 return false;
4991 }
4992 if (!network_thread()->Invoke<bool>(
4993 RTC_FROM_HERE, rtc::Bind(&PeerConnection::CreateSctpTransport_n,
Steve Antoneda6ccd2017-12-04 10:21:55 -08004994 this, mid, transport_name))) {
Steve Anton75737c02017-11-06 10:37:17 -08004995 return false;
4996 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08004997 for (const auto& channel : sctp_data_channels_) {
4998 channel->OnTransportChannelCreated();
4999 }
Steve Anton75737c02017-11-06 10:37:17 -08005000 } else {
Steve Anton75737c02017-11-06 10:37:17 -08005001 cricket::DtlsTransportInternal* rtp_dtls_transport =
5002 transport_controller_->CreateDtlsTransport(
5003 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5004 cricket::DtlsTransportInternal* rtcp_dtls_transport = nullptr;
5005 if (configuration_.rtcp_mux_policy !=
5006 PeerConnectionInterface::kRtcpMuxPolicyRequire) {
5007 rtcp_dtls_transport = transport_controller_->CreateDtlsTransport(
5008 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
5009 }
5010
5011 rtp_data_channel_ = channel_manager()->CreateRtpDataChannel(
5012 configuration_.media_config, rtp_dtls_transport, rtcp_dtls_transport,
Steve Antoneda6ccd2017-12-04 10:21:55 -08005013 signaling_thread(), mid, SrtpRequired());
Steve Anton75737c02017-11-06 10:37:17 -08005014
5015 if (!rtp_data_channel_) {
5016 transport_controller_->DestroyDtlsTransport(
5017 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5018 if (rtcp_dtls_transport) {
5019 transport_controller_->DestroyDtlsTransport(
5020 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
5021 }
5022 return false;
5023 }
5024
5025 rtp_data_channel_->SignalRtcpMuxFullyActive.connect(
5026 this, &PeerConnection::DestroyRtcpTransport_n);
5027 rtp_data_channel_->SignalDtlsSrtpSetupFailure.connect(
5028 this, &PeerConnection::OnDtlsSrtpSetupFailure);
5029 rtp_data_channel_->SignalSentPacket.connect(
5030 this, &PeerConnection::OnSentPacket_w);
5031 }
5032
Steve Anton75737c02017-11-06 10:37:17 -08005033 return true;
5034}
5035
5036Call::Stats PeerConnection::GetCallStats() {
5037 if (!worker_thread()->IsCurrent()) {
5038 return worker_thread()->Invoke<Call::Stats>(
5039 RTC_FROM_HERE, rtc::Bind(&PeerConnection::GetCallStats, this));
5040 }
5041 if (call_) {
5042 return call_->GetStats();
5043 } else {
5044 return Call::Stats();
5045 }
5046}
5047
5048std::unique_ptr<SessionStats> PeerConnection::GetSessionStats_n(
5049 const ChannelNamePairs& channel_name_pairs) {
5050 RTC_DCHECK(network_thread()->IsCurrent());
5051 std::unique_ptr<SessionStats> session_stats(new SessionStats());
5052 for (const auto channel_name_pair :
5053 {&channel_name_pairs.voice, &channel_name_pairs.video,
5054 &channel_name_pairs.data}) {
5055 if (*channel_name_pair) {
5056 cricket::TransportStats transport_stats;
5057 if (!transport_controller_->GetStats((*channel_name_pair)->transport_name,
5058 &transport_stats)) {
5059 return nullptr;
5060 }
Steve Anton75737c02017-11-06 10:37:17 -08005061 session_stats->transport_stats[(*channel_name_pair)->transport_name] =
5062 std::move(transport_stats);
5063 }
5064 }
5065 return session_stats;
5066}
5067
5068bool PeerConnection::CreateSctpTransport_n(const std::string& content_name,
5069 const std::string& transport_name) {
5070 RTC_DCHECK(network_thread()->IsCurrent());
5071 RTC_DCHECK(sctp_factory_);
5072 cricket::DtlsTransportInternal* tc =
5073 transport_controller_->CreateDtlsTransport_n(
5074 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5075 sctp_transport_ = sctp_factory_->CreateSctpTransport(tc);
5076 RTC_DCHECK(sctp_transport_);
5077 sctp_invoker_.reset(new rtc::AsyncInvoker());
5078 sctp_transport_->SignalReadyToSendData.connect(
5079 this, &PeerConnection::OnSctpTransportReadyToSendData_n);
5080 sctp_transport_->SignalDataReceived.connect(
5081 this, &PeerConnection::OnSctpTransportDataReceived_n);
5082 sctp_transport_->SignalStreamClosedRemotely.connect(
5083 this, &PeerConnection::OnSctpStreamClosedRemotely_n);
Oskar Sundbom9b28a032017-11-16 10:53:30 +01005084 sctp_transport_name_ = transport_name;
5085 sctp_content_name_ = content_name;
Steve Anton75737c02017-11-06 10:37:17 -08005086 return true;
5087}
5088
5089void PeerConnection::ChangeSctpTransport_n(const std::string& transport_name) {
5090 RTC_DCHECK(network_thread()->IsCurrent());
5091 RTC_DCHECK(sctp_transport_);
5092 RTC_DCHECK(sctp_transport_name_);
5093 std::string old_sctp_transport_name = *sctp_transport_name_;
Oskar Sundbom9b28a032017-11-16 10:53:30 +01005094 sctp_transport_name_ = transport_name;
Steve Anton75737c02017-11-06 10:37:17 -08005095 cricket::DtlsTransportInternal* tc =
5096 transport_controller_->CreateDtlsTransport_n(
5097 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5098 sctp_transport_->SetTransportChannel(tc);
5099 transport_controller_->DestroyDtlsTransport_n(
5100 old_sctp_transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5101}
5102
5103void PeerConnection::DestroySctpTransport_n() {
5104 RTC_DCHECK(network_thread()->IsCurrent());
5105 sctp_transport_.reset(nullptr);
Taylor Brandstetter389a97c2018-01-03 16:26:06 -08005106 transport_controller_->DestroyDtlsTransport_n(
5107 *sctp_transport_name_, cricket::ICE_CANDIDATE_COMPONENT_RTP);
Steve Anton75737c02017-11-06 10:37:17 -08005108 sctp_content_name_.reset();
5109 sctp_transport_name_.reset();
5110 sctp_invoker_.reset(nullptr);
5111 sctp_ready_to_send_data_ = false;
5112}
5113
5114void PeerConnection::OnSctpTransportReadyToSendData_n() {
5115 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5116 RTC_DCHECK(network_thread()->IsCurrent());
5117 // Note: Cannot use rtc::Bind here because it will grab a reference to
5118 // PeerConnection and potentially cause PeerConnection to live longer than
5119 // expected. It is safe not to grab a reference since the sctp_invoker_ will
5120 // be destroyed before PeerConnection is destroyed, and at that point all
5121 // pending tasks will be cleared.
5122 sctp_invoker_->AsyncInvoke<void>(RTC_FROM_HERE, signaling_thread(), [this] {
5123 OnSctpTransportReadyToSendData_s(true);
5124 });
5125}
5126
5127void PeerConnection::OnSctpTransportReadyToSendData_s(bool ready) {
5128 RTC_DCHECK(signaling_thread()->IsCurrent());
5129 sctp_ready_to_send_data_ = ready;
5130 SignalSctpReadyToSendData(ready);
5131}
5132
5133void PeerConnection::OnSctpTransportDataReceived_n(
5134 const cricket::ReceiveDataParams& params,
5135 const rtc::CopyOnWriteBuffer& payload) {
5136 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5137 RTC_DCHECK(network_thread()->IsCurrent());
5138 // Note: Cannot use rtc::Bind here because it will grab a reference to
5139 // PeerConnection and potentially cause PeerConnection to live longer than
5140 // expected. It is safe not to grab a reference since the sctp_invoker_ will
5141 // be destroyed before PeerConnection is destroyed, and at that point all
5142 // pending tasks will be cleared.
5143 sctp_invoker_->AsyncInvoke<void>(
5144 RTC_FROM_HERE, signaling_thread(), [this, params, payload] {
5145 OnSctpTransportDataReceived_s(params, payload);
5146 });
5147}
5148
5149void PeerConnection::OnSctpTransportDataReceived_s(
5150 const cricket::ReceiveDataParams& params,
5151 const rtc::CopyOnWriteBuffer& payload) {
5152 RTC_DCHECK(signaling_thread()->IsCurrent());
5153 if (params.type == cricket::DMT_CONTROL && IsOpenMessage(payload)) {
5154 // Received OPEN message; parse and signal that a new data channel should
5155 // be created.
5156 std::string label;
5157 InternalDataChannelInit config;
5158 config.id = params.ssrc;
5159 if (!ParseDataChannelOpenMessage(payload, &label, &config)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005160 RTC_LOG(LS_WARNING) << "Failed to parse the OPEN message for sid "
5161 << params.ssrc;
Steve Anton75737c02017-11-06 10:37:17 -08005162 return;
5163 }
5164 config.open_handshake_role = InternalDataChannelInit::kAcker;
5165 OnDataChannelOpenMessage(label, config);
5166 } else {
5167 // Otherwise just forward the signal.
5168 SignalSctpDataReceived(params, payload);
5169 }
5170}
5171
5172void PeerConnection::OnSctpStreamClosedRemotely_n(int sid) {
5173 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5174 RTC_DCHECK(network_thread()->IsCurrent());
5175 sctp_invoker_->AsyncInvoke<void>(
5176 RTC_FROM_HERE, signaling_thread(),
5177 rtc::Bind(&sigslot::signal1<int>::operator(),
5178 &SignalSctpStreamClosedRemotely, sid));
5179}
5180
5181// Returns false if bundle is enabled and rtcp_mux is disabled.
5182bool PeerConnection::ValidateBundleSettings(const SessionDescription* desc) {
5183 bool bundle_enabled = desc->HasGroup(cricket::GROUP_TYPE_BUNDLE);
5184 if (!bundle_enabled)
5185 return true;
5186
5187 const cricket::ContentGroup* bundle_group =
5188 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
5189 RTC_DCHECK(bundle_group != NULL);
5190
5191 const cricket::ContentInfos& contents = desc->contents();
5192 for (cricket::ContentInfos::const_iterator citer = contents.begin();
5193 citer != contents.end(); ++citer) {
5194 const cricket::ContentInfo* content = (&*citer);
5195 RTC_DCHECK(content != NULL);
5196 if (bundle_group->HasContentName(content->name) && !content->rejected &&
Steve Anton5adfafd2017-12-20 16:34:00 -08005197 content->type == MediaProtocolType::kRtp) {
Steve Anton75737c02017-11-06 10:37:17 -08005198 if (!HasRtcpMuxEnabled(content))
5199 return false;
5200 }
5201 }
5202 // RTCP-MUX is enabled in all the contents.
5203 return true;
5204}
5205
5206bool PeerConnection::HasRtcpMuxEnabled(const cricket::ContentInfo* content) {
Steve Antonb1c1de12017-12-21 15:14:30 -08005207 return content->media_description()->rtcp_mux();
Steve Anton75737c02017-11-06 10:37:17 -08005208}
5209
Steve Anton8a006912017-12-04 15:25:56 -08005210RTCError PeerConnection::ValidateSessionDescription(
Steve Anton75737c02017-11-06 10:37:17 -08005211 const SessionDescriptionInterface* sdesc,
Steve Anton8a006912017-12-04 15:25:56 -08005212 cricket::ContentSource source) {
Steve Antonf8470812017-12-04 10:46:21 -08005213 if (session_error() != SessionError::kNone) {
Steve Anton8a006912017-12-04 15:25:56 -08005214 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
Steve Anton75737c02017-11-06 10:37:17 -08005215 }
5216
5217 if (!sdesc || !sdesc->description()) {
Steve Anton8a006912017-12-04 15:25:56 -08005218 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidSdp);
Steve Anton75737c02017-11-06 10:37:17 -08005219 }
5220
Steve Anton3828c062017-12-06 10:34:51 -08005221 SdpType type = sdesc->GetType();
5222 if ((source == cricket::CS_LOCAL && !ExpectSetLocalDescription(type)) ||
5223 (source == cricket::CS_REMOTE && !ExpectSetRemoteDescription(type))) {
Steve Anton8a006912017-12-04 15:25:56 -08005224 LOG_AND_RETURN_ERROR(
5225 RTCErrorType::INVALID_PARAMETER,
5226 "Called in wrong state: " + GetSignalingStateString(signaling_state()));
Steve Anton75737c02017-11-06 10:37:17 -08005227 }
5228
5229 // Verify crypto settings.
5230 std::string crypto_error;
Steve Anton8a006912017-12-04 15:25:56 -08005231 if (webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED ||
5232 dtls_enabled_) {
5233 RTCError crypto_error = VerifyCrypto(sdesc->description(), dtls_enabled_);
5234 if (!crypto_error.ok()) {
5235 return crypto_error;
5236 }
Steve Anton75737c02017-11-06 10:37:17 -08005237 }
5238
5239 // Verify ice-ufrag and ice-pwd.
5240 if (!VerifyIceUfragPwdPresent(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08005241 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5242 kSdpWithoutIceUfragPwd);
Steve Anton75737c02017-11-06 10:37:17 -08005243 }
5244
5245 if (!ValidateBundleSettings(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08005246 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5247 kBundleWithoutRtcpMux);
Steve Anton75737c02017-11-06 10:37:17 -08005248 }
5249
5250 // TODO(skvlad): When the local rtcp-mux policy is Require, reject any
5251 // m-lines that do not rtcp-mux enabled.
5252
5253 // Verify m-lines in Answer when compared against Offer.
Steve Anton3828c062017-12-06 10:34:51 -08005254 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Anton75737c02017-11-06 10:37:17 -08005255 const cricket::SessionDescription* offer_desc =
5256 (source == cricket::CS_LOCAL) ? remote_description()->description()
5257 : local_description()->description();
5258 if (!MediaSectionsHaveSameCount(offer_desc, sdesc->description()) ||
5259 !MediaSectionsInSameOrder(offer_desc, sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08005260 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5261 kMlineMismatchInAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08005262 }
5263 } else {
5264 const cricket::SessionDescription* current_desc = nullptr;
5265 if (source == cricket::CS_LOCAL && local_description()) {
5266 current_desc = local_description()->description();
5267 } else if (source == cricket::CS_REMOTE && remote_description()) {
5268 current_desc = remote_description()->description();
5269 }
5270 // The re-offers should respect the order of m= sections in current
5271 // description. See RFC3264 Section 8 paragraph 4 for more details.
5272 if (current_desc &&
5273 !MediaSectionsInSameOrder(current_desc, sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08005274 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5275 kMlineMismatchInSubsequentOffer);
Steve Anton75737c02017-11-06 10:37:17 -08005276 }
5277 }
5278
Steve Anton8a006912017-12-04 15:25:56 -08005279 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08005280}
5281
Steve Anton3828c062017-12-06 10:34:51 -08005282bool PeerConnection::ExpectSetLocalDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08005283 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08005284 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08005285 return (state == PeerConnectionInterface::kStable) ||
5286 (state == PeerConnectionInterface::kHaveLocalOffer);
Steve Anton20393062017-12-04 16:24:52 -08005287 } else {
Steve Anton3828c062017-12-06 10:34:51 -08005288 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08005289 return (state == PeerConnectionInterface::kHaveRemoteOffer) ||
5290 (state == PeerConnectionInterface::kHaveLocalPrAnswer);
5291 }
5292}
5293
Steve Anton3828c062017-12-06 10:34:51 -08005294bool PeerConnection::ExpectSetRemoteDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08005295 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08005296 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08005297 return (state == PeerConnectionInterface::kStable) ||
5298 (state == PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton20393062017-12-04 16:24:52 -08005299 } else {
Steve Anton3828c062017-12-06 10:34:51 -08005300 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08005301 return (state == PeerConnectionInterface::kHaveLocalOffer) ||
5302 (state == PeerConnectionInterface::kHaveRemotePrAnswer);
5303 }
5304}
5305
Steve Antonf8470812017-12-04 10:46:21 -08005306const char* PeerConnection::SessionErrorToString(SessionError error) const {
5307 switch (error) {
5308 case SessionError::kNone:
5309 return "ERROR_NONE";
5310 case SessionError::kContent:
5311 return "ERROR_CONTENT";
5312 case SessionError::kTransport:
5313 return "ERROR_TRANSPORT";
5314 }
5315 RTC_NOTREACHED();
5316 return "";
5317}
5318
Steve Anton75737c02017-11-06 10:37:17 -08005319std::string PeerConnection::GetSessionErrorMsg() {
5320 std::ostringstream desc;
Steve Antonf8470812017-12-04 10:46:21 -08005321 desc << kSessionError << SessionErrorToString(session_error()) << ". ";
5322 desc << kSessionErrorDesc << session_error_desc() << ".";
Steve Anton75737c02017-11-06 10:37:17 -08005323 return desc.str();
5324}
5325
5326// We need to check the local/remote description for the Transport instead of
5327// the session, because a new Transport added during renegotiation may have
5328// them unset while the session has them set from the previous negotiation.
5329// Not doing so may trigger the auto generation of transport description and
5330// mess up DTLS identity information, ICE credential, etc.
5331bool PeerConnection::ReadyToUseRemoteCandidate(
5332 const IceCandidateInterface* candidate,
5333 const SessionDescriptionInterface* remote_desc,
5334 bool* valid) {
5335 *valid = true;
5336
5337 const SessionDescriptionInterface* current_remote_desc =
5338 remote_desc ? remote_desc : remote_description();
5339
5340 if (!current_remote_desc) {
5341 return false;
5342 }
5343
5344 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
5345 size_t remote_content_size =
5346 current_remote_desc->description()->contents().size();
5347 if (mediacontent_index >= remote_content_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005348 RTC_LOG(LS_ERROR)
5349 << "ReadyToUseRemoteCandidate: Invalid candidate media index "
5350 << mediacontent_index;
Steve Anton75737c02017-11-06 10:37:17 -08005351
5352 *valid = false;
5353 return false;
5354 }
5355
5356 cricket::ContentInfo content =
5357 current_remote_desc->description()->contents()[mediacontent_index];
5358
5359 const std::string transport_name = GetTransportName(content.name);
5360 if (transport_name.empty()) {
5361 return false;
5362 }
5363 return transport_controller_->ReadyForRemoteCandidates(transport_name);
5364}
5365
5366bool PeerConnection::SrtpRequired() const {
5367 return dtls_enabled_ ||
5368 webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED;
5369}
5370
5371void PeerConnection::OnTransportControllerGatheringState(
5372 cricket::IceGatheringState state) {
5373 RTC_DCHECK(signaling_thread()->IsCurrent());
5374 if (state == cricket::kIceGatheringGathering) {
5375 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringGathering);
5376 } else if (state == cricket::kIceGatheringComplete) {
5377 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringComplete);
5378 }
5379}
5380
5381void PeerConnection::ReportTransportStats() {
5382 // Use a set so we don't report the same stats twice if two channels share
5383 // a transport.
5384 std::set<std::string> transport_names;
5385 if (voice_channel()) {
5386 transport_names.insert(voice_channel()->transport_name());
5387 }
5388 if (video_channel()) {
5389 transport_names.insert(video_channel()->transport_name());
5390 }
5391 if (rtp_data_channel()) {
5392 transport_names.insert(rtp_data_channel()->transport_name());
5393 }
5394 if (sctp_transport_name_) {
5395 transport_names.insert(*sctp_transport_name_);
5396 }
5397 for (const auto& name : transport_names) {
5398 cricket::TransportStats stats;
5399 if (transport_controller_->GetStats(name, &stats)) {
5400 ReportBestConnectionState(stats);
5401 ReportNegotiatedCiphers(stats);
5402 }
5403 }
5404}
5405// Walk through the ConnectionInfos to gather best connection usage
5406// for IPv4 and IPv6.
5407void PeerConnection::ReportBestConnectionState(
5408 const cricket::TransportStats& stats) {
5409 RTC_DCHECK(metrics_observer());
5410 for (cricket::TransportChannelStatsList::const_iterator it =
5411 stats.channel_stats.begin();
5412 it != stats.channel_stats.end(); ++it) {
5413 for (cricket::ConnectionInfos::const_iterator it_info =
5414 it->connection_infos.begin();
5415 it_info != it->connection_infos.end(); ++it_info) {
5416 if (!it_info->best_connection) {
5417 continue;
5418 }
5419
5420 PeerConnectionEnumCounterType type = kPeerConnectionEnumCounterMax;
5421 const cricket::Candidate& local = it_info->local_candidate;
5422 const cricket::Candidate& remote = it_info->remote_candidate;
5423
5424 // Increment the counter for IceCandidatePairType.
5425 if (local.protocol() == cricket::TCP_PROTOCOL_NAME ||
5426 (local.type() == RELAY_PORT_TYPE &&
5427 local.relay_protocol() == cricket::TCP_PROTOCOL_NAME)) {
5428 type = kEnumCounterIceCandidatePairTypeTcp;
5429 } else if (local.protocol() == cricket::UDP_PROTOCOL_NAME) {
5430 type = kEnumCounterIceCandidatePairTypeUdp;
5431 } else {
5432 RTC_CHECK(0);
5433 }
5434 metrics_observer()->IncrementEnumCounter(
5435 type, GetIceCandidatePairCounter(local, remote),
5436 kIceCandidatePairMax);
5437
5438 // Increment the counter for IP type.
5439 if (local.address().family() == AF_INET) {
5440 metrics_observer()->IncrementEnumCounter(
5441 kEnumCounterAddressFamily, kBestConnections_IPv4,
5442 kPeerConnectionAddressFamilyCounter_Max);
5443
5444 } else if (local.address().family() == AF_INET6) {
5445 metrics_observer()->IncrementEnumCounter(
5446 kEnumCounterAddressFamily, kBestConnections_IPv6,
5447 kPeerConnectionAddressFamilyCounter_Max);
5448 } else {
5449 RTC_CHECK(0);
5450 }
5451
5452 return;
5453 }
5454 }
5455}
5456
5457void PeerConnection::ReportNegotiatedCiphers(
5458 const cricket::TransportStats& stats) {
5459 RTC_DCHECK(metrics_observer());
5460 if (!dtls_enabled_ || stats.channel_stats.empty()) {
5461 return;
5462 }
5463
5464 int srtp_crypto_suite = stats.channel_stats[0].srtp_crypto_suite;
5465 int ssl_cipher_suite = stats.channel_stats[0].ssl_cipher_suite;
5466 if (srtp_crypto_suite == rtc::SRTP_INVALID_CRYPTO_SUITE &&
5467 ssl_cipher_suite == rtc::TLS_NULL_WITH_NULL_NULL) {
5468 return;
5469 }
5470
5471 PeerConnectionEnumCounterType srtp_counter_type;
5472 PeerConnectionEnumCounterType ssl_counter_type;
5473 if (stats.transport_name == cricket::CN_AUDIO) {
5474 srtp_counter_type = kEnumCounterAudioSrtpCipher;
5475 ssl_counter_type = kEnumCounterAudioSslCipher;
5476 } else if (stats.transport_name == cricket::CN_VIDEO) {
5477 srtp_counter_type = kEnumCounterVideoSrtpCipher;
5478 ssl_counter_type = kEnumCounterVideoSslCipher;
5479 } else if (stats.transport_name == cricket::CN_DATA) {
5480 srtp_counter_type = kEnumCounterDataSrtpCipher;
5481 ssl_counter_type = kEnumCounterDataSslCipher;
5482 } else {
5483 RTC_NOTREACHED();
5484 return;
5485 }
5486
5487 if (srtp_crypto_suite != rtc::SRTP_INVALID_CRYPTO_SUITE) {
5488 metrics_observer()->IncrementSparseEnumCounter(srtp_counter_type,
5489 srtp_crypto_suite);
5490 }
5491 if (ssl_cipher_suite != rtc::TLS_NULL_WITH_NULL_NULL) {
5492 metrics_observer()->IncrementSparseEnumCounter(ssl_counter_type,
5493 ssl_cipher_suite);
5494 }
5495}
5496
5497void PeerConnection::OnSentPacket_w(const rtc::SentPacket& sent_packet) {
5498 RTC_DCHECK(worker_thread()->IsCurrent());
5499 RTC_DCHECK(call_);
5500 call_->OnSentPacket(sent_packet);
5501}
5502
5503const std::string PeerConnection::GetTransportName(
5504 const std::string& content_name) {
5505 cricket::BaseChannel* channel = GetChannel(content_name);
Steve Anton6fec8802017-12-04 10:37:29 -08005506 if (channel) {
5507 return channel->transport_name();
Steve Anton75737c02017-11-06 10:37:17 -08005508 }
Steve Anton6fec8802017-12-04 10:37:29 -08005509 if (sctp_transport_) {
5510 RTC_DCHECK(sctp_content_name_);
5511 RTC_DCHECK(sctp_transport_name_);
5512 if (content_name == *sctp_content_name_) {
5513 return *sctp_transport_name_;
5514 }
5515 }
5516 // Return an empty string if failed to retrieve the transport name.
5517 return "";
Steve Anton75737c02017-11-06 10:37:17 -08005518}
5519
5520void PeerConnection::DestroyRtcpTransport_n(const std::string& transport_name) {
5521 RTC_DCHECK(network_thread()->IsCurrent());
5522 transport_controller_->DestroyDtlsTransport_n(
5523 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
5524}
5525
Steve Anton6fec8802017-12-04 10:37:29 -08005526void PeerConnection::DestroyTransceiverChannel(
5527 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
5528 transceiver) {
5529 RTC_DCHECK(transceiver);
Steve Anton75737c02017-11-06 10:37:17 -08005530
Steve Anton6fec8802017-12-04 10:37:29 -08005531 cricket::BaseChannel* channel = transceiver->internal()->channel();
5532 if (channel) {
5533 transceiver->internal()->SetChannel(nullptr);
5534 DestroyBaseChannel(channel);
Steve Anton75737c02017-11-06 10:37:17 -08005535 }
5536}
5537
5538void PeerConnection::DestroyDataChannel() {
Steve Anton6fec8802017-12-04 10:37:29 -08005539 if (rtp_data_channel_) {
5540 OnDataChannelDestroyed();
5541 DestroyBaseChannel(rtp_data_channel_);
5542 rtp_data_channel_ = nullptr;
5543 }
5544
5545 // Note: Cannot use rtc::Bind to create a functor to invoke because it will
5546 // grab a reference to this PeerConnection. If this is called from the
5547 // PeerConnection destructor, the RefCountedObject vtable will have already
5548 // been destroyed (since it is a subclass of PeerConnection) and using
5549 // rtc::Bind will cause "Pure virtual function called" error to appear.
5550
5551 if (sctp_transport_) {
5552 OnDataChannelDestroyed();
5553 network_thread()->Invoke<void>(RTC_FROM_HERE,
5554 [this] { DestroySctpTransport_n(); });
5555 }
5556}
5557
5558void PeerConnection::DestroyBaseChannel(cricket::BaseChannel* channel) {
5559 RTC_DCHECK(channel);
5560 RTC_DCHECK(channel->rtp_dtls_transport());
5561
5562 // Need to cache these before destroying the base channel so that we do not
5563 // access uninitialized memory.
5564 const std::string transport_name =
5565 channel->rtp_dtls_transport()->transport_name();
5566 const bool need_to_delete_rtcp = (channel->rtcp_dtls_transport() != nullptr);
5567
5568 switch (channel->media_type()) {
5569 case cricket::MEDIA_TYPE_AUDIO:
5570 channel_manager()->DestroyVoiceChannel(
5571 static_cast<cricket::VoiceChannel*>(channel));
5572 break;
5573 case cricket::MEDIA_TYPE_VIDEO:
5574 channel_manager()->DestroyVideoChannel(
5575 static_cast<cricket::VideoChannel*>(channel));
5576 break;
5577 case cricket::MEDIA_TYPE_DATA:
5578 channel_manager()->DestroyRtpDataChannel(
5579 static_cast<cricket::RtpDataChannel*>(channel));
5580 break;
5581 default:
5582 RTC_NOTREACHED() << "Unknown media type: " << channel->media_type();
5583 break;
5584 }
5585
5586 // |channel| can no longer be used.
5587
Steve Anton75737c02017-11-06 10:37:17 -08005588 transport_controller_->DestroyDtlsTransport(
5589 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5590 if (need_to_delete_rtcp) {
5591 transport_controller_->DestroyDtlsTransport(
5592 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
5593 }
5594}
5595
Harald Alvestrand89061872018-01-02 14:08:34 +01005596void PeerConnection::ClearStatsCache() {
5597 if (stats_collector_) {
5598 stats_collector_->ClearCachedStatsReport();
5599 }
5600}
5601
henrike@webrtc.org28e20752013-07-10 00:45:36 +00005602} // namespace webrtc