blob: 4758f4f62c3fbe3d40cb1c44c2f91e226585e6c2 [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
Steve Anton7b581eb2018-02-01 11:32:31 -08001677 if (!(signaling_state_ == kHaveRemoteOffer ||
1678 signaling_state_ == kHaveLocalPrAnswer)) {
1679 std::string error =
1680 "CreateAnswer called when PeerConnection is in a wrong state.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001681 RTC_LOG(LS_ERROR) << error;
Steve Anton8d3444d2017-10-20 15:30:51 -07001682 PostCreateSessionDescriptionFailure(observer, error);
1683 return;
1684 }
1685
Steve Anton7b581eb2018-02-01 11:32:31 -08001686 // The remote description should be set if we're in the right state.
1687 RTC_DCHECK(remote_description());
Steve Anton8d3444d2017-10-20 15:30:51 -07001688
Steve Anton22da89f2018-01-25 13:58:07 -08001689 if (IsUnifiedPlan()) {
1690 if (options.offer_to_receive_audio != RTCOfferAnswerOptions::kUndefined) {
1691 RTC_LOG(LS_WARNING) << "CreateAnswer: offer_to_receive_audio is not "
1692 "supported with Unified Plan semantics. Use the "
1693 "RtpTransceiver API instead.";
1694 }
1695 if (options.offer_to_receive_video != RTCOfferAnswerOptions::kUndefined) {
1696 RTC_LOG(LS_WARNING) << "CreateAnswer: offer_to_receive_video is not "
1697 "supported with Unified Plan semantics. Use the "
1698 "RtpTransceiver API instead.";
1699 }
1700 }
1701
htaa2a49d92016-03-04 02:51:39 -08001702 cricket::MediaSessionOptions session_options;
zhihuang1c378ed2017-08-17 14:10:50 -07001703 GetOptionsForAnswer(options, &session_options);
htaa2a49d92016-03-04 02:51:39 -08001704
Steve Antond25da372017-11-06 14:50:29 -08001705 webrtc_session_desc_factory_->CreateAnswer(observer, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001706}
1707
1708void PeerConnection::SetLocalDescription(
1709 SetSessionDescriptionObserver* observer,
1710 SessionDescriptionInterface* desc) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001711 TRACE_EVENT0("webrtc", "PeerConnection::SetLocalDescription");
Steve Anton8a006912017-12-04 15:25:56 -08001712
nisse7ce109a2017-01-31 00:57:56 -08001713 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001714 RTC_LOG(LS_ERROR) << "SetLocalDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001715 return;
1716 }
Steve Anton8a006912017-12-04 15:25:56 -08001717
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001718 if (!desc) {
1719 PostSetSessionDescriptionFailure(observer, "SessionDescription is NULL.");
1720 return;
1721 }
Steve Anton8d3444d2017-10-20 15:30:51 -07001722
Steve Antona3a92c22017-12-07 10:27:41 -08001723 SdpType type = desc->GetType();
Steve Anton8d3444d2017-10-20 15:30:51 -07001724
Steve Anton8a006912017-12-04 15:25:56 -08001725 RTCError error = ApplyLocalDescription(rtc::WrapUnique(desc));
1726 // |desc| may be destroyed at this point.
1727
1728 if (!error.ok()) {
Steve Antona3a92c22017-12-07 10:27:41 -08001729 std::ostringstream oss;
1730 oss << "Failed to set local " << SdpTypeToString(type)
1731 << " sdp: " << error.message();
1732 std::string error_message = oss.str();
Steve Anton8a006912017-12-04 15:25:56 -08001733 RTC_LOG(LS_ERROR) << error_message << " (" << error.type() << ")";
1734 PostSetSessionDescriptionFailure(observer, std::move(error_message));
Steve Anton8d3444d2017-10-20 15:30:51 -07001735 return;
1736 }
Steve Anton8a006912017-12-04 15:25:56 -08001737 RTC_DCHECK(local_description());
1738
1739 PostSetSessionDescriptionSuccess(observer);
1740
1741 // According to JSEP, after setLocalDescription, changing the candidate pool
1742 // size is not allowed, and changing the set of ICE servers will not result
1743 // in new candidates being gathered.
1744 port_allocator_->FreezeCandidatePool();
1745
1746 // MaybeStartGathering needs to be called after posting
1747 // MSG_SET_SESSIONDESCRIPTION_SUCCESS, so that we don't signal any candidates
1748 // before signaling that SetLocalDescription completed.
1749 transport_controller_->MaybeStartGathering();
1750
Steve Antona3a92c22017-12-07 10:27:41 -08001751 if (local_description()->GetType() == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08001752 // TODO(deadbeef): We already had to hop to the network thread for
1753 // MaybeStartGathering...
1754 network_thread()->Invoke<void>(
1755 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
1756 port_allocator_.get()));
1757 }
1758}
1759
1760RTCError PeerConnection::ApplyLocalDescription(
1761 std::unique_ptr<SessionDescriptionInterface> desc) {
1762 RTC_DCHECK_RUN_ON(signaling_thread());
1763 RTC_DCHECK(desc);
1764
1765 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_LOCAL);
1766 if (!error.ok()) {
1767 return error;
1768 }
Steve Anton8d3444d2017-10-20 15:30:51 -07001769
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001770 // Update stats here so that we have the most recent stats for tracks and
1771 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001772 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 15:25:56 -08001773
1774 // Update the initial_offerer flag if this session is the initial_offerer.
Steve Anton3828c062017-12-06 10:34:51 -08001775 SdpType type = desc->GetType();
Steve Anton8a006912017-12-04 15:25:56 -08001776 if (!initial_offerer_.has_value()) {
Steve Anton3828c062017-12-06 10:34:51 -08001777 initial_offerer_.emplace(type == SdpType::kOffer);
Steve Anton8a006912017-12-04 15:25:56 -08001778 if (*initial_offerer_) {
1779 transport_controller_->SetIceRole(cricket::ICEROLE_CONTROLLING);
1780 } else {
1781 transport_controller_->SetIceRole(cricket::ICEROLE_CONTROLLED);
1782 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001783 }
Steve Anton8a006912017-12-04 15:25:56 -08001784
Steve Antondcc3c022017-12-22 16:02:54 -08001785 // Take a reference to the old local description since it's used below to
1786 // compare against the new local description. When setting the new local
1787 // description, grab ownership of the replaced session description in case it
1788 // is the same as |old_local_description|, to keep it alive for the duration
1789 // of the method.
1790 const SessionDescriptionInterface* old_local_description =
1791 local_description();
1792 std::unique_ptr<SessionDescriptionInterface> replaced_local_description;
Steve Anton3828c062017-12-06 10:34:51 -08001793 if (type == SdpType::kAnswer) {
Steve Antondcc3c022017-12-22 16:02:54 -08001794 replaced_local_description = pending_local_description_
1795 ? std::move(pending_local_description_)
1796 : std::move(current_local_description_);
Steve Anton8a006912017-12-04 15:25:56 -08001797 current_local_description_ = std::move(desc);
1798 pending_local_description_ = nullptr;
1799 current_remote_description_ = std::move(pending_remote_description_);
1800 } else {
Steve Antondcc3c022017-12-22 16:02:54 -08001801 replaced_local_description = std::move(pending_local_description_);
Steve Anton8a006912017-12-04 15:25:56 -08001802 pending_local_description_ = std::move(desc);
1803 }
1804 // The session description to apply now must be accessed by
1805 // |local_description()|.
Henrik Boströmfdb92012017-11-09 19:55:44 +01001806 RTC_DCHECK(local_description());
deadbeefab9b2d12015-10-14 11:33:11 -07001807
Steve Antondcc3c022017-12-22 16:02:54 -08001808 if (IsUnifiedPlan()) {
1809 RTCError error = UpdateTransceiversAndDataChannels(
1810 cricket::CS_LOCAL, old_local_description, *local_description());
Steve Anton8a006912017-12-04 15:25:56 -08001811 if (!error.ok()) {
1812 return error;
1813 }
Steve Antondcc3c022017-12-22 16:02:54 -08001814 for (auto transceiver : transceivers_) {
1815 const ContentInfo* content =
1816 FindMediaSectionForTransceiver(transceiver, local_description());
1817 if (!content) {
1818 continue;
1819 }
1820 const MediaContentDescription* media_desc = content->media_description();
1821 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
1822 transceiver->internal()->set_current_direction(media_desc->direction());
1823 }
1824 if (content->rejected && !transceiver->stopped()) {
1825 transceiver->Stop();
1826 }
1827 }
1828 } else {
1829 // Transport and Media channels will be created only when offer is set.
1830 if (type == SdpType::kOffer) {
1831 // TODO(bugs.webrtc.org/4676) - Handle CreateChannel failure, as new local
1832 // description is applied. Restore back to old description.
1833 RTCError error = CreateChannels(*local_description()->description());
1834 if (!error.ok()) {
1835 return error;
1836 }
1837 }
Steve Anton8a006912017-12-04 15:25:56 -08001838
Steve Antondcc3c022017-12-22 16:02:54 -08001839 // Remove unused channels if MediaContentDescription is rejected.
1840 RemoveUnusedChannels(local_description()->description());
1841 }
Steve Anton8a006912017-12-04 15:25:56 -08001842
Steve Anton3828c062017-12-06 10:34:51 -08001843 error = UpdateSessionState(type, cricket::CS_LOCAL);
Steve Anton8a006912017-12-04 15:25:56 -08001844 if (!error.ok()) {
1845 return error;
1846 }
Steve Antondcc3c022017-12-22 16:02:54 -08001847
Steve Anton8a006912017-12-04 15:25:56 -08001848 if (remote_description()) {
1849 // Now that we have a local description, we can push down remote candidates.
1850 UseCandidatesInSessionDescription(remote_description());
1851 }
1852
1853 pending_ice_restarts_.clear();
1854 if (session_error() != SessionError::kNone) {
1855 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
1856 }
1857
deadbeefab9b2d12015-10-14 11:33:11 -07001858 // If setting the description decided our SSL role, allocate any necessary
1859 // SCTP sids.
1860 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08001861 if (data_channel_type() == cricket::DCT_SCTP && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001862 AllocateSctpSids(role);
1863 }
1864
Steve Antond3679212018-01-17 17:41:02 -08001865 if (IsUnifiedPlan()) {
1866 for (auto transceiver : transceivers_) {
1867 const ContentInfo* content =
1868 FindMediaSectionForTransceiver(transceiver, local_description());
1869 if (!content) {
1870 continue;
1871 }
1872 if (content->rejected && !transceiver->stopped()) {
1873 transceiver->Stop();
1874 }
Steve Anton74255ff2018-01-24 18:32:57 -08001875 const auto& streams = content->media_description()->streams();
1876 if (!content->rejected && !streams.empty()) {
Steve Antond3679212018-01-17 17:41:02 -08001877 transceiver->internal()->sender_internal()->set_stream_ids(
Steve Anton74255ff2018-01-24 18:32:57 -08001878 {streams[0].sync_label});
Steve Antond3679212018-01-17 17:41:02 -08001879 transceiver->internal()->sender_internal()->SetSsrc(
Steve Anton74255ff2018-01-24 18:32:57 -08001880 streams[0].first_ssrc());
Steve Antond3679212018-01-17 17:41:02 -08001881 }
1882 }
1883 } else {
1884 // Plan B semantics.
1885
Steve Antondcc3c022017-12-22 16:02:54 -08001886 // Update state and SSRC of local MediaStreams and DataChannels based on the
1887 // local session description.
1888 const cricket::ContentInfo* audio_content =
1889 GetFirstAudioContent(local_description()->description());
1890 if (audio_content) {
1891 if (audio_content->rejected) {
1892 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
1893 } else {
1894 const cricket::AudioContentDescription* audio_desc =
1895 audio_content->media_description()->as_audio();
1896 UpdateLocalSenders(audio_desc->streams(), audio_desc->type());
1897 }
deadbeeffaac4972015-11-12 15:33:07 -08001898 }
deadbeefab9b2d12015-10-14 11:33:11 -07001899
Steve Antondcc3c022017-12-22 16:02:54 -08001900 const cricket::ContentInfo* video_content =
1901 GetFirstVideoContent(local_description()->description());
1902 if (video_content) {
1903 if (video_content->rejected) {
1904 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
1905 } else {
1906 const cricket::VideoContentDescription* video_desc =
1907 video_content->media_description()->as_video();
1908 UpdateLocalSenders(video_desc->streams(), video_desc->type());
1909 }
deadbeeffaac4972015-11-12 15:33:07 -08001910 }
deadbeefab9b2d12015-10-14 11:33:11 -07001911 }
1912
1913 const cricket::ContentInfo* data_content =
Henrik Boströmfdb92012017-11-09 19:55:44 +01001914 GetFirstDataContent(local_description()->description());
deadbeefab9b2d12015-10-14 11:33:11 -07001915 if (data_content) {
1916 const cricket::DataContentDescription* data_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08001917 data_content->media_description()->as_data();
deadbeefab9b2d12015-10-14 11:33:11 -07001918 if (rtc::starts_with(data_desc->protocol().data(),
1919 cricket::kMediaProtocolRtpPrefix)) {
1920 UpdateLocalRtpDataChannels(data_desc->streams());
1921 }
1922 }
1923
Steve Anton8a006912017-12-04 15:25:56 -08001924 return RTCError::OK();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001925}
1926
1927void PeerConnection::SetRemoteDescription(
Henrik Boströma4ecf552017-11-23 14:17:07 +00001928 SetSessionDescriptionObserver* observer,
1929 SessionDescriptionInterface* desc) {
Henrik Boström31638672017-11-23 17:48:32 +01001930 SetRemoteDescription(
1931 std::unique_ptr<SessionDescriptionInterface>(desc),
1932 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface>(
1933 new SetRemoteDescriptionObserverAdapter(this, observer)));
1934}
1935
1936void PeerConnection::SetRemoteDescription(
1937 std::unique_ptr<SessionDescriptionInterface> desc,
1938 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface> observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001939 TRACE_EVENT0("webrtc", "PeerConnection::SetRemoteDescription");
Steve Anton8a006912017-12-04 15:25:56 -08001940
nisse7ce109a2017-01-31 00:57:56 -08001941 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001942 RTC_LOG(LS_ERROR) << "SetRemoteDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001943 return;
1944 }
Steve Anton8a006912017-12-04 15:25:56 -08001945
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001946 if (!desc) {
Henrik Boström31638672017-11-23 17:48:32 +01001947 observer->OnSetRemoteDescriptionComplete(RTCError(
Steve Anton8a006912017-12-04 15:25:56 -08001948 RTCErrorType::INVALID_PARAMETER, "SessionDescription is NULL."));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001949 return;
1950 }
Steve Anton8d3444d2017-10-20 15:30:51 -07001951
Steve Antona3a92c22017-12-07 10:27:41 -08001952 const SdpType type = desc->GetType();
Steve Anton8a006912017-12-04 15:25:56 -08001953
1954 RTCError error = ApplyRemoteDescription(std::move(desc));
1955 // |desc| may be destroyed at this point.
1956
1957 if (!error.ok()) {
Steve Antona3a92c22017-12-07 10:27:41 -08001958 std::ostringstream oss;
1959 oss << "Failed to set remote " << SdpTypeToString(type)
1960 << " sdp: " << error.message();
1961 std::string error_message = oss.str();
Steve Anton8a006912017-12-04 15:25:56 -08001962 RTC_LOG(LS_ERROR) << error_message << " (" << error.type() << ")";
Henrik Boström31638672017-11-23 17:48:32 +01001963 observer->OnSetRemoteDescriptionComplete(
Steve Anton8a006912017-12-04 15:25:56 -08001964 RTCError(error.type(), std::move(error_message)));
Steve Anton8d3444d2017-10-20 15:30:51 -07001965 return;
1966 }
1967
Steve Antona3a92c22017-12-07 10:27:41 -08001968 if (remote_description()->GetType() == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08001969 // TODO(deadbeef): We already had to hop to the network thread for
1970 // MaybeStartGathering...
1971 network_thread()->Invoke<void>(
1972 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
1973 port_allocator_.get()));
1974 }
1975
1976 observer->OnSetRemoteDescriptionComplete(RTCError::OK());
1977}
1978
1979RTCError PeerConnection::ApplyRemoteDescription(
1980 std::unique_ptr<SessionDescriptionInterface> desc) {
1981 RTC_DCHECK_RUN_ON(signaling_thread());
1982 RTC_DCHECK(desc);
1983
1984 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_REMOTE);
1985 if (!error.ok()) {
1986 return error;
1987 }
1988
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001989 // Update stats here so that we have the most recent stats for tracks and
1990 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001991 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 15:25:56 -08001992
Steve Antondcc3c022017-12-22 16:02:54 -08001993 // Take a reference to the old remote description since it's used below to
1994 // compare against the new remote description. When setting the new remote
1995 // description, grab ownership of the replaced session description in case it
1996 // is the same as |old_remote_description|, to keep it alive for the duration
1997 // of the method.
Steve Anton8a006912017-12-04 15:25:56 -08001998 const SessionDescriptionInterface* old_remote_description =
1999 remote_description();
Steve Anton8a006912017-12-04 15:25:56 -08002000 std::unique_ptr<SessionDescriptionInterface> replaced_remote_description;
Steve Anton3828c062017-12-06 10:34:51 -08002001 SdpType type = desc->GetType();
2002 if (type == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002003 replaced_remote_description = pending_remote_description_
2004 ? std::move(pending_remote_description_)
2005 : std::move(current_remote_description_);
2006 current_remote_description_ = std::move(desc);
2007 pending_remote_description_ = nullptr;
2008 current_local_description_ = std::move(pending_local_description_);
2009 } else {
2010 replaced_remote_description = std::move(pending_remote_description_);
2011 pending_remote_description_ = std::move(desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002012 }
Steve Anton8a006912017-12-04 15:25:56 -08002013 // The session description to apply now must be accessed by
2014 // |remote_description()|.
Henrik Boströmfdb92012017-11-09 19:55:44 +01002015 RTC_DCHECK(remote_description());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002016
Steve Anton8a006912017-12-04 15:25:56 -08002017 // Transport and Media channels will be created only when offer is set.
Steve Antondcc3c022017-12-22 16:02:54 -08002018 if (IsUnifiedPlan()) {
2019 RTCError error = UpdateTransceiversAndDataChannels(
2020 cricket::CS_REMOTE, old_remote_description, *remote_description());
Steve Anton8a006912017-12-04 15:25:56 -08002021 if (!error.ok()) {
2022 return error;
2023 }
Steve Antondcc3c022017-12-22 16:02:54 -08002024 } else {
2025 if (type == SdpType::kOffer) {
2026 // TODO(bugs.webrtc.org/4676) - Handle CreateChannel failure, as new local
2027 // description is applied. Restore back to old description.
2028 RTCError error = CreateChannels(*remote_description()->description());
2029 if (!error.ok()) {
2030 return error;
2031 }
2032 }
Steve Anton8a006912017-12-04 15:25:56 -08002033
Steve Antondcc3c022017-12-22 16:02:54 -08002034 // Remove unused channels if MediaContentDescription is rejected.
2035 RemoveUnusedChannels(remote_description()->description());
2036 }
Steve Anton8a006912017-12-04 15:25:56 -08002037
2038 // NOTE: Candidates allocation will be initiated only when SetLocalDescription
2039 // is called.
Steve Anton3828c062017-12-06 10:34:51 -08002040 error = UpdateSessionState(type, cricket::CS_REMOTE);
Steve Anton8a006912017-12-04 15:25:56 -08002041 if (!error.ok()) {
2042 return error;
2043 }
2044
2045 if (local_description() &&
2046 !UseCandidatesInSessionDescription(remote_description())) {
2047 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidCandidates);
2048 }
2049
2050 if (old_remote_description) {
2051 for (const cricket::ContentInfo& content :
2052 old_remote_description->description()->contents()) {
2053 // Check if this new SessionDescription contains new ICE ufrag and
2054 // password that indicates the remote peer requests an ICE restart.
2055 // TODO(deadbeef): When we start storing both the current and pending
2056 // remote description, this should reset pending_ice_restarts and compare
2057 // against the current description.
2058 if (CheckForRemoteIceRestart(old_remote_description, remote_description(),
2059 content.name)) {
Steve Anton3828c062017-12-06 10:34:51 -08002060 if (type == SdpType::kOffer) {
Steve Anton8a006912017-12-04 15:25:56 -08002061 pending_ice_restarts_.insert(content.name);
2062 }
2063 } else {
2064 // We retain all received candidates only if ICE is not restarted.
2065 // When ICE is restarted, all previous candidates belong to an old
2066 // generation and should not be kept.
2067 // TODO(deadbeef): This goes against the W3C spec which says the remote
2068 // description should only contain candidates from the last set remote
2069 // description plus any candidates added since then. We should remove
2070 // this once we're sure it won't break anything.
2071 WebRtcSessionDescriptionFactory::CopyCandidatesFromSessionDescription(
2072 old_remote_description, content.name, mutable_remote_description());
2073 }
2074 }
2075 }
2076
2077 if (session_error() != SessionError::kNone) {
2078 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
2079 }
2080
2081 // Set the the ICE connection state to connecting since the connection may
2082 // become writable with peer reflexive candidates before any remote candidate
2083 // is signaled.
2084 // TODO(pthatcher): This is a short-term solution for crbug/446908. A real fix
2085 // is to have a new signal the indicates a change in checking state from the
2086 // transport and expose a new checking() member from transport that can be
2087 // read to determine the current checking state. The existing SignalConnecting
2088 // actually means "gathering candidates", so cannot be be used here.
Steve Antona3a92c22017-12-07 10:27:41 -08002089 if (remote_description()->GetType() != SdpType::kOffer &&
Steve Anton8a006912017-12-04 15:25:56 -08002090 ice_connection_state() == PeerConnectionInterface::kIceConnectionNew) {
2091 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
2092 }
2093
deadbeefab9b2d12015-10-14 11:33:11 -07002094 // If setting the description decided our SSL role, allocate any necessary
2095 // SCTP sids.
2096 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08002097 if (data_channel_type() == cricket::DCT_SCTP && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07002098 AllocateSctpSids(role);
2099 }
2100
Steve Antondcc3c022017-12-22 16:02:54 -08002101 if (IsUnifiedPlan()) {
Steve Antonef65ef12018-01-10 17:15:20 -08002102 std::vector<TrackEvent> track_events;
Steve Antondcc3c022017-12-22 16:02:54 -08002103 for (auto transceiver : transceivers_) {
2104 const ContentInfo* content =
2105 FindMediaSectionForTransceiver(transceiver, remote_description());
2106 if (!content) {
2107 continue;
2108 }
2109 const MediaContentDescription* media_desc = content->media_description();
2110 RtpTransceiverDirection local_direction =
2111 RtpTransceiverDirectionReversed(media_desc->direction());
2112 // From the WebRTC specification, steps 2.2.8.5/6 of section 4.4.1.6 "Set
2113 // the RTCSessionDescription: If direction is sendrecv or recvonly, and
2114 // transceiver's current direction is neither sendrecv nor recvonly,
2115 // process the addition of a remote track for the media description.
2116 if (RtpTransceiverDirectionHasRecv(local_direction) &&
2117 (!transceiver->current_direction() ||
2118 !RtpTransceiverDirectionHasRecv(
Steve Anton74255ff2018-01-24 18:32:57 -08002119 *transceiver->current_direction())) &&
2120 !media_desc->streams().empty()) {
Steve Antonef65ef12018-01-10 17:15:20 -08002121 const std::string& sync_label = media_desc->streams()[0].sync_label;
2122 rtc::scoped_refptr<MediaStreamInterface> stream =
2123 remote_streams_->find(sync_label);
2124 if (!stream) {
2125 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
2126 MediaStream::Create(sync_label));
2127 remote_streams_->AddStream(stream);
2128 }
2129 transceiver->internal()->receiver_internal()->SetStreams({stream});
2130 TrackEvent track_event;
2131 track_event.receiver = transceiver->receiver();
2132 track_event.streams = transceiver->receiver()->streams();
2133 track_events.push_back(std::move(track_event));
Steve Antondcc3c022017-12-22 16:02:54 -08002134 }
2135 // If direction is sendonly or inactive, and transceiver's current
2136 // direction is neither sendonly nor inactive, process the removal of a
2137 // remote track for the media description.
2138 if (!RtpTransceiverDirectionHasRecv(local_direction) &&
Steve Antonef65ef12018-01-10 17:15:20 -08002139 (transceiver->current_direction() &&
Steve Antondcc3c022017-12-22 16:02:54 -08002140 RtpTransceiverDirectionHasRecv(*transceiver->current_direction()))) {
Steve Antonef65ef12018-01-10 17:15:20 -08002141 transceiver->internal()->receiver_internal()->SetStreams({});
Steve Antondcc3c022017-12-22 16:02:54 -08002142 }
2143 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
2144 transceiver->internal()->set_current_direction(local_direction);
2145 }
2146 if (content->rejected && !transceiver->stopped()) {
2147 transceiver->Stop();
2148 }
Steve Anton74255ff2018-01-24 18:32:57 -08002149 if (!content->rejected && !media_desc->streams().empty()) {
Steve Antond3679212018-01-17 17:41:02 -08002150 transceiver->internal()->receiver_internal()->SetupMediaChannel(
Steve Anton5f94aa22018-02-01 10:58:30 -08002151 media_desc->streams()[0].first_ssrc());
Steve Antond3679212018-01-17 17:41:02 -08002152 }
Steve Antondcc3c022017-12-22 16:02:54 -08002153 }
Steve Antonef65ef12018-01-10 17:15:20 -08002154 for (auto event : track_events) {
2155 observer_->OnAddTrack(event.receiver, event.streams);
2156 }
Steve Antondcc3c022017-12-22 16:02:54 -08002157 }
2158
Henrik Boströmfdb92012017-11-09 19:55:44 +01002159 const cricket::ContentInfo* audio_content =
2160 GetFirstAudioContent(remote_description()->description());
2161 const cricket::ContentInfo* video_content =
2162 GetFirstVideoContent(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002163 const cricket::AudioContentDescription* audio_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002164 GetFirstAudioContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002165 const cricket::VideoContentDescription* video_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002166 GetFirstVideoContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002167 const cricket::DataContentDescription* data_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002168 GetFirstDataContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002169
2170 // Check if the descriptions include streams, just in case the peer supports
2171 // MSID, but doesn't indicate so with "a=msid-semantic".
Henrik Boströmfdb92012017-11-09 19:55:44 +01002172 if (remote_description()->description()->msid_supported() ||
deadbeefbda7e0b2015-12-08 17:13:40 -08002173 (audio_desc && !audio_desc->streams().empty()) ||
2174 (video_desc && !video_desc->streams().empty())) {
2175 remote_peer_supports_msid_ = true;
2176 }
deadbeefab9b2d12015-10-14 11:33:11 -07002177
2178 // We wait to signal new streams until we finish processing the description,
2179 // since only at that point will new streams have all their tracks.
2180 rtc::scoped_refptr<StreamCollection> new_streams(StreamCollection::Create());
2181
Steve Antondcc3c022017-12-22 16:02:54 -08002182 if (!IsUnifiedPlan()) {
2183 // TODO(steveanton): When removing RTP senders/receivers in response to a
2184 // rejected media section, there is some cleanup logic that expects the
2185 // voice/ video channel to still be set. But in this method the voice/video
2186 // channel would have been destroyed by the SetRemoteDescription caller
2187 // above so the cleanup that relies on them fails to run. The RemoveSenders
2188 // calls should be moved to right before the DestroyChannel calls to fix
2189 // this.
Steve Anton8d3444d2017-10-20 15:30:51 -07002190
Steve Antondcc3c022017-12-22 16:02:54 -08002191 // Find all audio rtp streams and create corresponding remote AudioTracks
2192 // and MediaStreams.
2193 if (audio_content) {
2194 if (audio_content->rejected) {
2195 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
2196 } else {
2197 bool default_audio_track_needed =
2198 !remote_peer_supports_msid_ &&
2199 RtpTransceiverDirectionHasSend(audio_desc->direction());
2200 UpdateRemoteSendersList(GetActiveStreams(audio_desc),
2201 default_audio_track_needed, audio_desc->type(),
2202 new_streams);
2203 }
deadbeeffaac4972015-11-12 15:33:07 -08002204 }
deadbeefab9b2d12015-10-14 11:33:11 -07002205
Steve Antondcc3c022017-12-22 16:02:54 -08002206 // Find all video rtp streams and create corresponding remote VideoTracks
2207 // and MediaStreams.
2208 if (video_content) {
2209 if (video_content->rejected) {
2210 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
2211 } else {
2212 bool default_video_track_needed =
2213 !remote_peer_supports_msid_ &&
2214 RtpTransceiverDirectionHasSend(video_desc->direction());
2215 UpdateRemoteSendersList(GetActiveStreams(video_desc),
2216 default_video_track_needed, video_desc->type(),
2217 new_streams);
2218 }
deadbeeffaac4972015-11-12 15:33:07 -08002219 }
deadbeefab9b2d12015-10-14 11:33:11 -07002220
Steve Antondcc3c022017-12-22 16:02:54 -08002221 // Update the DataChannels with the information from the remote peer.
2222 if (data_desc) {
2223 if (rtc::starts_with(data_desc->protocol().data(),
2224 cricket::kMediaProtocolRtpPrefix)) {
2225 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
2226 }
deadbeefab9b2d12015-10-14 11:33:11 -07002227 }
deadbeefab9b2d12015-10-14 11:33:11 -07002228
Steve Antondcc3c022017-12-22 16:02:54 -08002229 // Iterate new_streams and notify the observer about new MediaStreams.
2230 for (size_t i = 0; i < new_streams->count(); ++i) {
2231 MediaStreamInterface* new_stream = new_streams->at(i);
2232 stats_->AddStream(new_stream);
2233 observer_->OnAddStream(
2234 rtc::scoped_refptr<MediaStreamInterface>(new_stream));
2235 }
deadbeefab9b2d12015-10-14 11:33:11 -07002236
Steve Antondcc3c022017-12-22 16:02:54 -08002237 UpdateEndedRemoteMediaStreams();
2238 }
deadbeefab9b2d12015-10-14 11:33:11 -07002239
Steve Anton8a006912017-12-04 15:25:56 -08002240 return RTCError::OK();
deadbeeffc648b62015-10-13 16:42:33 -07002241}
2242
Steve Antondcc3c022017-12-22 16:02:54 -08002243RTCError PeerConnection::UpdateTransceiversAndDataChannels(
2244 cricket::ContentSource source,
2245 const SessionDescriptionInterface* old_session,
2246 const SessionDescriptionInterface& new_session) {
2247 RTC_DCHECK(IsUnifiedPlan());
2248
Steve Anton7464fca2018-01-19 11:10:37 -08002249 const cricket::ContentGroup* bundle_group = nullptr;
2250 if (new_session.GetType() == SdpType::kOffer) {
2251 auto bundle_group_or_error =
2252 GetEarlyBundleGroup(*new_session.description());
2253 if (!bundle_group_or_error.ok()) {
2254 return bundle_group_or_error.MoveError();
2255 }
2256 bundle_group = bundle_group_or_error.MoveValue();
Steve Antondcc3c022017-12-22 16:02:54 -08002257 }
Steve Antondcc3c022017-12-22 16:02:54 -08002258
2259 const ContentInfos& old_contents =
2260 (old_session ? old_session->description()->contents() : ContentInfos());
2261 const ContentInfos& new_contents = new_session.description()->contents();
2262
2263 for (size_t i = 0; i < new_contents.size(); ++i) {
2264 const cricket::ContentInfo& new_content = new_contents[i];
2265 const cricket::ContentInfo* old_content =
2266 (i < old_contents.size() ? &old_contents[i] : nullptr);
2267 cricket::MediaType media_type = new_content.media_description()->type();
2268 seen_mids_.insert(new_content.name);
2269 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
2270 media_type == cricket::MEDIA_TYPE_VIDEO) {
2271 auto transceiver_or_error =
2272 AssociateTransceiver(source, i, new_content, old_content);
2273 if (!transceiver_or_error.ok()) {
2274 return transceiver_or_error.MoveError();
2275 }
2276 auto transceiver = transceiver_or_error.MoveValue();
Steve Antondcc3c022017-12-22 16:02:54 -08002277 RTCError error =
2278 UpdateTransceiverChannel(transceiver, new_content, bundle_group);
2279 if (!error.ok()) {
2280 return error;
2281 }
2282 } else if (media_type == cricket::MEDIA_TYPE_DATA) {
Steve Antonfa2260d2017-12-28 16:38:23 -08002283 if (GetDataMid() && new_content.name != *GetDataMid()) {
2284 // Ignore all but the first data section.
2285 continue;
2286 }
2287 RTCError error = UpdateDataChannel(source, new_content, bundle_group);
2288 if (!error.ok()) {
2289 return error;
2290 }
Steve Antondcc3c022017-12-22 16:02:54 -08002291 } else {
2292 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
2293 "Unknown section type.");
2294 }
2295 }
2296
2297 return RTCError::OK();
2298}
2299
2300RTCError PeerConnection::UpdateTransceiverChannel(
2301 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2302 transceiver,
2303 const cricket::ContentInfo& content,
2304 const cricket::ContentGroup* bundle_group) {
2305 RTC_DCHECK(IsUnifiedPlan());
2306 RTC_DCHECK(transceiver);
2307 cricket::BaseChannel* channel = transceiver->internal()->channel();
2308 if (content.rejected) {
2309 if (channel) {
2310 transceiver->internal()->SetChannel(nullptr);
2311 DestroyBaseChannel(channel);
2312 }
2313 } else {
2314 if (!channel) {
2315 if (transceiver->internal()->media_type() == cricket::MEDIA_TYPE_AUDIO) {
2316 channel = CreateVoiceChannel(
2317 content.name,
2318 GetTransportNameForMediaSection(content.name, bundle_group));
2319 } else {
2320 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO,
2321 transceiver->internal()->media_type());
2322 channel = CreateVideoChannel(
2323 content.name,
2324 GetTransportNameForMediaSection(content.name, bundle_group));
2325 }
2326 if (!channel) {
2327 LOG_AND_RETURN_ERROR(
2328 RTCErrorType::INTERNAL_ERROR,
2329 "Failed to create channel for mid=" + content.name);
2330 }
2331 transceiver->internal()->SetChannel(channel);
2332 }
2333 }
2334 return RTCError::OK();
2335}
2336
Steve Antonfa2260d2017-12-28 16:38:23 -08002337RTCError PeerConnection::UpdateDataChannel(
2338 cricket::ContentSource source,
2339 const cricket::ContentInfo& content,
2340 const cricket::ContentGroup* bundle_group) {
2341 if (data_channel_type_ == cricket::DCT_NONE) {
Steve Antondbf9d032018-01-19 15:23:40 -08002342 // If data channels are disabled, ignore this media section. CreateAnswer
2343 // will take care of rejecting it.
2344 return RTCError::OK();
Steve Antonfa2260d2017-12-28 16:38:23 -08002345 }
2346 if (content.rejected) {
2347 DestroyDataChannel();
2348 } else {
2349 if (!rtp_data_channel_ && !sctp_transport_) {
2350 if (!CreateDataChannel(content.name, GetTransportNameForMediaSection(
2351 content.name, bundle_group))) {
2352 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
2353 "Failed to create data channel.");
2354 }
2355 }
2356 if (source == cricket::CS_REMOTE) {
2357 const MediaContentDescription* data_desc = content.media_description();
2358 if (data_desc && cricket::IsRtpProtocol(data_desc->protocol())) {
2359 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
2360 }
2361 }
2362 }
2363 return RTCError::OK();
2364}
2365
Steve Antondcc3c022017-12-22 16:02:54 -08002366RTCErrorOr<rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
2367PeerConnection::AssociateTransceiver(cricket::ContentSource source,
2368 size_t mline_index,
2369 const ContentInfo& content,
2370 const ContentInfo* old_content) {
2371 RTC_DCHECK(IsUnifiedPlan());
2372 // If the m= section is being recycled (rejected in previous remote
2373 // description, not rejected in current description), dissociate the currently
2374 // associated RtpTransceiver by setting its mid property to null, and discard
2375 // the mapping between the transceiver and its m= section index.
2376 if (old_content && old_content->rejected && !content.rejected) {
2377 auto old_transceiver = GetAssociatedTransceiver(old_content->name);
2378 if (old_transceiver) {
2379 old_transceiver->internal()->set_mid(rtc::nullopt);
2380 old_transceiver->internal()->set_mline_index(rtc::nullopt);
2381 }
2382 }
2383 const MediaContentDescription* media_desc = content.media_description();
2384 auto transceiver = GetAssociatedTransceiver(content.name);
2385 if (source == cricket::CS_LOCAL) {
2386 // Find the RtpTransceiver that corresponds to this m= section, using the
2387 // mapping between transceivers and m= section indices established when
2388 // creating the offer.
2389 if (!transceiver) {
2390 transceiver = GetTransceiverByMLineIndex(mline_index);
2391 }
2392 if (!transceiver) {
2393 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2394 "Unknown transceiver");
2395 }
2396 } else {
2397 RTC_DCHECK_EQ(source, cricket::CS_REMOTE);
2398 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers
2399 // of the same type...
2400 if (!transceiver &&
2401 RtpTransceiverDirectionHasRecv(media_desc->direction())) {
2402 transceiver = FindAvailableTransceiverToReceive(media_desc->type());
2403 }
2404 // If no RtpTransceiver was found in the previous step, create one with a
2405 // recvonly direction.
2406 if (!transceiver) {
Steve Anton02ee47c2018-01-10 16:26:06 -08002407 auto sender =
2408 CreateSender(media_desc->type(), nullptr, {rtc::CreateRandomUuid()});
Steve Anton5f94aa22018-02-01 10:58:30 -08002409 std::string receiver_id;
2410 if (!media_desc->streams().empty()) {
2411 receiver_id = media_desc->streams()[0].id;
2412 } else {
2413 receiver_id = rtc::CreateRandomUuid();
2414 }
2415 auto receiver = CreateReceiver(media_desc->type(), receiver_id);
Steve Anton02ee47c2018-01-10 16:26:06 -08002416 transceiver = CreateAndAddTransceiver(sender, receiver);
Steve Antondcc3c022017-12-22 16:02:54 -08002417 transceiver->internal()->set_direction(
2418 RtpTransceiverDirection::kRecvOnly);
2419 }
2420 }
2421 RTC_DCHECK(transceiver);
2422 if (transceiver->internal()->media_type() != media_desc->type()) {
2423 LOG_AND_RETURN_ERROR(
2424 RTCErrorType::INVALID_PARAMETER,
2425 "Transceiver type does not match media description type.");
2426 }
2427 // Associate the found or created RtpTransceiver with the m= section by
2428 // setting the value of the RtpTransceiver's mid property to the MID of the m=
2429 // section, and establish a mapping between the transceiver and the index of
2430 // the m= section.
2431 transceiver->internal()->set_mid(content.name);
2432 transceiver->internal()->set_mline_index(mline_index);
2433 return std::move(transceiver);
2434}
2435
2436rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2437PeerConnection::GetAssociatedTransceiver(const std::string& mid) const {
2438 RTC_DCHECK(IsUnifiedPlan());
2439 for (auto transceiver : transceivers_) {
2440 if (transceiver->mid() == mid) {
2441 return transceiver;
2442 }
2443 }
2444 return nullptr;
2445}
2446
2447rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2448PeerConnection::GetTransceiverByMLineIndex(size_t mline_index) const {
2449 RTC_DCHECK(IsUnifiedPlan());
2450 for (auto transceiver : transceivers_) {
2451 if (transceiver->internal()->mline_index() == mline_index) {
2452 return transceiver;
2453 }
2454 }
2455 return nullptr;
2456}
2457
2458rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2459PeerConnection::FindAvailableTransceiverToReceive(
2460 cricket::MediaType media_type) const {
2461 RTC_DCHECK(IsUnifiedPlan());
2462 // From JSEP section 5.10 (Applying a Remote Description):
2463 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers of
2464 // the same type that were added to the PeerConnection by addTrack and are not
2465 // associated with any m= section and are not stopped, find the first such
2466 // RtpTransceiver.
2467 for (auto transceiver : transceivers_) {
2468 if (transceiver->internal()->media_type() == media_type &&
2469 transceiver->internal()->created_by_addtrack() && !transceiver->mid() &&
2470 !transceiver->stopped()) {
2471 return transceiver;
2472 }
2473 }
2474 return nullptr;
2475}
2476
Steve Antoned10bd92017-12-05 10:52:59 -08002477const cricket::ContentInfo* PeerConnection::FindMediaSectionForTransceiver(
2478 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2479 transceiver,
2480 const SessionDescriptionInterface* sdesc) const {
2481 RTC_DCHECK(transceiver);
2482 RTC_DCHECK(sdesc);
2483 if (IsUnifiedPlan()) {
2484 if (!transceiver->internal()->mid()) {
2485 // This transceiver is not associated with a media section yet.
2486 return nullptr;
2487 }
2488 return sdesc->description()->GetContentByName(
2489 *transceiver->internal()->mid());
2490 } else {
2491 // Plan B only allows at most one audio and one video section, so use the
2492 // first media section of that type.
2493 return cricket::GetFirstMediaContent(sdesc->description()->contents(),
2494 transceiver->internal()->media_type());
2495 }
2496}
2497
deadbeef46c73892016-11-16 19:42:04 -08002498PeerConnectionInterface::RTCConfiguration PeerConnection::GetConfiguration() {
2499 return configuration_;
2500}
2501
deadbeef293e9262017-01-11 12:28:30 -08002502bool PeerConnection::SetConfiguration(const RTCConfiguration& configuration,
2503 RTCError* error) {
Peter Boström1a9d6152015-12-08 22:15:17 +01002504 TRACE_EVENT0("webrtc", "PeerConnection::SetConfiguration");
deadbeef6de92f92016-12-12 18:49:32 -08002505
Steve Anton75737c02017-11-06 10:37:17 -08002506 if (local_description() && configuration.ice_candidate_pool_size !=
2507 configuration_.ice_candidate_pool_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002508 RTC_LOG(LS_ERROR) << "Can't change candidate pool size after calling "
2509 "SetLocalDescription.";
deadbeef293e9262017-01-11 12:28:30 -08002510 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00002511 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002512
deadbeef293e9262017-01-11 12:28:30 -08002513 // The simplest (and most future-compatible) way to tell if the config was
2514 // modified in an invalid way is to copy each property we do support
2515 // modifying, then use operator==. There are far more properties we don't
2516 // support modifying than those we do, and more could be added.
2517 RTCConfiguration modified_config = configuration_;
2518 modified_config.servers = configuration.servers;
2519 modified_config.type = configuration.type;
2520 modified_config.ice_candidate_pool_size =
2521 configuration.ice_candidate_pool_size;
2522 modified_config.prune_turn_ports = configuration.prune_turn_ports;
skvladd1f5fda2017-02-03 16:54:05 -08002523 modified_config.ice_check_min_interval = configuration.ice_check_min_interval;
Jonas Orelandbdcee282017-10-10 14:01:40 +02002524 modified_config.turn_customizer = configuration.turn_customizer;
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08002525 modified_config.network_preference = configuration.network_preference;
deadbeef293e9262017-01-11 12:28:30 -08002526 if (configuration != modified_config) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002527 RTC_LOG(LS_ERROR) << "Modifying the configuration in an unsupported way.";
deadbeef293e9262017-01-11 12:28:30 -08002528 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
2529 }
2530
Steve Anton038834f2017-07-14 15:59:59 -07002531 // Validate the modified configuration.
2532 RTCError validate_error = ValidateConfiguration(modified_config);
2533 if (!validate_error.ok()) {
2534 return SafeSetError(std::move(validate_error), error);
2535 }
2536
deadbeef293e9262017-01-11 12:28:30 -08002537 // Note that this isn't possible through chromium, since it's an unsigned
2538 // short in WebIDL.
2539 if (configuration.ice_candidate_pool_size < 0 ||
2540 configuration.ice_candidate_pool_size > UINT16_MAX) {
2541 return SafeSetError(RTCErrorType::INVALID_RANGE, error);
2542 }
2543
2544 // Parse ICE servers before hopping to network thread.
2545 cricket::ServerAddresses stun_servers;
2546 std::vector<cricket::RelayServerConfig> turn_servers;
2547 RTCErrorType parse_error =
2548 ParseIceServers(configuration.servers, &stun_servers, &turn_servers);
2549 if (parse_error != RTCErrorType::NONE) {
2550 return SafeSetError(parse_error, error);
2551 }
2552
2553 // In theory this shouldn't fail.
2554 if (!network_thread()->Invoke<bool>(
2555 RTC_FROM_HERE,
2556 rtc::Bind(&PeerConnection::ReconfigurePortAllocator_n, this,
2557 stun_servers, turn_servers, modified_config.type,
2558 modified_config.ice_candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02002559 modified_config.prune_turn_ports,
2560 modified_config.turn_customizer))) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002561 RTC_LOG(LS_ERROR) << "Failed to apply configuration to PortAllocator.";
deadbeef293e9262017-01-11 12:28:30 -08002562 return SafeSetError(RTCErrorType::INTERNAL_ERROR, error);
2563 }
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07002564
deadbeefd1a38b52016-12-10 13:15:33 -08002565 // As described in JSEP, calling setConfiguration with new ICE servers or
2566 // candidate policy must set a "needs-ice-restart" bit so that the next offer
2567 // triggers an ICE restart which will pick up the changes.
deadbeef293e9262017-01-11 12:28:30 -08002568 if (modified_config.servers != configuration_.servers ||
2569 modified_config.type != configuration_.type ||
2570 modified_config.prune_turn_ports != configuration_.prune_turn_ports) {
Steve Antond25da372017-11-06 14:50:29 -08002571 transport_controller_->SetNeedsIceRestartFlag();
deadbeefd1a38b52016-12-10 13:15:33 -08002572 }
skvladd1f5fda2017-02-03 16:54:05 -08002573
2574 if (modified_config.ice_check_min_interval !=
2575 configuration_.ice_check_min_interval) {
Steve Antond25da372017-11-06 14:50:29 -08002576 transport_controller_->SetIceConfig(ParseIceConfig(modified_config));
skvladd1f5fda2017-02-03 16:54:05 -08002577 }
2578
deadbeef293e9262017-01-11 12:28:30 -08002579 configuration_ = modified_config;
2580 return SafeSetError(RTCErrorType::NONE, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00002581}
2582
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002583bool PeerConnection::AddIceCandidate(
2584 const IceCandidateInterface* ice_candidate) {
Peter Boström1a9d6152015-12-08 22:15:17 +01002585 TRACE_EVENT0("webrtc", "PeerConnection::AddIceCandidate");
zhihuang29ff8442016-07-27 11:07:25 -07002586 if (IsClosed()) {
2587 return false;
2588 }
Steve Antond25da372017-11-06 14:50:29 -08002589
2590 if (!remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002591 RTC_LOG(LS_ERROR) << "ProcessIceMessage: ICE candidates can't be added "
2592 << "without any remote session description.";
Steve Antond25da372017-11-06 14:50:29 -08002593 return false;
2594 }
2595
2596 if (!ice_candidate) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002597 RTC_LOG(LS_ERROR) << "ProcessIceMessage: Candidate is NULL.";
Steve Antond25da372017-11-06 14:50:29 -08002598 return false;
2599 }
2600
2601 bool valid = false;
2602 bool ready = ReadyToUseRemoteCandidate(ice_candidate, nullptr, &valid);
2603 if (!valid) {
2604 return false;
2605 }
2606
2607 // Add this candidate to the remote session description.
2608 if (!mutable_remote_description()->AddCandidate(ice_candidate)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002609 RTC_LOG(LS_ERROR) << "ProcessIceMessage: Candidate cannot be used.";
Steve Antond25da372017-11-06 14:50:29 -08002610 return false;
2611 }
2612
2613 if (ready) {
2614 return UseCandidate(ice_candidate);
2615 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002616 RTC_LOG(LS_INFO) << "ProcessIceMessage: Not ready to use candidate.";
Steve Antond25da372017-11-06 14:50:29 -08002617 return true;
2618 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002619}
2620
Honghai Zhang7fb69db2016-03-14 11:59:18 -07002621bool PeerConnection::RemoveIceCandidates(
2622 const std::vector<cricket::Candidate>& candidates) {
2623 TRACE_EVENT0("webrtc", "PeerConnection::RemoveIceCandidates");
Steve Antond25da372017-11-06 14:50:29 -08002624 if (!remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002625 RTC_LOG(LS_ERROR) << "RemoveRemoteIceCandidates: ICE candidates can't be "
2626 << "removed without any remote session description.";
Steve Antond25da372017-11-06 14:50:29 -08002627 return false;
2628 }
2629
2630 if (candidates.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002631 RTC_LOG(LS_ERROR) << "RemoveRemoteIceCandidates: candidates are empty.";
Steve Antond25da372017-11-06 14:50:29 -08002632 return false;
2633 }
2634
2635 size_t number_removed =
2636 mutable_remote_description()->RemoveCandidates(candidates);
2637 if (number_removed != candidates.size()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002638 RTC_LOG(LS_ERROR)
2639 << "RemoveRemoteIceCandidates: Failed to remove candidates. "
2640 << "Requested " << candidates.size() << " but only " << number_removed
2641 << " are removed.";
Steve Antond25da372017-11-06 14:50:29 -08002642 }
2643
2644 // Remove the candidates from the transport controller.
2645 std::string error;
2646 bool res = transport_controller_->RemoveRemoteCandidates(candidates, &error);
2647 if (!res && !error.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002648 RTC_LOG(LS_ERROR) << "Error when removing remote candidates: " << error;
Steve Antond25da372017-11-06 14:50:29 -08002649 }
2650 return true;
Honghai Zhang7fb69db2016-03-14 11:59:18 -07002651}
2652
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00002653void PeerConnection::RegisterUMAObserver(UMAObserver* observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +01002654 TRACE_EVENT0("webrtc", "PeerConnection::RegisterUmaObserver");
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00002655 uma_observer_ = observer;
guoweis@webrtc.org7169afd2014-12-04 17:59:29 +00002656
Steve Anton75737c02017-11-06 10:37:17 -08002657 if (transport_controller()) {
2658 transport_controller()->SetMetricsObserver(uma_observer_);
guoweis@webrtc.org7169afd2014-12-04 17:59:29 +00002659 }
2660
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00002661 // Send information about IPv4/IPv6 status.
deadbeef293e9262017-01-11 12:28:30 -08002662 if (uma_observer_) {
Honghai Zhangd93f50c2016-10-05 11:47:22 -07002663 port_allocator_->SetMetricsObserver(uma_observer_);
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00002664 if (port_allocator_->flags() & cricket::PORTALLOCATOR_ENABLE_IPV6) {
Guo-wei Shiehdfbe6792015-09-03 17:12:07 -07002665 uma_observer_->IncrementEnumCounter(
2666 kEnumCounterAddressFamily, kPeerConnection_IPv6,
2667 kPeerConnectionAddressFamilyCounter_Max);
mallinath@webrtc.orgb445f262014-05-23 22:19:37 +00002668 } else {
Guo-wei Shiehdfbe6792015-09-03 17:12:07 -07002669 uma_observer_->IncrementEnumCounter(
2670 kEnumCounterAddressFamily, kPeerConnection_IPv4,
2671 kPeerConnectionAddressFamilyCounter_Max);
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00002672 }
2673 }
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00002674}
2675
zstein4b979802017-06-02 14:37:37 -07002676RTCError PeerConnection::SetBitrate(const BitrateParameters& bitrate) {
Steve Anton978b8762017-09-29 12:15:02 -07002677 if (!worker_thread()->IsCurrent()) {
2678 return worker_thread()->Invoke<RTCError>(
zstein4b979802017-06-02 14:37:37 -07002679 RTC_FROM_HERE, rtc::Bind(&PeerConnection::SetBitrate, this, bitrate));
2680 }
2681
2682 const bool has_min = static_cast<bool>(bitrate.min_bitrate_bps);
2683 const bool has_current = static_cast<bool>(bitrate.current_bitrate_bps);
2684 const bool has_max = static_cast<bool>(bitrate.max_bitrate_bps);
2685 if (has_min && *bitrate.min_bitrate_bps < 0) {
2686 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2687 "min_bitrate_bps <= 0");
2688 }
2689 if (has_current) {
2690 if (has_min && *bitrate.current_bitrate_bps < *bitrate.min_bitrate_bps) {
2691 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2692 "current_bitrate_bps < min_bitrate_bps");
2693 } else if (*bitrate.current_bitrate_bps < 0) {
2694 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2695 "curent_bitrate_bps < 0");
2696 }
2697 }
2698 if (has_max) {
2699 if (has_current &&
2700 *bitrate.max_bitrate_bps < *bitrate.current_bitrate_bps) {
2701 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2702 "max_bitrate_bps < current_bitrate_bps");
2703 } else if (has_min && *bitrate.max_bitrate_bps < *bitrate.min_bitrate_bps) {
2704 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2705 "max_bitrate_bps < min_bitrate_bps");
2706 } else if (*bitrate.max_bitrate_bps < 0) {
2707 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2708 "max_bitrate_bps < 0");
2709 }
2710 }
2711
2712 Call::Config::BitrateConfigMask mask;
2713 mask.min_bitrate_bps = bitrate.min_bitrate_bps;
2714 mask.start_bitrate_bps = bitrate.current_bitrate_bps;
2715 mask.max_bitrate_bps = bitrate.max_bitrate_bps;
2716
2717 RTC_DCHECK(call_.get());
2718 call_->SetBitrateConfigMask(mask);
2719
2720 return RTCError::OK();
2721}
2722
Alex Narest78609d52017-10-20 10:37:47 +02002723void PeerConnection::SetBitrateAllocationStrategy(
2724 std::unique_ptr<rtc::BitrateAllocationStrategy>
2725 bitrate_allocation_strategy) {
2726 rtc::Thread* worker_thread = factory_->worker_thread();
2727 if (!worker_thread->IsCurrent()) {
2728 rtc::BitrateAllocationStrategy* strategy_raw =
2729 bitrate_allocation_strategy.release();
2730 auto functor = [this, strategy_raw]() {
2731 call_->SetBitrateAllocationStrategy(
2732 rtc::WrapUnique<rtc::BitrateAllocationStrategy>(strategy_raw));
2733 };
2734 worker_thread->Invoke<void>(RTC_FROM_HERE, functor);
2735 return;
2736 }
2737 RTC_DCHECK(call_.get());
2738 call_->SetBitrateAllocationStrategy(std::move(bitrate_allocation_strategy));
2739}
2740
henrika5f6bf242017-11-01 11:06:56 +01002741void PeerConnection::SetAudioPlayout(bool playout) {
2742 if (!worker_thread()->IsCurrent()) {
2743 worker_thread()->Invoke<void>(
2744 RTC_FROM_HERE,
2745 rtc::Bind(&PeerConnection::SetAudioPlayout, this, playout));
2746 return;
2747 }
2748 auto audio_state =
2749 factory_->channel_manager()->media_engine()->GetAudioState();
2750 audio_state->SetPlayout(playout);
2751}
2752
2753void PeerConnection::SetAudioRecording(bool recording) {
2754 if (!worker_thread()->IsCurrent()) {
2755 worker_thread()->Invoke<void>(
2756 RTC_FROM_HERE,
2757 rtc::Bind(&PeerConnection::SetAudioRecording, this, recording));
2758 return;
2759 }
2760 auto audio_state =
2761 factory_->channel_manager()->media_engine()->GetAudioState();
2762 audio_state->SetRecording(recording);
2763}
2764
Steve Anton8c0f7a72017-10-03 10:03:10 -07002765std::unique_ptr<rtc::SSLCertificate>
2766PeerConnection::GetRemoteAudioSSLCertificate() {
Steve Anton75737c02017-11-06 10:37:17 -08002767 if (!voice_channel()) {
Steve Anton8c0f7a72017-10-03 10:03:10 -07002768 return nullptr;
2769 }
Steve Anton75737c02017-11-06 10:37:17 -08002770 return GetRemoteSSLCertificate(voice_channel()->transport_name());
Steve Anton8c0f7a72017-10-03 10:03:10 -07002771}
2772
Zhi Huang70b820f2018-01-27 14:16:15 -08002773std::unique_ptr<rtc::SSLCertChain>
2774PeerConnection::GetRemoteAudioSSLCertChain() {
2775 if (!voice_channel()) {
2776 return nullptr;
2777 }
2778
2779 return transport_controller_->GetRemoteSSLCertChain(
2780 voice_channel()->transport_name());
2781}
2782
ivoc14d5dbe2016-07-04 07:06:55 -07002783bool PeerConnection::StartRtcEventLog(rtc::PlatformFile file,
2784 int64_t max_size_bytes) {
Elad Alon99c3fe52017-10-13 16:29:40 +02002785 // TODO(eladalon): It would be better to not allow negative values into PC.
2786 const size_t max_size = (max_size_bytes < 0)
2787 ? RtcEventLog::kUnlimitedOutput
2788 : rtc::saturated_cast<size_t>(max_size_bytes);
2789 return StartRtcEventLog(
Bjorn Tereliusde939432017-11-20 17:38:14 +01002790 rtc::MakeUnique<RtcEventLogOutputFile>(file, max_size),
2791 webrtc::RtcEventLog::kImmediateOutput);
Elad Alon99c3fe52017-10-13 16:29:40 +02002792}
2793
Bjorn Tereliusde939432017-11-20 17:38:14 +01002794bool PeerConnection::StartRtcEventLog(std::unique_ptr<RtcEventLogOutput> output,
2795 int64_t output_period_ms) {
Karl Wibergd6b48192017-10-16 23:01:06 +02002796 // TODO(eladalon): In C++14, this can be done with a lambda.
2797 struct Functor {
Bjorn Tereliusde939432017-11-20 17:38:14 +01002798 bool operator()() {
2799 return pc->StartRtcEventLog_w(std::move(output), output_period_ms);
2800 }
Karl Wibergd6b48192017-10-16 23:01:06 +02002801 PeerConnection* const pc;
2802 std::unique_ptr<RtcEventLogOutput> output;
Bjorn Tereliusde939432017-11-20 17:38:14 +01002803 const int64_t output_period_ms;
Elad Alon99c3fe52017-10-13 16:29:40 +02002804 };
Bjorn Tereliusde939432017-11-20 17:38:14 +01002805 return worker_thread()->Invoke<bool>(
2806 RTC_FROM_HERE, Functor{this, std::move(output), output_period_ms});
ivoc14d5dbe2016-07-04 07:06:55 -07002807}
2808
2809void PeerConnection::StopRtcEventLog() {
Steve Anton978b8762017-09-29 12:15:02 -07002810 worker_thread()->Invoke<void>(
ivoc14d5dbe2016-07-04 07:06:55 -07002811 RTC_FROM_HERE, rtc::Bind(&PeerConnection::StopRtcEventLog_w, this));
2812}
2813
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002814const SessionDescriptionInterface* PeerConnection::local_description() const {
Steve Anton75737c02017-11-06 10:37:17 -08002815 return pending_local_description_ ? pending_local_description_.get()
2816 : current_local_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002817}
2818
2819const SessionDescriptionInterface* PeerConnection::remote_description() const {
Steve Anton75737c02017-11-06 10:37:17 -08002820 return pending_remote_description_ ? pending_remote_description_.get()
2821 : current_remote_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002822}
2823
deadbeeffe4a8a42016-12-20 17:56:17 -08002824const SessionDescriptionInterface* PeerConnection::current_local_description()
2825 const {
Steve Anton75737c02017-11-06 10:37:17 -08002826 return current_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08002827}
2828
2829const SessionDescriptionInterface* PeerConnection::current_remote_description()
2830 const {
Steve Anton75737c02017-11-06 10:37:17 -08002831 return current_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08002832}
2833
2834const SessionDescriptionInterface* PeerConnection::pending_local_description()
2835 const {
Steve Anton75737c02017-11-06 10:37:17 -08002836 return pending_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08002837}
2838
2839const SessionDescriptionInterface* PeerConnection::pending_remote_description()
2840 const {
Steve Anton75737c02017-11-06 10:37:17 -08002841 return pending_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08002842}
2843
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002844void PeerConnection::Close() {
Peter Boström1a9d6152015-12-08 22:15:17 +01002845 TRACE_EVENT0("webrtc", "PeerConnection::Close");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002846 // Update stats here so that we have the most recent stats for tracks and
2847 // streams before the channels are closed.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00002848 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002849
Steve Anton75737c02017-11-06 10:37:17 -08002850 ChangeSignalingState(PeerConnectionInterface::kClosed);
Steve Anton3fe1b152017-12-12 10:20:08 -08002851
Steve Anton8af21862017-12-15 11:20:13 -08002852 for (auto transceiver : transceivers_) {
2853 transceiver->Stop();
2854 }
2855 DestroyAllChannels();
Steve Anton75737c02017-11-06 10:37:17 -08002856
deadbeef42a42632017-03-10 15:18:00 -08002857 network_thread()->Invoke<void>(
2858 RTC_FROM_HERE,
2859 rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
2860 port_allocator_.get()));
nisseeaabdf62017-05-05 02:23:02 -07002861
Steve Anton978b8762017-09-29 12:15:02 -07002862 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
eladalon248fd4f2017-09-06 05:18:15 -07002863 call_.reset();
2864 // The event log must outlive call (and any other object that uses it).
2865 event_log_.reset();
2866 });
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002867}
2868
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002869void PeerConnection::OnMessage(rtc::Message* msg) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002870 switch (msg->message_id) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002871 case MSG_SET_SESSIONDESCRIPTION_SUCCESS: {
2872 SetSessionDescriptionMsg* param =
2873 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
2874 param->observer->OnSuccess();
2875 delete param;
2876 break;
2877 }
2878 case MSG_SET_SESSIONDESCRIPTION_FAILED: {
2879 SetSessionDescriptionMsg* param =
2880 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
2881 param->observer->OnFailure(param->error);
2882 delete param;
2883 break;
2884 }
deadbeefab9b2d12015-10-14 11:33:11 -07002885 case MSG_CREATE_SESSIONDESCRIPTION_FAILED: {
2886 CreateSessionDescriptionMsg* param =
2887 static_cast<CreateSessionDescriptionMsg*>(msg->pdata);
2888 param->observer->OnFailure(param->error);
2889 delete param;
2890 break;
2891 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002892 case MSG_GETSTATS: {
2893 GetStatsMsg* param = static_cast<GetStatsMsg*>(msg->pdata);
nissee8abe3e2017-01-18 05:00:34 -08002894 StatsReports reports;
2895 stats_->GetStats(param->track, &reports);
2896 param->observer->OnComplete(reports);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002897 delete param;
2898 break;
2899 }
deadbeefbd292462015-12-14 18:15:29 -08002900 case MSG_FREE_DATACHANNELS: {
2901 sctp_data_channels_to_free_.clear();
2902 break;
2903 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002904 default:
nisseeb4ca4e2017-01-12 02:24:27 -08002905 RTC_NOTREACHED() << "Not implemented";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002906 break;
2907 }
2908}
2909
Steve Anton4171afb2017-11-20 10:20:22 -08002910void PeerConnection::CreateAudioReceiver(
2911 MediaStreamInterface* stream,
2912 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01002913 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
2914 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Steve Antond3679212018-01-17 17:41:02 -08002915 auto* audio_receiver = new AudioRtpReceiver(
2916 worker_thread(), remote_sender_info.sender_id, streams);
2917 audio_receiver->SetMediaChannel(voice_media_channel());
2918 audio_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
2919 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
2920 signaling_thread(), audio_receiver);
Steve Anton4171afb2017-11-20 10:20:22 -08002921 GetAudioTransceiver()->internal()->AddReceiver(receiver);
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01002922 observer_->OnAddTrack(receiver, std::move(streams));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002923}
2924
Steve Anton4171afb2017-11-20 10:20:22 -08002925void PeerConnection::CreateVideoReceiver(
2926 MediaStreamInterface* stream,
2927 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01002928 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
2929 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Steve Antond3679212018-01-17 17:41:02 -08002930 auto* video_receiver = new VideoRtpReceiver(
2931 worker_thread(), remote_sender_info.sender_id, streams);
2932 video_receiver->SetMediaChannel(video_media_channel());
2933 video_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
2934 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
2935 signaling_thread(), video_receiver);
Steve Anton4171afb2017-11-20 10:20:22 -08002936 GetVideoTransceiver()->internal()->AddReceiver(receiver);
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01002937 observer_->OnAddTrack(receiver, std::move(streams));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002938}
2939
deadbeef70ab1a12015-09-28 16:53:55 -07002940// TODO(deadbeef): Keep RtpReceivers around even if track goes away in remote
2941// description.
Henrik Boström933d8b02017-10-10 10:05:16 -07002942rtc::scoped_refptr<RtpReceiverInterface> PeerConnection::RemoveAndStopReceiver(
Steve Anton4171afb2017-11-20 10:20:22 -08002943 const RtpSenderInfo& remote_sender_info) {
2944 auto receiver = FindReceiverById(remote_sender_info.sender_id);
2945 if (!receiver) {
2946 RTC_LOG(LS_WARNING) << "RtpReceiver for track with id "
2947 << remote_sender_info.sender_id << " doesn't exist.";
Henrik Boström933d8b02017-10-10 10:05:16 -07002948 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07002949 }
Steve Anton4171afb2017-11-20 10:20:22 -08002950 if (receiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
2951 GetAudioTransceiver()->internal()->RemoveReceiver(receiver);
2952 } else {
2953 GetVideoTransceiver()->internal()->RemoveReceiver(receiver);
2954 }
Henrik Boström933d8b02017-10-10 10:05:16 -07002955 return receiver;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002956}
2957
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002958void PeerConnection::AddAudioTrack(AudioTrackInterface* track,
2959 MediaStreamInterface* stream) {
2960 RTC_DCHECK(!IsClosed());
2961 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08002962 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002963 // We already have a sender for this track, so just change the stream_id
2964 // so that it's correct in the next call to CreateOffer.
Steve Anton4171afb2017-11-20 10:20:22 -08002965 sender->internal()->set_stream_id(stream->label());
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002966 return;
2967 }
2968
2969 // Normal case; we've never seen this track before.
Steve Anton02ee47c2018-01-10 16:26:06 -08002970 auto new_sender =
2971 CreateSender(cricket::MEDIA_TYPE_AUDIO, track, {stream->label()});
2972 static_cast<AudioRtpSender*>(new_sender->internal())
Steve Anton47136dd2018-01-12 10:49:35 -08002973 ->SetMediaChannel(voice_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08002974 GetAudioTransceiver()->internal()->AddSender(new_sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002975 // If the sender has already been configured in SDP, we call SetSsrc,
2976 // which will connect the sender to the underlying transport. This can
2977 // occur if a local session description that contains the ID of the sender
2978 // is set before AddStream is called. It can also occur if the local
2979 // session description is not changed and RemoveStream is called, and
2980 // later AddStream is called again with the same stream.
Steve Anton4171afb2017-11-20 10:20:22 -08002981 const RtpSenderInfo* sender_info =
2982 FindSenderInfo(local_audio_sender_infos_, stream->label(), track->id());
2983 if (sender_info) {
2984 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002985 }
2986}
2987
2988// TODO(deadbeef): Don't destroy RtpSenders here; they should be kept around
2989// indefinitely, when we have unified plan SDP.
2990void PeerConnection::RemoveAudioTrack(AudioTrackInterface* track,
2991 MediaStreamInterface* stream) {
2992 RTC_DCHECK(!IsClosed());
2993 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08002994 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002995 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
2996 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002997 return;
2998 }
Steve Anton4171afb2017-11-20 10:20:22 -08002999 GetAudioTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003000}
3001
3002void PeerConnection::AddVideoTrack(VideoTrackInterface* track,
3003 MediaStreamInterface* stream) {
3004 RTC_DCHECK(!IsClosed());
3005 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003006 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003007 // We already have a sender for this track, so just change the stream_id
3008 // so that it's correct in the next call to CreateOffer.
Steve Anton4171afb2017-11-20 10:20:22 -08003009 sender->internal()->set_stream_id(stream->label());
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003010 return;
3011 }
3012
3013 // Normal case; we've never seen this track before.
Steve Anton02ee47c2018-01-10 16:26:06 -08003014 auto new_sender =
3015 CreateSender(cricket::MEDIA_TYPE_VIDEO, track, {stream->label()});
3016 static_cast<VideoRtpSender*>(new_sender->internal())
Steve Anton47136dd2018-01-12 10:49:35 -08003017 ->SetMediaChannel(video_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08003018 GetVideoTransceiver()->internal()->AddSender(new_sender);
3019 const RtpSenderInfo* sender_info =
3020 FindSenderInfo(local_video_sender_infos_, stream->label(), track->id());
3021 if (sender_info) {
3022 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003023 }
3024}
3025
3026void PeerConnection::RemoveVideoTrack(VideoTrackInterface* track,
3027 MediaStreamInterface* stream) {
3028 RTC_DCHECK(!IsClosed());
3029 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003030 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003031 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
3032 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003033 return;
3034 }
Steve Anton4171afb2017-11-20 10:20:22 -08003035 GetVideoTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003036}
3037
Steve Antonba818672017-11-06 10:21:57 -08003038void PeerConnection::SetIceConnectionState(IceConnectionState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07003039 RTC_DCHECK(signaling_thread()->IsCurrent());
Steve Antonba818672017-11-06 10:21:57 -08003040 if (ice_connection_state_ == new_state) {
3041 return;
3042 }
3043
deadbeefcbecd352015-09-23 11:50:27 -07003044 // After transitioning to "closed", ignore any additional states from
Steve Antonba818672017-11-06 10:21:57 -08003045 // TransportController (such as "disconnected").
deadbeefab9b2d12015-10-14 11:33:11 -07003046 if (IsClosed()) {
deadbeefcbecd352015-09-23 11:50:27 -07003047 return;
3048 }
Steve Antonba818672017-11-06 10:21:57 -08003049
Mirko Bonadei675513b2017-11-09 11:09:25 +01003050 RTC_LOG(LS_INFO) << "Changing IceConnectionState " << ice_connection_state_
3051 << " => " << new_state;
Steve Antonba818672017-11-06 10:21:57 -08003052 RTC_DCHECK(ice_connection_state_ !=
3053 PeerConnectionInterface::kIceConnectionClosed);
3054
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003055 ice_connection_state_ = new_state;
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00003056 observer_->OnIceConnectionChange(ice_connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003057}
3058
3059void PeerConnection::OnIceGatheringChange(
3060 PeerConnectionInterface::IceGatheringState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07003061 RTC_DCHECK(signaling_thread()->IsCurrent());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003062 if (IsClosed()) {
3063 return;
3064 }
3065 ice_gathering_state_ = new_state;
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00003066 observer_->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003067}
3068
jbauch81bf7b02017-03-25 08:31:12 -07003069void PeerConnection::OnIceCandidate(
3070 std::unique_ptr<IceCandidateInterface> candidate) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07003071 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07003072 if (IsClosed()) {
3073 return;
3074 }
jbauch81bf7b02017-03-25 08:31:12 -07003075 observer_->OnIceCandidate(candidate.get());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003076}
3077
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003078void PeerConnection::OnIceCandidatesRemoved(
3079 const std::vector<cricket::Candidate>& candidates) {
3080 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07003081 if (IsClosed()) {
3082 return;
3083 }
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003084 observer_->OnIceCandidatesRemoved(candidates);
3085}
3086
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003087void PeerConnection::ChangeSignalingState(
3088 PeerConnectionInterface::SignalingState signaling_state) {
Steve Antonba818672017-11-06 10:21:57 -08003089 RTC_DCHECK(signaling_thread()->IsCurrent());
3090 if (signaling_state_ == signaling_state) {
3091 return;
3092 }
Mirko Bonadei675513b2017-11-09 11:09:25 +01003093 RTC_LOG(LS_INFO) << "Session: " << session_id() << " Old state: "
3094 << GetSignalingStateString(signaling_state_)
3095 << " New state: "
3096 << GetSignalingStateString(signaling_state);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003097 signaling_state_ = signaling_state;
3098 if (signaling_state == kClosed) {
3099 ice_connection_state_ = kIceConnectionClosed;
3100 observer_->OnIceConnectionChange(ice_connection_state_);
3101 if (ice_gathering_state_ != kIceGatheringComplete) {
3102 ice_gathering_state_ = kIceGatheringComplete;
3103 observer_->OnIceGatheringChange(ice_gathering_state_);
3104 }
3105 }
3106 observer_->OnSignalingChange(signaling_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003107}
3108
deadbeefeb459812015-12-15 19:24:43 -08003109void PeerConnection::OnAudioTrackAdded(AudioTrackInterface* track,
3110 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003111 if (IsClosed()) {
3112 return;
3113 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003114 AddAudioTrack(track, stream);
3115 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003116}
3117
deadbeefeb459812015-12-15 19:24:43 -08003118void PeerConnection::OnAudioTrackRemoved(AudioTrackInterface* track,
3119 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003120 if (IsClosed()) {
3121 return;
3122 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003123 RemoveAudioTrack(track, stream);
3124 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003125}
3126
3127void PeerConnection::OnVideoTrackAdded(VideoTrackInterface* track,
3128 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003129 if (IsClosed()) {
3130 return;
3131 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003132 AddVideoTrack(track, stream);
3133 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003134}
3135
3136void PeerConnection::OnVideoTrackRemoved(VideoTrackInterface* track,
3137 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003138 if (IsClosed()) {
3139 return;
3140 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003141 RemoveVideoTrack(track, stream);
3142 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003143}
3144
Henrik Boström31638672017-11-23 17:48:32 +01003145void PeerConnection::PostSetSessionDescriptionSuccess(
3146 SetSessionDescriptionObserver* observer) {
3147 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
3148 signaling_thread()->Post(RTC_FROM_HERE, this,
3149 MSG_SET_SESSIONDESCRIPTION_SUCCESS, msg);
3150}
3151
deadbeefab9b2d12015-10-14 11:33:11 -07003152void PeerConnection::PostSetSessionDescriptionFailure(
3153 SetSessionDescriptionObserver* observer,
3154 const std::string& error) {
3155 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
3156 msg->error = error;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07003157 signaling_thread()->Post(RTC_FROM_HERE, this,
3158 MSG_SET_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07003159}
3160
3161void PeerConnection::PostCreateSessionDescriptionFailure(
3162 CreateSessionDescriptionObserver* observer,
3163 const std::string& error) {
3164 CreateSessionDescriptionMsg* msg = new CreateSessionDescriptionMsg(observer);
3165 msg->error = error;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07003166 signaling_thread()->Post(RTC_FROM_HERE, this,
3167 MSG_CREATE_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07003168}
3169
zhihuang1c378ed2017-08-17 14:10:50 -07003170void PeerConnection::GetOptionsForOffer(
Steve Antondcc3c022017-12-22 16:02:54 -08003171 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
deadbeefab9b2d12015-10-14 11:33:11 -07003172 cricket::MediaSessionOptions* session_options) {
Steve Antondcc3c022017-12-22 16:02:54 -08003173 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
zhihuang1c378ed2017-08-17 14:10:50 -07003174
Steve Antondcc3c022017-12-22 16:02:54 -08003175 if (IsUnifiedPlan()) {
3176 GetOptionsForUnifiedPlanOffer(offer_answer_options, session_options);
3177 } else {
3178 GetOptionsForPlanBOffer(offer_answer_options, session_options);
3179 }
3180
Steve Antonfa2260d2017-12-28 16:38:23 -08003181 // Intentionally unset the data channel type for RTP data channel with the
3182 // second condition. Otherwise the RTP data channels would be successfully
3183 // negotiated by default and the unit tests in WebRtcDataBrowserTest will fail
3184 // when building with chromium. We want to leave RTP data channels broken, so
3185 // people won't try to use them.
3186 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
3187 session_options->data_channel_type = data_channel_type();
3188 }
3189
Steve Antondcc3c022017-12-22 16:02:54 -08003190 // Apply ICE restart flag and renomination flag.
3191 for (auto& options : session_options->media_description_options) {
3192 options.transport_options.ice_restart = offer_answer_options.ice_restart;
3193 options.transport_options.enable_ice_renomination =
3194 configuration_.enable_ice_renomination;
3195 }
3196
3197 session_options->rtcp_cname = rtcp_cname_;
3198 session_options->crypto_options = factory_->options().crypto_options;
Steve Antone831b8c2018-02-01 12:22:16 -08003199 session_options->is_unified_plan = IsUnifiedPlan();
Steve Antondcc3c022017-12-22 16:02:54 -08003200}
3201
3202void PeerConnection::GetOptionsForPlanBOffer(
3203 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
3204 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07003205 // Figure out transceiver directional preferences.
3206 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
3207 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
3208
3209 // By default, generate sendrecv/recvonly m= sections.
3210 bool recv_audio = true;
3211 bool recv_video = true;
3212
3213 // By default, only offer a new m= section if we have media to send with it.
3214 bool offer_new_audio_description = send_audio;
3215 bool offer_new_video_description = send_video;
3216 bool offer_new_data_description = HasDataChannels();
3217
3218 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-22 16:02:54 -08003219 if (offer_answer_options.offer_to_receive_audio !=
3220 RTCOfferAnswerOptions::kUndefined) {
3221 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003222 offer_new_audio_description =
Steve Antondcc3c022017-12-22 16:02:54 -08003223 offer_new_audio_description ||
3224 (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003225 }
Steve Antondcc3c022017-12-22 16:02:54 -08003226 if (offer_answer_options.offer_to_receive_video !=
3227 RTCOfferAnswerOptions::kUndefined) {
3228 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003229 offer_new_video_description =
Steve Antondcc3c022017-12-22 16:02:54 -08003230 offer_new_video_description ||
3231 (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003232 }
3233
3234 rtc::Optional<size_t> audio_index;
3235 rtc::Optional<size_t> video_index;
3236 rtc::Optional<size_t> data_index;
3237 // If a current description exists, generate m= sections in the same order,
3238 // using the first audio/video/data section that appears and rejecting
3239 // extraneous ones.
Steve Anton75737c02017-11-06 10:37:17 -08003240 if (local_description()) {
zhihuang1c378ed2017-08-17 14:10:50 -07003241 GenerateMediaDescriptionOptions(
Steve Anton75737c02017-11-06 10:37:17 -08003242 local_description(),
Steve Anton1d03a752017-11-27 14:30:09 -08003243 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
3244 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
3245 &audio_index, &video_index, &data_index, session_options);
deadbeefab9b2d12015-10-14 11:33:11 -07003246 }
3247
zhihuang1c378ed2017-08-17 14:10:50 -07003248 // Add audio/video/data m= sections to the end if needed.
3249 if (!audio_index && offer_new_audio_description) {
3250 session_options->media_description_options.push_back(
3251 cricket::MediaDescriptionOptions(
3252 cricket::MEDIA_TYPE_AUDIO, cricket::CN_AUDIO,
Steve Anton1d03a752017-11-27 14:30:09 -08003253 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
3254 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003255 audio_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07003256 }
zhihuang1c378ed2017-08-17 14:10:50 -07003257 if (!video_index && offer_new_video_description) {
3258 session_options->media_description_options.push_back(
3259 cricket::MediaDescriptionOptions(
3260 cricket::MEDIA_TYPE_VIDEO, cricket::CN_VIDEO,
Steve Anton1d03a752017-11-27 14:30:09 -08003261 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
3262 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003263 video_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07003264 }
zhihuang1c378ed2017-08-17 14:10:50 -07003265 if (!data_index && offer_new_data_description) {
3266 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08003267 GetMediaDescriptionOptionsForActiveData(cricket::CN_DATA));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003268 data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07003269 }
3270
3271 cricket::MediaDescriptionOptions* audio_media_description_options =
3272 !audio_index ? nullptr
3273 : &session_options->media_description_options[*audio_index];
3274 cricket::MediaDescriptionOptions* video_media_description_options =
3275 !video_index ? nullptr
3276 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 14:10:50 -07003277
Steve Anton4171afb2017-11-20 10:20:22 -08003278 AddRtpSenderOptions(GetSendersInternal(), audio_media_description_options,
zhihuang1c378ed2017-08-17 14:10:50 -07003279 video_media_description_options);
Steve Antondcc3c022017-12-22 16:02:54 -08003280}
3281
3282// Find a new MID that is not already in |used_mids|, then add it to |used_mids|
3283// and return a reference to it.
3284// Generated MIDs should be no more than 3 bytes long to take up less space in
3285// the RTP packet.
3286static const std::string& AllocateMid(std::set<std::string>* used_mids) {
3287 RTC_DCHECK(used_mids);
3288 // We're boring: just generate MIDs 0, 1, 2, ...
3289 size_t i = 0;
3290 std::set<std::string>::iterator it;
3291 bool inserted;
3292 do {
3293 std::string mid = rtc::ToString(i++);
3294 auto insert_result = used_mids->insert(mid);
3295 it = insert_result.first;
3296 inserted = insert_result.second;
3297 } while (!inserted);
3298 return *it;
3299}
3300
3301static cricket::MediaDescriptionOptions
3302GetMediaDescriptionOptionsForTransceiver(
3303 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3304 transceiver,
3305 const std::string& mid) {
3306 cricket::MediaDescriptionOptions media_description_options(
3307 transceiver->internal()->media_type(), mid, transceiver->direction(),
3308 transceiver->stopped());
Steve Anton5f94aa22018-02-01 10:58:30 -08003309 // This behavior is specified in JSEP. The gist is that:
3310 // 1. The MSID is included if the RtpTransceiver's direction is sendonly or
3311 // sendrecv.
3312 // 2. If the MSID is included, then it must be included in any subsequent
3313 // offer/answer exactly the same until the RtpTransceiver is stopped.
3314 if (!transceiver->stopped() &&
3315 (RtpTransceiverDirectionHasSend(transceiver->direction()) ||
3316 transceiver->internal()->has_ever_been_used_to_send())) {
3317 cricket::SenderOptions sender_options;
3318 sender_options.track_id = transceiver->sender()->id();
3319 sender_options.stream_ids = transceiver->sender()->stream_ids();
3320 // TODO(bugs.webrtc.org/7600): Set num_sim_layers to the number of encodings
3321 // set in the RTP parameters when the transceiver was added.
3322 sender_options.num_sim_layers = 1;
3323 media_description_options.sender_options.push_back(sender_options);
3324 }
Steve Antondcc3c022017-12-22 16:02:54 -08003325 return media_description_options;
3326}
3327
3328void PeerConnection::GetOptionsForUnifiedPlanOffer(
3329 const RTCOfferAnswerOptions& offer_answer_options,
3330 cricket::MediaSessionOptions* session_options) {
3331 // Rules for generating an offer are dictated by JSEP sections 5.2.1 (Initial
3332 // Offers) and 5.2.2 (Subsequent Offers).
3333 RTC_DCHECK_EQ(session_options->media_description_options.size(), 0);
3334 const ContentInfos& local_contents =
3335 (local_description() ? local_description()->description()->contents()
3336 : ContentInfos());
3337 const ContentInfos& remote_contents =
3338 (remote_description() ? remote_description()->description()->contents()
3339 : ContentInfos());
3340 // The mline indices that can be recycled. New transceivers should reuse these
3341 // slots first.
3342 std::queue<size_t> recycleable_mline_indices;
3343 // Track the MIDs used in previous offer/answer exchanges and the current
3344 // offer so that new, unique MIDs are generated.
3345 std::set<std::string> used_mids = seen_mids_;
3346 // First, go through each media section that exists in either the local or
3347 // remote description and generate a media section in this offer for the
3348 // associated transceiver. If a media section can be recycled, generate a
3349 // default, rejected media section here that can be later overwritten.
3350 for (size_t i = 0;
3351 i < std::max(local_contents.size(), remote_contents.size()); ++i) {
3352 // Either |local_content| or |remote_content| is non-null.
3353 const ContentInfo* local_content =
3354 (i < local_contents.size() ? &local_contents[i] : nullptr);
3355 const ContentInfo* remote_content =
3356 (i < remote_contents.size() ? &remote_contents[i] : nullptr);
3357 bool had_been_rejected = (local_content && local_content->rejected) ||
3358 (remote_content && remote_content->rejected);
3359 const std::string& mid =
3360 (local_content ? local_content->name : remote_content->name);
3361 cricket::MediaType media_type =
3362 (local_content ? local_content->media_description()->type()
3363 : remote_content->media_description()->type());
3364 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
3365 media_type == cricket::MEDIA_TYPE_VIDEO) {
3366 auto transceiver = GetAssociatedTransceiver(mid);
3367 RTC_CHECK(transceiver);
3368 // A media section is considered eligible for recycling if it is marked as
3369 // rejected in either the local or remote description.
3370 if (had_been_rejected) {
3371 session_options->media_description_options.push_back(
3372 cricket::MediaDescriptionOptions(
3373 transceiver->internal()->media_type(), mid,
3374 RtpTransceiverDirection::kInactive,
3375 /*stopped=*/true));
3376 recycleable_mline_indices.push(i);
3377 } else {
3378 session_options->media_description_options.push_back(
3379 GetMediaDescriptionOptionsForTransceiver(transceiver, mid));
3380 // CreateOffer shouldn't really cause any state changes in
3381 // PeerConnection, but we need a way to match new transceivers to new
3382 // media sections in SetLocalDescription and JSEP specifies this is done
3383 // by recording the index of the media section generated for the
3384 // transceiver in the offer.
3385 transceiver->internal()->set_mline_index(i);
3386 }
3387 } else {
3388 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antonfa2260d2017-12-28 16:38:23 -08003389 RTC_CHECK(GetDataMid());
3390 if (had_been_rejected || mid != *GetDataMid()) {
3391 session_options->media_description_options.push_back(
3392 GetMediaDescriptionOptionsForRejectedData(mid));
3393 } else {
3394 session_options->media_description_options.push_back(
3395 GetMediaDescriptionOptionsForActiveData(mid));
3396 }
Steve Antondcc3c022017-12-22 16:02:54 -08003397 }
3398 }
3399 // Next, look for transceivers that are newly added (that is, are not stopped
3400 // and not associated). Reuse media sections marked as recyclable first,
3401 // otherwise append to the end of the offer. New media sections should be
3402 // added in the order they were added to the PeerConnection.
3403 for (auto transceiver : transceivers_) {
3404 if (transceiver->mid() || transceiver->stopped()) {
3405 continue;
3406 }
3407 size_t mline_index;
3408 if (!recycleable_mline_indices.empty()) {
3409 mline_index = recycleable_mline_indices.front();
3410 recycleable_mline_indices.pop();
3411 session_options->media_description_options[mline_index] =
3412 GetMediaDescriptionOptionsForTransceiver(transceiver,
3413 AllocateMid(&used_mids));
3414 } else {
3415 mline_index = session_options->media_description_options.size();
3416 session_options->media_description_options.push_back(
3417 GetMediaDescriptionOptionsForTransceiver(transceiver,
3418 AllocateMid(&used_mids)));
3419 }
3420 // See comment above for why CreateOffer changes the transceiver's state.
3421 transceiver->internal()->set_mline_index(mline_index);
3422 }
Steve Antonfa2260d2017-12-28 16:38:23 -08003423 // Lastly, add a m-section if we have local data channels and an m section
3424 // does not already exist.
3425 if (!GetDataMid() && HasDataChannels()) {
3426 session_options->media_description_options.push_back(
3427 GetMediaDescriptionOptionsForActiveData(AllocateMid(&used_mids)));
3428 }
Steve Antondcc3c022017-12-22 16:02:54 -08003429}
3430
3431void PeerConnection::GetOptionsForAnswer(
3432 const RTCOfferAnswerOptions& offer_answer_options,
3433 cricket::MediaSessionOptions* session_options) {
3434 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
3435
3436 if (IsUnifiedPlan()) {
3437 GetOptionsForUnifiedPlanAnswer(offer_answer_options, session_options);
3438 } else {
3439 GetOptionsForPlanBAnswer(offer_answer_options, session_options);
3440 }
3441
Steve Antonfa2260d2017-12-28 16:38:23 -08003442 // Intentionally unset the data channel type for RTP data channel. Otherwise
3443 // the RTP data channels would be successfully negotiated by default and the
3444 // unit tests in WebRtcDataBrowserTest will fail when building with chromium.
3445 // We want to leave RTP data channels broken, so people won't try to use them.
3446 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
3447 session_options->data_channel_type = data_channel_type();
3448 }
3449
Steve Antondcc3c022017-12-22 16:02:54 -08003450 // Apply ICE renomination flag.
3451 for (auto& options : session_options->media_description_options) {
3452 options.transport_options.enable_ice_renomination =
3453 configuration_.enable_ice_renomination;
3454 }
zhihuang8f65cdf2016-05-06 18:40:30 -07003455
3456 session_options->rtcp_cname = rtcp_cname_;
jbauchcb560652016-08-04 05:20:32 -07003457 session_options->crypto_options = factory_->options().crypto_options;
Steve Antone831b8c2018-02-01 12:22:16 -08003458 session_options->is_unified_plan = IsUnifiedPlan();
deadbeefab9b2d12015-10-14 11:33:11 -07003459}
3460
Steve Antondcc3c022017-12-22 16:02:54 -08003461void PeerConnection::GetOptionsForPlanBAnswer(
3462 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07003463 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07003464 // Figure out transceiver directional preferences.
3465 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
3466 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
3467
3468 // By default, generate sendrecv/recvonly m= sections. The direction is also
3469 // restricted by the direction in the offer.
3470 bool recv_audio = true;
3471 bool recv_video = true;
3472
3473 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-22 16:02:54 -08003474 if (offer_answer_options.offer_to_receive_audio !=
3475 RTCOfferAnswerOptions::kUndefined) {
3476 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
deadbeef0ed85b22016-02-23 17:24:52 -08003477 }
Steve Antondcc3c022017-12-22 16:02:54 -08003478 if (offer_answer_options.offer_to_receive_video !=
3479 RTCOfferAnswerOptions::kUndefined) {
3480 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003481 }
3482
3483 rtc::Optional<size_t> audio_index;
3484 rtc::Optional<size_t> video_index;
3485 rtc::Optional<size_t> data_index;
Steve Anton7b581eb2018-02-01 11:32:31 -08003486
3487 // Generate m= sections that match those in the offer.
3488 // Note that mediasession.cc will handle intersection our preferred
3489 // direction with the offered direction.
3490 GenerateMediaDescriptionOptions(
3491 remote_description(),
3492 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
3493 RtpTransceiverDirectionFromSendRecv(send_video, recv_video), &audio_index,
3494 &video_index, &data_index, session_options);
zhihuang1c378ed2017-08-17 14:10:50 -07003495
3496 cricket::MediaDescriptionOptions* audio_media_description_options =
3497 !audio_index ? nullptr
3498 : &session_options->media_description_options[*audio_index];
3499 cricket::MediaDescriptionOptions* video_media_description_options =
3500 !video_index ? nullptr
3501 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 14:10:50 -07003502
Steve Anton4171afb2017-11-20 10:20:22 -08003503 AddRtpSenderOptions(GetSendersInternal(), audio_media_description_options,
zhihuang1c378ed2017-08-17 14:10:50 -07003504 video_media_description_options);
Steve Antondcc3c022017-12-22 16:02:54 -08003505}
zhihuangaf388472016-11-02 16:49:48 -07003506
Steve Antondcc3c022017-12-22 16:02:54 -08003507void PeerConnection::GetOptionsForUnifiedPlanAnswer(
3508 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
3509 cricket::MediaSessionOptions* session_options) {
3510 // Rules for generating an answer are dictated by JSEP sections 5.3.1 (Initial
3511 // Answers) and 5.3.2 (Subsequent Answers).
3512 RTC_DCHECK(remote_description());
3513 RTC_DCHECK(remote_description()->GetType() == SdpType::kOffer);
3514 for (const ContentInfo& content :
3515 remote_description()->description()->contents()) {
3516 cricket::MediaType media_type = content.media_description()->type();
3517 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
3518 media_type == cricket::MEDIA_TYPE_VIDEO) {
3519 auto transceiver = GetAssociatedTransceiver(content.name);
3520 RTC_CHECK(transceiver);
3521 session_options->media_description_options.push_back(
3522 GetMediaDescriptionOptionsForTransceiver(transceiver, content.name));
3523 } else {
3524 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antondbf9d032018-01-19 15:23:40 -08003525 // Reject all data sections if data channels are disabled.
3526 // Reject a data section if it has already been rejected.
3527 // Reject all data sections except for the first one.
3528 if (data_channel_type_ == cricket::DCT_NONE || content.rejected ||
3529 content.name != *GetDataMid()) {
Steve Antonfa2260d2017-12-28 16:38:23 -08003530 session_options->media_description_options.push_back(
3531 GetMediaDescriptionOptionsForRejectedData(content.name));
3532 } else {
3533 session_options->media_description_options.push_back(
3534 GetMediaDescriptionOptionsForActiveData(content.name));
3535 }
Steve Antondcc3c022017-12-22 16:02:54 -08003536 }
3537 }
htaa2a49d92016-03-04 02:51:39 -08003538}
3539
zhihuang1c378ed2017-08-17 14:10:50 -07003540void PeerConnection::GenerateMediaDescriptionOptions(
3541 const SessionDescriptionInterface* session_desc,
Steve Anton1d03a752017-11-27 14:30:09 -08003542 RtpTransceiverDirection audio_direction,
3543 RtpTransceiverDirection video_direction,
zhihuang1c378ed2017-08-17 14:10:50 -07003544 rtc::Optional<size_t>* audio_index,
3545 rtc::Optional<size_t>* video_index,
3546 rtc::Optional<size_t>* data_index,
htaa2a49d92016-03-04 02:51:39 -08003547 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07003548 for (const cricket::ContentInfo& content :
3549 session_desc->description()->contents()) {
3550 if (IsAudioContent(&content)) {
3551 // If we already have an audio m= section, reject this extra one.
3552 if (*audio_index) {
3553 session_options->media_description_options.push_back(
3554 cricket::MediaDescriptionOptions(
3555 cricket::MEDIA_TYPE_AUDIO, content.name,
Steve Anton1d03a752017-11-27 14:30:09 -08003556 RtpTransceiverDirection::kInactive, true));
zhihuang1c378ed2017-08-17 14:10:50 -07003557 } else {
3558 session_options->media_description_options.push_back(
3559 cricket::MediaDescriptionOptions(
3560 cricket::MEDIA_TYPE_AUDIO, content.name, audio_direction,
Steve Anton1d03a752017-11-27 14:30:09 -08003561 audio_direction == RtpTransceiverDirection::kInactive));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003562 *audio_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07003563 }
3564 } else if (IsVideoContent(&content)) {
3565 // If we already have an video m= section, reject this extra one.
3566 if (*video_index) {
3567 session_options->media_description_options.push_back(
3568 cricket::MediaDescriptionOptions(
3569 cricket::MEDIA_TYPE_VIDEO, content.name,
Steve Anton1d03a752017-11-27 14:30:09 -08003570 RtpTransceiverDirection::kInactive, true));
zhihuang1c378ed2017-08-17 14:10:50 -07003571 } else {
3572 session_options->media_description_options.push_back(
3573 cricket::MediaDescriptionOptions(
3574 cricket::MEDIA_TYPE_VIDEO, content.name, video_direction,
Steve Anton1d03a752017-11-27 14:30:09 -08003575 video_direction == RtpTransceiverDirection::kInactive));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003576 *video_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07003577 }
3578 } else {
3579 RTC_DCHECK(IsDataContent(&content));
3580 // If we already have an data m= section, reject this extra one.
3581 if (*data_index) {
3582 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08003583 GetMediaDescriptionOptionsForRejectedData(content.name));
zhihuang1c378ed2017-08-17 14:10:50 -07003584 } else {
3585 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08003586 GetMediaDescriptionOptionsForActiveData(content.name));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003587 *data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07003588 }
3589 }
htaa2a49d92016-03-04 02:51:39 -08003590 }
deadbeefab9b2d12015-10-14 11:33:11 -07003591}
3592
Steve Antonfa2260d2017-12-28 16:38:23 -08003593cricket::MediaDescriptionOptions
3594PeerConnection::GetMediaDescriptionOptionsForActiveData(
3595 const std::string& mid) const {
3596 // Direction for data sections is meaningless, but legacy endpoints might
3597 // expect sendrecv.
3598 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
3599 RtpTransceiverDirection::kSendRecv,
3600 /*stopped=*/false);
3601 AddRtpDataChannelOptions(rtp_data_channels_, &options);
3602 return options;
3603}
3604
3605cricket::MediaDescriptionOptions
3606PeerConnection::GetMediaDescriptionOptionsForRejectedData(
3607 const std::string& mid) const {
3608 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
3609 RtpTransceiverDirection::kInactive,
3610 /*stopped=*/true);
3611 AddRtpDataChannelOptions(rtp_data_channels_, &options);
3612 return options;
3613}
3614
3615rtc::Optional<std::string> PeerConnection::GetDataMid() const {
3616 switch (data_channel_type_) {
3617 case cricket::DCT_RTP:
3618 if (!rtp_data_channel_) {
3619 return rtc::nullopt;
3620 }
3621 return rtp_data_channel_->content_name();
3622 case cricket::DCT_SCTP:
3623 return sctp_content_name_;
3624 default:
3625 return rtc::nullopt;
3626 }
3627}
3628
Steve Anton4171afb2017-11-20 10:20:22 -08003629void PeerConnection::RemoveSenders(cricket::MediaType media_type) {
3630 UpdateLocalSenders(std::vector<cricket::StreamParams>(), media_type);
3631 UpdateRemoteSendersList(std::vector<cricket::StreamParams>(), false,
deadbeefbda7e0b2015-12-08 17:13:40 -08003632 media_type, nullptr);
deadbeeffaac4972015-11-12 15:33:07 -08003633}
3634
Steve Anton4171afb2017-11-20 10:20:22 -08003635void PeerConnection::UpdateRemoteSendersList(
deadbeefab9b2d12015-10-14 11:33:11 -07003636 const cricket::StreamParamsVec& streams,
Steve Anton4171afb2017-11-20 10:20:22 -08003637 bool default_sender_needed,
deadbeefab9b2d12015-10-14 11:33:11 -07003638 cricket::MediaType media_type,
3639 StreamCollection* new_streams) {
Steve Anton4171afb2017-11-20 10:20:22 -08003640 std::vector<RtpSenderInfo>* current_senders =
3641 GetRemoteSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07003642
Steve Anton4171afb2017-11-20 10:20:22 -08003643 // Find removed senders. I.e., senders where the sender id or ssrc don't match
deadbeeffac06552015-11-25 11:26:01 -08003644 // the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08003645 for (auto sender_it = current_senders->begin();
3646 sender_it != current_senders->end();
3647 /* incremented manually */) {
3648 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07003649 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08003650 cricket::GetStreamBySsrc(streams, info.first_ssrc);
3651 bool sender_exists = params && params->id == info.sender_id;
deadbeefbda7e0b2015-12-08 17:13:40 -08003652 // If this is a default track, and we still need it, don't remove it.
Steve Anton4171afb2017-11-20 10:20:22 -08003653 if ((info.stream_label == kDefaultStreamLabel && default_sender_needed) ||
3654 sender_exists) {
3655 ++sender_it;
deadbeefbda7e0b2015-12-08 17:13:40 -08003656 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08003657 OnRemoteSenderRemoved(info, media_type);
3658 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07003659 }
3660 }
3661
Steve Anton4171afb2017-11-20 10:20:22 -08003662 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07003663 for (const cricket::StreamParams& params : streams) {
3664 // The sync_label is the MediaStream label and the |stream.id| is the
Steve Anton4171afb2017-11-20 10:20:22 -08003665 // sender id.
deadbeefab9b2d12015-10-14 11:33:11 -07003666 const std::string& stream_label = params.sync_label;
Steve Anton4171afb2017-11-20 10:20:22 -08003667 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07003668 uint32_t ssrc = params.first_ssrc();
3669
3670 rtc::scoped_refptr<MediaStreamInterface> stream =
3671 remote_streams_->find(stream_label);
3672 if (!stream) {
3673 // This is a new MediaStream. Create a new remote MediaStream.
perkjd61bf802016-03-24 03:16:19 -07003674 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
3675 MediaStream::Create(stream_label));
deadbeefab9b2d12015-10-14 11:33:11 -07003676 remote_streams_->AddStream(stream);
3677 new_streams->AddStream(stream);
3678 }
3679
Steve Anton4171afb2017-11-20 10:20:22 -08003680 const RtpSenderInfo* sender_info =
3681 FindSenderInfo(*current_senders, stream_label, sender_id);
3682 if (!sender_info) {
3683 current_senders->push_back(RtpSenderInfo(stream_label, sender_id, ssrc));
3684 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07003685 }
3686 }
deadbeefbda7e0b2015-12-08 17:13:40 -08003687
Steve Anton4171afb2017-11-20 10:20:22 -08003688 // Add default sender if necessary.
3689 if (default_sender_needed) {
deadbeefbda7e0b2015-12-08 17:13:40 -08003690 rtc::scoped_refptr<MediaStreamInterface> default_stream =
3691 remote_streams_->find(kDefaultStreamLabel);
3692 if (!default_stream) {
3693 // Create the new default MediaStream.
perkjd61bf802016-03-24 03:16:19 -07003694 default_stream = MediaStreamProxy::Create(
3695 rtc::Thread::Current(), MediaStream::Create(kDefaultStreamLabel));
deadbeefbda7e0b2015-12-08 17:13:40 -08003696 remote_streams_->AddStream(default_stream);
3697 new_streams->AddStream(default_stream);
3698 }
Steve Anton4171afb2017-11-20 10:20:22 -08003699 std::string default_sender_id = (media_type == cricket::MEDIA_TYPE_AUDIO)
3700 ? kDefaultAudioSenderId
3701 : kDefaultVideoSenderId;
3702 const RtpSenderInfo* default_sender_info = FindSenderInfo(
3703 *current_senders, kDefaultStreamLabel, default_sender_id);
3704 if (!default_sender_info) {
3705 current_senders->push_back(
3706 RtpSenderInfo(kDefaultStreamLabel, default_sender_id, 0));
3707 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefbda7e0b2015-12-08 17:13:40 -08003708 }
3709 }
deadbeefab9b2d12015-10-14 11:33:11 -07003710}
3711
Steve Anton4171afb2017-11-20 10:20:22 -08003712void PeerConnection::OnRemoteSenderAdded(const RtpSenderInfo& sender_info,
3713 cricket::MediaType media_type) {
3714 MediaStreamInterface* stream =
3715 remote_streams_->find(sender_info.stream_label);
deadbeefab9b2d12015-10-14 11:33:11 -07003716
3717 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 10:20:22 -08003718 CreateAudioReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07003719 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 10:20:22 -08003720 CreateVideoReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07003721 } else {
nisseeb4ca4e2017-01-12 02:24:27 -08003722 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07003723 }
3724}
3725
Steve Anton4171afb2017-11-20 10:20:22 -08003726void PeerConnection::OnRemoteSenderRemoved(const RtpSenderInfo& sender_info,
3727 cricket::MediaType media_type) {
3728 MediaStreamInterface* stream =
3729 remote_streams_->find(sender_info.stream_label);
deadbeefab9b2d12015-10-14 11:33:11 -07003730
Henrik Boström933d8b02017-10-10 10:05:16 -07003731 rtc::scoped_refptr<RtpReceiverInterface> receiver;
deadbeefab9b2d12015-10-14 11:33:11 -07003732 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
perkjd61bf802016-03-24 03:16:19 -07003733 // When the MediaEngine audio channel is destroyed, the RemoteAudioSource
3734 // will be notified which will end the AudioRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08003735 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07003736 rtc::scoped_refptr<AudioTrackInterface> audio_track =
Steve Anton4171afb2017-11-20 10:20:22 -08003737 stream->FindAudioTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07003738 if (audio_track) {
deadbeefab9b2d12015-10-14 11:33:11 -07003739 stream->RemoveTrack(audio_track);
deadbeefab9b2d12015-10-14 11:33:11 -07003740 }
3741 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
perkjd61bf802016-03-24 03:16:19 -07003742 // Stopping or destroying a VideoRtpReceiver will end the
3743 // VideoRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08003744 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07003745 rtc::scoped_refptr<VideoTrackInterface> video_track =
Steve Anton4171afb2017-11-20 10:20:22 -08003746 stream->FindVideoTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07003747 if (video_track) {
perkjd61bf802016-03-24 03:16:19 -07003748 // There's no guarantee the track is still available, e.g. the track may
3749 // have been removed from the stream by an application.
deadbeefab9b2d12015-10-14 11:33:11 -07003750 stream->RemoveTrack(video_track);
deadbeefab9b2d12015-10-14 11:33:11 -07003751 }
3752 } else {
nisseede5da42017-01-12 05:15:36 -08003753 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07003754 }
Henrik Boström933d8b02017-10-10 10:05:16 -07003755 if (receiver) {
3756 observer_->OnRemoveTrack(receiver);
3757 }
deadbeefab9b2d12015-10-14 11:33:11 -07003758}
3759
3760void PeerConnection::UpdateEndedRemoteMediaStreams() {
3761 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams_to_remove;
3762 for (size_t i = 0; i < remote_streams_->count(); ++i) {
3763 MediaStreamInterface* stream = remote_streams_->at(i);
3764 if (stream->GetAudioTracks().empty() && stream->GetVideoTracks().empty()) {
3765 streams_to_remove.push_back(stream);
3766 }
3767 }
3768
Taylor Brandstetter98cde262016-05-31 13:02:21 -07003769 for (auto& stream : streams_to_remove) {
deadbeefab9b2d12015-10-14 11:33:11 -07003770 remote_streams_->RemoveStream(stream);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07003771 observer_->OnRemoveStream(std::move(stream));
deadbeefab9b2d12015-10-14 11:33:11 -07003772 }
3773}
3774
Steve Anton4171afb2017-11-20 10:20:22 -08003775void PeerConnection::UpdateLocalSenders(
deadbeefab9b2d12015-10-14 11:33:11 -07003776 const std::vector<cricket::StreamParams>& streams,
3777 cricket::MediaType media_type) {
Steve Anton4171afb2017-11-20 10:20:22 -08003778 std::vector<RtpSenderInfo>* current_senders = GetLocalSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07003779
3780 // Find removed tracks. I.e., tracks where the track id, stream label or ssrc
3781 // don't match the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08003782 for (auto sender_it = current_senders->begin();
3783 sender_it != current_senders->end();
3784 /* incremented manually */) {
3785 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07003786 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08003787 cricket::GetStreamBySsrc(streams, info.first_ssrc);
3788 if (!params || params->id != info.sender_id ||
deadbeefab9b2d12015-10-14 11:33:11 -07003789 params->sync_label != info.stream_label) {
Steve Anton4171afb2017-11-20 10:20:22 -08003790 OnLocalSenderRemoved(info, media_type);
3791 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07003792 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08003793 ++sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07003794 }
3795 }
3796
Steve Anton4171afb2017-11-20 10:20:22 -08003797 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07003798 for (const cricket::StreamParams& params : streams) {
3799 // The sync_label is the MediaStream label and the |stream.id| is the
Steve Anton4171afb2017-11-20 10:20:22 -08003800 // sender id.
deadbeefab9b2d12015-10-14 11:33:11 -07003801 const std::string& stream_label = params.sync_label;
Steve Anton4171afb2017-11-20 10:20:22 -08003802 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07003803 uint32_t ssrc = params.first_ssrc();
Steve Anton4171afb2017-11-20 10:20:22 -08003804 const RtpSenderInfo* sender_info =
3805 FindSenderInfo(*current_senders, stream_label, sender_id);
3806 if (!sender_info) {
3807 current_senders->push_back(RtpSenderInfo(stream_label, sender_id, ssrc));
3808 OnLocalSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07003809 }
3810 }
3811}
3812
Steve Anton4171afb2017-11-20 10:20:22 -08003813void PeerConnection::OnLocalSenderAdded(const RtpSenderInfo& sender_info,
3814 cricket::MediaType media_type) {
3815 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08003816 if (!sender) {
Steve Anton4171afb2017-11-20 10:20:22 -08003817 RTC_LOG(LS_WARNING) << "An unknown RtpSender with id "
3818 << sender_info.sender_id
Mirko Bonadei675513b2017-11-09 11:09:25 +01003819 << " has been configured in the local description.";
deadbeefab9b2d12015-10-14 11:33:11 -07003820 return;
3821 }
3822
deadbeeffac06552015-11-25 11:26:01 -08003823 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003824 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
3825 << " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08003826 return;
deadbeefab9b2d12015-10-14 11:33:11 -07003827 }
deadbeeffac06552015-11-25 11:26:01 -08003828
Steve Anton4171afb2017-11-20 10:20:22 -08003829 sender->internal()->set_stream_id(sender_info.stream_label);
3830 sender->internal()->SetSsrc(sender_info.first_ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07003831}
3832
Steve Anton4171afb2017-11-20 10:20:22 -08003833void PeerConnection::OnLocalSenderRemoved(const RtpSenderInfo& sender_info,
3834 cricket::MediaType media_type) {
3835 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08003836 if (!sender) {
3837 // This is the normal case. I.e., RemoveStream has been called and the
deadbeefab9b2d12015-10-14 11:33:11 -07003838 // SessionDescriptions has been renegotiated.
3839 return;
3840 }
deadbeeffac06552015-11-25 11:26:01 -08003841
3842 // A sender has been removed from the SessionDescription but it's still
3843 // associated with the PeerConnection. This only occurs if the SDP doesn't
3844 // match with the calls to CreateSender, AddStream and RemoveStream.
3845 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003846 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
3847 << " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08003848 return;
deadbeefab9b2d12015-10-14 11:33:11 -07003849 }
deadbeeffac06552015-11-25 11:26:01 -08003850
Steve Anton4171afb2017-11-20 10:20:22 -08003851 sender->internal()->SetSsrc(0);
deadbeefab9b2d12015-10-14 11:33:11 -07003852}
3853
3854void PeerConnection::UpdateLocalRtpDataChannels(
3855 const cricket::StreamParamsVec& streams) {
3856 std::vector<std::string> existing_channels;
3857
3858 // Find new and active data channels.
3859 for (const cricket::StreamParams& params : streams) {
3860 // |it->sync_label| is actually the data channel label. The reason is that
3861 // we use the same naming of data channels as we do for
3862 // MediaStreams and Tracks.
3863 // For MediaStreams, the sync_label is the MediaStream label and the
3864 // track label is the same as |streamid|.
3865 const std::string& channel_label = params.sync_label;
3866 auto data_channel_it = rtp_data_channels_.find(channel_label);
nisse7ce109a2017-01-31 00:57:56 -08003867 if (data_channel_it == rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003868 RTC_LOG(LS_ERROR) << "channel label not found";
deadbeefab9b2d12015-10-14 11:33:11 -07003869 continue;
3870 }
3871 // Set the SSRC the data channel should use for sending.
3872 data_channel_it->second->SetSendSsrc(params.first_ssrc());
3873 existing_channels.push_back(data_channel_it->first);
3874 }
3875
3876 UpdateClosingRtpDataChannels(existing_channels, true);
3877}
3878
3879void PeerConnection::UpdateRemoteRtpDataChannels(
3880 const cricket::StreamParamsVec& streams) {
3881 std::vector<std::string> existing_channels;
3882
3883 // Find new and active data channels.
3884 for (const cricket::StreamParams& params : streams) {
3885 // The data channel label is either the mslabel or the SSRC if the mslabel
3886 // does not exist. Ex a=ssrc:444330170 mslabel:test1.
3887 std::string label = params.sync_label.empty()
3888 ? rtc::ToString(params.first_ssrc())
3889 : params.sync_label;
3890 auto data_channel_it = rtp_data_channels_.find(label);
3891 if (data_channel_it == rtp_data_channels_.end()) {
3892 // This is a new data channel.
3893 CreateRemoteRtpDataChannel(label, params.first_ssrc());
3894 } else {
3895 data_channel_it->second->SetReceiveSsrc(params.first_ssrc());
3896 }
3897 existing_channels.push_back(label);
3898 }
3899
3900 UpdateClosingRtpDataChannels(existing_channels, false);
3901}
3902
3903void PeerConnection::UpdateClosingRtpDataChannels(
3904 const std::vector<std::string>& active_channels,
3905 bool is_local_update) {
3906 auto it = rtp_data_channels_.begin();
3907 while (it != rtp_data_channels_.end()) {
3908 DataChannel* data_channel = it->second;
3909 if (std::find(active_channels.begin(), active_channels.end(),
3910 data_channel->label()) != active_channels.end()) {
3911 ++it;
3912 continue;
3913 }
3914
3915 if (is_local_update) {
3916 data_channel->SetSendSsrc(0);
3917 } else {
3918 data_channel->RemotePeerRequestClose();
3919 }
3920
3921 if (data_channel->state() == DataChannel::kClosed) {
3922 rtp_data_channels_.erase(it);
3923 it = rtp_data_channels_.begin();
3924 } else {
3925 ++it;
3926 }
3927 }
3928}
3929
3930void PeerConnection::CreateRemoteRtpDataChannel(const std::string& label,
3931 uint32_t remote_ssrc) {
3932 rtc::scoped_refptr<DataChannel> channel(
3933 InternalCreateDataChannel(label, nullptr));
3934 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003935 RTC_LOG(LS_WARNING) << "Remote peer requested a DataChannel but"
3936 << "CreateDataChannel failed.";
deadbeefab9b2d12015-10-14 11:33:11 -07003937 return;
3938 }
3939 channel->SetReceiveSsrc(remote_ssrc);
deadbeefa601f5c2016-06-06 14:27:39 -07003940 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
3941 DataChannelProxy::Create(signaling_thread(), channel);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07003942 observer_->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07003943}
3944
3945rtc::scoped_refptr<DataChannel> PeerConnection::InternalCreateDataChannel(
3946 const std::string& label,
3947 const InternalDataChannelInit* config) {
3948 if (IsClosed()) {
3949 return nullptr;
3950 }
Steve Anton75737c02017-11-06 10:37:17 -08003951 if (data_channel_type() == cricket::DCT_NONE) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003952 RTC_LOG(LS_ERROR)
deadbeefab9b2d12015-10-14 11:33:11 -07003953 << "InternalCreateDataChannel: Data is not supported in this call.";
3954 return nullptr;
3955 }
3956 InternalDataChannelInit new_config =
3957 config ? (*config) : InternalDataChannelInit();
Steve Anton75737c02017-11-06 10:37:17 -08003958 if (data_channel_type() == cricket::DCT_SCTP) {
deadbeefab9b2d12015-10-14 11:33:11 -07003959 if (new_config.id < 0) {
3960 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08003961 if ((GetSctpSslRole(&role)) &&
deadbeefab9b2d12015-10-14 11:33:11 -07003962 !sid_allocator_.AllocateSid(role, &new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003963 RTC_LOG(LS_ERROR)
3964 << "No id can be allocated for the SCTP data channel.";
deadbeefab9b2d12015-10-14 11:33:11 -07003965 return nullptr;
3966 }
3967 } else if (!sid_allocator_.ReserveSid(new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003968 RTC_LOG(LS_ERROR) << "Failed to create a SCTP data channel "
3969 << "because the id is already in use or out of range.";
deadbeefab9b2d12015-10-14 11:33:11 -07003970 return nullptr;
3971 }
3972 }
3973
Steve Anton75737c02017-11-06 10:37:17 -08003974 rtc::scoped_refptr<DataChannel> channel(
3975 DataChannel::Create(this, data_channel_type(), label, new_config));
deadbeefab9b2d12015-10-14 11:33:11 -07003976 if (!channel) {
3977 sid_allocator_.ReleaseSid(new_config.id);
3978 return nullptr;
3979 }
3980
3981 if (channel->data_channel_type() == cricket::DCT_RTP) {
3982 if (rtp_data_channels_.find(channel->label()) != rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003983 RTC_LOG(LS_ERROR) << "DataChannel with label " << channel->label()
3984 << " already exists.";
deadbeefab9b2d12015-10-14 11:33:11 -07003985 return nullptr;
3986 }
3987 rtp_data_channels_[channel->label()] = channel;
3988 } else {
3989 RTC_DCHECK(channel->data_channel_type() == cricket::DCT_SCTP);
3990 sctp_data_channels_.push_back(channel);
3991 channel->SignalClosed.connect(this,
3992 &PeerConnection::OnSctpDataChannelClosed);
3993 }
3994
Steve Anton2d8609c2018-01-23 16:38:46 -08003995 SignalDataChannelCreated_(channel.get());
deadbeefab9b2d12015-10-14 11:33:11 -07003996 return channel;
3997}
3998
3999bool PeerConnection::HasDataChannels() const {
4000 return !rtp_data_channels_.empty() || !sctp_data_channels_.empty();
4001}
4002
4003void PeerConnection::AllocateSctpSids(rtc::SSLRole role) {
4004 for (const auto& channel : sctp_data_channels_) {
4005 if (channel->id() < 0) {
4006 int sid;
4007 if (!sid_allocator_.AllocateSid(role, &sid)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004008 RTC_LOG(LS_ERROR) << "Failed to allocate SCTP sid.";
deadbeefab9b2d12015-10-14 11:33:11 -07004009 continue;
4010 }
4011 channel->SetSctpSid(sid);
4012 }
4013 }
4014}
4015
4016void PeerConnection::OnSctpDataChannelClosed(DataChannel* channel) {
deadbeefbd292462015-12-14 18:15:29 -08004017 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeefab9b2d12015-10-14 11:33:11 -07004018 for (auto it = sctp_data_channels_.begin(); it != sctp_data_channels_.end();
4019 ++it) {
4020 if (it->get() == channel) {
4021 if (channel->id() >= 0) {
4022 sid_allocator_.ReleaseSid(channel->id());
4023 }
deadbeefbd292462015-12-14 18:15:29 -08004024 // Since this method is triggered by a signal from the DataChannel,
4025 // we can't free it directly here; we need to free it asynchronously.
4026 sctp_data_channels_to_free_.push_back(*it);
deadbeefab9b2d12015-10-14 11:33:11 -07004027 sctp_data_channels_.erase(it);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07004028 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_FREE_DATACHANNELS,
4029 nullptr);
deadbeefab9b2d12015-10-14 11:33:11 -07004030 return;
4031 }
4032 }
4033}
4034
deadbeefab9b2d12015-10-14 11:33:11 -07004035void PeerConnection::OnDataChannelDestroyed() {
4036 // Use a temporary copy of the RTP/SCTP DataChannel list because the
4037 // DataChannel may callback to us and try to modify the list.
4038 std::map<std::string, rtc::scoped_refptr<DataChannel>> temp_rtp_dcs;
4039 temp_rtp_dcs.swap(rtp_data_channels_);
4040 for (const auto& kv : temp_rtp_dcs) {
4041 kv.second->OnTransportChannelDestroyed();
4042 }
4043
4044 std::vector<rtc::scoped_refptr<DataChannel>> temp_sctp_dcs;
4045 temp_sctp_dcs.swap(sctp_data_channels_);
4046 for (const auto& channel : temp_sctp_dcs) {
4047 channel->OnTransportChannelDestroyed();
4048 }
4049}
4050
4051void PeerConnection::OnDataChannelOpenMessage(
4052 const std::string& label,
4053 const InternalDataChannelInit& config) {
4054 rtc::scoped_refptr<DataChannel> channel(
4055 InternalCreateDataChannel(label, &config));
4056 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004057 RTC_LOG(LS_ERROR) << "Failed to create DataChannel from the OPEN message.";
deadbeefab9b2d12015-10-14 11:33:11 -07004058 return;
4059 }
4060
deadbeefa601f5c2016-06-06 14:27:39 -07004061 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
4062 DataChannelProxy::Create(signaling_thread(), channel);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07004063 observer_->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07004064}
4065
Steve Anton4171afb2017-11-20 10:20:22 -08004066rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
4067PeerConnection::GetAudioTransceiver() const {
4068 // This method only works with Plan B SDP, where there is a single
4069 // audio/video transceiver.
4070 RTC_DCHECK(!IsUnifiedPlan());
4071 for (auto transceiver : transceivers_) {
4072 if (transceiver->internal()->media_type() == cricket::MEDIA_TYPE_AUDIO) {
4073 return transceiver;
4074 }
4075 }
4076 RTC_NOTREACHED();
4077 return nullptr;
4078}
4079
4080rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
4081PeerConnection::GetVideoTransceiver() const {
4082 // This method only works with Plan B SDP, where there is a single
4083 // audio/video transceiver.
4084 RTC_DCHECK(!IsUnifiedPlan());
4085 for (auto transceiver : transceivers_) {
4086 if (transceiver->internal()->media_type() == cricket::MEDIA_TYPE_VIDEO) {
4087 return transceiver;
4088 }
4089 }
4090 RTC_NOTREACHED();
4091 return nullptr;
4092}
4093
4094// TODO(bugs.webrtc.org/7600): Remove this when multiple transceivers with
4095// individual transceiver directions are supported.
zhihuang1c378ed2017-08-17 14:10:50 -07004096bool PeerConnection::HasRtpSender(cricket::MediaType type) const {
Steve Anton4171afb2017-11-20 10:20:22 -08004097 switch (type) {
4098 case cricket::MEDIA_TYPE_AUDIO:
4099 return !GetAudioTransceiver()->internal()->senders().empty();
4100 case cricket::MEDIA_TYPE_VIDEO:
4101 return !GetVideoTransceiver()->internal()->senders().empty();
4102 case cricket::MEDIA_TYPE_DATA:
4103 return false;
4104 }
4105 RTC_NOTREACHED();
4106 return false;
zhihuang1c378ed2017-08-17 14:10:50 -07004107}
4108
Steve Anton4171afb2017-11-20 10:20:22 -08004109rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
4110PeerConnection::FindSenderForTrack(MediaStreamTrackInterface* track) const {
4111 for (auto transceiver : transceivers_) {
4112 for (auto sender : transceiver->internal()->senders()) {
4113 if (sender->track() == track) {
4114 return sender;
4115 }
4116 }
4117 }
4118 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08004119}
4120
Steve Anton4171afb2017-11-20 10:20:22 -08004121rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
4122PeerConnection::FindSenderById(const std::string& sender_id) const {
4123 for (auto transceiver : transceivers_) {
4124 for (auto sender : transceiver->internal()->senders()) {
4125 if (sender->id() == sender_id) {
4126 return sender;
4127 }
4128 }
4129 }
4130 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07004131}
4132
Steve Anton4171afb2017-11-20 10:20:22 -08004133rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
4134PeerConnection::FindReceiverById(const std::string& receiver_id) const {
4135 for (auto transceiver : transceivers_) {
4136 for (auto receiver : transceiver->internal()->receivers()) {
4137 if (receiver->id() == receiver_id) {
4138 return receiver;
4139 }
4140 }
4141 }
4142 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07004143}
4144
Steve Anton4171afb2017-11-20 10:20:22 -08004145std::vector<PeerConnection::RtpSenderInfo>*
4146PeerConnection::GetRemoteSenderInfos(cricket::MediaType media_type) {
4147 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
4148 media_type == cricket::MEDIA_TYPE_VIDEO);
4149 return (media_type == cricket::MEDIA_TYPE_AUDIO)
4150 ? &remote_audio_sender_infos_
4151 : &remote_video_sender_infos_;
4152}
4153
4154std::vector<PeerConnection::RtpSenderInfo>* PeerConnection::GetLocalSenderInfos(
deadbeefab9b2d12015-10-14 11:33:11 -07004155 cricket::MediaType media_type) {
4156 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
4157 media_type == cricket::MEDIA_TYPE_VIDEO);
Steve Anton4171afb2017-11-20 10:20:22 -08004158 return (media_type == cricket::MEDIA_TYPE_AUDIO) ? &local_audio_sender_infos_
4159 : &local_video_sender_infos_;
deadbeefab9b2d12015-10-14 11:33:11 -07004160}
4161
Steve Anton4171afb2017-11-20 10:20:22 -08004162const PeerConnection::RtpSenderInfo* PeerConnection::FindSenderInfo(
4163 const std::vector<PeerConnection::RtpSenderInfo>& infos,
deadbeefab9b2d12015-10-14 11:33:11 -07004164 const std::string& stream_label,
Steve Anton4171afb2017-11-20 10:20:22 -08004165 const std::string sender_id) const {
4166 for (const RtpSenderInfo& sender_info : infos) {
4167 if (sender_info.stream_label == stream_label &&
4168 sender_info.sender_id == sender_id) {
4169 return &sender_info;
deadbeefab9b2d12015-10-14 11:33:11 -07004170 }
4171 }
4172 return nullptr;
4173}
4174
4175DataChannel* PeerConnection::FindDataChannelBySid(int sid) const {
4176 for (const auto& channel : sctp_data_channels_) {
4177 if (channel->id() == sid) {
4178 return channel;
4179 }
4180 }
4181 return nullptr;
4182}
4183
deadbeef91dd5672016-05-18 16:55:30 -07004184bool PeerConnection::InitializePortAllocator_n(
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004185 const RTCConfiguration& configuration) {
4186 cricket::ServerAddresses stun_servers;
4187 std::vector<cricket::RelayServerConfig> turn_servers;
deadbeef293e9262017-01-11 12:28:30 -08004188 if (ParseIceServers(configuration.servers, &stun_servers, &turn_servers) !=
4189 RTCErrorType::NONE) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004190 return false;
4191 }
4192
Taylor Brandstetterf8e65772016-06-27 17:20:15 -07004193 port_allocator_->Initialize();
4194
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004195 // To handle both internal and externally created port allocator, we will
4196 // enable BUNDLE here.
4197 int portallocator_flags = port_allocator_->flags();
4198 portallocator_flags |= cricket::PORTALLOCATOR_ENABLE_SHARED_SOCKET |
zhihuangb09b3f92017-03-07 14:40:51 -08004199 cricket::PORTALLOCATOR_ENABLE_IPV6 |
4200 cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI;
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004201 // If the disable-IPv6 flag was specified, we'll not override it
4202 // by experiment.
4203 if (configuration.disable_ipv6) {
4204 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
sprangc1b57a12017-02-28 08:50:47 -08004205 } else if (webrtc::field_trial::FindFullName("WebRTC-IPv6Default")
4206 .find("Disabled") == 0) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004207 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
4208 }
4209
zhihuangb09b3f92017-03-07 14:40:51 -08004210 if (configuration.disable_ipv6_on_wifi) {
4211 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI);
Mirko Bonadei675513b2017-11-09 11:09:25 +01004212 RTC_LOG(LS_INFO) << "IPv6 candidates on Wi-Fi are disabled.";
zhihuangb09b3f92017-03-07 14:40:51 -08004213 }
4214
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004215 if (configuration.tcp_candidate_policy == kTcpCandidatePolicyDisabled) {
4216 portallocator_flags |= cricket::PORTALLOCATOR_DISABLE_TCP;
Mirko Bonadei675513b2017-11-09 11:09:25 +01004217 RTC_LOG(LS_INFO) << "TCP candidates are disabled.";
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004218 }
4219
honghaiz60347052016-05-31 18:29:12 -07004220 if (configuration.candidate_network_policy ==
4221 kCandidateNetworkPolicyLowCost) {
4222 portallocator_flags |= cricket::PORTALLOCATOR_DISABLE_COSTLY_NETWORKS;
Mirko Bonadei675513b2017-11-09 11:09:25 +01004223 RTC_LOG(LS_INFO) << "Do not gather candidates on high-cost networks";
honghaiz60347052016-05-31 18:29:12 -07004224 }
4225
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004226 port_allocator_->set_flags(portallocator_flags);
4227 // No step delay is used while allocating ports.
4228 port_allocator_->set_step_delay(cricket::kMinimumStepDelay);
4229 port_allocator_->set_candidate_filter(
4230 ConvertIceTransportTypeToCandidateFilter(configuration.type));
deadbeefd21eab32017-07-26 16:50:11 -07004231 port_allocator_->set_max_ipv6_networks(configuration.max_ipv6_networks);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004232
4233 // Call this last since it may create pooled allocator sessions using the
4234 // properties set above.
4235 port_allocator_->SetConfiguration(stun_servers, turn_servers,
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -07004236 configuration.ice_candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02004237 configuration.prune_turn_ports,
4238 configuration.turn_customizer);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004239 return true;
4240}
4241
deadbeef91dd5672016-05-18 16:55:30 -07004242bool PeerConnection::ReconfigurePortAllocator_n(
deadbeef293e9262017-01-11 12:28:30 -08004243 const cricket::ServerAddresses& stun_servers,
4244 const std::vector<cricket::RelayServerConfig>& turn_servers,
4245 IceTransportsType type,
4246 int candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02004247 bool prune_turn_ports,
4248 webrtc::TurnCustomizer* turn_customizer) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004249 port_allocator_->set_candidate_filter(
deadbeef293e9262017-01-11 12:28:30 -08004250 ConvertIceTransportTypeToCandidateFilter(type));
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004251 // Call this last since it may create pooled allocator sessions using the
4252 // candidate filter set above.
deadbeef6de92f92016-12-12 18:49:32 -08004253 return port_allocator_->SetConfiguration(
Jonas Orelandbdcee282017-10-10 14:01:40 +02004254 stun_servers, turn_servers, candidate_pool_size, prune_turn_ports,
4255 turn_customizer);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004256}
4257
Steve Antonba818672017-11-06 10:21:57 -08004258cricket::ChannelManager* PeerConnection::channel_manager() const {
4259 return factory_->channel_manager();
4260}
4261
4262MetricsObserverInterface* PeerConnection::metrics_observer() const {
4263 return uma_observer_;
4264}
4265
Elad Alon99c3fe52017-10-13 16:29:40 +02004266bool PeerConnection::StartRtcEventLog_w(
Bjorn Tereliusde939432017-11-20 17:38:14 +01004267 std::unique_ptr<RtcEventLogOutput> output,
4268 int64_t output_period_ms) {
zhihuang77985012017-02-07 15:45:16 -08004269 if (!event_log_) {
4270 return false;
4271 }
Bjorn Tereliusde939432017-11-20 17:38:14 +01004272 return event_log_->StartLogging(std::move(output), output_period_ms);
ivoc14d5dbe2016-07-04 07:06:55 -07004273}
4274
4275void PeerConnection::StopRtcEventLog_w() {
zhihuang77985012017-02-07 15:45:16 -08004276 if (event_log_) {
4277 event_log_->StopLogging();
4278 }
ivoc14d5dbe2016-07-04 07:06:55 -07004279}
nisseeaabdf62017-05-05 02:23:02 -07004280
Steve Anton75737c02017-11-06 10:37:17 -08004281cricket::BaseChannel* PeerConnection::GetChannel(
4282 const std::string& content_name) {
Steve Antondcc3c022017-12-22 16:02:54 -08004283 for (auto transceiver : transceivers_) {
4284 cricket::BaseChannel* channel = transceiver->internal()->channel();
4285 if (channel && channel->content_name() == content_name) {
4286 return channel;
4287 }
Steve Anton75737c02017-11-06 10:37:17 -08004288 }
4289 if (rtp_data_channel() &&
4290 rtp_data_channel()->content_name() == content_name) {
4291 return rtp_data_channel();
4292 }
4293 return nullptr;
4294}
4295
4296bool PeerConnection::GetSctpSslRole(rtc::SSLRole* role) {
4297 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004298 RTC_LOG(LS_INFO)
4299 << "Local and Remote descriptions must be applied to get the "
4300 << "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08004301 return false;
4302 }
4303 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004304 RTC_LOG(LS_INFO) << "Non-rejected SCTP m= section is needed to get the "
4305 << "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08004306 return false;
4307 }
4308
4309 return transport_controller_->GetSslRole(*sctp_transport_name_, role);
4310}
4311
4312bool PeerConnection::GetSslRole(const std::string& content_name,
4313 rtc::SSLRole* role) {
4314 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004315 RTC_LOG(LS_INFO)
4316 << "Local and Remote descriptions must be applied to get the "
4317 << "SSL Role of the session.";
Steve Anton75737c02017-11-06 10:37:17 -08004318 return false;
4319 }
4320
4321 return transport_controller_->GetSslRole(GetTransportName(content_name),
4322 role);
4323}
4324
Steve Anton75737c02017-11-06 10:37:17 -08004325// TODO(steveanton): Eventually it'd be nice to store the channels as a single
4326// vector of BaseChannel pointers instead of separate voice and video channel
4327// vectors. At that point, this will become a simple getter.
4328std::vector<cricket::BaseChannel*> PeerConnection::Channels() const {
4329 std::vector<cricket::BaseChannel*> channels;
Steve Anton4171afb2017-11-20 10:20:22 -08004330 if (voice_channel()) {
4331 channels.push_back(voice_channel());
4332 }
4333 if (video_channel()) {
4334 channels.push_back(video_channel());
4335 }
Steve Anton75737c02017-11-06 10:37:17 -08004336 if (rtp_data_channel_) {
4337 channels.push_back(rtp_data_channel_);
4338 }
4339 return channels;
4340}
4341
Steve Antonf8470812017-12-04 10:46:21 -08004342void PeerConnection::SetSessionError(SessionError error,
4343 const std::string& error_desc) {
4344 RTC_DCHECK_RUN_ON(signaling_thread());
4345 if (error != session_error_) {
4346 session_error_ = error;
4347 session_error_desc_ = error_desc;
Steve Anton75737c02017-11-06 10:37:17 -08004348 }
4349}
4350
Steve Anton3828c062017-12-06 10:34:51 -08004351RTCError PeerConnection::UpdateSessionState(SdpType type,
Steve Anton8a006912017-12-04 15:25:56 -08004352 cricket::ContentSource source) {
4353 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08004354
4355 // If there's already a pending error then no state transition should happen.
4356 // But all call-sites should be verifying this before calling us!
Steve Antonf8470812017-12-04 10:46:21 -08004357 RTC_DCHECK(session_error() == SessionError::kNone);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004358
4359 // If this is an answer then we know whether to BUNDLE or not. If both the
4360 // local and remote side have agreed to BUNDLE, go ahead and enable it.
Steve Anton3828c062017-12-06 10:34:51 -08004361 if (type == SdpType::kAnswer) {
Steve Anton75737c02017-11-06 10:37:17 -08004362 const cricket::ContentGroup* local_bundle =
4363 local_description()->description()->GetGroupByName(
4364 cricket::GROUP_TYPE_BUNDLE);
4365 const cricket::ContentGroup* remote_bundle =
4366 remote_description()->description()->GetGroupByName(
4367 cricket::GROUP_TYPE_BUNDLE);
4368 if (local_bundle && remote_bundle) {
4369 // The answerer decides the transport to bundle on.
4370 const cricket::ContentGroup* answer_bundle =
4371 (source == cricket::CS_LOCAL ? local_bundle : remote_bundle);
4372 if (!EnableBundle(*answer_bundle)) {
Steve Anton8a006912017-12-04 15:25:56 -08004373 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
4374 kEnableBundleFailed);
Steve Anton75737c02017-11-06 10:37:17 -08004375 }
4376 }
Steve Anton75737c02017-11-06 10:37:17 -08004377 }
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004378
4379 // Only push down the transport description after potentially enabling BUNDLE;
4380 // we don't want to push down a description on a transport about to be
4381 // destroyed.
Steve Anton3828c062017-12-06 10:34:51 -08004382 RTCError error = PushdownTransportDescription(source, type);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004383 if (!error.ok()) {
4384 return error;
4385 }
4386
4387 // If this is answer-ish we're ready to let media flow.
Steve Anton3828c062017-12-06 10:34:51 -08004388 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Antoned10bd92017-12-05 10:52:59 -08004389 EnableSending();
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004390 }
4391
4392 // Update the signaling state according to the specified state machine (see
4393 // https://w3c.github.io/webrtc-pc/#rtcsignalingstate-enum).
Steve Anton3828c062017-12-06 10:34:51 -08004394 if (type == SdpType::kOffer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004395 ChangeSignalingState(source == cricket::CS_LOCAL
4396 ? PeerConnectionInterface::kHaveLocalOffer
4397 : PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton3828c062017-12-06 10:34:51 -08004398 } else if (type == SdpType::kPrAnswer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004399 ChangeSignalingState(source == cricket::CS_LOCAL
4400 ? PeerConnectionInterface::kHaveLocalPrAnswer
4401 : PeerConnectionInterface::kHaveRemotePrAnswer);
4402 } else {
Steve Anton3828c062017-12-06 10:34:51 -08004403 RTC_DCHECK(type == SdpType::kAnswer);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004404 ChangeSignalingState(PeerConnectionInterface::kStable);
4405 }
4406
4407 // Update internal objects according to the session description's media
4408 // descriptions.
Steve Anton3828c062017-12-06 10:34:51 -08004409 error = PushdownMediaDescription(type, source);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004410 if (!error.ok()) {
4411 SetSessionError(SessionError::kContent, error.message());
4412 }
4413 if (session_error() != SessionError::kNone) {
4414 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
4415 }
4416
Steve Anton8a006912017-12-04 15:25:56 -08004417 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08004418}
4419
Steve Anton8a006912017-12-04 15:25:56 -08004420RTCError PeerConnection::PushdownMediaDescription(
Steve Anton3828c062017-12-06 10:34:51 -08004421 SdpType type,
Steve Anton8a006912017-12-04 15:25:56 -08004422 cricket::ContentSource source) {
Steve Antoned10bd92017-12-05 10:52:59 -08004423 const SessionDescriptionInterface* sdesc =
4424 (source == cricket::CS_LOCAL ? local_description()
4425 : remote_description());
Steve Anton75737c02017-11-06 10:37:17 -08004426 RTC_DCHECK(sdesc);
Steve Antoned10bd92017-12-05 10:52:59 -08004427
4428 // Push down the new SDP media section for each audio/video transceiver.
4429 for (auto transceiver : transceivers_) {
Steve Anton75737c02017-11-06 10:37:17 -08004430 const ContentInfo* content_info =
Steve Antoned10bd92017-12-05 10:52:59 -08004431 FindMediaSectionForTransceiver(transceiver, sdesc);
4432 cricket::BaseChannel* channel = transceiver->internal()->channel();
4433 if (!channel || !content_info || content_info->rejected) {
Steve Anton75737c02017-11-06 10:37:17 -08004434 continue;
4435 }
4436 const MediaContentDescription* content_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08004437 content_info->media_description();
Steve Antoned10bd92017-12-05 10:52:59 -08004438 if (!content_desc) {
4439 continue;
4440 }
4441 std::string error;
4442 bool success =
4443 (source == cricket::CS_LOCAL)
Steve Anton3828c062017-12-06 10:34:51 -08004444 ? channel->SetLocalContent(content_desc, type, &error)
4445 : channel->SetRemoteContent(content_desc, type, &error);
Steve Antoned10bd92017-12-05 10:52:59 -08004446 if (!success) {
4447 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, std::move(error));
4448 }
4449 }
4450
4451 // If using the RtpDataChannel, push down the new SDP section for it too.
4452 if (rtp_data_channel_) {
4453 const ContentInfo* data_content =
4454 cricket::GetFirstDataContent(sdesc->description());
4455 if (data_content && !data_content->rejected) {
4456 const MediaContentDescription* data_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08004457 data_content->media_description();
Steve Antoned10bd92017-12-05 10:52:59 -08004458 if (data_desc) {
4459 std::string error;
4460 bool success =
4461 (source == cricket::CS_LOCAL)
Steve Anton3828c062017-12-06 10:34:51 -08004462 ? rtp_data_channel_->SetLocalContent(data_desc, type, &error)
4463 : rtp_data_channel_->SetRemoteContent(data_desc, type,
Steve Antoned10bd92017-12-05 10:52:59 -08004464 &error);
4465 if (!success) {
4466 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
4467 std::move(error));
4468 }
Steve Anton75737c02017-11-06 10:37:17 -08004469 }
4470 }
4471 }
Steve Antoned10bd92017-12-05 10:52:59 -08004472
Steve Anton75737c02017-11-06 10:37:17 -08004473 // Need complete offer/answer with an SCTP m= section before starting SCTP,
4474 // according to https://tools.ietf.org/html/draft-ietf-mmusic-sctp-sdp-19
4475 if (sctp_transport_ && local_description() && remote_description() &&
4476 cricket::GetFirstDataContent(local_description()->description()) &&
4477 cricket::GetFirstDataContent(remote_description()->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08004478 bool success = network_thread()->Invoke<bool>(
Steve Anton75737c02017-11-06 10:37:17 -08004479 RTC_FROM_HERE,
4480 rtc::Bind(&PeerConnection::PushdownSctpParameters_n, this, source));
Steve Anton8a006912017-12-04 15:25:56 -08004481 if (!success) {
4482 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
4483 "Failed to push down SCTP parameters.");
4484 }
Steve Anton75737c02017-11-06 10:37:17 -08004485 }
Steve Antoned10bd92017-12-05 10:52:59 -08004486
Steve Anton8a006912017-12-04 15:25:56 -08004487 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08004488}
4489
4490bool PeerConnection::PushdownSctpParameters_n(cricket::ContentSource source) {
4491 RTC_DCHECK(network_thread()->IsCurrent());
4492 RTC_DCHECK(local_description());
4493 RTC_DCHECK(remote_description());
4494 // Apply the SCTP port (which is hidden inside a DataCodec structure...)
4495 // When we support "max-message-size", that would also be pushed down here.
4496 return sctp_transport_->Start(
4497 GetSctpPort(local_description()->description()),
4498 GetSctpPort(remote_description()->description()));
4499}
4500
Steve Anton8a006912017-12-04 15:25:56 -08004501RTCError PeerConnection::PushdownTransportDescription(
4502 cricket::ContentSource source,
Steve Anton3828c062017-12-06 10:34:51 -08004503 SdpType type) {
Steve Anton8a006912017-12-04 15:25:56 -08004504 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08004505
Steve Anton8a006912017-12-04 15:25:56 -08004506 const SessionDescriptionInterface* sdesc =
4507 (source == cricket::CS_LOCAL ? local_description()
4508 : remote_description());
4509 RTC_DCHECK(sdesc);
4510 for (const cricket::TransportInfo& tinfo :
4511 sdesc->description()->transport_infos()) {
4512 std::string error;
4513 bool success;
4514 if (source == cricket::CS_LOCAL) {
4515 success = transport_controller_->SetLocalTransportDescription(
Steve Anton3828c062017-12-06 10:34:51 -08004516 tinfo.content_name, tinfo.description, type, &error);
Steve Anton8a006912017-12-04 15:25:56 -08004517 } else {
4518 success = transport_controller_->SetRemoteTransportDescription(
Steve Anton3828c062017-12-06 10:34:51 -08004519 tinfo.content_name, tinfo.description, type, &error);
Steve Anton8a006912017-12-04 15:25:56 -08004520 }
4521 if (!success) {
Steve Antondcc3c022017-12-22 16:02:54 -08004522 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
4523 "Failed to push down transport description for " +
4524 tinfo.content_name + ": " + error);
Steve Anton75737c02017-11-06 10:37:17 -08004525 }
4526 }
4527
Steve Anton8a006912017-12-04 15:25:56 -08004528 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08004529}
4530
4531bool PeerConnection::GetTransportDescription(
4532 const SessionDescription* description,
4533 const std::string& content_name,
4534 cricket::TransportDescription* tdesc) {
4535 if (!description || !tdesc) {
4536 return false;
4537 }
4538 const TransportInfo* transport_info =
4539 description->GetTransportInfoByName(content_name);
4540 if (!transport_info) {
4541 return false;
4542 }
4543 *tdesc = transport_info->description;
4544 return true;
4545}
4546
4547bool PeerConnection::EnableBundle(const cricket::ContentGroup& bundle) {
4548 const std::string* first_content_name = bundle.FirstContentName();
4549 if (!first_content_name) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004550 RTC_LOG(LS_WARNING) << "Tried to BUNDLE with no contents.";
Steve Anton75737c02017-11-06 10:37:17 -08004551 return false;
4552 }
4553 const std::string& transport_name = *first_content_name;
4554
4555 auto maybe_set_transport = [this, bundle,
4556 transport_name](cricket::BaseChannel* ch) {
4557 if (!ch || !bundle.HasContentName(ch->content_name())) {
Steve Antoned10bd92017-12-05 10:52:59 -08004558 return;
Steve Anton75737c02017-11-06 10:37:17 -08004559 }
4560
4561 std::string old_transport_name = ch->transport_name();
4562 if (old_transport_name == transport_name) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004563 RTC_LOG(LS_INFO) << "BUNDLE already enabled for " << ch->content_name()
4564 << " on " << transport_name << ".";
Steve Antoned10bd92017-12-05 10:52:59 -08004565 return;
Steve Anton75737c02017-11-06 10:37:17 -08004566 }
4567
4568 cricket::DtlsTransportInternal* rtp_dtls_transport =
4569 transport_controller_->CreateDtlsTransport(
4570 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4571 bool need_rtcp = (ch->rtcp_dtls_transport() != nullptr);
4572 cricket::DtlsTransportInternal* rtcp_dtls_transport = nullptr;
4573 if (need_rtcp) {
4574 rtcp_dtls_transport = transport_controller_->CreateDtlsTransport(
4575 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
4576 }
4577
4578 ch->SetTransports(rtp_dtls_transport, rtcp_dtls_transport);
Mirko Bonadei675513b2017-11-09 11:09:25 +01004579 RTC_LOG(LS_INFO) << "Enabled BUNDLE for " << ch->content_name() << " on "
4580 << transport_name << ".";
Steve Anton75737c02017-11-06 10:37:17 -08004581 transport_controller_->DestroyDtlsTransport(
4582 old_transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4583 // If the channel needs rtcp, it means that the channel used to have a
4584 // rtcp transport which needs to be deleted now.
4585 if (need_rtcp) {
4586 transport_controller_->DestroyDtlsTransport(
4587 old_transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
4588 }
Steve Anton75737c02017-11-06 10:37:17 -08004589 };
4590
Steve Antoned10bd92017-12-05 10:52:59 -08004591 for (auto transceiver : transceivers_) {
4592 maybe_set_transport(transceiver->internal()->channel());
Steve Anton75737c02017-11-06 10:37:17 -08004593 }
Steve Antoned10bd92017-12-05 10:52:59 -08004594 maybe_set_transport(rtp_data_channel_);
4595
Steve Anton75737c02017-11-06 10:37:17 -08004596 // For SCTP, transport creation/deletion happens here instead of in the
4597 // object itself.
4598 if (sctp_transport_) {
4599 RTC_DCHECK(sctp_transport_name_);
4600 RTC_DCHECK(sctp_content_name_);
4601 if (transport_name != *sctp_transport_name_ &&
4602 bundle.HasContentName(*sctp_content_name_)) {
4603 network_thread()->Invoke<void>(
4604 RTC_FROM_HERE, rtc::Bind(&PeerConnection::ChangeSctpTransport_n, this,
4605 transport_name));
4606 }
4607 }
4608
4609 return true;
4610}
4611
Steve Anton75737c02017-11-06 10:37:17 -08004612cricket::IceConfig PeerConnection::ParseIceConfig(
4613 const PeerConnectionInterface::RTCConfiguration& config) const {
4614 cricket::ContinualGatheringPolicy gathering_policy;
4615 // TODO(honghaiz): Add the third continual gathering policy in
4616 // PeerConnectionInterface and map it to GATHER_CONTINUALLY_AND_RECOVER.
4617 switch (config.continual_gathering_policy) {
4618 case PeerConnectionInterface::GATHER_ONCE:
4619 gathering_policy = cricket::GATHER_ONCE;
4620 break;
4621 case PeerConnectionInterface::GATHER_CONTINUALLY:
4622 gathering_policy = cricket::GATHER_CONTINUALLY;
4623 break;
4624 default:
4625 RTC_NOTREACHED();
4626 gathering_policy = cricket::GATHER_ONCE;
4627 }
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08004628
Steve Anton75737c02017-11-06 10:37:17 -08004629 cricket::IceConfig ice_config;
4630 ice_config.receiving_timeout = config.ice_connection_receiving_timeout;
4631 ice_config.prioritize_most_likely_candidate_pairs =
4632 config.prioritize_most_likely_ice_candidate_pairs;
4633 ice_config.backup_connection_ping_interval =
4634 config.ice_backup_candidate_pair_ping_interval;
4635 ice_config.continual_gathering_policy = gathering_policy;
4636 ice_config.presume_writable_when_fully_relayed =
4637 config.presume_writable_when_fully_relayed;
4638 ice_config.ice_check_min_interval = config.ice_check_min_interval;
4639 ice_config.regather_all_networks_interval_range =
4640 config.ice_regather_interval_range;
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08004641 ice_config.network_preference = config.network_preference;
Steve Anton75737c02017-11-06 10:37:17 -08004642 return ice_config;
4643}
4644
Steve Anton75737c02017-11-06 10:37:17 -08004645bool PeerConnection::GetLocalTrackIdBySsrc(uint32_t ssrc,
4646 std::string* track_id) {
4647 if (!local_description()) {
4648 return false;
4649 }
4650 return webrtc::GetTrackIdBySsrc(local_description()->description(), ssrc,
4651 track_id);
4652}
4653
4654bool PeerConnection::GetRemoteTrackIdBySsrc(uint32_t ssrc,
4655 std::string* track_id) {
4656 if (!remote_description()) {
4657 return false;
4658 }
4659 return webrtc::GetTrackIdBySsrc(remote_description()->description(), ssrc,
4660 track_id);
4661}
4662
4663bool PeerConnection::SendData(const cricket::SendDataParams& params,
4664 const rtc::CopyOnWriteBuffer& payload,
4665 cricket::SendDataResult* result) {
4666 if (!rtp_data_channel_ && !sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004667 RTC_LOG(LS_ERROR) << "SendData called when rtp_data_channel_ "
4668 << "and sctp_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08004669 return false;
4670 }
4671 return rtp_data_channel_
4672 ? rtp_data_channel_->SendData(params, payload, result)
4673 : network_thread()->Invoke<bool>(
4674 RTC_FROM_HERE,
4675 Bind(&cricket::SctpTransportInternal::SendData,
4676 sctp_transport_.get(), params, payload, result));
4677}
4678
4679bool PeerConnection::ConnectDataChannel(DataChannel* webrtc_data_channel) {
4680 if (!rtp_data_channel_ && !sctp_transport_) {
4681 // Don't log an error here, because DataChannels are expected to call
4682 // ConnectDataChannel in this state. It's the only way to initially tell
4683 // whether or not the underlying transport is ready.
4684 return false;
4685 }
4686 if (rtp_data_channel_) {
4687 rtp_data_channel_->SignalReadyToSendData.connect(
4688 webrtc_data_channel, &DataChannel::OnChannelReady);
4689 rtp_data_channel_->SignalDataReceived.connect(webrtc_data_channel,
4690 &DataChannel::OnDataReceived);
4691 } else {
4692 SignalSctpReadyToSendData.connect(webrtc_data_channel,
4693 &DataChannel::OnChannelReady);
4694 SignalSctpDataReceived.connect(webrtc_data_channel,
4695 &DataChannel::OnDataReceived);
4696 SignalSctpStreamClosedRemotely.connect(
4697 webrtc_data_channel, &DataChannel::OnStreamClosedRemotely);
4698 }
4699 return true;
4700}
4701
4702void PeerConnection::DisconnectDataChannel(DataChannel* webrtc_data_channel) {
4703 if (!rtp_data_channel_ && !sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004704 RTC_LOG(LS_ERROR)
4705 << "DisconnectDataChannel called when rtp_data_channel_ and "
4706 "sctp_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08004707 return;
4708 }
4709 if (rtp_data_channel_) {
4710 rtp_data_channel_->SignalReadyToSendData.disconnect(webrtc_data_channel);
4711 rtp_data_channel_->SignalDataReceived.disconnect(webrtc_data_channel);
4712 } else {
4713 SignalSctpReadyToSendData.disconnect(webrtc_data_channel);
4714 SignalSctpDataReceived.disconnect(webrtc_data_channel);
4715 SignalSctpStreamClosedRemotely.disconnect(webrtc_data_channel);
4716 }
4717}
4718
4719void PeerConnection::AddSctpDataStream(int sid) {
4720 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004721 RTC_LOG(LS_ERROR)
4722 << "AddSctpDataStream called when sctp_transport_ is NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08004723 return;
4724 }
4725 network_thread()->Invoke<void>(
4726 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::OpenStream,
4727 sctp_transport_.get(), sid));
4728}
4729
4730void PeerConnection::RemoveSctpDataStream(int sid) {
4731 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004732 RTC_LOG(LS_ERROR) << "RemoveSctpDataStream called when sctp_transport_ is "
4733 << "NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08004734 return;
4735 }
4736 network_thread()->Invoke<void>(
4737 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::ResetStream,
4738 sctp_transport_.get(), sid));
4739}
4740
4741bool PeerConnection::ReadyToSendData() const {
4742 return (rtp_data_channel_ && rtp_data_channel_->ready_to_send_data()) ||
4743 sctp_ready_to_send_data_;
4744}
4745
4746std::unique_ptr<SessionStats> PeerConnection::GetSessionStats_s() {
4747 RTC_DCHECK(signaling_thread()->IsCurrent());
4748 ChannelNamePairs channel_name_pairs;
4749 if (voice_channel()) {
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004750 channel_name_pairs.voice = ChannelNamePair(
4751 voice_channel()->content_name(), voice_channel()->transport_name());
Steve Anton75737c02017-11-06 10:37:17 -08004752 }
4753 if (video_channel()) {
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004754 channel_name_pairs.video = ChannelNamePair(
4755 video_channel()->content_name(), video_channel()->transport_name());
Steve Anton75737c02017-11-06 10:37:17 -08004756 }
4757 if (rtp_data_channel()) {
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004758 channel_name_pairs.data =
Steve Anton75737c02017-11-06 10:37:17 -08004759 ChannelNamePair(rtp_data_channel()->content_name(),
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004760 rtp_data_channel()->transport_name());
Steve Anton75737c02017-11-06 10:37:17 -08004761 }
4762 if (sctp_transport_) {
4763 RTC_DCHECK(sctp_content_name_);
4764 RTC_DCHECK(sctp_transport_name_);
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004765 channel_name_pairs.data =
4766 ChannelNamePair(*sctp_content_name_, *sctp_transport_name_);
Steve Anton75737c02017-11-06 10:37:17 -08004767 }
4768 return GetSessionStats(channel_name_pairs);
4769}
4770
4771std::unique_ptr<SessionStats> PeerConnection::GetSessionStats(
4772 const ChannelNamePairs& channel_name_pairs) {
4773 if (network_thread()->IsCurrent()) {
4774 return GetSessionStats_n(channel_name_pairs);
4775 }
4776 return network_thread()->Invoke<std::unique_ptr<SessionStats>>(
4777 RTC_FROM_HERE,
4778 rtc::Bind(&PeerConnection::GetSessionStats_n, this, channel_name_pairs));
4779}
4780
4781bool PeerConnection::GetLocalCertificate(
4782 const std::string& transport_name,
4783 rtc::scoped_refptr<rtc::RTCCertificate>* certificate) {
4784 return transport_controller_->GetLocalCertificate(transport_name,
4785 certificate);
4786}
4787
4788std::unique_ptr<rtc::SSLCertificate> PeerConnection::GetRemoteSSLCertificate(
4789 const std::string& transport_name) {
4790 return transport_controller_->GetRemoteSSLCertificate(transport_name);
4791}
4792
4793cricket::DataChannelType PeerConnection::data_channel_type() const {
4794 return data_channel_type_;
4795}
4796
4797bool PeerConnection::IceRestartPending(const std::string& content_name) const {
4798 return pending_ice_restarts_.find(content_name) !=
4799 pending_ice_restarts_.end();
4800}
4801
Steve Anton75737c02017-11-06 10:37:17 -08004802bool PeerConnection::NeedsIceRestart(const std::string& content_name) const {
4803 return transport_controller_->NeedsIceRestart(content_name);
4804}
4805
4806void PeerConnection::OnCertificateReady(
4807 const rtc::scoped_refptr<rtc::RTCCertificate>& certificate) {
4808 transport_controller_->SetLocalCertificate(certificate);
4809}
4810
4811void PeerConnection::OnDtlsSrtpSetupFailure(cricket::BaseChannel*, bool rtcp) {
Steve Antonf8470812017-12-04 10:46:21 -08004812 SetSessionError(SessionError::kTransport,
4813 rtcp ? kDtlsSrtpSetupFailureRtcp : kDtlsSrtpSetupFailureRtp);
Steve Anton75737c02017-11-06 10:37:17 -08004814}
4815
4816void PeerConnection::OnTransportControllerConnectionState(
4817 cricket::IceConnectionState state) {
4818 switch (state) {
4819 case cricket::kIceConnectionConnecting:
4820 // If the current state is Connected or Completed, then there were
4821 // writable channels but now there are not, so the next state must
4822 // be Disconnected.
4823 // kIceConnectionConnecting is currently used as the default,
4824 // un-connected state by the TransportController, so its only use is
4825 // detecting disconnections.
4826 if (ice_connection_state_ ==
4827 PeerConnectionInterface::kIceConnectionConnected ||
4828 ice_connection_state_ ==
4829 PeerConnectionInterface::kIceConnectionCompleted) {
4830 SetIceConnectionState(
4831 PeerConnectionInterface::kIceConnectionDisconnected);
4832 }
4833 break;
4834 case cricket::kIceConnectionFailed:
4835 SetIceConnectionState(PeerConnectionInterface::kIceConnectionFailed);
4836 break;
4837 case cricket::kIceConnectionConnected:
Mirko Bonadei675513b2017-11-09 11:09:25 +01004838 RTC_LOG(LS_INFO) << "Changing to ICE connected state because "
4839 << "all transports are writable.";
Steve Anton75737c02017-11-06 10:37:17 -08004840 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
4841 break;
4842 case cricket::kIceConnectionCompleted:
Mirko Bonadei675513b2017-11-09 11:09:25 +01004843 RTC_LOG(LS_INFO) << "Changing to ICE completed state because "
4844 << "all transports are complete.";
Steve Anton75737c02017-11-06 10:37:17 -08004845 if (ice_connection_state_ !=
4846 PeerConnectionInterface::kIceConnectionConnected) {
4847 // If jumping directly from "checking" to "connected",
4848 // signal "connected" first.
4849 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
4850 }
4851 SetIceConnectionState(PeerConnectionInterface::kIceConnectionCompleted);
4852 if (metrics_observer()) {
4853 ReportTransportStats();
4854 }
4855 break;
4856 default:
4857 RTC_NOTREACHED();
4858 }
4859}
4860
4861void PeerConnection::OnTransportControllerCandidatesGathered(
4862 const std::string& transport_name,
4863 const cricket::Candidates& candidates) {
4864 RTC_DCHECK(signaling_thread()->IsCurrent());
4865 int sdp_mline_index;
4866 if (!GetLocalCandidateMediaIndex(transport_name, &sdp_mline_index)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004867 RTC_LOG(LS_ERROR)
4868 << "OnTransportControllerCandidatesGathered: content name "
4869 << transport_name << " not found";
Steve Anton75737c02017-11-06 10:37:17 -08004870 return;
4871 }
4872
4873 for (cricket::Candidates::const_iterator citer = candidates.begin();
4874 citer != candidates.end(); ++citer) {
4875 // Use transport_name as the candidate media id.
4876 std::unique_ptr<JsepIceCandidate> candidate(
4877 new JsepIceCandidate(transport_name, sdp_mline_index, *citer));
4878 if (local_description()) {
4879 mutable_local_description()->AddCandidate(candidate.get());
4880 }
4881 OnIceCandidate(std::move(candidate));
4882 }
4883}
4884
4885void PeerConnection::OnTransportControllerCandidatesRemoved(
4886 const std::vector<cricket::Candidate>& candidates) {
4887 RTC_DCHECK(signaling_thread()->IsCurrent());
4888 // Sanity check.
4889 for (const cricket::Candidate& candidate : candidates) {
4890 if (candidate.transport_name().empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004891 RTC_LOG(LS_ERROR) << "OnTransportControllerCandidatesRemoved: "
4892 << "empty content name in candidate "
4893 << candidate.ToString();
Steve Anton75737c02017-11-06 10:37:17 -08004894 return;
4895 }
4896 }
4897
4898 if (local_description()) {
4899 mutable_local_description()->RemoveCandidates(candidates);
4900 }
4901 OnIceCandidatesRemoved(candidates);
4902}
4903
4904void PeerConnection::OnTransportControllerDtlsHandshakeError(
4905 rtc::SSLHandshakeError error) {
4906 if (metrics_observer()) {
4907 metrics_observer()->IncrementEnumCounter(
4908 webrtc::kEnumCounterDtlsHandshakeError, static_cast<int>(error),
4909 static_cast<int>(rtc::SSLHandshakeError::MAX_VALUE));
4910 }
4911}
4912
Steve Antoned10bd92017-12-05 10:52:59 -08004913void PeerConnection::EnableSending() {
4914 for (auto transceiver : transceivers_) {
4915 cricket::BaseChannel* channel = transceiver->internal()->channel();
4916 if (channel && !channel->enabled()) {
4917 channel->Enable(true);
4918 }
Steve Anton75737c02017-11-06 10:37:17 -08004919 }
4920
Steve Anton4171afb2017-11-20 10:20:22 -08004921 if (rtp_data_channel_ && !rtp_data_channel_->enabled()) {
Steve Anton75737c02017-11-06 10:37:17 -08004922 rtp_data_channel_->Enable(true);
Steve Anton4171afb2017-11-20 10:20:22 -08004923 }
Steve Anton75737c02017-11-06 10:37:17 -08004924}
4925
4926// Returns the media index for a local ice candidate given the content name.
4927bool PeerConnection::GetLocalCandidateMediaIndex(
4928 const std::string& content_name,
4929 int* sdp_mline_index) {
4930 if (!local_description() || !sdp_mline_index) {
4931 return false;
4932 }
4933
4934 bool content_found = false;
4935 const ContentInfos& contents = local_description()->description()->contents();
4936 for (size_t index = 0; index < contents.size(); ++index) {
4937 if (contents[index].name == content_name) {
4938 *sdp_mline_index = static_cast<int>(index);
4939 content_found = true;
4940 break;
4941 }
4942 }
4943 return content_found;
4944}
4945
4946bool PeerConnection::UseCandidatesInSessionDescription(
4947 const SessionDescriptionInterface* remote_desc) {
4948 if (!remote_desc) {
4949 return true;
4950 }
4951 bool ret = true;
4952
4953 for (size_t m = 0; m < remote_desc->number_of_mediasections(); ++m) {
4954 const IceCandidateCollection* candidates = remote_desc->candidates(m);
4955 for (size_t n = 0; n < candidates->count(); ++n) {
4956 const IceCandidateInterface* candidate = candidates->at(n);
4957 bool valid = false;
4958 if (!ReadyToUseRemoteCandidate(candidate, remote_desc, &valid)) {
4959 if (valid) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004960 RTC_LOG(LS_INFO)
4961 << "UseCandidatesInSessionDescription: Not ready to use "
4962 << "candidate.";
Steve Anton75737c02017-11-06 10:37:17 -08004963 }
4964 continue;
4965 }
4966 ret = UseCandidate(candidate);
4967 if (!ret) {
4968 break;
4969 }
4970 }
4971 }
4972 return ret;
4973}
4974
4975bool PeerConnection::UseCandidate(const IceCandidateInterface* candidate) {
4976 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
4977 size_t remote_content_size =
4978 remote_description()->description()->contents().size();
4979 if (mediacontent_index >= remote_content_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004980 RTC_LOG(LS_ERROR) << "UseCandidate: Invalid candidate media index.";
Steve Anton75737c02017-11-06 10:37:17 -08004981 return false;
4982 }
4983
4984 cricket::ContentInfo content =
4985 remote_description()->description()->contents()[mediacontent_index];
4986 std::vector<cricket::Candidate> candidates;
4987 candidates.push_back(candidate->candidate());
4988 // Invoking BaseSession method to handle remote candidates.
4989 std::string error;
4990 if (transport_controller_->AddRemoteCandidates(content.name, candidates,
4991 &error)) {
4992 // Candidates successfully submitted for checking.
4993 if (ice_connection_state_ == PeerConnectionInterface::kIceConnectionNew ||
4994 ice_connection_state_ ==
4995 PeerConnectionInterface::kIceConnectionDisconnected) {
4996 // If state is New, then the session has just gotten its first remote ICE
4997 // candidates, so go to Checking.
4998 // If state is Disconnected, the session is re-using old candidates or
4999 // receiving additional ones, so go to Checking.
5000 // If state is Connected, stay Connected.
5001 // TODO(bemasc): If state is Connected, and the new candidates are for a
5002 // newly added transport, then the state actually _should_ move to
5003 // checking. Add a way to distinguish that case.
5004 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
5005 }
5006 // TODO(bemasc): If state is Completed, go back to Connected.
5007 } else {
5008 if (!error.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005009 RTC_LOG(LS_WARNING) << error;
Steve Anton75737c02017-11-06 10:37:17 -08005010 }
5011 }
5012 return true;
5013}
5014
5015void PeerConnection::RemoveUnusedChannels(const SessionDescription* desc) {
Steve Anton75737c02017-11-06 10:37:17 -08005016 // Destroy video channel first since it may have a pointer to the
5017 // voice channel.
5018 const cricket::ContentInfo* video_info = cricket::GetFirstVideoContent(desc);
Steve Anton6fec8802017-12-04 10:37:29 -08005019 if (!video_info || video_info->rejected) {
5020 DestroyTransceiverChannel(GetVideoTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08005021 }
5022
Steve Anton6fec8802017-12-04 10:37:29 -08005023 const cricket::ContentInfo* audio_info = cricket::GetFirstAudioContent(desc);
5024 if (!audio_info || audio_info->rejected) {
5025 DestroyTransceiverChannel(GetAudioTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08005026 }
5027
5028 const cricket::ContentInfo* data_info = cricket::GetFirstDataContent(desc);
5029 if (!data_info || data_info->rejected) {
Steve Anton6fec8802017-12-04 10:37:29 -08005030 DestroyDataChannel();
Steve Anton75737c02017-11-06 10:37:17 -08005031 }
5032}
5033
Steve Antoneda6ccd2017-12-04 10:21:55 -08005034std::string PeerConnection::GetTransportNameForMediaSection(
5035 const std::string& mid,
5036 const cricket::ContentGroup* bundle_group) const {
5037 if (!bundle_group) {
5038 return mid;
Steve Anton75737c02017-11-06 10:37:17 -08005039 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005040 const std::string* first_content_name = bundle_group->FirstContentName();
Steve Anton75737c02017-11-06 10:37:17 -08005041 if (!first_content_name) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005042 RTC_LOG(LS_WARNING) << "Tried to BUNDLE with no contents.";
Steve Antoneda6ccd2017-12-04 10:21:55 -08005043 return mid;
Steve Anton75737c02017-11-06 10:37:17 -08005044 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005045 if (!bundle_group->HasContentName(mid)) {
5046 RTC_LOG(LS_WARNING) << mid << " is not part of any bundle group";
5047 return mid;
Steve Anton75737c02017-11-06 10:37:17 -08005048 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005049 RTC_LOG(LS_INFO) << "Bundling " << mid << " on " << *first_content_name;
5050 return *first_content_name;
Steve Anton75737c02017-11-06 10:37:17 -08005051}
5052
Steve Antondcc3c022017-12-22 16:02:54 -08005053RTCErrorOr<const cricket::ContentGroup*> PeerConnection::GetEarlyBundleGroup(
5054 const SessionDescription& desc) const {
Steve Anton75737c02017-11-06 10:37:17 -08005055 const cricket::ContentGroup* bundle_group = nullptr;
5056 if (configuration_.bundle_policy ==
5057 PeerConnectionInterface::kBundlePolicyMaxBundle) {
Steve Antondcc3c022017-12-22 16:02:54 -08005058 bundle_group = desc.GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton75737c02017-11-06 10:37:17 -08005059 if (!bundle_group) {
Steve Anton8a006912017-12-04 15:25:56 -08005060 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5061 "max-bundle configured but session description "
5062 "has no BUNDLE group");
Steve Anton75737c02017-11-06 10:37:17 -08005063 }
5064 }
Steve Antondcc3c022017-12-22 16:02:54 -08005065 return std::move(bundle_group);
5066}
5067
5068RTCError PeerConnection::CreateChannels(const SessionDescription& desc) {
5069 auto bundle_group_or_error = GetEarlyBundleGroup(desc);
5070 if (!bundle_group_or_error.ok()) {
5071 return bundle_group_or_error.MoveError();
5072 }
5073 const cricket::ContentGroup* bundle_group = bundle_group_or_error.MoveValue();
Steve Anton75737c02017-11-06 10:37:17 -08005074
Steve Antoneda6ccd2017-12-04 10:21:55 -08005075 // Creating the media channels and transport proxies.
Steve Antondcc3c022017-12-22 16:02:54 -08005076 const cricket::ContentInfo* voice = cricket::GetFirstAudioContent(&desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08005077 if (voice && !voice->rejected &&
5078 !GetAudioTransceiver()->internal()->channel()) {
5079 cricket::VoiceChannel* voice_channel = CreateVoiceChannel(
5080 voice->name,
5081 GetTransportNameForMediaSection(voice->name, bundle_group));
5082 if (!voice_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08005083 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5084 "Failed to create voice channel.");
Steve Antoneda6ccd2017-12-04 10:21:55 -08005085 }
5086 GetAudioTransceiver()->internal()->SetChannel(voice_channel);
5087 }
5088
Steve Antondcc3c022017-12-22 16:02:54 -08005089 const cricket::ContentInfo* video = cricket::GetFirstVideoContent(&desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08005090 if (video && !video->rejected &&
5091 !GetVideoTransceiver()->internal()->channel()) {
5092 cricket::VideoChannel* video_channel = CreateVideoChannel(
5093 video->name,
5094 GetTransportNameForMediaSection(video->name, bundle_group));
5095 if (!video_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08005096 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5097 "Failed to create video channel.");
Steve Anton75737c02017-11-06 10:37:17 -08005098 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005099 GetVideoTransceiver()->internal()->SetChannel(video_channel);
Steve Anton75737c02017-11-06 10:37:17 -08005100 }
5101
Steve Antondcc3c022017-12-22 16:02:54 -08005102 const cricket::ContentInfo* data = cricket::GetFirstDataContent(&desc);
Steve Anton75737c02017-11-06 10:37:17 -08005103 if (data_channel_type_ != cricket::DCT_NONE && data && !data->rejected &&
5104 !rtp_data_channel_ && !sctp_transport_) {
Steve Antoneda6ccd2017-12-04 10:21:55 -08005105 if (!CreateDataChannel(data->name, GetTransportNameForMediaSection(
5106 data->name, bundle_group))) {
Steve Anton8a006912017-12-04 15:25:56 -08005107 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5108 "Failed to create data channel.");
Steve Anton75737c02017-11-06 10:37:17 -08005109 }
5110 }
5111
Steve Anton8a006912017-12-04 15:25:56 -08005112 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08005113}
5114
Steve Anton4171afb2017-11-20 10:20:22 -08005115// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08005116cricket::VoiceChannel* PeerConnection::CreateVoiceChannel(
5117 const std::string& mid,
5118 const std::string& transport_name) {
Steve Anton75737c02017-11-06 10:37:17 -08005119 cricket::DtlsTransportInternal* rtp_dtls_transport =
5120 transport_controller_->CreateDtlsTransport(
5121 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5122 cricket::DtlsTransportInternal* rtcp_dtls_transport = nullptr;
5123 if (configuration_.rtcp_mux_policy !=
5124 PeerConnectionInterface::kRtcpMuxPolicyRequire) {
5125 rtcp_dtls_transport = transport_controller_->CreateDtlsTransport(
5126 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
5127 }
5128
5129 cricket::VoiceChannel* voice_channel = channel_manager()->CreateVoiceChannel(
5130 call_.get(), configuration_.media_config, rtp_dtls_transport,
Steve Antoneda6ccd2017-12-04 10:21:55 -08005131 rtcp_dtls_transport, signaling_thread(), mid, SrtpRequired(),
5132 audio_options_);
Steve Anton75737c02017-11-06 10:37:17 -08005133 if (!voice_channel) {
5134 transport_controller_->DestroyDtlsTransport(
5135 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5136 if (rtcp_dtls_transport) {
5137 transport_controller_->DestroyDtlsTransport(
5138 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
5139 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005140 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08005141 }
Steve Anton75737c02017-11-06 10:37:17 -08005142 voice_channel->SignalRtcpMuxFullyActive.connect(
5143 this, &PeerConnection::DestroyRtcpTransport_n);
5144 voice_channel->SignalDtlsSrtpSetupFailure.connect(
5145 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08005146 voice_channel->SignalSentPacket.connect(this,
5147 &PeerConnection::OnSentPacket_w);
Steve Anton4171afb2017-11-20 10:20:22 -08005148
Steve Antoneda6ccd2017-12-04 10:21:55 -08005149 return voice_channel;
Steve Anton75737c02017-11-06 10:37:17 -08005150}
5151
Steve Anton4171afb2017-11-20 10:20:22 -08005152// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08005153cricket::VideoChannel* PeerConnection::CreateVideoChannel(
5154 const std::string& mid,
5155 const std::string& transport_name) {
Steve Anton75737c02017-11-06 10:37:17 -08005156 cricket::DtlsTransportInternal* rtp_dtls_transport =
5157 transport_controller_->CreateDtlsTransport(
5158 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5159 cricket::DtlsTransportInternal* rtcp_dtls_transport = nullptr;
5160 if (configuration_.rtcp_mux_policy !=
5161 PeerConnectionInterface::kRtcpMuxPolicyRequire) {
5162 rtcp_dtls_transport = transport_controller_->CreateDtlsTransport(
5163 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
5164 }
5165
5166 cricket::VideoChannel* video_channel = channel_manager()->CreateVideoChannel(
5167 call_.get(), configuration_.media_config, rtp_dtls_transport,
Steve Antoneda6ccd2017-12-04 10:21:55 -08005168 rtcp_dtls_transport, signaling_thread(), mid, SrtpRequired(),
5169 video_options_);
Steve Anton75737c02017-11-06 10:37:17 -08005170
5171 if (!video_channel) {
5172 transport_controller_->DestroyDtlsTransport(
5173 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5174 if (rtcp_dtls_transport) {
5175 transport_controller_->DestroyDtlsTransport(
5176 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
5177 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005178 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08005179 }
Steve Anton75737c02017-11-06 10:37:17 -08005180 video_channel->SignalRtcpMuxFullyActive.connect(
5181 this, &PeerConnection::DestroyRtcpTransport_n);
5182 video_channel->SignalDtlsSrtpSetupFailure.connect(
5183 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08005184 video_channel->SignalSentPacket.connect(this,
5185 &PeerConnection::OnSentPacket_w);
Steve Anton4171afb2017-11-20 10:20:22 -08005186
Steve Antoneda6ccd2017-12-04 10:21:55 -08005187 return video_channel;
Steve Anton75737c02017-11-06 10:37:17 -08005188}
5189
Steve Antoneda6ccd2017-12-04 10:21:55 -08005190bool PeerConnection::CreateDataChannel(const std::string& mid,
5191 const std::string& transport_name) {
Steve Anton75737c02017-11-06 10:37:17 -08005192 bool sctp = (data_channel_type_ == cricket::DCT_SCTP);
5193 if (sctp) {
5194 if (!sctp_factory_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005195 RTC_LOG(LS_ERROR)
Steve Anton75737c02017-11-06 10:37:17 -08005196 << "Trying to create SCTP transport, but didn't compile with "
5197 "SCTP support (HAVE_SCTP)";
5198 return false;
5199 }
5200 if (!network_thread()->Invoke<bool>(
5201 RTC_FROM_HERE, rtc::Bind(&PeerConnection::CreateSctpTransport_n,
Steve Antoneda6ccd2017-12-04 10:21:55 -08005202 this, mid, transport_name))) {
Steve Anton75737c02017-11-06 10:37:17 -08005203 return false;
5204 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005205 for (const auto& channel : sctp_data_channels_) {
5206 channel->OnTransportChannelCreated();
5207 }
Steve Anton75737c02017-11-06 10:37:17 -08005208 } else {
Steve Anton75737c02017-11-06 10:37:17 -08005209 cricket::DtlsTransportInternal* rtp_dtls_transport =
5210 transport_controller_->CreateDtlsTransport(
5211 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5212 cricket::DtlsTransportInternal* rtcp_dtls_transport = nullptr;
5213 if (configuration_.rtcp_mux_policy !=
5214 PeerConnectionInterface::kRtcpMuxPolicyRequire) {
5215 rtcp_dtls_transport = transport_controller_->CreateDtlsTransport(
5216 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
5217 }
5218
5219 rtp_data_channel_ = channel_manager()->CreateRtpDataChannel(
5220 configuration_.media_config, rtp_dtls_transport, rtcp_dtls_transport,
Steve Antoneda6ccd2017-12-04 10:21:55 -08005221 signaling_thread(), mid, SrtpRequired());
Steve Anton75737c02017-11-06 10:37:17 -08005222
5223 if (!rtp_data_channel_) {
5224 transport_controller_->DestroyDtlsTransport(
5225 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5226 if (rtcp_dtls_transport) {
5227 transport_controller_->DestroyDtlsTransport(
5228 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
5229 }
5230 return false;
5231 }
5232
5233 rtp_data_channel_->SignalRtcpMuxFullyActive.connect(
5234 this, &PeerConnection::DestroyRtcpTransport_n);
5235 rtp_data_channel_->SignalDtlsSrtpSetupFailure.connect(
5236 this, &PeerConnection::OnDtlsSrtpSetupFailure);
5237 rtp_data_channel_->SignalSentPacket.connect(
5238 this, &PeerConnection::OnSentPacket_w);
5239 }
5240
Steve Anton75737c02017-11-06 10:37:17 -08005241 return true;
5242}
5243
5244Call::Stats PeerConnection::GetCallStats() {
5245 if (!worker_thread()->IsCurrent()) {
5246 return worker_thread()->Invoke<Call::Stats>(
5247 RTC_FROM_HERE, rtc::Bind(&PeerConnection::GetCallStats, this));
5248 }
5249 if (call_) {
5250 return call_->GetStats();
5251 } else {
5252 return Call::Stats();
5253 }
5254}
5255
5256std::unique_ptr<SessionStats> PeerConnection::GetSessionStats_n(
5257 const ChannelNamePairs& channel_name_pairs) {
5258 RTC_DCHECK(network_thread()->IsCurrent());
5259 std::unique_ptr<SessionStats> session_stats(new SessionStats());
5260 for (const auto channel_name_pair :
5261 {&channel_name_pairs.voice, &channel_name_pairs.video,
5262 &channel_name_pairs.data}) {
5263 if (*channel_name_pair) {
5264 cricket::TransportStats transport_stats;
5265 if (!transport_controller_->GetStats((*channel_name_pair)->transport_name,
5266 &transport_stats)) {
5267 return nullptr;
5268 }
Steve Anton75737c02017-11-06 10:37:17 -08005269 session_stats->transport_stats[(*channel_name_pair)->transport_name] =
5270 std::move(transport_stats);
5271 }
5272 }
5273 return session_stats;
5274}
5275
5276bool PeerConnection::CreateSctpTransport_n(const std::string& content_name,
5277 const std::string& transport_name) {
5278 RTC_DCHECK(network_thread()->IsCurrent());
5279 RTC_DCHECK(sctp_factory_);
5280 cricket::DtlsTransportInternal* tc =
5281 transport_controller_->CreateDtlsTransport_n(
5282 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5283 sctp_transport_ = sctp_factory_->CreateSctpTransport(tc);
5284 RTC_DCHECK(sctp_transport_);
5285 sctp_invoker_.reset(new rtc::AsyncInvoker());
5286 sctp_transport_->SignalReadyToSendData.connect(
5287 this, &PeerConnection::OnSctpTransportReadyToSendData_n);
5288 sctp_transport_->SignalDataReceived.connect(
5289 this, &PeerConnection::OnSctpTransportDataReceived_n);
5290 sctp_transport_->SignalStreamClosedRemotely.connect(
5291 this, &PeerConnection::OnSctpStreamClosedRemotely_n);
Oskar Sundbom9b28a032017-11-16 10:53:30 +01005292 sctp_transport_name_ = transport_name;
5293 sctp_content_name_ = content_name;
Steve Anton75737c02017-11-06 10:37:17 -08005294 return true;
5295}
5296
5297void PeerConnection::ChangeSctpTransport_n(const std::string& transport_name) {
5298 RTC_DCHECK(network_thread()->IsCurrent());
5299 RTC_DCHECK(sctp_transport_);
5300 RTC_DCHECK(sctp_transport_name_);
5301 std::string old_sctp_transport_name = *sctp_transport_name_;
Oskar Sundbom9b28a032017-11-16 10:53:30 +01005302 sctp_transport_name_ = transport_name;
Steve Anton75737c02017-11-06 10:37:17 -08005303 cricket::DtlsTransportInternal* tc =
5304 transport_controller_->CreateDtlsTransport_n(
5305 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5306 sctp_transport_->SetTransportChannel(tc);
5307 transport_controller_->DestroyDtlsTransport_n(
5308 old_sctp_transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5309}
5310
5311void PeerConnection::DestroySctpTransport_n() {
5312 RTC_DCHECK(network_thread()->IsCurrent());
5313 sctp_transport_.reset(nullptr);
Taylor Brandstetter389a97c2018-01-03 16:26:06 -08005314 transport_controller_->DestroyDtlsTransport_n(
5315 *sctp_transport_name_, cricket::ICE_CANDIDATE_COMPONENT_RTP);
Steve Anton75737c02017-11-06 10:37:17 -08005316 sctp_content_name_.reset();
5317 sctp_transport_name_.reset();
5318 sctp_invoker_.reset(nullptr);
5319 sctp_ready_to_send_data_ = false;
5320}
5321
5322void PeerConnection::OnSctpTransportReadyToSendData_n() {
5323 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5324 RTC_DCHECK(network_thread()->IsCurrent());
5325 // Note: Cannot use rtc::Bind here because it will grab a reference to
5326 // PeerConnection and potentially cause PeerConnection to live longer than
5327 // expected. It is safe not to grab a reference since the sctp_invoker_ will
5328 // be destroyed before PeerConnection is destroyed, and at that point all
5329 // pending tasks will be cleared.
5330 sctp_invoker_->AsyncInvoke<void>(RTC_FROM_HERE, signaling_thread(), [this] {
5331 OnSctpTransportReadyToSendData_s(true);
5332 });
5333}
5334
5335void PeerConnection::OnSctpTransportReadyToSendData_s(bool ready) {
5336 RTC_DCHECK(signaling_thread()->IsCurrent());
5337 sctp_ready_to_send_data_ = ready;
5338 SignalSctpReadyToSendData(ready);
5339}
5340
5341void PeerConnection::OnSctpTransportDataReceived_n(
5342 const cricket::ReceiveDataParams& params,
5343 const rtc::CopyOnWriteBuffer& payload) {
5344 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5345 RTC_DCHECK(network_thread()->IsCurrent());
5346 // Note: Cannot use rtc::Bind here because it will grab a reference to
5347 // PeerConnection and potentially cause PeerConnection to live longer than
5348 // expected. It is safe not to grab a reference since the sctp_invoker_ will
5349 // be destroyed before PeerConnection is destroyed, and at that point all
5350 // pending tasks will be cleared.
5351 sctp_invoker_->AsyncInvoke<void>(
5352 RTC_FROM_HERE, signaling_thread(), [this, params, payload] {
5353 OnSctpTransportDataReceived_s(params, payload);
5354 });
5355}
5356
5357void PeerConnection::OnSctpTransportDataReceived_s(
5358 const cricket::ReceiveDataParams& params,
5359 const rtc::CopyOnWriteBuffer& payload) {
5360 RTC_DCHECK(signaling_thread()->IsCurrent());
5361 if (params.type == cricket::DMT_CONTROL && IsOpenMessage(payload)) {
5362 // Received OPEN message; parse and signal that a new data channel should
5363 // be created.
5364 std::string label;
5365 InternalDataChannelInit config;
5366 config.id = params.ssrc;
5367 if (!ParseDataChannelOpenMessage(payload, &label, &config)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005368 RTC_LOG(LS_WARNING) << "Failed to parse the OPEN message for sid "
5369 << params.ssrc;
Steve Anton75737c02017-11-06 10:37:17 -08005370 return;
5371 }
5372 config.open_handshake_role = InternalDataChannelInit::kAcker;
5373 OnDataChannelOpenMessage(label, config);
5374 } else {
5375 // Otherwise just forward the signal.
5376 SignalSctpDataReceived(params, payload);
5377 }
5378}
5379
5380void PeerConnection::OnSctpStreamClosedRemotely_n(int sid) {
5381 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5382 RTC_DCHECK(network_thread()->IsCurrent());
5383 sctp_invoker_->AsyncInvoke<void>(
5384 RTC_FROM_HERE, signaling_thread(),
5385 rtc::Bind(&sigslot::signal1<int>::operator(),
5386 &SignalSctpStreamClosedRemotely, sid));
5387}
5388
5389// Returns false if bundle is enabled and rtcp_mux is disabled.
5390bool PeerConnection::ValidateBundleSettings(const SessionDescription* desc) {
5391 bool bundle_enabled = desc->HasGroup(cricket::GROUP_TYPE_BUNDLE);
5392 if (!bundle_enabled)
5393 return true;
5394
5395 const cricket::ContentGroup* bundle_group =
5396 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
5397 RTC_DCHECK(bundle_group != NULL);
5398
5399 const cricket::ContentInfos& contents = desc->contents();
5400 for (cricket::ContentInfos::const_iterator citer = contents.begin();
5401 citer != contents.end(); ++citer) {
5402 const cricket::ContentInfo* content = (&*citer);
5403 RTC_DCHECK(content != NULL);
5404 if (bundle_group->HasContentName(content->name) && !content->rejected &&
Steve Anton5adfafd2017-12-20 16:34:00 -08005405 content->type == MediaProtocolType::kRtp) {
Steve Anton75737c02017-11-06 10:37:17 -08005406 if (!HasRtcpMuxEnabled(content))
5407 return false;
5408 }
5409 }
5410 // RTCP-MUX is enabled in all the contents.
5411 return true;
5412}
5413
5414bool PeerConnection::HasRtcpMuxEnabled(const cricket::ContentInfo* content) {
Steve Antonb1c1de12017-12-21 15:14:30 -08005415 return content->media_description()->rtcp_mux();
Steve Anton75737c02017-11-06 10:37:17 -08005416}
5417
Steve Anton8a006912017-12-04 15:25:56 -08005418RTCError PeerConnection::ValidateSessionDescription(
Steve Anton75737c02017-11-06 10:37:17 -08005419 const SessionDescriptionInterface* sdesc,
Steve Anton8a006912017-12-04 15:25:56 -08005420 cricket::ContentSource source) {
Steve Antonf8470812017-12-04 10:46:21 -08005421 if (session_error() != SessionError::kNone) {
Steve Anton8a006912017-12-04 15:25:56 -08005422 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
Steve Anton75737c02017-11-06 10:37:17 -08005423 }
5424
5425 if (!sdesc || !sdesc->description()) {
Steve Anton8a006912017-12-04 15:25:56 -08005426 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidSdp);
Steve Anton75737c02017-11-06 10:37:17 -08005427 }
5428
Steve Anton3828c062017-12-06 10:34:51 -08005429 SdpType type = sdesc->GetType();
5430 if ((source == cricket::CS_LOCAL && !ExpectSetLocalDescription(type)) ||
5431 (source == cricket::CS_REMOTE && !ExpectSetRemoteDescription(type))) {
Steve Anton8a006912017-12-04 15:25:56 -08005432 LOG_AND_RETURN_ERROR(
5433 RTCErrorType::INVALID_PARAMETER,
5434 "Called in wrong state: " + GetSignalingStateString(signaling_state()));
Steve Anton75737c02017-11-06 10:37:17 -08005435 }
5436
5437 // Verify crypto settings.
5438 std::string crypto_error;
Steve Anton8a006912017-12-04 15:25:56 -08005439 if (webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED ||
5440 dtls_enabled_) {
Harald Alvestrand194939b2018-01-24 16:04:13 +01005441 RTCError crypto_error =
5442 VerifyCrypto(sdesc->description(), dtls_enabled_, uma_observer_);
Steve Anton8a006912017-12-04 15:25:56 -08005443 if (!crypto_error.ok()) {
5444 return crypto_error;
5445 }
Steve Anton75737c02017-11-06 10:37:17 -08005446 }
5447
5448 // Verify ice-ufrag and ice-pwd.
5449 if (!VerifyIceUfragPwdPresent(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08005450 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5451 kSdpWithoutIceUfragPwd);
Steve Anton75737c02017-11-06 10:37:17 -08005452 }
5453
5454 if (!ValidateBundleSettings(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08005455 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5456 kBundleWithoutRtcpMux);
Steve Anton75737c02017-11-06 10:37:17 -08005457 }
5458
5459 // TODO(skvlad): When the local rtcp-mux policy is Require, reject any
5460 // m-lines that do not rtcp-mux enabled.
5461
5462 // Verify m-lines in Answer when compared against Offer.
Steve Anton3828c062017-12-06 10:34:51 -08005463 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Anton75737c02017-11-06 10:37:17 -08005464 const cricket::SessionDescription* offer_desc =
5465 (source == cricket::CS_LOCAL) ? remote_description()->description()
5466 : local_description()->description();
5467 if (!MediaSectionsHaveSameCount(offer_desc, sdesc->description()) ||
5468 !MediaSectionsInSameOrder(offer_desc, sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08005469 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5470 kMlineMismatchInAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08005471 }
5472 } else {
5473 const cricket::SessionDescription* current_desc = nullptr;
5474 if (source == cricket::CS_LOCAL && local_description()) {
5475 current_desc = local_description()->description();
5476 } else if (source == cricket::CS_REMOTE && remote_description()) {
5477 current_desc = remote_description()->description();
5478 }
5479 // The re-offers should respect the order of m= sections in current
5480 // description. See RFC3264 Section 8 paragraph 4 for more details.
5481 if (current_desc &&
5482 !MediaSectionsInSameOrder(current_desc, sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08005483 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5484 kMlineMismatchInSubsequentOffer);
Steve Anton75737c02017-11-06 10:37:17 -08005485 }
5486 }
5487
Steve Anton8a006912017-12-04 15:25:56 -08005488 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08005489}
5490
Steve Anton3828c062017-12-06 10:34:51 -08005491bool PeerConnection::ExpectSetLocalDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08005492 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08005493 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08005494 return (state == PeerConnectionInterface::kStable) ||
5495 (state == PeerConnectionInterface::kHaveLocalOffer);
Steve Anton20393062017-12-04 16:24:52 -08005496 } else {
Steve Anton3828c062017-12-06 10:34:51 -08005497 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08005498 return (state == PeerConnectionInterface::kHaveRemoteOffer) ||
5499 (state == PeerConnectionInterface::kHaveLocalPrAnswer);
5500 }
5501}
5502
Steve Anton3828c062017-12-06 10:34:51 -08005503bool PeerConnection::ExpectSetRemoteDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08005504 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08005505 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08005506 return (state == PeerConnectionInterface::kStable) ||
5507 (state == PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton20393062017-12-04 16:24:52 -08005508 } else {
Steve Anton3828c062017-12-06 10:34:51 -08005509 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08005510 return (state == PeerConnectionInterface::kHaveLocalOffer) ||
5511 (state == PeerConnectionInterface::kHaveRemotePrAnswer);
5512 }
5513}
5514
Steve Antonf8470812017-12-04 10:46:21 -08005515const char* PeerConnection::SessionErrorToString(SessionError error) const {
5516 switch (error) {
5517 case SessionError::kNone:
5518 return "ERROR_NONE";
5519 case SessionError::kContent:
5520 return "ERROR_CONTENT";
5521 case SessionError::kTransport:
5522 return "ERROR_TRANSPORT";
5523 }
5524 RTC_NOTREACHED();
5525 return "";
5526}
5527
Steve Anton75737c02017-11-06 10:37:17 -08005528std::string PeerConnection::GetSessionErrorMsg() {
5529 std::ostringstream desc;
Steve Antonf8470812017-12-04 10:46:21 -08005530 desc << kSessionError << SessionErrorToString(session_error()) << ". ";
5531 desc << kSessionErrorDesc << session_error_desc() << ".";
Steve Anton75737c02017-11-06 10:37:17 -08005532 return desc.str();
5533}
5534
5535// We need to check the local/remote description for the Transport instead of
5536// the session, because a new Transport added during renegotiation may have
5537// them unset while the session has them set from the previous negotiation.
5538// Not doing so may trigger the auto generation of transport description and
5539// mess up DTLS identity information, ICE credential, etc.
5540bool PeerConnection::ReadyToUseRemoteCandidate(
5541 const IceCandidateInterface* candidate,
5542 const SessionDescriptionInterface* remote_desc,
5543 bool* valid) {
5544 *valid = true;
5545
5546 const SessionDescriptionInterface* current_remote_desc =
5547 remote_desc ? remote_desc : remote_description();
5548
5549 if (!current_remote_desc) {
5550 return false;
5551 }
5552
5553 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
5554 size_t remote_content_size =
5555 current_remote_desc->description()->contents().size();
5556 if (mediacontent_index >= remote_content_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005557 RTC_LOG(LS_ERROR)
5558 << "ReadyToUseRemoteCandidate: Invalid candidate media index "
5559 << mediacontent_index;
Steve Anton75737c02017-11-06 10:37:17 -08005560
5561 *valid = false;
5562 return false;
5563 }
5564
5565 cricket::ContentInfo content =
5566 current_remote_desc->description()->contents()[mediacontent_index];
5567
5568 const std::string transport_name = GetTransportName(content.name);
5569 if (transport_name.empty()) {
5570 return false;
5571 }
5572 return transport_controller_->ReadyForRemoteCandidates(transport_name);
5573}
5574
5575bool PeerConnection::SrtpRequired() const {
5576 return dtls_enabled_ ||
5577 webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED;
5578}
5579
5580void PeerConnection::OnTransportControllerGatheringState(
5581 cricket::IceGatheringState state) {
5582 RTC_DCHECK(signaling_thread()->IsCurrent());
5583 if (state == cricket::kIceGatheringGathering) {
5584 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringGathering);
5585 } else if (state == cricket::kIceGatheringComplete) {
5586 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringComplete);
5587 }
5588}
5589
5590void PeerConnection::ReportTransportStats() {
Steve Antonc7b964c2018-02-01 14:39:45 -08005591 std::map<std::string, std::set<cricket::MediaType>>
5592 media_types_by_transport_name;
5593 for (auto transceiver : transceivers_) {
5594 if (transceiver->internal()->channel()) {
5595 const std::string& transport_name =
5596 transceiver->internal()->channel()->transport_name();
5597 media_types_by_transport_name[transport_name].insert(
5598 transceiver->internal()->media_type());
5599 }
Steve Anton75737c02017-11-06 10:37:17 -08005600 }
5601 if (rtp_data_channel()) {
Steve Antonc7b964c2018-02-01 14:39:45 -08005602 media_types_by_transport_name[rtp_data_channel()->transport_name()].insert(
5603 cricket::MEDIA_TYPE_DATA);
Steve Anton75737c02017-11-06 10:37:17 -08005604 }
5605 if (sctp_transport_name_) {
Steve Antonc7b964c2018-02-01 14:39:45 -08005606 media_types_by_transport_name[*sctp_transport_name_].insert(
5607 cricket::MEDIA_TYPE_DATA);
Steve Anton75737c02017-11-06 10:37:17 -08005608 }
Steve Antonc7b964c2018-02-01 14:39:45 -08005609 for (const auto& entry : media_types_by_transport_name) {
5610 const std::string& transport_name = entry.first;
5611 const std::set<cricket::MediaType> media_types = entry.second;
Steve Anton75737c02017-11-06 10:37:17 -08005612 cricket::TransportStats stats;
Steve Antonc7b964c2018-02-01 14:39:45 -08005613 if (transport_controller_->GetStats(transport_name, &stats)) {
Steve Anton75737c02017-11-06 10:37:17 -08005614 ReportBestConnectionState(stats);
Steve Antonc7b964c2018-02-01 14:39:45 -08005615 ReportNegotiatedCiphers(stats, media_types);
Steve Anton75737c02017-11-06 10:37:17 -08005616 }
5617 }
5618}
5619// Walk through the ConnectionInfos to gather best connection usage
5620// for IPv4 and IPv6.
5621void PeerConnection::ReportBestConnectionState(
5622 const cricket::TransportStats& stats) {
5623 RTC_DCHECK(metrics_observer());
Steve Antonc7b964c2018-02-01 14:39:45 -08005624 for (const cricket::TransportChannelStats& channel_stats :
5625 stats.channel_stats) {
5626 for (const cricket::ConnectionInfo& connection_info :
5627 channel_stats.connection_infos) {
5628 if (!connection_info.best_connection) {
Steve Anton75737c02017-11-06 10:37:17 -08005629 continue;
5630 }
5631
5632 PeerConnectionEnumCounterType type = kPeerConnectionEnumCounterMax;
Steve Antonc7b964c2018-02-01 14:39:45 -08005633 const cricket::Candidate& local = connection_info.local_candidate;
5634 const cricket::Candidate& remote = connection_info.remote_candidate;
Steve Anton75737c02017-11-06 10:37:17 -08005635
5636 // Increment the counter for IceCandidatePairType.
5637 if (local.protocol() == cricket::TCP_PROTOCOL_NAME ||
5638 (local.type() == RELAY_PORT_TYPE &&
5639 local.relay_protocol() == cricket::TCP_PROTOCOL_NAME)) {
5640 type = kEnumCounterIceCandidatePairTypeTcp;
5641 } else if (local.protocol() == cricket::UDP_PROTOCOL_NAME) {
5642 type = kEnumCounterIceCandidatePairTypeUdp;
5643 } else {
5644 RTC_CHECK(0);
5645 }
5646 metrics_observer()->IncrementEnumCounter(
5647 type, GetIceCandidatePairCounter(local, remote),
5648 kIceCandidatePairMax);
5649
5650 // Increment the counter for IP type.
5651 if (local.address().family() == AF_INET) {
5652 metrics_observer()->IncrementEnumCounter(
5653 kEnumCounterAddressFamily, kBestConnections_IPv4,
5654 kPeerConnectionAddressFamilyCounter_Max);
5655
5656 } else if (local.address().family() == AF_INET6) {
5657 metrics_observer()->IncrementEnumCounter(
5658 kEnumCounterAddressFamily, kBestConnections_IPv6,
5659 kPeerConnectionAddressFamilyCounter_Max);
5660 } else {
5661 RTC_CHECK(0);
5662 }
5663
5664 return;
5665 }
5666 }
5667}
5668
5669void PeerConnection::ReportNegotiatedCiphers(
Steve Antonc7b964c2018-02-01 14:39:45 -08005670 const cricket::TransportStats& stats,
5671 const std::set<cricket::MediaType>& media_types) {
Steve Anton75737c02017-11-06 10:37:17 -08005672 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
Steve Antonc7b964c2018-02-01 14:39:45 -08005684 for (cricket::MediaType media_type : media_types) {
5685 PeerConnectionEnumCounterType srtp_counter_type;
5686 PeerConnectionEnumCounterType ssl_counter_type;
5687 switch (media_type) {
5688 case cricket::MEDIA_TYPE_AUDIO:
5689 srtp_counter_type = kEnumCounterAudioSrtpCipher;
5690 ssl_counter_type = kEnumCounterAudioSslCipher;
5691 break;
5692 case cricket::MEDIA_TYPE_VIDEO:
5693 srtp_counter_type = kEnumCounterVideoSrtpCipher;
5694 ssl_counter_type = kEnumCounterVideoSslCipher;
5695 break;
5696 case cricket::MEDIA_TYPE_DATA:
5697 srtp_counter_type = kEnumCounterDataSrtpCipher;
5698 ssl_counter_type = kEnumCounterDataSslCipher;
5699 break;
5700 default:
5701 RTC_NOTREACHED();
5702 continue;
5703 }
5704 if (srtp_crypto_suite != rtc::SRTP_INVALID_CRYPTO_SUITE) {
5705 metrics_observer()->IncrementSparseEnumCounter(srtp_counter_type,
5706 srtp_crypto_suite);
5707 }
5708 if (ssl_cipher_suite != rtc::TLS_NULL_WITH_NULL_NULL) {
5709 metrics_observer()->IncrementSparseEnumCounter(ssl_counter_type,
5710 ssl_cipher_suite);
5711 }
Steve Anton75737c02017-11-06 10:37:17 -08005712 }
5713}
5714
5715void PeerConnection::OnSentPacket_w(const rtc::SentPacket& sent_packet) {
5716 RTC_DCHECK(worker_thread()->IsCurrent());
5717 RTC_DCHECK(call_);
5718 call_->OnSentPacket(sent_packet);
5719}
5720
5721const std::string PeerConnection::GetTransportName(
5722 const std::string& content_name) {
5723 cricket::BaseChannel* channel = GetChannel(content_name);
Steve Anton6fec8802017-12-04 10:37:29 -08005724 if (channel) {
5725 return channel->transport_name();
Steve Anton75737c02017-11-06 10:37:17 -08005726 }
Steve Anton6fec8802017-12-04 10:37:29 -08005727 if (sctp_transport_) {
5728 RTC_DCHECK(sctp_content_name_);
5729 RTC_DCHECK(sctp_transport_name_);
5730 if (content_name == *sctp_content_name_) {
5731 return *sctp_transport_name_;
5732 }
5733 }
5734 // Return an empty string if failed to retrieve the transport name.
5735 return "";
Steve Anton75737c02017-11-06 10:37:17 -08005736}
5737
5738void PeerConnection::DestroyRtcpTransport_n(const std::string& transport_name) {
5739 RTC_DCHECK(network_thread()->IsCurrent());
5740 transport_controller_->DestroyDtlsTransport_n(
5741 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
5742}
5743
Steve Anton6fec8802017-12-04 10:37:29 -08005744void PeerConnection::DestroyTransceiverChannel(
5745 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
5746 transceiver) {
5747 RTC_DCHECK(transceiver);
Steve Anton75737c02017-11-06 10:37:17 -08005748
Steve Anton6fec8802017-12-04 10:37:29 -08005749 cricket::BaseChannel* channel = transceiver->internal()->channel();
5750 if (channel) {
5751 transceiver->internal()->SetChannel(nullptr);
5752 DestroyBaseChannel(channel);
Steve Anton75737c02017-11-06 10:37:17 -08005753 }
5754}
5755
5756void PeerConnection::DestroyDataChannel() {
Steve Anton6fec8802017-12-04 10:37:29 -08005757 if (rtp_data_channel_) {
5758 OnDataChannelDestroyed();
5759 DestroyBaseChannel(rtp_data_channel_);
5760 rtp_data_channel_ = nullptr;
5761 }
5762
5763 // Note: Cannot use rtc::Bind to create a functor to invoke because it will
5764 // grab a reference to this PeerConnection. If this is called from the
5765 // PeerConnection destructor, the RefCountedObject vtable will have already
5766 // been destroyed (since it is a subclass of PeerConnection) and using
5767 // rtc::Bind will cause "Pure virtual function called" error to appear.
5768
5769 if (sctp_transport_) {
5770 OnDataChannelDestroyed();
5771 network_thread()->Invoke<void>(RTC_FROM_HERE,
5772 [this] { DestroySctpTransport_n(); });
5773 }
5774}
5775
5776void PeerConnection::DestroyBaseChannel(cricket::BaseChannel* channel) {
5777 RTC_DCHECK(channel);
5778 RTC_DCHECK(channel->rtp_dtls_transport());
5779
5780 // Need to cache these before destroying the base channel so that we do not
5781 // access uninitialized memory.
5782 const std::string transport_name =
5783 channel->rtp_dtls_transport()->transport_name();
5784 const bool need_to_delete_rtcp = (channel->rtcp_dtls_transport() != nullptr);
5785
5786 switch (channel->media_type()) {
5787 case cricket::MEDIA_TYPE_AUDIO:
5788 channel_manager()->DestroyVoiceChannel(
5789 static_cast<cricket::VoiceChannel*>(channel));
5790 break;
5791 case cricket::MEDIA_TYPE_VIDEO:
5792 channel_manager()->DestroyVideoChannel(
5793 static_cast<cricket::VideoChannel*>(channel));
5794 break;
5795 case cricket::MEDIA_TYPE_DATA:
5796 channel_manager()->DestroyRtpDataChannel(
5797 static_cast<cricket::RtpDataChannel*>(channel));
5798 break;
5799 default:
5800 RTC_NOTREACHED() << "Unknown media type: " << channel->media_type();
5801 break;
5802 }
5803
5804 // |channel| can no longer be used.
5805
Steve Anton75737c02017-11-06 10:37:17 -08005806 transport_controller_->DestroyDtlsTransport(
5807 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5808 if (need_to_delete_rtcp) {
5809 transport_controller_->DestroyDtlsTransport(
5810 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
5811 }
5812}
5813
Harald Alvestrand89061872018-01-02 14:08:34 +01005814void PeerConnection::ClearStatsCache() {
5815 if (stats_collector_) {
5816 stats_collector_->ClearCachedStatsReport();
5817 }
5818}
5819
henrike@webrtc.org28e20752013-07-10 00:45:36 +00005820} // namespace webrtc