blob: 5cccd854d7e4c4cfcf01c922b541c2c8285c3f6d [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
Oleh Prypinc22d6a82018-02-02 08:42:18 +00001677 if (IsClosed()) {
1678 std::string error = "CreateAnswer called when PeerConnection is closed.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001679 RTC_LOG(LS_ERROR) << error;
Steve Anton8d3444d2017-10-20 15:30:51 -07001680 PostCreateSessionDescriptionFailure(observer, error);
1681 return;
1682 }
1683
Oleh Prypinc22d6a82018-02-02 08:42:18 +00001684 if (remote_description() &&
1685 remote_description()->GetType() != SdpType::kOffer) {
1686 std::string error = "CreateAnswer called without remote offer.";
1687 RTC_LOG(LS_ERROR) << error;
1688 PostCreateSessionDescriptionFailure(observer, error);
1689 return;
1690 }
Steve Anton8d3444d2017-10-20 15:30:51 -07001691
Steve Anton22da89f2018-01-25 13:58:07 -08001692 if (IsUnifiedPlan()) {
1693 if (options.offer_to_receive_audio != RTCOfferAnswerOptions::kUndefined) {
1694 RTC_LOG(LS_WARNING) << "CreateAnswer: offer_to_receive_audio is not "
1695 "supported with Unified Plan semantics. Use the "
1696 "RtpTransceiver API instead.";
1697 }
1698 if (options.offer_to_receive_video != RTCOfferAnswerOptions::kUndefined) {
1699 RTC_LOG(LS_WARNING) << "CreateAnswer: offer_to_receive_video is not "
1700 "supported with Unified Plan semantics. Use the "
1701 "RtpTransceiver API instead.";
1702 }
1703 }
1704
htaa2a49d92016-03-04 02:51:39 -08001705 cricket::MediaSessionOptions session_options;
zhihuang1c378ed2017-08-17 14:10:50 -07001706 GetOptionsForAnswer(options, &session_options);
htaa2a49d92016-03-04 02:51:39 -08001707
Steve Antond25da372017-11-06 14:50:29 -08001708 webrtc_session_desc_factory_->CreateAnswer(observer, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001709}
1710
1711void PeerConnection::SetLocalDescription(
1712 SetSessionDescriptionObserver* observer,
1713 SessionDescriptionInterface* desc) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001714 TRACE_EVENT0("webrtc", "PeerConnection::SetLocalDescription");
Steve Anton8a006912017-12-04 15:25:56 -08001715
nisse7ce109a2017-01-31 00:57:56 -08001716 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001717 RTC_LOG(LS_ERROR) << "SetLocalDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001718 return;
1719 }
Steve Anton8a006912017-12-04 15:25:56 -08001720
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001721 if (!desc) {
1722 PostSetSessionDescriptionFailure(observer, "SessionDescription is NULL.");
1723 return;
1724 }
Steve Anton8d3444d2017-10-20 15:30:51 -07001725
Steve Antona3a92c22017-12-07 10:27:41 -08001726 SdpType type = desc->GetType();
Steve Anton8d3444d2017-10-20 15:30:51 -07001727
Steve Anton8a006912017-12-04 15:25:56 -08001728 RTCError error = ApplyLocalDescription(rtc::WrapUnique(desc));
1729 // |desc| may be destroyed at this point.
1730
1731 if (!error.ok()) {
Steve Antona3a92c22017-12-07 10:27:41 -08001732 std::ostringstream oss;
1733 oss << "Failed to set local " << SdpTypeToString(type)
1734 << " sdp: " << error.message();
1735 std::string error_message = oss.str();
Steve Anton8a006912017-12-04 15:25:56 -08001736 RTC_LOG(LS_ERROR) << error_message << " (" << error.type() << ")";
1737 PostSetSessionDescriptionFailure(observer, std::move(error_message));
Steve Anton8d3444d2017-10-20 15:30:51 -07001738 return;
1739 }
Steve Anton8a006912017-12-04 15:25:56 -08001740 RTC_DCHECK(local_description());
1741
1742 PostSetSessionDescriptionSuccess(observer);
1743
1744 // According to JSEP, after setLocalDescription, changing the candidate pool
1745 // size is not allowed, and changing the set of ICE servers will not result
1746 // in new candidates being gathered.
1747 port_allocator_->FreezeCandidatePool();
1748
1749 // MaybeStartGathering needs to be called after posting
1750 // MSG_SET_SESSIONDESCRIPTION_SUCCESS, so that we don't signal any candidates
1751 // before signaling that SetLocalDescription completed.
1752 transport_controller_->MaybeStartGathering();
1753
Steve Antona3a92c22017-12-07 10:27:41 -08001754 if (local_description()->GetType() == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08001755 // TODO(deadbeef): We already had to hop to the network thread for
1756 // MaybeStartGathering...
1757 network_thread()->Invoke<void>(
1758 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
1759 port_allocator_.get()));
1760 }
1761}
1762
1763RTCError PeerConnection::ApplyLocalDescription(
1764 std::unique_ptr<SessionDescriptionInterface> desc) {
1765 RTC_DCHECK_RUN_ON(signaling_thread());
1766 RTC_DCHECK(desc);
1767
1768 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_LOCAL);
1769 if (!error.ok()) {
1770 return error;
1771 }
Steve Anton8d3444d2017-10-20 15:30:51 -07001772
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001773 // Update stats here so that we have the most recent stats for tracks and
1774 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001775 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 15:25:56 -08001776
1777 // Update the initial_offerer flag if this session is the initial_offerer.
Steve Anton3828c062017-12-06 10:34:51 -08001778 SdpType type = desc->GetType();
Steve Anton8a006912017-12-04 15:25:56 -08001779 if (!initial_offerer_.has_value()) {
Steve Anton3828c062017-12-06 10:34:51 -08001780 initial_offerer_.emplace(type == SdpType::kOffer);
Steve Anton8a006912017-12-04 15:25:56 -08001781 if (*initial_offerer_) {
1782 transport_controller_->SetIceRole(cricket::ICEROLE_CONTROLLING);
1783 } else {
1784 transport_controller_->SetIceRole(cricket::ICEROLE_CONTROLLED);
1785 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001786 }
Steve Anton8a006912017-12-04 15:25:56 -08001787
Steve Antondcc3c022017-12-22 16:02:54 -08001788 // Take a reference to the old local description since it's used below to
1789 // compare against the new local description. When setting the new local
1790 // description, grab ownership of the replaced session description in case it
1791 // is the same as |old_local_description|, to keep it alive for the duration
1792 // of the method.
1793 const SessionDescriptionInterface* old_local_description =
1794 local_description();
1795 std::unique_ptr<SessionDescriptionInterface> replaced_local_description;
Steve Anton3828c062017-12-06 10:34:51 -08001796 if (type == SdpType::kAnswer) {
Steve Antondcc3c022017-12-22 16:02:54 -08001797 replaced_local_description = pending_local_description_
1798 ? std::move(pending_local_description_)
1799 : std::move(current_local_description_);
Steve Anton8a006912017-12-04 15:25:56 -08001800 current_local_description_ = std::move(desc);
1801 pending_local_description_ = nullptr;
1802 current_remote_description_ = std::move(pending_remote_description_);
1803 } else {
Steve Antondcc3c022017-12-22 16:02:54 -08001804 replaced_local_description = std::move(pending_local_description_);
Steve Anton8a006912017-12-04 15:25:56 -08001805 pending_local_description_ = std::move(desc);
1806 }
1807 // The session description to apply now must be accessed by
1808 // |local_description()|.
Henrik Boströmfdb92012017-11-09 19:55:44 +01001809 RTC_DCHECK(local_description());
deadbeefab9b2d12015-10-14 11:33:11 -07001810
Steve Antondcc3c022017-12-22 16:02:54 -08001811 if (IsUnifiedPlan()) {
1812 RTCError error = UpdateTransceiversAndDataChannels(
1813 cricket::CS_LOCAL, old_local_description, *local_description());
Steve Anton8a006912017-12-04 15:25:56 -08001814 if (!error.ok()) {
1815 return error;
1816 }
Steve Antondcc3c022017-12-22 16:02:54 -08001817 for (auto transceiver : transceivers_) {
1818 const ContentInfo* content =
1819 FindMediaSectionForTransceiver(transceiver, local_description());
1820 if (!content) {
1821 continue;
1822 }
1823 const MediaContentDescription* media_desc = content->media_description();
1824 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
1825 transceiver->internal()->set_current_direction(media_desc->direction());
1826 }
1827 if (content->rejected && !transceiver->stopped()) {
1828 transceiver->Stop();
1829 }
1830 }
1831 } else {
1832 // Transport and Media channels will be created only when offer is set.
1833 if (type == SdpType::kOffer) {
1834 // TODO(bugs.webrtc.org/4676) - Handle CreateChannel failure, as new local
1835 // description is applied. Restore back to old description.
1836 RTCError error = CreateChannels(*local_description()->description());
1837 if (!error.ok()) {
1838 return error;
1839 }
1840 }
Steve Anton8a006912017-12-04 15:25:56 -08001841
Steve Antondcc3c022017-12-22 16:02:54 -08001842 // Remove unused channels if MediaContentDescription is rejected.
1843 RemoveUnusedChannels(local_description()->description());
1844 }
Steve Anton8a006912017-12-04 15:25:56 -08001845
Steve Anton3828c062017-12-06 10:34:51 -08001846 error = UpdateSessionState(type, cricket::CS_LOCAL);
Steve Anton8a006912017-12-04 15:25:56 -08001847 if (!error.ok()) {
1848 return error;
1849 }
Steve Antondcc3c022017-12-22 16:02:54 -08001850
Steve Anton8a006912017-12-04 15:25:56 -08001851 if (remote_description()) {
1852 // Now that we have a local description, we can push down remote candidates.
1853 UseCandidatesInSessionDescription(remote_description());
1854 }
1855
1856 pending_ice_restarts_.clear();
1857 if (session_error() != SessionError::kNone) {
1858 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
1859 }
1860
deadbeefab9b2d12015-10-14 11:33:11 -07001861 // If setting the description decided our SSL role, allocate any necessary
1862 // SCTP sids.
1863 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08001864 if (data_channel_type() == cricket::DCT_SCTP && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001865 AllocateSctpSids(role);
1866 }
1867
Steve Antond3679212018-01-17 17:41:02 -08001868 if (IsUnifiedPlan()) {
1869 for (auto transceiver : transceivers_) {
1870 const ContentInfo* content =
1871 FindMediaSectionForTransceiver(transceiver, local_description());
1872 if (!content) {
1873 continue;
1874 }
1875 if (content->rejected && !transceiver->stopped()) {
1876 transceiver->Stop();
1877 }
Steve Anton74255ff2018-01-24 18:32:57 -08001878 const auto& streams = content->media_description()->streams();
1879 if (!content->rejected && !streams.empty()) {
Steve Antond3679212018-01-17 17:41:02 -08001880 transceiver->internal()->sender_internal()->set_stream_ids(
Steve Anton74255ff2018-01-24 18:32:57 -08001881 {streams[0].sync_label});
Steve Antond3679212018-01-17 17:41:02 -08001882 transceiver->internal()->sender_internal()->SetSsrc(
Steve Anton74255ff2018-01-24 18:32:57 -08001883 streams[0].first_ssrc());
Steve Antond3679212018-01-17 17:41:02 -08001884 }
1885 }
1886 } else {
1887 // Plan B semantics.
1888
Steve Antondcc3c022017-12-22 16:02:54 -08001889 // Update state and SSRC of local MediaStreams and DataChannels based on the
1890 // local session description.
1891 const cricket::ContentInfo* audio_content =
1892 GetFirstAudioContent(local_description()->description());
1893 if (audio_content) {
1894 if (audio_content->rejected) {
1895 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
1896 } else {
1897 const cricket::AudioContentDescription* audio_desc =
1898 audio_content->media_description()->as_audio();
1899 UpdateLocalSenders(audio_desc->streams(), audio_desc->type());
1900 }
deadbeeffaac4972015-11-12 15:33:07 -08001901 }
deadbeefab9b2d12015-10-14 11:33:11 -07001902
Steve Antondcc3c022017-12-22 16:02:54 -08001903 const cricket::ContentInfo* video_content =
1904 GetFirstVideoContent(local_description()->description());
1905 if (video_content) {
1906 if (video_content->rejected) {
1907 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
1908 } else {
1909 const cricket::VideoContentDescription* video_desc =
1910 video_content->media_description()->as_video();
1911 UpdateLocalSenders(video_desc->streams(), video_desc->type());
1912 }
deadbeeffaac4972015-11-12 15:33:07 -08001913 }
deadbeefab9b2d12015-10-14 11:33:11 -07001914 }
1915
1916 const cricket::ContentInfo* data_content =
Henrik Boströmfdb92012017-11-09 19:55:44 +01001917 GetFirstDataContent(local_description()->description());
deadbeefab9b2d12015-10-14 11:33:11 -07001918 if (data_content) {
1919 const cricket::DataContentDescription* data_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08001920 data_content->media_description()->as_data();
deadbeefab9b2d12015-10-14 11:33:11 -07001921 if (rtc::starts_with(data_desc->protocol().data(),
1922 cricket::kMediaProtocolRtpPrefix)) {
1923 UpdateLocalRtpDataChannels(data_desc->streams());
1924 }
1925 }
1926
Steve Anton8a006912017-12-04 15:25:56 -08001927 return RTCError::OK();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001928}
1929
1930void PeerConnection::SetRemoteDescription(
Henrik Boströma4ecf552017-11-23 14:17:07 +00001931 SetSessionDescriptionObserver* observer,
1932 SessionDescriptionInterface* desc) {
Henrik Boström31638672017-11-23 17:48:32 +01001933 SetRemoteDescription(
1934 std::unique_ptr<SessionDescriptionInterface>(desc),
1935 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface>(
1936 new SetRemoteDescriptionObserverAdapter(this, observer)));
1937}
1938
1939void PeerConnection::SetRemoteDescription(
1940 std::unique_ptr<SessionDescriptionInterface> desc,
1941 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface> observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001942 TRACE_EVENT0("webrtc", "PeerConnection::SetRemoteDescription");
Steve Anton8a006912017-12-04 15:25:56 -08001943
nisse7ce109a2017-01-31 00:57:56 -08001944 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001945 RTC_LOG(LS_ERROR) << "SetRemoteDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001946 return;
1947 }
Steve Anton8a006912017-12-04 15:25:56 -08001948
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001949 if (!desc) {
Henrik Boström31638672017-11-23 17:48:32 +01001950 observer->OnSetRemoteDescriptionComplete(RTCError(
Steve Anton8a006912017-12-04 15:25:56 -08001951 RTCErrorType::INVALID_PARAMETER, "SessionDescription is NULL."));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001952 return;
1953 }
Steve Anton8d3444d2017-10-20 15:30:51 -07001954
Steve Antona3a92c22017-12-07 10:27:41 -08001955 const SdpType type = desc->GetType();
Steve Anton8a006912017-12-04 15:25:56 -08001956
1957 RTCError error = ApplyRemoteDescription(std::move(desc));
1958 // |desc| may be destroyed at this point.
1959
1960 if (!error.ok()) {
Steve Antona3a92c22017-12-07 10:27:41 -08001961 std::ostringstream oss;
1962 oss << "Failed to set remote " << SdpTypeToString(type)
1963 << " sdp: " << error.message();
1964 std::string error_message = oss.str();
Steve Anton8a006912017-12-04 15:25:56 -08001965 RTC_LOG(LS_ERROR) << error_message << " (" << error.type() << ")";
Henrik Boström31638672017-11-23 17:48:32 +01001966 observer->OnSetRemoteDescriptionComplete(
Steve Anton8a006912017-12-04 15:25:56 -08001967 RTCError(error.type(), std::move(error_message)));
Steve Anton8d3444d2017-10-20 15:30:51 -07001968 return;
1969 }
1970
Steve Antona3a92c22017-12-07 10:27:41 -08001971 if (remote_description()->GetType() == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08001972 // TODO(deadbeef): We already had to hop to the network thread for
1973 // MaybeStartGathering...
1974 network_thread()->Invoke<void>(
1975 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
1976 port_allocator_.get()));
1977 }
1978
1979 observer->OnSetRemoteDescriptionComplete(RTCError::OK());
1980}
1981
1982RTCError PeerConnection::ApplyRemoteDescription(
1983 std::unique_ptr<SessionDescriptionInterface> desc) {
1984 RTC_DCHECK_RUN_ON(signaling_thread());
1985 RTC_DCHECK(desc);
1986
1987 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_REMOTE);
1988 if (!error.ok()) {
1989 return error;
1990 }
1991
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001992 // Update stats here so that we have the most recent stats for tracks and
1993 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001994 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 15:25:56 -08001995
Steve Antondcc3c022017-12-22 16:02:54 -08001996 // Take a reference to the old remote description since it's used below to
1997 // compare against the new remote description. When setting the new remote
1998 // description, grab ownership of the replaced session description in case it
1999 // is the same as |old_remote_description|, to keep it alive for the duration
2000 // of the method.
Steve Anton8a006912017-12-04 15:25:56 -08002001 const SessionDescriptionInterface* old_remote_description =
2002 remote_description();
Steve Anton8a006912017-12-04 15:25:56 -08002003 std::unique_ptr<SessionDescriptionInterface> replaced_remote_description;
Steve Anton3828c062017-12-06 10:34:51 -08002004 SdpType type = desc->GetType();
2005 if (type == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002006 replaced_remote_description = pending_remote_description_
2007 ? std::move(pending_remote_description_)
2008 : std::move(current_remote_description_);
2009 current_remote_description_ = std::move(desc);
2010 pending_remote_description_ = nullptr;
2011 current_local_description_ = std::move(pending_local_description_);
2012 } else {
2013 replaced_remote_description = std::move(pending_remote_description_);
2014 pending_remote_description_ = std::move(desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002015 }
Steve Anton8a006912017-12-04 15:25:56 -08002016 // The session description to apply now must be accessed by
2017 // |remote_description()|.
Henrik Boströmfdb92012017-11-09 19:55:44 +01002018 RTC_DCHECK(remote_description());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002019
Steve Anton8a006912017-12-04 15:25:56 -08002020 // Transport and Media channels will be created only when offer is set.
Steve Antondcc3c022017-12-22 16:02:54 -08002021 if (IsUnifiedPlan()) {
2022 RTCError error = UpdateTransceiversAndDataChannels(
2023 cricket::CS_REMOTE, old_remote_description, *remote_description());
Steve Anton8a006912017-12-04 15:25:56 -08002024 if (!error.ok()) {
2025 return error;
2026 }
Steve Antondcc3c022017-12-22 16:02:54 -08002027 } else {
2028 if (type == SdpType::kOffer) {
2029 // TODO(bugs.webrtc.org/4676) - Handle CreateChannel failure, as new local
2030 // description is applied. Restore back to old description.
2031 RTCError error = CreateChannels(*remote_description()->description());
2032 if (!error.ok()) {
2033 return error;
2034 }
2035 }
Steve Anton8a006912017-12-04 15:25:56 -08002036
Steve Antondcc3c022017-12-22 16:02:54 -08002037 // Remove unused channels if MediaContentDescription is rejected.
2038 RemoveUnusedChannels(remote_description()->description());
2039 }
Steve Anton8a006912017-12-04 15:25:56 -08002040
2041 // NOTE: Candidates allocation will be initiated only when SetLocalDescription
2042 // is called.
Steve Anton3828c062017-12-06 10:34:51 -08002043 error = UpdateSessionState(type, cricket::CS_REMOTE);
Steve Anton8a006912017-12-04 15:25:56 -08002044 if (!error.ok()) {
2045 return error;
2046 }
2047
2048 if (local_description() &&
2049 !UseCandidatesInSessionDescription(remote_description())) {
2050 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidCandidates);
2051 }
2052
2053 if (old_remote_description) {
2054 for (const cricket::ContentInfo& content :
2055 old_remote_description->description()->contents()) {
2056 // Check if this new SessionDescription contains new ICE ufrag and
2057 // password that indicates the remote peer requests an ICE restart.
2058 // TODO(deadbeef): When we start storing both the current and pending
2059 // remote description, this should reset pending_ice_restarts and compare
2060 // against the current description.
2061 if (CheckForRemoteIceRestart(old_remote_description, remote_description(),
2062 content.name)) {
Steve Anton3828c062017-12-06 10:34:51 -08002063 if (type == SdpType::kOffer) {
Steve Anton8a006912017-12-04 15:25:56 -08002064 pending_ice_restarts_.insert(content.name);
2065 }
2066 } else {
2067 // We retain all received candidates only if ICE is not restarted.
2068 // When ICE is restarted, all previous candidates belong to an old
2069 // generation and should not be kept.
2070 // TODO(deadbeef): This goes against the W3C spec which says the remote
2071 // description should only contain candidates from the last set remote
2072 // description plus any candidates added since then. We should remove
2073 // this once we're sure it won't break anything.
2074 WebRtcSessionDescriptionFactory::CopyCandidatesFromSessionDescription(
2075 old_remote_description, content.name, mutable_remote_description());
2076 }
2077 }
2078 }
2079
2080 if (session_error() != SessionError::kNone) {
2081 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
2082 }
2083
2084 // Set the the ICE connection state to connecting since the connection may
2085 // become writable with peer reflexive candidates before any remote candidate
2086 // is signaled.
2087 // TODO(pthatcher): This is a short-term solution for crbug/446908. A real fix
2088 // is to have a new signal the indicates a change in checking state from the
2089 // transport and expose a new checking() member from transport that can be
2090 // read to determine the current checking state. The existing SignalConnecting
2091 // actually means "gathering candidates", so cannot be be used here.
Steve Antona3a92c22017-12-07 10:27:41 -08002092 if (remote_description()->GetType() != SdpType::kOffer &&
Steve Anton8a006912017-12-04 15:25:56 -08002093 ice_connection_state() == PeerConnectionInterface::kIceConnectionNew) {
2094 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
2095 }
2096
deadbeefab9b2d12015-10-14 11:33:11 -07002097 // If setting the description decided our SSL role, allocate any necessary
2098 // SCTP sids.
2099 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08002100 if (data_channel_type() == cricket::DCT_SCTP && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07002101 AllocateSctpSids(role);
2102 }
2103
Steve Antondcc3c022017-12-22 16:02:54 -08002104 if (IsUnifiedPlan()) {
Steve Antonef65ef12018-01-10 17:15:20 -08002105 std::vector<TrackEvent> track_events;
Steve Antondcc3c022017-12-22 16:02:54 -08002106 for (auto transceiver : transceivers_) {
2107 const ContentInfo* content =
2108 FindMediaSectionForTransceiver(transceiver, remote_description());
2109 if (!content) {
2110 continue;
2111 }
2112 const MediaContentDescription* media_desc = content->media_description();
2113 RtpTransceiverDirection local_direction =
2114 RtpTransceiverDirectionReversed(media_desc->direction());
2115 // From the WebRTC specification, steps 2.2.8.5/6 of section 4.4.1.6 "Set
2116 // the RTCSessionDescription: If direction is sendrecv or recvonly, and
2117 // transceiver's current direction is neither sendrecv nor recvonly,
2118 // process the addition of a remote track for the media description.
2119 if (RtpTransceiverDirectionHasRecv(local_direction) &&
2120 (!transceiver->current_direction() ||
2121 !RtpTransceiverDirectionHasRecv(
Steve Anton74255ff2018-01-24 18:32:57 -08002122 *transceiver->current_direction())) &&
2123 !media_desc->streams().empty()) {
Steve Antonef65ef12018-01-10 17:15:20 -08002124 const std::string& sync_label = media_desc->streams()[0].sync_label;
2125 rtc::scoped_refptr<MediaStreamInterface> stream =
2126 remote_streams_->find(sync_label);
2127 if (!stream) {
2128 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
2129 MediaStream::Create(sync_label));
2130 remote_streams_->AddStream(stream);
2131 }
2132 transceiver->internal()->receiver_internal()->SetStreams({stream});
2133 TrackEvent track_event;
2134 track_event.receiver = transceiver->receiver();
2135 track_event.streams = transceiver->receiver()->streams();
2136 track_events.push_back(std::move(track_event));
Steve Antondcc3c022017-12-22 16:02:54 -08002137 }
2138 // If direction is sendonly or inactive, and transceiver's current
2139 // direction is neither sendonly nor inactive, process the removal of a
2140 // remote track for the media description.
2141 if (!RtpTransceiverDirectionHasRecv(local_direction) &&
Steve Antonef65ef12018-01-10 17:15:20 -08002142 (transceiver->current_direction() &&
Steve Antondcc3c022017-12-22 16:02:54 -08002143 RtpTransceiverDirectionHasRecv(*transceiver->current_direction()))) {
Steve Antonef65ef12018-01-10 17:15:20 -08002144 transceiver->internal()->receiver_internal()->SetStreams({});
Steve Antondcc3c022017-12-22 16:02:54 -08002145 }
2146 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
2147 transceiver->internal()->set_current_direction(local_direction);
2148 }
2149 if (content->rejected && !transceiver->stopped()) {
2150 transceiver->Stop();
2151 }
Steve Anton74255ff2018-01-24 18:32:57 -08002152 if (!content->rejected && !media_desc->streams().empty()) {
Steve Antond3679212018-01-17 17:41:02 -08002153 transceiver->internal()->receiver_internal()->SetupMediaChannel(
Steve Anton5f94aa22018-02-01 10:58:30 -08002154 media_desc->streams()[0].first_ssrc());
Steve Antond3679212018-01-17 17:41:02 -08002155 }
Steve Antondcc3c022017-12-22 16:02:54 -08002156 }
Steve Antonef65ef12018-01-10 17:15:20 -08002157 for (auto event : track_events) {
2158 observer_->OnAddTrack(event.receiver, event.streams);
2159 }
Steve Antondcc3c022017-12-22 16:02:54 -08002160 }
2161
Henrik Boströmfdb92012017-11-09 19:55:44 +01002162 const cricket::ContentInfo* audio_content =
2163 GetFirstAudioContent(remote_description()->description());
2164 const cricket::ContentInfo* video_content =
2165 GetFirstVideoContent(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002166 const cricket::AudioContentDescription* audio_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002167 GetFirstAudioContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002168 const cricket::VideoContentDescription* video_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002169 GetFirstVideoContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002170 const cricket::DataContentDescription* data_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002171 GetFirstDataContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002172
2173 // Check if the descriptions include streams, just in case the peer supports
2174 // MSID, but doesn't indicate so with "a=msid-semantic".
Henrik Boströmfdb92012017-11-09 19:55:44 +01002175 if (remote_description()->description()->msid_supported() ||
deadbeefbda7e0b2015-12-08 17:13:40 -08002176 (audio_desc && !audio_desc->streams().empty()) ||
2177 (video_desc && !video_desc->streams().empty())) {
2178 remote_peer_supports_msid_ = true;
2179 }
deadbeefab9b2d12015-10-14 11:33:11 -07002180
2181 // We wait to signal new streams until we finish processing the description,
2182 // since only at that point will new streams have all their tracks.
2183 rtc::scoped_refptr<StreamCollection> new_streams(StreamCollection::Create());
2184
Steve Antondcc3c022017-12-22 16:02:54 -08002185 if (!IsUnifiedPlan()) {
2186 // TODO(steveanton): When removing RTP senders/receivers in response to a
2187 // rejected media section, there is some cleanup logic that expects the
2188 // voice/ video channel to still be set. But in this method the voice/video
2189 // channel would have been destroyed by the SetRemoteDescription caller
2190 // above so the cleanup that relies on them fails to run. The RemoveSenders
2191 // calls should be moved to right before the DestroyChannel calls to fix
2192 // this.
Steve Anton8d3444d2017-10-20 15:30:51 -07002193
Steve Antondcc3c022017-12-22 16:02:54 -08002194 // Find all audio rtp streams and create corresponding remote AudioTracks
2195 // and MediaStreams.
2196 if (audio_content) {
2197 if (audio_content->rejected) {
2198 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
2199 } else {
2200 bool default_audio_track_needed =
2201 !remote_peer_supports_msid_ &&
2202 RtpTransceiverDirectionHasSend(audio_desc->direction());
2203 UpdateRemoteSendersList(GetActiveStreams(audio_desc),
2204 default_audio_track_needed, audio_desc->type(),
2205 new_streams);
2206 }
deadbeeffaac4972015-11-12 15:33:07 -08002207 }
deadbeefab9b2d12015-10-14 11:33:11 -07002208
Steve Antondcc3c022017-12-22 16:02:54 -08002209 // Find all video rtp streams and create corresponding remote VideoTracks
2210 // and MediaStreams.
2211 if (video_content) {
2212 if (video_content->rejected) {
2213 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
2214 } else {
2215 bool default_video_track_needed =
2216 !remote_peer_supports_msid_ &&
2217 RtpTransceiverDirectionHasSend(video_desc->direction());
2218 UpdateRemoteSendersList(GetActiveStreams(video_desc),
2219 default_video_track_needed, video_desc->type(),
2220 new_streams);
2221 }
deadbeeffaac4972015-11-12 15:33:07 -08002222 }
deadbeefab9b2d12015-10-14 11:33:11 -07002223
Steve Antondcc3c022017-12-22 16:02:54 -08002224 // Update the DataChannels with the information from the remote peer.
2225 if (data_desc) {
2226 if (rtc::starts_with(data_desc->protocol().data(),
2227 cricket::kMediaProtocolRtpPrefix)) {
2228 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
2229 }
deadbeefab9b2d12015-10-14 11:33:11 -07002230 }
deadbeefab9b2d12015-10-14 11:33:11 -07002231
Steve Antondcc3c022017-12-22 16:02:54 -08002232 // Iterate new_streams and notify the observer about new MediaStreams.
2233 for (size_t i = 0; i < new_streams->count(); ++i) {
2234 MediaStreamInterface* new_stream = new_streams->at(i);
2235 stats_->AddStream(new_stream);
2236 observer_->OnAddStream(
2237 rtc::scoped_refptr<MediaStreamInterface>(new_stream));
2238 }
deadbeefab9b2d12015-10-14 11:33:11 -07002239
Steve Antondcc3c022017-12-22 16:02:54 -08002240 UpdateEndedRemoteMediaStreams();
2241 }
deadbeefab9b2d12015-10-14 11:33:11 -07002242
Steve Anton8a006912017-12-04 15:25:56 -08002243 return RTCError::OK();
deadbeeffc648b62015-10-13 16:42:33 -07002244}
2245
Steve Antondcc3c022017-12-22 16:02:54 -08002246RTCError PeerConnection::UpdateTransceiversAndDataChannels(
2247 cricket::ContentSource source,
2248 const SessionDescriptionInterface* old_session,
2249 const SessionDescriptionInterface& new_session) {
2250 RTC_DCHECK(IsUnifiedPlan());
2251
Steve Anton7464fca2018-01-19 11:10:37 -08002252 const cricket::ContentGroup* bundle_group = nullptr;
2253 if (new_session.GetType() == SdpType::kOffer) {
2254 auto bundle_group_or_error =
2255 GetEarlyBundleGroup(*new_session.description());
2256 if (!bundle_group_or_error.ok()) {
2257 return bundle_group_or_error.MoveError();
2258 }
2259 bundle_group = bundle_group_or_error.MoveValue();
Steve Antondcc3c022017-12-22 16:02:54 -08002260 }
Steve Antondcc3c022017-12-22 16:02:54 -08002261
2262 const ContentInfos& old_contents =
2263 (old_session ? old_session->description()->contents() : ContentInfos());
2264 const ContentInfos& new_contents = new_session.description()->contents();
2265
2266 for (size_t i = 0; i < new_contents.size(); ++i) {
2267 const cricket::ContentInfo& new_content = new_contents[i];
2268 const cricket::ContentInfo* old_content =
2269 (i < old_contents.size() ? &old_contents[i] : nullptr);
2270 cricket::MediaType media_type = new_content.media_description()->type();
2271 seen_mids_.insert(new_content.name);
2272 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
2273 media_type == cricket::MEDIA_TYPE_VIDEO) {
2274 auto transceiver_or_error =
2275 AssociateTransceiver(source, i, new_content, old_content);
2276 if (!transceiver_or_error.ok()) {
2277 return transceiver_or_error.MoveError();
2278 }
2279 auto transceiver = transceiver_or_error.MoveValue();
Steve Antondcc3c022017-12-22 16:02:54 -08002280 RTCError error =
2281 UpdateTransceiverChannel(transceiver, new_content, bundle_group);
2282 if (!error.ok()) {
2283 return error;
2284 }
2285 } else if (media_type == cricket::MEDIA_TYPE_DATA) {
Steve Antonfa2260d2017-12-28 16:38:23 -08002286 if (GetDataMid() && new_content.name != *GetDataMid()) {
2287 // Ignore all but the first data section.
2288 continue;
2289 }
2290 RTCError error = UpdateDataChannel(source, new_content, bundle_group);
2291 if (!error.ok()) {
2292 return error;
2293 }
Steve Antondcc3c022017-12-22 16:02:54 -08002294 } else {
2295 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
2296 "Unknown section type.");
2297 }
2298 }
2299
2300 return RTCError::OK();
2301}
2302
2303RTCError PeerConnection::UpdateTransceiverChannel(
2304 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2305 transceiver,
2306 const cricket::ContentInfo& content,
2307 const cricket::ContentGroup* bundle_group) {
2308 RTC_DCHECK(IsUnifiedPlan());
2309 RTC_DCHECK(transceiver);
2310 cricket::BaseChannel* channel = transceiver->internal()->channel();
2311 if (content.rejected) {
2312 if (channel) {
2313 transceiver->internal()->SetChannel(nullptr);
2314 DestroyBaseChannel(channel);
2315 }
2316 } else {
2317 if (!channel) {
2318 if (transceiver->internal()->media_type() == cricket::MEDIA_TYPE_AUDIO) {
2319 channel = CreateVoiceChannel(
2320 content.name,
2321 GetTransportNameForMediaSection(content.name, bundle_group));
2322 } else {
2323 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO,
2324 transceiver->internal()->media_type());
2325 channel = CreateVideoChannel(
2326 content.name,
2327 GetTransportNameForMediaSection(content.name, bundle_group));
2328 }
2329 if (!channel) {
2330 LOG_AND_RETURN_ERROR(
2331 RTCErrorType::INTERNAL_ERROR,
2332 "Failed to create channel for mid=" + content.name);
2333 }
2334 transceiver->internal()->SetChannel(channel);
2335 }
2336 }
2337 return RTCError::OK();
2338}
2339
Steve Antonfa2260d2017-12-28 16:38:23 -08002340RTCError PeerConnection::UpdateDataChannel(
2341 cricket::ContentSource source,
2342 const cricket::ContentInfo& content,
2343 const cricket::ContentGroup* bundle_group) {
2344 if (data_channel_type_ == cricket::DCT_NONE) {
Steve Antondbf9d032018-01-19 15:23:40 -08002345 // If data channels are disabled, ignore this media section. CreateAnswer
2346 // will take care of rejecting it.
2347 return RTCError::OK();
Steve Antonfa2260d2017-12-28 16:38:23 -08002348 }
2349 if (content.rejected) {
2350 DestroyDataChannel();
2351 } else {
2352 if (!rtp_data_channel_ && !sctp_transport_) {
2353 if (!CreateDataChannel(content.name, GetTransportNameForMediaSection(
2354 content.name, bundle_group))) {
2355 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
2356 "Failed to create data channel.");
2357 }
2358 }
2359 if (source == cricket::CS_REMOTE) {
2360 const MediaContentDescription* data_desc = content.media_description();
2361 if (data_desc && cricket::IsRtpProtocol(data_desc->protocol())) {
2362 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
2363 }
2364 }
2365 }
2366 return RTCError::OK();
2367}
2368
Steve Antondcc3c022017-12-22 16:02:54 -08002369RTCErrorOr<rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
2370PeerConnection::AssociateTransceiver(cricket::ContentSource source,
2371 size_t mline_index,
2372 const ContentInfo& content,
2373 const ContentInfo* old_content) {
2374 RTC_DCHECK(IsUnifiedPlan());
2375 // If the m= section is being recycled (rejected in previous remote
2376 // description, not rejected in current description), dissociate the currently
2377 // associated RtpTransceiver by setting its mid property to null, and discard
2378 // the mapping between the transceiver and its m= section index.
2379 if (old_content && old_content->rejected && !content.rejected) {
2380 auto old_transceiver = GetAssociatedTransceiver(old_content->name);
2381 if (old_transceiver) {
2382 old_transceiver->internal()->set_mid(rtc::nullopt);
2383 old_transceiver->internal()->set_mline_index(rtc::nullopt);
2384 }
2385 }
2386 const MediaContentDescription* media_desc = content.media_description();
2387 auto transceiver = GetAssociatedTransceiver(content.name);
2388 if (source == cricket::CS_LOCAL) {
2389 // Find the RtpTransceiver that corresponds to this m= section, using the
2390 // mapping between transceivers and m= section indices established when
2391 // creating the offer.
2392 if (!transceiver) {
2393 transceiver = GetTransceiverByMLineIndex(mline_index);
2394 }
2395 if (!transceiver) {
2396 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2397 "Unknown transceiver");
2398 }
2399 } else {
2400 RTC_DCHECK_EQ(source, cricket::CS_REMOTE);
2401 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers
2402 // of the same type...
2403 if (!transceiver &&
2404 RtpTransceiverDirectionHasRecv(media_desc->direction())) {
2405 transceiver = FindAvailableTransceiverToReceive(media_desc->type());
2406 }
2407 // If no RtpTransceiver was found in the previous step, create one with a
2408 // recvonly direction.
2409 if (!transceiver) {
Steve Anton02ee47c2018-01-10 16:26:06 -08002410 auto sender =
2411 CreateSender(media_desc->type(), nullptr, {rtc::CreateRandomUuid()});
Steve Anton5f94aa22018-02-01 10:58:30 -08002412 std::string receiver_id;
2413 if (!media_desc->streams().empty()) {
2414 receiver_id = media_desc->streams()[0].id;
2415 } else {
2416 receiver_id = rtc::CreateRandomUuid();
2417 }
2418 auto receiver = CreateReceiver(media_desc->type(), receiver_id);
Steve Anton02ee47c2018-01-10 16:26:06 -08002419 transceiver = CreateAndAddTransceiver(sender, receiver);
Steve Antondcc3c022017-12-22 16:02:54 -08002420 transceiver->internal()->set_direction(
2421 RtpTransceiverDirection::kRecvOnly);
2422 }
2423 }
2424 RTC_DCHECK(transceiver);
2425 if (transceiver->internal()->media_type() != media_desc->type()) {
2426 LOG_AND_RETURN_ERROR(
2427 RTCErrorType::INVALID_PARAMETER,
2428 "Transceiver type does not match media description type.");
2429 }
2430 // Associate the found or created RtpTransceiver with the m= section by
2431 // setting the value of the RtpTransceiver's mid property to the MID of the m=
2432 // section, and establish a mapping between the transceiver and the index of
2433 // the m= section.
2434 transceiver->internal()->set_mid(content.name);
2435 transceiver->internal()->set_mline_index(mline_index);
2436 return std::move(transceiver);
2437}
2438
2439rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2440PeerConnection::GetAssociatedTransceiver(const std::string& mid) const {
2441 RTC_DCHECK(IsUnifiedPlan());
2442 for (auto transceiver : transceivers_) {
2443 if (transceiver->mid() == mid) {
2444 return transceiver;
2445 }
2446 }
2447 return nullptr;
2448}
2449
2450rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2451PeerConnection::GetTransceiverByMLineIndex(size_t mline_index) const {
2452 RTC_DCHECK(IsUnifiedPlan());
2453 for (auto transceiver : transceivers_) {
2454 if (transceiver->internal()->mline_index() == mline_index) {
2455 return transceiver;
2456 }
2457 }
2458 return nullptr;
2459}
2460
2461rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2462PeerConnection::FindAvailableTransceiverToReceive(
2463 cricket::MediaType media_type) const {
2464 RTC_DCHECK(IsUnifiedPlan());
2465 // From JSEP section 5.10 (Applying a Remote Description):
2466 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers of
2467 // the same type that were added to the PeerConnection by addTrack and are not
2468 // associated with any m= section and are not stopped, find the first such
2469 // RtpTransceiver.
2470 for (auto transceiver : transceivers_) {
2471 if (transceiver->internal()->media_type() == media_type &&
2472 transceiver->internal()->created_by_addtrack() && !transceiver->mid() &&
2473 !transceiver->stopped()) {
2474 return transceiver;
2475 }
2476 }
2477 return nullptr;
2478}
2479
Steve Antoned10bd92017-12-05 10:52:59 -08002480const cricket::ContentInfo* PeerConnection::FindMediaSectionForTransceiver(
2481 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2482 transceiver,
2483 const SessionDescriptionInterface* sdesc) const {
2484 RTC_DCHECK(transceiver);
2485 RTC_DCHECK(sdesc);
2486 if (IsUnifiedPlan()) {
2487 if (!transceiver->internal()->mid()) {
2488 // This transceiver is not associated with a media section yet.
2489 return nullptr;
2490 }
2491 return sdesc->description()->GetContentByName(
2492 *transceiver->internal()->mid());
2493 } else {
2494 // Plan B only allows at most one audio and one video section, so use the
2495 // first media section of that type.
2496 return cricket::GetFirstMediaContent(sdesc->description()->contents(),
2497 transceiver->internal()->media_type());
2498 }
2499}
2500
deadbeef46c73892016-11-16 19:42:04 -08002501PeerConnectionInterface::RTCConfiguration PeerConnection::GetConfiguration() {
2502 return configuration_;
2503}
2504
deadbeef293e9262017-01-11 12:28:30 -08002505bool PeerConnection::SetConfiguration(const RTCConfiguration& configuration,
2506 RTCError* error) {
Peter Boström1a9d6152015-12-08 22:15:17 +01002507 TRACE_EVENT0("webrtc", "PeerConnection::SetConfiguration");
deadbeef6de92f92016-12-12 18:49:32 -08002508
Steve Anton75737c02017-11-06 10:37:17 -08002509 if (local_description() && configuration.ice_candidate_pool_size !=
2510 configuration_.ice_candidate_pool_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002511 RTC_LOG(LS_ERROR) << "Can't change candidate pool size after calling "
2512 "SetLocalDescription.";
deadbeef293e9262017-01-11 12:28:30 -08002513 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00002514 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002515
deadbeef293e9262017-01-11 12:28:30 -08002516 // The simplest (and most future-compatible) way to tell if the config was
2517 // modified in an invalid way is to copy each property we do support
2518 // modifying, then use operator==. There are far more properties we don't
2519 // support modifying than those we do, and more could be added.
2520 RTCConfiguration modified_config = configuration_;
2521 modified_config.servers = configuration.servers;
2522 modified_config.type = configuration.type;
2523 modified_config.ice_candidate_pool_size =
2524 configuration.ice_candidate_pool_size;
2525 modified_config.prune_turn_ports = configuration.prune_turn_ports;
skvladd1f5fda2017-02-03 16:54:05 -08002526 modified_config.ice_check_min_interval = configuration.ice_check_min_interval;
Jonas Orelandbdcee282017-10-10 14:01:40 +02002527 modified_config.turn_customizer = configuration.turn_customizer;
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08002528 modified_config.network_preference = configuration.network_preference;
deadbeef293e9262017-01-11 12:28:30 -08002529 if (configuration != modified_config) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002530 RTC_LOG(LS_ERROR) << "Modifying the configuration in an unsupported way.";
deadbeef293e9262017-01-11 12:28:30 -08002531 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
2532 }
2533
Steve Anton038834f2017-07-14 15:59:59 -07002534 // Validate the modified configuration.
2535 RTCError validate_error = ValidateConfiguration(modified_config);
2536 if (!validate_error.ok()) {
2537 return SafeSetError(std::move(validate_error), error);
2538 }
2539
deadbeef293e9262017-01-11 12:28:30 -08002540 // Note that this isn't possible through chromium, since it's an unsigned
2541 // short in WebIDL.
2542 if (configuration.ice_candidate_pool_size < 0 ||
2543 configuration.ice_candidate_pool_size > UINT16_MAX) {
2544 return SafeSetError(RTCErrorType::INVALID_RANGE, error);
2545 }
2546
2547 // Parse ICE servers before hopping to network thread.
2548 cricket::ServerAddresses stun_servers;
2549 std::vector<cricket::RelayServerConfig> turn_servers;
2550 RTCErrorType parse_error =
2551 ParseIceServers(configuration.servers, &stun_servers, &turn_servers);
2552 if (parse_error != RTCErrorType::NONE) {
2553 return SafeSetError(parse_error, error);
2554 }
2555
2556 // In theory this shouldn't fail.
2557 if (!network_thread()->Invoke<bool>(
2558 RTC_FROM_HERE,
2559 rtc::Bind(&PeerConnection::ReconfigurePortAllocator_n, this,
2560 stun_servers, turn_servers, modified_config.type,
2561 modified_config.ice_candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02002562 modified_config.prune_turn_ports,
2563 modified_config.turn_customizer))) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002564 RTC_LOG(LS_ERROR) << "Failed to apply configuration to PortAllocator.";
deadbeef293e9262017-01-11 12:28:30 -08002565 return SafeSetError(RTCErrorType::INTERNAL_ERROR, error);
2566 }
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07002567
deadbeefd1a38b52016-12-10 13:15:33 -08002568 // As described in JSEP, calling setConfiguration with new ICE servers or
2569 // candidate policy must set a "needs-ice-restart" bit so that the next offer
2570 // triggers an ICE restart which will pick up the changes.
deadbeef293e9262017-01-11 12:28:30 -08002571 if (modified_config.servers != configuration_.servers ||
2572 modified_config.type != configuration_.type ||
2573 modified_config.prune_turn_ports != configuration_.prune_turn_ports) {
Steve Antond25da372017-11-06 14:50:29 -08002574 transport_controller_->SetNeedsIceRestartFlag();
deadbeefd1a38b52016-12-10 13:15:33 -08002575 }
skvladd1f5fda2017-02-03 16:54:05 -08002576
2577 if (modified_config.ice_check_min_interval !=
2578 configuration_.ice_check_min_interval) {
Steve Antond25da372017-11-06 14:50:29 -08002579 transport_controller_->SetIceConfig(ParseIceConfig(modified_config));
skvladd1f5fda2017-02-03 16:54:05 -08002580 }
2581
deadbeef293e9262017-01-11 12:28:30 -08002582 configuration_ = modified_config;
2583 return SafeSetError(RTCErrorType::NONE, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00002584}
2585
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002586bool PeerConnection::AddIceCandidate(
2587 const IceCandidateInterface* ice_candidate) {
Peter Boström1a9d6152015-12-08 22:15:17 +01002588 TRACE_EVENT0("webrtc", "PeerConnection::AddIceCandidate");
zhihuang29ff8442016-07-27 11:07:25 -07002589 if (IsClosed()) {
2590 return false;
2591 }
Steve Antond25da372017-11-06 14:50:29 -08002592
2593 if (!remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002594 RTC_LOG(LS_ERROR) << "ProcessIceMessage: ICE candidates can't be added "
2595 << "without any remote session description.";
Steve Antond25da372017-11-06 14:50:29 -08002596 return false;
2597 }
2598
2599 if (!ice_candidate) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002600 RTC_LOG(LS_ERROR) << "ProcessIceMessage: Candidate is NULL.";
Steve Antond25da372017-11-06 14:50:29 -08002601 return false;
2602 }
2603
2604 bool valid = false;
2605 bool ready = ReadyToUseRemoteCandidate(ice_candidate, nullptr, &valid);
2606 if (!valid) {
2607 return false;
2608 }
2609
2610 // Add this candidate to the remote session description.
2611 if (!mutable_remote_description()->AddCandidate(ice_candidate)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002612 RTC_LOG(LS_ERROR) << "ProcessIceMessage: Candidate cannot be used.";
Steve Antond25da372017-11-06 14:50:29 -08002613 return false;
2614 }
2615
2616 if (ready) {
2617 return UseCandidate(ice_candidate);
2618 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002619 RTC_LOG(LS_INFO) << "ProcessIceMessage: Not ready to use candidate.";
Steve Antond25da372017-11-06 14:50:29 -08002620 return true;
2621 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002622}
2623
Honghai Zhang7fb69db2016-03-14 11:59:18 -07002624bool PeerConnection::RemoveIceCandidates(
2625 const std::vector<cricket::Candidate>& candidates) {
2626 TRACE_EVENT0("webrtc", "PeerConnection::RemoveIceCandidates");
Steve Antond25da372017-11-06 14:50:29 -08002627 if (!remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002628 RTC_LOG(LS_ERROR) << "RemoveRemoteIceCandidates: ICE candidates can't be "
2629 << "removed without any remote session description.";
Steve Antond25da372017-11-06 14:50:29 -08002630 return false;
2631 }
2632
2633 if (candidates.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002634 RTC_LOG(LS_ERROR) << "RemoveRemoteIceCandidates: candidates are empty.";
Steve Antond25da372017-11-06 14:50:29 -08002635 return false;
2636 }
2637
2638 size_t number_removed =
2639 mutable_remote_description()->RemoveCandidates(candidates);
2640 if (number_removed != candidates.size()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002641 RTC_LOG(LS_ERROR)
2642 << "RemoveRemoteIceCandidates: Failed to remove candidates. "
2643 << "Requested " << candidates.size() << " but only " << number_removed
2644 << " are removed.";
Steve Antond25da372017-11-06 14:50:29 -08002645 }
2646
2647 // Remove the candidates from the transport controller.
2648 std::string error;
2649 bool res = transport_controller_->RemoveRemoteCandidates(candidates, &error);
2650 if (!res && !error.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002651 RTC_LOG(LS_ERROR) << "Error when removing remote candidates: " << error;
Steve Antond25da372017-11-06 14:50:29 -08002652 }
2653 return true;
Honghai Zhang7fb69db2016-03-14 11:59:18 -07002654}
2655
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00002656void PeerConnection::RegisterUMAObserver(UMAObserver* observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +01002657 TRACE_EVENT0("webrtc", "PeerConnection::RegisterUmaObserver");
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00002658 uma_observer_ = observer;
guoweis@webrtc.org7169afd2014-12-04 17:59:29 +00002659
Steve Anton75737c02017-11-06 10:37:17 -08002660 if (transport_controller()) {
2661 transport_controller()->SetMetricsObserver(uma_observer_);
guoweis@webrtc.org7169afd2014-12-04 17:59:29 +00002662 }
2663
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00002664 // Send information about IPv4/IPv6 status.
deadbeef293e9262017-01-11 12:28:30 -08002665 if (uma_observer_) {
Honghai Zhangd93f50c2016-10-05 11:47:22 -07002666 port_allocator_->SetMetricsObserver(uma_observer_);
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00002667 if (port_allocator_->flags() & cricket::PORTALLOCATOR_ENABLE_IPV6) {
Guo-wei Shiehdfbe6792015-09-03 17:12:07 -07002668 uma_observer_->IncrementEnumCounter(
2669 kEnumCounterAddressFamily, kPeerConnection_IPv6,
2670 kPeerConnectionAddressFamilyCounter_Max);
mallinath@webrtc.orgb445f262014-05-23 22:19:37 +00002671 } else {
Guo-wei Shiehdfbe6792015-09-03 17:12:07 -07002672 uma_observer_->IncrementEnumCounter(
2673 kEnumCounterAddressFamily, kPeerConnection_IPv4,
2674 kPeerConnectionAddressFamilyCounter_Max);
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00002675 }
2676 }
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00002677}
2678
zstein4b979802017-06-02 14:37:37 -07002679RTCError PeerConnection::SetBitrate(const BitrateParameters& bitrate) {
Steve Anton978b8762017-09-29 12:15:02 -07002680 if (!worker_thread()->IsCurrent()) {
2681 return worker_thread()->Invoke<RTCError>(
zstein4b979802017-06-02 14:37:37 -07002682 RTC_FROM_HERE, rtc::Bind(&PeerConnection::SetBitrate, this, bitrate));
2683 }
2684
2685 const bool has_min = static_cast<bool>(bitrate.min_bitrate_bps);
2686 const bool has_current = static_cast<bool>(bitrate.current_bitrate_bps);
2687 const bool has_max = static_cast<bool>(bitrate.max_bitrate_bps);
2688 if (has_min && *bitrate.min_bitrate_bps < 0) {
2689 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2690 "min_bitrate_bps <= 0");
2691 }
2692 if (has_current) {
2693 if (has_min && *bitrate.current_bitrate_bps < *bitrate.min_bitrate_bps) {
2694 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2695 "current_bitrate_bps < min_bitrate_bps");
2696 } else if (*bitrate.current_bitrate_bps < 0) {
2697 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2698 "curent_bitrate_bps < 0");
2699 }
2700 }
2701 if (has_max) {
2702 if (has_current &&
2703 *bitrate.max_bitrate_bps < *bitrate.current_bitrate_bps) {
2704 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2705 "max_bitrate_bps < current_bitrate_bps");
2706 } else if (has_min && *bitrate.max_bitrate_bps < *bitrate.min_bitrate_bps) {
2707 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2708 "max_bitrate_bps < min_bitrate_bps");
2709 } else if (*bitrate.max_bitrate_bps < 0) {
2710 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2711 "max_bitrate_bps < 0");
2712 }
2713 }
2714
2715 Call::Config::BitrateConfigMask mask;
2716 mask.min_bitrate_bps = bitrate.min_bitrate_bps;
2717 mask.start_bitrate_bps = bitrate.current_bitrate_bps;
2718 mask.max_bitrate_bps = bitrate.max_bitrate_bps;
2719
2720 RTC_DCHECK(call_.get());
2721 call_->SetBitrateConfigMask(mask);
2722
2723 return RTCError::OK();
2724}
2725
Alex Narest78609d52017-10-20 10:37:47 +02002726void PeerConnection::SetBitrateAllocationStrategy(
2727 std::unique_ptr<rtc::BitrateAllocationStrategy>
2728 bitrate_allocation_strategy) {
2729 rtc::Thread* worker_thread = factory_->worker_thread();
2730 if (!worker_thread->IsCurrent()) {
2731 rtc::BitrateAllocationStrategy* strategy_raw =
2732 bitrate_allocation_strategy.release();
2733 auto functor = [this, strategy_raw]() {
2734 call_->SetBitrateAllocationStrategy(
2735 rtc::WrapUnique<rtc::BitrateAllocationStrategy>(strategy_raw));
2736 };
2737 worker_thread->Invoke<void>(RTC_FROM_HERE, functor);
2738 return;
2739 }
2740 RTC_DCHECK(call_.get());
2741 call_->SetBitrateAllocationStrategy(std::move(bitrate_allocation_strategy));
2742}
2743
henrika5f6bf242017-11-01 11:06:56 +01002744void PeerConnection::SetAudioPlayout(bool playout) {
2745 if (!worker_thread()->IsCurrent()) {
2746 worker_thread()->Invoke<void>(
2747 RTC_FROM_HERE,
2748 rtc::Bind(&PeerConnection::SetAudioPlayout, this, playout));
2749 return;
2750 }
2751 auto audio_state =
2752 factory_->channel_manager()->media_engine()->GetAudioState();
2753 audio_state->SetPlayout(playout);
2754}
2755
2756void PeerConnection::SetAudioRecording(bool recording) {
2757 if (!worker_thread()->IsCurrent()) {
2758 worker_thread()->Invoke<void>(
2759 RTC_FROM_HERE,
2760 rtc::Bind(&PeerConnection::SetAudioRecording, this, recording));
2761 return;
2762 }
2763 auto audio_state =
2764 factory_->channel_manager()->media_engine()->GetAudioState();
2765 audio_state->SetRecording(recording);
2766}
2767
Steve Anton8c0f7a72017-10-03 10:03:10 -07002768std::unique_ptr<rtc::SSLCertificate>
2769PeerConnection::GetRemoteAudioSSLCertificate() {
Steve Anton75737c02017-11-06 10:37:17 -08002770 if (!voice_channel()) {
Steve Anton8c0f7a72017-10-03 10:03:10 -07002771 return nullptr;
2772 }
Steve Anton75737c02017-11-06 10:37:17 -08002773 return GetRemoteSSLCertificate(voice_channel()->transport_name());
Steve Anton8c0f7a72017-10-03 10:03:10 -07002774}
2775
Zhi Huang70b820f2018-01-27 14:16:15 -08002776std::unique_ptr<rtc::SSLCertChain>
2777PeerConnection::GetRemoteAudioSSLCertChain() {
2778 if (!voice_channel()) {
2779 return nullptr;
2780 }
2781
2782 return transport_controller_->GetRemoteSSLCertChain(
2783 voice_channel()->transport_name());
2784}
2785
ivoc14d5dbe2016-07-04 07:06:55 -07002786bool PeerConnection::StartRtcEventLog(rtc::PlatformFile file,
2787 int64_t max_size_bytes) {
Elad Alon99c3fe52017-10-13 16:29:40 +02002788 // TODO(eladalon): It would be better to not allow negative values into PC.
2789 const size_t max_size = (max_size_bytes < 0)
2790 ? RtcEventLog::kUnlimitedOutput
2791 : rtc::saturated_cast<size_t>(max_size_bytes);
2792 return StartRtcEventLog(
Bjorn Tereliusde939432017-11-20 17:38:14 +01002793 rtc::MakeUnique<RtcEventLogOutputFile>(file, max_size),
2794 webrtc::RtcEventLog::kImmediateOutput);
Elad Alon99c3fe52017-10-13 16:29:40 +02002795}
2796
Bjorn Tereliusde939432017-11-20 17:38:14 +01002797bool PeerConnection::StartRtcEventLog(std::unique_ptr<RtcEventLogOutput> output,
2798 int64_t output_period_ms) {
Karl Wibergd6b48192017-10-16 23:01:06 +02002799 // TODO(eladalon): In C++14, this can be done with a lambda.
2800 struct Functor {
Bjorn Tereliusde939432017-11-20 17:38:14 +01002801 bool operator()() {
2802 return pc->StartRtcEventLog_w(std::move(output), output_period_ms);
2803 }
Karl Wibergd6b48192017-10-16 23:01:06 +02002804 PeerConnection* const pc;
2805 std::unique_ptr<RtcEventLogOutput> output;
Bjorn Tereliusde939432017-11-20 17:38:14 +01002806 const int64_t output_period_ms;
Elad Alon99c3fe52017-10-13 16:29:40 +02002807 };
Bjorn Tereliusde939432017-11-20 17:38:14 +01002808 return worker_thread()->Invoke<bool>(
2809 RTC_FROM_HERE, Functor{this, std::move(output), output_period_ms});
ivoc14d5dbe2016-07-04 07:06:55 -07002810}
2811
2812void PeerConnection::StopRtcEventLog() {
Steve Anton978b8762017-09-29 12:15:02 -07002813 worker_thread()->Invoke<void>(
ivoc14d5dbe2016-07-04 07:06:55 -07002814 RTC_FROM_HERE, rtc::Bind(&PeerConnection::StopRtcEventLog_w, this));
2815}
2816
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002817const SessionDescriptionInterface* PeerConnection::local_description() const {
Steve Anton75737c02017-11-06 10:37:17 -08002818 return pending_local_description_ ? pending_local_description_.get()
2819 : current_local_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002820}
2821
2822const SessionDescriptionInterface* PeerConnection::remote_description() const {
Steve Anton75737c02017-11-06 10:37:17 -08002823 return pending_remote_description_ ? pending_remote_description_.get()
2824 : current_remote_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002825}
2826
deadbeeffe4a8a42016-12-20 17:56:17 -08002827const SessionDescriptionInterface* PeerConnection::current_local_description()
2828 const {
Steve Anton75737c02017-11-06 10:37:17 -08002829 return current_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08002830}
2831
2832const SessionDescriptionInterface* PeerConnection::current_remote_description()
2833 const {
Steve Anton75737c02017-11-06 10:37:17 -08002834 return current_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08002835}
2836
2837const SessionDescriptionInterface* PeerConnection::pending_local_description()
2838 const {
Steve Anton75737c02017-11-06 10:37:17 -08002839 return pending_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08002840}
2841
2842const SessionDescriptionInterface* PeerConnection::pending_remote_description()
2843 const {
Steve Anton75737c02017-11-06 10:37:17 -08002844 return pending_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08002845}
2846
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002847void PeerConnection::Close() {
Peter Boström1a9d6152015-12-08 22:15:17 +01002848 TRACE_EVENT0("webrtc", "PeerConnection::Close");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002849 // Update stats here so that we have the most recent stats for tracks and
2850 // streams before the channels are closed.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00002851 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002852
Steve Anton75737c02017-11-06 10:37:17 -08002853 ChangeSignalingState(PeerConnectionInterface::kClosed);
Steve Anton3fe1b152017-12-12 10:20:08 -08002854
Steve Anton8af21862017-12-15 11:20:13 -08002855 for (auto transceiver : transceivers_) {
2856 transceiver->Stop();
2857 }
2858 DestroyAllChannels();
Steve Anton75737c02017-11-06 10:37:17 -08002859
deadbeef42a42632017-03-10 15:18:00 -08002860 network_thread()->Invoke<void>(
2861 RTC_FROM_HERE,
2862 rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
2863 port_allocator_.get()));
nisseeaabdf62017-05-05 02:23:02 -07002864
Steve Anton978b8762017-09-29 12:15:02 -07002865 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
eladalon248fd4f2017-09-06 05:18:15 -07002866 call_.reset();
2867 // The event log must outlive call (and any other object that uses it).
2868 event_log_.reset();
2869 });
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002870}
2871
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002872void PeerConnection::OnMessage(rtc::Message* msg) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002873 switch (msg->message_id) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002874 case MSG_SET_SESSIONDESCRIPTION_SUCCESS: {
2875 SetSessionDescriptionMsg* param =
2876 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
2877 param->observer->OnSuccess();
2878 delete param;
2879 break;
2880 }
2881 case MSG_SET_SESSIONDESCRIPTION_FAILED: {
2882 SetSessionDescriptionMsg* param =
2883 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
2884 param->observer->OnFailure(param->error);
2885 delete param;
2886 break;
2887 }
deadbeefab9b2d12015-10-14 11:33:11 -07002888 case MSG_CREATE_SESSIONDESCRIPTION_FAILED: {
2889 CreateSessionDescriptionMsg* param =
2890 static_cast<CreateSessionDescriptionMsg*>(msg->pdata);
2891 param->observer->OnFailure(param->error);
2892 delete param;
2893 break;
2894 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002895 case MSG_GETSTATS: {
2896 GetStatsMsg* param = static_cast<GetStatsMsg*>(msg->pdata);
nissee8abe3e2017-01-18 05:00:34 -08002897 StatsReports reports;
2898 stats_->GetStats(param->track, &reports);
2899 param->observer->OnComplete(reports);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002900 delete param;
2901 break;
2902 }
deadbeefbd292462015-12-14 18:15:29 -08002903 case MSG_FREE_DATACHANNELS: {
2904 sctp_data_channels_to_free_.clear();
2905 break;
2906 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002907 default:
nisseeb4ca4e2017-01-12 02:24:27 -08002908 RTC_NOTREACHED() << "Not implemented";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002909 break;
2910 }
2911}
2912
Steve Anton4171afb2017-11-20 10:20:22 -08002913void PeerConnection::CreateAudioReceiver(
2914 MediaStreamInterface* stream,
2915 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01002916 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
2917 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Steve Antond3679212018-01-17 17:41:02 -08002918 auto* audio_receiver = new AudioRtpReceiver(
2919 worker_thread(), remote_sender_info.sender_id, streams);
2920 audio_receiver->SetMediaChannel(voice_media_channel());
2921 audio_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
2922 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
2923 signaling_thread(), audio_receiver);
Steve Anton4171afb2017-11-20 10:20:22 -08002924 GetAudioTransceiver()->internal()->AddReceiver(receiver);
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01002925 observer_->OnAddTrack(receiver, std::move(streams));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002926}
2927
Steve Anton4171afb2017-11-20 10:20:22 -08002928void PeerConnection::CreateVideoReceiver(
2929 MediaStreamInterface* stream,
2930 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01002931 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
2932 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Steve Antond3679212018-01-17 17:41:02 -08002933 auto* video_receiver = new VideoRtpReceiver(
2934 worker_thread(), remote_sender_info.sender_id, streams);
2935 video_receiver->SetMediaChannel(video_media_channel());
2936 video_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
2937 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
2938 signaling_thread(), video_receiver);
Steve Anton4171afb2017-11-20 10:20:22 -08002939 GetVideoTransceiver()->internal()->AddReceiver(receiver);
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01002940 observer_->OnAddTrack(receiver, std::move(streams));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002941}
2942
deadbeef70ab1a12015-09-28 16:53:55 -07002943// TODO(deadbeef): Keep RtpReceivers around even if track goes away in remote
2944// description.
Henrik Boström933d8b02017-10-10 10:05:16 -07002945rtc::scoped_refptr<RtpReceiverInterface> PeerConnection::RemoveAndStopReceiver(
Steve Anton4171afb2017-11-20 10:20:22 -08002946 const RtpSenderInfo& remote_sender_info) {
2947 auto receiver = FindReceiverById(remote_sender_info.sender_id);
2948 if (!receiver) {
2949 RTC_LOG(LS_WARNING) << "RtpReceiver for track with id "
2950 << remote_sender_info.sender_id << " doesn't exist.";
Henrik Boström933d8b02017-10-10 10:05:16 -07002951 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07002952 }
Steve Anton4171afb2017-11-20 10:20:22 -08002953 if (receiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
2954 GetAudioTransceiver()->internal()->RemoveReceiver(receiver);
2955 } else {
2956 GetVideoTransceiver()->internal()->RemoveReceiver(receiver);
2957 }
Henrik Boström933d8b02017-10-10 10:05:16 -07002958 return receiver;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002959}
2960
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002961void PeerConnection::AddAudioTrack(AudioTrackInterface* track,
2962 MediaStreamInterface* stream) {
2963 RTC_DCHECK(!IsClosed());
2964 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08002965 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002966 // We already have a sender for this track, so just change the stream_id
2967 // so that it's correct in the next call to CreateOffer.
Steve Anton4171afb2017-11-20 10:20:22 -08002968 sender->internal()->set_stream_id(stream->label());
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002969 return;
2970 }
2971
2972 // Normal case; we've never seen this track before.
Steve Anton02ee47c2018-01-10 16:26:06 -08002973 auto new_sender =
2974 CreateSender(cricket::MEDIA_TYPE_AUDIO, track, {stream->label()});
2975 static_cast<AudioRtpSender*>(new_sender->internal())
Steve Anton47136dd2018-01-12 10:49:35 -08002976 ->SetMediaChannel(voice_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08002977 GetAudioTransceiver()->internal()->AddSender(new_sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002978 // If the sender has already been configured in SDP, we call SetSsrc,
2979 // which will connect the sender to the underlying transport. This can
2980 // occur if a local session description that contains the ID of the sender
2981 // is set before AddStream is called. It can also occur if the local
2982 // session description is not changed and RemoveStream is called, and
2983 // later AddStream is called again with the same stream.
Steve Anton4171afb2017-11-20 10:20:22 -08002984 const RtpSenderInfo* sender_info =
2985 FindSenderInfo(local_audio_sender_infos_, stream->label(), track->id());
2986 if (sender_info) {
2987 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002988 }
2989}
2990
2991// TODO(deadbeef): Don't destroy RtpSenders here; they should be kept around
2992// indefinitely, when we have unified plan SDP.
2993void PeerConnection::RemoveAudioTrack(AudioTrackInterface* track,
2994 MediaStreamInterface* stream) {
2995 RTC_DCHECK(!IsClosed());
2996 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08002997 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002998 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
2999 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003000 return;
3001 }
Steve Anton4171afb2017-11-20 10:20:22 -08003002 GetAudioTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003003}
3004
3005void PeerConnection::AddVideoTrack(VideoTrackInterface* track,
3006 MediaStreamInterface* stream) {
3007 RTC_DCHECK(!IsClosed());
3008 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003009 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003010 // We already have a sender for this track, so just change the stream_id
3011 // so that it's correct in the next call to CreateOffer.
Steve Anton4171afb2017-11-20 10:20:22 -08003012 sender->internal()->set_stream_id(stream->label());
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003013 return;
3014 }
3015
3016 // Normal case; we've never seen this track before.
Steve Anton02ee47c2018-01-10 16:26:06 -08003017 auto new_sender =
3018 CreateSender(cricket::MEDIA_TYPE_VIDEO, track, {stream->label()});
3019 static_cast<VideoRtpSender*>(new_sender->internal())
Steve Anton47136dd2018-01-12 10:49:35 -08003020 ->SetMediaChannel(video_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08003021 GetVideoTransceiver()->internal()->AddSender(new_sender);
3022 const RtpSenderInfo* sender_info =
3023 FindSenderInfo(local_video_sender_infos_, stream->label(), track->id());
3024 if (sender_info) {
3025 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003026 }
3027}
3028
3029void PeerConnection::RemoveVideoTrack(VideoTrackInterface* track,
3030 MediaStreamInterface* stream) {
3031 RTC_DCHECK(!IsClosed());
3032 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003033 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003034 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
3035 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003036 return;
3037 }
Steve Anton4171afb2017-11-20 10:20:22 -08003038 GetVideoTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003039}
3040
Steve Antonba818672017-11-06 10:21:57 -08003041void PeerConnection::SetIceConnectionState(IceConnectionState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07003042 RTC_DCHECK(signaling_thread()->IsCurrent());
Steve Antonba818672017-11-06 10:21:57 -08003043 if (ice_connection_state_ == new_state) {
3044 return;
3045 }
3046
deadbeefcbecd352015-09-23 11:50:27 -07003047 // After transitioning to "closed", ignore any additional states from
Steve Antonba818672017-11-06 10:21:57 -08003048 // TransportController (such as "disconnected").
deadbeefab9b2d12015-10-14 11:33:11 -07003049 if (IsClosed()) {
deadbeefcbecd352015-09-23 11:50:27 -07003050 return;
3051 }
Steve Antonba818672017-11-06 10:21:57 -08003052
Mirko Bonadei675513b2017-11-09 11:09:25 +01003053 RTC_LOG(LS_INFO) << "Changing IceConnectionState " << ice_connection_state_
3054 << " => " << new_state;
Steve Antonba818672017-11-06 10:21:57 -08003055 RTC_DCHECK(ice_connection_state_ !=
3056 PeerConnectionInterface::kIceConnectionClosed);
3057
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003058 ice_connection_state_ = new_state;
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00003059 observer_->OnIceConnectionChange(ice_connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003060}
3061
3062void PeerConnection::OnIceGatheringChange(
3063 PeerConnectionInterface::IceGatheringState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07003064 RTC_DCHECK(signaling_thread()->IsCurrent());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003065 if (IsClosed()) {
3066 return;
3067 }
3068 ice_gathering_state_ = new_state;
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00003069 observer_->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003070}
3071
jbauch81bf7b02017-03-25 08:31:12 -07003072void PeerConnection::OnIceCandidate(
3073 std::unique_ptr<IceCandidateInterface> candidate) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07003074 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07003075 if (IsClosed()) {
3076 return;
3077 }
jbauch81bf7b02017-03-25 08:31:12 -07003078 observer_->OnIceCandidate(candidate.get());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003079}
3080
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003081void PeerConnection::OnIceCandidatesRemoved(
3082 const std::vector<cricket::Candidate>& candidates) {
3083 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07003084 if (IsClosed()) {
3085 return;
3086 }
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003087 observer_->OnIceCandidatesRemoved(candidates);
3088}
3089
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003090void PeerConnection::ChangeSignalingState(
3091 PeerConnectionInterface::SignalingState signaling_state) {
Steve Antonba818672017-11-06 10:21:57 -08003092 RTC_DCHECK(signaling_thread()->IsCurrent());
3093 if (signaling_state_ == signaling_state) {
3094 return;
3095 }
Mirko Bonadei675513b2017-11-09 11:09:25 +01003096 RTC_LOG(LS_INFO) << "Session: " << session_id() << " Old state: "
3097 << GetSignalingStateString(signaling_state_)
3098 << " New state: "
3099 << GetSignalingStateString(signaling_state);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003100 signaling_state_ = signaling_state;
3101 if (signaling_state == kClosed) {
3102 ice_connection_state_ = kIceConnectionClosed;
3103 observer_->OnIceConnectionChange(ice_connection_state_);
3104 if (ice_gathering_state_ != kIceGatheringComplete) {
3105 ice_gathering_state_ = kIceGatheringComplete;
3106 observer_->OnIceGatheringChange(ice_gathering_state_);
3107 }
3108 }
3109 observer_->OnSignalingChange(signaling_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003110}
3111
deadbeefeb459812015-12-15 19:24:43 -08003112void PeerConnection::OnAudioTrackAdded(AudioTrackInterface* track,
3113 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003114 if (IsClosed()) {
3115 return;
3116 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003117 AddAudioTrack(track, stream);
3118 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003119}
3120
deadbeefeb459812015-12-15 19:24:43 -08003121void PeerConnection::OnAudioTrackRemoved(AudioTrackInterface* track,
3122 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003123 if (IsClosed()) {
3124 return;
3125 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003126 RemoveAudioTrack(track, stream);
3127 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003128}
3129
3130void PeerConnection::OnVideoTrackAdded(VideoTrackInterface* track,
3131 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003132 if (IsClosed()) {
3133 return;
3134 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003135 AddVideoTrack(track, stream);
3136 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003137}
3138
3139void PeerConnection::OnVideoTrackRemoved(VideoTrackInterface* track,
3140 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003141 if (IsClosed()) {
3142 return;
3143 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003144 RemoveVideoTrack(track, stream);
3145 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003146}
3147
Henrik Boström31638672017-11-23 17:48:32 +01003148void PeerConnection::PostSetSessionDescriptionSuccess(
3149 SetSessionDescriptionObserver* observer) {
3150 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
3151 signaling_thread()->Post(RTC_FROM_HERE, this,
3152 MSG_SET_SESSIONDESCRIPTION_SUCCESS, msg);
3153}
3154
deadbeefab9b2d12015-10-14 11:33:11 -07003155void PeerConnection::PostSetSessionDescriptionFailure(
3156 SetSessionDescriptionObserver* observer,
3157 const std::string& error) {
3158 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
3159 msg->error = error;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07003160 signaling_thread()->Post(RTC_FROM_HERE, this,
3161 MSG_SET_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07003162}
3163
3164void PeerConnection::PostCreateSessionDescriptionFailure(
3165 CreateSessionDescriptionObserver* observer,
3166 const std::string& error) {
3167 CreateSessionDescriptionMsg* msg = new CreateSessionDescriptionMsg(observer);
3168 msg->error = error;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07003169 signaling_thread()->Post(RTC_FROM_HERE, this,
3170 MSG_CREATE_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07003171}
3172
zhihuang1c378ed2017-08-17 14:10:50 -07003173void PeerConnection::GetOptionsForOffer(
Steve Antondcc3c022017-12-22 16:02:54 -08003174 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
deadbeefab9b2d12015-10-14 11:33:11 -07003175 cricket::MediaSessionOptions* session_options) {
Steve Antondcc3c022017-12-22 16:02:54 -08003176 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
zhihuang1c378ed2017-08-17 14:10:50 -07003177
Steve Antondcc3c022017-12-22 16:02:54 -08003178 if (IsUnifiedPlan()) {
3179 GetOptionsForUnifiedPlanOffer(offer_answer_options, session_options);
3180 } else {
3181 GetOptionsForPlanBOffer(offer_answer_options, session_options);
3182 }
3183
Steve Antonfa2260d2017-12-28 16:38:23 -08003184 // Intentionally unset the data channel type for RTP data channel with the
3185 // second condition. Otherwise the RTP data channels would be successfully
3186 // negotiated by default and the unit tests in WebRtcDataBrowserTest will fail
3187 // when building with chromium. We want to leave RTP data channels broken, so
3188 // people won't try to use them.
3189 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
3190 session_options->data_channel_type = data_channel_type();
3191 }
3192
Steve Antondcc3c022017-12-22 16:02:54 -08003193 // Apply ICE restart flag and renomination flag.
3194 for (auto& options : session_options->media_description_options) {
3195 options.transport_options.ice_restart = offer_answer_options.ice_restart;
3196 options.transport_options.enable_ice_renomination =
3197 configuration_.enable_ice_renomination;
3198 }
3199
3200 session_options->rtcp_cname = rtcp_cname_;
3201 session_options->crypto_options = factory_->options().crypto_options;
Steve Antone831b8c2018-02-01 12:22:16 -08003202 session_options->is_unified_plan = IsUnifiedPlan();
Steve Antondcc3c022017-12-22 16:02:54 -08003203}
3204
3205void PeerConnection::GetOptionsForPlanBOffer(
3206 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
3207 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07003208 // Figure out transceiver directional preferences.
3209 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
3210 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
3211
3212 // By default, generate sendrecv/recvonly m= sections.
3213 bool recv_audio = true;
3214 bool recv_video = true;
3215
3216 // By default, only offer a new m= section if we have media to send with it.
3217 bool offer_new_audio_description = send_audio;
3218 bool offer_new_video_description = send_video;
3219 bool offer_new_data_description = HasDataChannels();
3220
3221 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-22 16:02:54 -08003222 if (offer_answer_options.offer_to_receive_audio !=
3223 RTCOfferAnswerOptions::kUndefined) {
3224 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003225 offer_new_audio_description =
Steve Antondcc3c022017-12-22 16:02:54 -08003226 offer_new_audio_description ||
3227 (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003228 }
Steve Antondcc3c022017-12-22 16:02:54 -08003229 if (offer_answer_options.offer_to_receive_video !=
3230 RTCOfferAnswerOptions::kUndefined) {
3231 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003232 offer_new_video_description =
Steve Antondcc3c022017-12-22 16:02:54 -08003233 offer_new_video_description ||
3234 (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003235 }
3236
3237 rtc::Optional<size_t> audio_index;
3238 rtc::Optional<size_t> video_index;
3239 rtc::Optional<size_t> data_index;
3240 // If a current description exists, generate m= sections in the same order,
3241 // using the first audio/video/data section that appears and rejecting
3242 // extraneous ones.
Steve Anton75737c02017-11-06 10:37:17 -08003243 if (local_description()) {
zhihuang1c378ed2017-08-17 14:10:50 -07003244 GenerateMediaDescriptionOptions(
Steve Anton75737c02017-11-06 10:37:17 -08003245 local_description(),
Steve Anton1d03a752017-11-27 14:30:09 -08003246 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
3247 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
3248 &audio_index, &video_index, &data_index, session_options);
deadbeefab9b2d12015-10-14 11:33:11 -07003249 }
3250
zhihuang1c378ed2017-08-17 14:10:50 -07003251 // Add audio/video/data m= sections to the end if needed.
3252 if (!audio_index && offer_new_audio_description) {
3253 session_options->media_description_options.push_back(
3254 cricket::MediaDescriptionOptions(
3255 cricket::MEDIA_TYPE_AUDIO, cricket::CN_AUDIO,
Steve Anton1d03a752017-11-27 14:30:09 -08003256 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
3257 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003258 audio_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07003259 }
zhihuang1c378ed2017-08-17 14:10:50 -07003260 if (!video_index && offer_new_video_description) {
3261 session_options->media_description_options.push_back(
3262 cricket::MediaDescriptionOptions(
3263 cricket::MEDIA_TYPE_VIDEO, cricket::CN_VIDEO,
Steve Anton1d03a752017-11-27 14:30:09 -08003264 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
3265 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003266 video_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07003267 }
zhihuang1c378ed2017-08-17 14:10:50 -07003268 if (!data_index && offer_new_data_description) {
3269 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08003270 GetMediaDescriptionOptionsForActiveData(cricket::CN_DATA));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003271 data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07003272 }
3273
3274 cricket::MediaDescriptionOptions* audio_media_description_options =
3275 !audio_index ? nullptr
3276 : &session_options->media_description_options[*audio_index];
3277 cricket::MediaDescriptionOptions* video_media_description_options =
3278 !video_index ? nullptr
3279 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 14:10:50 -07003280
Steve Anton4171afb2017-11-20 10:20:22 -08003281 AddRtpSenderOptions(GetSendersInternal(), audio_media_description_options,
zhihuang1c378ed2017-08-17 14:10:50 -07003282 video_media_description_options);
Steve Antondcc3c022017-12-22 16:02:54 -08003283}
3284
3285// Find a new MID that is not already in |used_mids|, then add it to |used_mids|
3286// and return a reference to it.
3287// Generated MIDs should be no more than 3 bytes long to take up less space in
3288// the RTP packet.
3289static const std::string& AllocateMid(std::set<std::string>* used_mids) {
3290 RTC_DCHECK(used_mids);
3291 // We're boring: just generate MIDs 0, 1, 2, ...
3292 size_t i = 0;
3293 std::set<std::string>::iterator it;
3294 bool inserted;
3295 do {
3296 std::string mid = rtc::ToString(i++);
3297 auto insert_result = used_mids->insert(mid);
3298 it = insert_result.first;
3299 inserted = insert_result.second;
3300 } while (!inserted);
3301 return *it;
3302}
3303
3304static cricket::MediaDescriptionOptions
3305GetMediaDescriptionOptionsForTransceiver(
3306 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3307 transceiver,
3308 const std::string& mid) {
3309 cricket::MediaDescriptionOptions media_description_options(
3310 transceiver->internal()->media_type(), mid, transceiver->direction(),
3311 transceiver->stopped());
Steve Anton5f94aa22018-02-01 10:58:30 -08003312 // This behavior is specified in JSEP. The gist is that:
3313 // 1. The MSID is included if the RtpTransceiver's direction is sendonly or
3314 // sendrecv.
3315 // 2. If the MSID is included, then it must be included in any subsequent
3316 // offer/answer exactly the same until the RtpTransceiver is stopped.
3317 if (!transceiver->stopped() &&
3318 (RtpTransceiverDirectionHasSend(transceiver->direction()) ||
3319 transceiver->internal()->has_ever_been_used_to_send())) {
3320 cricket::SenderOptions sender_options;
3321 sender_options.track_id = transceiver->sender()->id();
3322 sender_options.stream_ids = transceiver->sender()->stream_ids();
3323 // TODO(bugs.webrtc.org/7600): Set num_sim_layers to the number of encodings
3324 // set in the RTP parameters when the transceiver was added.
3325 sender_options.num_sim_layers = 1;
3326 media_description_options.sender_options.push_back(sender_options);
3327 }
Steve Antondcc3c022017-12-22 16:02:54 -08003328 return media_description_options;
3329}
3330
3331void PeerConnection::GetOptionsForUnifiedPlanOffer(
3332 const RTCOfferAnswerOptions& offer_answer_options,
3333 cricket::MediaSessionOptions* session_options) {
3334 // Rules for generating an offer are dictated by JSEP sections 5.2.1 (Initial
3335 // Offers) and 5.2.2 (Subsequent Offers).
3336 RTC_DCHECK_EQ(session_options->media_description_options.size(), 0);
3337 const ContentInfos& local_contents =
3338 (local_description() ? local_description()->description()->contents()
3339 : ContentInfos());
3340 const ContentInfos& remote_contents =
3341 (remote_description() ? remote_description()->description()->contents()
3342 : ContentInfos());
3343 // The mline indices that can be recycled. New transceivers should reuse these
3344 // slots first.
3345 std::queue<size_t> recycleable_mline_indices;
3346 // Track the MIDs used in previous offer/answer exchanges and the current
3347 // offer so that new, unique MIDs are generated.
3348 std::set<std::string> used_mids = seen_mids_;
3349 // First, go through each media section that exists in either the local or
3350 // remote description and generate a media section in this offer for the
3351 // associated transceiver. If a media section can be recycled, generate a
3352 // default, rejected media section here that can be later overwritten.
3353 for (size_t i = 0;
3354 i < std::max(local_contents.size(), remote_contents.size()); ++i) {
3355 // Either |local_content| or |remote_content| is non-null.
3356 const ContentInfo* local_content =
3357 (i < local_contents.size() ? &local_contents[i] : nullptr);
3358 const ContentInfo* remote_content =
3359 (i < remote_contents.size() ? &remote_contents[i] : nullptr);
3360 bool had_been_rejected = (local_content && local_content->rejected) ||
3361 (remote_content && remote_content->rejected);
3362 const std::string& mid =
3363 (local_content ? local_content->name : remote_content->name);
3364 cricket::MediaType media_type =
3365 (local_content ? local_content->media_description()->type()
3366 : remote_content->media_description()->type());
3367 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
3368 media_type == cricket::MEDIA_TYPE_VIDEO) {
3369 auto transceiver = GetAssociatedTransceiver(mid);
3370 RTC_CHECK(transceiver);
3371 // A media section is considered eligible for recycling if it is marked as
3372 // rejected in either the local or remote description.
3373 if (had_been_rejected) {
3374 session_options->media_description_options.push_back(
3375 cricket::MediaDescriptionOptions(
3376 transceiver->internal()->media_type(), mid,
3377 RtpTransceiverDirection::kInactive,
3378 /*stopped=*/true));
3379 recycleable_mline_indices.push(i);
3380 } else {
3381 session_options->media_description_options.push_back(
3382 GetMediaDescriptionOptionsForTransceiver(transceiver, mid));
3383 // CreateOffer shouldn't really cause any state changes in
3384 // PeerConnection, but we need a way to match new transceivers to new
3385 // media sections in SetLocalDescription and JSEP specifies this is done
3386 // by recording the index of the media section generated for the
3387 // transceiver in the offer.
3388 transceiver->internal()->set_mline_index(i);
3389 }
3390 } else {
3391 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antonfa2260d2017-12-28 16:38:23 -08003392 RTC_CHECK(GetDataMid());
3393 if (had_been_rejected || mid != *GetDataMid()) {
3394 session_options->media_description_options.push_back(
3395 GetMediaDescriptionOptionsForRejectedData(mid));
3396 } else {
3397 session_options->media_description_options.push_back(
3398 GetMediaDescriptionOptionsForActiveData(mid));
3399 }
Steve Antondcc3c022017-12-22 16:02:54 -08003400 }
3401 }
3402 // Next, look for transceivers that are newly added (that is, are not stopped
3403 // and not associated). Reuse media sections marked as recyclable first,
3404 // otherwise append to the end of the offer. New media sections should be
3405 // added in the order they were added to the PeerConnection.
3406 for (auto transceiver : transceivers_) {
3407 if (transceiver->mid() || transceiver->stopped()) {
3408 continue;
3409 }
3410 size_t mline_index;
3411 if (!recycleable_mline_indices.empty()) {
3412 mline_index = recycleable_mline_indices.front();
3413 recycleable_mline_indices.pop();
3414 session_options->media_description_options[mline_index] =
3415 GetMediaDescriptionOptionsForTransceiver(transceiver,
3416 AllocateMid(&used_mids));
3417 } else {
3418 mline_index = session_options->media_description_options.size();
3419 session_options->media_description_options.push_back(
3420 GetMediaDescriptionOptionsForTransceiver(transceiver,
3421 AllocateMid(&used_mids)));
3422 }
3423 // See comment above for why CreateOffer changes the transceiver's state.
3424 transceiver->internal()->set_mline_index(mline_index);
3425 }
Steve Antonfa2260d2017-12-28 16:38:23 -08003426 // Lastly, add a m-section if we have local data channels and an m section
3427 // does not already exist.
3428 if (!GetDataMid() && HasDataChannels()) {
3429 session_options->media_description_options.push_back(
3430 GetMediaDescriptionOptionsForActiveData(AllocateMid(&used_mids)));
3431 }
Steve Antondcc3c022017-12-22 16:02:54 -08003432}
3433
3434void PeerConnection::GetOptionsForAnswer(
3435 const RTCOfferAnswerOptions& offer_answer_options,
3436 cricket::MediaSessionOptions* session_options) {
3437 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
3438
3439 if (IsUnifiedPlan()) {
3440 GetOptionsForUnifiedPlanAnswer(offer_answer_options, session_options);
3441 } else {
3442 GetOptionsForPlanBAnswer(offer_answer_options, session_options);
3443 }
3444
Steve Antonfa2260d2017-12-28 16:38:23 -08003445 // Intentionally unset the data channel type for RTP data channel. Otherwise
3446 // the RTP data channels would be successfully negotiated by default and the
3447 // unit tests in WebRtcDataBrowserTest will fail when building with chromium.
3448 // We want to leave RTP data channels broken, so people won't try to use them.
3449 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
3450 session_options->data_channel_type = data_channel_type();
3451 }
3452
Steve Antondcc3c022017-12-22 16:02:54 -08003453 // Apply ICE renomination flag.
3454 for (auto& options : session_options->media_description_options) {
3455 options.transport_options.enable_ice_renomination =
3456 configuration_.enable_ice_renomination;
3457 }
zhihuang8f65cdf2016-05-06 18:40:30 -07003458
3459 session_options->rtcp_cname = rtcp_cname_;
jbauchcb560652016-08-04 05:20:32 -07003460 session_options->crypto_options = factory_->options().crypto_options;
Steve Antone831b8c2018-02-01 12:22:16 -08003461 session_options->is_unified_plan = IsUnifiedPlan();
deadbeefab9b2d12015-10-14 11:33:11 -07003462}
3463
Steve Antondcc3c022017-12-22 16:02:54 -08003464void PeerConnection::GetOptionsForPlanBAnswer(
3465 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07003466 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07003467 // Figure out transceiver directional preferences.
3468 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
3469 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
3470
3471 // By default, generate sendrecv/recvonly m= sections. The direction is also
3472 // restricted by the direction in the offer.
3473 bool recv_audio = true;
3474 bool recv_video = true;
3475
3476 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-22 16:02:54 -08003477 if (offer_answer_options.offer_to_receive_audio !=
3478 RTCOfferAnswerOptions::kUndefined) {
3479 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
deadbeef0ed85b22016-02-23 17:24:52 -08003480 }
Steve Antondcc3c022017-12-22 16:02:54 -08003481 if (offer_answer_options.offer_to_receive_video !=
3482 RTCOfferAnswerOptions::kUndefined) {
3483 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003484 }
3485
3486 rtc::Optional<size_t> audio_index;
3487 rtc::Optional<size_t> video_index;
3488 rtc::Optional<size_t> data_index;
Oleh Prypinc22d6a82018-02-02 08:42:18 +00003489 if (remote_description()) {
3490 // The pending remote description should be an offer.
3491 RTC_DCHECK(remote_description()->GetType() == SdpType::kOffer);
3492 // Generate m= sections that match those in the offer.
3493 // Note that mediasession.cc will handle intersection our preferred
3494 // direction with the offered direction.
3495 GenerateMediaDescriptionOptions(
3496 remote_description(),
3497 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
3498 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
3499 &audio_index, &video_index, &data_index, session_options);
3500 }
zhihuang1c378ed2017-08-17 14:10:50 -07003501
3502 cricket::MediaDescriptionOptions* audio_media_description_options =
3503 !audio_index ? nullptr
3504 : &session_options->media_description_options[*audio_index];
3505 cricket::MediaDescriptionOptions* video_media_description_options =
3506 !video_index ? nullptr
3507 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 14:10:50 -07003508
Steve Anton4171afb2017-11-20 10:20:22 -08003509 AddRtpSenderOptions(GetSendersInternal(), audio_media_description_options,
zhihuang1c378ed2017-08-17 14:10:50 -07003510 video_media_description_options);
Steve Antondcc3c022017-12-22 16:02:54 -08003511}
zhihuangaf388472016-11-02 16:49:48 -07003512
Steve Antondcc3c022017-12-22 16:02:54 -08003513void PeerConnection::GetOptionsForUnifiedPlanAnswer(
3514 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
3515 cricket::MediaSessionOptions* session_options) {
3516 // Rules for generating an answer are dictated by JSEP sections 5.3.1 (Initial
3517 // Answers) and 5.3.2 (Subsequent Answers).
3518 RTC_DCHECK(remote_description());
3519 RTC_DCHECK(remote_description()->GetType() == SdpType::kOffer);
3520 for (const ContentInfo& content :
3521 remote_description()->description()->contents()) {
3522 cricket::MediaType media_type = content.media_description()->type();
3523 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
3524 media_type == cricket::MEDIA_TYPE_VIDEO) {
3525 auto transceiver = GetAssociatedTransceiver(content.name);
3526 RTC_CHECK(transceiver);
3527 session_options->media_description_options.push_back(
3528 GetMediaDescriptionOptionsForTransceiver(transceiver, content.name));
3529 } else {
3530 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antondbf9d032018-01-19 15:23:40 -08003531 // Reject all data sections if data channels are disabled.
3532 // Reject a data section if it has already been rejected.
3533 // Reject all data sections except for the first one.
3534 if (data_channel_type_ == cricket::DCT_NONE || content.rejected ||
3535 content.name != *GetDataMid()) {
Steve Antonfa2260d2017-12-28 16:38:23 -08003536 session_options->media_description_options.push_back(
3537 GetMediaDescriptionOptionsForRejectedData(content.name));
3538 } else {
3539 session_options->media_description_options.push_back(
3540 GetMediaDescriptionOptionsForActiveData(content.name));
3541 }
Steve Antondcc3c022017-12-22 16:02:54 -08003542 }
3543 }
htaa2a49d92016-03-04 02:51:39 -08003544}
3545
zhihuang1c378ed2017-08-17 14:10:50 -07003546void PeerConnection::GenerateMediaDescriptionOptions(
3547 const SessionDescriptionInterface* session_desc,
Steve Anton1d03a752017-11-27 14:30:09 -08003548 RtpTransceiverDirection audio_direction,
3549 RtpTransceiverDirection video_direction,
zhihuang1c378ed2017-08-17 14:10:50 -07003550 rtc::Optional<size_t>* audio_index,
3551 rtc::Optional<size_t>* video_index,
3552 rtc::Optional<size_t>* data_index,
htaa2a49d92016-03-04 02:51:39 -08003553 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07003554 for (const cricket::ContentInfo& content :
3555 session_desc->description()->contents()) {
3556 if (IsAudioContent(&content)) {
3557 // If we already have an audio m= section, reject this extra one.
3558 if (*audio_index) {
3559 session_options->media_description_options.push_back(
3560 cricket::MediaDescriptionOptions(
3561 cricket::MEDIA_TYPE_AUDIO, content.name,
Steve Anton1d03a752017-11-27 14:30:09 -08003562 RtpTransceiverDirection::kInactive, true));
zhihuang1c378ed2017-08-17 14:10:50 -07003563 } else {
3564 session_options->media_description_options.push_back(
3565 cricket::MediaDescriptionOptions(
3566 cricket::MEDIA_TYPE_AUDIO, content.name, audio_direction,
Steve Anton1d03a752017-11-27 14:30:09 -08003567 audio_direction == RtpTransceiverDirection::kInactive));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003568 *audio_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07003569 }
3570 } else if (IsVideoContent(&content)) {
3571 // If we already have an video m= section, reject this extra one.
3572 if (*video_index) {
3573 session_options->media_description_options.push_back(
3574 cricket::MediaDescriptionOptions(
3575 cricket::MEDIA_TYPE_VIDEO, content.name,
Steve Anton1d03a752017-11-27 14:30:09 -08003576 RtpTransceiverDirection::kInactive, true));
zhihuang1c378ed2017-08-17 14:10:50 -07003577 } else {
3578 session_options->media_description_options.push_back(
3579 cricket::MediaDescriptionOptions(
3580 cricket::MEDIA_TYPE_VIDEO, content.name, video_direction,
Steve Anton1d03a752017-11-27 14:30:09 -08003581 video_direction == RtpTransceiverDirection::kInactive));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003582 *video_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07003583 }
3584 } else {
3585 RTC_DCHECK(IsDataContent(&content));
3586 // If we already have an data m= section, reject this extra one.
3587 if (*data_index) {
3588 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08003589 GetMediaDescriptionOptionsForRejectedData(content.name));
zhihuang1c378ed2017-08-17 14:10:50 -07003590 } else {
3591 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08003592 GetMediaDescriptionOptionsForActiveData(content.name));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003593 *data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07003594 }
3595 }
htaa2a49d92016-03-04 02:51:39 -08003596 }
deadbeefab9b2d12015-10-14 11:33:11 -07003597}
3598
Steve Antonfa2260d2017-12-28 16:38:23 -08003599cricket::MediaDescriptionOptions
3600PeerConnection::GetMediaDescriptionOptionsForActiveData(
3601 const std::string& mid) const {
3602 // Direction for data sections is meaningless, but legacy endpoints might
3603 // expect sendrecv.
3604 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
3605 RtpTransceiverDirection::kSendRecv,
3606 /*stopped=*/false);
3607 AddRtpDataChannelOptions(rtp_data_channels_, &options);
3608 return options;
3609}
3610
3611cricket::MediaDescriptionOptions
3612PeerConnection::GetMediaDescriptionOptionsForRejectedData(
3613 const std::string& mid) const {
3614 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
3615 RtpTransceiverDirection::kInactive,
3616 /*stopped=*/true);
3617 AddRtpDataChannelOptions(rtp_data_channels_, &options);
3618 return options;
3619}
3620
3621rtc::Optional<std::string> PeerConnection::GetDataMid() const {
3622 switch (data_channel_type_) {
3623 case cricket::DCT_RTP:
3624 if (!rtp_data_channel_) {
3625 return rtc::nullopt;
3626 }
3627 return rtp_data_channel_->content_name();
3628 case cricket::DCT_SCTP:
3629 return sctp_content_name_;
3630 default:
3631 return rtc::nullopt;
3632 }
3633}
3634
Steve Anton4171afb2017-11-20 10:20:22 -08003635void PeerConnection::RemoveSenders(cricket::MediaType media_type) {
3636 UpdateLocalSenders(std::vector<cricket::StreamParams>(), media_type);
3637 UpdateRemoteSendersList(std::vector<cricket::StreamParams>(), false,
deadbeefbda7e0b2015-12-08 17:13:40 -08003638 media_type, nullptr);
deadbeeffaac4972015-11-12 15:33:07 -08003639}
3640
Steve Anton4171afb2017-11-20 10:20:22 -08003641void PeerConnection::UpdateRemoteSendersList(
deadbeefab9b2d12015-10-14 11:33:11 -07003642 const cricket::StreamParamsVec& streams,
Steve Anton4171afb2017-11-20 10:20:22 -08003643 bool default_sender_needed,
deadbeefab9b2d12015-10-14 11:33:11 -07003644 cricket::MediaType media_type,
3645 StreamCollection* new_streams) {
Steve Anton4171afb2017-11-20 10:20:22 -08003646 std::vector<RtpSenderInfo>* current_senders =
3647 GetRemoteSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07003648
Steve Anton4171afb2017-11-20 10:20:22 -08003649 // Find removed senders. I.e., senders where the sender id or ssrc don't match
deadbeeffac06552015-11-25 11:26:01 -08003650 // the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08003651 for (auto sender_it = current_senders->begin();
3652 sender_it != current_senders->end();
3653 /* incremented manually */) {
3654 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07003655 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08003656 cricket::GetStreamBySsrc(streams, info.first_ssrc);
3657 bool sender_exists = params && params->id == info.sender_id;
deadbeefbda7e0b2015-12-08 17:13:40 -08003658 // If this is a default track, and we still need it, don't remove it.
Steve Anton4171afb2017-11-20 10:20:22 -08003659 if ((info.stream_label == kDefaultStreamLabel && default_sender_needed) ||
3660 sender_exists) {
3661 ++sender_it;
deadbeefbda7e0b2015-12-08 17:13:40 -08003662 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08003663 OnRemoteSenderRemoved(info, media_type);
3664 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07003665 }
3666 }
3667
Steve Anton4171afb2017-11-20 10:20:22 -08003668 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07003669 for (const cricket::StreamParams& params : streams) {
3670 // The sync_label is the MediaStream label and the |stream.id| is the
Steve Anton4171afb2017-11-20 10:20:22 -08003671 // sender id.
deadbeefab9b2d12015-10-14 11:33:11 -07003672 const std::string& stream_label = params.sync_label;
Steve Anton4171afb2017-11-20 10:20:22 -08003673 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07003674 uint32_t ssrc = params.first_ssrc();
3675
3676 rtc::scoped_refptr<MediaStreamInterface> stream =
3677 remote_streams_->find(stream_label);
3678 if (!stream) {
3679 // This is a new MediaStream. Create a new remote MediaStream.
perkjd61bf802016-03-24 03:16:19 -07003680 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
3681 MediaStream::Create(stream_label));
deadbeefab9b2d12015-10-14 11:33:11 -07003682 remote_streams_->AddStream(stream);
3683 new_streams->AddStream(stream);
3684 }
3685
Steve Anton4171afb2017-11-20 10:20:22 -08003686 const RtpSenderInfo* sender_info =
3687 FindSenderInfo(*current_senders, stream_label, sender_id);
3688 if (!sender_info) {
3689 current_senders->push_back(RtpSenderInfo(stream_label, sender_id, ssrc));
3690 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07003691 }
3692 }
deadbeefbda7e0b2015-12-08 17:13:40 -08003693
Steve Anton4171afb2017-11-20 10:20:22 -08003694 // Add default sender if necessary.
3695 if (default_sender_needed) {
deadbeefbda7e0b2015-12-08 17:13:40 -08003696 rtc::scoped_refptr<MediaStreamInterface> default_stream =
3697 remote_streams_->find(kDefaultStreamLabel);
3698 if (!default_stream) {
3699 // Create the new default MediaStream.
perkjd61bf802016-03-24 03:16:19 -07003700 default_stream = MediaStreamProxy::Create(
3701 rtc::Thread::Current(), MediaStream::Create(kDefaultStreamLabel));
deadbeefbda7e0b2015-12-08 17:13:40 -08003702 remote_streams_->AddStream(default_stream);
3703 new_streams->AddStream(default_stream);
3704 }
Steve Anton4171afb2017-11-20 10:20:22 -08003705 std::string default_sender_id = (media_type == cricket::MEDIA_TYPE_AUDIO)
3706 ? kDefaultAudioSenderId
3707 : kDefaultVideoSenderId;
3708 const RtpSenderInfo* default_sender_info = FindSenderInfo(
3709 *current_senders, kDefaultStreamLabel, default_sender_id);
3710 if (!default_sender_info) {
3711 current_senders->push_back(
3712 RtpSenderInfo(kDefaultStreamLabel, default_sender_id, 0));
3713 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefbda7e0b2015-12-08 17:13:40 -08003714 }
3715 }
deadbeefab9b2d12015-10-14 11:33:11 -07003716}
3717
Steve Anton4171afb2017-11-20 10:20:22 -08003718void PeerConnection::OnRemoteSenderAdded(const RtpSenderInfo& sender_info,
3719 cricket::MediaType media_type) {
3720 MediaStreamInterface* stream =
3721 remote_streams_->find(sender_info.stream_label);
deadbeefab9b2d12015-10-14 11:33:11 -07003722
3723 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 10:20:22 -08003724 CreateAudioReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07003725 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 10:20:22 -08003726 CreateVideoReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07003727 } else {
nisseeb4ca4e2017-01-12 02:24:27 -08003728 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07003729 }
3730}
3731
Steve Anton4171afb2017-11-20 10:20:22 -08003732void PeerConnection::OnRemoteSenderRemoved(const RtpSenderInfo& sender_info,
3733 cricket::MediaType media_type) {
3734 MediaStreamInterface* stream =
3735 remote_streams_->find(sender_info.stream_label);
deadbeefab9b2d12015-10-14 11:33:11 -07003736
Henrik Boström933d8b02017-10-10 10:05:16 -07003737 rtc::scoped_refptr<RtpReceiverInterface> receiver;
deadbeefab9b2d12015-10-14 11:33:11 -07003738 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
perkjd61bf802016-03-24 03:16:19 -07003739 // When the MediaEngine audio channel is destroyed, the RemoteAudioSource
3740 // will be notified which will end the AudioRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08003741 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07003742 rtc::scoped_refptr<AudioTrackInterface> audio_track =
Steve Anton4171afb2017-11-20 10:20:22 -08003743 stream->FindAudioTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07003744 if (audio_track) {
deadbeefab9b2d12015-10-14 11:33:11 -07003745 stream->RemoveTrack(audio_track);
deadbeefab9b2d12015-10-14 11:33:11 -07003746 }
3747 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
perkjd61bf802016-03-24 03:16:19 -07003748 // Stopping or destroying a VideoRtpReceiver will end the
3749 // VideoRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08003750 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07003751 rtc::scoped_refptr<VideoTrackInterface> video_track =
Steve Anton4171afb2017-11-20 10:20:22 -08003752 stream->FindVideoTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07003753 if (video_track) {
perkjd61bf802016-03-24 03:16:19 -07003754 // There's no guarantee the track is still available, e.g. the track may
3755 // have been removed from the stream by an application.
deadbeefab9b2d12015-10-14 11:33:11 -07003756 stream->RemoveTrack(video_track);
deadbeefab9b2d12015-10-14 11:33:11 -07003757 }
3758 } else {
nisseede5da42017-01-12 05:15:36 -08003759 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07003760 }
Henrik Boström933d8b02017-10-10 10:05:16 -07003761 if (receiver) {
3762 observer_->OnRemoveTrack(receiver);
3763 }
deadbeefab9b2d12015-10-14 11:33:11 -07003764}
3765
3766void PeerConnection::UpdateEndedRemoteMediaStreams() {
3767 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams_to_remove;
3768 for (size_t i = 0; i < remote_streams_->count(); ++i) {
3769 MediaStreamInterface* stream = remote_streams_->at(i);
3770 if (stream->GetAudioTracks().empty() && stream->GetVideoTracks().empty()) {
3771 streams_to_remove.push_back(stream);
3772 }
3773 }
3774
Taylor Brandstetter98cde262016-05-31 13:02:21 -07003775 for (auto& stream : streams_to_remove) {
deadbeefab9b2d12015-10-14 11:33:11 -07003776 remote_streams_->RemoveStream(stream);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07003777 observer_->OnRemoveStream(std::move(stream));
deadbeefab9b2d12015-10-14 11:33:11 -07003778 }
3779}
3780
Steve Anton4171afb2017-11-20 10:20:22 -08003781void PeerConnection::UpdateLocalSenders(
deadbeefab9b2d12015-10-14 11:33:11 -07003782 const std::vector<cricket::StreamParams>& streams,
3783 cricket::MediaType media_type) {
Steve Anton4171afb2017-11-20 10:20:22 -08003784 std::vector<RtpSenderInfo>* current_senders = GetLocalSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07003785
3786 // Find removed tracks. I.e., tracks where the track id, stream label or ssrc
3787 // don't match the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08003788 for (auto sender_it = current_senders->begin();
3789 sender_it != current_senders->end();
3790 /* incremented manually */) {
3791 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07003792 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08003793 cricket::GetStreamBySsrc(streams, info.first_ssrc);
3794 if (!params || params->id != info.sender_id ||
deadbeefab9b2d12015-10-14 11:33:11 -07003795 params->sync_label != info.stream_label) {
Steve Anton4171afb2017-11-20 10:20:22 -08003796 OnLocalSenderRemoved(info, media_type);
3797 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07003798 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08003799 ++sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07003800 }
3801 }
3802
Steve Anton4171afb2017-11-20 10:20:22 -08003803 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07003804 for (const cricket::StreamParams& params : streams) {
3805 // The sync_label is the MediaStream label and the |stream.id| is the
Steve Anton4171afb2017-11-20 10:20:22 -08003806 // sender id.
deadbeefab9b2d12015-10-14 11:33:11 -07003807 const std::string& stream_label = params.sync_label;
Steve Anton4171afb2017-11-20 10:20:22 -08003808 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07003809 uint32_t ssrc = params.first_ssrc();
Steve Anton4171afb2017-11-20 10:20:22 -08003810 const RtpSenderInfo* sender_info =
3811 FindSenderInfo(*current_senders, stream_label, sender_id);
3812 if (!sender_info) {
3813 current_senders->push_back(RtpSenderInfo(stream_label, sender_id, ssrc));
3814 OnLocalSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07003815 }
3816 }
3817}
3818
Steve Anton4171afb2017-11-20 10:20:22 -08003819void PeerConnection::OnLocalSenderAdded(const RtpSenderInfo& sender_info,
3820 cricket::MediaType media_type) {
3821 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08003822 if (!sender) {
Steve Anton4171afb2017-11-20 10:20:22 -08003823 RTC_LOG(LS_WARNING) << "An unknown RtpSender with id "
3824 << sender_info.sender_id
Mirko Bonadei675513b2017-11-09 11:09:25 +01003825 << " has been configured in the local description.";
deadbeefab9b2d12015-10-14 11:33:11 -07003826 return;
3827 }
3828
deadbeeffac06552015-11-25 11:26:01 -08003829 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003830 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
3831 << " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08003832 return;
deadbeefab9b2d12015-10-14 11:33:11 -07003833 }
deadbeeffac06552015-11-25 11:26:01 -08003834
Steve Anton4171afb2017-11-20 10:20:22 -08003835 sender->internal()->set_stream_id(sender_info.stream_label);
3836 sender->internal()->SetSsrc(sender_info.first_ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07003837}
3838
Steve Anton4171afb2017-11-20 10:20:22 -08003839void PeerConnection::OnLocalSenderRemoved(const RtpSenderInfo& sender_info,
3840 cricket::MediaType media_type) {
3841 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08003842 if (!sender) {
3843 // This is the normal case. I.e., RemoveStream has been called and the
deadbeefab9b2d12015-10-14 11:33:11 -07003844 // SessionDescriptions has been renegotiated.
3845 return;
3846 }
deadbeeffac06552015-11-25 11:26:01 -08003847
3848 // A sender has been removed from the SessionDescription but it's still
3849 // associated with the PeerConnection. This only occurs if the SDP doesn't
3850 // match with the calls to CreateSender, AddStream and RemoveStream.
3851 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003852 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
3853 << " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08003854 return;
deadbeefab9b2d12015-10-14 11:33:11 -07003855 }
deadbeeffac06552015-11-25 11:26:01 -08003856
Steve Anton4171afb2017-11-20 10:20:22 -08003857 sender->internal()->SetSsrc(0);
deadbeefab9b2d12015-10-14 11:33:11 -07003858}
3859
3860void PeerConnection::UpdateLocalRtpDataChannels(
3861 const cricket::StreamParamsVec& streams) {
3862 std::vector<std::string> existing_channels;
3863
3864 // Find new and active data channels.
3865 for (const cricket::StreamParams& params : streams) {
3866 // |it->sync_label| is actually the data channel label. The reason is that
3867 // we use the same naming of data channels as we do for
3868 // MediaStreams and Tracks.
3869 // For MediaStreams, the sync_label is the MediaStream label and the
3870 // track label is the same as |streamid|.
3871 const std::string& channel_label = params.sync_label;
3872 auto data_channel_it = rtp_data_channels_.find(channel_label);
nisse7ce109a2017-01-31 00:57:56 -08003873 if (data_channel_it == rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003874 RTC_LOG(LS_ERROR) << "channel label not found";
deadbeefab9b2d12015-10-14 11:33:11 -07003875 continue;
3876 }
3877 // Set the SSRC the data channel should use for sending.
3878 data_channel_it->second->SetSendSsrc(params.first_ssrc());
3879 existing_channels.push_back(data_channel_it->first);
3880 }
3881
3882 UpdateClosingRtpDataChannels(existing_channels, true);
3883}
3884
3885void PeerConnection::UpdateRemoteRtpDataChannels(
3886 const cricket::StreamParamsVec& streams) {
3887 std::vector<std::string> existing_channels;
3888
3889 // Find new and active data channels.
3890 for (const cricket::StreamParams& params : streams) {
3891 // The data channel label is either the mslabel or the SSRC if the mslabel
3892 // does not exist. Ex a=ssrc:444330170 mslabel:test1.
3893 std::string label = params.sync_label.empty()
3894 ? rtc::ToString(params.first_ssrc())
3895 : params.sync_label;
3896 auto data_channel_it = rtp_data_channels_.find(label);
3897 if (data_channel_it == rtp_data_channels_.end()) {
3898 // This is a new data channel.
3899 CreateRemoteRtpDataChannel(label, params.first_ssrc());
3900 } else {
3901 data_channel_it->second->SetReceiveSsrc(params.first_ssrc());
3902 }
3903 existing_channels.push_back(label);
3904 }
3905
3906 UpdateClosingRtpDataChannels(existing_channels, false);
3907}
3908
3909void PeerConnection::UpdateClosingRtpDataChannels(
3910 const std::vector<std::string>& active_channels,
3911 bool is_local_update) {
3912 auto it = rtp_data_channels_.begin();
3913 while (it != rtp_data_channels_.end()) {
3914 DataChannel* data_channel = it->second;
3915 if (std::find(active_channels.begin(), active_channels.end(),
3916 data_channel->label()) != active_channels.end()) {
3917 ++it;
3918 continue;
3919 }
3920
3921 if (is_local_update) {
3922 data_channel->SetSendSsrc(0);
3923 } else {
3924 data_channel->RemotePeerRequestClose();
3925 }
3926
3927 if (data_channel->state() == DataChannel::kClosed) {
3928 rtp_data_channels_.erase(it);
3929 it = rtp_data_channels_.begin();
3930 } else {
3931 ++it;
3932 }
3933 }
3934}
3935
3936void PeerConnection::CreateRemoteRtpDataChannel(const std::string& label,
3937 uint32_t remote_ssrc) {
3938 rtc::scoped_refptr<DataChannel> channel(
3939 InternalCreateDataChannel(label, nullptr));
3940 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003941 RTC_LOG(LS_WARNING) << "Remote peer requested a DataChannel but"
3942 << "CreateDataChannel failed.";
deadbeefab9b2d12015-10-14 11:33:11 -07003943 return;
3944 }
3945 channel->SetReceiveSsrc(remote_ssrc);
deadbeefa601f5c2016-06-06 14:27:39 -07003946 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
3947 DataChannelProxy::Create(signaling_thread(), channel);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07003948 observer_->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07003949}
3950
3951rtc::scoped_refptr<DataChannel> PeerConnection::InternalCreateDataChannel(
3952 const std::string& label,
3953 const InternalDataChannelInit* config) {
3954 if (IsClosed()) {
3955 return nullptr;
3956 }
Steve Anton75737c02017-11-06 10:37:17 -08003957 if (data_channel_type() == cricket::DCT_NONE) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003958 RTC_LOG(LS_ERROR)
deadbeefab9b2d12015-10-14 11:33:11 -07003959 << "InternalCreateDataChannel: Data is not supported in this call.";
3960 return nullptr;
3961 }
3962 InternalDataChannelInit new_config =
3963 config ? (*config) : InternalDataChannelInit();
Steve Anton75737c02017-11-06 10:37:17 -08003964 if (data_channel_type() == cricket::DCT_SCTP) {
deadbeefab9b2d12015-10-14 11:33:11 -07003965 if (new_config.id < 0) {
3966 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08003967 if ((GetSctpSslRole(&role)) &&
deadbeefab9b2d12015-10-14 11:33:11 -07003968 !sid_allocator_.AllocateSid(role, &new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003969 RTC_LOG(LS_ERROR)
3970 << "No id can be allocated for the SCTP data channel.";
deadbeefab9b2d12015-10-14 11:33:11 -07003971 return nullptr;
3972 }
3973 } else if (!sid_allocator_.ReserveSid(new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003974 RTC_LOG(LS_ERROR) << "Failed to create a SCTP data channel "
3975 << "because the id is already in use or out of range.";
deadbeefab9b2d12015-10-14 11:33:11 -07003976 return nullptr;
3977 }
3978 }
3979
Steve Anton75737c02017-11-06 10:37:17 -08003980 rtc::scoped_refptr<DataChannel> channel(
3981 DataChannel::Create(this, data_channel_type(), label, new_config));
deadbeefab9b2d12015-10-14 11:33:11 -07003982 if (!channel) {
3983 sid_allocator_.ReleaseSid(new_config.id);
3984 return nullptr;
3985 }
3986
3987 if (channel->data_channel_type() == cricket::DCT_RTP) {
3988 if (rtp_data_channels_.find(channel->label()) != rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003989 RTC_LOG(LS_ERROR) << "DataChannel with label " << channel->label()
3990 << " already exists.";
deadbeefab9b2d12015-10-14 11:33:11 -07003991 return nullptr;
3992 }
3993 rtp_data_channels_[channel->label()] = channel;
3994 } else {
3995 RTC_DCHECK(channel->data_channel_type() == cricket::DCT_SCTP);
3996 sctp_data_channels_.push_back(channel);
3997 channel->SignalClosed.connect(this,
3998 &PeerConnection::OnSctpDataChannelClosed);
3999 }
4000
Steve Anton2d8609c2018-01-23 16:38:46 -08004001 SignalDataChannelCreated_(channel.get());
deadbeefab9b2d12015-10-14 11:33:11 -07004002 return channel;
4003}
4004
4005bool PeerConnection::HasDataChannels() const {
4006 return !rtp_data_channels_.empty() || !sctp_data_channels_.empty();
4007}
4008
4009void PeerConnection::AllocateSctpSids(rtc::SSLRole role) {
4010 for (const auto& channel : sctp_data_channels_) {
4011 if (channel->id() < 0) {
4012 int sid;
4013 if (!sid_allocator_.AllocateSid(role, &sid)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004014 RTC_LOG(LS_ERROR) << "Failed to allocate SCTP sid.";
deadbeefab9b2d12015-10-14 11:33:11 -07004015 continue;
4016 }
4017 channel->SetSctpSid(sid);
4018 }
4019 }
4020}
4021
4022void PeerConnection::OnSctpDataChannelClosed(DataChannel* channel) {
deadbeefbd292462015-12-14 18:15:29 -08004023 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeefab9b2d12015-10-14 11:33:11 -07004024 for (auto it = sctp_data_channels_.begin(); it != sctp_data_channels_.end();
4025 ++it) {
4026 if (it->get() == channel) {
4027 if (channel->id() >= 0) {
4028 sid_allocator_.ReleaseSid(channel->id());
4029 }
deadbeefbd292462015-12-14 18:15:29 -08004030 // Since this method is triggered by a signal from the DataChannel,
4031 // we can't free it directly here; we need to free it asynchronously.
4032 sctp_data_channels_to_free_.push_back(*it);
deadbeefab9b2d12015-10-14 11:33:11 -07004033 sctp_data_channels_.erase(it);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07004034 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_FREE_DATACHANNELS,
4035 nullptr);
deadbeefab9b2d12015-10-14 11:33:11 -07004036 return;
4037 }
4038 }
4039}
4040
deadbeefab9b2d12015-10-14 11:33:11 -07004041void PeerConnection::OnDataChannelDestroyed() {
4042 // Use a temporary copy of the RTP/SCTP DataChannel list because the
4043 // DataChannel may callback to us and try to modify the list.
4044 std::map<std::string, rtc::scoped_refptr<DataChannel>> temp_rtp_dcs;
4045 temp_rtp_dcs.swap(rtp_data_channels_);
4046 for (const auto& kv : temp_rtp_dcs) {
4047 kv.second->OnTransportChannelDestroyed();
4048 }
4049
4050 std::vector<rtc::scoped_refptr<DataChannel>> temp_sctp_dcs;
4051 temp_sctp_dcs.swap(sctp_data_channels_);
4052 for (const auto& channel : temp_sctp_dcs) {
4053 channel->OnTransportChannelDestroyed();
4054 }
4055}
4056
4057void PeerConnection::OnDataChannelOpenMessage(
4058 const std::string& label,
4059 const InternalDataChannelInit& config) {
4060 rtc::scoped_refptr<DataChannel> channel(
4061 InternalCreateDataChannel(label, &config));
4062 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004063 RTC_LOG(LS_ERROR) << "Failed to create DataChannel from the OPEN message.";
deadbeefab9b2d12015-10-14 11:33:11 -07004064 return;
4065 }
4066
deadbeefa601f5c2016-06-06 14:27:39 -07004067 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
4068 DataChannelProxy::Create(signaling_thread(), channel);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07004069 observer_->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07004070}
4071
Steve Anton4171afb2017-11-20 10:20:22 -08004072rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
4073PeerConnection::GetAudioTransceiver() const {
4074 // This method only works with Plan B SDP, where there is a single
4075 // audio/video transceiver.
4076 RTC_DCHECK(!IsUnifiedPlan());
4077 for (auto transceiver : transceivers_) {
4078 if (transceiver->internal()->media_type() == cricket::MEDIA_TYPE_AUDIO) {
4079 return transceiver;
4080 }
4081 }
4082 RTC_NOTREACHED();
4083 return nullptr;
4084}
4085
4086rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
4087PeerConnection::GetVideoTransceiver() const {
4088 // This method only works with Plan B SDP, where there is a single
4089 // audio/video transceiver.
4090 RTC_DCHECK(!IsUnifiedPlan());
4091 for (auto transceiver : transceivers_) {
4092 if (transceiver->internal()->media_type() == cricket::MEDIA_TYPE_VIDEO) {
4093 return transceiver;
4094 }
4095 }
4096 RTC_NOTREACHED();
4097 return nullptr;
4098}
4099
4100// TODO(bugs.webrtc.org/7600): Remove this when multiple transceivers with
4101// individual transceiver directions are supported.
zhihuang1c378ed2017-08-17 14:10:50 -07004102bool PeerConnection::HasRtpSender(cricket::MediaType type) const {
Steve Anton4171afb2017-11-20 10:20:22 -08004103 switch (type) {
4104 case cricket::MEDIA_TYPE_AUDIO:
4105 return !GetAudioTransceiver()->internal()->senders().empty();
4106 case cricket::MEDIA_TYPE_VIDEO:
4107 return !GetVideoTransceiver()->internal()->senders().empty();
4108 case cricket::MEDIA_TYPE_DATA:
4109 return false;
4110 }
4111 RTC_NOTREACHED();
4112 return false;
zhihuang1c378ed2017-08-17 14:10:50 -07004113}
4114
Steve Anton4171afb2017-11-20 10:20:22 -08004115rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
4116PeerConnection::FindSenderForTrack(MediaStreamTrackInterface* track) const {
4117 for (auto transceiver : transceivers_) {
4118 for (auto sender : transceiver->internal()->senders()) {
4119 if (sender->track() == track) {
4120 return sender;
4121 }
4122 }
4123 }
4124 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08004125}
4126
Steve Anton4171afb2017-11-20 10:20:22 -08004127rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
4128PeerConnection::FindSenderById(const std::string& sender_id) const {
4129 for (auto transceiver : transceivers_) {
4130 for (auto sender : transceiver->internal()->senders()) {
4131 if (sender->id() == sender_id) {
4132 return sender;
4133 }
4134 }
4135 }
4136 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07004137}
4138
Steve Anton4171afb2017-11-20 10:20:22 -08004139rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
4140PeerConnection::FindReceiverById(const std::string& receiver_id) const {
4141 for (auto transceiver : transceivers_) {
4142 for (auto receiver : transceiver->internal()->receivers()) {
4143 if (receiver->id() == receiver_id) {
4144 return receiver;
4145 }
4146 }
4147 }
4148 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07004149}
4150
Steve Anton4171afb2017-11-20 10:20:22 -08004151std::vector<PeerConnection::RtpSenderInfo>*
4152PeerConnection::GetRemoteSenderInfos(cricket::MediaType media_type) {
4153 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
4154 media_type == cricket::MEDIA_TYPE_VIDEO);
4155 return (media_type == cricket::MEDIA_TYPE_AUDIO)
4156 ? &remote_audio_sender_infos_
4157 : &remote_video_sender_infos_;
4158}
4159
4160std::vector<PeerConnection::RtpSenderInfo>* PeerConnection::GetLocalSenderInfos(
deadbeefab9b2d12015-10-14 11:33:11 -07004161 cricket::MediaType media_type) {
4162 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
4163 media_type == cricket::MEDIA_TYPE_VIDEO);
Steve Anton4171afb2017-11-20 10:20:22 -08004164 return (media_type == cricket::MEDIA_TYPE_AUDIO) ? &local_audio_sender_infos_
4165 : &local_video_sender_infos_;
deadbeefab9b2d12015-10-14 11:33:11 -07004166}
4167
Steve Anton4171afb2017-11-20 10:20:22 -08004168const PeerConnection::RtpSenderInfo* PeerConnection::FindSenderInfo(
4169 const std::vector<PeerConnection::RtpSenderInfo>& infos,
deadbeefab9b2d12015-10-14 11:33:11 -07004170 const std::string& stream_label,
Steve Anton4171afb2017-11-20 10:20:22 -08004171 const std::string sender_id) const {
4172 for (const RtpSenderInfo& sender_info : infos) {
4173 if (sender_info.stream_label == stream_label &&
4174 sender_info.sender_id == sender_id) {
4175 return &sender_info;
deadbeefab9b2d12015-10-14 11:33:11 -07004176 }
4177 }
4178 return nullptr;
4179}
4180
4181DataChannel* PeerConnection::FindDataChannelBySid(int sid) const {
4182 for (const auto& channel : sctp_data_channels_) {
4183 if (channel->id() == sid) {
4184 return channel;
4185 }
4186 }
4187 return nullptr;
4188}
4189
deadbeef91dd5672016-05-18 16:55:30 -07004190bool PeerConnection::InitializePortAllocator_n(
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004191 const RTCConfiguration& configuration) {
4192 cricket::ServerAddresses stun_servers;
4193 std::vector<cricket::RelayServerConfig> turn_servers;
deadbeef293e9262017-01-11 12:28:30 -08004194 if (ParseIceServers(configuration.servers, &stun_servers, &turn_servers) !=
4195 RTCErrorType::NONE) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004196 return false;
4197 }
4198
Taylor Brandstetterf8e65772016-06-27 17:20:15 -07004199 port_allocator_->Initialize();
4200
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004201 // To handle both internal and externally created port allocator, we will
4202 // enable BUNDLE here.
4203 int portallocator_flags = port_allocator_->flags();
4204 portallocator_flags |= cricket::PORTALLOCATOR_ENABLE_SHARED_SOCKET |
zhihuangb09b3f92017-03-07 14:40:51 -08004205 cricket::PORTALLOCATOR_ENABLE_IPV6 |
4206 cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI;
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004207 // If the disable-IPv6 flag was specified, we'll not override it
4208 // by experiment.
4209 if (configuration.disable_ipv6) {
4210 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
sprangc1b57a12017-02-28 08:50:47 -08004211 } else if (webrtc::field_trial::FindFullName("WebRTC-IPv6Default")
4212 .find("Disabled") == 0) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004213 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
4214 }
4215
zhihuangb09b3f92017-03-07 14:40:51 -08004216 if (configuration.disable_ipv6_on_wifi) {
4217 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI);
Mirko Bonadei675513b2017-11-09 11:09:25 +01004218 RTC_LOG(LS_INFO) << "IPv6 candidates on Wi-Fi are disabled.";
zhihuangb09b3f92017-03-07 14:40:51 -08004219 }
4220
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004221 if (configuration.tcp_candidate_policy == kTcpCandidatePolicyDisabled) {
4222 portallocator_flags |= cricket::PORTALLOCATOR_DISABLE_TCP;
Mirko Bonadei675513b2017-11-09 11:09:25 +01004223 RTC_LOG(LS_INFO) << "TCP candidates are disabled.";
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004224 }
4225
honghaiz60347052016-05-31 18:29:12 -07004226 if (configuration.candidate_network_policy ==
4227 kCandidateNetworkPolicyLowCost) {
4228 portallocator_flags |= cricket::PORTALLOCATOR_DISABLE_COSTLY_NETWORKS;
Mirko Bonadei675513b2017-11-09 11:09:25 +01004229 RTC_LOG(LS_INFO) << "Do not gather candidates on high-cost networks";
honghaiz60347052016-05-31 18:29:12 -07004230 }
4231
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004232 port_allocator_->set_flags(portallocator_flags);
4233 // No step delay is used while allocating ports.
4234 port_allocator_->set_step_delay(cricket::kMinimumStepDelay);
4235 port_allocator_->set_candidate_filter(
4236 ConvertIceTransportTypeToCandidateFilter(configuration.type));
deadbeefd21eab32017-07-26 16:50:11 -07004237 port_allocator_->set_max_ipv6_networks(configuration.max_ipv6_networks);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004238
4239 // Call this last since it may create pooled allocator sessions using the
4240 // properties set above.
4241 port_allocator_->SetConfiguration(stun_servers, turn_servers,
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -07004242 configuration.ice_candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02004243 configuration.prune_turn_ports,
4244 configuration.turn_customizer);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004245 return true;
4246}
4247
deadbeef91dd5672016-05-18 16:55:30 -07004248bool PeerConnection::ReconfigurePortAllocator_n(
deadbeef293e9262017-01-11 12:28:30 -08004249 const cricket::ServerAddresses& stun_servers,
4250 const std::vector<cricket::RelayServerConfig>& turn_servers,
4251 IceTransportsType type,
4252 int candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02004253 bool prune_turn_ports,
4254 webrtc::TurnCustomizer* turn_customizer) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004255 port_allocator_->set_candidate_filter(
deadbeef293e9262017-01-11 12:28:30 -08004256 ConvertIceTransportTypeToCandidateFilter(type));
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004257 // Call this last since it may create pooled allocator sessions using the
4258 // candidate filter set above.
deadbeef6de92f92016-12-12 18:49:32 -08004259 return port_allocator_->SetConfiguration(
Jonas Orelandbdcee282017-10-10 14:01:40 +02004260 stun_servers, turn_servers, candidate_pool_size, prune_turn_ports,
4261 turn_customizer);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004262}
4263
Steve Antonba818672017-11-06 10:21:57 -08004264cricket::ChannelManager* PeerConnection::channel_manager() const {
4265 return factory_->channel_manager();
4266}
4267
4268MetricsObserverInterface* PeerConnection::metrics_observer() const {
4269 return uma_observer_;
4270}
4271
Elad Alon99c3fe52017-10-13 16:29:40 +02004272bool PeerConnection::StartRtcEventLog_w(
Bjorn Tereliusde939432017-11-20 17:38:14 +01004273 std::unique_ptr<RtcEventLogOutput> output,
4274 int64_t output_period_ms) {
zhihuang77985012017-02-07 15:45:16 -08004275 if (!event_log_) {
4276 return false;
4277 }
Bjorn Tereliusde939432017-11-20 17:38:14 +01004278 return event_log_->StartLogging(std::move(output), output_period_ms);
ivoc14d5dbe2016-07-04 07:06:55 -07004279}
4280
4281void PeerConnection::StopRtcEventLog_w() {
zhihuang77985012017-02-07 15:45:16 -08004282 if (event_log_) {
4283 event_log_->StopLogging();
4284 }
ivoc14d5dbe2016-07-04 07:06:55 -07004285}
nisseeaabdf62017-05-05 02:23:02 -07004286
Steve Anton75737c02017-11-06 10:37:17 -08004287cricket::BaseChannel* PeerConnection::GetChannel(
4288 const std::string& content_name) {
Steve Antondcc3c022017-12-22 16:02:54 -08004289 for (auto transceiver : transceivers_) {
4290 cricket::BaseChannel* channel = transceiver->internal()->channel();
4291 if (channel && channel->content_name() == content_name) {
4292 return channel;
4293 }
Steve Anton75737c02017-11-06 10:37:17 -08004294 }
4295 if (rtp_data_channel() &&
4296 rtp_data_channel()->content_name() == content_name) {
4297 return rtp_data_channel();
4298 }
4299 return nullptr;
4300}
4301
4302bool PeerConnection::GetSctpSslRole(rtc::SSLRole* role) {
4303 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004304 RTC_LOG(LS_INFO)
4305 << "Local and Remote descriptions must be applied to get the "
4306 << "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08004307 return false;
4308 }
4309 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004310 RTC_LOG(LS_INFO) << "Non-rejected SCTP m= section is needed to get the "
4311 << "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08004312 return false;
4313 }
4314
4315 return transport_controller_->GetSslRole(*sctp_transport_name_, role);
4316}
4317
4318bool PeerConnection::GetSslRole(const std::string& content_name,
4319 rtc::SSLRole* role) {
4320 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004321 RTC_LOG(LS_INFO)
4322 << "Local and Remote descriptions must be applied to get the "
4323 << "SSL Role of the session.";
Steve Anton75737c02017-11-06 10:37:17 -08004324 return false;
4325 }
4326
4327 return transport_controller_->GetSslRole(GetTransportName(content_name),
4328 role);
4329}
4330
Steve Anton75737c02017-11-06 10:37:17 -08004331// TODO(steveanton): Eventually it'd be nice to store the channels as a single
4332// vector of BaseChannel pointers instead of separate voice and video channel
4333// vectors. At that point, this will become a simple getter.
4334std::vector<cricket::BaseChannel*> PeerConnection::Channels() const {
4335 std::vector<cricket::BaseChannel*> channels;
Steve Anton4171afb2017-11-20 10:20:22 -08004336 if (voice_channel()) {
4337 channels.push_back(voice_channel());
4338 }
4339 if (video_channel()) {
4340 channels.push_back(video_channel());
4341 }
Steve Anton75737c02017-11-06 10:37:17 -08004342 if (rtp_data_channel_) {
4343 channels.push_back(rtp_data_channel_);
4344 }
4345 return channels;
4346}
4347
Steve Antonf8470812017-12-04 10:46:21 -08004348void PeerConnection::SetSessionError(SessionError error,
4349 const std::string& error_desc) {
4350 RTC_DCHECK_RUN_ON(signaling_thread());
4351 if (error != session_error_) {
4352 session_error_ = error;
4353 session_error_desc_ = error_desc;
Steve Anton75737c02017-11-06 10:37:17 -08004354 }
4355}
4356
Steve Anton3828c062017-12-06 10:34:51 -08004357RTCError PeerConnection::UpdateSessionState(SdpType type,
Steve Anton8a006912017-12-04 15:25:56 -08004358 cricket::ContentSource source) {
4359 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08004360
4361 // If there's already a pending error then no state transition should happen.
4362 // But all call-sites should be verifying this before calling us!
Steve Antonf8470812017-12-04 10:46:21 -08004363 RTC_DCHECK(session_error() == SessionError::kNone);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004364
4365 // If this is an answer then we know whether to BUNDLE or not. If both the
4366 // local and remote side have agreed to BUNDLE, go ahead and enable it.
Steve Anton3828c062017-12-06 10:34:51 -08004367 if (type == SdpType::kAnswer) {
Steve Anton75737c02017-11-06 10:37:17 -08004368 const cricket::ContentGroup* local_bundle =
4369 local_description()->description()->GetGroupByName(
4370 cricket::GROUP_TYPE_BUNDLE);
4371 const cricket::ContentGroup* remote_bundle =
4372 remote_description()->description()->GetGroupByName(
4373 cricket::GROUP_TYPE_BUNDLE);
4374 if (local_bundle && remote_bundle) {
4375 // The answerer decides the transport to bundle on.
4376 const cricket::ContentGroup* answer_bundle =
4377 (source == cricket::CS_LOCAL ? local_bundle : remote_bundle);
4378 if (!EnableBundle(*answer_bundle)) {
Steve Anton8a006912017-12-04 15:25:56 -08004379 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
4380 kEnableBundleFailed);
Steve Anton75737c02017-11-06 10:37:17 -08004381 }
4382 }
Steve Anton75737c02017-11-06 10:37:17 -08004383 }
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004384
4385 // Only push down the transport description after potentially enabling BUNDLE;
4386 // we don't want to push down a description on a transport about to be
4387 // destroyed.
Steve Anton3828c062017-12-06 10:34:51 -08004388 RTCError error = PushdownTransportDescription(source, type);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004389 if (!error.ok()) {
4390 return error;
4391 }
4392
4393 // If this is answer-ish we're ready to let media flow.
Steve Anton3828c062017-12-06 10:34:51 -08004394 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Antoned10bd92017-12-05 10:52:59 -08004395 EnableSending();
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004396 }
4397
4398 // Update the signaling state according to the specified state machine (see
4399 // https://w3c.github.io/webrtc-pc/#rtcsignalingstate-enum).
Steve Anton3828c062017-12-06 10:34:51 -08004400 if (type == SdpType::kOffer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004401 ChangeSignalingState(source == cricket::CS_LOCAL
4402 ? PeerConnectionInterface::kHaveLocalOffer
4403 : PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton3828c062017-12-06 10:34:51 -08004404 } else if (type == SdpType::kPrAnswer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004405 ChangeSignalingState(source == cricket::CS_LOCAL
4406 ? PeerConnectionInterface::kHaveLocalPrAnswer
4407 : PeerConnectionInterface::kHaveRemotePrAnswer);
4408 } else {
Steve Anton3828c062017-12-06 10:34:51 -08004409 RTC_DCHECK(type == SdpType::kAnswer);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004410 ChangeSignalingState(PeerConnectionInterface::kStable);
4411 }
4412
4413 // Update internal objects according to the session description's media
4414 // descriptions.
Steve Anton3828c062017-12-06 10:34:51 -08004415 error = PushdownMediaDescription(type, source);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004416 if (!error.ok()) {
4417 SetSessionError(SessionError::kContent, error.message());
4418 }
4419 if (session_error() != SessionError::kNone) {
4420 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
4421 }
4422
Steve Anton8a006912017-12-04 15:25:56 -08004423 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08004424}
4425
Steve Anton8a006912017-12-04 15:25:56 -08004426RTCError PeerConnection::PushdownMediaDescription(
Steve Anton3828c062017-12-06 10:34:51 -08004427 SdpType type,
Steve Anton8a006912017-12-04 15:25:56 -08004428 cricket::ContentSource source) {
Steve Antoned10bd92017-12-05 10:52:59 -08004429 const SessionDescriptionInterface* sdesc =
4430 (source == cricket::CS_LOCAL ? local_description()
4431 : remote_description());
Steve Anton75737c02017-11-06 10:37:17 -08004432 RTC_DCHECK(sdesc);
Steve Antoned10bd92017-12-05 10:52:59 -08004433
4434 // Push down the new SDP media section for each audio/video transceiver.
4435 for (auto transceiver : transceivers_) {
Steve Anton75737c02017-11-06 10:37:17 -08004436 const ContentInfo* content_info =
Steve Antoned10bd92017-12-05 10:52:59 -08004437 FindMediaSectionForTransceiver(transceiver, sdesc);
4438 cricket::BaseChannel* channel = transceiver->internal()->channel();
4439 if (!channel || !content_info || content_info->rejected) {
Steve Anton75737c02017-11-06 10:37:17 -08004440 continue;
4441 }
4442 const MediaContentDescription* content_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08004443 content_info->media_description();
Steve Antoned10bd92017-12-05 10:52:59 -08004444 if (!content_desc) {
4445 continue;
4446 }
4447 std::string error;
4448 bool success =
4449 (source == cricket::CS_LOCAL)
Steve Anton3828c062017-12-06 10:34:51 -08004450 ? channel->SetLocalContent(content_desc, type, &error)
4451 : channel->SetRemoteContent(content_desc, type, &error);
Steve Antoned10bd92017-12-05 10:52:59 -08004452 if (!success) {
4453 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, std::move(error));
4454 }
4455 }
4456
4457 // If using the RtpDataChannel, push down the new SDP section for it too.
4458 if (rtp_data_channel_) {
4459 const ContentInfo* data_content =
4460 cricket::GetFirstDataContent(sdesc->description());
4461 if (data_content && !data_content->rejected) {
4462 const MediaContentDescription* data_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08004463 data_content->media_description();
Steve Antoned10bd92017-12-05 10:52:59 -08004464 if (data_desc) {
4465 std::string error;
4466 bool success =
4467 (source == cricket::CS_LOCAL)
Steve Anton3828c062017-12-06 10:34:51 -08004468 ? rtp_data_channel_->SetLocalContent(data_desc, type, &error)
4469 : rtp_data_channel_->SetRemoteContent(data_desc, type,
Steve Antoned10bd92017-12-05 10:52:59 -08004470 &error);
4471 if (!success) {
4472 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
4473 std::move(error));
4474 }
Steve Anton75737c02017-11-06 10:37:17 -08004475 }
4476 }
4477 }
Steve Antoned10bd92017-12-05 10:52:59 -08004478
Steve Anton75737c02017-11-06 10:37:17 -08004479 // Need complete offer/answer with an SCTP m= section before starting SCTP,
4480 // according to https://tools.ietf.org/html/draft-ietf-mmusic-sctp-sdp-19
4481 if (sctp_transport_ && local_description() && remote_description() &&
4482 cricket::GetFirstDataContent(local_description()->description()) &&
4483 cricket::GetFirstDataContent(remote_description()->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08004484 bool success = network_thread()->Invoke<bool>(
Steve Anton75737c02017-11-06 10:37:17 -08004485 RTC_FROM_HERE,
4486 rtc::Bind(&PeerConnection::PushdownSctpParameters_n, this, source));
Steve Anton8a006912017-12-04 15:25:56 -08004487 if (!success) {
4488 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
4489 "Failed to push down SCTP parameters.");
4490 }
Steve Anton75737c02017-11-06 10:37:17 -08004491 }
Steve Antoned10bd92017-12-05 10:52:59 -08004492
Steve Anton8a006912017-12-04 15:25:56 -08004493 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08004494}
4495
4496bool PeerConnection::PushdownSctpParameters_n(cricket::ContentSource source) {
4497 RTC_DCHECK(network_thread()->IsCurrent());
4498 RTC_DCHECK(local_description());
4499 RTC_DCHECK(remote_description());
4500 // Apply the SCTP port (which is hidden inside a DataCodec structure...)
4501 // When we support "max-message-size", that would also be pushed down here.
4502 return sctp_transport_->Start(
4503 GetSctpPort(local_description()->description()),
4504 GetSctpPort(remote_description()->description()));
4505}
4506
Steve Anton8a006912017-12-04 15:25:56 -08004507RTCError PeerConnection::PushdownTransportDescription(
4508 cricket::ContentSource source,
Steve Anton3828c062017-12-06 10:34:51 -08004509 SdpType type) {
Steve Anton8a006912017-12-04 15:25:56 -08004510 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08004511
Steve Anton8a006912017-12-04 15:25:56 -08004512 const SessionDescriptionInterface* sdesc =
4513 (source == cricket::CS_LOCAL ? local_description()
4514 : remote_description());
4515 RTC_DCHECK(sdesc);
4516 for (const cricket::TransportInfo& tinfo :
4517 sdesc->description()->transport_infos()) {
4518 std::string error;
4519 bool success;
4520 if (source == cricket::CS_LOCAL) {
4521 success = transport_controller_->SetLocalTransportDescription(
Steve Anton3828c062017-12-06 10:34:51 -08004522 tinfo.content_name, tinfo.description, type, &error);
Steve Anton8a006912017-12-04 15:25:56 -08004523 } else {
4524 success = transport_controller_->SetRemoteTransportDescription(
Steve Anton3828c062017-12-06 10:34:51 -08004525 tinfo.content_name, tinfo.description, type, &error);
Steve Anton8a006912017-12-04 15:25:56 -08004526 }
4527 if (!success) {
Steve Antondcc3c022017-12-22 16:02:54 -08004528 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
4529 "Failed to push down transport description for " +
4530 tinfo.content_name + ": " + error);
Steve Anton75737c02017-11-06 10:37:17 -08004531 }
4532 }
4533
Steve Anton8a006912017-12-04 15:25:56 -08004534 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08004535}
4536
4537bool PeerConnection::GetTransportDescription(
4538 const SessionDescription* description,
4539 const std::string& content_name,
4540 cricket::TransportDescription* tdesc) {
4541 if (!description || !tdesc) {
4542 return false;
4543 }
4544 const TransportInfo* transport_info =
4545 description->GetTransportInfoByName(content_name);
4546 if (!transport_info) {
4547 return false;
4548 }
4549 *tdesc = transport_info->description;
4550 return true;
4551}
4552
4553bool PeerConnection::EnableBundle(const cricket::ContentGroup& bundle) {
4554 const std::string* first_content_name = bundle.FirstContentName();
4555 if (!first_content_name) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004556 RTC_LOG(LS_WARNING) << "Tried to BUNDLE with no contents.";
Steve Anton75737c02017-11-06 10:37:17 -08004557 return false;
4558 }
4559 const std::string& transport_name = *first_content_name;
4560
4561 auto maybe_set_transport = [this, bundle,
4562 transport_name](cricket::BaseChannel* ch) {
4563 if (!ch || !bundle.HasContentName(ch->content_name())) {
Steve Antoned10bd92017-12-05 10:52:59 -08004564 return;
Steve Anton75737c02017-11-06 10:37:17 -08004565 }
4566
4567 std::string old_transport_name = ch->transport_name();
4568 if (old_transport_name == transport_name) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004569 RTC_LOG(LS_INFO) << "BUNDLE already enabled for " << ch->content_name()
4570 << " on " << transport_name << ".";
Steve Antoned10bd92017-12-05 10:52:59 -08004571 return;
Steve Anton75737c02017-11-06 10:37:17 -08004572 }
4573
4574 cricket::DtlsTransportInternal* rtp_dtls_transport =
4575 transport_controller_->CreateDtlsTransport(
4576 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4577 bool need_rtcp = (ch->rtcp_dtls_transport() != nullptr);
4578 cricket::DtlsTransportInternal* rtcp_dtls_transport = nullptr;
4579 if (need_rtcp) {
4580 rtcp_dtls_transport = transport_controller_->CreateDtlsTransport(
4581 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
4582 }
4583
4584 ch->SetTransports(rtp_dtls_transport, rtcp_dtls_transport);
Mirko Bonadei675513b2017-11-09 11:09:25 +01004585 RTC_LOG(LS_INFO) << "Enabled BUNDLE for " << ch->content_name() << " on "
4586 << transport_name << ".";
Steve Anton75737c02017-11-06 10:37:17 -08004587 transport_controller_->DestroyDtlsTransport(
4588 old_transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4589 // If the channel needs rtcp, it means that the channel used to have a
4590 // rtcp transport which needs to be deleted now.
4591 if (need_rtcp) {
4592 transport_controller_->DestroyDtlsTransport(
4593 old_transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
4594 }
Steve Anton75737c02017-11-06 10:37:17 -08004595 };
4596
Steve Antoned10bd92017-12-05 10:52:59 -08004597 for (auto transceiver : transceivers_) {
4598 maybe_set_transport(transceiver->internal()->channel());
Steve Anton75737c02017-11-06 10:37:17 -08004599 }
Steve Antoned10bd92017-12-05 10:52:59 -08004600 maybe_set_transport(rtp_data_channel_);
4601
Steve Anton75737c02017-11-06 10:37:17 -08004602 // For SCTP, transport creation/deletion happens here instead of in the
4603 // object itself.
4604 if (sctp_transport_) {
4605 RTC_DCHECK(sctp_transport_name_);
4606 RTC_DCHECK(sctp_content_name_);
4607 if (transport_name != *sctp_transport_name_ &&
4608 bundle.HasContentName(*sctp_content_name_)) {
4609 network_thread()->Invoke<void>(
4610 RTC_FROM_HERE, rtc::Bind(&PeerConnection::ChangeSctpTransport_n, this,
4611 transport_name));
4612 }
4613 }
4614
4615 return true;
4616}
4617
Steve Anton75737c02017-11-06 10:37:17 -08004618cricket::IceConfig PeerConnection::ParseIceConfig(
4619 const PeerConnectionInterface::RTCConfiguration& config) const {
4620 cricket::ContinualGatheringPolicy gathering_policy;
4621 // TODO(honghaiz): Add the third continual gathering policy in
4622 // PeerConnectionInterface and map it to GATHER_CONTINUALLY_AND_RECOVER.
4623 switch (config.continual_gathering_policy) {
4624 case PeerConnectionInterface::GATHER_ONCE:
4625 gathering_policy = cricket::GATHER_ONCE;
4626 break;
4627 case PeerConnectionInterface::GATHER_CONTINUALLY:
4628 gathering_policy = cricket::GATHER_CONTINUALLY;
4629 break;
4630 default:
4631 RTC_NOTREACHED();
4632 gathering_policy = cricket::GATHER_ONCE;
4633 }
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08004634
Steve Anton75737c02017-11-06 10:37:17 -08004635 cricket::IceConfig ice_config;
4636 ice_config.receiving_timeout = config.ice_connection_receiving_timeout;
4637 ice_config.prioritize_most_likely_candidate_pairs =
4638 config.prioritize_most_likely_ice_candidate_pairs;
4639 ice_config.backup_connection_ping_interval =
4640 config.ice_backup_candidate_pair_ping_interval;
4641 ice_config.continual_gathering_policy = gathering_policy;
4642 ice_config.presume_writable_when_fully_relayed =
4643 config.presume_writable_when_fully_relayed;
4644 ice_config.ice_check_min_interval = config.ice_check_min_interval;
4645 ice_config.regather_all_networks_interval_range =
4646 config.ice_regather_interval_range;
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08004647 ice_config.network_preference = config.network_preference;
Steve Anton75737c02017-11-06 10:37:17 -08004648 return ice_config;
4649}
4650
Steve Anton75737c02017-11-06 10:37:17 -08004651bool PeerConnection::GetLocalTrackIdBySsrc(uint32_t ssrc,
4652 std::string* track_id) {
4653 if (!local_description()) {
4654 return false;
4655 }
4656 return webrtc::GetTrackIdBySsrc(local_description()->description(), ssrc,
4657 track_id);
4658}
4659
4660bool PeerConnection::GetRemoteTrackIdBySsrc(uint32_t ssrc,
4661 std::string* track_id) {
4662 if (!remote_description()) {
4663 return false;
4664 }
4665 return webrtc::GetTrackIdBySsrc(remote_description()->description(), ssrc,
4666 track_id);
4667}
4668
4669bool PeerConnection::SendData(const cricket::SendDataParams& params,
4670 const rtc::CopyOnWriteBuffer& payload,
4671 cricket::SendDataResult* result) {
4672 if (!rtp_data_channel_ && !sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004673 RTC_LOG(LS_ERROR) << "SendData called when rtp_data_channel_ "
4674 << "and sctp_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08004675 return false;
4676 }
4677 return rtp_data_channel_
4678 ? rtp_data_channel_->SendData(params, payload, result)
4679 : network_thread()->Invoke<bool>(
4680 RTC_FROM_HERE,
4681 Bind(&cricket::SctpTransportInternal::SendData,
4682 sctp_transport_.get(), params, payload, result));
4683}
4684
4685bool PeerConnection::ConnectDataChannel(DataChannel* webrtc_data_channel) {
4686 if (!rtp_data_channel_ && !sctp_transport_) {
4687 // Don't log an error here, because DataChannels are expected to call
4688 // ConnectDataChannel in this state. It's the only way to initially tell
4689 // whether or not the underlying transport is ready.
4690 return false;
4691 }
4692 if (rtp_data_channel_) {
4693 rtp_data_channel_->SignalReadyToSendData.connect(
4694 webrtc_data_channel, &DataChannel::OnChannelReady);
4695 rtp_data_channel_->SignalDataReceived.connect(webrtc_data_channel,
4696 &DataChannel::OnDataReceived);
4697 } else {
4698 SignalSctpReadyToSendData.connect(webrtc_data_channel,
4699 &DataChannel::OnChannelReady);
4700 SignalSctpDataReceived.connect(webrtc_data_channel,
4701 &DataChannel::OnDataReceived);
4702 SignalSctpStreamClosedRemotely.connect(
4703 webrtc_data_channel, &DataChannel::OnStreamClosedRemotely);
4704 }
4705 return true;
4706}
4707
4708void PeerConnection::DisconnectDataChannel(DataChannel* webrtc_data_channel) {
4709 if (!rtp_data_channel_ && !sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004710 RTC_LOG(LS_ERROR)
4711 << "DisconnectDataChannel called when rtp_data_channel_ and "
4712 "sctp_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08004713 return;
4714 }
4715 if (rtp_data_channel_) {
4716 rtp_data_channel_->SignalReadyToSendData.disconnect(webrtc_data_channel);
4717 rtp_data_channel_->SignalDataReceived.disconnect(webrtc_data_channel);
4718 } else {
4719 SignalSctpReadyToSendData.disconnect(webrtc_data_channel);
4720 SignalSctpDataReceived.disconnect(webrtc_data_channel);
4721 SignalSctpStreamClosedRemotely.disconnect(webrtc_data_channel);
4722 }
4723}
4724
4725void PeerConnection::AddSctpDataStream(int sid) {
4726 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004727 RTC_LOG(LS_ERROR)
4728 << "AddSctpDataStream called when sctp_transport_ is NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08004729 return;
4730 }
4731 network_thread()->Invoke<void>(
4732 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::OpenStream,
4733 sctp_transport_.get(), sid));
4734}
4735
4736void PeerConnection::RemoveSctpDataStream(int sid) {
4737 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004738 RTC_LOG(LS_ERROR) << "RemoveSctpDataStream called when sctp_transport_ is "
4739 << "NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08004740 return;
4741 }
4742 network_thread()->Invoke<void>(
4743 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::ResetStream,
4744 sctp_transport_.get(), sid));
4745}
4746
4747bool PeerConnection::ReadyToSendData() const {
4748 return (rtp_data_channel_ && rtp_data_channel_->ready_to_send_data()) ||
4749 sctp_ready_to_send_data_;
4750}
4751
4752std::unique_ptr<SessionStats> PeerConnection::GetSessionStats_s() {
4753 RTC_DCHECK(signaling_thread()->IsCurrent());
4754 ChannelNamePairs channel_name_pairs;
4755 if (voice_channel()) {
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004756 channel_name_pairs.voice = ChannelNamePair(
4757 voice_channel()->content_name(), voice_channel()->transport_name());
Steve Anton75737c02017-11-06 10:37:17 -08004758 }
4759 if (video_channel()) {
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004760 channel_name_pairs.video = ChannelNamePair(
4761 video_channel()->content_name(), video_channel()->transport_name());
Steve Anton75737c02017-11-06 10:37:17 -08004762 }
4763 if (rtp_data_channel()) {
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004764 channel_name_pairs.data =
Steve Anton75737c02017-11-06 10:37:17 -08004765 ChannelNamePair(rtp_data_channel()->content_name(),
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004766 rtp_data_channel()->transport_name());
Steve Anton75737c02017-11-06 10:37:17 -08004767 }
4768 if (sctp_transport_) {
4769 RTC_DCHECK(sctp_content_name_);
4770 RTC_DCHECK(sctp_transport_name_);
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004771 channel_name_pairs.data =
4772 ChannelNamePair(*sctp_content_name_, *sctp_transport_name_);
Steve Anton75737c02017-11-06 10:37:17 -08004773 }
4774 return GetSessionStats(channel_name_pairs);
4775}
4776
4777std::unique_ptr<SessionStats> PeerConnection::GetSessionStats(
4778 const ChannelNamePairs& channel_name_pairs) {
4779 if (network_thread()->IsCurrent()) {
4780 return GetSessionStats_n(channel_name_pairs);
4781 }
4782 return network_thread()->Invoke<std::unique_ptr<SessionStats>>(
4783 RTC_FROM_HERE,
4784 rtc::Bind(&PeerConnection::GetSessionStats_n, this, channel_name_pairs));
4785}
4786
4787bool PeerConnection::GetLocalCertificate(
4788 const std::string& transport_name,
4789 rtc::scoped_refptr<rtc::RTCCertificate>* certificate) {
4790 return transport_controller_->GetLocalCertificate(transport_name,
4791 certificate);
4792}
4793
4794std::unique_ptr<rtc::SSLCertificate> PeerConnection::GetRemoteSSLCertificate(
4795 const std::string& transport_name) {
4796 return transport_controller_->GetRemoteSSLCertificate(transport_name);
4797}
4798
4799cricket::DataChannelType PeerConnection::data_channel_type() const {
4800 return data_channel_type_;
4801}
4802
4803bool PeerConnection::IceRestartPending(const std::string& content_name) const {
4804 return pending_ice_restarts_.find(content_name) !=
4805 pending_ice_restarts_.end();
4806}
4807
Steve Anton75737c02017-11-06 10:37:17 -08004808bool PeerConnection::NeedsIceRestart(const std::string& content_name) const {
4809 return transport_controller_->NeedsIceRestart(content_name);
4810}
4811
4812void PeerConnection::OnCertificateReady(
4813 const rtc::scoped_refptr<rtc::RTCCertificate>& certificate) {
4814 transport_controller_->SetLocalCertificate(certificate);
4815}
4816
4817void PeerConnection::OnDtlsSrtpSetupFailure(cricket::BaseChannel*, bool rtcp) {
Steve Antonf8470812017-12-04 10:46:21 -08004818 SetSessionError(SessionError::kTransport,
4819 rtcp ? kDtlsSrtpSetupFailureRtcp : kDtlsSrtpSetupFailureRtp);
Steve Anton75737c02017-11-06 10:37:17 -08004820}
4821
4822void PeerConnection::OnTransportControllerConnectionState(
4823 cricket::IceConnectionState state) {
4824 switch (state) {
4825 case cricket::kIceConnectionConnecting:
4826 // If the current state is Connected or Completed, then there were
4827 // writable channels but now there are not, so the next state must
4828 // be Disconnected.
4829 // kIceConnectionConnecting is currently used as the default,
4830 // un-connected state by the TransportController, so its only use is
4831 // detecting disconnections.
4832 if (ice_connection_state_ ==
4833 PeerConnectionInterface::kIceConnectionConnected ||
4834 ice_connection_state_ ==
4835 PeerConnectionInterface::kIceConnectionCompleted) {
4836 SetIceConnectionState(
4837 PeerConnectionInterface::kIceConnectionDisconnected);
4838 }
4839 break;
4840 case cricket::kIceConnectionFailed:
4841 SetIceConnectionState(PeerConnectionInterface::kIceConnectionFailed);
4842 break;
4843 case cricket::kIceConnectionConnected:
Mirko Bonadei675513b2017-11-09 11:09:25 +01004844 RTC_LOG(LS_INFO) << "Changing to ICE connected state because "
4845 << "all transports are writable.";
Steve Anton75737c02017-11-06 10:37:17 -08004846 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
4847 break;
4848 case cricket::kIceConnectionCompleted:
Mirko Bonadei675513b2017-11-09 11:09:25 +01004849 RTC_LOG(LS_INFO) << "Changing to ICE completed state because "
4850 << "all transports are complete.";
Steve Anton75737c02017-11-06 10:37:17 -08004851 if (ice_connection_state_ !=
4852 PeerConnectionInterface::kIceConnectionConnected) {
4853 // If jumping directly from "checking" to "connected",
4854 // signal "connected" first.
4855 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
4856 }
4857 SetIceConnectionState(PeerConnectionInterface::kIceConnectionCompleted);
4858 if (metrics_observer()) {
4859 ReportTransportStats();
4860 }
4861 break;
4862 default:
4863 RTC_NOTREACHED();
4864 }
4865}
4866
4867void PeerConnection::OnTransportControllerCandidatesGathered(
4868 const std::string& transport_name,
4869 const cricket::Candidates& candidates) {
4870 RTC_DCHECK(signaling_thread()->IsCurrent());
4871 int sdp_mline_index;
4872 if (!GetLocalCandidateMediaIndex(transport_name, &sdp_mline_index)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004873 RTC_LOG(LS_ERROR)
4874 << "OnTransportControllerCandidatesGathered: content name "
4875 << transport_name << " not found";
Steve Anton75737c02017-11-06 10:37:17 -08004876 return;
4877 }
4878
4879 for (cricket::Candidates::const_iterator citer = candidates.begin();
4880 citer != candidates.end(); ++citer) {
4881 // Use transport_name as the candidate media id.
4882 std::unique_ptr<JsepIceCandidate> candidate(
4883 new JsepIceCandidate(transport_name, sdp_mline_index, *citer));
4884 if (local_description()) {
4885 mutable_local_description()->AddCandidate(candidate.get());
4886 }
4887 OnIceCandidate(std::move(candidate));
4888 }
4889}
4890
4891void PeerConnection::OnTransportControllerCandidatesRemoved(
4892 const std::vector<cricket::Candidate>& candidates) {
4893 RTC_DCHECK(signaling_thread()->IsCurrent());
4894 // Sanity check.
4895 for (const cricket::Candidate& candidate : candidates) {
4896 if (candidate.transport_name().empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004897 RTC_LOG(LS_ERROR) << "OnTransportControllerCandidatesRemoved: "
4898 << "empty content name in candidate "
4899 << candidate.ToString();
Steve Anton75737c02017-11-06 10:37:17 -08004900 return;
4901 }
4902 }
4903
4904 if (local_description()) {
4905 mutable_local_description()->RemoveCandidates(candidates);
4906 }
4907 OnIceCandidatesRemoved(candidates);
4908}
4909
4910void PeerConnection::OnTransportControllerDtlsHandshakeError(
4911 rtc::SSLHandshakeError error) {
4912 if (metrics_observer()) {
4913 metrics_observer()->IncrementEnumCounter(
4914 webrtc::kEnumCounterDtlsHandshakeError, static_cast<int>(error),
4915 static_cast<int>(rtc::SSLHandshakeError::MAX_VALUE));
4916 }
4917}
4918
Steve Antoned10bd92017-12-05 10:52:59 -08004919void PeerConnection::EnableSending() {
4920 for (auto transceiver : transceivers_) {
4921 cricket::BaseChannel* channel = transceiver->internal()->channel();
4922 if (channel && !channel->enabled()) {
4923 channel->Enable(true);
4924 }
Steve Anton75737c02017-11-06 10:37:17 -08004925 }
4926
Steve Anton4171afb2017-11-20 10:20:22 -08004927 if (rtp_data_channel_ && !rtp_data_channel_->enabled()) {
Steve Anton75737c02017-11-06 10:37:17 -08004928 rtp_data_channel_->Enable(true);
Steve Anton4171afb2017-11-20 10:20:22 -08004929 }
Steve Anton75737c02017-11-06 10:37:17 -08004930}
4931
4932// Returns the media index for a local ice candidate given the content name.
4933bool PeerConnection::GetLocalCandidateMediaIndex(
4934 const std::string& content_name,
4935 int* sdp_mline_index) {
4936 if (!local_description() || !sdp_mline_index) {
4937 return false;
4938 }
4939
4940 bool content_found = false;
4941 const ContentInfos& contents = local_description()->description()->contents();
4942 for (size_t index = 0; index < contents.size(); ++index) {
4943 if (contents[index].name == content_name) {
4944 *sdp_mline_index = static_cast<int>(index);
4945 content_found = true;
4946 break;
4947 }
4948 }
4949 return content_found;
4950}
4951
4952bool PeerConnection::UseCandidatesInSessionDescription(
4953 const SessionDescriptionInterface* remote_desc) {
4954 if (!remote_desc) {
4955 return true;
4956 }
4957 bool ret = true;
4958
4959 for (size_t m = 0; m < remote_desc->number_of_mediasections(); ++m) {
4960 const IceCandidateCollection* candidates = remote_desc->candidates(m);
4961 for (size_t n = 0; n < candidates->count(); ++n) {
4962 const IceCandidateInterface* candidate = candidates->at(n);
4963 bool valid = false;
4964 if (!ReadyToUseRemoteCandidate(candidate, remote_desc, &valid)) {
4965 if (valid) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004966 RTC_LOG(LS_INFO)
4967 << "UseCandidatesInSessionDescription: Not ready to use "
4968 << "candidate.";
Steve Anton75737c02017-11-06 10:37:17 -08004969 }
4970 continue;
4971 }
4972 ret = UseCandidate(candidate);
4973 if (!ret) {
4974 break;
4975 }
4976 }
4977 }
4978 return ret;
4979}
4980
4981bool PeerConnection::UseCandidate(const IceCandidateInterface* candidate) {
4982 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
4983 size_t remote_content_size =
4984 remote_description()->description()->contents().size();
4985 if (mediacontent_index >= remote_content_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004986 RTC_LOG(LS_ERROR) << "UseCandidate: Invalid candidate media index.";
Steve Anton75737c02017-11-06 10:37:17 -08004987 return false;
4988 }
4989
4990 cricket::ContentInfo content =
4991 remote_description()->description()->contents()[mediacontent_index];
4992 std::vector<cricket::Candidate> candidates;
4993 candidates.push_back(candidate->candidate());
4994 // Invoking BaseSession method to handle remote candidates.
4995 std::string error;
4996 if (transport_controller_->AddRemoteCandidates(content.name, candidates,
4997 &error)) {
4998 // Candidates successfully submitted for checking.
4999 if (ice_connection_state_ == PeerConnectionInterface::kIceConnectionNew ||
5000 ice_connection_state_ ==
5001 PeerConnectionInterface::kIceConnectionDisconnected) {
5002 // If state is New, then the session has just gotten its first remote ICE
5003 // candidates, so go to Checking.
5004 // If state is Disconnected, the session is re-using old candidates or
5005 // receiving additional ones, so go to Checking.
5006 // If state is Connected, stay Connected.
5007 // TODO(bemasc): If state is Connected, and the new candidates are for a
5008 // newly added transport, then the state actually _should_ move to
5009 // checking. Add a way to distinguish that case.
5010 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
5011 }
5012 // TODO(bemasc): If state is Completed, go back to Connected.
5013 } else {
5014 if (!error.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005015 RTC_LOG(LS_WARNING) << error;
Steve Anton75737c02017-11-06 10:37:17 -08005016 }
5017 }
5018 return true;
5019}
5020
5021void PeerConnection::RemoveUnusedChannels(const SessionDescription* desc) {
Steve Anton75737c02017-11-06 10:37:17 -08005022 // Destroy video channel first since it may have a pointer to the
5023 // voice channel.
5024 const cricket::ContentInfo* video_info = cricket::GetFirstVideoContent(desc);
Steve Anton6fec8802017-12-04 10:37:29 -08005025 if (!video_info || video_info->rejected) {
5026 DestroyTransceiverChannel(GetVideoTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08005027 }
5028
Steve Anton6fec8802017-12-04 10:37:29 -08005029 const cricket::ContentInfo* audio_info = cricket::GetFirstAudioContent(desc);
5030 if (!audio_info || audio_info->rejected) {
5031 DestroyTransceiverChannel(GetAudioTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08005032 }
5033
5034 const cricket::ContentInfo* data_info = cricket::GetFirstDataContent(desc);
5035 if (!data_info || data_info->rejected) {
Steve Anton6fec8802017-12-04 10:37:29 -08005036 DestroyDataChannel();
Steve Anton75737c02017-11-06 10:37:17 -08005037 }
5038}
5039
Steve Antoneda6ccd2017-12-04 10:21:55 -08005040std::string PeerConnection::GetTransportNameForMediaSection(
5041 const std::string& mid,
5042 const cricket::ContentGroup* bundle_group) const {
5043 if (!bundle_group) {
5044 return mid;
Steve Anton75737c02017-11-06 10:37:17 -08005045 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005046 const std::string* first_content_name = bundle_group->FirstContentName();
Steve Anton75737c02017-11-06 10:37:17 -08005047 if (!first_content_name) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005048 RTC_LOG(LS_WARNING) << "Tried to BUNDLE with no contents.";
Steve Antoneda6ccd2017-12-04 10:21:55 -08005049 return mid;
Steve Anton75737c02017-11-06 10:37:17 -08005050 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005051 if (!bundle_group->HasContentName(mid)) {
5052 RTC_LOG(LS_WARNING) << mid << " is not part of any bundle group";
5053 return mid;
Steve Anton75737c02017-11-06 10:37:17 -08005054 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005055 RTC_LOG(LS_INFO) << "Bundling " << mid << " on " << *first_content_name;
5056 return *first_content_name;
Steve Anton75737c02017-11-06 10:37:17 -08005057}
5058
Steve Antondcc3c022017-12-22 16:02:54 -08005059RTCErrorOr<const cricket::ContentGroup*> PeerConnection::GetEarlyBundleGroup(
5060 const SessionDescription& desc) const {
Steve Anton75737c02017-11-06 10:37:17 -08005061 const cricket::ContentGroup* bundle_group = nullptr;
5062 if (configuration_.bundle_policy ==
5063 PeerConnectionInterface::kBundlePolicyMaxBundle) {
Steve Antondcc3c022017-12-22 16:02:54 -08005064 bundle_group = desc.GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton75737c02017-11-06 10:37:17 -08005065 if (!bundle_group) {
Steve Anton8a006912017-12-04 15:25:56 -08005066 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5067 "max-bundle configured but session description "
5068 "has no BUNDLE group");
Steve Anton75737c02017-11-06 10:37:17 -08005069 }
5070 }
Steve Antondcc3c022017-12-22 16:02:54 -08005071 return std::move(bundle_group);
5072}
5073
5074RTCError PeerConnection::CreateChannels(const SessionDescription& desc) {
5075 auto bundle_group_or_error = GetEarlyBundleGroup(desc);
5076 if (!bundle_group_or_error.ok()) {
5077 return bundle_group_or_error.MoveError();
5078 }
5079 const cricket::ContentGroup* bundle_group = bundle_group_or_error.MoveValue();
Steve Anton75737c02017-11-06 10:37:17 -08005080
Steve Antoneda6ccd2017-12-04 10:21:55 -08005081 // Creating the media channels and transport proxies.
Steve Antondcc3c022017-12-22 16:02:54 -08005082 const cricket::ContentInfo* voice = cricket::GetFirstAudioContent(&desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08005083 if (voice && !voice->rejected &&
5084 !GetAudioTransceiver()->internal()->channel()) {
5085 cricket::VoiceChannel* voice_channel = CreateVoiceChannel(
5086 voice->name,
5087 GetTransportNameForMediaSection(voice->name, bundle_group));
5088 if (!voice_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08005089 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5090 "Failed to create voice channel.");
Steve Antoneda6ccd2017-12-04 10:21:55 -08005091 }
5092 GetAudioTransceiver()->internal()->SetChannel(voice_channel);
5093 }
5094
Steve Antondcc3c022017-12-22 16:02:54 -08005095 const cricket::ContentInfo* video = cricket::GetFirstVideoContent(&desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08005096 if (video && !video->rejected &&
5097 !GetVideoTransceiver()->internal()->channel()) {
5098 cricket::VideoChannel* video_channel = CreateVideoChannel(
5099 video->name,
5100 GetTransportNameForMediaSection(video->name, bundle_group));
5101 if (!video_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08005102 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5103 "Failed to create video channel.");
Steve Anton75737c02017-11-06 10:37:17 -08005104 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005105 GetVideoTransceiver()->internal()->SetChannel(video_channel);
Steve Anton75737c02017-11-06 10:37:17 -08005106 }
5107
Steve Antondcc3c022017-12-22 16:02:54 -08005108 const cricket::ContentInfo* data = cricket::GetFirstDataContent(&desc);
Steve Anton75737c02017-11-06 10:37:17 -08005109 if (data_channel_type_ != cricket::DCT_NONE && data && !data->rejected &&
5110 !rtp_data_channel_ && !sctp_transport_) {
Steve Antoneda6ccd2017-12-04 10:21:55 -08005111 if (!CreateDataChannel(data->name, GetTransportNameForMediaSection(
5112 data->name, bundle_group))) {
Steve Anton8a006912017-12-04 15:25:56 -08005113 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5114 "Failed to create data channel.");
Steve Anton75737c02017-11-06 10:37:17 -08005115 }
5116 }
5117
Steve Anton8a006912017-12-04 15:25:56 -08005118 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08005119}
5120
Steve Anton4171afb2017-11-20 10:20:22 -08005121// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08005122cricket::VoiceChannel* PeerConnection::CreateVoiceChannel(
5123 const std::string& mid,
5124 const std::string& transport_name) {
Steve Anton75737c02017-11-06 10:37:17 -08005125 cricket::DtlsTransportInternal* rtp_dtls_transport =
5126 transport_controller_->CreateDtlsTransport(
5127 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5128 cricket::DtlsTransportInternal* rtcp_dtls_transport = nullptr;
5129 if (configuration_.rtcp_mux_policy !=
5130 PeerConnectionInterface::kRtcpMuxPolicyRequire) {
5131 rtcp_dtls_transport = transport_controller_->CreateDtlsTransport(
5132 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
5133 }
5134
5135 cricket::VoiceChannel* voice_channel = channel_manager()->CreateVoiceChannel(
5136 call_.get(), configuration_.media_config, rtp_dtls_transport,
Steve Antoneda6ccd2017-12-04 10:21:55 -08005137 rtcp_dtls_transport, signaling_thread(), mid, SrtpRequired(),
5138 audio_options_);
Steve Anton75737c02017-11-06 10:37:17 -08005139 if (!voice_channel) {
5140 transport_controller_->DestroyDtlsTransport(
5141 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5142 if (rtcp_dtls_transport) {
5143 transport_controller_->DestroyDtlsTransport(
5144 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
5145 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005146 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08005147 }
Steve Anton75737c02017-11-06 10:37:17 -08005148 voice_channel->SignalRtcpMuxFullyActive.connect(
5149 this, &PeerConnection::DestroyRtcpTransport_n);
5150 voice_channel->SignalDtlsSrtpSetupFailure.connect(
5151 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08005152 voice_channel->SignalSentPacket.connect(this,
5153 &PeerConnection::OnSentPacket_w);
Steve Anton4171afb2017-11-20 10:20:22 -08005154
Steve Antoneda6ccd2017-12-04 10:21:55 -08005155 return voice_channel;
Steve Anton75737c02017-11-06 10:37:17 -08005156}
5157
Steve Anton4171afb2017-11-20 10:20:22 -08005158// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08005159cricket::VideoChannel* PeerConnection::CreateVideoChannel(
5160 const std::string& mid,
5161 const std::string& transport_name) {
Steve Anton75737c02017-11-06 10:37:17 -08005162 cricket::DtlsTransportInternal* rtp_dtls_transport =
5163 transport_controller_->CreateDtlsTransport(
5164 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5165 cricket::DtlsTransportInternal* rtcp_dtls_transport = nullptr;
5166 if (configuration_.rtcp_mux_policy !=
5167 PeerConnectionInterface::kRtcpMuxPolicyRequire) {
5168 rtcp_dtls_transport = transport_controller_->CreateDtlsTransport(
5169 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
5170 }
5171
5172 cricket::VideoChannel* video_channel = channel_manager()->CreateVideoChannel(
5173 call_.get(), configuration_.media_config, rtp_dtls_transport,
Steve Antoneda6ccd2017-12-04 10:21:55 -08005174 rtcp_dtls_transport, signaling_thread(), mid, SrtpRequired(),
5175 video_options_);
Steve Anton75737c02017-11-06 10:37:17 -08005176
5177 if (!video_channel) {
5178 transport_controller_->DestroyDtlsTransport(
5179 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5180 if (rtcp_dtls_transport) {
5181 transport_controller_->DestroyDtlsTransport(
5182 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
5183 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005184 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08005185 }
Steve Anton75737c02017-11-06 10:37:17 -08005186 video_channel->SignalRtcpMuxFullyActive.connect(
5187 this, &PeerConnection::DestroyRtcpTransport_n);
5188 video_channel->SignalDtlsSrtpSetupFailure.connect(
5189 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08005190 video_channel->SignalSentPacket.connect(this,
5191 &PeerConnection::OnSentPacket_w);
Steve Anton4171afb2017-11-20 10:20:22 -08005192
Steve Antoneda6ccd2017-12-04 10:21:55 -08005193 return video_channel;
Steve Anton75737c02017-11-06 10:37:17 -08005194}
5195
Steve Antoneda6ccd2017-12-04 10:21:55 -08005196bool PeerConnection::CreateDataChannel(const std::string& mid,
5197 const std::string& transport_name) {
Steve Anton75737c02017-11-06 10:37:17 -08005198 bool sctp = (data_channel_type_ == cricket::DCT_SCTP);
5199 if (sctp) {
5200 if (!sctp_factory_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005201 RTC_LOG(LS_ERROR)
Steve Anton75737c02017-11-06 10:37:17 -08005202 << "Trying to create SCTP transport, but didn't compile with "
5203 "SCTP support (HAVE_SCTP)";
5204 return false;
5205 }
5206 if (!network_thread()->Invoke<bool>(
5207 RTC_FROM_HERE, rtc::Bind(&PeerConnection::CreateSctpTransport_n,
Steve Antoneda6ccd2017-12-04 10:21:55 -08005208 this, mid, transport_name))) {
Steve Anton75737c02017-11-06 10:37:17 -08005209 return false;
5210 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005211 for (const auto& channel : sctp_data_channels_) {
5212 channel->OnTransportChannelCreated();
5213 }
Steve Anton75737c02017-11-06 10:37:17 -08005214 } else {
Steve Anton75737c02017-11-06 10:37:17 -08005215 cricket::DtlsTransportInternal* rtp_dtls_transport =
5216 transport_controller_->CreateDtlsTransport(
5217 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5218 cricket::DtlsTransportInternal* rtcp_dtls_transport = nullptr;
5219 if (configuration_.rtcp_mux_policy !=
5220 PeerConnectionInterface::kRtcpMuxPolicyRequire) {
5221 rtcp_dtls_transport = transport_controller_->CreateDtlsTransport(
5222 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
5223 }
5224
5225 rtp_data_channel_ = channel_manager()->CreateRtpDataChannel(
5226 configuration_.media_config, rtp_dtls_transport, rtcp_dtls_transport,
Steve Antoneda6ccd2017-12-04 10:21:55 -08005227 signaling_thread(), mid, SrtpRequired());
Steve Anton75737c02017-11-06 10:37:17 -08005228
5229 if (!rtp_data_channel_) {
5230 transport_controller_->DestroyDtlsTransport(
5231 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5232 if (rtcp_dtls_transport) {
5233 transport_controller_->DestroyDtlsTransport(
5234 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
5235 }
5236 return false;
5237 }
5238
5239 rtp_data_channel_->SignalRtcpMuxFullyActive.connect(
5240 this, &PeerConnection::DestroyRtcpTransport_n);
5241 rtp_data_channel_->SignalDtlsSrtpSetupFailure.connect(
5242 this, &PeerConnection::OnDtlsSrtpSetupFailure);
5243 rtp_data_channel_->SignalSentPacket.connect(
5244 this, &PeerConnection::OnSentPacket_w);
5245 }
5246
Steve Anton75737c02017-11-06 10:37:17 -08005247 return true;
5248}
5249
5250Call::Stats PeerConnection::GetCallStats() {
5251 if (!worker_thread()->IsCurrent()) {
5252 return worker_thread()->Invoke<Call::Stats>(
5253 RTC_FROM_HERE, rtc::Bind(&PeerConnection::GetCallStats, this));
5254 }
5255 if (call_) {
5256 return call_->GetStats();
5257 } else {
5258 return Call::Stats();
5259 }
5260}
5261
5262std::unique_ptr<SessionStats> PeerConnection::GetSessionStats_n(
5263 const ChannelNamePairs& channel_name_pairs) {
5264 RTC_DCHECK(network_thread()->IsCurrent());
5265 std::unique_ptr<SessionStats> session_stats(new SessionStats());
5266 for (const auto channel_name_pair :
5267 {&channel_name_pairs.voice, &channel_name_pairs.video,
5268 &channel_name_pairs.data}) {
5269 if (*channel_name_pair) {
5270 cricket::TransportStats transport_stats;
5271 if (!transport_controller_->GetStats((*channel_name_pair)->transport_name,
5272 &transport_stats)) {
5273 return nullptr;
5274 }
Steve Anton75737c02017-11-06 10:37:17 -08005275 session_stats->transport_stats[(*channel_name_pair)->transport_name] =
5276 std::move(transport_stats);
5277 }
5278 }
5279 return session_stats;
5280}
5281
5282bool PeerConnection::CreateSctpTransport_n(const std::string& content_name,
5283 const std::string& transport_name) {
5284 RTC_DCHECK(network_thread()->IsCurrent());
5285 RTC_DCHECK(sctp_factory_);
5286 cricket::DtlsTransportInternal* tc =
5287 transport_controller_->CreateDtlsTransport_n(
5288 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5289 sctp_transport_ = sctp_factory_->CreateSctpTransport(tc);
5290 RTC_DCHECK(sctp_transport_);
5291 sctp_invoker_.reset(new rtc::AsyncInvoker());
5292 sctp_transport_->SignalReadyToSendData.connect(
5293 this, &PeerConnection::OnSctpTransportReadyToSendData_n);
5294 sctp_transport_->SignalDataReceived.connect(
5295 this, &PeerConnection::OnSctpTransportDataReceived_n);
5296 sctp_transport_->SignalStreamClosedRemotely.connect(
5297 this, &PeerConnection::OnSctpStreamClosedRemotely_n);
Oskar Sundbom9b28a032017-11-16 10:53:30 +01005298 sctp_transport_name_ = transport_name;
5299 sctp_content_name_ = content_name;
Steve Anton75737c02017-11-06 10:37:17 -08005300 return true;
5301}
5302
5303void PeerConnection::ChangeSctpTransport_n(const std::string& transport_name) {
5304 RTC_DCHECK(network_thread()->IsCurrent());
5305 RTC_DCHECK(sctp_transport_);
5306 RTC_DCHECK(sctp_transport_name_);
5307 std::string old_sctp_transport_name = *sctp_transport_name_;
Oskar Sundbom9b28a032017-11-16 10:53:30 +01005308 sctp_transport_name_ = transport_name;
Steve Anton75737c02017-11-06 10:37:17 -08005309 cricket::DtlsTransportInternal* tc =
5310 transport_controller_->CreateDtlsTransport_n(
5311 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5312 sctp_transport_->SetTransportChannel(tc);
5313 transport_controller_->DestroyDtlsTransport_n(
5314 old_sctp_transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5315}
5316
5317void PeerConnection::DestroySctpTransport_n() {
5318 RTC_DCHECK(network_thread()->IsCurrent());
5319 sctp_transport_.reset(nullptr);
Taylor Brandstetter389a97c2018-01-03 16:26:06 -08005320 transport_controller_->DestroyDtlsTransport_n(
5321 *sctp_transport_name_, cricket::ICE_CANDIDATE_COMPONENT_RTP);
Steve Anton75737c02017-11-06 10:37:17 -08005322 sctp_content_name_.reset();
5323 sctp_transport_name_.reset();
5324 sctp_invoker_.reset(nullptr);
5325 sctp_ready_to_send_data_ = false;
5326}
5327
5328void PeerConnection::OnSctpTransportReadyToSendData_n() {
5329 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5330 RTC_DCHECK(network_thread()->IsCurrent());
5331 // Note: Cannot use rtc::Bind here because it will grab a reference to
5332 // PeerConnection and potentially cause PeerConnection to live longer than
5333 // expected. It is safe not to grab a reference since the sctp_invoker_ will
5334 // be destroyed before PeerConnection is destroyed, and at that point all
5335 // pending tasks will be cleared.
5336 sctp_invoker_->AsyncInvoke<void>(RTC_FROM_HERE, signaling_thread(), [this] {
5337 OnSctpTransportReadyToSendData_s(true);
5338 });
5339}
5340
5341void PeerConnection::OnSctpTransportReadyToSendData_s(bool ready) {
5342 RTC_DCHECK(signaling_thread()->IsCurrent());
5343 sctp_ready_to_send_data_ = ready;
5344 SignalSctpReadyToSendData(ready);
5345}
5346
5347void PeerConnection::OnSctpTransportDataReceived_n(
5348 const cricket::ReceiveDataParams& params,
5349 const rtc::CopyOnWriteBuffer& payload) {
5350 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5351 RTC_DCHECK(network_thread()->IsCurrent());
5352 // Note: Cannot use rtc::Bind here because it will grab a reference to
5353 // PeerConnection and potentially cause PeerConnection to live longer than
5354 // expected. It is safe not to grab a reference since the sctp_invoker_ will
5355 // be destroyed before PeerConnection is destroyed, and at that point all
5356 // pending tasks will be cleared.
5357 sctp_invoker_->AsyncInvoke<void>(
5358 RTC_FROM_HERE, signaling_thread(), [this, params, payload] {
5359 OnSctpTransportDataReceived_s(params, payload);
5360 });
5361}
5362
5363void PeerConnection::OnSctpTransportDataReceived_s(
5364 const cricket::ReceiveDataParams& params,
5365 const rtc::CopyOnWriteBuffer& payload) {
5366 RTC_DCHECK(signaling_thread()->IsCurrent());
5367 if (params.type == cricket::DMT_CONTROL && IsOpenMessage(payload)) {
5368 // Received OPEN message; parse and signal that a new data channel should
5369 // be created.
5370 std::string label;
5371 InternalDataChannelInit config;
5372 config.id = params.ssrc;
5373 if (!ParseDataChannelOpenMessage(payload, &label, &config)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005374 RTC_LOG(LS_WARNING) << "Failed to parse the OPEN message for sid "
5375 << params.ssrc;
Steve Anton75737c02017-11-06 10:37:17 -08005376 return;
5377 }
5378 config.open_handshake_role = InternalDataChannelInit::kAcker;
5379 OnDataChannelOpenMessage(label, config);
5380 } else {
5381 // Otherwise just forward the signal.
5382 SignalSctpDataReceived(params, payload);
5383 }
5384}
5385
5386void PeerConnection::OnSctpStreamClosedRemotely_n(int sid) {
5387 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5388 RTC_DCHECK(network_thread()->IsCurrent());
5389 sctp_invoker_->AsyncInvoke<void>(
5390 RTC_FROM_HERE, signaling_thread(),
5391 rtc::Bind(&sigslot::signal1<int>::operator(),
5392 &SignalSctpStreamClosedRemotely, sid));
5393}
5394
5395// Returns false if bundle is enabled and rtcp_mux is disabled.
5396bool PeerConnection::ValidateBundleSettings(const SessionDescription* desc) {
5397 bool bundle_enabled = desc->HasGroup(cricket::GROUP_TYPE_BUNDLE);
5398 if (!bundle_enabled)
5399 return true;
5400
5401 const cricket::ContentGroup* bundle_group =
5402 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
5403 RTC_DCHECK(bundle_group != NULL);
5404
5405 const cricket::ContentInfos& contents = desc->contents();
5406 for (cricket::ContentInfos::const_iterator citer = contents.begin();
5407 citer != contents.end(); ++citer) {
5408 const cricket::ContentInfo* content = (&*citer);
5409 RTC_DCHECK(content != NULL);
5410 if (bundle_group->HasContentName(content->name) && !content->rejected &&
Steve Anton5adfafd2017-12-20 16:34:00 -08005411 content->type == MediaProtocolType::kRtp) {
Steve Anton75737c02017-11-06 10:37:17 -08005412 if (!HasRtcpMuxEnabled(content))
5413 return false;
5414 }
5415 }
5416 // RTCP-MUX is enabled in all the contents.
5417 return true;
5418}
5419
5420bool PeerConnection::HasRtcpMuxEnabled(const cricket::ContentInfo* content) {
Steve Antonb1c1de12017-12-21 15:14:30 -08005421 return content->media_description()->rtcp_mux();
Steve Anton75737c02017-11-06 10:37:17 -08005422}
5423
Steve Anton8a006912017-12-04 15:25:56 -08005424RTCError PeerConnection::ValidateSessionDescription(
Steve Anton75737c02017-11-06 10:37:17 -08005425 const SessionDescriptionInterface* sdesc,
Steve Anton8a006912017-12-04 15:25:56 -08005426 cricket::ContentSource source) {
Steve Antonf8470812017-12-04 10:46:21 -08005427 if (session_error() != SessionError::kNone) {
Steve Anton8a006912017-12-04 15:25:56 -08005428 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
Steve Anton75737c02017-11-06 10:37:17 -08005429 }
5430
5431 if (!sdesc || !sdesc->description()) {
Steve Anton8a006912017-12-04 15:25:56 -08005432 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidSdp);
Steve Anton75737c02017-11-06 10:37:17 -08005433 }
5434
Steve Anton3828c062017-12-06 10:34:51 -08005435 SdpType type = sdesc->GetType();
5436 if ((source == cricket::CS_LOCAL && !ExpectSetLocalDescription(type)) ||
5437 (source == cricket::CS_REMOTE && !ExpectSetRemoteDescription(type))) {
Steve Anton8a006912017-12-04 15:25:56 -08005438 LOG_AND_RETURN_ERROR(
5439 RTCErrorType::INVALID_PARAMETER,
5440 "Called in wrong state: " + GetSignalingStateString(signaling_state()));
Steve Anton75737c02017-11-06 10:37:17 -08005441 }
5442
5443 // Verify crypto settings.
5444 std::string crypto_error;
Steve Anton8a006912017-12-04 15:25:56 -08005445 if (webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED ||
5446 dtls_enabled_) {
Harald Alvestrand194939b2018-01-24 16:04:13 +01005447 RTCError crypto_error =
5448 VerifyCrypto(sdesc->description(), dtls_enabled_, uma_observer_);
Steve Anton8a006912017-12-04 15:25:56 -08005449 if (!crypto_error.ok()) {
5450 return crypto_error;
5451 }
Steve Anton75737c02017-11-06 10:37:17 -08005452 }
5453
5454 // Verify ice-ufrag and ice-pwd.
5455 if (!VerifyIceUfragPwdPresent(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08005456 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5457 kSdpWithoutIceUfragPwd);
Steve Anton75737c02017-11-06 10:37:17 -08005458 }
5459
5460 if (!ValidateBundleSettings(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08005461 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5462 kBundleWithoutRtcpMux);
Steve Anton75737c02017-11-06 10:37:17 -08005463 }
5464
5465 // TODO(skvlad): When the local rtcp-mux policy is Require, reject any
5466 // m-lines that do not rtcp-mux enabled.
5467
5468 // Verify m-lines in Answer when compared against Offer.
Steve Anton3828c062017-12-06 10:34:51 -08005469 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Anton75737c02017-11-06 10:37:17 -08005470 const cricket::SessionDescription* offer_desc =
5471 (source == cricket::CS_LOCAL) ? remote_description()->description()
5472 : local_description()->description();
5473 if (!MediaSectionsHaveSameCount(offer_desc, sdesc->description()) ||
5474 !MediaSectionsInSameOrder(offer_desc, sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08005475 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5476 kMlineMismatchInAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08005477 }
5478 } else {
5479 const cricket::SessionDescription* current_desc = nullptr;
5480 if (source == cricket::CS_LOCAL && local_description()) {
5481 current_desc = local_description()->description();
5482 } else if (source == cricket::CS_REMOTE && remote_description()) {
5483 current_desc = remote_description()->description();
5484 }
5485 // The re-offers should respect the order of m= sections in current
5486 // description. See RFC3264 Section 8 paragraph 4 for more details.
5487 if (current_desc &&
5488 !MediaSectionsInSameOrder(current_desc, sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08005489 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5490 kMlineMismatchInSubsequentOffer);
Steve Anton75737c02017-11-06 10:37:17 -08005491 }
5492 }
5493
Steve Anton8a006912017-12-04 15:25:56 -08005494 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08005495}
5496
Steve Anton3828c062017-12-06 10:34:51 -08005497bool PeerConnection::ExpectSetLocalDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08005498 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08005499 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08005500 return (state == PeerConnectionInterface::kStable) ||
5501 (state == PeerConnectionInterface::kHaveLocalOffer);
Steve Anton20393062017-12-04 16:24:52 -08005502 } else {
Steve Anton3828c062017-12-06 10:34:51 -08005503 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08005504 return (state == PeerConnectionInterface::kHaveRemoteOffer) ||
5505 (state == PeerConnectionInterface::kHaveLocalPrAnswer);
5506 }
5507}
5508
Steve Anton3828c062017-12-06 10:34:51 -08005509bool PeerConnection::ExpectSetRemoteDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08005510 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08005511 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08005512 return (state == PeerConnectionInterface::kStable) ||
5513 (state == PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton20393062017-12-04 16:24:52 -08005514 } else {
Steve Anton3828c062017-12-06 10:34:51 -08005515 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08005516 return (state == PeerConnectionInterface::kHaveLocalOffer) ||
5517 (state == PeerConnectionInterface::kHaveRemotePrAnswer);
5518 }
5519}
5520
Steve Antonf8470812017-12-04 10:46:21 -08005521const char* PeerConnection::SessionErrorToString(SessionError error) const {
5522 switch (error) {
5523 case SessionError::kNone:
5524 return "ERROR_NONE";
5525 case SessionError::kContent:
5526 return "ERROR_CONTENT";
5527 case SessionError::kTransport:
5528 return "ERROR_TRANSPORT";
5529 }
5530 RTC_NOTREACHED();
5531 return "";
5532}
5533
Steve Anton75737c02017-11-06 10:37:17 -08005534std::string PeerConnection::GetSessionErrorMsg() {
5535 std::ostringstream desc;
Steve Antonf8470812017-12-04 10:46:21 -08005536 desc << kSessionError << SessionErrorToString(session_error()) << ". ";
5537 desc << kSessionErrorDesc << session_error_desc() << ".";
Steve Anton75737c02017-11-06 10:37:17 -08005538 return desc.str();
5539}
5540
5541// We need to check the local/remote description for the Transport instead of
5542// the session, because a new Transport added during renegotiation may have
5543// them unset while the session has them set from the previous negotiation.
5544// Not doing so may trigger the auto generation of transport description and
5545// mess up DTLS identity information, ICE credential, etc.
5546bool PeerConnection::ReadyToUseRemoteCandidate(
5547 const IceCandidateInterface* candidate,
5548 const SessionDescriptionInterface* remote_desc,
5549 bool* valid) {
5550 *valid = true;
5551
5552 const SessionDescriptionInterface* current_remote_desc =
5553 remote_desc ? remote_desc : remote_description();
5554
5555 if (!current_remote_desc) {
5556 return false;
5557 }
5558
5559 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
5560 size_t remote_content_size =
5561 current_remote_desc->description()->contents().size();
5562 if (mediacontent_index >= remote_content_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005563 RTC_LOG(LS_ERROR)
5564 << "ReadyToUseRemoteCandidate: Invalid candidate media index "
5565 << mediacontent_index;
Steve Anton75737c02017-11-06 10:37:17 -08005566
5567 *valid = false;
5568 return false;
5569 }
5570
5571 cricket::ContentInfo content =
5572 current_remote_desc->description()->contents()[mediacontent_index];
5573
5574 const std::string transport_name = GetTransportName(content.name);
5575 if (transport_name.empty()) {
5576 return false;
5577 }
5578 return transport_controller_->ReadyForRemoteCandidates(transport_name);
5579}
5580
5581bool PeerConnection::SrtpRequired() const {
5582 return dtls_enabled_ ||
5583 webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED;
5584}
5585
5586void PeerConnection::OnTransportControllerGatheringState(
5587 cricket::IceGatheringState state) {
5588 RTC_DCHECK(signaling_thread()->IsCurrent());
5589 if (state == cricket::kIceGatheringGathering) {
5590 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringGathering);
5591 } else if (state == cricket::kIceGatheringComplete) {
5592 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringComplete);
5593 }
5594}
5595
5596void PeerConnection::ReportTransportStats() {
Steve Antonc7b964c2018-02-01 14:39:45 -08005597 std::map<std::string, std::set<cricket::MediaType>>
5598 media_types_by_transport_name;
5599 for (auto transceiver : transceivers_) {
5600 if (transceiver->internal()->channel()) {
5601 const std::string& transport_name =
5602 transceiver->internal()->channel()->transport_name();
5603 media_types_by_transport_name[transport_name].insert(
5604 transceiver->internal()->media_type());
5605 }
Steve Anton75737c02017-11-06 10:37:17 -08005606 }
5607 if (rtp_data_channel()) {
Steve Antonc7b964c2018-02-01 14:39:45 -08005608 media_types_by_transport_name[rtp_data_channel()->transport_name()].insert(
5609 cricket::MEDIA_TYPE_DATA);
Steve Anton75737c02017-11-06 10:37:17 -08005610 }
5611 if (sctp_transport_name_) {
Steve Antonc7b964c2018-02-01 14:39:45 -08005612 media_types_by_transport_name[*sctp_transport_name_].insert(
5613 cricket::MEDIA_TYPE_DATA);
Steve Anton75737c02017-11-06 10:37:17 -08005614 }
Steve Antonc7b964c2018-02-01 14:39:45 -08005615 for (const auto& entry : media_types_by_transport_name) {
5616 const std::string& transport_name = entry.first;
5617 const std::set<cricket::MediaType> media_types = entry.second;
Steve Anton75737c02017-11-06 10:37:17 -08005618 cricket::TransportStats stats;
Steve Antonc7b964c2018-02-01 14:39:45 -08005619 if (transport_controller_->GetStats(transport_name, &stats)) {
Steve Anton75737c02017-11-06 10:37:17 -08005620 ReportBestConnectionState(stats);
Steve Antonc7b964c2018-02-01 14:39:45 -08005621 ReportNegotiatedCiphers(stats, media_types);
Steve Anton75737c02017-11-06 10:37:17 -08005622 }
5623 }
5624}
5625// Walk through the ConnectionInfos to gather best connection usage
5626// for IPv4 and IPv6.
5627void PeerConnection::ReportBestConnectionState(
5628 const cricket::TransportStats& stats) {
5629 RTC_DCHECK(metrics_observer());
Steve Antonc7b964c2018-02-01 14:39:45 -08005630 for (const cricket::TransportChannelStats& channel_stats :
5631 stats.channel_stats) {
5632 for (const cricket::ConnectionInfo& connection_info :
5633 channel_stats.connection_infos) {
5634 if (!connection_info.best_connection) {
Steve Anton75737c02017-11-06 10:37:17 -08005635 continue;
5636 }
5637
5638 PeerConnectionEnumCounterType type = kPeerConnectionEnumCounterMax;
Steve Antonc7b964c2018-02-01 14:39:45 -08005639 const cricket::Candidate& local = connection_info.local_candidate;
5640 const cricket::Candidate& remote = connection_info.remote_candidate;
Steve Anton75737c02017-11-06 10:37:17 -08005641
5642 // Increment the counter for IceCandidatePairType.
5643 if (local.protocol() == cricket::TCP_PROTOCOL_NAME ||
5644 (local.type() == RELAY_PORT_TYPE &&
5645 local.relay_protocol() == cricket::TCP_PROTOCOL_NAME)) {
5646 type = kEnumCounterIceCandidatePairTypeTcp;
5647 } else if (local.protocol() == cricket::UDP_PROTOCOL_NAME) {
5648 type = kEnumCounterIceCandidatePairTypeUdp;
5649 } else {
5650 RTC_CHECK(0);
5651 }
5652 metrics_observer()->IncrementEnumCounter(
5653 type, GetIceCandidatePairCounter(local, remote),
5654 kIceCandidatePairMax);
5655
5656 // Increment the counter for IP type.
5657 if (local.address().family() == AF_INET) {
5658 metrics_observer()->IncrementEnumCounter(
5659 kEnumCounterAddressFamily, kBestConnections_IPv4,
5660 kPeerConnectionAddressFamilyCounter_Max);
5661
5662 } else if (local.address().family() == AF_INET6) {
5663 metrics_observer()->IncrementEnumCounter(
5664 kEnumCounterAddressFamily, kBestConnections_IPv6,
5665 kPeerConnectionAddressFamilyCounter_Max);
5666 } else {
5667 RTC_CHECK(0);
5668 }
5669
5670 return;
5671 }
5672 }
5673}
5674
5675void PeerConnection::ReportNegotiatedCiphers(
Steve Antonc7b964c2018-02-01 14:39:45 -08005676 const cricket::TransportStats& stats,
5677 const std::set<cricket::MediaType>& media_types) {
Steve Anton75737c02017-11-06 10:37:17 -08005678 RTC_DCHECK(metrics_observer());
5679 if (!dtls_enabled_ || stats.channel_stats.empty()) {
5680 return;
5681 }
5682
5683 int srtp_crypto_suite = stats.channel_stats[0].srtp_crypto_suite;
5684 int ssl_cipher_suite = stats.channel_stats[0].ssl_cipher_suite;
5685 if (srtp_crypto_suite == rtc::SRTP_INVALID_CRYPTO_SUITE &&
5686 ssl_cipher_suite == rtc::TLS_NULL_WITH_NULL_NULL) {
5687 return;
5688 }
5689
Steve Antonc7b964c2018-02-01 14:39:45 -08005690 for (cricket::MediaType media_type : media_types) {
5691 PeerConnectionEnumCounterType srtp_counter_type;
5692 PeerConnectionEnumCounterType ssl_counter_type;
5693 switch (media_type) {
5694 case cricket::MEDIA_TYPE_AUDIO:
5695 srtp_counter_type = kEnumCounterAudioSrtpCipher;
5696 ssl_counter_type = kEnumCounterAudioSslCipher;
5697 break;
5698 case cricket::MEDIA_TYPE_VIDEO:
5699 srtp_counter_type = kEnumCounterVideoSrtpCipher;
5700 ssl_counter_type = kEnumCounterVideoSslCipher;
5701 break;
5702 case cricket::MEDIA_TYPE_DATA:
5703 srtp_counter_type = kEnumCounterDataSrtpCipher;
5704 ssl_counter_type = kEnumCounterDataSslCipher;
5705 break;
5706 default:
5707 RTC_NOTREACHED();
5708 continue;
5709 }
5710 if (srtp_crypto_suite != rtc::SRTP_INVALID_CRYPTO_SUITE) {
5711 metrics_observer()->IncrementSparseEnumCounter(srtp_counter_type,
5712 srtp_crypto_suite);
5713 }
5714 if (ssl_cipher_suite != rtc::TLS_NULL_WITH_NULL_NULL) {
5715 metrics_observer()->IncrementSparseEnumCounter(ssl_counter_type,
5716 ssl_cipher_suite);
5717 }
Steve Anton75737c02017-11-06 10:37:17 -08005718 }
5719}
5720
5721void PeerConnection::OnSentPacket_w(const rtc::SentPacket& sent_packet) {
5722 RTC_DCHECK(worker_thread()->IsCurrent());
5723 RTC_DCHECK(call_);
5724 call_->OnSentPacket(sent_packet);
5725}
5726
5727const std::string PeerConnection::GetTransportName(
5728 const std::string& content_name) {
5729 cricket::BaseChannel* channel = GetChannel(content_name);
Steve Anton6fec8802017-12-04 10:37:29 -08005730 if (channel) {
5731 return channel->transport_name();
Steve Anton75737c02017-11-06 10:37:17 -08005732 }
Steve Anton6fec8802017-12-04 10:37:29 -08005733 if (sctp_transport_) {
5734 RTC_DCHECK(sctp_content_name_);
5735 RTC_DCHECK(sctp_transport_name_);
5736 if (content_name == *sctp_content_name_) {
5737 return *sctp_transport_name_;
5738 }
5739 }
5740 // Return an empty string if failed to retrieve the transport name.
5741 return "";
Steve Anton75737c02017-11-06 10:37:17 -08005742}
5743
5744void PeerConnection::DestroyRtcpTransport_n(const std::string& transport_name) {
5745 RTC_DCHECK(network_thread()->IsCurrent());
5746 transport_controller_->DestroyDtlsTransport_n(
5747 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
5748}
5749
Steve Anton6fec8802017-12-04 10:37:29 -08005750void PeerConnection::DestroyTransceiverChannel(
5751 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
5752 transceiver) {
5753 RTC_DCHECK(transceiver);
Steve Anton75737c02017-11-06 10:37:17 -08005754
Steve Anton6fec8802017-12-04 10:37:29 -08005755 cricket::BaseChannel* channel = transceiver->internal()->channel();
5756 if (channel) {
5757 transceiver->internal()->SetChannel(nullptr);
5758 DestroyBaseChannel(channel);
Steve Anton75737c02017-11-06 10:37:17 -08005759 }
5760}
5761
5762void PeerConnection::DestroyDataChannel() {
Steve Anton6fec8802017-12-04 10:37:29 -08005763 if (rtp_data_channel_) {
5764 OnDataChannelDestroyed();
5765 DestroyBaseChannel(rtp_data_channel_);
5766 rtp_data_channel_ = nullptr;
5767 }
5768
5769 // Note: Cannot use rtc::Bind to create a functor to invoke because it will
5770 // grab a reference to this PeerConnection. If this is called from the
5771 // PeerConnection destructor, the RefCountedObject vtable will have already
5772 // been destroyed (since it is a subclass of PeerConnection) and using
5773 // rtc::Bind will cause "Pure virtual function called" error to appear.
5774
5775 if (sctp_transport_) {
5776 OnDataChannelDestroyed();
5777 network_thread()->Invoke<void>(RTC_FROM_HERE,
5778 [this] { DestroySctpTransport_n(); });
5779 }
5780}
5781
5782void PeerConnection::DestroyBaseChannel(cricket::BaseChannel* channel) {
5783 RTC_DCHECK(channel);
5784 RTC_DCHECK(channel->rtp_dtls_transport());
5785
5786 // Need to cache these before destroying the base channel so that we do not
5787 // access uninitialized memory.
5788 const std::string transport_name =
5789 channel->rtp_dtls_transport()->transport_name();
5790 const bool need_to_delete_rtcp = (channel->rtcp_dtls_transport() != nullptr);
5791
5792 switch (channel->media_type()) {
5793 case cricket::MEDIA_TYPE_AUDIO:
5794 channel_manager()->DestroyVoiceChannel(
5795 static_cast<cricket::VoiceChannel*>(channel));
5796 break;
5797 case cricket::MEDIA_TYPE_VIDEO:
5798 channel_manager()->DestroyVideoChannel(
5799 static_cast<cricket::VideoChannel*>(channel));
5800 break;
5801 case cricket::MEDIA_TYPE_DATA:
5802 channel_manager()->DestroyRtpDataChannel(
5803 static_cast<cricket::RtpDataChannel*>(channel));
5804 break;
5805 default:
5806 RTC_NOTREACHED() << "Unknown media type: " << channel->media_type();
5807 break;
5808 }
5809
5810 // |channel| can no longer be used.
5811
Steve Anton75737c02017-11-06 10:37:17 -08005812 transport_controller_->DestroyDtlsTransport(
5813 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5814 if (need_to_delete_rtcp) {
5815 transport_controller_->DestroyDtlsTransport(
5816 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
5817 }
5818}
5819
Harald Alvestrand89061872018-01-02 14:08:34 +01005820void PeerConnection::ClearStatsCache() {
5821 if (stats_collector_) {
5822 stats_collector_->ClearCachedStatsReport();
5823 }
5824}
5825
henrike@webrtc.org28e20752013-07-10 00:45:36 +00005826} // namespace webrtc