blob: fefa321b373675a2bd01c413d8c9d121dbc18bab [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,
1262 const RtpTransceiverInit& init) {
1263 RTC_DCHECK((media_type == cricket::MEDIA_TYPE_AUDIO ||
1264 media_type == cricket::MEDIA_TYPE_VIDEO));
1265 if (track) {
1266 RTC_DCHECK_EQ(media_type,
1267 (track->kind() == MediaStreamTrackInterface::kAudioKind
1268 ? cricket::MEDIA_TYPE_AUDIO
1269 : cricket::MEDIA_TYPE_VIDEO));
1270 }
1271
1272 // TODO(bugs.webrtc.org/7600): Verify init.
1273
Steve Anton02ee47c2018-01-10 16:26:06 -08001274 if (init.stream_labels.size() > 1u) {
1275 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
1276 "More than one stream is not yet supported.");
Steve Antonf9381f02017-12-14 10:23:57 -08001277 }
1278
Steve Anton02ee47c2018-01-10 16:26:06 -08001279 std::vector<std::string> stream_labels = {!init.stream_labels.empty()
1280 ? init.stream_labels[0]
1281 : rtc::CreateRandomUuid()};
1282
1283 auto sender = CreateSender(media_type, track, stream_labels);
1284 auto receiver = CreateReceiver(media_type, rtc::CreateRandomUuid());
1285 auto transceiver = CreateAndAddTransceiver(sender, receiver);
1286 transceiver->internal()->set_direction(init.direction);
1287
Steve Antonf9381f02017-12-14 10:23:57 -08001288 observer_->OnRenegotiationNeeded();
1289
1290 return rtc::scoped_refptr<RtpTransceiverInterface>(transceiver);
1291}
1292
Steve Anton02ee47c2018-01-10 16:26:06 -08001293rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
1294PeerConnection::CreateSender(
1295 cricket::MediaType media_type,
1296 rtc::scoped_refptr<MediaStreamTrackInterface> track,
1297 const std::vector<std::string>& stream_labels) {
Steve Anton9158ef62017-11-27 13:01:52 -08001298 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> sender;
Steve Anton02ee47c2018-01-10 16:26:06 -08001299 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
1300 RTC_DCHECK(!track ||
1301 (track->kind() == MediaStreamTrackInterface::kAudioKind));
1302 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
1303 signaling_thread(),
Steve Anton47136dd2018-01-12 10:49:35 -08001304 new AudioRtpSender(worker_thread(),
1305 static_cast<AudioTrackInterface*>(track.get()),
Steve Anton02ee47c2018-01-10 16:26:06 -08001306 stream_labels, stats_.get()));
1307 } else {
1308 RTC_DCHECK_EQ(media_type, cricket::MEDIA_TYPE_VIDEO);
1309 RTC_DCHECK(!track ||
1310 (track->kind() == MediaStreamTrackInterface::kVideoKind));
1311 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
1312 signaling_thread(),
Steve Anton47136dd2018-01-12 10:49:35 -08001313 new VideoRtpSender(worker_thread(),
1314 static_cast<VideoTrackInterface*>(track.get()),
Steve Anton02ee47c2018-01-10 16:26:06 -08001315 stream_labels));
1316 }
1317 sender->internal()->set_stream_ids(stream_labels);
1318 return sender;
1319}
1320
1321rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1322PeerConnection::CreateReceiver(cricket::MediaType media_type,
1323 const std::string& receiver_id) {
Steve Anton9158ef62017-11-27 13:01:52 -08001324 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1325 receiver;
Steve Anton9158ef62017-11-27 13:01:52 -08001326 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton9158ef62017-11-27 13:01:52 -08001327 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
Steve Anton60776752018-01-10 11:51:34 -08001328 signaling_thread(),
Steve Antond3679212018-01-17 17:41:02 -08001329 new AudioRtpReceiver(worker_thread(), receiver_id, {}));
Steve Anton9158ef62017-11-27 13:01:52 -08001330 } else {
Steve Anton02ee47c2018-01-10 16:26:06 -08001331 RTC_DCHECK_EQ(media_type, cricket::MEDIA_TYPE_VIDEO);
Steve Anton9158ef62017-11-27 13:01:52 -08001332 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
1333 signaling_thread(),
Steve Antond3679212018-01-17 17:41:02 -08001334 new VideoRtpReceiver(worker_thread(), receiver_id, {}));
Steve Anton9158ef62017-11-27 13:01:52 -08001335 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001336 return receiver;
1337}
1338
1339rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1340PeerConnection::CreateAndAddTransceiver(
1341 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> sender,
1342 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1343 receiver) {
1344 auto transceiver = RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1345 signaling_thread(), new RtpTransceiver(sender, receiver));
Steve Anton9158ef62017-11-27 13:01:52 -08001346 transceivers_.push_back(transceiver);
Steve Antonf9381f02017-12-14 10:23:57 -08001347 return transceiver;
Steve Anton9158ef62017-11-27 13:01:52 -08001348}
1349
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001350rtc::scoped_refptr<DtmfSenderInterface> PeerConnection::CreateDtmfSender(
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001351 AudioTrackInterface* track) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001352 TRACE_EVENT0("webrtc", "PeerConnection::CreateDtmfSender");
zhihuang29ff8442016-07-27 11:07:25 -07001353 if (IsClosed()) {
1354 return nullptr;
1355 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001356 if (!track) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001357 RTC_LOG(LS_ERROR) << "CreateDtmfSender - track is NULL.";
deadbeef20cb0c12017-02-01 20:27:00 -08001358 return nullptr;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001359 }
Steve Anton4171afb2017-11-20 10:20:22 -08001360 auto track_sender = FindSenderForTrack(track);
1361 if (!track_sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001362 RTC_LOG(LS_ERROR) << "CreateDtmfSender called with a non-added track.";
deadbeef20cb0c12017-02-01 20:27:00 -08001363 return nullptr;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001364 }
1365
Steve Anton4171afb2017-11-20 10:20:22 -08001366 return track_sender->GetDtmfSender();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001367}
1368
deadbeeffac06552015-11-25 11:26:01 -08001369rtc::scoped_refptr<RtpSenderInterface> PeerConnection::CreateSender(
deadbeefbd7d8f72015-12-18 16:58:44 -08001370 const std::string& kind,
1371 const std::string& stream_id) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001372 TRACE_EVENT0("webrtc", "PeerConnection::CreateSender");
zhihuang29ff8442016-07-27 11:07:25 -07001373 if (IsClosed()) {
1374 return nullptr;
1375 }
Steve Anton4171afb2017-11-20 10:20:22 -08001376
Steve Anton02ee47c2018-01-10 16:26:06 -08001377 std::vector<std::string> stream_labels;
1378 if (!stream_id.empty()) {
1379 stream_labels.push_back(stream_id);
1380 }
1381
Steve Anton4171afb2017-11-20 10:20:22 -08001382 // TODO(steveanton): Move construction of the RtpSenders to RtpTransceiver.
deadbeefa601f5c2016-06-06 14:27:39 -07001383 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender;
deadbeeffac06552015-11-25 11:26:01 -08001384 if (kind == MediaStreamTrackInterface::kAudioKind) {
Steve Anton47136dd2018-01-12 10:49:35 -08001385 auto* audio_sender = new AudioRtpSender(worker_thread(), nullptr,
1386 stream_labels, stats_.get());
1387 audio_sender->SetMediaChannel(voice_media_channel());
deadbeefa601f5c2016-06-06 14:27:39 -07001388 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton02ee47c2018-01-10 16:26:06 -08001389 signaling_thread(), audio_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001390 GetAudioTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 11:26:01 -08001391 } else if (kind == MediaStreamTrackInterface::kVideoKind) {
Steve Anton47136dd2018-01-12 10:49:35 -08001392 auto* video_sender =
1393 new VideoRtpSender(worker_thread(), nullptr, stream_labels);
1394 video_sender->SetMediaChannel(video_media_channel());
deadbeefa601f5c2016-06-06 14:27:39 -07001395 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton02ee47c2018-01-10 16:26:06 -08001396 signaling_thread(), video_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001397 GetVideoTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 11:26:01 -08001398 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001399 RTC_LOG(LS_ERROR) << "CreateSender called with invalid kind: " << kind;
Steve Anton4171afb2017-11-20 10:20:22 -08001400 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08001401 }
Steve Anton4171afb2017-11-20 10:20:22 -08001402
deadbeefe1f9d832016-01-14 15:35:42 -08001403 return new_sender;
deadbeeffac06552015-11-25 11:26:01 -08001404}
1405
deadbeef70ab1a12015-09-28 16:53:55 -07001406std::vector<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::GetSenders()
1407 const {
deadbeefa601f5c2016-06-06 14:27:39 -07001408 std::vector<rtc::scoped_refptr<RtpSenderInterface>> ret;
Steve Anton4171afb2017-11-20 10:20:22 -08001409 for (auto sender : GetSendersInternal()) {
1410 ret.push_back(sender);
deadbeefa601f5c2016-06-06 14:27:39 -07001411 }
1412 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -07001413}
1414
Steve Anton4171afb2017-11-20 10:20:22 -08001415std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1416PeerConnection::GetSendersInternal() const {
1417 std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1418 all_senders;
1419 for (auto transceiver : transceivers_) {
1420 auto senders = transceiver->internal()->senders();
1421 all_senders.insert(all_senders.end(), senders.begin(), senders.end());
1422 }
1423 return all_senders;
1424}
1425
deadbeef70ab1a12015-09-28 16:53:55 -07001426std::vector<rtc::scoped_refptr<RtpReceiverInterface>>
1427PeerConnection::GetReceivers() const {
deadbeefa601f5c2016-06-06 14:27:39 -07001428 std::vector<rtc::scoped_refptr<RtpReceiverInterface>> ret;
Steve Anton4171afb2017-11-20 10:20:22 -08001429 for (const auto& receiver : GetReceiversInternal()) {
1430 ret.push_back(receiver);
deadbeefa601f5c2016-06-06 14:27:39 -07001431 }
1432 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -07001433}
1434
Steve Anton4171afb2017-11-20 10:20:22 -08001435std::vector<
1436 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1437PeerConnection::GetReceiversInternal() const {
1438 std::vector<
1439 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1440 all_receivers;
1441 for (auto transceiver : transceivers_) {
1442 auto receivers = transceiver->internal()->receivers();
1443 all_receivers.insert(all_receivers.end(), receivers.begin(),
1444 receivers.end());
1445 }
1446 return all_receivers;
1447}
1448
Steve Anton9158ef62017-11-27 13:01:52 -08001449std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
1450PeerConnection::GetTransceivers() const {
1451 RTC_DCHECK(IsUnifiedPlan());
1452 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> all_transceivers;
1453 for (auto transceiver : transceivers_) {
1454 all_transceivers.push_back(transceiver);
1455 }
1456 return all_transceivers;
1457}
1458
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001459bool PeerConnection::GetStats(StatsObserver* observer,
wu@webrtc.orgb9a088b2014-02-13 23:18:49 +00001460 MediaStreamTrackInterface* track,
1461 StatsOutputLevel level) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001462 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
deadbeef0a6c4ca2015-10-06 11:38:28 -07001463 RTC_DCHECK(signaling_thread()->IsCurrent());
nisse7ce109a2017-01-31 00:57:56 -08001464 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001465 RTC_LOG(LS_ERROR) << "GetStats - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001466 return false;
1467 }
1468
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001469 stats_->UpdateStats(level);
zhihuange9e94c32016-11-04 11:38:15 -07001470 // The StatsCollector is used to tell if a track is valid because it may
1471 // remember tracks that the PeerConnection previously removed.
1472 if (track && !stats_->IsValidTrack(track->id())) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001473 RTC_LOG(LS_WARNING) << "GetStats is called with an invalid track: "
1474 << track->id();
zhihuange9e94c32016-11-04 11:38:15 -07001475 return false;
1476 }
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001477 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_GETSTATS,
tommi@webrtc.org5b06b062014-08-15 08:38:30 +00001478 new GetStatsMsg(observer, track));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001479 return true;
1480}
1481
hbos74e1a4f2016-09-15 23:33:01 -07001482void PeerConnection::GetStats(RTCStatsCollectorCallback* callback) {
1483 RTC_DCHECK(stats_collector_);
1484 stats_collector_->GetStatsReport(callback);
1485}
1486
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001487PeerConnectionInterface::SignalingState PeerConnection::signaling_state() {
1488 return signaling_state_;
1489}
1490
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001491PeerConnectionInterface::IceConnectionState
1492PeerConnection::ice_connection_state() {
1493 return ice_connection_state_;
1494}
1495
1496PeerConnectionInterface::IceGatheringState
1497PeerConnection::ice_gathering_state() {
1498 return ice_gathering_state_;
1499}
1500
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001501rtc::scoped_refptr<DataChannelInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001502PeerConnection::CreateDataChannel(
1503 const std::string& label,
1504 const DataChannelInit* config) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001505 TRACE_EVENT0("webrtc", "PeerConnection::CreateDataChannel");
zhihuang9763d562016-08-05 11:14:50 -07001506
deadbeefab9b2d12015-10-14 11:33:11 -07001507 bool first_datachannel = !HasDataChannels();
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001508
kwibergd1fe2812016-04-27 06:47:29 -07001509 std::unique_ptr<InternalDataChannelInit> internal_config;
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00001510 if (config) {
1511 internal_config.reset(new InternalDataChannelInit(*config));
1512 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001513 rtc::scoped_refptr<DataChannelInterface> channel(
deadbeefab9b2d12015-10-14 11:33:11 -07001514 InternalCreateDataChannel(label, internal_config.get()));
1515 if (!channel.get()) {
1516 return nullptr;
1517 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001518
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001519 // Trigger the onRenegotiationNeeded event for every new RTP DataChannel, or
1520 // the first SCTP DataChannel.
Steve Anton75737c02017-11-06 10:37:17 -08001521 if (data_channel_type() == cricket::DCT_RTP || first_datachannel) {
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001522 observer_->OnRenegotiationNeeded();
1523 }
wu@webrtc.org91053e72013-08-10 07:18:04 +00001524
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001525 return DataChannelProxy::Create(signaling_thread(), channel.get());
1526}
1527
1528void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
1529 const MediaConstraintsInterface* constraints) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001530 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
Steve Anton8d3444d2017-10-20 15:30:51 -07001531
zhihuang1c378ed2017-08-17 14:10:50 -07001532 PeerConnectionInterface::RTCOfferAnswerOptions offer_answer_options;
1533 // Always create an offer even if |ConvertConstraintsToOfferAnswerOptions|
1534 // returns false for now. Because |ConvertConstraintsToOfferAnswerOptions|
1535 // compares the mandatory fields parsed with the mandatory fields added in the
1536 // |constraints| and some downstream applications might create offers with
1537 // mandatory fields which would not be parsed in the helper method. For
1538 // example, in Chromium/remoting, |kEnableDtlsSrtp| is added to the
1539 // |constraints| as a mandatory field but it is not parsed.
1540 ConvertConstraintsToOfferAnswerOptions(constraints, &offer_answer_options);
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001541
zhihuang1c378ed2017-08-17 14:10:50 -07001542 CreateOffer(observer, offer_answer_options);
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001543}
1544
1545void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
1546 const RTCOfferAnswerOptions& options) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001547 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
Steve Anton8d3444d2017-10-20 15:30:51 -07001548
nisse7ce109a2017-01-31 00:57:56 -08001549 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001550 RTC_LOG(LS_ERROR) << "CreateOffer - observer is NULL.";
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001551 return;
1552 }
deadbeefab9b2d12015-10-14 11:33:11 -07001553
Steve Anton8d3444d2017-10-20 15:30:51 -07001554 if (IsClosed()) {
1555 std::string error = "CreateOffer called when PeerConnection is closed.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001556 RTC_LOG(LS_ERROR) << error;
Steve Anton8d3444d2017-10-20 15:30:51 -07001557 PostCreateSessionDescriptionFailure(observer, error);
1558 return;
1559 }
1560
zhihuang1c378ed2017-08-17 14:10:50 -07001561 if (!ValidateOfferAnswerOptions(options)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001562 std::string error = "CreateOffer called with invalid options.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001563 RTC_LOG(LS_ERROR) << error;
deadbeefab9b2d12015-10-14 11:33:11 -07001564 PostCreateSessionDescriptionFailure(observer, error);
1565 return;
1566 }
1567
zhihuang1c378ed2017-08-17 14:10:50 -07001568 cricket::MediaSessionOptions session_options;
1569 GetOptionsForOffer(options, &session_options);
Steve Antond25da372017-11-06 14:50:29 -08001570 webrtc_session_desc_factory_->CreateOffer(observer, options, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001571}
1572
1573void PeerConnection::CreateAnswer(
1574 CreateSessionDescriptionObserver* observer,
1575 const MediaConstraintsInterface* constraints) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001576 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
Steve Anton8d3444d2017-10-20 15:30:51 -07001577
nisse7ce109a2017-01-31 00:57:56 -08001578 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001579 RTC_LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001580 return;
1581 }
deadbeefab9b2d12015-10-14 11:33:11 -07001582
zhihuang1c378ed2017-08-17 14:10:50 -07001583 PeerConnectionInterface::RTCOfferAnswerOptions offer_answer_options;
1584 if (!ConvertConstraintsToOfferAnswerOptions(constraints,
1585 &offer_answer_options)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001586 std::string error = "CreateAnswer called with invalid constraints.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001587 RTC_LOG(LS_ERROR) << error;
deadbeefab9b2d12015-10-14 11:33:11 -07001588 PostCreateSessionDescriptionFailure(observer, error);
1589 return;
1590 }
1591
Steve Anton8d3444d2017-10-20 15:30:51 -07001592 CreateAnswer(observer, offer_answer_options);
htaa2a49d92016-03-04 02:51:39 -08001593}
1594
1595void PeerConnection::CreateAnswer(CreateSessionDescriptionObserver* observer,
1596 const RTCOfferAnswerOptions& options) {
1597 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
nisse7ce109a2017-01-31 00:57:56 -08001598 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001599 RTC_LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
htaa2a49d92016-03-04 02:51:39 -08001600 return;
1601 }
1602
Steve Anton8d3444d2017-10-20 15:30:51 -07001603 if (IsClosed()) {
1604 std::string error = "CreateAnswer called when PeerConnection is closed.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001605 RTC_LOG(LS_ERROR) << error;
Steve Anton8d3444d2017-10-20 15:30:51 -07001606 PostCreateSessionDescriptionFailure(observer, error);
1607 return;
1608 }
1609
Steve Anton75737c02017-11-06 10:37:17 -08001610 if (remote_description() &&
Steve Antona3a92c22017-12-07 10:27:41 -08001611 remote_description()->GetType() != SdpType::kOffer) {
Steve Anton8d3444d2017-10-20 15:30:51 -07001612 std::string error = "CreateAnswer called without remote offer.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001613 RTC_LOG(LS_ERROR) << error;
Steve Anton8d3444d2017-10-20 15:30:51 -07001614 PostCreateSessionDescriptionFailure(observer, error);
1615 return;
1616 }
1617
htaa2a49d92016-03-04 02:51:39 -08001618 cricket::MediaSessionOptions session_options;
zhihuang1c378ed2017-08-17 14:10:50 -07001619 GetOptionsForAnswer(options, &session_options);
htaa2a49d92016-03-04 02:51:39 -08001620
Steve Antond25da372017-11-06 14:50:29 -08001621 webrtc_session_desc_factory_->CreateAnswer(observer, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001622}
1623
1624void PeerConnection::SetLocalDescription(
1625 SetSessionDescriptionObserver* observer,
1626 SessionDescriptionInterface* desc) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001627 TRACE_EVENT0("webrtc", "PeerConnection::SetLocalDescription");
Steve Anton8a006912017-12-04 15:25:56 -08001628
nisse7ce109a2017-01-31 00:57:56 -08001629 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001630 RTC_LOG(LS_ERROR) << "SetLocalDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001631 return;
1632 }
Steve Anton8a006912017-12-04 15:25:56 -08001633
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001634 if (!desc) {
1635 PostSetSessionDescriptionFailure(observer, "SessionDescription is NULL.");
1636 return;
1637 }
Steve Anton8d3444d2017-10-20 15:30:51 -07001638
Steve Antona3a92c22017-12-07 10:27:41 -08001639 SdpType type = desc->GetType();
Steve Anton8d3444d2017-10-20 15:30:51 -07001640
Steve Anton8a006912017-12-04 15:25:56 -08001641 RTCError error = ApplyLocalDescription(rtc::WrapUnique(desc));
1642 // |desc| may be destroyed at this point.
1643
1644 if (!error.ok()) {
Steve Antona3a92c22017-12-07 10:27:41 -08001645 std::ostringstream oss;
1646 oss << "Failed to set local " << SdpTypeToString(type)
1647 << " sdp: " << error.message();
1648 std::string error_message = oss.str();
Steve Anton8a006912017-12-04 15:25:56 -08001649 RTC_LOG(LS_ERROR) << error_message << " (" << error.type() << ")";
1650 PostSetSessionDescriptionFailure(observer, std::move(error_message));
Steve Anton8d3444d2017-10-20 15:30:51 -07001651 return;
1652 }
Steve Anton8a006912017-12-04 15:25:56 -08001653 RTC_DCHECK(local_description());
1654
1655 PostSetSessionDescriptionSuccess(observer);
1656
1657 // According to JSEP, after setLocalDescription, changing the candidate pool
1658 // size is not allowed, and changing the set of ICE servers will not result
1659 // in new candidates being gathered.
1660 port_allocator_->FreezeCandidatePool();
1661
1662 // MaybeStartGathering needs to be called after posting
1663 // MSG_SET_SESSIONDESCRIPTION_SUCCESS, so that we don't signal any candidates
1664 // before signaling that SetLocalDescription completed.
1665 transport_controller_->MaybeStartGathering();
1666
Steve Antona3a92c22017-12-07 10:27:41 -08001667 if (local_description()->GetType() == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08001668 // TODO(deadbeef): We already had to hop to the network thread for
1669 // MaybeStartGathering...
1670 network_thread()->Invoke<void>(
1671 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
1672 port_allocator_.get()));
1673 }
1674}
1675
1676RTCError PeerConnection::ApplyLocalDescription(
1677 std::unique_ptr<SessionDescriptionInterface> desc) {
1678 RTC_DCHECK_RUN_ON(signaling_thread());
1679 RTC_DCHECK(desc);
1680
1681 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_LOCAL);
1682 if (!error.ok()) {
1683 return error;
1684 }
Steve Anton8d3444d2017-10-20 15:30:51 -07001685
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001686 // Update stats here so that we have the most recent stats for tracks and
1687 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001688 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 15:25:56 -08001689
1690 // Update the initial_offerer flag if this session is the initial_offerer.
Steve Anton3828c062017-12-06 10:34:51 -08001691 SdpType type = desc->GetType();
Steve Anton8a006912017-12-04 15:25:56 -08001692 if (!initial_offerer_.has_value()) {
Steve Anton3828c062017-12-06 10:34:51 -08001693 initial_offerer_.emplace(type == SdpType::kOffer);
Steve Anton8a006912017-12-04 15:25:56 -08001694 if (*initial_offerer_) {
1695 transport_controller_->SetIceRole(cricket::ICEROLE_CONTROLLING);
1696 } else {
1697 transport_controller_->SetIceRole(cricket::ICEROLE_CONTROLLED);
1698 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001699 }
Steve Anton8a006912017-12-04 15:25:56 -08001700
Steve Antondcc3c022017-12-22 16:02:54 -08001701 // Take a reference to the old local description since it's used below to
1702 // compare against the new local description. When setting the new local
1703 // description, grab ownership of the replaced session description in case it
1704 // is the same as |old_local_description|, to keep it alive for the duration
1705 // of the method.
1706 const SessionDescriptionInterface* old_local_description =
1707 local_description();
1708 std::unique_ptr<SessionDescriptionInterface> replaced_local_description;
Steve Anton3828c062017-12-06 10:34:51 -08001709 if (type == SdpType::kAnswer) {
Steve Antondcc3c022017-12-22 16:02:54 -08001710 replaced_local_description = pending_local_description_
1711 ? std::move(pending_local_description_)
1712 : std::move(current_local_description_);
Steve Anton8a006912017-12-04 15:25:56 -08001713 current_local_description_ = std::move(desc);
1714 pending_local_description_ = nullptr;
1715 current_remote_description_ = std::move(pending_remote_description_);
1716 } else {
Steve Antondcc3c022017-12-22 16:02:54 -08001717 replaced_local_description = std::move(pending_local_description_);
Steve Anton8a006912017-12-04 15:25:56 -08001718 pending_local_description_ = std::move(desc);
1719 }
1720 // The session description to apply now must be accessed by
1721 // |local_description()|.
Henrik Boströmfdb92012017-11-09 19:55:44 +01001722 RTC_DCHECK(local_description());
deadbeefab9b2d12015-10-14 11:33:11 -07001723
Steve Antondcc3c022017-12-22 16:02:54 -08001724 if (IsUnifiedPlan()) {
1725 RTCError error = UpdateTransceiversAndDataChannels(
1726 cricket::CS_LOCAL, old_local_description, *local_description());
Steve Anton8a006912017-12-04 15:25:56 -08001727 if (!error.ok()) {
1728 return error;
1729 }
Steve Antondcc3c022017-12-22 16:02:54 -08001730 for (auto transceiver : transceivers_) {
1731 const ContentInfo* content =
1732 FindMediaSectionForTransceiver(transceiver, local_description());
1733 if (!content) {
1734 continue;
1735 }
1736 const MediaContentDescription* media_desc = content->media_description();
1737 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
1738 transceiver->internal()->set_current_direction(media_desc->direction());
1739 }
1740 if (content->rejected && !transceiver->stopped()) {
1741 transceiver->Stop();
1742 }
1743 }
1744 } else {
1745 // Transport and Media channels will be created only when offer is set.
1746 if (type == SdpType::kOffer) {
1747 // TODO(bugs.webrtc.org/4676) - Handle CreateChannel failure, as new local
1748 // description is applied. Restore back to old description.
1749 RTCError error = CreateChannels(*local_description()->description());
1750 if (!error.ok()) {
1751 return error;
1752 }
1753 }
Steve Anton8a006912017-12-04 15:25:56 -08001754
Steve Antondcc3c022017-12-22 16:02:54 -08001755 // Remove unused channels if MediaContentDescription is rejected.
1756 RemoveUnusedChannels(local_description()->description());
1757 }
Steve Anton8a006912017-12-04 15:25:56 -08001758
Steve Anton3828c062017-12-06 10:34:51 -08001759 error = UpdateSessionState(type, cricket::CS_LOCAL);
Steve Anton8a006912017-12-04 15:25:56 -08001760 if (!error.ok()) {
1761 return error;
1762 }
Steve Antondcc3c022017-12-22 16:02:54 -08001763
Steve Anton8a006912017-12-04 15:25:56 -08001764 if (remote_description()) {
1765 // Now that we have a local description, we can push down remote candidates.
1766 UseCandidatesInSessionDescription(remote_description());
1767 }
1768
1769 pending_ice_restarts_.clear();
1770 if (session_error() != SessionError::kNone) {
1771 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
1772 }
1773
deadbeefab9b2d12015-10-14 11:33:11 -07001774 // If setting the description decided our SSL role, allocate any necessary
1775 // SCTP sids.
1776 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08001777 if (data_channel_type() == cricket::DCT_SCTP && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001778 AllocateSctpSids(role);
1779 }
1780
Steve Antond3679212018-01-17 17:41:02 -08001781 if (IsUnifiedPlan()) {
1782 for (auto transceiver : transceivers_) {
1783 const ContentInfo* content =
1784 FindMediaSectionForTransceiver(transceiver, local_description());
1785 if (!content) {
1786 continue;
1787 }
1788 if (content->rejected && !transceiver->stopped()) {
1789 transceiver->Stop();
1790 }
1791 if (!content->rejected) {
1792 const auto& stream = content->media_description()->streams()[0];
1793 transceiver->internal()->sender_internal()->set_stream_ids(
1794 {stream.sync_label});
1795 transceiver->internal()->sender_internal()->SetSsrc(
1796 stream.first_ssrc());
1797 }
1798 }
1799 } else {
1800 // Plan B semantics.
1801
Steve Antondcc3c022017-12-22 16:02:54 -08001802 // Update state and SSRC of local MediaStreams and DataChannels based on the
1803 // local session description.
1804 const cricket::ContentInfo* audio_content =
1805 GetFirstAudioContent(local_description()->description());
1806 if (audio_content) {
1807 if (audio_content->rejected) {
1808 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
1809 } else {
1810 const cricket::AudioContentDescription* audio_desc =
1811 audio_content->media_description()->as_audio();
1812 UpdateLocalSenders(audio_desc->streams(), audio_desc->type());
1813 }
deadbeeffaac4972015-11-12 15:33:07 -08001814 }
deadbeefab9b2d12015-10-14 11:33:11 -07001815
Steve Antondcc3c022017-12-22 16:02:54 -08001816 const cricket::ContentInfo* video_content =
1817 GetFirstVideoContent(local_description()->description());
1818 if (video_content) {
1819 if (video_content->rejected) {
1820 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
1821 } else {
1822 const cricket::VideoContentDescription* video_desc =
1823 video_content->media_description()->as_video();
1824 UpdateLocalSenders(video_desc->streams(), video_desc->type());
1825 }
deadbeeffaac4972015-11-12 15:33:07 -08001826 }
deadbeefab9b2d12015-10-14 11:33:11 -07001827 }
1828
1829 const cricket::ContentInfo* data_content =
Henrik Boströmfdb92012017-11-09 19:55:44 +01001830 GetFirstDataContent(local_description()->description());
deadbeefab9b2d12015-10-14 11:33:11 -07001831 if (data_content) {
1832 const cricket::DataContentDescription* data_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08001833 data_content->media_description()->as_data();
deadbeefab9b2d12015-10-14 11:33:11 -07001834 if (rtc::starts_with(data_desc->protocol().data(),
1835 cricket::kMediaProtocolRtpPrefix)) {
1836 UpdateLocalRtpDataChannels(data_desc->streams());
1837 }
1838 }
1839
Steve Anton8a006912017-12-04 15:25:56 -08001840 return RTCError::OK();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001841}
1842
1843void PeerConnection::SetRemoteDescription(
Henrik Boströma4ecf552017-11-23 14:17:07 +00001844 SetSessionDescriptionObserver* observer,
1845 SessionDescriptionInterface* desc) {
Henrik Boström31638672017-11-23 17:48:32 +01001846 SetRemoteDescription(
1847 std::unique_ptr<SessionDescriptionInterface>(desc),
1848 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface>(
1849 new SetRemoteDescriptionObserverAdapter(this, observer)));
1850}
1851
1852void PeerConnection::SetRemoteDescription(
1853 std::unique_ptr<SessionDescriptionInterface> desc,
1854 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface> observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001855 TRACE_EVENT0("webrtc", "PeerConnection::SetRemoteDescription");
Steve Anton8a006912017-12-04 15:25:56 -08001856
nisse7ce109a2017-01-31 00:57:56 -08001857 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001858 RTC_LOG(LS_ERROR) << "SetRemoteDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001859 return;
1860 }
Steve Anton8a006912017-12-04 15:25:56 -08001861
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001862 if (!desc) {
Henrik Boström31638672017-11-23 17:48:32 +01001863 observer->OnSetRemoteDescriptionComplete(RTCError(
Steve Anton8a006912017-12-04 15:25:56 -08001864 RTCErrorType::INVALID_PARAMETER, "SessionDescription is NULL."));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001865 return;
1866 }
Steve Anton8d3444d2017-10-20 15:30:51 -07001867
Steve Antona3a92c22017-12-07 10:27:41 -08001868 const SdpType type = desc->GetType();
Steve Anton8a006912017-12-04 15:25:56 -08001869
1870 RTCError error = ApplyRemoteDescription(std::move(desc));
1871 // |desc| may be destroyed at this point.
1872
1873 if (!error.ok()) {
Steve Antona3a92c22017-12-07 10:27:41 -08001874 std::ostringstream oss;
1875 oss << "Failed to set remote " << SdpTypeToString(type)
1876 << " sdp: " << error.message();
1877 std::string error_message = oss.str();
Steve Anton8a006912017-12-04 15:25:56 -08001878 RTC_LOG(LS_ERROR) << error_message << " (" << error.type() << ")";
Henrik Boström31638672017-11-23 17:48:32 +01001879 observer->OnSetRemoteDescriptionComplete(
Steve Anton8a006912017-12-04 15:25:56 -08001880 RTCError(error.type(), std::move(error_message)));
Steve Anton8d3444d2017-10-20 15:30:51 -07001881 return;
1882 }
1883
Steve Antona3a92c22017-12-07 10:27:41 -08001884 if (remote_description()->GetType() == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08001885 // TODO(deadbeef): We already had to hop to the network thread for
1886 // MaybeStartGathering...
1887 network_thread()->Invoke<void>(
1888 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
1889 port_allocator_.get()));
1890 }
1891
1892 observer->OnSetRemoteDescriptionComplete(RTCError::OK());
1893}
1894
1895RTCError PeerConnection::ApplyRemoteDescription(
1896 std::unique_ptr<SessionDescriptionInterface> desc) {
1897 RTC_DCHECK_RUN_ON(signaling_thread());
1898 RTC_DCHECK(desc);
1899
1900 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_REMOTE);
1901 if (!error.ok()) {
1902 return error;
1903 }
1904
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001905 // Update stats here so that we have the most recent stats for tracks and
1906 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001907 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 15:25:56 -08001908
Steve Antondcc3c022017-12-22 16:02:54 -08001909 // Take a reference to the old remote description since it's used below to
1910 // compare against the new remote description. When setting the new remote
1911 // description, grab ownership of the replaced session description in case it
1912 // is the same as |old_remote_description|, to keep it alive for the duration
1913 // of the method.
Steve Anton8a006912017-12-04 15:25:56 -08001914 const SessionDescriptionInterface* old_remote_description =
1915 remote_description();
Steve Anton8a006912017-12-04 15:25:56 -08001916 std::unique_ptr<SessionDescriptionInterface> replaced_remote_description;
Steve Anton3828c062017-12-06 10:34:51 -08001917 SdpType type = desc->GetType();
1918 if (type == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08001919 replaced_remote_description = pending_remote_description_
1920 ? std::move(pending_remote_description_)
1921 : std::move(current_remote_description_);
1922 current_remote_description_ = std::move(desc);
1923 pending_remote_description_ = nullptr;
1924 current_local_description_ = std::move(pending_local_description_);
1925 } else {
1926 replaced_remote_description = std::move(pending_remote_description_);
1927 pending_remote_description_ = std::move(desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001928 }
Steve Anton8a006912017-12-04 15:25:56 -08001929 // The session description to apply now must be accessed by
1930 // |remote_description()|.
Henrik Boströmfdb92012017-11-09 19:55:44 +01001931 RTC_DCHECK(remote_description());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001932
Steve Anton8a006912017-12-04 15:25:56 -08001933 // Transport and Media channels will be created only when offer is set.
Steve Antondcc3c022017-12-22 16:02:54 -08001934 if (IsUnifiedPlan()) {
1935 RTCError error = UpdateTransceiversAndDataChannels(
1936 cricket::CS_REMOTE, old_remote_description, *remote_description());
Steve Anton8a006912017-12-04 15:25:56 -08001937 if (!error.ok()) {
1938 return error;
1939 }
Steve Antondcc3c022017-12-22 16:02:54 -08001940 } else {
1941 if (type == SdpType::kOffer) {
1942 // TODO(bugs.webrtc.org/4676) - Handle CreateChannel failure, as new local
1943 // description is applied. Restore back to old description.
1944 RTCError error = CreateChannels(*remote_description()->description());
1945 if (!error.ok()) {
1946 return error;
1947 }
1948 }
Steve Anton8a006912017-12-04 15:25:56 -08001949
Steve Antondcc3c022017-12-22 16:02:54 -08001950 // Remove unused channels if MediaContentDescription is rejected.
1951 RemoveUnusedChannels(remote_description()->description());
1952 }
Steve Anton8a006912017-12-04 15:25:56 -08001953
1954 // NOTE: Candidates allocation will be initiated only when SetLocalDescription
1955 // is called.
Steve Anton3828c062017-12-06 10:34:51 -08001956 error = UpdateSessionState(type, cricket::CS_REMOTE);
Steve Anton8a006912017-12-04 15:25:56 -08001957 if (!error.ok()) {
1958 return error;
1959 }
1960
1961 if (local_description() &&
1962 !UseCandidatesInSessionDescription(remote_description())) {
1963 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidCandidates);
1964 }
1965
1966 if (old_remote_description) {
1967 for (const cricket::ContentInfo& content :
1968 old_remote_description->description()->contents()) {
1969 // Check if this new SessionDescription contains new ICE ufrag and
1970 // password that indicates the remote peer requests an ICE restart.
1971 // TODO(deadbeef): When we start storing both the current and pending
1972 // remote description, this should reset pending_ice_restarts and compare
1973 // against the current description.
1974 if (CheckForRemoteIceRestart(old_remote_description, remote_description(),
1975 content.name)) {
Steve Anton3828c062017-12-06 10:34:51 -08001976 if (type == SdpType::kOffer) {
Steve Anton8a006912017-12-04 15:25:56 -08001977 pending_ice_restarts_.insert(content.name);
1978 }
1979 } else {
1980 // We retain all received candidates only if ICE is not restarted.
1981 // When ICE is restarted, all previous candidates belong to an old
1982 // generation and should not be kept.
1983 // TODO(deadbeef): This goes against the W3C spec which says the remote
1984 // description should only contain candidates from the last set remote
1985 // description plus any candidates added since then. We should remove
1986 // this once we're sure it won't break anything.
1987 WebRtcSessionDescriptionFactory::CopyCandidatesFromSessionDescription(
1988 old_remote_description, content.name, mutable_remote_description());
1989 }
1990 }
1991 }
1992
1993 if (session_error() != SessionError::kNone) {
1994 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
1995 }
1996
1997 // Set the the ICE connection state to connecting since the connection may
1998 // become writable with peer reflexive candidates before any remote candidate
1999 // is signaled.
2000 // TODO(pthatcher): This is a short-term solution for crbug/446908. A real fix
2001 // is to have a new signal the indicates a change in checking state from the
2002 // transport and expose a new checking() member from transport that can be
2003 // read to determine the current checking state. The existing SignalConnecting
2004 // actually means "gathering candidates", so cannot be be used here.
Steve Antona3a92c22017-12-07 10:27:41 -08002005 if (remote_description()->GetType() != SdpType::kOffer &&
Steve Anton8a006912017-12-04 15:25:56 -08002006 ice_connection_state() == PeerConnectionInterface::kIceConnectionNew) {
2007 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
2008 }
2009
deadbeefab9b2d12015-10-14 11:33:11 -07002010 // If setting the description decided our SSL role, allocate any necessary
2011 // SCTP sids.
2012 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08002013 if (data_channel_type() == cricket::DCT_SCTP && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07002014 AllocateSctpSids(role);
2015 }
2016
Steve Antondcc3c022017-12-22 16:02:54 -08002017 if (IsUnifiedPlan()) {
Steve Antonef65ef12018-01-10 17:15:20 -08002018 std::vector<TrackEvent> track_events;
Steve Antondcc3c022017-12-22 16:02:54 -08002019 for (auto transceiver : transceivers_) {
2020 const ContentInfo* content =
2021 FindMediaSectionForTransceiver(transceiver, remote_description());
2022 if (!content) {
2023 continue;
2024 }
2025 const MediaContentDescription* media_desc = content->media_description();
2026 RtpTransceiverDirection local_direction =
2027 RtpTransceiverDirectionReversed(media_desc->direction());
2028 // From the WebRTC specification, steps 2.2.8.5/6 of section 4.4.1.6 "Set
2029 // the RTCSessionDescription: If direction is sendrecv or recvonly, and
2030 // transceiver's current direction is neither sendrecv nor recvonly,
2031 // process the addition of a remote track for the media description.
2032 if (RtpTransceiverDirectionHasRecv(local_direction) &&
2033 (!transceiver->current_direction() ||
2034 !RtpTransceiverDirectionHasRecv(
2035 *transceiver->current_direction()))) {
Steve Antonef65ef12018-01-10 17:15:20 -08002036 const std::string& sync_label = media_desc->streams()[0].sync_label;
2037 rtc::scoped_refptr<MediaStreamInterface> stream =
2038 remote_streams_->find(sync_label);
2039 if (!stream) {
2040 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
2041 MediaStream::Create(sync_label));
2042 remote_streams_->AddStream(stream);
2043 }
2044 transceiver->internal()->receiver_internal()->SetStreams({stream});
2045 TrackEvent track_event;
2046 track_event.receiver = transceiver->receiver();
2047 track_event.streams = transceiver->receiver()->streams();
2048 track_events.push_back(std::move(track_event));
Steve Antondcc3c022017-12-22 16:02:54 -08002049 }
2050 // If direction is sendonly or inactive, and transceiver's current
2051 // direction is neither sendonly nor inactive, process the removal of a
2052 // remote track for the media description.
2053 if (!RtpTransceiverDirectionHasRecv(local_direction) &&
Steve Antonef65ef12018-01-10 17:15:20 -08002054 (transceiver->current_direction() &&
Steve Antondcc3c022017-12-22 16:02:54 -08002055 RtpTransceiverDirectionHasRecv(*transceiver->current_direction()))) {
Steve Antonef65ef12018-01-10 17:15:20 -08002056 transceiver->internal()->receiver_internal()->SetStreams({});
Steve Antondcc3c022017-12-22 16:02:54 -08002057 }
2058 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
2059 transceiver->internal()->set_current_direction(local_direction);
2060 }
2061 if (content->rejected && !transceiver->stopped()) {
2062 transceiver->Stop();
2063 }
Steve Antond3679212018-01-17 17:41:02 -08002064 if (!content->rejected) {
2065 const auto& stream = content->media_description()->streams()[0];
2066 transceiver->internal()->receiver_internal()->SetupMediaChannel(
2067 stream.first_ssrc());
2068 }
Steve Antondcc3c022017-12-22 16:02:54 -08002069 }
Steve Antonef65ef12018-01-10 17:15:20 -08002070 for (auto event : track_events) {
2071 observer_->OnAddTrack(event.receiver, event.streams);
2072 }
Steve Antondcc3c022017-12-22 16:02:54 -08002073 }
2074
Henrik Boströmfdb92012017-11-09 19:55:44 +01002075 const cricket::ContentInfo* audio_content =
2076 GetFirstAudioContent(remote_description()->description());
2077 const cricket::ContentInfo* video_content =
2078 GetFirstVideoContent(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002079 const cricket::AudioContentDescription* audio_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002080 GetFirstAudioContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002081 const cricket::VideoContentDescription* video_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002082 GetFirstVideoContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002083 const cricket::DataContentDescription* data_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002084 GetFirstDataContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002085
2086 // Check if the descriptions include streams, just in case the peer supports
2087 // MSID, but doesn't indicate so with "a=msid-semantic".
Henrik Boströmfdb92012017-11-09 19:55:44 +01002088 if (remote_description()->description()->msid_supported() ||
deadbeefbda7e0b2015-12-08 17:13:40 -08002089 (audio_desc && !audio_desc->streams().empty()) ||
2090 (video_desc && !video_desc->streams().empty())) {
2091 remote_peer_supports_msid_ = true;
2092 }
deadbeefab9b2d12015-10-14 11:33:11 -07002093
2094 // We wait to signal new streams until we finish processing the description,
2095 // since only at that point will new streams have all their tracks.
2096 rtc::scoped_refptr<StreamCollection> new_streams(StreamCollection::Create());
2097
Steve Antondcc3c022017-12-22 16:02:54 -08002098 if (!IsUnifiedPlan()) {
2099 // TODO(steveanton): When removing RTP senders/receivers in response to a
2100 // rejected media section, there is some cleanup logic that expects the
2101 // voice/ video channel to still be set. But in this method the voice/video
2102 // channel would have been destroyed by the SetRemoteDescription caller
2103 // above so the cleanup that relies on them fails to run. The RemoveSenders
2104 // calls should be moved to right before the DestroyChannel calls to fix
2105 // this.
Steve Anton8d3444d2017-10-20 15:30:51 -07002106
Steve Antondcc3c022017-12-22 16:02:54 -08002107 // Find all audio rtp streams and create corresponding remote AudioTracks
2108 // and MediaStreams.
2109 if (audio_content) {
2110 if (audio_content->rejected) {
2111 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
2112 } else {
2113 bool default_audio_track_needed =
2114 !remote_peer_supports_msid_ &&
2115 RtpTransceiverDirectionHasSend(audio_desc->direction());
2116 UpdateRemoteSendersList(GetActiveStreams(audio_desc),
2117 default_audio_track_needed, audio_desc->type(),
2118 new_streams);
2119 }
deadbeeffaac4972015-11-12 15:33:07 -08002120 }
deadbeefab9b2d12015-10-14 11:33:11 -07002121
Steve Antondcc3c022017-12-22 16:02:54 -08002122 // Find all video rtp streams and create corresponding remote VideoTracks
2123 // and MediaStreams.
2124 if (video_content) {
2125 if (video_content->rejected) {
2126 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
2127 } else {
2128 bool default_video_track_needed =
2129 !remote_peer_supports_msid_ &&
2130 RtpTransceiverDirectionHasSend(video_desc->direction());
2131 UpdateRemoteSendersList(GetActiveStreams(video_desc),
2132 default_video_track_needed, video_desc->type(),
2133 new_streams);
2134 }
deadbeeffaac4972015-11-12 15:33:07 -08002135 }
deadbeefab9b2d12015-10-14 11:33:11 -07002136
Steve Antondcc3c022017-12-22 16:02:54 -08002137 // Update the DataChannels with the information from the remote peer.
2138 if (data_desc) {
2139 if (rtc::starts_with(data_desc->protocol().data(),
2140 cricket::kMediaProtocolRtpPrefix)) {
2141 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
2142 }
deadbeefab9b2d12015-10-14 11:33:11 -07002143 }
deadbeefab9b2d12015-10-14 11:33:11 -07002144
Steve Antondcc3c022017-12-22 16:02:54 -08002145 // Iterate new_streams and notify the observer about new MediaStreams.
2146 for (size_t i = 0; i < new_streams->count(); ++i) {
2147 MediaStreamInterface* new_stream = new_streams->at(i);
2148 stats_->AddStream(new_stream);
2149 observer_->OnAddStream(
2150 rtc::scoped_refptr<MediaStreamInterface>(new_stream));
2151 }
deadbeefab9b2d12015-10-14 11:33:11 -07002152
Steve Antondcc3c022017-12-22 16:02:54 -08002153 UpdateEndedRemoteMediaStreams();
2154 }
deadbeefab9b2d12015-10-14 11:33:11 -07002155
Steve Anton8a006912017-12-04 15:25:56 -08002156 return RTCError::OK();
deadbeeffc648b62015-10-13 16:42:33 -07002157}
2158
Steve Antondcc3c022017-12-22 16:02:54 -08002159RTCError PeerConnection::UpdateTransceiversAndDataChannels(
2160 cricket::ContentSource source,
2161 const SessionDescriptionInterface* old_session,
2162 const SessionDescriptionInterface& new_session) {
2163 RTC_DCHECK(IsUnifiedPlan());
2164
Steve Anton7464fca2018-01-19 11:10:37 -08002165 const cricket::ContentGroup* bundle_group = nullptr;
2166 if (new_session.GetType() == SdpType::kOffer) {
2167 auto bundle_group_or_error =
2168 GetEarlyBundleGroup(*new_session.description());
2169 if (!bundle_group_or_error.ok()) {
2170 return bundle_group_or_error.MoveError();
2171 }
2172 bundle_group = bundle_group_or_error.MoveValue();
Steve Antondcc3c022017-12-22 16:02:54 -08002173 }
Steve Antondcc3c022017-12-22 16:02:54 -08002174
2175 const ContentInfos& old_contents =
2176 (old_session ? old_session->description()->contents() : ContentInfos());
2177 const ContentInfos& new_contents = new_session.description()->contents();
2178
2179 for (size_t i = 0; i < new_contents.size(); ++i) {
2180 const cricket::ContentInfo& new_content = new_contents[i];
2181 const cricket::ContentInfo* old_content =
2182 (i < old_contents.size() ? &old_contents[i] : nullptr);
2183 cricket::MediaType media_type = new_content.media_description()->type();
2184 seen_mids_.insert(new_content.name);
2185 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
2186 media_type == cricket::MEDIA_TYPE_VIDEO) {
2187 auto transceiver_or_error =
2188 AssociateTransceiver(source, i, new_content, old_content);
2189 if (!transceiver_or_error.ok()) {
2190 return transceiver_or_error.MoveError();
2191 }
2192 auto transceiver = transceiver_or_error.MoveValue();
2193 if (source == cricket::CS_LOCAL && transceiver->stopped()) {
2194 continue;
2195 }
2196 RTCError error =
2197 UpdateTransceiverChannel(transceiver, new_content, bundle_group);
2198 if (!error.ok()) {
2199 return error;
2200 }
2201 } else if (media_type == cricket::MEDIA_TYPE_DATA) {
Steve Antonfa2260d2017-12-28 16:38:23 -08002202 if (GetDataMid() && new_content.name != *GetDataMid()) {
2203 // Ignore all but the first data section.
2204 continue;
2205 }
2206 RTCError error = UpdateDataChannel(source, new_content, bundle_group);
2207 if (!error.ok()) {
2208 return error;
2209 }
Steve Antondcc3c022017-12-22 16:02:54 -08002210 } else {
2211 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
2212 "Unknown section type.");
2213 }
2214 }
2215
2216 return RTCError::OK();
2217}
2218
2219RTCError PeerConnection::UpdateTransceiverChannel(
2220 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2221 transceiver,
2222 const cricket::ContentInfo& content,
2223 const cricket::ContentGroup* bundle_group) {
2224 RTC_DCHECK(IsUnifiedPlan());
2225 RTC_DCHECK(transceiver);
2226 cricket::BaseChannel* channel = transceiver->internal()->channel();
2227 if (content.rejected) {
2228 if (channel) {
2229 transceiver->internal()->SetChannel(nullptr);
2230 DestroyBaseChannel(channel);
2231 }
2232 } else {
2233 if (!channel) {
2234 if (transceiver->internal()->media_type() == cricket::MEDIA_TYPE_AUDIO) {
2235 channel = CreateVoiceChannel(
2236 content.name,
2237 GetTransportNameForMediaSection(content.name, bundle_group));
2238 } else {
2239 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO,
2240 transceiver->internal()->media_type());
2241 channel = CreateVideoChannel(
2242 content.name,
2243 GetTransportNameForMediaSection(content.name, bundle_group));
2244 }
2245 if (!channel) {
2246 LOG_AND_RETURN_ERROR(
2247 RTCErrorType::INTERNAL_ERROR,
2248 "Failed to create channel for mid=" + content.name);
2249 }
2250 transceiver->internal()->SetChannel(channel);
2251 }
2252 }
2253 return RTCError::OK();
2254}
2255
Steve Antonfa2260d2017-12-28 16:38:23 -08002256RTCError PeerConnection::UpdateDataChannel(
2257 cricket::ContentSource source,
2258 const cricket::ContentInfo& content,
2259 const cricket::ContentGroup* bundle_group) {
2260 if (data_channel_type_ == cricket::DCT_NONE) {
Steve Antondbf9d032018-01-19 15:23:40 -08002261 // If data channels are disabled, ignore this media section. CreateAnswer
2262 // will take care of rejecting it.
2263 return RTCError::OK();
Steve Antonfa2260d2017-12-28 16:38:23 -08002264 }
2265 if (content.rejected) {
2266 DestroyDataChannel();
2267 } else {
2268 if (!rtp_data_channel_ && !sctp_transport_) {
2269 if (!CreateDataChannel(content.name, GetTransportNameForMediaSection(
2270 content.name, bundle_group))) {
2271 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
2272 "Failed to create data channel.");
2273 }
2274 }
2275 if (source == cricket::CS_REMOTE) {
2276 const MediaContentDescription* data_desc = content.media_description();
2277 if (data_desc && cricket::IsRtpProtocol(data_desc->protocol())) {
2278 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
2279 }
2280 }
2281 }
2282 return RTCError::OK();
2283}
2284
Steve Antondcc3c022017-12-22 16:02:54 -08002285RTCErrorOr<rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
2286PeerConnection::AssociateTransceiver(cricket::ContentSource source,
2287 size_t mline_index,
2288 const ContentInfo& content,
2289 const ContentInfo* old_content) {
2290 RTC_DCHECK(IsUnifiedPlan());
2291 // If the m= section is being recycled (rejected in previous remote
2292 // description, not rejected in current description), dissociate the currently
2293 // associated RtpTransceiver by setting its mid property to null, and discard
2294 // the mapping between the transceiver and its m= section index.
2295 if (old_content && old_content->rejected && !content.rejected) {
2296 auto old_transceiver = GetAssociatedTransceiver(old_content->name);
2297 if (old_transceiver) {
2298 old_transceiver->internal()->set_mid(rtc::nullopt);
2299 old_transceiver->internal()->set_mline_index(rtc::nullopt);
2300 }
2301 }
2302 const MediaContentDescription* media_desc = content.media_description();
2303 auto transceiver = GetAssociatedTransceiver(content.name);
2304 if (source == cricket::CS_LOCAL) {
2305 // Find the RtpTransceiver that corresponds to this m= section, using the
2306 // mapping between transceivers and m= section indices established when
2307 // creating the offer.
2308 if (!transceiver) {
2309 transceiver = GetTransceiverByMLineIndex(mline_index);
2310 }
2311 if (!transceiver) {
2312 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2313 "Unknown transceiver");
2314 }
2315 } else {
2316 RTC_DCHECK_EQ(source, cricket::CS_REMOTE);
2317 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers
2318 // of the same type...
2319 if (!transceiver &&
2320 RtpTransceiverDirectionHasRecv(media_desc->direction())) {
2321 transceiver = FindAvailableTransceiverToReceive(media_desc->type());
2322 }
2323 // If no RtpTransceiver was found in the previous step, create one with a
2324 // recvonly direction.
2325 if (!transceiver) {
Steve Anton02ee47c2018-01-10 16:26:06 -08002326 auto sender =
2327 CreateSender(media_desc->type(), nullptr, {rtc::CreateRandomUuid()});
2328 auto receiver =
2329 CreateReceiver(media_desc->type(), media_desc->streams()[0].id);
2330 transceiver = CreateAndAddTransceiver(sender, receiver);
Steve Antondcc3c022017-12-22 16:02:54 -08002331 transceiver->internal()->set_direction(
2332 RtpTransceiverDirection::kRecvOnly);
2333 }
2334 }
2335 RTC_DCHECK(transceiver);
2336 if (transceiver->internal()->media_type() != media_desc->type()) {
2337 LOG_AND_RETURN_ERROR(
2338 RTCErrorType::INVALID_PARAMETER,
2339 "Transceiver type does not match media description type.");
2340 }
2341 // Associate the found or created RtpTransceiver with the m= section by
2342 // setting the value of the RtpTransceiver's mid property to the MID of the m=
2343 // section, and establish a mapping between the transceiver and the index of
2344 // the m= section.
2345 transceiver->internal()->set_mid(content.name);
2346 transceiver->internal()->set_mline_index(mline_index);
2347 return std::move(transceiver);
2348}
2349
2350rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2351PeerConnection::GetAssociatedTransceiver(const std::string& mid) const {
2352 RTC_DCHECK(IsUnifiedPlan());
2353 for (auto transceiver : transceivers_) {
2354 if (transceiver->mid() == mid) {
2355 return transceiver;
2356 }
2357 }
2358 return nullptr;
2359}
2360
2361rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2362PeerConnection::GetTransceiverByMLineIndex(size_t mline_index) const {
2363 RTC_DCHECK(IsUnifiedPlan());
2364 for (auto transceiver : transceivers_) {
2365 if (transceiver->internal()->mline_index() == mline_index) {
2366 return transceiver;
2367 }
2368 }
2369 return nullptr;
2370}
2371
2372rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2373PeerConnection::FindAvailableTransceiverToReceive(
2374 cricket::MediaType media_type) const {
2375 RTC_DCHECK(IsUnifiedPlan());
2376 // From JSEP section 5.10 (Applying a Remote Description):
2377 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers of
2378 // the same type that were added to the PeerConnection by addTrack and are not
2379 // associated with any m= section and are not stopped, find the first such
2380 // RtpTransceiver.
2381 for (auto transceiver : transceivers_) {
2382 if (transceiver->internal()->media_type() == media_type &&
2383 transceiver->internal()->created_by_addtrack() && !transceiver->mid() &&
2384 !transceiver->stopped()) {
2385 return transceiver;
2386 }
2387 }
2388 return nullptr;
2389}
2390
Steve Antoned10bd92017-12-05 10:52:59 -08002391const cricket::ContentInfo* PeerConnection::FindMediaSectionForTransceiver(
2392 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2393 transceiver,
2394 const SessionDescriptionInterface* sdesc) const {
2395 RTC_DCHECK(transceiver);
2396 RTC_DCHECK(sdesc);
2397 if (IsUnifiedPlan()) {
2398 if (!transceiver->internal()->mid()) {
2399 // This transceiver is not associated with a media section yet.
2400 return nullptr;
2401 }
2402 return sdesc->description()->GetContentByName(
2403 *transceiver->internal()->mid());
2404 } else {
2405 // Plan B only allows at most one audio and one video section, so use the
2406 // first media section of that type.
2407 return cricket::GetFirstMediaContent(sdesc->description()->contents(),
2408 transceiver->internal()->media_type());
2409 }
2410}
2411
deadbeef46c73892016-11-16 19:42:04 -08002412PeerConnectionInterface::RTCConfiguration PeerConnection::GetConfiguration() {
2413 return configuration_;
2414}
2415
deadbeef293e9262017-01-11 12:28:30 -08002416bool PeerConnection::SetConfiguration(const RTCConfiguration& configuration,
2417 RTCError* error) {
Peter Boström1a9d6152015-12-08 22:15:17 +01002418 TRACE_EVENT0("webrtc", "PeerConnection::SetConfiguration");
deadbeef6de92f92016-12-12 18:49:32 -08002419
Steve Anton75737c02017-11-06 10:37:17 -08002420 if (local_description() && configuration.ice_candidate_pool_size !=
2421 configuration_.ice_candidate_pool_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002422 RTC_LOG(LS_ERROR) << "Can't change candidate pool size after calling "
2423 "SetLocalDescription.";
deadbeef293e9262017-01-11 12:28:30 -08002424 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00002425 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002426
deadbeef293e9262017-01-11 12:28:30 -08002427 // The simplest (and most future-compatible) way to tell if the config was
2428 // modified in an invalid way is to copy each property we do support
2429 // modifying, then use operator==. There are far more properties we don't
2430 // support modifying than those we do, and more could be added.
2431 RTCConfiguration modified_config = configuration_;
2432 modified_config.servers = configuration.servers;
2433 modified_config.type = configuration.type;
2434 modified_config.ice_candidate_pool_size =
2435 configuration.ice_candidate_pool_size;
2436 modified_config.prune_turn_ports = configuration.prune_turn_ports;
skvladd1f5fda2017-02-03 16:54:05 -08002437 modified_config.ice_check_min_interval = configuration.ice_check_min_interval;
Jonas Orelandbdcee282017-10-10 14:01:40 +02002438 modified_config.turn_customizer = configuration.turn_customizer;
deadbeef293e9262017-01-11 12:28:30 -08002439 if (configuration != modified_config) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002440 RTC_LOG(LS_ERROR) << "Modifying the configuration in an unsupported way.";
deadbeef293e9262017-01-11 12:28:30 -08002441 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
2442 }
2443
Steve Anton038834f2017-07-14 15:59:59 -07002444 // Validate the modified configuration.
2445 RTCError validate_error = ValidateConfiguration(modified_config);
2446 if (!validate_error.ok()) {
2447 return SafeSetError(std::move(validate_error), error);
2448 }
2449
deadbeef293e9262017-01-11 12:28:30 -08002450 // Note that this isn't possible through chromium, since it's an unsigned
2451 // short in WebIDL.
2452 if (configuration.ice_candidate_pool_size < 0 ||
2453 configuration.ice_candidate_pool_size > UINT16_MAX) {
2454 return SafeSetError(RTCErrorType::INVALID_RANGE, error);
2455 }
2456
2457 // Parse ICE servers before hopping to network thread.
2458 cricket::ServerAddresses stun_servers;
2459 std::vector<cricket::RelayServerConfig> turn_servers;
2460 RTCErrorType parse_error =
2461 ParseIceServers(configuration.servers, &stun_servers, &turn_servers);
2462 if (parse_error != RTCErrorType::NONE) {
2463 return SafeSetError(parse_error, error);
2464 }
2465
2466 // In theory this shouldn't fail.
2467 if (!network_thread()->Invoke<bool>(
2468 RTC_FROM_HERE,
2469 rtc::Bind(&PeerConnection::ReconfigurePortAllocator_n, this,
2470 stun_servers, turn_servers, modified_config.type,
2471 modified_config.ice_candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02002472 modified_config.prune_turn_ports,
2473 modified_config.turn_customizer))) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002474 RTC_LOG(LS_ERROR) << "Failed to apply configuration to PortAllocator.";
deadbeef293e9262017-01-11 12:28:30 -08002475 return SafeSetError(RTCErrorType::INTERNAL_ERROR, error);
2476 }
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07002477
deadbeefd1a38b52016-12-10 13:15:33 -08002478 // As described in JSEP, calling setConfiguration with new ICE servers or
2479 // candidate policy must set a "needs-ice-restart" bit so that the next offer
2480 // triggers an ICE restart which will pick up the changes.
deadbeef293e9262017-01-11 12:28:30 -08002481 if (modified_config.servers != configuration_.servers ||
2482 modified_config.type != configuration_.type ||
2483 modified_config.prune_turn_ports != configuration_.prune_turn_ports) {
Steve Antond25da372017-11-06 14:50:29 -08002484 transport_controller_->SetNeedsIceRestartFlag();
deadbeefd1a38b52016-12-10 13:15:33 -08002485 }
skvladd1f5fda2017-02-03 16:54:05 -08002486
2487 if (modified_config.ice_check_min_interval !=
2488 configuration_.ice_check_min_interval) {
Steve Antond25da372017-11-06 14:50:29 -08002489 transport_controller_->SetIceConfig(ParseIceConfig(modified_config));
skvladd1f5fda2017-02-03 16:54:05 -08002490 }
2491
deadbeef293e9262017-01-11 12:28:30 -08002492 configuration_ = modified_config;
2493 return SafeSetError(RTCErrorType::NONE, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00002494}
2495
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002496bool PeerConnection::AddIceCandidate(
2497 const IceCandidateInterface* ice_candidate) {
Peter Boström1a9d6152015-12-08 22:15:17 +01002498 TRACE_EVENT0("webrtc", "PeerConnection::AddIceCandidate");
zhihuang29ff8442016-07-27 11:07:25 -07002499 if (IsClosed()) {
2500 return false;
2501 }
Steve Antond25da372017-11-06 14:50:29 -08002502
2503 if (!remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002504 RTC_LOG(LS_ERROR) << "ProcessIceMessage: ICE candidates can't be added "
2505 << "without any remote session description.";
Steve Antond25da372017-11-06 14:50:29 -08002506 return false;
2507 }
2508
2509 if (!ice_candidate) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002510 RTC_LOG(LS_ERROR) << "ProcessIceMessage: Candidate is NULL.";
Steve Antond25da372017-11-06 14:50:29 -08002511 return false;
2512 }
2513
2514 bool valid = false;
2515 bool ready = ReadyToUseRemoteCandidate(ice_candidate, nullptr, &valid);
2516 if (!valid) {
2517 return false;
2518 }
2519
2520 // Add this candidate to the remote session description.
2521 if (!mutable_remote_description()->AddCandidate(ice_candidate)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002522 RTC_LOG(LS_ERROR) << "ProcessIceMessage: Candidate cannot be used.";
Steve Antond25da372017-11-06 14:50:29 -08002523 return false;
2524 }
2525
2526 if (ready) {
2527 return UseCandidate(ice_candidate);
2528 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002529 RTC_LOG(LS_INFO) << "ProcessIceMessage: Not ready to use candidate.";
Steve Antond25da372017-11-06 14:50:29 -08002530 return true;
2531 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002532}
2533
Honghai Zhang7fb69db2016-03-14 11:59:18 -07002534bool PeerConnection::RemoveIceCandidates(
2535 const std::vector<cricket::Candidate>& candidates) {
2536 TRACE_EVENT0("webrtc", "PeerConnection::RemoveIceCandidates");
Steve Antond25da372017-11-06 14:50:29 -08002537 if (!remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002538 RTC_LOG(LS_ERROR) << "RemoveRemoteIceCandidates: ICE candidates can't be "
2539 << "removed without any remote session description.";
Steve Antond25da372017-11-06 14:50:29 -08002540 return false;
2541 }
2542
2543 if (candidates.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002544 RTC_LOG(LS_ERROR) << "RemoveRemoteIceCandidates: candidates are empty.";
Steve Antond25da372017-11-06 14:50:29 -08002545 return false;
2546 }
2547
2548 size_t number_removed =
2549 mutable_remote_description()->RemoveCandidates(candidates);
2550 if (number_removed != candidates.size()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002551 RTC_LOG(LS_ERROR)
2552 << "RemoveRemoteIceCandidates: Failed to remove candidates. "
2553 << "Requested " << candidates.size() << " but only " << number_removed
2554 << " are removed.";
Steve Antond25da372017-11-06 14:50:29 -08002555 }
2556
2557 // Remove the candidates from the transport controller.
2558 std::string error;
2559 bool res = transport_controller_->RemoveRemoteCandidates(candidates, &error);
2560 if (!res && !error.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002561 RTC_LOG(LS_ERROR) << "Error when removing remote candidates: " << error;
Steve Antond25da372017-11-06 14:50:29 -08002562 }
2563 return true;
Honghai Zhang7fb69db2016-03-14 11:59:18 -07002564}
2565
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00002566void PeerConnection::RegisterUMAObserver(UMAObserver* observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +01002567 TRACE_EVENT0("webrtc", "PeerConnection::RegisterUmaObserver");
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00002568 uma_observer_ = observer;
guoweis@webrtc.org7169afd2014-12-04 17:59:29 +00002569
Steve Anton75737c02017-11-06 10:37:17 -08002570 if (transport_controller()) {
2571 transport_controller()->SetMetricsObserver(uma_observer_);
guoweis@webrtc.org7169afd2014-12-04 17:59:29 +00002572 }
2573
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00002574 // Send information about IPv4/IPv6 status.
deadbeef293e9262017-01-11 12:28:30 -08002575 if (uma_observer_) {
Honghai Zhangd93f50c2016-10-05 11:47:22 -07002576 port_allocator_->SetMetricsObserver(uma_observer_);
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00002577 if (port_allocator_->flags() & cricket::PORTALLOCATOR_ENABLE_IPV6) {
Guo-wei Shiehdfbe6792015-09-03 17:12:07 -07002578 uma_observer_->IncrementEnumCounter(
2579 kEnumCounterAddressFamily, kPeerConnection_IPv6,
2580 kPeerConnectionAddressFamilyCounter_Max);
mallinath@webrtc.orgb445f262014-05-23 22:19:37 +00002581 } else {
Guo-wei Shiehdfbe6792015-09-03 17:12:07 -07002582 uma_observer_->IncrementEnumCounter(
2583 kEnumCounterAddressFamily, kPeerConnection_IPv4,
2584 kPeerConnectionAddressFamilyCounter_Max);
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00002585 }
2586 }
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00002587}
2588
zstein4b979802017-06-02 14:37:37 -07002589RTCError PeerConnection::SetBitrate(const BitrateParameters& bitrate) {
Steve Anton978b8762017-09-29 12:15:02 -07002590 if (!worker_thread()->IsCurrent()) {
2591 return worker_thread()->Invoke<RTCError>(
zstein4b979802017-06-02 14:37:37 -07002592 RTC_FROM_HERE, rtc::Bind(&PeerConnection::SetBitrate, this, bitrate));
2593 }
2594
2595 const bool has_min = static_cast<bool>(bitrate.min_bitrate_bps);
2596 const bool has_current = static_cast<bool>(bitrate.current_bitrate_bps);
2597 const bool has_max = static_cast<bool>(bitrate.max_bitrate_bps);
2598 if (has_min && *bitrate.min_bitrate_bps < 0) {
2599 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2600 "min_bitrate_bps <= 0");
2601 }
2602 if (has_current) {
2603 if (has_min && *bitrate.current_bitrate_bps < *bitrate.min_bitrate_bps) {
2604 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2605 "current_bitrate_bps < min_bitrate_bps");
2606 } else if (*bitrate.current_bitrate_bps < 0) {
2607 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2608 "curent_bitrate_bps < 0");
2609 }
2610 }
2611 if (has_max) {
2612 if (has_current &&
2613 *bitrate.max_bitrate_bps < *bitrate.current_bitrate_bps) {
2614 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2615 "max_bitrate_bps < current_bitrate_bps");
2616 } else if (has_min && *bitrate.max_bitrate_bps < *bitrate.min_bitrate_bps) {
2617 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2618 "max_bitrate_bps < min_bitrate_bps");
2619 } else if (*bitrate.max_bitrate_bps < 0) {
2620 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2621 "max_bitrate_bps < 0");
2622 }
2623 }
2624
2625 Call::Config::BitrateConfigMask mask;
2626 mask.min_bitrate_bps = bitrate.min_bitrate_bps;
2627 mask.start_bitrate_bps = bitrate.current_bitrate_bps;
2628 mask.max_bitrate_bps = bitrate.max_bitrate_bps;
2629
2630 RTC_DCHECK(call_.get());
2631 call_->SetBitrateConfigMask(mask);
2632
2633 return RTCError::OK();
2634}
2635
Alex Narest78609d52017-10-20 10:37:47 +02002636void PeerConnection::SetBitrateAllocationStrategy(
2637 std::unique_ptr<rtc::BitrateAllocationStrategy>
2638 bitrate_allocation_strategy) {
2639 rtc::Thread* worker_thread = factory_->worker_thread();
2640 if (!worker_thread->IsCurrent()) {
2641 rtc::BitrateAllocationStrategy* strategy_raw =
2642 bitrate_allocation_strategy.release();
2643 auto functor = [this, strategy_raw]() {
2644 call_->SetBitrateAllocationStrategy(
2645 rtc::WrapUnique<rtc::BitrateAllocationStrategy>(strategy_raw));
2646 };
2647 worker_thread->Invoke<void>(RTC_FROM_HERE, functor);
2648 return;
2649 }
2650 RTC_DCHECK(call_.get());
2651 call_->SetBitrateAllocationStrategy(std::move(bitrate_allocation_strategy));
2652}
2653
henrika5f6bf242017-11-01 11:06:56 +01002654void PeerConnection::SetAudioPlayout(bool playout) {
2655 if (!worker_thread()->IsCurrent()) {
2656 worker_thread()->Invoke<void>(
2657 RTC_FROM_HERE,
2658 rtc::Bind(&PeerConnection::SetAudioPlayout, this, playout));
2659 return;
2660 }
2661 auto audio_state =
2662 factory_->channel_manager()->media_engine()->GetAudioState();
2663 audio_state->SetPlayout(playout);
2664}
2665
2666void PeerConnection::SetAudioRecording(bool recording) {
2667 if (!worker_thread()->IsCurrent()) {
2668 worker_thread()->Invoke<void>(
2669 RTC_FROM_HERE,
2670 rtc::Bind(&PeerConnection::SetAudioRecording, this, recording));
2671 return;
2672 }
2673 auto audio_state =
2674 factory_->channel_manager()->media_engine()->GetAudioState();
2675 audio_state->SetRecording(recording);
2676}
2677
Steve Anton8c0f7a72017-10-03 10:03:10 -07002678std::unique_ptr<rtc::SSLCertificate>
2679PeerConnection::GetRemoteAudioSSLCertificate() {
Steve Anton75737c02017-11-06 10:37:17 -08002680 if (!voice_channel()) {
Steve Anton8c0f7a72017-10-03 10:03:10 -07002681 return nullptr;
2682 }
Steve Anton75737c02017-11-06 10:37:17 -08002683 return GetRemoteSSLCertificate(voice_channel()->transport_name());
Steve Anton8c0f7a72017-10-03 10:03:10 -07002684}
2685
ivoc14d5dbe2016-07-04 07:06:55 -07002686bool PeerConnection::StartRtcEventLog(rtc::PlatformFile file,
2687 int64_t max_size_bytes) {
Elad Alon99c3fe52017-10-13 16:29:40 +02002688 // TODO(eladalon): It would be better to not allow negative values into PC.
2689 const size_t max_size = (max_size_bytes < 0)
2690 ? RtcEventLog::kUnlimitedOutput
2691 : rtc::saturated_cast<size_t>(max_size_bytes);
2692 return StartRtcEventLog(
Bjorn Tereliusde939432017-11-20 17:38:14 +01002693 rtc::MakeUnique<RtcEventLogOutputFile>(file, max_size),
2694 webrtc::RtcEventLog::kImmediateOutput);
Elad Alon99c3fe52017-10-13 16:29:40 +02002695}
2696
Bjorn Tereliusde939432017-11-20 17:38:14 +01002697bool PeerConnection::StartRtcEventLog(std::unique_ptr<RtcEventLogOutput> output,
2698 int64_t output_period_ms) {
Karl Wibergd6b48192017-10-16 23:01:06 +02002699 // TODO(eladalon): In C++14, this can be done with a lambda.
2700 struct Functor {
Bjorn Tereliusde939432017-11-20 17:38:14 +01002701 bool operator()() {
2702 return pc->StartRtcEventLog_w(std::move(output), output_period_ms);
2703 }
Karl Wibergd6b48192017-10-16 23:01:06 +02002704 PeerConnection* const pc;
2705 std::unique_ptr<RtcEventLogOutput> output;
Bjorn Tereliusde939432017-11-20 17:38:14 +01002706 const int64_t output_period_ms;
Elad Alon99c3fe52017-10-13 16:29:40 +02002707 };
Bjorn Tereliusde939432017-11-20 17:38:14 +01002708 return worker_thread()->Invoke<bool>(
2709 RTC_FROM_HERE, Functor{this, std::move(output), output_period_ms});
ivoc14d5dbe2016-07-04 07:06:55 -07002710}
2711
2712void PeerConnection::StopRtcEventLog() {
Steve Anton978b8762017-09-29 12:15:02 -07002713 worker_thread()->Invoke<void>(
ivoc14d5dbe2016-07-04 07:06:55 -07002714 RTC_FROM_HERE, rtc::Bind(&PeerConnection::StopRtcEventLog_w, this));
2715}
2716
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002717const SessionDescriptionInterface* PeerConnection::local_description() const {
Steve Anton75737c02017-11-06 10:37:17 -08002718 return pending_local_description_ ? pending_local_description_.get()
2719 : current_local_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002720}
2721
2722const SessionDescriptionInterface* PeerConnection::remote_description() const {
Steve Anton75737c02017-11-06 10:37:17 -08002723 return pending_remote_description_ ? pending_remote_description_.get()
2724 : current_remote_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002725}
2726
deadbeeffe4a8a42016-12-20 17:56:17 -08002727const SessionDescriptionInterface* PeerConnection::current_local_description()
2728 const {
Steve Anton75737c02017-11-06 10:37:17 -08002729 return current_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08002730}
2731
2732const SessionDescriptionInterface* PeerConnection::current_remote_description()
2733 const {
Steve Anton75737c02017-11-06 10:37:17 -08002734 return current_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08002735}
2736
2737const SessionDescriptionInterface* PeerConnection::pending_local_description()
2738 const {
Steve Anton75737c02017-11-06 10:37:17 -08002739 return pending_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08002740}
2741
2742const SessionDescriptionInterface* PeerConnection::pending_remote_description()
2743 const {
Steve Anton75737c02017-11-06 10:37:17 -08002744 return pending_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08002745}
2746
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002747void PeerConnection::Close() {
Peter Boström1a9d6152015-12-08 22:15:17 +01002748 TRACE_EVENT0("webrtc", "PeerConnection::Close");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002749 // Update stats here so that we have the most recent stats for tracks and
2750 // streams before the channels are closed.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00002751 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002752
Steve Anton75737c02017-11-06 10:37:17 -08002753 ChangeSignalingState(PeerConnectionInterface::kClosed);
Steve Anton3fe1b152017-12-12 10:20:08 -08002754
Steve Anton8af21862017-12-15 11:20:13 -08002755 for (auto transceiver : transceivers_) {
2756 transceiver->Stop();
2757 }
2758 DestroyAllChannels();
Steve Anton75737c02017-11-06 10:37:17 -08002759
deadbeef42a42632017-03-10 15:18:00 -08002760 network_thread()->Invoke<void>(
2761 RTC_FROM_HERE,
2762 rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
2763 port_allocator_.get()));
nisseeaabdf62017-05-05 02:23:02 -07002764
Steve Anton978b8762017-09-29 12:15:02 -07002765 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
eladalon248fd4f2017-09-06 05:18:15 -07002766 call_.reset();
2767 // The event log must outlive call (and any other object that uses it).
2768 event_log_.reset();
2769 });
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002770}
2771
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002772void PeerConnection::OnMessage(rtc::Message* msg) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002773 switch (msg->message_id) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002774 case MSG_SET_SESSIONDESCRIPTION_SUCCESS: {
2775 SetSessionDescriptionMsg* param =
2776 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
2777 param->observer->OnSuccess();
2778 delete param;
2779 break;
2780 }
2781 case MSG_SET_SESSIONDESCRIPTION_FAILED: {
2782 SetSessionDescriptionMsg* param =
2783 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
2784 param->observer->OnFailure(param->error);
2785 delete param;
2786 break;
2787 }
deadbeefab9b2d12015-10-14 11:33:11 -07002788 case MSG_CREATE_SESSIONDESCRIPTION_FAILED: {
2789 CreateSessionDescriptionMsg* param =
2790 static_cast<CreateSessionDescriptionMsg*>(msg->pdata);
2791 param->observer->OnFailure(param->error);
2792 delete param;
2793 break;
2794 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002795 case MSG_GETSTATS: {
2796 GetStatsMsg* param = static_cast<GetStatsMsg*>(msg->pdata);
nissee8abe3e2017-01-18 05:00:34 -08002797 StatsReports reports;
2798 stats_->GetStats(param->track, &reports);
2799 param->observer->OnComplete(reports);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002800 delete param;
2801 break;
2802 }
deadbeefbd292462015-12-14 18:15:29 -08002803 case MSG_FREE_DATACHANNELS: {
2804 sctp_data_channels_to_free_.clear();
2805 break;
2806 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002807 default:
nisseeb4ca4e2017-01-12 02:24:27 -08002808 RTC_NOTREACHED() << "Not implemented";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002809 break;
2810 }
2811}
2812
Steve Anton4171afb2017-11-20 10:20:22 -08002813void PeerConnection::CreateAudioReceiver(
2814 MediaStreamInterface* stream,
2815 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01002816 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
2817 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Steve Antond3679212018-01-17 17:41:02 -08002818 auto* audio_receiver = new AudioRtpReceiver(
2819 worker_thread(), remote_sender_info.sender_id, streams);
2820 audio_receiver->SetMediaChannel(voice_media_channel());
2821 audio_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
2822 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
2823 signaling_thread(), audio_receiver);
Steve Anton4171afb2017-11-20 10:20:22 -08002824 GetAudioTransceiver()->internal()->AddReceiver(receiver);
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01002825 observer_->OnAddTrack(receiver, std::move(streams));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002826}
2827
Steve Anton4171afb2017-11-20 10:20:22 -08002828void PeerConnection::CreateVideoReceiver(
2829 MediaStreamInterface* stream,
2830 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01002831 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
2832 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Steve Antond3679212018-01-17 17:41:02 -08002833 auto* video_receiver = new VideoRtpReceiver(
2834 worker_thread(), remote_sender_info.sender_id, streams);
2835 video_receiver->SetMediaChannel(video_media_channel());
2836 video_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
2837 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
2838 signaling_thread(), video_receiver);
Steve Anton4171afb2017-11-20 10:20:22 -08002839 GetVideoTransceiver()->internal()->AddReceiver(receiver);
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01002840 observer_->OnAddTrack(receiver, std::move(streams));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002841}
2842
deadbeef70ab1a12015-09-28 16:53:55 -07002843// TODO(deadbeef): Keep RtpReceivers around even if track goes away in remote
2844// description.
Henrik Boström933d8b02017-10-10 10:05:16 -07002845rtc::scoped_refptr<RtpReceiverInterface> PeerConnection::RemoveAndStopReceiver(
Steve Anton4171afb2017-11-20 10:20:22 -08002846 const RtpSenderInfo& remote_sender_info) {
2847 auto receiver = FindReceiverById(remote_sender_info.sender_id);
2848 if (!receiver) {
2849 RTC_LOG(LS_WARNING) << "RtpReceiver for track with id "
2850 << remote_sender_info.sender_id << " doesn't exist.";
Henrik Boström933d8b02017-10-10 10:05:16 -07002851 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07002852 }
Steve Anton4171afb2017-11-20 10:20:22 -08002853 if (receiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
2854 GetAudioTransceiver()->internal()->RemoveReceiver(receiver);
2855 } else {
2856 GetVideoTransceiver()->internal()->RemoveReceiver(receiver);
2857 }
Henrik Boström933d8b02017-10-10 10:05:16 -07002858 return receiver;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002859}
2860
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002861void PeerConnection::AddAudioTrack(AudioTrackInterface* track,
2862 MediaStreamInterface* stream) {
2863 RTC_DCHECK(!IsClosed());
2864 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08002865 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002866 // We already have a sender for this track, so just change the stream_id
2867 // so that it's correct in the next call to CreateOffer.
Steve Anton4171afb2017-11-20 10:20:22 -08002868 sender->internal()->set_stream_id(stream->label());
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002869 return;
2870 }
2871
2872 // Normal case; we've never seen this track before.
Steve Anton02ee47c2018-01-10 16:26:06 -08002873 auto new_sender =
2874 CreateSender(cricket::MEDIA_TYPE_AUDIO, track, {stream->label()});
2875 static_cast<AudioRtpSender*>(new_sender->internal())
Steve Anton47136dd2018-01-12 10:49:35 -08002876 ->SetMediaChannel(voice_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08002877 GetAudioTransceiver()->internal()->AddSender(new_sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002878 // If the sender has already been configured in SDP, we call SetSsrc,
2879 // which will connect the sender to the underlying transport. This can
2880 // occur if a local session description that contains the ID of the sender
2881 // is set before AddStream is called. It can also occur if the local
2882 // session description is not changed and RemoveStream is called, and
2883 // later AddStream is called again with the same stream.
Steve Anton4171afb2017-11-20 10:20:22 -08002884 const RtpSenderInfo* sender_info =
2885 FindSenderInfo(local_audio_sender_infos_, stream->label(), track->id());
2886 if (sender_info) {
2887 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002888 }
2889}
2890
2891// TODO(deadbeef): Don't destroy RtpSenders here; they should be kept around
2892// indefinitely, when we have unified plan SDP.
2893void PeerConnection::RemoveAudioTrack(AudioTrackInterface* track,
2894 MediaStreamInterface* stream) {
2895 RTC_DCHECK(!IsClosed());
2896 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08002897 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002898 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
2899 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002900 return;
2901 }
Steve Anton4171afb2017-11-20 10:20:22 -08002902 GetAudioTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002903}
2904
2905void PeerConnection::AddVideoTrack(VideoTrackInterface* track,
2906 MediaStreamInterface* stream) {
2907 RTC_DCHECK(!IsClosed());
2908 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08002909 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002910 // We already have a sender for this track, so just change the stream_id
2911 // so that it's correct in the next call to CreateOffer.
Steve Anton4171afb2017-11-20 10:20:22 -08002912 sender->internal()->set_stream_id(stream->label());
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002913 return;
2914 }
2915
2916 // Normal case; we've never seen this track before.
Steve Anton02ee47c2018-01-10 16:26:06 -08002917 auto new_sender =
2918 CreateSender(cricket::MEDIA_TYPE_VIDEO, track, {stream->label()});
2919 static_cast<VideoRtpSender*>(new_sender->internal())
Steve Anton47136dd2018-01-12 10:49:35 -08002920 ->SetMediaChannel(video_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08002921 GetVideoTransceiver()->internal()->AddSender(new_sender);
2922 const RtpSenderInfo* sender_info =
2923 FindSenderInfo(local_video_sender_infos_, stream->label(), track->id());
2924 if (sender_info) {
2925 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002926 }
2927}
2928
2929void PeerConnection::RemoveVideoTrack(VideoTrackInterface* track,
2930 MediaStreamInterface* stream) {
2931 RTC_DCHECK(!IsClosed());
2932 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08002933 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002934 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
2935 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002936 return;
2937 }
Steve Anton4171afb2017-11-20 10:20:22 -08002938 GetVideoTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002939}
2940
Steve Antonba818672017-11-06 10:21:57 -08002941void PeerConnection::SetIceConnectionState(IceConnectionState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07002942 RTC_DCHECK(signaling_thread()->IsCurrent());
Steve Antonba818672017-11-06 10:21:57 -08002943 if (ice_connection_state_ == new_state) {
2944 return;
2945 }
2946
deadbeefcbecd352015-09-23 11:50:27 -07002947 // After transitioning to "closed", ignore any additional states from
Steve Antonba818672017-11-06 10:21:57 -08002948 // TransportController (such as "disconnected").
deadbeefab9b2d12015-10-14 11:33:11 -07002949 if (IsClosed()) {
deadbeefcbecd352015-09-23 11:50:27 -07002950 return;
2951 }
Steve Antonba818672017-11-06 10:21:57 -08002952
Mirko Bonadei675513b2017-11-09 11:09:25 +01002953 RTC_LOG(LS_INFO) << "Changing IceConnectionState " << ice_connection_state_
2954 << " => " << new_state;
Steve Antonba818672017-11-06 10:21:57 -08002955 RTC_DCHECK(ice_connection_state_ !=
2956 PeerConnectionInterface::kIceConnectionClosed);
2957
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002958 ice_connection_state_ = new_state;
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00002959 observer_->OnIceConnectionChange(ice_connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002960}
2961
2962void PeerConnection::OnIceGatheringChange(
2963 PeerConnectionInterface::IceGatheringState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07002964 RTC_DCHECK(signaling_thread()->IsCurrent());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002965 if (IsClosed()) {
2966 return;
2967 }
2968 ice_gathering_state_ = new_state;
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00002969 observer_->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002970}
2971
jbauch81bf7b02017-03-25 08:31:12 -07002972void PeerConnection::OnIceCandidate(
2973 std::unique_ptr<IceCandidateInterface> candidate) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07002974 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07002975 if (IsClosed()) {
2976 return;
2977 }
jbauch81bf7b02017-03-25 08:31:12 -07002978 observer_->OnIceCandidate(candidate.get());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002979}
2980
Honghai Zhang7fb69db2016-03-14 11:59:18 -07002981void PeerConnection::OnIceCandidatesRemoved(
2982 const std::vector<cricket::Candidate>& candidates) {
2983 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07002984 if (IsClosed()) {
2985 return;
2986 }
Honghai Zhang7fb69db2016-03-14 11:59:18 -07002987 observer_->OnIceCandidatesRemoved(candidates);
2988}
2989
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002990void PeerConnection::ChangeSignalingState(
2991 PeerConnectionInterface::SignalingState signaling_state) {
Steve Antonba818672017-11-06 10:21:57 -08002992 RTC_DCHECK(signaling_thread()->IsCurrent());
2993 if (signaling_state_ == signaling_state) {
2994 return;
2995 }
Mirko Bonadei675513b2017-11-09 11:09:25 +01002996 RTC_LOG(LS_INFO) << "Session: " << session_id() << " Old state: "
2997 << GetSignalingStateString(signaling_state_)
2998 << " New state: "
2999 << GetSignalingStateString(signaling_state);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003000 signaling_state_ = signaling_state;
3001 if (signaling_state == kClosed) {
3002 ice_connection_state_ = kIceConnectionClosed;
3003 observer_->OnIceConnectionChange(ice_connection_state_);
3004 if (ice_gathering_state_ != kIceGatheringComplete) {
3005 ice_gathering_state_ = kIceGatheringComplete;
3006 observer_->OnIceGatheringChange(ice_gathering_state_);
3007 }
3008 }
3009 observer_->OnSignalingChange(signaling_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003010}
3011
deadbeefeb459812015-12-15 19:24:43 -08003012void PeerConnection::OnAudioTrackAdded(AudioTrackInterface* track,
3013 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003014 if (IsClosed()) {
3015 return;
3016 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003017 AddAudioTrack(track, stream);
3018 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003019}
3020
deadbeefeb459812015-12-15 19:24:43 -08003021void PeerConnection::OnAudioTrackRemoved(AudioTrackInterface* track,
3022 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003023 if (IsClosed()) {
3024 return;
3025 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003026 RemoveAudioTrack(track, stream);
3027 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003028}
3029
3030void PeerConnection::OnVideoTrackAdded(VideoTrackInterface* track,
3031 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003032 if (IsClosed()) {
3033 return;
3034 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003035 AddVideoTrack(track, stream);
3036 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003037}
3038
3039void PeerConnection::OnVideoTrackRemoved(VideoTrackInterface* track,
3040 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003041 if (IsClosed()) {
3042 return;
3043 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003044 RemoveVideoTrack(track, stream);
3045 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003046}
3047
Henrik Boström31638672017-11-23 17:48:32 +01003048void PeerConnection::PostSetSessionDescriptionSuccess(
3049 SetSessionDescriptionObserver* observer) {
3050 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
3051 signaling_thread()->Post(RTC_FROM_HERE, this,
3052 MSG_SET_SESSIONDESCRIPTION_SUCCESS, msg);
3053}
3054
deadbeefab9b2d12015-10-14 11:33:11 -07003055void PeerConnection::PostSetSessionDescriptionFailure(
3056 SetSessionDescriptionObserver* observer,
3057 const std::string& error) {
3058 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
3059 msg->error = error;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07003060 signaling_thread()->Post(RTC_FROM_HERE, this,
3061 MSG_SET_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07003062}
3063
3064void PeerConnection::PostCreateSessionDescriptionFailure(
3065 CreateSessionDescriptionObserver* observer,
3066 const std::string& error) {
3067 CreateSessionDescriptionMsg* msg = new CreateSessionDescriptionMsg(observer);
3068 msg->error = error;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07003069 signaling_thread()->Post(RTC_FROM_HERE, this,
3070 MSG_CREATE_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07003071}
3072
zhihuang1c378ed2017-08-17 14:10:50 -07003073void PeerConnection::GetOptionsForOffer(
Steve Antondcc3c022017-12-22 16:02:54 -08003074 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
deadbeefab9b2d12015-10-14 11:33:11 -07003075 cricket::MediaSessionOptions* session_options) {
Steve Antondcc3c022017-12-22 16:02:54 -08003076 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
zhihuang1c378ed2017-08-17 14:10:50 -07003077
Steve Antondcc3c022017-12-22 16:02:54 -08003078 if (IsUnifiedPlan()) {
3079 GetOptionsForUnifiedPlanOffer(offer_answer_options, session_options);
3080 } else {
3081 GetOptionsForPlanBOffer(offer_answer_options, session_options);
3082 }
3083
Steve Antonfa2260d2017-12-28 16:38:23 -08003084 // Intentionally unset the data channel type for RTP data channel with the
3085 // second condition. Otherwise the RTP data channels would be successfully
3086 // negotiated by default and the unit tests in WebRtcDataBrowserTest will fail
3087 // when building with chromium. We want to leave RTP data channels broken, so
3088 // people won't try to use them.
3089 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
3090 session_options->data_channel_type = data_channel_type();
3091 }
3092
Steve Antondcc3c022017-12-22 16:02:54 -08003093 // Apply ICE restart flag and renomination flag.
3094 for (auto& options : session_options->media_description_options) {
3095 options.transport_options.ice_restart = offer_answer_options.ice_restart;
3096 options.transport_options.enable_ice_renomination =
3097 configuration_.enable_ice_renomination;
3098 }
3099
3100 session_options->rtcp_cname = rtcp_cname_;
3101 session_options->crypto_options = factory_->options().crypto_options;
3102}
3103
3104void PeerConnection::GetOptionsForPlanBOffer(
3105 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
3106 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07003107 // Figure out transceiver directional preferences.
3108 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
3109 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
3110
3111 // By default, generate sendrecv/recvonly m= sections.
3112 bool recv_audio = true;
3113 bool recv_video = true;
3114
3115 // By default, only offer a new m= section if we have media to send with it.
3116 bool offer_new_audio_description = send_audio;
3117 bool offer_new_video_description = send_video;
3118 bool offer_new_data_description = HasDataChannels();
3119
3120 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-22 16:02:54 -08003121 if (offer_answer_options.offer_to_receive_audio !=
3122 RTCOfferAnswerOptions::kUndefined) {
3123 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003124 offer_new_audio_description =
Steve Antondcc3c022017-12-22 16:02:54 -08003125 offer_new_audio_description ||
3126 (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003127 }
Steve Antondcc3c022017-12-22 16:02:54 -08003128 if (offer_answer_options.offer_to_receive_video !=
3129 RTCOfferAnswerOptions::kUndefined) {
3130 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003131 offer_new_video_description =
Steve Antondcc3c022017-12-22 16:02:54 -08003132 offer_new_video_description ||
3133 (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003134 }
3135
3136 rtc::Optional<size_t> audio_index;
3137 rtc::Optional<size_t> video_index;
3138 rtc::Optional<size_t> data_index;
3139 // If a current description exists, generate m= sections in the same order,
3140 // using the first audio/video/data section that appears and rejecting
3141 // extraneous ones.
Steve Anton75737c02017-11-06 10:37:17 -08003142 if (local_description()) {
zhihuang1c378ed2017-08-17 14:10:50 -07003143 GenerateMediaDescriptionOptions(
Steve Anton75737c02017-11-06 10:37:17 -08003144 local_description(),
Steve Anton1d03a752017-11-27 14:30:09 -08003145 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
3146 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
3147 &audio_index, &video_index, &data_index, session_options);
deadbeefab9b2d12015-10-14 11:33:11 -07003148 }
3149
zhihuang1c378ed2017-08-17 14:10:50 -07003150 // Add audio/video/data m= sections to the end if needed.
3151 if (!audio_index && offer_new_audio_description) {
3152 session_options->media_description_options.push_back(
3153 cricket::MediaDescriptionOptions(
3154 cricket::MEDIA_TYPE_AUDIO, cricket::CN_AUDIO,
Steve Anton1d03a752017-11-27 14:30:09 -08003155 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
3156 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003157 audio_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07003158 }
zhihuang1c378ed2017-08-17 14:10:50 -07003159 if (!video_index && offer_new_video_description) {
3160 session_options->media_description_options.push_back(
3161 cricket::MediaDescriptionOptions(
3162 cricket::MEDIA_TYPE_VIDEO, cricket::CN_VIDEO,
Steve Anton1d03a752017-11-27 14:30:09 -08003163 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
3164 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003165 video_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07003166 }
zhihuang1c378ed2017-08-17 14:10:50 -07003167 if (!data_index && offer_new_data_description) {
3168 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08003169 GetMediaDescriptionOptionsForActiveData(cricket::CN_DATA));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003170 data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07003171 }
3172
3173 cricket::MediaDescriptionOptions* audio_media_description_options =
3174 !audio_index ? nullptr
3175 : &session_options->media_description_options[*audio_index];
3176 cricket::MediaDescriptionOptions* video_media_description_options =
3177 !video_index ? nullptr
3178 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 14:10:50 -07003179
Steve Anton4171afb2017-11-20 10:20:22 -08003180 AddRtpSenderOptions(GetSendersInternal(), audio_media_description_options,
zhihuang1c378ed2017-08-17 14:10:50 -07003181 video_media_description_options);
Steve Antondcc3c022017-12-22 16:02:54 -08003182}
3183
3184// Find a new MID that is not already in |used_mids|, then add it to |used_mids|
3185// and return a reference to it.
3186// Generated MIDs should be no more than 3 bytes long to take up less space in
3187// the RTP packet.
3188static const std::string& AllocateMid(std::set<std::string>* used_mids) {
3189 RTC_DCHECK(used_mids);
3190 // We're boring: just generate MIDs 0, 1, 2, ...
3191 size_t i = 0;
3192 std::set<std::string>::iterator it;
3193 bool inserted;
3194 do {
3195 std::string mid = rtc::ToString(i++);
3196 auto insert_result = used_mids->insert(mid);
3197 it = insert_result.first;
3198 inserted = insert_result.second;
3199 } while (!inserted);
3200 return *it;
3201}
3202
3203static cricket::MediaDescriptionOptions
3204GetMediaDescriptionOptionsForTransceiver(
3205 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3206 transceiver,
3207 const std::string& mid) {
3208 cricket::MediaDescriptionOptions media_description_options(
3209 transceiver->internal()->media_type(), mid, transceiver->direction(),
3210 transceiver->stopped());
3211 cricket::SenderOptions sender_options;
3212 sender_options.track_id = transceiver->sender()->id();
3213 sender_options.stream_ids = transceiver->sender()->stream_ids();
3214 // TODO(bugs.webrtc.org/7600): Set num_sim_layers to the number of encodings
3215 // set in the RTP parameters when the transceiver was added.
3216 sender_options.num_sim_layers = 1;
3217 media_description_options.sender_options.push_back(sender_options);
3218 return media_description_options;
3219}
3220
3221void PeerConnection::GetOptionsForUnifiedPlanOffer(
3222 const RTCOfferAnswerOptions& offer_answer_options,
3223 cricket::MediaSessionOptions* session_options) {
3224 // Rules for generating an offer are dictated by JSEP sections 5.2.1 (Initial
3225 // Offers) and 5.2.2 (Subsequent Offers).
3226 RTC_DCHECK_EQ(session_options->media_description_options.size(), 0);
3227 const ContentInfos& local_contents =
3228 (local_description() ? local_description()->description()->contents()
3229 : ContentInfos());
3230 const ContentInfos& remote_contents =
3231 (remote_description() ? remote_description()->description()->contents()
3232 : ContentInfos());
3233 // The mline indices that can be recycled. New transceivers should reuse these
3234 // slots first.
3235 std::queue<size_t> recycleable_mline_indices;
3236 // Track the MIDs used in previous offer/answer exchanges and the current
3237 // offer so that new, unique MIDs are generated.
3238 std::set<std::string> used_mids = seen_mids_;
3239 // First, go through each media section that exists in either the local or
3240 // remote description and generate a media section in this offer for the
3241 // associated transceiver. If a media section can be recycled, generate a
3242 // default, rejected media section here that can be later overwritten.
3243 for (size_t i = 0;
3244 i < std::max(local_contents.size(), remote_contents.size()); ++i) {
3245 // Either |local_content| or |remote_content| is non-null.
3246 const ContentInfo* local_content =
3247 (i < local_contents.size() ? &local_contents[i] : nullptr);
3248 const ContentInfo* remote_content =
3249 (i < remote_contents.size() ? &remote_contents[i] : nullptr);
3250 bool had_been_rejected = (local_content && local_content->rejected) ||
3251 (remote_content && remote_content->rejected);
3252 const std::string& mid =
3253 (local_content ? local_content->name : remote_content->name);
3254 cricket::MediaType media_type =
3255 (local_content ? local_content->media_description()->type()
3256 : remote_content->media_description()->type());
3257 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
3258 media_type == cricket::MEDIA_TYPE_VIDEO) {
3259 auto transceiver = GetAssociatedTransceiver(mid);
3260 RTC_CHECK(transceiver);
3261 // A media section is considered eligible for recycling if it is marked as
3262 // rejected in either the local or remote description.
3263 if (had_been_rejected) {
3264 session_options->media_description_options.push_back(
3265 cricket::MediaDescriptionOptions(
3266 transceiver->internal()->media_type(), mid,
3267 RtpTransceiverDirection::kInactive,
3268 /*stopped=*/true));
3269 recycleable_mline_indices.push(i);
3270 } else {
3271 session_options->media_description_options.push_back(
3272 GetMediaDescriptionOptionsForTransceiver(transceiver, mid));
3273 // CreateOffer shouldn't really cause any state changes in
3274 // PeerConnection, but we need a way to match new transceivers to new
3275 // media sections in SetLocalDescription and JSEP specifies this is done
3276 // by recording the index of the media section generated for the
3277 // transceiver in the offer.
3278 transceiver->internal()->set_mline_index(i);
3279 }
3280 } else {
3281 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antonfa2260d2017-12-28 16:38:23 -08003282 RTC_CHECK(GetDataMid());
3283 if (had_been_rejected || mid != *GetDataMid()) {
3284 session_options->media_description_options.push_back(
3285 GetMediaDescriptionOptionsForRejectedData(mid));
3286 } else {
3287 session_options->media_description_options.push_back(
3288 GetMediaDescriptionOptionsForActiveData(mid));
3289 }
Steve Antondcc3c022017-12-22 16:02:54 -08003290 }
3291 }
3292 // Next, look for transceivers that are newly added (that is, are not stopped
3293 // and not associated). Reuse media sections marked as recyclable first,
3294 // otherwise append to the end of the offer. New media sections should be
3295 // added in the order they were added to the PeerConnection.
3296 for (auto transceiver : transceivers_) {
3297 if (transceiver->mid() || transceiver->stopped()) {
3298 continue;
3299 }
3300 size_t mline_index;
3301 if (!recycleable_mline_indices.empty()) {
3302 mline_index = recycleable_mline_indices.front();
3303 recycleable_mline_indices.pop();
3304 session_options->media_description_options[mline_index] =
3305 GetMediaDescriptionOptionsForTransceiver(transceiver,
3306 AllocateMid(&used_mids));
3307 } else {
3308 mline_index = session_options->media_description_options.size();
3309 session_options->media_description_options.push_back(
3310 GetMediaDescriptionOptionsForTransceiver(transceiver,
3311 AllocateMid(&used_mids)));
3312 }
3313 // See comment above for why CreateOffer changes the transceiver's state.
3314 transceiver->internal()->set_mline_index(mline_index);
3315 }
Steve Antonfa2260d2017-12-28 16:38:23 -08003316 // Lastly, add a m-section if we have local data channels and an m section
3317 // does not already exist.
3318 if (!GetDataMid() && HasDataChannels()) {
3319 session_options->media_description_options.push_back(
3320 GetMediaDescriptionOptionsForActiveData(AllocateMid(&used_mids)));
3321 }
Steve Antondcc3c022017-12-22 16:02:54 -08003322}
3323
3324void PeerConnection::GetOptionsForAnswer(
3325 const RTCOfferAnswerOptions& offer_answer_options,
3326 cricket::MediaSessionOptions* session_options) {
3327 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
3328
3329 if (IsUnifiedPlan()) {
3330 GetOptionsForUnifiedPlanAnswer(offer_answer_options, session_options);
3331 } else {
3332 GetOptionsForPlanBAnswer(offer_answer_options, session_options);
3333 }
3334
Steve Antonfa2260d2017-12-28 16:38:23 -08003335 // Intentionally unset the data channel type for RTP data channel. Otherwise
3336 // the RTP data channels would be successfully negotiated by default and the
3337 // unit tests in WebRtcDataBrowserTest will fail when building with chromium.
3338 // We want to leave RTP data channels broken, so people won't try to use them.
3339 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
3340 session_options->data_channel_type = data_channel_type();
3341 }
3342
Steve Antondcc3c022017-12-22 16:02:54 -08003343 // Apply ICE renomination flag.
3344 for (auto& options : session_options->media_description_options) {
3345 options.transport_options.enable_ice_renomination =
3346 configuration_.enable_ice_renomination;
3347 }
zhihuang8f65cdf2016-05-06 18:40:30 -07003348
3349 session_options->rtcp_cname = rtcp_cname_;
jbauchcb560652016-08-04 05:20:32 -07003350 session_options->crypto_options = factory_->options().crypto_options;
deadbeefab9b2d12015-10-14 11:33:11 -07003351}
3352
Steve Antondcc3c022017-12-22 16:02:54 -08003353void PeerConnection::GetOptionsForPlanBAnswer(
3354 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07003355 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07003356 // Figure out transceiver directional preferences.
3357 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
3358 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
3359
3360 // By default, generate sendrecv/recvonly m= sections. The direction is also
3361 // restricted by the direction in the offer.
3362 bool recv_audio = true;
3363 bool recv_video = true;
3364
3365 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-22 16:02:54 -08003366 if (offer_answer_options.offer_to_receive_audio !=
3367 RTCOfferAnswerOptions::kUndefined) {
3368 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
deadbeef0ed85b22016-02-23 17:24:52 -08003369 }
Steve Antondcc3c022017-12-22 16:02:54 -08003370 if (offer_answer_options.offer_to_receive_video !=
3371 RTCOfferAnswerOptions::kUndefined) {
3372 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003373 }
3374
3375 rtc::Optional<size_t> audio_index;
3376 rtc::Optional<size_t> video_index;
3377 rtc::Optional<size_t> data_index;
Steve Anton75737c02017-11-06 10:37:17 -08003378 if (remote_description()) {
zhihuang141aacb2017-08-29 13:23:53 -07003379 // The pending remote description should be an offer.
Steve Antona3a92c22017-12-07 10:27:41 -08003380 RTC_DCHECK(remote_description()->GetType() == SdpType::kOffer);
zhihuang141aacb2017-08-29 13:23:53 -07003381 // Generate m= sections that match those in the offer.
3382 // Note that mediasession.cc will handle intersection our preferred
3383 // direction with the offered direction.
3384 GenerateMediaDescriptionOptions(
Steve Anton75737c02017-11-06 10:37:17 -08003385 remote_description(),
Steve Anton1d03a752017-11-27 14:30:09 -08003386 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
3387 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
3388 &audio_index, &video_index, &data_index, session_options);
zhihuang141aacb2017-08-29 13:23:53 -07003389 }
zhihuang1c378ed2017-08-17 14:10:50 -07003390
3391 cricket::MediaDescriptionOptions* audio_media_description_options =
3392 !audio_index ? nullptr
3393 : &session_options->media_description_options[*audio_index];
3394 cricket::MediaDescriptionOptions* video_media_description_options =
3395 !video_index ? nullptr
3396 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 14:10:50 -07003397
Steve Anton4171afb2017-11-20 10:20:22 -08003398 AddRtpSenderOptions(GetSendersInternal(), audio_media_description_options,
zhihuang1c378ed2017-08-17 14:10:50 -07003399 video_media_description_options);
Steve Antondcc3c022017-12-22 16:02:54 -08003400}
zhihuangaf388472016-11-02 16:49:48 -07003401
Steve Antondcc3c022017-12-22 16:02:54 -08003402void PeerConnection::GetOptionsForUnifiedPlanAnswer(
3403 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
3404 cricket::MediaSessionOptions* session_options) {
3405 // Rules for generating an answer are dictated by JSEP sections 5.3.1 (Initial
3406 // Answers) and 5.3.2 (Subsequent Answers).
3407 RTC_DCHECK(remote_description());
3408 RTC_DCHECK(remote_description()->GetType() == SdpType::kOffer);
3409 for (const ContentInfo& content :
3410 remote_description()->description()->contents()) {
3411 cricket::MediaType media_type = content.media_description()->type();
3412 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
3413 media_type == cricket::MEDIA_TYPE_VIDEO) {
3414 auto transceiver = GetAssociatedTransceiver(content.name);
3415 RTC_CHECK(transceiver);
3416 session_options->media_description_options.push_back(
3417 GetMediaDescriptionOptionsForTransceiver(transceiver, content.name));
3418 } else {
3419 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antondbf9d032018-01-19 15:23:40 -08003420 // Reject all data sections if data channels are disabled.
3421 // Reject a data section if it has already been rejected.
3422 // Reject all data sections except for the first one.
3423 if (data_channel_type_ == cricket::DCT_NONE || content.rejected ||
3424 content.name != *GetDataMid()) {
Steve Antonfa2260d2017-12-28 16:38:23 -08003425 session_options->media_description_options.push_back(
3426 GetMediaDescriptionOptionsForRejectedData(content.name));
3427 } else {
3428 session_options->media_description_options.push_back(
3429 GetMediaDescriptionOptionsForActiveData(content.name));
3430 }
Steve Antondcc3c022017-12-22 16:02:54 -08003431 }
3432 }
htaa2a49d92016-03-04 02:51:39 -08003433}
3434
zhihuang1c378ed2017-08-17 14:10:50 -07003435void PeerConnection::GenerateMediaDescriptionOptions(
3436 const SessionDescriptionInterface* session_desc,
Steve Anton1d03a752017-11-27 14:30:09 -08003437 RtpTransceiverDirection audio_direction,
3438 RtpTransceiverDirection video_direction,
zhihuang1c378ed2017-08-17 14:10:50 -07003439 rtc::Optional<size_t>* audio_index,
3440 rtc::Optional<size_t>* video_index,
3441 rtc::Optional<size_t>* data_index,
htaa2a49d92016-03-04 02:51:39 -08003442 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07003443 for (const cricket::ContentInfo& content :
3444 session_desc->description()->contents()) {
3445 if (IsAudioContent(&content)) {
3446 // If we already have an audio m= section, reject this extra one.
3447 if (*audio_index) {
3448 session_options->media_description_options.push_back(
3449 cricket::MediaDescriptionOptions(
3450 cricket::MEDIA_TYPE_AUDIO, content.name,
Steve Anton1d03a752017-11-27 14:30:09 -08003451 RtpTransceiverDirection::kInactive, true));
zhihuang1c378ed2017-08-17 14:10:50 -07003452 } else {
3453 session_options->media_description_options.push_back(
3454 cricket::MediaDescriptionOptions(
3455 cricket::MEDIA_TYPE_AUDIO, content.name, audio_direction,
Steve Anton1d03a752017-11-27 14:30:09 -08003456 audio_direction == RtpTransceiverDirection::kInactive));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003457 *audio_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07003458 }
3459 } else if (IsVideoContent(&content)) {
3460 // If we already have an video m= section, reject this extra one.
3461 if (*video_index) {
3462 session_options->media_description_options.push_back(
3463 cricket::MediaDescriptionOptions(
3464 cricket::MEDIA_TYPE_VIDEO, content.name,
Steve Anton1d03a752017-11-27 14:30:09 -08003465 RtpTransceiverDirection::kInactive, true));
zhihuang1c378ed2017-08-17 14:10:50 -07003466 } else {
3467 session_options->media_description_options.push_back(
3468 cricket::MediaDescriptionOptions(
3469 cricket::MEDIA_TYPE_VIDEO, content.name, video_direction,
Steve Anton1d03a752017-11-27 14:30:09 -08003470 video_direction == RtpTransceiverDirection::kInactive));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003471 *video_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07003472 }
3473 } else {
3474 RTC_DCHECK(IsDataContent(&content));
3475 // If we already have an data m= section, reject this extra one.
3476 if (*data_index) {
3477 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08003478 GetMediaDescriptionOptionsForRejectedData(content.name));
zhihuang1c378ed2017-08-17 14:10:50 -07003479 } else {
3480 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08003481 GetMediaDescriptionOptionsForActiveData(content.name));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003482 *data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07003483 }
3484 }
htaa2a49d92016-03-04 02:51:39 -08003485 }
deadbeefab9b2d12015-10-14 11:33:11 -07003486}
3487
Steve Antonfa2260d2017-12-28 16:38:23 -08003488cricket::MediaDescriptionOptions
3489PeerConnection::GetMediaDescriptionOptionsForActiveData(
3490 const std::string& mid) const {
3491 // Direction for data sections is meaningless, but legacy endpoints might
3492 // expect sendrecv.
3493 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
3494 RtpTransceiverDirection::kSendRecv,
3495 /*stopped=*/false);
3496 AddRtpDataChannelOptions(rtp_data_channels_, &options);
3497 return options;
3498}
3499
3500cricket::MediaDescriptionOptions
3501PeerConnection::GetMediaDescriptionOptionsForRejectedData(
3502 const std::string& mid) const {
3503 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
3504 RtpTransceiverDirection::kInactive,
3505 /*stopped=*/true);
3506 AddRtpDataChannelOptions(rtp_data_channels_, &options);
3507 return options;
3508}
3509
3510rtc::Optional<std::string> PeerConnection::GetDataMid() const {
3511 switch (data_channel_type_) {
3512 case cricket::DCT_RTP:
3513 if (!rtp_data_channel_) {
3514 return rtc::nullopt;
3515 }
3516 return rtp_data_channel_->content_name();
3517 case cricket::DCT_SCTP:
3518 return sctp_content_name_;
3519 default:
3520 return rtc::nullopt;
3521 }
3522}
3523
Steve Anton4171afb2017-11-20 10:20:22 -08003524void PeerConnection::RemoveSenders(cricket::MediaType media_type) {
3525 UpdateLocalSenders(std::vector<cricket::StreamParams>(), media_type);
3526 UpdateRemoteSendersList(std::vector<cricket::StreamParams>(), false,
deadbeefbda7e0b2015-12-08 17:13:40 -08003527 media_type, nullptr);
deadbeeffaac4972015-11-12 15:33:07 -08003528}
3529
Steve Anton4171afb2017-11-20 10:20:22 -08003530void PeerConnection::UpdateRemoteSendersList(
deadbeefab9b2d12015-10-14 11:33:11 -07003531 const cricket::StreamParamsVec& streams,
Steve Anton4171afb2017-11-20 10:20:22 -08003532 bool default_sender_needed,
deadbeefab9b2d12015-10-14 11:33:11 -07003533 cricket::MediaType media_type,
3534 StreamCollection* new_streams) {
Steve Anton4171afb2017-11-20 10:20:22 -08003535 std::vector<RtpSenderInfo>* current_senders =
3536 GetRemoteSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07003537
Steve Anton4171afb2017-11-20 10:20:22 -08003538 // Find removed senders. I.e., senders where the sender id or ssrc don't match
deadbeeffac06552015-11-25 11:26:01 -08003539 // the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08003540 for (auto sender_it = current_senders->begin();
3541 sender_it != current_senders->end();
3542 /* incremented manually */) {
3543 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07003544 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08003545 cricket::GetStreamBySsrc(streams, info.first_ssrc);
3546 bool sender_exists = params && params->id == info.sender_id;
deadbeefbda7e0b2015-12-08 17:13:40 -08003547 // If this is a default track, and we still need it, don't remove it.
Steve Anton4171afb2017-11-20 10:20:22 -08003548 if ((info.stream_label == kDefaultStreamLabel && default_sender_needed) ||
3549 sender_exists) {
3550 ++sender_it;
deadbeefbda7e0b2015-12-08 17:13:40 -08003551 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08003552 OnRemoteSenderRemoved(info, media_type);
3553 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07003554 }
3555 }
3556
Steve Anton4171afb2017-11-20 10:20:22 -08003557 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07003558 for (const cricket::StreamParams& params : streams) {
3559 // The sync_label is the MediaStream label and the |stream.id| is the
Steve Anton4171afb2017-11-20 10:20:22 -08003560 // sender id.
deadbeefab9b2d12015-10-14 11:33:11 -07003561 const std::string& stream_label = params.sync_label;
Steve Anton4171afb2017-11-20 10:20:22 -08003562 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07003563 uint32_t ssrc = params.first_ssrc();
3564
3565 rtc::scoped_refptr<MediaStreamInterface> stream =
3566 remote_streams_->find(stream_label);
3567 if (!stream) {
3568 // This is a new MediaStream. Create a new remote MediaStream.
perkjd61bf802016-03-24 03:16:19 -07003569 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
3570 MediaStream::Create(stream_label));
deadbeefab9b2d12015-10-14 11:33:11 -07003571 remote_streams_->AddStream(stream);
3572 new_streams->AddStream(stream);
3573 }
3574
Steve Anton4171afb2017-11-20 10:20:22 -08003575 const RtpSenderInfo* sender_info =
3576 FindSenderInfo(*current_senders, stream_label, sender_id);
3577 if (!sender_info) {
3578 current_senders->push_back(RtpSenderInfo(stream_label, sender_id, ssrc));
3579 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07003580 }
3581 }
deadbeefbda7e0b2015-12-08 17:13:40 -08003582
Steve Anton4171afb2017-11-20 10:20:22 -08003583 // Add default sender if necessary.
3584 if (default_sender_needed) {
deadbeefbda7e0b2015-12-08 17:13:40 -08003585 rtc::scoped_refptr<MediaStreamInterface> default_stream =
3586 remote_streams_->find(kDefaultStreamLabel);
3587 if (!default_stream) {
3588 // Create the new default MediaStream.
perkjd61bf802016-03-24 03:16:19 -07003589 default_stream = MediaStreamProxy::Create(
3590 rtc::Thread::Current(), MediaStream::Create(kDefaultStreamLabel));
deadbeefbda7e0b2015-12-08 17:13:40 -08003591 remote_streams_->AddStream(default_stream);
3592 new_streams->AddStream(default_stream);
3593 }
Steve Anton4171afb2017-11-20 10:20:22 -08003594 std::string default_sender_id = (media_type == cricket::MEDIA_TYPE_AUDIO)
3595 ? kDefaultAudioSenderId
3596 : kDefaultVideoSenderId;
3597 const RtpSenderInfo* default_sender_info = FindSenderInfo(
3598 *current_senders, kDefaultStreamLabel, default_sender_id);
3599 if (!default_sender_info) {
3600 current_senders->push_back(
3601 RtpSenderInfo(kDefaultStreamLabel, default_sender_id, 0));
3602 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefbda7e0b2015-12-08 17:13:40 -08003603 }
3604 }
deadbeefab9b2d12015-10-14 11:33:11 -07003605}
3606
Steve Anton4171afb2017-11-20 10:20:22 -08003607void PeerConnection::OnRemoteSenderAdded(const RtpSenderInfo& sender_info,
3608 cricket::MediaType media_type) {
3609 MediaStreamInterface* stream =
3610 remote_streams_->find(sender_info.stream_label);
deadbeefab9b2d12015-10-14 11:33:11 -07003611
3612 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 10:20:22 -08003613 CreateAudioReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07003614 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 10:20:22 -08003615 CreateVideoReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07003616 } else {
nisseeb4ca4e2017-01-12 02:24:27 -08003617 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07003618 }
3619}
3620
Steve Anton4171afb2017-11-20 10:20:22 -08003621void PeerConnection::OnRemoteSenderRemoved(const RtpSenderInfo& sender_info,
3622 cricket::MediaType media_type) {
3623 MediaStreamInterface* stream =
3624 remote_streams_->find(sender_info.stream_label);
deadbeefab9b2d12015-10-14 11:33:11 -07003625
Henrik Boström933d8b02017-10-10 10:05:16 -07003626 rtc::scoped_refptr<RtpReceiverInterface> receiver;
deadbeefab9b2d12015-10-14 11:33:11 -07003627 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
perkjd61bf802016-03-24 03:16:19 -07003628 // When the MediaEngine audio channel is destroyed, the RemoteAudioSource
3629 // will be notified which will end the AudioRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08003630 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07003631 rtc::scoped_refptr<AudioTrackInterface> audio_track =
Steve Anton4171afb2017-11-20 10:20:22 -08003632 stream->FindAudioTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07003633 if (audio_track) {
deadbeefab9b2d12015-10-14 11:33:11 -07003634 stream->RemoveTrack(audio_track);
deadbeefab9b2d12015-10-14 11:33:11 -07003635 }
3636 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
perkjd61bf802016-03-24 03:16:19 -07003637 // Stopping or destroying a VideoRtpReceiver will end the
3638 // VideoRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08003639 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07003640 rtc::scoped_refptr<VideoTrackInterface> video_track =
Steve Anton4171afb2017-11-20 10:20:22 -08003641 stream->FindVideoTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07003642 if (video_track) {
perkjd61bf802016-03-24 03:16:19 -07003643 // There's no guarantee the track is still available, e.g. the track may
3644 // have been removed from the stream by an application.
deadbeefab9b2d12015-10-14 11:33:11 -07003645 stream->RemoveTrack(video_track);
deadbeefab9b2d12015-10-14 11:33:11 -07003646 }
3647 } else {
nisseede5da42017-01-12 05:15:36 -08003648 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07003649 }
Henrik Boström933d8b02017-10-10 10:05:16 -07003650 if (receiver) {
3651 observer_->OnRemoveTrack(receiver);
3652 }
deadbeefab9b2d12015-10-14 11:33:11 -07003653}
3654
3655void PeerConnection::UpdateEndedRemoteMediaStreams() {
3656 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams_to_remove;
3657 for (size_t i = 0; i < remote_streams_->count(); ++i) {
3658 MediaStreamInterface* stream = remote_streams_->at(i);
3659 if (stream->GetAudioTracks().empty() && stream->GetVideoTracks().empty()) {
3660 streams_to_remove.push_back(stream);
3661 }
3662 }
3663
Taylor Brandstetter98cde262016-05-31 13:02:21 -07003664 for (auto& stream : streams_to_remove) {
deadbeefab9b2d12015-10-14 11:33:11 -07003665 remote_streams_->RemoveStream(stream);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07003666 observer_->OnRemoveStream(std::move(stream));
deadbeefab9b2d12015-10-14 11:33:11 -07003667 }
3668}
3669
Steve Anton4171afb2017-11-20 10:20:22 -08003670void PeerConnection::UpdateLocalSenders(
deadbeefab9b2d12015-10-14 11:33:11 -07003671 const std::vector<cricket::StreamParams>& streams,
3672 cricket::MediaType media_type) {
Steve Anton4171afb2017-11-20 10:20:22 -08003673 std::vector<RtpSenderInfo>* current_senders = GetLocalSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07003674
3675 // Find removed tracks. I.e., tracks where the track id, stream label or ssrc
3676 // don't match the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08003677 for (auto sender_it = current_senders->begin();
3678 sender_it != current_senders->end();
3679 /* incremented manually */) {
3680 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07003681 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08003682 cricket::GetStreamBySsrc(streams, info.first_ssrc);
3683 if (!params || params->id != info.sender_id ||
deadbeefab9b2d12015-10-14 11:33:11 -07003684 params->sync_label != info.stream_label) {
Steve Anton4171afb2017-11-20 10:20:22 -08003685 OnLocalSenderRemoved(info, media_type);
3686 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07003687 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08003688 ++sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07003689 }
3690 }
3691
Steve Anton4171afb2017-11-20 10:20:22 -08003692 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07003693 for (const cricket::StreamParams& params : streams) {
3694 // The sync_label is the MediaStream label and the |stream.id| is the
Steve Anton4171afb2017-11-20 10:20:22 -08003695 // sender id.
deadbeefab9b2d12015-10-14 11:33:11 -07003696 const std::string& stream_label = params.sync_label;
Steve Anton4171afb2017-11-20 10:20:22 -08003697 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07003698 uint32_t ssrc = params.first_ssrc();
Steve Anton4171afb2017-11-20 10:20:22 -08003699 const RtpSenderInfo* sender_info =
3700 FindSenderInfo(*current_senders, stream_label, sender_id);
3701 if (!sender_info) {
3702 current_senders->push_back(RtpSenderInfo(stream_label, sender_id, ssrc));
3703 OnLocalSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07003704 }
3705 }
3706}
3707
Steve Anton4171afb2017-11-20 10:20:22 -08003708void PeerConnection::OnLocalSenderAdded(const RtpSenderInfo& sender_info,
3709 cricket::MediaType media_type) {
3710 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08003711 if (!sender) {
Steve Anton4171afb2017-11-20 10:20:22 -08003712 RTC_LOG(LS_WARNING) << "An unknown RtpSender with id "
3713 << sender_info.sender_id
Mirko Bonadei675513b2017-11-09 11:09:25 +01003714 << " has been configured in the local description.";
deadbeefab9b2d12015-10-14 11:33:11 -07003715 return;
3716 }
3717
deadbeeffac06552015-11-25 11:26:01 -08003718 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003719 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
3720 << " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08003721 return;
deadbeefab9b2d12015-10-14 11:33:11 -07003722 }
deadbeeffac06552015-11-25 11:26:01 -08003723
Steve Anton4171afb2017-11-20 10:20:22 -08003724 sender->internal()->set_stream_id(sender_info.stream_label);
3725 sender->internal()->SetSsrc(sender_info.first_ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07003726}
3727
Steve Anton4171afb2017-11-20 10:20:22 -08003728void PeerConnection::OnLocalSenderRemoved(const RtpSenderInfo& sender_info,
3729 cricket::MediaType media_type) {
3730 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08003731 if (!sender) {
3732 // This is the normal case. I.e., RemoveStream has been called and the
deadbeefab9b2d12015-10-14 11:33:11 -07003733 // SessionDescriptions has been renegotiated.
3734 return;
3735 }
deadbeeffac06552015-11-25 11:26:01 -08003736
3737 // A sender has been removed from the SessionDescription but it's still
3738 // associated with the PeerConnection. This only occurs if the SDP doesn't
3739 // match with the calls to CreateSender, AddStream and RemoveStream.
3740 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003741 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
3742 << " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08003743 return;
deadbeefab9b2d12015-10-14 11:33:11 -07003744 }
deadbeeffac06552015-11-25 11:26:01 -08003745
Steve Anton4171afb2017-11-20 10:20:22 -08003746 sender->internal()->SetSsrc(0);
deadbeefab9b2d12015-10-14 11:33:11 -07003747}
3748
3749void PeerConnection::UpdateLocalRtpDataChannels(
3750 const cricket::StreamParamsVec& streams) {
3751 std::vector<std::string> existing_channels;
3752
3753 // Find new and active data channels.
3754 for (const cricket::StreamParams& params : streams) {
3755 // |it->sync_label| is actually the data channel label. The reason is that
3756 // we use the same naming of data channels as we do for
3757 // MediaStreams and Tracks.
3758 // For MediaStreams, the sync_label is the MediaStream label and the
3759 // track label is the same as |streamid|.
3760 const std::string& channel_label = params.sync_label;
3761 auto data_channel_it = rtp_data_channels_.find(channel_label);
nisse7ce109a2017-01-31 00:57:56 -08003762 if (data_channel_it == rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003763 RTC_LOG(LS_ERROR) << "channel label not found";
deadbeefab9b2d12015-10-14 11:33:11 -07003764 continue;
3765 }
3766 // Set the SSRC the data channel should use for sending.
3767 data_channel_it->second->SetSendSsrc(params.first_ssrc());
3768 existing_channels.push_back(data_channel_it->first);
3769 }
3770
3771 UpdateClosingRtpDataChannels(existing_channels, true);
3772}
3773
3774void PeerConnection::UpdateRemoteRtpDataChannels(
3775 const cricket::StreamParamsVec& streams) {
3776 std::vector<std::string> existing_channels;
3777
3778 // Find new and active data channels.
3779 for (const cricket::StreamParams& params : streams) {
3780 // The data channel label is either the mslabel or the SSRC if the mslabel
3781 // does not exist. Ex a=ssrc:444330170 mslabel:test1.
3782 std::string label = params.sync_label.empty()
3783 ? rtc::ToString(params.first_ssrc())
3784 : params.sync_label;
3785 auto data_channel_it = rtp_data_channels_.find(label);
3786 if (data_channel_it == rtp_data_channels_.end()) {
3787 // This is a new data channel.
3788 CreateRemoteRtpDataChannel(label, params.first_ssrc());
3789 } else {
3790 data_channel_it->second->SetReceiveSsrc(params.first_ssrc());
3791 }
3792 existing_channels.push_back(label);
3793 }
3794
3795 UpdateClosingRtpDataChannels(existing_channels, false);
3796}
3797
3798void PeerConnection::UpdateClosingRtpDataChannels(
3799 const std::vector<std::string>& active_channels,
3800 bool is_local_update) {
3801 auto it = rtp_data_channels_.begin();
3802 while (it != rtp_data_channels_.end()) {
3803 DataChannel* data_channel = it->second;
3804 if (std::find(active_channels.begin(), active_channels.end(),
3805 data_channel->label()) != active_channels.end()) {
3806 ++it;
3807 continue;
3808 }
3809
3810 if (is_local_update) {
3811 data_channel->SetSendSsrc(0);
3812 } else {
3813 data_channel->RemotePeerRequestClose();
3814 }
3815
3816 if (data_channel->state() == DataChannel::kClosed) {
3817 rtp_data_channels_.erase(it);
3818 it = rtp_data_channels_.begin();
3819 } else {
3820 ++it;
3821 }
3822 }
3823}
3824
3825void PeerConnection::CreateRemoteRtpDataChannel(const std::string& label,
3826 uint32_t remote_ssrc) {
3827 rtc::scoped_refptr<DataChannel> channel(
3828 InternalCreateDataChannel(label, nullptr));
3829 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003830 RTC_LOG(LS_WARNING) << "Remote peer requested a DataChannel but"
3831 << "CreateDataChannel failed.";
deadbeefab9b2d12015-10-14 11:33:11 -07003832 return;
3833 }
3834 channel->SetReceiveSsrc(remote_ssrc);
deadbeefa601f5c2016-06-06 14:27:39 -07003835 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
3836 DataChannelProxy::Create(signaling_thread(), channel);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07003837 observer_->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07003838}
3839
3840rtc::scoped_refptr<DataChannel> PeerConnection::InternalCreateDataChannel(
3841 const std::string& label,
3842 const InternalDataChannelInit* config) {
3843 if (IsClosed()) {
3844 return nullptr;
3845 }
Steve Anton75737c02017-11-06 10:37:17 -08003846 if (data_channel_type() == cricket::DCT_NONE) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003847 RTC_LOG(LS_ERROR)
deadbeefab9b2d12015-10-14 11:33:11 -07003848 << "InternalCreateDataChannel: Data is not supported in this call.";
3849 return nullptr;
3850 }
3851 InternalDataChannelInit new_config =
3852 config ? (*config) : InternalDataChannelInit();
Steve Anton75737c02017-11-06 10:37:17 -08003853 if (data_channel_type() == cricket::DCT_SCTP) {
deadbeefab9b2d12015-10-14 11:33:11 -07003854 if (new_config.id < 0) {
3855 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08003856 if ((GetSctpSslRole(&role)) &&
deadbeefab9b2d12015-10-14 11:33:11 -07003857 !sid_allocator_.AllocateSid(role, &new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003858 RTC_LOG(LS_ERROR)
3859 << "No id can be allocated for the SCTP data channel.";
deadbeefab9b2d12015-10-14 11:33:11 -07003860 return nullptr;
3861 }
3862 } else if (!sid_allocator_.ReserveSid(new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003863 RTC_LOG(LS_ERROR) << "Failed to create a SCTP data channel "
3864 << "because the id is already in use or out of range.";
deadbeefab9b2d12015-10-14 11:33:11 -07003865 return nullptr;
3866 }
3867 }
3868
Steve Anton75737c02017-11-06 10:37:17 -08003869 rtc::scoped_refptr<DataChannel> channel(
3870 DataChannel::Create(this, data_channel_type(), label, new_config));
deadbeefab9b2d12015-10-14 11:33:11 -07003871 if (!channel) {
3872 sid_allocator_.ReleaseSid(new_config.id);
3873 return nullptr;
3874 }
3875
3876 if (channel->data_channel_type() == cricket::DCT_RTP) {
3877 if (rtp_data_channels_.find(channel->label()) != rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003878 RTC_LOG(LS_ERROR) << "DataChannel with label " << channel->label()
3879 << " already exists.";
deadbeefab9b2d12015-10-14 11:33:11 -07003880 return nullptr;
3881 }
3882 rtp_data_channels_[channel->label()] = channel;
3883 } else {
3884 RTC_DCHECK(channel->data_channel_type() == cricket::DCT_SCTP);
3885 sctp_data_channels_.push_back(channel);
3886 channel->SignalClosed.connect(this,
3887 &PeerConnection::OnSctpDataChannelClosed);
3888 }
3889
Steve Anton2d8609c2018-01-23 16:38:46 -08003890 SignalDataChannelCreated_(channel.get());
deadbeefab9b2d12015-10-14 11:33:11 -07003891 return channel;
3892}
3893
3894bool PeerConnection::HasDataChannels() const {
3895 return !rtp_data_channels_.empty() || !sctp_data_channels_.empty();
3896}
3897
3898void PeerConnection::AllocateSctpSids(rtc::SSLRole role) {
3899 for (const auto& channel : sctp_data_channels_) {
3900 if (channel->id() < 0) {
3901 int sid;
3902 if (!sid_allocator_.AllocateSid(role, &sid)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003903 RTC_LOG(LS_ERROR) << "Failed to allocate SCTP sid.";
deadbeefab9b2d12015-10-14 11:33:11 -07003904 continue;
3905 }
3906 channel->SetSctpSid(sid);
3907 }
3908 }
3909}
3910
3911void PeerConnection::OnSctpDataChannelClosed(DataChannel* channel) {
deadbeefbd292462015-12-14 18:15:29 -08003912 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeefab9b2d12015-10-14 11:33:11 -07003913 for (auto it = sctp_data_channels_.begin(); it != sctp_data_channels_.end();
3914 ++it) {
3915 if (it->get() == channel) {
3916 if (channel->id() >= 0) {
3917 sid_allocator_.ReleaseSid(channel->id());
3918 }
deadbeefbd292462015-12-14 18:15:29 -08003919 // Since this method is triggered by a signal from the DataChannel,
3920 // we can't free it directly here; we need to free it asynchronously.
3921 sctp_data_channels_to_free_.push_back(*it);
deadbeefab9b2d12015-10-14 11:33:11 -07003922 sctp_data_channels_.erase(it);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07003923 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_FREE_DATACHANNELS,
3924 nullptr);
deadbeefab9b2d12015-10-14 11:33:11 -07003925 return;
3926 }
3927 }
3928}
3929
deadbeefab9b2d12015-10-14 11:33:11 -07003930void PeerConnection::OnDataChannelDestroyed() {
3931 // Use a temporary copy of the RTP/SCTP DataChannel list because the
3932 // DataChannel may callback to us and try to modify the list.
3933 std::map<std::string, rtc::scoped_refptr<DataChannel>> temp_rtp_dcs;
3934 temp_rtp_dcs.swap(rtp_data_channels_);
3935 for (const auto& kv : temp_rtp_dcs) {
3936 kv.second->OnTransportChannelDestroyed();
3937 }
3938
3939 std::vector<rtc::scoped_refptr<DataChannel>> temp_sctp_dcs;
3940 temp_sctp_dcs.swap(sctp_data_channels_);
3941 for (const auto& channel : temp_sctp_dcs) {
3942 channel->OnTransportChannelDestroyed();
3943 }
3944}
3945
3946void PeerConnection::OnDataChannelOpenMessage(
3947 const std::string& label,
3948 const InternalDataChannelInit& config) {
3949 rtc::scoped_refptr<DataChannel> channel(
3950 InternalCreateDataChannel(label, &config));
3951 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003952 RTC_LOG(LS_ERROR) << "Failed to create DataChannel from the OPEN message.";
deadbeefab9b2d12015-10-14 11:33:11 -07003953 return;
3954 }
3955
deadbeefa601f5c2016-06-06 14:27:39 -07003956 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
3957 DataChannelProxy::Create(signaling_thread(), channel);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07003958 observer_->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07003959}
3960
Steve Anton4171afb2017-11-20 10:20:22 -08003961rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3962PeerConnection::GetAudioTransceiver() const {
3963 // This method only works with Plan B SDP, where there is a single
3964 // audio/video transceiver.
3965 RTC_DCHECK(!IsUnifiedPlan());
3966 for (auto transceiver : transceivers_) {
3967 if (transceiver->internal()->media_type() == cricket::MEDIA_TYPE_AUDIO) {
3968 return transceiver;
3969 }
3970 }
3971 RTC_NOTREACHED();
3972 return nullptr;
3973}
3974
3975rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3976PeerConnection::GetVideoTransceiver() const {
3977 // This method only works with Plan B SDP, where there is a single
3978 // audio/video transceiver.
3979 RTC_DCHECK(!IsUnifiedPlan());
3980 for (auto transceiver : transceivers_) {
3981 if (transceiver->internal()->media_type() == cricket::MEDIA_TYPE_VIDEO) {
3982 return transceiver;
3983 }
3984 }
3985 RTC_NOTREACHED();
3986 return nullptr;
3987}
3988
3989// TODO(bugs.webrtc.org/7600): Remove this when multiple transceivers with
3990// individual transceiver directions are supported.
zhihuang1c378ed2017-08-17 14:10:50 -07003991bool PeerConnection::HasRtpSender(cricket::MediaType type) const {
Steve Anton4171afb2017-11-20 10:20:22 -08003992 switch (type) {
3993 case cricket::MEDIA_TYPE_AUDIO:
3994 return !GetAudioTransceiver()->internal()->senders().empty();
3995 case cricket::MEDIA_TYPE_VIDEO:
3996 return !GetVideoTransceiver()->internal()->senders().empty();
3997 case cricket::MEDIA_TYPE_DATA:
3998 return false;
3999 }
4000 RTC_NOTREACHED();
4001 return false;
zhihuang1c378ed2017-08-17 14:10:50 -07004002}
4003
Steve Anton4171afb2017-11-20 10:20:22 -08004004rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
4005PeerConnection::FindSenderForTrack(MediaStreamTrackInterface* track) const {
4006 for (auto transceiver : transceivers_) {
4007 for (auto sender : transceiver->internal()->senders()) {
4008 if (sender->track() == track) {
4009 return sender;
4010 }
4011 }
4012 }
4013 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08004014}
4015
Steve Anton4171afb2017-11-20 10:20:22 -08004016rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
4017PeerConnection::FindSenderById(const std::string& sender_id) const {
4018 for (auto transceiver : transceivers_) {
4019 for (auto sender : transceiver->internal()->senders()) {
4020 if (sender->id() == sender_id) {
4021 return sender;
4022 }
4023 }
4024 }
4025 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07004026}
4027
Steve Anton4171afb2017-11-20 10:20:22 -08004028rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
4029PeerConnection::FindReceiverById(const std::string& receiver_id) const {
4030 for (auto transceiver : transceivers_) {
4031 for (auto receiver : transceiver->internal()->receivers()) {
4032 if (receiver->id() == receiver_id) {
4033 return receiver;
4034 }
4035 }
4036 }
4037 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07004038}
4039
Steve Anton4171afb2017-11-20 10:20:22 -08004040std::vector<PeerConnection::RtpSenderInfo>*
4041PeerConnection::GetRemoteSenderInfos(cricket::MediaType media_type) {
4042 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
4043 media_type == cricket::MEDIA_TYPE_VIDEO);
4044 return (media_type == cricket::MEDIA_TYPE_AUDIO)
4045 ? &remote_audio_sender_infos_
4046 : &remote_video_sender_infos_;
4047}
4048
4049std::vector<PeerConnection::RtpSenderInfo>* PeerConnection::GetLocalSenderInfos(
deadbeefab9b2d12015-10-14 11:33:11 -07004050 cricket::MediaType media_type) {
4051 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
4052 media_type == cricket::MEDIA_TYPE_VIDEO);
Steve Anton4171afb2017-11-20 10:20:22 -08004053 return (media_type == cricket::MEDIA_TYPE_AUDIO) ? &local_audio_sender_infos_
4054 : &local_video_sender_infos_;
deadbeefab9b2d12015-10-14 11:33:11 -07004055}
4056
Steve Anton4171afb2017-11-20 10:20:22 -08004057const PeerConnection::RtpSenderInfo* PeerConnection::FindSenderInfo(
4058 const std::vector<PeerConnection::RtpSenderInfo>& infos,
deadbeefab9b2d12015-10-14 11:33:11 -07004059 const std::string& stream_label,
Steve Anton4171afb2017-11-20 10:20:22 -08004060 const std::string sender_id) const {
4061 for (const RtpSenderInfo& sender_info : infos) {
4062 if (sender_info.stream_label == stream_label &&
4063 sender_info.sender_id == sender_id) {
4064 return &sender_info;
deadbeefab9b2d12015-10-14 11:33:11 -07004065 }
4066 }
4067 return nullptr;
4068}
4069
4070DataChannel* PeerConnection::FindDataChannelBySid(int sid) const {
4071 for (const auto& channel : sctp_data_channels_) {
4072 if (channel->id() == sid) {
4073 return channel;
4074 }
4075 }
4076 return nullptr;
4077}
4078
deadbeef91dd5672016-05-18 16:55:30 -07004079bool PeerConnection::InitializePortAllocator_n(
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004080 const RTCConfiguration& configuration) {
4081 cricket::ServerAddresses stun_servers;
4082 std::vector<cricket::RelayServerConfig> turn_servers;
deadbeef293e9262017-01-11 12:28:30 -08004083 if (ParseIceServers(configuration.servers, &stun_servers, &turn_servers) !=
4084 RTCErrorType::NONE) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004085 return false;
4086 }
4087
Taylor Brandstetterf8e65772016-06-27 17:20:15 -07004088 port_allocator_->Initialize();
4089
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004090 // To handle both internal and externally created port allocator, we will
4091 // enable BUNDLE here.
4092 int portallocator_flags = port_allocator_->flags();
4093 portallocator_flags |= cricket::PORTALLOCATOR_ENABLE_SHARED_SOCKET |
zhihuangb09b3f92017-03-07 14:40:51 -08004094 cricket::PORTALLOCATOR_ENABLE_IPV6 |
4095 cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI;
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004096 // If the disable-IPv6 flag was specified, we'll not override it
4097 // by experiment.
4098 if (configuration.disable_ipv6) {
4099 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
sprangc1b57a12017-02-28 08:50:47 -08004100 } else if (webrtc::field_trial::FindFullName("WebRTC-IPv6Default")
4101 .find("Disabled") == 0) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004102 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
4103 }
4104
zhihuangb09b3f92017-03-07 14:40:51 -08004105 if (configuration.disable_ipv6_on_wifi) {
4106 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI);
Mirko Bonadei675513b2017-11-09 11:09:25 +01004107 RTC_LOG(LS_INFO) << "IPv6 candidates on Wi-Fi are disabled.";
zhihuangb09b3f92017-03-07 14:40:51 -08004108 }
4109
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004110 if (configuration.tcp_candidate_policy == kTcpCandidatePolicyDisabled) {
4111 portallocator_flags |= cricket::PORTALLOCATOR_DISABLE_TCP;
Mirko Bonadei675513b2017-11-09 11:09:25 +01004112 RTC_LOG(LS_INFO) << "TCP candidates are disabled.";
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004113 }
4114
honghaiz60347052016-05-31 18:29:12 -07004115 if (configuration.candidate_network_policy ==
4116 kCandidateNetworkPolicyLowCost) {
4117 portallocator_flags |= cricket::PORTALLOCATOR_DISABLE_COSTLY_NETWORKS;
Mirko Bonadei675513b2017-11-09 11:09:25 +01004118 RTC_LOG(LS_INFO) << "Do not gather candidates on high-cost networks";
honghaiz60347052016-05-31 18:29:12 -07004119 }
4120
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004121 port_allocator_->set_flags(portallocator_flags);
4122 // No step delay is used while allocating ports.
4123 port_allocator_->set_step_delay(cricket::kMinimumStepDelay);
4124 port_allocator_->set_candidate_filter(
4125 ConvertIceTransportTypeToCandidateFilter(configuration.type));
deadbeefd21eab32017-07-26 16:50:11 -07004126 port_allocator_->set_max_ipv6_networks(configuration.max_ipv6_networks);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004127
4128 // Call this last since it may create pooled allocator sessions using the
4129 // properties set above.
4130 port_allocator_->SetConfiguration(stun_servers, turn_servers,
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -07004131 configuration.ice_candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02004132 configuration.prune_turn_ports,
4133 configuration.turn_customizer);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004134 return true;
4135}
4136
deadbeef91dd5672016-05-18 16:55:30 -07004137bool PeerConnection::ReconfigurePortAllocator_n(
deadbeef293e9262017-01-11 12:28:30 -08004138 const cricket::ServerAddresses& stun_servers,
4139 const std::vector<cricket::RelayServerConfig>& turn_servers,
4140 IceTransportsType type,
4141 int candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02004142 bool prune_turn_ports,
4143 webrtc::TurnCustomizer* turn_customizer) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004144 port_allocator_->set_candidate_filter(
deadbeef293e9262017-01-11 12:28:30 -08004145 ConvertIceTransportTypeToCandidateFilter(type));
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004146 // Call this last since it may create pooled allocator sessions using the
4147 // candidate filter set above.
deadbeef6de92f92016-12-12 18:49:32 -08004148 return port_allocator_->SetConfiguration(
Jonas Orelandbdcee282017-10-10 14:01:40 +02004149 stun_servers, turn_servers, candidate_pool_size, prune_turn_ports,
4150 turn_customizer);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004151}
4152
Steve Antonba818672017-11-06 10:21:57 -08004153cricket::ChannelManager* PeerConnection::channel_manager() const {
4154 return factory_->channel_manager();
4155}
4156
4157MetricsObserverInterface* PeerConnection::metrics_observer() const {
4158 return uma_observer_;
4159}
4160
Elad Alon99c3fe52017-10-13 16:29:40 +02004161bool PeerConnection::StartRtcEventLog_w(
Bjorn Tereliusde939432017-11-20 17:38:14 +01004162 std::unique_ptr<RtcEventLogOutput> output,
4163 int64_t output_period_ms) {
zhihuang77985012017-02-07 15:45:16 -08004164 if (!event_log_) {
4165 return false;
4166 }
Bjorn Tereliusde939432017-11-20 17:38:14 +01004167 return event_log_->StartLogging(std::move(output), output_period_ms);
ivoc14d5dbe2016-07-04 07:06:55 -07004168}
4169
4170void PeerConnection::StopRtcEventLog_w() {
zhihuang77985012017-02-07 15:45:16 -08004171 if (event_log_) {
4172 event_log_->StopLogging();
4173 }
ivoc14d5dbe2016-07-04 07:06:55 -07004174}
nisseeaabdf62017-05-05 02:23:02 -07004175
Steve Anton75737c02017-11-06 10:37:17 -08004176cricket::BaseChannel* PeerConnection::GetChannel(
4177 const std::string& content_name) {
Steve Antondcc3c022017-12-22 16:02:54 -08004178 for (auto transceiver : transceivers_) {
4179 cricket::BaseChannel* channel = transceiver->internal()->channel();
4180 if (channel && channel->content_name() == content_name) {
4181 return channel;
4182 }
Steve Anton75737c02017-11-06 10:37:17 -08004183 }
4184 if (rtp_data_channel() &&
4185 rtp_data_channel()->content_name() == content_name) {
4186 return rtp_data_channel();
4187 }
4188 return nullptr;
4189}
4190
4191bool PeerConnection::GetSctpSslRole(rtc::SSLRole* role) {
4192 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004193 RTC_LOG(LS_INFO)
4194 << "Local and Remote descriptions must be applied to get the "
4195 << "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08004196 return false;
4197 }
4198 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004199 RTC_LOG(LS_INFO) << "Non-rejected SCTP m= section is needed to get the "
4200 << "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08004201 return false;
4202 }
4203
4204 return transport_controller_->GetSslRole(*sctp_transport_name_, role);
4205}
4206
4207bool PeerConnection::GetSslRole(const std::string& content_name,
4208 rtc::SSLRole* role) {
4209 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004210 RTC_LOG(LS_INFO)
4211 << "Local and Remote descriptions must be applied to get the "
4212 << "SSL Role of the session.";
Steve Anton75737c02017-11-06 10:37:17 -08004213 return false;
4214 }
4215
4216 return transport_controller_->GetSslRole(GetTransportName(content_name),
4217 role);
4218}
4219
Steve Anton75737c02017-11-06 10:37:17 -08004220// TODO(steveanton): Eventually it'd be nice to store the channels as a single
4221// vector of BaseChannel pointers instead of separate voice and video channel
4222// vectors. At that point, this will become a simple getter.
4223std::vector<cricket::BaseChannel*> PeerConnection::Channels() const {
4224 std::vector<cricket::BaseChannel*> channels;
Steve Anton4171afb2017-11-20 10:20:22 -08004225 if (voice_channel()) {
4226 channels.push_back(voice_channel());
4227 }
4228 if (video_channel()) {
4229 channels.push_back(video_channel());
4230 }
Steve Anton75737c02017-11-06 10:37:17 -08004231 if (rtp_data_channel_) {
4232 channels.push_back(rtp_data_channel_);
4233 }
4234 return channels;
4235}
4236
Steve Antonf8470812017-12-04 10:46:21 -08004237void PeerConnection::SetSessionError(SessionError error,
4238 const std::string& error_desc) {
4239 RTC_DCHECK_RUN_ON(signaling_thread());
4240 if (error != session_error_) {
4241 session_error_ = error;
4242 session_error_desc_ = error_desc;
Steve Anton75737c02017-11-06 10:37:17 -08004243 }
4244}
4245
Steve Anton3828c062017-12-06 10:34:51 -08004246RTCError PeerConnection::UpdateSessionState(SdpType type,
Steve Anton8a006912017-12-04 15:25:56 -08004247 cricket::ContentSource source) {
4248 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08004249
4250 // If there's already a pending error then no state transition should happen.
4251 // But all call-sites should be verifying this before calling us!
Steve Antonf8470812017-12-04 10:46:21 -08004252 RTC_DCHECK(session_error() == SessionError::kNone);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004253
4254 // If this is an answer then we know whether to BUNDLE or not. If both the
4255 // local and remote side have agreed to BUNDLE, go ahead and enable it.
Steve Anton3828c062017-12-06 10:34:51 -08004256 if (type == SdpType::kAnswer) {
Steve Anton75737c02017-11-06 10:37:17 -08004257 const cricket::ContentGroup* local_bundle =
4258 local_description()->description()->GetGroupByName(
4259 cricket::GROUP_TYPE_BUNDLE);
4260 const cricket::ContentGroup* remote_bundle =
4261 remote_description()->description()->GetGroupByName(
4262 cricket::GROUP_TYPE_BUNDLE);
4263 if (local_bundle && remote_bundle) {
4264 // The answerer decides the transport to bundle on.
4265 const cricket::ContentGroup* answer_bundle =
4266 (source == cricket::CS_LOCAL ? local_bundle : remote_bundle);
4267 if (!EnableBundle(*answer_bundle)) {
Steve Anton8a006912017-12-04 15:25:56 -08004268 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
4269 kEnableBundleFailed);
Steve Anton75737c02017-11-06 10:37:17 -08004270 }
4271 }
Steve Anton75737c02017-11-06 10:37:17 -08004272 }
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004273
4274 // Only push down the transport description after potentially enabling BUNDLE;
4275 // we don't want to push down a description on a transport about to be
4276 // destroyed.
Steve Anton3828c062017-12-06 10:34:51 -08004277 RTCError error = PushdownTransportDescription(source, type);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004278 if (!error.ok()) {
4279 return error;
4280 }
4281
4282 // If this is answer-ish we're ready to let media flow.
Steve Anton3828c062017-12-06 10:34:51 -08004283 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Antoned10bd92017-12-05 10:52:59 -08004284 EnableSending();
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004285 }
4286
4287 // Update the signaling state according to the specified state machine (see
4288 // https://w3c.github.io/webrtc-pc/#rtcsignalingstate-enum).
Steve Anton3828c062017-12-06 10:34:51 -08004289 if (type == SdpType::kOffer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004290 ChangeSignalingState(source == cricket::CS_LOCAL
4291 ? PeerConnectionInterface::kHaveLocalOffer
4292 : PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton3828c062017-12-06 10:34:51 -08004293 } else if (type == SdpType::kPrAnswer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004294 ChangeSignalingState(source == cricket::CS_LOCAL
4295 ? PeerConnectionInterface::kHaveLocalPrAnswer
4296 : PeerConnectionInterface::kHaveRemotePrAnswer);
4297 } else {
Steve Anton3828c062017-12-06 10:34:51 -08004298 RTC_DCHECK(type == SdpType::kAnswer);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004299 ChangeSignalingState(PeerConnectionInterface::kStable);
4300 }
4301
4302 // Update internal objects according to the session description's media
4303 // descriptions.
Steve Anton3828c062017-12-06 10:34:51 -08004304 error = PushdownMediaDescription(type, source);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004305 if (!error.ok()) {
4306 SetSessionError(SessionError::kContent, error.message());
4307 }
4308 if (session_error() != SessionError::kNone) {
4309 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
4310 }
4311
Steve Anton8a006912017-12-04 15:25:56 -08004312 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08004313}
4314
Steve Anton8a006912017-12-04 15:25:56 -08004315RTCError PeerConnection::PushdownMediaDescription(
Steve Anton3828c062017-12-06 10:34:51 -08004316 SdpType type,
Steve Anton8a006912017-12-04 15:25:56 -08004317 cricket::ContentSource source) {
Steve Antoned10bd92017-12-05 10:52:59 -08004318 const SessionDescriptionInterface* sdesc =
4319 (source == cricket::CS_LOCAL ? local_description()
4320 : remote_description());
Steve Anton75737c02017-11-06 10:37:17 -08004321 RTC_DCHECK(sdesc);
Steve Antoned10bd92017-12-05 10:52:59 -08004322
4323 // Push down the new SDP media section for each audio/video transceiver.
4324 for (auto transceiver : transceivers_) {
Steve Anton75737c02017-11-06 10:37:17 -08004325 const ContentInfo* content_info =
Steve Antoned10bd92017-12-05 10:52:59 -08004326 FindMediaSectionForTransceiver(transceiver, sdesc);
4327 cricket::BaseChannel* channel = transceiver->internal()->channel();
4328 if (!channel || !content_info || content_info->rejected) {
Steve Anton75737c02017-11-06 10:37:17 -08004329 continue;
4330 }
4331 const MediaContentDescription* content_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08004332 content_info->media_description();
Steve Antoned10bd92017-12-05 10:52:59 -08004333 if (!content_desc) {
4334 continue;
4335 }
4336 std::string error;
4337 bool success =
4338 (source == cricket::CS_LOCAL)
Steve Anton3828c062017-12-06 10:34:51 -08004339 ? channel->SetLocalContent(content_desc, type, &error)
4340 : channel->SetRemoteContent(content_desc, type, &error);
Steve Antoned10bd92017-12-05 10:52:59 -08004341 if (!success) {
4342 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, std::move(error));
4343 }
4344 }
4345
4346 // If using the RtpDataChannel, push down the new SDP section for it too.
4347 if (rtp_data_channel_) {
4348 const ContentInfo* data_content =
4349 cricket::GetFirstDataContent(sdesc->description());
4350 if (data_content && !data_content->rejected) {
4351 const MediaContentDescription* data_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08004352 data_content->media_description();
Steve Antoned10bd92017-12-05 10:52:59 -08004353 if (data_desc) {
4354 std::string error;
4355 bool success =
4356 (source == cricket::CS_LOCAL)
Steve Anton3828c062017-12-06 10:34:51 -08004357 ? rtp_data_channel_->SetLocalContent(data_desc, type, &error)
4358 : rtp_data_channel_->SetRemoteContent(data_desc, type,
Steve Antoned10bd92017-12-05 10:52:59 -08004359 &error);
4360 if (!success) {
4361 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
4362 std::move(error));
4363 }
Steve Anton75737c02017-11-06 10:37:17 -08004364 }
4365 }
4366 }
Steve Antoned10bd92017-12-05 10:52:59 -08004367
Steve Anton75737c02017-11-06 10:37:17 -08004368 // Need complete offer/answer with an SCTP m= section before starting SCTP,
4369 // according to https://tools.ietf.org/html/draft-ietf-mmusic-sctp-sdp-19
4370 if (sctp_transport_ && local_description() && remote_description() &&
4371 cricket::GetFirstDataContent(local_description()->description()) &&
4372 cricket::GetFirstDataContent(remote_description()->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08004373 bool success = network_thread()->Invoke<bool>(
Steve Anton75737c02017-11-06 10:37:17 -08004374 RTC_FROM_HERE,
4375 rtc::Bind(&PeerConnection::PushdownSctpParameters_n, this, source));
Steve Anton8a006912017-12-04 15:25:56 -08004376 if (!success) {
4377 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
4378 "Failed to push down SCTP parameters.");
4379 }
Steve Anton75737c02017-11-06 10:37:17 -08004380 }
Steve Antoned10bd92017-12-05 10:52:59 -08004381
Steve Anton8a006912017-12-04 15:25:56 -08004382 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08004383}
4384
4385bool PeerConnection::PushdownSctpParameters_n(cricket::ContentSource source) {
4386 RTC_DCHECK(network_thread()->IsCurrent());
4387 RTC_DCHECK(local_description());
4388 RTC_DCHECK(remote_description());
4389 // Apply the SCTP port (which is hidden inside a DataCodec structure...)
4390 // When we support "max-message-size", that would also be pushed down here.
4391 return sctp_transport_->Start(
4392 GetSctpPort(local_description()->description()),
4393 GetSctpPort(remote_description()->description()));
4394}
4395
Steve Anton8a006912017-12-04 15:25:56 -08004396RTCError PeerConnection::PushdownTransportDescription(
4397 cricket::ContentSource source,
Steve Anton3828c062017-12-06 10:34:51 -08004398 SdpType type) {
Steve Anton8a006912017-12-04 15:25:56 -08004399 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08004400
Steve Anton8a006912017-12-04 15:25:56 -08004401 const SessionDescriptionInterface* sdesc =
4402 (source == cricket::CS_LOCAL ? local_description()
4403 : remote_description());
4404 RTC_DCHECK(sdesc);
4405 for (const cricket::TransportInfo& tinfo :
4406 sdesc->description()->transport_infos()) {
4407 std::string error;
4408 bool success;
4409 if (source == cricket::CS_LOCAL) {
4410 success = transport_controller_->SetLocalTransportDescription(
Steve Anton3828c062017-12-06 10:34:51 -08004411 tinfo.content_name, tinfo.description, type, &error);
Steve Anton8a006912017-12-04 15:25:56 -08004412 } else {
4413 success = transport_controller_->SetRemoteTransportDescription(
Steve Anton3828c062017-12-06 10:34:51 -08004414 tinfo.content_name, tinfo.description, type, &error);
Steve Anton8a006912017-12-04 15:25:56 -08004415 }
4416 if (!success) {
Steve Antondcc3c022017-12-22 16:02:54 -08004417 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
4418 "Failed to push down transport description for " +
4419 tinfo.content_name + ": " + error);
Steve Anton75737c02017-11-06 10:37:17 -08004420 }
4421 }
4422
Steve Anton8a006912017-12-04 15:25:56 -08004423 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08004424}
4425
4426bool PeerConnection::GetTransportDescription(
4427 const SessionDescription* description,
4428 const std::string& content_name,
4429 cricket::TransportDescription* tdesc) {
4430 if (!description || !tdesc) {
4431 return false;
4432 }
4433 const TransportInfo* transport_info =
4434 description->GetTransportInfoByName(content_name);
4435 if (!transport_info) {
4436 return false;
4437 }
4438 *tdesc = transport_info->description;
4439 return true;
4440}
4441
4442bool PeerConnection::EnableBundle(const cricket::ContentGroup& bundle) {
4443 const std::string* first_content_name = bundle.FirstContentName();
4444 if (!first_content_name) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004445 RTC_LOG(LS_WARNING) << "Tried to BUNDLE with no contents.";
Steve Anton75737c02017-11-06 10:37:17 -08004446 return false;
4447 }
4448 const std::string& transport_name = *first_content_name;
4449
4450 auto maybe_set_transport = [this, bundle,
4451 transport_name](cricket::BaseChannel* ch) {
4452 if (!ch || !bundle.HasContentName(ch->content_name())) {
Steve Antoned10bd92017-12-05 10:52:59 -08004453 return;
Steve Anton75737c02017-11-06 10:37:17 -08004454 }
4455
4456 std::string old_transport_name = ch->transport_name();
4457 if (old_transport_name == transport_name) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004458 RTC_LOG(LS_INFO) << "BUNDLE already enabled for " << ch->content_name()
4459 << " on " << transport_name << ".";
Steve Antoned10bd92017-12-05 10:52:59 -08004460 return;
Steve Anton75737c02017-11-06 10:37:17 -08004461 }
4462
4463 cricket::DtlsTransportInternal* rtp_dtls_transport =
4464 transport_controller_->CreateDtlsTransport(
4465 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4466 bool need_rtcp = (ch->rtcp_dtls_transport() != nullptr);
4467 cricket::DtlsTransportInternal* rtcp_dtls_transport = nullptr;
4468 if (need_rtcp) {
4469 rtcp_dtls_transport = transport_controller_->CreateDtlsTransport(
4470 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
4471 }
4472
4473 ch->SetTransports(rtp_dtls_transport, rtcp_dtls_transport);
Mirko Bonadei675513b2017-11-09 11:09:25 +01004474 RTC_LOG(LS_INFO) << "Enabled BUNDLE for " << ch->content_name() << " on "
4475 << transport_name << ".";
Steve Anton75737c02017-11-06 10:37:17 -08004476 transport_controller_->DestroyDtlsTransport(
4477 old_transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4478 // If the channel needs rtcp, it means that the channel used to have a
4479 // rtcp transport which needs to be deleted now.
4480 if (need_rtcp) {
4481 transport_controller_->DestroyDtlsTransport(
4482 old_transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
4483 }
Steve Anton75737c02017-11-06 10:37:17 -08004484 };
4485
Steve Antoned10bd92017-12-05 10:52:59 -08004486 for (auto transceiver : transceivers_) {
4487 maybe_set_transport(transceiver->internal()->channel());
Steve Anton75737c02017-11-06 10:37:17 -08004488 }
Steve Antoned10bd92017-12-05 10:52:59 -08004489 maybe_set_transport(rtp_data_channel_);
4490
Steve Anton75737c02017-11-06 10:37:17 -08004491 // For SCTP, transport creation/deletion happens here instead of in the
4492 // object itself.
4493 if (sctp_transport_) {
4494 RTC_DCHECK(sctp_transport_name_);
4495 RTC_DCHECK(sctp_content_name_);
4496 if (transport_name != *sctp_transport_name_ &&
4497 bundle.HasContentName(*sctp_content_name_)) {
4498 network_thread()->Invoke<void>(
4499 RTC_FROM_HERE, rtc::Bind(&PeerConnection::ChangeSctpTransport_n, this,
4500 transport_name));
4501 }
4502 }
4503
4504 return true;
4505}
4506
Steve Anton75737c02017-11-06 10:37:17 -08004507cricket::IceConfig PeerConnection::ParseIceConfig(
4508 const PeerConnectionInterface::RTCConfiguration& config) const {
4509 cricket::ContinualGatheringPolicy gathering_policy;
4510 // TODO(honghaiz): Add the third continual gathering policy in
4511 // PeerConnectionInterface and map it to GATHER_CONTINUALLY_AND_RECOVER.
4512 switch (config.continual_gathering_policy) {
4513 case PeerConnectionInterface::GATHER_ONCE:
4514 gathering_policy = cricket::GATHER_ONCE;
4515 break;
4516 case PeerConnectionInterface::GATHER_CONTINUALLY:
4517 gathering_policy = cricket::GATHER_CONTINUALLY;
4518 break;
4519 default:
4520 RTC_NOTREACHED();
4521 gathering_policy = cricket::GATHER_ONCE;
4522 }
4523 cricket::IceConfig ice_config;
4524 ice_config.receiving_timeout = config.ice_connection_receiving_timeout;
4525 ice_config.prioritize_most_likely_candidate_pairs =
4526 config.prioritize_most_likely_ice_candidate_pairs;
4527 ice_config.backup_connection_ping_interval =
4528 config.ice_backup_candidate_pair_ping_interval;
4529 ice_config.continual_gathering_policy = gathering_policy;
4530 ice_config.presume_writable_when_fully_relayed =
4531 config.presume_writable_when_fully_relayed;
4532 ice_config.ice_check_min_interval = config.ice_check_min_interval;
4533 ice_config.regather_all_networks_interval_range =
4534 config.ice_regather_interval_range;
4535 return ice_config;
4536}
4537
Steve Anton75737c02017-11-06 10:37:17 -08004538bool PeerConnection::GetLocalTrackIdBySsrc(uint32_t ssrc,
4539 std::string* track_id) {
4540 if (!local_description()) {
4541 return false;
4542 }
4543 return webrtc::GetTrackIdBySsrc(local_description()->description(), ssrc,
4544 track_id);
4545}
4546
4547bool PeerConnection::GetRemoteTrackIdBySsrc(uint32_t ssrc,
4548 std::string* track_id) {
4549 if (!remote_description()) {
4550 return false;
4551 }
4552 return webrtc::GetTrackIdBySsrc(remote_description()->description(), ssrc,
4553 track_id);
4554}
4555
4556bool PeerConnection::SendData(const cricket::SendDataParams& params,
4557 const rtc::CopyOnWriteBuffer& payload,
4558 cricket::SendDataResult* result) {
4559 if (!rtp_data_channel_ && !sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004560 RTC_LOG(LS_ERROR) << "SendData called when rtp_data_channel_ "
4561 << "and sctp_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08004562 return false;
4563 }
4564 return rtp_data_channel_
4565 ? rtp_data_channel_->SendData(params, payload, result)
4566 : network_thread()->Invoke<bool>(
4567 RTC_FROM_HERE,
4568 Bind(&cricket::SctpTransportInternal::SendData,
4569 sctp_transport_.get(), params, payload, result));
4570}
4571
4572bool PeerConnection::ConnectDataChannel(DataChannel* webrtc_data_channel) {
4573 if (!rtp_data_channel_ && !sctp_transport_) {
4574 // Don't log an error here, because DataChannels are expected to call
4575 // ConnectDataChannel in this state. It's the only way to initially tell
4576 // whether or not the underlying transport is ready.
4577 return false;
4578 }
4579 if (rtp_data_channel_) {
4580 rtp_data_channel_->SignalReadyToSendData.connect(
4581 webrtc_data_channel, &DataChannel::OnChannelReady);
4582 rtp_data_channel_->SignalDataReceived.connect(webrtc_data_channel,
4583 &DataChannel::OnDataReceived);
4584 } else {
4585 SignalSctpReadyToSendData.connect(webrtc_data_channel,
4586 &DataChannel::OnChannelReady);
4587 SignalSctpDataReceived.connect(webrtc_data_channel,
4588 &DataChannel::OnDataReceived);
4589 SignalSctpStreamClosedRemotely.connect(
4590 webrtc_data_channel, &DataChannel::OnStreamClosedRemotely);
4591 }
4592 return true;
4593}
4594
4595void PeerConnection::DisconnectDataChannel(DataChannel* webrtc_data_channel) {
4596 if (!rtp_data_channel_ && !sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004597 RTC_LOG(LS_ERROR)
4598 << "DisconnectDataChannel called when rtp_data_channel_ and "
4599 "sctp_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08004600 return;
4601 }
4602 if (rtp_data_channel_) {
4603 rtp_data_channel_->SignalReadyToSendData.disconnect(webrtc_data_channel);
4604 rtp_data_channel_->SignalDataReceived.disconnect(webrtc_data_channel);
4605 } else {
4606 SignalSctpReadyToSendData.disconnect(webrtc_data_channel);
4607 SignalSctpDataReceived.disconnect(webrtc_data_channel);
4608 SignalSctpStreamClosedRemotely.disconnect(webrtc_data_channel);
4609 }
4610}
4611
4612void PeerConnection::AddSctpDataStream(int sid) {
4613 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004614 RTC_LOG(LS_ERROR)
4615 << "AddSctpDataStream called when sctp_transport_ is NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08004616 return;
4617 }
4618 network_thread()->Invoke<void>(
4619 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::OpenStream,
4620 sctp_transport_.get(), sid));
4621}
4622
4623void PeerConnection::RemoveSctpDataStream(int sid) {
4624 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004625 RTC_LOG(LS_ERROR) << "RemoveSctpDataStream called when sctp_transport_ is "
4626 << "NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08004627 return;
4628 }
4629 network_thread()->Invoke<void>(
4630 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::ResetStream,
4631 sctp_transport_.get(), sid));
4632}
4633
4634bool PeerConnection::ReadyToSendData() const {
4635 return (rtp_data_channel_ && rtp_data_channel_->ready_to_send_data()) ||
4636 sctp_ready_to_send_data_;
4637}
4638
4639std::unique_ptr<SessionStats> PeerConnection::GetSessionStats_s() {
4640 RTC_DCHECK(signaling_thread()->IsCurrent());
4641 ChannelNamePairs channel_name_pairs;
4642 if (voice_channel()) {
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004643 channel_name_pairs.voice = ChannelNamePair(
4644 voice_channel()->content_name(), voice_channel()->transport_name());
Steve Anton75737c02017-11-06 10:37:17 -08004645 }
4646 if (video_channel()) {
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004647 channel_name_pairs.video = ChannelNamePair(
4648 video_channel()->content_name(), video_channel()->transport_name());
Steve Anton75737c02017-11-06 10:37:17 -08004649 }
4650 if (rtp_data_channel()) {
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004651 channel_name_pairs.data =
Steve Anton75737c02017-11-06 10:37:17 -08004652 ChannelNamePair(rtp_data_channel()->content_name(),
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004653 rtp_data_channel()->transport_name());
Steve Anton75737c02017-11-06 10:37:17 -08004654 }
4655 if (sctp_transport_) {
4656 RTC_DCHECK(sctp_content_name_);
4657 RTC_DCHECK(sctp_transport_name_);
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004658 channel_name_pairs.data =
4659 ChannelNamePair(*sctp_content_name_, *sctp_transport_name_);
Steve Anton75737c02017-11-06 10:37:17 -08004660 }
4661 return GetSessionStats(channel_name_pairs);
4662}
4663
4664std::unique_ptr<SessionStats> PeerConnection::GetSessionStats(
4665 const ChannelNamePairs& channel_name_pairs) {
4666 if (network_thread()->IsCurrent()) {
4667 return GetSessionStats_n(channel_name_pairs);
4668 }
4669 return network_thread()->Invoke<std::unique_ptr<SessionStats>>(
4670 RTC_FROM_HERE,
4671 rtc::Bind(&PeerConnection::GetSessionStats_n, this, channel_name_pairs));
4672}
4673
4674bool PeerConnection::GetLocalCertificate(
4675 const std::string& transport_name,
4676 rtc::scoped_refptr<rtc::RTCCertificate>* certificate) {
4677 return transport_controller_->GetLocalCertificate(transport_name,
4678 certificate);
4679}
4680
4681std::unique_ptr<rtc::SSLCertificate> PeerConnection::GetRemoteSSLCertificate(
4682 const std::string& transport_name) {
4683 return transport_controller_->GetRemoteSSLCertificate(transport_name);
4684}
4685
4686cricket::DataChannelType PeerConnection::data_channel_type() const {
4687 return data_channel_type_;
4688}
4689
4690bool PeerConnection::IceRestartPending(const std::string& content_name) const {
4691 return pending_ice_restarts_.find(content_name) !=
4692 pending_ice_restarts_.end();
4693}
4694
Steve Anton75737c02017-11-06 10:37:17 -08004695bool PeerConnection::NeedsIceRestart(const std::string& content_name) const {
4696 return transport_controller_->NeedsIceRestart(content_name);
4697}
4698
4699void PeerConnection::OnCertificateReady(
4700 const rtc::scoped_refptr<rtc::RTCCertificate>& certificate) {
4701 transport_controller_->SetLocalCertificate(certificate);
4702}
4703
4704void PeerConnection::OnDtlsSrtpSetupFailure(cricket::BaseChannel*, bool rtcp) {
Steve Antonf8470812017-12-04 10:46:21 -08004705 SetSessionError(SessionError::kTransport,
4706 rtcp ? kDtlsSrtpSetupFailureRtcp : kDtlsSrtpSetupFailureRtp);
Steve Anton75737c02017-11-06 10:37:17 -08004707}
4708
4709void PeerConnection::OnTransportControllerConnectionState(
4710 cricket::IceConnectionState state) {
4711 switch (state) {
4712 case cricket::kIceConnectionConnecting:
4713 // If the current state is Connected or Completed, then there were
4714 // writable channels but now there are not, so the next state must
4715 // be Disconnected.
4716 // kIceConnectionConnecting is currently used as the default,
4717 // un-connected state by the TransportController, so its only use is
4718 // detecting disconnections.
4719 if (ice_connection_state_ ==
4720 PeerConnectionInterface::kIceConnectionConnected ||
4721 ice_connection_state_ ==
4722 PeerConnectionInterface::kIceConnectionCompleted) {
4723 SetIceConnectionState(
4724 PeerConnectionInterface::kIceConnectionDisconnected);
4725 }
4726 break;
4727 case cricket::kIceConnectionFailed:
4728 SetIceConnectionState(PeerConnectionInterface::kIceConnectionFailed);
4729 break;
4730 case cricket::kIceConnectionConnected:
Mirko Bonadei675513b2017-11-09 11:09:25 +01004731 RTC_LOG(LS_INFO) << "Changing to ICE connected state because "
4732 << "all transports are writable.";
Steve Anton75737c02017-11-06 10:37:17 -08004733 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
4734 break;
4735 case cricket::kIceConnectionCompleted:
Mirko Bonadei675513b2017-11-09 11:09:25 +01004736 RTC_LOG(LS_INFO) << "Changing to ICE completed state because "
4737 << "all transports are complete.";
Steve Anton75737c02017-11-06 10:37:17 -08004738 if (ice_connection_state_ !=
4739 PeerConnectionInterface::kIceConnectionConnected) {
4740 // If jumping directly from "checking" to "connected",
4741 // signal "connected" first.
4742 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
4743 }
4744 SetIceConnectionState(PeerConnectionInterface::kIceConnectionCompleted);
4745 if (metrics_observer()) {
4746 ReportTransportStats();
4747 }
4748 break;
4749 default:
4750 RTC_NOTREACHED();
4751 }
4752}
4753
4754void PeerConnection::OnTransportControllerCandidatesGathered(
4755 const std::string& transport_name,
4756 const cricket::Candidates& candidates) {
4757 RTC_DCHECK(signaling_thread()->IsCurrent());
4758 int sdp_mline_index;
4759 if (!GetLocalCandidateMediaIndex(transport_name, &sdp_mline_index)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004760 RTC_LOG(LS_ERROR)
4761 << "OnTransportControllerCandidatesGathered: content name "
4762 << transport_name << " not found";
Steve Anton75737c02017-11-06 10:37:17 -08004763 return;
4764 }
4765
4766 for (cricket::Candidates::const_iterator citer = candidates.begin();
4767 citer != candidates.end(); ++citer) {
4768 // Use transport_name as the candidate media id.
4769 std::unique_ptr<JsepIceCandidate> candidate(
4770 new JsepIceCandidate(transport_name, sdp_mline_index, *citer));
4771 if (local_description()) {
4772 mutable_local_description()->AddCandidate(candidate.get());
4773 }
4774 OnIceCandidate(std::move(candidate));
4775 }
4776}
4777
4778void PeerConnection::OnTransportControllerCandidatesRemoved(
4779 const std::vector<cricket::Candidate>& candidates) {
4780 RTC_DCHECK(signaling_thread()->IsCurrent());
4781 // Sanity check.
4782 for (const cricket::Candidate& candidate : candidates) {
4783 if (candidate.transport_name().empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004784 RTC_LOG(LS_ERROR) << "OnTransportControllerCandidatesRemoved: "
4785 << "empty content name in candidate "
4786 << candidate.ToString();
Steve Anton75737c02017-11-06 10:37:17 -08004787 return;
4788 }
4789 }
4790
4791 if (local_description()) {
4792 mutable_local_description()->RemoveCandidates(candidates);
4793 }
4794 OnIceCandidatesRemoved(candidates);
4795}
4796
4797void PeerConnection::OnTransportControllerDtlsHandshakeError(
4798 rtc::SSLHandshakeError error) {
4799 if (metrics_observer()) {
4800 metrics_observer()->IncrementEnumCounter(
4801 webrtc::kEnumCounterDtlsHandshakeError, static_cast<int>(error),
4802 static_cast<int>(rtc::SSLHandshakeError::MAX_VALUE));
4803 }
4804}
4805
Steve Antoned10bd92017-12-05 10:52:59 -08004806void PeerConnection::EnableSending() {
4807 for (auto transceiver : transceivers_) {
4808 cricket::BaseChannel* channel = transceiver->internal()->channel();
4809 if (channel && !channel->enabled()) {
4810 channel->Enable(true);
4811 }
Steve Anton75737c02017-11-06 10:37:17 -08004812 }
4813
Steve Anton4171afb2017-11-20 10:20:22 -08004814 if (rtp_data_channel_ && !rtp_data_channel_->enabled()) {
Steve Anton75737c02017-11-06 10:37:17 -08004815 rtp_data_channel_->Enable(true);
Steve Anton4171afb2017-11-20 10:20:22 -08004816 }
Steve Anton75737c02017-11-06 10:37:17 -08004817}
4818
4819// Returns the media index for a local ice candidate given the content name.
4820bool PeerConnection::GetLocalCandidateMediaIndex(
4821 const std::string& content_name,
4822 int* sdp_mline_index) {
4823 if (!local_description() || !sdp_mline_index) {
4824 return false;
4825 }
4826
4827 bool content_found = false;
4828 const ContentInfos& contents = local_description()->description()->contents();
4829 for (size_t index = 0; index < contents.size(); ++index) {
4830 if (contents[index].name == content_name) {
4831 *sdp_mline_index = static_cast<int>(index);
4832 content_found = true;
4833 break;
4834 }
4835 }
4836 return content_found;
4837}
4838
4839bool PeerConnection::UseCandidatesInSessionDescription(
4840 const SessionDescriptionInterface* remote_desc) {
4841 if (!remote_desc) {
4842 return true;
4843 }
4844 bool ret = true;
4845
4846 for (size_t m = 0; m < remote_desc->number_of_mediasections(); ++m) {
4847 const IceCandidateCollection* candidates = remote_desc->candidates(m);
4848 for (size_t n = 0; n < candidates->count(); ++n) {
4849 const IceCandidateInterface* candidate = candidates->at(n);
4850 bool valid = false;
4851 if (!ReadyToUseRemoteCandidate(candidate, remote_desc, &valid)) {
4852 if (valid) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004853 RTC_LOG(LS_INFO)
4854 << "UseCandidatesInSessionDescription: Not ready to use "
4855 << "candidate.";
Steve Anton75737c02017-11-06 10:37:17 -08004856 }
4857 continue;
4858 }
4859 ret = UseCandidate(candidate);
4860 if (!ret) {
4861 break;
4862 }
4863 }
4864 }
4865 return ret;
4866}
4867
4868bool PeerConnection::UseCandidate(const IceCandidateInterface* candidate) {
4869 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
4870 size_t remote_content_size =
4871 remote_description()->description()->contents().size();
4872 if (mediacontent_index >= remote_content_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004873 RTC_LOG(LS_ERROR) << "UseCandidate: Invalid candidate media index.";
Steve Anton75737c02017-11-06 10:37:17 -08004874 return false;
4875 }
4876
4877 cricket::ContentInfo content =
4878 remote_description()->description()->contents()[mediacontent_index];
4879 std::vector<cricket::Candidate> candidates;
4880 candidates.push_back(candidate->candidate());
4881 // Invoking BaseSession method to handle remote candidates.
4882 std::string error;
4883 if (transport_controller_->AddRemoteCandidates(content.name, candidates,
4884 &error)) {
4885 // Candidates successfully submitted for checking.
4886 if (ice_connection_state_ == PeerConnectionInterface::kIceConnectionNew ||
4887 ice_connection_state_ ==
4888 PeerConnectionInterface::kIceConnectionDisconnected) {
4889 // If state is New, then the session has just gotten its first remote ICE
4890 // candidates, so go to Checking.
4891 // If state is Disconnected, the session is re-using old candidates or
4892 // receiving additional ones, so go to Checking.
4893 // If state is Connected, stay Connected.
4894 // TODO(bemasc): If state is Connected, and the new candidates are for a
4895 // newly added transport, then the state actually _should_ move to
4896 // checking. Add a way to distinguish that case.
4897 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
4898 }
4899 // TODO(bemasc): If state is Completed, go back to Connected.
4900 } else {
4901 if (!error.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004902 RTC_LOG(LS_WARNING) << error;
Steve Anton75737c02017-11-06 10:37:17 -08004903 }
4904 }
4905 return true;
4906}
4907
4908void PeerConnection::RemoveUnusedChannels(const SessionDescription* desc) {
Steve Anton75737c02017-11-06 10:37:17 -08004909 // Destroy video channel first since it may have a pointer to the
4910 // voice channel.
4911 const cricket::ContentInfo* video_info = cricket::GetFirstVideoContent(desc);
Steve Anton6fec8802017-12-04 10:37:29 -08004912 if (!video_info || video_info->rejected) {
4913 DestroyTransceiverChannel(GetVideoTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08004914 }
4915
Steve Anton6fec8802017-12-04 10:37:29 -08004916 const cricket::ContentInfo* audio_info = cricket::GetFirstAudioContent(desc);
4917 if (!audio_info || audio_info->rejected) {
4918 DestroyTransceiverChannel(GetAudioTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08004919 }
4920
4921 const cricket::ContentInfo* data_info = cricket::GetFirstDataContent(desc);
4922 if (!data_info || data_info->rejected) {
Steve Anton6fec8802017-12-04 10:37:29 -08004923 DestroyDataChannel();
Steve Anton75737c02017-11-06 10:37:17 -08004924 }
4925}
4926
Steve Antoneda6ccd2017-12-04 10:21:55 -08004927std::string PeerConnection::GetTransportNameForMediaSection(
4928 const std::string& mid,
4929 const cricket::ContentGroup* bundle_group) const {
4930 if (!bundle_group) {
4931 return mid;
Steve Anton75737c02017-11-06 10:37:17 -08004932 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08004933 const std::string* first_content_name = bundle_group->FirstContentName();
Steve Anton75737c02017-11-06 10:37:17 -08004934 if (!first_content_name) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004935 RTC_LOG(LS_WARNING) << "Tried to BUNDLE with no contents.";
Steve Antoneda6ccd2017-12-04 10:21:55 -08004936 return mid;
Steve Anton75737c02017-11-06 10:37:17 -08004937 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08004938 if (!bundle_group->HasContentName(mid)) {
4939 RTC_LOG(LS_WARNING) << mid << " is not part of any bundle group";
4940 return mid;
Steve Anton75737c02017-11-06 10:37:17 -08004941 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08004942 RTC_LOG(LS_INFO) << "Bundling " << mid << " on " << *first_content_name;
4943 return *first_content_name;
Steve Anton75737c02017-11-06 10:37:17 -08004944}
4945
Steve Antondcc3c022017-12-22 16:02:54 -08004946RTCErrorOr<const cricket::ContentGroup*> PeerConnection::GetEarlyBundleGroup(
4947 const SessionDescription& desc) const {
Steve Anton75737c02017-11-06 10:37:17 -08004948 const cricket::ContentGroup* bundle_group = nullptr;
4949 if (configuration_.bundle_policy ==
4950 PeerConnectionInterface::kBundlePolicyMaxBundle) {
Steve Antondcc3c022017-12-22 16:02:54 -08004951 bundle_group = desc.GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton75737c02017-11-06 10:37:17 -08004952 if (!bundle_group) {
Steve Anton8a006912017-12-04 15:25:56 -08004953 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
4954 "max-bundle configured but session description "
4955 "has no BUNDLE group");
Steve Anton75737c02017-11-06 10:37:17 -08004956 }
4957 }
Steve Antondcc3c022017-12-22 16:02:54 -08004958 return std::move(bundle_group);
4959}
4960
4961RTCError PeerConnection::CreateChannels(const SessionDescription& desc) {
4962 auto bundle_group_or_error = GetEarlyBundleGroup(desc);
4963 if (!bundle_group_or_error.ok()) {
4964 return bundle_group_or_error.MoveError();
4965 }
4966 const cricket::ContentGroup* bundle_group = bundle_group_or_error.MoveValue();
Steve Anton75737c02017-11-06 10:37:17 -08004967
Steve Antoneda6ccd2017-12-04 10:21:55 -08004968 // Creating the media channels and transport proxies.
Steve Antondcc3c022017-12-22 16:02:54 -08004969 const cricket::ContentInfo* voice = cricket::GetFirstAudioContent(&desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08004970 if (voice && !voice->rejected &&
4971 !GetAudioTransceiver()->internal()->channel()) {
4972 cricket::VoiceChannel* voice_channel = CreateVoiceChannel(
4973 voice->name,
4974 GetTransportNameForMediaSection(voice->name, bundle_group));
4975 if (!voice_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08004976 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
4977 "Failed to create voice channel.");
Steve Antoneda6ccd2017-12-04 10:21:55 -08004978 }
4979 GetAudioTransceiver()->internal()->SetChannel(voice_channel);
4980 }
4981
Steve Antondcc3c022017-12-22 16:02:54 -08004982 const cricket::ContentInfo* video = cricket::GetFirstVideoContent(&desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08004983 if (video && !video->rejected &&
4984 !GetVideoTransceiver()->internal()->channel()) {
4985 cricket::VideoChannel* video_channel = CreateVideoChannel(
4986 video->name,
4987 GetTransportNameForMediaSection(video->name, bundle_group));
4988 if (!video_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08004989 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
4990 "Failed to create video channel.");
Steve Anton75737c02017-11-06 10:37:17 -08004991 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08004992 GetVideoTransceiver()->internal()->SetChannel(video_channel);
Steve Anton75737c02017-11-06 10:37:17 -08004993 }
4994
Steve Antondcc3c022017-12-22 16:02:54 -08004995 const cricket::ContentInfo* data = cricket::GetFirstDataContent(&desc);
Steve Anton75737c02017-11-06 10:37:17 -08004996 if (data_channel_type_ != cricket::DCT_NONE && data && !data->rejected &&
4997 !rtp_data_channel_ && !sctp_transport_) {
Steve Antoneda6ccd2017-12-04 10:21:55 -08004998 if (!CreateDataChannel(data->name, GetTransportNameForMediaSection(
4999 data->name, bundle_group))) {
Steve Anton8a006912017-12-04 15:25:56 -08005000 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5001 "Failed to create data channel.");
Steve Anton75737c02017-11-06 10:37:17 -08005002 }
5003 }
5004
Steve Anton8a006912017-12-04 15:25:56 -08005005 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08005006}
5007
Steve Anton4171afb2017-11-20 10:20:22 -08005008// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08005009cricket::VoiceChannel* PeerConnection::CreateVoiceChannel(
5010 const std::string& mid,
5011 const std::string& transport_name) {
Steve Anton75737c02017-11-06 10:37:17 -08005012 cricket::DtlsTransportInternal* rtp_dtls_transport =
5013 transport_controller_->CreateDtlsTransport(
5014 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5015 cricket::DtlsTransportInternal* rtcp_dtls_transport = nullptr;
5016 if (configuration_.rtcp_mux_policy !=
5017 PeerConnectionInterface::kRtcpMuxPolicyRequire) {
5018 rtcp_dtls_transport = transport_controller_->CreateDtlsTransport(
5019 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
5020 }
5021
5022 cricket::VoiceChannel* voice_channel = channel_manager()->CreateVoiceChannel(
5023 call_.get(), configuration_.media_config, rtp_dtls_transport,
Steve Antoneda6ccd2017-12-04 10:21:55 -08005024 rtcp_dtls_transport, signaling_thread(), mid, SrtpRequired(),
5025 audio_options_);
Steve Anton75737c02017-11-06 10:37:17 -08005026 if (!voice_channel) {
5027 transport_controller_->DestroyDtlsTransport(
5028 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5029 if (rtcp_dtls_transport) {
5030 transport_controller_->DestroyDtlsTransport(
5031 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
5032 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005033 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08005034 }
Steve Anton75737c02017-11-06 10:37:17 -08005035 voice_channel->SignalRtcpMuxFullyActive.connect(
5036 this, &PeerConnection::DestroyRtcpTransport_n);
5037 voice_channel->SignalDtlsSrtpSetupFailure.connect(
5038 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08005039 voice_channel->SignalSentPacket.connect(this,
5040 &PeerConnection::OnSentPacket_w);
Steve Anton4171afb2017-11-20 10:20:22 -08005041
Steve Antoneda6ccd2017-12-04 10:21:55 -08005042 return voice_channel;
Steve Anton75737c02017-11-06 10:37:17 -08005043}
5044
Steve Anton4171afb2017-11-20 10:20:22 -08005045// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08005046cricket::VideoChannel* PeerConnection::CreateVideoChannel(
5047 const std::string& mid,
5048 const std::string& transport_name) {
Steve Anton75737c02017-11-06 10:37:17 -08005049 cricket::DtlsTransportInternal* rtp_dtls_transport =
5050 transport_controller_->CreateDtlsTransport(
5051 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5052 cricket::DtlsTransportInternal* rtcp_dtls_transport = nullptr;
5053 if (configuration_.rtcp_mux_policy !=
5054 PeerConnectionInterface::kRtcpMuxPolicyRequire) {
5055 rtcp_dtls_transport = transport_controller_->CreateDtlsTransport(
5056 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
5057 }
5058
5059 cricket::VideoChannel* video_channel = channel_manager()->CreateVideoChannel(
5060 call_.get(), configuration_.media_config, rtp_dtls_transport,
Steve Antoneda6ccd2017-12-04 10:21:55 -08005061 rtcp_dtls_transport, signaling_thread(), mid, SrtpRequired(),
5062 video_options_);
Steve Anton75737c02017-11-06 10:37:17 -08005063
5064 if (!video_channel) {
5065 transport_controller_->DestroyDtlsTransport(
5066 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5067 if (rtcp_dtls_transport) {
5068 transport_controller_->DestroyDtlsTransport(
5069 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
5070 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005071 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08005072 }
Steve Anton75737c02017-11-06 10:37:17 -08005073 video_channel->SignalRtcpMuxFullyActive.connect(
5074 this, &PeerConnection::DestroyRtcpTransport_n);
5075 video_channel->SignalDtlsSrtpSetupFailure.connect(
5076 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08005077 video_channel->SignalSentPacket.connect(this,
5078 &PeerConnection::OnSentPacket_w);
Steve Anton4171afb2017-11-20 10:20:22 -08005079
Steve Antoneda6ccd2017-12-04 10:21:55 -08005080 return video_channel;
Steve Anton75737c02017-11-06 10:37:17 -08005081}
5082
Steve Antoneda6ccd2017-12-04 10:21:55 -08005083bool PeerConnection::CreateDataChannel(const std::string& mid,
5084 const std::string& transport_name) {
Steve Anton75737c02017-11-06 10:37:17 -08005085 bool sctp = (data_channel_type_ == cricket::DCT_SCTP);
5086 if (sctp) {
5087 if (!sctp_factory_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005088 RTC_LOG(LS_ERROR)
Steve Anton75737c02017-11-06 10:37:17 -08005089 << "Trying to create SCTP transport, but didn't compile with "
5090 "SCTP support (HAVE_SCTP)";
5091 return false;
5092 }
5093 if (!network_thread()->Invoke<bool>(
5094 RTC_FROM_HERE, rtc::Bind(&PeerConnection::CreateSctpTransport_n,
Steve Antoneda6ccd2017-12-04 10:21:55 -08005095 this, mid, transport_name))) {
Steve Anton75737c02017-11-06 10:37:17 -08005096 return false;
5097 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005098 for (const auto& channel : sctp_data_channels_) {
5099 channel->OnTransportChannelCreated();
5100 }
Steve Anton75737c02017-11-06 10:37:17 -08005101 } else {
Steve Anton75737c02017-11-06 10:37:17 -08005102 cricket::DtlsTransportInternal* rtp_dtls_transport =
5103 transport_controller_->CreateDtlsTransport(
5104 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5105 cricket::DtlsTransportInternal* rtcp_dtls_transport = nullptr;
5106 if (configuration_.rtcp_mux_policy !=
5107 PeerConnectionInterface::kRtcpMuxPolicyRequire) {
5108 rtcp_dtls_transport = transport_controller_->CreateDtlsTransport(
5109 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
5110 }
5111
5112 rtp_data_channel_ = channel_manager()->CreateRtpDataChannel(
5113 configuration_.media_config, rtp_dtls_transport, rtcp_dtls_transport,
Steve Antoneda6ccd2017-12-04 10:21:55 -08005114 signaling_thread(), mid, SrtpRequired());
Steve Anton75737c02017-11-06 10:37:17 -08005115
5116 if (!rtp_data_channel_) {
5117 transport_controller_->DestroyDtlsTransport(
5118 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5119 if (rtcp_dtls_transport) {
5120 transport_controller_->DestroyDtlsTransport(
5121 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
5122 }
5123 return false;
5124 }
5125
5126 rtp_data_channel_->SignalRtcpMuxFullyActive.connect(
5127 this, &PeerConnection::DestroyRtcpTransport_n);
5128 rtp_data_channel_->SignalDtlsSrtpSetupFailure.connect(
5129 this, &PeerConnection::OnDtlsSrtpSetupFailure);
5130 rtp_data_channel_->SignalSentPacket.connect(
5131 this, &PeerConnection::OnSentPacket_w);
5132 }
5133
Steve Anton75737c02017-11-06 10:37:17 -08005134 return true;
5135}
5136
5137Call::Stats PeerConnection::GetCallStats() {
5138 if (!worker_thread()->IsCurrent()) {
5139 return worker_thread()->Invoke<Call::Stats>(
5140 RTC_FROM_HERE, rtc::Bind(&PeerConnection::GetCallStats, this));
5141 }
5142 if (call_) {
5143 return call_->GetStats();
5144 } else {
5145 return Call::Stats();
5146 }
5147}
5148
5149std::unique_ptr<SessionStats> PeerConnection::GetSessionStats_n(
5150 const ChannelNamePairs& channel_name_pairs) {
5151 RTC_DCHECK(network_thread()->IsCurrent());
5152 std::unique_ptr<SessionStats> session_stats(new SessionStats());
5153 for (const auto channel_name_pair :
5154 {&channel_name_pairs.voice, &channel_name_pairs.video,
5155 &channel_name_pairs.data}) {
5156 if (*channel_name_pair) {
5157 cricket::TransportStats transport_stats;
5158 if (!transport_controller_->GetStats((*channel_name_pair)->transport_name,
5159 &transport_stats)) {
5160 return nullptr;
5161 }
Steve Anton75737c02017-11-06 10:37:17 -08005162 session_stats->transport_stats[(*channel_name_pair)->transport_name] =
5163 std::move(transport_stats);
5164 }
5165 }
5166 return session_stats;
5167}
5168
5169bool PeerConnection::CreateSctpTransport_n(const std::string& content_name,
5170 const std::string& transport_name) {
5171 RTC_DCHECK(network_thread()->IsCurrent());
5172 RTC_DCHECK(sctp_factory_);
5173 cricket::DtlsTransportInternal* tc =
5174 transport_controller_->CreateDtlsTransport_n(
5175 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5176 sctp_transport_ = sctp_factory_->CreateSctpTransport(tc);
5177 RTC_DCHECK(sctp_transport_);
5178 sctp_invoker_.reset(new rtc::AsyncInvoker());
5179 sctp_transport_->SignalReadyToSendData.connect(
5180 this, &PeerConnection::OnSctpTransportReadyToSendData_n);
5181 sctp_transport_->SignalDataReceived.connect(
5182 this, &PeerConnection::OnSctpTransportDataReceived_n);
5183 sctp_transport_->SignalStreamClosedRemotely.connect(
5184 this, &PeerConnection::OnSctpStreamClosedRemotely_n);
Oskar Sundbom9b28a032017-11-16 10:53:30 +01005185 sctp_transport_name_ = transport_name;
5186 sctp_content_name_ = content_name;
Steve Anton75737c02017-11-06 10:37:17 -08005187 return true;
5188}
5189
5190void PeerConnection::ChangeSctpTransport_n(const std::string& transport_name) {
5191 RTC_DCHECK(network_thread()->IsCurrent());
5192 RTC_DCHECK(sctp_transport_);
5193 RTC_DCHECK(sctp_transport_name_);
5194 std::string old_sctp_transport_name = *sctp_transport_name_;
Oskar Sundbom9b28a032017-11-16 10:53:30 +01005195 sctp_transport_name_ = transport_name;
Steve Anton75737c02017-11-06 10:37:17 -08005196 cricket::DtlsTransportInternal* tc =
5197 transport_controller_->CreateDtlsTransport_n(
5198 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5199 sctp_transport_->SetTransportChannel(tc);
5200 transport_controller_->DestroyDtlsTransport_n(
5201 old_sctp_transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5202}
5203
5204void PeerConnection::DestroySctpTransport_n() {
5205 RTC_DCHECK(network_thread()->IsCurrent());
5206 sctp_transport_.reset(nullptr);
Taylor Brandstetter389a97c2018-01-03 16:26:06 -08005207 transport_controller_->DestroyDtlsTransport_n(
5208 *sctp_transport_name_, cricket::ICE_CANDIDATE_COMPONENT_RTP);
Steve Anton75737c02017-11-06 10:37:17 -08005209 sctp_content_name_.reset();
5210 sctp_transport_name_.reset();
5211 sctp_invoker_.reset(nullptr);
5212 sctp_ready_to_send_data_ = false;
5213}
5214
5215void PeerConnection::OnSctpTransportReadyToSendData_n() {
5216 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5217 RTC_DCHECK(network_thread()->IsCurrent());
5218 // Note: Cannot use rtc::Bind here because it will grab a reference to
5219 // PeerConnection and potentially cause PeerConnection to live longer than
5220 // expected. It is safe not to grab a reference since the sctp_invoker_ will
5221 // be destroyed before PeerConnection is destroyed, and at that point all
5222 // pending tasks will be cleared.
5223 sctp_invoker_->AsyncInvoke<void>(RTC_FROM_HERE, signaling_thread(), [this] {
5224 OnSctpTransportReadyToSendData_s(true);
5225 });
5226}
5227
5228void PeerConnection::OnSctpTransportReadyToSendData_s(bool ready) {
5229 RTC_DCHECK(signaling_thread()->IsCurrent());
5230 sctp_ready_to_send_data_ = ready;
5231 SignalSctpReadyToSendData(ready);
5232}
5233
5234void PeerConnection::OnSctpTransportDataReceived_n(
5235 const cricket::ReceiveDataParams& params,
5236 const rtc::CopyOnWriteBuffer& payload) {
5237 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5238 RTC_DCHECK(network_thread()->IsCurrent());
5239 // Note: Cannot use rtc::Bind here because it will grab a reference to
5240 // PeerConnection and potentially cause PeerConnection to live longer than
5241 // expected. It is safe not to grab a reference since the sctp_invoker_ will
5242 // be destroyed before PeerConnection is destroyed, and at that point all
5243 // pending tasks will be cleared.
5244 sctp_invoker_->AsyncInvoke<void>(
5245 RTC_FROM_HERE, signaling_thread(), [this, params, payload] {
5246 OnSctpTransportDataReceived_s(params, payload);
5247 });
5248}
5249
5250void PeerConnection::OnSctpTransportDataReceived_s(
5251 const cricket::ReceiveDataParams& params,
5252 const rtc::CopyOnWriteBuffer& payload) {
5253 RTC_DCHECK(signaling_thread()->IsCurrent());
5254 if (params.type == cricket::DMT_CONTROL && IsOpenMessage(payload)) {
5255 // Received OPEN message; parse and signal that a new data channel should
5256 // be created.
5257 std::string label;
5258 InternalDataChannelInit config;
5259 config.id = params.ssrc;
5260 if (!ParseDataChannelOpenMessage(payload, &label, &config)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005261 RTC_LOG(LS_WARNING) << "Failed to parse the OPEN message for sid "
5262 << params.ssrc;
Steve Anton75737c02017-11-06 10:37:17 -08005263 return;
5264 }
5265 config.open_handshake_role = InternalDataChannelInit::kAcker;
5266 OnDataChannelOpenMessage(label, config);
5267 } else {
5268 // Otherwise just forward the signal.
5269 SignalSctpDataReceived(params, payload);
5270 }
5271}
5272
5273void PeerConnection::OnSctpStreamClosedRemotely_n(int sid) {
5274 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5275 RTC_DCHECK(network_thread()->IsCurrent());
5276 sctp_invoker_->AsyncInvoke<void>(
5277 RTC_FROM_HERE, signaling_thread(),
5278 rtc::Bind(&sigslot::signal1<int>::operator(),
5279 &SignalSctpStreamClosedRemotely, sid));
5280}
5281
5282// Returns false if bundle is enabled and rtcp_mux is disabled.
5283bool PeerConnection::ValidateBundleSettings(const SessionDescription* desc) {
5284 bool bundle_enabled = desc->HasGroup(cricket::GROUP_TYPE_BUNDLE);
5285 if (!bundle_enabled)
5286 return true;
5287
5288 const cricket::ContentGroup* bundle_group =
5289 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
5290 RTC_DCHECK(bundle_group != NULL);
5291
5292 const cricket::ContentInfos& contents = desc->contents();
5293 for (cricket::ContentInfos::const_iterator citer = contents.begin();
5294 citer != contents.end(); ++citer) {
5295 const cricket::ContentInfo* content = (&*citer);
5296 RTC_DCHECK(content != NULL);
5297 if (bundle_group->HasContentName(content->name) && !content->rejected &&
Steve Anton5adfafd2017-12-20 16:34:00 -08005298 content->type == MediaProtocolType::kRtp) {
Steve Anton75737c02017-11-06 10:37:17 -08005299 if (!HasRtcpMuxEnabled(content))
5300 return false;
5301 }
5302 }
5303 // RTCP-MUX is enabled in all the contents.
5304 return true;
5305}
5306
5307bool PeerConnection::HasRtcpMuxEnabled(const cricket::ContentInfo* content) {
Steve Antonb1c1de12017-12-21 15:14:30 -08005308 return content->media_description()->rtcp_mux();
Steve Anton75737c02017-11-06 10:37:17 -08005309}
5310
Steve Anton8a006912017-12-04 15:25:56 -08005311RTCError PeerConnection::ValidateSessionDescription(
Steve Anton75737c02017-11-06 10:37:17 -08005312 const SessionDescriptionInterface* sdesc,
Steve Anton8a006912017-12-04 15:25:56 -08005313 cricket::ContentSource source) {
Steve Antonf8470812017-12-04 10:46:21 -08005314 if (session_error() != SessionError::kNone) {
Steve Anton8a006912017-12-04 15:25:56 -08005315 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
Steve Anton75737c02017-11-06 10:37:17 -08005316 }
5317
5318 if (!sdesc || !sdesc->description()) {
Steve Anton8a006912017-12-04 15:25:56 -08005319 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidSdp);
Steve Anton75737c02017-11-06 10:37:17 -08005320 }
5321
Steve Anton3828c062017-12-06 10:34:51 -08005322 SdpType type = sdesc->GetType();
5323 if ((source == cricket::CS_LOCAL && !ExpectSetLocalDescription(type)) ||
5324 (source == cricket::CS_REMOTE && !ExpectSetRemoteDescription(type))) {
Steve Anton8a006912017-12-04 15:25:56 -08005325 LOG_AND_RETURN_ERROR(
5326 RTCErrorType::INVALID_PARAMETER,
5327 "Called in wrong state: " + GetSignalingStateString(signaling_state()));
Steve Anton75737c02017-11-06 10:37:17 -08005328 }
5329
5330 // Verify crypto settings.
5331 std::string crypto_error;
Steve Anton8a006912017-12-04 15:25:56 -08005332 if (webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED ||
5333 dtls_enabled_) {
Harald Alvestrand194939b2018-01-24 16:04:13 +01005334 RTCError crypto_error =
5335 VerifyCrypto(sdesc->description(), dtls_enabled_, uma_observer_);
Steve Anton8a006912017-12-04 15:25:56 -08005336 if (!crypto_error.ok()) {
5337 return crypto_error;
5338 }
Steve Anton75737c02017-11-06 10:37:17 -08005339 }
5340
5341 // Verify ice-ufrag and ice-pwd.
5342 if (!VerifyIceUfragPwdPresent(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08005343 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5344 kSdpWithoutIceUfragPwd);
Steve Anton75737c02017-11-06 10:37:17 -08005345 }
5346
5347 if (!ValidateBundleSettings(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08005348 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5349 kBundleWithoutRtcpMux);
Steve Anton75737c02017-11-06 10:37:17 -08005350 }
5351
5352 // TODO(skvlad): When the local rtcp-mux policy is Require, reject any
5353 // m-lines that do not rtcp-mux enabled.
5354
5355 // Verify m-lines in Answer when compared against Offer.
Steve Anton3828c062017-12-06 10:34:51 -08005356 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Anton75737c02017-11-06 10:37:17 -08005357 const cricket::SessionDescription* offer_desc =
5358 (source == cricket::CS_LOCAL) ? remote_description()->description()
5359 : local_description()->description();
5360 if (!MediaSectionsHaveSameCount(offer_desc, sdesc->description()) ||
5361 !MediaSectionsInSameOrder(offer_desc, sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08005362 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5363 kMlineMismatchInAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08005364 }
5365 } else {
5366 const cricket::SessionDescription* current_desc = nullptr;
5367 if (source == cricket::CS_LOCAL && local_description()) {
5368 current_desc = local_description()->description();
5369 } else if (source == cricket::CS_REMOTE && remote_description()) {
5370 current_desc = remote_description()->description();
5371 }
5372 // The re-offers should respect the order of m= sections in current
5373 // description. See RFC3264 Section 8 paragraph 4 for more details.
5374 if (current_desc &&
5375 !MediaSectionsInSameOrder(current_desc, sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08005376 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5377 kMlineMismatchInSubsequentOffer);
Steve Anton75737c02017-11-06 10:37:17 -08005378 }
5379 }
5380
Steve Anton02ee47c2018-01-10 16:26:06 -08005381 // Unified Plan SDP should have exactly one stream per m= section for audio
5382 // and video.
5383 if (IsUnifiedPlan()) {
5384 for (const ContentInfo& content : sdesc->description()->contents()) {
5385 if (content.rejected) {
5386 continue;
5387 }
5388 if (content.media_description()) {
5389 cricket::MediaType media_type = content.media_description()->type();
5390 if (!(media_type == cricket::MEDIA_TYPE_AUDIO ||
5391 media_type == cricket::MEDIA_TYPE_VIDEO)) {
5392 continue;
5393 }
5394 const cricket::StreamParamsVec& streams =
5395 content.media_description()->streams();
5396 if (streams.size() != 1u) {
5397 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5398 "Unified Plan SDP should have exactly one "
5399 "track per media section for audio and video.");
5400 }
5401 }
5402 }
5403 }
5404
Steve Anton8a006912017-12-04 15:25:56 -08005405 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08005406}
5407
Steve Anton3828c062017-12-06 10:34:51 -08005408bool PeerConnection::ExpectSetLocalDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08005409 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08005410 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08005411 return (state == PeerConnectionInterface::kStable) ||
5412 (state == PeerConnectionInterface::kHaveLocalOffer);
Steve Anton20393062017-12-04 16:24:52 -08005413 } else {
Steve Anton3828c062017-12-06 10:34:51 -08005414 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08005415 return (state == PeerConnectionInterface::kHaveRemoteOffer) ||
5416 (state == PeerConnectionInterface::kHaveLocalPrAnswer);
5417 }
5418}
5419
Steve Anton3828c062017-12-06 10:34:51 -08005420bool PeerConnection::ExpectSetRemoteDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08005421 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08005422 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08005423 return (state == PeerConnectionInterface::kStable) ||
5424 (state == PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton20393062017-12-04 16:24:52 -08005425 } else {
Steve Anton3828c062017-12-06 10:34:51 -08005426 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08005427 return (state == PeerConnectionInterface::kHaveLocalOffer) ||
5428 (state == PeerConnectionInterface::kHaveRemotePrAnswer);
5429 }
5430}
5431
Steve Antonf8470812017-12-04 10:46:21 -08005432const char* PeerConnection::SessionErrorToString(SessionError error) const {
5433 switch (error) {
5434 case SessionError::kNone:
5435 return "ERROR_NONE";
5436 case SessionError::kContent:
5437 return "ERROR_CONTENT";
5438 case SessionError::kTransport:
5439 return "ERROR_TRANSPORT";
5440 }
5441 RTC_NOTREACHED();
5442 return "";
5443}
5444
Steve Anton75737c02017-11-06 10:37:17 -08005445std::string PeerConnection::GetSessionErrorMsg() {
5446 std::ostringstream desc;
Steve Antonf8470812017-12-04 10:46:21 -08005447 desc << kSessionError << SessionErrorToString(session_error()) << ". ";
5448 desc << kSessionErrorDesc << session_error_desc() << ".";
Steve Anton75737c02017-11-06 10:37:17 -08005449 return desc.str();
5450}
5451
5452// We need to check the local/remote description for the Transport instead of
5453// the session, because a new Transport added during renegotiation may have
5454// them unset while the session has them set from the previous negotiation.
5455// Not doing so may trigger the auto generation of transport description and
5456// mess up DTLS identity information, ICE credential, etc.
5457bool PeerConnection::ReadyToUseRemoteCandidate(
5458 const IceCandidateInterface* candidate,
5459 const SessionDescriptionInterface* remote_desc,
5460 bool* valid) {
5461 *valid = true;
5462
5463 const SessionDescriptionInterface* current_remote_desc =
5464 remote_desc ? remote_desc : remote_description();
5465
5466 if (!current_remote_desc) {
5467 return false;
5468 }
5469
5470 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
5471 size_t remote_content_size =
5472 current_remote_desc->description()->contents().size();
5473 if (mediacontent_index >= remote_content_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005474 RTC_LOG(LS_ERROR)
5475 << "ReadyToUseRemoteCandidate: Invalid candidate media index "
5476 << mediacontent_index;
Steve Anton75737c02017-11-06 10:37:17 -08005477
5478 *valid = false;
5479 return false;
5480 }
5481
5482 cricket::ContentInfo content =
5483 current_remote_desc->description()->contents()[mediacontent_index];
5484
5485 const std::string transport_name = GetTransportName(content.name);
5486 if (transport_name.empty()) {
5487 return false;
5488 }
5489 return transport_controller_->ReadyForRemoteCandidates(transport_name);
5490}
5491
5492bool PeerConnection::SrtpRequired() const {
5493 return dtls_enabled_ ||
5494 webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED;
5495}
5496
5497void PeerConnection::OnTransportControllerGatheringState(
5498 cricket::IceGatheringState state) {
5499 RTC_DCHECK(signaling_thread()->IsCurrent());
5500 if (state == cricket::kIceGatheringGathering) {
5501 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringGathering);
5502 } else if (state == cricket::kIceGatheringComplete) {
5503 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringComplete);
5504 }
5505}
5506
5507void PeerConnection::ReportTransportStats() {
5508 // Use a set so we don't report the same stats twice if two channels share
5509 // a transport.
5510 std::set<std::string> transport_names;
5511 if (voice_channel()) {
5512 transport_names.insert(voice_channel()->transport_name());
5513 }
5514 if (video_channel()) {
5515 transport_names.insert(video_channel()->transport_name());
5516 }
5517 if (rtp_data_channel()) {
5518 transport_names.insert(rtp_data_channel()->transport_name());
5519 }
5520 if (sctp_transport_name_) {
5521 transport_names.insert(*sctp_transport_name_);
5522 }
5523 for (const auto& name : transport_names) {
5524 cricket::TransportStats stats;
5525 if (transport_controller_->GetStats(name, &stats)) {
5526 ReportBestConnectionState(stats);
5527 ReportNegotiatedCiphers(stats);
5528 }
5529 }
5530}
5531// Walk through the ConnectionInfos to gather best connection usage
5532// for IPv4 and IPv6.
5533void PeerConnection::ReportBestConnectionState(
5534 const cricket::TransportStats& stats) {
5535 RTC_DCHECK(metrics_observer());
5536 for (cricket::TransportChannelStatsList::const_iterator it =
5537 stats.channel_stats.begin();
5538 it != stats.channel_stats.end(); ++it) {
5539 for (cricket::ConnectionInfos::const_iterator it_info =
5540 it->connection_infos.begin();
5541 it_info != it->connection_infos.end(); ++it_info) {
5542 if (!it_info->best_connection) {
5543 continue;
5544 }
5545
5546 PeerConnectionEnumCounterType type = kPeerConnectionEnumCounterMax;
5547 const cricket::Candidate& local = it_info->local_candidate;
5548 const cricket::Candidate& remote = it_info->remote_candidate;
5549
5550 // Increment the counter for IceCandidatePairType.
5551 if (local.protocol() == cricket::TCP_PROTOCOL_NAME ||
5552 (local.type() == RELAY_PORT_TYPE &&
5553 local.relay_protocol() == cricket::TCP_PROTOCOL_NAME)) {
5554 type = kEnumCounterIceCandidatePairTypeTcp;
5555 } else if (local.protocol() == cricket::UDP_PROTOCOL_NAME) {
5556 type = kEnumCounterIceCandidatePairTypeUdp;
5557 } else {
5558 RTC_CHECK(0);
5559 }
5560 metrics_observer()->IncrementEnumCounter(
5561 type, GetIceCandidatePairCounter(local, remote),
5562 kIceCandidatePairMax);
5563
5564 // Increment the counter for IP type.
5565 if (local.address().family() == AF_INET) {
5566 metrics_observer()->IncrementEnumCounter(
5567 kEnumCounterAddressFamily, kBestConnections_IPv4,
5568 kPeerConnectionAddressFamilyCounter_Max);
5569
5570 } else if (local.address().family() == AF_INET6) {
5571 metrics_observer()->IncrementEnumCounter(
5572 kEnumCounterAddressFamily, kBestConnections_IPv6,
5573 kPeerConnectionAddressFamilyCounter_Max);
5574 } else {
5575 RTC_CHECK(0);
5576 }
5577
5578 return;
5579 }
5580 }
5581}
5582
5583void PeerConnection::ReportNegotiatedCiphers(
5584 const cricket::TransportStats& stats) {
5585 RTC_DCHECK(metrics_observer());
5586 if (!dtls_enabled_ || stats.channel_stats.empty()) {
5587 return;
5588 }
5589
5590 int srtp_crypto_suite = stats.channel_stats[0].srtp_crypto_suite;
5591 int ssl_cipher_suite = stats.channel_stats[0].ssl_cipher_suite;
5592 if (srtp_crypto_suite == rtc::SRTP_INVALID_CRYPTO_SUITE &&
5593 ssl_cipher_suite == rtc::TLS_NULL_WITH_NULL_NULL) {
5594 return;
5595 }
5596
5597 PeerConnectionEnumCounterType srtp_counter_type;
5598 PeerConnectionEnumCounterType ssl_counter_type;
5599 if (stats.transport_name == cricket::CN_AUDIO) {
5600 srtp_counter_type = kEnumCounterAudioSrtpCipher;
5601 ssl_counter_type = kEnumCounterAudioSslCipher;
5602 } else if (stats.transport_name == cricket::CN_VIDEO) {
5603 srtp_counter_type = kEnumCounterVideoSrtpCipher;
5604 ssl_counter_type = kEnumCounterVideoSslCipher;
5605 } else if (stats.transport_name == cricket::CN_DATA) {
5606 srtp_counter_type = kEnumCounterDataSrtpCipher;
5607 ssl_counter_type = kEnumCounterDataSslCipher;
5608 } else {
5609 RTC_NOTREACHED();
5610 return;
5611 }
5612
5613 if (srtp_crypto_suite != rtc::SRTP_INVALID_CRYPTO_SUITE) {
5614 metrics_observer()->IncrementSparseEnumCounter(srtp_counter_type,
5615 srtp_crypto_suite);
5616 }
5617 if (ssl_cipher_suite != rtc::TLS_NULL_WITH_NULL_NULL) {
5618 metrics_observer()->IncrementSparseEnumCounter(ssl_counter_type,
5619 ssl_cipher_suite);
5620 }
5621}
5622
5623void PeerConnection::OnSentPacket_w(const rtc::SentPacket& sent_packet) {
5624 RTC_DCHECK(worker_thread()->IsCurrent());
5625 RTC_DCHECK(call_);
5626 call_->OnSentPacket(sent_packet);
5627}
5628
5629const std::string PeerConnection::GetTransportName(
5630 const std::string& content_name) {
5631 cricket::BaseChannel* channel = GetChannel(content_name);
Steve Anton6fec8802017-12-04 10:37:29 -08005632 if (channel) {
5633 return channel->transport_name();
Steve Anton75737c02017-11-06 10:37:17 -08005634 }
Steve Anton6fec8802017-12-04 10:37:29 -08005635 if (sctp_transport_) {
5636 RTC_DCHECK(sctp_content_name_);
5637 RTC_DCHECK(sctp_transport_name_);
5638 if (content_name == *sctp_content_name_) {
5639 return *sctp_transport_name_;
5640 }
5641 }
5642 // Return an empty string if failed to retrieve the transport name.
5643 return "";
Steve Anton75737c02017-11-06 10:37:17 -08005644}
5645
5646void PeerConnection::DestroyRtcpTransport_n(const std::string& transport_name) {
5647 RTC_DCHECK(network_thread()->IsCurrent());
5648 transport_controller_->DestroyDtlsTransport_n(
5649 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
5650}
5651
Steve Anton6fec8802017-12-04 10:37:29 -08005652void PeerConnection::DestroyTransceiverChannel(
5653 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
5654 transceiver) {
5655 RTC_DCHECK(transceiver);
Steve Anton75737c02017-11-06 10:37:17 -08005656
Steve Anton6fec8802017-12-04 10:37:29 -08005657 cricket::BaseChannel* channel = transceiver->internal()->channel();
5658 if (channel) {
5659 transceiver->internal()->SetChannel(nullptr);
5660 DestroyBaseChannel(channel);
Steve Anton75737c02017-11-06 10:37:17 -08005661 }
5662}
5663
5664void PeerConnection::DestroyDataChannel() {
Steve Anton6fec8802017-12-04 10:37:29 -08005665 if (rtp_data_channel_) {
5666 OnDataChannelDestroyed();
5667 DestroyBaseChannel(rtp_data_channel_);
5668 rtp_data_channel_ = nullptr;
5669 }
5670
5671 // Note: Cannot use rtc::Bind to create a functor to invoke because it will
5672 // grab a reference to this PeerConnection. If this is called from the
5673 // PeerConnection destructor, the RefCountedObject vtable will have already
5674 // been destroyed (since it is a subclass of PeerConnection) and using
5675 // rtc::Bind will cause "Pure virtual function called" error to appear.
5676
5677 if (sctp_transport_) {
5678 OnDataChannelDestroyed();
5679 network_thread()->Invoke<void>(RTC_FROM_HERE,
5680 [this] { DestroySctpTransport_n(); });
5681 }
5682}
5683
5684void PeerConnection::DestroyBaseChannel(cricket::BaseChannel* channel) {
5685 RTC_DCHECK(channel);
5686 RTC_DCHECK(channel->rtp_dtls_transport());
5687
5688 // Need to cache these before destroying the base channel so that we do not
5689 // access uninitialized memory.
5690 const std::string transport_name =
5691 channel->rtp_dtls_transport()->transport_name();
5692 const bool need_to_delete_rtcp = (channel->rtcp_dtls_transport() != nullptr);
5693
5694 switch (channel->media_type()) {
5695 case cricket::MEDIA_TYPE_AUDIO:
5696 channel_manager()->DestroyVoiceChannel(
5697 static_cast<cricket::VoiceChannel*>(channel));
5698 break;
5699 case cricket::MEDIA_TYPE_VIDEO:
5700 channel_manager()->DestroyVideoChannel(
5701 static_cast<cricket::VideoChannel*>(channel));
5702 break;
5703 case cricket::MEDIA_TYPE_DATA:
5704 channel_manager()->DestroyRtpDataChannel(
5705 static_cast<cricket::RtpDataChannel*>(channel));
5706 break;
5707 default:
5708 RTC_NOTREACHED() << "Unknown media type: " << channel->media_type();
5709 break;
5710 }
5711
5712 // |channel| can no longer be used.
5713
Steve Anton75737c02017-11-06 10:37:17 -08005714 transport_controller_->DestroyDtlsTransport(
5715 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5716 if (need_to_delete_rtcp) {
5717 transport_controller_->DestroyDtlsTransport(
5718 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
5719 }
5720}
5721
Harald Alvestrand89061872018-01-02 14:08:34 +01005722void PeerConnection::ClearStatsCache() {
5723 if (stats_collector_) {
5724 stats_collector_->ClearCachedStatsReport();
5725 }
5726}
5727
henrike@webrtc.org28e20752013-07-10 00:45:36 +00005728} // namespace webrtc