blob: 0596869eba9440230c5494923138485015785707 [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.
Harald Alvestrand194939b2018-01-24 16:04:13 +0100367RTCError VerifyCrypto(const SessionDescription* desc,
368 bool dtls_enabled,
369 rtc::scoped_refptr<webrtc::UMAObserver> uma_observer) {
Steve Anton75737c02017-11-06 10:37:17 -0800370 const cricket::ContentGroup* bundle =
371 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton8a006912017-12-04 15:25:56 -0800372 for (const cricket::ContentInfo& content_info : desc->contents()) {
373 if (content_info.rejected) {
Steve Anton75737c02017-11-06 10:37:17 -0800374 continue;
375 }
Steve Anton8a006912017-12-04 15:25:56 -0800376 const std::string& mid = content_info.name;
377 if (bundle && bundle->HasContentName(mid) &&
378 mid != *(bundle->FirstContentName())) {
Steve Anton75737c02017-11-06 10:37:17 -0800379 // This isn't the first media section in the BUNDLE group, so it's not
380 // required to have crypto attributes, since only the crypto attributes
381 // from the first section actually get used.
382 continue;
383 }
384
385 // If the content isn't rejected or bundled into another m= section, crypto
386 // must be present.
Steve Antonb1c1de12017-12-21 15:14:30 -0800387 const MediaContentDescription* media = content_info.media_description();
Steve Anton8a006912017-12-04 15:25:56 -0800388 const TransportInfo* tinfo = desc->GetTransportInfoByName(mid);
Steve Anton75737c02017-11-06 10:37:17 -0800389 if (!media || !tinfo) {
390 // Something is not right.
Steve Anton8a006912017-12-04 15:25:56 -0800391 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidSdp);
Steve Anton75737c02017-11-06 10:37:17 -0800392 }
393 if (dtls_enabled) {
394 if (!tinfo->description.identity_fingerprint) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100395 RTC_LOG(LS_WARNING)
396 << "Session description must have DTLS fingerprint if "
397 "DTLS enabled.";
Steve Anton8a006912017-12-04 15:25:56 -0800398 return RTCError(RTCErrorType::INVALID_PARAMETER,
399 kSdpWithoutDtlsFingerprint);
Steve Anton75737c02017-11-06 10:37:17 -0800400 }
Harald Alvestrand194939b2018-01-24 16:04:13 +0100401 if (uma_observer) {
402 uma_observer->IncrementEnumCounter(webrtc::kEnumCounterKeyProtocol,
403 webrtc::kEnumCounterKeyProtocolDtls,
404 webrtc::kEnumCounterKeyProtocolMax);
405 }
Steve Anton75737c02017-11-06 10:37:17 -0800406 } else {
407 if (media->cryptos().empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100408 RTC_LOG(LS_WARNING)
Steve Anton75737c02017-11-06 10:37:17 -0800409 << "Session description must have SDES when DTLS disabled.";
Steve Anton8a006912017-12-04 15:25:56 -0800410 return RTCError(RTCErrorType::INVALID_PARAMETER, kSdpWithoutSdesCrypto);
Steve Anton75737c02017-11-06 10:37:17 -0800411 }
Harald Alvestrand194939b2018-01-24 16:04:13 +0100412 if (uma_observer) {
413 uma_observer->IncrementEnumCounter(webrtc::kEnumCounterKeyProtocol,
414 webrtc::kEnumCounterKeyProtocolSdes,
415 webrtc::kEnumCounterKeyProtocolMax);
416 }
Steve Anton75737c02017-11-06 10:37:17 -0800417 }
418 }
Steve Anton8a006912017-12-04 15:25:56 -0800419 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -0800420}
421
422// Checks that each non-rejected content has ice-ufrag and ice-pwd set, unless
423// it's in a BUNDLE group, in which case only the BUNDLE-tag section (first
424// media section/description in the BUNDLE group) needs a ufrag and pwd.
425bool VerifyIceUfragPwdPresent(const SessionDescription* desc) {
426 const cricket::ContentGroup* bundle =
427 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton8a006912017-12-04 15:25:56 -0800428 for (const cricket::ContentInfo& content_info : desc->contents()) {
429 if (content_info.rejected) {
Steve Anton75737c02017-11-06 10:37:17 -0800430 continue;
431 }
Steve Anton8a006912017-12-04 15:25:56 -0800432 const std::string& mid = content_info.name;
433 if (bundle && bundle->HasContentName(mid) &&
434 mid != *(bundle->FirstContentName())) {
Steve Anton75737c02017-11-06 10:37:17 -0800435 // This isn't the first media section in the BUNDLE group, so it's not
436 // required to have ufrag/password, since only the ufrag/password from
437 // the first section actually get used.
438 continue;
439 }
440
441 // If the content isn't rejected or bundled into another m= section,
442 // ice-ufrag and ice-pwd must be present.
Steve Anton8a006912017-12-04 15:25:56 -0800443 const TransportInfo* tinfo = desc->GetTransportInfoByName(mid);
Steve Anton75737c02017-11-06 10:37:17 -0800444 if (!tinfo) {
445 // Something is not right.
Mirko Bonadei675513b2017-11-09 11:09:25 +0100446 RTC_LOG(LS_ERROR) << kInvalidSdp;
Steve Anton75737c02017-11-06 10:37:17 -0800447 return false;
448 }
449 if (tinfo->description.ice_ufrag.empty() ||
450 tinfo->description.ice_pwd.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100451 RTC_LOG(LS_ERROR) << "Session description must have ice ufrag and pwd.";
Steve Anton75737c02017-11-06 10:37:17 -0800452 return false;
453 }
454 }
455 return true;
456}
457
458bool GetTrackIdBySsrc(const SessionDescription* session_description,
459 uint32_t ssrc,
460 std::string* track_id) {
461 RTC_DCHECK(track_id != NULL);
462
Steve Antonb1c1de12017-12-21 15:14:30 -0800463 const cricket::AudioContentDescription* audio_desc =
464 cricket::GetFirstAudioContentDescription(session_description);
465 if (audio_desc) {
466 const auto* found = cricket::GetStreamBySsrc(audio_desc->streams(), ssrc);
Steve Anton75737c02017-11-06 10:37:17 -0800467 if (found) {
468 *track_id = found->id;
469 return true;
470 }
471 }
472
Steve Antonb1c1de12017-12-21 15:14:30 -0800473 const cricket::VideoContentDescription* video_desc =
474 cricket::GetFirstVideoContentDescription(session_description);
475 if (video_desc) {
476 const auto* found = cricket::GetStreamBySsrc(video_desc->streams(), ssrc);
Steve Anton75737c02017-11-06 10:37:17 -0800477 if (found) {
478 *track_id = found->id;
479 return true;
480 }
481 }
482 return false;
483}
484
485// Get the SCTP port out of a SessionDescription.
486// Return -1 if not found.
487int GetSctpPort(const SessionDescription* session_description) {
Steve Antonb1c1de12017-12-21 15:14:30 -0800488 const cricket::DataContentDescription* data_desc =
489 GetFirstDataContentDescription(session_description);
490 RTC_DCHECK(data_desc);
491 if (!data_desc) {
Steve Anton75737c02017-11-06 10:37:17 -0800492 return -1;
493 }
Steve Anton75737c02017-11-06 10:37:17 -0800494 std::string value;
495 cricket::DataCodec match_pattern(cricket::kGoogleSctpDataCodecPlType,
496 cricket::kGoogleSctpDataCodecName);
Steve Antonb1c1de12017-12-21 15:14:30 -0800497 for (const cricket::DataCodec& codec : data_desc->codecs()) {
Steve Anton75737c02017-11-06 10:37:17 -0800498 if (!codec.Matches(match_pattern)) {
499 continue;
500 }
501 if (codec.GetParam(cricket::kCodecParamPort, &value)) {
502 return rtc::FromString<int>(value);
503 }
504 }
505 return -1;
506}
507
Steve Anton75737c02017-11-06 10:37:17 -0800508// Returns true if |new_desc| requests an ICE restart (i.e., new ufrag/pwd).
509bool CheckForRemoteIceRestart(const SessionDescriptionInterface* old_desc,
510 const SessionDescriptionInterface* new_desc,
511 const std::string& content_name) {
512 if (!old_desc) {
513 return false;
514 }
515 const SessionDescription* new_sd = new_desc->description();
516 const SessionDescription* old_sd = old_desc->description();
517 const ContentInfo* cinfo = new_sd->GetContentByName(content_name);
518 if (!cinfo || cinfo->rejected) {
519 return false;
520 }
521 // If the content isn't rejected, check if ufrag and password has changed.
522 const cricket::TransportDescription* new_transport_desc =
523 new_sd->GetTransportDescriptionByName(content_name);
524 const cricket::TransportDescription* old_transport_desc =
525 old_sd->GetTransportDescriptionByName(content_name);
526 if (!new_transport_desc || !old_transport_desc) {
527 // No transport description exists. This is not an ICE restart.
528 return false;
529 }
530 if (cricket::IceCredentialsChanged(
531 old_transport_desc->ice_ufrag, old_transport_desc->ice_pwd,
532 new_transport_desc->ice_ufrag, new_transport_desc->ice_pwd)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100533 RTC_LOG(LS_INFO) << "Remote peer requests ICE restart for " << content_name
534 << ".";
Steve Anton75737c02017-11-06 10:37:17 -0800535 return true;
536 }
537 return false;
538}
539
540} // namespace
541
Henrik Boström31638672017-11-23 17:48:32 +0100542// Upon completion, posts a task to execute the callback of the
543// SetSessionDescriptionObserver asynchronously on the same thread. At this
544// point, the state of the peer connection might no longer reflect the effects
545// of the SetRemoteDescription operation, as the peer connection could have been
546// modified during the post.
547// TODO(hbos): Remove this class once we remove the version of
548// PeerConnectionInterface::SetRemoteDescription() that takes a
549// SetSessionDescriptionObserver as an argument.
550class PeerConnection::SetRemoteDescriptionObserverAdapter
551 : public rtc::RefCountedObject<SetRemoteDescriptionObserverInterface> {
552 public:
553 SetRemoteDescriptionObserverAdapter(
554 rtc::scoped_refptr<PeerConnection> pc,
555 rtc::scoped_refptr<SetSessionDescriptionObserver> wrapper)
556 : pc_(std::move(pc)), wrapper_(std::move(wrapper)) {}
557
558 // SetRemoteDescriptionObserverInterface implementation.
559 void OnSetRemoteDescriptionComplete(RTCError error) override {
560 if (error.ok())
561 pc_->PostSetSessionDescriptionSuccess(wrapper_);
562 else
563 pc_->PostSetSessionDescriptionFailure(wrapper_, error.message());
564 }
565
566 private:
567 rtc::scoped_refptr<PeerConnection> pc_;
568 rtc::scoped_refptr<SetSessionDescriptionObserver> wrapper_;
569};
570
deadbeef293e9262017-01-11 12:28:30 -0800571bool PeerConnectionInterface::RTCConfiguration::operator==(
572 const PeerConnectionInterface::RTCConfiguration& o) const {
573 // This static_assert prevents us from accidentally breaking operator==.
Steve Anton300bf8e2017-07-14 10:13:10 -0700574 // Note: Order matters! Fields must be ordered the same as RTCConfiguration.
deadbeef293e9262017-01-11 12:28:30 -0800575 struct stuff_being_tested_for_equality {
Magnus Jedvert3beb2072017-07-14 14:23:56 +0000576 IceServers servers;
Steve Anton300bf8e2017-07-14 10:13:10 -0700577 IceTransportsType type;
deadbeef293e9262017-01-11 12:28:30 -0800578 BundlePolicy bundle_policy;
579 RtcpMuxPolicy rtcp_mux_policy;
Steve Anton300bf8e2017-07-14 10:13:10 -0700580 std::vector<rtc::scoped_refptr<rtc::RTCCertificate>> certificates;
581 int ice_candidate_pool_size;
582 bool disable_ipv6;
583 bool disable_ipv6_on_wifi;
deadbeefd21eab32017-07-26 16:50:11 -0700584 int max_ipv6_networks;
Steve Anton300bf8e2017-07-14 10:13:10 -0700585 bool enable_rtp_data_channel;
586 rtc::Optional<int> screencast_min_bitrate;
587 rtc::Optional<bool> combined_audio_video_bwe;
588 rtc::Optional<bool> enable_dtls_srtp;
deadbeef293e9262017-01-11 12:28:30 -0800589 TcpCandidatePolicy tcp_candidate_policy;
590 CandidateNetworkPolicy candidate_network_policy;
591 int audio_jitter_buffer_max_packets;
592 bool audio_jitter_buffer_fast_accelerate;
593 int ice_connection_receiving_timeout;
594 int ice_backup_candidate_pair_ping_interval;
595 ContinualGatheringPolicy continual_gathering_policy;
deadbeef293e9262017-01-11 12:28:30 -0800596 bool prioritize_most_likely_ice_candidate_pairs;
597 struct cricket::MediaConfig media_config;
deadbeef293e9262017-01-11 12:28:30 -0800598 bool prune_turn_ports;
599 bool presume_writable_when_fully_relayed;
600 bool enable_ice_renomination;
601 bool redetermine_role_on_ice_restart;
skvlad51072462017-02-02 11:50:14 -0800602 rtc::Optional<int> ice_check_min_interval;
Steve Anton300bf8e2017-07-14 10:13:10 -0700603 rtc::Optional<rtc::IntervalRange> ice_regather_interval_range;
Jonas Orelandbdcee282017-10-10 14:01:40 +0200604 webrtc::TurnCustomizer* turn_customizer;
Steve Anton79e79602017-11-20 10:25:56 -0800605 SdpSemantics sdp_semantics;
Qingsi Wang9a5c6f82018-02-01 10:38:40 -0800606 rtc::Optional<rtc::AdapterType> network_preference;
deadbeef293e9262017-01-11 12:28:30 -0800607 };
608 static_assert(sizeof(stuff_being_tested_for_equality) == sizeof(*this),
609 "Did you add something to RTCConfiguration and forget to "
610 "update operator==?");
611 return type == o.type && servers == o.servers &&
612 bundle_policy == o.bundle_policy &&
613 rtcp_mux_policy == o.rtcp_mux_policy &&
614 tcp_candidate_policy == o.tcp_candidate_policy &&
615 candidate_network_policy == o.candidate_network_policy &&
616 audio_jitter_buffer_max_packets == o.audio_jitter_buffer_max_packets &&
617 audio_jitter_buffer_fast_accelerate ==
618 o.audio_jitter_buffer_fast_accelerate &&
619 ice_connection_receiving_timeout ==
620 o.ice_connection_receiving_timeout &&
621 ice_backup_candidate_pair_ping_interval ==
622 o.ice_backup_candidate_pair_ping_interval &&
623 continual_gathering_policy == o.continual_gathering_policy &&
624 certificates == o.certificates &&
625 prioritize_most_likely_ice_candidate_pairs ==
626 o.prioritize_most_likely_ice_candidate_pairs &&
627 media_config == o.media_config && disable_ipv6 == o.disable_ipv6 &&
zhihuangb09b3f92017-03-07 14:40:51 -0800628 disable_ipv6_on_wifi == o.disable_ipv6_on_wifi &&
deadbeefd21eab32017-07-26 16:50:11 -0700629 max_ipv6_networks == o.max_ipv6_networks &&
deadbeef293e9262017-01-11 12:28:30 -0800630 enable_rtp_data_channel == o.enable_rtp_data_channel &&
deadbeef293e9262017-01-11 12:28:30 -0800631 screencast_min_bitrate == o.screencast_min_bitrate &&
632 combined_audio_video_bwe == o.combined_audio_video_bwe &&
633 enable_dtls_srtp == o.enable_dtls_srtp &&
634 ice_candidate_pool_size == o.ice_candidate_pool_size &&
635 prune_turn_ports == o.prune_turn_ports &&
636 presume_writable_when_fully_relayed ==
637 o.presume_writable_when_fully_relayed &&
638 enable_ice_renomination == o.enable_ice_renomination &&
skvlad51072462017-02-02 11:50:14 -0800639 redetermine_role_on_ice_restart == o.redetermine_role_on_ice_restart &&
Steve Anton300bf8e2017-07-14 10:13:10 -0700640 ice_check_min_interval == o.ice_check_min_interval &&
Jonas Orelandbdcee282017-10-10 14:01:40 +0200641 ice_regather_interval_range == o.ice_regather_interval_range &&
Steve Anton79e79602017-11-20 10:25:56 -0800642 turn_customizer == o.turn_customizer &&
Qingsi Wang9a5c6f82018-02-01 10:38:40 -0800643 sdp_semantics == o.sdp_semantics &&
644 network_preference == o.network_preference;
deadbeef293e9262017-01-11 12:28:30 -0800645}
646
647bool PeerConnectionInterface::RTCConfiguration::operator!=(
648 const PeerConnectionInterface::RTCConfiguration& o) const {
649 return !(*this == o);
deadbeef3edec7c2016-12-10 11:44:26 -0800650}
651
zhihuang8f65cdf2016-05-06 18:40:30 -0700652// Generate a RTCP CNAME when a PeerConnection is created.
653std::string GenerateRtcpCname() {
654 std::string cname;
655 if (!rtc::CreateRandomString(kRtcpCnameLength, &cname)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100656 RTC_LOG(LS_ERROR) << "Failed to generate CNAME.";
nisseeb4ca4e2017-01-12 02:24:27 -0800657 RTC_NOTREACHED();
zhihuang8f65cdf2016-05-06 18:40:30 -0700658 }
659 return cname;
660}
661
zhihuang1c378ed2017-08-17 14:10:50 -0700662bool ValidateOfferAnswerOptions(
663 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options) {
664 return IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_audio) &&
665 IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_video);
olka3c747662017-08-17 06:50:32 -0700666}
667
zhihuang1c378ed2017-08-17 14:10:50 -0700668// From |rtc_options|, fill parts of |session_options| shared by all generated
669// m= sections (in other words, nothing that involves a map/array).
670void ExtractSharedMediaSessionOptions(
671 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options,
672 cricket::MediaSessionOptions* session_options) {
673 session_options->vad_enabled = rtc_options.voice_activity_detection;
674 session_options->bundle_enabled = rtc_options.use_rtp_mux;
675}
zhihuanga77e6bb2017-08-14 18:17:48 -0700676
zhihuang1c378ed2017-08-17 14:10:50 -0700677bool ConvertConstraintsToOfferAnswerOptions(
678 const MediaConstraintsInterface* constraints,
679 PeerConnectionInterface::RTCOfferAnswerOptions* offer_answer_options) {
olka3c747662017-08-17 06:50:32 -0700680 if (!constraints) {
681 return true;
682 }
zhihuang1c378ed2017-08-17 14:10:50 -0700683
684 bool value = false;
685 size_t mandatory_constraints_satisfied = 0;
686
687 if (FindConstraint(constraints,
688 MediaConstraintsInterface::kOfferToReceiveAudio, &value,
689 &mandatory_constraints_satisfied)) {
690 offer_answer_options->offer_to_receive_audio =
691 value ? PeerConnectionInterface::RTCOfferAnswerOptions::
692 kOfferToReceiveMediaTrue
693 : 0;
694 }
695
696 if (FindConstraint(constraints,
697 MediaConstraintsInterface::kOfferToReceiveVideo, &value,
698 &mandatory_constraints_satisfied)) {
699 offer_answer_options->offer_to_receive_video =
700 value ? PeerConnectionInterface::RTCOfferAnswerOptions::
701 kOfferToReceiveMediaTrue
702 : 0;
703 }
704 if (FindConstraint(constraints,
705 MediaConstraintsInterface::kVoiceActivityDetection, &value,
706 &mandatory_constraints_satisfied)) {
707 offer_answer_options->voice_activity_detection = value;
708 }
709 if (FindConstraint(constraints, MediaConstraintsInterface::kUseRtpMux, &value,
710 &mandatory_constraints_satisfied)) {
711 offer_answer_options->use_rtp_mux = value;
712 }
713 if (FindConstraint(constraints, MediaConstraintsInterface::kIceRestart,
714 &value, &mandatory_constraints_satisfied)) {
715 offer_answer_options->ice_restart = value;
716 }
717
deadbeefab9b2d12015-10-14 11:33:11 -0700718 return mandatory_constraints_satisfied == constraints->GetMandatory().size();
719}
720
zhihuang38ede132017-06-15 12:52:32 -0700721PeerConnection::PeerConnection(PeerConnectionFactory* factory,
722 std::unique_ptr<RtcEventLog> event_log,
723 std::unique_ptr<Call> call)
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000724 : factory_(factory),
zhihuang38ede132017-06-15 12:52:32 -0700725 event_log_(std::move(event_log)),
zhihuang8f65cdf2016-05-06 18:40:30 -0700726 rtcp_cname_(GenerateRtcpCname()),
deadbeefab9b2d12015-10-14 11:33:11 -0700727 local_streams_(StreamCollection::Create()),
zhihuang38ede132017-06-15 12:52:32 -0700728 remote_streams_(StreamCollection::Create()),
729 call_(std::move(call)) {}
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000730
731PeerConnection::~PeerConnection() {
Peter Boström1a9d6152015-12-08 22:15:17 +0100732 TRACE_EVENT0("webrtc", "PeerConnection::~PeerConnection");
Steve Anton4171afb2017-11-20 10:20:22 -0800733 RTC_DCHECK_RUN_ON(signaling_thread());
734
Steve Anton8af21862017-12-15 11:20:13 -0800735 // Need to stop transceivers before destroying the stats collector because
736 // AudioRtpSender has a reference to the StatsCollector it will update when
737 // stopping.
738 for (auto transceiver : transceivers_) {
739 transceiver->Stop();
740 }
Steve Anton4171afb2017-11-20 10:20:22 -0800741
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700742 stats_.reset(nullptr);
hbosb78306a2016-12-19 05:06:57 -0800743 if (stats_collector_) {
744 stats_collector_->WaitForPendingRequest();
745 stats_collector_ = nullptr;
746 }
Steve Anton75737c02017-11-06 10:37:17 -0800747
Steve Anton8af21862017-12-15 11:20:13 -0800748 // Don't destroy BaseChannels until after stats has been cleaned up so that
749 // the last stats request can still read from the channels.
750 DestroyAllChannels();
751
Mirko Bonadei675513b2017-11-09 11:09:25 +0100752 RTC_LOG(LS_INFO) << "Session: " << session_id() << " is destroyed.";
Steve Anton75737c02017-11-06 10:37:17 -0800753
754 webrtc_session_desc_factory_.reset();
755 sctp_invoker_.reset();
756 sctp_factory_.reset();
757 transport_controller_.reset();
758
deadbeef91dd5672016-05-18 16:55:30 -0700759 // port_allocator_ lives on the network thread and should be destroyed there.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700760 network_thread()->Invoke<void>(RTC_FROM_HERE,
nisseeaabdf62017-05-05 02:23:02 -0700761 [this] { port_allocator_.reset(); });
eladalon248fd4f2017-09-06 05:18:15 -0700762 // call_ and event_log_ must be destroyed on the worker thread.
Steve Anton978b8762017-09-29 12:15:02 -0700763 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
eladalon248fd4f2017-09-06 05:18:15 -0700764 call_.reset();
765 event_log_.reset();
766 });
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000767}
768
Steve Anton8af21862017-12-15 11:20:13 -0800769void PeerConnection::DestroyAllChannels() {
Steve Anton3fe1b152017-12-12 10:20:08 -0800770 // Destroy video channels first since they may have a pointer to a voice
771 // channel.
772 for (auto transceiver : transceivers_) {
773 if (transceiver->internal()->media_type() == cricket::MEDIA_TYPE_VIDEO) {
774 DestroyTransceiverChannel(transceiver);
775 }
776 }
777 for (auto transceiver : transceivers_) {
778 if (transceiver->internal()->media_type() == cricket::MEDIA_TYPE_AUDIO) {
779 DestroyTransceiverChannel(transceiver);
780 }
781 }
782 DestroyDataChannel();
783}
784
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000785bool PeerConnection::Initialize(
buildbot@webrtc.org41451d42014-05-03 05:39:45 +0000786 const PeerConnectionInterface::RTCConfiguration& configuration,
kwibergd1fe2812016-04-27 06:47:29 -0700787 std::unique_ptr<cricket::PortAllocator> allocator,
Henrik Boströmd03c23b2016-06-01 11:44:18 +0200788 std::unique_ptr<rtc::RTCCertificateGeneratorInterface> cert_generator,
deadbeef653b8e02015-11-11 12:55:10 -0800789 PeerConnectionObserver* observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100790 TRACE_EVENT0("webrtc", "PeerConnection::Initialize");
Steve Anton038834f2017-07-14 15:59:59 -0700791
792 RTCError config_error = ValidateConfiguration(configuration);
793 if (!config_error.ok()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100794 RTC_LOG(LS_ERROR) << "Invalid configuration: " << config_error.message();
Steve Anton038834f2017-07-14 15:59:59 -0700795 return false;
796 }
797
deadbeef293e9262017-01-11 12:28:30 -0800798 if (!allocator) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100799 RTC_LOG(LS_ERROR)
800 << "PeerConnection initialized without a PortAllocator? "
801 << "This shouldn't happen if using PeerConnectionFactory.";
deadbeef293e9262017-01-11 12:28:30 -0800802 return false;
803 }
Jonas Orelandbdcee282017-10-10 14:01:40 +0200804
deadbeef653b8e02015-11-11 12:55:10 -0800805 if (!observer) {
deadbeef293e9262017-01-11 12:28:30 -0800806 // TODO(deadbeef): Why do we do this?
Mirko Bonadei675513b2017-11-09 11:09:25 +0100807 RTC_LOG(LS_ERROR) << "PeerConnection initialized without a "
808 << "PeerConnectionObserver";
deadbeef653b8e02015-11-11 12:55:10 -0800809 return false;
810 }
pthatcher@webrtc.org877ac762015-02-04 22:03:09 +0000811 observer_ = observer;
kwiberg0eb15ed2015-12-17 03:04:15 -0800812 port_allocator_ = std::move(allocator);
deadbeef653b8e02015-11-11 12:55:10 -0800813
deadbeef91dd5672016-05-18 16:55:30 -0700814 // The port allocator lives on the network thread and should be initialized
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700815 // there.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700816 if (!network_thread()->Invoke<bool>(
817 RTC_FROM_HERE, rtc::Bind(&PeerConnection::InitializePortAllocator_n,
818 this, configuration))) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000819 return false;
820 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000821
Steve Anton75737c02017-11-06 10:37:17 -0800822 // RFC 3264: The numeric value of the session id and version in the
823 // o line MUST be representable with a "64 bit signed integer".
824 // Due to this constraint session id |session_id_| is max limited to
825 // LLONG_MAX.
826 session_id_ = rtc::ToString(rtc::CreateRandomId64() & LLONG_MAX);
827 transport_controller_.reset(factory_->CreateTransportController(
828 port_allocator_.get(), configuration.redetermine_role_on_ice_restart));
829 transport_controller_->SetIceRole(cricket::ICEROLE_CONTROLLED);
830 transport_controller_->SignalConnectionState.connect(
831 this, &PeerConnection::OnTransportControllerConnectionState);
832 transport_controller_->SignalGatheringState.connect(
833 this, &PeerConnection::OnTransportControllerGatheringState);
834 transport_controller_->SignalCandidatesGathered.connect(
835 this, &PeerConnection::OnTransportControllerCandidatesGathered);
836 transport_controller_->SignalCandidatesRemoved.connect(
837 this, &PeerConnection::OnTransportControllerCandidatesRemoved);
838 transport_controller_->SignalDtlsHandshakeError.connect(
839 this, &PeerConnection::OnTransportControllerDtlsHandshakeError);
840
841 sctp_factory_ = factory_->CreateSctpTransportInternalFactory();
zhihuang29ff8442016-07-27 11:07:25 -0700842
deadbeefab9b2d12015-10-14 11:33:11 -0700843 stats_.reset(new StatsCollector(this));
hbos74e1a4f2016-09-15 23:33:01 -0700844 stats_collector_ = RTCStatsCollector::Create(this);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000845
Steve Antonba818672017-11-06 10:21:57 -0800846 configuration_ = configuration;
847
Steve Anton75737c02017-11-06 10:37:17 -0800848 const PeerConnectionFactoryInterface::Options& options = factory_->options();
849
850 transport_controller_->SetSslMaxProtocolVersion(options.ssl_max_version);
851
852 // Obtain a certificate from RTCConfiguration if any were provided (optional).
853 rtc::scoped_refptr<rtc::RTCCertificate> certificate;
854 if (!configuration.certificates.empty()) {
855 // TODO(hbos,torbjorng): Decide on certificate-selection strategy instead of
856 // just picking the first one. The decision should be made based on the DTLS
857 // handshake. The DTLS negotiations need to know about all certificates.
858 certificate = configuration.certificates[0];
859 }
860
Steve Antond25da372017-11-06 14:50:29 -0800861 transport_controller_->SetIceConfig(ParseIceConfig(configuration));
Steve Anton75737c02017-11-06 10:37:17 -0800862
863 if (options.disable_encryption) {
864 dtls_enabled_ = false;
865 } else {
866 // Enable DTLS by default if we have an identity store or a certificate.
867 dtls_enabled_ = (cert_generator || certificate);
868 // |configuration| can override the default |dtls_enabled_| value.
869 if (configuration.enable_dtls_srtp) {
870 dtls_enabled_ = *(configuration.enable_dtls_srtp);
871 }
872 }
873
874 // Enable creation of RTP data channels if the kEnableRtpDataChannels is set.
875 // It takes precendence over the disable_sctp_data_channels
876 // PeerConnectionFactoryInterface::Options.
877 if (configuration.enable_rtp_data_channel) {
878 data_channel_type_ = cricket::DCT_RTP;
879 } else {
880 // DTLS has to be enabled to use SCTP.
881 if (!options.disable_sctp_data_channels && dtls_enabled_) {
882 data_channel_type_ = cricket::DCT_SCTP;
883 }
884 }
885
886 video_options_.screencast_min_bitrate_kbps =
887 configuration.screencast_min_bitrate;
888 audio_options_.combined_audio_video_bwe =
889 configuration.combined_audio_video_bwe;
890
891 audio_options_.audio_jitter_buffer_max_packets =
Oskar Sundbom9b28a032017-11-16 10:53:30 +0100892 configuration.audio_jitter_buffer_max_packets;
Steve Anton75737c02017-11-06 10:37:17 -0800893
894 audio_options_.audio_jitter_buffer_fast_accelerate =
Oskar Sundbom9b28a032017-11-16 10:53:30 +0100895 configuration.audio_jitter_buffer_fast_accelerate;
Steve Anton75737c02017-11-06 10:37:17 -0800896
897 // Whether the certificate generator/certificate is null or not determines
898 // what PeerConnectionDescriptionFactory will do, so make sure that we give it
899 // the right instructions by clearing the variables if needed.
900 if (!dtls_enabled_) {
901 cert_generator.reset();
902 certificate = nullptr;
903 } else if (certificate) {
904 // Favor generated certificate over the certificate generator.
905 cert_generator.reset();
906 }
907
908 webrtc_session_desc_factory_.reset(new WebRtcSessionDescriptionFactory(
909 signaling_thread(), channel_manager(), this, session_id(),
910 std::move(cert_generator), certificate));
911 webrtc_session_desc_factory_->SignalCertificateReady.connect(
912 this, &PeerConnection::OnCertificateReady);
913
914 if (options.disable_encryption) {
915 webrtc_session_desc_factory_->SetSdesPolicy(cricket::SEC_DISABLED);
916 }
917
918 webrtc_session_desc_factory_->set_enable_encrypted_rtp_header_extensions(
919 options.crypto_options.enable_encrypted_rtp_header_extensions);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000920
Steve Anton4171afb2017-11-20 10:20:22 -0800921 // Add default audio/video transceivers for Plan B SDP.
922 if (!IsUnifiedPlan()) {
923 transceivers_.push_back(
924 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
925 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_AUDIO)));
926 transceivers_.push_back(
927 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
928 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_VIDEO)));
929 }
930
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000931 return true;
932}
933
Steve Anton038834f2017-07-14 15:59:59 -0700934RTCError PeerConnection::ValidateConfiguration(
935 const RTCConfiguration& config) const {
936 if (config.ice_regather_interval_range &&
937 config.continual_gathering_policy == GATHER_ONCE) {
938 return RTCError(RTCErrorType::INVALID_PARAMETER,
939 "ice_regather_interval_range specified but continual "
940 "gathering policy is GATHER_ONCE");
941 }
942 return RTCError::OK();
943}
944
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000945rtc::scoped_refptr<StreamCollectionInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000946PeerConnection::local_streams() {
deadbeefab9b2d12015-10-14 11:33:11 -0700947 return local_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000948}
949
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000950rtc::scoped_refptr<StreamCollectionInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000951PeerConnection::remote_streams() {
deadbeefab9b2d12015-10-14 11:33:11 -0700952 return remote_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000953}
954
perkj@webrtc.orgc2dd5ee2014-11-04 11:31:29 +0000955bool PeerConnection::AddStream(MediaStreamInterface* local_stream) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100956 TRACE_EVENT0("webrtc", "PeerConnection::AddStream");
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000957 if (IsClosed()) {
958 return false;
959 }
deadbeefab9b2d12015-10-14 11:33:11 -0700960 if (!CanAddLocalMediaStream(local_streams_, local_stream)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000961 return false;
962 }
deadbeefab9b2d12015-10-14 11:33:11 -0700963
964 local_streams_->AddStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -0800965 MediaStreamObserver* observer = new MediaStreamObserver(local_stream);
966 observer->SignalAudioTrackAdded.connect(this,
967 &PeerConnection::OnAudioTrackAdded);
968 observer->SignalAudioTrackRemoved.connect(
969 this, &PeerConnection::OnAudioTrackRemoved);
970 observer->SignalVideoTrackAdded.connect(this,
971 &PeerConnection::OnVideoTrackAdded);
972 observer->SignalVideoTrackRemoved.connect(
973 this, &PeerConnection::OnVideoTrackRemoved);
kwibergd1fe2812016-04-27 06:47:29 -0700974 stream_observers_.push_back(std::unique_ptr<MediaStreamObserver>(observer));
deadbeefab9b2d12015-10-14 11:33:11 -0700975
deadbeefab9b2d12015-10-14 11:33:11 -0700976 for (const auto& track : local_stream->GetAudioTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -0700977 AddAudioTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -0700978 }
979 for (const auto& track : local_stream->GetVideoTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -0700980 AddVideoTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -0700981 }
982
tommi@webrtc.org03505bc2014-07-14 20:15:26 +0000983 stats_->AddStream(local_stream);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000984 observer_->OnRenegotiationNeeded();
985 return true;
986}
987
988void PeerConnection::RemoveStream(MediaStreamInterface* local_stream) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100989 TRACE_EVENT0("webrtc", "PeerConnection::RemoveStream");
korniltsev.anatolyec390b52017-07-24 17:00:25 -0700990 if (!IsClosed()) {
991 for (const auto& track : local_stream->GetAudioTracks()) {
992 RemoveAudioTrack(track.get(), local_stream);
993 }
994 for (const auto& track : local_stream->GetVideoTracks()) {
995 RemoveVideoTrack(track.get(), local_stream);
996 }
deadbeefab9b2d12015-10-14 11:33:11 -0700997 }
deadbeefab9b2d12015-10-14 11:33:11 -0700998 local_streams_->RemoveStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -0800999 stream_observers_.erase(
1000 std::remove_if(
1001 stream_observers_.begin(), stream_observers_.end(),
kwibergd1fe2812016-04-27 06:47:29 -07001002 [local_stream](const std::unique_ptr<MediaStreamObserver>& observer) {
deadbeefeb459812015-12-15 19:24:43 -08001003 return observer->stream()->label().compare(local_stream->label()) ==
1004 0;
1005 }),
1006 stream_observers_.end());
deadbeefab9b2d12015-10-14 11:33:11 -07001007
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001008 if (IsClosed()) {
1009 return;
1010 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001011 observer_->OnRenegotiationNeeded();
1012}
1013
deadbeefe1f9d832016-01-14 15:35:42 -08001014rtc::scoped_refptr<RtpSenderInterface> PeerConnection::AddTrack(
1015 MediaStreamTrackInterface* track,
1016 std::vector<MediaStreamInterface*> streams) {
1017 TRACE_EVENT0("webrtc", "PeerConnection::AddTrack");
Steve Antonf9381f02017-12-14 10:23:57 -08001018 std::vector<std::string> stream_labels;
1019 for (auto* stream : streams) {
1020 if (!stream) {
1021 RTC_LOG(LS_ERROR) << "Stream list has null element.";
1022 return nullptr;
1023 }
1024 stream_labels.push_back(stream->label());
1025 }
Steve Anton2d6c76a2018-01-05 17:10:52 -08001026 auto sender_or_error = AddTrack(track, stream_labels);
Steve Antonf9381f02017-12-14 10:23:57 -08001027 if (!sender_or_error.ok()) {
deadbeefe1f9d832016-01-14 15:35:42 -08001028 return nullptr;
1029 }
Steve Antonf9381f02017-12-14 10:23:57 -08001030 return sender_or_error.MoveValue();
1031}
1032
Steve Anton2d6c76a2018-01-05 17:10:52 -08001033RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::AddTrack(
Steve Antonf9381f02017-12-14 10:23:57 -08001034 rtc::scoped_refptr<MediaStreamTrackInterface> track,
1035 const std::vector<std::string>& stream_labels) {
Steve Anton2d6c76a2018-01-05 17:10:52 -08001036 TRACE_EVENT0("webrtc", "PeerConnection::AddTrack");
Steve Antonf9381f02017-12-14 10:23:57 -08001037 if (!track) {
1038 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "Track is null.");
1039 }
1040 if (!(track->kind() == MediaStreamTrackInterface::kAudioKind ||
1041 track->kind() == MediaStreamTrackInterface::kVideoKind)) {
1042 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1043 "Track has invalid kind: " + track->kind());
1044 }
1045 // TODO(bugs.webrtc.org/7932): Support adding a track to multiple streams.
1046 if (stream_labels.size() > 1u) {
1047 LOG_AND_RETURN_ERROR(
1048 RTCErrorType::UNSUPPORTED_OPERATION,
1049 "AddTrack with more than one stream is not currently supported.");
1050 }
1051 if (IsClosed()) {
1052 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
1053 "PeerConnection is closed.");
deadbeefe1f9d832016-01-14 15:35:42 -08001054 }
Steve Anton4171afb2017-11-20 10:20:22 -08001055 if (FindSenderForTrack(track)) {
Steve Antonf9381f02017-12-14 10:23:57 -08001056 LOG_AND_RETURN_ERROR(
1057 RTCErrorType::INVALID_PARAMETER,
1058 "Sender already exists for track " + track->id() + ".");
deadbeefe1f9d832016-01-14 15:35:42 -08001059 }
Steve Antonf9381f02017-12-14 10:23:57 -08001060 // TODO(bugs.webrtc.org/7933): MediaSession expects the sender to have exactly
1061 // one stream. AddTrackInternal will return an error if there is more than one
1062 // stream, but if the caller specifies none then we need to generate a random
1063 // stream label.
1064 std::vector<std::string> adjusted_stream_labels = stream_labels;
1065 if (stream_labels.empty()) {
1066 adjusted_stream_labels.push_back(rtc::CreateRandomUuid());
1067 }
1068 RTC_DCHECK_EQ(1, adjusted_stream_labels.size());
1069 auto sender_or_error =
1070 (IsUnifiedPlan() ? AddTrackUnifiedPlan(track, adjusted_stream_labels)
1071 : AddTrackPlanB(track, adjusted_stream_labels));
1072 if (sender_or_error.ok()) {
1073 observer_->OnRenegotiationNeeded();
Steve Anton43a723a2018-01-04 15:48:17 -08001074 stats_->AddTrack(track);
Steve Antonf9381f02017-12-14 10:23:57 -08001075 }
1076 return sender_or_error;
1077}
deadbeefe1f9d832016-01-14 15:35:42 -08001078
Steve Antonf9381f02017-12-14 10:23:57 -08001079RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>>
1080PeerConnection::AddTrackPlanB(
1081 rtc::scoped_refptr<MediaStreamTrackInterface> track,
1082 const std::vector<std::string>& stream_labels) {
Steve Anton02ee47c2018-01-10 16:26:06 -08001083 cricket::MediaType media_type =
1084 (track->kind() == MediaStreamTrackInterface::kAudioKind
1085 ? cricket::MEDIA_TYPE_AUDIO
1086 : cricket::MEDIA_TYPE_VIDEO);
1087 auto new_sender = CreateSender(media_type, track, stream_labels);
deadbeefe1f9d832016-01-14 15:35:42 -08001088 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
Steve Anton02ee47c2018-01-10 16:26:06 -08001089 static_cast<AudioRtpSender*>(new_sender->internal())
Steve Anton47136dd2018-01-12 10:49:35 -08001090 ->SetMediaChannel(voice_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08001091 GetAudioTransceiver()->internal()->AddSender(new_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001092 const RtpSenderInfo* sender_info =
1093 FindSenderInfo(local_audio_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 } else {
1099 RTC_DCHECK_EQ(MediaStreamTrackInterface::kVideoKind, track->kind());
Steve Anton02ee47c2018-01-10 16:26:06 -08001100 static_cast<VideoRtpSender*>(new_sender->internal())
Steve Anton47136dd2018-01-12 10:49:35 -08001101 ->SetMediaChannel(video_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08001102 GetVideoTransceiver()->internal()->AddSender(new_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001103 const RtpSenderInfo* sender_info =
1104 FindSenderInfo(local_video_sender_infos_,
1105 new_sender->internal()->stream_id(), track->id());
1106 if (sender_info) {
1107 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -08001108 }
deadbeefe1f9d832016-01-14 15:35:42 -08001109 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001110 return rtc::scoped_refptr<RtpSenderInterface>(new_sender);
Steve Antonf9381f02017-12-14 10:23:57 -08001111}
deadbeefe1f9d832016-01-14 15:35:42 -08001112
Steve Antonf9381f02017-12-14 10:23:57 -08001113RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>>
1114PeerConnection::AddTrackUnifiedPlan(
1115 rtc::scoped_refptr<MediaStreamTrackInterface> track,
1116 const std::vector<std::string>& stream_labels) {
1117 auto transceiver = FindFirstTransceiverForAddedTrack(track);
1118 if (transceiver) {
1119 if (transceiver->direction() == RtpTransceiverDirection::kRecvOnly) {
1120 transceiver->SetDirection(RtpTransceiverDirection::kSendRecv);
1121 } else if (transceiver->direction() == RtpTransceiverDirection::kInactive) {
1122 transceiver->SetDirection(RtpTransceiverDirection::kSendOnly);
1123 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001124 transceiver->sender()->SetTrack(track);
1125 transceiver->internal()->sender_internal()->set_stream_ids(stream_labels);
Steve Antonf9381f02017-12-14 10:23:57 -08001126 } else {
1127 cricket::MediaType media_type =
1128 (track->kind() == MediaStreamTrackInterface::kAudioKind
1129 ? cricket::MEDIA_TYPE_AUDIO
1130 : cricket::MEDIA_TYPE_VIDEO);
Steve Anton02ee47c2018-01-10 16:26:06 -08001131 auto sender = CreateSender(media_type, track, stream_labels);
1132 auto receiver = CreateReceiver(media_type, rtc::CreateRandomUuid());
1133 transceiver = CreateAndAddTransceiver(sender, receiver);
Steve Antonf9381f02017-12-14 10:23:57 -08001134 transceiver->internal()->set_created_by_addtrack(true);
1135 transceiver->SetDirection(RtpTransceiverDirection::kSendRecv);
1136 }
Steve Antonf9381f02017-12-14 10:23:57 -08001137 return transceiver->sender();
1138}
1139
1140rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1141PeerConnection::FindFirstTransceiverForAddedTrack(
1142 rtc::scoped_refptr<MediaStreamTrackInterface> track) {
1143 RTC_DCHECK(track);
1144 for (auto transceiver : transceivers_) {
1145 if (!transceiver->sender()->track() &&
1146 cricket::MediaTypeToString(transceiver->internal()->media_type()) ==
1147 track->kind() &&
1148 !transceiver->internal()->has_ever_been_used_to_send()) {
1149 return transceiver;
1150 }
1151 }
1152 return nullptr;
deadbeefe1f9d832016-01-14 15:35:42 -08001153}
1154
1155bool PeerConnection::RemoveTrack(RtpSenderInterface* sender) {
1156 TRACE_EVENT0("webrtc", "PeerConnection::RemoveTrack");
Steve Antonf9381f02017-12-14 10:23:57 -08001157 return RemoveTrackInternal(sender).ok();
1158}
1159
1160RTCError PeerConnection::RemoveTrackInternal(
1161 rtc::scoped_refptr<RtpSenderInterface> sender) {
1162 if (!sender) {
1163 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "Sender is null.");
1164 }
deadbeefe1f9d832016-01-14 15:35:42 -08001165 if (IsClosed()) {
Steve Antonf9381f02017-12-14 10:23:57 -08001166 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
1167 "PeerConnection is closed.");
deadbeefe1f9d832016-01-14 15:35:42 -08001168 }
Steve Antonf9381f02017-12-14 10:23:57 -08001169 if (IsUnifiedPlan()) {
1170 auto transceiver = FindTransceiverBySender(sender);
1171 if (!transceiver || !sender->track()) {
1172 return RTCError::OK();
1173 }
1174 sender->SetTrack(nullptr);
1175 if (transceiver->direction() == RtpTransceiverDirection::kSendRecv) {
1176 transceiver->internal()->SetDirection(RtpTransceiverDirection::kRecvOnly);
1177 } else if (transceiver->direction() == RtpTransceiverDirection::kSendOnly) {
1178 transceiver->internal()->SetDirection(RtpTransceiverDirection::kInactive);
1179 }
Steve Anton4171afb2017-11-20 10:20:22 -08001180 } else {
Steve Antonf9381f02017-12-14 10:23:57 -08001181 bool removed;
1182 if (sender->media_type() == cricket::MEDIA_TYPE_AUDIO) {
1183 removed = GetAudioTransceiver()->internal()->RemoveSender(sender);
1184 } else {
1185 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, sender->media_type());
1186 removed = GetVideoTransceiver()->internal()->RemoveSender(sender);
1187 }
1188 if (!removed) {
1189 LOG_AND_RETURN_ERROR(
1190 RTCErrorType::INVALID_PARAMETER,
1191 "Couldn't find sender " + sender->id() + " to remove.");
1192 }
Steve Anton4171afb2017-11-20 10:20:22 -08001193 }
deadbeefe1f9d832016-01-14 15:35:42 -08001194 observer_->OnRenegotiationNeeded();
Steve Antonf9381f02017-12-14 10:23:57 -08001195 return RTCError::OK();
1196}
1197
1198rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1199PeerConnection::FindTransceiverBySender(
1200 rtc::scoped_refptr<RtpSenderInterface> sender) {
1201 for (auto transceiver : transceivers_) {
1202 if (transceiver->sender() == sender) {
1203 return transceiver;
1204 }
1205 }
1206 return nullptr;
deadbeefe1f9d832016-01-14 15:35:42 -08001207}
1208
Steve Anton9158ef62017-11-27 13:01:52 -08001209RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1210PeerConnection::AddTransceiver(
1211 rtc::scoped_refptr<MediaStreamTrackInterface> track) {
1212 return AddTransceiver(track, RtpTransceiverInit());
1213}
1214
1215RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1216PeerConnection::AddTransceiver(
1217 rtc::scoped_refptr<MediaStreamTrackInterface> track,
1218 const RtpTransceiverInit& init) {
1219 if (!IsUnifiedPlan()) {
1220 LOG_AND_RETURN_ERROR(
1221 RTCErrorType::INTERNAL_ERROR,
1222 "AddTransceiver only supported when Unified Plan is enabled.");
1223 }
1224 if (!track) {
1225 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "track is null");
1226 }
1227 cricket::MediaType media_type;
1228 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
1229 media_type = cricket::MEDIA_TYPE_AUDIO;
1230 } else if (track->kind() == MediaStreamTrackInterface::kVideoKind) {
1231 media_type = cricket::MEDIA_TYPE_VIDEO;
1232 } else {
1233 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1234 "Track kind is not audio or video");
1235 }
1236 return AddTransceiver(media_type, track, init);
1237}
1238
1239RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1240PeerConnection::AddTransceiver(cricket::MediaType media_type) {
1241 return AddTransceiver(media_type, RtpTransceiverInit());
1242}
1243
1244RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1245PeerConnection::AddTransceiver(cricket::MediaType media_type,
1246 const RtpTransceiverInit& init) {
1247 if (!IsUnifiedPlan()) {
1248 LOG_AND_RETURN_ERROR(
1249 RTCErrorType::INTERNAL_ERROR,
1250 "AddTransceiver only supported when Unified Plan is enabled.");
1251 }
1252 if (!(media_type == cricket::MEDIA_TYPE_AUDIO ||
1253 media_type == cricket::MEDIA_TYPE_VIDEO)) {
1254 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1255 "media type is not audio or video");
1256 }
1257 return AddTransceiver(media_type, nullptr, init);
1258}
1259
1260RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1261PeerConnection::AddTransceiver(
1262 cricket::MediaType media_type,
1263 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Steve Anton22da89f2018-01-25 13:58:07 -08001264 const RtpTransceiverInit& init,
1265 bool fire_callback) {
Steve Anton9158ef62017-11-27 13:01:52 -08001266 RTC_DCHECK((media_type == cricket::MEDIA_TYPE_AUDIO ||
1267 media_type == cricket::MEDIA_TYPE_VIDEO));
1268 if (track) {
1269 RTC_DCHECK_EQ(media_type,
1270 (track->kind() == MediaStreamTrackInterface::kAudioKind
1271 ? cricket::MEDIA_TYPE_AUDIO
1272 : cricket::MEDIA_TYPE_VIDEO));
1273 }
1274
1275 // TODO(bugs.webrtc.org/7600): Verify init.
1276
Steve Anton02ee47c2018-01-10 16:26:06 -08001277 if (init.stream_labels.size() > 1u) {
1278 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
1279 "More than one stream is not yet supported.");
Steve Antonf9381f02017-12-14 10:23:57 -08001280 }
1281
Steve Anton02ee47c2018-01-10 16:26:06 -08001282 std::vector<std::string> stream_labels = {!init.stream_labels.empty()
1283 ? init.stream_labels[0]
1284 : rtc::CreateRandomUuid()};
1285
1286 auto sender = CreateSender(media_type, track, stream_labels);
1287 auto receiver = CreateReceiver(media_type, rtc::CreateRandomUuid());
1288 auto transceiver = CreateAndAddTransceiver(sender, receiver);
1289 transceiver->internal()->set_direction(init.direction);
1290
Steve Anton22da89f2018-01-25 13:58:07 -08001291 if (fire_callback) {
1292 observer_->OnRenegotiationNeeded();
1293 }
Steve Antonf9381f02017-12-14 10:23:57 -08001294
1295 return rtc::scoped_refptr<RtpTransceiverInterface>(transceiver);
1296}
1297
Steve Anton02ee47c2018-01-10 16:26:06 -08001298rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
1299PeerConnection::CreateSender(
1300 cricket::MediaType media_type,
1301 rtc::scoped_refptr<MediaStreamTrackInterface> track,
1302 const std::vector<std::string>& stream_labels) {
Steve Anton9158ef62017-11-27 13:01:52 -08001303 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> sender;
Steve Anton02ee47c2018-01-10 16:26:06 -08001304 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
1305 RTC_DCHECK(!track ||
1306 (track->kind() == MediaStreamTrackInterface::kAudioKind));
1307 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
1308 signaling_thread(),
Steve Anton47136dd2018-01-12 10:49:35 -08001309 new AudioRtpSender(worker_thread(),
1310 static_cast<AudioTrackInterface*>(track.get()),
Steve Anton02ee47c2018-01-10 16:26:06 -08001311 stream_labels, stats_.get()));
1312 } else {
1313 RTC_DCHECK_EQ(media_type, cricket::MEDIA_TYPE_VIDEO);
1314 RTC_DCHECK(!track ||
1315 (track->kind() == MediaStreamTrackInterface::kVideoKind));
1316 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
1317 signaling_thread(),
Steve Anton47136dd2018-01-12 10:49:35 -08001318 new VideoRtpSender(worker_thread(),
1319 static_cast<VideoTrackInterface*>(track.get()),
Steve Anton02ee47c2018-01-10 16:26:06 -08001320 stream_labels));
1321 }
1322 sender->internal()->set_stream_ids(stream_labels);
1323 return sender;
1324}
1325
1326rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1327PeerConnection::CreateReceiver(cricket::MediaType media_type,
1328 const std::string& receiver_id) {
Steve Anton9158ef62017-11-27 13:01:52 -08001329 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1330 receiver;
Steve Anton9158ef62017-11-27 13:01:52 -08001331 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton9158ef62017-11-27 13:01:52 -08001332 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
Steve Anton60776752018-01-10 11:51:34 -08001333 signaling_thread(),
Steve Antond3679212018-01-17 17:41:02 -08001334 new AudioRtpReceiver(worker_thread(), receiver_id, {}));
Steve Anton9158ef62017-11-27 13:01:52 -08001335 } else {
Steve Anton02ee47c2018-01-10 16:26:06 -08001336 RTC_DCHECK_EQ(media_type, cricket::MEDIA_TYPE_VIDEO);
Steve Anton9158ef62017-11-27 13:01:52 -08001337 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
1338 signaling_thread(),
Steve Antond3679212018-01-17 17:41:02 -08001339 new VideoRtpReceiver(worker_thread(), receiver_id, {}));
Steve Anton9158ef62017-11-27 13:01:52 -08001340 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001341 return receiver;
1342}
1343
1344rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1345PeerConnection::CreateAndAddTransceiver(
1346 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> sender,
1347 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1348 receiver) {
1349 auto transceiver = RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1350 signaling_thread(), new RtpTransceiver(sender, receiver));
Steve Anton9158ef62017-11-27 13:01:52 -08001351 transceivers_.push_back(transceiver);
Steve Antonf9381f02017-12-14 10:23:57 -08001352 return transceiver;
Steve Anton9158ef62017-11-27 13:01:52 -08001353}
1354
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001355rtc::scoped_refptr<DtmfSenderInterface> PeerConnection::CreateDtmfSender(
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001356 AudioTrackInterface* track) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001357 TRACE_EVENT0("webrtc", "PeerConnection::CreateDtmfSender");
zhihuang29ff8442016-07-27 11:07:25 -07001358 if (IsClosed()) {
1359 return nullptr;
1360 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001361 if (!track) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001362 RTC_LOG(LS_ERROR) << "CreateDtmfSender - track is NULL.";
deadbeef20cb0c12017-02-01 20:27:00 -08001363 return nullptr;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001364 }
Steve Anton4171afb2017-11-20 10:20:22 -08001365 auto track_sender = FindSenderForTrack(track);
1366 if (!track_sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001367 RTC_LOG(LS_ERROR) << "CreateDtmfSender called with a non-added track.";
deadbeef20cb0c12017-02-01 20:27:00 -08001368 return nullptr;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001369 }
1370
Steve Anton4171afb2017-11-20 10:20:22 -08001371 return track_sender->GetDtmfSender();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001372}
1373
deadbeeffac06552015-11-25 11:26:01 -08001374rtc::scoped_refptr<RtpSenderInterface> PeerConnection::CreateSender(
deadbeefbd7d8f72015-12-18 16:58:44 -08001375 const std::string& kind,
1376 const std::string& stream_id) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001377 TRACE_EVENT0("webrtc", "PeerConnection::CreateSender");
zhihuang29ff8442016-07-27 11:07:25 -07001378 if (IsClosed()) {
1379 return nullptr;
1380 }
Steve Anton4171afb2017-11-20 10:20:22 -08001381
Steve Anton02ee47c2018-01-10 16:26:06 -08001382 std::vector<std::string> stream_labels;
1383 if (!stream_id.empty()) {
1384 stream_labels.push_back(stream_id);
1385 }
1386
Steve Anton4171afb2017-11-20 10:20:22 -08001387 // TODO(steveanton): Move construction of the RtpSenders to RtpTransceiver.
deadbeefa601f5c2016-06-06 14:27:39 -07001388 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender;
deadbeeffac06552015-11-25 11:26:01 -08001389 if (kind == MediaStreamTrackInterface::kAudioKind) {
Steve Anton47136dd2018-01-12 10:49:35 -08001390 auto* audio_sender = new AudioRtpSender(worker_thread(), nullptr,
1391 stream_labels, stats_.get());
1392 audio_sender->SetMediaChannel(voice_media_channel());
deadbeefa601f5c2016-06-06 14:27:39 -07001393 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton02ee47c2018-01-10 16:26:06 -08001394 signaling_thread(), audio_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001395 GetAudioTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 11:26:01 -08001396 } else if (kind == MediaStreamTrackInterface::kVideoKind) {
Steve Anton47136dd2018-01-12 10:49:35 -08001397 auto* video_sender =
1398 new VideoRtpSender(worker_thread(), nullptr, stream_labels);
1399 video_sender->SetMediaChannel(video_media_channel());
deadbeefa601f5c2016-06-06 14:27:39 -07001400 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton02ee47c2018-01-10 16:26:06 -08001401 signaling_thread(), video_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001402 GetVideoTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 11:26:01 -08001403 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001404 RTC_LOG(LS_ERROR) << "CreateSender called with invalid kind: " << kind;
Steve Anton4171afb2017-11-20 10:20:22 -08001405 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08001406 }
Steve Anton4171afb2017-11-20 10:20:22 -08001407
deadbeefe1f9d832016-01-14 15:35:42 -08001408 return new_sender;
deadbeeffac06552015-11-25 11:26:01 -08001409}
1410
deadbeef70ab1a12015-09-28 16:53:55 -07001411std::vector<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::GetSenders()
1412 const {
deadbeefa601f5c2016-06-06 14:27:39 -07001413 std::vector<rtc::scoped_refptr<RtpSenderInterface>> ret;
Steve Anton4171afb2017-11-20 10:20:22 -08001414 for (auto sender : GetSendersInternal()) {
1415 ret.push_back(sender);
deadbeefa601f5c2016-06-06 14:27:39 -07001416 }
1417 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -07001418}
1419
Steve Anton4171afb2017-11-20 10:20:22 -08001420std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1421PeerConnection::GetSendersInternal() const {
1422 std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1423 all_senders;
1424 for (auto transceiver : transceivers_) {
1425 auto senders = transceiver->internal()->senders();
1426 all_senders.insert(all_senders.end(), senders.begin(), senders.end());
1427 }
1428 return all_senders;
1429}
1430
deadbeef70ab1a12015-09-28 16:53:55 -07001431std::vector<rtc::scoped_refptr<RtpReceiverInterface>>
1432PeerConnection::GetReceivers() const {
deadbeefa601f5c2016-06-06 14:27:39 -07001433 std::vector<rtc::scoped_refptr<RtpReceiverInterface>> ret;
Steve Anton4171afb2017-11-20 10:20:22 -08001434 for (const auto& receiver : GetReceiversInternal()) {
1435 ret.push_back(receiver);
deadbeefa601f5c2016-06-06 14:27:39 -07001436 }
1437 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -07001438}
1439
Steve Anton4171afb2017-11-20 10:20:22 -08001440std::vector<
1441 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1442PeerConnection::GetReceiversInternal() const {
1443 std::vector<
1444 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1445 all_receivers;
1446 for (auto transceiver : transceivers_) {
1447 auto receivers = transceiver->internal()->receivers();
1448 all_receivers.insert(all_receivers.end(), receivers.begin(),
1449 receivers.end());
1450 }
1451 return all_receivers;
1452}
1453
Steve Anton9158ef62017-11-27 13:01:52 -08001454std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
1455PeerConnection::GetTransceivers() const {
1456 RTC_DCHECK(IsUnifiedPlan());
1457 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> all_transceivers;
1458 for (auto transceiver : transceivers_) {
1459 all_transceivers.push_back(transceiver);
1460 }
1461 return all_transceivers;
1462}
1463
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001464bool PeerConnection::GetStats(StatsObserver* observer,
wu@webrtc.orgb9a088b2014-02-13 23:18:49 +00001465 MediaStreamTrackInterface* track,
1466 StatsOutputLevel level) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001467 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
deadbeef0a6c4ca2015-10-06 11:38:28 -07001468 RTC_DCHECK(signaling_thread()->IsCurrent());
nisse7ce109a2017-01-31 00:57:56 -08001469 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001470 RTC_LOG(LS_ERROR) << "GetStats - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001471 return false;
1472 }
1473
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001474 stats_->UpdateStats(level);
zhihuange9e94c32016-11-04 11:38:15 -07001475 // The StatsCollector is used to tell if a track is valid because it may
1476 // remember tracks that the PeerConnection previously removed.
1477 if (track && !stats_->IsValidTrack(track->id())) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001478 RTC_LOG(LS_WARNING) << "GetStats is called with an invalid track: "
1479 << track->id();
zhihuange9e94c32016-11-04 11:38:15 -07001480 return false;
1481 }
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001482 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_GETSTATS,
tommi@webrtc.org5b06b062014-08-15 08:38:30 +00001483 new GetStatsMsg(observer, track));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001484 return true;
1485}
1486
hbos74e1a4f2016-09-15 23:33:01 -07001487void PeerConnection::GetStats(RTCStatsCollectorCallback* callback) {
1488 RTC_DCHECK(stats_collector_);
1489 stats_collector_->GetStatsReport(callback);
1490}
1491
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001492PeerConnectionInterface::SignalingState PeerConnection::signaling_state() {
1493 return signaling_state_;
1494}
1495
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001496PeerConnectionInterface::IceConnectionState
1497PeerConnection::ice_connection_state() {
1498 return ice_connection_state_;
1499}
1500
1501PeerConnectionInterface::IceGatheringState
1502PeerConnection::ice_gathering_state() {
1503 return ice_gathering_state_;
1504}
1505
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001506rtc::scoped_refptr<DataChannelInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001507PeerConnection::CreateDataChannel(
1508 const std::string& label,
1509 const DataChannelInit* config) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001510 TRACE_EVENT0("webrtc", "PeerConnection::CreateDataChannel");
zhihuang9763d562016-08-05 11:14:50 -07001511
deadbeefab9b2d12015-10-14 11:33:11 -07001512 bool first_datachannel = !HasDataChannels();
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001513
kwibergd1fe2812016-04-27 06:47:29 -07001514 std::unique_ptr<InternalDataChannelInit> internal_config;
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00001515 if (config) {
1516 internal_config.reset(new InternalDataChannelInit(*config));
1517 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001518 rtc::scoped_refptr<DataChannelInterface> channel(
deadbeefab9b2d12015-10-14 11:33:11 -07001519 InternalCreateDataChannel(label, internal_config.get()));
1520 if (!channel.get()) {
1521 return nullptr;
1522 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001523
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001524 // Trigger the onRenegotiationNeeded event for every new RTP DataChannel, or
1525 // the first SCTP DataChannel.
Steve Anton75737c02017-11-06 10:37:17 -08001526 if (data_channel_type() == cricket::DCT_RTP || first_datachannel) {
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001527 observer_->OnRenegotiationNeeded();
1528 }
wu@webrtc.org91053e72013-08-10 07:18:04 +00001529
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001530 return DataChannelProxy::Create(signaling_thread(), channel.get());
1531}
1532
1533void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
1534 const MediaConstraintsInterface* constraints) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001535 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
Steve Anton8d3444d2017-10-20 15:30:51 -07001536
zhihuang1c378ed2017-08-17 14:10:50 -07001537 PeerConnectionInterface::RTCOfferAnswerOptions offer_answer_options;
1538 // Always create an offer even if |ConvertConstraintsToOfferAnswerOptions|
1539 // returns false for now. Because |ConvertConstraintsToOfferAnswerOptions|
1540 // compares the mandatory fields parsed with the mandatory fields added in the
1541 // |constraints| and some downstream applications might create offers with
1542 // mandatory fields which would not be parsed in the helper method. For
1543 // example, in Chromium/remoting, |kEnableDtlsSrtp| is added to the
1544 // |constraints| as a mandatory field but it is not parsed.
1545 ConvertConstraintsToOfferAnswerOptions(constraints, &offer_answer_options);
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001546
zhihuang1c378ed2017-08-17 14:10:50 -07001547 CreateOffer(observer, offer_answer_options);
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001548}
1549
1550void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
1551 const RTCOfferAnswerOptions& options) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001552 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
Steve Anton8d3444d2017-10-20 15:30:51 -07001553
nisse7ce109a2017-01-31 00:57:56 -08001554 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001555 RTC_LOG(LS_ERROR) << "CreateOffer - observer is NULL.";
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001556 return;
1557 }
deadbeefab9b2d12015-10-14 11:33:11 -07001558
Steve Anton8d3444d2017-10-20 15:30:51 -07001559 if (IsClosed()) {
1560 std::string error = "CreateOffer called when PeerConnection is closed.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001561 RTC_LOG(LS_ERROR) << error;
Steve Anton8d3444d2017-10-20 15:30:51 -07001562 PostCreateSessionDescriptionFailure(observer, error);
1563 return;
1564 }
1565
zhihuang1c378ed2017-08-17 14:10:50 -07001566 if (!ValidateOfferAnswerOptions(options)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001567 std::string error = "CreateOffer called with invalid options.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001568 RTC_LOG(LS_ERROR) << error;
deadbeefab9b2d12015-10-14 11:33:11 -07001569 PostCreateSessionDescriptionFailure(observer, error);
1570 return;
1571 }
1572
Steve Anton22da89f2018-01-25 13:58:07 -08001573 // Legacy handling for offer_to_receive_audio and offer_to_receive_video.
1574 // Specified in WebRTC section 4.4.3.2 "Legacy configuration extensions".
1575 if (IsUnifiedPlan()) {
1576 RTCError error = HandleLegacyOfferOptions(options);
1577 if (!error.ok()) {
1578 PostCreateSessionDescriptionFailure(observer, error.message());
1579 return;
1580 }
1581 }
1582
zhihuang1c378ed2017-08-17 14:10:50 -07001583 cricket::MediaSessionOptions session_options;
1584 GetOptionsForOffer(options, &session_options);
Steve Antond25da372017-11-06 14:50:29 -08001585 webrtc_session_desc_factory_->CreateOffer(observer, options, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001586}
1587
Steve Anton22da89f2018-01-25 13:58:07 -08001588RTCError PeerConnection::HandleLegacyOfferOptions(
1589 const RTCOfferAnswerOptions& options) {
1590 RTC_DCHECK(IsUnifiedPlan());
1591
1592 if (options.offer_to_receive_audio == 0) {
1593 RemoveRecvDirectionFromReceivingTransceiversOfType(
1594 cricket::MEDIA_TYPE_AUDIO);
1595 } else if (options.offer_to_receive_audio == 1) {
1596 AddUpToOneReceivingTransceiverOfType(cricket::MEDIA_TYPE_AUDIO);
1597 } else if (options.offer_to_receive_audio > 1) {
1598 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
1599 "offer_to_receive_audio > 1 is not supported.");
1600 }
1601
1602 if (options.offer_to_receive_video == 0) {
1603 RemoveRecvDirectionFromReceivingTransceiversOfType(
1604 cricket::MEDIA_TYPE_VIDEO);
1605 } else if (options.offer_to_receive_video == 1) {
1606 AddUpToOneReceivingTransceiverOfType(cricket::MEDIA_TYPE_VIDEO);
1607 } else if (options.offer_to_receive_video > 1) {
1608 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
1609 "offer_to_receive_video > 1 is not supported.");
1610 }
1611
1612 return RTCError::OK();
1613}
1614
1615void PeerConnection::RemoveRecvDirectionFromReceivingTransceiversOfType(
1616 cricket::MediaType media_type) {
1617 for (auto transceiver : GetReceivingTransceiversOfType(media_type)) {
1618 transceiver->internal()->set_direction(
1619 RtpTransceiverDirectionWithRecvSet(transceiver->direction(), false));
1620 }
1621}
1622
1623void PeerConnection::AddUpToOneReceivingTransceiverOfType(
1624 cricket::MediaType media_type) {
1625 if (GetReceivingTransceiversOfType(media_type).empty()) {
1626 RtpTransceiverInit init;
1627 init.direction = RtpTransceiverDirection::kRecvOnly;
1628 AddTransceiver(media_type, nullptr, init, /*fire_callback=*/false);
1629 }
1630}
1631
1632std::vector<rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
1633PeerConnection::GetReceivingTransceiversOfType(cricket::MediaType media_type) {
1634 std::vector<
1635 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
1636 receiving_transceivers;
1637 for (auto transceiver : transceivers_) {
1638 if (!transceiver->stopped() &&
1639 transceiver->internal()->media_type() == media_type &&
1640 RtpTransceiverDirectionHasRecv(transceiver->direction())) {
1641 receiving_transceivers.push_back(transceiver);
1642 }
1643 }
1644 return receiving_transceivers;
1645}
1646
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001647void PeerConnection::CreateAnswer(
1648 CreateSessionDescriptionObserver* observer,
1649 const MediaConstraintsInterface* constraints) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001650 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
Steve Anton8d3444d2017-10-20 15:30:51 -07001651
nisse7ce109a2017-01-31 00:57:56 -08001652 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001653 RTC_LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001654 return;
1655 }
deadbeefab9b2d12015-10-14 11:33:11 -07001656
zhihuang1c378ed2017-08-17 14:10:50 -07001657 PeerConnectionInterface::RTCOfferAnswerOptions offer_answer_options;
1658 if (!ConvertConstraintsToOfferAnswerOptions(constraints,
1659 &offer_answer_options)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001660 std::string error = "CreateAnswer called with invalid constraints.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001661 RTC_LOG(LS_ERROR) << error;
deadbeefab9b2d12015-10-14 11:33:11 -07001662 PostCreateSessionDescriptionFailure(observer, error);
1663 return;
1664 }
1665
Steve Anton8d3444d2017-10-20 15:30:51 -07001666 CreateAnswer(observer, offer_answer_options);
htaa2a49d92016-03-04 02:51:39 -08001667}
1668
1669void PeerConnection::CreateAnswer(CreateSessionDescriptionObserver* observer,
1670 const RTCOfferAnswerOptions& options) {
1671 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
nisse7ce109a2017-01-31 00:57:56 -08001672 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001673 RTC_LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
htaa2a49d92016-03-04 02:51:39 -08001674 return;
1675 }
1676
Taylor Brandstetter94d8cce2018-01-26 22:44:21 +00001677 if (IsClosed()) {
1678 std::string error = "CreateAnswer called when PeerConnection is closed.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001679 RTC_LOG(LS_ERROR) << error;
Steve Anton8d3444d2017-10-20 15:30:51 -07001680 PostCreateSessionDescriptionFailure(observer, error);
1681 return;
1682 }
1683
Taylor Brandstetter94d8cce2018-01-26 22:44:21 +00001684 if (remote_description() &&
1685 remote_description()->GetType() != SdpType::kOffer) {
1686 std::string error = "CreateAnswer called without remote offer.";
1687 RTC_LOG(LS_ERROR) << error;
1688 PostCreateSessionDescriptionFailure(observer, error);
1689 return;
1690 }
Steve Anton8d3444d2017-10-20 15:30:51 -07001691
Steve Anton22da89f2018-01-25 13:58:07 -08001692 if (IsUnifiedPlan()) {
1693 if (options.offer_to_receive_audio != RTCOfferAnswerOptions::kUndefined) {
1694 RTC_LOG(LS_WARNING) << "CreateAnswer: offer_to_receive_audio is not "
1695 "supported with Unified Plan semantics. Use the "
1696 "RtpTransceiver API instead.";
1697 }
1698 if (options.offer_to_receive_video != RTCOfferAnswerOptions::kUndefined) {
1699 RTC_LOG(LS_WARNING) << "CreateAnswer: offer_to_receive_video is not "
1700 "supported with Unified Plan semantics. Use the "
1701 "RtpTransceiver API instead.";
1702 }
1703 }
1704
htaa2a49d92016-03-04 02:51:39 -08001705 cricket::MediaSessionOptions session_options;
zhihuang1c378ed2017-08-17 14:10:50 -07001706 GetOptionsForAnswer(options, &session_options);
htaa2a49d92016-03-04 02:51:39 -08001707
Steve Antond25da372017-11-06 14:50:29 -08001708 webrtc_session_desc_factory_->CreateAnswer(observer, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001709}
1710
1711void PeerConnection::SetLocalDescription(
1712 SetSessionDescriptionObserver* observer,
1713 SessionDescriptionInterface* desc) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001714 TRACE_EVENT0("webrtc", "PeerConnection::SetLocalDescription");
Steve Anton8a006912017-12-04 15:25:56 -08001715
nisse7ce109a2017-01-31 00:57:56 -08001716 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001717 RTC_LOG(LS_ERROR) << "SetLocalDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001718 return;
1719 }
Steve Anton8a006912017-12-04 15:25:56 -08001720
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001721 if (!desc) {
1722 PostSetSessionDescriptionFailure(observer, "SessionDescription is NULL.");
1723 return;
1724 }
Steve Anton8d3444d2017-10-20 15:30:51 -07001725
Steve Antona3a92c22017-12-07 10:27:41 -08001726 SdpType type = desc->GetType();
Steve Anton8d3444d2017-10-20 15:30:51 -07001727
Steve Anton8a006912017-12-04 15:25:56 -08001728 RTCError error = ApplyLocalDescription(rtc::WrapUnique(desc));
1729 // |desc| may be destroyed at this point.
1730
1731 if (!error.ok()) {
Steve Antona3a92c22017-12-07 10:27:41 -08001732 std::ostringstream oss;
1733 oss << "Failed to set local " << SdpTypeToString(type)
1734 << " sdp: " << error.message();
1735 std::string error_message = oss.str();
Steve Anton8a006912017-12-04 15:25:56 -08001736 RTC_LOG(LS_ERROR) << error_message << " (" << error.type() << ")";
1737 PostSetSessionDescriptionFailure(observer, std::move(error_message));
Steve Anton8d3444d2017-10-20 15:30:51 -07001738 return;
1739 }
Steve Anton8a006912017-12-04 15:25:56 -08001740 RTC_DCHECK(local_description());
1741
1742 PostSetSessionDescriptionSuccess(observer);
1743
1744 // According to JSEP, after setLocalDescription, changing the candidate pool
1745 // size is not allowed, and changing the set of ICE servers will not result
1746 // in new candidates being gathered.
1747 port_allocator_->FreezeCandidatePool();
1748
1749 // MaybeStartGathering needs to be called after posting
1750 // MSG_SET_SESSIONDESCRIPTION_SUCCESS, so that we don't signal any candidates
1751 // before signaling that SetLocalDescription completed.
1752 transport_controller_->MaybeStartGathering();
1753
Steve Antona3a92c22017-12-07 10:27:41 -08001754 if (local_description()->GetType() == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08001755 // TODO(deadbeef): We already had to hop to the network thread for
1756 // MaybeStartGathering...
1757 network_thread()->Invoke<void>(
1758 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
1759 port_allocator_.get()));
1760 }
1761}
1762
1763RTCError PeerConnection::ApplyLocalDescription(
1764 std::unique_ptr<SessionDescriptionInterface> desc) {
1765 RTC_DCHECK_RUN_ON(signaling_thread());
1766 RTC_DCHECK(desc);
1767
1768 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_LOCAL);
1769 if (!error.ok()) {
1770 return error;
1771 }
Steve Anton8d3444d2017-10-20 15:30:51 -07001772
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001773 // Update stats here so that we have the most recent stats for tracks and
1774 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001775 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 15:25:56 -08001776
1777 // Update the initial_offerer flag if this session is the initial_offerer.
Steve Anton3828c062017-12-06 10:34:51 -08001778 SdpType type = desc->GetType();
Steve Anton8a006912017-12-04 15:25:56 -08001779 if (!initial_offerer_.has_value()) {
Steve Anton3828c062017-12-06 10:34:51 -08001780 initial_offerer_.emplace(type == SdpType::kOffer);
Steve Anton8a006912017-12-04 15:25:56 -08001781 if (*initial_offerer_) {
1782 transport_controller_->SetIceRole(cricket::ICEROLE_CONTROLLING);
1783 } else {
1784 transport_controller_->SetIceRole(cricket::ICEROLE_CONTROLLED);
1785 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001786 }
Steve Anton8a006912017-12-04 15:25:56 -08001787
Steve Antondcc3c022017-12-22 16:02:54 -08001788 // Take a reference to the old local description since it's used below to
1789 // compare against the new local description. When setting the new local
1790 // description, grab ownership of the replaced session description in case it
1791 // is the same as |old_local_description|, to keep it alive for the duration
1792 // of the method.
1793 const SessionDescriptionInterface* old_local_description =
1794 local_description();
1795 std::unique_ptr<SessionDescriptionInterface> replaced_local_description;
Steve Anton3828c062017-12-06 10:34:51 -08001796 if (type == SdpType::kAnswer) {
Steve Antondcc3c022017-12-22 16:02:54 -08001797 replaced_local_description = pending_local_description_
1798 ? std::move(pending_local_description_)
1799 : std::move(current_local_description_);
Steve Anton8a006912017-12-04 15:25:56 -08001800 current_local_description_ = std::move(desc);
1801 pending_local_description_ = nullptr;
1802 current_remote_description_ = std::move(pending_remote_description_);
1803 } else {
Steve Antondcc3c022017-12-22 16:02:54 -08001804 replaced_local_description = std::move(pending_local_description_);
Steve Anton8a006912017-12-04 15:25:56 -08001805 pending_local_description_ = std::move(desc);
1806 }
1807 // The session description to apply now must be accessed by
1808 // |local_description()|.
Henrik Boströmfdb92012017-11-09 19:55:44 +01001809 RTC_DCHECK(local_description());
deadbeefab9b2d12015-10-14 11:33:11 -07001810
Steve Antondcc3c022017-12-22 16:02:54 -08001811 if (IsUnifiedPlan()) {
1812 RTCError error = UpdateTransceiversAndDataChannels(
1813 cricket::CS_LOCAL, old_local_description, *local_description());
Steve Anton8a006912017-12-04 15:25:56 -08001814 if (!error.ok()) {
1815 return error;
1816 }
Steve Antondcc3c022017-12-22 16:02:54 -08001817 for (auto transceiver : transceivers_) {
1818 const ContentInfo* content =
1819 FindMediaSectionForTransceiver(transceiver, local_description());
1820 if (!content) {
1821 continue;
1822 }
1823 const MediaContentDescription* media_desc = content->media_description();
1824 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
1825 transceiver->internal()->set_current_direction(media_desc->direction());
1826 }
1827 if (content->rejected && !transceiver->stopped()) {
1828 transceiver->Stop();
1829 }
1830 }
1831 } else {
1832 // Transport and Media channels will be created only when offer is set.
1833 if (type == SdpType::kOffer) {
1834 // TODO(bugs.webrtc.org/4676) - Handle CreateChannel failure, as new local
1835 // description is applied. Restore back to old description.
1836 RTCError error = CreateChannels(*local_description()->description());
1837 if (!error.ok()) {
1838 return error;
1839 }
1840 }
Steve Anton8a006912017-12-04 15:25:56 -08001841
Steve Antondcc3c022017-12-22 16:02:54 -08001842 // Remove unused channels if MediaContentDescription is rejected.
1843 RemoveUnusedChannels(local_description()->description());
1844 }
Steve Anton8a006912017-12-04 15:25:56 -08001845
Steve Anton3828c062017-12-06 10:34:51 -08001846 error = UpdateSessionState(type, cricket::CS_LOCAL);
Steve Anton8a006912017-12-04 15:25:56 -08001847 if (!error.ok()) {
1848 return error;
1849 }
Steve Antondcc3c022017-12-22 16:02:54 -08001850
Steve Anton8a006912017-12-04 15:25:56 -08001851 if (remote_description()) {
1852 // Now that we have a local description, we can push down remote candidates.
1853 UseCandidatesInSessionDescription(remote_description());
1854 }
1855
1856 pending_ice_restarts_.clear();
1857 if (session_error() != SessionError::kNone) {
1858 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
1859 }
1860
deadbeefab9b2d12015-10-14 11:33:11 -07001861 // If setting the description decided our SSL role, allocate any necessary
1862 // SCTP sids.
1863 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08001864 if (data_channel_type() == cricket::DCT_SCTP && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001865 AllocateSctpSids(role);
1866 }
1867
Steve Antond3679212018-01-17 17:41:02 -08001868 if (IsUnifiedPlan()) {
1869 for (auto transceiver : transceivers_) {
1870 const ContentInfo* content =
1871 FindMediaSectionForTransceiver(transceiver, local_description());
1872 if (!content) {
1873 continue;
1874 }
1875 if (content->rejected && !transceiver->stopped()) {
1876 transceiver->Stop();
1877 }
Steve Anton74255ff2018-01-24 18:32:57 -08001878 const auto& streams = content->media_description()->streams();
1879 if (!content->rejected && !streams.empty()) {
Steve Antond3679212018-01-17 17:41:02 -08001880 transceiver->internal()->sender_internal()->set_stream_ids(
Steve Anton74255ff2018-01-24 18:32:57 -08001881 {streams[0].sync_label});
Steve Antond3679212018-01-17 17:41:02 -08001882 transceiver->internal()->sender_internal()->SetSsrc(
Steve Anton74255ff2018-01-24 18:32:57 -08001883 streams[0].first_ssrc());
Steve Antond3679212018-01-17 17:41:02 -08001884 }
1885 }
1886 } else {
1887 // Plan B semantics.
1888
Steve Antondcc3c022017-12-22 16:02:54 -08001889 // Update state and SSRC of local MediaStreams and DataChannels based on the
1890 // local session description.
1891 const cricket::ContentInfo* audio_content =
1892 GetFirstAudioContent(local_description()->description());
1893 if (audio_content) {
1894 if (audio_content->rejected) {
1895 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
1896 } else {
1897 const cricket::AudioContentDescription* audio_desc =
1898 audio_content->media_description()->as_audio();
1899 UpdateLocalSenders(audio_desc->streams(), audio_desc->type());
1900 }
deadbeeffaac4972015-11-12 15:33:07 -08001901 }
deadbeefab9b2d12015-10-14 11:33:11 -07001902
Steve Antondcc3c022017-12-22 16:02:54 -08001903 const cricket::ContentInfo* video_content =
1904 GetFirstVideoContent(local_description()->description());
1905 if (video_content) {
1906 if (video_content->rejected) {
1907 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
1908 } else {
1909 const cricket::VideoContentDescription* video_desc =
1910 video_content->media_description()->as_video();
1911 UpdateLocalSenders(video_desc->streams(), video_desc->type());
1912 }
deadbeeffaac4972015-11-12 15:33:07 -08001913 }
deadbeefab9b2d12015-10-14 11:33:11 -07001914 }
1915
1916 const cricket::ContentInfo* data_content =
Henrik Boströmfdb92012017-11-09 19:55:44 +01001917 GetFirstDataContent(local_description()->description());
deadbeefab9b2d12015-10-14 11:33:11 -07001918 if (data_content) {
1919 const cricket::DataContentDescription* data_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08001920 data_content->media_description()->as_data();
deadbeefab9b2d12015-10-14 11:33:11 -07001921 if (rtc::starts_with(data_desc->protocol().data(),
1922 cricket::kMediaProtocolRtpPrefix)) {
1923 UpdateLocalRtpDataChannels(data_desc->streams());
1924 }
1925 }
1926
Steve Anton8a006912017-12-04 15:25:56 -08001927 return RTCError::OK();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001928}
1929
1930void PeerConnection::SetRemoteDescription(
Henrik Boströma4ecf552017-11-23 14:17:07 +00001931 SetSessionDescriptionObserver* observer,
1932 SessionDescriptionInterface* desc) {
Henrik Boström31638672017-11-23 17:48:32 +01001933 SetRemoteDescription(
1934 std::unique_ptr<SessionDescriptionInterface>(desc),
1935 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface>(
1936 new SetRemoteDescriptionObserverAdapter(this, observer)));
1937}
1938
1939void PeerConnection::SetRemoteDescription(
1940 std::unique_ptr<SessionDescriptionInterface> desc,
1941 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface> observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001942 TRACE_EVENT0("webrtc", "PeerConnection::SetRemoteDescription");
Steve Anton8a006912017-12-04 15:25:56 -08001943
nisse7ce109a2017-01-31 00:57:56 -08001944 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001945 RTC_LOG(LS_ERROR) << "SetRemoteDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001946 return;
1947 }
Steve Anton8a006912017-12-04 15:25:56 -08001948
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001949 if (!desc) {
Henrik Boström31638672017-11-23 17:48:32 +01001950 observer->OnSetRemoteDescriptionComplete(RTCError(
Steve Anton8a006912017-12-04 15:25:56 -08001951 RTCErrorType::INVALID_PARAMETER, "SessionDescription is NULL."));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001952 return;
1953 }
Steve Anton8d3444d2017-10-20 15:30:51 -07001954
Steve Antona3a92c22017-12-07 10:27:41 -08001955 const SdpType type = desc->GetType();
Steve Anton8a006912017-12-04 15:25:56 -08001956
1957 RTCError error = ApplyRemoteDescription(std::move(desc));
1958 // |desc| may be destroyed at this point.
1959
1960 if (!error.ok()) {
Steve Antona3a92c22017-12-07 10:27:41 -08001961 std::ostringstream oss;
1962 oss << "Failed to set remote " << SdpTypeToString(type)
1963 << " sdp: " << error.message();
1964 std::string error_message = oss.str();
Steve Anton8a006912017-12-04 15:25:56 -08001965 RTC_LOG(LS_ERROR) << error_message << " (" << error.type() << ")";
Henrik Boström31638672017-11-23 17:48:32 +01001966 observer->OnSetRemoteDescriptionComplete(
Steve Anton8a006912017-12-04 15:25:56 -08001967 RTCError(error.type(), std::move(error_message)));
Steve Anton8d3444d2017-10-20 15:30:51 -07001968 return;
1969 }
1970
Steve Antona3a92c22017-12-07 10:27:41 -08001971 if (remote_description()->GetType() == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08001972 // TODO(deadbeef): We already had to hop to the network thread for
1973 // MaybeStartGathering...
1974 network_thread()->Invoke<void>(
1975 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
1976 port_allocator_.get()));
1977 }
1978
1979 observer->OnSetRemoteDescriptionComplete(RTCError::OK());
1980}
1981
1982RTCError PeerConnection::ApplyRemoteDescription(
1983 std::unique_ptr<SessionDescriptionInterface> desc) {
1984 RTC_DCHECK_RUN_ON(signaling_thread());
1985 RTC_DCHECK(desc);
1986
1987 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_REMOTE);
1988 if (!error.ok()) {
1989 return error;
1990 }
1991
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001992 // Update stats here so that we have the most recent stats for tracks and
1993 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001994 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 15:25:56 -08001995
Steve Antondcc3c022017-12-22 16:02:54 -08001996 // Take a reference to the old remote description since it's used below to
1997 // compare against the new remote description. When setting the new remote
1998 // description, grab ownership of the replaced session description in case it
1999 // is the same as |old_remote_description|, to keep it alive for the duration
2000 // of the method.
Steve Anton8a006912017-12-04 15:25:56 -08002001 const SessionDescriptionInterface* old_remote_description =
2002 remote_description();
Steve Anton8a006912017-12-04 15:25:56 -08002003 std::unique_ptr<SessionDescriptionInterface> replaced_remote_description;
Steve Anton3828c062017-12-06 10:34:51 -08002004 SdpType type = desc->GetType();
2005 if (type == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002006 replaced_remote_description = pending_remote_description_
2007 ? std::move(pending_remote_description_)
2008 : std::move(current_remote_description_);
2009 current_remote_description_ = std::move(desc);
2010 pending_remote_description_ = nullptr;
2011 current_local_description_ = std::move(pending_local_description_);
2012 } else {
2013 replaced_remote_description = std::move(pending_remote_description_);
2014 pending_remote_description_ = std::move(desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002015 }
Steve Anton8a006912017-12-04 15:25:56 -08002016 // The session description to apply now must be accessed by
2017 // |remote_description()|.
Henrik Boströmfdb92012017-11-09 19:55:44 +01002018 RTC_DCHECK(remote_description());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002019
Steve Anton8a006912017-12-04 15:25:56 -08002020 // Transport and Media channels will be created only when offer is set.
Steve Antondcc3c022017-12-22 16:02:54 -08002021 if (IsUnifiedPlan()) {
2022 RTCError error = UpdateTransceiversAndDataChannels(
2023 cricket::CS_REMOTE, old_remote_description, *remote_description());
Steve Anton8a006912017-12-04 15:25:56 -08002024 if (!error.ok()) {
2025 return error;
2026 }
Steve Antondcc3c022017-12-22 16:02:54 -08002027 } else {
2028 if (type == SdpType::kOffer) {
2029 // TODO(bugs.webrtc.org/4676) - Handle CreateChannel failure, as new local
2030 // description is applied. Restore back to old description.
2031 RTCError error = CreateChannels(*remote_description()->description());
2032 if (!error.ok()) {
2033 return error;
2034 }
2035 }
Steve Anton8a006912017-12-04 15:25:56 -08002036
Steve Antondcc3c022017-12-22 16:02:54 -08002037 // Remove unused channels if MediaContentDescription is rejected.
2038 RemoveUnusedChannels(remote_description()->description());
2039 }
Steve Anton8a006912017-12-04 15:25:56 -08002040
2041 // NOTE: Candidates allocation will be initiated only when SetLocalDescription
2042 // is called.
Steve Anton3828c062017-12-06 10:34:51 -08002043 error = UpdateSessionState(type, cricket::CS_REMOTE);
Steve Anton8a006912017-12-04 15:25:56 -08002044 if (!error.ok()) {
2045 return error;
2046 }
2047
2048 if (local_description() &&
2049 !UseCandidatesInSessionDescription(remote_description())) {
2050 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidCandidates);
2051 }
2052
2053 if (old_remote_description) {
2054 for (const cricket::ContentInfo& content :
2055 old_remote_description->description()->contents()) {
2056 // Check if this new SessionDescription contains new ICE ufrag and
2057 // password that indicates the remote peer requests an ICE restart.
2058 // TODO(deadbeef): When we start storing both the current and pending
2059 // remote description, this should reset pending_ice_restarts and compare
2060 // against the current description.
2061 if (CheckForRemoteIceRestart(old_remote_description, remote_description(),
2062 content.name)) {
Steve Anton3828c062017-12-06 10:34:51 -08002063 if (type == SdpType::kOffer) {
Steve Anton8a006912017-12-04 15:25:56 -08002064 pending_ice_restarts_.insert(content.name);
2065 }
2066 } else {
2067 // We retain all received candidates only if ICE is not restarted.
2068 // When ICE is restarted, all previous candidates belong to an old
2069 // generation and should not be kept.
2070 // TODO(deadbeef): This goes against the W3C spec which says the remote
2071 // description should only contain candidates from the last set remote
2072 // description plus any candidates added since then. We should remove
2073 // this once we're sure it won't break anything.
2074 WebRtcSessionDescriptionFactory::CopyCandidatesFromSessionDescription(
2075 old_remote_description, content.name, mutable_remote_description());
2076 }
2077 }
2078 }
2079
2080 if (session_error() != SessionError::kNone) {
2081 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
2082 }
2083
2084 // Set the the ICE connection state to connecting since the connection may
2085 // become writable with peer reflexive candidates before any remote candidate
2086 // is signaled.
2087 // TODO(pthatcher): This is a short-term solution for crbug/446908. A real fix
2088 // is to have a new signal the indicates a change in checking state from the
2089 // transport and expose a new checking() member from transport that can be
2090 // read to determine the current checking state. The existing SignalConnecting
2091 // actually means "gathering candidates", so cannot be be used here.
Steve Antona3a92c22017-12-07 10:27:41 -08002092 if (remote_description()->GetType() != SdpType::kOffer &&
Steve Anton8a006912017-12-04 15:25:56 -08002093 ice_connection_state() == PeerConnectionInterface::kIceConnectionNew) {
2094 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
2095 }
2096
deadbeefab9b2d12015-10-14 11:33:11 -07002097 // If setting the description decided our SSL role, allocate any necessary
2098 // SCTP sids.
2099 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08002100 if (data_channel_type() == cricket::DCT_SCTP && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07002101 AllocateSctpSids(role);
2102 }
2103
Steve Antondcc3c022017-12-22 16:02:54 -08002104 if (IsUnifiedPlan()) {
Steve Antonef65ef12018-01-10 17:15:20 -08002105 std::vector<TrackEvent> track_events;
Steve Antondcc3c022017-12-22 16:02:54 -08002106 for (auto transceiver : transceivers_) {
2107 const ContentInfo* content =
2108 FindMediaSectionForTransceiver(transceiver, remote_description());
2109 if (!content) {
2110 continue;
2111 }
2112 const MediaContentDescription* media_desc = content->media_description();
2113 RtpTransceiverDirection local_direction =
2114 RtpTransceiverDirectionReversed(media_desc->direction());
2115 // From the WebRTC specification, steps 2.2.8.5/6 of section 4.4.1.6 "Set
2116 // the RTCSessionDescription: If direction is sendrecv or recvonly, and
2117 // transceiver's current direction is neither sendrecv nor recvonly,
2118 // process the addition of a remote track for the media description.
2119 if (RtpTransceiverDirectionHasRecv(local_direction) &&
2120 (!transceiver->current_direction() ||
2121 !RtpTransceiverDirectionHasRecv(
Steve Anton74255ff2018-01-24 18:32:57 -08002122 *transceiver->current_direction())) &&
2123 !media_desc->streams().empty()) {
Steve Antonef65ef12018-01-10 17:15:20 -08002124 const std::string& sync_label = media_desc->streams()[0].sync_label;
2125 rtc::scoped_refptr<MediaStreamInterface> stream =
2126 remote_streams_->find(sync_label);
2127 if (!stream) {
2128 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
2129 MediaStream::Create(sync_label));
2130 remote_streams_->AddStream(stream);
2131 }
2132 transceiver->internal()->receiver_internal()->SetStreams({stream});
2133 TrackEvent track_event;
2134 track_event.receiver = transceiver->receiver();
2135 track_event.streams = transceiver->receiver()->streams();
2136 track_events.push_back(std::move(track_event));
Steve Antondcc3c022017-12-22 16:02:54 -08002137 }
2138 // If direction is sendonly or inactive, and transceiver's current
2139 // direction is neither sendonly nor inactive, process the removal of a
2140 // remote track for the media description.
2141 if (!RtpTransceiverDirectionHasRecv(local_direction) &&
Steve Antonef65ef12018-01-10 17:15:20 -08002142 (transceiver->current_direction() &&
Steve Antondcc3c022017-12-22 16:02:54 -08002143 RtpTransceiverDirectionHasRecv(*transceiver->current_direction()))) {
Steve Antonef65ef12018-01-10 17:15:20 -08002144 transceiver->internal()->receiver_internal()->SetStreams({});
Steve Antondcc3c022017-12-22 16:02:54 -08002145 }
2146 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
2147 transceiver->internal()->set_current_direction(local_direction);
2148 }
2149 if (content->rejected && !transceiver->stopped()) {
2150 transceiver->Stop();
2151 }
Steve Anton74255ff2018-01-24 18:32:57 -08002152 if (!content->rejected && !media_desc->streams().empty()) {
Steve Antond3679212018-01-17 17:41:02 -08002153 const auto& stream = content->media_description()->streams()[0];
2154 transceiver->internal()->receiver_internal()->SetupMediaChannel(
2155 stream.first_ssrc());
2156 }
Steve Antondcc3c022017-12-22 16:02:54 -08002157 }
Steve Antonef65ef12018-01-10 17:15:20 -08002158 for (auto event : track_events) {
2159 observer_->OnAddTrack(event.receiver, event.streams);
2160 }
Steve Antondcc3c022017-12-22 16:02:54 -08002161 }
2162
Henrik Boströmfdb92012017-11-09 19:55:44 +01002163 const cricket::ContentInfo* audio_content =
2164 GetFirstAudioContent(remote_description()->description());
2165 const cricket::ContentInfo* video_content =
2166 GetFirstVideoContent(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002167 const cricket::AudioContentDescription* audio_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002168 GetFirstAudioContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002169 const cricket::VideoContentDescription* video_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002170 GetFirstVideoContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002171 const cricket::DataContentDescription* data_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002172 GetFirstDataContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002173
2174 // Check if the descriptions include streams, just in case the peer supports
2175 // MSID, but doesn't indicate so with "a=msid-semantic".
Henrik Boströmfdb92012017-11-09 19:55:44 +01002176 if (remote_description()->description()->msid_supported() ||
deadbeefbda7e0b2015-12-08 17:13:40 -08002177 (audio_desc && !audio_desc->streams().empty()) ||
2178 (video_desc && !video_desc->streams().empty())) {
2179 remote_peer_supports_msid_ = true;
2180 }
deadbeefab9b2d12015-10-14 11:33:11 -07002181
2182 // We wait to signal new streams until we finish processing the description,
2183 // since only at that point will new streams have all their tracks.
2184 rtc::scoped_refptr<StreamCollection> new_streams(StreamCollection::Create());
2185
Steve Antondcc3c022017-12-22 16:02:54 -08002186 if (!IsUnifiedPlan()) {
2187 // TODO(steveanton): When removing RTP senders/receivers in response to a
2188 // rejected media section, there is some cleanup logic that expects the
2189 // voice/ video channel to still be set. But in this method the voice/video
2190 // channel would have been destroyed by the SetRemoteDescription caller
2191 // above so the cleanup that relies on them fails to run. The RemoveSenders
2192 // calls should be moved to right before the DestroyChannel calls to fix
2193 // this.
Steve Anton8d3444d2017-10-20 15:30:51 -07002194
Steve Antondcc3c022017-12-22 16:02:54 -08002195 // Find all audio rtp streams and create corresponding remote AudioTracks
2196 // and MediaStreams.
2197 if (audio_content) {
2198 if (audio_content->rejected) {
2199 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
2200 } else {
2201 bool default_audio_track_needed =
2202 !remote_peer_supports_msid_ &&
2203 RtpTransceiverDirectionHasSend(audio_desc->direction());
2204 UpdateRemoteSendersList(GetActiveStreams(audio_desc),
2205 default_audio_track_needed, audio_desc->type(),
2206 new_streams);
2207 }
deadbeeffaac4972015-11-12 15:33:07 -08002208 }
deadbeefab9b2d12015-10-14 11:33:11 -07002209
Steve Antondcc3c022017-12-22 16:02:54 -08002210 // Find all video rtp streams and create corresponding remote VideoTracks
2211 // and MediaStreams.
2212 if (video_content) {
2213 if (video_content->rejected) {
2214 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
2215 } else {
2216 bool default_video_track_needed =
2217 !remote_peer_supports_msid_ &&
2218 RtpTransceiverDirectionHasSend(video_desc->direction());
2219 UpdateRemoteSendersList(GetActiveStreams(video_desc),
2220 default_video_track_needed, video_desc->type(),
2221 new_streams);
2222 }
deadbeeffaac4972015-11-12 15:33:07 -08002223 }
deadbeefab9b2d12015-10-14 11:33:11 -07002224
Steve Antondcc3c022017-12-22 16:02:54 -08002225 // Update the DataChannels with the information from the remote peer.
2226 if (data_desc) {
2227 if (rtc::starts_with(data_desc->protocol().data(),
2228 cricket::kMediaProtocolRtpPrefix)) {
2229 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
2230 }
deadbeefab9b2d12015-10-14 11:33:11 -07002231 }
deadbeefab9b2d12015-10-14 11:33:11 -07002232
Steve Antondcc3c022017-12-22 16:02:54 -08002233 // Iterate new_streams and notify the observer about new MediaStreams.
2234 for (size_t i = 0; i < new_streams->count(); ++i) {
2235 MediaStreamInterface* new_stream = new_streams->at(i);
2236 stats_->AddStream(new_stream);
2237 observer_->OnAddStream(
2238 rtc::scoped_refptr<MediaStreamInterface>(new_stream));
2239 }
deadbeefab9b2d12015-10-14 11:33:11 -07002240
Steve Antondcc3c022017-12-22 16:02:54 -08002241 UpdateEndedRemoteMediaStreams();
2242 }
deadbeefab9b2d12015-10-14 11:33:11 -07002243
Steve Anton8a006912017-12-04 15:25:56 -08002244 return RTCError::OK();
deadbeeffc648b62015-10-13 16:42:33 -07002245}
2246
Steve Antondcc3c022017-12-22 16:02:54 -08002247RTCError PeerConnection::UpdateTransceiversAndDataChannels(
2248 cricket::ContentSource source,
2249 const SessionDescriptionInterface* old_session,
2250 const SessionDescriptionInterface& new_session) {
2251 RTC_DCHECK(IsUnifiedPlan());
2252
Steve Anton7464fca2018-01-19 11:10:37 -08002253 const cricket::ContentGroup* bundle_group = nullptr;
2254 if (new_session.GetType() == SdpType::kOffer) {
2255 auto bundle_group_or_error =
2256 GetEarlyBundleGroup(*new_session.description());
2257 if (!bundle_group_or_error.ok()) {
2258 return bundle_group_or_error.MoveError();
2259 }
2260 bundle_group = bundle_group_or_error.MoveValue();
Steve Antondcc3c022017-12-22 16:02:54 -08002261 }
Steve Antondcc3c022017-12-22 16:02:54 -08002262
2263 const ContentInfos& old_contents =
2264 (old_session ? old_session->description()->contents() : ContentInfos());
2265 const ContentInfos& new_contents = new_session.description()->contents();
2266
2267 for (size_t i = 0; i < new_contents.size(); ++i) {
2268 const cricket::ContentInfo& new_content = new_contents[i];
2269 const cricket::ContentInfo* old_content =
2270 (i < old_contents.size() ? &old_contents[i] : nullptr);
2271 cricket::MediaType media_type = new_content.media_description()->type();
2272 seen_mids_.insert(new_content.name);
2273 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
2274 media_type == cricket::MEDIA_TYPE_VIDEO) {
2275 auto transceiver_or_error =
2276 AssociateTransceiver(source, i, new_content, old_content);
2277 if (!transceiver_or_error.ok()) {
2278 return transceiver_or_error.MoveError();
2279 }
2280 auto transceiver = transceiver_or_error.MoveValue();
Steve Antondcc3c022017-12-22 16:02:54 -08002281 RTCError error =
2282 UpdateTransceiverChannel(transceiver, new_content, bundle_group);
2283 if (!error.ok()) {
2284 return error;
2285 }
2286 } else if (media_type == cricket::MEDIA_TYPE_DATA) {
Steve Antonfa2260d2017-12-28 16:38:23 -08002287 if (GetDataMid() && new_content.name != *GetDataMid()) {
2288 // Ignore all but the first data section.
2289 continue;
2290 }
2291 RTCError error = UpdateDataChannel(source, new_content, bundle_group);
2292 if (!error.ok()) {
2293 return error;
2294 }
Steve Antondcc3c022017-12-22 16:02:54 -08002295 } else {
2296 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
2297 "Unknown section type.");
2298 }
2299 }
2300
2301 return RTCError::OK();
2302}
2303
2304RTCError PeerConnection::UpdateTransceiverChannel(
2305 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2306 transceiver,
2307 const cricket::ContentInfo& content,
2308 const cricket::ContentGroup* bundle_group) {
2309 RTC_DCHECK(IsUnifiedPlan());
2310 RTC_DCHECK(transceiver);
2311 cricket::BaseChannel* channel = transceiver->internal()->channel();
2312 if (content.rejected) {
2313 if (channel) {
2314 transceiver->internal()->SetChannel(nullptr);
2315 DestroyBaseChannel(channel);
2316 }
2317 } else {
2318 if (!channel) {
2319 if (transceiver->internal()->media_type() == cricket::MEDIA_TYPE_AUDIO) {
2320 channel = CreateVoiceChannel(
2321 content.name,
2322 GetTransportNameForMediaSection(content.name, bundle_group));
2323 } else {
2324 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO,
2325 transceiver->internal()->media_type());
2326 channel = CreateVideoChannel(
2327 content.name,
2328 GetTransportNameForMediaSection(content.name, bundle_group));
2329 }
2330 if (!channel) {
2331 LOG_AND_RETURN_ERROR(
2332 RTCErrorType::INTERNAL_ERROR,
2333 "Failed to create channel for mid=" + content.name);
2334 }
2335 transceiver->internal()->SetChannel(channel);
2336 }
2337 }
2338 return RTCError::OK();
2339}
2340
Steve Antonfa2260d2017-12-28 16:38:23 -08002341RTCError PeerConnection::UpdateDataChannel(
2342 cricket::ContentSource source,
2343 const cricket::ContentInfo& content,
2344 const cricket::ContentGroup* bundle_group) {
2345 if (data_channel_type_ == cricket::DCT_NONE) {
Steve Antondbf9d032018-01-19 15:23:40 -08002346 // If data channels are disabled, ignore this media section. CreateAnswer
2347 // will take care of rejecting it.
2348 return RTCError::OK();
Steve Antonfa2260d2017-12-28 16:38:23 -08002349 }
2350 if (content.rejected) {
2351 DestroyDataChannel();
2352 } else {
2353 if (!rtp_data_channel_ && !sctp_transport_) {
2354 if (!CreateDataChannel(content.name, GetTransportNameForMediaSection(
2355 content.name, bundle_group))) {
2356 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
2357 "Failed to create data channel.");
2358 }
2359 }
2360 if (source == cricket::CS_REMOTE) {
2361 const MediaContentDescription* data_desc = content.media_description();
2362 if (data_desc && cricket::IsRtpProtocol(data_desc->protocol())) {
2363 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
2364 }
2365 }
2366 }
2367 return RTCError::OK();
2368}
2369
Steve Antondcc3c022017-12-22 16:02:54 -08002370RTCErrorOr<rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
2371PeerConnection::AssociateTransceiver(cricket::ContentSource source,
2372 size_t mline_index,
2373 const ContentInfo& content,
2374 const ContentInfo* old_content) {
2375 RTC_DCHECK(IsUnifiedPlan());
2376 // If the m= section is being recycled (rejected in previous remote
2377 // description, not rejected in current description), dissociate the currently
2378 // associated RtpTransceiver by setting its mid property to null, and discard
2379 // the mapping between the transceiver and its m= section index.
2380 if (old_content && old_content->rejected && !content.rejected) {
2381 auto old_transceiver = GetAssociatedTransceiver(old_content->name);
2382 if (old_transceiver) {
2383 old_transceiver->internal()->set_mid(rtc::nullopt);
2384 old_transceiver->internal()->set_mline_index(rtc::nullopt);
2385 }
2386 }
2387 const MediaContentDescription* media_desc = content.media_description();
2388 auto transceiver = GetAssociatedTransceiver(content.name);
2389 if (source == cricket::CS_LOCAL) {
2390 // Find the RtpTransceiver that corresponds to this m= section, using the
2391 // mapping between transceivers and m= section indices established when
2392 // creating the offer.
2393 if (!transceiver) {
2394 transceiver = GetTransceiverByMLineIndex(mline_index);
2395 }
2396 if (!transceiver) {
2397 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2398 "Unknown transceiver");
2399 }
2400 } else {
2401 RTC_DCHECK_EQ(source, cricket::CS_REMOTE);
2402 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers
2403 // of the same type...
2404 if (!transceiver &&
2405 RtpTransceiverDirectionHasRecv(media_desc->direction())) {
2406 transceiver = FindAvailableTransceiverToReceive(media_desc->type());
2407 }
2408 // If no RtpTransceiver was found in the previous step, create one with a
2409 // recvonly direction.
2410 if (!transceiver) {
Steve Anton02ee47c2018-01-10 16:26:06 -08002411 auto sender =
2412 CreateSender(media_desc->type(), nullptr, {rtc::CreateRandomUuid()});
2413 auto receiver =
2414 CreateReceiver(media_desc->type(), media_desc->streams()[0].id);
2415 transceiver = CreateAndAddTransceiver(sender, receiver);
Steve Antondcc3c022017-12-22 16:02:54 -08002416 transceiver->internal()->set_direction(
2417 RtpTransceiverDirection::kRecvOnly);
2418 }
2419 }
2420 RTC_DCHECK(transceiver);
2421 if (transceiver->internal()->media_type() != media_desc->type()) {
2422 LOG_AND_RETURN_ERROR(
2423 RTCErrorType::INVALID_PARAMETER,
2424 "Transceiver type does not match media description type.");
2425 }
2426 // Associate the found or created RtpTransceiver with the m= section by
2427 // setting the value of the RtpTransceiver's mid property to the MID of the m=
2428 // section, and establish a mapping between the transceiver and the index of
2429 // the m= section.
2430 transceiver->internal()->set_mid(content.name);
2431 transceiver->internal()->set_mline_index(mline_index);
2432 return std::move(transceiver);
2433}
2434
2435rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2436PeerConnection::GetAssociatedTransceiver(const std::string& mid) const {
2437 RTC_DCHECK(IsUnifiedPlan());
2438 for (auto transceiver : transceivers_) {
2439 if (transceiver->mid() == mid) {
2440 return transceiver;
2441 }
2442 }
2443 return nullptr;
2444}
2445
2446rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2447PeerConnection::GetTransceiverByMLineIndex(size_t mline_index) const {
2448 RTC_DCHECK(IsUnifiedPlan());
2449 for (auto transceiver : transceivers_) {
2450 if (transceiver->internal()->mline_index() == mline_index) {
2451 return transceiver;
2452 }
2453 }
2454 return nullptr;
2455}
2456
2457rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2458PeerConnection::FindAvailableTransceiverToReceive(
2459 cricket::MediaType media_type) const {
2460 RTC_DCHECK(IsUnifiedPlan());
2461 // From JSEP section 5.10 (Applying a Remote Description):
2462 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers of
2463 // the same type that were added to the PeerConnection by addTrack and are not
2464 // associated with any m= section and are not stopped, find the first such
2465 // RtpTransceiver.
2466 for (auto transceiver : transceivers_) {
2467 if (transceiver->internal()->media_type() == media_type &&
2468 transceiver->internal()->created_by_addtrack() && !transceiver->mid() &&
2469 !transceiver->stopped()) {
2470 return transceiver;
2471 }
2472 }
2473 return nullptr;
2474}
2475
Steve Antoned10bd92017-12-05 10:52:59 -08002476const cricket::ContentInfo* PeerConnection::FindMediaSectionForTransceiver(
2477 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2478 transceiver,
2479 const SessionDescriptionInterface* sdesc) const {
2480 RTC_DCHECK(transceiver);
2481 RTC_DCHECK(sdesc);
2482 if (IsUnifiedPlan()) {
2483 if (!transceiver->internal()->mid()) {
2484 // This transceiver is not associated with a media section yet.
2485 return nullptr;
2486 }
2487 return sdesc->description()->GetContentByName(
2488 *transceiver->internal()->mid());
2489 } else {
2490 // Plan B only allows at most one audio and one video section, so use the
2491 // first media section of that type.
2492 return cricket::GetFirstMediaContent(sdesc->description()->contents(),
2493 transceiver->internal()->media_type());
2494 }
2495}
2496
deadbeef46c73892016-11-16 19:42:04 -08002497PeerConnectionInterface::RTCConfiguration PeerConnection::GetConfiguration() {
2498 return configuration_;
2499}
2500
deadbeef293e9262017-01-11 12:28:30 -08002501bool PeerConnection::SetConfiguration(const RTCConfiguration& configuration,
2502 RTCError* error) {
Peter Boström1a9d6152015-12-08 22:15:17 +01002503 TRACE_EVENT0("webrtc", "PeerConnection::SetConfiguration");
deadbeef6de92f92016-12-12 18:49:32 -08002504
Steve Anton75737c02017-11-06 10:37:17 -08002505 if (local_description() && configuration.ice_candidate_pool_size !=
2506 configuration_.ice_candidate_pool_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002507 RTC_LOG(LS_ERROR) << "Can't change candidate pool size after calling "
2508 "SetLocalDescription.";
deadbeef293e9262017-01-11 12:28:30 -08002509 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00002510 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002511
deadbeef293e9262017-01-11 12:28:30 -08002512 // The simplest (and most future-compatible) way to tell if the config was
2513 // modified in an invalid way is to copy each property we do support
2514 // modifying, then use operator==. There are far more properties we don't
2515 // support modifying than those we do, and more could be added.
2516 RTCConfiguration modified_config = configuration_;
2517 modified_config.servers = configuration.servers;
2518 modified_config.type = configuration.type;
2519 modified_config.ice_candidate_pool_size =
2520 configuration.ice_candidate_pool_size;
2521 modified_config.prune_turn_ports = configuration.prune_turn_ports;
skvladd1f5fda2017-02-03 16:54:05 -08002522 modified_config.ice_check_min_interval = configuration.ice_check_min_interval;
Jonas Orelandbdcee282017-10-10 14:01:40 +02002523 modified_config.turn_customizer = configuration.turn_customizer;
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08002524 modified_config.network_preference = configuration.network_preference;
deadbeef293e9262017-01-11 12:28:30 -08002525 if (configuration != modified_config) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002526 RTC_LOG(LS_ERROR) << "Modifying the configuration in an unsupported way.";
deadbeef293e9262017-01-11 12:28:30 -08002527 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
2528 }
2529
Steve Anton038834f2017-07-14 15:59:59 -07002530 // Validate the modified configuration.
2531 RTCError validate_error = ValidateConfiguration(modified_config);
2532 if (!validate_error.ok()) {
2533 return SafeSetError(std::move(validate_error), error);
2534 }
2535
deadbeef293e9262017-01-11 12:28:30 -08002536 // Note that this isn't possible through chromium, since it's an unsigned
2537 // short in WebIDL.
2538 if (configuration.ice_candidate_pool_size < 0 ||
2539 configuration.ice_candidate_pool_size > UINT16_MAX) {
2540 return SafeSetError(RTCErrorType::INVALID_RANGE, error);
2541 }
2542
2543 // Parse ICE servers before hopping to network thread.
2544 cricket::ServerAddresses stun_servers;
2545 std::vector<cricket::RelayServerConfig> turn_servers;
2546 RTCErrorType parse_error =
2547 ParseIceServers(configuration.servers, &stun_servers, &turn_servers);
2548 if (parse_error != RTCErrorType::NONE) {
2549 return SafeSetError(parse_error, error);
2550 }
2551
2552 // In theory this shouldn't fail.
2553 if (!network_thread()->Invoke<bool>(
2554 RTC_FROM_HERE,
2555 rtc::Bind(&PeerConnection::ReconfigurePortAllocator_n, this,
2556 stun_servers, turn_servers, modified_config.type,
2557 modified_config.ice_candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02002558 modified_config.prune_turn_ports,
2559 modified_config.turn_customizer))) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002560 RTC_LOG(LS_ERROR) << "Failed to apply configuration to PortAllocator.";
deadbeef293e9262017-01-11 12:28:30 -08002561 return SafeSetError(RTCErrorType::INTERNAL_ERROR, error);
2562 }
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07002563
deadbeefd1a38b52016-12-10 13:15:33 -08002564 // As described in JSEP, calling setConfiguration with new ICE servers or
2565 // candidate policy must set a "needs-ice-restart" bit so that the next offer
2566 // triggers an ICE restart which will pick up the changes.
deadbeef293e9262017-01-11 12:28:30 -08002567 if (modified_config.servers != configuration_.servers ||
2568 modified_config.type != configuration_.type ||
2569 modified_config.prune_turn_ports != configuration_.prune_turn_ports) {
Steve Antond25da372017-11-06 14:50:29 -08002570 transport_controller_->SetNeedsIceRestartFlag();
deadbeefd1a38b52016-12-10 13:15:33 -08002571 }
skvladd1f5fda2017-02-03 16:54:05 -08002572
2573 if (modified_config.ice_check_min_interval !=
2574 configuration_.ice_check_min_interval) {
Steve Antond25da372017-11-06 14:50:29 -08002575 transport_controller_->SetIceConfig(ParseIceConfig(modified_config));
skvladd1f5fda2017-02-03 16:54:05 -08002576 }
2577
deadbeef293e9262017-01-11 12:28:30 -08002578 configuration_ = modified_config;
2579 return SafeSetError(RTCErrorType::NONE, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00002580}
2581
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002582bool PeerConnection::AddIceCandidate(
2583 const IceCandidateInterface* ice_candidate) {
Peter Boström1a9d6152015-12-08 22:15:17 +01002584 TRACE_EVENT0("webrtc", "PeerConnection::AddIceCandidate");
zhihuang29ff8442016-07-27 11:07:25 -07002585 if (IsClosed()) {
2586 return false;
2587 }
Steve Antond25da372017-11-06 14:50:29 -08002588
2589 if (!remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002590 RTC_LOG(LS_ERROR) << "ProcessIceMessage: ICE candidates can't be added "
2591 << "without any remote session description.";
Steve Antond25da372017-11-06 14:50:29 -08002592 return false;
2593 }
2594
2595 if (!ice_candidate) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002596 RTC_LOG(LS_ERROR) << "ProcessIceMessage: Candidate is NULL.";
Steve Antond25da372017-11-06 14:50:29 -08002597 return false;
2598 }
2599
2600 bool valid = false;
2601 bool ready = ReadyToUseRemoteCandidate(ice_candidate, nullptr, &valid);
2602 if (!valid) {
2603 return false;
2604 }
2605
2606 // Add this candidate to the remote session description.
2607 if (!mutable_remote_description()->AddCandidate(ice_candidate)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002608 RTC_LOG(LS_ERROR) << "ProcessIceMessage: Candidate cannot be used.";
Steve Antond25da372017-11-06 14:50:29 -08002609 return false;
2610 }
2611
2612 if (ready) {
2613 return UseCandidate(ice_candidate);
2614 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002615 RTC_LOG(LS_INFO) << "ProcessIceMessage: Not ready to use candidate.";
Steve Antond25da372017-11-06 14:50:29 -08002616 return true;
2617 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002618}
2619
Honghai Zhang7fb69db2016-03-14 11:59:18 -07002620bool PeerConnection::RemoveIceCandidates(
2621 const std::vector<cricket::Candidate>& candidates) {
2622 TRACE_EVENT0("webrtc", "PeerConnection::RemoveIceCandidates");
Steve Antond25da372017-11-06 14:50:29 -08002623 if (!remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002624 RTC_LOG(LS_ERROR) << "RemoveRemoteIceCandidates: ICE candidates can't be "
2625 << "removed without any remote session description.";
Steve Antond25da372017-11-06 14:50:29 -08002626 return false;
2627 }
2628
2629 if (candidates.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002630 RTC_LOG(LS_ERROR) << "RemoveRemoteIceCandidates: candidates are empty.";
Steve Antond25da372017-11-06 14:50:29 -08002631 return false;
2632 }
2633
2634 size_t number_removed =
2635 mutable_remote_description()->RemoveCandidates(candidates);
2636 if (number_removed != candidates.size()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002637 RTC_LOG(LS_ERROR)
2638 << "RemoveRemoteIceCandidates: Failed to remove candidates. "
2639 << "Requested " << candidates.size() << " but only " << number_removed
2640 << " are removed.";
Steve Antond25da372017-11-06 14:50:29 -08002641 }
2642
2643 // Remove the candidates from the transport controller.
2644 std::string error;
2645 bool res = transport_controller_->RemoveRemoteCandidates(candidates, &error);
2646 if (!res && !error.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002647 RTC_LOG(LS_ERROR) << "Error when removing remote candidates: " << error;
Steve Antond25da372017-11-06 14:50:29 -08002648 }
2649 return true;
Honghai Zhang7fb69db2016-03-14 11:59:18 -07002650}
2651
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00002652void PeerConnection::RegisterUMAObserver(UMAObserver* observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +01002653 TRACE_EVENT0("webrtc", "PeerConnection::RegisterUmaObserver");
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00002654 uma_observer_ = observer;
guoweis@webrtc.org7169afd2014-12-04 17:59:29 +00002655
Steve Anton75737c02017-11-06 10:37:17 -08002656 if (transport_controller()) {
2657 transport_controller()->SetMetricsObserver(uma_observer_);
guoweis@webrtc.org7169afd2014-12-04 17:59:29 +00002658 }
2659
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00002660 // Send information about IPv4/IPv6 status.
deadbeef293e9262017-01-11 12:28:30 -08002661 if (uma_observer_) {
Honghai Zhangd93f50c2016-10-05 11:47:22 -07002662 port_allocator_->SetMetricsObserver(uma_observer_);
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00002663 if (port_allocator_->flags() & cricket::PORTALLOCATOR_ENABLE_IPV6) {
Guo-wei Shiehdfbe6792015-09-03 17:12:07 -07002664 uma_observer_->IncrementEnumCounter(
2665 kEnumCounterAddressFamily, kPeerConnection_IPv6,
2666 kPeerConnectionAddressFamilyCounter_Max);
mallinath@webrtc.orgb445f262014-05-23 22:19:37 +00002667 } else {
Guo-wei Shiehdfbe6792015-09-03 17:12:07 -07002668 uma_observer_->IncrementEnumCounter(
2669 kEnumCounterAddressFamily, kPeerConnection_IPv4,
2670 kPeerConnectionAddressFamilyCounter_Max);
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00002671 }
2672 }
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00002673}
2674
zstein4b979802017-06-02 14:37:37 -07002675RTCError PeerConnection::SetBitrate(const BitrateParameters& bitrate) {
Steve Anton978b8762017-09-29 12:15:02 -07002676 if (!worker_thread()->IsCurrent()) {
2677 return worker_thread()->Invoke<RTCError>(
zstein4b979802017-06-02 14:37:37 -07002678 RTC_FROM_HERE, rtc::Bind(&PeerConnection::SetBitrate, this, bitrate));
2679 }
2680
2681 const bool has_min = static_cast<bool>(bitrate.min_bitrate_bps);
2682 const bool has_current = static_cast<bool>(bitrate.current_bitrate_bps);
2683 const bool has_max = static_cast<bool>(bitrate.max_bitrate_bps);
2684 if (has_min && *bitrate.min_bitrate_bps < 0) {
2685 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2686 "min_bitrate_bps <= 0");
2687 }
2688 if (has_current) {
2689 if (has_min && *bitrate.current_bitrate_bps < *bitrate.min_bitrate_bps) {
2690 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2691 "current_bitrate_bps < min_bitrate_bps");
2692 } else if (*bitrate.current_bitrate_bps < 0) {
2693 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2694 "curent_bitrate_bps < 0");
2695 }
2696 }
2697 if (has_max) {
2698 if (has_current &&
2699 *bitrate.max_bitrate_bps < *bitrate.current_bitrate_bps) {
2700 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2701 "max_bitrate_bps < current_bitrate_bps");
2702 } else if (has_min && *bitrate.max_bitrate_bps < *bitrate.min_bitrate_bps) {
2703 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2704 "max_bitrate_bps < min_bitrate_bps");
2705 } else if (*bitrate.max_bitrate_bps < 0) {
2706 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2707 "max_bitrate_bps < 0");
2708 }
2709 }
2710
2711 Call::Config::BitrateConfigMask mask;
2712 mask.min_bitrate_bps = bitrate.min_bitrate_bps;
2713 mask.start_bitrate_bps = bitrate.current_bitrate_bps;
2714 mask.max_bitrate_bps = bitrate.max_bitrate_bps;
2715
2716 RTC_DCHECK(call_.get());
2717 call_->SetBitrateConfigMask(mask);
2718
2719 return RTCError::OK();
2720}
2721
Alex Narest78609d52017-10-20 10:37:47 +02002722void PeerConnection::SetBitrateAllocationStrategy(
2723 std::unique_ptr<rtc::BitrateAllocationStrategy>
2724 bitrate_allocation_strategy) {
2725 rtc::Thread* worker_thread = factory_->worker_thread();
2726 if (!worker_thread->IsCurrent()) {
2727 rtc::BitrateAllocationStrategy* strategy_raw =
2728 bitrate_allocation_strategy.release();
2729 auto functor = [this, strategy_raw]() {
2730 call_->SetBitrateAllocationStrategy(
2731 rtc::WrapUnique<rtc::BitrateAllocationStrategy>(strategy_raw));
2732 };
2733 worker_thread->Invoke<void>(RTC_FROM_HERE, functor);
2734 return;
2735 }
2736 RTC_DCHECK(call_.get());
2737 call_->SetBitrateAllocationStrategy(std::move(bitrate_allocation_strategy));
2738}
2739
henrika5f6bf242017-11-01 11:06:56 +01002740void PeerConnection::SetAudioPlayout(bool playout) {
2741 if (!worker_thread()->IsCurrent()) {
2742 worker_thread()->Invoke<void>(
2743 RTC_FROM_HERE,
2744 rtc::Bind(&PeerConnection::SetAudioPlayout, this, playout));
2745 return;
2746 }
2747 auto audio_state =
2748 factory_->channel_manager()->media_engine()->GetAudioState();
2749 audio_state->SetPlayout(playout);
2750}
2751
2752void PeerConnection::SetAudioRecording(bool recording) {
2753 if (!worker_thread()->IsCurrent()) {
2754 worker_thread()->Invoke<void>(
2755 RTC_FROM_HERE,
2756 rtc::Bind(&PeerConnection::SetAudioRecording, this, recording));
2757 return;
2758 }
2759 auto audio_state =
2760 factory_->channel_manager()->media_engine()->GetAudioState();
2761 audio_state->SetRecording(recording);
2762}
2763
Steve Anton8c0f7a72017-10-03 10:03:10 -07002764std::unique_ptr<rtc::SSLCertificate>
2765PeerConnection::GetRemoteAudioSSLCertificate() {
Steve Anton75737c02017-11-06 10:37:17 -08002766 if (!voice_channel()) {
Steve Anton8c0f7a72017-10-03 10:03:10 -07002767 return nullptr;
2768 }
Steve Anton75737c02017-11-06 10:37:17 -08002769 return GetRemoteSSLCertificate(voice_channel()->transport_name());
Steve Anton8c0f7a72017-10-03 10:03:10 -07002770}
2771
Zhi Huang70b820f2018-01-27 14:16:15 -08002772std::unique_ptr<rtc::SSLCertChain>
2773PeerConnection::GetRemoteAudioSSLCertChain() {
2774 if (!voice_channel()) {
2775 return nullptr;
2776 }
2777
2778 return transport_controller_->GetRemoteSSLCertChain(
2779 voice_channel()->transport_name());
2780}
2781
ivoc14d5dbe2016-07-04 07:06:55 -07002782bool PeerConnection::StartRtcEventLog(rtc::PlatformFile file,
2783 int64_t max_size_bytes) {
Elad Alon99c3fe52017-10-13 16:29:40 +02002784 // TODO(eladalon): It would be better to not allow negative values into PC.
2785 const size_t max_size = (max_size_bytes < 0)
2786 ? RtcEventLog::kUnlimitedOutput
2787 : rtc::saturated_cast<size_t>(max_size_bytes);
2788 return StartRtcEventLog(
Bjorn Tereliusde939432017-11-20 17:38:14 +01002789 rtc::MakeUnique<RtcEventLogOutputFile>(file, max_size),
2790 webrtc::RtcEventLog::kImmediateOutput);
Elad Alon99c3fe52017-10-13 16:29:40 +02002791}
2792
Bjorn Tereliusde939432017-11-20 17:38:14 +01002793bool PeerConnection::StartRtcEventLog(std::unique_ptr<RtcEventLogOutput> output,
2794 int64_t output_period_ms) {
Karl Wibergd6b48192017-10-16 23:01:06 +02002795 // TODO(eladalon): In C++14, this can be done with a lambda.
2796 struct Functor {
Bjorn Tereliusde939432017-11-20 17:38:14 +01002797 bool operator()() {
2798 return pc->StartRtcEventLog_w(std::move(output), output_period_ms);
2799 }
Karl Wibergd6b48192017-10-16 23:01:06 +02002800 PeerConnection* const pc;
2801 std::unique_ptr<RtcEventLogOutput> output;
Bjorn Tereliusde939432017-11-20 17:38:14 +01002802 const int64_t output_period_ms;
Elad Alon99c3fe52017-10-13 16:29:40 +02002803 };
Bjorn Tereliusde939432017-11-20 17:38:14 +01002804 return worker_thread()->Invoke<bool>(
2805 RTC_FROM_HERE, Functor{this, std::move(output), output_period_ms});
ivoc14d5dbe2016-07-04 07:06:55 -07002806}
2807
2808void PeerConnection::StopRtcEventLog() {
Steve Anton978b8762017-09-29 12:15:02 -07002809 worker_thread()->Invoke<void>(
ivoc14d5dbe2016-07-04 07:06:55 -07002810 RTC_FROM_HERE, rtc::Bind(&PeerConnection::StopRtcEventLog_w, this));
2811}
2812
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002813const SessionDescriptionInterface* PeerConnection::local_description() const {
Steve Anton75737c02017-11-06 10:37:17 -08002814 return pending_local_description_ ? pending_local_description_.get()
2815 : current_local_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002816}
2817
2818const SessionDescriptionInterface* PeerConnection::remote_description() const {
Steve Anton75737c02017-11-06 10:37:17 -08002819 return pending_remote_description_ ? pending_remote_description_.get()
2820 : current_remote_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002821}
2822
deadbeeffe4a8a42016-12-20 17:56:17 -08002823const SessionDescriptionInterface* PeerConnection::current_local_description()
2824 const {
Steve Anton75737c02017-11-06 10:37:17 -08002825 return current_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08002826}
2827
2828const SessionDescriptionInterface* PeerConnection::current_remote_description()
2829 const {
Steve Anton75737c02017-11-06 10:37:17 -08002830 return current_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08002831}
2832
2833const SessionDescriptionInterface* PeerConnection::pending_local_description()
2834 const {
Steve Anton75737c02017-11-06 10:37:17 -08002835 return pending_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08002836}
2837
2838const SessionDescriptionInterface* PeerConnection::pending_remote_description()
2839 const {
Steve Anton75737c02017-11-06 10:37:17 -08002840 return pending_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08002841}
2842
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002843void PeerConnection::Close() {
Peter Boström1a9d6152015-12-08 22:15:17 +01002844 TRACE_EVENT0("webrtc", "PeerConnection::Close");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002845 // Update stats here so that we have the most recent stats for tracks and
2846 // streams before the channels are closed.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00002847 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002848
Steve Anton75737c02017-11-06 10:37:17 -08002849 ChangeSignalingState(PeerConnectionInterface::kClosed);
Steve Anton3fe1b152017-12-12 10:20:08 -08002850
Steve Anton8af21862017-12-15 11:20:13 -08002851 for (auto transceiver : transceivers_) {
2852 transceiver->Stop();
2853 }
2854 DestroyAllChannels();
Steve Anton75737c02017-11-06 10:37:17 -08002855
deadbeef42a42632017-03-10 15:18:00 -08002856 network_thread()->Invoke<void>(
2857 RTC_FROM_HERE,
2858 rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
2859 port_allocator_.get()));
nisseeaabdf62017-05-05 02:23:02 -07002860
Steve Anton978b8762017-09-29 12:15:02 -07002861 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
eladalon248fd4f2017-09-06 05:18:15 -07002862 call_.reset();
2863 // The event log must outlive call (and any other object that uses it).
2864 event_log_.reset();
2865 });
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002866}
2867
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002868void PeerConnection::OnMessage(rtc::Message* msg) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002869 switch (msg->message_id) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002870 case MSG_SET_SESSIONDESCRIPTION_SUCCESS: {
2871 SetSessionDescriptionMsg* param =
2872 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
2873 param->observer->OnSuccess();
2874 delete param;
2875 break;
2876 }
2877 case MSG_SET_SESSIONDESCRIPTION_FAILED: {
2878 SetSessionDescriptionMsg* param =
2879 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
2880 param->observer->OnFailure(param->error);
2881 delete param;
2882 break;
2883 }
deadbeefab9b2d12015-10-14 11:33:11 -07002884 case MSG_CREATE_SESSIONDESCRIPTION_FAILED: {
2885 CreateSessionDescriptionMsg* param =
2886 static_cast<CreateSessionDescriptionMsg*>(msg->pdata);
2887 param->observer->OnFailure(param->error);
2888 delete param;
2889 break;
2890 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002891 case MSG_GETSTATS: {
2892 GetStatsMsg* param = static_cast<GetStatsMsg*>(msg->pdata);
nissee8abe3e2017-01-18 05:00:34 -08002893 StatsReports reports;
2894 stats_->GetStats(param->track, &reports);
2895 param->observer->OnComplete(reports);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002896 delete param;
2897 break;
2898 }
deadbeefbd292462015-12-14 18:15:29 -08002899 case MSG_FREE_DATACHANNELS: {
2900 sctp_data_channels_to_free_.clear();
2901 break;
2902 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002903 default:
nisseeb4ca4e2017-01-12 02:24:27 -08002904 RTC_NOTREACHED() << "Not implemented";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002905 break;
2906 }
2907}
2908
Steve Anton4171afb2017-11-20 10:20:22 -08002909void PeerConnection::CreateAudioReceiver(
2910 MediaStreamInterface* stream,
2911 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01002912 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
2913 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Steve Antond3679212018-01-17 17:41:02 -08002914 auto* audio_receiver = new AudioRtpReceiver(
2915 worker_thread(), remote_sender_info.sender_id, streams);
2916 audio_receiver->SetMediaChannel(voice_media_channel());
2917 audio_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
2918 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
2919 signaling_thread(), audio_receiver);
Steve Anton4171afb2017-11-20 10:20:22 -08002920 GetAudioTransceiver()->internal()->AddReceiver(receiver);
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01002921 observer_->OnAddTrack(receiver, std::move(streams));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002922}
2923
Steve Anton4171afb2017-11-20 10:20:22 -08002924void PeerConnection::CreateVideoReceiver(
2925 MediaStreamInterface* stream,
2926 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01002927 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
2928 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Steve Antond3679212018-01-17 17:41:02 -08002929 auto* video_receiver = new VideoRtpReceiver(
2930 worker_thread(), remote_sender_info.sender_id, streams);
2931 video_receiver->SetMediaChannel(video_media_channel());
2932 video_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
2933 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
2934 signaling_thread(), video_receiver);
Steve Anton4171afb2017-11-20 10:20:22 -08002935 GetVideoTransceiver()->internal()->AddReceiver(receiver);
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01002936 observer_->OnAddTrack(receiver, std::move(streams));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002937}
2938
deadbeef70ab1a12015-09-28 16:53:55 -07002939// TODO(deadbeef): Keep RtpReceivers around even if track goes away in remote
2940// description.
Henrik Boström933d8b02017-10-10 10:05:16 -07002941rtc::scoped_refptr<RtpReceiverInterface> PeerConnection::RemoveAndStopReceiver(
Steve Anton4171afb2017-11-20 10:20:22 -08002942 const RtpSenderInfo& remote_sender_info) {
2943 auto receiver = FindReceiverById(remote_sender_info.sender_id);
2944 if (!receiver) {
2945 RTC_LOG(LS_WARNING) << "RtpReceiver for track with id "
2946 << remote_sender_info.sender_id << " doesn't exist.";
Henrik Boström933d8b02017-10-10 10:05:16 -07002947 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07002948 }
Steve Anton4171afb2017-11-20 10:20:22 -08002949 if (receiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
2950 GetAudioTransceiver()->internal()->RemoveReceiver(receiver);
2951 } else {
2952 GetVideoTransceiver()->internal()->RemoveReceiver(receiver);
2953 }
Henrik Boström933d8b02017-10-10 10:05:16 -07002954 return receiver;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002955}
2956
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002957void PeerConnection::AddAudioTrack(AudioTrackInterface* track,
2958 MediaStreamInterface* stream) {
2959 RTC_DCHECK(!IsClosed());
2960 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08002961 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002962 // We already have a sender for this track, so just change the stream_id
2963 // so that it's correct in the next call to CreateOffer.
Steve Anton4171afb2017-11-20 10:20:22 -08002964 sender->internal()->set_stream_id(stream->label());
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002965 return;
2966 }
2967
2968 // Normal case; we've never seen this track before.
Steve Anton02ee47c2018-01-10 16:26:06 -08002969 auto new_sender =
2970 CreateSender(cricket::MEDIA_TYPE_AUDIO, track, {stream->label()});
2971 static_cast<AudioRtpSender*>(new_sender->internal())
Steve Anton47136dd2018-01-12 10:49:35 -08002972 ->SetMediaChannel(voice_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08002973 GetAudioTransceiver()->internal()->AddSender(new_sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002974 // If the sender has already been configured in SDP, we call SetSsrc,
2975 // which will connect the sender to the underlying transport. This can
2976 // occur if a local session description that contains the ID of the sender
2977 // is set before AddStream is called. It can also occur if the local
2978 // session description is not changed and RemoveStream is called, and
2979 // later AddStream is called again with the same stream.
Steve Anton4171afb2017-11-20 10:20:22 -08002980 const RtpSenderInfo* sender_info =
2981 FindSenderInfo(local_audio_sender_infos_, stream->label(), track->id());
2982 if (sender_info) {
2983 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002984 }
2985}
2986
2987// TODO(deadbeef): Don't destroy RtpSenders here; they should be kept around
2988// indefinitely, when we have unified plan SDP.
2989void PeerConnection::RemoveAudioTrack(AudioTrackInterface* track,
2990 MediaStreamInterface* stream) {
2991 RTC_DCHECK(!IsClosed());
2992 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08002993 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002994 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
2995 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002996 return;
2997 }
Steve Anton4171afb2017-11-20 10:20:22 -08002998 GetAudioTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002999}
3000
3001void PeerConnection::AddVideoTrack(VideoTrackInterface* track,
3002 MediaStreamInterface* stream) {
3003 RTC_DCHECK(!IsClosed());
3004 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003005 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003006 // We already have a sender for this track, so just change the stream_id
3007 // so that it's correct in the next call to CreateOffer.
Steve Anton4171afb2017-11-20 10:20:22 -08003008 sender->internal()->set_stream_id(stream->label());
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003009 return;
3010 }
3011
3012 // Normal case; we've never seen this track before.
Steve Anton02ee47c2018-01-10 16:26:06 -08003013 auto new_sender =
3014 CreateSender(cricket::MEDIA_TYPE_VIDEO, track, {stream->label()});
3015 static_cast<VideoRtpSender*>(new_sender->internal())
Steve Anton47136dd2018-01-12 10:49:35 -08003016 ->SetMediaChannel(video_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08003017 GetVideoTransceiver()->internal()->AddSender(new_sender);
3018 const RtpSenderInfo* sender_info =
3019 FindSenderInfo(local_video_sender_infos_, stream->label(), track->id());
3020 if (sender_info) {
3021 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003022 }
3023}
3024
3025void PeerConnection::RemoveVideoTrack(VideoTrackInterface* track,
3026 MediaStreamInterface* stream) {
3027 RTC_DCHECK(!IsClosed());
3028 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003029 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003030 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
3031 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003032 return;
3033 }
Steve Anton4171afb2017-11-20 10:20:22 -08003034 GetVideoTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003035}
3036
Steve Antonba818672017-11-06 10:21:57 -08003037void PeerConnection::SetIceConnectionState(IceConnectionState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07003038 RTC_DCHECK(signaling_thread()->IsCurrent());
Steve Antonba818672017-11-06 10:21:57 -08003039 if (ice_connection_state_ == new_state) {
3040 return;
3041 }
3042
deadbeefcbecd352015-09-23 11:50:27 -07003043 // After transitioning to "closed", ignore any additional states from
Steve Antonba818672017-11-06 10:21:57 -08003044 // TransportController (such as "disconnected").
deadbeefab9b2d12015-10-14 11:33:11 -07003045 if (IsClosed()) {
deadbeefcbecd352015-09-23 11:50:27 -07003046 return;
3047 }
Steve Antonba818672017-11-06 10:21:57 -08003048
Mirko Bonadei675513b2017-11-09 11:09:25 +01003049 RTC_LOG(LS_INFO) << "Changing IceConnectionState " << ice_connection_state_
3050 << " => " << new_state;
Steve Antonba818672017-11-06 10:21:57 -08003051 RTC_DCHECK(ice_connection_state_ !=
3052 PeerConnectionInterface::kIceConnectionClosed);
3053
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003054 ice_connection_state_ = new_state;
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00003055 observer_->OnIceConnectionChange(ice_connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003056}
3057
3058void PeerConnection::OnIceGatheringChange(
3059 PeerConnectionInterface::IceGatheringState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07003060 RTC_DCHECK(signaling_thread()->IsCurrent());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003061 if (IsClosed()) {
3062 return;
3063 }
3064 ice_gathering_state_ = new_state;
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00003065 observer_->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003066}
3067
jbauch81bf7b02017-03-25 08:31:12 -07003068void PeerConnection::OnIceCandidate(
3069 std::unique_ptr<IceCandidateInterface> candidate) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07003070 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07003071 if (IsClosed()) {
3072 return;
3073 }
jbauch81bf7b02017-03-25 08:31:12 -07003074 observer_->OnIceCandidate(candidate.get());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003075}
3076
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003077void PeerConnection::OnIceCandidatesRemoved(
3078 const std::vector<cricket::Candidate>& candidates) {
3079 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07003080 if (IsClosed()) {
3081 return;
3082 }
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003083 observer_->OnIceCandidatesRemoved(candidates);
3084}
3085
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003086void PeerConnection::ChangeSignalingState(
3087 PeerConnectionInterface::SignalingState signaling_state) {
Steve Antonba818672017-11-06 10:21:57 -08003088 RTC_DCHECK(signaling_thread()->IsCurrent());
3089 if (signaling_state_ == signaling_state) {
3090 return;
3091 }
Mirko Bonadei675513b2017-11-09 11:09:25 +01003092 RTC_LOG(LS_INFO) << "Session: " << session_id() << " Old state: "
3093 << GetSignalingStateString(signaling_state_)
3094 << " New state: "
3095 << GetSignalingStateString(signaling_state);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003096 signaling_state_ = signaling_state;
3097 if (signaling_state == kClosed) {
3098 ice_connection_state_ = kIceConnectionClosed;
3099 observer_->OnIceConnectionChange(ice_connection_state_);
3100 if (ice_gathering_state_ != kIceGatheringComplete) {
3101 ice_gathering_state_ = kIceGatheringComplete;
3102 observer_->OnIceGatheringChange(ice_gathering_state_);
3103 }
3104 }
3105 observer_->OnSignalingChange(signaling_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003106}
3107
deadbeefeb459812015-12-15 19:24:43 -08003108void PeerConnection::OnAudioTrackAdded(AudioTrackInterface* track,
3109 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003110 if (IsClosed()) {
3111 return;
3112 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003113 AddAudioTrack(track, stream);
3114 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003115}
3116
deadbeefeb459812015-12-15 19:24:43 -08003117void PeerConnection::OnAudioTrackRemoved(AudioTrackInterface* track,
3118 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003119 if (IsClosed()) {
3120 return;
3121 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003122 RemoveAudioTrack(track, stream);
3123 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003124}
3125
3126void PeerConnection::OnVideoTrackAdded(VideoTrackInterface* track,
3127 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003128 if (IsClosed()) {
3129 return;
3130 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003131 AddVideoTrack(track, stream);
3132 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003133}
3134
3135void PeerConnection::OnVideoTrackRemoved(VideoTrackInterface* track,
3136 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003137 if (IsClosed()) {
3138 return;
3139 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003140 RemoveVideoTrack(track, stream);
3141 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003142}
3143
Henrik Boström31638672017-11-23 17:48:32 +01003144void PeerConnection::PostSetSessionDescriptionSuccess(
3145 SetSessionDescriptionObserver* observer) {
3146 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
3147 signaling_thread()->Post(RTC_FROM_HERE, this,
3148 MSG_SET_SESSIONDESCRIPTION_SUCCESS, msg);
3149}
3150
deadbeefab9b2d12015-10-14 11:33:11 -07003151void PeerConnection::PostSetSessionDescriptionFailure(
3152 SetSessionDescriptionObserver* observer,
3153 const std::string& error) {
3154 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
3155 msg->error = error;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07003156 signaling_thread()->Post(RTC_FROM_HERE, this,
3157 MSG_SET_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07003158}
3159
3160void PeerConnection::PostCreateSessionDescriptionFailure(
3161 CreateSessionDescriptionObserver* observer,
3162 const std::string& error) {
3163 CreateSessionDescriptionMsg* msg = new CreateSessionDescriptionMsg(observer);
3164 msg->error = error;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07003165 signaling_thread()->Post(RTC_FROM_HERE, this,
3166 MSG_CREATE_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07003167}
3168
zhihuang1c378ed2017-08-17 14:10:50 -07003169void PeerConnection::GetOptionsForOffer(
Steve Antondcc3c022017-12-22 16:02:54 -08003170 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
deadbeefab9b2d12015-10-14 11:33:11 -07003171 cricket::MediaSessionOptions* session_options) {
Steve Antondcc3c022017-12-22 16:02:54 -08003172 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
zhihuang1c378ed2017-08-17 14:10:50 -07003173
Steve Antondcc3c022017-12-22 16:02:54 -08003174 if (IsUnifiedPlan()) {
3175 GetOptionsForUnifiedPlanOffer(offer_answer_options, session_options);
3176 } else {
3177 GetOptionsForPlanBOffer(offer_answer_options, session_options);
3178 }
3179
Steve Antonfa2260d2017-12-28 16:38:23 -08003180 // Intentionally unset the data channel type for RTP data channel with the
3181 // second condition. Otherwise the RTP data channels would be successfully
3182 // negotiated by default and the unit tests in WebRtcDataBrowserTest will fail
3183 // when building with chromium. We want to leave RTP data channels broken, so
3184 // people won't try to use them.
3185 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
3186 session_options->data_channel_type = data_channel_type();
3187 }
3188
Steve Antondcc3c022017-12-22 16:02:54 -08003189 // Apply ICE restart flag and renomination flag.
3190 for (auto& options : session_options->media_description_options) {
3191 options.transport_options.ice_restart = offer_answer_options.ice_restart;
3192 options.transport_options.enable_ice_renomination =
3193 configuration_.enable_ice_renomination;
3194 }
3195
3196 session_options->rtcp_cname = rtcp_cname_;
3197 session_options->crypto_options = factory_->options().crypto_options;
3198}
3199
3200void PeerConnection::GetOptionsForPlanBOffer(
3201 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
3202 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07003203 // Figure out transceiver directional preferences.
3204 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
3205 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
3206
3207 // By default, generate sendrecv/recvonly m= sections.
3208 bool recv_audio = true;
3209 bool recv_video = true;
3210
3211 // By default, only offer a new m= section if we have media to send with it.
3212 bool offer_new_audio_description = send_audio;
3213 bool offer_new_video_description = send_video;
3214 bool offer_new_data_description = HasDataChannels();
3215
3216 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-22 16:02:54 -08003217 if (offer_answer_options.offer_to_receive_audio !=
3218 RTCOfferAnswerOptions::kUndefined) {
3219 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003220 offer_new_audio_description =
Steve Antondcc3c022017-12-22 16:02:54 -08003221 offer_new_audio_description ||
3222 (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003223 }
Steve Antondcc3c022017-12-22 16:02:54 -08003224 if (offer_answer_options.offer_to_receive_video !=
3225 RTCOfferAnswerOptions::kUndefined) {
3226 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003227 offer_new_video_description =
Steve Antondcc3c022017-12-22 16:02:54 -08003228 offer_new_video_description ||
3229 (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003230 }
3231
3232 rtc::Optional<size_t> audio_index;
3233 rtc::Optional<size_t> video_index;
3234 rtc::Optional<size_t> data_index;
3235 // If a current description exists, generate m= sections in the same order,
3236 // using the first audio/video/data section that appears and rejecting
3237 // extraneous ones.
Steve Anton75737c02017-11-06 10:37:17 -08003238 if (local_description()) {
zhihuang1c378ed2017-08-17 14:10:50 -07003239 GenerateMediaDescriptionOptions(
Steve Anton75737c02017-11-06 10:37:17 -08003240 local_description(),
Steve Anton1d03a752017-11-27 14:30:09 -08003241 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
3242 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
3243 &audio_index, &video_index, &data_index, session_options);
deadbeefab9b2d12015-10-14 11:33:11 -07003244 }
3245
zhihuang1c378ed2017-08-17 14:10:50 -07003246 // Add audio/video/data m= sections to the end if needed.
3247 if (!audio_index && offer_new_audio_description) {
3248 session_options->media_description_options.push_back(
3249 cricket::MediaDescriptionOptions(
3250 cricket::MEDIA_TYPE_AUDIO, cricket::CN_AUDIO,
Steve Anton1d03a752017-11-27 14:30:09 -08003251 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
3252 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003253 audio_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07003254 }
zhihuang1c378ed2017-08-17 14:10:50 -07003255 if (!video_index && offer_new_video_description) {
3256 session_options->media_description_options.push_back(
3257 cricket::MediaDescriptionOptions(
3258 cricket::MEDIA_TYPE_VIDEO, cricket::CN_VIDEO,
Steve Anton1d03a752017-11-27 14:30:09 -08003259 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
3260 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003261 video_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07003262 }
zhihuang1c378ed2017-08-17 14:10:50 -07003263 if (!data_index && offer_new_data_description) {
3264 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08003265 GetMediaDescriptionOptionsForActiveData(cricket::CN_DATA));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003266 data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07003267 }
3268
3269 cricket::MediaDescriptionOptions* audio_media_description_options =
3270 !audio_index ? nullptr
3271 : &session_options->media_description_options[*audio_index];
3272 cricket::MediaDescriptionOptions* video_media_description_options =
3273 !video_index ? nullptr
3274 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 14:10:50 -07003275
Steve Anton4171afb2017-11-20 10:20:22 -08003276 AddRtpSenderOptions(GetSendersInternal(), audio_media_description_options,
zhihuang1c378ed2017-08-17 14:10:50 -07003277 video_media_description_options);
Steve Antondcc3c022017-12-22 16:02:54 -08003278}
3279
3280// Find a new MID that is not already in |used_mids|, then add it to |used_mids|
3281// and return a reference to it.
3282// Generated MIDs should be no more than 3 bytes long to take up less space in
3283// the RTP packet.
3284static const std::string& AllocateMid(std::set<std::string>* used_mids) {
3285 RTC_DCHECK(used_mids);
3286 // We're boring: just generate MIDs 0, 1, 2, ...
3287 size_t i = 0;
3288 std::set<std::string>::iterator it;
3289 bool inserted;
3290 do {
3291 std::string mid = rtc::ToString(i++);
3292 auto insert_result = used_mids->insert(mid);
3293 it = insert_result.first;
3294 inserted = insert_result.second;
3295 } while (!inserted);
3296 return *it;
3297}
3298
3299static cricket::MediaDescriptionOptions
3300GetMediaDescriptionOptionsForTransceiver(
3301 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3302 transceiver,
3303 const std::string& mid) {
3304 cricket::MediaDescriptionOptions media_description_options(
3305 transceiver->internal()->media_type(), mid, transceiver->direction(),
3306 transceiver->stopped());
3307 cricket::SenderOptions sender_options;
3308 sender_options.track_id = transceiver->sender()->id();
3309 sender_options.stream_ids = transceiver->sender()->stream_ids();
3310 // TODO(bugs.webrtc.org/7600): Set num_sim_layers to the number of encodings
3311 // set in the RTP parameters when the transceiver was added.
3312 sender_options.num_sim_layers = 1;
3313 media_description_options.sender_options.push_back(sender_options);
3314 return media_description_options;
3315}
3316
3317void PeerConnection::GetOptionsForUnifiedPlanOffer(
3318 const RTCOfferAnswerOptions& offer_answer_options,
3319 cricket::MediaSessionOptions* session_options) {
3320 // Rules for generating an offer are dictated by JSEP sections 5.2.1 (Initial
3321 // Offers) and 5.2.2 (Subsequent Offers).
3322 RTC_DCHECK_EQ(session_options->media_description_options.size(), 0);
3323 const ContentInfos& local_contents =
3324 (local_description() ? local_description()->description()->contents()
3325 : ContentInfos());
3326 const ContentInfos& remote_contents =
3327 (remote_description() ? remote_description()->description()->contents()
3328 : ContentInfos());
3329 // The mline indices that can be recycled. New transceivers should reuse these
3330 // slots first.
3331 std::queue<size_t> recycleable_mline_indices;
3332 // Track the MIDs used in previous offer/answer exchanges and the current
3333 // offer so that new, unique MIDs are generated.
3334 std::set<std::string> used_mids = seen_mids_;
3335 // First, go through each media section that exists in either the local or
3336 // remote description and generate a media section in this offer for the
3337 // associated transceiver. If a media section can be recycled, generate a
3338 // default, rejected media section here that can be later overwritten.
3339 for (size_t i = 0;
3340 i < std::max(local_contents.size(), remote_contents.size()); ++i) {
3341 // Either |local_content| or |remote_content| is non-null.
3342 const ContentInfo* local_content =
3343 (i < local_contents.size() ? &local_contents[i] : nullptr);
3344 const ContentInfo* remote_content =
3345 (i < remote_contents.size() ? &remote_contents[i] : nullptr);
3346 bool had_been_rejected = (local_content && local_content->rejected) ||
3347 (remote_content && remote_content->rejected);
3348 const std::string& mid =
3349 (local_content ? local_content->name : remote_content->name);
3350 cricket::MediaType media_type =
3351 (local_content ? local_content->media_description()->type()
3352 : remote_content->media_description()->type());
3353 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
3354 media_type == cricket::MEDIA_TYPE_VIDEO) {
3355 auto transceiver = GetAssociatedTransceiver(mid);
3356 RTC_CHECK(transceiver);
3357 // A media section is considered eligible for recycling if it is marked as
3358 // rejected in either the local or remote description.
3359 if (had_been_rejected) {
3360 session_options->media_description_options.push_back(
3361 cricket::MediaDescriptionOptions(
3362 transceiver->internal()->media_type(), mid,
3363 RtpTransceiverDirection::kInactive,
3364 /*stopped=*/true));
3365 recycleable_mline_indices.push(i);
3366 } else {
3367 session_options->media_description_options.push_back(
3368 GetMediaDescriptionOptionsForTransceiver(transceiver, mid));
3369 // CreateOffer shouldn't really cause any state changes in
3370 // PeerConnection, but we need a way to match new transceivers to new
3371 // media sections in SetLocalDescription and JSEP specifies this is done
3372 // by recording the index of the media section generated for the
3373 // transceiver in the offer.
3374 transceiver->internal()->set_mline_index(i);
3375 }
3376 } else {
3377 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antonfa2260d2017-12-28 16:38:23 -08003378 RTC_CHECK(GetDataMid());
3379 if (had_been_rejected || mid != *GetDataMid()) {
3380 session_options->media_description_options.push_back(
3381 GetMediaDescriptionOptionsForRejectedData(mid));
3382 } else {
3383 session_options->media_description_options.push_back(
3384 GetMediaDescriptionOptionsForActiveData(mid));
3385 }
Steve Antondcc3c022017-12-22 16:02:54 -08003386 }
3387 }
3388 // Next, look for transceivers that are newly added (that is, are not stopped
3389 // and not associated). Reuse media sections marked as recyclable first,
3390 // otherwise append to the end of the offer. New media sections should be
3391 // added in the order they were added to the PeerConnection.
3392 for (auto transceiver : transceivers_) {
3393 if (transceiver->mid() || transceiver->stopped()) {
3394 continue;
3395 }
3396 size_t mline_index;
3397 if (!recycleable_mline_indices.empty()) {
3398 mline_index = recycleable_mline_indices.front();
3399 recycleable_mline_indices.pop();
3400 session_options->media_description_options[mline_index] =
3401 GetMediaDescriptionOptionsForTransceiver(transceiver,
3402 AllocateMid(&used_mids));
3403 } else {
3404 mline_index = session_options->media_description_options.size();
3405 session_options->media_description_options.push_back(
3406 GetMediaDescriptionOptionsForTransceiver(transceiver,
3407 AllocateMid(&used_mids)));
3408 }
3409 // See comment above for why CreateOffer changes the transceiver's state.
3410 transceiver->internal()->set_mline_index(mline_index);
3411 }
Steve Antonfa2260d2017-12-28 16:38:23 -08003412 // Lastly, add a m-section if we have local data channels and an m section
3413 // does not already exist.
3414 if (!GetDataMid() && HasDataChannels()) {
3415 session_options->media_description_options.push_back(
3416 GetMediaDescriptionOptionsForActiveData(AllocateMid(&used_mids)));
3417 }
Steve Antondcc3c022017-12-22 16:02:54 -08003418}
3419
3420void PeerConnection::GetOptionsForAnswer(
3421 const RTCOfferAnswerOptions& offer_answer_options,
3422 cricket::MediaSessionOptions* session_options) {
3423 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
3424
3425 if (IsUnifiedPlan()) {
3426 GetOptionsForUnifiedPlanAnswer(offer_answer_options, session_options);
3427 } else {
3428 GetOptionsForPlanBAnswer(offer_answer_options, session_options);
3429 }
3430
Steve Antonfa2260d2017-12-28 16:38:23 -08003431 // Intentionally unset the data channel type for RTP data channel. Otherwise
3432 // the RTP data channels would be successfully negotiated by default and the
3433 // unit tests in WebRtcDataBrowserTest will fail when building with chromium.
3434 // We want to leave RTP data channels broken, so people won't try to use them.
3435 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
3436 session_options->data_channel_type = data_channel_type();
3437 }
3438
Steve Antondcc3c022017-12-22 16:02:54 -08003439 // Apply ICE renomination flag.
3440 for (auto& options : session_options->media_description_options) {
3441 options.transport_options.enable_ice_renomination =
3442 configuration_.enable_ice_renomination;
3443 }
zhihuang8f65cdf2016-05-06 18:40:30 -07003444
3445 session_options->rtcp_cname = rtcp_cname_;
jbauchcb560652016-08-04 05:20:32 -07003446 session_options->crypto_options = factory_->options().crypto_options;
deadbeefab9b2d12015-10-14 11:33:11 -07003447}
3448
Steve Antondcc3c022017-12-22 16:02:54 -08003449void PeerConnection::GetOptionsForPlanBAnswer(
3450 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07003451 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07003452 // Figure out transceiver directional preferences.
3453 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
3454 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
3455
3456 // By default, generate sendrecv/recvonly m= sections. The direction is also
3457 // restricted by the direction in the offer.
3458 bool recv_audio = true;
3459 bool recv_video = true;
3460
3461 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-22 16:02:54 -08003462 if (offer_answer_options.offer_to_receive_audio !=
3463 RTCOfferAnswerOptions::kUndefined) {
3464 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
deadbeef0ed85b22016-02-23 17:24:52 -08003465 }
Steve Antondcc3c022017-12-22 16:02:54 -08003466 if (offer_answer_options.offer_to_receive_video !=
3467 RTCOfferAnswerOptions::kUndefined) {
3468 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003469 }
3470
3471 rtc::Optional<size_t> audio_index;
3472 rtc::Optional<size_t> video_index;
3473 rtc::Optional<size_t> data_index;
Taylor Brandstetter94d8cce2018-01-26 22:44:21 +00003474 if (remote_description()) {
3475 // The pending remote description should be an offer.
3476 RTC_DCHECK(remote_description()->GetType() == SdpType::kOffer);
3477 // Generate m= sections that match those in the offer.
3478 // Note that mediasession.cc will handle intersection our preferred
3479 // direction with the offered direction.
3480 GenerateMediaDescriptionOptions(
3481 remote_description(),
3482 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
3483 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
3484 &audio_index, &video_index, &data_index, session_options);
3485 }
zhihuang1c378ed2017-08-17 14:10:50 -07003486
3487 cricket::MediaDescriptionOptions* audio_media_description_options =
3488 !audio_index ? nullptr
3489 : &session_options->media_description_options[*audio_index];
3490 cricket::MediaDescriptionOptions* video_media_description_options =
3491 !video_index ? nullptr
3492 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 14:10:50 -07003493
Steve Anton4171afb2017-11-20 10:20:22 -08003494 AddRtpSenderOptions(GetSendersInternal(), audio_media_description_options,
zhihuang1c378ed2017-08-17 14:10:50 -07003495 video_media_description_options);
Steve Antondcc3c022017-12-22 16:02:54 -08003496}
zhihuangaf388472016-11-02 16:49:48 -07003497
Steve Antondcc3c022017-12-22 16:02:54 -08003498void PeerConnection::GetOptionsForUnifiedPlanAnswer(
3499 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
3500 cricket::MediaSessionOptions* session_options) {
3501 // Rules for generating an answer are dictated by JSEP sections 5.3.1 (Initial
3502 // Answers) and 5.3.2 (Subsequent Answers).
3503 RTC_DCHECK(remote_description());
3504 RTC_DCHECK(remote_description()->GetType() == SdpType::kOffer);
3505 for (const ContentInfo& content :
3506 remote_description()->description()->contents()) {
3507 cricket::MediaType media_type = content.media_description()->type();
3508 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
3509 media_type == cricket::MEDIA_TYPE_VIDEO) {
3510 auto transceiver = GetAssociatedTransceiver(content.name);
3511 RTC_CHECK(transceiver);
3512 session_options->media_description_options.push_back(
3513 GetMediaDescriptionOptionsForTransceiver(transceiver, content.name));
3514 } else {
3515 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antondbf9d032018-01-19 15:23:40 -08003516 // Reject all data sections if data channels are disabled.
3517 // Reject a data section if it has already been rejected.
3518 // Reject all data sections except for the first one.
3519 if (data_channel_type_ == cricket::DCT_NONE || content.rejected ||
3520 content.name != *GetDataMid()) {
Steve Antonfa2260d2017-12-28 16:38:23 -08003521 session_options->media_description_options.push_back(
3522 GetMediaDescriptionOptionsForRejectedData(content.name));
3523 } else {
3524 session_options->media_description_options.push_back(
3525 GetMediaDescriptionOptionsForActiveData(content.name));
3526 }
Steve Antondcc3c022017-12-22 16:02:54 -08003527 }
3528 }
htaa2a49d92016-03-04 02:51:39 -08003529}
3530
zhihuang1c378ed2017-08-17 14:10:50 -07003531void PeerConnection::GenerateMediaDescriptionOptions(
3532 const SessionDescriptionInterface* session_desc,
Steve Anton1d03a752017-11-27 14:30:09 -08003533 RtpTransceiverDirection audio_direction,
3534 RtpTransceiverDirection video_direction,
zhihuang1c378ed2017-08-17 14:10:50 -07003535 rtc::Optional<size_t>* audio_index,
3536 rtc::Optional<size_t>* video_index,
3537 rtc::Optional<size_t>* data_index,
htaa2a49d92016-03-04 02:51:39 -08003538 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07003539 for (const cricket::ContentInfo& content :
3540 session_desc->description()->contents()) {
3541 if (IsAudioContent(&content)) {
3542 // If we already have an audio m= section, reject this extra one.
3543 if (*audio_index) {
3544 session_options->media_description_options.push_back(
3545 cricket::MediaDescriptionOptions(
3546 cricket::MEDIA_TYPE_AUDIO, content.name,
Steve Anton1d03a752017-11-27 14:30:09 -08003547 RtpTransceiverDirection::kInactive, true));
zhihuang1c378ed2017-08-17 14:10:50 -07003548 } else {
3549 session_options->media_description_options.push_back(
3550 cricket::MediaDescriptionOptions(
3551 cricket::MEDIA_TYPE_AUDIO, content.name, audio_direction,
Steve Anton1d03a752017-11-27 14:30:09 -08003552 audio_direction == RtpTransceiverDirection::kInactive));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003553 *audio_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07003554 }
3555 } else if (IsVideoContent(&content)) {
3556 // If we already have an video m= section, reject this extra one.
3557 if (*video_index) {
3558 session_options->media_description_options.push_back(
3559 cricket::MediaDescriptionOptions(
3560 cricket::MEDIA_TYPE_VIDEO, content.name,
Steve Anton1d03a752017-11-27 14:30:09 -08003561 RtpTransceiverDirection::kInactive, true));
zhihuang1c378ed2017-08-17 14:10:50 -07003562 } else {
3563 session_options->media_description_options.push_back(
3564 cricket::MediaDescriptionOptions(
3565 cricket::MEDIA_TYPE_VIDEO, content.name, video_direction,
Steve Anton1d03a752017-11-27 14:30:09 -08003566 video_direction == RtpTransceiverDirection::kInactive));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003567 *video_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07003568 }
3569 } else {
3570 RTC_DCHECK(IsDataContent(&content));
3571 // If we already have an data m= section, reject this extra one.
3572 if (*data_index) {
3573 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08003574 GetMediaDescriptionOptionsForRejectedData(content.name));
zhihuang1c378ed2017-08-17 14:10:50 -07003575 } else {
3576 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08003577 GetMediaDescriptionOptionsForActiveData(content.name));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003578 *data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07003579 }
3580 }
htaa2a49d92016-03-04 02:51:39 -08003581 }
deadbeefab9b2d12015-10-14 11:33:11 -07003582}
3583
Steve Antonfa2260d2017-12-28 16:38:23 -08003584cricket::MediaDescriptionOptions
3585PeerConnection::GetMediaDescriptionOptionsForActiveData(
3586 const std::string& mid) const {
3587 // Direction for data sections is meaningless, but legacy endpoints might
3588 // expect sendrecv.
3589 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
3590 RtpTransceiverDirection::kSendRecv,
3591 /*stopped=*/false);
3592 AddRtpDataChannelOptions(rtp_data_channels_, &options);
3593 return options;
3594}
3595
3596cricket::MediaDescriptionOptions
3597PeerConnection::GetMediaDescriptionOptionsForRejectedData(
3598 const std::string& mid) const {
3599 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
3600 RtpTransceiverDirection::kInactive,
3601 /*stopped=*/true);
3602 AddRtpDataChannelOptions(rtp_data_channels_, &options);
3603 return options;
3604}
3605
3606rtc::Optional<std::string> PeerConnection::GetDataMid() const {
3607 switch (data_channel_type_) {
3608 case cricket::DCT_RTP:
3609 if (!rtp_data_channel_) {
3610 return rtc::nullopt;
3611 }
3612 return rtp_data_channel_->content_name();
3613 case cricket::DCT_SCTP:
3614 return sctp_content_name_;
3615 default:
3616 return rtc::nullopt;
3617 }
3618}
3619
Steve Anton4171afb2017-11-20 10:20:22 -08003620void PeerConnection::RemoveSenders(cricket::MediaType media_type) {
3621 UpdateLocalSenders(std::vector<cricket::StreamParams>(), media_type);
3622 UpdateRemoteSendersList(std::vector<cricket::StreamParams>(), false,
deadbeefbda7e0b2015-12-08 17:13:40 -08003623 media_type, nullptr);
deadbeeffaac4972015-11-12 15:33:07 -08003624}
3625
Steve Anton4171afb2017-11-20 10:20:22 -08003626void PeerConnection::UpdateRemoteSendersList(
deadbeefab9b2d12015-10-14 11:33:11 -07003627 const cricket::StreamParamsVec& streams,
Steve Anton4171afb2017-11-20 10:20:22 -08003628 bool default_sender_needed,
deadbeefab9b2d12015-10-14 11:33:11 -07003629 cricket::MediaType media_type,
3630 StreamCollection* new_streams) {
Steve Anton4171afb2017-11-20 10:20:22 -08003631 std::vector<RtpSenderInfo>* current_senders =
3632 GetRemoteSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07003633
Steve Anton4171afb2017-11-20 10:20:22 -08003634 // Find removed senders. I.e., senders where the sender id or ssrc don't match
deadbeeffac06552015-11-25 11:26:01 -08003635 // the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08003636 for (auto sender_it = current_senders->begin();
3637 sender_it != current_senders->end();
3638 /* incremented manually */) {
3639 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07003640 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08003641 cricket::GetStreamBySsrc(streams, info.first_ssrc);
3642 bool sender_exists = params && params->id == info.sender_id;
deadbeefbda7e0b2015-12-08 17:13:40 -08003643 // If this is a default track, and we still need it, don't remove it.
Steve Anton4171afb2017-11-20 10:20:22 -08003644 if ((info.stream_label == kDefaultStreamLabel && default_sender_needed) ||
3645 sender_exists) {
3646 ++sender_it;
deadbeefbda7e0b2015-12-08 17:13:40 -08003647 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08003648 OnRemoteSenderRemoved(info, media_type);
3649 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07003650 }
3651 }
3652
Steve Anton4171afb2017-11-20 10:20:22 -08003653 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07003654 for (const cricket::StreamParams& params : streams) {
3655 // The sync_label is the MediaStream label and the |stream.id| is the
Steve Anton4171afb2017-11-20 10:20:22 -08003656 // sender id.
deadbeefab9b2d12015-10-14 11:33:11 -07003657 const std::string& stream_label = params.sync_label;
Steve Anton4171afb2017-11-20 10:20:22 -08003658 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07003659 uint32_t ssrc = params.first_ssrc();
3660
3661 rtc::scoped_refptr<MediaStreamInterface> stream =
3662 remote_streams_->find(stream_label);
3663 if (!stream) {
3664 // This is a new MediaStream. Create a new remote MediaStream.
perkjd61bf802016-03-24 03:16:19 -07003665 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
3666 MediaStream::Create(stream_label));
deadbeefab9b2d12015-10-14 11:33:11 -07003667 remote_streams_->AddStream(stream);
3668 new_streams->AddStream(stream);
3669 }
3670
Steve Anton4171afb2017-11-20 10:20:22 -08003671 const RtpSenderInfo* sender_info =
3672 FindSenderInfo(*current_senders, stream_label, sender_id);
3673 if (!sender_info) {
3674 current_senders->push_back(RtpSenderInfo(stream_label, sender_id, ssrc));
3675 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07003676 }
3677 }
deadbeefbda7e0b2015-12-08 17:13:40 -08003678
Steve Anton4171afb2017-11-20 10:20:22 -08003679 // Add default sender if necessary.
3680 if (default_sender_needed) {
deadbeefbda7e0b2015-12-08 17:13:40 -08003681 rtc::scoped_refptr<MediaStreamInterface> default_stream =
3682 remote_streams_->find(kDefaultStreamLabel);
3683 if (!default_stream) {
3684 // Create the new default MediaStream.
perkjd61bf802016-03-24 03:16:19 -07003685 default_stream = MediaStreamProxy::Create(
3686 rtc::Thread::Current(), MediaStream::Create(kDefaultStreamLabel));
deadbeefbda7e0b2015-12-08 17:13:40 -08003687 remote_streams_->AddStream(default_stream);
3688 new_streams->AddStream(default_stream);
3689 }
Steve Anton4171afb2017-11-20 10:20:22 -08003690 std::string default_sender_id = (media_type == cricket::MEDIA_TYPE_AUDIO)
3691 ? kDefaultAudioSenderId
3692 : kDefaultVideoSenderId;
3693 const RtpSenderInfo* default_sender_info = FindSenderInfo(
3694 *current_senders, kDefaultStreamLabel, default_sender_id);
3695 if (!default_sender_info) {
3696 current_senders->push_back(
3697 RtpSenderInfo(kDefaultStreamLabel, default_sender_id, 0));
3698 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefbda7e0b2015-12-08 17:13:40 -08003699 }
3700 }
deadbeefab9b2d12015-10-14 11:33:11 -07003701}
3702
Steve Anton4171afb2017-11-20 10:20:22 -08003703void PeerConnection::OnRemoteSenderAdded(const RtpSenderInfo& sender_info,
3704 cricket::MediaType media_type) {
3705 MediaStreamInterface* stream =
3706 remote_streams_->find(sender_info.stream_label);
deadbeefab9b2d12015-10-14 11:33:11 -07003707
3708 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 10:20:22 -08003709 CreateAudioReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07003710 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 10:20:22 -08003711 CreateVideoReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07003712 } else {
nisseeb4ca4e2017-01-12 02:24:27 -08003713 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07003714 }
3715}
3716
Steve Anton4171afb2017-11-20 10:20:22 -08003717void PeerConnection::OnRemoteSenderRemoved(const RtpSenderInfo& sender_info,
3718 cricket::MediaType media_type) {
3719 MediaStreamInterface* stream =
3720 remote_streams_->find(sender_info.stream_label);
deadbeefab9b2d12015-10-14 11:33:11 -07003721
Henrik Boström933d8b02017-10-10 10:05:16 -07003722 rtc::scoped_refptr<RtpReceiverInterface> receiver;
deadbeefab9b2d12015-10-14 11:33:11 -07003723 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
perkjd61bf802016-03-24 03:16:19 -07003724 // When the MediaEngine audio channel is destroyed, the RemoteAudioSource
3725 // will be notified which will end the AudioRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08003726 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07003727 rtc::scoped_refptr<AudioTrackInterface> audio_track =
Steve Anton4171afb2017-11-20 10:20:22 -08003728 stream->FindAudioTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07003729 if (audio_track) {
deadbeefab9b2d12015-10-14 11:33:11 -07003730 stream->RemoveTrack(audio_track);
deadbeefab9b2d12015-10-14 11:33:11 -07003731 }
3732 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
perkjd61bf802016-03-24 03:16:19 -07003733 // Stopping or destroying a VideoRtpReceiver will end the
3734 // VideoRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08003735 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07003736 rtc::scoped_refptr<VideoTrackInterface> video_track =
Steve Anton4171afb2017-11-20 10:20:22 -08003737 stream->FindVideoTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07003738 if (video_track) {
perkjd61bf802016-03-24 03:16:19 -07003739 // There's no guarantee the track is still available, e.g. the track may
3740 // have been removed from the stream by an application.
deadbeefab9b2d12015-10-14 11:33:11 -07003741 stream->RemoveTrack(video_track);
deadbeefab9b2d12015-10-14 11:33:11 -07003742 }
3743 } else {
nisseede5da42017-01-12 05:15:36 -08003744 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07003745 }
Henrik Boström933d8b02017-10-10 10:05:16 -07003746 if (receiver) {
3747 observer_->OnRemoveTrack(receiver);
3748 }
deadbeefab9b2d12015-10-14 11:33:11 -07003749}
3750
3751void PeerConnection::UpdateEndedRemoteMediaStreams() {
3752 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams_to_remove;
3753 for (size_t i = 0; i < remote_streams_->count(); ++i) {
3754 MediaStreamInterface* stream = remote_streams_->at(i);
3755 if (stream->GetAudioTracks().empty() && stream->GetVideoTracks().empty()) {
3756 streams_to_remove.push_back(stream);
3757 }
3758 }
3759
Taylor Brandstetter98cde262016-05-31 13:02:21 -07003760 for (auto& stream : streams_to_remove) {
deadbeefab9b2d12015-10-14 11:33:11 -07003761 remote_streams_->RemoveStream(stream);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07003762 observer_->OnRemoveStream(std::move(stream));
deadbeefab9b2d12015-10-14 11:33:11 -07003763 }
3764}
3765
Steve Anton4171afb2017-11-20 10:20:22 -08003766void PeerConnection::UpdateLocalSenders(
deadbeefab9b2d12015-10-14 11:33:11 -07003767 const std::vector<cricket::StreamParams>& streams,
3768 cricket::MediaType media_type) {
Steve Anton4171afb2017-11-20 10:20:22 -08003769 std::vector<RtpSenderInfo>* current_senders = GetLocalSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07003770
3771 // Find removed tracks. I.e., tracks where the track id, stream label or ssrc
3772 // don't match the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08003773 for (auto sender_it = current_senders->begin();
3774 sender_it != current_senders->end();
3775 /* incremented manually */) {
3776 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07003777 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08003778 cricket::GetStreamBySsrc(streams, info.first_ssrc);
3779 if (!params || params->id != info.sender_id ||
deadbeefab9b2d12015-10-14 11:33:11 -07003780 params->sync_label != info.stream_label) {
Steve Anton4171afb2017-11-20 10:20:22 -08003781 OnLocalSenderRemoved(info, media_type);
3782 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07003783 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08003784 ++sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07003785 }
3786 }
3787
Steve Anton4171afb2017-11-20 10:20:22 -08003788 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07003789 for (const cricket::StreamParams& params : streams) {
3790 // The sync_label is the MediaStream label and the |stream.id| is the
Steve Anton4171afb2017-11-20 10:20:22 -08003791 // sender id.
deadbeefab9b2d12015-10-14 11:33:11 -07003792 const std::string& stream_label = params.sync_label;
Steve Anton4171afb2017-11-20 10:20:22 -08003793 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07003794 uint32_t ssrc = params.first_ssrc();
Steve Anton4171afb2017-11-20 10:20:22 -08003795 const RtpSenderInfo* sender_info =
3796 FindSenderInfo(*current_senders, stream_label, sender_id);
3797 if (!sender_info) {
3798 current_senders->push_back(RtpSenderInfo(stream_label, sender_id, ssrc));
3799 OnLocalSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07003800 }
3801 }
3802}
3803
Steve Anton4171afb2017-11-20 10:20:22 -08003804void PeerConnection::OnLocalSenderAdded(const RtpSenderInfo& sender_info,
3805 cricket::MediaType media_type) {
3806 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08003807 if (!sender) {
Steve Anton4171afb2017-11-20 10:20:22 -08003808 RTC_LOG(LS_WARNING) << "An unknown RtpSender with id "
3809 << sender_info.sender_id
Mirko Bonadei675513b2017-11-09 11:09:25 +01003810 << " has been configured in the local description.";
deadbeefab9b2d12015-10-14 11:33:11 -07003811 return;
3812 }
3813
deadbeeffac06552015-11-25 11:26:01 -08003814 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003815 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
3816 << " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08003817 return;
deadbeefab9b2d12015-10-14 11:33:11 -07003818 }
deadbeeffac06552015-11-25 11:26:01 -08003819
Steve Anton4171afb2017-11-20 10:20:22 -08003820 sender->internal()->set_stream_id(sender_info.stream_label);
3821 sender->internal()->SetSsrc(sender_info.first_ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07003822}
3823
Steve Anton4171afb2017-11-20 10:20:22 -08003824void PeerConnection::OnLocalSenderRemoved(const RtpSenderInfo& sender_info,
3825 cricket::MediaType media_type) {
3826 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08003827 if (!sender) {
3828 // This is the normal case. I.e., RemoveStream has been called and the
deadbeefab9b2d12015-10-14 11:33:11 -07003829 // SessionDescriptions has been renegotiated.
3830 return;
3831 }
deadbeeffac06552015-11-25 11:26:01 -08003832
3833 // A sender has been removed from the SessionDescription but it's still
3834 // associated with the PeerConnection. This only occurs if the SDP doesn't
3835 // match with the calls to CreateSender, AddStream and RemoveStream.
3836 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003837 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
3838 << " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08003839 return;
deadbeefab9b2d12015-10-14 11:33:11 -07003840 }
deadbeeffac06552015-11-25 11:26:01 -08003841
Steve Anton4171afb2017-11-20 10:20:22 -08003842 sender->internal()->SetSsrc(0);
deadbeefab9b2d12015-10-14 11:33:11 -07003843}
3844
3845void PeerConnection::UpdateLocalRtpDataChannels(
3846 const cricket::StreamParamsVec& streams) {
3847 std::vector<std::string> existing_channels;
3848
3849 // Find new and active data channels.
3850 for (const cricket::StreamParams& params : streams) {
3851 // |it->sync_label| is actually the data channel label. The reason is that
3852 // we use the same naming of data channels as we do for
3853 // MediaStreams and Tracks.
3854 // For MediaStreams, the sync_label is the MediaStream label and the
3855 // track label is the same as |streamid|.
3856 const std::string& channel_label = params.sync_label;
3857 auto data_channel_it = rtp_data_channels_.find(channel_label);
nisse7ce109a2017-01-31 00:57:56 -08003858 if (data_channel_it == rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003859 RTC_LOG(LS_ERROR) << "channel label not found";
deadbeefab9b2d12015-10-14 11:33:11 -07003860 continue;
3861 }
3862 // Set the SSRC the data channel should use for sending.
3863 data_channel_it->second->SetSendSsrc(params.first_ssrc());
3864 existing_channels.push_back(data_channel_it->first);
3865 }
3866
3867 UpdateClosingRtpDataChannels(existing_channels, true);
3868}
3869
3870void PeerConnection::UpdateRemoteRtpDataChannels(
3871 const cricket::StreamParamsVec& streams) {
3872 std::vector<std::string> existing_channels;
3873
3874 // Find new and active data channels.
3875 for (const cricket::StreamParams& params : streams) {
3876 // The data channel label is either the mslabel or the SSRC if the mslabel
3877 // does not exist. Ex a=ssrc:444330170 mslabel:test1.
3878 std::string label = params.sync_label.empty()
3879 ? rtc::ToString(params.first_ssrc())
3880 : params.sync_label;
3881 auto data_channel_it = rtp_data_channels_.find(label);
3882 if (data_channel_it == rtp_data_channels_.end()) {
3883 // This is a new data channel.
3884 CreateRemoteRtpDataChannel(label, params.first_ssrc());
3885 } else {
3886 data_channel_it->second->SetReceiveSsrc(params.first_ssrc());
3887 }
3888 existing_channels.push_back(label);
3889 }
3890
3891 UpdateClosingRtpDataChannels(existing_channels, false);
3892}
3893
3894void PeerConnection::UpdateClosingRtpDataChannels(
3895 const std::vector<std::string>& active_channels,
3896 bool is_local_update) {
3897 auto it = rtp_data_channels_.begin();
3898 while (it != rtp_data_channels_.end()) {
3899 DataChannel* data_channel = it->second;
3900 if (std::find(active_channels.begin(), active_channels.end(),
3901 data_channel->label()) != active_channels.end()) {
3902 ++it;
3903 continue;
3904 }
3905
3906 if (is_local_update) {
3907 data_channel->SetSendSsrc(0);
3908 } else {
3909 data_channel->RemotePeerRequestClose();
3910 }
3911
3912 if (data_channel->state() == DataChannel::kClosed) {
3913 rtp_data_channels_.erase(it);
3914 it = rtp_data_channels_.begin();
3915 } else {
3916 ++it;
3917 }
3918 }
3919}
3920
3921void PeerConnection::CreateRemoteRtpDataChannel(const std::string& label,
3922 uint32_t remote_ssrc) {
3923 rtc::scoped_refptr<DataChannel> channel(
3924 InternalCreateDataChannel(label, nullptr));
3925 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003926 RTC_LOG(LS_WARNING) << "Remote peer requested a DataChannel but"
3927 << "CreateDataChannel failed.";
deadbeefab9b2d12015-10-14 11:33:11 -07003928 return;
3929 }
3930 channel->SetReceiveSsrc(remote_ssrc);
deadbeefa601f5c2016-06-06 14:27:39 -07003931 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
3932 DataChannelProxy::Create(signaling_thread(), channel);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07003933 observer_->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07003934}
3935
3936rtc::scoped_refptr<DataChannel> PeerConnection::InternalCreateDataChannel(
3937 const std::string& label,
3938 const InternalDataChannelInit* config) {
3939 if (IsClosed()) {
3940 return nullptr;
3941 }
Steve Anton75737c02017-11-06 10:37:17 -08003942 if (data_channel_type() == cricket::DCT_NONE) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003943 RTC_LOG(LS_ERROR)
deadbeefab9b2d12015-10-14 11:33:11 -07003944 << "InternalCreateDataChannel: Data is not supported in this call.";
3945 return nullptr;
3946 }
3947 InternalDataChannelInit new_config =
3948 config ? (*config) : InternalDataChannelInit();
Steve Anton75737c02017-11-06 10:37:17 -08003949 if (data_channel_type() == cricket::DCT_SCTP) {
deadbeefab9b2d12015-10-14 11:33:11 -07003950 if (new_config.id < 0) {
3951 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08003952 if ((GetSctpSslRole(&role)) &&
deadbeefab9b2d12015-10-14 11:33:11 -07003953 !sid_allocator_.AllocateSid(role, &new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003954 RTC_LOG(LS_ERROR)
3955 << "No id can be allocated for the SCTP data channel.";
deadbeefab9b2d12015-10-14 11:33:11 -07003956 return nullptr;
3957 }
3958 } else if (!sid_allocator_.ReserveSid(new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003959 RTC_LOG(LS_ERROR) << "Failed to create a SCTP data channel "
3960 << "because the id is already in use or out of range.";
deadbeefab9b2d12015-10-14 11:33:11 -07003961 return nullptr;
3962 }
3963 }
3964
Steve Anton75737c02017-11-06 10:37:17 -08003965 rtc::scoped_refptr<DataChannel> channel(
3966 DataChannel::Create(this, data_channel_type(), label, new_config));
deadbeefab9b2d12015-10-14 11:33:11 -07003967 if (!channel) {
3968 sid_allocator_.ReleaseSid(new_config.id);
3969 return nullptr;
3970 }
3971
3972 if (channel->data_channel_type() == cricket::DCT_RTP) {
3973 if (rtp_data_channels_.find(channel->label()) != rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003974 RTC_LOG(LS_ERROR) << "DataChannel with label " << channel->label()
3975 << " already exists.";
deadbeefab9b2d12015-10-14 11:33:11 -07003976 return nullptr;
3977 }
3978 rtp_data_channels_[channel->label()] = channel;
3979 } else {
3980 RTC_DCHECK(channel->data_channel_type() == cricket::DCT_SCTP);
3981 sctp_data_channels_.push_back(channel);
3982 channel->SignalClosed.connect(this,
3983 &PeerConnection::OnSctpDataChannelClosed);
3984 }
3985
Steve Anton2d8609c2018-01-23 16:38:46 -08003986 SignalDataChannelCreated_(channel.get());
deadbeefab9b2d12015-10-14 11:33:11 -07003987 return channel;
3988}
3989
3990bool PeerConnection::HasDataChannels() const {
3991 return !rtp_data_channels_.empty() || !sctp_data_channels_.empty();
3992}
3993
3994void PeerConnection::AllocateSctpSids(rtc::SSLRole role) {
3995 for (const auto& channel : sctp_data_channels_) {
3996 if (channel->id() < 0) {
3997 int sid;
3998 if (!sid_allocator_.AllocateSid(role, &sid)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003999 RTC_LOG(LS_ERROR) << "Failed to allocate SCTP sid.";
deadbeefab9b2d12015-10-14 11:33:11 -07004000 continue;
4001 }
4002 channel->SetSctpSid(sid);
4003 }
4004 }
4005}
4006
4007void PeerConnection::OnSctpDataChannelClosed(DataChannel* channel) {
deadbeefbd292462015-12-14 18:15:29 -08004008 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeefab9b2d12015-10-14 11:33:11 -07004009 for (auto it = sctp_data_channels_.begin(); it != sctp_data_channels_.end();
4010 ++it) {
4011 if (it->get() == channel) {
4012 if (channel->id() >= 0) {
4013 sid_allocator_.ReleaseSid(channel->id());
4014 }
deadbeefbd292462015-12-14 18:15:29 -08004015 // Since this method is triggered by a signal from the DataChannel,
4016 // we can't free it directly here; we need to free it asynchronously.
4017 sctp_data_channels_to_free_.push_back(*it);
deadbeefab9b2d12015-10-14 11:33:11 -07004018 sctp_data_channels_.erase(it);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07004019 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_FREE_DATACHANNELS,
4020 nullptr);
deadbeefab9b2d12015-10-14 11:33:11 -07004021 return;
4022 }
4023 }
4024}
4025
deadbeefab9b2d12015-10-14 11:33:11 -07004026void PeerConnection::OnDataChannelDestroyed() {
4027 // Use a temporary copy of the RTP/SCTP DataChannel list because the
4028 // DataChannel may callback to us and try to modify the list.
4029 std::map<std::string, rtc::scoped_refptr<DataChannel>> temp_rtp_dcs;
4030 temp_rtp_dcs.swap(rtp_data_channels_);
4031 for (const auto& kv : temp_rtp_dcs) {
4032 kv.second->OnTransportChannelDestroyed();
4033 }
4034
4035 std::vector<rtc::scoped_refptr<DataChannel>> temp_sctp_dcs;
4036 temp_sctp_dcs.swap(sctp_data_channels_);
4037 for (const auto& channel : temp_sctp_dcs) {
4038 channel->OnTransportChannelDestroyed();
4039 }
4040}
4041
4042void PeerConnection::OnDataChannelOpenMessage(
4043 const std::string& label,
4044 const InternalDataChannelInit& config) {
4045 rtc::scoped_refptr<DataChannel> channel(
4046 InternalCreateDataChannel(label, &config));
4047 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004048 RTC_LOG(LS_ERROR) << "Failed to create DataChannel from the OPEN message.";
deadbeefab9b2d12015-10-14 11:33:11 -07004049 return;
4050 }
4051
deadbeefa601f5c2016-06-06 14:27:39 -07004052 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
4053 DataChannelProxy::Create(signaling_thread(), channel);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07004054 observer_->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07004055}
4056
Steve Anton4171afb2017-11-20 10:20:22 -08004057rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
4058PeerConnection::GetAudioTransceiver() const {
4059 // This method only works with Plan B SDP, where there is a single
4060 // audio/video transceiver.
4061 RTC_DCHECK(!IsUnifiedPlan());
4062 for (auto transceiver : transceivers_) {
4063 if (transceiver->internal()->media_type() == cricket::MEDIA_TYPE_AUDIO) {
4064 return transceiver;
4065 }
4066 }
4067 RTC_NOTREACHED();
4068 return nullptr;
4069}
4070
4071rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
4072PeerConnection::GetVideoTransceiver() const {
4073 // This method only works with Plan B SDP, where there is a single
4074 // audio/video transceiver.
4075 RTC_DCHECK(!IsUnifiedPlan());
4076 for (auto transceiver : transceivers_) {
4077 if (transceiver->internal()->media_type() == cricket::MEDIA_TYPE_VIDEO) {
4078 return transceiver;
4079 }
4080 }
4081 RTC_NOTREACHED();
4082 return nullptr;
4083}
4084
4085// TODO(bugs.webrtc.org/7600): Remove this when multiple transceivers with
4086// individual transceiver directions are supported.
zhihuang1c378ed2017-08-17 14:10:50 -07004087bool PeerConnection::HasRtpSender(cricket::MediaType type) const {
Steve Anton4171afb2017-11-20 10:20:22 -08004088 switch (type) {
4089 case cricket::MEDIA_TYPE_AUDIO:
4090 return !GetAudioTransceiver()->internal()->senders().empty();
4091 case cricket::MEDIA_TYPE_VIDEO:
4092 return !GetVideoTransceiver()->internal()->senders().empty();
4093 case cricket::MEDIA_TYPE_DATA:
4094 return false;
4095 }
4096 RTC_NOTREACHED();
4097 return false;
zhihuang1c378ed2017-08-17 14:10:50 -07004098}
4099
Steve Anton4171afb2017-11-20 10:20:22 -08004100rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
4101PeerConnection::FindSenderForTrack(MediaStreamTrackInterface* track) const {
4102 for (auto transceiver : transceivers_) {
4103 for (auto sender : transceiver->internal()->senders()) {
4104 if (sender->track() == track) {
4105 return sender;
4106 }
4107 }
4108 }
4109 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08004110}
4111
Steve Anton4171afb2017-11-20 10:20:22 -08004112rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
4113PeerConnection::FindSenderById(const std::string& sender_id) const {
4114 for (auto transceiver : transceivers_) {
4115 for (auto sender : transceiver->internal()->senders()) {
4116 if (sender->id() == sender_id) {
4117 return sender;
4118 }
4119 }
4120 }
4121 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07004122}
4123
Steve Anton4171afb2017-11-20 10:20:22 -08004124rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
4125PeerConnection::FindReceiverById(const std::string& receiver_id) const {
4126 for (auto transceiver : transceivers_) {
4127 for (auto receiver : transceiver->internal()->receivers()) {
4128 if (receiver->id() == receiver_id) {
4129 return receiver;
4130 }
4131 }
4132 }
4133 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07004134}
4135
Steve Anton4171afb2017-11-20 10:20:22 -08004136std::vector<PeerConnection::RtpSenderInfo>*
4137PeerConnection::GetRemoteSenderInfos(cricket::MediaType media_type) {
4138 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
4139 media_type == cricket::MEDIA_TYPE_VIDEO);
4140 return (media_type == cricket::MEDIA_TYPE_AUDIO)
4141 ? &remote_audio_sender_infos_
4142 : &remote_video_sender_infos_;
4143}
4144
4145std::vector<PeerConnection::RtpSenderInfo>* PeerConnection::GetLocalSenderInfos(
deadbeefab9b2d12015-10-14 11:33:11 -07004146 cricket::MediaType media_type) {
4147 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
4148 media_type == cricket::MEDIA_TYPE_VIDEO);
Steve Anton4171afb2017-11-20 10:20:22 -08004149 return (media_type == cricket::MEDIA_TYPE_AUDIO) ? &local_audio_sender_infos_
4150 : &local_video_sender_infos_;
deadbeefab9b2d12015-10-14 11:33:11 -07004151}
4152
Steve Anton4171afb2017-11-20 10:20:22 -08004153const PeerConnection::RtpSenderInfo* PeerConnection::FindSenderInfo(
4154 const std::vector<PeerConnection::RtpSenderInfo>& infos,
deadbeefab9b2d12015-10-14 11:33:11 -07004155 const std::string& stream_label,
Steve Anton4171afb2017-11-20 10:20:22 -08004156 const std::string sender_id) const {
4157 for (const RtpSenderInfo& sender_info : infos) {
4158 if (sender_info.stream_label == stream_label &&
4159 sender_info.sender_id == sender_id) {
4160 return &sender_info;
deadbeefab9b2d12015-10-14 11:33:11 -07004161 }
4162 }
4163 return nullptr;
4164}
4165
4166DataChannel* PeerConnection::FindDataChannelBySid(int sid) const {
4167 for (const auto& channel : sctp_data_channels_) {
4168 if (channel->id() == sid) {
4169 return channel;
4170 }
4171 }
4172 return nullptr;
4173}
4174
deadbeef91dd5672016-05-18 16:55:30 -07004175bool PeerConnection::InitializePortAllocator_n(
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004176 const RTCConfiguration& configuration) {
4177 cricket::ServerAddresses stun_servers;
4178 std::vector<cricket::RelayServerConfig> turn_servers;
deadbeef293e9262017-01-11 12:28:30 -08004179 if (ParseIceServers(configuration.servers, &stun_servers, &turn_servers) !=
4180 RTCErrorType::NONE) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004181 return false;
4182 }
4183
Taylor Brandstetterf8e65772016-06-27 17:20:15 -07004184 port_allocator_->Initialize();
4185
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004186 // To handle both internal and externally created port allocator, we will
4187 // enable BUNDLE here.
4188 int portallocator_flags = port_allocator_->flags();
4189 portallocator_flags |= cricket::PORTALLOCATOR_ENABLE_SHARED_SOCKET |
zhihuangb09b3f92017-03-07 14:40:51 -08004190 cricket::PORTALLOCATOR_ENABLE_IPV6 |
4191 cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI;
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004192 // If the disable-IPv6 flag was specified, we'll not override it
4193 // by experiment.
4194 if (configuration.disable_ipv6) {
4195 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
sprangc1b57a12017-02-28 08:50:47 -08004196 } else if (webrtc::field_trial::FindFullName("WebRTC-IPv6Default")
4197 .find("Disabled") == 0) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004198 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
4199 }
4200
zhihuangb09b3f92017-03-07 14:40:51 -08004201 if (configuration.disable_ipv6_on_wifi) {
4202 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI);
Mirko Bonadei675513b2017-11-09 11:09:25 +01004203 RTC_LOG(LS_INFO) << "IPv6 candidates on Wi-Fi are disabled.";
zhihuangb09b3f92017-03-07 14:40:51 -08004204 }
4205
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004206 if (configuration.tcp_candidate_policy == kTcpCandidatePolicyDisabled) {
4207 portallocator_flags |= cricket::PORTALLOCATOR_DISABLE_TCP;
Mirko Bonadei675513b2017-11-09 11:09:25 +01004208 RTC_LOG(LS_INFO) << "TCP candidates are disabled.";
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004209 }
4210
honghaiz60347052016-05-31 18:29:12 -07004211 if (configuration.candidate_network_policy ==
4212 kCandidateNetworkPolicyLowCost) {
4213 portallocator_flags |= cricket::PORTALLOCATOR_DISABLE_COSTLY_NETWORKS;
Mirko Bonadei675513b2017-11-09 11:09:25 +01004214 RTC_LOG(LS_INFO) << "Do not gather candidates on high-cost networks";
honghaiz60347052016-05-31 18:29:12 -07004215 }
4216
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004217 port_allocator_->set_flags(portallocator_flags);
4218 // No step delay is used while allocating ports.
4219 port_allocator_->set_step_delay(cricket::kMinimumStepDelay);
4220 port_allocator_->set_candidate_filter(
4221 ConvertIceTransportTypeToCandidateFilter(configuration.type));
deadbeefd21eab32017-07-26 16:50:11 -07004222 port_allocator_->set_max_ipv6_networks(configuration.max_ipv6_networks);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004223
4224 // Call this last since it may create pooled allocator sessions using the
4225 // properties set above.
4226 port_allocator_->SetConfiguration(stun_servers, turn_servers,
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -07004227 configuration.ice_candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02004228 configuration.prune_turn_ports,
4229 configuration.turn_customizer);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004230 return true;
4231}
4232
deadbeef91dd5672016-05-18 16:55:30 -07004233bool PeerConnection::ReconfigurePortAllocator_n(
deadbeef293e9262017-01-11 12:28:30 -08004234 const cricket::ServerAddresses& stun_servers,
4235 const std::vector<cricket::RelayServerConfig>& turn_servers,
4236 IceTransportsType type,
4237 int candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02004238 bool prune_turn_ports,
4239 webrtc::TurnCustomizer* turn_customizer) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004240 port_allocator_->set_candidate_filter(
deadbeef293e9262017-01-11 12:28:30 -08004241 ConvertIceTransportTypeToCandidateFilter(type));
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004242 // Call this last since it may create pooled allocator sessions using the
4243 // candidate filter set above.
deadbeef6de92f92016-12-12 18:49:32 -08004244 return port_allocator_->SetConfiguration(
Jonas Orelandbdcee282017-10-10 14:01:40 +02004245 stun_servers, turn_servers, candidate_pool_size, prune_turn_ports,
4246 turn_customizer);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004247}
4248
Steve Antonba818672017-11-06 10:21:57 -08004249cricket::ChannelManager* PeerConnection::channel_manager() const {
4250 return factory_->channel_manager();
4251}
4252
4253MetricsObserverInterface* PeerConnection::metrics_observer() const {
4254 return uma_observer_;
4255}
4256
Elad Alon99c3fe52017-10-13 16:29:40 +02004257bool PeerConnection::StartRtcEventLog_w(
Bjorn Tereliusde939432017-11-20 17:38:14 +01004258 std::unique_ptr<RtcEventLogOutput> output,
4259 int64_t output_period_ms) {
zhihuang77985012017-02-07 15:45:16 -08004260 if (!event_log_) {
4261 return false;
4262 }
Bjorn Tereliusde939432017-11-20 17:38:14 +01004263 return event_log_->StartLogging(std::move(output), output_period_ms);
ivoc14d5dbe2016-07-04 07:06:55 -07004264}
4265
4266void PeerConnection::StopRtcEventLog_w() {
zhihuang77985012017-02-07 15:45:16 -08004267 if (event_log_) {
4268 event_log_->StopLogging();
4269 }
ivoc14d5dbe2016-07-04 07:06:55 -07004270}
nisseeaabdf62017-05-05 02:23:02 -07004271
Steve Anton75737c02017-11-06 10:37:17 -08004272cricket::BaseChannel* PeerConnection::GetChannel(
4273 const std::string& content_name) {
Steve Antondcc3c022017-12-22 16:02:54 -08004274 for (auto transceiver : transceivers_) {
4275 cricket::BaseChannel* channel = transceiver->internal()->channel();
4276 if (channel && channel->content_name() == content_name) {
4277 return channel;
4278 }
Steve Anton75737c02017-11-06 10:37:17 -08004279 }
4280 if (rtp_data_channel() &&
4281 rtp_data_channel()->content_name() == content_name) {
4282 return rtp_data_channel();
4283 }
4284 return nullptr;
4285}
4286
4287bool PeerConnection::GetSctpSslRole(rtc::SSLRole* role) {
4288 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004289 RTC_LOG(LS_INFO)
4290 << "Local and Remote descriptions must be applied to get the "
4291 << "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08004292 return false;
4293 }
4294 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004295 RTC_LOG(LS_INFO) << "Non-rejected SCTP m= section is needed to get the "
4296 << "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08004297 return false;
4298 }
4299
4300 return transport_controller_->GetSslRole(*sctp_transport_name_, role);
4301}
4302
4303bool PeerConnection::GetSslRole(const std::string& content_name,
4304 rtc::SSLRole* role) {
4305 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004306 RTC_LOG(LS_INFO)
4307 << "Local and Remote descriptions must be applied to get the "
4308 << "SSL Role of the session.";
Steve Anton75737c02017-11-06 10:37:17 -08004309 return false;
4310 }
4311
4312 return transport_controller_->GetSslRole(GetTransportName(content_name),
4313 role);
4314}
4315
Steve Anton75737c02017-11-06 10:37:17 -08004316// TODO(steveanton): Eventually it'd be nice to store the channels as a single
4317// vector of BaseChannel pointers instead of separate voice and video channel
4318// vectors. At that point, this will become a simple getter.
4319std::vector<cricket::BaseChannel*> PeerConnection::Channels() const {
4320 std::vector<cricket::BaseChannel*> channels;
Steve Anton4171afb2017-11-20 10:20:22 -08004321 if (voice_channel()) {
4322 channels.push_back(voice_channel());
4323 }
4324 if (video_channel()) {
4325 channels.push_back(video_channel());
4326 }
Steve Anton75737c02017-11-06 10:37:17 -08004327 if (rtp_data_channel_) {
4328 channels.push_back(rtp_data_channel_);
4329 }
4330 return channels;
4331}
4332
Steve Antonf8470812017-12-04 10:46:21 -08004333void PeerConnection::SetSessionError(SessionError error,
4334 const std::string& error_desc) {
4335 RTC_DCHECK_RUN_ON(signaling_thread());
4336 if (error != session_error_) {
4337 session_error_ = error;
4338 session_error_desc_ = error_desc;
Steve Anton75737c02017-11-06 10:37:17 -08004339 }
4340}
4341
Steve Anton3828c062017-12-06 10:34:51 -08004342RTCError PeerConnection::UpdateSessionState(SdpType type,
Steve Anton8a006912017-12-04 15:25:56 -08004343 cricket::ContentSource source) {
4344 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08004345
4346 // If there's already a pending error then no state transition should happen.
4347 // But all call-sites should be verifying this before calling us!
Steve Antonf8470812017-12-04 10:46:21 -08004348 RTC_DCHECK(session_error() == SessionError::kNone);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004349
4350 // If this is an answer then we know whether to BUNDLE or not. If both the
4351 // local and remote side have agreed to BUNDLE, go ahead and enable it.
Steve Anton3828c062017-12-06 10:34:51 -08004352 if (type == SdpType::kAnswer) {
Steve Anton75737c02017-11-06 10:37:17 -08004353 const cricket::ContentGroup* local_bundle =
4354 local_description()->description()->GetGroupByName(
4355 cricket::GROUP_TYPE_BUNDLE);
4356 const cricket::ContentGroup* remote_bundle =
4357 remote_description()->description()->GetGroupByName(
4358 cricket::GROUP_TYPE_BUNDLE);
4359 if (local_bundle && remote_bundle) {
4360 // The answerer decides the transport to bundle on.
4361 const cricket::ContentGroup* answer_bundle =
4362 (source == cricket::CS_LOCAL ? local_bundle : remote_bundle);
4363 if (!EnableBundle(*answer_bundle)) {
Steve Anton8a006912017-12-04 15:25:56 -08004364 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
4365 kEnableBundleFailed);
Steve Anton75737c02017-11-06 10:37:17 -08004366 }
4367 }
Steve Anton75737c02017-11-06 10:37:17 -08004368 }
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004369
4370 // Only push down the transport description after potentially enabling BUNDLE;
4371 // we don't want to push down a description on a transport about to be
4372 // destroyed.
Steve Anton3828c062017-12-06 10:34:51 -08004373 RTCError error = PushdownTransportDescription(source, type);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004374 if (!error.ok()) {
4375 return error;
4376 }
4377
4378 // If this is answer-ish we're ready to let media flow.
Steve Anton3828c062017-12-06 10:34:51 -08004379 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Antoned10bd92017-12-05 10:52:59 -08004380 EnableSending();
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004381 }
4382
4383 // Update the signaling state according to the specified state machine (see
4384 // https://w3c.github.io/webrtc-pc/#rtcsignalingstate-enum).
Steve Anton3828c062017-12-06 10:34:51 -08004385 if (type == SdpType::kOffer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004386 ChangeSignalingState(source == cricket::CS_LOCAL
4387 ? PeerConnectionInterface::kHaveLocalOffer
4388 : PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton3828c062017-12-06 10:34:51 -08004389 } else if (type == SdpType::kPrAnswer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004390 ChangeSignalingState(source == cricket::CS_LOCAL
4391 ? PeerConnectionInterface::kHaveLocalPrAnswer
4392 : PeerConnectionInterface::kHaveRemotePrAnswer);
4393 } else {
Steve Anton3828c062017-12-06 10:34:51 -08004394 RTC_DCHECK(type == SdpType::kAnswer);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004395 ChangeSignalingState(PeerConnectionInterface::kStable);
4396 }
4397
4398 // Update internal objects according to the session description's media
4399 // descriptions.
Steve Anton3828c062017-12-06 10:34:51 -08004400 error = PushdownMediaDescription(type, source);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004401 if (!error.ok()) {
4402 SetSessionError(SessionError::kContent, error.message());
4403 }
4404 if (session_error() != SessionError::kNone) {
4405 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
4406 }
4407
Steve Anton8a006912017-12-04 15:25:56 -08004408 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08004409}
4410
Steve Anton8a006912017-12-04 15:25:56 -08004411RTCError PeerConnection::PushdownMediaDescription(
Steve Anton3828c062017-12-06 10:34:51 -08004412 SdpType type,
Steve Anton8a006912017-12-04 15:25:56 -08004413 cricket::ContentSource source) {
Steve Antoned10bd92017-12-05 10:52:59 -08004414 const SessionDescriptionInterface* sdesc =
4415 (source == cricket::CS_LOCAL ? local_description()
4416 : remote_description());
Steve Anton75737c02017-11-06 10:37:17 -08004417 RTC_DCHECK(sdesc);
Steve Antoned10bd92017-12-05 10:52:59 -08004418
4419 // Push down the new SDP media section for each audio/video transceiver.
4420 for (auto transceiver : transceivers_) {
Steve Anton75737c02017-11-06 10:37:17 -08004421 const ContentInfo* content_info =
Steve Antoned10bd92017-12-05 10:52:59 -08004422 FindMediaSectionForTransceiver(transceiver, sdesc);
4423 cricket::BaseChannel* channel = transceiver->internal()->channel();
4424 if (!channel || !content_info || content_info->rejected) {
Steve Anton75737c02017-11-06 10:37:17 -08004425 continue;
4426 }
4427 const MediaContentDescription* content_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08004428 content_info->media_description();
Steve Antoned10bd92017-12-05 10:52:59 -08004429 if (!content_desc) {
4430 continue;
4431 }
4432 std::string error;
4433 bool success =
4434 (source == cricket::CS_LOCAL)
Steve Anton3828c062017-12-06 10:34:51 -08004435 ? channel->SetLocalContent(content_desc, type, &error)
4436 : channel->SetRemoteContent(content_desc, type, &error);
Steve Antoned10bd92017-12-05 10:52:59 -08004437 if (!success) {
4438 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, std::move(error));
4439 }
4440 }
4441
4442 // If using the RtpDataChannel, push down the new SDP section for it too.
4443 if (rtp_data_channel_) {
4444 const ContentInfo* data_content =
4445 cricket::GetFirstDataContent(sdesc->description());
4446 if (data_content && !data_content->rejected) {
4447 const MediaContentDescription* data_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08004448 data_content->media_description();
Steve Antoned10bd92017-12-05 10:52:59 -08004449 if (data_desc) {
4450 std::string error;
4451 bool success =
4452 (source == cricket::CS_LOCAL)
Steve Anton3828c062017-12-06 10:34:51 -08004453 ? rtp_data_channel_->SetLocalContent(data_desc, type, &error)
4454 : rtp_data_channel_->SetRemoteContent(data_desc, type,
Steve Antoned10bd92017-12-05 10:52:59 -08004455 &error);
4456 if (!success) {
4457 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
4458 std::move(error));
4459 }
Steve Anton75737c02017-11-06 10:37:17 -08004460 }
4461 }
4462 }
Steve Antoned10bd92017-12-05 10:52:59 -08004463
Steve Anton75737c02017-11-06 10:37:17 -08004464 // Need complete offer/answer with an SCTP m= section before starting SCTP,
4465 // according to https://tools.ietf.org/html/draft-ietf-mmusic-sctp-sdp-19
4466 if (sctp_transport_ && local_description() && remote_description() &&
4467 cricket::GetFirstDataContent(local_description()->description()) &&
4468 cricket::GetFirstDataContent(remote_description()->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08004469 bool success = network_thread()->Invoke<bool>(
Steve Anton75737c02017-11-06 10:37:17 -08004470 RTC_FROM_HERE,
4471 rtc::Bind(&PeerConnection::PushdownSctpParameters_n, this, source));
Steve Anton8a006912017-12-04 15:25:56 -08004472 if (!success) {
4473 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
4474 "Failed to push down SCTP parameters.");
4475 }
Steve Anton75737c02017-11-06 10:37:17 -08004476 }
Steve Antoned10bd92017-12-05 10:52:59 -08004477
Steve Anton8a006912017-12-04 15:25:56 -08004478 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08004479}
4480
4481bool PeerConnection::PushdownSctpParameters_n(cricket::ContentSource source) {
4482 RTC_DCHECK(network_thread()->IsCurrent());
4483 RTC_DCHECK(local_description());
4484 RTC_DCHECK(remote_description());
4485 // Apply the SCTP port (which is hidden inside a DataCodec structure...)
4486 // When we support "max-message-size", that would also be pushed down here.
4487 return sctp_transport_->Start(
4488 GetSctpPort(local_description()->description()),
4489 GetSctpPort(remote_description()->description()));
4490}
4491
Steve Anton8a006912017-12-04 15:25:56 -08004492RTCError PeerConnection::PushdownTransportDescription(
4493 cricket::ContentSource source,
Steve Anton3828c062017-12-06 10:34:51 -08004494 SdpType type) {
Steve Anton8a006912017-12-04 15:25:56 -08004495 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08004496
Steve Anton8a006912017-12-04 15:25:56 -08004497 const SessionDescriptionInterface* sdesc =
4498 (source == cricket::CS_LOCAL ? local_description()
4499 : remote_description());
4500 RTC_DCHECK(sdesc);
4501 for (const cricket::TransportInfo& tinfo :
4502 sdesc->description()->transport_infos()) {
4503 std::string error;
4504 bool success;
4505 if (source == cricket::CS_LOCAL) {
4506 success = transport_controller_->SetLocalTransportDescription(
Steve Anton3828c062017-12-06 10:34:51 -08004507 tinfo.content_name, tinfo.description, type, &error);
Steve Anton8a006912017-12-04 15:25:56 -08004508 } else {
4509 success = transport_controller_->SetRemoteTransportDescription(
Steve Anton3828c062017-12-06 10:34:51 -08004510 tinfo.content_name, tinfo.description, type, &error);
Steve Anton8a006912017-12-04 15:25:56 -08004511 }
4512 if (!success) {
Steve Antondcc3c022017-12-22 16:02:54 -08004513 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
4514 "Failed to push down transport description for " +
4515 tinfo.content_name + ": " + error);
Steve Anton75737c02017-11-06 10:37:17 -08004516 }
4517 }
4518
Steve Anton8a006912017-12-04 15:25:56 -08004519 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08004520}
4521
4522bool PeerConnection::GetTransportDescription(
4523 const SessionDescription* description,
4524 const std::string& content_name,
4525 cricket::TransportDescription* tdesc) {
4526 if (!description || !tdesc) {
4527 return false;
4528 }
4529 const TransportInfo* transport_info =
4530 description->GetTransportInfoByName(content_name);
4531 if (!transport_info) {
4532 return false;
4533 }
4534 *tdesc = transport_info->description;
4535 return true;
4536}
4537
4538bool PeerConnection::EnableBundle(const cricket::ContentGroup& bundle) {
4539 const std::string* first_content_name = bundle.FirstContentName();
4540 if (!first_content_name) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004541 RTC_LOG(LS_WARNING) << "Tried to BUNDLE with no contents.";
Steve Anton75737c02017-11-06 10:37:17 -08004542 return false;
4543 }
4544 const std::string& transport_name = *first_content_name;
4545
4546 auto maybe_set_transport = [this, bundle,
4547 transport_name](cricket::BaseChannel* ch) {
4548 if (!ch || !bundle.HasContentName(ch->content_name())) {
Steve Antoned10bd92017-12-05 10:52:59 -08004549 return;
Steve Anton75737c02017-11-06 10:37:17 -08004550 }
4551
4552 std::string old_transport_name = ch->transport_name();
4553 if (old_transport_name == transport_name) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004554 RTC_LOG(LS_INFO) << "BUNDLE already enabled for " << ch->content_name()
4555 << " on " << transport_name << ".";
Steve Antoned10bd92017-12-05 10:52:59 -08004556 return;
Steve Anton75737c02017-11-06 10:37:17 -08004557 }
4558
4559 cricket::DtlsTransportInternal* rtp_dtls_transport =
4560 transport_controller_->CreateDtlsTransport(
4561 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4562 bool need_rtcp = (ch->rtcp_dtls_transport() != nullptr);
4563 cricket::DtlsTransportInternal* rtcp_dtls_transport = nullptr;
4564 if (need_rtcp) {
4565 rtcp_dtls_transport = transport_controller_->CreateDtlsTransport(
4566 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
4567 }
4568
4569 ch->SetTransports(rtp_dtls_transport, rtcp_dtls_transport);
Mirko Bonadei675513b2017-11-09 11:09:25 +01004570 RTC_LOG(LS_INFO) << "Enabled BUNDLE for " << ch->content_name() << " on "
4571 << transport_name << ".";
Steve Anton75737c02017-11-06 10:37:17 -08004572 transport_controller_->DestroyDtlsTransport(
4573 old_transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4574 // If the channel needs rtcp, it means that the channel used to have a
4575 // rtcp transport which needs to be deleted now.
4576 if (need_rtcp) {
4577 transport_controller_->DestroyDtlsTransport(
4578 old_transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
4579 }
Steve Anton75737c02017-11-06 10:37:17 -08004580 };
4581
Steve Antoned10bd92017-12-05 10:52:59 -08004582 for (auto transceiver : transceivers_) {
4583 maybe_set_transport(transceiver->internal()->channel());
Steve Anton75737c02017-11-06 10:37:17 -08004584 }
Steve Antoned10bd92017-12-05 10:52:59 -08004585 maybe_set_transport(rtp_data_channel_);
4586
Steve Anton75737c02017-11-06 10:37:17 -08004587 // For SCTP, transport creation/deletion happens here instead of in the
4588 // object itself.
4589 if (sctp_transport_) {
4590 RTC_DCHECK(sctp_transport_name_);
4591 RTC_DCHECK(sctp_content_name_);
4592 if (transport_name != *sctp_transport_name_ &&
4593 bundle.HasContentName(*sctp_content_name_)) {
4594 network_thread()->Invoke<void>(
4595 RTC_FROM_HERE, rtc::Bind(&PeerConnection::ChangeSctpTransport_n, this,
4596 transport_name));
4597 }
4598 }
4599
4600 return true;
4601}
4602
Steve Anton75737c02017-11-06 10:37:17 -08004603cricket::IceConfig PeerConnection::ParseIceConfig(
4604 const PeerConnectionInterface::RTCConfiguration& config) const {
4605 cricket::ContinualGatheringPolicy gathering_policy;
4606 // TODO(honghaiz): Add the third continual gathering policy in
4607 // PeerConnectionInterface and map it to GATHER_CONTINUALLY_AND_RECOVER.
4608 switch (config.continual_gathering_policy) {
4609 case PeerConnectionInterface::GATHER_ONCE:
4610 gathering_policy = cricket::GATHER_ONCE;
4611 break;
4612 case PeerConnectionInterface::GATHER_CONTINUALLY:
4613 gathering_policy = cricket::GATHER_CONTINUALLY;
4614 break;
4615 default:
4616 RTC_NOTREACHED();
4617 gathering_policy = cricket::GATHER_ONCE;
4618 }
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08004619
Steve Anton75737c02017-11-06 10:37:17 -08004620 cricket::IceConfig ice_config;
4621 ice_config.receiving_timeout = config.ice_connection_receiving_timeout;
4622 ice_config.prioritize_most_likely_candidate_pairs =
4623 config.prioritize_most_likely_ice_candidate_pairs;
4624 ice_config.backup_connection_ping_interval =
4625 config.ice_backup_candidate_pair_ping_interval;
4626 ice_config.continual_gathering_policy = gathering_policy;
4627 ice_config.presume_writable_when_fully_relayed =
4628 config.presume_writable_when_fully_relayed;
4629 ice_config.ice_check_min_interval = config.ice_check_min_interval;
4630 ice_config.regather_all_networks_interval_range =
4631 config.ice_regather_interval_range;
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08004632 ice_config.network_preference = config.network_preference;
Steve Anton75737c02017-11-06 10:37:17 -08004633 return ice_config;
4634}
4635
Steve Anton75737c02017-11-06 10:37:17 -08004636bool PeerConnection::GetLocalTrackIdBySsrc(uint32_t ssrc,
4637 std::string* track_id) {
4638 if (!local_description()) {
4639 return false;
4640 }
4641 return webrtc::GetTrackIdBySsrc(local_description()->description(), ssrc,
4642 track_id);
4643}
4644
4645bool PeerConnection::GetRemoteTrackIdBySsrc(uint32_t ssrc,
4646 std::string* track_id) {
4647 if (!remote_description()) {
4648 return false;
4649 }
4650 return webrtc::GetTrackIdBySsrc(remote_description()->description(), ssrc,
4651 track_id);
4652}
4653
4654bool PeerConnection::SendData(const cricket::SendDataParams& params,
4655 const rtc::CopyOnWriteBuffer& payload,
4656 cricket::SendDataResult* result) {
4657 if (!rtp_data_channel_ && !sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004658 RTC_LOG(LS_ERROR) << "SendData called when rtp_data_channel_ "
4659 << "and sctp_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08004660 return false;
4661 }
4662 return rtp_data_channel_
4663 ? rtp_data_channel_->SendData(params, payload, result)
4664 : network_thread()->Invoke<bool>(
4665 RTC_FROM_HERE,
4666 Bind(&cricket::SctpTransportInternal::SendData,
4667 sctp_transport_.get(), params, payload, result));
4668}
4669
4670bool PeerConnection::ConnectDataChannel(DataChannel* webrtc_data_channel) {
4671 if (!rtp_data_channel_ && !sctp_transport_) {
4672 // Don't log an error here, because DataChannels are expected to call
4673 // ConnectDataChannel in this state. It's the only way to initially tell
4674 // whether or not the underlying transport is ready.
4675 return false;
4676 }
4677 if (rtp_data_channel_) {
4678 rtp_data_channel_->SignalReadyToSendData.connect(
4679 webrtc_data_channel, &DataChannel::OnChannelReady);
4680 rtp_data_channel_->SignalDataReceived.connect(webrtc_data_channel,
4681 &DataChannel::OnDataReceived);
4682 } else {
4683 SignalSctpReadyToSendData.connect(webrtc_data_channel,
4684 &DataChannel::OnChannelReady);
4685 SignalSctpDataReceived.connect(webrtc_data_channel,
4686 &DataChannel::OnDataReceived);
4687 SignalSctpStreamClosedRemotely.connect(
4688 webrtc_data_channel, &DataChannel::OnStreamClosedRemotely);
4689 }
4690 return true;
4691}
4692
4693void PeerConnection::DisconnectDataChannel(DataChannel* webrtc_data_channel) {
4694 if (!rtp_data_channel_ && !sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004695 RTC_LOG(LS_ERROR)
4696 << "DisconnectDataChannel called when rtp_data_channel_ and "
4697 "sctp_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08004698 return;
4699 }
4700 if (rtp_data_channel_) {
4701 rtp_data_channel_->SignalReadyToSendData.disconnect(webrtc_data_channel);
4702 rtp_data_channel_->SignalDataReceived.disconnect(webrtc_data_channel);
4703 } else {
4704 SignalSctpReadyToSendData.disconnect(webrtc_data_channel);
4705 SignalSctpDataReceived.disconnect(webrtc_data_channel);
4706 SignalSctpStreamClosedRemotely.disconnect(webrtc_data_channel);
4707 }
4708}
4709
4710void PeerConnection::AddSctpDataStream(int sid) {
4711 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004712 RTC_LOG(LS_ERROR)
4713 << "AddSctpDataStream called when sctp_transport_ is NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08004714 return;
4715 }
4716 network_thread()->Invoke<void>(
4717 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::OpenStream,
4718 sctp_transport_.get(), sid));
4719}
4720
4721void PeerConnection::RemoveSctpDataStream(int sid) {
4722 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004723 RTC_LOG(LS_ERROR) << "RemoveSctpDataStream called when sctp_transport_ is "
4724 << "NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08004725 return;
4726 }
4727 network_thread()->Invoke<void>(
4728 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::ResetStream,
4729 sctp_transport_.get(), sid));
4730}
4731
4732bool PeerConnection::ReadyToSendData() const {
4733 return (rtp_data_channel_ && rtp_data_channel_->ready_to_send_data()) ||
4734 sctp_ready_to_send_data_;
4735}
4736
4737std::unique_ptr<SessionStats> PeerConnection::GetSessionStats_s() {
4738 RTC_DCHECK(signaling_thread()->IsCurrent());
4739 ChannelNamePairs channel_name_pairs;
4740 if (voice_channel()) {
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004741 channel_name_pairs.voice = ChannelNamePair(
4742 voice_channel()->content_name(), voice_channel()->transport_name());
Steve Anton75737c02017-11-06 10:37:17 -08004743 }
4744 if (video_channel()) {
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004745 channel_name_pairs.video = ChannelNamePair(
4746 video_channel()->content_name(), video_channel()->transport_name());
Steve Anton75737c02017-11-06 10:37:17 -08004747 }
4748 if (rtp_data_channel()) {
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004749 channel_name_pairs.data =
Steve Anton75737c02017-11-06 10:37:17 -08004750 ChannelNamePair(rtp_data_channel()->content_name(),
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004751 rtp_data_channel()->transport_name());
Steve Anton75737c02017-11-06 10:37:17 -08004752 }
4753 if (sctp_transport_) {
4754 RTC_DCHECK(sctp_content_name_);
4755 RTC_DCHECK(sctp_transport_name_);
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004756 channel_name_pairs.data =
4757 ChannelNamePair(*sctp_content_name_, *sctp_transport_name_);
Steve Anton75737c02017-11-06 10:37:17 -08004758 }
4759 return GetSessionStats(channel_name_pairs);
4760}
4761
4762std::unique_ptr<SessionStats> PeerConnection::GetSessionStats(
4763 const ChannelNamePairs& channel_name_pairs) {
4764 if (network_thread()->IsCurrent()) {
4765 return GetSessionStats_n(channel_name_pairs);
4766 }
4767 return network_thread()->Invoke<std::unique_ptr<SessionStats>>(
4768 RTC_FROM_HERE,
4769 rtc::Bind(&PeerConnection::GetSessionStats_n, this, channel_name_pairs));
4770}
4771
4772bool PeerConnection::GetLocalCertificate(
4773 const std::string& transport_name,
4774 rtc::scoped_refptr<rtc::RTCCertificate>* certificate) {
4775 return transport_controller_->GetLocalCertificate(transport_name,
4776 certificate);
4777}
4778
4779std::unique_ptr<rtc::SSLCertificate> PeerConnection::GetRemoteSSLCertificate(
4780 const std::string& transport_name) {
4781 return transport_controller_->GetRemoteSSLCertificate(transport_name);
4782}
4783
4784cricket::DataChannelType PeerConnection::data_channel_type() const {
4785 return data_channel_type_;
4786}
4787
4788bool PeerConnection::IceRestartPending(const std::string& content_name) const {
4789 return pending_ice_restarts_.find(content_name) !=
4790 pending_ice_restarts_.end();
4791}
4792
Steve Anton75737c02017-11-06 10:37:17 -08004793bool PeerConnection::NeedsIceRestart(const std::string& content_name) const {
4794 return transport_controller_->NeedsIceRestart(content_name);
4795}
4796
4797void PeerConnection::OnCertificateReady(
4798 const rtc::scoped_refptr<rtc::RTCCertificate>& certificate) {
4799 transport_controller_->SetLocalCertificate(certificate);
4800}
4801
4802void PeerConnection::OnDtlsSrtpSetupFailure(cricket::BaseChannel*, bool rtcp) {
Steve Antonf8470812017-12-04 10:46:21 -08004803 SetSessionError(SessionError::kTransport,
4804 rtcp ? kDtlsSrtpSetupFailureRtcp : kDtlsSrtpSetupFailureRtp);
Steve Anton75737c02017-11-06 10:37:17 -08004805}
4806
4807void PeerConnection::OnTransportControllerConnectionState(
4808 cricket::IceConnectionState state) {
4809 switch (state) {
4810 case cricket::kIceConnectionConnecting:
4811 // If the current state is Connected or Completed, then there were
4812 // writable channels but now there are not, so the next state must
4813 // be Disconnected.
4814 // kIceConnectionConnecting is currently used as the default,
4815 // un-connected state by the TransportController, so its only use is
4816 // detecting disconnections.
4817 if (ice_connection_state_ ==
4818 PeerConnectionInterface::kIceConnectionConnected ||
4819 ice_connection_state_ ==
4820 PeerConnectionInterface::kIceConnectionCompleted) {
4821 SetIceConnectionState(
4822 PeerConnectionInterface::kIceConnectionDisconnected);
4823 }
4824 break;
4825 case cricket::kIceConnectionFailed:
4826 SetIceConnectionState(PeerConnectionInterface::kIceConnectionFailed);
4827 break;
4828 case cricket::kIceConnectionConnected:
Mirko Bonadei675513b2017-11-09 11:09:25 +01004829 RTC_LOG(LS_INFO) << "Changing to ICE connected state because "
4830 << "all transports are writable.";
Steve Anton75737c02017-11-06 10:37:17 -08004831 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
4832 break;
4833 case cricket::kIceConnectionCompleted:
Mirko Bonadei675513b2017-11-09 11:09:25 +01004834 RTC_LOG(LS_INFO) << "Changing to ICE completed state because "
4835 << "all transports are complete.";
Steve Anton75737c02017-11-06 10:37:17 -08004836 if (ice_connection_state_ !=
4837 PeerConnectionInterface::kIceConnectionConnected) {
4838 // If jumping directly from "checking" to "connected",
4839 // signal "connected" first.
4840 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
4841 }
4842 SetIceConnectionState(PeerConnectionInterface::kIceConnectionCompleted);
4843 if (metrics_observer()) {
4844 ReportTransportStats();
4845 }
4846 break;
4847 default:
4848 RTC_NOTREACHED();
4849 }
4850}
4851
4852void PeerConnection::OnTransportControllerCandidatesGathered(
4853 const std::string& transport_name,
4854 const cricket::Candidates& candidates) {
4855 RTC_DCHECK(signaling_thread()->IsCurrent());
4856 int sdp_mline_index;
4857 if (!GetLocalCandidateMediaIndex(transport_name, &sdp_mline_index)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004858 RTC_LOG(LS_ERROR)
4859 << "OnTransportControllerCandidatesGathered: content name "
4860 << transport_name << " not found";
Steve Anton75737c02017-11-06 10:37:17 -08004861 return;
4862 }
4863
4864 for (cricket::Candidates::const_iterator citer = candidates.begin();
4865 citer != candidates.end(); ++citer) {
4866 // Use transport_name as the candidate media id.
4867 std::unique_ptr<JsepIceCandidate> candidate(
4868 new JsepIceCandidate(transport_name, sdp_mline_index, *citer));
4869 if (local_description()) {
4870 mutable_local_description()->AddCandidate(candidate.get());
4871 }
4872 OnIceCandidate(std::move(candidate));
4873 }
4874}
4875
4876void PeerConnection::OnTransportControllerCandidatesRemoved(
4877 const std::vector<cricket::Candidate>& candidates) {
4878 RTC_DCHECK(signaling_thread()->IsCurrent());
4879 // Sanity check.
4880 for (const cricket::Candidate& candidate : candidates) {
4881 if (candidate.transport_name().empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004882 RTC_LOG(LS_ERROR) << "OnTransportControllerCandidatesRemoved: "
4883 << "empty content name in candidate "
4884 << candidate.ToString();
Steve Anton75737c02017-11-06 10:37:17 -08004885 return;
4886 }
4887 }
4888
4889 if (local_description()) {
4890 mutable_local_description()->RemoveCandidates(candidates);
4891 }
4892 OnIceCandidatesRemoved(candidates);
4893}
4894
4895void PeerConnection::OnTransportControllerDtlsHandshakeError(
4896 rtc::SSLHandshakeError error) {
4897 if (metrics_observer()) {
4898 metrics_observer()->IncrementEnumCounter(
4899 webrtc::kEnumCounterDtlsHandshakeError, static_cast<int>(error),
4900 static_cast<int>(rtc::SSLHandshakeError::MAX_VALUE));
4901 }
4902}
4903
Steve Antoned10bd92017-12-05 10:52:59 -08004904void PeerConnection::EnableSending() {
4905 for (auto transceiver : transceivers_) {
4906 cricket::BaseChannel* channel = transceiver->internal()->channel();
4907 if (channel && !channel->enabled()) {
4908 channel->Enable(true);
4909 }
Steve Anton75737c02017-11-06 10:37:17 -08004910 }
4911
Steve Anton4171afb2017-11-20 10:20:22 -08004912 if (rtp_data_channel_ && !rtp_data_channel_->enabled()) {
Steve Anton75737c02017-11-06 10:37:17 -08004913 rtp_data_channel_->Enable(true);
Steve Anton4171afb2017-11-20 10:20:22 -08004914 }
Steve Anton75737c02017-11-06 10:37:17 -08004915}
4916
4917// Returns the media index for a local ice candidate given the content name.
4918bool PeerConnection::GetLocalCandidateMediaIndex(
4919 const std::string& content_name,
4920 int* sdp_mline_index) {
4921 if (!local_description() || !sdp_mline_index) {
4922 return false;
4923 }
4924
4925 bool content_found = false;
4926 const ContentInfos& contents = local_description()->description()->contents();
4927 for (size_t index = 0; index < contents.size(); ++index) {
4928 if (contents[index].name == content_name) {
4929 *sdp_mline_index = static_cast<int>(index);
4930 content_found = true;
4931 break;
4932 }
4933 }
4934 return content_found;
4935}
4936
4937bool PeerConnection::UseCandidatesInSessionDescription(
4938 const SessionDescriptionInterface* remote_desc) {
4939 if (!remote_desc) {
4940 return true;
4941 }
4942 bool ret = true;
4943
4944 for (size_t m = 0; m < remote_desc->number_of_mediasections(); ++m) {
4945 const IceCandidateCollection* candidates = remote_desc->candidates(m);
4946 for (size_t n = 0; n < candidates->count(); ++n) {
4947 const IceCandidateInterface* candidate = candidates->at(n);
4948 bool valid = false;
4949 if (!ReadyToUseRemoteCandidate(candidate, remote_desc, &valid)) {
4950 if (valid) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004951 RTC_LOG(LS_INFO)
4952 << "UseCandidatesInSessionDescription: Not ready to use "
4953 << "candidate.";
Steve Anton75737c02017-11-06 10:37:17 -08004954 }
4955 continue;
4956 }
4957 ret = UseCandidate(candidate);
4958 if (!ret) {
4959 break;
4960 }
4961 }
4962 }
4963 return ret;
4964}
4965
4966bool PeerConnection::UseCandidate(const IceCandidateInterface* candidate) {
4967 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
4968 size_t remote_content_size =
4969 remote_description()->description()->contents().size();
4970 if (mediacontent_index >= remote_content_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004971 RTC_LOG(LS_ERROR) << "UseCandidate: Invalid candidate media index.";
Steve Anton75737c02017-11-06 10:37:17 -08004972 return false;
4973 }
4974
4975 cricket::ContentInfo content =
4976 remote_description()->description()->contents()[mediacontent_index];
4977 std::vector<cricket::Candidate> candidates;
4978 candidates.push_back(candidate->candidate());
4979 // Invoking BaseSession method to handle remote candidates.
4980 std::string error;
4981 if (transport_controller_->AddRemoteCandidates(content.name, candidates,
4982 &error)) {
4983 // Candidates successfully submitted for checking.
4984 if (ice_connection_state_ == PeerConnectionInterface::kIceConnectionNew ||
4985 ice_connection_state_ ==
4986 PeerConnectionInterface::kIceConnectionDisconnected) {
4987 // If state is New, then the session has just gotten its first remote ICE
4988 // candidates, so go to Checking.
4989 // If state is Disconnected, the session is re-using old candidates or
4990 // receiving additional ones, so go to Checking.
4991 // If state is Connected, stay Connected.
4992 // TODO(bemasc): If state is Connected, and the new candidates are for a
4993 // newly added transport, then the state actually _should_ move to
4994 // checking. Add a way to distinguish that case.
4995 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
4996 }
4997 // TODO(bemasc): If state is Completed, go back to Connected.
4998 } else {
4999 if (!error.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005000 RTC_LOG(LS_WARNING) << error;
Steve Anton75737c02017-11-06 10:37:17 -08005001 }
5002 }
5003 return true;
5004}
5005
5006void PeerConnection::RemoveUnusedChannels(const SessionDescription* desc) {
Steve Anton75737c02017-11-06 10:37:17 -08005007 // Destroy video channel first since it may have a pointer to the
5008 // voice channel.
5009 const cricket::ContentInfo* video_info = cricket::GetFirstVideoContent(desc);
Steve Anton6fec8802017-12-04 10:37:29 -08005010 if (!video_info || video_info->rejected) {
5011 DestroyTransceiverChannel(GetVideoTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08005012 }
5013
Steve Anton6fec8802017-12-04 10:37:29 -08005014 const cricket::ContentInfo* audio_info = cricket::GetFirstAudioContent(desc);
5015 if (!audio_info || audio_info->rejected) {
5016 DestroyTransceiverChannel(GetAudioTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08005017 }
5018
5019 const cricket::ContentInfo* data_info = cricket::GetFirstDataContent(desc);
5020 if (!data_info || data_info->rejected) {
Steve Anton6fec8802017-12-04 10:37:29 -08005021 DestroyDataChannel();
Steve Anton75737c02017-11-06 10:37:17 -08005022 }
5023}
5024
Steve Antoneda6ccd2017-12-04 10:21:55 -08005025std::string PeerConnection::GetTransportNameForMediaSection(
5026 const std::string& mid,
5027 const cricket::ContentGroup* bundle_group) const {
5028 if (!bundle_group) {
5029 return mid;
Steve Anton75737c02017-11-06 10:37:17 -08005030 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005031 const std::string* first_content_name = bundle_group->FirstContentName();
Steve Anton75737c02017-11-06 10:37:17 -08005032 if (!first_content_name) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005033 RTC_LOG(LS_WARNING) << "Tried to BUNDLE with no contents.";
Steve Antoneda6ccd2017-12-04 10:21:55 -08005034 return mid;
Steve Anton75737c02017-11-06 10:37:17 -08005035 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005036 if (!bundle_group->HasContentName(mid)) {
5037 RTC_LOG(LS_WARNING) << mid << " is not part of any bundle group";
5038 return mid;
Steve Anton75737c02017-11-06 10:37:17 -08005039 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005040 RTC_LOG(LS_INFO) << "Bundling " << mid << " on " << *first_content_name;
5041 return *first_content_name;
Steve Anton75737c02017-11-06 10:37:17 -08005042}
5043
Steve Antondcc3c022017-12-22 16:02:54 -08005044RTCErrorOr<const cricket::ContentGroup*> PeerConnection::GetEarlyBundleGroup(
5045 const SessionDescription& desc) const {
Steve Anton75737c02017-11-06 10:37:17 -08005046 const cricket::ContentGroup* bundle_group = nullptr;
5047 if (configuration_.bundle_policy ==
5048 PeerConnectionInterface::kBundlePolicyMaxBundle) {
Steve Antondcc3c022017-12-22 16:02:54 -08005049 bundle_group = desc.GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton75737c02017-11-06 10:37:17 -08005050 if (!bundle_group) {
Steve Anton8a006912017-12-04 15:25:56 -08005051 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5052 "max-bundle configured but session description "
5053 "has no BUNDLE group");
Steve Anton75737c02017-11-06 10:37:17 -08005054 }
5055 }
Steve Antondcc3c022017-12-22 16:02:54 -08005056 return std::move(bundle_group);
5057}
5058
5059RTCError PeerConnection::CreateChannels(const SessionDescription& desc) {
5060 auto bundle_group_or_error = GetEarlyBundleGroup(desc);
5061 if (!bundle_group_or_error.ok()) {
5062 return bundle_group_or_error.MoveError();
5063 }
5064 const cricket::ContentGroup* bundle_group = bundle_group_or_error.MoveValue();
Steve Anton75737c02017-11-06 10:37:17 -08005065
Steve Antoneda6ccd2017-12-04 10:21:55 -08005066 // Creating the media channels and transport proxies.
Steve Antondcc3c022017-12-22 16:02:54 -08005067 const cricket::ContentInfo* voice = cricket::GetFirstAudioContent(&desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08005068 if (voice && !voice->rejected &&
5069 !GetAudioTransceiver()->internal()->channel()) {
5070 cricket::VoiceChannel* voice_channel = CreateVoiceChannel(
5071 voice->name,
5072 GetTransportNameForMediaSection(voice->name, bundle_group));
5073 if (!voice_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08005074 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5075 "Failed to create voice channel.");
Steve Antoneda6ccd2017-12-04 10:21:55 -08005076 }
5077 GetAudioTransceiver()->internal()->SetChannel(voice_channel);
5078 }
5079
Steve Antondcc3c022017-12-22 16:02:54 -08005080 const cricket::ContentInfo* video = cricket::GetFirstVideoContent(&desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08005081 if (video && !video->rejected &&
5082 !GetVideoTransceiver()->internal()->channel()) {
5083 cricket::VideoChannel* video_channel = CreateVideoChannel(
5084 video->name,
5085 GetTransportNameForMediaSection(video->name, bundle_group));
5086 if (!video_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08005087 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5088 "Failed to create video channel.");
Steve Anton75737c02017-11-06 10:37:17 -08005089 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005090 GetVideoTransceiver()->internal()->SetChannel(video_channel);
Steve Anton75737c02017-11-06 10:37:17 -08005091 }
5092
Steve Antondcc3c022017-12-22 16:02:54 -08005093 const cricket::ContentInfo* data = cricket::GetFirstDataContent(&desc);
Steve Anton75737c02017-11-06 10:37:17 -08005094 if (data_channel_type_ != cricket::DCT_NONE && data && !data->rejected &&
5095 !rtp_data_channel_ && !sctp_transport_) {
Steve Antoneda6ccd2017-12-04 10:21:55 -08005096 if (!CreateDataChannel(data->name, GetTransportNameForMediaSection(
5097 data->name, bundle_group))) {
Steve Anton8a006912017-12-04 15:25:56 -08005098 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5099 "Failed to create data channel.");
Steve Anton75737c02017-11-06 10:37:17 -08005100 }
5101 }
5102
Steve Anton8a006912017-12-04 15:25:56 -08005103 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08005104}
5105
Steve Anton4171afb2017-11-20 10:20:22 -08005106// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08005107cricket::VoiceChannel* PeerConnection::CreateVoiceChannel(
5108 const std::string& mid,
5109 const std::string& transport_name) {
Steve Anton75737c02017-11-06 10:37:17 -08005110 cricket::DtlsTransportInternal* rtp_dtls_transport =
5111 transport_controller_->CreateDtlsTransport(
5112 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5113 cricket::DtlsTransportInternal* rtcp_dtls_transport = nullptr;
5114 if (configuration_.rtcp_mux_policy !=
5115 PeerConnectionInterface::kRtcpMuxPolicyRequire) {
5116 rtcp_dtls_transport = transport_controller_->CreateDtlsTransport(
5117 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
5118 }
5119
5120 cricket::VoiceChannel* voice_channel = channel_manager()->CreateVoiceChannel(
5121 call_.get(), configuration_.media_config, rtp_dtls_transport,
Steve Antoneda6ccd2017-12-04 10:21:55 -08005122 rtcp_dtls_transport, signaling_thread(), mid, SrtpRequired(),
5123 audio_options_);
Steve Anton75737c02017-11-06 10:37:17 -08005124 if (!voice_channel) {
5125 transport_controller_->DestroyDtlsTransport(
5126 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5127 if (rtcp_dtls_transport) {
5128 transport_controller_->DestroyDtlsTransport(
5129 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
5130 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005131 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08005132 }
Steve Anton75737c02017-11-06 10:37:17 -08005133 voice_channel->SignalRtcpMuxFullyActive.connect(
5134 this, &PeerConnection::DestroyRtcpTransport_n);
5135 voice_channel->SignalDtlsSrtpSetupFailure.connect(
5136 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08005137 voice_channel->SignalSentPacket.connect(this,
5138 &PeerConnection::OnSentPacket_w);
Steve Anton4171afb2017-11-20 10:20:22 -08005139
Steve Antoneda6ccd2017-12-04 10:21:55 -08005140 return voice_channel;
Steve Anton75737c02017-11-06 10:37:17 -08005141}
5142
Steve Anton4171afb2017-11-20 10:20:22 -08005143// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08005144cricket::VideoChannel* PeerConnection::CreateVideoChannel(
5145 const std::string& mid,
5146 const std::string& transport_name) {
Steve Anton75737c02017-11-06 10:37:17 -08005147 cricket::DtlsTransportInternal* rtp_dtls_transport =
5148 transport_controller_->CreateDtlsTransport(
5149 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5150 cricket::DtlsTransportInternal* rtcp_dtls_transport = nullptr;
5151 if (configuration_.rtcp_mux_policy !=
5152 PeerConnectionInterface::kRtcpMuxPolicyRequire) {
5153 rtcp_dtls_transport = transport_controller_->CreateDtlsTransport(
5154 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
5155 }
5156
5157 cricket::VideoChannel* video_channel = channel_manager()->CreateVideoChannel(
5158 call_.get(), configuration_.media_config, rtp_dtls_transport,
Steve Antoneda6ccd2017-12-04 10:21:55 -08005159 rtcp_dtls_transport, signaling_thread(), mid, SrtpRequired(),
5160 video_options_);
Steve Anton75737c02017-11-06 10:37:17 -08005161
5162 if (!video_channel) {
5163 transport_controller_->DestroyDtlsTransport(
5164 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5165 if (rtcp_dtls_transport) {
5166 transport_controller_->DestroyDtlsTransport(
5167 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
5168 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005169 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08005170 }
Steve Anton75737c02017-11-06 10:37:17 -08005171 video_channel->SignalRtcpMuxFullyActive.connect(
5172 this, &PeerConnection::DestroyRtcpTransport_n);
5173 video_channel->SignalDtlsSrtpSetupFailure.connect(
5174 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08005175 video_channel->SignalSentPacket.connect(this,
5176 &PeerConnection::OnSentPacket_w);
Steve Anton4171afb2017-11-20 10:20:22 -08005177
Steve Antoneda6ccd2017-12-04 10:21:55 -08005178 return video_channel;
Steve Anton75737c02017-11-06 10:37:17 -08005179}
5180
Steve Antoneda6ccd2017-12-04 10:21:55 -08005181bool PeerConnection::CreateDataChannel(const std::string& mid,
5182 const std::string& transport_name) {
Steve Anton75737c02017-11-06 10:37:17 -08005183 bool sctp = (data_channel_type_ == cricket::DCT_SCTP);
5184 if (sctp) {
5185 if (!sctp_factory_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005186 RTC_LOG(LS_ERROR)
Steve Anton75737c02017-11-06 10:37:17 -08005187 << "Trying to create SCTP transport, but didn't compile with "
5188 "SCTP support (HAVE_SCTP)";
5189 return false;
5190 }
5191 if (!network_thread()->Invoke<bool>(
5192 RTC_FROM_HERE, rtc::Bind(&PeerConnection::CreateSctpTransport_n,
Steve Antoneda6ccd2017-12-04 10:21:55 -08005193 this, mid, transport_name))) {
Steve Anton75737c02017-11-06 10:37:17 -08005194 return false;
5195 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005196 for (const auto& channel : sctp_data_channels_) {
5197 channel->OnTransportChannelCreated();
5198 }
Steve Anton75737c02017-11-06 10:37:17 -08005199 } else {
Steve Anton75737c02017-11-06 10:37:17 -08005200 cricket::DtlsTransportInternal* rtp_dtls_transport =
5201 transport_controller_->CreateDtlsTransport(
5202 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5203 cricket::DtlsTransportInternal* rtcp_dtls_transport = nullptr;
5204 if (configuration_.rtcp_mux_policy !=
5205 PeerConnectionInterface::kRtcpMuxPolicyRequire) {
5206 rtcp_dtls_transport = transport_controller_->CreateDtlsTransport(
5207 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
5208 }
5209
5210 rtp_data_channel_ = channel_manager()->CreateRtpDataChannel(
5211 configuration_.media_config, rtp_dtls_transport, rtcp_dtls_transport,
Steve Antoneda6ccd2017-12-04 10:21:55 -08005212 signaling_thread(), mid, SrtpRequired());
Steve Anton75737c02017-11-06 10:37:17 -08005213
5214 if (!rtp_data_channel_) {
5215 transport_controller_->DestroyDtlsTransport(
5216 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5217 if (rtcp_dtls_transport) {
5218 transport_controller_->DestroyDtlsTransport(
5219 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
5220 }
5221 return false;
5222 }
5223
5224 rtp_data_channel_->SignalRtcpMuxFullyActive.connect(
5225 this, &PeerConnection::DestroyRtcpTransport_n);
5226 rtp_data_channel_->SignalDtlsSrtpSetupFailure.connect(
5227 this, &PeerConnection::OnDtlsSrtpSetupFailure);
5228 rtp_data_channel_->SignalSentPacket.connect(
5229 this, &PeerConnection::OnSentPacket_w);
5230 }
5231
Steve Anton75737c02017-11-06 10:37:17 -08005232 return true;
5233}
5234
5235Call::Stats PeerConnection::GetCallStats() {
5236 if (!worker_thread()->IsCurrent()) {
5237 return worker_thread()->Invoke<Call::Stats>(
5238 RTC_FROM_HERE, rtc::Bind(&PeerConnection::GetCallStats, this));
5239 }
5240 if (call_) {
5241 return call_->GetStats();
5242 } else {
5243 return Call::Stats();
5244 }
5245}
5246
5247std::unique_ptr<SessionStats> PeerConnection::GetSessionStats_n(
5248 const ChannelNamePairs& channel_name_pairs) {
5249 RTC_DCHECK(network_thread()->IsCurrent());
5250 std::unique_ptr<SessionStats> session_stats(new SessionStats());
5251 for (const auto channel_name_pair :
5252 {&channel_name_pairs.voice, &channel_name_pairs.video,
5253 &channel_name_pairs.data}) {
5254 if (*channel_name_pair) {
5255 cricket::TransportStats transport_stats;
5256 if (!transport_controller_->GetStats((*channel_name_pair)->transport_name,
5257 &transport_stats)) {
5258 return nullptr;
5259 }
Steve Anton75737c02017-11-06 10:37:17 -08005260 session_stats->transport_stats[(*channel_name_pair)->transport_name] =
5261 std::move(transport_stats);
5262 }
5263 }
5264 return session_stats;
5265}
5266
5267bool PeerConnection::CreateSctpTransport_n(const std::string& content_name,
5268 const std::string& transport_name) {
5269 RTC_DCHECK(network_thread()->IsCurrent());
5270 RTC_DCHECK(sctp_factory_);
5271 cricket::DtlsTransportInternal* tc =
5272 transport_controller_->CreateDtlsTransport_n(
5273 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5274 sctp_transport_ = sctp_factory_->CreateSctpTransport(tc);
5275 RTC_DCHECK(sctp_transport_);
5276 sctp_invoker_.reset(new rtc::AsyncInvoker());
5277 sctp_transport_->SignalReadyToSendData.connect(
5278 this, &PeerConnection::OnSctpTransportReadyToSendData_n);
5279 sctp_transport_->SignalDataReceived.connect(
5280 this, &PeerConnection::OnSctpTransportDataReceived_n);
5281 sctp_transport_->SignalStreamClosedRemotely.connect(
5282 this, &PeerConnection::OnSctpStreamClosedRemotely_n);
Oskar Sundbom9b28a032017-11-16 10:53:30 +01005283 sctp_transport_name_ = transport_name;
5284 sctp_content_name_ = content_name;
Steve Anton75737c02017-11-06 10:37:17 -08005285 return true;
5286}
5287
5288void PeerConnection::ChangeSctpTransport_n(const std::string& transport_name) {
5289 RTC_DCHECK(network_thread()->IsCurrent());
5290 RTC_DCHECK(sctp_transport_);
5291 RTC_DCHECK(sctp_transport_name_);
5292 std::string old_sctp_transport_name = *sctp_transport_name_;
Oskar Sundbom9b28a032017-11-16 10:53:30 +01005293 sctp_transport_name_ = transport_name;
Steve Anton75737c02017-11-06 10:37:17 -08005294 cricket::DtlsTransportInternal* tc =
5295 transport_controller_->CreateDtlsTransport_n(
5296 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5297 sctp_transport_->SetTransportChannel(tc);
5298 transport_controller_->DestroyDtlsTransport_n(
5299 old_sctp_transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5300}
5301
5302void PeerConnection::DestroySctpTransport_n() {
5303 RTC_DCHECK(network_thread()->IsCurrent());
5304 sctp_transport_.reset(nullptr);
Taylor Brandstetter389a97c2018-01-03 16:26:06 -08005305 transport_controller_->DestroyDtlsTransport_n(
5306 *sctp_transport_name_, cricket::ICE_CANDIDATE_COMPONENT_RTP);
Steve Anton75737c02017-11-06 10:37:17 -08005307 sctp_content_name_.reset();
5308 sctp_transport_name_.reset();
5309 sctp_invoker_.reset(nullptr);
5310 sctp_ready_to_send_data_ = false;
5311}
5312
5313void PeerConnection::OnSctpTransportReadyToSendData_n() {
5314 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5315 RTC_DCHECK(network_thread()->IsCurrent());
5316 // Note: Cannot use rtc::Bind here because it will grab a reference to
5317 // PeerConnection and potentially cause PeerConnection to live longer than
5318 // expected. It is safe not to grab a reference since the sctp_invoker_ will
5319 // be destroyed before PeerConnection is destroyed, and at that point all
5320 // pending tasks will be cleared.
5321 sctp_invoker_->AsyncInvoke<void>(RTC_FROM_HERE, signaling_thread(), [this] {
5322 OnSctpTransportReadyToSendData_s(true);
5323 });
5324}
5325
5326void PeerConnection::OnSctpTransportReadyToSendData_s(bool ready) {
5327 RTC_DCHECK(signaling_thread()->IsCurrent());
5328 sctp_ready_to_send_data_ = ready;
5329 SignalSctpReadyToSendData(ready);
5330}
5331
5332void PeerConnection::OnSctpTransportDataReceived_n(
5333 const cricket::ReceiveDataParams& params,
5334 const rtc::CopyOnWriteBuffer& payload) {
5335 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5336 RTC_DCHECK(network_thread()->IsCurrent());
5337 // Note: Cannot use rtc::Bind here because it will grab a reference to
5338 // PeerConnection and potentially cause PeerConnection to live longer than
5339 // expected. It is safe not to grab a reference since the sctp_invoker_ will
5340 // be destroyed before PeerConnection is destroyed, and at that point all
5341 // pending tasks will be cleared.
5342 sctp_invoker_->AsyncInvoke<void>(
5343 RTC_FROM_HERE, signaling_thread(), [this, params, payload] {
5344 OnSctpTransportDataReceived_s(params, payload);
5345 });
5346}
5347
5348void PeerConnection::OnSctpTransportDataReceived_s(
5349 const cricket::ReceiveDataParams& params,
5350 const rtc::CopyOnWriteBuffer& payload) {
5351 RTC_DCHECK(signaling_thread()->IsCurrent());
5352 if (params.type == cricket::DMT_CONTROL && IsOpenMessage(payload)) {
5353 // Received OPEN message; parse and signal that a new data channel should
5354 // be created.
5355 std::string label;
5356 InternalDataChannelInit config;
5357 config.id = params.ssrc;
5358 if (!ParseDataChannelOpenMessage(payload, &label, &config)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005359 RTC_LOG(LS_WARNING) << "Failed to parse the OPEN message for sid "
5360 << params.ssrc;
Steve Anton75737c02017-11-06 10:37:17 -08005361 return;
5362 }
5363 config.open_handshake_role = InternalDataChannelInit::kAcker;
5364 OnDataChannelOpenMessage(label, config);
5365 } else {
5366 // Otherwise just forward the signal.
5367 SignalSctpDataReceived(params, payload);
5368 }
5369}
5370
5371void PeerConnection::OnSctpStreamClosedRemotely_n(int sid) {
5372 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5373 RTC_DCHECK(network_thread()->IsCurrent());
5374 sctp_invoker_->AsyncInvoke<void>(
5375 RTC_FROM_HERE, signaling_thread(),
5376 rtc::Bind(&sigslot::signal1<int>::operator(),
5377 &SignalSctpStreamClosedRemotely, sid));
5378}
5379
5380// Returns false if bundle is enabled and rtcp_mux is disabled.
5381bool PeerConnection::ValidateBundleSettings(const SessionDescription* desc) {
5382 bool bundle_enabled = desc->HasGroup(cricket::GROUP_TYPE_BUNDLE);
5383 if (!bundle_enabled)
5384 return true;
5385
5386 const cricket::ContentGroup* bundle_group =
5387 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
5388 RTC_DCHECK(bundle_group != NULL);
5389
5390 const cricket::ContentInfos& contents = desc->contents();
5391 for (cricket::ContentInfos::const_iterator citer = contents.begin();
5392 citer != contents.end(); ++citer) {
5393 const cricket::ContentInfo* content = (&*citer);
5394 RTC_DCHECK(content != NULL);
5395 if (bundle_group->HasContentName(content->name) && !content->rejected &&
Steve Anton5adfafd2017-12-20 16:34:00 -08005396 content->type == MediaProtocolType::kRtp) {
Steve Anton75737c02017-11-06 10:37:17 -08005397 if (!HasRtcpMuxEnabled(content))
5398 return false;
5399 }
5400 }
5401 // RTCP-MUX is enabled in all the contents.
5402 return true;
5403}
5404
5405bool PeerConnection::HasRtcpMuxEnabled(const cricket::ContentInfo* content) {
Steve Antonb1c1de12017-12-21 15:14:30 -08005406 return content->media_description()->rtcp_mux();
Steve Anton75737c02017-11-06 10:37:17 -08005407}
5408
Steve Anton8a006912017-12-04 15:25:56 -08005409RTCError PeerConnection::ValidateSessionDescription(
Steve Anton75737c02017-11-06 10:37:17 -08005410 const SessionDescriptionInterface* sdesc,
Steve Anton8a006912017-12-04 15:25:56 -08005411 cricket::ContentSource source) {
Steve Antonf8470812017-12-04 10:46:21 -08005412 if (session_error() != SessionError::kNone) {
Steve Anton8a006912017-12-04 15:25:56 -08005413 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
Steve Anton75737c02017-11-06 10:37:17 -08005414 }
5415
5416 if (!sdesc || !sdesc->description()) {
Steve Anton8a006912017-12-04 15:25:56 -08005417 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidSdp);
Steve Anton75737c02017-11-06 10:37:17 -08005418 }
5419
Steve Anton3828c062017-12-06 10:34:51 -08005420 SdpType type = sdesc->GetType();
5421 if ((source == cricket::CS_LOCAL && !ExpectSetLocalDescription(type)) ||
5422 (source == cricket::CS_REMOTE && !ExpectSetRemoteDescription(type))) {
Steve Anton8a006912017-12-04 15:25:56 -08005423 LOG_AND_RETURN_ERROR(
5424 RTCErrorType::INVALID_PARAMETER,
5425 "Called in wrong state: " + GetSignalingStateString(signaling_state()));
Steve Anton75737c02017-11-06 10:37:17 -08005426 }
5427
5428 // Verify crypto settings.
5429 std::string crypto_error;
Steve Anton8a006912017-12-04 15:25:56 -08005430 if (webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED ||
5431 dtls_enabled_) {
Harald Alvestrand194939b2018-01-24 16:04:13 +01005432 RTCError crypto_error =
5433 VerifyCrypto(sdesc->description(), dtls_enabled_, uma_observer_);
Steve Anton8a006912017-12-04 15:25:56 -08005434 if (!crypto_error.ok()) {
5435 return crypto_error;
5436 }
Steve Anton75737c02017-11-06 10:37:17 -08005437 }
5438
5439 // Verify ice-ufrag and ice-pwd.
5440 if (!VerifyIceUfragPwdPresent(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08005441 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5442 kSdpWithoutIceUfragPwd);
Steve Anton75737c02017-11-06 10:37:17 -08005443 }
5444
5445 if (!ValidateBundleSettings(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08005446 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5447 kBundleWithoutRtcpMux);
Steve Anton75737c02017-11-06 10:37:17 -08005448 }
5449
5450 // TODO(skvlad): When the local rtcp-mux policy is Require, reject any
5451 // m-lines that do not rtcp-mux enabled.
5452
5453 // Verify m-lines in Answer when compared against Offer.
Steve Anton3828c062017-12-06 10:34:51 -08005454 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Anton75737c02017-11-06 10:37:17 -08005455 const cricket::SessionDescription* offer_desc =
5456 (source == cricket::CS_LOCAL) ? remote_description()->description()
5457 : local_description()->description();
5458 if (!MediaSectionsHaveSameCount(offer_desc, sdesc->description()) ||
5459 !MediaSectionsInSameOrder(offer_desc, sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08005460 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5461 kMlineMismatchInAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08005462 }
5463 } else {
5464 const cricket::SessionDescription* current_desc = nullptr;
5465 if (source == cricket::CS_LOCAL && local_description()) {
5466 current_desc = local_description()->description();
5467 } else if (source == cricket::CS_REMOTE && remote_description()) {
5468 current_desc = remote_description()->description();
5469 }
5470 // The re-offers should respect the order of m= sections in current
5471 // description. See RFC3264 Section 8 paragraph 4 for more details.
5472 if (current_desc &&
5473 !MediaSectionsInSameOrder(current_desc, sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08005474 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5475 kMlineMismatchInSubsequentOffer);
Steve Anton75737c02017-11-06 10:37:17 -08005476 }
5477 }
5478
Steve Anton8a006912017-12-04 15:25:56 -08005479 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08005480}
5481
Steve Anton3828c062017-12-06 10:34:51 -08005482bool PeerConnection::ExpectSetLocalDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08005483 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08005484 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08005485 return (state == PeerConnectionInterface::kStable) ||
5486 (state == PeerConnectionInterface::kHaveLocalOffer);
Steve Anton20393062017-12-04 16:24:52 -08005487 } else {
Steve Anton3828c062017-12-06 10:34:51 -08005488 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08005489 return (state == PeerConnectionInterface::kHaveRemoteOffer) ||
5490 (state == PeerConnectionInterface::kHaveLocalPrAnswer);
5491 }
5492}
5493
Steve Anton3828c062017-12-06 10:34:51 -08005494bool PeerConnection::ExpectSetRemoteDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08005495 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08005496 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08005497 return (state == PeerConnectionInterface::kStable) ||
5498 (state == PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton20393062017-12-04 16:24:52 -08005499 } else {
Steve Anton3828c062017-12-06 10:34:51 -08005500 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08005501 return (state == PeerConnectionInterface::kHaveLocalOffer) ||
5502 (state == PeerConnectionInterface::kHaveRemotePrAnswer);
5503 }
5504}
5505
Steve Antonf8470812017-12-04 10:46:21 -08005506const char* PeerConnection::SessionErrorToString(SessionError error) const {
5507 switch (error) {
5508 case SessionError::kNone:
5509 return "ERROR_NONE";
5510 case SessionError::kContent:
5511 return "ERROR_CONTENT";
5512 case SessionError::kTransport:
5513 return "ERROR_TRANSPORT";
5514 }
5515 RTC_NOTREACHED();
5516 return "";
5517}
5518
Steve Anton75737c02017-11-06 10:37:17 -08005519std::string PeerConnection::GetSessionErrorMsg() {
5520 std::ostringstream desc;
Steve Antonf8470812017-12-04 10:46:21 -08005521 desc << kSessionError << SessionErrorToString(session_error()) << ". ";
5522 desc << kSessionErrorDesc << session_error_desc() << ".";
Steve Anton75737c02017-11-06 10:37:17 -08005523 return desc.str();
5524}
5525
5526// We need to check the local/remote description for the Transport instead of
5527// the session, because a new Transport added during renegotiation may have
5528// them unset while the session has them set from the previous negotiation.
5529// Not doing so may trigger the auto generation of transport description and
5530// mess up DTLS identity information, ICE credential, etc.
5531bool PeerConnection::ReadyToUseRemoteCandidate(
5532 const IceCandidateInterface* candidate,
5533 const SessionDescriptionInterface* remote_desc,
5534 bool* valid) {
5535 *valid = true;
5536
5537 const SessionDescriptionInterface* current_remote_desc =
5538 remote_desc ? remote_desc : remote_description();
5539
5540 if (!current_remote_desc) {
5541 return false;
5542 }
5543
5544 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
5545 size_t remote_content_size =
5546 current_remote_desc->description()->contents().size();
5547 if (mediacontent_index >= remote_content_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005548 RTC_LOG(LS_ERROR)
5549 << "ReadyToUseRemoteCandidate: Invalid candidate media index "
5550 << mediacontent_index;
Steve Anton75737c02017-11-06 10:37:17 -08005551
5552 *valid = false;
5553 return false;
5554 }
5555
5556 cricket::ContentInfo content =
5557 current_remote_desc->description()->contents()[mediacontent_index];
5558
5559 const std::string transport_name = GetTransportName(content.name);
5560 if (transport_name.empty()) {
5561 return false;
5562 }
5563 return transport_controller_->ReadyForRemoteCandidates(transport_name);
5564}
5565
5566bool PeerConnection::SrtpRequired() const {
5567 return dtls_enabled_ ||
5568 webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED;
5569}
5570
5571void PeerConnection::OnTransportControllerGatheringState(
5572 cricket::IceGatheringState state) {
5573 RTC_DCHECK(signaling_thread()->IsCurrent());
5574 if (state == cricket::kIceGatheringGathering) {
5575 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringGathering);
5576 } else if (state == cricket::kIceGatheringComplete) {
5577 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringComplete);
5578 }
5579}
5580
5581void PeerConnection::ReportTransportStats() {
5582 // Use a set so we don't report the same stats twice if two channels share
5583 // a transport.
5584 std::set<std::string> transport_names;
5585 if (voice_channel()) {
5586 transport_names.insert(voice_channel()->transport_name());
5587 }
5588 if (video_channel()) {
5589 transport_names.insert(video_channel()->transport_name());
5590 }
5591 if (rtp_data_channel()) {
5592 transport_names.insert(rtp_data_channel()->transport_name());
5593 }
5594 if (sctp_transport_name_) {
5595 transport_names.insert(*sctp_transport_name_);
5596 }
5597 for (const auto& name : transport_names) {
5598 cricket::TransportStats stats;
5599 if (transport_controller_->GetStats(name, &stats)) {
5600 ReportBestConnectionState(stats);
5601 ReportNegotiatedCiphers(stats);
5602 }
5603 }
5604}
5605// Walk through the ConnectionInfos to gather best connection usage
5606// for IPv4 and IPv6.
5607void PeerConnection::ReportBestConnectionState(
5608 const cricket::TransportStats& stats) {
5609 RTC_DCHECK(metrics_observer());
5610 for (cricket::TransportChannelStatsList::const_iterator it =
5611 stats.channel_stats.begin();
5612 it != stats.channel_stats.end(); ++it) {
5613 for (cricket::ConnectionInfos::const_iterator it_info =
5614 it->connection_infos.begin();
5615 it_info != it->connection_infos.end(); ++it_info) {
5616 if (!it_info->best_connection) {
5617 continue;
5618 }
5619
5620 PeerConnectionEnumCounterType type = kPeerConnectionEnumCounterMax;
5621 const cricket::Candidate& local = it_info->local_candidate;
5622 const cricket::Candidate& remote = it_info->remote_candidate;
5623
5624 // Increment the counter for IceCandidatePairType.
5625 if (local.protocol() == cricket::TCP_PROTOCOL_NAME ||
5626 (local.type() == RELAY_PORT_TYPE &&
5627 local.relay_protocol() == cricket::TCP_PROTOCOL_NAME)) {
5628 type = kEnumCounterIceCandidatePairTypeTcp;
5629 } else if (local.protocol() == cricket::UDP_PROTOCOL_NAME) {
5630 type = kEnumCounterIceCandidatePairTypeUdp;
5631 } else {
5632 RTC_CHECK(0);
5633 }
5634 metrics_observer()->IncrementEnumCounter(
5635 type, GetIceCandidatePairCounter(local, remote),
5636 kIceCandidatePairMax);
5637
5638 // Increment the counter for IP type.
5639 if (local.address().family() == AF_INET) {
5640 metrics_observer()->IncrementEnumCounter(
5641 kEnumCounterAddressFamily, kBestConnections_IPv4,
5642 kPeerConnectionAddressFamilyCounter_Max);
5643
5644 } else if (local.address().family() == AF_INET6) {
5645 metrics_observer()->IncrementEnumCounter(
5646 kEnumCounterAddressFamily, kBestConnections_IPv6,
5647 kPeerConnectionAddressFamilyCounter_Max);
5648 } else {
5649 RTC_CHECK(0);
5650 }
5651
5652 return;
5653 }
5654 }
5655}
5656
5657void PeerConnection::ReportNegotiatedCiphers(
5658 const cricket::TransportStats& stats) {
5659 RTC_DCHECK(metrics_observer());
5660 if (!dtls_enabled_ || stats.channel_stats.empty()) {
5661 return;
5662 }
5663
5664 int srtp_crypto_suite = stats.channel_stats[0].srtp_crypto_suite;
5665 int ssl_cipher_suite = stats.channel_stats[0].ssl_cipher_suite;
5666 if (srtp_crypto_suite == rtc::SRTP_INVALID_CRYPTO_SUITE &&
5667 ssl_cipher_suite == rtc::TLS_NULL_WITH_NULL_NULL) {
5668 return;
5669 }
5670
5671 PeerConnectionEnumCounterType srtp_counter_type;
5672 PeerConnectionEnumCounterType ssl_counter_type;
5673 if (stats.transport_name == cricket::CN_AUDIO) {
5674 srtp_counter_type = kEnumCounterAudioSrtpCipher;
5675 ssl_counter_type = kEnumCounterAudioSslCipher;
5676 } else if (stats.transport_name == cricket::CN_VIDEO) {
5677 srtp_counter_type = kEnumCounterVideoSrtpCipher;
5678 ssl_counter_type = kEnumCounterVideoSslCipher;
5679 } else if (stats.transport_name == cricket::CN_DATA) {
5680 srtp_counter_type = kEnumCounterDataSrtpCipher;
5681 ssl_counter_type = kEnumCounterDataSslCipher;
5682 } else {
5683 RTC_NOTREACHED();
5684 return;
5685 }
5686
5687 if (srtp_crypto_suite != rtc::SRTP_INVALID_CRYPTO_SUITE) {
5688 metrics_observer()->IncrementSparseEnumCounter(srtp_counter_type,
5689 srtp_crypto_suite);
5690 }
5691 if (ssl_cipher_suite != rtc::TLS_NULL_WITH_NULL_NULL) {
5692 metrics_observer()->IncrementSparseEnumCounter(ssl_counter_type,
5693 ssl_cipher_suite);
5694 }
5695}
5696
5697void PeerConnection::OnSentPacket_w(const rtc::SentPacket& sent_packet) {
5698 RTC_DCHECK(worker_thread()->IsCurrent());
5699 RTC_DCHECK(call_);
5700 call_->OnSentPacket(sent_packet);
5701}
5702
5703const std::string PeerConnection::GetTransportName(
5704 const std::string& content_name) {
5705 cricket::BaseChannel* channel = GetChannel(content_name);
Steve Anton6fec8802017-12-04 10:37:29 -08005706 if (channel) {
5707 return channel->transport_name();
Steve Anton75737c02017-11-06 10:37:17 -08005708 }
Steve Anton6fec8802017-12-04 10:37:29 -08005709 if (sctp_transport_) {
5710 RTC_DCHECK(sctp_content_name_);
5711 RTC_DCHECK(sctp_transport_name_);
5712 if (content_name == *sctp_content_name_) {
5713 return *sctp_transport_name_;
5714 }
5715 }
5716 // Return an empty string if failed to retrieve the transport name.
5717 return "";
Steve Anton75737c02017-11-06 10:37:17 -08005718}
5719
5720void PeerConnection::DestroyRtcpTransport_n(const std::string& transport_name) {
5721 RTC_DCHECK(network_thread()->IsCurrent());
5722 transport_controller_->DestroyDtlsTransport_n(
5723 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
5724}
5725
Steve Anton6fec8802017-12-04 10:37:29 -08005726void PeerConnection::DestroyTransceiverChannel(
5727 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
5728 transceiver) {
5729 RTC_DCHECK(transceiver);
Steve Anton75737c02017-11-06 10:37:17 -08005730
Steve Anton6fec8802017-12-04 10:37:29 -08005731 cricket::BaseChannel* channel = transceiver->internal()->channel();
5732 if (channel) {
5733 transceiver->internal()->SetChannel(nullptr);
5734 DestroyBaseChannel(channel);
Steve Anton75737c02017-11-06 10:37:17 -08005735 }
5736}
5737
5738void PeerConnection::DestroyDataChannel() {
Steve Anton6fec8802017-12-04 10:37:29 -08005739 if (rtp_data_channel_) {
5740 OnDataChannelDestroyed();
5741 DestroyBaseChannel(rtp_data_channel_);
5742 rtp_data_channel_ = nullptr;
5743 }
5744
5745 // Note: Cannot use rtc::Bind to create a functor to invoke because it will
5746 // grab a reference to this PeerConnection. If this is called from the
5747 // PeerConnection destructor, the RefCountedObject vtable will have already
5748 // been destroyed (since it is a subclass of PeerConnection) and using
5749 // rtc::Bind will cause "Pure virtual function called" error to appear.
5750
5751 if (sctp_transport_) {
5752 OnDataChannelDestroyed();
5753 network_thread()->Invoke<void>(RTC_FROM_HERE,
5754 [this] { DestroySctpTransport_n(); });
5755 }
5756}
5757
5758void PeerConnection::DestroyBaseChannel(cricket::BaseChannel* channel) {
5759 RTC_DCHECK(channel);
5760 RTC_DCHECK(channel->rtp_dtls_transport());
5761
5762 // Need to cache these before destroying the base channel so that we do not
5763 // access uninitialized memory.
5764 const std::string transport_name =
5765 channel->rtp_dtls_transport()->transport_name();
5766 const bool need_to_delete_rtcp = (channel->rtcp_dtls_transport() != nullptr);
5767
5768 switch (channel->media_type()) {
5769 case cricket::MEDIA_TYPE_AUDIO:
5770 channel_manager()->DestroyVoiceChannel(
5771 static_cast<cricket::VoiceChannel*>(channel));
5772 break;
5773 case cricket::MEDIA_TYPE_VIDEO:
5774 channel_manager()->DestroyVideoChannel(
5775 static_cast<cricket::VideoChannel*>(channel));
5776 break;
5777 case cricket::MEDIA_TYPE_DATA:
5778 channel_manager()->DestroyRtpDataChannel(
5779 static_cast<cricket::RtpDataChannel*>(channel));
5780 break;
5781 default:
5782 RTC_NOTREACHED() << "Unknown media type: " << channel->media_type();
5783 break;
5784 }
5785
5786 // |channel| can no longer be used.
5787
Steve Anton75737c02017-11-06 10:37:17 -08005788 transport_controller_->DestroyDtlsTransport(
5789 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5790 if (need_to_delete_rtcp) {
5791 transport_controller_->DestroyDtlsTransport(
5792 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
5793 }
5794}
5795
Harald Alvestrand89061872018-01-02 14:08:34 +01005796void PeerConnection::ClearStatsCache() {
5797 if (stats_collector_) {
5798 stats_collector_->ClearCachedStatsReport();
5799 }
5800}
5801
henrike@webrtc.org28e20752013-07-10 00:45:36 +00005802} // namespace webrtc