blob: 3578095ce30a4bb14e021f9a033278e4d0d41026 [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;
deadbeef293e9262017-01-11 12:28:30 -0800606 };
607 static_assert(sizeof(stuff_being_tested_for_equality) == sizeof(*this),
608 "Did you add something to RTCConfiguration and forget to "
609 "update operator==?");
610 return type == o.type && servers == o.servers &&
611 bundle_policy == o.bundle_policy &&
612 rtcp_mux_policy == o.rtcp_mux_policy &&
613 tcp_candidate_policy == o.tcp_candidate_policy &&
614 candidate_network_policy == o.candidate_network_policy &&
615 audio_jitter_buffer_max_packets == o.audio_jitter_buffer_max_packets &&
616 audio_jitter_buffer_fast_accelerate ==
617 o.audio_jitter_buffer_fast_accelerate &&
618 ice_connection_receiving_timeout ==
619 o.ice_connection_receiving_timeout &&
620 ice_backup_candidate_pair_ping_interval ==
621 o.ice_backup_candidate_pair_ping_interval &&
622 continual_gathering_policy == o.continual_gathering_policy &&
623 certificates == o.certificates &&
624 prioritize_most_likely_ice_candidate_pairs ==
625 o.prioritize_most_likely_ice_candidate_pairs &&
626 media_config == o.media_config && disable_ipv6 == o.disable_ipv6 &&
zhihuangb09b3f92017-03-07 14:40:51 -0800627 disable_ipv6_on_wifi == o.disable_ipv6_on_wifi &&
deadbeefd21eab32017-07-26 16:50:11 -0700628 max_ipv6_networks == o.max_ipv6_networks &&
deadbeef293e9262017-01-11 12:28:30 -0800629 enable_rtp_data_channel == o.enable_rtp_data_channel &&
deadbeef293e9262017-01-11 12:28:30 -0800630 screencast_min_bitrate == o.screencast_min_bitrate &&
631 combined_audio_video_bwe == o.combined_audio_video_bwe &&
632 enable_dtls_srtp == o.enable_dtls_srtp &&
633 ice_candidate_pool_size == o.ice_candidate_pool_size &&
634 prune_turn_ports == o.prune_turn_ports &&
635 presume_writable_when_fully_relayed ==
636 o.presume_writable_when_fully_relayed &&
637 enable_ice_renomination == o.enable_ice_renomination &&
skvlad51072462017-02-02 11:50:14 -0800638 redetermine_role_on_ice_restart == o.redetermine_role_on_ice_restart &&
Steve Anton300bf8e2017-07-14 10:13:10 -0700639 ice_check_min_interval == o.ice_check_min_interval &&
Jonas Orelandbdcee282017-10-10 14:01:40 +0200640 ice_regather_interval_range == o.ice_regather_interval_range &&
Steve Anton79e79602017-11-20 10:25:56 -0800641 turn_customizer == o.turn_customizer &&
642 sdp_semantics == o.sdp_semantics;
deadbeef293e9262017-01-11 12:28:30 -0800643}
644
645bool PeerConnectionInterface::RTCConfiguration::operator!=(
646 const PeerConnectionInterface::RTCConfiguration& o) const {
647 return !(*this == o);
deadbeef3edec7c2016-12-10 11:44:26 -0800648}
649
zhihuang8f65cdf2016-05-06 18:40:30 -0700650// Generate a RTCP CNAME when a PeerConnection is created.
651std::string GenerateRtcpCname() {
652 std::string cname;
653 if (!rtc::CreateRandomString(kRtcpCnameLength, &cname)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100654 RTC_LOG(LS_ERROR) << "Failed to generate CNAME.";
nisseeb4ca4e2017-01-12 02:24:27 -0800655 RTC_NOTREACHED();
zhihuang8f65cdf2016-05-06 18:40:30 -0700656 }
657 return cname;
658}
659
zhihuang1c378ed2017-08-17 14:10:50 -0700660bool ValidateOfferAnswerOptions(
661 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options) {
662 return IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_audio) &&
663 IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_video);
olka3c747662017-08-17 06:50:32 -0700664}
665
zhihuang1c378ed2017-08-17 14:10:50 -0700666// From |rtc_options|, fill parts of |session_options| shared by all generated
667// m= sections (in other words, nothing that involves a map/array).
668void ExtractSharedMediaSessionOptions(
669 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options,
670 cricket::MediaSessionOptions* session_options) {
671 session_options->vad_enabled = rtc_options.voice_activity_detection;
672 session_options->bundle_enabled = rtc_options.use_rtp_mux;
673}
zhihuanga77e6bb2017-08-14 18:17:48 -0700674
zhihuang1c378ed2017-08-17 14:10:50 -0700675bool ConvertConstraintsToOfferAnswerOptions(
676 const MediaConstraintsInterface* constraints,
677 PeerConnectionInterface::RTCOfferAnswerOptions* offer_answer_options) {
olka3c747662017-08-17 06:50:32 -0700678 if (!constraints) {
679 return true;
680 }
zhihuang1c378ed2017-08-17 14:10:50 -0700681
682 bool value = false;
683 size_t mandatory_constraints_satisfied = 0;
684
685 if (FindConstraint(constraints,
686 MediaConstraintsInterface::kOfferToReceiveAudio, &value,
687 &mandatory_constraints_satisfied)) {
688 offer_answer_options->offer_to_receive_audio =
689 value ? PeerConnectionInterface::RTCOfferAnswerOptions::
690 kOfferToReceiveMediaTrue
691 : 0;
692 }
693
694 if (FindConstraint(constraints,
695 MediaConstraintsInterface::kOfferToReceiveVideo, &value,
696 &mandatory_constraints_satisfied)) {
697 offer_answer_options->offer_to_receive_video =
698 value ? PeerConnectionInterface::RTCOfferAnswerOptions::
699 kOfferToReceiveMediaTrue
700 : 0;
701 }
702 if (FindConstraint(constraints,
703 MediaConstraintsInterface::kVoiceActivityDetection, &value,
704 &mandatory_constraints_satisfied)) {
705 offer_answer_options->voice_activity_detection = value;
706 }
707 if (FindConstraint(constraints, MediaConstraintsInterface::kUseRtpMux, &value,
708 &mandatory_constraints_satisfied)) {
709 offer_answer_options->use_rtp_mux = value;
710 }
711 if (FindConstraint(constraints, MediaConstraintsInterface::kIceRestart,
712 &value, &mandatory_constraints_satisfied)) {
713 offer_answer_options->ice_restart = value;
714 }
715
deadbeefab9b2d12015-10-14 11:33:11 -0700716 return mandatory_constraints_satisfied == constraints->GetMandatory().size();
717}
718
zhihuang38ede132017-06-15 12:52:32 -0700719PeerConnection::PeerConnection(PeerConnectionFactory* factory,
720 std::unique_ptr<RtcEventLog> event_log,
721 std::unique_ptr<Call> call)
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000722 : factory_(factory),
zhihuang38ede132017-06-15 12:52:32 -0700723 event_log_(std::move(event_log)),
zhihuang8f65cdf2016-05-06 18:40:30 -0700724 rtcp_cname_(GenerateRtcpCname()),
deadbeefab9b2d12015-10-14 11:33:11 -0700725 local_streams_(StreamCollection::Create()),
zhihuang38ede132017-06-15 12:52:32 -0700726 remote_streams_(StreamCollection::Create()),
727 call_(std::move(call)) {}
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000728
729PeerConnection::~PeerConnection() {
Peter Boström1a9d6152015-12-08 22:15:17 +0100730 TRACE_EVENT0("webrtc", "PeerConnection::~PeerConnection");
Steve Anton4171afb2017-11-20 10:20:22 -0800731 RTC_DCHECK_RUN_ON(signaling_thread());
732
Steve Anton8af21862017-12-15 11:20:13 -0800733 // Need to stop transceivers before destroying the stats collector because
734 // AudioRtpSender has a reference to the StatsCollector it will update when
735 // stopping.
736 for (auto transceiver : transceivers_) {
737 transceiver->Stop();
738 }
Steve Anton4171afb2017-11-20 10:20:22 -0800739
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700740 stats_.reset(nullptr);
hbosb78306a2016-12-19 05:06:57 -0800741 if (stats_collector_) {
742 stats_collector_->WaitForPendingRequest();
743 stats_collector_ = nullptr;
744 }
Steve Anton75737c02017-11-06 10:37:17 -0800745
Steve Anton8af21862017-12-15 11:20:13 -0800746 // Don't destroy BaseChannels until after stats has been cleaned up so that
747 // the last stats request can still read from the channels.
748 DestroyAllChannels();
749
Mirko Bonadei675513b2017-11-09 11:09:25 +0100750 RTC_LOG(LS_INFO) << "Session: " << session_id() << " is destroyed.";
Steve Anton75737c02017-11-06 10:37:17 -0800751
752 webrtc_session_desc_factory_.reset();
753 sctp_invoker_.reset();
754 sctp_factory_.reset();
755 transport_controller_.reset();
756
deadbeef91dd5672016-05-18 16:55:30 -0700757 // port_allocator_ lives on the network thread and should be destroyed there.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700758 network_thread()->Invoke<void>(RTC_FROM_HERE,
nisseeaabdf62017-05-05 02:23:02 -0700759 [this] { port_allocator_.reset(); });
eladalon248fd4f2017-09-06 05:18:15 -0700760 // call_ and event_log_ must be destroyed on the worker thread.
Steve Anton978b8762017-09-29 12:15:02 -0700761 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
eladalon248fd4f2017-09-06 05:18:15 -0700762 call_.reset();
763 event_log_.reset();
764 });
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000765}
766
Steve Anton8af21862017-12-15 11:20:13 -0800767void PeerConnection::DestroyAllChannels() {
Steve Anton3fe1b152017-12-12 10:20:08 -0800768 // Destroy video channels first since they may have a pointer to a voice
769 // channel.
770 for (auto transceiver : transceivers_) {
771 if (transceiver->internal()->media_type() == cricket::MEDIA_TYPE_VIDEO) {
772 DestroyTransceiverChannel(transceiver);
773 }
774 }
775 for (auto transceiver : transceivers_) {
776 if (transceiver->internal()->media_type() == cricket::MEDIA_TYPE_AUDIO) {
777 DestroyTransceiverChannel(transceiver);
778 }
779 }
780 DestroyDataChannel();
781}
782
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000783bool PeerConnection::Initialize(
buildbot@webrtc.org41451d42014-05-03 05:39:45 +0000784 const PeerConnectionInterface::RTCConfiguration& configuration,
kwibergd1fe2812016-04-27 06:47:29 -0700785 std::unique_ptr<cricket::PortAllocator> allocator,
Henrik Boströmd03c23b2016-06-01 11:44:18 +0200786 std::unique_ptr<rtc::RTCCertificateGeneratorInterface> cert_generator,
deadbeef653b8e02015-11-11 12:55:10 -0800787 PeerConnectionObserver* observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100788 TRACE_EVENT0("webrtc", "PeerConnection::Initialize");
Steve Anton038834f2017-07-14 15:59:59 -0700789
790 RTCError config_error = ValidateConfiguration(configuration);
791 if (!config_error.ok()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100792 RTC_LOG(LS_ERROR) << "Invalid configuration: " << config_error.message();
Steve Anton038834f2017-07-14 15:59:59 -0700793 return false;
794 }
795
deadbeef293e9262017-01-11 12:28:30 -0800796 if (!allocator) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100797 RTC_LOG(LS_ERROR)
798 << "PeerConnection initialized without a PortAllocator? "
799 << "This shouldn't happen if using PeerConnectionFactory.";
deadbeef293e9262017-01-11 12:28:30 -0800800 return false;
801 }
Jonas Orelandbdcee282017-10-10 14:01:40 +0200802
deadbeef653b8e02015-11-11 12:55:10 -0800803 if (!observer) {
deadbeef293e9262017-01-11 12:28:30 -0800804 // TODO(deadbeef): Why do we do this?
Mirko Bonadei675513b2017-11-09 11:09:25 +0100805 RTC_LOG(LS_ERROR) << "PeerConnection initialized without a "
806 << "PeerConnectionObserver";
deadbeef653b8e02015-11-11 12:55:10 -0800807 return false;
808 }
pthatcher@webrtc.org877ac762015-02-04 22:03:09 +0000809 observer_ = observer;
kwiberg0eb15ed2015-12-17 03:04:15 -0800810 port_allocator_ = std::move(allocator);
deadbeef653b8e02015-11-11 12:55:10 -0800811
deadbeef91dd5672016-05-18 16:55:30 -0700812 // The port allocator lives on the network thread and should be initialized
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700813 // there.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700814 if (!network_thread()->Invoke<bool>(
815 RTC_FROM_HERE, rtc::Bind(&PeerConnection::InitializePortAllocator_n,
816 this, configuration))) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000817 return false;
818 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000819
Steve Anton75737c02017-11-06 10:37:17 -0800820 // RFC 3264: The numeric value of the session id and version in the
821 // o line MUST be representable with a "64 bit signed integer".
822 // Due to this constraint session id |session_id_| is max limited to
823 // LLONG_MAX.
824 session_id_ = rtc::ToString(rtc::CreateRandomId64() & LLONG_MAX);
825 transport_controller_.reset(factory_->CreateTransportController(
826 port_allocator_.get(), configuration.redetermine_role_on_ice_restart));
827 transport_controller_->SetIceRole(cricket::ICEROLE_CONTROLLED);
828 transport_controller_->SignalConnectionState.connect(
829 this, &PeerConnection::OnTransportControllerConnectionState);
830 transport_controller_->SignalGatheringState.connect(
831 this, &PeerConnection::OnTransportControllerGatheringState);
832 transport_controller_->SignalCandidatesGathered.connect(
833 this, &PeerConnection::OnTransportControllerCandidatesGathered);
834 transport_controller_->SignalCandidatesRemoved.connect(
835 this, &PeerConnection::OnTransportControllerCandidatesRemoved);
836 transport_controller_->SignalDtlsHandshakeError.connect(
837 this, &PeerConnection::OnTransportControllerDtlsHandshakeError);
838
839 sctp_factory_ = factory_->CreateSctpTransportInternalFactory();
zhihuang29ff8442016-07-27 11:07:25 -0700840
deadbeefab9b2d12015-10-14 11:33:11 -0700841 stats_.reset(new StatsCollector(this));
hbos74e1a4f2016-09-15 23:33:01 -0700842 stats_collector_ = RTCStatsCollector::Create(this);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000843
Steve Antonba818672017-11-06 10:21:57 -0800844 configuration_ = configuration;
845
Steve Anton75737c02017-11-06 10:37:17 -0800846 const PeerConnectionFactoryInterface::Options& options = factory_->options();
847
848 transport_controller_->SetSslMaxProtocolVersion(options.ssl_max_version);
849
850 // Obtain a certificate from RTCConfiguration if any were provided (optional).
851 rtc::scoped_refptr<rtc::RTCCertificate> certificate;
852 if (!configuration.certificates.empty()) {
853 // TODO(hbos,torbjorng): Decide on certificate-selection strategy instead of
854 // just picking the first one. The decision should be made based on the DTLS
855 // handshake. The DTLS negotiations need to know about all certificates.
856 certificate = configuration.certificates[0];
857 }
858
Steve Antond25da372017-11-06 14:50:29 -0800859 transport_controller_->SetIceConfig(ParseIceConfig(configuration));
Steve Anton75737c02017-11-06 10:37:17 -0800860
861 if (options.disable_encryption) {
862 dtls_enabled_ = false;
863 } else {
864 // Enable DTLS by default if we have an identity store or a certificate.
865 dtls_enabled_ = (cert_generator || certificate);
866 // |configuration| can override the default |dtls_enabled_| value.
867 if (configuration.enable_dtls_srtp) {
868 dtls_enabled_ = *(configuration.enable_dtls_srtp);
869 }
870 }
871
872 // Enable creation of RTP data channels if the kEnableRtpDataChannels is set.
873 // It takes precendence over the disable_sctp_data_channels
874 // PeerConnectionFactoryInterface::Options.
875 if (configuration.enable_rtp_data_channel) {
876 data_channel_type_ = cricket::DCT_RTP;
877 } else {
878 // DTLS has to be enabled to use SCTP.
879 if (!options.disable_sctp_data_channels && dtls_enabled_) {
880 data_channel_type_ = cricket::DCT_SCTP;
881 }
882 }
883
884 video_options_.screencast_min_bitrate_kbps =
885 configuration.screencast_min_bitrate;
886 audio_options_.combined_audio_video_bwe =
887 configuration.combined_audio_video_bwe;
888
889 audio_options_.audio_jitter_buffer_max_packets =
Oskar Sundbom9b28a032017-11-16 10:53:30 +0100890 configuration.audio_jitter_buffer_max_packets;
Steve Anton75737c02017-11-06 10:37:17 -0800891
892 audio_options_.audio_jitter_buffer_fast_accelerate =
Oskar Sundbom9b28a032017-11-16 10:53:30 +0100893 configuration.audio_jitter_buffer_fast_accelerate;
Steve Anton75737c02017-11-06 10:37:17 -0800894
895 // Whether the certificate generator/certificate is null or not determines
896 // what PeerConnectionDescriptionFactory will do, so make sure that we give it
897 // the right instructions by clearing the variables if needed.
898 if (!dtls_enabled_) {
899 cert_generator.reset();
900 certificate = nullptr;
901 } else if (certificate) {
902 // Favor generated certificate over the certificate generator.
903 cert_generator.reset();
904 }
905
906 webrtc_session_desc_factory_.reset(new WebRtcSessionDescriptionFactory(
907 signaling_thread(), channel_manager(), this, session_id(),
908 std::move(cert_generator), certificate));
909 webrtc_session_desc_factory_->SignalCertificateReady.connect(
910 this, &PeerConnection::OnCertificateReady);
911
912 if (options.disable_encryption) {
913 webrtc_session_desc_factory_->SetSdesPolicy(cricket::SEC_DISABLED);
914 }
915
916 webrtc_session_desc_factory_->set_enable_encrypted_rtp_header_extensions(
917 options.crypto_options.enable_encrypted_rtp_header_extensions);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000918
Steve Anton4171afb2017-11-20 10:20:22 -0800919 // Add default audio/video transceivers for Plan B SDP.
920 if (!IsUnifiedPlan()) {
921 transceivers_.push_back(
922 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
923 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_AUDIO)));
924 transceivers_.push_back(
925 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
926 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_VIDEO)));
927 }
928
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000929 return true;
930}
931
Steve Anton038834f2017-07-14 15:59:59 -0700932RTCError PeerConnection::ValidateConfiguration(
933 const RTCConfiguration& config) const {
934 if (config.ice_regather_interval_range &&
935 config.continual_gathering_policy == GATHER_ONCE) {
936 return RTCError(RTCErrorType::INVALID_PARAMETER,
937 "ice_regather_interval_range specified but continual "
938 "gathering policy is GATHER_ONCE");
939 }
940 return RTCError::OK();
941}
942
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000943rtc::scoped_refptr<StreamCollectionInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000944PeerConnection::local_streams() {
deadbeefab9b2d12015-10-14 11:33:11 -0700945 return local_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000946}
947
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000948rtc::scoped_refptr<StreamCollectionInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000949PeerConnection::remote_streams() {
deadbeefab9b2d12015-10-14 11:33:11 -0700950 return remote_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000951}
952
perkj@webrtc.orgc2dd5ee2014-11-04 11:31:29 +0000953bool PeerConnection::AddStream(MediaStreamInterface* local_stream) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100954 TRACE_EVENT0("webrtc", "PeerConnection::AddStream");
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000955 if (IsClosed()) {
956 return false;
957 }
deadbeefab9b2d12015-10-14 11:33:11 -0700958 if (!CanAddLocalMediaStream(local_streams_, local_stream)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000959 return false;
960 }
deadbeefab9b2d12015-10-14 11:33:11 -0700961
962 local_streams_->AddStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -0800963 MediaStreamObserver* observer = new MediaStreamObserver(local_stream);
964 observer->SignalAudioTrackAdded.connect(this,
965 &PeerConnection::OnAudioTrackAdded);
966 observer->SignalAudioTrackRemoved.connect(
967 this, &PeerConnection::OnAudioTrackRemoved);
968 observer->SignalVideoTrackAdded.connect(this,
969 &PeerConnection::OnVideoTrackAdded);
970 observer->SignalVideoTrackRemoved.connect(
971 this, &PeerConnection::OnVideoTrackRemoved);
kwibergd1fe2812016-04-27 06:47:29 -0700972 stream_observers_.push_back(std::unique_ptr<MediaStreamObserver>(observer));
deadbeefab9b2d12015-10-14 11:33:11 -0700973
deadbeefab9b2d12015-10-14 11:33:11 -0700974 for (const auto& track : local_stream->GetAudioTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -0700975 AddAudioTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -0700976 }
977 for (const auto& track : local_stream->GetVideoTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -0700978 AddVideoTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -0700979 }
980
tommi@webrtc.org03505bc2014-07-14 20:15:26 +0000981 stats_->AddStream(local_stream);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000982 observer_->OnRenegotiationNeeded();
983 return true;
984}
985
986void PeerConnection::RemoveStream(MediaStreamInterface* local_stream) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100987 TRACE_EVENT0("webrtc", "PeerConnection::RemoveStream");
korniltsev.anatolyec390b52017-07-24 17:00:25 -0700988 if (!IsClosed()) {
989 for (const auto& track : local_stream->GetAudioTracks()) {
990 RemoveAudioTrack(track.get(), local_stream);
991 }
992 for (const auto& track : local_stream->GetVideoTracks()) {
993 RemoveVideoTrack(track.get(), local_stream);
994 }
deadbeefab9b2d12015-10-14 11:33:11 -0700995 }
deadbeefab9b2d12015-10-14 11:33:11 -0700996 local_streams_->RemoveStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -0800997 stream_observers_.erase(
998 std::remove_if(
999 stream_observers_.begin(), stream_observers_.end(),
kwibergd1fe2812016-04-27 06:47:29 -07001000 [local_stream](const std::unique_ptr<MediaStreamObserver>& observer) {
deadbeefeb459812015-12-15 19:24:43 -08001001 return observer->stream()->label().compare(local_stream->label()) ==
1002 0;
1003 }),
1004 stream_observers_.end());
deadbeefab9b2d12015-10-14 11:33:11 -07001005
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001006 if (IsClosed()) {
1007 return;
1008 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001009 observer_->OnRenegotiationNeeded();
1010}
1011
deadbeefe1f9d832016-01-14 15:35:42 -08001012rtc::scoped_refptr<RtpSenderInterface> PeerConnection::AddTrack(
1013 MediaStreamTrackInterface* track,
1014 std::vector<MediaStreamInterface*> streams) {
1015 TRACE_EVENT0("webrtc", "PeerConnection::AddTrack");
Steve Antonf9381f02017-12-14 10:23:57 -08001016 std::vector<std::string> stream_labels;
1017 for (auto* stream : streams) {
1018 if (!stream) {
1019 RTC_LOG(LS_ERROR) << "Stream list has null element.";
1020 return nullptr;
1021 }
1022 stream_labels.push_back(stream->label());
1023 }
Steve Anton2d6c76a2018-01-05 17:10:52 -08001024 auto sender_or_error = AddTrack(track, stream_labels);
Steve Antonf9381f02017-12-14 10:23:57 -08001025 if (!sender_or_error.ok()) {
deadbeefe1f9d832016-01-14 15:35:42 -08001026 return nullptr;
1027 }
Steve Antonf9381f02017-12-14 10:23:57 -08001028 return sender_or_error.MoveValue();
1029}
1030
Steve Anton2d6c76a2018-01-05 17:10:52 -08001031RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::AddTrack(
Steve Antonf9381f02017-12-14 10:23:57 -08001032 rtc::scoped_refptr<MediaStreamTrackInterface> track,
1033 const std::vector<std::string>& stream_labels) {
Steve Anton2d6c76a2018-01-05 17:10:52 -08001034 TRACE_EVENT0("webrtc", "PeerConnection::AddTrack");
Steve Antonf9381f02017-12-14 10:23:57 -08001035 if (!track) {
1036 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "Track is null.");
1037 }
1038 if (!(track->kind() == MediaStreamTrackInterface::kAudioKind ||
1039 track->kind() == MediaStreamTrackInterface::kVideoKind)) {
1040 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1041 "Track has invalid kind: " + track->kind());
1042 }
1043 // TODO(bugs.webrtc.org/7932): Support adding a track to multiple streams.
1044 if (stream_labels.size() > 1u) {
1045 LOG_AND_RETURN_ERROR(
1046 RTCErrorType::UNSUPPORTED_OPERATION,
1047 "AddTrack with more than one stream is not currently supported.");
1048 }
1049 if (IsClosed()) {
1050 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
1051 "PeerConnection is closed.");
deadbeefe1f9d832016-01-14 15:35:42 -08001052 }
Steve Anton4171afb2017-11-20 10:20:22 -08001053 if (FindSenderForTrack(track)) {
Steve Antonf9381f02017-12-14 10:23:57 -08001054 LOG_AND_RETURN_ERROR(
1055 RTCErrorType::INVALID_PARAMETER,
1056 "Sender already exists for track " + track->id() + ".");
deadbeefe1f9d832016-01-14 15:35:42 -08001057 }
Steve Antonf9381f02017-12-14 10:23:57 -08001058 // TODO(bugs.webrtc.org/7933): MediaSession expects the sender to have exactly
1059 // one stream. AddTrackInternal will return an error if there is more than one
1060 // stream, but if the caller specifies none then we need to generate a random
1061 // stream label.
1062 std::vector<std::string> adjusted_stream_labels = stream_labels;
1063 if (stream_labels.empty()) {
1064 adjusted_stream_labels.push_back(rtc::CreateRandomUuid());
1065 }
1066 RTC_DCHECK_EQ(1, adjusted_stream_labels.size());
1067 auto sender_or_error =
1068 (IsUnifiedPlan() ? AddTrackUnifiedPlan(track, adjusted_stream_labels)
1069 : AddTrackPlanB(track, adjusted_stream_labels));
1070 if (sender_or_error.ok()) {
1071 observer_->OnRenegotiationNeeded();
Steve Anton43a723a2018-01-04 15:48:17 -08001072 stats_->AddTrack(track);
Steve Antonf9381f02017-12-14 10:23:57 -08001073 }
1074 return sender_or_error;
1075}
deadbeefe1f9d832016-01-14 15:35:42 -08001076
Steve Antonf9381f02017-12-14 10:23:57 -08001077RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>>
1078PeerConnection::AddTrackPlanB(
1079 rtc::scoped_refptr<MediaStreamTrackInterface> track,
1080 const std::vector<std::string>& stream_labels) {
Steve Anton02ee47c2018-01-10 16:26:06 -08001081 cricket::MediaType media_type =
1082 (track->kind() == MediaStreamTrackInterface::kAudioKind
1083 ? cricket::MEDIA_TYPE_AUDIO
1084 : cricket::MEDIA_TYPE_VIDEO);
1085 auto new_sender = CreateSender(media_type, track, stream_labels);
deadbeefe1f9d832016-01-14 15:35:42 -08001086 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
Steve Anton02ee47c2018-01-10 16:26:06 -08001087 static_cast<AudioRtpSender*>(new_sender->internal())
Steve Anton47136dd2018-01-12 10:49:35 -08001088 ->SetMediaChannel(voice_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08001089 GetAudioTransceiver()->internal()->AddSender(new_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001090 const RtpSenderInfo* sender_info =
1091 FindSenderInfo(local_audio_sender_infos_,
1092 new_sender->internal()->stream_id(), track->id());
1093 if (sender_info) {
1094 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -08001095 }
Steve Antonf9381f02017-12-14 10:23:57 -08001096 } else {
1097 RTC_DCHECK_EQ(MediaStreamTrackInterface::kVideoKind, track->kind());
Steve Anton02ee47c2018-01-10 16:26:06 -08001098 static_cast<VideoRtpSender*>(new_sender->internal())
Steve Anton47136dd2018-01-12 10:49:35 -08001099 ->SetMediaChannel(video_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08001100 GetVideoTransceiver()->internal()->AddSender(new_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001101 const RtpSenderInfo* sender_info =
1102 FindSenderInfo(local_video_sender_infos_,
1103 new_sender->internal()->stream_id(), track->id());
1104 if (sender_info) {
1105 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -08001106 }
deadbeefe1f9d832016-01-14 15:35:42 -08001107 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001108 return rtc::scoped_refptr<RtpSenderInterface>(new_sender);
Steve Antonf9381f02017-12-14 10:23:57 -08001109}
deadbeefe1f9d832016-01-14 15:35:42 -08001110
Steve Antonf9381f02017-12-14 10:23:57 -08001111RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>>
1112PeerConnection::AddTrackUnifiedPlan(
1113 rtc::scoped_refptr<MediaStreamTrackInterface> track,
1114 const std::vector<std::string>& stream_labels) {
1115 auto transceiver = FindFirstTransceiverForAddedTrack(track);
1116 if (transceiver) {
1117 if (transceiver->direction() == RtpTransceiverDirection::kRecvOnly) {
1118 transceiver->SetDirection(RtpTransceiverDirection::kSendRecv);
1119 } else if (transceiver->direction() == RtpTransceiverDirection::kInactive) {
1120 transceiver->SetDirection(RtpTransceiverDirection::kSendOnly);
1121 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001122 transceiver->sender()->SetTrack(track);
1123 transceiver->internal()->sender_internal()->set_stream_ids(stream_labels);
Steve Antonf9381f02017-12-14 10:23:57 -08001124 } else {
1125 cricket::MediaType media_type =
1126 (track->kind() == MediaStreamTrackInterface::kAudioKind
1127 ? cricket::MEDIA_TYPE_AUDIO
1128 : cricket::MEDIA_TYPE_VIDEO);
Steve Anton02ee47c2018-01-10 16:26:06 -08001129 auto sender = CreateSender(media_type, track, stream_labels);
1130 auto receiver = CreateReceiver(media_type, rtc::CreateRandomUuid());
1131 transceiver = CreateAndAddTransceiver(sender, receiver);
Steve Antonf9381f02017-12-14 10:23:57 -08001132 transceiver->internal()->set_created_by_addtrack(true);
1133 transceiver->SetDirection(RtpTransceiverDirection::kSendRecv);
1134 }
Steve Antonf9381f02017-12-14 10:23:57 -08001135 return transceiver->sender();
1136}
1137
1138rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1139PeerConnection::FindFirstTransceiverForAddedTrack(
1140 rtc::scoped_refptr<MediaStreamTrackInterface> track) {
1141 RTC_DCHECK(track);
1142 for (auto transceiver : transceivers_) {
1143 if (!transceiver->sender()->track() &&
1144 cricket::MediaTypeToString(transceiver->internal()->media_type()) ==
1145 track->kind() &&
1146 !transceiver->internal()->has_ever_been_used_to_send()) {
1147 return transceiver;
1148 }
1149 }
1150 return nullptr;
deadbeefe1f9d832016-01-14 15:35:42 -08001151}
1152
1153bool PeerConnection::RemoveTrack(RtpSenderInterface* sender) {
1154 TRACE_EVENT0("webrtc", "PeerConnection::RemoveTrack");
Steve Antonf9381f02017-12-14 10:23:57 -08001155 return RemoveTrackInternal(sender).ok();
1156}
1157
1158RTCError PeerConnection::RemoveTrackInternal(
1159 rtc::scoped_refptr<RtpSenderInterface> sender) {
1160 if (!sender) {
1161 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "Sender is null.");
1162 }
deadbeefe1f9d832016-01-14 15:35:42 -08001163 if (IsClosed()) {
Steve Antonf9381f02017-12-14 10:23:57 -08001164 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
1165 "PeerConnection is closed.");
deadbeefe1f9d832016-01-14 15:35:42 -08001166 }
Steve Antonf9381f02017-12-14 10:23:57 -08001167 if (IsUnifiedPlan()) {
1168 auto transceiver = FindTransceiverBySender(sender);
1169 if (!transceiver || !sender->track()) {
1170 return RTCError::OK();
1171 }
1172 sender->SetTrack(nullptr);
1173 if (transceiver->direction() == RtpTransceiverDirection::kSendRecv) {
1174 transceiver->internal()->SetDirection(RtpTransceiverDirection::kRecvOnly);
1175 } else if (transceiver->direction() == RtpTransceiverDirection::kSendOnly) {
1176 transceiver->internal()->SetDirection(RtpTransceiverDirection::kInactive);
1177 }
Steve Anton4171afb2017-11-20 10:20:22 -08001178 } else {
Steve Antonf9381f02017-12-14 10:23:57 -08001179 bool removed;
1180 if (sender->media_type() == cricket::MEDIA_TYPE_AUDIO) {
1181 removed = GetAudioTransceiver()->internal()->RemoveSender(sender);
1182 } else {
1183 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, sender->media_type());
1184 removed = GetVideoTransceiver()->internal()->RemoveSender(sender);
1185 }
1186 if (!removed) {
1187 LOG_AND_RETURN_ERROR(
1188 RTCErrorType::INVALID_PARAMETER,
1189 "Couldn't find sender " + sender->id() + " to remove.");
1190 }
Steve Anton4171afb2017-11-20 10:20:22 -08001191 }
deadbeefe1f9d832016-01-14 15:35:42 -08001192 observer_->OnRenegotiationNeeded();
Steve Antonf9381f02017-12-14 10:23:57 -08001193 return RTCError::OK();
1194}
1195
1196rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1197PeerConnection::FindTransceiverBySender(
1198 rtc::scoped_refptr<RtpSenderInterface> sender) {
1199 for (auto transceiver : transceivers_) {
1200 if (transceiver->sender() == sender) {
1201 return transceiver;
1202 }
1203 }
1204 return nullptr;
deadbeefe1f9d832016-01-14 15:35:42 -08001205}
1206
Steve Anton9158ef62017-11-27 13:01:52 -08001207RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1208PeerConnection::AddTransceiver(
1209 rtc::scoped_refptr<MediaStreamTrackInterface> track) {
1210 return AddTransceiver(track, RtpTransceiverInit());
1211}
1212
1213RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1214PeerConnection::AddTransceiver(
1215 rtc::scoped_refptr<MediaStreamTrackInterface> track,
1216 const RtpTransceiverInit& init) {
1217 if (!IsUnifiedPlan()) {
1218 LOG_AND_RETURN_ERROR(
1219 RTCErrorType::INTERNAL_ERROR,
1220 "AddTransceiver only supported when Unified Plan is enabled.");
1221 }
1222 if (!track) {
1223 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "track is null");
1224 }
1225 cricket::MediaType media_type;
1226 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
1227 media_type = cricket::MEDIA_TYPE_AUDIO;
1228 } else if (track->kind() == MediaStreamTrackInterface::kVideoKind) {
1229 media_type = cricket::MEDIA_TYPE_VIDEO;
1230 } else {
1231 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1232 "Track kind is not audio or video");
1233 }
1234 return AddTransceiver(media_type, track, init);
1235}
1236
1237RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1238PeerConnection::AddTransceiver(cricket::MediaType media_type) {
1239 return AddTransceiver(media_type, RtpTransceiverInit());
1240}
1241
1242RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1243PeerConnection::AddTransceiver(cricket::MediaType media_type,
1244 const RtpTransceiverInit& init) {
1245 if (!IsUnifiedPlan()) {
1246 LOG_AND_RETURN_ERROR(
1247 RTCErrorType::INTERNAL_ERROR,
1248 "AddTransceiver only supported when Unified Plan is enabled.");
1249 }
1250 if (!(media_type == cricket::MEDIA_TYPE_AUDIO ||
1251 media_type == cricket::MEDIA_TYPE_VIDEO)) {
1252 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1253 "media type is not audio or video");
1254 }
1255 return AddTransceiver(media_type, nullptr, init);
1256}
1257
1258RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1259PeerConnection::AddTransceiver(
1260 cricket::MediaType media_type,
1261 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Steve Anton22da89f2018-01-25 13:58:07 -08001262 const RtpTransceiverInit& init,
1263 bool fire_callback) {
Steve Anton9158ef62017-11-27 13:01:52 -08001264 RTC_DCHECK((media_type == cricket::MEDIA_TYPE_AUDIO ||
1265 media_type == cricket::MEDIA_TYPE_VIDEO));
1266 if (track) {
1267 RTC_DCHECK_EQ(media_type,
1268 (track->kind() == MediaStreamTrackInterface::kAudioKind
1269 ? cricket::MEDIA_TYPE_AUDIO
1270 : cricket::MEDIA_TYPE_VIDEO));
1271 }
1272
1273 // TODO(bugs.webrtc.org/7600): Verify init.
1274
Steve Anton02ee47c2018-01-10 16:26:06 -08001275 if (init.stream_labels.size() > 1u) {
1276 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
1277 "More than one stream is not yet supported.");
Steve Antonf9381f02017-12-14 10:23:57 -08001278 }
1279
Steve Anton02ee47c2018-01-10 16:26:06 -08001280 std::vector<std::string> stream_labels = {!init.stream_labels.empty()
1281 ? init.stream_labels[0]
1282 : rtc::CreateRandomUuid()};
1283
1284 auto sender = CreateSender(media_type, track, stream_labels);
1285 auto receiver = CreateReceiver(media_type, rtc::CreateRandomUuid());
1286 auto transceiver = CreateAndAddTransceiver(sender, receiver);
1287 transceiver->internal()->set_direction(init.direction);
1288
Steve Anton22da89f2018-01-25 13:58:07 -08001289 if (fire_callback) {
1290 observer_->OnRenegotiationNeeded();
1291 }
Steve Antonf9381f02017-12-14 10:23:57 -08001292
1293 return rtc::scoped_refptr<RtpTransceiverInterface>(transceiver);
1294}
1295
Steve Anton02ee47c2018-01-10 16:26:06 -08001296rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
1297PeerConnection::CreateSender(
1298 cricket::MediaType media_type,
1299 rtc::scoped_refptr<MediaStreamTrackInterface> track,
1300 const std::vector<std::string>& stream_labels) {
Steve Anton9158ef62017-11-27 13:01:52 -08001301 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> sender;
Steve Anton02ee47c2018-01-10 16:26:06 -08001302 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
1303 RTC_DCHECK(!track ||
1304 (track->kind() == MediaStreamTrackInterface::kAudioKind));
1305 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
1306 signaling_thread(),
Steve Anton47136dd2018-01-12 10:49:35 -08001307 new AudioRtpSender(worker_thread(),
1308 static_cast<AudioTrackInterface*>(track.get()),
Steve Anton02ee47c2018-01-10 16:26:06 -08001309 stream_labels, stats_.get()));
1310 } else {
1311 RTC_DCHECK_EQ(media_type, cricket::MEDIA_TYPE_VIDEO);
1312 RTC_DCHECK(!track ||
1313 (track->kind() == MediaStreamTrackInterface::kVideoKind));
1314 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
1315 signaling_thread(),
Steve Anton47136dd2018-01-12 10:49:35 -08001316 new VideoRtpSender(worker_thread(),
1317 static_cast<VideoTrackInterface*>(track.get()),
Steve Anton02ee47c2018-01-10 16:26:06 -08001318 stream_labels));
1319 }
1320 sender->internal()->set_stream_ids(stream_labels);
1321 return sender;
1322}
1323
1324rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1325PeerConnection::CreateReceiver(cricket::MediaType media_type,
1326 const std::string& receiver_id) {
Steve Anton9158ef62017-11-27 13:01:52 -08001327 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1328 receiver;
Steve Anton9158ef62017-11-27 13:01:52 -08001329 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton9158ef62017-11-27 13:01:52 -08001330 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
Steve Anton60776752018-01-10 11:51:34 -08001331 signaling_thread(),
Steve Antond3679212018-01-17 17:41:02 -08001332 new AudioRtpReceiver(worker_thread(), receiver_id, {}));
Steve Anton9158ef62017-11-27 13:01:52 -08001333 } else {
Steve Anton02ee47c2018-01-10 16:26:06 -08001334 RTC_DCHECK_EQ(media_type, cricket::MEDIA_TYPE_VIDEO);
Steve Anton9158ef62017-11-27 13:01:52 -08001335 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
1336 signaling_thread(),
Steve Antond3679212018-01-17 17:41:02 -08001337 new VideoRtpReceiver(worker_thread(), receiver_id, {}));
Steve Anton9158ef62017-11-27 13:01:52 -08001338 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001339 return receiver;
1340}
1341
1342rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1343PeerConnection::CreateAndAddTransceiver(
1344 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> sender,
1345 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1346 receiver) {
1347 auto transceiver = RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1348 signaling_thread(), new RtpTransceiver(sender, receiver));
Steve Anton9158ef62017-11-27 13:01:52 -08001349 transceivers_.push_back(transceiver);
Steve Antonf9381f02017-12-14 10:23:57 -08001350 return transceiver;
Steve Anton9158ef62017-11-27 13:01:52 -08001351}
1352
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001353rtc::scoped_refptr<DtmfSenderInterface> PeerConnection::CreateDtmfSender(
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001354 AudioTrackInterface* track) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001355 TRACE_EVENT0("webrtc", "PeerConnection::CreateDtmfSender");
zhihuang29ff8442016-07-27 11:07:25 -07001356 if (IsClosed()) {
1357 return nullptr;
1358 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001359 if (!track) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001360 RTC_LOG(LS_ERROR) << "CreateDtmfSender - track is NULL.";
deadbeef20cb0c12017-02-01 20:27:00 -08001361 return nullptr;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001362 }
Steve Anton4171afb2017-11-20 10:20:22 -08001363 auto track_sender = FindSenderForTrack(track);
1364 if (!track_sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001365 RTC_LOG(LS_ERROR) << "CreateDtmfSender called with a non-added track.";
deadbeef20cb0c12017-02-01 20:27:00 -08001366 return nullptr;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001367 }
1368
Steve Anton4171afb2017-11-20 10:20:22 -08001369 return track_sender->GetDtmfSender();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001370}
1371
deadbeeffac06552015-11-25 11:26:01 -08001372rtc::scoped_refptr<RtpSenderInterface> PeerConnection::CreateSender(
deadbeefbd7d8f72015-12-18 16:58:44 -08001373 const std::string& kind,
1374 const std::string& stream_id) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001375 TRACE_EVENT0("webrtc", "PeerConnection::CreateSender");
zhihuang29ff8442016-07-27 11:07:25 -07001376 if (IsClosed()) {
1377 return nullptr;
1378 }
Steve Anton4171afb2017-11-20 10:20:22 -08001379
Steve Anton02ee47c2018-01-10 16:26:06 -08001380 std::vector<std::string> stream_labels;
1381 if (!stream_id.empty()) {
1382 stream_labels.push_back(stream_id);
1383 }
1384
Steve Anton4171afb2017-11-20 10:20:22 -08001385 // TODO(steveanton): Move construction of the RtpSenders to RtpTransceiver.
deadbeefa601f5c2016-06-06 14:27:39 -07001386 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender;
deadbeeffac06552015-11-25 11:26:01 -08001387 if (kind == MediaStreamTrackInterface::kAudioKind) {
Steve Anton47136dd2018-01-12 10:49:35 -08001388 auto* audio_sender = new AudioRtpSender(worker_thread(), nullptr,
1389 stream_labels, stats_.get());
1390 audio_sender->SetMediaChannel(voice_media_channel());
deadbeefa601f5c2016-06-06 14:27:39 -07001391 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton02ee47c2018-01-10 16:26:06 -08001392 signaling_thread(), audio_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001393 GetAudioTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 11:26:01 -08001394 } else if (kind == MediaStreamTrackInterface::kVideoKind) {
Steve Anton47136dd2018-01-12 10:49:35 -08001395 auto* video_sender =
1396 new VideoRtpSender(worker_thread(), nullptr, stream_labels);
1397 video_sender->SetMediaChannel(video_media_channel());
deadbeefa601f5c2016-06-06 14:27:39 -07001398 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton02ee47c2018-01-10 16:26:06 -08001399 signaling_thread(), video_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001400 GetVideoTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 11:26:01 -08001401 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001402 RTC_LOG(LS_ERROR) << "CreateSender called with invalid kind: " << kind;
Steve Anton4171afb2017-11-20 10:20:22 -08001403 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08001404 }
Steve Anton4171afb2017-11-20 10:20:22 -08001405
deadbeefe1f9d832016-01-14 15:35:42 -08001406 return new_sender;
deadbeeffac06552015-11-25 11:26:01 -08001407}
1408
deadbeef70ab1a12015-09-28 16:53:55 -07001409std::vector<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::GetSenders()
1410 const {
deadbeefa601f5c2016-06-06 14:27:39 -07001411 std::vector<rtc::scoped_refptr<RtpSenderInterface>> ret;
Steve Anton4171afb2017-11-20 10:20:22 -08001412 for (auto sender : GetSendersInternal()) {
1413 ret.push_back(sender);
deadbeefa601f5c2016-06-06 14:27:39 -07001414 }
1415 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -07001416}
1417
Steve Anton4171afb2017-11-20 10:20:22 -08001418std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1419PeerConnection::GetSendersInternal() const {
1420 std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1421 all_senders;
1422 for (auto transceiver : transceivers_) {
1423 auto senders = transceiver->internal()->senders();
1424 all_senders.insert(all_senders.end(), senders.begin(), senders.end());
1425 }
1426 return all_senders;
1427}
1428
deadbeef70ab1a12015-09-28 16:53:55 -07001429std::vector<rtc::scoped_refptr<RtpReceiverInterface>>
1430PeerConnection::GetReceivers() const {
deadbeefa601f5c2016-06-06 14:27:39 -07001431 std::vector<rtc::scoped_refptr<RtpReceiverInterface>> ret;
Steve Anton4171afb2017-11-20 10:20:22 -08001432 for (const auto& receiver : GetReceiversInternal()) {
1433 ret.push_back(receiver);
deadbeefa601f5c2016-06-06 14:27:39 -07001434 }
1435 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -07001436}
1437
Steve Anton4171afb2017-11-20 10:20:22 -08001438std::vector<
1439 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1440PeerConnection::GetReceiversInternal() const {
1441 std::vector<
1442 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1443 all_receivers;
1444 for (auto transceiver : transceivers_) {
1445 auto receivers = transceiver->internal()->receivers();
1446 all_receivers.insert(all_receivers.end(), receivers.begin(),
1447 receivers.end());
1448 }
1449 return all_receivers;
1450}
1451
Steve Anton9158ef62017-11-27 13:01:52 -08001452std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
1453PeerConnection::GetTransceivers() const {
1454 RTC_DCHECK(IsUnifiedPlan());
1455 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> all_transceivers;
1456 for (auto transceiver : transceivers_) {
1457 all_transceivers.push_back(transceiver);
1458 }
1459 return all_transceivers;
1460}
1461
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001462bool PeerConnection::GetStats(StatsObserver* observer,
wu@webrtc.orgb9a088b2014-02-13 23:18:49 +00001463 MediaStreamTrackInterface* track,
1464 StatsOutputLevel level) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001465 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
deadbeef0a6c4ca2015-10-06 11:38:28 -07001466 RTC_DCHECK(signaling_thread()->IsCurrent());
nisse7ce109a2017-01-31 00:57:56 -08001467 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001468 RTC_LOG(LS_ERROR) << "GetStats - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001469 return false;
1470 }
1471
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001472 stats_->UpdateStats(level);
zhihuange9e94c32016-11-04 11:38:15 -07001473 // The StatsCollector is used to tell if a track is valid because it may
1474 // remember tracks that the PeerConnection previously removed.
1475 if (track && !stats_->IsValidTrack(track->id())) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001476 RTC_LOG(LS_WARNING) << "GetStats is called with an invalid track: "
1477 << track->id();
zhihuange9e94c32016-11-04 11:38:15 -07001478 return false;
1479 }
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001480 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_GETSTATS,
tommi@webrtc.org5b06b062014-08-15 08:38:30 +00001481 new GetStatsMsg(observer, track));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001482 return true;
1483}
1484
hbos74e1a4f2016-09-15 23:33:01 -07001485void PeerConnection::GetStats(RTCStatsCollectorCallback* callback) {
1486 RTC_DCHECK(stats_collector_);
1487 stats_collector_->GetStatsReport(callback);
1488}
1489
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001490PeerConnectionInterface::SignalingState PeerConnection::signaling_state() {
1491 return signaling_state_;
1492}
1493
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001494PeerConnectionInterface::IceConnectionState
1495PeerConnection::ice_connection_state() {
1496 return ice_connection_state_;
1497}
1498
1499PeerConnectionInterface::IceGatheringState
1500PeerConnection::ice_gathering_state() {
1501 return ice_gathering_state_;
1502}
1503
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001504rtc::scoped_refptr<DataChannelInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001505PeerConnection::CreateDataChannel(
1506 const std::string& label,
1507 const DataChannelInit* config) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001508 TRACE_EVENT0("webrtc", "PeerConnection::CreateDataChannel");
zhihuang9763d562016-08-05 11:14:50 -07001509
deadbeefab9b2d12015-10-14 11:33:11 -07001510 bool first_datachannel = !HasDataChannels();
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001511
kwibergd1fe2812016-04-27 06:47:29 -07001512 std::unique_ptr<InternalDataChannelInit> internal_config;
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00001513 if (config) {
1514 internal_config.reset(new InternalDataChannelInit(*config));
1515 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001516 rtc::scoped_refptr<DataChannelInterface> channel(
deadbeefab9b2d12015-10-14 11:33:11 -07001517 InternalCreateDataChannel(label, internal_config.get()));
1518 if (!channel.get()) {
1519 return nullptr;
1520 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001521
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001522 // Trigger the onRenegotiationNeeded event for every new RTP DataChannel, or
1523 // the first SCTP DataChannel.
Steve Anton75737c02017-11-06 10:37:17 -08001524 if (data_channel_type() == cricket::DCT_RTP || first_datachannel) {
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001525 observer_->OnRenegotiationNeeded();
1526 }
wu@webrtc.org91053e72013-08-10 07:18:04 +00001527
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001528 return DataChannelProxy::Create(signaling_thread(), channel.get());
1529}
1530
1531void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
1532 const MediaConstraintsInterface* constraints) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001533 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
Steve Anton8d3444d2017-10-20 15:30:51 -07001534
zhihuang1c378ed2017-08-17 14:10:50 -07001535 PeerConnectionInterface::RTCOfferAnswerOptions offer_answer_options;
1536 // Always create an offer even if |ConvertConstraintsToOfferAnswerOptions|
1537 // returns false for now. Because |ConvertConstraintsToOfferAnswerOptions|
1538 // compares the mandatory fields parsed with the mandatory fields added in the
1539 // |constraints| and some downstream applications might create offers with
1540 // mandatory fields which would not be parsed in the helper method. For
1541 // example, in Chromium/remoting, |kEnableDtlsSrtp| is added to the
1542 // |constraints| as a mandatory field but it is not parsed.
1543 ConvertConstraintsToOfferAnswerOptions(constraints, &offer_answer_options);
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001544
zhihuang1c378ed2017-08-17 14:10:50 -07001545 CreateOffer(observer, offer_answer_options);
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001546}
1547
1548void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
1549 const RTCOfferAnswerOptions& options) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001550 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
Steve Anton8d3444d2017-10-20 15:30:51 -07001551
nisse7ce109a2017-01-31 00:57:56 -08001552 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001553 RTC_LOG(LS_ERROR) << "CreateOffer - observer is NULL.";
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001554 return;
1555 }
deadbeefab9b2d12015-10-14 11:33:11 -07001556
Steve Anton8d3444d2017-10-20 15:30:51 -07001557 if (IsClosed()) {
1558 std::string error = "CreateOffer called when PeerConnection is closed.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001559 RTC_LOG(LS_ERROR) << error;
Steve Anton8d3444d2017-10-20 15:30:51 -07001560 PostCreateSessionDescriptionFailure(observer, error);
1561 return;
1562 }
1563
zhihuang1c378ed2017-08-17 14:10:50 -07001564 if (!ValidateOfferAnswerOptions(options)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001565 std::string error = "CreateOffer called with invalid options.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001566 RTC_LOG(LS_ERROR) << error;
deadbeefab9b2d12015-10-14 11:33:11 -07001567 PostCreateSessionDescriptionFailure(observer, error);
1568 return;
1569 }
1570
Steve Anton22da89f2018-01-25 13:58:07 -08001571 // Legacy handling for offer_to_receive_audio and offer_to_receive_video.
1572 // Specified in WebRTC section 4.4.3.2 "Legacy configuration extensions".
1573 if (IsUnifiedPlan()) {
1574 RTCError error = HandleLegacyOfferOptions(options);
1575 if (!error.ok()) {
1576 PostCreateSessionDescriptionFailure(observer, error.message());
1577 return;
1578 }
1579 }
1580
zhihuang1c378ed2017-08-17 14:10:50 -07001581 cricket::MediaSessionOptions session_options;
1582 GetOptionsForOffer(options, &session_options);
Steve Antond25da372017-11-06 14:50:29 -08001583 webrtc_session_desc_factory_->CreateOffer(observer, options, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001584}
1585
Steve Anton22da89f2018-01-25 13:58:07 -08001586RTCError PeerConnection::HandleLegacyOfferOptions(
1587 const RTCOfferAnswerOptions& options) {
1588 RTC_DCHECK(IsUnifiedPlan());
1589
1590 if (options.offer_to_receive_audio == 0) {
1591 RemoveRecvDirectionFromReceivingTransceiversOfType(
1592 cricket::MEDIA_TYPE_AUDIO);
1593 } else if (options.offer_to_receive_audio == 1) {
1594 AddUpToOneReceivingTransceiverOfType(cricket::MEDIA_TYPE_AUDIO);
1595 } else if (options.offer_to_receive_audio > 1) {
1596 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
1597 "offer_to_receive_audio > 1 is not supported.");
1598 }
1599
1600 if (options.offer_to_receive_video == 0) {
1601 RemoveRecvDirectionFromReceivingTransceiversOfType(
1602 cricket::MEDIA_TYPE_VIDEO);
1603 } else if (options.offer_to_receive_video == 1) {
1604 AddUpToOneReceivingTransceiverOfType(cricket::MEDIA_TYPE_VIDEO);
1605 } else if (options.offer_to_receive_video > 1) {
1606 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
1607 "offer_to_receive_video > 1 is not supported.");
1608 }
1609
1610 return RTCError::OK();
1611}
1612
1613void PeerConnection::RemoveRecvDirectionFromReceivingTransceiversOfType(
1614 cricket::MediaType media_type) {
1615 for (auto transceiver : GetReceivingTransceiversOfType(media_type)) {
1616 transceiver->internal()->set_direction(
1617 RtpTransceiverDirectionWithRecvSet(transceiver->direction(), false));
1618 }
1619}
1620
1621void PeerConnection::AddUpToOneReceivingTransceiverOfType(
1622 cricket::MediaType media_type) {
1623 if (GetReceivingTransceiversOfType(media_type).empty()) {
1624 RtpTransceiverInit init;
1625 init.direction = RtpTransceiverDirection::kRecvOnly;
1626 AddTransceiver(media_type, nullptr, init, /*fire_callback=*/false);
1627 }
1628}
1629
1630std::vector<rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
1631PeerConnection::GetReceivingTransceiversOfType(cricket::MediaType media_type) {
1632 std::vector<
1633 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
1634 receiving_transceivers;
1635 for (auto transceiver : transceivers_) {
1636 if (!transceiver->stopped() &&
1637 transceiver->internal()->media_type() == media_type &&
1638 RtpTransceiverDirectionHasRecv(transceiver->direction())) {
1639 receiving_transceivers.push_back(transceiver);
1640 }
1641 }
1642 return receiving_transceivers;
1643}
1644
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001645void PeerConnection::CreateAnswer(
1646 CreateSessionDescriptionObserver* observer,
1647 const MediaConstraintsInterface* constraints) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001648 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
Steve Anton8d3444d2017-10-20 15:30:51 -07001649
nisse7ce109a2017-01-31 00:57:56 -08001650 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001651 RTC_LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001652 return;
1653 }
deadbeefab9b2d12015-10-14 11:33:11 -07001654
zhihuang1c378ed2017-08-17 14:10:50 -07001655 PeerConnectionInterface::RTCOfferAnswerOptions offer_answer_options;
1656 if (!ConvertConstraintsToOfferAnswerOptions(constraints,
1657 &offer_answer_options)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001658 std::string error = "CreateAnswer called with invalid constraints.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001659 RTC_LOG(LS_ERROR) << error;
deadbeefab9b2d12015-10-14 11:33:11 -07001660 PostCreateSessionDescriptionFailure(observer, error);
1661 return;
1662 }
1663
Steve Anton8d3444d2017-10-20 15:30:51 -07001664 CreateAnswer(observer, offer_answer_options);
htaa2a49d92016-03-04 02:51:39 -08001665}
1666
1667void PeerConnection::CreateAnswer(CreateSessionDescriptionObserver* observer,
1668 const RTCOfferAnswerOptions& options) {
1669 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
nisse7ce109a2017-01-31 00:57:56 -08001670 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001671 RTC_LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
htaa2a49d92016-03-04 02:51:39 -08001672 return;
1673 }
1674
Taylor Brandstetter94d8cce2018-01-26 22:44:21 +00001675 if (IsClosed()) {
1676 std::string error = "CreateAnswer called when PeerConnection is closed.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001677 RTC_LOG(LS_ERROR) << error;
Steve Anton8d3444d2017-10-20 15:30:51 -07001678 PostCreateSessionDescriptionFailure(observer, error);
1679 return;
1680 }
1681
Taylor Brandstetter94d8cce2018-01-26 22:44:21 +00001682 if (remote_description() &&
1683 remote_description()->GetType() != SdpType::kOffer) {
1684 std::string error = "CreateAnswer called without remote offer.";
1685 RTC_LOG(LS_ERROR) << error;
1686 PostCreateSessionDescriptionFailure(observer, error);
1687 return;
1688 }
Steve Anton8d3444d2017-10-20 15:30:51 -07001689
Steve Anton22da89f2018-01-25 13:58:07 -08001690 if (IsUnifiedPlan()) {
1691 if (options.offer_to_receive_audio != RTCOfferAnswerOptions::kUndefined) {
1692 RTC_LOG(LS_WARNING) << "CreateAnswer: offer_to_receive_audio is not "
1693 "supported with Unified Plan semantics. Use the "
1694 "RtpTransceiver API instead.";
1695 }
1696 if (options.offer_to_receive_video != RTCOfferAnswerOptions::kUndefined) {
1697 RTC_LOG(LS_WARNING) << "CreateAnswer: offer_to_receive_video is not "
1698 "supported with Unified Plan semantics. Use the "
1699 "RtpTransceiver API instead.";
1700 }
1701 }
1702
htaa2a49d92016-03-04 02:51:39 -08001703 cricket::MediaSessionOptions session_options;
zhihuang1c378ed2017-08-17 14:10:50 -07001704 GetOptionsForAnswer(options, &session_options);
htaa2a49d92016-03-04 02:51:39 -08001705
Steve Antond25da372017-11-06 14:50:29 -08001706 webrtc_session_desc_factory_->CreateAnswer(observer, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001707}
1708
1709void PeerConnection::SetLocalDescription(
1710 SetSessionDescriptionObserver* observer,
1711 SessionDescriptionInterface* desc) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001712 TRACE_EVENT0("webrtc", "PeerConnection::SetLocalDescription");
Steve Anton8a006912017-12-04 15:25:56 -08001713
nisse7ce109a2017-01-31 00:57:56 -08001714 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001715 RTC_LOG(LS_ERROR) << "SetLocalDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001716 return;
1717 }
Steve Anton8a006912017-12-04 15:25:56 -08001718
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001719 if (!desc) {
1720 PostSetSessionDescriptionFailure(observer, "SessionDescription is NULL.");
1721 return;
1722 }
Steve Anton8d3444d2017-10-20 15:30:51 -07001723
Steve Antona3a92c22017-12-07 10:27:41 -08001724 SdpType type = desc->GetType();
Steve Anton8d3444d2017-10-20 15:30:51 -07001725
Steve Anton8a006912017-12-04 15:25:56 -08001726 RTCError error = ApplyLocalDescription(rtc::WrapUnique(desc));
1727 // |desc| may be destroyed at this point.
1728
1729 if (!error.ok()) {
Steve Antona3a92c22017-12-07 10:27:41 -08001730 std::ostringstream oss;
1731 oss << "Failed to set local " << SdpTypeToString(type)
1732 << " sdp: " << error.message();
1733 std::string error_message = oss.str();
Steve Anton8a006912017-12-04 15:25:56 -08001734 RTC_LOG(LS_ERROR) << error_message << " (" << error.type() << ")";
1735 PostSetSessionDescriptionFailure(observer, std::move(error_message));
Steve Anton8d3444d2017-10-20 15:30:51 -07001736 return;
1737 }
Steve Anton8a006912017-12-04 15:25:56 -08001738 RTC_DCHECK(local_description());
1739
1740 PostSetSessionDescriptionSuccess(observer);
1741
1742 // According to JSEP, after setLocalDescription, changing the candidate pool
1743 // size is not allowed, and changing the set of ICE servers will not result
1744 // in new candidates being gathered.
1745 port_allocator_->FreezeCandidatePool();
1746
1747 // MaybeStartGathering needs to be called after posting
1748 // MSG_SET_SESSIONDESCRIPTION_SUCCESS, so that we don't signal any candidates
1749 // before signaling that SetLocalDescription completed.
1750 transport_controller_->MaybeStartGathering();
1751
Steve Antona3a92c22017-12-07 10:27:41 -08001752 if (local_description()->GetType() == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08001753 // TODO(deadbeef): We already had to hop to the network thread for
1754 // MaybeStartGathering...
1755 network_thread()->Invoke<void>(
1756 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
1757 port_allocator_.get()));
1758 }
1759}
1760
1761RTCError PeerConnection::ApplyLocalDescription(
1762 std::unique_ptr<SessionDescriptionInterface> desc) {
1763 RTC_DCHECK_RUN_ON(signaling_thread());
1764 RTC_DCHECK(desc);
1765
1766 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_LOCAL);
1767 if (!error.ok()) {
1768 return error;
1769 }
Steve Anton8d3444d2017-10-20 15:30:51 -07001770
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001771 // Update stats here so that we have the most recent stats for tracks and
1772 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001773 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 15:25:56 -08001774
1775 // Update the initial_offerer flag if this session is the initial_offerer.
Steve Anton3828c062017-12-06 10:34:51 -08001776 SdpType type = desc->GetType();
Steve Anton8a006912017-12-04 15:25:56 -08001777 if (!initial_offerer_.has_value()) {
Steve Anton3828c062017-12-06 10:34:51 -08001778 initial_offerer_.emplace(type == SdpType::kOffer);
Steve Anton8a006912017-12-04 15:25:56 -08001779 if (*initial_offerer_) {
1780 transport_controller_->SetIceRole(cricket::ICEROLE_CONTROLLING);
1781 } else {
1782 transport_controller_->SetIceRole(cricket::ICEROLE_CONTROLLED);
1783 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001784 }
Steve Anton8a006912017-12-04 15:25:56 -08001785
Steve Antondcc3c022017-12-22 16:02:54 -08001786 // Take a reference to the old local description since it's used below to
1787 // compare against the new local description. When setting the new local
1788 // description, grab ownership of the replaced session description in case it
1789 // is the same as |old_local_description|, to keep it alive for the duration
1790 // of the method.
1791 const SessionDescriptionInterface* old_local_description =
1792 local_description();
1793 std::unique_ptr<SessionDescriptionInterface> replaced_local_description;
Steve Anton3828c062017-12-06 10:34:51 -08001794 if (type == SdpType::kAnswer) {
Steve Antondcc3c022017-12-22 16:02:54 -08001795 replaced_local_description = pending_local_description_
1796 ? std::move(pending_local_description_)
1797 : std::move(current_local_description_);
Steve Anton8a006912017-12-04 15:25:56 -08001798 current_local_description_ = std::move(desc);
1799 pending_local_description_ = nullptr;
1800 current_remote_description_ = std::move(pending_remote_description_);
1801 } else {
Steve Antondcc3c022017-12-22 16:02:54 -08001802 replaced_local_description = std::move(pending_local_description_);
Steve Anton8a006912017-12-04 15:25:56 -08001803 pending_local_description_ = std::move(desc);
1804 }
1805 // The session description to apply now must be accessed by
1806 // |local_description()|.
Henrik Boströmfdb92012017-11-09 19:55:44 +01001807 RTC_DCHECK(local_description());
deadbeefab9b2d12015-10-14 11:33:11 -07001808
Steve Antondcc3c022017-12-22 16:02:54 -08001809 if (IsUnifiedPlan()) {
1810 RTCError error = UpdateTransceiversAndDataChannels(
1811 cricket::CS_LOCAL, old_local_description, *local_description());
Steve Anton8a006912017-12-04 15:25:56 -08001812 if (!error.ok()) {
1813 return error;
1814 }
Steve Antondcc3c022017-12-22 16:02:54 -08001815 for (auto transceiver : transceivers_) {
1816 const ContentInfo* content =
1817 FindMediaSectionForTransceiver(transceiver, local_description());
1818 if (!content) {
1819 continue;
1820 }
1821 const MediaContentDescription* media_desc = content->media_description();
1822 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
1823 transceiver->internal()->set_current_direction(media_desc->direction());
1824 }
1825 if (content->rejected && !transceiver->stopped()) {
1826 transceiver->Stop();
1827 }
1828 }
1829 } else {
1830 // Transport and Media channels will be created only when offer is set.
1831 if (type == SdpType::kOffer) {
1832 // TODO(bugs.webrtc.org/4676) - Handle CreateChannel failure, as new local
1833 // description is applied. Restore back to old description.
1834 RTCError error = CreateChannels(*local_description()->description());
1835 if (!error.ok()) {
1836 return error;
1837 }
1838 }
Steve Anton8a006912017-12-04 15:25:56 -08001839
Steve Antondcc3c022017-12-22 16:02:54 -08001840 // Remove unused channels if MediaContentDescription is rejected.
1841 RemoveUnusedChannels(local_description()->description());
1842 }
Steve Anton8a006912017-12-04 15:25:56 -08001843
Steve Anton3828c062017-12-06 10:34:51 -08001844 error = UpdateSessionState(type, cricket::CS_LOCAL);
Steve Anton8a006912017-12-04 15:25:56 -08001845 if (!error.ok()) {
1846 return error;
1847 }
Steve Antondcc3c022017-12-22 16:02:54 -08001848
Steve Anton8a006912017-12-04 15:25:56 -08001849 if (remote_description()) {
1850 // Now that we have a local description, we can push down remote candidates.
1851 UseCandidatesInSessionDescription(remote_description());
1852 }
1853
1854 pending_ice_restarts_.clear();
1855 if (session_error() != SessionError::kNone) {
1856 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
1857 }
1858
deadbeefab9b2d12015-10-14 11:33:11 -07001859 // If setting the description decided our SSL role, allocate any necessary
1860 // SCTP sids.
1861 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08001862 if (data_channel_type() == cricket::DCT_SCTP && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001863 AllocateSctpSids(role);
1864 }
1865
Steve Antond3679212018-01-17 17:41:02 -08001866 if (IsUnifiedPlan()) {
1867 for (auto transceiver : transceivers_) {
1868 const ContentInfo* content =
1869 FindMediaSectionForTransceiver(transceiver, local_description());
1870 if (!content) {
1871 continue;
1872 }
1873 if (content->rejected && !transceiver->stopped()) {
1874 transceiver->Stop();
1875 }
Steve Anton74255ff2018-01-24 18:32:57 -08001876 const auto& streams = content->media_description()->streams();
1877 if (!content->rejected && !streams.empty()) {
Steve Antond3679212018-01-17 17:41:02 -08001878 transceiver->internal()->sender_internal()->set_stream_ids(
Steve Anton74255ff2018-01-24 18:32:57 -08001879 {streams[0].sync_label});
Steve Antond3679212018-01-17 17:41:02 -08001880 transceiver->internal()->sender_internal()->SetSsrc(
Steve Anton74255ff2018-01-24 18:32:57 -08001881 streams[0].first_ssrc());
Steve Antond3679212018-01-17 17:41:02 -08001882 }
1883 }
1884 } else {
1885 // Plan B semantics.
1886
Steve Antondcc3c022017-12-22 16:02:54 -08001887 // Update state and SSRC of local MediaStreams and DataChannels based on the
1888 // local session description.
1889 const cricket::ContentInfo* audio_content =
1890 GetFirstAudioContent(local_description()->description());
1891 if (audio_content) {
1892 if (audio_content->rejected) {
1893 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
1894 } else {
1895 const cricket::AudioContentDescription* audio_desc =
1896 audio_content->media_description()->as_audio();
1897 UpdateLocalSenders(audio_desc->streams(), audio_desc->type());
1898 }
deadbeeffaac4972015-11-12 15:33:07 -08001899 }
deadbeefab9b2d12015-10-14 11:33:11 -07001900
Steve Antondcc3c022017-12-22 16:02:54 -08001901 const cricket::ContentInfo* video_content =
1902 GetFirstVideoContent(local_description()->description());
1903 if (video_content) {
1904 if (video_content->rejected) {
1905 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
1906 } else {
1907 const cricket::VideoContentDescription* video_desc =
1908 video_content->media_description()->as_video();
1909 UpdateLocalSenders(video_desc->streams(), video_desc->type());
1910 }
deadbeeffaac4972015-11-12 15:33:07 -08001911 }
deadbeefab9b2d12015-10-14 11:33:11 -07001912 }
1913
1914 const cricket::ContentInfo* data_content =
Henrik Boströmfdb92012017-11-09 19:55:44 +01001915 GetFirstDataContent(local_description()->description());
deadbeefab9b2d12015-10-14 11:33:11 -07001916 if (data_content) {
1917 const cricket::DataContentDescription* data_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08001918 data_content->media_description()->as_data();
deadbeefab9b2d12015-10-14 11:33:11 -07001919 if (rtc::starts_with(data_desc->protocol().data(),
1920 cricket::kMediaProtocolRtpPrefix)) {
1921 UpdateLocalRtpDataChannels(data_desc->streams());
1922 }
1923 }
1924
Steve Anton8a006912017-12-04 15:25:56 -08001925 return RTCError::OK();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001926}
1927
1928void PeerConnection::SetRemoteDescription(
Henrik Boströma4ecf552017-11-23 14:17:07 +00001929 SetSessionDescriptionObserver* observer,
1930 SessionDescriptionInterface* desc) {
Henrik Boström31638672017-11-23 17:48:32 +01001931 SetRemoteDescription(
1932 std::unique_ptr<SessionDescriptionInterface>(desc),
1933 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface>(
1934 new SetRemoteDescriptionObserverAdapter(this, observer)));
1935}
1936
1937void PeerConnection::SetRemoteDescription(
1938 std::unique_ptr<SessionDescriptionInterface> desc,
1939 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface> observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001940 TRACE_EVENT0("webrtc", "PeerConnection::SetRemoteDescription");
Steve Anton8a006912017-12-04 15:25:56 -08001941
nisse7ce109a2017-01-31 00:57:56 -08001942 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001943 RTC_LOG(LS_ERROR) << "SetRemoteDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001944 return;
1945 }
Steve Anton8a006912017-12-04 15:25:56 -08001946
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001947 if (!desc) {
Henrik Boström31638672017-11-23 17:48:32 +01001948 observer->OnSetRemoteDescriptionComplete(RTCError(
Steve Anton8a006912017-12-04 15:25:56 -08001949 RTCErrorType::INVALID_PARAMETER, "SessionDescription is NULL."));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001950 return;
1951 }
Steve Anton8d3444d2017-10-20 15:30:51 -07001952
Steve Antona3a92c22017-12-07 10:27:41 -08001953 const SdpType type = desc->GetType();
Steve Anton8a006912017-12-04 15:25:56 -08001954
1955 RTCError error = ApplyRemoteDescription(std::move(desc));
1956 // |desc| may be destroyed at this point.
1957
1958 if (!error.ok()) {
Steve Antona3a92c22017-12-07 10:27:41 -08001959 std::ostringstream oss;
1960 oss << "Failed to set remote " << SdpTypeToString(type)
1961 << " sdp: " << error.message();
1962 std::string error_message = oss.str();
Steve Anton8a006912017-12-04 15:25:56 -08001963 RTC_LOG(LS_ERROR) << error_message << " (" << error.type() << ")";
Henrik Boström31638672017-11-23 17:48:32 +01001964 observer->OnSetRemoteDescriptionComplete(
Steve Anton8a006912017-12-04 15:25:56 -08001965 RTCError(error.type(), std::move(error_message)));
Steve Anton8d3444d2017-10-20 15:30:51 -07001966 return;
1967 }
1968
Steve Antona3a92c22017-12-07 10:27:41 -08001969 if (remote_description()->GetType() == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08001970 // TODO(deadbeef): We already had to hop to the network thread for
1971 // MaybeStartGathering...
1972 network_thread()->Invoke<void>(
1973 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
1974 port_allocator_.get()));
1975 }
1976
1977 observer->OnSetRemoteDescriptionComplete(RTCError::OK());
1978}
1979
1980RTCError PeerConnection::ApplyRemoteDescription(
1981 std::unique_ptr<SessionDescriptionInterface> desc) {
1982 RTC_DCHECK_RUN_ON(signaling_thread());
1983 RTC_DCHECK(desc);
1984
1985 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_REMOTE);
1986 if (!error.ok()) {
1987 return error;
1988 }
1989
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001990 // Update stats here so that we have the most recent stats for tracks and
1991 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001992 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 15:25:56 -08001993
Steve Antondcc3c022017-12-22 16:02:54 -08001994 // Take a reference to the old remote description since it's used below to
1995 // compare against the new remote description. When setting the new remote
1996 // description, grab ownership of the replaced session description in case it
1997 // is the same as |old_remote_description|, to keep it alive for the duration
1998 // of the method.
Steve Anton8a006912017-12-04 15:25:56 -08001999 const SessionDescriptionInterface* old_remote_description =
2000 remote_description();
Steve Anton8a006912017-12-04 15:25:56 -08002001 std::unique_ptr<SessionDescriptionInterface> replaced_remote_description;
Steve Anton3828c062017-12-06 10:34:51 -08002002 SdpType type = desc->GetType();
2003 if (type == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002004 replaced_remote_description = pending_remote_description_
2005 ? std::move(pending_remote_description_)
2006 : std::move(current_remote_description_);
2007 current_remote_description_ = std::move(desc);
2008 pending_remote_description_ = nullptr;
2009 current_local_description_ = std::move(pending_local_description_);
2010 } else {
2011 replaced_remote_description = std::move(pending_remote_description_);
2012 pending_remote_description_ = std::move(desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002013 }
Steve Anton8a006912017-12-04 15:25:56 -08002014 // The session description to apply now must be accessed by
2015 // |remote_description()|.
Henrik Boströmfdb92012017-11-09 19:55:44 +01002016 RTC_DCHECK(remote_description());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002017
Steve Anton8a006912017-12-04 15:25:56 -08002018 // Transport and Media channels will be created only when offer is set.
Steve Antondcc3c022017-12-22 16:02:54 -08002019 if (IsUnifiedPlan()) {
2020 RTCError error = UpdateTransceiversAndDataChannels(
2021 cricket::CS_REMOTE, old_remote_description, *remote_description());
Steve Anton8a006912017-12-04 15:25:56 -08002022 if (!error.ok()) {
2023 return error;
2024 }
Steve Antondcc3c022017-12-22 16:02:54 -08002025 } else {
2026 if (type == SdpType::kOffer) {
2027 // TODO(bugs.webrtc.org/4676) - Handle CreateChannel failure, as new local
2028 // description is applied. Restore back to old description.
2029 RTCError error = CreateChannels(*remote_description()->description());
2030 if (!error.ok()) {
2031 return error;
2032 }
2033 }
Steve Anton8a006912017-12-04 15:25:56 -08002034
Steve Antondcc3c022017-12-22 16:02:54 -08002035 // Remove unused channels if MediaContentDescription is rejected.
2036 RemoveUnusedChannels(remote_description()->description());
2037 }
Steve Anton8a006912017-12-04 15:25:56 -08002038
2039 // NOTE: Candidates allocation will be initiated only when SetLocalDescription
2040 // is called.
Steve Anton3828c062017-12-06 10:34:51 -08002041 error = UpdateSessionState(type, cricket::CS_REMOTE);
Steve Anton8a006912017-12-04 15:25:56 -08002042 if (!error.ok()) {
2043 return error;
2044 }
2045
2046 if (local_description() &&
2047 !UseCandidatesInSessionDescription(remote_description())) {
2048 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidCandidates);
2049 }
2050
2051 if (old_remote_description) {
2052 for (const cricket::ContentInfo& content :
2053 old_remote_description->description()->contents()) {
2054 // Check if this new SessionDescription contains new ICE ufrag and
2055 // password that indicates the remote peer requests an ICE restart.
2056 // TODO(deadbeef): When we start storing both the current and pending
2057 // remote description, this should reset pending_ice_restarts and compare
2058 // against the current description.
2059 if (CheckForRemoteIceRestart(old_remote_description, remote_description(),
2060 content.name)) {
Steve Anton3828c062017-12-06 10:34:51 -08002061 if (type == SdpType::kOffer) {
Steve Anton8a006912017-12-04 15:25:56 -08002062 pending_ice_restarts_.insert(content.name);
2063 }
2064 } else {
2065 // We retain all received candidates only if ICE is not restarted.
2066 // When ICE is restarted, all previous candidates belong to an old
2067 // generation and should not be kept.
2068 // TODO(deadbeef): This goes against the W3C spec which says the remote
2069 // description should only contain candidates from the last set remote
2070 // description plus any candidates added since then. We should remove
2071 // this once we're sure it won't break anything.
2072 WebRtcSessionDescriptionFactory::CopyCandidatesFromSessionDescription(
2073 old_remote_description, content.name, mutable_remote_description());
2074 }
2075 }
2076 }
2077
2078 if (session_error() != SessionError::kNone) {
2079 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
2080 }
2081
2082 // Set the the ICE connection state to connecting since the connection may
2083 // become writable with peer reflexive candidates before any remote candidate
2084 // is signaled.
2085 // TODO(pthatcher): This is a short-term solution for crbug/446908. A real fix
2086 // is to have a new signal the indicates a change in checking state from the
2087 // transport and expose a new checking() member from transport that can be
2088 // read to determine the current checking state. The existing SignalConnecting
2089 // actually means "gathering candidates", so cannot be be used here.
Steve Antona3a92c22017-12-07 10:27:41 -08002090 if (remote_description()->GetType() != SdpType::kOffer &&
Steve Anton8a006912017-12-04 15:25:56 -08002091 ice_connection_state() == PeerConnectionInterface::kIceConnectionNew) {
2092 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
2093 }
2094
deadbeefab9b2d12015-10-14 11:33:11 -07002095 // If setting the description decided our SSL role, allocate any necessary
2096 // SCTP sids.
2097 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08002098 if (data_channel_type() == cricket::DCT_SCTP && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07002099 AllocateSctpSids(role);
2100 }
2101
Steve Antondcc3c022017-12-22 16:02:54 -08002102 if (IsUnifiedPlan()) {
Steve Antonef65ef12018-01-10 17:15:20 -08002103 std::vector<TrackEvent> track_events;
Steve Antondcc3c022017-12-22 16:02:54 -08002104 for (auto transceiver : transceivers_) {
2105 const ContentInfo* content =
2106 FindMediaSectionForTransceiver(transceiver, remote_description());
2107 if (!content) {
2108 continue;
2109 }
2110 const MediaContentDescription* media_desc = content->media_description();
2111 RtpTransceiverDirection local_direction =
2112 RtpTransceiverDirectionReversed(media_desc->direction());
2113 // From the WebRTC specification, steps 2.2.8.5/6 of section 4.4.1.6 "Set
2114 // the RTCSessionDescription: If direction is sendrecv or recvonly, and
2115 // transceiver's current direction is neither sendrecv nor recvonly,
2116 // process the addition of a remote track for the media description.
2117 if (RtpTransceiverDirectionHasRecv(local_direction) &&
2118 (!transceiver->current_direction() ||
2119 !RtpTransceiverDirectionHasRecv(
Steve Anton74255ff2018-01-24 18:32:57 -08002120 *transceiver->current_direction())) &&
2121 !media_desc->streams().empty()) {
Steve Antonef65ef12018-01-10 17:15:20 -08002122 const std::string& sync_label = media_desc->streams()[0].sync_label;
2123 rtc::scoped_refptr<MediaStreamInterface> stream =
2124 remote_streams_->find(sync_label);
2125 if (!stream) {
2126 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
2127 MediaStream::Create(sync_label));
2128 remote_streams_->AddStream(stream);
2129 }
2130 transceiver->internal()->receiver_internal()->SetStreams({stream});
2131 TrackEvent track_event;
2132 track_event.receiver = transceiver->receiver();
2133 track_event.streams = transceiver->receiver()->streams();
2134 track_events.push_back(std::move(track_event));
Steve Antondcc3c022017-12-22 16:02:54 -08002135 }
2136 // If direction is sendonly or inactive, and transceiver's current
2137 // direction is neither sendonly nor inactive, process the removal of a
2138 // remote track for the media description.
2139 if (!RtpTransceiverDirectionHasRecv(local_direction) &&
Steve Antonef65ef12018-01-10 17:15:20 -08002140 (transceiver->current_direction() &&
Steve Antondcc3c022017-12-22 16:02:54 -08002141 RtpTransceiverDirectionHasRecv(*transceiver->current_direction()))) {
Steve Antonef65ef12018-01-10 17:15:20 -08002142 transceiver->internal()->receiver_internal()->SetStreams({});
Steve Antondcc3c022017-12-22 16:02:54 -08002143 }
2144 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
2145 transceiver->internal()->set_current_direction(local_direction);
2146 }
2147 if (content->rejected && !transceiver->stopped()) {
2148 transceiver->Stop();
2149 }
Steve Anton74255ff2018-01-24 18:32:57 -08002150 if (!content->rejected && !media_desc->streams().empty()) {
Steve Antond3679212018-01-17 17:41:02 -08002151 const auto& stream = content->media_description()->streams()[0];
2152 transceiver->internal()->receiver_internal()->SetupMediaChannel(
2153 stream.first_ssrc());
2154 }
Steve Antondcc3c022017-12-22 16:02:54 -08002155 }
Steve Antonef65ef12018-01-10 17:15:20 -08002156 for (auto event : track_events) {
2157 observer_->OnAddTrack(event.receiver, event.streams);
2158 }
Steve Antondcc3c022017-12-22 16:02:54 -08002159 }
2160
Henrik Boströmfdb92012017-11-09 19:55:44 +01002161 const cricket::ContentInfo* audio_content =
2162 GetFirstAudioContent(remote_description()->description());
2163 const cricket::ContentInfo* video_content =
2164 GetFirstVideoContent(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002165 const cricket::AudioContentDescription* audio_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002166 GetFirstAudioContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002167 const cricket::VideoContentDescription* video_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002168 GetFirstVideoContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002169 const cricket::DataContentDescription* data_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002170 GetFirstDataContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002171
2172 // Check if the descriptions include streams, just in case the peer supports
2173 // MSID, but doesn't indicate so with "a=msid-semantic".
Henrik Boströmfdb92012017-11-09 19:55:44 +01002174 if (remote_description()->description()->msid_supported() ||
deadbeefbda7e0b2015-12-08 17:13:40 -08002175 (audio_desc && !audio_desc->streams().empty()) ||
2176 (video_desc && !video_desc->streams().empty())) {
2177 remote_peer_supports_msid_ = true;
2178 }
deadbeefab9b2d12015-10-14 11:33:11 -07002179
2180 // We wait to signal new streams until we finish processing the description,
2181 // since only at that point will new streams have all their tracks.
2182 rtc::scoped_refptr<StreamCollection> new_streams(StreamCollection::Create());
2183
Steve Antondcc3c022017-12-22 16:02:54 -08002184 if (!IsUnifiedPlan()) {
2185 // TODO(steveanton): When removing RTP senders/receivers in response to a
2186 // rejected media section, there is some cleanup logic that expects the
2187 // voice/ video channel to still be set. But in this method the voice/video
2188 // channel would have been destroyed by the SetRemoteDescription caller
2189 // above so the cleanup that relies on them fails to run. The RemoveSenders
2190 // calls should be moved to right before the DestroyChannel calls to fix
2191 // this.
Steve Anton8d3444d2017-10-20 15:30:51 -07002192
Steve Antondcc3c022017-12-22 16:02:54 -08002193 // Find all audio rtp streams and create corresponding remote AudioTracks
2194 // and MediaStreams.
2195 if (audio_content) {
2196 if (audio_content->rejected) {
2197 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
2198 } else {
2199 bool default_audio_track_needed =
2200 !remote_peer_supports_msid_ &&
2201 RtpTransceiverDirectionHasSend(audio_desc->direction());
2202 UpdateRemoteSendersList(GetActiveStreams(audio_desc),
2203 default_audio_track_needed, audio_desc->type(),
2204 new_streams);
2205 }
deadbeeffaac4972015-11-12 15:33:07 -08002206 }
deadbeefab9b2d12015-10-14 11:33:11 -07002207
Steve Antondcc3c022017-12-22 16:02:54 -08002208 // Find all video rtp streams and create corresponding remote VideoTracks
2209 // and MediaStreams.
2210 if (video_content) {
2211 if (video_content->rejected) {
2212 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
2213 } else {
2214 bool default_video_track_needed =
2215 !remote_peer_supports_msid_ &&
2216 RtpTransceiverDirectionHasSend(video_desc->direction());
2217 UpdateRemoteSendersList(GetActiveStreams(video_desc),
2218 default_video_track_needed, video_desc->type(),
2219 new_streams);
2220 }
deadbeeffaac4972015-11-12 15:33:07 -08002221 }
deadbeefab9b2d12015-10-14 11:33:11 -07002222
Steve Antondcc3c022017-12-22 16:02:54 -08002223 // Update the DataChannels with the information from the remote peer.
2224 if (data_desc) {
2225 if (rtc::starts_with(data_desc->protocol().data(),
2226 cricket::kMediaProtocolRtpPrefix)) {
2227 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
2228 }
deadbeefab9b2d12015-10-14 11:33:11 -07002229 }
deadbeefab9b2d12015-10-14 11:33:11 -07002230
Steve Antondcc3c022017-12-22 16:02:54 -08002231 // Iterate new_streams and notify the observer about new MediaStreams.
2232 for (size_t i = 0; i < new_streams->count(); ++i) {
2233 MediaStreamInterface* new_stream = new_streams->at(i);
2234 stats_->AddStream(new_stream);
2235 observer_->OnAddStream(
2236 rtc::scoped_refptr<MediaStreamInterface>(new_stream));
2237 }
deadbeefab9b2d12015-10-14 11:33:11 -07002238
Steve Antondcc3c022017-12-22 16:02:54 -08002239 UpdateEndedRemoteMediaStreams();
2240 }
deadbeefab9b2d12015-10-14 11:33:11 -07002241
Steve Anton8a006912017-12-04 15:25:56 -08002242 return RTCError::OK();
deadbeeffc648b62015-10-13 16:42:33 -07002243}
2244
Steve Antondcc3c022017-12-22 16:02:54 -08002245RTCError PeerConnection::UpdateTransceiversAndDataChannels(
2246 cricket::ContentSource source,
2247 const SessionDescriptionInterface* old_session,
2248 const SessionDescriptionInterface& new_session) {
2249 RTC_DCHECK(IsUnifiedPlan());
2250
Steve Anton7464fca2018-01-19 11:10:37 -08002251 const cricket::ContentGroup* bundle_group = nullptr;
2252 if (new_session.GetType() == SdpType::kOffer) {
2253 auto bundle_group_or_error =
2254 GetEarlyBundleGroup(*new_session.description());
2255 if (!bundle_group_or_error.ok()) {
2256 return bundle_group_or_error.MoveError();
2257 }
2258 bundle_group = bundle_group_or_error.MoveValue();
Steve Antondcc3c022017-12-22 16:02:54 -08002259 }
Steve Antondcc3c022017-12-22 16:02:54 -08002260
2261 const ContentInfos& old_contents =
2262 (old_session ? old_session->description()->contents() : ContentInfos());
2263 const ContentInfos& new_contents = new_session.description()->contents();
2264
2265 for (size_t i = 0; i < new_contents.size(); ++i) {
2266 const cricket::ContentInfo& new_content = new_contents[i];
2267 const cricket::ContentInfo* old_content =
2268 (i < old_contents.size() ? &old_contents[i] : nullptr);
2269 cricket::MediaType media_type = new_content.media_description()->type();
2270 seen_mids_.insert(new_content.name);
2271 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
2272 media_type == cricket::MEDIA_TYPE_VIDEO) {
2273 auto transceiver_or_error =
2274 AssociateTransceiver(source, i, new_content, old_content);
2275 if (!transceiver_or_error.ok()) {
2276 return transceiver_or_error.MoveError();
2277 }
2278 auto transceiver = transceiver_or_error.MoveValue();
Steve Antondcc3c022017-12-22 16:02:54 -08002279 RTCError error =
2280 UpdateTransceiverChannel(transceiver, new_content, bundle_group);
2281 if (!error.ok()) {
2282 return error;
2283 }
2284 } else if (media_type == cricket::MEDIA_TYPE_DATA) {
Steve Antonfa2260d2017-12-28 16:38:23 -08002285 if (GetDataMid() && new_content.name != *GetDataMid()) {
2286 // Ignore all but the first data section.
2287 continue;
2288 }
2289 RTCError error = UpdateDataChannel(source, new_content, bundle_group);
2290 if (!error.ok()) {
2291 return error;
2292 }
Steve Antondcc3c022017-12-22 16:02:54 -08002293 } else {
2294 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
2295 "Unknown section type.");
2296 }
2297 }
2298
2299 return RTCError::OK();
2300}
2301
2302RTCError PeerConnection::UpdateTransceiverChannel(
2303 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2304 transceiver,
2305 const cricket::ContentInfo& content,
2306 const cricket::ContentGroup* bundle_group) {
2307 RTC_DCHECK(IsUnifiedPlan());
2308 RTC_DCHECK(transceiver);
2309 cricket::BaseChannel* channel = transceiver->internal()->channel();
2310 if (content.rejected) {
2311 if (channel) {
2312 transceiver->internal()->SetChannel(nullptr);
2313 DestroyBaseChannel(channel);
2314 }
2315 } else {
2316 if (!channel) {
2317 if (transceiver->internal()->media_type() == cricket::MEDIA_TYPE_AUDIO) {
2318 channel = CreateVoiceChannel(
2319 content.name,
2320 GetTransportNameForMediaSection(content.name, bundle_group));
2321 } else {
2322 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO,
2323 transceiver->internal()->media_type());
2324 channel = CreateVideoChannel(
2325 content.name,
2326 GetTransportNameForMediaSection(content.name, bundle_group));
2327 }
2328 if (!channel) {
2329 LOG_AND_RETURN_ERROR(
2330 RTCErrorType::INTERNAL_ERROR,
2331 "Failed to create channel for mid=" + content.name);
2332 }
2333 transceiver->internal()->SetChannel(channel);
2334 }
2335 }
2336 return RTCError::OK();
2337}
2338
Steve Antonfa2260d2017-12-28 16:38:23 -08002339RTCError PeerConnection::UpdateDataChannel(
2340 cricket::ContentSource source,
2341 const cricket::ContentInfo& content,
2342 const cricket::ContentGroup* bundle_group) {
2343 if (data_channel_type_ == cricket::DCT_NONE) {
Steve Antondbf9d032018-01-19 15:23:40 -08002344 // If data channels are disabled, ignore this media section. CreateAnswer
2345 // will take care of rejecting it.
2346 return RTCError::OK();
Steve Antonfa2260d2017-12-28 16:38:23 -08002347 }
2348 if (content.rejected) {
2349 DestroyDataChannel();
2350 } else {
2351 if (!rtp_data_channel_ && !sctp_transport_) {
2352 if (!CreateDataChannel(content.name, GetTransportNameForMediaSection(
2353 content.name, bundle_group))) {
2354 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
2355 "Failed to create data channel.");
2356 }
2357 }
2358 if (source == cricket::CS_REMOTE) {
2359 const MediaContentDescription* data_desc = content.media_description();
2360 if (data_desc && cricket::IsRtpProtocol(data_desc->protocol())) {
2361 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
2362 }
2363 }
2364 }
2365 return RTCError::OK();
2366}
2367
Steve Antondcc3c022017-12-22 16:02:54 -08002368RTCErrorOr<rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
2369PeerConnection::AssociateTransceiver(cricket::ContentSource source,
2370 size_t mline_index,
2371 const ContentInfo& content,
2372 const ContentInfo* old_content) {
2373 RTC_DCHECK(IsUnifiedPlan());
2374 // If the m= section is being recycled (rejected in previous remote
2375 // description, not rejected in current description), dissociate the currently
2376 // associated RtpTransceiver by setting its mid property to null, and discard
2377 // the mapping between the transceiver and its m= section index.
2378 if (old_content && old_content->rejected && !content.rejected) {
2379 auto old_transceiver = GetAssociatedTransceiver(old_content->name);
2380 if (old_transceiver) {
2381 old_transceiver->internal()->set_mid(rtc::nullopt);
2382 old_transceiver->internal()->set_mline_index(rtc::nullopt);
2383 }
2384 }
2385 const MediaContentDescription* media_desc = content.media_description();
2386 auto transceiver = GetAssociatedTransceiver(content.name);
2387 if (source == cricket::CS_LOCAL) {
2388 // Find the RtpTransceiver that corresponds to this m= section, using the
2389 // mapping between transceivers and m= section indices established when
2390 // creating the offer.
2391 if (!transceiver) {
2392 transceiver = GetTransceiverByMLineIndex(mline_index);
2393 }
2394 if (!transceiver) {
2395 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2396 "Unknown transceiver");
2397 }
2398 } else {
2399 RTC_DCHECK_EQ(source, cricket::CS_REMOTE);
2400 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers
2401 // of the same type...
2402 if (!transceiver &&
2403 RtpTransceiverDirectionHasRecv(media_desc->direction())) {
2404 transceiver = FindAvailableTransceiverToReceive(media_desc->type());
2405 }
2406 // If no RtpTransceiver was found in the previous step, create one with a
2407 // recvonly direction.
2408 if (!transceiver) {
Steve Anton02ee47c2018-01-10 16:26:06 -08002409 auto sender =
2410 CreateSender(media_desc->type(), nullptr, {rtc::CreateRandomUuid()});
2411 auto receiver =
2412 CreateReceiver(media_desc->type(), media_desc->streams()[0].id);
2413 transceiver = CreateAndAddTransceiver(sender, receiver);
Steve Antondcc3c022017-12-22 16:02:54 -08002414 transceiver->internal()->set_direction(
2415 RtpTransceiverDirection::kRecvOnly);
2416 }
2417 }
2418 RTC_DCHECK(transceiver);
2419 if (transceiver->internal()->media_type() != media_desc->type()) {
2420 LOG_AND_RETURN_ERROR(
2421 RTCErrorType::INVALID_PARAMETER,
2422 "Transceiver type does not match media description type.");
2423 }
2424 // Associate the found or created RtpTransceiver with the m= section by
2425 // setting the value of the RtpTransceiver's mid property to the MID of the m=
2426 // section, and establish a mapping between the transceiver and the index of
2427 // the m= section.
2428 transceiver->internal()->set_mid(content.name);
2429 transceiver->internal()->set_mline_index(mline_index);
2430 return std::move(transceiver);
2431}
2432
2433rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2434PeerConnection::GetAssociatedTransceiver(const std::string& mid) const {
2435 RTC_DCHECK(IsUnifiedPlan());
2436 for (auto transceiver : transceivers_) {
2437 if (transceiver->mid() == mid) {
2438 return transceiver;
2439 }
2440 }
2441 return nullptr;
2442}
2443
2444rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2445PeerConnection::GetTransceiverByMLineIndex(size_t mline_index) const {
2446 RTC_DCHECK(IsUnifiedPlan());
2447 for (auto transceiver : transceivers_) {
2448 if (transceiver->internal()->mline_index() == mline_index) {
2449 return transceiver;
2450 }
2451 }
2452 return nullptr;
2453}
2454
2455rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2456PeerConnection::FindAvailableTransceiverToReceive(
2457 cricket::MediaType media_type) const {
2458 RTC_DCHECK(IsUnifiedPlan());
2459 // From JSEP section 5.10 (Applying a Remote Description):
2460 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers of
2461 // the same type that were added to the PeerConnection by addTrack and are not
2462 // associated with any m= section and are not stopped, find the first such
2463 // RtpTransceiver.
2464 for (auto transceiver : transceivers_) {
2465 if (transceiver->internal()->media_type() == media_type &&
2466 transceiver->internal()->created_by_addtrack() && !transceiver->mid() &&
2467 !transceiver->stopped()) {
2468 return transceiver;
2469 }
2470 }
2471 return nullptr;
2472}
2473
Steve Antoned10bd92017-12-05 10:52:59 -08002474const cricket::ContentInfo* PeerConnection::FindMediaSectionForTransceiver(
2475 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2476 transceiver,
2477 const SessionDescriptionInterface* sdesc) const {
2478 RTC_DCHECK(transceiver);
2479 RTC_DCHECK(sdesc);
2480 if (IsUnifiedPlan()) {
2481 if (!transceiver->internal()->mid()) {
2482 // This transceiver is not associated with a media section yet.
2483 return nullptr;
2484 }
2485 return sdesc->description()->GetContentByName(
2486 *transceiver->internal()->mid());
2487 } else {
2488 // Plan B only allows at most one audio and one video section, so use the
2489 // first media section of that type.
2490 return cricket::GetFirstMediaContent(sdesc->description()->contents(),
2491 transceiver->internal()->media_type());
2492 }
2493}
2494
deadbeef46c73892016-11-16 19:42:04 -08002495PeerConnectionInterface::RTCConfiguration PeerConnection::GetConfiguration() {
2496 return configuration_;
2497}
2498
deadbeef293e9262017-01-11 12:28:30 -08002499bool PeerConnection::SetConfiguration(const RTCConfiguration& configuration,
2500 RTCError* error) {
Peter Boström1a9d6152015-12-08 22:15:17 +01002501 TRACE_EVENT0("webrtc", "PeerConnection::SetConfiguration");
deadbeef6de92f92016-12-12 18:49:32 -08002502
Steve Anton75737c02017-11-06 10:37:17 -08002503 if (local_description() && configuration.ice_candidate_pool_size !=
2504 configuration_.ice_candidate_pool_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002505 RTC_LOG(LS_ERROR) << "Can't change candidate pool size after calling "
2506 "SetLocalDescription.";
deadbeef293e9262017-01-11 12:28:30 -08002507 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00002508 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002509
deadbeef293e9262017-01-11 12:28:30 -08002510 // The simplest (and most future-compatible) way to tell if the config was
2511 // modified in an invalid way is to copy each property we do support
2512 // modifying, then use operator==. There are far more properties we don't
2513 // support modifying than those we do, and more could be added.
2514 RTCConfiguration modified_config = configuration_;
2515 modified_config.servers = configuration.servers;
2516 modified_config.type = configuration.type;
2517 modified_config.ice_candidate_pool_size =
2518 configuration.ice_candidate_pool_size;
2519 modified_config.prune_turn_ports = configuration.prune_turn_ports;
skvladd1f5fda2017-02-03 16:54:05 -08002520 modified_config.ice_check_min_interval = configuration.ice_check_min_interval;
Jonas Orelandbdcee282017-10-10 14:01:40 +02002521 modified_config.turn_customizer = configuration.turn_customizer;
deadbeef293e9262017-01-11 12:28:30 -08002522 if (configuration != modified_config) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002523 RTC_LOG(LS_ERROR) << "Modifying the configuration in an unsupported way.";
deadbeef293e9262017-01-11 12:28:30 -08002524 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
2525 }
2526
Steve Anton038834f2017-07-14 15:59:59 -07002527 // Validate the modified configuration.
2528 RTCError validate_error = ValidateConfiguration(modified_config);
2529 if (!validate_error.ok()) {
2530 return SafeSetError(std::move(validate_error), error);
2531 }
2532
deadbeef293e9262017-01-11 12:28:30 -08002533 // Note that this isn't possible through chromium, since it's an unsigned
2534 // short in WebIDL.
2535 if (configuration.ice_candidate_pool_size < 0 ||
2536 configuration.ice_candidate_pool_size > UINT16_MAX) {
2537 return SafeSetError(RTCErrorType::INVALID_RANGE, error);
2538 }
2539
2540 // Parse ICE servers before hopping to network thread.
2541 cricket::ServerAddresses stun_servers;
2542 std::vector<cricket::RelayServerConfig> turn_servers;
2543 RTCErrorType parse_error =
2544 ParseIceServers(configuration.servers, &stun_servers, &turn_servers);
2545 if (parse_error != RTCErrorType::NONE) {
2546 return SafeSetError(parse_error, error);
2547 }
2548
2549 // In theory this shouldn't fail.
2550 if (!network_thread()->Invoke<bool>(
2551 RTC_FROM_HERE,
2552 rtc::Bind(&PeerConnection::ReconfigurePortAllocator_n, this,
2553 stun_servers, turn_servers, modified_config.type,
2554 modified_config.ice_candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02002555 modified_config.prune_turn_ports,
2556 modified_config.turn_customizer))) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002557 RTC_LOG(LS_ERROR) << "Failed to apply configuration to PortAllocator.";
deadbeef293e9262017-01-11 12:28:30 -08002558 return SafeSetError(RTCErrorType::INTERNAL_ERROR, error);
2559 }
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07002560
deadbeefd1a38b52016-12-10 13:15:33 -08002561 // As described in JSEP, calling setConfiguration with new ICE servers or
2562 // candidate policy must set a "needs-ice-restart" bit so that the next offer
2563 // triggers an ICE restart which will pick up the changes.
deadbeef293e9262017-01-11 12:28:30 -08002564 if (modified_config.servers != configuration_.servers ||
2565 modified_config.type != configuration_.type ||
2566 modified_config.prune_turn_ports != configuration_.prune_turn_ports) {
Steve Antond25da372017-11-06 14:50:29 -08002567 transport_controller_->SetNeedsIceRestartFlag();
deadbeefd1a38b52016-12-10 13:15:33 -08002568 }
skvladd1f5fda2017-02-03 16:54:05 -08002569
2570 if (modified_config.ice_check_min_interval !=
2571 configuration_.ice_check_min_interval) {
Steve Antond25da372017-11-06 14:50:29 -08002572 transport_controller_->SetIceConfig(ParseIceConfig(modified_config));
skvladd1f5fda2017-02-03 16:54:05 -08002573 }
2574
deadbeef293e9262017-01-11 12:28:30 -08002575 configuration_ = modified_config;
2576 return SafeSetError(RTCErrorType::NONE, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00002577}
2578
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002579bool PeerConnection::AddIceCandidate(
2580 const IceCandidateInterface* ice_candidate) {
Peter Boström1a9d6152015-12-08 22:15:17 +01002581 TRACE_EVENT0("webrtc", "PeerConnection::AddIceCandidate");
zhihuang29ff8442016-07-27 11:07:25 -07002582 if (IsClosed()) {
2583 return false;
2584 }
Steve Antond25da372017-11-06 14:50:29 -08002585
2586 if (!remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002587 RTC_LOG(LS_ERROR) << "ProcessIceMessage: ICE candidates can't be added "
2588 << "without any remote session description.";
Steve Antond25da372017-11-06 14:50:29 -08002589 return false;
2590 }
2591
2592 if (!ice_candidate) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002593 RTC_LOG(LS_ERROR) << "ProcessIceMessage: Candidate is NULL.";
Steve Antond25da372017-11-06 14:50:29 -08002594 return false;
2595 }
2596
2597 bool valid = false;
2598 bool ready = ReadyToUseRemoteCandidate(ice_candidate, nullptr, &valid);
2599 if (!valid) {
2600 return false;
2601 }
2602
2603 // Add this candidate to the remote session description.
2604 if (!mutable_remote_description()->AddCandidate(ice_candidate)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002605 RTC_LOG(LS_ERROR) << "ProcessIceMessage: Candidate cannot be used.";
Steve Antond25da372017-11-06 14:50:29 -08002606 return false;
2607 }
2608
2609 if (ready) {
2610 return UseCandidate(ice_candidate);
2611 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002612 RTC_LOG(LS_INFO) << "ProcessIceMessage: Not ready to use candidate.";
Steve Antond25da372017-11-06 14:50:29 -08002613 return true;
2614 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002615}
2616
Honghai Zhang7fb69db2016-03-14 11:59:18 -07002617bool PeerConnection::RemoveIceCandidates(
2618 const std::vector<cricket::Candidate>& candidates) {
2619 TRACE_EVENT0("webrtc", "PeerConnection::RemoveIceCandidates");
Steve Antond25da372017-11-06 14:50:29 -08002620 if (!remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002621 RTC_LOG(LS_ERROR) << "RemoveRemoteIceCandidates: ICE candidates can't be "
2622 << "removed without any remote session description.";
Steve Antond25da372017-11-06 14:50:29 -08002623 return false;
2624 }
2625
2626 if (candidates.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002627 RTC_LOG(LS_ERROR) << "RemoveRemoteIceCandidates: candidates are empty.";
Steve Antond25da372017-11-06 14:50:29 -08002628 return false;
2629 }
2630
2631 size_t number_removed =
2632 mutable_remote_description()->RemoveCandidates(candidates);
2633 if (number_removed != candidates.size()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002634 RTC_LOG(LS_ERROR)
2635 << "RemoveRemoteIceCandidates: Failed to remove candidates. "
2636 << "Requested " << candidates.size() << " but only " << number_removed
2637 << " are removed.";
Steve Antond25da372017-11-06 14:50:29 -08002638 }
2639
2640 // Remove the candidates from the transport controller.
2641 std::string error;
2642 bool res = transport_controller_->RemoveRemoteCandidates(candidates, &error);
2643 if (!res && !error.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002644 RTC_LOG(LS_ERROR) << "Error when removing remote candidates: " << error;
Steve Antond25da372017-11-06 14:50:29 -08002645 }
2646 return true;
Honghai Zhang7fb69db2016-03-14 11:59:18 -07002647}
2648
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00002649void PeerConnection::RegisterUMAObserver(UMAObserver* observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +01002650 TRACE_EVENT0("webrtc", "PeerConnection::RegisterUmaObserver");
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00002651 uma_observer_ = observer;
guoweis@webrtc.org7169afd2014-12-04 17:59:29 +00002652
Steve Anton75737c02017-11-06 10:37:17 -08002653 if (transport_controller()) {
2654 transport_controller()->SetMetricsObserver(uma_observer_);
guoweis@webrtc.org7169afd2014-12-04 17:59:29 +00002655 }
2656
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00002657 // Send information about IPv4/IPv6 status.
deadbeef293e9262017-01-11 12:28:30 -08002658 if (uma_observer_) {
Honghai Zhangd93f50c2016-10-05 11:47:22 -07002659 port_allocator_->SetMetricsObserver(uma_observer_);
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00002660 if (port_allocator_->flags() & cricket::PORTALLOCATOR_ENABLE_IPV6) {
Guo-wei Shiehdfbe6792015-09-03 17:12:07 -07002661 uma_observer_->IncrementEnumCounter(
2662 kEnumCounterAddressFamily, kPeerConnection_IPv6,
2663 kPeerConnectionAddressFamilyCounter_Max);
mallinath@webrtc.orgb445f262014-05-23 22:19:37 +00002664 } else {
Guo-wei Shiehdfbe6792015-09-03 17:12:07 -07002665 uma_observer_->IncrementEnumCounter(
2666 kEnumCounterAddressFamily, kPeerConnection_IPv4,
2667 kPeerConnectionAddressFamilyCounter_Max);
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00002668 }
2669 }
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00002670}
2671
zstein4b979802017-06-02 14:37:37 -07002672RTCError PeerConnection::SetBitrate(const BitrateParameters& bitrate) {
Steve Anton978b8762017-09-29 12:15:02 -07002673 if (!worker_thread()->IsCurrent()) {
2674 return worker_thread()->Invoke<RTCError>(
zstein4b979802017-06-02 14:37:37 -07002675 RTC_FROM_HERE, rtc::Bind(&PeerConnection::SetBitrate, this, bitrate));
2676 }
2677
2678 const bool has_min = static_cast<bool>(bitrate.min_bitrate_bps);
2679 const bool has_current = static_cast<bool>(bitrate.current_bitrate_bps);
2680 const bool has_max = static_cast<bool>(bitrate.max_bitrate_bps);
2681 if (has_min && *bitrate.min_bitrate_bps < 0) {
2682 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2683 "min_bitrate_bps <= 0");
2684 }
2685 if (has_current) {
2686 if (has_min && *bitrate.current_bitrate_bps < *bitrate.min_bitrate_bps) {
2687 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2688 "current_bitrate_bps < min_bitrate_bps");
2689 } else if (*bitrate.current_bitrate_bps < 0) {
2690 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2691 "curent_bitrate_bps < 0");
2692 }
2693 }
2694 if (has_max) {
2695 if (has_current &&
2696 *bitrate.max_bitrate_bps < *bitrate.current_bitrate_bps) {
2697 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2698 "max_bitrate_bps < current_bitrate_bps");
2699 } else if (has_min && *bitrate.max_bitrate_bps < *bitrate.min_bitrate_bps) {
2700 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2701 "max_bitrate_bps < min_bitrate_bps");
2702 } else if (*bitrate.max_bitrate_bps < 0) {
2703 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2704 "max_bitrate_bps < 0");
2705 }
2706 }
2707
2708 Call::Config::BitrateConfigMask mask;
2709 mask.min_bitrate_bps = bitrate.min_bitrate_bps;
2710 mask.start_bitrate_bps = bitrate.current_bitrate_bps;
2711 mask.max_bitrate_bps = bitrate.max_bitrate_bps;
2712
2713 RTC_DCHECK(call_.get());
2714 call_->SetBitrateConfigMask(mask);
2715
2716 return RTCError::OK();
2717}
2718
Alex Narest78609d52017-10-20 10:37:47 +02002719void PeerConnection::SetBitrateAllocationStrategy(
2720 std::unique_ptr<rtc::BitrateAllocationStrategy>
2721 bitrate_allocation_strategy) {
2722 rtc::Thread* worker_thread = factory_->worker_thread();
2723 if (!worker_thread->IsCurrent()) {
2724 rtc::BitrateAllocationStrategy* strategy_raw =
2725 bitrate_allocation_strategy.release();
2726 auto functor = [this, strategy_raw]() {
2727 call_->SetBitrateAllocationStrategy(
2728 rtc::WrapUnique<rtc::BitrateAllocationStrategy>(strategy_raw));
2729 };
2730 worker_thread->Invoke<void>(RTC_FROM_HERE, functor);
2731 return;
2732 }
2733 RTC_DCHECK(call_.get());
2734 call_->SetBitrateAllocationStrategy(std::move(bitrate_allocation_strategy));
2735}
2736
henrika5f6bf242017-11-01 11:06:56 +01002737void PeerConnection::SetAudioPlayout(bool playout) {
2738 if (!worker_thread()->IsCurrent()) {
2739 worker_thread()->Invoke<void>(
2740 RTC_FROM_HERE,
2741 rtc::Bind(&PeerConnection::SetAudioPlayout, this, playout));
2742 return;
2743 }
2744 auto audio_state =
2745 factory_->channel_manager()->media_engine()->GetAudioState();
2746 audio_state->SetPlayout(playout);
2747}
2748
2749void PeerConnection::SetAudioRecording(bool recording) {
2750 if (!worker_thread()->IsCurrent()) {
2751 worker_thread()->Invoke<void>(
2752 RTC_FROM_HERE,
2753 rtc::Bind(&PeerConnection::SetAudioRecording, this, recording));
2754 return;
2755 }
2756 auto audio_state =
2757 factory_->channel_manager()->media_engine()->GetAudioState();
2758 audio_state->SetRecording(recording);
2759}
2760
Steve Anton8c0f7a72017-10-03 10:03:10 -07002761std::unique_ptr<rtc::SSLCertificate>
2762PeerConnection::GetRemoteAudioSSLCertificate() {
Steve Anton75737c02017-11-06 10:37:17 -08002763 if (!voice_channel()) {
Steve Anton8c0f7a72017-10-03 10:03:10 -07002764 return nullptr;
2765 }
Steve Anton75737c02017-11-06 10:37:17 -08002766 return GetRemoteSSLCertificate(voice_channel()->transport_name());
Steve Anton8c0f7a72017-10-03 10:03:10 -07002767}
2768
ivoc14d5dbe2016-07-04 07:06:55 -07002769bool PeerConnection::StartRtcEventLog(rtc::PlatformFile file,
2770 int64_t max_size_bytes) {
Elad Alon99c3fe52017-10-13 16:29:40 +02002771 // TODO(eladalon): It would be better to not allow negative values into PC.
2772 const size_t max_size = (max_size_bytes < 0)
2773 ? RtcEventLog::kUnlimitedOutput
2774 : rtc::saturated_cast<size_t>(max_size_bytes);
2775 return StartRtcEventLog(
Bjorn Tereliusde939432017-11-20 17:38:14 +01002776 rtc::MakeUnique<RtcEventLogOutputFile>(file, max_size),
2777 webrtc::RtcEventLog::kImmediateOutput);
Elad Alon99c3fe52017-10-13 16:29:40 +02002778}
2779
Bjorn Tereliusde939432017-11-20 17:38:14 +01002780bool PeerConnection::StartRtcEventLog(std::unique_ptr<RtcEventLogOutput> output,
2781 int64_t output_period_ms) {
Karl Wibergd6b48192017-10-16 23:01:06 +02002782 // TODO(eladalon): In C++14, this can be done with a lambda.
2783 struct Functor {
Bjorn Tereliusde939432017-11-20 17:38:14 +01002784 bool operator()() {
2785 return pc->StartRtcEventLog_w(std::move(output), output_period_ms);
2786 }
Karl Wibergd6b48192017-10-16 23:01:06 +02002787 PeerConnection* const pc;
2788 std::unique_ptr<RtcEventLogOutput> output;
Bjorn Tereliusde939432017-11-20 17:38:14 +01002789 const int64_t output_period_ms;
Elad Alon99c3fe52017-10-13 16:29:40 +02002790 };
Bjorn Tereliusde939432017-11-20 17:38:14 +01002791 return worker_thread()->Invoke<bool>(
2792 RTC_FROM_HERE, Functor{this, std::move(output), output_period_ms});
ivoc14d5dbe2016-07-04 07:06:55 -07002793}
2794
2795void PeerConnection::StopRtcEventLog() {
Steve Anton978b8762017-09-29 12:15:02 -07002796 worker_thread()->Invoke<void>(
ivoc14d5dbe2016-07-04 07:06:55 -07002797 RTC_FROM_HERE, rtc::Bind(&PeerConnection::StopRtcEventLog_w, this));
2798}
2799
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002800const SessionDescriptionInterface* PeerConnection::local_description() const {
Steve Anton75737c02017-11-06 10:37:17 -08002801 return pending_local_description_ ? pending_local_description_.get()
2802 : current_local_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002803}
2804
2805const SessionDescriptionInterface* PeerConnection::remote_description() const {
Steve Anton75737c02017-11-06 10:37:17 -08002806 return pending_remote_description_ ? pending_remote_description_.get()
2807 : current_remote_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002808}
2809
deadbeeffe4a8a42016-12-20 17:56:17 -08002810const SessionDescriptionInterface* PeerConnection::current_local_description()
2811 const {
Steve Anton75737c02017-11-06 10:37:17 -08002812 return current_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08002813}
2814
2815const SessionDescriptionInterface* PeerConnection::current_remote_description()
2816 const {
Steve Anton75737c02017-11-06 10:37:17 -08002817 return current_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08002818}
2819
2820const SessionDescriptionInterface* PeerConnection::pending_local_description()
2821 const {
Steve Anton75737c02017-11-06 10:37:17 -08002822 return pending_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08002823}
2824
2825const SessionDescriptionInterface* PeerConnection::pending_remote_description()
2826 const {
Steve Anton75737c02017-11-06 10:37:17 -08002827 return pending_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08002828}
2829
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002830void PeerConnection::Close() {
Peter Boström1a9d6152015-12-08 22:15:17 +01002831 TRACE_EVENT0("webrtc", "PeerConnection::Close");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002832 // Update stats here so that we have the most recent stats for tracks and
2833 // streams before the channels are closed.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00002834 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002835
Steve Anton75737c02017-11-06 10:37:17 -08002836 ChangeSignalingState(PeerConnectionInterface::kClosed);
Steve Anton3fe1b152017-12-12 10:20:08 -08002837
Steve Anton8af21862017-12-15 11:20:13 -08002838 for (auto transceiver : transceivers_) {
2839 transceiver->Stop();
2840 }
2841 DestroyAllChannels();
Steve Anton75737c02017-11-06 10:37:17 -08002842
deadbeef42a42632017-03-10 15:18:00 -08002843 network_thread()->Invoke<void>(
2844 RTC_FROM_HERE,
2845 rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
2846 port_allocator_.get()));
nisseeaabdf62017-05-05 02:23:02 -07002847
Steve Anton978b8762017-09-29 12:15:02 -07002848 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
eladalon248fd4f2017-09-06 05:18:15 -07002849 call_.reset();
2850 // The event log must outlive call (and any other object that uses it).
2851 event_log_.reset();
2852 });
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002853}
2854
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002855void PeerConnection::OnMessage(rtc::Message* msg) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002856 switch (msg->message_id) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002857 case MSG_SET_SESSIONDESCRIPTION_SUCCESS: {
2858 SetSessionDescriptionMsg* param =
2859 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
2860 param->observer->OnSuccess();
2861 delete param;
2862 break;
2863 }
2864 case MSG_SET_SESSIONDESCRIPTION_FAILED: {
2865 SetSessionDescriptionMsg* param =
2866 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
2867 param->observer->OnFailure(param->error);
2868 delete param;
2869 break;
2870 }
deadbeefab9b2d12015-10-14 11:33:11 -07002871 case MSG_CREATE_SESSIONDESCRIPTION_FAILED: {
2872 CreateSessionDescriptionMsg* param =
2873 static_cast<CreateSessionDescriptionMsg*>(msg->pdata);
2874 param->observer->OnFailure(param->error);
2875 delete param;
2876 break;
2877 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002878 case MSG_GETSTATS: {
2879 GetStatsMsg* param = static_cast<GetStatsMsg*>(msg->pdata);
nissee8abe3e2017-01-18 05:00:34 -08002880 StatsReports reports;
2881 stats_->GetStats(param->track, &reports);
2882 param->observer->OnComplete(reports);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002883 delete param;
2884 break;
2885 }
deadbeefbd292462015-12-14 18:15:29 -08002886 case MSG_FREE_DATACHANNELS: {
2887 sctp_data_channels_to_free_.clear();
2888 break;
2889 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002890 default:
nisseeb4ca4e2017-01-12 02:24:27 -08002891 RTC_NOTREACHED() << "Not implemented";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002892 break;
2893 }
2894}
2895
Steve Anton4171afb2017-11-20 10:20:22 -08002896void PeerConnection::CreateAudioReceiver(
2897 MediaStreamInterface* stream,
2898 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01002899 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
2900 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Steve Antond3679212018-01-17 17:41:02 -08002901 auto* audio_receiver = new AudioRtpReceiver(
2902 worker_thread(), remote_sender_info.sender_id, streams);
2903 audio_receiver->SetMediaChannel(voice_media_channel());
2904 audio_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
2905 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
2906 signaling_thread(), audio_receiver);
Steve Anton4171afb2017-11-20 10:20:22 -08002907 GetAudioTransceiver()->internal()->AddReceiver(receiver);
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01002908 observer_->OnAddTrack(receiver, std::move(streams));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002909}
2910
Steve Anton4171afb2017-11-20 10:20:22 -08002911void PeerConnection::CreateVideoReceiver(
2912 MediaStreamInterface* stream,
2913 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01002914 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
2915 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Steve Antond3679212018-01-17 17:41:02 -08002916 auto* video_receiver = new VideoRtpReceiver(
2917 worker_thread(), remote_sender_info.sender_id, streams);
2918 video_receiver->SetMediaChannel(video_media_channel());
2919 video_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
2920 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
2921 signaling_thread(), video_receiver);
Steve Anton4171afb2017-11-20 10:20:22 -08002922 GetVideoTransceiver()->internal()->AddReceiver(receiver);
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01002923 observer_->OnAddTrack(receiver, std::move(streams));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002924}
2925
deadbeef70ab1a12015-09-28 16:53:55 -07002926// TODO(deadbeef): Keep RtpReceivers around even if track goes away in remote
2927// description.
Henrik Boström933d8b02017-10-10 10:05:16 -07002928rtc::scoped_refptr<RtpReceiverInterface> PeerConnection::RemoveAndStopReceiver(
Steve Anton4171afb2017-11-20 10:20:22 -08002929 const RtpSenderInfo& remote_sender_info) {
2930 auto receiver = FindReceiverById(remote_sender_info.sender_id);
2931 if (!receiver) {
2932 RTC_LOG(LS_WARNING) << "RtpReceiver for track with id "
2933 << remote_sender_info.sender_id << " doesn't exist.";
Henrik Boström933d8b02017-10-10 10:05:16 -07002934 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07002935 }
Steve Anton4171afb2017-11-20 10:20:22 -08002936 if (receiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
2937 GetAudioTransceiver()->internal()->RemoveReceiver(receiver);
2938 } else {
2939 GetVideoTransceiver()->internal()->RemoveReceiver(receiver);
2940 }
Henrik Boström933d8b02017-10-10 10:05:16 -07002941 return receiver;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002942}
2943
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002944void PeerConnection::AddAudioTrack(AudioTrackInterface* track,
2945 MediaStreamInterface* stream) {
2946 RTC_DCHECK(!IsClosed());
2947 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08002948 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002949 // We already have a sender for this track, so just change the stream_id
2950 // so that it's correct in the next call to CreateOffer.
Steve Anton4171afb2017-11-20 10:20:22 -08002951 sender->internal()->set_stream_id(stream->label());
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002952 return;
2953 }
2954
2955 // Normal case; we've never seen this track before.
Steve Anton02ee47c2018-01-10 16:26:06 -08002956 auto new_sender =
2957 CreateSender(cricket::MEDIA_TYPE_AUDIO, track, {stream->label()});
2958 static_cast<AudioRtpSender*>(new_sender->internal())
Steve Anton47136dd2018-01-12 10:49:35 -08002959 ->SetMediaChannel(voice_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08002960 GetAudioTransceiver()->internal()->AddSender(new_sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002961 // If the sender has already been configured in SDP, we call SetSsrc,
2962 // which will connect the sender to the underlying transport. This can
2963 // occur if a local session description that contains the ID of the sender
2964 // is set before AddStream is called. It can also occur if the local
2965 // session description is not changed and RemoveStream is called, and
2966 // later AddStream is called again with the same stream.
Steve Anton4171afb2017-11-20 10:20:22 -08002967 const RtpSenderInfo* sender_info =
2968 FindSenderInfo(local_audio_sender_infos_, stream->label(), track->id());
2969 if (sender_info) {
2970 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002971 }
2972}
2973
2974// TODO(deadbeef): Don't destroy RtpSenders here; they should be kept around
2975// indefinitely, when we have unified plan SDP.
2976void PeerConnection::RemoveAudioTrack(AudioTrackInterface* track,
2977 MediaStreamInterface* stream) {
2978 RTC_DCHECK(!IsClosed());
2979 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08002980 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002981 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
2982 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002983 return;
2984 }
Steve Anton4171afb2017-11-20 10:20:22 -08002985 GetAudioTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002986}
2987
2988void PeerConnection::AddVideoTrack(VideoTrackInterface* track,
2989 MediaStreamInterface* stream) {
2990 RTC_DCHECK(!IsClosed());
2991 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08002992 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002993 // We already have a sender for this track, so just change the stream_id
2994 // so that it's correct in the next call to CreateOffer.
Steve Anton4171afb2017-11-20 10:20:22 -08002995 sender->internal()->set_stream_id(stream->label());
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002996 return;
2997 }
2998
2999 // Normal case; we've never seen this track before.
Steve Anton02ee47c2018-01-10 16:26:06 -08003000 auto new_sender =
3001 CreateSender(cricket::MEDIA_TYPE_VIDEO, track, {stream->label()});
3002 static_cast<VideoRtpSender*>(new_sender->internal())
Steve Anton47136dd2018-01-12 10:49:35 -08003003 ->SetMediaChannel(video_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08003004 GetVideoTransceiver()->internal()->AddSender(new_sender);
3005 const RtpSenderInfo* sender_info =
3006 FindSenderInfo(local_video_sender_infos_, stream->label(), track->id());
3007 if (sender_info) {
3008 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003009 }
3010}
3011
3012void PeerConnection::RemoveVideoTrack(VideoTrackInterface* track,
3013 MediaStreamInterface* stream) {
3014 RTC_DCHECK(!IsClosed());
3015 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003016 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003017 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
3018 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003019 return;
3020 }
Steve Anton4171afb2017-11-20 10:20:22 -08003021 GetVideoTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003022}
3023
Steve Antonba818672017-11-06 10:21:57 -08003024void PeerConnection::SetIceConnectionState(IceConnectionState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07003025 RTC_DCHECK(signaling_thread()->IsCurrent());
Steve Antonba818672017-11-06 10:21:57 -08003026 if (ice_connection_state_ == new_state) {
3027 return;
3028 }
3029
deadbeefcbecd352015-09-23 11:50:27 -07003030 // After transitioning to "closed", ignore any additional states from
Steve Antonba818672017-11-06 10:21:57 -08003031 // TransportController (such as "disconnected").
deadbeefab9b2d12015-10-14 11:33:11 -07003032 if (IsClosed()) {
deadbeefcbecd352015-09-23 11:50:27 -07003033 return;
3034 }
Steve Antonba818672017-11-06 10:21:57 -08003035
Mirko Bonadei675513b2017-11-09 11:09:25 +01003036 RTC_LOG(LS_INFO) << "Changing IceConnectionState " << ice_connection_state_
3037 << " => " << new_state;
Steve Antonba818672017-11-06 10:21:57 -08003038 RTC_DCHECK(ice_connection_state_ !=
3039 PeerConnectionInterface::kIceConnectionClosed);
3040
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003041 ice_connection_state_ = new_state;
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00003042 observer_->OnIceConnectionChange(ice_connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003043}
3044
3045void PeerConnection::OnIceGatheringChange(
3046 PeerConnectionInterface::IceGatheringState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07003047 RTC_DCHECK(signaling_thread()->IsCurrent());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003048 if (IsClosed()) {
3049 return;
3050 }
3051 ice_gathering_state_ = new_state;
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00003052 observer_->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003053}
3054
jbauch81bf7b02017-03-25 08:31:12 -07003055void PeerConnection::OnIceCandidate(
3056 std::unique_ptr<IceCandidateInterface> candidate) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07003057 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07003058 if (IsClosed()) {
3059 return;
3060 }
jbauch81bf7b02017-03-25 08:31:12 -07003061 observer_->OnIceCandidate(candidate.get());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003062}
3063
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003064void PeerConnection::OnIceCandidatesRemoved(
3065 const std::vector<cricket::Candidate>& candidates) {
3066 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07003067 if (IsClosed()) {
3068 return;
3069 }
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003070 observer_->OnIceCandidatesRemoved(candidates);
3071}
3072
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003073void PeerConnection::ChangeSignalingState(
3074 PeerConnectionInterface::SignalingState signaling_state) {
Steve Antonba818672017-11-06 10:21:57 -08003075 RTC_DCHECK(signaling_thread()->IsCurrent());
3076 if (signaling_state_ == signaling_state) {
3077 return;
3078 }
Mirko Bonadei675513b2017-11-09 11:09:25 +01003079 RTC_LOG(LS_INFO) << "Session: " << session_id() << " Old state: "
3080 << GetSignalingStateString(signaling_state_)
3081 << " New state: "
3082 << GetSignalingStateString(signaling_state);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003083 signaling_state_ = signaling_state;
3084 if (signaling_state == kClosed) {
3085 ice_connection_state_ = kIceConnectionClosed;
3086 observer_->OnIceConnectionChange(ice_connection_state_);
3087 if (ice_gathering_state_ != kIceGatheringComplete) {
3088 ice_gathering_state_ = kIceGatheringComplete;
3089 observer_->OnIceGatheringChange(ice_gathering_state_);
3090 }
3091 }
3092 observer_->OnSignalingChange(signaling_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003093}
3094
deadbeefeb459812015-12-15 19:24:43 -08003095void PeerConnection::OnAudioTrackAdded(AudioTrackInterface* track,
3096 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003097 if (IsClosed()) {
3098 return;
3099 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003100 AddAudioTrack(track, stream);
3101 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003102}
3103
deadbeefeb459812015-12-15 19:24:43 -08003104void PeerConnection::OnAudioTrackRemoved(AudioTrackInterface* track,
3105 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003106 if (IsClosed()) {
3107 return;
3108 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003109 RemoveAudioTrack(track, stream);
3110 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003111}
3112
3113void PeerConnection::OnVideoTrackAdded(VideoTrackInterface* track,
3114 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003115 if (IsClosed()) {
3116 return;
3117 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003118 AddVideoTrack(track, stream);
3119 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003120}
3121
3122void PeerConnection::OnVideoTrackRemoved(VideoTrackInterface* track,
3123 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003124 if (IsClosed()) {
3125 return;
3126 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003127 RemoveVideoTrack(track, stream);
3128 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003129}
3130
Henrik Boström31638672017-11-23 17:48:32 +01003131void PeerConnection::PostSetSessionDescriptionSuccess(
3132 SetSessionDescriptionObserver* observer) {
3133 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
3134 signaling_thread()->Post(RTC_FROM_HERE, this,
3135 MSG_SET_SESSIONDESCRIPTION_SUCCESS, msg);
3136}
3137
deadbeefab9b2d12015-10-14 11:33:11 -07003138void PeerConnection::PostSetSessionDescriptionFailure(
3139 SetSessionDescriptionObserver* observer,
3140 const std::string& error) {
3141 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
3142 msg->error = error;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07003143 signaling_thread()->Post(RTC_FROM_HERE, this,
3144 MSG_SET_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07003145}
3146
3147void PeerConnection::PostCreateSessionDescriptionFailure(
3148 CreateSessionDescriptionObserver* observer,
3149 const std::string& error) {
3150 CreateSessionDescriptionMsg* msg = new CreateSessionDescriptionMsg(observer);
3151 msg->error = error;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07003152 signaling_thread()->Post(RTC_FROM_HERE, this,
3153 MSG_CREATE_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07003154}
3155
zhihuang1c378ed2017-08-17 14:10:50 -07003156void PeerConnection::GetOptionsForOffer(
Steve Antondcc3c022017-12-22 16:02:54 -08003157 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
deadbeefab9b2d12015-10-14 11:33:11 -07003158 cricket::MediaSessionOptions* session_options) {
Steve Antondcc3c022017-12-22 16:02:54 -08003159 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
zhihuang1c378ed2017-08-17 14:10:50 -07003160
Steve Antondcc3c022017-12-22 16:02:54 -08003161 if (IsUnifiedPlan()) {
3162 GetOptionsForUnifiedPlanOffer(offer_answer_options, session_options);
3163 } else {
3164 GetOptionsForPlanBOffer(offer_answer_options, session_options);
3165 }
3166
Steve Antonfa2260d2017-12-28 16:38:23 -08003167 // Intentionally unset the data channel type for RTP data channel with the
3168 // second condition. Otherwise the RTP data channels would be successfully
3169 // negotiated by default and the unit tests in WebRtcDataBrowserTest will fail
3170 // when building with chromium. We want to leave RTP data channels broken, so
3171 // people won't try to use them.
3172 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
3173 session_options->data_channel_type = data_channel_type();
3174 }
3175
Steve Antondcc3c022017-12-22 16:02:54 -08003176 // Apply ICE restart flag and renomination flag.
3177 for (auto& options : session_options->media_description_options) {
3178 options.transport_options.ice_restart = offer_answer_options.ice_restart;
3179 options.transport_options.enable_ice_renomination =
3180 configuration_.enable_ice_renomination;
3181 }
3182
3183 session_options->rtcp_cname = rtcp_cname_;
3184 session_options->crypto_options = factory_->options().crypto_options;
3185}
3186
3187void PeerConnection::GetOptionsForPlanBOffer(
3188 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
3189 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07003190 // Figure out transceiver directional preferences.
3191 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
3192 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
3193
3194 // By default, generate sendrecv/recvonly m= sections.
3195 bool recv_audio = true;
3196 bool recv_video = true;
3197
3198 // By default, only offer a new m= section if we have media to send with it.
3199 bool offer_new_audio_description = send_audio;
3200 bool offer_new_video_description = send_video;
3201 bool offer_new_data_description = HasDataChannels();
3202
3203 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-22 16:02:54 -08003204 if (offer_answer_options.offer_to_receive_audio !=
3205 RTCOfferAnswerOptions::kUndefined) {
3206 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003207 offer_new_audio_description =
Steve Antondcc3c022017-12-22 16:02:54 -08003208 offer_new_audio_description ||
3209 (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003210 }
Steve Antondcc3c022017-12-22 16:02:54 -08003211 if (offer_answer_options.offer_to_receive_video !=
3212 RTCOfferAnswerOptions::kUndefined) {
3213 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003214 offer_new_video_description =
Steve Antondcc3c022017-12-22 16:02:54 -08003215 offer_new_video_description ||
3216 (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003217 }
3218
3219 rtc::Optional<size_t> audio_index;
3220 rtc::Optional<size_t> video_index;
3221 rtc::Optional<size_t> data_index;
3222 // If a current description exists, generate m= sections in the same order,
3223 // using the first audio/video/data section that appears and rejecting
3224 // extraneous ones.
Steve Anton75737c02017-11-06 10:37:17 -08003225 if (local_description()) {
zhihuang1c378ed2017-08-17 14:10:50 -07003226 GenerateMediaDescriptionOptions(
Steve Anton75737c02017-11-06 10:37:17 -08003227 local_description(),
Steve Anton1d03a752017-11-27 14:30:09 -08003228 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
3229 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
3230 &audio_index, &video_index, &data_index, session_options);
deadbeefab9b2d12015-10-14 11:33:11 -07003231 }
3232
zhihuang1c378ed2017-08-17 14:10:50 -07003233 // Add audio/video/data m= sections to the end if needed.
3234 if (!audio_index && offer_new_audio_description) {
3235 session_options->media_description_options.push_back(
3236 cricket::MediaDescriptionOptions(
3237 cricket::MEDIA_TYPE_AUDIO, cricket::CN_AUDIO,
Steve Anton1d03a752017-11-27 14:30:09 -08003238 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
3239 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003240 audio_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07003241 }
zhihuang1c378ed2017-08-17 14:10:50 -07003242 if (!video_index && offer_new_video_description) {
3243 session_options->media_description_options.push_back(
3244 cricket::MediaDescriptionOptions(
3245 cricket::MEDIA_TYPE_VIDEO, cricket::CN_VIDEO,
Steve Anton1d03a752017-11-27 14:30:09 -08003246 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
3247 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003248 video_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07003249 }
zhihuang1c378ed2017-08-17 14:10:50 -07003250 if (!data_index && offer_new_data_description) {
3251 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08003252 GetMediaDescriptionOptionsForActiveData(cricket::CN_DATA));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003253 data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07003254 }
3255
3256 cricket::MediaDescriptionOptions* audio_media_description_options =
3257 !audio_index ? nullptr
3258 : &session_options->media_description_options[*audio_index];
3259 cricket::MediaDescriptionOptions* video_media_description_options =
3260 !video_index ? nullptr
3261 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 14:10:50 -07003262
Steve Anton4171afb2017-11-20 10:20:22 -08003263 AddRtpSenderOptions(GetSendersInternal(), audio_media_description_options,
zhihuang1c378ed2017-08-17 14:10:50 -07003264 video_media_description_options);
Steve Antondcc3c022017-12-22 16:02:54 -08003265}
3266
3267// Find a new MID that is not already in |used_mids|, then add it to |used_mids|
3268// and return a reference to it.
3269// Generated MIDs should be no more than 3 bytes long to take up less space in
3270// the RTP packet.
3271static const std::string& AllocateMid(std::set<std::string>* used_mids) {
3272 RTC_DCHECK(used_mids);
3273 // We're boring: just generate MIDs 0, 1, 2, ...
3274 size_t i = 0;
3275 std::set<std::string>::iterator it;
3276 bool inserted;
3277 do {
3278 std::string mid = rtc::ToString(i++);
3279 auto insert_result = used_mids->insert(mid);
3280 it = insert_result.first;
3281 inserted = insert_result.second;
3282 } while (!inserted);
3283 return *it;
3284}
3285
3286static cricket::MediaDescriptionOptions
3287GetMediaDescriptionOptionsForTransceiver(
3288 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3289 transceiver,
3290 const std::string& mid) {
3291 cricket::MediaDescriptionOptions media_description_options(
3292 transceiver->internal()->media_type(), mid, transceiver->direction(),
3293 transceiver->stopped());
3294 cricket::SenderOptions sender_options;
3295 sender_options.track_id = transceiver->sender()->id();
3296 sender_options.stream_ids = transceiver->sender()->stream_ids();
3297 // TODO(bugs.webrtc.org/7600): Set num_sim_layers to the number of encodings
3298 // set in the RTP parameters when the transceiver was added.
3299 sender_options.num_sim_layers = 1;
3300 media_description_options.sender_options.push_back(sender_options);
3301 return media_description_options;
3302}
3303
3304void PeerConnection::GetOptionsForUnifiedPlanOffer(
3305 const RTCOfferAnswerOptions& offer_answer_options,
3306 cricket::MediaSessionOptions* session_options) {
3307 // Rules for generating an offer are dictated by JSEP sections 5.2.1 (Initial
3308 // Offers) and 5.2.2 (Subsequent Offers).
3309 RTC_DCHECK_EQ(session_options->media_description_options.size(), 0);
3310 const ContentInfos& local_contents =
3311 (local_description() ? local_description()->description()->contents()
3312 : ContentInfos());
3313 const ContentInfos& remote_contents =
3314 (remote_description() ? remote_description()->description()->contents()
3315 : ContentInfos());
3316 // The mline indices that can be recycled. New transceivers should reuse these
3317 // slots first.
3318 std::queue<size_t> recycleable_mline_indices;
3319 // Track the MIDs used in previous offer/answer exchanges and the current
3320 // offer so that new, unique MIDs are generated.
3321 std::set<std::string> used_mids = seen_mids_;
3322 // First, go through each media section that exists in either the local or
3323 // remote description and generate a media section in this offer for the
3324 // associated transceiver. If a media section can be recycled, generate a
3325 // default, rejected media section here that can be later overwritten.
3326 for (size_t i = 0;
3327 i < std::max(local_contents.size(), remote_contents.size()); ++i) {
3328 // Either |local_content| or |remote_content| is non-null.
3329 const ContentInfo* local_content =
3330 (i < local_contents.size() ? &local_contents[i] : nullptr);
3331 const ContentInfo* remote_content =
3332 (i < remote_contents.size() ? &remote_contents[i] : nullptr);
3333 bool had_been_rejected = (local_content && local_content->rejected) ||
3334 (remote_content && remote_content->rejected);
3335 const std::string& mid =
3336 (local_content ? local_content->name : remote_content->name);
3337 cricket::MediaType media_type =
3338 (local_content ? local_content->media_description()->type()
3339 : remote_content->media_description()->type());
3340 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
3341 media_type == cricket::MEDIA_TYPE_VIDEO) {
3342 auto transceiver = GetAssociatedTransceiver(mid);
3343 RTC_CHECK(transceiver);
3344 // A media section is considered eligible for recycling if it is marked as
3345 // rejected in either the local or remote description.
3346 if (had_been_rejected) {
3347 session_options->media_description_options.push_back(
3348 cricket::MediaDescriptionOptions(
3349 transceiver->internal()->media_type(), mid,
3350 RtpTransceiverDirection::kInactive,
3351 /*stopped=*/true));
3352 recycleable_mline_indices.push(i);
3353 } else {
3354 session_options->media_description_options.push_back(
3355 GetMediaDescriptionOptionsForTransceiver(transceiver, mid));
3356 // CreateOffer shouldn't really cause any state changes in
3357 // PeerConnection, but we need a way to match new transceivers to new
3358 // media sections in SetLocalDescription and JSEP specifies this is done
3359 // by recording the index of the media section generated for the
3360 // transceiver in the offer.
3361 transceiver->internal()->set_mline_index(i);
3362 }
3363 } else {
3364 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antonfa2260d2017-12-28 16:38:23 -08003365 RTC_CHECK(GetDataMid());
3366 if (had_been_rejected || mid != *GetDataMid()) {
3367 session_options->media_description_options.push_back(
3368 GetMediaDescriptionOptionsForRejectedData(mid));
3369 } else {
3370 session_options->media_description_options.push_back(
3371 GetMediaDescriptionOptionsForActiveData(mid));
3372 }
Steve Antondcc3c022017-12-22 16:02:54 -08003373 }
3374 }
3375 // Next, look for transceivers that are newly added (that is, are not stopped
3376 // and not associated). Reuse media sections marked as recyclable first,
3377 // otherwise append to the end of the offer. New media sections should be
3378 // added in the order they were added to the PeerConnection.
3379 for (auto transceiver : transceivers_) {
3380 if (transceiver->mid() || transceiver->stopped()) {
3381 continue;
3382 }
3383 size_t mline_index;
3384 if (!recycleable_mline_indices.empty()) {
3385 mline_index = recycleable_mline_indices.front();
3386 recycleable_mline_indices.pop();
3387 session_options->media_description_options[mline_index] =
3388 GetMediaDescriptionOptionsForTransceiver(transceiver,
3389 AllocateMid(&used_mids));
3390 } else {
3391 mline_index = session_options->media_description_options.size();
3392 session_options->media_description_options.push_back(
3393 GetMediaDescriptionOptionsForTransceiver(transceiver,
3394 AllocateMid(&used_mids)));
3395 }
3396 // See comment above for why CreateOffer changes the transceiver's state.
3397 transceiver->internal()->set_mline_index(mline_index);
3398 }
Steve Antonfa2260d2017-12-28 16:38:23 -08003399 // Lastly, add a m-section if we have local data channels and an m section
3400 // does not already exist.
3401 if (!GetDataMid() && HasDataChannels()) {
3402 session_options->media_description_options.push_back(
3403 GetMediaDescriptionOptionsForActiveData(AllocateMid(&used_mids)));
3404 }
Steve Antondcc3c022017-12-22 16:02:54 -08003405}
3406
3407void PeerConnection::GetOptionsForAnswer(
3408 const RTCOfferAnswerOptions& offer_answer_options,
3409 cricket::MediaSessionOptions* session_options) {
3410 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
3411
3412 if (IsUnifiedPlan()) {
3413 GetOptionsForUnifiedPlanAnswer(offer_answer_options, session_options);
3414 } else {
3415 GetOptionsForPlanBAnswer(offer_answer_options, session_options);
3416 }
3417
Steve Antonfa2260d2017-12-28 16:38:23 -08003418 // Intentionally unset the data channel type for RTP data channel. Otherwise
3419 // the RTP data channels would be successfully negotiated by default and the
3420 // unit tests in WebRtcDataBrowserTest will fail when building with chromium.
3421 // We want to leave RTP data channels broken, so people won't try to use them.
3422 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
3423 session_options->data_channel_type = data_channel_type();
3424 }
3425
Steve Antondcc3c022017-12-22 16:02:54 -08003426 // Apply ICE renomination flag.
3427 for (auto& options : session_options->media_description_options) {
3428 options.transport_options.enable_ice_renomination =
3429 configuration_.enable_ice_renomination;
3430 }
zhihuang8f65cdf2016-05-06 18:40:30 -07003431
3432 session_options->rtcp_cname = rtcp_cname_;
jbauchcb560652016-08-04 05:20:32 -07003433 session_options->crypto_options = factory_->options().crypto_options;
deadbeefab9b2d12015-10-14 11:33:11 -07003434}
3435
Steve Antondcc3c022017-12-22 16:02:54 -08003436void PeerConnection::GetOptionsForPlanBAnswer(
3437 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07003438 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07003439 // Figure out transceiver directional preferences.
3440 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
3441 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
3442
3443 // By default, generate sendrecv/recvonly m= sections. The direction is also
3444 // restricted by the direction in the offer.
3445 bool recv_audio = true;
3446 bool recv_video = true;
3447
3448 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-22 16:02:54 -08003449 if (offer_answer_options.offer_to_receive_audio !=
3450 RTCOfferAnswerOptions::kUndefined) {
3451 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
deadbeef0ed85b22016-02-23 17:24:52 -08003452 }
Steve Antondcc3c022017-12-22 16:02:54 -08003453 if (offer_answer_options.offer_to_receive_video !=
3454 RTCOfferAnswerOptions::kUndefined) {
3455 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003456 }
3457
3458 rtc::Optional<size_t> audio_index;
3459 rtc::Optional<size_t> video_index;
3460 rtc::Optional<size_t> data_index;
Taylor Brandstetter94d8cce2018-01-26 22:44:21 +00003461 if (remote_description()) {
3462 // The pending remote description should be an offer.
3463 RTC_DCHECK(remote_description()->GetType() == SdpType::kOffer);
3464 // Generate m= sections that match those in the offer.
3465 // Note that mediasession.cc will handle intersection our preferred
3466 // direction with the offered direction.
3467 GenerateMediaDescriptionOptions(
3468 remote_description(),
3469 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
3470 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
3471 &audio_index, &video_index, &data_index, session_options);
3472 }
zhihuang1c378ed2017-08-17 14:10:50 -07003473
3474 cricket::MediaDescriptionOptions* audio_media_description_options =
3475 !audio_index ? nullptr
3476 : &session_options->media_description_options[*audio_index];
3477 cricket::MediaDescriptionOptions* video_media_description_options =
3478 !video_index ? nullptr
3479 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 14:10:50 -07003480
Steve Anton4171afb2017-11-20 10:20:22 -08003481 AddRtpSenderOptions(GetSendersInternal(), audio_media_description_options,
zhihuang1c378ed2017-08-17 14:10:50 -07003482 video_media_description_options);
Steve Antondcc3c022017-12-22 16:02:54 -08003483}
zhihuangaf388472016-11-02 16:49:48 -07003484
Steve Antondcc3c022017-12-22 16:02:54 -08003485void PeerConnection::GetOptionsForUnifiedPlanAnswer(
3486 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
3487 cricket::MediaSessionOptions* session_options) {
3488 // Rules for generating an answer are dictated by JSEP sections 5.3.1 (Initial
3489 // Answers) and 5.3.2 (Subsequent Answers).
3490 RTC_DCHECK(remote_description());
3491 RTC_DCHECK(remote_description()->GetType() == SdpType::kOffer);
3492 for (const ContentInfo& content :
3493 remote_description()->description()->contents()) {
3494 cricket::MediaType media_type = content.media_description()->type();
3495 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
3496 media_type == cricket::MEDIA_TYPE_VIDEO) {
3497 auto transceiver = GetAssociatedTransceiver(content.name);
3498 RTC_CHECK(transceiver);
3499 session_options->media_description_options.push_back(
3500 GetMediaDescriptionOptionsForTransceiver(transceiver, content.name));
3501 } else {
3502 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antondbf9d032018-01-19 15:23:40 -08003503 // Reject all data sections if data channels are disabled.
3504 // Reject a data section if it has already been rejected.
3505 // Reject all data sections except for the first one.
3506 if (data_channel_type_ == cricket::DCT_NONE || content.rejected ||
3507 content.name != *GetDataMid()) {
Steve Antonfa2260d2017-12-28 16:38:23 -08003508 session_options->media_description_options.push_back(
3509 GetMediaDescriptionOptionsForRejectedData(content.name));
3510 } else {
3511 session_options->media_description_options.push_back(
3512 GetMediaDescriptionOptionsForActiveData(content.name));
3513 }
Steve Antondcc3c022017-12-22 16:02:54 -08003514 }
3515 }
htaa2a49d92016-03-04 02:51:39 -08003516}
3517
zhihuang1c378ed2017-08-17 14:10:50 -07003518void PeerConnection::GenerateMediaDescriptionOptions(
3519 const SessionDescriptionInterface* session_desc,
Steve Anton1d03a752017-11-27 14:30:09 -08003520 RtpTransceiverDirection audio_direction,
3521 RtpTransceiverDirection video_direction,
zhihuang1c378ed2017-08-17 14:10:50 -07003522 rtc::Optional<size_t>* audio_index,
3523 rtc::Optional<size_t>* video_index,
3524 rtc::Optional<size_t>* data_index,
htaa2a49d92016-03-04 02:51:39 -08003525 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07003526 for (const cricket::ContentInfo& content :
3527 session_desc->description()->contents()) {
3528 if (IsAudioContent(&content)) {
3529 // If we already have an audio m= section, reject this extra one.
3530 if (*audio_index) {
3531 session_options->media_description_options.push_back(
3532 cricket::MediaDescriptionOptions(
3533 cricket::MEDIA_TYPE_AUDIO, content.name,
Steve Anton1d03a752017-11-27 14:30:09 -08003534 RtpTransceiverDirection::kInactive, true));
zhihuang1c378ed2017-08-17 14:10:50 -07003535 } else {
3536 session_options->media_description_options.push_back(
3537 cricket::MediaDescriptionOptions(
3538 cricket::MEDIA_TYPE_AUDIO, content.name, audio_direction,
Steve Anton1d03a752017-11-27 14:30:09 -08003539 audio_direction == RtpTransceiverDirection::kInactive));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003540 *audio_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07003541 }
3542 } else if (IsVideoContent(&content)) {
3543 // If we already have an video m= section, reject this extra one.
3544 if (*video_index) {
3545 session_options->media_description_options.push_back(
3546 cricket::MediaDescriptionOptions(
3547 cricket::MEDIA_TYPE_VIDEO, content.name,
Steve Anton1d03a752017-11-27 14:30:09 -08003548 RtpTransceiverDirection::kInactive, true));
zhihuang1c378ed2017-08-17 14:10:50 -07003549 } else {
3550 session_options->media_description_options.push_back(
3551 cricket::MediaDescriptionOptions(
3552 cricket::MEDIA_TYPE_VIDEO, content.name, video_direction,
Steve Anton1d03a752017-11-27 14:30:09 -08003553 video_direction == RtpTransceiverDirection::kInactive));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003554 *video_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07003555 }
3556 } else {
3557 RTC_DCHECK(IsDataContent(&content));
3558 // If we already have an data m= section, reject this extra one.
3559 if (*data_index) {
3560 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08003561 GetMediaDescriptionOptionsForRejectedData(content.name));
zhihuang1c378ed2017-08-17 14:10:50 -07003562 } else {
3563 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08003564 GetMediaDescriptionOptionsForActiveData(content.name));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003565 *data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07003566 }
3567 }
htaa2a49d92016-03-04 02:51:39 -08003568 }
deadbeefab9b2d12015-10-14 11:33:11 -07003569}
3570
Steve Antonfa2260d2017-12-28 16:38:23 -08003571cricket::MediaDescriptionOptions
3572PeerConnection::GetMediaDescriptionOptionsForActiveData(
3573 const std::string& mid) const {
3574 // Direction for data sections is meaningless, but legacy endpoints might
3575 // expect sendrecv.
3576 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
3577 RtpTransceiverDirection::kSendRecv,
3578 /*stopped=*/false);
3579 AddRtpDataChannelOptions(rtp_data_channels_, &options);
3580 return options;
3581}
3582
3583cricket::MediaDescriptionOptions
3584PeerConnection::GetMediaDescriptionOptionsForRejectedData(
3585 const std::string& mid) const {
3586 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
3587 RtpTransceiverDirection::kInactive,
3588 /*stopped=*/true);
3589 AddRtpDataChannelOptions(rtp_data_channels_, &options);
3590 return options;
3591}
3592
3593rtc::Optional<std::string> PeerConnection::GetDataMid() const {
3594 switch (data_channel_type_) {
3595 case cricket::DCT_RTP:
3596 if (!rtp_data_channel_) {
3597 return rtc::nullopt;
3598 }
3599 return rtp_data_channel_->content_name();
3600 case cricket::DCT_SCTP:
3601 return sctp_content_name_;
3602 default:
3603 return rtc::nullopt;
3604 }
3605}
3606
Steve Anton4171afb2017-11-20 10:20:22 -08003607void PeerConnection::RemoveSenders(cricket::MediaType media_type) {
3608 UpdateLocalSenders(std::vector<cricket::StreamParams>(), media_type);
3609 UpdateRemoteSendersList(std::vector<cricket::StreamParams>(), false,
deadbeefbda7e0b2015-12-08 17:13:40 -08003610 media_type, nullptr);
deadbeeffaac4972015-11-12 15:33:07 -08003611}
3612
Steve Anton4171afb2017-11-20 10:20:22 -08003613void PeerConnection::UpdateRemoteSendersList(
deadbeefab9b2d12015-10-14 11:33:11 -07003614 const cricket::StreamParamsVec& streams,
Steve Anton4171afb2017-11-20 10:20:22 -08003615 bool default_sender_needed,
deadbeefab9b2d12015-10-14 11:33:11 -07003616 cricket::MediaType media_type,
3617 StreamCollection* new_streams) {
Steve Anton4171afb2017-11-20 10:20:22 -08003618 std::vector<RtpSenderInfo>* current_senders =
3619 GetRemoteSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07003620
Steve Anton4171afb2017-11-20 10:20:22 -08003621 // Find removed senders. I.e., senders where the sender id or ssrc don't match
deadbeeffac06552015-11-25 11:26:01 -08003622 // the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08003623 for (auto sender_it = current_senders->begin();
3624 sender_it != current_senders->end();
3625 /* incremented manually */) {
3626 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07003627 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08003628 cricket::GetStreamBySsrc(streams, info.first_ssrc);
3629 bool sender_exists = params && params->id == info.sender_id;
deadbeefbda7e0b2015-12-08 17:13:40 -08003630 // If this is a default track, and we still need it, don't remove it.
Steve Anton4171afb2017-11-20 10:20:22 -08003631 if ((info.stream_label == kDefaultStreamLabel && default_sender_needed) ||
3632 sender_exists) {
3633 ++sender_it;
deadbeefbda7e0b2015-12-08 17:13:40 -08003634 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08003635 OnRemoteSenderRemoved(info, media_type);
3636 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07003637 }
3638 }
3639
Steve Anton4171afb2017-11-20 10:20:22 -08003640 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07003641 for (const cricket::StreamParams& params : streams) {
3642 // The sync_label is the MediaStream label and the |stream.id| is the
Steve Anton4171afb2017-11-20 10:20:22 -08003643 // sender id.
deadbeefab9b2d12015-10-14 11:33:11 -07003644 const std::string& stream_label = params.sync_label;
Steve Anton4171afb2017-11-20 10:20:22 -08003645 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07003646 uint32_t ssrc = params.first_ssrc();
3647
3648 rtc::scoped_refptr<MediaStreamInterface> stream =
3649 remote_streams_->find(stream_label);
3650 if (!stream) {
3651 // This is a new MediaStream. Create a new remote MediaStream.
perkjd61bf802016-03-24 03:16:19 -07003652 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
3653 MediaStream::Create(stream_label));
deadbeefab9b2d12015-10-14 11:33:11 -07003654 remote_streams_->AddStream(stream);
3655 new_streams->AddStream(stream);
3656 }
3657
Steve Anton4171afb2017-11-20 10:20:22 -08003658 const RtpSenderInfo* sender_info =
3659 FindSenderInfo(*current_senders, stream_label, sender_id);
3660 if (!sender_info) {
3661 current_senders->push_back(RtpSenderInfo(stream_label, sender_id, ssrc));
3662 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07003663 }
3664 }
deadbeefbda7e0b2015-12-08 17:13:40 -08003665
Steve Anton4171afb2017-11-20 10:20:22 -08003666 // Add default sender if necessary.
3667 if (default_sender_needed) {
deadbeefbda7e0b2015-12-08 17:13:40 -08003668 rtc::scoped_refptr<MediaStreamInterface> default_stream =
3669 remote_streams_->find(kDefaultStreamLabel);
3670 if (!default_stream) {
3671 // Create the new default MediaStream.
perkjd61bf802016-03-24 03:16:19 -07003672 default_stream = MediaStreamProxy::Create(
3673 rtc::Thread::Current(), MediaStream::Create(kDefaultStreamLabel));
deadbeefbda7e0b2015-12-08 17:13:40 -08003674 remote_streams_->AddStream(default_stream);
3675 new_streams->AddStream(default_stream);
3676 }
Steve Anton4171afb2017-11-20 10:20:22 -08003677 std::string default_sender_id = (media_type == cricket::MEDIA_TYPE_AUDIO)
3678 ? kDefaultAudioSenderId
3679 : kDefaultVideoSenderId;
3680 const RtpSenderInfo* default_sender_info = FindSenderInfo(
3681 *current_senders, kDefaultStreamLabel, default_sender_id);
3682 if (!default_sender_info) {
3683 current_senders->push_back(
3684 RtpSenderInfo(kDefaultStreamLabel, default_sender_id, 0));
3685 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefbda7e0b2015-12-08 17:13:40 -08003686 }
3687 }
deadbeefab9b2d12015-10-14 11:33:11 -07003688}
3689
Steve Anton4171afb2017-11-20 10:20:22 -08003690void PeerConnection::OnRemoteSenderAdded(const RtpSenderInfo& sender_info,
3691 cricket::MediaType media_type) {
3692 MediaStreamInterface* stream =
3693 remote_streams_->find(sender_info.stream_label);
deadbeefab9b2d12015-10-14 11:33:11 -07003694
3695 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 10:20:22 -08003696 CreateAudioReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07003697 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 10:20:22 -08003698 CreateVideoReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07003699 } else {
nisseeb4ca4e2017-01-12 02:24:27 -08003700 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07003701 }
3702}
3703
Steve Anton4171afb2017-11-20 10:20:22 -08003704void PeerConnection::OnRemoteSenderRemoved(const RtpSenderInfo& sender_info,
3705 cricket::MediaType media_type) {
3706 MediaStreamInterface* stream =
3707 remote_streams_->find(sender_info.stream_label);
deadbeefab9b2d12015-10-14 11:33:11 -07003708
Henrik Boström933d8b02017-10-10 10:05:16 -07003709 rtc::scoped_refptr<RtpReceiverInterface> receiver;
deadbeefab9b2d12015-10-14 11:33:11 -07003710 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
perkjd61bf802016-03-24 03:16:19 -07003711 // When the MediaEngine audio channel is destroyed, the RemoteAudioSource
3712 // will be notified which will end the AudioRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08003713 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07003714 rtc::scoped_refptr<AudioTrackInterface> audio_track =
Steve Anton4171afb2017-11-20 10:20:22 -08003715 stream->FindAudioTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07003716 if (audio_track) {
deadbeefab9b2d12015-10-14 11:33:11 -07003717 stream->RemoveTrack(audio_track);
deadbeefab9b2d12015-10-14 11:33:11 -07003718 }
3719 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
perkjd61bf802016-03-24 03:16:19 -07003720 // Stopping or destroying a VideoRtpReceiver will end the
3721 // VideoRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08003722 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07003723 rtc::scoped_refptr<VideoTrackInterface> video_track =
Steve Anton4171afb2017-11-20 10:20:22 -08003724 stream->FindVideoTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07003725 if (video_track) {
perkjd61bf802016-03-24 03:16:19 -07003726 // There's no guarantee the track is still available, e.g. the track may
3727 // have been removed from the stream by an application.
deadbeefab9b2d12015-10-14 11:33:11 -07003728 stream->RemoveTrack(video_track);
deadbeefab9b2d12015-10-14 11:33:11 -07003729 }
3730 } else {
nisseede5da42017-01-12 05:15:36 -08003731 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07003732 }
Henrik Boström933d8b02017-10-10 10:05:16 -07003733 if (receiver) {
3734 observer_->OnRemoveTrack(receiver);
3735 }
deadbeefab9b2d12015-10-14 11:33:11 -07003736}
3737
3738void PeerConnection::UpdateEndedRemoteMediaStreams() {
3739 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams_to_remove;
3740 for (size_t i = 0; i < remote_streams_->count(); ++i) {
3741 MediaStreamInterface* stream = remote_streams_->at(i);
3742 if (stream->GetAudioTracks().empty() && stream->GetVideoTracks().empty()) {
3743 streams_to_remove.push_back(stream);
3744 }
3745 }
3746
Taylor Brandstetter98cde262016-05-31 13:02:21 -07003747 for (auto& stream : streams_to_remove) {
deadbeefab9b2d12015-10-14 11:33:11 -07003748 remote_streams_->RemoveStream(stream);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07003749 observer_->OnRemoveStream(std::move(stream));
deadbeefab9b2d12015-10-14 11:33:11 -07003750 }
3751}
3752
Steve Anton4171afb2017-11-20 10:20:22 -08003753void PeerConnection::UpdateLocalSenders(
deadbeefab9b2d12015-10-14 11:33:11 -07003754 const std::vector<cricket::StreamParams>& streams,
3755 cricket::MediaType media_type) {
Steve Anton4171afb2017-11-20 10:20:22 -08003756 std::vector<RtpSenderInfo>* current_senders = GetLocalSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07003757
3758 // Find removed tracks. I.e., tracks where the track id, stream label or ssrc
3759 // don't match the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08003760 for (auto sender_it = current_senders->begin();
3761 sender_it != current_senders->end();
3762 /* incremented manually */) {
3763 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07003764 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08003765 cricket::GetStreamBySsrc(streams, info.first_ssrc);
3766 if (!params || params->id != info.sender_id ||
deadbeefab9b2d12015-10-14 11:33:11 -07003767 params->sync_label != info.stream_label) {
Steve Anton4171afb2017-11-20 10:20:22 -08003768 OnLocalSenderRemoved(info, media_type);
3769 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07003770 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08003771 ++sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07003772 }
3773 }
3774
Steve Anton4171afb2017-11-20 10:20:22 -08003775 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07003776 for (const cricket::StreamParams& params : streams) {
3777 // The sync_label is the MediaStream label and the |stream.id| is the
Steve Anton4171afb2017-11-20 10:20:22 -08003778 // sender id.
deadbeefab9b2d12015-10-14 11:33:11 -07003779 const std::string& stream_label = params.sync_label;
Steve Anton4171afb2017-11-20 10:20:22 -08003780 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07003781 uint32_t ssrc = params.first_ssrc();
Steve Anton4171afb2017-11-20 10:20:22 -08003782 const RtpSenderInfo* sender_info =
3783 FindSenderInfo(*current_senders, stream_label, sender_id);
3784 if (!sender_info) {
3785 current_senders->push_back(RtpSenderInfo(stream_label, sender_id, ssrc));
3786 OnLocalSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07003787 }
3788 }
3789}
3790
Steve Anton4171afb2017-11-20 10:20:22 -08003791void PeerConnection::OnLocalSenderAdded(const RtpSenderInfo& sender_info,
3792 cricket::MediaType media_type) {
3793 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08003794 if (!sender) {
Steve Anton4171afb2017-11-20 10:20:22 -08003795 RTC_LOG(LS_WARNING) << "An unknown RtpSender with id "
3796 << sender_info.sender_id
Mirko Bonadei675513b2017-11-09 11:09:25 +01003797 << " has been configured in the local description.";
deadbeefab9b2d12015-10-14 11:33:11 -07003798 return;
3799 }
3800
deadbeeffac06552015-11-25 11:26:01 -08003801 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003802 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
3803 << " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08003804 return;
deadbeefab9b2d12015-10-14 11:33:11 -07003805 }
deadbeeffac06552015-11-25 11:26:01 -08003806
Steve Anton4171afb2017-11-20 10:20:22 -08003807 sender->internal()->set_stream_id(sender_info.stream_label);
3808 sender->internal()->SetSsrc(sender_info.first_ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07003809}
3810
Steve Anton4171afb2017-11-20 10:20:22 -08003811void PeerConnection::OnLocalSenderRemoved(const RtpSenderInfo& sender_info,
3812 cricket::MediaType media_type) {
3813 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08003814 if (!sender) {
3815 // This is the normal case. I.e., RemoveStream has been called and the
deadbeefab9b2d12015-10-14 11:33:11 -07003816 // SessionDescriptions has been renegotiated.
3817 return;
3818 }
deadbeeffac06552015-11-25 11:26:01 -08003819
3820 // A sender has been removed from the SessionDescription but it's still
3821 // associated with the PeerConnection. This only occurs if the SDP doesn't
3822 // match with the calls to CreateSender, AddStream and RemoveStream.
3823 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003824 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
3825 << " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08003826 return;
deadbeefab9b2d12015-10-14 11:33:11 -07003827 }
deadbeeffac06552015-11-25 11:26:01 -08003828
Steve Anton4171afb2017-11-20 10:20:22 -08003829 sender->internal()->SetSsrc(0);
deadbeefab9b2d12015-10-14 11:33:11 -07003830}
3831
3832void PeerConnection::UpdateLocalRtpDataChannels(
3833 const cricket::StreamParamsVec& streams) {
3834 std::vector<std::string> existing_channels;
3835
3836 // Find new and active data channels.
3837 for (const cricket::StreamParams& params : streams) {
3838 // |it->sync_label| is actually the data channel label. The reason is that
3839 // we use the same naming of data channels as we do for
3840 // MediaStreams and Tracks.
3841 // For MediaStreams, the sync_label is the MediaStream label and the
3842 // track label is the same as |streamid|.
3843 const std::string& channel_label = params.sync_label;
3844 auto data_channel_it = rtp_data_channels_.find(channel_label);
nisse7ce109a2017-01-31 00:57:56 -08003845 if (data_channel_it == rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003846 RTC_LOG(LS_ERROR) << "channel label not found";
deadbeefab9b2d12015-10-14 11:33:11 -07003847 continue;
3848 }
3849 // Set the SSRC the data channel should use for sending.
3850 data_channel_it->second->SetSendSsrc(params.first_ssrc());
3851 existing_channels.push_back(data_channel_it->first);
3852 }
3853
3854 UpdateClosingRtpDataChannels(existing_channels, true);
3855}
3856
3857void PeerConnection::UpdateRemoteRtpDataChannels(
3858 const cricket::StreamParamsVec& streams) {
3859 std::vector<std::string> existing_channels;
3860
3861 // Find new and active data channels.
3862 for (const cricket::StreamParams& params : streams) {
3863 // The data channel label is either the mslabel or the SSRC if the mslabel
3864 // does not exist. Ex a=ssrc:444330170 mslabel:test1.
3865 std::string label = params.sync_label.empty()
3866 ? rtc::ToString(params.first_ssrc())
3867 : params.sync_label;
3868 auto data_channel_it = rtp_data_channels_.find(label);
3869 if (data_channel_it == rtp_data_channels_.end()) {
3870 // This is a new data channel.
3871 CreateRemoteRtpDataChannel(label, params.first_ssrc());
3872 } else {
3873 data_channel_it->second->SetReceiveSsrc(params.first_ssrc());
3874 }
3875 existing_channels.push_back(label);
3876 }
3877
3878 UpdateClosingRtpDataChannels(existing_channels, false);
3879}
3880
3881void PeerConnection::UpdateClosingRtpDataChannels(
3882 const std::vector<std::string>& active_channels,
3883 bool is_local_update) {
3884 auto it = rtp_data_channels_.begin();
3885 while (it != rtp_data_channels_.end()) {
3886 DataChannel* data_channel = it->second;
3887 if (std::find(active_channels.begin(), active_channels.end(),
3888 data_channel->label()) != active_channels.end()) {
3889 ++it;
3890 continue;
3891 }
3892
3893 if (is_local_update) {
3894 data_channel->SetSendSsrc(0);
3895 } else {
3896 data_channel->RemotePeerRequestClose();
3897 }
3898
3899 if (data_channel->state() == DataChannel::kClosed) {
3900 rtp_data_channels_.erase(it);
3901 it = rtp_data_channels_.begin();
3902 } else {
3903 ++it;
3904 }
3905 }
3906}
3907
3908void PeerConnection::CreateRemoteRtpDataChannel(const std::string& label,
3909 uint32_t remote_ssrc) {
3910 rtc::scoped_refptr<DataChannel> channel(
3911 InternalCreateDataChannel(label, nullptr));
3912 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003913 RTC_LOG(LS_WARNING) << "Remote peer requested a DataChannel but"
3914 << "CreateDataChannel failed.";
deadbeefab9b2d12015-10-14 11:33:11 -07003915 return;
3916 }
3917 channel->SetReceiveSsrc(remote_ssrc);
deadbeefa601f5c2016-06-06 14:27:39 -07003918 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
3919 DataChannelProxy::Create(signaling_thread(), channel);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07003920 observer_->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07003921}
3922
3923rtc::scoped_refptr<DataChannel> PeerConnection::InternalCreateDataChannel(
3924 const std::string& label,
3925 const InternalDataChannelInit* config) {
3926 if (IsClosed()) {
3927 return nullptr;
3928 }
Steve Anton75737c02017-11-06 10:37:17 -08003929 if (data_channel_type() == cricket::DCT_NONE) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003930 RTC_LOG(LS_ERROR)
deadbeefab9b2d12015-10-14 11:33:11 -07003931 << "InternalCreateDataChannel: Data is not supported in this call.";
3932 return nullptr;
3933 }
3934 InternalDataChannelInit new_config =
3935 config ? (*config) : InternalDataChannelInit();
Steve Anton75737c02017-11-06 10:37:17 -08003936 if (data_channel_type() == cricket::DCT_SCTP) {
deadbeefab9b2d12015-10-14 11:33:11 -07003937 if (new_config.id < 0) {
3938 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08003939 if ((GetSctpSslRole(&role)) &&
deadbeefab9b2d12015-10-14 11:33:11 -07003940 !sid_allocator_.AllocateSid(role, &new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003941 RTC_LOG(LS_ERROR)
3942 << "No id can be allocated for the SCTP data channel.";
deadbeefab9b2d12015-10-14 11:33:11 -07003943 return nullptr;
3944 }
3945 } else if (!sid_allocator_.ReserveSid(new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003946 RTC_LOG(LS_ERROR) << "Failed to create a SCTP data channel "
3947 << "because the id is already in use or out of range.";
deadbeefab9b2d12015-10-14 11:33:11 -07003948 return nullptr;
3949 }
3950 }
3951
Steve Anton75737c02017-11-06 10:37:17 -08003952 rtc::scoped_refptr<DataChannel> channel(
3953 DataChannel::Create(this, data_channel_type(), label, new_config));
deadbeefab9b2d12015-10-14 11:33:11 -07003954 if (!channel) {
3955 sid_allocator_.ReleaseSid(new_config.id);
3956 return nullptr;
3957 }
3958
3959 if (channel->data_channel_type() == cricket::DCT_RTP) {
3960 if (rtp_data_channels_.find(channel->label()) != rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003961 RTC_LOG(LS_ERROR) << "DataChannel with label " << channel->label()
3962 << " already exists.";
deadbeefab9b2d12015-10-14 11:33:11 -07003963 return nullptr;
3964 }
3965 rtp_data_channels_[channel->label()] = channel;
3966 } else {
3967 RTC_DCHECK(channel->data_channel_type() == cricket::DCT_SCTP);
3968 sctp_data_channels_.push_back(channel);
3969 channel->SignalClosed.connect(this,
3970 &PeerConnection::OnSctpDataChannelClosed);
3971 }
3972
Steve Anton2d8609c2018-01-23 16:38:46 -08003973 SignalDataChannelCreated_(channel.get());
deadbeefab9b2d12015-10-14 11:33:11 -07003974 return channel;
3975}
3976
3977bool PeerConnection::HasDataChannels() const {
3978 return !rtp_data_channels_.empty() || !sctp_data_channels_.empty();
3979}
3980
3981void PeerConnection::AllocateSctpSids(rtc::SSLRole role) {
3982 for (const auto& channel : sctp_data_channels_) {
3983 if (channel->id() < 0) {
3984 int sid;
3985 if (!sid_allocator_.AllocateSid(role, &sid)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003986 RTC_LOG(LS_ERROR) << "Failed to allocate SCTP sid.";
deadbeefab9b2d12015-10-14 11:33:11 -07003987 continue;
3988 }
3989 channel->SetSctpSid(sid);
3990 }
3991 }
3992}
3993
3994void PeerConnection::OnSctpDataChannelClosed(DataChannel* channel) {
deadbeefbd292462015-12-14 18:15:29 -08003995 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeefab9b2d12015-10-14 11:33:11 -07003996 for (auto it = sctp_data_channels_.begin(); it != sctp_data_channels_.end();
3997 ++it) {
3998 if (it->get() == channel) {
3999 if (channel->id() >= 0) {
4000 sid_allocator_.ReleaseSid(channel->id());
4001 }
deadbeefbd292462015-12-14 18:15:29 -08004002 // Since this method is triggered by a signal from the DataChannel,
4003 // we can't free it directly here; we need to free it asynchronously.
4004 sctp_data_channels_to_free_.push_back(*it);
deadbeefab9b2d12015-10-14 11:33:11 -07004005 sctp_data_channels_.erase(it);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07004006 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_FREE_DATACHANNELS,
4007 nullptr);
deadbeefab9b2d12015-10-14 11:33:11 -07004008 return;
4009 }
4010 }
4011}
4012
deadbeefab9b2d12015-10-14 11:33:11 -07004013void PeerConnection::OnDataChannelDestroyed() {
4014 // Use a temporary copy of the RTP/SCTP DataChannel list because the
4015 // DataChannel may callback to us and try to modify the list.
4016 std::map<std::string, rtc::scoped_refptr<DataChannel>> temp_rtp_dcs;
4017 temp_rtp_dcs.swap(rtp_data_channels_);
4018 for (const auto& kv : temp_rtp_dcs) {
4019 kv.second->OnTransportChannelDestroyed();
4020 }
4021
4022 std::vector<rtc::scoped_refptr<DataChannel>> temp_sctp_dcs;
4023 temp_sctp_dcs.swap(sctp_data_channels_);
4024 for (const auto& channel : temp_sctp_dcs) {
4025 channel->OnTransportChannelDestroyed();
4026 }
4027}
4028
4029void PeerConnection::OnDataChannelOpenMessage(
4030 const std::string& label,
4031 const InternalDataChannelInit& config) {
4032 rtc::scoped_refptr<DataChannel> channel(
4033 InternalCreateDataChannel(label, &config));
4034 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004035 RTC_LOG(LS_ERROR) << "Failed to create DataChannel from the OPEN message.";
deadbeefab9b2d12015-10-14 11:33:11 -07004036 return;
4037 }
4038
deadbeefa601f5c2016-06-06 14:27:39 -07004039 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
4040 DataChannelProxy::Create(signaling_thread(), channel);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07004041 observer_->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07004042}
4043
Steve Anton4171afb2017-11-20 10:20:22 -08004044rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
4045PeerConnection::GetAudioTransceiver() const {
4046 // This method only works with Plan B SDP, where there is a single
4047 // audio/video transceiver.
4048 RTC_DCHECK(!IsUnifiedPlan());
4049 for (auto transceiver : transceivers_) {
4050 if (transceiver->internal()->media_type() == cricket::MEDIA_TYPE_AUDIO) {
4051 return transceiver;
4052 }
4053 }
4054 RTC_NOTREACHED();
4055 return nullptr;
4056}
4057
4058rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
4059PeerConnection::GetVideoTransceiver() const {
4060 // This method only works with Plan B SDP, where there is a single
4061 // audio/video transceiver.
4062 RTC_DCHECK(!IsUnifiedPlan());
4063 for (auto transceiver : transceivers_) {
4064 if (transceiver->internal()->media_type() == cricket::MEDIA_TYPE_VIDEO) {
4065 return transceiver;
4066 }
4067 }
4068 RTC_NOTREACHED();
4069 return nullptr;
4070}
4071
4072// TODO(bugs.webrtc.org/7600): Remove this when multiple transceivers with
4073// individual transceiver directions are supported.
zhihuang1c378ed2017-08-17 14:10:50 -07004074bool PeerConnection::HasRtpSender(cricket::MediaType type) const {
Steve Anton4171afb2017-11-20 10:20:22 -08004075 switch (type) {
4076 case cricket::MEDIA_TYPE_AUDIO:
4077 return !GetAudioTransceiver()->internal()->senders().empty();
4078 case cricket::MEDIA_TYPE_VIDEO:
4079 return !GetVideoTransceiver()->internal()->senders().empty();
4080 case cricket::MEDIA_TYPE_DATA:
4081 return false;
4082 }
4083 RTC_NOTREACHED();
4084 return false;
zhihuang1c378ed2017-08-17 14:10:50 -07004085}
4086
Steve Anton4171afb2017-11-20 10:20:22 -08004087rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
4088PeerConnection::FindSenderForTrack(MediaStreamTrackInterface* track) const {
4089 for (auto transceiver : transceivers_) {
4090 for (auto sender : transceiver->internal()->senders()) {
4091 if (sender->track() == track) {
4092 return sender;
4093 }
4094 }
4095 }
4096 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08004097}
4098
Steve Anton4171afb2017-11-20 10:20:22 -08004099rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
4100PeerConnection::FindSenderById(const std::string& sender_id) const {
4101 for (auto transceiver : transceivers_) {
4102 for (auto sender : transceiver->internal()->senders()) {
4103 if (sender->id() == sender_id) {
4104 return sender;
4105 }
4106 }
4107 }
4108 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07004109}
4110
Steve Anton4171afb2017-11-20 10:20:22 -08004111rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
4112PeerConnection::FindReceiverById(const std::string& receiver_id) const {
4113 for (auto transceiver : transceivers_) {
4114 for (auto receiver : transceiver->internal()->receivers()) {
4115 if (receiver->id() == receiver_id) {
4116 return receiver;
4117 }
4118 }
4119 }
4120 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07004121}
4122
Steve Anton4171afb2017-11-20 10:20:22 -08004123std::vector<PeerConnection::RtpSenderInfo>*
4124PeerConnection::GetRemoteSenderInfos(cricket::MediaType media_type) {
4125 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
4126 media_type == cricket::MEDIA_TYPE_VIDEO);
4127 return (media_type == cricket::MEDIA_TYPE_AUDIO)
4128 ? &remote_audio_sender_infos_
4129 : &remote_video_sender_infos_;
4130}
4131
4132std::vector<PeerConnection::RtpSenderInfo>* PeerConnection::GetLocalSenderInfos(
deadbeefab9b2d12015-10-14 11:33:11 -07004133 cricket::MediaType media_type) {
4134 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
4135 media_type == cricket::MEDIA_TYPE_VIDEO);
Steve Anton4171afb2017-11-20 10:20:22 -08004136 return (media_type == cricket::MEDIA_TYPE_AUDIO) ? &local_audio_sender_infos_
4137 : &local_video_sender_infos_;
deadbeefab9b2d12015-10-14 11:33:11 -07004138}
4139
Steve Anton4171afb2017-11-20 10:20:22 -08004140const PeerConnection::RtpSenderInfo* PeerConnection::FindSenderInfo(
4141 const std::vector<PeerConnection::RtpSenderInfo>& infos,
deadbeefab9b2d12015-10-14 11:33:11 -07004142 const std::string& stream_label,
Steve Anton4171afb2017-11-20 10:20:22 -08004143 const std::string sender_id) const {
4144 for (const RtpSenderInfo& sender_info : infos) {
4145 if (sender_info.stream_label == stream_label &&
4146 sender_info.sender_id == sender_id) {
4147 return &sender_info;
deadbeefab9b2d12015-10-14 11:33:11 -07004148 }
4149 }
4150 return nullptr;
4151}
4152
4153DataChannel* PeerConnection::FindDataChannelBySid(int sid) const {
4154 for (const auto& channel : sctp_data_channels_) {
4155 if (channel->id() == sid) {
4156 return channel;
4157 }
4158 }
4159 return nullptr;
4160}
4161
deadbeef91dd5672016-05-18 16:55:30 -07004162bool PeerConnection::InitializePortAllocator_n(
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004163 const RTCConfiguration& configuration) {
4164 cricket::ServerAddresses stun_servers;
4165 std::vector<cricket::RelayServerConfig> turn_servers;
deadbeef293e9262017-01-11 12:28:30 -08004166 if (ParseIceServers(configuration.servers, &stun_servers, &turn_servers) !=
4167 RTCErrorType::NONE) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004168 return false;
4169 }
4170
Taylor Brandstetterf8e65772016-06-27 17:20:15 -07004171 port_allocator_->Initialize();
4172
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004173 // To handle both internal and externally created port allocator, we will
4174 // enable BUNDLE here.
4175 int portallocator_flags = port_allocator_->flags();
4176 portallocator_flags |= cricket::PORTALLOCATOR_ENABLE_SHARED_SOCKET |
zhihuangb09b3f92017-03-07 14:40:51 -08004177 cricket::PORTALLOCATOR_ENABLE_IPV6 |
4178 cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI;
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004179 // If the disable-IPv6 flag was specified, we'll not override it
4180 // by experiment.
4181 if (configuration.disable_ipv6) {
4182 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
sprangc1b57a12017-02-28 08:50:47 -08004183 } else if (webrtc::field_trial::FindFullName("WebRTC-IPv6Default")
4184 .find("Disabled") == 0) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004185 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
4186 }
4187
zhihuangb09b3f92017-03-07 14:40:51 -08004188 if (configuration.disable_ipv6_on_wifi) {
4189 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI);
Mirko Bonadei675513b2017-11-09 11:09:25 +01004190 RTC_LOG(LS_INFO) << "IPv6 candidates on Wi-Fi are disabled.";
zhihuangb09b3f92017-03-07 14:40:51 -08004191 }
4192
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004193 if (configuration.tcp_candidate_policy == kTcpCandidatePolicyDisabled) {
4194 portallocator_flags |= cricket::PORTALLOCATOR_DISABLE_TCP;
Mirko Bonadei675513b2017-11-09 11:09:25 +01004195 RTC_LOG(LS_INFO) << "TCP candidates are disabled.";
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004196 }
4197
honghaiz60347052016-05-31 18:29:12 -07004198 if (configuration.candidate_network_policy ==
4199 kCandidateNetworkPolicyLowCost) {
4200 portallocator_flags |= cricket::PORTALLOCATOR_DISABLE_COSTLY_NETWORKS;
Mirko Bonadei675513b2017-11-09 11:09:25 +01004201 RTC_LOG(LS_INFO) << "Do not gather candidates on high-cost networks";
honghaiz60347052016-05-31 18:29:12 -07004202 }
4203
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004204 port_allocator_->set_flags(portallocator_flags);
4205 // No step delay is used while allocating ports.
4206 port_allocator_->set_step_delay(cricket::kMinimumStepDelay);
4207 port_allocator_->set_candidate_filter(
4208 ConvertIceTransportTypeToCandidateFilter(configuration.type));
deadbeefd21eab32017-07-26 16:50:11 -07004209 port_allocator_->set_max_ipv6_networks(configuration.max_ipv6_networks);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004210
4211 // Call this last since it may create pooled allocator sessions using the
4212 // properties set above.
4213 port_allocator_->SetConfiguration(stun_servers, turn_servers,
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -07004214 configuration.ice_candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02004215 configuration.prune_turn_ports,
4216 configuration.turn_customizer);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004217 return true;
4218}
4219
deadbeef91dd5672016-05-18 16:55:30 -07004220bool PeerConnection::ReconfigurePortAllocator_n(
deadbeef293e9262017-01-11 12:28:30 -08004221 const cricket::ServerAddresses& stun_servers,
4222 const std::vector<cricket::RelayServerConfig>& turn_servers,
4223 IceTransportsType type,
4224 int candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02004225 bool prune_turn_ports,
4226 webrtc::TurnCustomizer* turn_customizer) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004227 port_allocator_->set_candidate_filter(
deadbeef293e9262017-01-11 12:28:30 -08004228 ConvertIceTransportTypeToCandidateFilter(type));
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004229 // Call this last since it may create pooled allocator sessions using the
4230 // candidate filter set above.
deadbeef6de92f92016-12-12 18:49:32 -08004231 return port_allocator_->SetConfiguration(
Jonas Orelandbdcee282017-10-10 14:01:40 +02004232 stun_servers, turn_servers, candidate_pool_size, prune_turn_ports,
4233 turn_customizer);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004234}
4235
Steve Antonba818672017-11-06 10:21:57 -08004236cricket::ChannelManager* PeerConnection::channel_manager() const {
4237 return factory_->channel_manager();
4238}
4239
4240MetricsObserverInterface* PeerConnection::metrics_observer() const {
4241 return uma_observer_;
4242}
4243
Elad Alon99c3fe52017-10-13 16:29:40 +02004244bool PeerConnection::StartRtcEventLog_w(
Bjorn Tereliusde939432017-11-20 17:38:14 +01004245 std::unique_ptr<RtcEventLogOutput> output,
4246 int64_t output_period_ms) {
zhihuang77985012017-02-07 15:45:16 -08004247 if (!event_log_) {
4248 return false;
4249 }
Bjorn Tereliusde939432017-11-20 17:38:14 +01004250 return event_log_->StartLogging(std::move(output), output_period_ms);
ivoc14d5dbe2016-07-04 07:06:55 -07004251}
4252
4253void PeerConnection::StopRtcEventLog_w() {
zhihuang77985012017-02-07 15:45:16 -08004254 if (event_log_) {
4255 event_log_->StopLogging();
4256 }
ivoc14d5dbe2016-07-04 07:06:55 -07004257}
nisseeaabdf62017-05-05 02:23:02 -07004258
Steve Anton75737c02017-11-06 10:37:17 -08004259cricket::BaseChannel* PeerConnection::GetChannel(
4260 const std::string& content_name) {
Steve Antondcc3c022017-12-22 16:02:54 -08004261 for (auto transceiver : transceivers_) {
4262 cricket::BaseChannel* channel = transceiver->internal()->channel();
4263 if (channel && channel->content_name() == content_name) {
4264 return channel;
4265 }
Steve Anton75737c02017-11-06 10:37:17 -08004266 }
4267 if (rtp_data_channel() &&
4268 rtp_data_channel()->content_name() == content_name) {
4269 return rtp_data_channel();
4270 }
4271 return nullptr;
4272}
4273
4274bool PeerConnection::GetSctpSslRole(rtc::SSLRole* role) {
4275 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004276 RTC_LOG(LS_INFO)
4277 << "Local and Remote descriptions must be applied to get the "
4278 << "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08004279 return false;
4280 }
4281 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004282 RTC_LOG(LS_INFO) << "Non-rejected SCTP m= section is needed to get the "
4283 << "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08004284 return false;
4285 }
4286
4287 return transport_controller_->GetSslRole(*sctp_transport_name_, role);
4288}
4289
4290bool PeerConnection::GetSslRole(const std::string& content_name,
4291 rtc::SSLRole* role) {
4292 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004293 RTC_LOG(LS_INFO)
4294 << "Local and Remote descriptions must be applied to get the "
4295 << "SSL Role of the session.";
Steve Anton75737c02017-11-06 10:37:17 -08004296 return false;
4297 }
4298
4299 return transport_controller_->GetSslRole(GetTransportName(content_name),
4300 role);
4301}
4302
Steve Anton75737c02017-11-06 10:37:17 -08004303// TODO(steveanton): Eventually it'd be nice to store the channels as a single
4304// vector of BaseChannel pointers instead of separate voice and video channel
4305// vectors. At that point, this will become a simple getter.
4306std::vector<cricket::BaseChannel*> PeerConnection::Channels() const {
4307 std::vector<cricket::BaseChannel*> channels;
Steve Anton4171afb2017-11-20 10:20:22 -08004308 if (voice_channel()) {
4309 channels.push_back(voice_channel());
4310 }
4311 if (video_channel()) {
4312 channels.push_back(video_channel());
4313 }
Steve Anton75737c02017-11-06 10:37:17 -08004314 if (rtp_data_channel_) {
4315 channels.push_back(rtp_data_channel_);
4316 }
4317 return channels;
4318}
4319
Steve Antonf8470812017-12-04 10:46:21 -08004320void PeerConnection::SetSessionError(SessionError error,
4321 const std::string& error_desc) {
4322 RTC_DCHECK_RUN_ON(signaling_thread());
4323 if (error != session_error_) {
4324 session_error_ = error;
4325 session_error_desc_ = error_desc;
Steve Anton75737c02017-11-06 10:37:17 -08004326 }
4327}
4328
Steve Anton3828c062017-12-06 10:34:51 -08004329RTCError PeerConnection::UpdateSessionState(SdpType type,
Steve Anton8a006912017-12-04 15:25:56 -08004330 cricket::ContentSource source) {
4331 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08004332
4333 // If there's already a pending error then no state transition should happen.
4334 // But all call-sites should be verifying this before calling us!
Steve Antonf8470812017-12-04 10:46:21 -08004335 RTC_DCHECK(session_error() == SessionError::kNone);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004336
4337 // If this is an answer then we know whether to BUNDLE or not. If both the
4338 // local and remote side have agreed to BUNDLE, go ahead and enable it.
Steve Anton3828c062017-12-06 10:34:51 -08004339 if (type == SdpType::kAnswer) {
Steve Anton75737c02017-11-06 10:37:17 -08004340 const cricket::ContentGroup* local_bundle =
4341 local_description()->description()->GetGroupByName(
4342 cricket::GROUP_TYPE_BUNDLE);
4343 const cricket::ContentGroup* remote_bundle =
4344 remote_description()->description()->GetGroupByName(
4345 cricket::GROUP_TYPE_BUNDLE);
4346 if (local_bundle && remote_bundle) {
4347 // The answerer decides the transport to bundle on.
4348 const cricket::ContentGroup* answer_bundle =
4349 (source == cricket::CS_LOCAL ? local_bundle : remote_bundle);
4350 if (!EnableBundle(*answer_bundle)) {
Steve Anton8a006912017-12-04 15:25:56 -08004351 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
4352 kEnableBundleFailed);
Steve Anton75737c02017-11-06 10:37:17 -08004353 }
4354 }
Steve Anton75737c02017-11-06 10:37:17 -08004355 }
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004356
4357 // Only push down the transport description after potentially enabling BUNDLE;
4358 // we don't want to push down a description on a transport about to be
4359 // destroyed.
Steve Anton3828c062017-12-06 10:34:51 -08004360 RTCError error = PushdownTransportDescription(source, type);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004361 if (!error.ok()) {
4362 return error;
4363 }
4364
4365 // If this is answer-ish we're ready to let media flow.
Steve Anton3828c062017-12-06 10:34:51 -08004366 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Antoned10bd92017-12-05 10:52:59 -08004367 EnableSending();
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004368 }
4369
4370 // Update the signaling state according to the specified state machine (see
4371 // https://w3c.github.io/webrtc-pc/#rtcsignalingstate-enum).
Steve Anton3828c062017-12-06 10:34:51 -08004372 if (type == SdpType::kOffer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004373 ChangeSignalingState(source == cricket::CS_LOCAL
4374 ? PeerConnectionInterface::kHaveLocalOffer
4375 : PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton3828c062017-12-06 10:34:51 -08004376 } else if (type == SdpType::kPrAnswer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004377 ChangeSignalingState(source == cricket::CS_LOCAL
4378 ? PeerConnectionInterface::kHaveLocalPrAnswer
4379 : PeerConnectionInterface::kHaveRemotePrAnswer);
4380 } else {
Steve Anton3828c062017-12-06 10:34:51 -08004381 RTC_DCHECK(type == SdpType::kAnswer);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004382 ChangeSignalingState(PeerConnectionInterface::kStable);
4383 }
4384
4385 // Update internal objects according to the session description's media
4386 // descriptions.
Steve Anton3828c062017-12-06 10:34:51 -08004387 error = PushdownMediaDescription(type, source);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004388 if (!error.ok()) {
4389 SetSessionError(SessionError::kContent, error.message());
4390 }
4391 if (session_error() != SessionError::kNone) {
4392 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
4393 }
4394
Steve Anton8a006912017-12-04 15:25:56 -08004395 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08004396}
4397
Steve Anton8a006912017-12-04 15:25:56 -08004398RTCError PeerConnection::PushdownMediaDescription(
Steve Anton3828c062017-12-06 10:34:51 -08004399 SdpType type,
Steve Anton8a006912017-12-04 15:25:56 -08004400 cricket::ContentSource source) {
Steve Antoned10bd92017-12-05 10:52:59 -08004401 const SessionDescriptionInterface* sdesc =
4402 (source == cricket::CS_LOCAL ? local_description()
4403 : remote_description());
Steve Anton75737c02017-11-06 10:37:17 -08004404 RTC_DCHECK(sdesc);
Steve Antoned10bd92017-12-05 10:52:59 -08004405
4406 // Push down the new SDP media section for each audio/video transceiver.
4407 for (auto transceiver : transceivers_) {
Steve Anton75737c02017-11-06 10:37:17 -08004408 const ContentInfo* content_info =
Steve Antoned10bd92017-12-05 10:52:59 -08004409 FindMediaSectionForTransceiver(transceiver, sdesc);
4410 cricket::BaseChannel* channel = transceiver->internal()->channel();
4411 if (!channel || !content_info || content_info->rejected) {
Steve Anton75737c02017-11-06 10:37:17 -08004412 continue;
4413 }
4414 const MediaContentDescription* content_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08004415 content_info->media_description();
Steve Antoned10bd92017-12-05 10:52:59 -08004416 if (!content_desc) {
4417 continue;
4418 }
4419 std::string error;
4420 bool success =
4421 (source == cricket::CS_LOCAL)
Steve Anton3828c062017-12-06 10:34:51 -08004422 ? channel->SetLocalContent(content_desc, type, &error)
4423 : channel->SetRemoteContent(content_desc, type, &error);
Steve Antoned10bd92017-12-05 10:52:59 -08004424 if (!success) {
4425 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, std::move(error));
4426 }
4427 }
4428
4429 // If using the RtpDataChannel, push down the new SDP section for it too.
4430 if (rtp_data_channel_) {
4431 const ContentInfo* data_content =
4432 cricket::GetFirstDataContent(sdesc->description());
4433 if (data_content && !data_content->rejected) {
4434 const MediaContentDescription* data_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08004435 data_content->media_description();
Steve Antoned10bd92017-12-05 10:52:59 -08004436 if (data_desc) {
4437 std::string error;
4438 bool success =
4439 (source == cricket::CS_LOCAL)
Steve Anton3828c062017-12-06 10:34:51 -08004440 ? rtp_data_channel_->SetLocalContent(data_desc, type, &error)
4441 : rtp_data_channel_->SetRemoteContent(data_desc, type,
Steve Antoned10bd92017-12-05 10:52:59 -08004442 &error);
4443 if (!success) {
4444 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
4445 std::move(error));
4446 }
Steve Anton75737c02017-11-06 10:37:17 -08004447 }
4448 }
4449 }
Steve Antoned10bd92017-12-05 10:52:59 -08004450
Steve Anton75737c02017-11-06 10:37:17 -08004451 // Need complete offer/answer with an SCTP m= section before starting SCTP,
4452 // according to https://tools.ietf.org/html/draft-ietf-mmusic-sctp-sdp-19
4453 if (sctp_transport_ && local_description() && remote_description() &&
4454 cricket::GetFirstDataContent(local_description()->description()) &&
4455 cricket::GetFirstDataContent(remote_description()->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08004456 bool success = network_thread()->Invoke<bool>(
Steve Anton75737c02017-11-06 10:37:17 -08004457 RTC_FROM_HERE,
4458 rtc::Bind(&PeerConnection::PushdownSctpParameters_n, this, source));
Steve Anton8a006912017-12-04 15:25:56 -08004459 if (!success) {
4460 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
4461 "Failed to push down SCTP parameters.");
4462 }
Steve Anton75737c02017-11-06 10:37:17 -08004463 }
Steve Antoned10bd92017-12-05 10:52:59 -08004464
Steve Anton8a006912017-12-04 15:25:56 -08004465 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08004466}
4467
4468bool PeerConnection::PushdownSctpParameters_n(cricket::ContentSource source) {
4469 RTC_DCHECK(network_thread()->IsCurrent());
4470 RTC_DCHECK(local_description());
4471 RTC_DCHECK(remote_description());
4472 // Apply the SCTP port (which is hidden inside a DataCodec structure...)
4473 // When we support "max-message-size", that would also be pushed down here.
4474 return sctp_transport_->Start(
4475 GetSctpPort(local_description()->description()),
4476 GetSctpPort(remote_description()->description()));
4477}
4478
Steve Anton8a006912017-12-04 15:25:56 -08004479RTCError PeerConnection::PushdownTransportDescription(
4480 cricket::ContentSource source,
Steve Anton3828c062017-12-06 10:34:51 -08004481 SdpType type) {
Steve Anton8a006912017-12-04 15:25:56 -08004482 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08004483
Steve Anton8a006912017-12-04 15:25:56 -08004484 const SessionDescriptionInterface* sdesc =
4485 (source == cricket::CS_LOCAL ? local_description()
4486 : remote_description());
4487 RTC_DCHECK(sdesc);
4488 for (const cricket::TransportInfo& tinfo :
4489 sdesc->description()->transport_infos()) {
4490 std::string error;
4491 bool success;
4492 if (source == cricket::CS_LOCAL) {
4493 success = transport_controller_->SetLocalTransportDescription(
Steve Anton3828c062017-12-06 10:34:51 -08004494 tinfo.content_name, tinfo.description, type, &error);
Steve Anton8a006912017-12-04 15:25:56 -08004495 } else {
4496 success = transport_controller_->SetRemoteTransportDescription(
Steve Anton3828c062017-12-06 10:34:51 -08004497 tinfo.content_name, tinfo.description, type, &error);
Steve Anton8a006912017-12-04 15:25:56 -08004498 }
4499 if (!success) {
Steve Antondcc3c022017-12-22 16:02:54 -08004500 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
4501 "Failed to push down transport description for " +
4502 tinfo.content_name + ": " + error);
Steve Anton75737c02017-11-06 10:37:17 -08004503 }
4504 }
4505
Steve Anton8a006912017-12-04 15:25:56 -08004506 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08004507}
4508
4509bool PeerConnection::GetTransportDescription(
4510 const SessionDescription* description,
4511 const std::string& content_name,
4512 cricket::TransportDescription* tdesc) {
4513 if (!description || !tdesc) {
4514 return false;
4515 }
4516 const TransportInfo* transport_info =
4517 description->GetTransportInfoByName(content_name);
4518 if (!transport_info) {
4519 return false;
4520 }
4521 *tdesc = transport_info->description;
4522 return true;
4523}
4524
4525bool PeerConnection::EnableBundle(const cricket::ContentGroup& bundle) {
4526 const std::string* first_content_name = bundle.FirstContentName();
4527 if (!first_content_name) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004528 RTC_LOG(LS_WARNING) << "Tried to BUNDLE with no contents.";
Steve Anton75737c02017-11-06 10:37:17 -08004529 return false;
4530 }
4531 const std::string& transport_name = *first_content_name;
4532
4533 auto maybe_set_transport = [this, bundle,
4534 transport_name](cricket::BaseChannel* ch) {
4535 if (!ch || !bundle.HasContentName(ch->content_name())) {
Steve Antoned10bd92017-12-05 10:52:59 -08004536 return;
Steve Anton75737c02017-11-06 10:37:17 -08004537 }
4538
4539 std::string old_transport_name = ch->transport_name();
4540 if (old_transport_name == transport_name) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004541 RTC_LOG(LS_INFO) << "BUNDLE already enabled for " << ch->content_name()
4542 << " on " << transport_name << ".";
Steve Antoned10bd92017-12-05 10:52:59 -08004543 return;
Steve Anton75737c02017-11-06 10:37:17 -08004544 }
4545
4546 cricket::DtlsTransportInternal* rtp_dtls_transport =
4547 transport_controller_->CreateDtlsTransport(
4548 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4549 bool need_rtcp = (ch->rtcp_dtls_transport() != nullptr);
4550 cricket::DtlsTransportInternal* rtcp_dtls_transport = nullptr;
4551 if (need_rtcp) {
4552 rtcp_dtls_transport = transport_controller_->CreateDtlsTransport(
4553 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
4554 }
4555
4556 ch->SetTransports(rtp_dtls_transport, rtcp_dtls_transport);
Mirko Bonadei675513b2017-11-09 11:09:25 +01004557 RTC_LOG(LS_INFO) << "Enabled BUNDLE for " << ch->content_name() << " on "
4558 << transport_name << ".";
Steve Anton75737c02017-11-06 10:37:17 -08004559 transport_controller_->DestroyDtlsTransport(
4560 old_transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4561 // If the channel needs rtcp, it means that the channel used to have a
4562 // rtcp transport which needs to be deleted now.
4563 if (need_rtcp) {
4564 transport_controller_->DestroyDtlsTransport(
4565 old_transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
4566 }
Steve Anton75737c02017-11-06 10:37:17 -08004567 };
4568
Steve Antoned10bd92017-12-05 10:52:59 -08004569 for (auto transceiver : transceivers_) {
4570 maybe_set_transport(transceiver->internal()->channel());
Steve Anton75737c02017-11-06 10:37:17 -08004571 }
Steve Antoned10bd92017-12-05 10:52:59 -08004572 maybe_set_transport(rtp_data_channel_);
4573
Steve Anton75737c02017-11-06 10:37:17 -08004574 // For SCTP, transport creation/deletion happens here instead of in the
4575 // object itself.
4576 if (sctp_transport_) {
4577 RTC_DCHECK(sctp_transport_name_);
4578 RTC_DCHECK(sctp_content_name_);
4579 if (transport_name != *sctp_transport_name_ &&
4580 bundle.HasContentName(*sctp_content_name_)) {
4581 network_thread()->Invoke<void>(
4582 RTC_FROM_HERE, rtc::Bind(&PeerConnection::ChangeSctpTransport_n, this,
4583 transport_name));
4584 }
4585 }
4586
4587 return true;
4588}
4589
Steve Anton75737c02017-11-06 10:37:17 -08004590cricket::IceConfig PeerConnection::ParseIceConfig(
4591 const PeerConnectionInterface::RTCConfiguration& config) const {
4592 cricket::ContinualGatheringPolicy gathering_policy;
4593 // TODO(honghaiz): Add the third continual gathering policy in
4594 // PeerConnectionInterface and map it to GATHER_CONTINUALLY_AND_RECOVER.
4595 switch (config.continual_gathering_policy) {
4596 case PeerConnectionInterface::GATHER_ONCE:
4597 gathering_policy = cricket::GATHER_ONCE;
4598 break;
4599 case PeerConnectionInterface::GATHER_CONTINUALLY:
4600 gathering_policy = cricket::GATHER_CONTINUALLY;
4601 break;
4602 default:
4603 RTC_NOTREACHED();
4604 gathering_policy = cricket::GATHER_ONCE;
4605 }
4606 cricket::IceConfig ice_config;
4607 ice_config.receiving_timeout = config.ice_connection_receiving_timeout;
4608 ice_config.prioritize_most_likely_candidate_pairs =
4609 config.prioritize_most_likely_ice_candidate_pairs;
4610 ice_config.backup_connection_ping_interval =
4611 config.ice_backup_candidate_pair_ping_interval;
4612 ice_config.continual_gathering_policy = gathering_policy;
4613 ice_config.presume_writable_when_fully_relayed =
4614 config.presume_writable_when_fully_relayed;
4615 ice_config.ice_check_min_interval = config.ice_check_min_interval;
4616 ice_config.regather_all_networks_interval_range =
4617 config.ice_regather_interval_range;
4618 return ice_config;
4619}
4620
Steve Anton75737c02017-11-06 10:37:17 -08004621bool PeerConnection::GetLocalTrackIdBySsrc(uint32_t ssrc,
4622 std::string* track_id) {
4623 if (!local_description()) {
4624 return false;
4625 }
4626 return webrtc::GetTrackIdBySsrc(local_description()->description(), ssrc,
4627 track_id);
4628}
4629
4630bool PeerConnection::GetRemoteTrackIdBySsrc(uint32_t ssrc,
4631 std::string* track_id) {
4632 if (!remote_description()) {
4633 return false;
4634 }
4635 return webrtc::GetTrackIdBySsrc(remote_description()->description(), ssrc,
4636 track_id);
4637}
4638
4639bool PeerConnection::SendData(const cricket::SendDataParams& params,
4640 const rtc::CopyOnWriteBuffer& payload,
4641 cricket::SendDataResult* result) {
4642 if (!rtp_data_channel_ && !sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004643 RTC_LOG(LS_ERROR) << "SendData called when rtp_data_channel_ "
4644 << "and sctp_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08004645 return false;
4646 }
4647 return rtp_data_channel_
4648 ? rtp_data_channel_->SendData(params, payload, result)
4649 : network_thread()->Invoke<bool>(
4650 RTC_FROM_HERE,
4651 Bind(&cricket::SctpTransportInternal::SendData,
4652 sctp_transport_.get(), params, payload, result));
4653}
4654
4655bool PeerConnection::ConnectDataChannel(DataChannel* webrtc_data_channel) {
4656 if (!rtp_data_channel_ && !sctp_transport_) {
4657 // Don't log an error here, because DataChannels are expected to call
4658 // ConnectDataChannel in this state. It's the only way to initially tell
4659 // whether or not the underlying transport is ready.
4660 return false;
4661 }
4662 if (rtp_data_channel_) {
4663 rtp_data_channel_->SignalReadyToSendData.connect(
4664 webrtc_data_channel, &DataChannel::OnChannelReady);
4665 rtp_data_channel_->SignalDataReceived.connect(webrtc_data_channel,
4666 &DataChannel::OnDataReceived);
4667 } else {
4668 SignalSctpReadyToSendData.connect(webrtc_data_channel,
4669 &DataChannel::OnChannelReady);
4670 SignalSctpDataReceived.connect(webrtc_data_channel,
4671 &DataChannel::OnDataReceived);
4672 SignalSctpStreamClosedRemotely.connect(
4673 webrtc_data_channel, &DataChannel::OnStreamClosedRemotely);
4674 }
4675 return true;
4676}
4677
4678void PeerConnection::DisconnectDataChannel(DataChannel* webrtc_data_channel) {
4679 if (!rtp_data_channel_ && !sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004680 RTC_LOG(LS_ERROR)
4681 << "DisconnectDataChannel called when rtp_data_channel_ and "
4682 "sctp_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08004683 return;
4684 }
4685 if (rtp_data_channel_) {
4686 rtp_data_channel_->SignalReadyToSendData.disconnect(webrtc_data_channel);
4687 rtp_data_channel_->SignalDataReceived.disconnect(webrtc_data_channel);
4688 } else {
4689 SignalSctpReadyToSendData.disconnect(webrtc_data_channel);
4690 SignalSctpDataReceived.disconnect(webrtc_data_channel);
4691 SignalSctpStreamClosedRemotely.disconnect(webrtc_data_channel);
4692 }
4693}
4694
4695void PeerConnection::AddSctpDataStream(int sid) {
4696 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004697 RTC_LOG(LS_ERROR)
4698 << "AddSctpDataStream called when sctp_transport_ is NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08004699 return;
4700 }
4701 network_thread()->Invoke<void>(
4702 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::OpenStream,
4703 sctp_transport_.get(), sid));
4704}
4705
4706void PeerConnection::RemoveSctpDataStream(int sid) {
4707 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004708 RTC_LOG(LS_ERROR) << "RemoveSctpDataStream called when sctp_transport_ is "
4709 << "NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08004710 return;
4711 }
4712 network_thread()->Invoke<void>(
4713 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::ResetStream,
4714 sctp_transport_.get(), sid));
4715}
4716
4717bool PeerConnection::ReadyToSendData() const {
4718 return (rtp_data_channel_ && rtp_data_channel_->ready_to_send_data()) ||
4719 sctp_ready_to_send_data_;
4720}
4721
4722std::unique_ptr<SessionStats> PeerConnection::GetSessionStats_s() {
4723 RTC_DCHECK(signaling_thread()->IsCurrent());
4724 ChannelNamePairs channel_name_pairs;
4725 if (voice_channel()) {
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004726 channel_name_pairs.voice = ChannelNamePair(
4727 voice_channel()->content_name(), voice_channel()->transport_name());
Steve Anton75737c02017-11-06 10:37:17 -08004728 }
4729 if (video_channel()) {
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004730 channel_name_pairs.video = ChannelNamePair(
4731 video_channel()->content_name(), video_channel()->transport_name());
Steve Anton75737c02017-11-06 10:37:17 -08004732 }
4733 if (rtp_data_channel()) {
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004734 channel_name_pairs.data =
Steve Anton75737c02017-11-06 10:37:17 -08004735 ChannelNamePair(rtp_data_channel()->content_name(),
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004736 rtp_data_channel()->transport_name());
Steve Anton75737c02017-11-06 10:37:17 -08004737 }
4738 if (sctp_transport_) {
4739 RTC_DCHECK(sctp_content_name_);
4740 RTC_DCHECK(sctp_transport_name_);
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004741 channel_name_pairs.data =
4742 ChannelNamePair(*sctp_content_name_, *sctp_transport_name_);
Steve Anton75737c02017-11-06 10:37:17 -08004743 }
4744 return GetSessionStats(channel_name_pairs);
4745}
4746
4747std::unique_ptr<SessionStats> PeerConnection::GetSessionStats(
4748 const ChannelNamePairs& channel_name_pairs) {
4749 if (network_thread()->IsCurrent()) {
4750 return GetSessionStats_n(channel_name_pairs);
4751 }
4752 return network_thread()->Invoke<std::unique_ptr<SessionStats>>(
4753 RTC_FROM_HERE,
4754 rtc::Bind(&PeerConnection::GetSessionStats_n, this, channel_name_pairs));
4755}
4756
4757bool PeerConnection::GetLocalCertificate(
4758 const std::string& transport_name,
4759 rtc::scoped_refptr<rtc::RTCCertificate>* certificate) {
4760 return transport_controller_->GetLocalCertificate(transport_name,
4761 certificate);
4762}
4763
4764std::unique_ptr<rtc::SSLCertificate> PeerConnection::GetRemoteSSLCertificate(
4765 const std::string& transport_name) {
4766 return transport_controller_->GetRemoteSSLCertificate(transport_name);
4767}
4768
4769cricket::DataChannelType PeerConnection::data_channel_type() const {
4770 return data_channel_type_;
4771}
4772
4773bool PeerConnection::IceRestartPending(const std::string& content_name) const {
4774 return pending_ice_restarts_.find(content_name) !=
4775 pending_ice_restarts_.end();
4776}
4777
Steve Anton75737c02017-11-06 10:37:17 -08004778bool PeerConnection::NeedsIceRestart(const std::string& content_name) const {
4779 return transport_controller_->NeedsIceRestart(content_name);
4780}
4781
4782void PeerConnection::OnCertificateReady(
4783 const rtc::scoped_refptr<rtc::RTCCertificate>& certificate) {
4784 transport_controller_->SetLocalCertificate(certificate);
4785}
4786
4787void PeerConnection::OnDtlsSrtpSetupFailure(cricket::BaseChannel*, bool rtcp) {
Steve Antonf8470812017-12-04 10:46:21 -08004788 SetSessionError(SessionError::kTransport,
4789 rtcp ? kDtlsSrtpSetupFailureRtcp : kDtlsSrtpSetupFailureRtp);
Steve Anton75737c02017-11-06 10:37:17 -08004790}
4791
4792void PeerConnection::OnTransportControllerConnectionState(
4793 cricket::IceConnectionState state) {
4794 switch (state) {
4795 case cricket::kIceConnectionConnecting:
4796 // If the current state is Connected or Completed, then there were
4797 // writable channels but now there are not, so the next state must
4798 // be Disconnected.
4799 // kIceConnectionConnecting is currently used as the default,
4800 // un-connected state by the TransportController, so its only use is
4801 // detecting disconnections.
4802 if (ice_connection_state_ ==
4803 PeerConnectionInterface::kIceConnectionConnected ||
4804 ice_connection_state_ ==
4805 PeerConnectionInterface::kIceConnectionCompleted) {
4806 SetIceConnectionState(
4807 PeerConnectionInterface::kIceConnectionDisconnected);
4808 }
4809 break;
4810 case cricket::kIceConnectionFailed:
4811 SetIceConnectionState(PeerConnectionInterface::kIceConnectionFailed);
4812 break;
4813 case cricket::kIceConnectionConnected:
Mirko Bonadei675513b2017-11-09 11:09:25 +01004814 RTC_LOG(LS_INFO) << "Changing to ICE connected state because "
4815 << "all transports are writable.";
Steve Anton75737c02017-11-06 10:37:17 -08004816 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
4817 break;
4818 case cricket::kIceConnectionCompleted:
Mirko Bonadei675513b2017-11-09 11:09:25 +01004819 RTC_LOG(LS_INFO) << "Changing to ICE completed state because "
4820 << "all transports are complete.";
Steve Anton75737c02017-11-06 10:37:17 -08004821 if (ice_connection_state_ !=
4822 PeerConnectionInterface::kIceConnectionConnected) {
4823 // If jumping directly from "checking" to "connected",
4824 // signal "connected" first.
4825 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
4826 }
4827 SetIceConnectionState(PeerConnectionInterface::kIceConnectionCompleted);
4828 if (metrics_observer()) {
4829 ReportTransportStats();
4830 }
4831 break;
4832 default:
4833 RTC_NOTREACHED();
4834 }
4835}
4836
4837void PeerConnection::OnTransportControllerCandidatesGathered(
4838 const std::string& transport_name,
4839 const cricket::Candidates& candidates) {
4840 RTC_DCHECK(signaling_thread()->IsCurrent());
4841 int sdp_mline_index;
4842 if (!GetLocalCandidateMediaIndex(transport_name, &sdp_mline_index)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004843 RTC_LOG(LS_ERROR)
4844 << "OnTransportControllerCandidatesGathered: content name "
4845 << transport_name << " not found";
Steve Anton75737c02017-11-06 10:37:17 -08004846 return;
4847 }
4848
4849 for (cricket::Candidates::const_iterator citer = candidates.begin();
4850 citer != candidates.end(); ++citer) {
4851 // Use transport_name as the candidate media id.
4852 std::unique_ptr<JsepIceCandidate> candidate(
4853 new JsepIceCandidate(transport_name, sdp_mline_index, *citer));
4854 if (local_description()) {
4855 mutable_local_description()->AddCandidate(candidate.get());
4856 }
4857 OnIceCandidate(std::move(candidate));
4858 }
4859}
4860
4861void PeerConnection::OnTransportControllerCandidatesRemoved(
4862 const std::vector<cricket::Candidate>& candidates) {
4863 RTC_DCHECK(signaling_thread()->IsCurrent());
4864 // Sanity check.
4865 for (const cricket::Candidate& candidate : candidates) {
4866 if (candidate.transport_name().empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004867 RTC_LOG(LS_ERROR) << "OnTransportControllerCandidatesRemoved: "
4868 << "empty content name in candidate "
4869 << candidate.ToString();
Steve Anton75737c02017-11-06 10:37:17 -08004870 return;
4871 }
4872 }
4873
4874 if (local_description()) {
4875 mutable_local_description()->RemoveCandidates(candidates);
4876 }
4877 OnIceCandidatesRemoved(candidates);
4878}
4879
4880void PeerConnection::OnTransportControllerDtlsHandshakeError(
4881 rtc::SSLHandshakeError error) {
4882 if (metrics_observer()) {
4883 metrics_observer()->IncrementEnumCounter(
4884 webrtc::kEnumCounterDtlsHandshakeError, static_cast<int>(error),
4885 static_cast<int>(rtc::SSLHandshakeError::MAX_VALUE));
4886 }
4887}
4888
Steve Antoned10bd92017-12-05 10:52:59 -08004889void PeerConnection::EnableSending() {
4890 for (auto transceiver : transceivers_) {
4891 cricket::BaseChannel* channel = transceiver->internal()->channel();
4892 if (channel && !channel->enabled()) {
4893 channel->Enable(true);
4894 }
Steve Anton75737c02017-11-06 10:37:17 -08004895 }
4896
Steve Anton4171afb2017-11-20 10:20:22 -08004897 if (rtp_data_channel_ && !rtp_data_channel_->enabled()) {
Steve Anton75737c02017-11-06 10:37:17 -08004898 rtp_data_channel_->Enable(true);
Steve Anton4171afb2017-11-20 10:20:22 -08004899 }
Steve Anton75737c02017-11-06 10:37:17 -08004900}
4901
4902// Returns the media index for a local ice candidate given the content name.
4903bool PeerConnection::GetLocalCandidateMediaIndex(
4904 const std::string& content_name,
4905 int* sdp_mline_index) {
4906 if (!local_description() || !sdp_mline_index) {
4907 return false;
4908 }
4909
4910 bool content_found = false;
4911 const ContentInfos& contents = local_description()->description()->contents();
4912 for (size_t index = 0; index < contents.size(); ++index) {
4913 if (contents[index].name == content_name) {
4914 *sdp_mline_index = static_cast<int>(index);
4915 content_found = true;
4916 break;
4917 }
4918 }
4919 return content_found;
4920}
4921
4922bool PeerConnection::UseCandidatesInSessionDescription(
4923 const SessionDescriptionInterface* remote_desc) {
4924 if (!remote_desc) {
4925 return true;
4926 }
4927 bool ret = true;
4928
4929 for (size_t m = 0; m < remote_desc->number_of_mediasections(); ++m) {
4930 const IceCandidateCollection* candidates = remote_desc->candidates(m);
4931 for (size_t n = 0; n < candidates->count(); ++n) {
4932 const IceCandidateInterface* candidate = candidates->at(n);
4933 bool valid = false;
4934 if (!ReadyToUseRemoteCandidate(candidate, remote_desc, &valid)) {
4935 if (valid) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004936 RTC_LOG(LS_INFO)
4937 << "UseCandidatesInSessionDescription: Not ready to use "
4938 << "candidate.";
Steve Anton75737c02017-11-06 10:37:17 -08004939 }
4940 continue;
4941 }
4942 ret = UseCandidate(candidate);
4943 if (!ret) {
4944 break;
4945 }
4946 }
4947 }
4948 return ret;
4949}
4950
4951bool PeerConnection::UseCandidate(const IceCandidateInterface* candidate) {
4952 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
4953 size_t remote_content_size =
4954 remote_description()->description()->contents().size();
4955 if (mediacontent_index >= remote_content_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004956 RTC_LOG(LS_ERROR) << "UseCandidate: Invalid candidate media index.";
Steve Anton75737c02017-11-06 10:37:17 -08004957 return false;
4958 }
4959
4960 cricket::ContentInfo content =
4961 remote_description()->description()->contents()[mediacontent_index];
4962 std::vector<cricket::Candidate> candidates;
4963 candidates.push_back(candidate->candidate());
4964 // Invoking BaseSession method to handle remote candidates.
4965 std::string error;
4966 if (transport_controller_->AddRemoteCandidates(content.name, candidates,
4967 &error)) {
4968 // Candidates successfully submitted for checking.
4969 if (ice_connection_state_ == PeerConnectionInterface::kIceConnectionNew ||
4970 ice_connection_state_ ==
4971 PeerConnectionInterface::kIceConnectionDisconnected) {
4972 // If state is New, then the session has just gotten its first remote ICE
4973 // candidates, so go to Checking.
4974 // If state is Disconnected, the session is re-using old candidates or
4975 // receiving additional ones, so go to Checking.
4976 // If state is Connected, stay Connected.
4977 // TODO(bemasc): If state is Connected, and the new candidates are for a
4978 // newly added transport, then the state actually _should_ move to
4979 // checking. Add a way to distinguish that case.
4980 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
4981 }
4982 // TODO(bemasc): If state is Completed, go back to Connected.
4983 } else {
4984 if (!error.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004985 RTC_LOG(LS_WARNING) << error;
Steve Anton75737c02017-11-06 10:37:17 -08004986 }
4987 }
4988 return true;
4989}
4990
4991void PeerConnection::RemoveUnusedChannels(const SessionDescription* desc) {
Steve Anton75737c02017-11-06 10:37:17 -08004992 // Destroy video channel first since it may have a pointer to the
4993 // voice channel.
4994 const cricket::ContentInfo* video_info = cricket::GetFirstVideoContent(desc);
Steve Anton6fec8802017-12-04 10:37:29 -08004995 if (!video_info || video_info->rejected) {
4996 DestroyTransceiverChannel(GetVideoTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08004997 }
4998
Steve Anton6fec8802017-12-04 10:37:29 -08004999 const cricket::ContentInfo* audio_info = cricket::GetFirstAudioContent(desc);
5000 if (!audio_info || audio_info->rejected) {
5001 DestroyTransceiverChannel(GetAudioTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08005002 }
5003
5004 const cricket::ContentInfo* data_info = cricket::GetFirstDataContent(desc);
5005 if (!data_info || data_info->rejected) {
Steve Anton6fec8802017-12-04 10:37:29 -08005006 DestroyDataChannel();
Steve Anton75737c02017-11-06 10:37:17 -08005007 }
5008}
5009
Steve Antoneda6ccd2017-12-04 10:21:55 -08005010std::string PeerConnection::GetTransportNameForMediaSection(
5011 const std::string& mid,
5012 const cricket::ContentGroup* bundle_group) const {
5013 if (!bundle_group) {
5014 return mid;
Steve Anton75737c02017-11-06 10:37:17 -08005015 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005016 const std::string* first_content_name = bundle_group->FirstContentName();
Steve Anton75737c02017-11-06 10:37:17 -08005017 if (!first_content_name) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005018 RTC_LOG(LS_WARNING) << "Tried to BUNDLE with no contents.";
Steve Antoneda6ccd2017-12-04 10:21:55 -08005019 return mid;
Steve Anton75737c02017-11-06 10:37:17 -08005020 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005021 if (!bundle_group->HasContentName(mid)) {
5022 RTC_LOG(LS_WARNING) << mid << " is not part of any bundle group";
5023 return mid;
Steve Anton75737c02017-11-06 10:37:17 -08005024 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005025 RTC_LOG(LS_INFO) << "Bundling " << mid << " on " << *first_content_name;
5026 return *first_content_name;
Steve Anton75737c02017-11-06 10:37:17 -08005027}
5028
Steve Antondcc3c022017-12-22 16:02:54 -08005029RTCErrorOr<const cricket::ContentGroup*> PeerConnection::GetEarlyBundleGroup(
5030 const SessionDescription& desc) const {
Steve Anton75737c02017-11-06 10:37:17 -08005031 const cricket::ContentGroup* bundle_group = nullptr;
5032 if (configuration_.bundle_policy ==
5033 PeerConnectionInterface::kBundlePolicyMaxBundle) {
Steve Antondcc3c022017-12-22 16:02:54 -08005034 bundle_group = desc.GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton75737c02017-11-06 10:37:17 -08005035 if (!bundle_group) {
Steve Anton8a006912017-12-04 15:25:56 -08005036 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5037 "max-bundle configured but session description "
5038 "has no BUNDLE group");
Steve Anton75737c02017-11-06 10:37:17 -08005039 }
5040 }
Steve Antondcc3c022017-12-22 16:02:54 -08005041 return std::move(bundle_group);
5042}
5043
5044RTCError PeerConnection::CreateChannels(const SessionDescription& desc) {
5045 auto bundle_group_or_error = GetEarlyBundleGroup(desc);
5046 if (!bundle_group_or_error.ok()) {
5047 return bundle_group_or_error.MoveError();
5048 }
5049 const cricket::ContentGroup* bundle_group = bundle_group_or_error.MoveValue();
Steve Anton75737c02017-11-06 10:37:17 -08005050
Steve Antoneda6ccd2017-12-04 10:21:55 -08005051 // Creating the media channels and transport proxies.
Steve Antondcc3c022017-12-22 16:02:54 -08005052 const cricket::ContentInfo* voice = cricket::GetFirstAudioContent(&desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08005053 if (voice && !voice->rejected &&
5054 !GetAudioTransceiver()->internal()->channel()) {
5055 cricket::VoiceChannel* voice_channel = CreateVoiceChannel(
5056 voice->name,
5057 GetTransportNameForMediaSection(voice->name, bundle_group));
5058 if (!voice_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08005059 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5060 "Failed to create voice channel.");
Steve Antoneda6ccd2017-12-04 10:21:55 -08005061 }
5062 GetAudioTransceiver()->internal()->SetChannel(voice_channel);
5063 }
5064
Steve Antondcc3c022017-12-22 16:02:54 -08005065 const cricket::ContentInfo* video = cricket::GetFirstVideoContent(&desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08005066 if (video && !video->rejected &&
5067 !GetVideoTransceiver()->internal()->channel()) {
5068 cricket::VideoChannel* video_channel = CreateVideoChannel(
5069 video->name,
5070 GetTransportNameForMediaSection(video->name, bundle_group));
5071 if (!video_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08005072 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5073 "Failed to create video channel.");
Steve Anton75737c02017-11-06 10:37:17 -08005074 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005075 GetVideoTransceiver()->internal()->SetChannel(video_channel);
Steve Anton75737c02017-11-06 10:37:17 -08005076 }
5077
Steve Antondcc3c022017-12-22 16:02:54 -08005078 const cricket::ContentInfo* data = cricket::GetFirstDataContent(&desc);
Steve Anton75737c02017-11-06 10:37:17 -08005079 if (data_channel_type_ != cricket::DCT_NONE && data && !data->rejected &&
5080 !rtp_data_channel_ && !sctp_transport_) {
Steve Antoneda6ccd2017-12-04 10:21:55 -08005081 if (!CreateDataChannel(data->name, GetTransportNameForMediaSection(
5082 data->name, bundle_group))) {
Steve Anton8a006912017-12-04 15:25:56 -08005083 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5084 "Failed to create data channel.");
Steve Anton75737c02017-11-06 10:37:17 -08005085 }
5086 }
5087
Steve Anton8a006912017-12-04 15:25:56 -08005088 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08005089}
5090
Steve Anton4171afb2017-11-20 10:20:22 -08005091// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08005092cricket::VoiceChannel* PeerConnection::CreateVoiceChannel(
5093 const std::string& mid,
5094 const std::string& transport_name) {
Steve Anton75737c02017-11-06 10:37:17 -08005095 cricket::DtlsTransportInternal* rtp_dtls_transport =
5096 transport_controller_->CreateDtlsTransport(
5097 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5098 cricket::DtlsTransportInternal* rtcp_dtls_transport = nullptr;
5099 if (configuration_.rtcp_mux_policy !=
5100 PeerConnectionInterface::kRtcpMuxPolicyRequire) {
5101 rtcp_dtls_transport = transport_controller_->CreateDtlsTransport(
5102 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
5103 }
5104
5105 cricket::VoiceChannel* voice_channel = channel_manager()->CreateVoiceChannel(
5106 call_.get(), configuration_.media_config, rtp_dtls_transport,
Steve Antoneda6ccd2017-12-04 10:21:55 -08005107 rtcp_dtls_transport, signaling_thread(), mid, SrtpRequired(),
5108 audio_options_);
Steve Anton75737c02017-11-06 10:37:17 -08005109 if (!voice_channel) {
5110 transport_controller_->DestroyDtlsTransport(
5111 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5112 if (rtcp_dtls_transport) {
5113 transport_controller_->DestroyDtlsTransport(
5114 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
5115 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005116 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08005117 }
Steve Anton75737c02017-11-06 10:37:17 -08005118 voice_channel->SignalRtcpMuxFullyActive.connect(
5119 this, &PeerConnection::DestroyRtcpTransport_n);
5120 voice_channel->SignalDtlsSrtpSetupFailure.connect(
5121 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08005122 voice_channel->SignalSentPacket.connect(this,
5123 &PeerConnection::OnSentPacket_w);
Steve Anton4171afb2017-11-20 10:20:22 -08005124
Steve Antoneda6ccd2017-12-04 10:21:55 -08005125 return voice_channel;
Steve Anton75737c02017-11-06 10:37:17 -08005126}
5127
Steve Anton4171afb2017-11-20 10:20:22 -08005128// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08005129cricket::VideoChannel* PeerConnection::CreateVideoChannel(
5130 const std::string& mid,
5131 const std::string& transport_name) {
Steve Anton75737c02017-11-06 10:37:17 -08005132 cricket::DtlsTransportInternal* rtp_dtls_transport =
5133 transport_controller_->CreateDtlsTransport(
5134 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5135 cricket::DtlsTransportInternal* rtcp_dtls_transport = nullptr;
5136 if (configuration_.rtcp_mux_policy !=
5137 PeerConnectionInterface::kRtcpMuxPolicyRequire) {
5138 rtcp_dtls_transport = transport_controller_->CreateDtlsTransport(
5139 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
5140 }
5141
5142 cricket::VideoChannel* video_channel = channel_manager()->CreateVideoChannel(
5143 call_.get(), configuration_.media_config, rtp_dtls_transport,
Steve Antoneda6ccd2017-12-04 10:21:55 -08005144 rtcp_dtls_transport, signaling_thread(), mid, SrtpRequired(),
5145 video_options_);
Steve Anton75737c02017-11-06 10:37:17 -08005146
5147 if (!video_channel) {
5148 transport_controller_->DestroyDtlsTransport(
5149 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5150 if (rtcp_dtls_transport) {
5151 transport_controller_->DestroyDtlsTransport(
5152 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
5153 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005154 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08005155 }
Steve Anton75737c02017-11-06 10:37:17 -08005156 video_channel->SignalRtcpMuxFullyActive.connect(
5157 this, &PeerConnection::DestroyRtcpTransport_n);
5158 video_channel->SignalDtlsSrtpSetupFailure.connect(
5159 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08005160 video_channel->SignalSentPacket.connect(this,
5161 &PeerConnection::OnSentPacket_w);
Steve Anton4171afb2017-11-20 10:20:22 -08005162
Steve Antoneda6ccd2017-12-04 10:21:55 -08005163 return video_channel;
Steve Anton75737c02017-11-06 10:37:17 -08005164}
5165
Steve Antoneda6ccd2017-12-04 10:21:55 -08005166bool PeerConnection::CreateDataChannel(const std::string& mid,
5167 const std::string& transport_name) {
Steve Anton75737c02017-11-06 10:37:17 -08005168 bool sctp = (data_channel_type_ == cricket::DCT_SCTP);
5169 if (sctp) {
5170 if (!sctp_factory_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005171 RTC_LOG(LS_ERROR)
Steve Anton75737c02017-11-06 10:37:17 -08005172 << "Trying to create SCTP transport, but didn't compile with "
5173 "SCTP support (HAVE_SCTP)";
5174 return false;
5175 }
5176 if (!network_thread()->Invoke<bool>(
5177 RTC_FROM_HERE, rtc::Bind(&PeerConnection::CreateSctpTransport_n,
Steve Antoneda6ccd2017-12-04 10:21:55 -08005178 this, mid, transport_name))) {
Steve Anton75737c02017-11-06 10:37:17 -08005179 return false;
5180 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005181 for (const auto& channel : sctp_data_channels_) {
5182 channel->OnTransportChannelCreated();
5183 }
Steve Anton75737c02017-11-06 10:37:17 -08005184 } else {
Steve Anton75737c02017-11-06 10:37:17 -08005185 cricket::DtlsTransportInternal* rtp_dtls_transport =
5186 transport_controller_->CreateDtlsTransport(
5187 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5188 cricket::DtlsTransportInternal* rtcp_dtls_transport = nullptr;
5189 if (configuration_.rtcp_mux_policy !=
5190 PeerConnectionInterface::kRtcpMuxPolicyRequire) {
5191 rtcp_dtls_transport = transport_controller_->CreateDtlsTransport(
5192 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
5193 }
5194
5195 rtp_data_channel_ = channel_manager()->CreateRtpDataChannel(
5196 configuration_.media_config, rtp_dtls_transport, rtcp_dtls_transport,
Steve Antoneda6ccd2017-12-04 10:21:55 -08005197 signaling_thread(), mid, SrtpRequired());
Steve Anton75737c02017-11-06 10:37:17 -08005198
5199 if (!rtp_data_channel_) {
5200 transport_controller_->DestroyDtlsTransport(
5201 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5202 if (rtcp_dtls_transport) {
5203 transport_controller_->DestroyDtlsTransport(
5204 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
5205 }
5206 return false;
5207 }
5208
5209 rtp_data_channel_->SignalRtcpMuxFullyActive.connect(
5210 this, &PeerConnection::DestroyRtcpTransport_n);
5211 rtp_data_channel_->SignalDtlsSrtpSetupFailure.connect(
5212 this, &PeerConnection::OnDtlsSrtpSetupFailure);
5213 rtp_data_channel_->SignalSentPacket.connect(
5214 this, &PeerConnection::OnSentPacket_w);
5215 }
5216
Steve Anton75737c02017-11-06 10:37:17 -08005217 return true;
5218}
5219
5220Call::Stats PeerConnection::GetCallStats() {
5221 if (!worker_thread()->IsCurrent()) {
5222 return worker_thread()->Invoke<Call::Stats>(
5223 RTC_FROM_HERE, rtc::Bind(&PeerConnection::GetCallStats, this));
5224 }
5225 if (call_) {
5226 return call_->GetStats();
5227 } else {
5228 return Call::Stats();
5229 }
5230}
5231
5232std::unique_ptr<SessionStats> PeerConnection::GetSessionStats_n(
5233 const ChannelNamePairs& channel_name_pairs) {
5234 RTC_DCHECK(network_thread()->IsCurrent());
5235 std::unique_ptr<SessionStats> session_stats(new SessionStats());
5236 for (const auto channel_name_pair :
5237 {&channel_name_pairs.voice, &channel_name_pairs.video,
5238 &channel_name_pairs.data}) {
5239 if (*channel_name_pair) {
5240 cricket::TransportStats transport_stats;
5241 if (!transport_controller_->GetStats((*channel_name_pair)->transport_name,
5242 &transport_stats)) {
5243 return nullptr;
5244 }
Steve Anton75737c02017-11-06 10:37:17 -08005245 session_stats->transport_stats[(*channel_name_pair)->transport_name] =
5246 std::move(transport_stats);
5247 }
5248 }
5249 return session_stats;
5250}
5251
5252bool PeerConnection::CreateSctpTransport_n(const std::string& content_name,
5253 const std::string& transport_name) {
5254 RTC_DCHECK(network_thread()->IsCurrent());
5255 RTC_DCHECK(sctp_factory_);
5256 cricket::DtlsTransportInternal* tc =
5257 transport_controller_->CreateDtlsTransport_n(
5258 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5259 sctp_transport_ = sctp_factory_->CreateSctpTransport(tc);
5260 RTC_DCHECK(sctp_transport_);
5261 sctp_invoker_.reset(new rtc::AsyncInvoker());
5262 sctp_transport_->SignalReadyToSendData.connect(
5263 this, &PeerConnection::OnSctpTransportReadyToSendData_n);
5264 sctp_transport_->SignalDataReceived.connect(
5265 this, &PeerConnection::OnSctpTransportDataReceived_n);
5266 sctp_transport_->SignalStreamClosedRemotely.connect(
5267 this, &PeerConnection::OnSctpStreamClosedRemotely_n);
Oskar Sundbom9b28a032017-11-16 10:53:30 +01005268 sctp_transport_name_ = transport_name;
5269 sctp_content_name_ = content_name;
Steve Anton75737c02017-11-06 10:37:17 -08005270 return true;
5271}
5272
5273void PeerConnection::ChangeSctpTransport_n(const std::string& transport_name) {
5274 RTC_DCHECK(network_thread()->IsCurrent());
5275 RTC_DCHECK(sctp_transport_);
5276 RTC_DCHECK(sctp_transport_name_);
5277 std::string old_sctp_transport_name = *sctp_transport_name_;
Oskar Sundbom9b28a032017-11-16 10:53:30 +01005278 sctp_transport_name_ = transport_name;
Steve Anton75737c02017-11-06 10:37:17 -08005279 cricket::DtlsTransportInternal* tc =
5280 transport_controller_->CreateDtlsTransport_n(
5281 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5282 sctp_transport_->SetTransportChannel(tc);
5283 transport_controller_->DestroyDtlsTransport_n(
5284 old_sctp_transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5285}
5286
5287void PeerConnection::DestroySctpTransport_n() {
5288 RTC_DCHECK(network_thread()->IsCurrent());
5289 sctp_transport_.reset(nullptr);
Taylor Brandstetter389a97c2018-01-03 16:26:06 -08005290 transport_controller_->DestroyDtlsTransport_n(
5291 *sctp_transport_name_, cricket::ICE_CANDIDATE_COMPONENT_RTP);
Steve Anton75737c02017-11-06 10:37:17 -08005292 sctp_content_name_.reset();
5293 sctp_transport_name_.reset();
5294 sctp_invoker_.reset(nullptr);
5295 sctp_ready_to_send_data_ = false;
5296}
5297
5298void PeerConnection::OnSctpTransportReadyToSendData_n() {
5299 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5300 RTC_DCHECK(network_thread()->IsCurrent());
5301 // Note: Cannot use rtc::Bind here because it will grab a reference to
5302 // PeerConnection and potentially cause PeerConnection to live longer than
5303 // expected. It is safe not to grab a reference since the sctp_invoker_ will
5304 // be destroyed before PeerConnection is destroyed, and at that point all
5305 // pending tasks will be cleared.
5306 sctp_invoker_->AsyncInvoke<void>(RTC_FROM_HERE, signaling_thread(), [this] {
5307 OnSctpTransportReadyToSendData_s(true);
5308 });
5309}
5310
5311void PeerConnection::OnSctpTransportReadyToSendData_s(bool ready) {
5312 RTC_DCHECK(signaling_thread()->IsCurrent());
5313 sctp_ready_to_send_data_ = ready;
5314 SignalSctpReadyToSendData(ready);
5315}
5316
5317void PeerConnection::OnSctpTransportDataReceived_n(
5318 const cricket::ReceiveDataParams& params,
5319 const rtc::CopyOnWriteBuffer& payload) {
5320 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5321 RTC_DCHECK(network_thread()->IsCurrent());
5322 // Note: Cannot use rtc::Bind here because it will grab a reference to
5323 // PeerConnection and potentially cause PeerConnection to live longer than
5324 // expected. It is safe not to grab a reference since the sctp_invoker_ will
5325 // be destroyed before PeerConnection is destroyed, and at that point all
5326 // pending tasks will be cleared.
5327 sctp_invoker_->AsyncInvoke<void>(
5328 RTC_FROM_HERE, signaling_thread(), [this, params, payload] {
5329 OnSctpTransportDataReceived_s(params, payload);
5330 });
5331}
5332
5333void PeerConnection::OnSctpTransportDataReceived_s(
5334 const cricket::ReceiveDataParams& params,
5335 const rtc::CopyOnWriteBuffer& payload) {
5336 RTC_DCHECK(signaling_thread()->IsCurrent());
5337 if (params.type == cricket::DMT_CONTROL && IsOpenMessage(payload)) {
5338 // Received OPEN message; parse and signal that a new data channel should
5339 // be created.
5340 std::string label;
5341 InternalDataChannelInit config;
5342 config.id = params.ssrc;
5343 if (!ParseDataChannelOpenMessage(payload, &label, &config)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005344 RTC_LOG(LS_WARNING) << "Failed to parse the OPEN message for sid "
5345 << params.ssrc;
Steve Anton75737c02017-11-06 10:37:17 -08005346 return;
5347 }
5348 config.open_handshake_role = InternalDataChannelInit::kAcker;
5349 OnDataChannelOpenMessage(label, config);
5350 } else {
5351 // Otherwise just forward the signal.
5352 SignalSctpDataReceived(params, payload);
5353 }
5354}
5355
5356void PeerConnection::OnSctpStreamClosedRemotely_n(int sid) {
5357 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5358 RTC_DCHECK(network_thread()->IsCurrent());
5359 sctp_invoker_->AsyncInvoke<void>(
5360 RTC_FROM_HERE, signaling_thread(),
5361 rtc::Bind(&sigslot::signal1<int>::operator(),
5362 &SignalSctpStreamClosedRemotely, sid));
5363}
5364
5365// Returns false if bundle is enabled and rtcp_mux is disabled.
5366bool PeerConnection::ValidateBundleSettings(const SessionDescription* desc) {
5367 bool bundle_enabled = desc->HasGroup(cricket::GROUP_TYPE_BUNDLE);
5368 if (!bundle_enabled)
5369 return true;
5370
5371 const cricket::ContentGroup* bundle_group =
5372 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
5373 RTC_DCHECK(bundle_group != NULL);
5374
5375 const cricket::ContentInfos& contents = desc->contents();
5376 for (cricket::ContentInfos::const_iterator citer = contents.begin();
5377 citer != contents.end(); ++citer) {
5378 const cricket::ContentInfo* content = (&*citer);
5379 RTC_DCHECK(content != NULL);
5380 if (bundle_group->HasContentName(content->name) && !content->rejected &&
Steve Anton5adfafd2017-12-20 16:34:00 -08005381 content->type == MediaProtocolType::kRtp) {
Steve Anton75737c02017-11-06 10:37:17 -08005382 if (!HasRtcpMuxEnabled(content))
5383 return false;
5384 }
5385 }
5386 // RTCP-MUX is enabled in all the contents.
5387 return true;
5388}
5389
5390bool PeerConnection::HasRtcpMuxEnabled(const cricket::ContentInfo* content) {
Steve Antonb1c1de12017-12-21 15:14:30 -08005391 return content->media_description()->rtcp_mux();
Steve Anton75737c02017-11-06 10:37:17 -08005392}
5393
Steve Anton8a006912017-12-04 15:25:56 -08005394RTCError PeerConnection::ValidateSessionDescription(
Steve Anton75737c02017-11-06 10:37:17 -08005395 const SessionDescriptionInterface* sdesc,
Steve Anton8a006912017-12-04 15:25:56 -08005396 cricket::ContentSource source) {
Steve Antonf8470812017-12-04 10:46:21 -08005397 if (session_error() != SessionError::kNone) {
Steve Anton8a006912017-12-04 15:25:56 -08005398 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
Steve Anton75737c02017-11-06 10:37:17 -08005399 }
5400
5401 if (!sdesc || !sdesc->description()) {
Steve Anton8a006912017-12-04 15:25:56 -08005402 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidSdp);
Steve Anton75737c02017-11-06 10:37:17 -08005403 }
5404
Steve Anton3828c062017-12-06 10:34:51 -08005405 SdpType type = sdesc->GetType();
5406 if ((source == cricket::CS_LOCAL && !ExpectSetLocalDescription(type)) ||
5407 (source == cricket::CS_REMOTE && !ExpectSetRemoteDescription(type))) {
Steve Anton8a006912017-12-04 15:25:56 -08005408 LOG_AND_RETURN_ERROR(
5409 RTCErrorType::INVALID_PARAMETER,
5410 "Called in wrong state: " + GetSignalingStateString(signaling_state()));
Steve Anton75737c02017-11-06 10:37:17 -08005411 }
5412
5413 // Verify crypto settings.
5414 std::string crypto_error;
Steve Anton8a006912017-12-04 15:25:56 -08005415 if (webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED ||
5416 dtls_enabled_) {
Harald Alvestrand194939b2018-01-24 16:04:13 +01005417 RTCError crypto_error =
5418 VerifyCrypto(sdesc->description(), dtls_enabled_, uma_observer_);
Steve Anton8a006912017-12-04 15:25:56 -08005419 if (!crypto_error.ok()) {
5420 return crypto_error;
5421 }
Steve Anton75737c02017-11-06 10:37:17 -08005422 }
5423
5424 // Verify ice-ufrag and ice-pwd.
5425 if (!VerifyIceUfragPwdPresent(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08005426 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5427 kSdpWithoutIceUfragPwd);
Steve Anton75737c02017-11-06 10:37:17 -08005428 }
5429
5430 if (!ValidateBundleSettings(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08005431 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5432 kBundleWithoutRtcpMux);
Steve Anton75737c02017-11-06 10:37:17 -08005433 }
5434
5435 // TODO(skvlad): When the local rtcp-mux policy is Require, reject any
5436 // m-lines that do not rtcp-mux enabled.
5437
5438 // Verify m-lines in Answer when compared against Offer.
Steve Anton3828c062017-12-06 10:34:51 -08005439 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Anton75737c02017-11-06 10:37:17 -08005440 const cricket::SessionDescription* offer_desc =
5441 (source == cricket::CS_LOCAL) ? remote_description()->description()
5442 : local_description()->description();
5443 if (!MediaSectionsHaveSameCount(offer_desc, sdesc->description()) ||
5444 !MediaSectionsInSameOrder(offer_desc, sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08005445 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5446 kMlineMismatchInAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08005447 }
5448 } else {
5449 const cricket::SessionDescription* current_desc = nullptr;
5450 if (source == cricket::CS_LOCAL && local_description()) {
5451 current_desc = local_description()->description();
5452 } else if (source == cricket::CS_REMOTE && remote_description()) {
5453 current_desc = remote_description()->description();
5454 }
5455 // The re-offers should respect the order of m= sections in current
5456 // description. See RFC3264 Section 8 paragraph 4 for more details.
5457 if (current_desc &&
5458 !MediaSectionsInSameOrder(current_desc, sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08005459 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5460 kMlineMismatchInSubsequentOffer);
Steve Anton75737c02017-11-06 10:37:17 -08005461 }
5462 }
5463
Steve Anton8a006912017-12-04 15:25:56 -08005464 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08005465}
5466
Steve Anton3828c062017-12-06 10:34:51 -08005467bool PeerConnection::ExpectSetLocalDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08005468 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08005469 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08005470 return (state == PeerConnectionInterface::kStable) ||
5471 (state == PeerConnectionInterface::kHaveLocalOffer);
Steve Anton20393062017-12-04 16:24:52 -08005472 } else {
Steve Anton3828c062017-12-06 10:34:51 -08005473 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08005474 return (state == PeerConnectionInterface::kHaveRemoteOffer) ||
5475 (state == PeerConnectionInterface::kHaveLocalPrAnswer);
5476 }
5477}
5478
Steve Anton3828c062017-12-06 10:34:51 -08005479bool PeerConnection::ExpectSetRemoteDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08005480 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08005481 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08005482 return (state == PeerConnectionInterface::kStable) ||
5483 (state == PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton20393062017-12-04 16:24:52 -08005484 } else {
Steve Anton3828c062017-12-06 10:34:51 -08005485 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08005486 return (state == PeerConnectionInterface::kHaveLocalOffer) ||
5487 (state == PeerConnectionInterface::kHaveRemotePrAnswer);
5488 }
5489}
5490
Steve Antonf8470812017-12-04 10:46:21 -08005491const char* PeerConnection::SessionErrorToString(SessionError error) const {
5492 switch (error) {
5493 case SessionError::kNone:
5494 return "ERROR_NONE";
5495 case SessionError::kContent:
5496 return "ERROR_CONTENT";
5497 case SessionError::kTransport:
5498 return "ERROR_TRANSPORT";
5499 }
5500 RTC_NOTREACHED();
5501 return "";
5502}
5503
Steve Anton75737c02017-11-06 10:37:17 -08005504std::string PeerConnection::GetSessionErrorMsg() {
5505 std::ostringstream desc;
Steve Antonf8470812017-12-04 10:46:21 -08005506 desc << kSessionError << SessionErrorToString(session_error()) << ". ";
5507 desc << kSessionErrorDesc << session_error_desc() << ".";
Steve Anton75737c02017-11-06 10:37:17 -08005508 return desc.str();
5509}
5510
5511// We need to check the local/remote description for the Transport instead of
5512// the session, because a new Transport added during renegotiation may have
5513// them unset while the session has them set from the previous negotiation.
5514// Not doing so may trigger the auto generation of transport description and
5515// mess up DTLS identity information, ICE credential, etc.
5516bool PeerConnection::ReadyToUseRemoteCandidate(
5517 const IceCandidateInterface* candidate,
5518 const SessionDescriptionInterface* remote_desc,
5519 bool* valid) {
5520 *valid = true;
5521
5522 const SessionDescriptionInterface* current_remote_desc =
5523 remote_desc ? remote_desc : remote_description();
5524
5525 if (!current_remote_desc) {
5526 return false;
5527 }
5528
5529 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
5530 size_t remote_content_size =
5531 current_remote_desc->description()->contents().size();
5532 if (mediacontent_index >= remote_content_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005533 RTC_LOG(LS_ERROR)
5534 << "ReadyToUseRemoteCandidate: Invalid candidate media index "
5535 << mediacontent_index;
Steve Anton75737c02017-11-06 10:37:17 -08005536
5537 *valid = false;
5538 return false;
5539 }
5540
5541 cricket::ContentInfo content =
5542 current_remote_desc->description()->contents()[mediacontent_index];
5543
5544 const std::string transport_name = GetTransportName(content.name);
5545 if (transport_name.empty()) {
5546 return false;
5547 }
5548 return transport_controller_->ReadyForRemoteCandidates(transport_name);
5549}
5550
5551bool PeerConnection::SrtpRequired() const {
5552 return dtls_enabled_ ||
5553 webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED;
5554}
5555
5556void PeerConnection::OnTransportControllerGatheringState(
5557 cricket::IceGatheringState state) {
5558 RTC_DCHECK(signaling_thread()->IsCurrent());
5559 if (state == cricket::kIceGatheringGathering) {
5560 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringGathering);
5561 } else if (state == cricket::kIceGatheringComplete) {
5562 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringComplete);
5563 }
5564}
5565
5566void PeerConnection::ReportTransportStats() {
5567 // Use a set so we don't report the same stats twice if two channels share
5568 // a transport.
5569 std::set<std::string> transport_names;
5570 if (voice_channel()) {
5571 transport_names.insert(voice_channel()->transport_name());
5572 }
5573 if (video_channel()) {
5574 transport_names.insert(video_channel()->transport_name());
5575 }
5576 if (rtp_data_channel()) {
5577 transport_names.insert(rtp_data_channel()->transport_name());
5578 }
5579 if (sctp_transport_name_) {
5580 transport_names.insert(*sctp_transport_name_);
5581 }
5582 for (const auto& name : transport_names) {
5583 cricket::TransportStats stats;
5584 if (transport_controller_->GetStats(name, &stats)) {
5585 ReportBestConnectionState(stats);
5586 ReportNegotiatedCiphers(stats);
5587 }
5588 }
5589}
5590// Walk through the ConnectionInfos to gather best connection usage
5591// for IPv4 and IPv6.
5592void PeerConnection::ReportBestConnectionState(
5593 const cricket::TransportStats& stats) {
5594 RTC_DCHECK(metrics_observer());
5595 for (cricket::TransportChannelStatsList::const_iterator it =
5596 stats.channel_stats.begin();
5597 it != stats.channel_stats.end(); ++it) {
5598 for (cricket::ConnectionInfos::const_iterator it_info =
5599 it->connection_infos.begin();
5600 it_info != it->connection_infos.end(); ++it_info) {
5601 if (!it_info->best_connection) {
5602 continue;
5603 }
5604
5605 PeerConnectionEnumCounterType type = kPeerConnectionEnumCounterMax;
5606 const cricket::Candidate& local = it_info->local_candidate;
5607 const cricket::Candidate& remote = it_info->remote_candidate;
5608
5609 // Increment the counter for IceCandidatePairType.
5610 if (local.protocol() == cricket::TCP_PROTOCOL_NAME ||
5611 (local.type() == RELAY_PORT_TYPE &&
5612 local.relay_protocol() == cricket::TCP_PROTOCOL_NAME)) {
5613 type = kEnumCounterIceCandidatePairTypeTcp;
5614 } else if (local.protocol() == cricket::UDP_PROTOCOL_NAME) {
5615 type = kEnumCounterIceCandidatePairTypeUdp;
5616 } else {
5617 RTC_CHECK(0);
5618 }
5619 metrics_observer()->IncrementEnumCounter(
5620 type, GetIceCandidatePairCounter(local, remote),
5621 kIceCandidatePairMax);
5622
5623 // Increment the counter for IP type.
5624 if (local.address().family() == AF_INET) {
5625 metrics_observer()->IncrementEnumCounter(
5626 kEnumCounterAddressFamily, kBestConnections_IPv4,
5627 kPeerConnectionAddressFamilyCounter_Max);
5628
5629 } else if (local.address().family() == AF_INET6) {
5630 metrics_observer()->IncrementEnumCounter(
5631 kEnumCounterAddressFamily, kBestConnections_IPv6,
5632 kPeerConnectionAddressFamilyCounter_Max);
5633 } else {
5634 RTC_CHECK(0);
5635 }
5636
5637 return;
5638 }
5639 }
5640}
5641
5642void PeerConnection::ReportNegotiatedCiphers(
5643 const cricket::TransportStats& stats) {
5644 RTC_DCHECK(metrics_observer());
5645 if (!dtls_enabled_ || stats.channel_stats.empty()) {
5646 return;
5647 }
5648
5649 int srtp_crypto_suite = stats.channel_stats[0].srtp_crypto_suite;
5650 int ssl_cipher_suite = stats.channel_stats[0].ssl_cipher_suite;
5651 if (srtp_crypto_suite == rtc::SRTP_INVALID_CRYPTO_SUITE &&
5652 ssl_cipher_suite == rtc::TLS_NULL_WITH_NULL_NULL) {
5653 return;
5654 }
5655
5656 PeerConnectionEnumCounterType srtp_counter_type;
5657 PeerConnectionEnumCounterType ssl_counter_type;
5658 if (stats.transport_name == cricket::CN_AUDIO) {
5659 srtp_counter_type = kEnumCounterAudioSrtpCipher;
5660 ssl_counter_type = kEnumCounterAudioSslCipher;
5661 } else if (stats.transport_name == cricket::CN_VIDEO) {
5662 srtp_counter_type = kEnumCounterVideoSrtpCipher;
5663 ssl_counter_type = kEnumCounterVideoSslCipher;
5664 } else if (stats.transport_name == cricket::CN_DATA) {
5665 srtp_counter_type = kEnumCounterDataSrtpCipher;
5666 ssl_counter_type = kEnumCounterDataSslCipher;
5667 } else {
5668 RTC_NOTREACHED();
5669 return;
5670 }
5671
5672 if (srtp_crypto_suite != rtc::SRTP_INVALID_CRYPTO_SUITE) {
5673 metrics_observer()->IncrementSparseEnumCounter(srtp_counter_type,
5674 srtp_crypto_suite);
5675 }
5676 if (ssl_cipher_suite != rtc::TLS_NULL_WITH_NULL_NULL) {
5677 metrics_observer()->IncrementSparseEnumCounter(ssl_counter_type,
5678 ssl_cipher_suite);
5679 }
5680}
5681
5682void PeerConnection::OnSentPacket_w(const rtc::SentPacket& sent_packet) {
5683 RTC_DCHECK(worker_thread()->IsCurrent());
5684 RTC_DCHECK(call_);
5685 call_->OnSentPacket(sent_packet);
5686}
5687
5688const std::string PeerConnection::GetTransportName(
5689 const std::string& content_name) {
5690 cricket::BaseChannel* channel = GetChannel(content_name);
Steve Anton6fec8802017-12-04 10:37:29 -08005691 if (channel) {
5692 return channel->transport_name();
Steve Anton75737c02017-11-06 10:37:17 -08005693 }
Steve Anton6fec8802017-12-04 10:37:29 -08005694 if (sctp_transport_) {
5695 RTC_DCHECK(sctp_content_name_);
5696 RTC_DCHECK(sctp_transport_name_);
5697 if (content_name == *sctp_content_name_) {
5698 return *sctp_transport_name_;
5699 }
5700 }
5701 // Return an empty string if failed to retrieve the transport name.
5702 return "";
Steve Anton75737c02017-11-06 10:37:17 -08005703}
5704
5705void PeerConnection::DestroyRtcpTransport_n(const std::string& transport_name) {
5706 RTC_DCHECK(network_thread()->IsCurrent());
5707 transport_controller_->DestroyDtlsTransport_n(
5708 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
5709}
5710
Steve Anton6fec8802017-12-04 10:37:29 -08005711void PeerConnection::DestroyTransceiverChannel(
5712 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
5713 transceiver) {
5714 RTC_DCHECK(transceiver);
Steve Anton75737c02017-11-06 10:37:17 -08005715
Steve Anton6fec8802017-12-04 10:37:29 -08005716 cricket::BaseChannel* channel = transceiver->internal()->channel();
5717 if (channel) {
5718 transceiver->internal()->SetChannel(nullptr);
5719 DestroyBaseChannel(channel);
Steve Anton75737c02017-11-06 10:37:17 -08005720 }
5721}
5722
5723void PeerConnection::DestroyDataChannel() {
Steve Anton6fec8802017-12-04 10:37:29 -08005724 if (rtp_data_channel_) {
5725 OnDataChannelDestroyed();
5726 DestroyBaseChannel(rtp_data_channel_);
5727 rtp_data_channel_ = nullptr;
5728 }
5729
5730 // Note: Cannot use rtc::Bind to create a functor to invoke because it will
5731 // grab a reference to this PeerConnection. If this is called from the
5732 // PeerConnection destructor, the RefCountedObject vtable will have already
5733 // been destroyed (since it is a subclass of PeerConnection) and using
5734 // rtc::Bind will cause "Pure virtual function called" error to appear.
5735
5736 if (sctp_transport_) {
5737 OnDataChannelDestroyed();
5738 network_thread()->Invoke<void>(RTC_FROM_HERE,
5739 [this] { DestroySctpTransport_n(); });
5740 }
5741}
5742
5743void PeerConnection::DestroyBaseChannel(cricket::BaseChannel* channel) {
5744 RTC_DCHECK(channel);
5745 RTC_DCHECK(channel->rtp_dtls_transport());
5746
5747 // Need to cache these before destroying the base channel so that we do not
5748 // access uninitialized memory.
5749 const std::string transport_name =
5750 channel->rtp_dtls_transport()->transport_name();
5751 const bool need_to_delete_rtcp = (channel->rtcp_dtls_transport() != nullptr);
5752
5753 switch (channel->media_type()) {
5754 case cricket::MEDIA_TYPE_AUDIO:
5755 channel_manager()->DestroyVoiceChannel(
5756 static_cast<cricket::VoiceChannel*>(channel));
5757 break;
5758 case cricket::MEDIA_TYPE_VIDEO:
5759 channel_manager()->DestroyVideoChannel(
5760 static_cast<cricket::VideoChannel*>(channel));
5761 break;
5762 case cricket::MEDIA_TYPE_DATA:
5763 channel_manager()->DestroyRtpDataChannel(
5764 static_cast<cricket::RtpDataChannel*>(channel));
5765 break;
5766 default:
5767 RTC_NOTREACHED() << "Unknown media type: " << channel->media_type();
5768 break;
5769 }
5770
5771 // |channel| can no longer be used.
5772
Steve Anton75737c02017-11-06 10:37:17 -08005773 transport_controller_->DestroyDtlsTransport(
5774 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5775 if (need_to_delete_rtcp) {
5776 transport_controller_->DestroyDtlsTransport(
5777 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
5778 }
5779}
5780
Harald Alvestrand89061872018-01-02 14:08:34 +01005781void PeerConnection::ClearStatsCache() {
5782 if (stats_collector_) {
5783 stats_collector_->ClearCachedStatsReport();
5784 }
5785}
5786
henrike@webrtc.org28e20752013-07-10 00:45:36 +00005787} // namespace webrtc