blob: c361468c68293e777dc9b22307ee8cd5bd247f47 [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 transceiver->internal()->receiver_internal()->SetupMediaChannel(
Steve Anton5f94aa22018-02-01 10:58:30 -08002154 media_desc->streams()[0].first_ssrc());
Steve Antond3679212018-01-17 17:41:02 -08002155 }
Steve Antondcc3c022017-12-22 16:02:54 -08002156 }
Steve Antonef65ef12018-01-10 17:15:20 -08002157 for (auto event : track_events) {
2158 observer_->OnAddTrack(event.receiver, event.streams);
2159 }
Steve Antondcc3c022017-12-22 16:02:54 -08002160 }
2161
Henrik Boströmfdb92012017-11-09 19:55:44 +01002162 const cricket::ContentInfo* audio_content =
2163 GetFirstAudioContent(remote_description()->description());
2164 const cricket::ContentInfo* video_content =
2165 GetFirstVideoContent(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002166 const cricket::AudioContentDescription* audio_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002167 GetFirstAudioContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002168 const cricket::VideoContentDescription* video_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002169 GetFirstVideoContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002170 const cricket::DataContentDescription* data_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002171 GetFirstDataContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002172
2173 // Check if the descriptions include streams, just in case the peer supports
2174 // MSID, but doesn't indicate so with "a=msid-semantic".
Henrik Boströmfdb92012017-11-09 19:55:44 +01002175 if (remote_description()->description()->msid_supported() ||
deadbeefbda7e0b2015-12-08 17:13:40 -08002176 (audio_desc && !audio_desc->streams().empty()) ||
2177 (video_desc && !video_desc->streams().empty())) {
2178 remote_peer_supports_msid_ = true;
2179 }
deadbeefab9b2d12015-10-14 11:33:11 -07002180
2181 // We wait to signal new streams until we finish processing the description,
2182 // since only at that point will new streams have all their tracks.
2183 rtc::scoped_refptr<StreamCollection> new_streams(StreamCollection::Create());
2184
Steve Antondcc3c022017-12-22 16:02:54 -08002185 if (!IsUnifiedPlan()) {
2186 // TODO(steveanton): When removing RTP senders/receivers in response to a
2187 // rejected media section, there is some cleanup logic that expects the
2188 // voice/ video channel to still be set. But in this method the voice/video
2189 // channel would have been destroyed by the SetRemoteDescription caller
2190 // above so the cleanup that relies on them fails to run. The RemoveSenders
2191 // calls should be moved to right before the DestroyChannel calls to fix
2192 // this.
Steve Anton8d3444d2017-10-20 15:30:51 -07002193
Steve Antondcc3c022017-12-22 16:02:54 -08002194 // Find all audio rtp streams and create corresponding remote AudioTracks
2195 // and MediaStreams.
2196 if (audio_content) {
2197 if (audio_content->rejected) {
2198 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
2199 } else {
2200 bool default_audio_track_needed =
2201 !remote_peer_supports_msid_ &&
2202 RtpTransceiverDirectionHasSend(audio_desc->direction());
2203 UpdateRemoteSendersList(GetActiveStreams(audio_desc),
2204 default_audio_track_needed, audio_desc->type(),
2205 new_streams);
2206 }
deadbeeffaac4972015-11-12 15:33:07 -08002207 }
deadbeefab9b2d12015-10-14 11:33:11 -07002208
Steve Antondcc3c022017-12-22 16:02:54 -08002209 // Find all video rtp streams and create corresponding remote VideoTracks
2210 // and MediaStreams.
2211 if (video_content) {
2212 if (video_content->rejected) {
2213 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
2214 } else {
2215 bool default_video_track_needed =
2216 !remote_peer_supports_msid_ &&
2217 RtpTransceiverDirectionHasSend(video_desc->direction());
2218 UpdateRemoteSendersList(GetActiveStreams(video_desc),
2219 default_video_track_needed, video_desc->type(),
2220 new_streams);
2221 }
deadbeeffaac4972015-11-12 15:33:07 -08002222 }
deadbeefab9b2d12015-10-14 11:33:11 -07002223
Steve Antondcc3c022017-12-22 16:02:54 -08002224 // Update the DataChannels with the information from the remote peer.
2225 if (data_desc) {
2226 if (rtc::starts_with(data_desc->protocol().data(),
2227 cricket::kMediaProtocolRtpPrefix)) {
2228 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
2229 }
deadbeefab9b2d12015-10-14 11:33:11 -07002230 }
deadbeefab9b2d12015-10-14 11:33:11 -07002231
Steve Antondcc3c022017-12-22 16:02:54 -08002232 // Iterate new_streams and notify the observer about new MediaStreams.
2233 for (size_t i = 0; i < new_streams->count(); ++i) {
2234 MediaStreamInterface* new_stream = new_streams->at(i);
2235 stats_->AddStream(new_stream);
2236 observer_->OnAddStream(
2237 rtc::scoped_refptr<MediaStreamInterface>(new_stream));
2238 }
deadbeefab9b2d12015-10-14 11:33:11 -07002239
Steve Antondcc3c022017-12-22 16:02:54 -08002240 UpdateEndedRemoteMediaStreams();
2241 }
deadbeefab9b2d12015-10-14 11:33:11 -07002242
Steve Anton8a006912017-12-04 15:25:56 -08002243 return RTCError::OK();
deadbeeffc648b62015-10-13 16:42:33 -07002244}
2245
Steve Antondcc3c022017-12-22 16:02:54 -08002246RTCError PeerConnection::UpdateTransceiversAndDataChannels(
2247 cricket::ContentSource source,
2248 const SessionDescriptionInterface* old_session,
2249 const SessionDescriptionInterface& new_session) {
2250 RTC_DCHECK(IsUnifiedPlan());
2251
Steve Anton7464fca2018-01-19 11:10:37 -08002252 const cricket::ContentGroup* bundle_group = nullptr;
2253 if (new_session.GetType() == SdpType::kOffer) {
2254 auto bundle_group_or_error =
2255 GetEarlyBundleGroup(*new_session.description());
2256 if (!bundle_group_or_error.ok()) {
2257 return bundle_group_or_error.MoveError();
2258 }
2259 bundle_group = bundle_group_or_error.MoveValue();
Steve Antondcc3c022017-12-22 16:02:54 -08002260 }
Steve Antondcc3c022017-12-22 16:02:54 -08002261
2262 const ContentInfos& old_contents =
2263 (old_session ? old_session->description()->contents() : ContentInfos());
2264 const ContentInfos& new_contents = new_session.description()->contents();
2265
2266 for (size_t i = 0; i < new_contents.size(); ++i) {
2267 const cricket::ContentInfo& new_content = new_contents[i];
2268 const cricket::ContentInfo* old_content =
2269 (i < old_contents.size() ? &old_contents[i] : nullptr);
2270 cricket::MediaType media_type = new_content.media_description()->type();
2271 seen_mids_.insert(new_content.name);
2272 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
2273 media_type == cricket::MEDIA_TYPE_VIDEO) {
2274 auto transceiver_or_error =
2275 AssociateTransceiver(source, i, new_content, old_content);
2276 if (!transceiver_or_error.ok()) {
2277 return transceiver_or_error.MoveError();
2278 }
2279 auto transceiver = transceiver_or_error.MoveValue();
Steve Antondcc3c022017-12-22 16:02:54 -08002280 RTCError error =
2281 UpdateTransceiverChannel(transceiver, new_content, bundle_group);
2282 if (!error.ok()) {
2283 return error;
2284 }
2285 } else if (media_type == cricket::MEDIA_TYPE_DATA) {
Steve Antonfa2260d2017-12-28 16:38:23 -08002286 if (GetDataMid() && new_content.name != *GetDataMid()) {
2287 // Ignore all but the first data section.
2288 continue;
2289 }
2290 RTCError error = UpdateDataChannel(source, new_content, bundle_group);
2291 if (!error.ok()) {
2292 return error;
2293 }
Steve Antondcc3c022017-12-22 16:02:54 -08002294 } else {
2295 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
2296 "Unknown section type.");
2297 }
2298 }
2299
2300 return RTCError::OK();
2301}
2302
2303RTCError PeerConnection::UpdateTransceiverChannel(
2304 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2305 transceiver,
2306 const cricket::ContentInfo& content,
2307 const cricket::ContentGroup* bundle_group) {
2308 RTC_DCHECK(IsUnifiedPlan());
2309 RTC_DCHECK(transceiver);
2310 cricket::BaseChannel* channel = transceiver->internal()->channel();
2311 if (content.rejected) {
2312 if (channel) {
2313 transceiver->internal()->SetChannel(nullptr);
2314 DestroyBaseChannel(channel);
2315 }
2316 } else {
2317 if (!channel) {
2318 if (transceiver->internal()->media_type() == cricket::MEDIA_TYPE_AUDIO) {
2319 channel = CreateVoiceChannel(
2320 content.name,
2321 GetTransportNameForMediaSection(content.name, bundle_group));
2322 } else {
2323 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO,
2324 transceiver->internal()->media_type());
2325 channel = CreateVideoChannel(
2326 content.name,
2327 GetTransportNameForMediaSection(content.name, bundle_group));
2328 }
2329 if (!channel) {
2330 LOG_AND_RETURN_ERROR(
2331 RTCErrorType::INTERNAL_ERROR,
2332 "Failed to create channel for mid=" + content.name);
2333 }
2334 transceiver->internal()->SetChannel(channel);
2335 }
2336 }
2337 return RTCError::OK();
2338}
2339
Steve Antonfa2260d2017-12-28 16:38:23 -08002340RTCError PeerConnection::UpdateDataChannel(
2341 cricket::ContentSource source,
2342 const cricket::ContentInfo& content,
2343 const cricket::ContentGroup* bundle_group) {
2344 if (data_channel_type_ == cricket::DCT_NONE) {
Steve Antondbf9d032018-01-19 15:23:40 -08002345 // If data channels are disabled, ignore this media section. CreateAnswer
2346 // will take care of rejecting it.
2347 return RTCError::OK();
Steve Antonfa2260d2017-12-28 16:38:23 -08002348 }
2349 if (content.rejected) {
2350 DestroyDataChannel();
2351 } else {
2352 if (!rtp_data_channel_ && !sctp_transport_) {
2353 if (!CreateDataChannel(content.name, GetTransportNameForMediaSection(
2354 content.name, bundle_group))) {
2355 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
2356 "Failed to create data channel.");
2357 }
2358 }
2359 if (source == cricket::CS_REMOTE) {
2360 const MediaContentDescription* data_desc = content.media_description();
2361 if (data_desc && cricket::IsRtpProtocol(data_desc->protocol())) {
2362 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
2363 }
2364 }
2365 }
2366 return RTCError::OK();
2367}
2368
Steve Antondcc3c022017-12-22 16:02:54 -08002369RTCErrorOr<rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
2370PeerConnection::AssociateTransceiver(cricket::ContentSource source,
2371 size_t mline_index,
2372 const ContentInfo& content,
2373 const ContentInfo* old_content) {
2374 RTC_DCHECK(IsUnifiedPlan());
2375 // If the m= section is being recycled (rejected in previous remote
2376 // description, not rejected in current description), dissociate the currently
2377 // associated RtpTransceiver by setting its mid property to null, and discard
2378 // the mapping between the transceiver and its m= section index.
2379 if (old_content && old_content->rejected && !content.rejected) {
2380 auto old_transceiver = GetAssociatedTransceiver(old_content->name);
2381 if (old_transceiver) {
2382 old_transceiver->internal()->set_mid(rtc::nullopt);
2383 old_transceiver->internal()->set_mline_index(rtc::nullopt);
2384 }
2385 }
2386 const MediaContentDescription* media_desc = content.media_description();
2387 auto transceiver = GetAssociatedTransceiver(content.name);
2388 if (source == cricket::CS_LOCAL) {
2389 // Find the RtpTransceiver that corresponds to this m= section, using the
2390 // mapping between transceivers and m= section indices established when
2391 // creating the offer.
2392 if (!transceiver) {
2393 transceiver = GetTransceiverByMLineIndex(mline_index);
2394 }
2395 if (!transceiver) {
2396 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2397 "Unknown transceiver");
2398 }
2399 } else {
2400 RTC_DCHECK_EQ(source, cricket::CS_REMOTE);
2401 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers
2402 // of the same type...
2403 if (!transceiver &&
2404 RtpTransceiverDirectionHasRecv(media_desc->direction())) {
2405 transceiver = FindAvailableTransceiverToReceive(media_desc->type());
2406 }
2407 // If no RtpTransceiver was found in the previous step, create one with a
2408 // recvonly direction.
2409 if (!transceiver) {
Steve Anton02ee47c2018-01-10 16:26:06 -08002410 auto sender =
2411 CreateSender(media_desc->type(), nullptr, {rtc::CreateRandomUuid()});
Steve Anton5f94aa22018-02-01 10:58:30 -08002412 std::string receiver_id;
2413 if (!media_desc->streams().empty()) {
2414 receiver_id = media_desc->streams()[0].id;
2415 } else {
2416 receiver_id = rtc::CreateRandomUuid();
2417 }
2418 auto receiver = CreateReceiver(media_desc->type(), receiver_id);
Steve Anton02ee47c2018-01-10 16:26:06 -08002419 transceiver = CreateAndAddTransceiver(sender, receiver);
Steve Antondcc3c022017-12-22 16:02:54 -08002420 transceiver->internal()->set_direction(
2421 RtpTransceiverDirection::kRecvOnly);
2422 }
2423 }
2424 RTC_DCHECK(transceiver);
2425 if (transceiver->internal()->media_type() != media_desc->type()) {
2426 LOG_AND_RETURN_ERROR(
2427 RTCErrorType::INVALID_PARAMETER,
2428 "Transceiver type does not match media description type.");
2429 }
2430 // Associate the found or created RtpTransceiver with the m= section by
2431 // setting the value of the RtpTransceiver's mid property to the MID of the m=
2432 // section, and establish a mapping between the transceiver and the index of
2433 // the m= section.
2434 transceiver->internal()->set_mid(content.name);
2435 transceiver->internal()->set_mline_index(mline_index);
2436 return std::move(transceiver);
2437}
2438
2439rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2440PeerConnection::GetAssociatedTransceiver(const std::string& mid) const {
2441 RTC_DCHECK(IsUnifiedPlan());
2442 for (auto transceiver : transceivers_) {
2443 if (transceiver->mid() == mid) {
2444 return transceiver;
2445 }
2446 }
2447 return nullptr;
2448}
2449
2450rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2451PeerConnection::GetTransceiverByMLineIndex(size_t mline_index) const {
2452 RTC_DCHECK(IsUnifiedPlan());
2453 for (auto transceiver : transceivers_) {
2454 if (transceiver->internal()->mline_index() == mline_index) {
2455 return transceiver;
2456 }
2457 }
2458 return nullptr;
2459}
2460
2461rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2462PeerConnection::FindAvailableTransceiverToReceive(
2463 cricket::MediaType media_type) const {
2464 RTC_DCHECK(IsUnifiedPlan());
2465 // From JSEP section 5.10 (Applying a Remote Description):
2466 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers of
2467 // the same type that were added to the PeerConnection by addTrack and are not
2468 // associated with any m= section and are not stopped, find the first such
2469 // RtpTransceiver.
2470 for (auto transceiver : transceivers_) {
2471 if (transceiver->internal()->media_type() == media_type &&
2472 transceiver->internal()->created_by_addtrack() && !transceiver->mid() &&
2473 !transceiver->stopped()) {
2474 return transceiver;
2475 }
2476 }
2477 return nullptr;
2478}
2479
Steve Antoned10bd92017-12-05 10:52:59 -08002480const cricket::ContentInfo* PeerConnection::FindMediaSectionForTransceiver(
2481 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2482 transceiver,
2483 const SessionDescriptionInterface* sdesc) const {
2484 RTC_DCHECK(transceiver);
2485 RTC_DCHECK(sdesc);
2486 if (IsUnifiedPlan()) {
2487 if (!transceiver->internal()->mid()) {
2488 // This transceiver is not associated with a media section yet.
2489 return nullptr;
2490 }
2491 return sdesc->description()->GetContentByName(
2492 *transceiver->internal()->mid());
2493 } else {
2494 // Plan B only allows at most one audio and one video section, so use the
2495 // first media section of that type.
2496 return cricket::GetFirstMediaContent(sdesc->description()->contents(),
2497 transceiver->internal()->media_type());
2498 }
2499}
2500
deadbeef46c73892016-11-16 19:42:04 -08002501PeerConnectionInterface::RTCConfiguration PeerConnection::GetConfiguration() {
2502 return configuration_;
2503}
2504
deadbeef293e9262017-01-11 12:28:30 -08002505bool PeerConnection::SetConfiguration(const RTCConfiguration& configuration,
2506 RTCError* error) {
Peter Boström1a9d6152015-12-08 22:15:17 +01002507 TRACE_EVENT0("webrtc", "PeerConnection::SetConfiguration");
deadbeef6de92f92016-12-12 18:49:32 -08002508
Steve Anton75737c02017-11-06 10:37:17 -08002509 if (local_description() && configuration.ice_candidate_pool_size !=
2510 configuration_.ice_candidate_pool_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002511 RTC_LOG(LS_ERROR) << "Can't change candidate pool size after calling "
2512 "SetLocalDescription.";
deadbeef293e9262017-01-11 12:28:30 -08002513 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00002514 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002515
deadbeef293e9262017-01-11 12:28:30 -08002516 // The simplest (and most future-compatible) way to tell if the config was
2517 // modified in an invalid way is to copy each property we do support
2518 // modifying, then use operator==. There are far more properties we don't
2519 // support modifying than those we do, and more could be added.
2520 RTCConfiguration modified_config = configuration_;
2521 modified_config.servers = configuration.servers;
2522 modified_config.type = configuration.type;
2523 modified_config.ice_candidate_pool_size =
2524 configuration.ice_candidate_pool_size;
2525 modified_config.prune_turn_ports = configuration.prune_turn_ports;
skvladd1f5fda2017-02-03 16:54:05 -08002526 modified_config.ice_check_min_interval = configuration.ice_check_min_interval;
Jonas Orelandbdcee282017-10-10 14:01:40 +02002527 modified_config.turn_customizer = configuration.turn_customizer;
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08002528 modified_config.network_preference = configuration.network_preference;
deadbeef293e9262017-01-11 12:28:30 -08002529 if (configuration != modified_config) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002530 RTC_LOG(LS_ERROR) << "Modifying the configuration in an unsupported way.";
deadbeef293e9262017-01-11 12:28:30 -08002531 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
2532 }
2533
Steve Anton038834f2017-07-14 15:59:59 -07002534 // Validate the modified configuration.
2535 RTCError validate_error = ValidateConfiguration(modified_config);
2536 if (!validate_error.ok()) {
2537 return SafeSetError(std::move(validate_error), error);
2538 }
2539
deadbeef293e9262017-01-11 12:28:30 -08002540 // Note that this isn't possible through chromium, since it's an unsigned
2541 // short in WebIDL.
2542 if (configuration.ice_candidate_pool_size < 0 ||
2543 configuration.ice_candidate_pool_size > UINT16_MAX) {
2544 return SafeSetError(RTCErrorType::INVALID_RANGE, error);
2545 }
2546
2547 // Parse ICE servers before hopping to network thread.
2548 cricket::ServerAddresses stun_servers;
2549 std::vector<cricket::RelayServerConfig> turn_servers;
2550 RTCErrorType parse_error =
2551 ParseIceServers(configuration.servers, &stun_servers, &turn_servers);
2552 if (parse_error != RTCErrorType::NONE) {
2553 return SafeSetError(parse_error, error);
2554 }
2555
2556 // In theory this shouldn't fail.
2557 if (!network_thread()->Invoke<bool>(
2558 RTC_FROM_HERE,
2559 rtc::Bind(&PeerConnection::ReconfigurePortAllocator_n, this,
2560 stun_servers, turn_servers, modified_config.type,
2561 modified_config.ice_candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02002562 modified_config.prune_turn_ports,
2563 modified_config.turn_customizer))) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002564 RTC_LOG(LS_ERROR) << "Failed to apply configuration to PortAllocator.";
deadbeef293e9262017-01-11 12:28:30 -08002565 return SafeSetError(RTCErrorType::INTERNAL_ERROR, error);
2566 }
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07002567
deadbeefd1a38b52016-12-10 13:15:33 -08002568 // As described in JSEP, calling setConfiguration with new ICE servers or
2569 // candidate policy must set a "needs-ice-restart" bit so that the next offer
2570 // triggers an ICE restart which will pick up the changes.
deadbeef293e9262017-01-11 12:28:30 -08002571 if (modified_config.servers != configuration_.servers ||
2572 modified_config.type != configuration_.type ||
2573 modified_config.prune_turn_ports != configuration_.prune_turn_ports) {
Steve Antond25da372017-11-06 14:50:29 -08002574 transport_controller_->SetNeedsIceRestartFlag();
deadbeefd1a38b52016-12-10 13:15:33 -08002575 }
skvladd1f5fda2017-02-03 16:54:05 -08002576
2577 if (modified_config.ice_check_min_interval !=
2578 configuration_.ice_check_min_interval) {
Steve Antond25da372017-11-06 14:50:29 -08002579 transport_controller_->SetIceConfig(ParseIceConfig(modified_config));
skvladd1f5fda2017-02-03 16:54:05 -08002580 }
2581
deadbeef293e9262017-01-11 12:28:30 -08002582 configuration_ = modified_config;
2583 return SafeSetError(RTCErrorType::NONE, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00002584}
2585
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002586bool PeerConnection::AddIceCandidate(
2587 const IceCandidateInterface* ice_candidate) {
Peter Boström1a9d6152015-12-08 22:15:17 +01002588 TRACE_EVENT0("webrtc", "PeerConnection::AddIceCandidate");
zhihuang29ff8442016-07-27 11:07:25 -07002589 if (IsClosed()) {
2590 return false;
2591 }
Steve Antond25da372017-11-06 14:50:29 -08002592
2593 if (!remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002594 RTC_LOG(LS_ERROR) << "ProcessIceMessage: ICE candidates can't be added "
2595 << "without any remote session description.";
Steve Antond25da372017-11-06 14:50:29 -08002596 return false;
2597 }
2598
2599 if (!ice_candidate) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002600 RTC_LOG(LS_ERROR) << "ProcessIceMessage: Candidate is NULL.";
Steve Antond25da372017-11-06 14:50:29 -08002601 return false;
2602 }
2603
2604 bool valid = false;
2605 bool ready = ReadyToUseRemoteCandidate(ice_candidate, nullptr, &valid);
2606 if (!valid) {
2607 return false;
2608 }
2609
2610 // Add this candidate to the remote session description.
2611 if (!mutable_remote_description()->AddCandidate(ice_candidate)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002612 RTC_LOG(LS_ERROR) << "ProcessIceMessage: Candidate cannot be used.";
Steve Antond25da372017-11-06 14:50:29 -08002613 return false;
2614 }
2615
2616 if (ready) {
2617 return UseCandidate(ice_candidate);
2618 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002619 RTC_LOG(LS_INFO) << "ProcessIceMessage: Not ready to use candidate.";
Steve Antond25da372017-11-06 14:50:29 -08002620 return true;
2621 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002622}
2623
Honghai Zhang7fb69db2016-03-14 11:59:18 -07002624bool PeerConnection::RemoveIceCandidates(
2625 const std::vector<cricket::Candidate>& candidates) {
2626 TRACE_EVENT0("webrtc", "PeerConnection::RemoveIceCandidates");
Steve Antond25da372017-11-06 14:50:29 -08002627 if (!remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002628 RTC_LOG(LS_ERROR) << "RemoveRemoteIceCandidates: ICE candidates can't be "
2629 << "removed without any remote session description.";
Steve Antond25da372017-11-06 14:50:29 -08002630 return false;
2631 }
2632
2633 if (candidates.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002634 RTC_LOG(LS_ERROR) << "RemoveRemoteIceCandidates: candidates are empty.";
Steve Antond25da372017-11-06 14:50:29 -08002635 return false;
2636 }
2637
2638 size_t number_removed =
2639 mutable_remote_description()->RemoveCandidates(candidates);
2640 if (number_removed != candidates.size()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002641 RTC_LOG(LS_ERROR)
2642 << "RemoveRemoteIceCandidates: Failed to remove candidates. "
2643 << "Requested " << candidates.size() << " but only " << number_removed
2644 << " are removed.";
Steve Antond25da372017-11-06 14:50:29 -08002645 }
2646
2647 // Remove the candidates from the transport controller.
2648 std::string error;
2649 bool res = transport_controller_->RemoveRemoteCandidates(candidates, &error);
2650 if (!res && !error.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002651 RTC_LOG(LS_ERROR) << "Error when removing remote candidates: " << error;
Steve Antond25da372017-11-06 14:50:29 -08002652 }
2653 return true;
Honghai Zhang7fb69db2016-03-14 11:59:18 -07002654}
2655
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00002656void PeerConnection::RegisterUMAObserver(UMAObserver* observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +01002657 TRACE_EVENT0("webrtc", "PeerConnection::RegisterUmaObserver");
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00002658 uma_observer_ = observer;
guoweis@webrtc.org7169afd2014-12-04 17:59:29 +00002659
Steve Anton75737c02017-11-06 10:37:17 -08002660 if (transport_controller()) {
2661 transport_controller()->SetMetricsObserver(uma_observer_);
guoweis@webrtc.org7169afd2014-12-04 17:59:29 +00002662 }
2663
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00002664 // Send information about IPv4/IPv6 status.
deadbeef293e9262017-01-11 12:28:30 -08002665 if (uma_observer_) {
Honghai Zhangd93f50c2016-10-05 11:47:22 -07002666 port_allocator_->SetMetricsObserver(uma_observer_);
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00002667 if (port_allocator_->flags() & cricket::PORTALLOCATOR_ENABLE_IPV6) {
Guo-wei Shiehdfbe6792015-09-03 17:12:07 -07002668 uma_observer_->IncrementEnumCounter(
2669 kEnumCounterAddressFamily, kPeerConnection_IPv6,
2670 kPeerConnectionAddressFamilyCounter_Max);
mallinath@webrtc.orgb445f262014-05-23 22:19:37 +00002671 } else {
Guo-wei Shiehdfbe6792015-09-03 17:12:07 -07002672 uma_observer_->IncrementEnumCounter(
2673 kEnumCounterAddressFamily, kPeerConnection_IPv4,
2674 kPeerConnectionAddressFamilyCounter_Max);
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00002675 }
2676 }
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00002677}
2678
zstein4b979802017-06-02 14:37:37 -07002679RTCError PeerConnection::SetBitrate(const BitrateParameters& bitrate) {
Steve Anton978b8762017-09-29 12:15:02 -07002680 if (!worker_thread()->IsCurrent()) {
2681 return worker_thread()->Invoke<RTCError>(
zstein4b979802017-06-02 14:37:37 -07002682 RTC_FROM_HERE, rtc::Bind(&PeerConnection::SetBitrate, this, bitrate));
2683 }
2684
2685 const bool has_min = static_cast<bool>(bitrate.min_bitrate_bps);
2686 const bool has_current = static_cast<bool>(bitrate.current_bitrate_bps);
2687 const bool has_max = static_cast<bool>(bitrate.max_bitrate_bps);
2688 if (has_min && *bitrate.min_bitrate_bps < 0) {
2689 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2690 "min_bitrate_bps <= 0");
2691 }
2692 if (has_current) {
2693 if (has_min && *bitrate.current_bitrate_bps < *bitrate.min_bitrate_bps) {
2694 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2695 "current_bitrate_bps < min_bitrate_bps");
2696 } else if (*bitrate.current_bitrate_bps < 0) {
2697 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2698 "curent_bitrate_bps < 0");
2699 }
2700 }
2701 if (has_max) {
2702 if (has_current &&
2703 *bitrate.max_bitrate_bps < *bitrate.current_bitrate_bps) {
2704 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2705 "max_bitrate_bps < current_bitrate_bps");
2706 } else if (has_min && *bitrate.max_bitrate_bps < *bitrate.min_bitrate_bps) {
2707 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2708 "max_bitrate_bps < min_bitrate_bps");
2709 } else if (*bitrate.max_bitrate_bps < 0) {
2710 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2711 "max_bitrate_bps < 0");
2712 }
2713 }
2714
2715 Call::Config::BitrateConfigMask mask;
2716 mask.min_bitrate_bps = bitrate.min_bitrate_bps;
2717 mask.start_bitrate_bps = bitrate.current_bitrate_bps;
2718 mask.max_bitrate_bps = bitrate.max_bitrate_bps;
2719
2720 RTC_DCHECK(call_.get());
2721 call_->SetBitrateConfigMask(mask);
2722
2723 return RTCError::OK();
2724}
2725
Alex Narest78609d52017-10-20 10:37:47 +02002726void PeerConnection::SetBitrateAllocationStrategy(
2727 std::unique_ptr<rtc::BitrateAllocationStrategy>
2728 bitrate_allocation_strategy) {
2729 rtc::Thread* worker_thread = factory_->worker_thread();
2730 if (!worker_thread->IsCurrent()) {
2731 rtc::BitrateAllocationStrategy* strategy_raw =
2732 bitrate_allocation_strategy.release();
2733 auto functor = [this, strategy_raw]() {
2734 call_->SetBitrateAllocationStrategy(
2735 rtc::WrapUnique<rtc::BitrateAllocationStrategy>(strategy_raw));
2736 };
2737 worker_thread->Invoke<void>(RTC_FROM_HERE, functor);
2738 return;
2739 }
2740 RTC_DCHECK(call_.get());
2741 call_->SetBitrateAllocationStrategy(std::move(bitrate_allocation_strategy));
2742}
2743
henrika5f6bf242017-11-01 11:06:56 +01002744void PeerConnection::SetAudioPlayout(bool playout) {
2745 if (!worker_thread()->IsCurrent()) {
2746 worker_thread()->Invoke<void>(
2747 RTC_FROM_HERE,
2748 rtc::Bind(&PeerConnection::SetAudioPlayout, this, playout));
2749 return;
2750 }
2751 auto audio_state =
2752 factory_->channel_manager()->media_engine()->GetAudioState();
2753 audio_state->SetPlayout(playout);
2754}
2755
2756void PeerConnection::SetAudioRecording(bool recording) {
2757 if (!worker_thread()->IsCurrent()) {
2758 worker_thread()->Invoke<void>(
2759 RTC_FROM_HERE,
2760 rtc::Bind(&PeerConnection::SetAudioRecording, this, recording));
2761 return;
2762 }
2763 auto audio_state =
2764 factory_->channel_manager()->media_engine()->GetAudioState();
2765 audio_state->SetRecording(recording);
2766}
2767
Steve Anton8c0f7a72017-10-03 10:03:10 -07002768std::unique_ptr<rtc::SSLCertificate>
2769PeerConnection::GetRemoteAudioSSLCertificate() {
Steve Anton75737c02017-11-06 10:37:17 -08002770 if (!voice_channel()) {
Steve Anton8c0f7a72017-10-03 10:03:10 -07002771 return nullptr;
2772 }
Steve Anton75737c02017-11-06 10:37:17 -08002773 return GetRemoteSSLCertificate(voice_channel()->transport_name());
Steve Anton8c0f7a72017-10-03 10:03:10 -07002774}
2775
Zhi Huang70b820f2018-01-27 14:16:15 -08002776std::unique_ptr<rtc::SSLCertChain>
2777PeerConnection::GetRemoteAudioSSLCertChain() {
2778 if (!voice_channel()) {
2779 return nullptr;
2780 }
2781
2782 return transport_controller_->GetRemoteSSLCertChain(
2783 voice_channel()->transport_name());
2784}
2785
ivoc14d5dbe2016-07-04 07:06:55 -07002786bool PeerConnection::StartRtcEventLog(rtc::PlatformFile file,
2787 int64_t max_size_bytes) {
Elad Alon99c3fe52017-10-13 16:29:40 +02002788 // TODO(eladalon): It would be better to not allow negative values into PC.
2789 const size_t max_size = (max_size_bytes < 0)
2790 ? RtcEventLog::kUnlimitedOutput
2791 : rtc::saturated_cast<size_t>(max_size_bytes);
2792 return StartRtcEventLog(
Bjorn Tereliusde939432017-11-20 17:38:14 +01002793 rtc::MakeUnique<RtcEventLogOutputFile>(file, max_size),
2794 webrtc::RtcEventLog::kImmediateOutput);
Elad Alon99c3fe52017-10-13 16:29:40 +02002795}
2796
Bjorn Tereliusde939432017-11-20 17:38:14 +01002797bool PeerConnection::StartRtcEventLog(std::unique_ptr<RtcEventLogOutput> output,
2798 int64_t output_period_ms) {
Karl Wibergd6b48192017-10-16 23:01:06 +02002799 // TODO(eladalon): In C++14, this can be done with a lambda.
2800 struct Functor {
Bjorn Tereliusde939432017-11-20 17:38:14 +01002801 bool operator()() {
2802 return pc->StartRtcEventLog_w(std::move(output), output_period_ms);
2803 }
Karl Wibergd6b48192017-10-16 23:01:06 +02002804 PeerConnection* const pc;
2805 std::unique_ptr<RtcEventLogOutput> output;
Bjorn Tereliusde939432017-11-20 17:38:14 +01002806 const int64_t output_period_ms;
Elad Alon99c3fe52017-10-13 16:29:40 +02002807 };
Bjorn Tereliusde939432017-11-20 17:38:14 +01002808 return worker_thread()->Invoke<bool>(
2809 RTC_FROM_HERE, Functor{this, std::move(output), output_period_ms});
ivoc14d5dbe2016-07-04 07:06:55 -07002810}
2811
2812void PeerConnection::StopRtcEventLog() {
Steve Anton978b8762017-09-29 12:15:02 -07002813 worker_thread()->Invoke<void>(
ivoc14d5dbe2016-07-04 07:06:55 -07002814 RTC_FROM_HERE, rtc::Bind(&PeerConnection::StopRtcEventLog_w, this));
2815}
2816
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002817const SessionDescriptionInterface* PeerConnection::local_description() const {
Steve Anton75737c02017-11-06 10:37:17 -08002818 return pending_local_description_ ? pending_local_description_.get()
2819 : current_local_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002820}
2821
2822const SessionDescriptionInterface* PeerConnection::remote_description() const {
Steve Anton75737c02017-11-06 10:37:17 -08002823 return pending_remote_description_ ? pending_remote_description_.get()
2824 : current_remote_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002825}
2826
deadbeeffe4a8a42016-12-20 17:56:17 -08002827const SessionDescriptionInterface* PeerConnection::current_local_description()
2828 const {
Steve Anton75737c02017-11-06 10:37:17 -08002829 return current_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08002830}
2831
2832const SessionDescriptionInterface* PeerConnection::current_remote_description()
2833 const {
Steve Anton75737c02017-11-06 10:37:17 -08002834 return current_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08002835}
2836
2837const SessionDescriptionInterface* PeerConnection::pending_local_description()
2838 const {
Steve Anton75737c02017-11-06 10:37:17 -08002839 return pending_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08002840}
2841
2842const SessionDescriptionInterface* PeerConnection::pending_remote_description()
2843 const {
Steve Anton75737c02017-11-06 10:37:17 -08002844 return pending_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08002845}
2846
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002847void PeerConnection::Close() {
Peter Boström1a9d6152015-12-08 22:15:17 +01002848 TRACE_EVENT0("webrtc", "PeerConnection::Close");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002849 // Update stats here so that we have the most recent stats for tracks and
2850 // streams before the channels are closed.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00002851 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002852
Steve Anton75737c02017-11-06 10:37:17 -08002853 ChangeSignalingState(PeerConnectionInterface::kClosed);
Steve Anton3fe1b152017-12-12 10:20:08 -08002854
Steve Anton8af21862017-12-15 11:20:13 -08002855 for (auto transceiver : transceivers_) {
2856 transceiver->Stop();
2857 }
2858 DestroyAllChannels();
Steve Anton75737c02017-11-06 10:37:17 -08002859
deadbeef42a42632017-03-10 15:18:00 -08002860 network_thread()->Invoke<void>(
2861 RTC_FROM_HERE,
2862 rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
2863 port_allocator_.get()));
nisseeaabdf62017-05-05 02:23:02 -07002864
Steve Anton978b8762017-09-29 12:15:02 -07002865 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
eladalon248fd4f2017-09-06 05:18:15 -07002866 call_.reset();
2867 // The event log must outlive call (and any other object that uses it).
2868 event_log_.reset();
2869 });
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002870}
2871
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002872void PeerConnection::OnMessage(rtc::Message* msg) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002873 switch (msg->message_id) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002874 case MSG_SET_SESSIONDESCRIPTION_SUCCESS: {
2875 SetSessionDescriptionMsg* param =
2876 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
2877 param->observer->OnSuccess();
2878 delete param;
2879 break;
2880 }
2881 case MSG_SET_SESSIONDESCRIPTION_FAILED: {
2882 SetSessionDescriptionMsg* param =
2883 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
2884 param->observer->OnFailure(param->error);
2885 delete param;
2886 break;
2887 }
deadbeefab9b2d12015-10-14 11:33:11 -07002888 case MSG_CREATE_SESSIONDESCRIPTION_FAILED: {
2889 CreateSessionDescriptionMsg* param =
2890 static_cast<CreateSessionDescriptionMsg*>(msg->pdata);
2891 param->observer->OnFailure(param->error);
2892 delete param;
2893 break;
2894 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002895 case MSG_GETSTATS: {
2896 GetStatsMsg* param = static_cast<GetStatsMsg*>(msg->pdata);
nissee8abe3e2017-01-18 05:00:34 -08002897 StatsReports reports;
2898 stats_->GetStats(param->track, &reports);
2899 param->observer->OnComplete(reports);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002900 delete param;
2901 break;
2902 }
deadbeefbd292462015-12-14 18:15:29 -08002903 case MSG_FREE_DATACHANNELS: {
2904 sctp_data_channels_to_free_.clear();
2905 break;
2906 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002907 default:
nisseeb4ca4e2017-01-12 02:24:27 -08002908 RTC_NOTREACHED() << "Not implemented";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002909 break;
2910 }
2911}
2912
Steve Anton4171afb2017-11-20 10:20:22 -08002913void PeerConnection::CreateAudioReceiver(
2914 MediaStreamInterface* stream,
2915 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01002916 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
2917 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Steve Antond3679212018-01-17 17:41:02 -08002918 auto* audio_receiver = new AudioRtpReceiver(
2919 worker_thread(), remote_sender_info.sender_id, streams);
2920 audio_receiver->SetMediaChannel(voice_media_channel());
2921 audio_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
2922 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
2923 signaling_thread(), audio_receiver);
Steve Anton4171afb2017-11-20 10:20:22 -08002924 GetAudioTransceiver()->internal()->AddReceiver(receiver);
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01002925 observer_->OnAddTrack(receiver, std::move(streams));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002926}
2927
Steve Anton4171afb2017-11-20 10:20:22 -08002928void PeerConnection::CreateVideoReceiver(
2929 MediaStreamInterface* stream,
2930 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01002931 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
2932 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Steve Antond3679212018-01-17 17:41:02 -08002933 auto* video_receiver = new VideoRtpReceiver(
2934 worker_thread(), remote_sender_info.sender_id, streams);
2935 video_receiver->SetMediaChannel(video_media_channel());
2936 video_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
2937 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
2938 signaling_thread(), video_receiver);
Steve Anton4171afb2017-11-20 10:20:22 -08002939 GetVideoTransceiver()->internal()->AddReceiver(receiver);
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01002940 observer_->OnAddTrack(receiver, std::move(streams));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002941}
2942
deadbeef70ab1a12015-09-28 16:53:55 -07002943// TODO(deadbeef): Keep RtpReceivers around even if track goes away in remote
2944// description.
Henrik Boström933d8b02017-10-10 10:05:16 -07002945rtc::scoped_refptr<RtpReceiverInterface> PeerConnection::RemoveAndStopReceiver(
Steve Anton4171afb2017-11-20 10:20:22 -08002946 const RtpSenderInfo& remote_sender_info) {
2947 auto receiver = FindReceiverById(remote_sender_info.sender_id);
2948 if (!receiver) {
2949 RTC_LOG(LS_WARNING) << "RtpReceiver for track with id "
2950 << remote_sender_info.sender_id << " doesn't exist.";
Henrik Boström933d8b02017-10-10 10:05:16 -07002951 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07002952 }
Steve Anton4171afb2017-11-20 10:20:22 -08002953 if (receiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
2954 GetAudioTransceiver()->internal()->RemoveReceiver(receiver);
2955 } else {
2956 GetVideoTransceiver()->internal()->RemoveReceiver(receiver);
2957 }
Henrik Boström933d8b02017-10-10 10:05:16 -07002958 return receiver;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002959}
2960
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002961void PeerConnection::AddAudioTrack(AudioTrackInterface* track,
2962 MediaStreamInterface* stream) {
2963 RTC_DCHECK(!IsClosed());
2964 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08002965 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002966 // We already have a sender for this track, so just change the stream_id
2967 // so that it's correct in the next call to CreateOffer.
Steve Anton4171afb2017-11-20 10:20:22 -08002968 sender->internal()->set_stream_id(stream->label());
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002969 return;
2970 }
2971
2972 // Normal case; we've never seen this track before.
Steve Anton02ee47c2018-01-10 16:26:06 -08002973 auto new_sender =
2974 CreateSender(cricket::MEDIA_TYPE_AUDIO, track, {stream->label()});
2975 static_cast<AudioRtpSender*>(new_sender->internal())
Steve Anton47136dd2018-01-12 10:49:35 -08002976 ->SetMediaChannel(voice_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08002977 GetAudioTransceiver()->internal()->AddSender(new_sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002978 // If the sender has already been configured in SDP, we call SetSsrc,
2979 // which will connect the sender to the underlying transport. This can
2980 // occur if a local session description that contains the ID of the sender
2981 // is set before AddStream is called. It can also occur if the local
2982 // session description is not changed and RemoveStream is called, and
2983 // later AddStream is called again with the same stream.
Steve Anton4171afb2017-11-20 10:20:22 -08002984 const RtpSenderInfo* sender_info =
2985 FindSenderInfo(local_audio_sender_infos_, stream->label(), track->id());
2986 if (sender_info) {
2987 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002988 }
2989}
2990
2991// TODO(deadbeef): Don't destroy RtpSenders here; they should be kept around
2992// indefinitely, when we have unified plan SDP.
2993void PeerConnection::RemoveAudioTrack(AudioTrackInterface* track,
2994 MediaStreamInterface* stream) {
2995 RTC_DCHECK(!IsClosed());
2996 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08002997 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002998 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
2999 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003000 return;
3001 }
Steve Anton4171afb2017-11-20 10:20:22 -08003002 GetAudioTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003003}
3004
3005void PeerConnection::AddVideoTrack(VideoTrackInterface* track,
3006 MediaStreamInterface* stream) {
3007 RTC_DCHECK(!IsClosed());
3008 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003009 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003010 // We already have a sender for this track, so just change the stream_id
3011 // so that it's correct in the next call to CreateOffer.
Steve Anton4171afb2017-11-20 10:20:22 -08003012 sender->internal()->set_stream_id(stream->label());
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003013 return;
3014 }
3015
3016 // Normal case; we've never seen this track before.
Steve Anton02ee47c2018-01-10 16:26:06 -08003017 auto new_sender =
3018 CreateSender(cricket::MEDIA_TYPE_VIDEO, track, {stream->label()});
3019 static_cast<VideoRtpSender*>(new_sender->internal())
Steve Anton47136dd2018-01-12 10:49:35 -08003020 ->SetMediaChannel(video_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08003021 GetVideoTransceiver()->internal()->AddSender(new_sender);
3022 const RtpSenderInfo* sender_info =
3023 FindSenderInfo(local_video_sender_infos_, stream->label(), track->id());
3024 if (sender_info) {
3025 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003026 }
3027}
3028
3029void PeerConnection::RemoveVideoTrack(VideoTrackInterface* track,
3030 MediaStreamInterface* stream) {
3031 RTC_DCHECK(!IsClosed());
3032 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003033 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003034 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
3035 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003036 return;
3037 }
Steve Anton4171afb2017-11-20 10:20:22 -08003038 GetVideoTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003039}
3040
Steve Antonba818672017-11-06 10:21:57 -08003041void PeerConnection::SetIceConnectionState(IceConnectionState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07003042 RTC_DCHECK(signaling_thread()->IsCurrent());
Steve Antonba818672017-11-06 10:21:57 -08003043 if (ice_connection_state_ == new_state) {
3044 return;
3045 }
3046
deadbeefcbecd352015-09-23 11:50:27 -07003047 // After transitioning to "closed", ignore any additional states from
Steve Antonba818672017-11-06 10:21:57 -08003048 // TransportController (such as "disconnected").
deadbeefab9b2d12015-10-14 11:33:11 -07003049 if (IsClosed()) {
deadbeefcbecd352015-09-23 11:50:27 -07003050 return;
3051 }
Steve Antonba818672017-11-06 10:21:57 -08003052
Mirko Bonadei675513b2017-11-09 11:09:25 +01003053 RTC_LOG(LS_INFO) << "Changing IceConnectionState " << ice_connection_state_
3054 << " => " << new_state;
Steve Antonba818672017-11-06 10:21:57 -08003055 RTC_DCHECK(ice_connection_state_ !=
3056 PeerConnectionInterface::kIceConnectionClosed);
3057
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003058 ice_connection_state_ = new_state;
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00003059 observer_->OnIceConnectionChange(ice_connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003060}
3061
3062void PeerConnection::OnIceGatheringChange(
3063 PeerConnectionInterface::IceGatheringState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07003064 RTC_DCHECK(signaling_thread()->IsCurrent());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003065 if (IsClosed()) {
3066 return;
3067 }
3068 ice_gathering_state_ = new_state;
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00003069 observer_->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003070}
3071
jbauch81bf7b02017-03-25 08:31:12 -07003072void PeerConnection::OnIceCandidate(
3073 std::unique_ptr<IceCandidateInterface> candidate) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07003074 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07003075 if (IsClosed()) {
3076 return;
3077 }
jbauch81bf7b02017-03-25 08:31:12 -07003078 observer_->OnIceCandidate(candidate.get());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003079}
3080
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003081void PeerConnection::OnIceCandidatesRemoved(
3082 const std::vector<cricket::Candidate>& candidates) {
3083 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07003084 if (IsClosed()) {
3085 return;
3086 }
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003087 observer_->OnIceCandidatesRemoved(candidates);
3088}
3089
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003090void PeerConnection::ChangeSignalingState(
3091 PeerConnectionInterface::SignalingState signaling_state) {
Steve Antonba818672017-11-06 10:21:57 -08003092 RTC_DCHECK(signaling_thread()->IsCurrent());
3093 if (signaling_state_ == signaling_state) {
3094 return;
3095 }
Mirko Bonadei675513b2017-11-09 11:09:25 +01003096 RTC_LOG(LS_INFO) << "Session: " << session_id() << " Old state: "
3097 << GetSignalingStateString(signaling_state_)
3098 << " New state: "
3099 << GetSignalingStateString(signaling_state);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003100 signaling_state_ = signaling_state;
3101 if (signaling_state == kClosed) {
3102 ice_connection_state_ = kIceConnectionClosed;
3103 observer_->OnIceConnectionChange(ice_connection_state_);
3104 if (ice_gathering_state_ != kIceGatheringComplete) {
3105 ice_gathering_state_ = kIceGatheringComplete;
3106 observer_->OnIceGatheringChange(ice_gathering_state_);
3107 }
3108 }
3109 observer_->OnSignalingChange(signaling_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003110}
3111
deadbeefeb459812015-12-15 19:24:43 -08003112void PeerConnection::OnAudioTrackAdded(AudioTrackInterface* track,
3113 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003114 if (IsClosed()) {
3115 return;
3116 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003117 AddAudioTrack(track, stream);
3118 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003119}
3120
deadbeefeb459812015-12-15 19:24:43 -08003121void PeerConnection::OnAudioTrackRemoved(AudioTrackInterface* track,
3122 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003123 if (IsClosed()) {
3124 return;
3125 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003126 RemoveAudioTrack(track, stream);
3127 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003128}
3129
3130void PeerConnection::OnVideoTrackAdded(VideoTrackInterface* track,
3131 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003132 if (IsClosed()) {
3133 return;
3134 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003135 AddVideoTrack(track, stream);
3136 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003137}
3138
3139void PeerConnection::OnVideoTrackRemoved(VideoTrackInterface* track,
3140 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003141 if (IsClosed()) {
3142 return;
3143 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003144 RemoveVideoTrack(track, stream);
3145 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003146}
3147
Henrik Boström31638672017-11-23 17:48:32 +01003148void PeerConnection::PostSetSessionDescriptionSuccess(
3149 SetSessionDescriptionObserver* observer) {
3150 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
3151 signaling_thread()->Post(RTC_FROM_HERE, this,
3152 MSG_SET_SESSIONDESCRIPTION_SUCCESS, msg);
3153}
3154
deadbeefab9b2d12015-10-14 11:33:11 -07003155void PeerConnection::PostSetSessionDescriptionFailure(
3156 SetSessionDescriptionObserver* observer,
3157 const std::string& error) {
3158 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
3159 msg->error = error;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07003160 signaling_thread()->Post(RTC_FROM_HERE, this,
3161 MSG_SET_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07003162}
3163
3164void PeerConnection::PostCreateSessionDescriptionFailure(
3165 CreateSessionDescriptionObserver* observer,
3166 const std::string& error) {
3167 CreateSessionDescriptionMsg* msg = new CreateSessionDescriptionMsg(observer);
3168 msg->error = error;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07003169 signaling_thread()->Post(RTC_FROM_HERE, this,
3170 MSG_CREATE_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07003171}
3172
zhihuang1c378ed2017-08-17 14:10:50 -07003173void PeerConnection::GetOptionsForOffer(
Steve Antondcc3c022017-12-22 16:02:54 -08003174 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
deadbeefab9b2d12015-10-14 11:33:11 -07003175 cricket::MediaSessionOptions* session_options) {
Steve Antondcc3c022017-12-22 16:02:54 -08003176 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
zhihuang1c378ed2017-08-17 14:10:50 -07003177
Steve Antondcc3c022017-12-22 16:02:54 -08003178 if (IsUnifiedPlan()) {
3179 GetOptionsForUnifiedPlanOffer(offer_answer_options, session_options);
3180 } else {
3181 GetOptionsForPlanBOffer(offer_answer_options, session_options);
3182 }
3183
Steve Antonfa2260d2017-12-28 16:38:23 -08003184 // Intentionally unset the data channel type for RTP data channel with the
3185 // second condition. Otherwise the RTP data channels would be successfully
3186 // negotiated by default and the unit tests in WebRtcDataBrowserTest will fail
3187 // when building with chromium. We want to leave RTP data channels broken, so
3188 // people won't try to use them.
3189 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
3190 session_options->data_channel_type = data_channel_type();
3191 }
3192
Steve Antondcc3c022017-12-22 16:02:54 -08003193 // Apply ICE restart flag and renomination flag.
3194 for (auto& options : session_options->media_description_options) {
3195 options.transport_options.ice_restart = offer_answer_options.ice_restart;
3196 options.transport_options.enable_ice_renomination =
3197 configuration_.enable_ice_renomination;
3198 }
3199
3200 session_options->rtcp_cname = rtcp_cname_;
3201 session_options->crypto_options = factory_->options().crypto_options;
3202}
3203
3204void PeerConnection::GetOptionsForPlanBOffer(
3205 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
3206 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07003207 // Figure out transceiver directional preferences.
3208 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
3209 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
3210
3211 // By default, generate sendrecv/recvonly m= sections.
3212 bool recv_audio = true;
3213 bool recv_video = true;
3214
3215 // By default, only offer a new m= section if we have media to send with it.
3216 bool offer_new_audio_description = send_audio;
3217 bool offer_new_video_description = send_video;
3218 bool offer_new_data_description = HasDataChannels();
3219
3220 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-22 16:02:54 -08003221 if (offer_answer_options.offer_to_receive_audio !=
3222 RTCOfferAnswerOptions::kUndefined) {
3223 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003224 offer_new_audio_description =
Steve Antondcc3c022017-12-22 16:02:54 -08003225 offer_new_audio_description ||
3226 (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003227 }
Steve Antondcc3c022017-12-22 16:02:54 -08003228 if (offer_answer_options.offer_to_receive_video !=
3229 RTCOfferAnswerOptions::kUndefined) {
3230 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003231 offer_new_video_description =
Steve Antondcc3c022017-12-22 16:02:54 -08003232 offer_new_video_description ||
3233 (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003234 }
3235
3236 rtc::Optional<size_t> audio_index;
3237 rtc::Optional<size_t> video_index;
3238 rtc::Optional<size_t> data_index;
3239 // If a current description exists, generate m= sections in the same order,
3240 // using the first audio/video/data section that appears and rejecting
3241 // extraneous ones.
Steve Anton75737c02017-11-06 10:37:17 -08003242 if (local_description()) {
zhihuang1c378ed2017-08-17 14:10:50 -07003243 GenerateMediaDescriptionOptions(
Steve Anton75737c02017-11-06 10:37:17 -08003244 local_description(),
Steve Anton1d03a752017-11-27 14:30:09 -08003245 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
3246 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
3247 &audio_index, &video_index, &data_index, session_options);
deadbeefab9b2d12015-10-14 11:33:11 -07003248 }
3249
zhihuang1c378ed2017-08-17 14:10:50 -07003250 // Add audio/video/data m= sections to the end if needed.
3251 if (!audio_index && offer_new_audio_description) {
3252 session_options->media_description_options.push_back(
3253 cricket::MediaDescriptionOptions(
3254 cricket::MEDIA_TYPE_AUDIO, cricket::CN_AUDIO,
Steve Anton1d03a752017-11-27 14:30:09 -08003255 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
3256 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003257 audio_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07003258 }
zhihuang1c378ed2017-08-17 14:10:50 -07003259 if (!video_index && offer_new_video_description) {
3260 session_options->media_description_options.push_back(
3261 cricket::MediaDescriptionOptions(
3262 cricket::MEDIA_TYPE_VIDEO, cricket::CN_VIDEO,
Steve Anton1d03a752017-11-27 14:30:09 -08003263 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
3264 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003265 video_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07003266 }
zhihuang1c378ed2017-08-17 14:10:50 -07003267 if (!data_index && offer_new_data_description) {
3268 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08003269 GetMediaDescriptionOptionsForActiveData(cricket::CN_DATA));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003270 data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07003271 }
3272
3273 cricket::MediaDescriptionOptions* audio_media_description_options =
3274 !audio_index ? nullptr
3275 : &session_options->media_description_options[*audio_index];
3276 cricket::MediaDescriptionOptions* video_media_description_options =
3277 !video_index ? nullptr
3278 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 14:10:50 -07003279
Steve Anton4171afb2017-11-20 10:20:22 -08003280 AddRtpSenderOptions(GetSendersInternal(), audio_media_description_options,
zhihuang1c378ed2017-08-17 14:10:50 -07003281 video_media_description_options);
Steve Antondcc3c022017-12-22 16:02:54 -08003282}
3283
3284// Find a new MID that is not already in |used_mids|, then add it to |used_mids|
3285// and return a reference to it.
3286// Generated MIDs should be no more than 3 bytes long to take up less space in
3287// the RTP packet.
3288static const std::string& AllocateMid(std::set<std::string>* used_mids) {
3289 RTC_DCHECK(used_mids);
3290 // We're boring: just generate MIDs 0, 1, 2, ...
3291 size_t i = 0;
3292 std::set<std::string>::iterator it;
3293 bool inserted;
3294 do {
3295 std::string mid = rtc::ToString(i++);
3296 auto insert_result = used_mids->insert(mid);
3297 it = insert_result.first;
3298 inserted = insert_result.second;
3299 } while (!inserted);
3300 return *it;
3301}
3302
3303static cricket::MediaDescriptionOptions
3304GetMediaDescriptionOptionsForTransceiver(
3305 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3306 transceiver,
3307 const std::string& mid) {
3308 cricket::MediaDescriptionOptions media_description_options(
3309 transceiver->internal()->media_type(), mid, transceiver->direction(),
3310 transceiver->stopped());
Steve Anton5f94aa22018-02-01 10:58:30 -08003311 // This behavior is specified in JSEP. The gist is that:
3312 // 1. The MSID is included if the RtpTransceiver's direction is sendonly or
3313 // sendrecv.
3314 // 2. If the MSID is included, then it must be included in any subsequent
3315 // offer/answer exactly the same until the RtpTransceiver is stopped.
3316 if (!transceiver->stopped() &&
3317 (RtpTransceiverDirectionHasSend(transceiver->direction()) ||
3318 transceiver->internal()->has_ever_been_used_to_send())) {
3319 cricket::SenderOptions sender_options;
3320 sender_options.track_id = transceiver->sender()->id();
3321 sender_options.stream_ids = transceiver->sender()->stream_ids();
3322 // TODO(bugs.webrtc.org/7600): Set num_sim_layers to the number of encodings
3323 // set in the RTP parameters when the transceiver was added.
3324 sender_options.num_sim_layers = 1;
3325 media_description_options.sender_options.push_back(sender_options);
3326 }
Steve Antondcc3c022017-12-22 16:02:54 -08003327 return media_description_options;
3328}
3329
3330void PeerConnection::GetOptionsForUnifiedPlanOffer(
3331 const RTCOfferAnswerOptions& offer_answer_options,
3332 cricket::MediaSessionOptions* session_options) {
3333 // Rules for generating an offer are dictated by JSEP sections 5.2.1 (Initial
3334 // Offers) and 5.2.2 (Subsequent Offers).
3335 RTC_DCHECK_EQ(session_options->media_description_options.size(), 0);
3336 const ContentInfos& local_contents =
3337 (local_description() ? local_description()->description()->contents()
3338 : ContentInfos());
3339 const ContentInfos& remote_contents =
3340 (remote_description() ? remote_description()->description()->contents()
3341 : ContentInfos());
3342 // The mline indices that can be recycled. New transceivers should reuse these
3343 // slots first.
3344 std::queue<size_t> recycleable_mline_indices;
3345 // Track the MIDs used in previous offer/answer exchanges and the current
3346 // offer so that new, unique MIDs are generated.
3347 std::set<std::string> used_mids = seen_mids_;
3348 // First, go through each media section that exists in either the local or
3349 // remote description and generate a media section in this offer for the
3350 // associated transceiver. If a media section can be recycled, generate a
3351 // default, rejected media section here that can be later overwritten.
3352 for (size_t i = 0;
3353 i < std::max(local_contents.size(), remote_contents.size()); ++i) {
3354 // Either |local_content| or |remote_content| is non-null.
3355 const ContentInfo* local_content =
3356 (i < local_contents.size() ? &local_contents[i] : nullptr);
3357 const ContentInfo* remote_content =
3358 (i < remote_contents.size() ? &remote_contents[i] : nullptr);
3359 bool had_been_rejected = (local_content && local_content->rejected) ||
3360 (remote_content && remote_content->rejected);
3361 const std::string& mid =
3362 (local_content ? local_content->name : remote_content->name);
3363 cricket::MediaType media_type =
3364 (local_content ? local_content->media_description()->type()
3365 : remote_content->media_description()->type());
3366 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
3367 media_type == cricket::MEDIA_TYPE_VIDEO) {
3368 auto transceiver = GetAssociatedTransceiver(mid);
3369 RTC_CHECK(transceiver);
3370 // A media section is considered eligible for recycling if it is marked as
3371 // rejected in either the local or remote description.
3372 if (had_been_rejected) {
3373 session_options->media_description_options.push_back(
3374 cricket::MediaDescriptionOptions(
3375 transceiver->internal()->media_type(), mid,
3376 RtpTransceiverDirection::kInactive,
3377 /*stopped=*/true));
3378 recycleable_mline_indices.push(i);
3379 } else {
3380 session_options->media_description_options.push_back(
3381 GetMediaDescriptionOptionsForTransceiver(transceiver, mid));
3382 // CreateOffer shouldn't really cause any state changes in
3383 // PeerConnection, but we need a way to match new transceivers to new
3384 // media sections in SetLocalDescription and JSEP specifies this is done
3385 // by recording the index of the media section generated for the
3386 // transceiver in the offer.
3387 transceiver->internal()->set_mline_index(i);
3388 }
3389 } else {
3390 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antonfa2260d2017-12-28 16:38:23 -08003391 RTC_CHECK(GetDataMid());
3392 if (had_been_rejected || mid != *GetDataMid()) {
3393 session_options->media_description_options.push_back(
3394 GetMediaDescriptionOptionsForRejectedData(mid));
3395 } else {
3396 session_options->media_description_options.push_back(
3397 GetMediaDescriptionOptionsForActiveData(mid));
3398 }
Steve Antondcc3c022017-12-22 16:02:54 -08003399 }
3400 }
3401 // Next, look for transceivers that are newly added (that is, are not stopped
3402 // and not associated). Reuse media sections marked as recyclable first,
3403 // otherwise append to the end of the offer. New media sections should be
3404 // added in the order they were added to the PeerConnection.
3405 for (auto transceiver : transceivers_) {
3406 if (transceiver->mid() || transceiver->stopped()) {
3407 continue;
3408 }
3409 size_t mline_index;
3410 if (!recycleable_mline_indices.empty()) {
3411 mline_index = recycleable_mline_indices.front();
3412 recycleable_mline_indices.pop();
3413 session_options->media_description_options[mline_index] =
3414 GetMediaDescriptionOptionsForTransceiver(transceiver,
3415 AllocateMid(&used_mids));
3416 } else {
3417 mline_index = session_options->media_description_options.size();
3418 session_options->media_description_options.push_back(
3419 GetMediaDescriptionOptionsForTransceiver(transceiver,
3420 AllocateMid(&used_mids)));
3421 }
3422 // See comment above for why CreateOffer changes the transceiver's state.
3423 transceiver->internal()->set_mline_index(mline_index);
3424 }
Steve Antonfa2260d2017-12-28 16:38:23 -08003425 // Lastly, add a m-section if we have local data channels and an m section
3426 // does not already exist.
3427 if (!GetDataMid() && HasDataChannels()) {
3428 session_options->media_description_options.push_back(
3429 GetMediaDescriptionOptionsForActiveData(AllocateMid(&used_mids)));
3430 }
Steve Antondcc3c022017-12-22 16:02:54 -08003431}
3432
3433void PeerConnection::GetOptionsForAnswer(
3434 const RTCOfferAnswerOptions& offer_answer_options,
3435 cricket::MediaSessionOptions* session_options) {
3436 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
3437
3438 if (IsUnifiedPlan()) {
3439 GetOptionsForUnifiedPlanAnswer(offer_answer_options, session_options);
3440 } else {
3441 GetOptionsForPlanBAnswer(offer_answer_options, session_options);
3442 }
3443
Steve Antonfa2260d2017-12-28 16:38:23 -08003444 // Intentionally unset the data channel type for RTP data channel. Otherwise
3445 // the RTP data channels would be successfully negotiated by default and the
3446 // unit tests in WebRtcDataBrowserTest will fail when building with chromium.
3447 // We want to leave RTP data channels broken, so people won't try to use them.
3448 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
3449 session_options->data_channel_type = data_channel_type();
3450 }
3451
Steve Antondcc3c022017-12-22 16:02:54 -08003452 // Apply ICE renomination flag.
3453 for (auto& options : session_options->media_description_options) {
3454 options.transport_options.enable_ice_renomination =
3455 configuration_.enable_ice_renomination;
3456 }
zhihuang8f65cdf2016-05-06 18:40:30 -07003457
3458 session_options->rtcp_cname = rtcp_cname_;
jbauchcb560652016-08-04 05:20:32 -07003459 session_options->crypto_options = factory_->options().crypto_options;
deadbeefab9b2d12015-10-14 11:33:11 -07003460}
3461
Steve Antondcc3c022017-12-22 16:02:54 -08003462void PeerConnection::GetOptionsForPlanBAnswer(
3463 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07003464 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07003465 // Figure out transceiver directional preferences.
3466 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
3467 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
3468
3469 // By default, generate sendrecv/recvonly m= sections. The direction is also
3470 // restricted by the direction in the offer.
3471 bool recv_audio = true;
3472 bool recv_video = true;
3473
3474 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-22 16:02:54 -08003475 if (offer_answer_options.offer_to_receive_audio !=
3476 RTCOfferAnswerOptions::kUndefined) {
3477 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
deadbeef0ed85b22016-02-23 17:24:52 -08003478 }
Steve Antondcc3c022017-12-22 16:02:54 -08003479 if (offer_answer_options.offer_to_receive_video !=
3480 RTCOfferAnswerOptions::kUndefined) {
3481 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003482 }
3483
3484 rtc::Optional<size_t> audio_index;
3485 rtc::Optional<size_t> video_index;
3486 rtc::Optional<size_t> data_index;
Taylor Brandstetter94d8cce2018-01-26 22:44:21 +00003487 if (remote_description()) {
3488 // The pending remote description should be an offer.
3489 RTC_DCHECK(remote_description()->GetType() == SdpType::kOffer);
3490 // Generate m= sections that match those in the offer.
3491 // Note that mediasession.cc will handle intersection our preferred
3492 // direction with the offered direction.
3493 GenerateMediaDescriptionOptions(
3494 remote_description(),
3495 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
3496 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
3497 &audio_index, &video_index, &data_index, session_options);
3498 }
zhihuang1c378ed2017-08-17 14:10:50 -07003499
3500 cricket::MediaDescriptionOptions* audio_media_description_options =
3501 !audio_index ? nullptr
3502 : &session_options->media_description_options[*audio_index];
3503 cricket::MediaDescriptionOptions* video_media_description_options =
3504 !video_index ? nullptr
3505 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 14:10:50 -07003506
Steve Anton4171afb2017-11-20 10:20:22 -08003507 AddRtpSenderOptions(GetSendersInternal(), audio_media_description_options,
zhihuang1c378ed2017-08-17 14:10:50 -07003508 video_media_description_options);
Steve Antondcc3c022017-12-22 16:02:54 -08003509}
zhihuangaf388472016-11-02 16:49:48 -07003510
Steve Antondcc3c022017-12-22 16:02:54 -08003511void PeerConnection::GetOptionsForUnifiedPlanAnswer(
3512 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
3513 cricket::MediaSessionOptions* session_options) {
3514 // Rules for generating an answer are dictated by JSEP sections 5.3.1 (Initial
3515 // Answers) and 5.3.2 (Subsequent Answers).
3516 RTC_DCHECK(remote_description());
3517 RTC_DCHECK(remote_description()->GetType() == SdpType::kOffer);
3518 for (const ContentInfo& content :
3519 remote_description()->description()->contents()) {
3520 cricket::MediaType media_type = content.media_description()->type();
3521 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
3522 media_type == cricket::MEDIA_TYPE_VIDEO) {
3523 auto transceiver = GetAssociatedTransceiver(content.name);
3524 RTC_CHECK(transceiver);
3525 session_options->media_description_options.push_back(
3526 GetMediaDescriptionOptionsForTransceiver(transceiver, content.name));
3527 } else {
3528 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antondbf9d032018-01-19 15:23:40 -08003529 // Reject all data sections if data channels are disabled.
3530 // Reject a data section if it has already been rejected.
3531 // Reject all data sections except for the first one.
3532 if (data_channel_type_ == cricket::DCT_NONE || content.rejected ||
3533 content.name != *GetDataMid()) {
Steve Antonfa2260d2017-12-28 16:38:23 -08003534 session_options->media_description_options.push_back(
3535 GetMediaDescriptionOptionsForRejectedData(content.name));
3536 } else {
3537 session_options->media_description_options.push_back(
3538 GetMediaDescriptionOptionsForActiveData(content.name));
3539 }
Steve Antondcc3c022017-12-22 16:02:54 -08003540 }
3541 }
htaa2a49d92016-03-04 02:51:39 -08003542}
3543
zhihuang1c378ed2017-08-17 14:10:50 -07003544void PeerConnection::GenerateMediaDescriptionOptions(
3545 const SessionDescriptionInterface* session_desc,
Steve Anton1d03a752017-11-27 14:30:09 -08003546 RtpTransceiverDirection audio_direction,
3547 RtpTransceiverDirection video_direction,
zhihuang1c378ed2017-08-17 14:10:50 -07003548 rtc::Optional<size_t>* audio_index,
3549 rtc::Optional<size_t>* video_index,
3550 rtc::Optional<size_t>* data_index,
htaa2a49d92016-03-04 02:51:39 -08003551 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07003552 for (const cricket::ContentInfo& content :
3553 session_desc->description()->contents()) {
3554 if (IsAudioContent(&content)) {
3555 // If we already have an audio m= section, reject this extra one.
3556 if (*audio_index) {
3557 session_options->media_description_options.push_back(
3558 cricket::MediaDescriptionOptions(
3559 cricket::MEDIA_TYPE_AUDIO, content.name,
Steve Anton1d03a752017-11-27 14:30:09 -08003560 RtpTransceiverDirection::kInactive, true));
zhihuang1c378ed2017-08-17 14:10:50 -07003561 } else {
3562 session_options->media_description_options.push_back(
3563 cricket::MediaDescriptionOptions(
3564 cricket::MEDIA_TYPE_AUDIO, content.name, audio_direction,
Steve Anton1d03a752017-11-27 14:30:09 -08003565 audio_direction == RtpTransceiverDirection::kInactive));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003566 *audio_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07003567 }
3568 } else if (IsVideoContent(&content)) {
3569 // If we already have an video m= section, reject this extra one.
3570 if (*video_index) {
3571 session_options->media_description_options.push_back(
3572 cricket::MediaDescriptionOptions(
3573 cricket::MEDIA_TYPE_VIDEO, content.name,
Steve Anton1d03a752017-11-27 14:30:09 -08003574 RtpTransceiverDirection::kInactive, true));
zhihuang1c378ed2017-08-17 14:10:50 -07003575 } else {
3576 session_options->media_description_options.push_back(
3577 cricket::MediaDescriptionOptions(
3578 cricket::MEDIA_TYPE_VIDEO, content.name, video_direction,
Steve Anton1d03a752017-11-27 14:30:09 -08003579 video_direction == RtpTransceiverDirection::kInactive));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003580 *video_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07003581 }
3582 } else {
3583 RTC_DCHECK(IsDataContent(&content));
3584 // If we already have an data m= section, reject this extra one.
3585 if (*data_index) {
3586 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08003587 GetMediaDescriptionOptionsForRejectedData(content.name));
zhihuang1c378ed2017-08-17 14:10:50 -07003588 } else {
3589 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08003590 GetMediaDescriptionOptionsForActiveData(content.name));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003591 *data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07003592 }
3593 }
htaa2a49d92016-03-04 02:51:39 -08003594 }
deadbeefab9b2d12015-10-14 11:33:11 -07003595}
3596
Steve Antonfa2260d2017-12-28 16:38:23 -08003597cricket::MediaDescriptionOptions
3598PeerConnection::GetMediaDescriptionOptionsForActiveData(
3599 const std::string& mid) const {
3600 // Direction for data sections is meaningless, but legacy endpoints might
3601 // expect sendrecv.
3602 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
3603 RtpTransceiverDirection::kSendRecv,
3604 /*stopped=*/false);
3605 AddRtpDataChannelOptions(rtp_data_channels_, &options);
3606 return options;
3607}
3608
3609cricket::MediaDescriptionOptions
3610PeerConnection::GetMediaDescriptionOptionsForRejectedData(
3611 const std::string& mid) const {
3612 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
3613 RtpTransceiverDirection::kInactive,
3614 /*stopped=*/true);
3615 AddRtpDataChannelOptions(rtp_data_channels_, &options);
3616 return options;
3617}
3618
3619rtc::Optional<std::string> PeerConnection::GetDataMid() const {
3620 switch (data_channel_type_) {
3621 case cricket::DCT_RTP:
3622 if (!rtp_data_channel_) {
3623 return rtc::nullopt;
3624 }
3625 return rtp_data_channel_->content_name();
3626 case cricket::DCT_SCTP:
3627 return sctp_content_name_;
3628 default:
3629 return rtc::nullopt;
3630 }
3631}
3632
Steve Anton4171afb2017-11-20 10:20:22 -08003633void PeerConnection::RemoveSenders(cricket::MediaType media_type) {
3634 UpdateLocalSenders(std::vector<cricket::StreamParams>(), media_type);
3635 UpdateRemoteSendersList(std::vector<cricket::StreamParams>(), false,
deadbeefbda7e0b2015-12-08 17:13:40 -08003636 media_type, nullptr);
deadbeeffaac4972015-11-12 15:33:07 -08003637}
3638
Steve Anton4171afb2017-11-20 10:20:22 -08003639void PeerConnection::UpdateRemoteSendersList(
deadbeefab9b2d12015-10-14 11:33:11 -07003640 const cricket::StreamParamsVec& streams,
Steve Anton4171afb2017-11-20 10:20:22 -08003641 bool default_sender_needed,
deadbeefab9b2d12015-10-14 11:33:11 -07003642 cricket::MediaType media_type,
3643 StreamCollection* new_streams) {
Steve Anton4171afb2017-11-20 10:20:22 -08003644 std::vector<RtpSenderInfo>* current_senders =
3645 GetRemoteSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07003646
Steve Anton4171afb2017-11-20 10:20:22 -08003647 // Find removed senders. I.e., senders where the sender id or ssrc don't match
deadbeeffac06552015-11-25 11:26:01 -08003648 // the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08003649 for (auto sender_it = current_senders->begin();
3650 sender_it != current_senders->end();
3651 /* incremented manually */) {
3652 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07003653 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08003654 cricket::GetStreamBySsrc(streams, info.first_ssrc);
3655 bool sender_exists = params && params->id == info.sender_id;
deadbeefbda7e0b2015-12-08 17:13:40 -08003656 // If this is a default track, and we still need it, don't remove it.
Steve Anton4171afb2017-11-20 10:20:22 -08003657 if ((info.stream_label == kDefaultStreamLabel && default_sender_needed) ||
3658 sender_exists) {
3659 ++sender_it;
deadbeefbda7e0b2015-12-08 17:13:40 -08003660 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08003661 OnRemoteSenderRemoved(info, media_type);
3662 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07003663 }
3664 }
3665
Steve Anton4171afb2017-11-20 10:20:22 -08003666 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07003667 for (const cricket::StreamParams& params : streams) {
3668 // The sync_label is the MediaStream label and the |stream.id| is the
Steve Anton4171afb2017-11-20 10:20:22 -08003669 // sender id.
deadbeefab9b2d12015-10-14 11:33:11 -07003670 const std::string& stream_label = params.sync_label;
Steve Anton4171afb2017-11-20 10:20:22 -08003671 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07003672 uint32_t ssrc = params.first_ssrc();
3673
3674 rtc::scoped_refptr<MediaStreamInterface> stream =
3675 remote_streams_->find(stream_label);
3676 if (!stream) {
3677 // This is a new MediaStream. Create a new remote MediaStream.
perkjd61bf802016-03-24 03:16:19 -07003678 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
3679 MediaStream::Create(stream_label));
deadbeefab9b2d12015-10-14 11:33:11 -07003680 remote_streams_->AddStream(stream);
3681 new_streams->AddStream(stream);
3682 }
3683
Steve Anton4171afb2017-11-20 10:20:22 -08003684 const RtpSenderInfo* sender_info =
3685 FindSenderInfo(*current_senders, stream_label, sender_id);
3686 if (!sender_info) {
3687 current_senders->push_back(RtpSenderInfo(stream_label, sender_id, ssrc));
3688 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07003689 }
3690 }
deadbeefbda7e0b2015-12-08 17:13:40 -08003691
Steve Anton4171afb2017-11-20 10:20:22 -08003692 // Add default sender if necessary.
3693 if (default_sender_needed) {
deadbeefbda7e0b2015-12-08 17:13:40 -08003694 rtc::scoped_refptr<MediaStreamInterface> default_stream =
3695 remote_streams_->find(kDefaultStreamLabel);
3696 if (!default_stream) {
3697 // Create the new default MediaStream.
perkjd61bf802016-03-24 03:16:19 -07003698 default_stream = MediaStreamProxy::Create(
3699 rtc::Thread::Current(), MediaStream::Create(kDefaultStreamLabel));
deadbeefbda7e0b2015-12-08 17:13:40 -08003700 remote_streams_->AddStream(default_stream);
3701 new_streams->AddStream(default_stream);
3702 }
Steve Anton4171afb2017-11-20 10:20:22 -08003703 std::string default_sender_id = (media_type == cricket::MEDIA_TYPE_AUDIO)
3704 ? kDefaultAudioSenderId
3705 : kDefaultVideoSenderId;
3706 const RtpSenderInfo* default_sender_info = FindSenderInfo(
3707 *current_senders, kDefaultStreamLabel, default_sender_id);
3708 if (!default_sender_info) {
3709 current_senders->push_back(
3710 RtpSenderInfo(kDefaultStreamLabel, default_sender_id, 0));
3711 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefbda7e0b2015-12-08 17:13:40 -08003712 }
3713 }
deadbeefab9b2d12015-10-14 11:33:11 -07003714}
3715
Steve Anton4171afb2017-11-20 10:20:22 -08003716void PeerConnection::OnRemoteSenderAdded(const RtpSenderInfo& sender_info,
3717 cricket::MediaType media_type) {
3718 MediaStreamInterface* stream =
3719 remote_streams_->find(sender_info.stream_label);
deadbeefab9b2d12015-10-14 11:33:11 -07003720
3721 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 10:20:22 -08003722 CreateAudioReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07003723 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 10:20:22 -08003724 CreateVideoReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07003725 } else {
nisseeb4ca4e2017-01-12 02:24:27 -08003726 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07003727 }
3728}
3729
Steve Anton4171afb2017-11-20 10:20:22 -08003730void PeerConnection::OnRemoteSenderRemoved(const RtpSenderInfo& sender_info,
3731 cricket::MediaType media_type) {
3732 MediaStreamInterface* stream =
3733 remote_streams_->find(sender_info.stream_label);
deadbeefab9b2d12015-10-14 11:33:11 -07003734
Henrik Boström933d8b02017-10-10 10:05:16 -07003735 rtc::scoped_refptr<RtpReceiverInterface> receiver;
deadbeefab9b2d12015-10-14 11:33:11 -07003736 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
perkjd61bf802016-03-24 03:16:19 -07003737 // When the MediaEngine audio channel is destroyed, the RemoteAudioSource
3738 // will be notified which will end the AudioRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08003739 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07003740 rtc::scoped_refptr<AudioTrackInterface> audio_track =
Steve Anton4171afb2017-11-20 10:20:22 -08003741 stream->FindAudioTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07003742 if (audio_track) {
deadbeefab9b2d12015-10-14 11:33:11 -07003743 stream->RemoveTrack(audio_track);
deadbeefab9b2d12015-10-14 11:33:11 -07003744 }
3745 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
perkjd61bf802016-03-24 03:16:19 -07003746 // Stopping or destroying a VideoRtpReceiver will end the
3747 // VideoRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08003748 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07003749 rtc::scoped_refptr<VideoTrackInterface> video_track =
Steve Anton4171afb2017-11-20 10:20:22 -08003750 stream->FindVideoTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07003751 if (video_track) {
perkjd61bf802016-03-24 03:16:19 -07003752 // There's no guarantee the track is still available, e.g. the track may
3753 // have been removed from the stream by an application.
deadbeefab9b2d12015-10-14 11:33:11 -07003754 stream->RemoveTrack(video_track);
deadbeefab9b2d12015-10-14 11:33:11 -07003755 }
3756 } else {
nisseede5da42017-01-12 05:15:36 -08003757 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07003758 }
Henrik Boström933d8b02017-10-10 10:05:16 -07003759 if (receiver) {
3760 observer_->OnRemoveTrack(receiver);
3761 }
deadbeefab9b2d12015-10-14 11:33:11 -07003762}
3763
3764void PeerConnection::UpdateEndedRemoteMediaStreams() {
3765 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams_to_remove;
3766 for (size_t i = 0; i < remote_streams_->count(); ++i) {
3767 MediaStreamInterface* stream = remote_streams_->at(i);
3768 if (stream->GetAudioTracks().empty() && stream->GetVideoTracks().empty()) {
3769 streams_to_remove.push_back(stream);
3770 }
3771 }
3772
Taylor Brandstetter98cde262016-05-31 13:02:21 -07003773 for (auto& stream : streams_to_remove) {
deadbeefab9b2d12015-10-14 11:33:11 -07003774 remote_streams_->RemoveStream(stream);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07003775 observer_->OnRemoveStream(std::move(stream));
deadbeefab9b2d12015-10-14 11:33:11 -07003776 }
3777}
3778
Steve Anton4171afb2017-11-20 10:20:22 -08003779void PeerConnection::UpdateLocalSenders(
deadbeefab9b2d12015-10-14 11:33:11 -07003780 const std::vector<cricket::StreamParams>& streams,
3781 cricket::MediaType media_type) {
Steve Anton4171afb2017-11-20 10:20:22 -08003782 std::vector<RtpSenderInfo>* current_senders = GetLocalSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07003783
3784 // Find removed tracks. I.e., tracks where the track id, stream label or ssrc
3785 // don't match the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08003786 for (auto sender_it = current_senders->begin();
3787 sender_it != current_senders->end();
3788 /* incremented manually */) {
3789 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07003790 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08003791 cricket::GetStreamBySsrc(streams, info.first_ssrc);
3792 if (!params || params->id != info.sender_id ||
deadbeefab9b2d12015-10-14 11:33:11 -07003793 params->sync_label != info.stream_label) {
Steve Anton4171afb2017-11-20 10:20:22 -08003794 OnLocalSenderRemoved(info, media_type);
3795 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07003796 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08003797 ++sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07003798 }
3799 }
3800
Steve Anton4171afb2017-11-20 10:20:22 -08003801 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07003802 for (const cricket::StreamParams& params : streams) {
3803 // The sync_label is the MediaStream label and the |stream.id| is the
Steve Anton4171afb2017-11-20 10:20:22 -08003804 // sender id.
deadbeefab9b2d12015-10-14 11:33:11 -07003805 const std::string& stream_label = params.sync_label;
Steve Anton4171afb2017-11-20 10:20:22 -08003806 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07003807 uint32_t ssrc = params.first_ssrc();
Steve Anton4171afb2017-11-20 10:20:22 -08003808 const RtpSenderInfo* sender_info =
3809 FindSenderInfo(*current_senders, stream_label, sender_id);
3810 if (!sender_info) {
3811 current_senders->push_back(RtpSenderInfo(stream_label, sender_id, ssrc));
3812 OnLocalSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07003813 }
3814 }
3815}
3816
Steve Anton4171afb2017-11-20 10:20:22 -08003817void PeerConnection::OnLocalSenderAdded(const RtpSenderInfo& sender_info,
3818 cricket::MediaType media_type) {
3819 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08003820 if (!sender) {
Steve Anton4171afb2017-11-20 10:20:22 -08003821 RTC_LOG(LS_WARNING) << "An unknown RtpSender with id "
3822 << sender_info.sender_id
Mirko Bonadei675513b2017-11-09 11:09:25 +01003823 << " has been configured in the local description.";
deadbeefab9b2d12015-10-14 11:33:11 -07003824 return;
3825 }
3826
deadbeeffac06552015-11-25 11:26:01 -08003827 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003828 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
3829 << " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08003830 return;
deadbeefab9b2d12015-10-14 11:33:11 -07003831 }
deadbeeffac06552015-11-25 11:26:01 -08003832
Steve Anton4171afb2017-11-20 10:20:22 -08003833 sender->internal()->set_stream_id(sender_info.stream_label);
3834 sender->internal()->SetSsrc(sender_info.first_ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07003835}
3836
Steve Anton4171afb2017-11-20 10:20:22 -08003837void PeerConnection::OnLocalSenderRemoved(const RtpSenderInfo& sender_info,
3838 cricket::MediaType media_type) {
3839 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08003840 if (!sender) {
3841 // This is the normal case. I.e., RemoveStream has been called and the
deadbeefab9b2d12015-10-14 11:33:11 -07003842 // SessionDescriptions has been renegotiated.
3843 return;
3844 }
deadbeeffac06552015-11-25 11:26:01 -08003845
3846 // A sender has been removed from the SessionDescription but it's still
3847 // associated with the PeerConnection. This only occurs if the SDP doesn't
3848 // match with the calls to CreateSender, AddStream and RemoveStream.
3849 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003850 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
3851 << " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08003852 return;
deadbeefab9b2d12015-10-14 11:33:11 -07003853 }
deadbeeffac06552015-11-25 11:26:01 -08003854
Steve Anton4171afb2017-11-20 10:20:22 -08003855 sender->internal()->SetSsrc(0);
deadbeefab9b2d12015-10-14 11:33:11 -07003856}
3857
3858void PeerConnection::UpdateLocalRtpDataChannels(
3859 const cricket::StreamParamsVec& streams) {
3860 std::vector<std::string> existing_channels;
3861
3862 // Find new and active data channels.
3863 for (const cricket::StreamParams& params : streams) {
3864 // |it->sync_label| is actually the data channel label. The reason is that
3865 // we use the same naming of data channels as we do for
3866 // MediaStreams and Tracks.
3867 // For MediaStreams, the sync_label is the MediaStream label and the
3868 // track label is the same as |streamid|.
3869 const std::string& channel_label = params.sync_label;
3870 auto data_channel_it = rtp_data_channels_.find(channel_label);
nisse7ce109a2017-01-31 00:57:56 -08003871 if (data_channel_it == rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003872 RTC_LOG(LS_ERROR) << "channel label not found";
deadbeefab9b2d12015-10-14 11:33:11 -07003873 continue;
3874 }
3875 // Set the SSRC the data channel should use for sending.
3876 data_channel_it->second->SetSendSsrc(params.first_ssrc());
3877 existing_channels.push_back(data_channel_it->first);
3878 }
3879
3880 UpdateClosingRtpDataChannels(existing_channels, true);
3881}
3882
3883void PeerConnection::UpdateRemoteRtpDataChannels(
3884 const cricket::StreamParamsVec& streams) {
3885 std::vector<std::string> existing_channels;
3886
3887 // Find new and active data channels.
3888 for (const cricket::StreamParams& params : streams) {
3889 // The data channel label is either the mslabel or the SSRC if the mslabel
3890 // does not exist. Ex a=ssrc:444330170 mslabel:test1.
3891 std::string label = params.sync_label.empty()
3892 ? rtc::ToString(params.first_ssrc())
3893 : params.sync_label;
3894 auto data_channel_it = rtp_data_channels_.find(label);
3895 if (data_channel_it == rtp_data_channels_.end()) {
3896 // This is a new data channel.
3897 CreateRemoteRtpDataChannel(label, params.first_ssrc());
3898 } else {
3899 data_channel_it->second->SetReceiveSsrc(params.first_ssrc());
3900 }
3901 existing_channels.push_back(label);
3902 }
3903
3904 UpdateClosingRtpDataChannels(existing_channels, false);
3905}
3906
3907void PeerConnection::UpdateClosingRtpDataChannels(
3908 const std::vector<std::string>& active_channels,
3909 bool is_local_update) {
3910 auto it = rtp_data_channels_.begin();
3911 while (it != rtp_data_channels_.end()) {
3912 DataChannel* data_channel = it->second;
3913 if (std::find(active_channels.begin(), active_channels.end(),
3914 data_channel->label()) != active_channels.end()) {
3915 ++it;
3916 continue;
3917 }
3918
3919 if (is_local_update) {
3920 data_channel->SetSendSsrc(0);
3921 } else {
3922 data_channel->RemotePeerRequestClose();
3923 }
3924
3925 if (data_channel->state() == DataChannel::kClosed) {
3926 rtp_data_channels_.erase(it);
3927 it = rtp_data_channels_.begin();
3928 } else {
3929 ++it;
3930 }
3931 }
3932}
3933
3934void PeerConnection::CreateRemoteRtpDataChannel(const std::string& label,
3935 uint32_t remote_ssrc) {
3936 rtc::scoped_refptr<DataChannel> channel(
3937 InternalCreateDataChannel(label, nullptr));
3938 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003939 RTC_LOG(LS_WARNING) << "Remote peer requested a DataChannel but"
3940 << "CreateDataChannel failed.";
deadbeefab9b2d12015-10-14 11:33:11 -07003941 return;
3942 }
3943 channel->SetReceiveSsrc(remote_ssrc);
deadbeefa601f5c2016-06-06 14:27:39 -07003944 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
3945 DataChannelProxy::Create(signaling_thread(), channel);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07003946 observer_->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07003947}
3948
3949rtc::scoped_refptr<DataChannel> PeerConnection::InternalCreateDataChannel(
3950 const std::string& label,
3951 const InternalDataChannelInit* config) {
3952 if (IsClosed()) {
3953 return nullptr;
3954 }
Steve Anton75737c02017-11-06 10:37:17 -08003955 if (data_channel_type() == cricket::DCT_NONE) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003956 RTC_LOG(LS_ERROR)
deadbeefab9b2d12015-10-14 11:33:11 -07003957 << "InternalCreateDataChannel: Data is not supported in this call.";
3958 return nullptr;
3959 }
3960 InternalDataChannelInit new_config =
3961 config ? (*config) : InternalDataChannelInit();
Steve Anton75737c02017-11-06 10:37:17 -08003962 if (data_channel_type() == cricket::DCT_SCTP) {
deadbeefab9b2d12015-10-14 11:33:11 -07003963 if (new_config.id < 0) {
3964 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08003965 if ((GetSctpSslRole(&role)) &&
deadbeefab9b2d12015-10-14 11:33:11 -07003966 !sid_allocator_.AllocateSid(role, &new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003967 RTC_LOG(LS_ERROR)
3968 << "No id can be allocated for the SCTP data channel.";
deadbeefab9b2d12015-10-14 11:33:11 -07003969 return nullptr;
3970 }
3971 } else if (!sid_allocator_.ReserveSid(new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003972 RTC_LOG(LS_ERROR) << "Failed to create a SCTP data channel "
3973 << "because the id is already in use or out of range.";
deadbeefab9b2d12015-10-14 11:33:11 -07003974 return nullptr;
3975 }
3976 }
3977
Steve Anton75737c02017-11-06 10:37:17 -08003978 rtc::scoped_refptr<DataChannel> channel(
3979 DataChannel::Create(this, data_channel_type(), label, new_config));
deadbeefab9b2d12015-10-14 11:33:11 -07003980 if (!channel) {
3981 sid_allocator_.ReleaseSid(new_config.id);
3982 return nullptr;
3983 }
3984
3985 if (channel->data_channel_type() == cricket::DCT_RTP) {
3986 if (rtp_data_channels_.find(channel->label()) != rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003987 RTC_LOG(LS_ERROR) << "DataChannel with label " << channel->label()
3988 << " already exists.";
deadbeefab9b2d12015-10-14 11:33:11 -07003989 return nullptr;
3990 }
3991 rtp_data_channels_[channel->label()] = channel;
3992 } else {
3993 RTC_DCHECK(channel->data_channel_type() == cricket::DCT_SCTP);
3994 sctp_data_channels_.push_back(channel);
3995 channel->SignalClosed.connect(this,
3996 &PeerConnection::OnSctpDataChannelClosed);
3997 }
3998
Steve Anton2d8609c2018-01-23 16:38:46 -08003999 SignalDataChannelCreated_(channel.get());
deadbeefab9b2d12015-10-14 11:33:11 -07004000 return channel;
4001}
4002
4003bool PeerConnection::HasDataChannels() const {
4004 return !rtp_data_channels_.empty() || !sctp_data_channels_.empty();
4005}
4006
4007void PeerConnection::AllocateSctpSids(rtc::SSLRole role) {
4008 for (const auto& channel : sctp_data_channels_) {
4009 if (channel->id() < 0) {
4010 int sid;
4011 if (!sid_allocator_.AllocateSid(role, &sid)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004012 RTC_LOG(LS_ERROR) << "Failed to allocate SCTP sid.";
deadbeefab9b2d12015-10-14 11:33:11 -07004013 continue;
4014 }
4015 channel->SetSctpSid(sid);
4016 }
4017 }
4018}
4019
4020void PeerConnection::OnSctpDataChannelClosed(DataChannel* channel) {
deadbeefbd292462015-12-14 18:15:29 -08004021 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeefab9b2d12015-10-14 11:33:11 -07004022 for (auto it = sctp_data_channels_.begin(); it != sctp_data_channels_.end();
4023 ++it) {
4024 if (it->get() == channel) {
4025 if (channel->id() >= 0) {
4026 sid_allocator_.ReleaseSid(channel->id());
4027 }
deadbeefbd292462015-12-14 18:15:29 -08004028 // Since this method is triggered by a signal from the DataChannel,
4029 // we can't free it directly here; we need to free it asynchronously.
4030 sctp_data_channels_to_free_.push_back(*it);
deadbeefab9b2d12015-10-14 11:33:11 -07004031 sctp_data_channels_.erase(it);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07004032 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_FREE_DATACHANNELS,
4033 nullptr);
deadbeefab9b2d12015-10-14 11:33:11 -07004034 return;
4035 }
4036 }
4037}
4038
deadbeefab9b2d12015-10-14 11:33:11 -07004039void PeerConnection::OnDataChannelDestroyed() {
4040 // Use a temporary copy of the RTP/SCTP DataChannel list because the
4041 // DataChannel may callback to us and try to modify the list.
4042 std::map<std::string, rtc::scoped_refptr<DataChannel>> temp_rtp_dcs;
4043 temp_rtp_dcs.swap(rtp_data_channels_);
4044 for (const auto& kv : temp_rtp_dcs) {
4045 kv.second->OnTransportChannelDestroyed();
4046 }
4047
4048 std::vector<rtc::scoped_refptr<DataChannel>> temp_sctp_dcs;
4049 temp_sctp_dcs.swap(sctp_data_channels_);
4050 for (const auto& channel : temp_sctp_dcs) {
4051 channel->OnTransportChannelDestroyed();
4052 }
4053}
4054
4055void PeerConnection::OnDataChannelOpenMessage(
4056 const std::string& label,
4057 const InternalDataChannelInit& config) {
4058 rtc::scoped_refptr<DataChannel> channel(
4059 InternalCreateDataChannel(label, &config));
4060 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004061 RTC_LOG(LS_ERROR) << "Failed to create DataChannel from the OPEN message.";
deadbeefab9b2d12015-10-14 11:33:11 -07004062 return;
4063 }
4064
deadbeefa601f5c2016-06-06 14:27:39 -07004065 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
4066 DataChannelProxy::Create(signaling_thread(), channel);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07004067 observer_->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07004068}
4069
Steve Anton4171afb2017-11-20 10:20:22 -08004070rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
4071PeerConnection::GetAudioTransceiver() const {
4072 // This method only works with Plan B SDP, where there is a single
4073 // audio/video transceiver.
4074 RTC_DCHECK(!IsUnifiedPlan());
4075 for (auto transceiver : transceivers_) {
4076 if (transceiver->internal()->media_type() == cricket::MEDIA_TYPE_AUDIO) {
4077 return transceiver;
4078 }
4079 }
4080 RTC_NOTREACHED();
4081 return nullptr;
4082}
4083
4084rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
4085PeerConnection::GetVideoTransceiver() const {
4086 // This method only works with Plan B SDP, where there is a single
4087 // audio/video transceiver.
4088 RTC_DCHECK(!IsUnifiedPlan());
4089 for (auto transceiver : transceivers_) {
4090 if (transceiver->internal()->media_type() == cricket::MEDIA_TYPE_VIDEO) {
4091 return transceiver;
4092 }
4093 }
4094 RTC_NOTREACHED();
4095 return nullptr;
4096}
4097
4098// TODO(bugs.webrtc.org/7600): Remove this when multiple transceivers with
4099// individual transceiver directions are supported.
zhihuang1c378ed2017-08-17 14:10:50 -07004100bool PeerConnection::HasRtpSender(cricket::MediaType type) const {
Steve Anton4171afb2017-11-20 10:20:22 -08004101 switch (type) {
4102 case cricket::MEDIA_TYPE_AUDIO:
4103 return !GetAudioTransceiver()->internal()->senders().empty();
4104 case cricket::MEDIA_TYPE_VIDEO:
4105 return !GetVideoTransceiver()->internal()->senders().empty();
4106 case cricket::MEDIA_TYPE_DATA:
4107 return false;
4108 }
4109 RTC_NOTREACHED();
4110 return false;
zhihuang1c378ed2017-08-17 14:10:50 -07004111}
4112
Steve Anton4171afb2017-11-20 10:20:22 -08004113rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
4114PeerConnection::FindSenderForTrack(MediaStreamTrackInterface* track) const {
4115 for (auto transceiver : transceivers_) {
4116 for (auto sender : transceiver->internal()->senders()) {
4117 if (sender->track() == track) {
4118 return sender;
4119 }
4120 }
4121 }
4122 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08004123}
4124
Steve Anton4171afb2017-11-20 10:20:22 -08004125rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
4126PeerConnection::FindSenderById(const std::string& sender_id) const {
4127 for (auto transceiver : transceivers_) {
4128 for (auto sender : transceiver->internal()->senders()) {
4129 if (sender->id() == sender_id) {
4130 return sender;
4131 }
4132 }
4133 }
4134 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07004135}
4136
Steve Anton4171afb2017-11-20 10:20:22 -08004137rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
4138PeerConnection::FindReceiverById(const std::string& receiver_id) const {
4139 for (auto transceiver : transceivers_) {
4140 for (auto receiver : transceiver->internal()->receivers()) {
4141 if (receiver->id() == receiver_id) {
4142 return receiver;
4143 }
4144 }
4145 }
4146 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07004147}
4148
Steve Anton4171afb2017-11-20 10:20:22 -08004149std::vector<PeerConnection::RtpSenderInfo>*
4150PeerConnection::GetRemoteSenderInfos(cricket::MediaType media_type) {
4151 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
4152 media_type == cricket::MEDIA_TYPE_VIDEO);
4153 return (media_type == cricket::MEDIA_TYPE_AUDIO)
4154 ? &remote_audio_sender_infos_
4155 : &remote_video_sender_infos_;
4156}
4157
4158std::vector<PeerConnection::RtpSenderInfo>* PeerConnection::GetLocalSenderInfos(
deadbeefab9b2d12015-10-14 11:33:11 -07004159 cricket::MediaType media_type) {
4160 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
4161 media_type == cricket::MEDIA_TYPE_VIDEO);
Steve Anton4171afb2017-11-20 10:20:22 -08004162 return (media_type == cricket::MEDIA_TYPE_AUDIO) ? &local_audio_sender_infos_
4163 : &local_video_sender_infos_;
deadbeefab9b2d12015-10-14 11:33:11 -07004164}
4165
Steve Anton4171afb2017-11-20 10:20:22 -08004166const PeerConnection::RtpSenderInfo* PeerConnection::FindSenderInfo(
4167 const std::vector<PeerConnection::RtpSenderInfo>& infos,
deadbeefab9b2d12015-10-14 11:33:11 -07004168 const std::string& stream_label,
Steve Anton4171afb2017-11-20 10:20:22 -08004169 const std::string sender_id) const {
4170 for (const RtpSenderInfo& sender_info : infos) {
4171 if (sender_info.stream_label == stream_label &&
4172 sender_info.sender_id == sender_id) {
4173 return &sender_info;
deadbeefab9b2d12015-10-14 11:33:11 -07004174 }
4175 }
4176 return nullptr;
4177}
4178
4179DataChannel* PeerConnection::FindDataChannelBySid(int sid) const {
4180 for (const auto& channel : sctp_data_channels_) {
4181 if (channel->id() == sid) {
4182 return channel;
4183 }
4184 }
4185 return nullptr;
4186}
4187
deadbeef91dd5672016-05-18 16:55:30 -07004188bool PeerConnection::InitializePortAllocator_n(
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004189 const RTCConfiguration& configuration) {
4190 cricket::ServerAddresses stun_servers;
4191 std::vector<cricket::RelayServerConfig> turn_servers;
deadbeef293e9262017-01-11 12:28:30 -08004192 if (ParseIceServers(configuration.servers, &stun_servers, &turn_servers) !=
4193 RTCErrorType::NONE) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004194 return false;
4195 }
4196
Taylor Brandstetterf8e65772016-06-27 17:20:15 -07004197 port_allocator_->Initialize();
4198
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004199 // To handle both internal and externally created port allocator, we will
4200 // enable BUNDLE here.
4201 int portallocator_flags = port_allocator_->flags();
4202 portallocator_flags |= cricket::PORTALLOCATOR_ENABLE_SHARED_SOCKET |
zhihuangb09b3f92017-03-07 14:40:51 -08004203 cricket::PORTALLOCATOR_ENABLE_IPV6 |
4204 cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI;
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004205 // If the disable-IPv6 flag was specified, we'll not override it
4206 // by experiment.
4207 if (configuration.disable_ipv6) {
4208 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
sprangc1b57a12017-02-28 08:50:47 -08004209 } else if (webrtc::field_trial::FindFullName("WebRTC-IPv6Default")
4210 .find("Disabled") == 0) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004211 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
4212 }
4213
zhihuangb09b3f92017-03-07 14:40:51 -08004214 if (configuration.disable_ipv6_on_wifi) {
4215 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI);
Mirko Bonadei675513b2017-11-09 11:09:25 +01004216 RTC_LOG(LS_INFO) << "IPv6 candidates on Wi-Fi are disabled.";
zhihuangb09b3f92017-03-07 14:40:51 -08004217 }
4218
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004219 if (configuration.tcp_candidate_policy == kTcpCandidatePolicyDisabled) {
4220 portallocator_flags |= cricket::PORTALLOCATOR_DISABLE_TCP;
Mirko Bonadei675513b2017-11-09 11:09:25 +01004221 RTC_LOG(LS_INFO) << "TCP candidates are disabled.";
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004222 }
4223
honghaiz60347052016-05-31 18:29:12 -07004224 if (configuration.candidate_network_policy ==
4225 kCandidateNetworkPolicyLowCost) {
4226 portallocator_flags |= cricket::PORTALLOCATOR_DISABLE_COSTLY_NETWORKS;
Mirko Bonadei675513b2017-11-09 11:09:25 +01004227 RTC_LOG(LS_INFO) << "Do not gather candidates on high-cost networks";
honghaiz60347052016-05-31 18:29:12 -07004228 }
4229
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004230 port_allocator_->set_flags(portallocator_flags);
4231 // No step delay is used while allocating ports.
4232 port_allocator_->set_step_delay(cricket::kMinimumStepDelay);
4233 port_allocator_->set_candidate_filter(
4234 ConvertIceTransportTypeToCandidateFilter(configuration.type));
deadbeefd21eab32017-07-26 16:50:11 -07004235 port_allocator_->set_max_ipv6_networks(configuration.max_ipv6_networks);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004236
4237 // Call this last since it may create pooled allocator sessions using the
4238 // properties set above.
4239 port_allocator_->SetConfiguration(stun_servers, turn_servers,
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -07004240 configuration.ice_candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02004241 configuration.prune_turn_ports,
4242 configuration.turn_customizer);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004243 return true;
4244}
4245
deadbeef91dd5672016-05-18 16:55:30 -07004246bool PeerConnection::ReconfigurePortAllocator_n(
deadbeef293e9262017-01-11 12:28:30 -08004247 const cricket::ServerAddresses& stun_servers,
4248 const std::vector<cricket::RelayServerConfig>& turn_servers,
4249 IceTransportsType type,
4250 int candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02004251 bool prune_turn_ports,
4252 webrtc::TurnCustomizer* turn_customizer) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004253 port_allocator_->set_candidate_filter(
deadbeef293e9262017-01-11 12:28:30 -08004254 ConvertIceTransportTypeToCandidateFilter(type));
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004255 // Call this last since it may create pooled allocator sessions using the
4256 // candidate filter set above.
deadbeef6de92f92016-12-12 18:49:32 -08004257 return port_allocator_->SetConfiguration(
Jonas Orelandbdcee282017-10-10 14:01:40 +02004258 stun_servers, turn_servers, candidate_pool_size, prune_turn_ports,
4259 turn_customizer);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004260}
4261
Steve Antonba818672017-11-06 10:21:57 -08004262cricket::ChannelManager* PeerConnection::channel_manager() const {
4263 return factory_->channel_manager();
4264}
4265
4266MetricsObserverInterface* PeerConnection::metrics_observer() const {
4267 return uma_observer_;
4268}
4269
Elad Alon99c3fe52017-10-13 16:29:40 +02004270bool PeerConnection::StartRtcEventLog_w(
Bjorn Tereliusde939432017-11-20 17:38:14 +01004271 std::unique_ptr<RtcEventLogOutput> output,
4272 int64_t output_period_ms) {
zhihuang77985012017-02-07 15:45:16 -08004273 if (!event_log_) {
4274 return false;
4275 }
Bjorn Tereliusde939432017-11-20 17:38:14 +01004276 return event_log_->StartLogging(std::move(output), output_period_ms);
ivoc14d5dbe2016-07-04 07:06:55 -07004277}
4278
4279void PeerConnection::StopRtcEventLog_w() {
zhihuang77985012017-02-07 15:45:16 -08004280 if (event_log_) {
4281 event_log_->StopLogging();
4282 }
ivoc14d5dbe2016-07-04 07:06:55 -07004283}
nisseeaabdf62017-05-05 02:23:02 -07004284
Steve Anton75737c02017-11-06 10:37:17 -08004285cricket::BaseChannel* PeerConnection::GetChannel(
4286 const std::string& content_name) {
Steve Antondcc3c022017-12-22 16:02:54 -08004287 for (auto transceiver : transceivers_) {
4288 cricket::BaseChannel* channel = transceiver->internal()->channel();
4289 if (channel && channel->content_name() == content_name) {
4290 return channel;
4291 }
Steve Anton75737c02017-11-06 10:37:17 -08004292 }
4293 if (rtp_data_channel() &&
4294 rtp_data_channel()->content_name() == content_name) {
4295 return rtp_data_channel();
4296 }
4297 return nullptr;
4298}
4299
4300bool PeerConnection::GetSctpSslRole(rtc::SSLRole* role) {
4301 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004302 RTC_LOG(LS_INFO)
4303 << "Local and Remote descriptions must be applied to get the "
4304 << "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08004305 return false;
4306 }
4307 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004308 RTC_LOG(LS_INFO) << "Non-rejected SCTP m= section is needed to get the "
4309 << "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08004310 return false;
4311 }
4312
4313 return transport_controller_->GetSslRole(*sctp_transport_name_, role);
4314}
4315
4316bool PeerConnection::GetSslRole(const std::string& content_name,
4317 rtc::SSLRole* role) {
4318 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004319 RTC_LOG(LS_INFO)
4320 << "Local and Remote descriptions must be applied to get the "
4321 << "SSL Role of the session.";
Steve Anton75737c02017-11-06 10:37:17 -08004322 return false;
4323 }
4324
4325 return transport_controller_->GetSslRole(GetTransportName(content_name),
4326 role);
4327}
4328
Steve Anton75737c02017-11-06 10:37:17 -08004329// TODO(steveanton): Eventually it'd be nice to store the channels as a single
4330// vector of BaseChannel pointers instead of separate voice and video channel
4331// vectors. At that point, this will become a simple getter.
4332std::vector<cricket::BaseChannel*> PeerConnection::Channels() const {
4333 std::vector<cricket::BaseChannel*> channels;
Steve Anton4171afb2017-11-20 10:20:22 -08004334 if (voice_channel()) {
4335 channels.push_back(voice_channel());
4336 }
4337 if (video_channel()) {
4338 channels.push_back(video_channel());
4339 }
Steve Anton75737c02017-11-06 10:37:17 -08004340 if (rtp_data_channel_) {
4341 channels.push_back(rtp_data_channel_);
4342 }
4343 return channels;
4344}
4345
Steve Antonf8470812017-12-04 10:46:21 -08004346void PeerConnection::SetSessionError(SessionError error,
4347 const std::string& error_desc) {
4348 RTC_DCHECK_RUN_ON(signaling_thread());
4349 if (error != session_error_) {
4350 session_error_ = error;
4351 session_error_desc_ = error_desc;
Steve Anton75737c02017-11-06 10:37:17 -08004352 }
4353}
4354
Steve Anton3828c062017-12-06 10:34:51 -08004355RTCError PeerConnection::UpdateSessionState(SdpType type,
Steve Anton8a006912017-12-04 15:25:56 -08004356 cricket::ContentSource source) {
4357 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08004358
4359 // If there's already a pending error then no state transition should happen.
4360 // But all call-sites should be verifying this before calling us!
Steve Antonf8470812017-12-04 10:46:21 -08004361 RTC_DCHECK(session_error() == SessionError::kNone);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004362
4363 // If this is an answer then we know whether to BUNDLE or not. If both the
4364 // local and remote side have agreed to BUNDLE, go ahead and enable it.
Steve Anton3828c062017-12-06 10:34:51 -08004365 if (type == SdpType::kAnswer) {
Steve Anton75737c02017-11-06 10:37:17 -08004366 const cricket::ContentGroup* local_bundle =
4367 local_description()->description()->GetGroupByName(
4368 cricket::GROUP_TYPE_BUNDLE);
4369 const cricket::ContentGroup* remote_bundle =
4370 remote_description()->description()->GetGroupByName(
4371 cricket::GROUP_TYPE_BUNDLE);
4372 if (local_bundle && remote_bundle) {
4373 // The answerer decides the transport to bundle on.
4374 const cricket::ContentGroup* answer_bundle =
4375 (source == cricket::CS_LOCAL ? local_bundle : remote_bundle);
4376 if (!EnableBundle(*answer_bundle)) {
Steve Anton8a006912017-12-04 15:25:56 -08004377 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
4378 kEnableBundleFailed);
Steve Anton75737c02017-11-06 10:37:17 -08004379 }
4380 }
Steve Anton75737c02017-11-06 10:37:17 -08004381 }
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004382
4383 // Only push down the transport description after potentially enabling BUNDLE;
4384 // we don't want to push down a description on a transport about to be
4385 // destroyed.
Steve Anton3828c062017-12-06 10:34:51 -08004386 RTCError error = PushdownTransportDescription(source, type);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004387 if (!error.ok()) {
4388 return error;
4389 }
4390
4391 // If this is answer-ish we're ready to let media flow.
Steve Anton3828c062017-12-06 10:34:51 -08004392 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Antoned10bd92017-12-05 10:52:59 -08004393 EnableSending();
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004394 }
4395
4396 // Update the signaling state according to the specified state machine (see
4397 // https://w3c.github.io/webrtc-pc/#rtcsignalingstate-enum).
Steve Anton3828c062017-12-06 10:34:51 -08004398 if (type == SdpType::kOffer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004399 ChangeSignalingState(source == cricket::CS_LOCAL
4400 ? PeerConnectionInterface::kHaveLocalOffer
4401 : PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton3828c062017-12-06 10:34:51 -08004402 } else if (type == SdpType::kPrAnswer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004403 ChangeSignalingState(source == cricket::CS_LOCAL
4404 ? PeerConnectionInterface::kHaveLocalPrAnswer
4405 : PeerConnectionInterface::kHaveRemotePrAnswer);
4406 } else {
Steve Anton3828c062017-12-06 10:34:51 -08004407 RTC_DCHECK(type == SdpType::kAnswer);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004408 ChangeSignalingState(PeerConnectionInterface::kStable);
4409 }
4410
4411 // Update internal objects according to the session description's media
4412 // descriptions.
Steve Anton3828c062017-12-06 10:34:51 -08004413 error = PushdownMediaDescription(type, source);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004414 if (!error.ok()) {
4415 SetSessionError(SessionError::kContent, error.message());
4416 }
4417 if (session_error() != SessionError::kNone) {
4418 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
4419 }
4420
Steve Anton8a006912017-12-04 15:25:56 -08004421 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08004422}
4423
Steve Anton8a006912017-12-04 15:25:56 -08004424RTCError PeerConnection::PushdownMediaDescription(
Steve Anton3828c062017-12-06 10:34:51 -08004425 SdpType type,
Steve Anton8a006912017-12-04 15:25:56 -08004426 cricket::ContentSource source) {
Steve Antoned10bd92017-12-05 10:52:59 -08004427 const SessionDescriptionInterface* sdesc =
4428 (source == cricket::CS_LOCAL ? local_description()
4429 : remote_description());
Steve Anton75737c02017-11-06 10:37:17 -08004430 RTC_DCHECK(sdesc);
Steve Antoned10bd92017-12-05 10:52:59 -08004431
4432 // Push down the new SDP media section for each audio/video transceiver.
4433 for (auto transceiver : transceivers_) {
Steve Anton75737c02017-11-06 10:37:17 -08004434 const ContentInfo* content_info =
Steve Antoned10bd92017-12-05 10:52:59 -08004435 FindMediaSectionForTransceiver(transceiver, sdesc);
4436 cricket::BaseChannel* channel = transceiver->internal()->channel();
4437 if (!channel || !content_info || content_info->rejected) {
Steve Anton75737c02017-11-06 10:37:17 -08004438 continue;
4439 }
4440 const MediaContentDescription* content_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08004441 content_info->media_description();
Steve Antoned10bd92017-12-05 10:52:59 -08004442 if (!content_desc) {
4443 continue;
4444 }
4445 std::string error;
4446 bool success =
4447 (source == cricket::CS_LOCAL)
Steve Anton3828c062017-12-06 10:34:51 -08004448 ? channel->SetLocalContent(content_desc, type, &error)
4449 : channel->SetRemoteContent(content_desc, type, &error);
Steve Antoned10bd92017-12-05 10:52:59 -08004450 if (!success) {
4451 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, std::move(error));
4452 }
4453 }
4454
4455 // If using the RtpDataChannel, push down the new SDP section for it too.
4456 if (rtp_data_channel_) {
4457 const ContentInfo* data_content =
4458 cricket::GetFirstDataContent(sdesc->description());
4459 if (data_content && !data_content->rejected) {
4460 const MediaContentDescription* data_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08004461 data_content->media_description();
Steve Antoned10bd92017-12-05 10:52:59 -08004462 if (data_desc) {
4463 std::string error;
4464 bool success =
4465 (source == cricket::CS_LOCAL)
Steve Anton3828c062017-12-06 10:34:51 -08004466 ? rtp_data_channel_->SetLocalContent(data_desc, type, &error)
4467 : rtp_data_channel_->SetRemoteContent(data_desc, type,
Steve Antoned10bd92017-12-05 10:52:59 -08004468 &error);
4469 if (!success) {
4470 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
4471 std::move(error));
4472 }
Steve Anton75737c02017-11-06 10:37:17 -08004473 }
4474 }
4475 }
Steve Antoned10bd92017-12-05 10:52:59 -08004476
Steve Anton75737c02017-11-06 10:37:17 -08004477 // Need complete offer/answer with an SCTP m= section before starting SCTP,
4478 // according to https://tools.ietf.org/html/draft-ietf-mmusic-sctp-sdp-19
4479 if (sctp_transport_ && local_description() && remote_description() &&
4480 cricket::GetFirstDataContent(local_description()->description()) &&
4481 cricket::GetFirstDataContent(remote_description()->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08004482 bool success = network_thread()->Invoke<bool>(
Steve Anton75737c02017-11-06 10:37:17 -08004483 RTC_FROM_HERE,
4484 rtc::Bind(&PeerConnection::PushdownSctpParameters_n, this, source));
Steve Anton8a006912017-12-04 15:25:56 -08004485 if (!success) {
4486 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
4487 "Failed to push down SCTP parameters.");
4488 }
Steve Anton75737c02017-11-06 10:37:17 -08004489 }
Steve Antoned10bd92017-12-05 10:52:59 -08004490
Steve Anton8a006912017-12-04 15:25:56 -08004491 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08004492}
4493
4494bool PeerConnection::PushdownSctpParameters_n(cricket::ContentSource source) {
4495 RTC_DCHECK(network_thread()->IsCurrent());
4496 RTC_DCHECK(local_description());
4497 RTC_DCHECK(remote_description());
4498 // Apply the SCTP port (which is hidden inside a DataCodec structure...)
4499 // When we support "max-message-size", that would also be pushed down here.
4500 return sctp_transport_->Start(
4501 GetSctpPort(local_description()->description()),
4502 GetSctpPort(remote_description()->description()));
4503}
4504
Steve Anton8a006912017-12-04 15:25:56 -08004505RTCError PeerConnection::PushdownTransportDescription(
4506 cricket::ContentSource source,
Steve Anton3828c062017-12-06 10:34:51 -08004507 SdpType type) {
Steve Anton8a006912017-12-04 15:25:56 -08004508 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08004509
Steve Anton8a006912017-12-04 15:25:56 -08004510 const SessionDescriptionInterface* sdesc =
4511 (source == cricket::CS_LOCAL ? local_description()
4512 : remote_description());
4513 RTC_DCHECK(sdesc);
4514 for (const cricket::TransportInfo& tinfo :
4515 sdesc->description()->transport_infos()) {
4516 std::string error;
4517 bool success;
4518 if (source == cricket::CS_LOCAL) {
4519 success = transport_controller_->SetLocalTransportDescription(
Steve Anton3828c062017-12-06 10:34:51 -08004520 tinfo.content_name, tinfo.description, type, &error);
Steve Anton8a006912017-12-04 15:25:56 -08004521 } else {
4522 success = transport_controller_->SetRemoteTransportDescription(
Steve Anton3828c062017-12-06 10:34:51 -08004523 tinfo.content_name, tinfo.description, type, &error);
Steve Anton8a006912017-12-04 15:25:56 -08004524 }
4525 if (!success) {
Steve Antondcc3c022017-12-22 16:02:54 -08004526 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
4527 "Failed to push down transport description for " +
4528 tinfo.content_name + ": " + error);
Steve Anton75737c02017-11-06 10:37:17 -08004529 }
4530 }
4531
Steve Anton8a006912017-12-04 15:25:56 -08004532 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08004533}
4534
4535bool PeerConnection::GetTransportDescription(
4536 const SessionDescription* description,
4537 const std::string& content_name,
4538 cricket::TransportDescription* tdesc) {
4539 if (!description || !tdesc) {
4540 return false;
4541 }
4542 const TransportInfo* transport_info =
4543 description->GetTransportInfoByName(content_name);
4544 if (!transport_info) {
4545 return false;
4546 }
4547 *tdesc = transport_info->description;
4548 return true;
4549}
4550
4551bool PeerConnection::EnableBundle(const cricket::ContentGroup& bundle) {
4552 const std::string* first_content_name = bundle.FirstContentName();
4553 if (!first_content_name) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004554 RTC_LOG(LS_WARNING) << "Tried to BUNDLE with no contents.";
Steve Anton75737c02017-11-06 10:37:17 -08004555 return false;
4556 }
4557 const std::string& transport_name = *first_content_name;
4558
4559 auto maybe_set_transport = [this, bundle,
4560 transport_name](cricket::BaseChannel* ch) {
4561 if (!ch || !bundle.HasContentName(ch->content_name())) {
Steve Antoned10bd92017-12-05 10:52:59 -08004562 return;
Steve Anton75737c02017-11-06 10:37:17 -08004563 }
4564
4565 std::string old_transport_name = ch->transport_name();
4566 if (old_transport_name == transport_name) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004567 RTC_LOG(LS_INFO) << "BUNDLE already enabled for " << ch->content_name()
4568 << " on " << transport_name << ".";
Steve Antoned10bd92017-12-05 10:52:59 -08004569 return;
Steve Anton75737c02017-11-06 10:37:17 -08004570 }
4571
4572 cricket::DtlsTransportInternal* rtp_dtls_transport =
4573 transport_controller_->CreateDtlsTransport(
4574 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4575 bool need_rtcp = (ch->rtcp_dtls_transport() != nullptr);
4576 cricket::DtlsTransportInternal* rtcp_dtls_transport = nullptr;
4577 if (need_rtcp) {
4578 rtcp_dtls_transport = transport_controller_->CreateDtlsTransport(
4579 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
4580 }
4581
4582 ch->SetTransports(rtp_dtls_transport, rtcp_dtls_transport);
Mirko Bonadei675513b2017-11-09 11:09:25 +01004583 RTC_LOG(LS_INFO) << "Enabled BUNDLE for " << ch->content_name() << " on "
4584 << transport_name << ".";
Steve Anton75737c02017-11-06 10:37:17 -08004585 transport_controller_->DestroyDtlsTransport(
4586 old_transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4587 // If the channel needs rtcp, it means that the channel used to have a
4588 // rtcp transport which needs to be deleted now.
4589 if (need_rtcp) {
4590 transport_controller_->DestroyDtlsTransport(
4591 old_transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
4592 }
Steve Anton75737c02017-11-06 10:37:17 -08004593 };
4594
Steve Antoned10bd92017-12-05 10:52:59 -08004595 for (auto transceiver : transceivers_) {
4596 maybe_set_transport(transceiver->internal()->channel());
Steve Anton75737c02017-11-06 10:37:17 -08004597 }
Steve Antoned10bd92017-12-05 10:52:59 -08004598 maybe_set_transport(rtp_data_channel_);
4599
Steve Anton75737c02017-11-06 10:37:17 -08004600 // For SCTP, transport creation/deletion happens here instead of in the
4601 // object itself.
4602 if (sctp_transport_) {
4603 RTC_DCHECK(sctp_transport_name_);
4604 RTC_DCHECK(sctp_content_name_);
4605 if (transport_name != *sctp_transport_name_ &&
4606 bundle.HasContentName(*sctp_content_name_)) {
4607 network_thread()->Invoke<void>(
4608 RTC_FROM_HERE, rtc::Bind(&PeerConnection::ChangeSctpTransport_n, this,
4609 transport_name));
4610 }
4611 }
4612
4613 return true;
4614}
4615
Steve Anton75737c02017-11-06 10:37:17 -08004616cricket::IceConfig PeerConnection::ParseIceConfig(
4617 const PeerConnectionInterface::RTCConfiguration& config) const {
4618 cricket::ContinualGatheringPolicy gathering_policy;
4619 // TODO(honghaiz): Add the third continual gathering policy in
4620 // PeerConnectionInterface and map it to GATHER_CONTINUALLY_AND_RECOVER.
4621 switch (config.continual_gathering_policy) {
4622 case PeerConnectionInterface::GATHER_ONCE:
4623 gathering_policy = cricket::GATHER_ONCE;
4624 break;
4625 case PeerConnectionInterface::GATHER_CONTINUALLY:
4626 gathering_policy = cricket::GATHER_CONTINUALLY;
4627 break;
4628 default:
4629 RTC_NOTREACHED();
4630 gathering_policy = cricket::GATHER_ONCE;
4631 }
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08004632
Steve Anton75737c02017-11-06 10:37:17 -08004633 cricket::IceConfig ice_config;
4634 ice_config.receiving_timeout = config.ice_connection_receiving_timeout;
4635 ice_config.prioritize_most_likely_candidate_pairs =
4636 config.prioritize_most_likely_ice_candidate_pairs;
4637 ice_config.backup_connection_ping_interval =
4638 config.ice_backup_candidate_pair_ping_interval;
4639 ice_config.continual_gathering_policy = gathering_policy;
4640 ice_config.presume_writable_when_fully_relayed =
4641 config.presume_writable_when_fully_relayed;
4642 ice_config.ice_check_min_interval = config.ice_check_min_interval;
4643 ice_config.regather_all_networks_interval_range =
4644 config.ice_regather_interval_range;
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08004645 ice_config.network_preference = config.network_preference;
Steve Anton75737c02017-11-06 10:37:17 -08004646 return ice_config;
4647}
4648
Steve Anton75737c02017-11-06 10:37:17 -08004649bool PeerConnection::GetLocalTrackIdBySsrc(uint32_t ssrc,
4650 std::string* track_id) {
4651 if (!local_description()) {
4652 return false;
4653 }
4654 return webrtc::GetTrackIdBySsrc(local_description()->description(), ssrc,
4655 track_id);
4656}
4657
4658bool PeerConnection::GetRemoteTrackIdBySsrc(uint32_t ssrc,
4659 std::string* track_id) {
4660 if (!remote_description()) {
4661 return false;
4662 }
4663 return webrtc::GetTrackIdBySsrc(remote_description()->description(), ssrc,
4664 track_id);
4665}
4666
4667bool PeerConnection::SendData(const cricket::SendDataParams& params,
4668 const rtc::CopyOnWriteBuffer& payload,
4669 cricket::SendDataResult* result) {
4670 if (!rtp_data_channel_ && !sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004671 RTC_LOG(LS_ERROR) << "SendData called when rtp_data_channel_ "
4672 << "and sctp_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08004673 return false;
4674 }
4675 return rtp_data_channel_
4676 ? rtp_data_channel_->SendData(params, payload, result)
4677 : network_thread()->Invoke<bool>(
4678 RTC_FROM_HERE,
4679 Bind(&cricket::SctpTransportInternal::SendData,
4680 sctp_transport_.get(), params, payload, result));
4681}
4682
4683bool PeerConnection::ConnectDataChannel(DataChannel* webrtc_data_channel) {
4684 if (!rtp_data_channel_ && !sctp_transport_) {
4685 // Don't log an error here, because DataChannels are expected to call
4686 // ConnectDataChannel in this state. It's the only way to initially tell
4687 // whether or not the underlying transport is ready.
4688 return false;
4689 }
4690 if (rtp_data_channel_) {
4691 rtp_data_channel_->SignalReadyToSendData.connect(
4692 webrtc_data_channel, &DataChannel::OnChannelReady);
4693 rtp_data_channel_->SignalDataReceived.connect(webrtc_data_channel,
4694 &DataChannel::OnDataReceived);
4695 } else {
4696 SignalSctpReadyToSendData.connect(webrtc_data_channel,
4697 &DataChannel::OnChannelReady);
4698 SignalSctpDataReceived.connect(webrtc_data_channel,
4699 &DataChannel::OnDataReceived);
4700 SignalSctpStreamClosedRemotely.connect(
4701 webrtc_data_channel, &DataChannel::OnStreamClosedRemotely);
4702 }
4703 return true;
4704}
4705
4706void PeerConnection::DisconnectDataChannel(DataChannel* webrtc_data_channel) {
4707 if (!rtp_data_channel_ && !sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004708 RTC_LOG(LS_ERROR)
4709 << "DisconnectDataChannel called when rtp_data_channel_ and "
4710 "sctp_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08004711 return;
4712 }
4713 if (rtp_data_channel_) {
4714 rtp_data_channel_->SignalReadyToSendData.disconnect(webrtc_data_channel);
4715 rtp_data_channel_->SignalDataReceived.disconnect(webrtc_data_channel);
4716 } else {
4717 SignalSctpReadyToSendData.disconnect(webrtc_data_channel);
4718 SignalSctpDataReceived.disconnect(webrtc_data_channel);
4719 SignalSctpStreamClosedRemotely.disconnect(webrtc_data_channel);
4720 }
4721}
4722
4723void PeerConnection::AddSctpDataStream(int sid) {
4724 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004725 RTC_LOG(LS_ERROR)
4726 << "AddSctpDataStream called when sctp_transport_ is NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08004727 return;
4728 }
4729 network_thread()->Invoke<void>(
4730 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::OpenStream,
4731 sctp_transport_.get(), sid));
4732}
4733
4734void PeerConnection::RemoveSctpDataStream(int sid) {
4735 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004736 RTC_LOG(LS_ERROR) << "RemoveSctpDataStream called when sctp_transport_ is "
4737 << "NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08004738 return;
4739 }
4740 network_thread()->Invoke<void>(
4741 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::ResetStream,
4742 sctp_transport_.get(), sid));
4743}
4744
4745bool PeerConnection::ReadyToSendData() const {
4746 return (rtp_data_channel_ && rtp_data_channel_->ready_to_send_data()) ||
4747 sctp_ready_to_send_data_;
4748}
4749
4750std::unique_ptr<SessionStats> PeerConnection::GetSessionStats_s() {
4751 RTC_DCHECK(signaling_thread()->IsCurrent());
4752 ChannelNamePairs channel_name_pairs;
4753 if (voice_channel()) {
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004754 channel_name_pairs.voice = ChannelNamePair(
4755 voice_channel()->content_name(), voice_channel()->transport_name());
Steve Anton75737c02017-11-06 10:37:17 -08004756 }
4757 if (video_channel()) {
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004758 channel_name_pairs.video = ChannelNamePair(
4759 video_channel()->content_name(), video_channel()->transport_name());
Steve Anton75737c02017-11-06 10:37:17 -08004760 }
4761 if (rtp_data_channel()) {
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004762 channel_name_pairs.data =
Steve Anton75737c02017-11-06 10:37:17 -08004763 ChannelNamePair(rtp_data_channel()->content_name(),
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004764 rtp_data_channel()->transport_name());
Steve Anton75737c02017-11-06 10:37:17 -08004765 }
4766 if (sctp_transport_) {
4767 RTC_DCHECK(sctp_content_name_);
4768 RTC_DCHECK(sctp_transport_name_);
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004769 channel_name_pairs.data =
4770 ChannelNamePair(*sctp_content_name_, *sctp_transport_name_);
Steve Anton75737c02017-11-06 10:37:17 -08004771 }
4772 return GetSessionStats(channel_name_pairs);
4773}
4774
4775std::unique_ptr<SessionStats> PeerConnection::GetSessionStats(
4776 const ChannelNamePairs& channel_name_pairs) {
4777 if (network_thread()->IsCurrent()) {
4778 return GetSessionStats_n(channel_name_pairs);
4779 }
4780 return network_thread()->Invoke<std::unique_ptr<SessionStats>>(
4781 RTC_FROM_HERE,
4782 rtc::Bind(&PeerConnection::GetSessionStats_n, this, channel_name_pairs));
4783}
4784
4785bool PeerConnection::GetLocalCertificate(
4786 const std::string& transport_name,
4787 rtc::scoped_refptr<rtc::RTCCertificate>* certificate) {
4788 return transport_controller_->GetLocalCertificate(transport_name,
4789 certificate);
4790}
4791
4792std::unique_ptr<rtc::SSLCertificate> PeerConnection::GetRemoteSSLCertificate(
4793 const std::string& transport_name) {
4794 return transport_controller_->GetRemoteSSLCertificate(transport_name);
4795}
4796
4797cricket::DataChannelType PeerConnection::data_channel_type() const {
4798 return data_channel_type_;
4799}
4800
4801bool PeerConnection::IceRestartPending(const std::string& content_name) const {
4802 return pending_ice_restarts_.find(content_name) !=
4803 pending_ice_restarts_.end();
4804}
4805
Steve Anton75737c02017-11-06 10:37:17 -08004806bool PeerConnection::NeedsIceRestart(const std::string& content_name) const {
4807 return transport_controller_->NeedsIceRestart(content_name);
4808}
4809
4810void PeerConnection::OnCertificateReady(
4811 const rtc::scoped_refptr<rtc::RTCCertificate>& certificate) {
4812 transport_controller_->SetLocalCertificate(certificate);
4813}
4814
4815void PeerConnection::OnDtlsSrtpSetupFailure(cricket::BaseChannel*, bool rtcp) {
Steve Antonf8470812017-12-04 10:46:21 -08004816 SetSessionError(SessionError::kTransport,
4817 rtcp ? kDtlsSrtpSetupFailureRtcp : kDtlsSrtpSetupFailureRtp);
Steve Anton75737c02017-11-06 10:37:17 -08004818}
4819
4820void PeerConnection::OnTransportControllerConnectionState(
4821 cricket::IceConnectionState state) {
4822 switch (state) {
4823 case cricket::kIceConnectionConnecting:
4824 // If the current state is Connected or Completed, then there were
4825 // writable channels but now there are not, so the next state must
4826 // be Disconnected.
4827 // kIceConnectionConnecting is currently used as the default,
4828 // un-connected state by the TransportController, so its only use is
4829 // detecting disconnections.
4830 if (ice_connection_state_ ==
4831 PeerConnectionInterface::kIceConnectionConnected ||
4832 ice_connection_state_ ==
4833 PeerConnectionInterface::kIceConnectionCompleted) {
4834 SetIceConnectionState(
4835 PeerConnectionInterface::kIceConnectionDisconnected);
4836 }
4837 break;
4838 case cricket::kIceConnectionFailed:
4839 SetIceConnectionState(PeerConnectionInterface::kIceConnectionFailed);
4840 break;
4841 case cricket::kIceConnectionConnected:
Mirko Bonadei675513b2017-11-09 11:09:25 +01004842 RTC_LOG(LS_INFO) << "Changing to ICE connected state because "
4843 << "all transports are writable.";
Steve Anton75737c02017-11-06 10:37:17 -08004844 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
4845 break;
4846 case cricket::kIceConnectionCompleted:
Mirko Bonadei675513b2017-11-09 11:09:25 +01004847 RTC_LOG(LS_INFO) << "Changing to ICE completed state because "
4848 << "all transports are complete.";
Steve Anton75737c02017-11-06 10:37:17 -08004849 if (ice_connection_state_ !=
4850 PeerConnectionInterface::kIceConnectionConnected) {
4851 // If jumping directly from "checking" to "connected",
4852 // signal "connected" first.
4853 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
4854 }
4855 SetIceConnectionState(PeerConnectionInterface::kIceConnectionCompleted);
4856 if (metrics_observer()) {
4857 ReportTransportStats();
4858 }
4859 break;
4860 default:
4861 RTC_NOTREACHED();
4862 }
4863}
4864
4865void PeerConnection::OnTransportControllerCandidatesGathered(
4866 const std::string& transport_name,
4867 const cricket::Candidates& candidates) {
4868 RTC_DCHECK(signaling_thread()->IsCurrent());
4869 int sdp_mline_index;
4870 if (!GetLocalCandidateMediaIndex(transport_name, &sdp_mline_index)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004871 RTC_LOG(LS_ERROR)
4872 << "OnTransportControllerCandidatesGathered: content name "
4873 << transport_name << " not found";
Steve Anton75737c02017-11-06 10:37:17 -08004874 return;
4875 }
4876
4877 for (cricket::Candidates::const_iterator citer = candidates.begin();
4878 citer != candidates.end(); ++citer) {
4879 // Use transport_name as the candidate media id.
4880 std::unique_ptr<JsepIceCandidate> candidate(
4881 new JsepIceCandidate(transport_name, sdp_mline_index, *citer));
4882 if (local_description()) {
4883 mutable_local_description()->AddCandidate(candidate.get());
4884 }
4885 OnIceCandidate(std::move(candidate));
4886 }
4887}
4888
4889void PeerConnection::OnTransportControllerCandidatesRemoved(
4890 const std::vector<cricket::Candidate>& candidates) {
4891 RTC_DCHECK(signaling_thread()->IsCurrent());
4892 // Sanity check.
4893 for (const cricket::Candidate& candidate : candidates) {
4894 if (candidate.transport_name().empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004895 RTC_LOG(LS_ERROR) << "OnTransportControllerCandidatesRemoved: "
4896 << "empty content name in candidate "
4897 << candidate.ToString();
Steve Anton75737c02017-11-06 10:37:17 -08004898 return;
4899 }
4900 }
4901
4902 if (local_description()) {
4903 mutable_local_description()->RemoveCandidates(candidates);
4904 }
4905 OnIceCandidatesRemoved(candidates);
4906}
4907
4908void PeerConnection::OnTransportControllerDtlsHandshakeError(
4909 rtc::SSLHandshakeError error) {
4910 if (metrics_observer()) {
4911 metrics_observer()->IncrementEnumCounter(
4912 webrtc::kEnumCounterDtlsHandshakeError, static_cast<int>(error),
4913 static_cast<int>(rtc::SSLHandshakeError::MAX_VALUE));
4914 }
4915}
4916
Steve Antoned10bd92017-12-05 10:52:59 -08004917void PeerConnection::EnableSending() {
4918 for (auto transceiver : transceivers_) {
4919 cricket::BaseChannel* channel = transceiver->internal()->channel();
4920 if (channel && !channel->enabled()) {
4921 channel->Enable(true);
4922 }
Steve Anton75737c02017-11-06 10:37:17 -08004923 }
4924
Steve Anton4171afb2017-11-20 10:20:22 -08004925 if (rtp_data_channel_ && !rtp_data_channel_->enabled()) {
Steve Anton75737c02017-11-06 10:37:17 -08004926 rtp_data_channel_->Enable(true);
Steve Anton4171afb2017-11-20 10:20:22 -08004927 }
Steve Anton75737c02017-11-06 10:37:17 -08004928}
4929
4930// Returns the media index for a local ice candidate given the content name.
4931bool PeerConnection::GetLocalCandidateMediaIndex(
4932 const std::string& content_name,
4933 int* sdp_mline_index) {
4934 if (!local_description() || !sdp_mline_index) {
4935 return false;
4936 }
4937
4938 bool content_found = false;
4939 const ContentInfos& contents = local_description()->description()->contents();
4940 for (size_t index = 0; index < contents.size(); ++index) {
4941 if (contents[index].name == content_name) {
4942 *sdp_mline_index = static_cast<int>(index);
4943 content_found = true;
4944 break;
4945 }
4946 }
4947 return content_found;
4948}
4949
4950bool PeerConnection::UseCandidatesInSessionDescription(
4951 const SessionDescriptionInterface* remote_desc) {
4952 if (!remote_desc) {
4953 return true;
4954 }
4955 bool ret = true;
4956
4957 for (size_t m = 0; m < remote_desc->number_of_mediasections(); ++m) {
4958 const IceCandidateCollection* candidates = remote_desc->candidates(m);
4959 for (size_t n = 0; n < candidates->count(); ++n) {
4960 const IceCandidateInterface* candidate = candidates->at(n);
4961 bool valid = false;
4962 if (!ReadyToUseRemoteCandidate(candidate, remote_desc, &valid)) {
4963 if (valid) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004964 RTC_LOG(LS_INFO)
4965 << "UseCandidatesInSessionDescription: Not ready to use "
4966 << "candidate.";
Steve Anton75737c02017-11-06 10:37:17 -08004967 }
4968 continue;
4969 }
4970 ret = UseCandidate(candidate);
4971 if (!ret) {
4972 break;
4973 }
4974 }
4975 }
4976 return ret;
4977}
4978
4979bool PeerConnection::UseCandidate(const IceCandidateInterface* candidate) {
4980 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
4981 size_t remote_content_size =
4982 remote_description()->description()->contents().size();
4983 if (mediacontent_index >= remote_content_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004984 RTC_LOG(LS_ERROR) << "UseCandidate: Invalid candidate media index.";
Steve Anton75737c02017-11-06 10:37:17 -08004985 return false;
4986 }
4987
4988 cricket::ContentInfo content =
4989 remote_description()->description()->contents()[mediacontent_index];
4990 std::vector<cricket::Candidate> candidates;
4991 candidates.push_back(candidate->candidate());
4992 // Invoking BaseSession method to handle remote candidates.
4993 std::string error;
4994 if (transport_controller_->AddRemoteCandidates(content.name, candidates,
4995 &error)) {
4996 // Candidates successfully submitted for checking.
4997 if (ice_connection_state_ == PeerConnectionInterface::kIceConnectionNew ||
4998 ice_connection_state_ ==
4999 PeerConnectionInterface::kIceConnectionDisconnected) {
5000 // If state is New, then the session has just gotten its first remote ICE
5001 // candidates, so go to Checking.
5002 // If state is Disconnected, the session is re-using old candidates or
5003 // receiving additional ones, so go to Checking.
5004 // If state is Connected, stay Connected.
5005 // TODO(bemasc): If state is Connected, and the new candidates are for a
5006 // newly added transport, then the state actually _should_ move to
5007 // checking. Add a way to distinguish that case.
5008 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
5009 }
5010 // TODO(bemasc): If state is Completed, go back to Connected.
5011 } else {
5012 if (!error.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005013 RTC_LOG(LS_WARNING) << error;
Steve Anton75737c02017-11-06 10:37:17 -08005014 }
5015 }
5016 return true;
5017}
5018
5019void PeerConnection::RemoveUnusedChannels(const SessionDescription* desc) {
Steve Anton75737c02017-11-06 10:37:17 -08005020 // Destroy video channel first since it may have a pointer to the
5021 // voice channel.
5022 const cricket::ContentInfo* video_info = cricket::GetFirstVideoContent(desc);
Steve Anton6fec8802017-12-04 10:37:29 -08005023 if (!video_info || video_info->rejected) {
5024 DestroyTransceiverChannel(GetVideoTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08005025 }
5026
Steve Anton6fec8802017-12-04 10:37:29 -08005027 const cricket::ContentInfo* audio_info = cricket::GetFirstAudioContent(desc);
5028 if (!audio_info || audio_info->rejected) {
5029 DestroyTransceiverChannel(GetAudioTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08005030 }
5031
5032 const cricket::ContentInfo* data_info = cricket::GetFirstDataContent(desc);
5033 if (!data_info || data_info->rejected) {
Steve Anton6fec8802017-12-04 10:37:29 -08005034 DestroyDataChannel();
Steve Anton75737c02017-11-06 10:37:17 -08005035 }
5036}
5037
Steve Antoneda6ccd2017-12-04 10:21:55 -08005038std::string PeerConnection::GetTransportNameForMediaSection(
5039 const std::string& mid,
5040 const cricket::ContentGroup* bundle_group) const {
5041 if (!bundle_group) {
5042 return mid;
Steve Anton75737c02017-11-06 10:37:17 -08005043 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005044 const std::string* first_content_name = bundle_group->FirstContentName();
Steve Anton75737c02017-11-06 10:37:17 -08005045 if (!first_content_name) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005046 RTC_LOG(LS_WARNING) << "Tried to BUNDLE with no contents.";
Steve Antoneda6ccd2017-12-04 10:21:55 -08005047 return mid;
Steve Anton75737c02017-11-06 10:37:17 -08005048 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005049 if (!bundle_group->HasContentName(mid)) {
5050 RTC_LOG(LS_WARNING) << mid << " is not part of any bundle group";
5051 return mid;
Steve Anton75737c02017-11-06 10:37:17 -08005052 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005053 RTC_LOG(LS_INFO) << "Bundling " << mid << " on " << *first_content_name;
5054 return *first_content_name;
Steve Anton75737c02017-11-06 10:37:17 -08005055}
5056
Steve Antondcc3c022017-12-22 16:02:54 -08005057RTCErrorOr<const cricket::ContentGroup*> PeerConnection::GetEarlyBundleGroup(
5058 const SessionDescription& desc) const {
Steve Anton75737c02017-11-06 10:37:17 -08005059 const cricket::ContentGroup* bundle_group = nullptr;
5060 if (configuration_.bundle_policy ==
5061 PeerConnectionInterface::kBundlePolicyMaxBundle) {
Steve Antondcc3c022017-12-22 16:02:54 -08005062 bundle_group = desc.GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton75737c02017-11-06 10:37:17 -08005063 if (!bundle_group) {
Steve Anton8a006912017-12-04 15:25:56 -08005064 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5065 "max-bundle configured but session description "
5066 "has no BUNDLE group");
Steve Anton75737c02017-11-06 10:37:17 -08005067 }
5068 }
Steve Antondcc3c022017-12-22 16:02:54 -08005069 return std::move(bundle_group);
5070}
5071
5072RTCError PeerConnection::CreateChannels(const SessionDescription& desc) {
5073 auto bundle_group_or_error = GetEarlyBundleGroup(desc);
5074 if (!bundle_group_or_error.ok()) {
5075 return bundle_group_or_error.MoveError();
5076 }
5077 const cricket::ContentGroup* bundle_group = bundle_group_or_error.MoveValue();
Steve Anton75737c02017-11-06 10:37:17 -08005078
Steve Antoneda6ccd2017-12-04 10:21:55 -08005079 // Creating the media channels and transport proxies.
Steve Antondcc3c022017-12-22 16:02:54 -08005080 const cricket::ContentInfo* voice = cricket::GetFirstAudioContent(&desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08005081 if (voice && !voice->rejected &&
5082 !GetAudioTransceiver()->internal()->channel()) {
5083 cricket::VoiceChannel* voice_channel = CreateVoiceChannel(
5084 voice->name,
5085 GetTransportNameForMediaSection(voice->name, bundle_group));
5086 if (!voice_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08005087 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5088 "Failed to create voice channel.");
Steve Antoneda6ccd2017-12-04 10:21:55 -08005089 }
5090 GetAudioTransceiver()->internal()->SetChannel(voice_channel);
5091 }
5092
Steve Antondcc3c022017-12-22 16:02:54 -08005093 const cricket::ContentInfo* video = cricket::GetFirstVideoContent(&desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08005094 if (video && !video->rejected &&
5095 !GetVideoTransceiver()->internal()->channel()) {
5096 cricket::VideoChannel* video_channel = CreateVideoChannel(
5097 video->name,
5098 GetTransportNameForMediaSection(video->name, bundle_group));
5099 if (!video_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08005100 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5101 "Failed to create video channel.");
Steve Anton75737c02017-11-06 10:37:17 -08005102 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005103 GetVideoTransceiver()->internal()->SetChannel(video_channel);
Steve Anton75737c02017-11-06 10:37:17 -08005104 }
5105
Steve Antondcc3c022017-12-22 16:02:54 -08005106 const cricket::ContentInfo* data = cricket::GetFirstDataContent(&desc);
Steve Anton75737c02017-11-06 10:37:17 -08005107 if (data_channel_type_ != cricket::DCT_NONE && data && !data->rejected &&
5108 !rtp_data_channel_ && !sctp_transport_) {
Steve Antoneda6ccd2017-12-04 10:21:55 -08005109 if (!CreateDataChannel(data->name, GetTransportNameForMediaSection(
5110 data->name, bundle_group))) {
Steve Anton8a006912017-12-04 15:25:56 -08005111 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5112 "Failed to create data channel.");
Steve Anton75737c02017-11-06 10:37:17 -08005113 }
5114 }
5115
Steve Anton8a006912017-12-04 15:25:56 -08005116 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08005117}
5118
Steve Anton4171afb2017-11-20 10:20:22 -08005119// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08005120cricket::VoiceChannel* PeerConnection::CreateVoiceChannel(
5121 const std::string& mid,
5122 const std::string& transport_name) {
Steve Anton75737c02017-11-06 10:37:17 -08005123 cricket::DtlsTransportInternal* rtp_dtls_transport =
5124 transport_controller_->CreateDtlsTransport(
5125 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5126 cricket::DtlsTransportInternal* rtcp_dtls_transport = nullptr;
5127 if (configuration_.rtcp_mux_policy !=
5128 PeerConnectionInterface::kRtcpMuxPolicyRequire) {
5129 rtcp_dtls_transport = transport_controller_->CreateDtlsTransport(
5130 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
5131 }
5132
5133 cricket::VoiceChannel* voice_channel = channel_manager()->CreateVoiceChannel(
5134 call_.get(), configuration_.media_config, rtp_dtls_transport,
Steve Antoneda6ccd2017-12-04 10:21:55 -08005135 rtcp_dtls_transport, signaling_thread(), mid, SrtpRequired(),
5136 audio_options_);
Steve Anton75737c02017-11-06 10:37:17 -08005137 if (!voice_channel) {
5138 transport_controller_->DestroyDtlsTransport(
5139 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5140 if (rtcp_dtls_transport) {
5141 transport_controller_->DestroyDtlsTransport(
5142 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
5143 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005144 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08005145 }
Steve Anton75737c02017-11-06 10:37:17 -08005146 voice_channel->SignalRtcpMuxFullyActive.connect(
5147 this, &PeerConnection::DestroyRtcpTransport_n);
5148 voice_channel->SignalDtlsSrtpSetupFailure.connect(
5149 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08005150 voice_channel->SignalSentPacket.connect(this,
5151 &PeerConnection::OnSentPacket_w);
Steve Anton4171afb2017-11-20 10:20:22 -08005152
Steve Antoneda6ccd2017-12-04 10:21:55 -08005153 return voice_channel;
Steve Anton75737c02017-11-06 10:37:17 -08005154}
5155
Steve Anton4171afb2017-11-20 10:20:22 -08005156// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08005157cricket::VideoChannel* PeerConnection::CreateVideoChannel(
5158 const std::string& mid,
5159 const std::string& transport_name) {
Steve Anton75737c02017-11-06 10:37:17 -08005160 cricket::DtlsTransportInternal* rtp_dtls_transport =
5161 transport_controller_->CreateDtlsTransport(
5162 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5163 cricket::DtlsTransportInternal* rtcp_dtls_transport = nullptr;
5164 if (configuration_.rtcp_mux_policy !=
5165 PeerConnectionInterface::kRtcpMuxPolicyRequire) {
5166 rtcp_dtls_transport = transport_controller_->CreateDtlsTransport(
5167 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
5168 }
5169
5170 cricket::VideoChannel* video_channel = channel_manager()->CreateVideoChannel(
5171 call_.get(), configuration_.media_config, rtp_dtls_transport,
Steve Antoneda6ccd2017-12-04 10:21:55 -08005172 rtcp_dtls_transport, signaling_thread(), mid, SrtpRequired(),
5173 video_options_);
Steve Anton75737c02017-11-06 10:37:17 -08005174
5175 if (!video_channel) {
5176 transport_controller_->DestroyDtlsTransport(
5177 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5178 if (rtcp_dtls_transport) {
5179 transport_controller_->DestroyDtlsTransport(
5180 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
5181 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005182 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08005183 }
Steve Anton75737c02017-11-06 10:37:17 -08005184 video_channel->SignalRtcpMuxFullyActive.connect(
5185 this, &PeerConnection::DestroyRtcpTransport_n);
5186 video_channel->SignalDtlsSrtpSetupFailure.connect(
5187 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08005188 video_channel->SignalSentPacket.connect(this,
5189 &PeerConnection::OnSentPacket_w);
Steve Anton4171afb2017-11-20 10:20:22 -08005190
Steve Antoneda6ccd2017-12-04 10:21:55 -08005191 return video_channel;
Steve Anton75737c02017-11-06 10:37:17 -08005192}
5193
Steve Antoneda6ccd2017-12-04 10:21:55 -08005194bool PeerConnection::CreateDataChannel(const std::string& mid,
5195 const std::string& transport_name) {
Steve Anton75737c02017-11-06 10:37:17 -08005196 bool sctp = (data_channel_type_ == cricket::DCT_SCTP);
5197 if (sctp) {
5198 if (!sctp_factory_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005199 RTC_LOG(LS_ERROR)
Steve Anton75737c02017-11-06 10:37:17 -08005200 << "Trying to create SCTP transport, but didn't compile with "
5201 "SCTP support (HAVE_SCTP)";
5202 return false;
5203 }
5204 if (!network_thread()->Invoke<bool>(
5205 RTC_FROM_HERE, rtc::Bind(&PeerConnection::CreateSctpTransport_n,
Steve Antoneda6ccd2017-12-04 10:21:55 -08005206 this, mid, transport_name))) {
Steve Anton75737c02017-11-06 10:37:17 -08005207 return false;
5208 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005209 for (const auto& channel : sctp_data_channels_) {
5210 channel->OnTransportChannelCreated();
5211 }
Steve Anton75737c02017-11-06 10:37:17 -08005212 } else {
Steve Anton75737c02017-11-06 10:37:17 -08005213 cricket::DtlsTransportInternal* rtp_dtls_transport =
5214 transport_controller_->CreateDtlsTransport(
5215 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5216 cricket::DtlsTransportInternal* rtcp_dtls_transport = nullptr;
5217 if (configuration_.rtcp_mux_policy !=
5218 PeerConnectionInterface::kRtcpMuxPolicyRequire) {
5219 rtcp_dtls_transport = transport_controller_->CreateDtlsTransport(
5220 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
5221 }
5222
5223 rtp_data_channel_ = channel_manager()->CreateRtpDataChannel(
5224 configuration_.media_config, rtp_dtls_transport, rtcp_dtls_transport,
Steve Antoneda6ccd2017-12-04 10:21:55 -08005225 signaling_thread(), mid, SrtpRequired());
Steve Anton75737c02017-11-06 10:37:17 -08005226
5227 if (!rtp_data_channel_) {
5228 transport_controller_->DestroyDtlsTransport(
5229 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5230 if (rtcp_dtls_transport) {
5231 transport_controller_->DestroyDtlsTransport(
5232 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
5233 }
5234 return false;
5235 }
5236
5237 rtp_data_channel_->SignalRtcpMuxFullyActive.connect(
5238 this, &PeerConnection::DestroyRtcpTransport_n);
5239 rtp_data_channel_->SignalDtlsSrtpSetupFailure.connect(
5240 this, &PeerConnection::OnDtlsSrtpSetupFailure);
5241 rtp_data_channel_->SignalSentPacket.connect(
5242 this, &PeerConnection::OnSentPacket_w);
5243 }
5244
Steve Anton75737c02017-11-06 10:37:17 -08005245 return true;
5246}
5247
5248Call::Stats PeerConnection::GetCallStats() {
5249 if (!worker_thread()->IsCurrent()) {
5250 return worker_thread()->Invoke<Call::Stats>(
5251 RTC_FROM_HERE, rtc::Bind(&PeerConnection::GetCallStats, this));
5252 }
5253 if (call_) {
5254 return call_->GetStats();
5255 } else {
5256 return Call::Stats();
5257 }
5258}
5259
5260std::unique_ptr<SessionStats> PeerConnection::GetSessionStats_n(
5261 const ChannelNamePairs& channel_name_pairs) {
5262 RTC_DCHECK(network_thread()->IsCurrent());
5263 std::unique_ptr<SessionStats> session_stats(new SessionStats());
5264 for (const auto channel_name_pair :
5265 {&channel_name_pairs.voice, &channel_name_pairs.video,
5266 &channel_name_pairs.data}) {
5267 if (*channel_name_pair) {
5268 cricket::TransportStats transport_stats;
5269 if (!transport_controller_->GetStats((*channel_name_pair)->transport_name,
5270 &transport_stats)) {
5271 return nullptr;
5272 }
Steve Anton75737c02017-11-06 10:37:17 -08005273 session_stats->transport_stats[(*channel_name_pair)->transport_name] =
5274 std::move(transport_stats);
5275 }
5276 }
5277 return session_stats;
5278}
5279
5280bool PeerConnection::CreateSctpTransport_n(const std::string& content_name,
5281 const std::string& transport_name) {
5282 RTC_DCHECK(network_thread()->IsCurrent());
5283 RTC_DCHECK(sctp_factory_);
5284 cricket::DtlsTransportInternal* tc =
5285 transport_controller_->CreateDtlsTransport_n(
5286 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5287 sctp_transport_ = sctp_factory_->CreateSctpTransport(tc);
5288 RTC_DCHECK(sctp_transport_);
5289 sctp_invoker_.reset(new rtc::AsyncInvoker());
5290 sctp_transport_->SignalReadyToSendData.connect(
5291 this, &PeerConnection::OnSctpTransportReadyToSendData_n);
5292 sctp_transport_->SignalDataReceived.connect(
5293 this, &PeerConnection::OnSctpTransportDataReceived_n);
5294 sctp_transport_->SignalStreamClosedRemotely.connect(
5295 this, &PeerConnection::OnSctpStreamClosedRemotely_n);
Oskar Sundbom9b28a032017-11-16 10:53:30 +01005296 sctp_transport_name_ = transport_name;
5297 sctp_content_name_ = content_name;
Steve Anton75737c02017-11-06 10:37:17 -08005298 return true;
5299}
5300
5301void PeerConnection::ChangeSctpTransport_n(const std::string& transport_name) {
5302 RTC_DCHECK(network_thread()->IsCurrent());
5303 RTC_DCHECK(sctp_transport_);
5304 RTC_DCHECK(sctp_transport_name_);
5305 std::string old_sctp_transport_name = *sctp_transport_name_;
Oskar Sundbom9b28a032017-11-16 10:53:30 +01005306 sctp_transport_name_ = transport_name;
Steve Anton75737c02017-11-06 10:37:17 -08005307 cricket::DtlsTransportInternal* tc =
5308 transport_controller_->CreateDtlsTransport_n(
5309 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5310 sctp_transport_->SetTransportChannel(tc);
5311 transport_controller_->DestroyDtlsTransport_n(
5312 old_sctp_transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5313}
5314
5315void PeerConnection::DestroySctpTransport_n() {
5316 RTC_DCHECK(network_thread()->IsCurrent());
5317 sctp_transport_.reset(nullptr);
Taylor Brandstetter389a97c2018-01-03 16:26:06 -08005318 transport_controller_->DestroyDtlsTransport_n(
5319 *sctp_transport_name_, cricket::ICE_CANDIDATE_COMPONENT_RTP);
Steve Anton75737c02017-11-06 10:37:17 -08005320 sctp_content_name_.reset();
5321 sctp_transport_name_.reset();
5322 sctp_invoker_.reset(nullptr);
5323 sctp_ready_to_send_data_ = false;
5324}
5325
5326void PeerConnection::OnSctpTransportReadyToSendData_n() {
5327 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5328 RTC_DCHECK(network_thread()->IsCurrent());
5329 // Note: Cannot use rtc::Bind here because it will grab a reference to
5330 // PeerConnection and potentially cause PeerConnection to live longer than
5331 // expected. It is safe not to grab a reference since the sctp_invoker_ will
5332 // be destroyed before PeerConnection is destroyed, and at that point all
5333 // pending tasks will be cleared.
5334 sctp_invoker_->AsyncInvoke<void>(RTC_FROM_HERE, signaling_thread(), [this] {
5335 OnSctpTransportReadyToSendData_s(true);
5336 });
5337}
5338
5339void PeerConnection::OnSctpTransportReadyToSendData_s(bool ready) {
5340 RTC_DCHECK(signaling_thread()->IsCurrent());
5341 sctp_ready_to_send_data_ = ready;
5342 SignalSctpReadyToSendData(ready);
5343}
5344
5345void PeerConnection::OnSctpTransportDataReceived_n(
5346 const cricket::ReceiveDataParams& params,
5347 const rtc::CopyOnWriteBuffer& payload) {
5348 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5349 RTC_DCHECK(network_thread()->IsCurrent());
5350 // Note: Cannot use rtc::Bind here because it will grab a reference to
5351 // PeerConnection and potentially cause PeerConnection to live longer than
5352 // expected. It is safe not to grab a reference since the sctp_invoker_ will
5353 // be destroyed before PeerConnection is destroyed, and at that point all
5354 // pending tasks will be cleared.
5355 sctp_invoker_->AsyncInvoke<void>(
5356 RTC_FROM_HERE, signaling_thread(), [this, params, payload] {
5357 OnSctpTransportDataReceived_s(params, payload);
5358 });
5359}
5360
5361void PeerConnection::OnSctpTransportDataReceived_s(
5362 const cricket::ReceiveDataParams& params,
5363 const rtc::CopyOnWriteBuffer& payload) {
5364 RTC_DCHECK(signaling_thread()->IsCurrent());
5365 if (params.type == cricket::DMT_CONTROL && IsOpenMessage(payload)) {
5366 // Received OPEN message; parse and signal that a new data channel should
5367 // be created.
5368 std::string label;
5369 InternalDataChannelInit config;
5370 config.id = params.ssrc;
5371 if (!ParseDataChannelOpenMessage(payload, &label, &config)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005372 RTC_LOG(LS_WARNING) << "Failed to parse the OPEN message for sid "
5373 << params.ssrc;
Steve Anton75737c02017-11-06 10:37:17 -08005374 return;
5375 }
5376 config.open_handshake_role = InternalDataChannelInit::kAcker;
5377 OnDataChannelOpenMessage(label, config);
5378 } else {
5379 // Otherwise just forward the signal.
5380 SignalSctpDataReceived(params, payload);
5381 }
5382}
5383
5384void PeerConnection::OnSctpStreamClosedRemotely_n(int sid) {
5385 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5386 RTC_DCHECK(network_thread()->IsCurrent());
5387 sctp_invoker_->AsyncInvoke<void>(
5388 RTC_FROM_HERE, signaling_thread(),
5389 rtc::Bind(&sigslot::signal1<int>::operator(),
5390 &SignalSctpStreamClosedRemotely, sid));
5391}
5392
5393// Returns false if bundle is enabled and rtcp_mux is disabled.
5394bool PeerConnection::ValidateBundleSettings(const SessionDescription* desc) {
5395 bool bundle_enabled = desc->HasGroup(cricket::GROUP_TYPE_BUNDLE);
5396 if (!bundle_enabled)
5397 return true;
5398
5399 const cricket::ContentGroup* bundle_group =
5400 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
5401 RTC_DCHECK(bundle_group != NULL);
5402
5403 const cricket::ContentInfos& contents = desc->contents();
5404 for (cricket::ContentInfos::const_iterator citer = contents.begin();
5405 citer != contents.end(); ++citer) {
5406 const cricket::ContentInfo* content = (&*citer);
5407 RTC_DCHECK(content != NULL);
5408 if (bundle_group->HasContentName(content->name) && !content->rejected &&
Steve Anton5adfafd2017-12-20 16:34:00 -08005409 content->type == MediaProtocolType::kRtp) {
Steve Anton75737c02017-11-06 10:37:17 -08005410 if (!HasRtcpMuxEnabled(content))
5411 return false;
5412 }
5413 }
5414 // RTCP-MUX is enabled in all the contents.
5415 return true;
5416}
5417
5418bool PeerConnection::HasRtcpMuxEnabled(const cricket::ContentInfo* content) {
Steve Antonb1c1de12017-12-21 15:14:30 -08005419 return content->media_description()->rtcp_mux();
Steve Anton75737c02017-11-06 10:37:17 -08005420}
5421
Steve Anton8a006912017-12-04 15:25:56 -08005422RTCError PeerConnection::ValidateSessionDescription(
Steve Anton75737c02017-11-06 10:37:17 -08005423 const SessionDescriptionInterface* sdesc,
Steve Anton8a006912017-12-04 15:25:56 -08005424 cricket::ContentSource source) {
Steve Antonf8470812017-12-04 10:46:21 -08005425 if (session_error() != SessionError::kNone) {
Steve Anton8a006912017-12-04 15:25:56 -08005426 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
Steve Anton75737c02017-11-06 10:37:17 -08005427 }
5428
5429 if (!sdesc || !sdesc->description()) {
Steve Anton8a006912017-12-04 15:25:56 -08005430 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidSdp);
Steve Anton75737c02017-11-06 10:37:17 -08005431 }
5432
Steve Anton3828c062017-12-06 10:34:51 -08005433 SdpType type = sdesc->GetType();
5434 if ((source == cricket::CS_LOCAL && !ExpectSetLocalDescription(type)) ||
5435 (source == cricket::CS_REMOTE && !ExpectSetRemoteDescription(type))) {
Steve Anton8a006912017-12-04 15:25:56 -08005436 LOG_AND_RETURN_ERROR(
5437 RTCErrorType::INVALID_PARAMETER,
5438 "Called in wrong state: " + GetSignalingStateString(signaling_state()));
Steve Anton75737c02017-11-06 10:37:17 -08005439 }
5440
5441 // Verify crypto settings.
5442 std::string crypto_error;
Steve Anton8a006912017-12-04 15:25:56 -08005443 if (webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED ||
5444 dtls_enabled_) {
Harald Alvestrand194939b2018-01-24 16:04:13 +01005445 RTCError crypto_error =
5446 VerifyCrypto(sdesc->description(), dtls_enabled_, uma_observer_);
Steve Anton8a006912017-12-04 15:25:56 -08005447 if (!crypto_error.ok()) {
5448 return crypto_error;
5449 }
Steve Anton75737c02017-11-06 10:37:17 -08005450 }
5451
5452 // Verify ice-ufrag and ice-pwd.
5453 if (!VerifyIceUfragPwdPresent(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08005454 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5455 kSdpWithoutIceUfragPwd);
Steve Anton75737c02017-11-06 10:37:17 -08005456 }
5457
5458 if (!ValidateBundleSettings(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08005459 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5460 kBundleWithoutRtcpMux);
Steve Anton75737c02017-11-06 10:37:17 -08005461 }
5462
5463 // TODO(skvlad): When the local rtcp-mux policy is Require, reject any
5464 // m-lines that do not rtcp-mux enabled.
5465
5466 // Verify m-lines in Answer when compared against Offer.
Steve Anton3828c062017-12-06 10:34:51 -08005467 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Anton75737c02017-11-06 10:37:17 -08005468 const cricket::SessionDescription* offer_desc =
5469 (source == cricket::CS_LOCAL) ? remote_description()->description()
5470 : local_description()->description();
5471 if (!MediaSectionsHaveSameCount(offer_desc, sdesc->description()) ||
5472 !MediaSectionsInSameOrder(offer_desc, sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08005473 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5474 kMlineMismatchInAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08005475 }
5476 } else {
5477 const cricket::SessionDescription* current_desc = nullptr;
5478 if (source == cricket::CS_LOCAL && local_description()) {
5479 current_desc = local_description()->description();
5480 } else if (source == cricket::CS_REMOTE && remote_description()) {
5481 current_desc = remote_description()->description();
5482 }
5483 // The re-offers should respect the order of m= sections in current
5484 // description. See RFC3264 Section 8 paragraph 4 for more details.
5485 if (current_desc &&
5486 !MediaSectionsInSameOrder(current_desc, sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08005487 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5488 kMlineMismatchInSubsequentOffer);
Steve Anton75737c02017-11-06 10:37:17 -08005489 }
5490 }
5491
Steve Anton8a006912017-12-04 15:25:56 -08005492 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08005493}
5494
Steve Anton3828c062017-12-06 10:34:51 -08005495bool PeerConnection::ExpectSetLocalDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08005496 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08005497 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08005498 return (state == PeerConnectionInterface::kStable) ||
5499 (state == PeerConnectionInterface::kHaveLocalOffer);
Steve Anton20393062017-12-04 16:24:52 -08005500 } else {
Steve Anton3828c062017-12-06 10:34:51 -08005501 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08005502 return (state == PeerConnectionInterface::kHaveRemoteOffer) ||
5503 (state == PeerConnectionInterface::kHaveLocalPrAnswer);
5504 }
5505}
5506
Steve Anton3828c062017-12-06 10:34:51 -08005507bool PeerConnection::ExpectSetRemoteDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08005508 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08005509 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08005510 return (state == PeerConnectionInterface::kStable) ||
5511 (state == PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton20393062017-12-04 16:24:52 -08005512 } else {
Steve Anton3828c062017-12-06 10:34:51 -08005513 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08005514 return (state == PeerConnectionInterface::kHaveLocalOffer) ||
5515 (state == PeerConnectionInterface::kHaveRemotePrAnswer);
5516 }
5517}
5518
Steve Antonf8470812017-12-04 10:46:21 -08005519const char* PeerConnection::SessionErrorToString(SessionError error) const {
5520 switch (error) {
5521 case SessionError::kNone:
5522 return "ERROR_NONE";
5523 case SessionError::kContent:
5524 return "ERROR_CONTENT";
5525 case SessionError::kTransport:
5526 return "ERROR_TRANSPORT";
5527 }
5528 RTC_NOTREACHED();
5529 return "";
5530}
5531
Steve Anton75737c02017-11-06 10:37:17 -08005532std::string PeerConnection::GetSessionErrorMsg() {
5533 std::ostringstream desc;
Steve Antonf8470812017-12-04 10:46:21 -08005534 desc << kSessionError << SessionErrorToString(session_error()) << ". ";
5535 desc << kSessionErrorDesc << session_error_desc() << ".";
Steve Anton75737c02017-11-06 10:37:17 -08005536 return desc.str();
5537}
5538
5539// We need to check the local/remote description for the Transport instead of
5540// the session, because a new Transport added during renegotiation may have
5541// them unset while the session has them set from the previous negotiation.
5542// Not doing so may trigger the auto generation of transport description and
5543// mess up DTLS identity information, ICE credential, etc.
5544bool PeerConnection::ReadyToUseRemoteCandidate(
5545 const IceCandidateInterface* candidate,
5546 const SessionDescriptionInterface* remote_desc,
5547 bool* valid) {
5548 *valid = true;
5549
5550 const SessionDescriptionInterface* current_remote_desc =
5551 remote_desc ? remote_desc : remote_description();
5552
5553 if (!current_remote_desc) {
5554 return false;
5555 }
5556
5557 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
5558 size_t remote_content_size =
5559 current_remote_desc->description()->contents().size();
5560 if (mediacontent_index >= remote_content_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005561 RTC_LOG(LS_ERROR)
5562 << "ReadyToUseRemoteCandidate: Invalid candidate media index "
5563 << mediacontent_index;
Steve Anton75737c02017-11-06 10:37:17 -08005564
5565 *valid = false;
5566 return false;
5567 }
5568
5569 cricket::ContentInfo content =
5570 current_remote_desc->description()->contents()[mediacontent_index];
5571
5572 const std::string transport_name = GetTransportName(content.name);
5573 if (transport_name.empty()) {
5574 return false;
5575 }
5576 return transport_controller_->ReadyForRemoteCandidates(transport_name);
5577}
5578
5579bool PeerConnection::SrtpRequired() const {
5580 return dtls_enabled_ ||
5581 webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED;
5582}
5583
5584void PeerConnection::OnTransportControllerGatheringState(
5585 cricket::IceGatheringState state) {
5586 RTC_DCHECK(signaling_thread()->IsCurrent());
5587 if (state == cricket::kIceGatheringGathering) {
5588 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringGathering);
5589 } else if (state == cricket::kIceGatheringComplete) {
5590 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringComplete);
5591 }
5592}
5593
5594void PeerConnection::ReportTransportStats() {
5595 // Use a set so we don't report the same stats twice if two channels share
5596 // a transport.
5597 std::set<std::string> transport_names;
5598 if (voice_channel()) {
5599 transport_names.insert(voice_channel()->transport_name());
5600 }
5601 if (video_channel()) {
5602 transport_names.insert(video_channel()->transport_name());
5603 }
5604 if (rtp_data_channel()) {
5605 transport_names.insert(rtp_data_channel()->transport_name());
5606 }
5607 if (sctp_transport_name_) {
5608 transport_names.insert(*sctp_transport_name_);
5609 }
5610 for (const auto& name : transport_names) {
5611 cricket::TransportStats stats;
5612 if (transport_controller_->GetStats(name, &stats)) {
5613 ReportBestConnectionState(stats);
5614 ReportNegotiatedCiphers(stats);
5615 }
5616 }
5617}
5618// Walk through the ConnectionInfos to gather best connection usage
5619// for IPv4 and IPv6.
5620void PeerConnection::ReportBestConnectionState(
5621 const cricket::TransportStats& stats) {
5622 RTC_DCHECK(metrics_observer());
5623 for (cricket::TransportChannelStatsList::const_iterator it =
5624 stats.channel_stats.begin();
5625 it != stats.channel_stats.end(); ++it) {
5626 for (cricket::ConnectionInfos::const_iterator it_info =
5627 it->connection_infos.begin();
5628 it_info != it->connection_infos.end(); ++it_info) {
5629 if (!it_info->best_connection) {
5630 continue;
5631 }
5632
5633 PeerConnectionEnumCounterType type = kPeerConnectionEnumCounterMax;
5634 const cricket::Candidate& local = it_info->local_candidate;
5635 const cricket::Candidate& remote = it_info->remote_candidate;
5636
5637 // Increment the counter for IceCandidatePairType.
5638 if (local.protocol() == cricket::TCP_PROTOCOL_NAME ||
5639 (local.type() == RELAY_PORT_TYPE &&
5640 local.relay_protocol() == cricket::TCP_PROTOCOL_NAME)) {
5641 type = kEnumCounterIceCandidatePairTypeTcp;
5642 } else if (local.protocol() == cricket::UDP_PROTOCOL_NAME) {
5643 type = kEnumCounterIceCandidatePairTypeUdp;
5644 } else {
5645 RTC_CHECK(0);
5646 }
5647 metrics_observer()->IncrementEnumCounter(
5648 type, GetIceCandidatePairCounter(local, remote),
5649 kIceCandidatePairMax);
5650
5651 // Increment the counter for IP type.
5652 if (local.address().family() == AF_INET) {
5653 metrics_observer()->IncrementEnumCounter(
5654 kEnumCounterAddressFamily, kBestConnections_IPv4,
5655 kPeerConnectionAddressFamilyCounter_Max);
5656
5657 } else if (local.address().family() == AF_INET6) {
5658 metrics_observer()->IncrementEnumCounter(
5659 kEnumCounterAddressFamily, kBestConnections_IPv6,
5660 kPeerConnectionAddressFamilyCounter_Max);
5661 } else {
5662 RTC_CHECK(0);
5663 }
5664
5665 return;
5666 }
5667 }
5668}
5669
5670void PeerConnection::ReportNegotiatedCiphers(
5671 const cricket::TransportStats& stats) {
5672 RTC_DCHECK(metrics_observer());
5673 if (!dtls_enabled_ || stats.channel_stats.empty()) {
5674 return;
5675 }
5676
5677 int srtp_crypto_suite = stats.channel_stats[0].srtp_crypto_suite;
5678 int ssl_cipher_suite = stats.channel_stats[0].ssl_cipher_suite;
5679 if (srtp_crypto_suite == rtc::SRTP_INVALID_CRYPTO_SUITE &&
5680 ssl_cipher_suite == rtc::TLS_NULL_WITH_NULL_NULL) {
5681 return;
5682 }
5683
5684 PeerConnectionEnumCounterType srtp_counter_type;
5685 PeerConnectionEnumCounterType ssl_counter_type;
5686 if (stats.transport_name == cricket::CN_AUDIO) {
5687 srtp_counter_type = kEnumCounterAudioSrtpCipher;
5688 ssl_counter_type = kEnumCounterAudioSslCipher;
5689 } else if (stats.transport_name == cricket::CN_VIDEO) {
5690 srtp_counter_type = kEnumCounterVideoSrtpCipher;
5691 ssl_counter_type = kEnumCounterVideoSslCipher;
5692 } else if (stats.transport_name == cricket::CN_DATA) {
5693 srtp_counter_type = kEnumCounterDataSrtpCipher;
5694 ssl_counter_type = kEnumCounterDataSslCipher;
5695 } else {
5696 RTC_NOTREACHED();
5697 return;
5698 }
5699
5700 if (srtp_crypto_suite != rtc::SRTP_INVALID_CRYPTO_SUITE) {
5701 metrics_observer()->IncrementSparseEnumCounter(srtp_counter_type,
5702 srtp_crypto_suite);
5703 }
5704 if (ssl_cipher_suite != rtc::TLS_NULL_WITH_NULL_NULL) {
5705 metrics_observer()->IncrementSparseEnumCounter(ssl_counter_type,
5706 ssl_cipher_suite);
5707 }
5708}
5709
5710void PeerConnection::OnSentPacket_w(const rtc::SentPacket& sent_packet) {
5711 RTC_DCHECK(worker_thread()->IsCurrent());
5712 RTC_DCHECK(call_);
5713 call_->OnSentPacket(sent_packet);
5714}
5715
5716const std::string PeerConnection::GetTransportName(
5717 const std::string& content_name) {
5718 cricket::BaseChannel* channel = GetChannel(content_name);
Steve Anton6fec8802017-12-04 10:37:29 -08005719 if (channel) {
5720 return channel->transport_name();
Steve Anton75737c02017-11-06 10:37:17 -08005721 }
Steve Anton6fec8802017-12-04 10:37:29 -08005722 if (sctp_transport_) {
5723 RTC_DCHECK(sctp_content_name_);
5724 RTC_DCHECK(sctp_transport_name_);
5725 if (content_name == *sctp_content_name_) {
5726 return *sctp_transport_name_;
5727 }
5728 }
5729 // Return an empty string if failed to retrieve the transport name.
5730 return "";
Steve Anton75737c02017-11-06 10:37:17 -08005731}
5732
5733void PeerConnection::DestroyRtcpTransport_n(const std::string& transport_name) {
5734 RTC_DCHECK(network_thread()->IsCurrent());
5735 transport_controller_->DestroyDtlsTransport_n(
5736 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
5737}
5738
Steve Anton6fec8802017-12-04 10:37:29 -08005739void PeerConnection::DestroyTransceiverChannel(
5740 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
5741 transceiver) {
5742 RTC_DCHECK(transceiver);
Steve Anton75737c02017-11-06 10:37:17 -08005743
Steve Anton6fec8802017-12-04 10:37:29 -08005744 cricket::BaseChannel* channel = transceiver->internal()->channel();
5745 if (channel) {
5746 transceiver->internal()->SetChannel(nullptr);
5747 DestroyBaseChannel(channel);
Steve Anton75737c02017-11-06 10:37:17 -08005748 }
5749}
5750
5751void PeerConnection::DestroyDataChannel() {
Steve Anton6fec8802017-12-04 10:37:29 -08005752 if (rtp_data_channel_) {
5753 OnDataChannelDestroyed();
5754 DestroyBaseChannel(rtp_data_channel_);
5755 rtp_data_channel_ = nullptr;
5756 }
5757
5758 // Note: Cannot use rtc::Bind to create a functor to invoke because it will
5759 // grab a reference to this PeerConnection. If this is called from the
5760 // PeerConnection destructor, the RefCountedObject vtable will have already
5761 // been destroyed (since it is a subclass of PeerConnection) and using
5762 // rtc::Bind will cause "Pure virtual function called" error to appear.
5763
5764 if (sctp_transport_) {
5765 OnDataChannelDestroyed();
5766 network_thread()->Invoke<void>(RTC_FROM_HERE,
5767 [this] { DestroySctpTransport_n(); });
5768 }
5769}
5770
5771void PeerConnection::DestroyBaseChannel(cricket::BaseChannel* channel) {
5772 RTC_DCHECK(channel);
5773 RTC_DCHECK(channel->rtp_dtls_transport());
5774
5775 // Need to cache these before destroying the base channel so that we do not
5776 // access uninitialized memory.
5777 const std::string transport_name =
5778 channel->rtp_dtls_transport()->transport_name();
5779 const bool need_to_delete_rtcp = (channel->rtcp_dtls_transport() != nullptr);
5780
5781 switch (channel->media_type()) {
5782 case cricket::MEDIA_TYPE_AUDIO:
5783 channel_manager()->DestroyVoiceChannel(
5784 static_cast<cricket::VoiceChannel*>(channel));
5785 break;
5786 case cricket::MEDIA_TYPE_VIDEO:
5787 channel_manager()->DestroyVideoChannel(
5788 static_cast<cricket::VideoChannel*>(channel));
5789 break;
5790 case cricket::MEDIA_TYPE_DATA:
5791 channel_manager()->DestroyRtpDataChannel(
5792 static_cast<cricket::RtpDataChannel*>(channel));
5793 break;
5794 default:
5795 RTC_NOTREACHED() << "Unknown media type: " << channel->media_type();
5796 break;
5797 }
5798
5799 // |channel| can no longer be used.
5800
Steve Anton75737c02017-11-06 10:37:17 -08005801 transport_controller_->DestroyDtlsTransport(
5802 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5803 if (need_to_delete_rtcp) {
5804 transport_controller_->DestroyDtlsTransport(
5805 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
5806 }
5807}
5808
Harald Alvestrand89061872018-01-02 14:08:34 +01005809void PeerConnection::ClearStatsCache() {
5810 if (stats_collector_) {
5811 stats_collector_->ClearCachedStatsReport();
5812 }
5813}
5814
henrike@webrtc.org28e20752013-07-10 00:45:36 +00005815} // namespace webrtc