blob: 07e326d21949f858f4b8719c596f72cc7c3e1ed8 [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
Taylor Brandstetter94d8cce2018-01-26 22:44:21 +00001603 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
Taylor Brandstetter94d8cce2018-01-26 22:44:21 +00001610 if (remote_description() &&
1611 remote_description()->GetType() != SdpType::kOffer) {
1612 std::string error = "CreateAnswer called without remote offer.";
1613 RTC_LOG(LS_ERROR) << error;
1614 PostCreateSessionDescriptionFailure(observer, error);
1615 return;
1616 }
Steve Anton8d3444d2017-10-20 15:30:51 -07001617
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();
Steve Antondcc3c022017-12-22 16:02:54 -08002193 RTCError error =
2194 UpdateTransceiverChannel(transceiver, new_content, bundle_group);
2195 if (!error.ok()) {
2196 return error;
2197 }
2198 } else if (media_type == cricket::MEDIA_TYPE_DATA) {
Steve Antonfa2260d2017-12-28 16:38:23 -08002199 if (GetDataMid() && new_content.name != *GetDataMid()) {
2200 // Ignore all but the first data section.
2201 continue;
2202 }
2203 RTCError error = UpdateDataChannel(source, new_content, bundle_group);
2204 if (!error.ok()) {
2205 return error;
2206 }
Steve Antondcc3c022017-12-22 16:02:54 -08002207 } else {
2208 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
2209 "Unknown section type.");
2210 }
2211 }
2212
2213 return RTCError::OK();
2214}
2215
2216RTCError PeerConnection::UpdateTransceiverChannel(
2217 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2218 transceiver,
2219 const cricket::ContentInfo& content,
2220 const cricket::ContentGroup* bundle_group) {
2221 RTC_DCHECK(IsUnifiedPlan());
2222 RTC_DCHECK(transceiver);
2223 cricket::BaseChannel* channel = transceiver->internal()->channel();
2224 if (content.rejected) {
2225 if (channel) {
2226 transceiver->internal()->SetChannel(nullptr);
2227 DestroyBaseChannel(channel);
2228 }
2229 } else {
2230 if (!channel) {
2231 if (transceiver->internal()->media_type() == cricket::MEDIA_TYPE_AUDIO) {
2232 channel = CreateVoiceChannel(
2233 content.name,
2234 GetTransportNameForMediaSection(content.name, bundle_group));
2235 } else {
2236 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO,
2237 transceiver->internal()->media_type());
2238 channel = CreateVideoChannel(
2239 content.name,
2240 GetTransportNameForMediaSection(content.name, bundle_group));
2241 }
2242 if (!channel) {
2243 LOG_AND_RETURN_ERROR(
2244 RTCErrorType::INTERNAL_ERROR,
2245 "Failed to create channel for mid=" + content.name);
2246 }
2247 transceiver->internal()->SetChannel(channel);
2248 }
2249 }
2250 return RTCError::OK();
2251}
2252
Steve Antonfa2260d2017-12-28 16:38:23 -08002253RTCError PeerConnection::UpdateDataChannel(
2254 cricket::ContentSource source,
2255 const cricket::ContentInfo& content,
2256 const cricket::ContentGroup* bundle_group) {
2257 if (data_channel_type_ == cricket::DCT_NONE) {
Steve Antondbf9d032018-01-19 15:23:40 -08002258 // If data channels are disabled, ignore this media section. CreateAnswer
2259 // will take care of rejecting it.
2260 return RTCError::OK();
Steve Antonfa2260d2017-12-28 16:38:23 -08002261 }
2262 if (content.rejected) {
2263 DestroyDataChannel();
2264 } else {
2265 if (!rtp_data_channel_ && !sctp_transport_) {
2266 if (!CreateDataChannel(content.name, GetTransportNameForMediaSection(
2267 content.name, bundle_group))) {
2268 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
2269 "Failed to create data channel.");
2270 }
2271 }
2272 if (source == cricket::CS_REMOTE) {
2273 const MediaContentDescription* data_desc = content.media_description();
2274 if (data_desc && cricket::IsRtpProtocol(data_desc->protocol())) {
2275 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
2276 }
2277 }
2278 }
2279 return RTCError::OK();
2280}
2281
Steve Antondcc3c022017-12-22 16:02:54 -08002282RTCErrorOr<rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
2283PeerConnection::AssociateTransceiver(cricket::ContentSource source,
2284 size_t mline_index,
2285 const ContentInfo& content,
2286 const ContentInfo* old_content) {
2287 RTC_DCHECK(IsUnifiedPlan());
2288 // If the m= section is being recycled (rejected in previous remote
2289 // description, not rejected in current description), dissociate the currently
2290 // associated RtpTransceiver by setting its mid property to null, and discard
2291 // the mapping between the transceiver and its m= section index.
2292 if (old_content && old_content->rejected && !content.rejected) {
2293 auto old_transceiver = GetAssociatedTransceiver(old_content->name);
2294 if (old_transceiver) {
2295 old_transceiver->internal()->set_mid(rtc::nullopt);
2296 old_transceiver->internal()->set_mline_index(rtc::nullopt);
2297 }
2298 }
2299 const MediaContentDescription* media_desc = content.media_description();
2300 auto transceiver = GetAssociatedTransceiver(content.name);
2301 if (source == cricket::CS_LOCAL) {
2302 // Find the RtpTransceiver that corresponds to this m= section, using the
2303 // mapping between transceivers and m= section indices established when
2304 // creating the offer.
2305 if (!transceiver) {
2306 transceiver = GetTransceiverByMLineIndex(mline_index);
2307 }
2308 if (!transceiver) {
2309 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2310 "Unknown transceiver");
2311 }
2312 } else {
2313 RTC_DCHECK_EQ(source, cricket::CS_REMOTE);
2314 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers
2315 // of the same type...
2316 if (!transceiver &&
2317 RtpTransceiverDirectionHasRecv(media_desc->direction())) {
2318 transceiver = FindAvailableTransceiverToReceive(media_desc->type());
2319 }
2320 // If no RtpTransceiver was found in the previous step, create one with a
2321 // recvonly direction.
2322 if (!transceiver) {
Steve Anton02ee47c2018-01-10 16:26:06 -08002323 auto sender =
2324 CreateSender(media_desc->type(), nullptr, {rtc::CreateRandomUuid()});
2325 auto receiver =
2326 CreateReceiver(media_desc->type(), media_desc->streams()[0].id);
2327 transceiver = CreateAndAddTransceiver(sender, receiver);
Steve Antondcc3c022017-12-22 16:02:54 -08002328 transceiver->internal()->set_direction(
2329 RtpTransceiverDirection::kRecvOnly);
2330 }
2331 }
2332 RTC_DCHECK(transceiver);
2333 if (transceiver->internal()->media_type() != media_desc->type()) {
2334 LOG_AND_RETURN_ERROR(
2335 RTCErrorType::INVALID_PARAMETER,
2336 "Transceiver type does not match media description type.");
2337 }
2338 // Associate the found or created RtpTransceiver with the m= section by
2339 // setting the value of the RtpTransceiver's mid property to the MID of the m=
2340 // section, and establish a mapping between the transceiver and the index of
2341 // the m= section.
2342 transceiver->internal()->set_mid(content.name);
2343 transceiver->internal()->set_mline_index(mline_index);
2344 return std::move(transceiver);
2345}
2346
2347rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2348PeerConnection::GetAssociatedTransceiver(const std::string& mid) const {
2349 RTC_DCHECK(IsUnifiedPlan());
2350 for (auto transceiver : transceivers_) {
2351 if (transceiver->mid() == mid) {
2352 return transceiver;
2353 }
2354 }
2355 return nullptr;
2356}
2357
2358rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2359PeerConnection::GetTransceiverByMLineIndex(size_t mline_index) const {
2360 RTC_DCHECK(IsUnifiedPlan());
2361 for (auto transceiver : transceivers_) {
2362 if (transceiver->internal()->mline_index() == mline_index) {
2363 return transceiver;
2364 }
2365 }
2366 return nullptr;
2367}
2368
2369rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2370PeerConnection::FindAvailableTransceiverToReceive(
2371 cricket::MediaType media_type) const {
2372 RTC_DCHECK(IsUnifiedPlan());
2373 // From JSEP section 5.10 (Applying a Remote Description):
2374 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers of
2375 // the same type that were added to the PeerConnection by addTrack and are not
2376 // associated with any m= section and are not stopped, find the first such
2377 // RtpTransceiver.
2378 for (auto transceiver : transceivers_) {
2379 if (transceiver->internal()->media_type() == media_type &&
2380 transceiver->internal()->created_by_addtrack() && !transceiver->mid() &&
2381 !transceiver->stopped()) {
2382 return transceiver;
2383 }
2384 }
2385 return nullptr;
2386}
2387
Steve Antoned10bd92017-12-05 10:52:59 -08002388const cricket::ContentInfo* PeerConnection::FindMediaSectionForTransceiver(
2389 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2390 transceiver,
2391 const SessionDescriptionInterface* sdesc) const {
2392 RTC_DCHECK(transceiver);
2393 RTC_DCHECK(sdesc);
2394 if (IsUnifiedPlan()) {
2395 if (!transceiver->internal()->mid()) {
2396 // This transceiver is not associated with a media section yet.
2397 return nullptr;
2398 }
2399 return sdesc->description()->GetContentByName(
2400 *transceiver->internal()->mid());
2401 } else {
2402 // Plan B only allows at most one audio and one video section, so use the
2403 // first media section of that type.
2404 return cricket::GetFirstMediaContent(sdesc->description()->contents(),
2405 transceiver->internal()->media_type());
2406 }
2407}
2408
deadbeef46c73892016-11-16 19:42:04 -08002409PeerConnectionInterface::RTCConfiguration PeerConnection::GetConfiguration() {
2410 return configuration_;
2411}
2412
deadbeef293e9262017-01-11 12:28:30 -08002413bool PeerConnection::SetConfiguration(const RTCConfiguration& configuration,
2414 RTCError* error) {
Peter Boström1a9d6152015-12-08 22:15:17 +01002415 TRACE_EVENT0("webrtc", "PeerConnection::SetConfiguration");
deadbeef6de92f92016-12-12 18:49:32 -08002416
Steve Anton75737c02017-11-06 10:37:17 -08002417 if (local_description() && configuration.ice_candidate_pool_size !=
2418 configuration_.ice_candidate_pool_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002419 RTC_LOG(LS_ERROR) << "Can't change candidate pool size after calling "
2420 "SetLocalDescription.";
deadbeef293e9262017-01-11 12:28:30 -08002421 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00002422 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002423
deadbeef293e9262017-01-11 12:28:30 -08002424 // The simplest (and most future-compatible) way to tell if the config was
2425 // modified in an invalid way is to copy each property we do support
2426 // modifying, then use operator==. There are far more properties we don't
2427 // support modifying than those we do, and more could be added.
2428 RTCConfiguration modified_config = configuration_;
2429 modified_config.servers = configuration.servers;
2430 modified_config.type = configuration.type;
2431 modified_config.ice_candidate_pool_size =
2432 configuration.ice_candidate_pool_size;
2433 modified_config.prune_turn_ports = configuration.prune_turn_ports;
skvladd1f5fda2017-02-03 16:54:05 -08002434 modified_config.ice_check_min_interval = configuration.ice_check_min_interval;
Jonas Orelandbdcee282017-10-10 14:01:40 +02002435 modified_config.turn_customizer = configuration.turn_customizer;
deadbeef293e9262017-01-11 12:28:30 -08002436 if (configuration != modified_config) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002437 RTC_LOG(LS_ERROR) << "Modifying the configuration in an unsupported way.";
deadbeef293e9262017-01-11 12:28:30 -08002438 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
2439 }
2440
Steve Anton038834f2017-07-14 15:59:59 -07002441 // Validate the modified configuration.
2442 RTCError validate_error = ValidateConfiguration(modified_config);
2443 if (!validate_error.ok()) {
2444 return SafeSetError(std::move(validate_error), error);
2445 }
2446
deadbeef293e9262017-01-11 12:28:30 -08002447 // Note that this isn't possible through chromium, since it's an unsigned
2448 // short in WebIDL.
2449 if (configuration.ice_candidate_pool_size < 0 ||
2450 configuration.ice_candidate_pool_size > UINT16_MAX) {
2451 return SafeSetError(RTCErrorType::INVALID_RANGE, error);
2452 }
2453
2454 // Parse ICE servers before hopping to network thread.
2455 cricket::ServerAddresses stun_servers;
2456 std::vector<cricket::RelayServerConfig> turn_servers;
2457 RTCErrorType parse_error =
2458 ParseIceServers(configuration.servers, &stun_servers, &turn_servers);
2459 if (parse_error != RTCErrorType::NONE) {
2460 return SafeSetError(parse_error, error);
2461 }
2462
2463 // In theory this shouldn't fail.
2464 if (!network_thread()->Invoke<bool>(
2465 RTC_FROM_HERE,
2466 rtc::Bind(&PeerConnection::ReconfigurePortAllocator_n, this,
2467 stun_servers, turn_servers, modified_config.type,
2468 modified_config.ice_candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02002469 modified_config.prune_turn_ports,
2470 modified_config.turn_customizer))) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002471 RTC_LOG(LS_ERROR) << "Failed to apply configuration to PortAllocator.";
deadbeef293e9262017-01-11 12:28:30 -08002472 return SafeSetError(RTCErrorType::INTERNAL_ERROR, error);
2473 }
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07002474
deadbeefd1a38b52016-12-10 13:15:33 -08002475 // As described in JSEP, calling setConfiguration with new ICE servers or
2476 // candidate policy must set a "needs-ice-restart" bit so that the next offer
2477 // triggers an ICE restart which will pick up the changes.
deadbeef293e9262017-01-11 12:28:30 -08002478 if (modified_config.servers != configuration_.servers ||
2479 modified_config.type != configuration_.type ||
2480 modified_config.prune_turn_ports != configuration_.prune_turn_ports) {
Steve Antond25da372017-11-06 14:50:29 -08002481 transport_controller_->SetNeedsIceRestartFlag();
deadbeefd1a38b52016-12-10 13:15:33 -08002482 }
skvladd1f5fda2017-02-03 16:54:05 -08002483
2484 if (modified_config.ice_check_min_interval !=
2485 configuration_.ice_check_min_interval) {
Steve Antond25da372017-11-06 14:50:29 -08002486 transport_controller_->SetIceConfig(ParseIceConfig(modified_config));
skvladd1f5fda2017-02-03 16:54:05 -08002487 }
2488
deadbeef293e9262017-01-11 12:28:30 -08002489 configuration_ = modified_config;
2490 return SafeSetError(RTCErrorType::NONE, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00002491}
2492
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002493bool PeerConnection::AddIceCandidate(
2494 const IceCandidateInterface* ice_candidate) {
Peter Boström1a9d6152015-12-08 22:15:17 +01002495 TRACE_EVENT0("webrtc", "PeerConnection::AddIceCandidate");
zhihuang29ff8442016-07-27 11:07:25 -07002496 if (IsClosed()) {
2497 return false;
2498 }
Steve Antond25da372017-11-06 14:50:29 -08002499
2500 if (!remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002501 RTC_LOG(LS_ERROR) << "ProcessIceMessage: ICE candidates can't be added "
2502 << "without any remote session description.";
Steve Antond25da372017-11-06 14:50:29 -08002503 return false;
2504 }
2505
2506 if (!ice_candidate) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002507 RTC_LOG(LS_ERROR) << "ProcessIceMessage: Candidate is NULL.";
Steve Antond25da372017-11-06 14:50:29 -08002508 return false;
2509 }
2510
2511 bool valid = false;
2512 bool ready = ReadyToUseRemoteCandidate(ice_candidate, nullptr, &valid);
2513 if (!valid) {
2514 return false;
2515 }
2516
2517 // Add this candidate to the remote session description.
2518 if (!mutable_remote_description()->AddCandidate(ice_candidate)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002519 RTC_LOG(LS_ERROR) << "ProcessIceMessage: Candidate cannot be used.";
Steve Antond25da372017-11-06 14:50:29 -08002520 return false;
2521 }
2522
2523 if (ready) {
2524 return UseCandidate(ice_candidate);
2525 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002526 RTC_LOG(LS_INFO) << "ProcessIceMessage: Not ready to use candidate.";
Steve Antond25da372017-11-06 14:50:29 -08002527 return true;
2528 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002529}
2530
Honghai Zhang7fb69db2016-03-14 11:59:18 -07002531bool PeerConnection::RemoveIceCandidates(
2532 const std::vector<cricket::Candidate>& candidates) {
2533 TRACE_EVENT0("webrtc", "PeerConnection::RemoveIceCandidates");
Steve Antond25da372017-11-06 14:50:29 -08002534 if (!remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002535 RTC_LOG(LS_ERROR) << "RemoveRemoteIceCandidates: ICE candidates can't be "
2536 << "removed without any remote session description.";
Steve Antond25da372017-11-06 14:50:29 -08002537 return false;
2538 }
2539
2540 if (candidates.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002541 RTC_LOG(LS_ERROR) << "RemoveRemoteIceCandidates: candidates are empty.";
Steve Antond25da372017-11-06 14:50:29 -08002542 return false;
2543 }
2544
2545 size_t number_removed =
2546 mutable_remote_description()->RemoveCandidates(candidates);
2547 if (number_removed != candidates.size()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002548 RTC_LOG(LS_ERROR)
2549 << "RemoveRemoteIceCandidates: Failed to remove candidates. "
2550 << "Requested " << candidates.size() << " but only " << number_removed
2551 << " are removed.";
Steve Antond25da372017-11-06 14:50:29 -08002552 }
2553
2554 // Remove the candidates from the transport controller.
2555 std::string error;
2556 bool res = transport_controller_->RemoveRemoteCandidates(candidates, &error);
2557 if (!res && !error.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002558 RTC_LOG(LS_ERROR) << "Error when removing remote candidates: " << error;
Steve Antond25da372017-11-06 14:50:29 -08002559 }
2560 return true;
Honghai Zhang7fb69db2016-03-14 11:59:18 -07002561}
2562
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00002563void PeerConnection::RegisterUMAObserver(UMAObserver* observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +01002564 TRACE_EVENT0("webrtc", "PeerConnection::RegisterUmaObserver");
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00002565 uma_observer_ = observer;
guoweis@webrtc.org7169afd2014-12-04 17:59:29 +00002566
Steve Anton75737c02017-11-06 10:37:17 -08002567 if (transport_controller()) {
2568 transport_controller()->SetMetricsObserver(uma_observer_);
guoweis@webrtc.org7169afd2014-12-04 17:59:29 +00002569 }
2570
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00002571 // Send information about IPv4/IPv6 status.
deadbeef293e9262017-01-11 12:28:30 -08002572 if (uma_observer_) {
Honghai Zhangd93f50c2016-10-05 11:47:22 -07002573 port_allocator_->SetMetricsObserver(uma_observer_);
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00002574 if (port_allocator_->flags() & cricket::PORTALLOCATOR_ENABLE_IPV6) {
Guo-wei Shiehdfbe6792015-09-03 17:12:07 -07002575 uma_observer_->IncrementEnumCounter(
2576 kEnumCounterAddressFamily, kPeerConnection_IPv6,
2577 kPeerConnectionAddressFamilyCounter_Max);
mallinath@webrtc.orgb445f262014-05-23 22:19:37 +00002578 } else {
Guo-wei Shiehdfbe6792015-09-03 17:12:07 -07002579 uma_observer_->IncrementEnumCounter(
2580 kEnumCounterAddressFamily, kPeerConnection_IPv4,
2581 kPeerConnectionAddressFamilyCounter_Max);
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00002582 }
2583 }
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00002584}
2585
zstein4b979802017-06-02 14:37:37 -07002586RTCError PeerConnection::SetBitrate(const BitrateParameters& bitrate) {
Steve Anton978b8762017-09-29 12:15:02 -07002587 if (!worker_thread()->IsCurrent()) {
2588 return worker_thread()->Invoke<RTCError>(
zstein4b979802017-06-02 14:37:37 -07002589 RTC_FROM_HERE, rtc::Bind(&PeerConnection::SetBitrate, this, bitrate));
2590 }
2591
2592 const bool has_min = static_cast<bool>(bitrate.min_bitrate_bps);
2593 const bool has_current = static_cast<bool>(bitrate.current_bitrate_bps);
2594 const bool has_max = static_cast<bool>(bitrate.max_bitrate_bps);
2595 if (has_min && *bitrate.min_bitrate_bps < 0) {
2596 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2597 "min_bitrate_bps <= 0");
2598 }
2599 if (has_current) {
2600 if (has_min && *bitrate.current_bitrate_bps < *bitrate.min_bitrate_bps) {
2601 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2602 "current_bitrate_bps < min_bitrate_bps");
2603 } else if (*bitrate.current_bitrate_bps < 0) {
2604 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2605 "curent_bitrate_bps < 0");
2606 }
2607 }
2608 if (has_max) {
2609 if (has_current &&
2610 *bitrate.max_bitrate_bps < *bitrate.current_bitrate_bps) {
2611 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2612 "max_bitrate_bps < current_bitrate_bps");
2613 } else if (has_min && *bitrate.max_bitrate_bps < *bitrate.min_bitrate_bps) {
2614 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2615 "max_bitrate_bps < min_bitrate_bps");
2616 } else if (*bitrate.max_bitrate_bps < 0) {
2617 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2618 "max_bitrate_bps < 0");
2619 }
2620 }
2621
2622 Call::Config::BitrateConfigMask mask;
2623 mask.min_bitrate_bps = bitrate.min_bitrate_bps;
2624 mask.start_bitrate_bps = bitrate.current_bitrate_bps;
2625 mask.max_bitrate_bps = bitrate.max_bitrate_bps;
2626
2627 RTC_DCHECK(call_.get());
2628 call_->SetBitrateConfigMask(mask);
2629
2630 return RTCError::OK();
2631}
2632
Alex Narest78609d52017-10-20 10:37:47 +02002633void PeerConnection::SetBitrateAllocationStrategy(
2634 std::unique_ptr<rtc::BitrateAllocationStrategy>
2635 bitrate_allocation_strategy) {
2636 rtc::Thread* worker_thread = factory_->worker_thread();
2637 if (!worker_thread->IsCurrent()) {
2638 rtc::BitrateAllocationStrategy* strategy_raw =
2639 bitrate_allocation_strategy.release();
2640 auto functor = [this, strategy_raw]() {
2641 call_->SetBitrateAllocationStrategy(
2642 rtc::WrapUnique<rtc::BitrateAllocationStrategy>(strategy_raw));
2643 };
2644 worker_thread->Invoke<void>(RTC_FROM_HERE, functor);
2645 return;
2646 }
2647 RTC_DCHECK(call_.get());
2648 call_->SetBitrateAllocationStrategy(std::move(bitrate_allocation_strategy));
2649}
2650
henrika5f6bf242017-11-01 11:06:56 +01002651void PeerConnection::SetAudioPlayout(bool playout) {
2652 if (!worker_thread()->IsCurrent()) {
2653 worker_thread()->Invoke<void>(
2654 RTC_FROM_HERE,
2655 rtc::Bind(&PeerConnection::SetAudioPlayout, this, playout));
2656 return;
2657 }
2658 auto audio_state =
2659 factory_->channel_manager()->media_engine()->GetAudioState();
2660 audio_state->SetPlayout(playout);
2661}
2662
2663void PeerConnection::SetAudioRecording(bool recording) {
2664 if (!worker_thread()->IsCurrent()) {
2665 worker_thread()->Invoke<void>(
2666 RTC_FROM_HERE,
2667 rtc::Bind(&PeerConnection::SetAudioRecording, this, recording));
2668 return;
2669 }
2670 auto audio_state =
2671 factory_->channel_manager()->media_engine()->GetAudioState();
2672 audio_state->SetRecording(recording);
2673}
2674
Steve Anton8c0f7a72017-10-03 10:03:10 -07002675std::unique_ptr<rtc::SSLCertificate>
2676PeerConnection::GetRemoteAudioSSLCertificate() {
Steve Anton75737c02017-11-06 10:37:17 -08002677 if (!voice_channel()) {
Steve Anton8c0f7a72017-10-03 10:03:10 -07002678 return nullptr;
2679 }
Steve Anton75737c02017-11-06 10:37:17 -08002680 return GetRemoteSSLCertificate(voice_channel()->transport_name());
Steve Anton8c0f7a72017-10-03 10:03:10 -07002681}
2682
ivoc14d5dbe2016-07-04 07:06:55 -07002683bool PeerConnection::StartRtcEventLog(rtc::PlatformFile file,
2684 int64_t max_size_bytes) {
Elad Alon99c3fe52017-10-13 16:29:40 +02002685 // TODO(eladalon): It would be better to not allow negative values into PC.
2686 const size_t max_size = (max_size_bytes < 0)
2687 ? RtcEventLog::kUnlimitedOutput
2688 : rtc::saturated_cast<size_t>(max_size_bytes);
2689 return StartRtcEventLog(
Bjorn Tereliusde939432017-11-20 17:38:14 +01002690 rtc::MakeUnique<RtcEventLogOutputFile>(file, max_size),
2691 webrtc::RtcEventLog::kImmediateOutput);
Elad Alon99c3fe52017-10-13 16:29:40 +02002692}
2693
Bjorn Tereliusde939432017-11-20 17:38:14 +01002694bool PeerConnection::StartRtcEventLog(std::unique_ptr<RtcEventLogOutput> output,
2695 int64_t output_period_ms) {
Karl Wibergd6b48192017-10-16 23:01:06 +02002696 // TODO(eladalon): In C++14, this can be done with a lambda.
2697 struct Functor {
Bjorn Tereliusde939432017-11-20 17:38:14 +01002698 bool operator()() {
2699 return pc->StartRtcEventLog_w(std::move(output), output_period_ms);
2700 }
Karl Wibergd6b48192017-10-16 23:01:06 +02002701 PeerConnection* const pc;
2702 std::unique_ptr<RtcEventLogOutput> output;
Bjorn Tereliusde939432017-11-20 17:38:14 +01002703 const int64_t output_period_ms;
Elad Alon99c3fe52017-10-13 16:29:40 +02002704 };
Bjorn Tereliusde939432017-11-20 17:38:14 +01002705 return worker_thread()->Invoke<bool>(
2706 RTC_FROM_HERE, Functor{this, std::move(output), output_period_ms});
ivoc14d5dbe2016-07-04 07:06:55 -07002707}
2708
2709void PeerConnection::StopRtcEventLog() {
Steve Anton978b8762017-09-29 12:15:02 -07002710 worker_thread()->Invoke<void>(
ivoc14d5dbe2016-07-04 07:06:55 -07002711 RTC_FROM_HERE, rtc::Bind(&PeerConnection::StopRtcEventLog_w, this));
2712}
2713
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002714const SessionDescriptionInterface* PeerConnection::local_description() const {
Steve Anton75737c02017-11-06 10:37:17 -08002715 return pending_local_description_ ? pending_local_description_.get()
2716 : current_local_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002717}
2718
2719const SessionDescriptionInterface* PeerConnection::remote_description() const {
Steve Anton75737c02017-11-06 10:37:17 -08002720 return pending_remote_description_ ? pending_remote_description_.get()
2721 : current_remote_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002722}
2723
deadbeeffe4a8a42016-12-20 17:56:17 -08002724const SessionDescriptionInterface* PeerConnection::current_local_description()
2725 const {
Steve Anton75737c02017-11-06 10:37:17 -08002726 return current_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08002727}
2728
2729const SessionDescriptionInterface* PeerConnection::current_remote_description()
2730 const {
Steve Anton75737c02017-11-06 10:37:17 -08002731 return current_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08002732}
2733
2734const SessionDescriptionInterface* PeerConnection::pending_local_description()
2735 const {
Steve Anton75737c02017-11-06 10:37:17 -08002736 return pending_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08002737}
2738
2739const SessionDescriptionInterface* PeerConnection::pending_remote_description()
2740 const {
Steve Anton75737c02017-11-06 10:37:17 -08002741 return pending_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08002742}
2743
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002744void PeerConnection::Close() {
Peter Boström1a9d6152015-12-08 22:15:17 +01002745 TRACE_EVENT0("webrtc", "PeerConnection::Close");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002746 // Update stats here so that we have the most recent stats for tracks and
2747 // streams before the channels are closed.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00002748 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002749
Steve Anton75737c02017-11-06 10:37:17 -08002750 ChangeSignalingState(PeerConnectionInterface::kClosed);
Steve Anton3fe1b152017-12-12 10:20:08 -08002751
Steve Anton8af21862017-12-15 11:20:13 -08002752 for (auto transceiver : transceivers_) {
2753 transceiver->Stop();
2754 }
2755 DestroyAllChannels();
Steve Anton75737c02017-11-06 10:37:17 -08002756
deadbeef42a42632017-03-10 15:18:00 -08002757 network_thread()->Invoke<void>(
2758 RTC_FROM_HERE,
2759 rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
2760 port_allocator_.get()));
nisseeaabdf62017-05-05 02:23:02 -07002761
Steve Anton978b8762017-09-29 12:15:02 -07002762 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
eladalon248fd4f2017-09-06 05:18:15 -07002763 call_.reset();
2764 // The event log must outlive call (and any other object that uses it).
2765 event_log_.reset();
2766 });
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002767}
2768
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002769void PeerConnection::OnMessage(rtc::Message* msg) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002770 switch (msg->message_id) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002771 case MSG_SET_SESSIONDESCRIPTION_SUCCESS: {
2772 SetSessionDescriptionMsg* param =
2773 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
2774 param->observer->OnSuccess();
2775 delete param;
2776 break;
2777 }
2778 case MSG_SET_SESSIONDESCRIPTION_FAILED: {
2779 SetSessionDescriptionMsg* param =
2780 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
2781 param->observer->OnFailure(param->error);
2782 delete param;
2783 break;
2784 }
deadbeefab9b2d12015-10-14 11:33:11 -07002785 case MSG_CREATE_SESSIONDESCRIPTION_FAILED: {
2786 CreateSessionDescriptionMsg* param =
2787 static_cast<CreateSessionDescriptionMsg*>(msg->pdata);
2788 param->observer->OnFailure(param->error);
2789 delete param;
2790 break;
2791 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002792 case MSG_GETSTATS: {
2793 GetStatsMsg* param = static_cast<GetStatsMsg*>(msg->pdata);
nissee8abe3e2017-01-18 05:00:34 -08002794 StatsReports reports;
2795 stats_->GetStats(param->track, &reports);
2796 param->observer->OnComplete(reports);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002797 delete param;
2798 break;
2799 }
deadbeefbd292462015-12-14 18:15:29 -08002800 case MSG_FREE_DATACHANNELS: {
2801 sctp_data_channels_to_free_.clear();
2802 break;
2803 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002804 default:
nisseeb4ca4e2017-01-12 02:24:27 -08002805 RTC_NOTREACHED() << "Not implemented";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002806 break;
2807 }
2808}
2809
Steve Anton4171afb2017-11-20 10:20:22 -08002810void PeerConnection::CreateAudioReceiver(
2811 MediaStreamInterface* stream,
2812 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01002813 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
2814 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Steve Antond3679212018-01-17 17:41:02 -08002815 auto* audio_receiver = new AudioRtpReceiver(
2816 worker_thread(), remote_sender_info.sender_id, streams);
2817 audio_receiver->SetMediaChannel(voice_media_channel());
2818 audio_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
2819 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
2820 signaling_thread(), audio_receiver);
Steve Anton4171afb2017-11-20 10:20:22 -08002821 GetAudioTransceiver()->internal()->AddReceiver(receiver);
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01002822 observer_->OnAddTrack(receiver, std::move(streams));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002823}
2824
Steve Anton4171afb2017-11-20 10:20:22 -08002825void PeerConnection::CreateVideoReceiver(
2826 MediaStreamInterface* stream,
2827 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01002828 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
2829 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Steve Antond3679212018-01-17 17:41:02 -08002830 auto* video_receiver = new VideoRtpReceiver(
2831 worker_thread(), remote_sender_info.sender_id, streams);
2832 video_receiver->SetMediaChannel(video_media_channel());
2833 video_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
2834 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
2835 signaling_thread(), video_receiver);
Steve Anton4171afb2017-11-20 10:20:22 -08002836 GetVideoTransceiver()->internal()->AddReceiver(receiver);
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01002837 observer_->OnAddTrack(receiver, std::move(streams));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002838}
2839
deadbeef70ab1a12015-09-28 16:53:55 -07002840// TODO(deadbeef): Keep RtpReceivers around even if track goes away in remote
2841// description.
Henrik Boström933d8b02017-10-10 10:05:16 -07002842rtc::scoped_refptr<RtpReceiverInterface> PeerConnection::RemoveAndStopReceiver(
Steve Anton4171afb2017-11-20 10:20:22 -08002843 const RtpSenderInfo& remote_sender_info) {
2844 auto receiver = FindReceiverById(remote_sender_info.sender_id);
2845 if (!receiver) {
2846 RTC_LOG(LS_WARNING) << "RtpReceiver for track with id "
2847 << remote_sender_info.sender_id << " doesn't exist.";
Henrik Boström933d8b02017-10-10 10:05:16 -07002848 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07002849 }
Steve Anton4171afb2017-11-20 10:20:22 -08002850 if (receiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
2851 GetAudioTransceiver()->internal()->RemoveReceiver(receiver);
2852 } else {
2853 GetVideoTransceiver()->internal()->RemoveReceiver(receiver);
2854 }
Henrik Boström933d8b02017-10-10 10:05:16 -07002855 return receiver;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002856}
2857
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002858void PeerConnection::AddAudioTrack(AudioTrackInterface* track,
2859 MediaStreamInterface* stream) {
2860 RTC_DCHECK(!IsClosed());
2861 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08002862 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002863 // We already have a sender for this track, so just change the stream_id
2864 // so that it's correct in the next call to CreateOffer.
Steve Anton4171afb2017-11-20 10:20:22 -08002865 sender->internal()->set_stream_id(stream->label());
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002866 return;
2867 }
2868
2869 // Normal case; we've never seen this track before.
Steve Anton02ee47c2018-01-10 16:26:06 -08002870 auto new_sender =
2871 CreateSender(cricket::MEDIA_TYPE_AUDIO, track, {stream->label()});
2872 static_cast<AudioRtpSender*>(new_sender->internal())
Steve Anton47136dd2018-01-12 10:49:35 -08002873 ->SetMediaChannel(voice_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08002874 GetAudioTransceiver()->internal()->AddSender(new_sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002875 // If the sender has already been configured in SDP, we call SetSsrc,
2876 // which will connect the sender to the underlying transport. This can
2877 // occur if a local session description that contains the ID of the sender
2878 // is set before AddStream is called. It can also occur if the local
2879 // session description is not changed and RemoveStream is called, and
2880 // later AddStream is called again with the same stream.
Steve Anton4171afb2017-11-20 10:20:22 -08002881 const RtpSenderInfo* sender_info =
2882 FindSenderInfo(local_audio_sender_infos_, stream->label(), track->id());
2883 if (sender_info) {
2884 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002885 }
2886}
2887
2888// TODO(deadbeef): Don't destroy RtpSenders here; they should be kept around
2889// indefinitely, when we have unified plan SDP.
2890void PeerConnection::RemoveAudioTrack(AudioTrackInterface* track,
2891 MediaStreamInterface* stream) {
2892 RTC_DCHECK(!IsClosed());
2893 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08002894 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002895 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
2896 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002897 return;
2898 }
Steve Anton4171afb2017-11-20 10:20:22 -08002899 GetAudioTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002900}
2901
2902void PeerConnection::AddVideoTrack(VideoTrackInterface* track,
2903 MediaStreamInterface* stream) {
2904 RTC_DCHECK(!IsClosed());
2905 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08002906 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002907 // We already have a sender for this track, so just change the stream_id
2908 // so that it's correct in the next call to CreateOffer.
Steve Anton4171afb2017-11-20 10:20:22 -08002909 sender->internal()->set_stream_id(stream->label());
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002910 return;
2911 }
2912
2913 // Normal case; we've never seen this track before.
Steve Anton02ee47c2018-01-10 16:26:06 -08002914 auto new_sender =
2915 CreateSender(cricket::MEDIA_TYPE_VIDEO, track, {stream->label()});
2916 static_cast<VideoRtpSender*>(new_sender->internal())
Steve Anton47136dd2018-01-12 10:49:35 -08002917 ->SetMediaChannel(video_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08002918 GetVideoTransceiver()->internal()->AddSender(new_sender);
2919 const RtpSenderInfo* sender_info =
2920 FindSenderInfo(local_video_sender_infos_, stream->label(), track->id());
2921 if (sender_info) {
2922 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002923 }
2924}
2925
2926void PeerConnection::RemoveVideoTrack(VideoTrackInterface* track,
2927 MediaStreamInterface* stream) {
2928 RTC_DCHECK(!IsClosed());
2929 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08002930 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002931 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
2932 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002933 return;
2934 }
Steve Anton4171afb2017-11-20 10:20:22 -08002935 GetVideoTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002936}
2937
Steve Antonba818672017-11-06 10:21:57 -08002938void PeerConnection::SetIceConnectionState(IceConnectionState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07002939 RTC_DCHECK(signaling_thread()->IsCurrent());
Steve Antonba818672017-11-06 10:21:57 -08002940 if (ice_connection_state_ == new_state) {
2941 return;
2942 }
2943
deadbeefcbecd352015-09-23 11:50:27 -07002944 // After transitioning to "closed", ignore any additional states from
Steve Antonba818672017-11-06 10:21:57 -08002945 // TransportController (such as "disconnected").
deadbeefab9b2d12015-10-14 11:33:11 -07002946 if (IsClosed()) {
deadbeefcbecd352015-09-23 11:50:27 -07002947 return;
2948 }
Steve Antonba818672017-11-06 10:21:57 -08002949
Mirko Bonadei675513b2017-11-09 11:09:25 +01002950 RTC_LOG(LS_INFO) << "Changing IceConnectionState " << ice_connection_state_
2951 << " => " << new_state;
Steve Antonba818672017-11-06 10:21:57 -08002952 RTC_DCHECK(ice_connection_state_ !=
2953 PeerConnectionInterface::kIceConnectionClosed);
2954
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002955 ice_connection_state_ = new_state;
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00002956 observer_->OnIceConnectionChange(ice_connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002957}
2958
2959void PeerConnection::OnIceGatheringChange(
2960 PeerConnectionInterface::IceGatheringState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07002961 RTC_DCHECK(signaling_thread()->IsCurrent());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002962 if (IsClosed()) {
2963 return;
2964 }
2965 ice_gathering_state_ = new_state;
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00002966 observer_->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002967}
2968
jbauch81bf7b02017-03-25 08:31:12 -07002969void PeerConnection::OnIceCandidate(
2970 std::unique_ptr<IceCandidateInterface> candidate) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07002971 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07002972 if (IsClosed()) {
2973 return;
2974 }
jbauch81bf7b02017-03-25 08:31:12 -07002975 observer_->OnIceCandidate(candidate.get());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002976}
2977
Honghai Zhang7fb69db2016-03-14 11:59:18 -07002978void PeerConnection::OnIceCandidatesRemoved(
2979 const std::vector<cricket::Candidate>& candidates) {
2980 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07002981 if (IsClosed()) {
2982 return;
2983 }
Honghai Zhang7fb69db2016-03-14 11:59:18 -07002984 observer_->OnIceCandidatesRemoved(candidates);
2985}
2986
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002987void PeerConnection::ChangeSignalingState(
2988 PeerConnectionInterface::SignalingState signaling_state) {
Steve Antonba818672017-11-06 10:21:57 -08002989 RTC_DCHECK(signaling_thread()->IsCurrent());
2990 if (signaling_state_ == signaling_state) {
2991 return;
2992 }
Mirko Bonadei675513b2017-11-09 11:09:25 +01002993 RTC_LOG(LS_INFO) << "Session: " << session_id() << " Old state: "
2994 << GetSignalingStateString(signaling_state_)
2995 << " New state: "
2996 << GetSignalingStateString(signaling_state);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002997 signaling_state_ = signaling_state;
2998 if (signaling_state == kClosed) {
2999 ice_connection_state_ = kIceConnectionClosed;
3000 observer_->OnIceConnectionChange(ice_connection_state_);
3001 if (ice_gathering_state_ != kIceGatheringComplete) {
3002 ice_gathering_state_ = kIceGatheringComplete;
3003 observer_->OnIceGatheringChange(ice_gathering_state_);
3004 }
3005 }
3006 observer_->OnSignalingChange(signaling_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003007}
3008
deadbeefeb459812015-12-15 19:24:43 -08003009void PeerConnection::OnAudioTrackAdded(AudioTrackInterface* track,
3010 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003011 if (IsClosed()) {
3012 return;
3013 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003014 AddAudioTrack(track, stream);
3015 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003016}
3017
deadbeefeb459812015-12-15 19:24:43 -08003018void PeerConnection::OnAudioTrackRemoved(AudioTrackInterface* track,
3019 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003020 if (IsClosed()) {
3021 return;
3022 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003023 RemoveAudioTrack(track, stream);
3024 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003025}
3026
3027void PeerConnection::OnVideoTrackAdded(VideoTrackInterface* track,
3028 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003029 if (IsClosed()) {
3030 return;
3031 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003032 AddVideoTrack(track, stream);
3033 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003034}
3035
3036void PeerConnection::OnVideoTrackRemoved(VideoTrackInterface* track,
3037 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003038 if (IsClosed()) {
3039 return;
3040 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003041 RemoveVideoTrack(track, stream);
3042 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003043}
3044
Henrik Boström31638672017-11-23 17:48:32 +01003045void PeerConnection::PostSetSessionDescriptionSuccess(
3046 SetSessionDescriptionObserver* observer) {
3047 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
3048 signaling_thread()->Post(RTC_FROM_HERE, this,
3049 MSG_SET_SESSIONDESCRIPTION_SUCCESS, msg);
3050}
3051
deadbeefab9b2d12015-10-14 11:33:11 -07003052void PeerConnection::PostSetSessionDescriptionFailure(
3053 SetSessionDescriptionObserver* observer,
3054 const std::string& error) {
3055 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
3056 msg->error = error;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07003057 signaling_thread()->Post(RTC_FROM_HERE, this,
3058 MSG_SET_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07003059}
3060
3061void PeerConnection::PostCreateSessionDescriptionFailure(
3062 CreateSessionDescriptionObserver* observer,
3063 const std::string& error) {
3064 CreateSessionDescriptionMsg* msg = new CreateSessionDescriptionMsg(observer);
3065 msg->error = error;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07003066 signaling_thread()->Post(RTC_FROM_HERE, this,
3067 MSG_CREATE_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07003068}
3069
zhihuang1c378ed2017-08-17 14:10:50 -07003070void PeerConnection::GetOptionsForOffer(
Steve Antondcc3c022017-12-22 16:02:54 -08003071 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
deadbeefab9b2d12015-10-14 11:33:11 -07003072 cricket::MediaSessionOptions* session_options) {
Steve Antondcc3c022017-12-22 16:02:54 -08003073 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
zhihuang1c378ed2017-08-17 14:10:50 -07003074
Steve Antondcc3c022017-12-22 16:02:54 -08003075 if (IsUnifiedPlan()) {
3076 GetOptionsForUnifiedPlanOffer(offer_answer_options, session_options);
3077 } else {
3078 GetOptionsForPlanBOffer(offer_answer_options, session_options);
3079 }
3080
Steve Antonfa2260d2017-12-28 16:38:23 -08003081 // Intentionally unset the data channel type for RTP data channel with the
3082 // second condition. Otherwise the RTP data channels would be successfully
3083 // negotiated by default and the unit tests in WebRtcDataBrowserTest will fail
3084 // when building with chromium. We want to leave RTP data channels broken, so
3085 // people won't try to use them.
3086 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
3087 session_options->data_channel_type = data_channel_type();
3088 }
3089
Steve Antondcc3c022017-12-22 16:02:54 -08003090 // Apply ICE restart flag and renomination flag.
3091 for (auto& options : session_options->media_description_options) {
3092 options.transport_options.ice_restart = offer_answer_options.ice_restart;
3093 options.transport_options.enable_ice_renomination =
3094 configuration_.enable_ice_renomination;
3095 }
3096
3097 session_options->rtcp_cname = rtcp_cname_;
3098 session_options->crypto_options = factory_->options().crypto_options;
3099}
3100
3101void PeerConnection::GetOptionsForPlanBOffer(
3102 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
3103 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07003104 // Figure out transceiver directional preferences.
3105 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
3106 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
3107
3108 // By default, generate sendrecv/recvonly m= sections.
3109 bool recv_audio = true;
3110 bool recv_video = true;
3111
3112 // By default, only offer a new m= section if we have media to send with it.
3113 bool offer_new_audio_description = send_audio;
3114 bool offer_new_video_description = send_video;
3115 bool offer_new_data_description = HasDataChannels();
3116
3117 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-22 16:02:54 -08003118 if (offer_answer_options.offer_to_receive_audio !=
3119 RTCOfferAnswerOptions::kUndefined) {
3120 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003121 offer_new_audio_description =
Steve Antondcc3c022017-12-22 16:02:54 -08003122 offer_new_audio_description ||
3123 (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003124 }
Steve Antondcc3c022017-12-22 16:02:54 -08003125 if (offer_answer_options.offer_to_receive_video !=
3126 RTCOfferAnswerOptions::kUndefined) {
3127 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003128 offer_new_video_description =
Steve Antondcc3c022017-12-22 16:02:54 -08003129 offer_new_video_description ||
3130 (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003131 }
3132
3133 rtc::Optional<size_t> audio_index;
3134 rtc::Optional<size_t> video_index;
3135 rtc::Optional<size_t> data_index;
3136 // If a current description exists, generate m= sections in the same order,
3137 // using the first audio/video/data section that appears and rejecting
3138 // extraneous ones.
Steve Anton75737c02017-11-06 10:37:17 -08003139 if (local_description()) {
zhihuang1c378ed2017-08-17 14:10:50 -07003140 GenerateMediaDescriptionOptions(
Steve Anton75737c02017-11-06 10:37:17 -08003141 local_description(),
Steve Anton1d03a752017-11-27 14:30:09 -08003142 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
3143 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
3144 &audio_index, &video_index, &data_index, session_options);
deadbeefab9b2d12015-10-14 11:33:11 -07003145 }
3146
zhihuang1c378ed2017-08-17 14:10:50 -07003147 // Add audio/video/data m= sections to the end if needed.
3148 if (!audio_index && offer_new_audio_description) {
3149 session_options->media_description_options.push_back(
3150 cricket::MediaDescriptionOptions(
3151 cricket::MEDIA_TYPE_AUDIO, cricket::CN_AUDIO,
Steve Anton1d03a752017-11-27 14:30:09 -08003152 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
3153 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003154 audio_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07003155 }
zhihuang1c378ed2017-08-17 14:10:50 -07003156 if (!video_index && offer_new_video_description) {
3157 session_options->media_description_options.push_back(
3158 cricket::MediaDescriptionOptions(
3159 cricket::MEDIA_TYPE_VIDEO, cricket::CN_VIDEO,
Steve Anton1d03a752017-11-27 14:30:09 -08003160 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
3161 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003162 video_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07003163 }
zhihuang1c378ed2017-08-17 14:10:50 -07003164 if (!data_index && offer_new_data_description) {
3165 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08003166 GetMediaDescriptionOptionsForActiveData(cricket::CN_DATA));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003167 data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07003168 }
3169
3170 cricket::MediaDescriptionOptions* audio_media_description_options =
3171 !audio_index ? nullptr
3172 : &session_options->media_description_options[*audio_index];
3173 cricket::MediaDescriptionOptions* video_media_description_options =
3174 !video_index ? nullptr
3175 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 14:10:50 -07003176
Steve Anton4171afb2017-11-20 10:20:22 -08003177 AddRtpSenderOptions(GetSendersInternal(), audio_media_description_options,
zhihuang1c378ed2017-08-17 14:10:50 -07003178 video_media_description_options);
Steve Antondcc3c022017-12-22 16:02:54 -08003179}
3180
3181// Find a new MID that is not already in |used_mids|, then add it to |used_mids|
3182// and return a reference to it.
3183// Generated MIDs should be no more than 3 bytes long to take up less space in
3184// the RTP packet.
3185static const std::string& AllocateMid(std::set<std::string>* used_mids) {
3186 RTC_DCHECK(used_mids);
3187 // We're boring: just generate MIDs 0, 1, 2, ...
3188 size_t i = 0;
3189 std::set<std::string>::iterator it;
3190 bool inserted;
3191 do {
3192 std::string mid = rtc::ToString(i++);
3193 auto insert_result = used_mids->insert(mid);
3194 it = insert_result.first;
3195 inserted = insert_result.second;
3196 } while (!inserted);
3197 return *it;
3198}
3199
3200static cricket::MediaDescriptionOptions
3201GetMediaDescriptionOptionsForTransceiver(
3202 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3203 transceiver,
3204 const std::string& mid) {
3205 cricket::MediaDescriptionOptions media_description_options(
3206 transceiver->internal()->media_type(), mid, transceiver->direction(),
3207 transceiver->stopped());
3208 cricket::SenderOptions sender_options;
3209 sender_options.track_id = transceiver->sender()->id();
3210 sender_options.stream_ids = transceiver->sender()->stream_ids();
3211 // TODO(bugs.webrtc.org/7600): Set num_sim_layers to the number of encodings
3212 // set in the RTP parameters when the transceiver was added.
3213 sender_options.num_sim_layers = 1;
3214 media_description_options.sender_options.push_back(sender_options);
3215 return media_description_options;
3216}
3217
3218void PeerConnection::GetOptionsForUnifiedPlanOffer(
3219 const RTCOfferAnswerOptions& offer_answer_options,
3220 cricket::MediaSessionOptions* session_options) {
3221 // Rules for generating an offer are dictated by JSEP sections 5.2.1 (Initial
3222 // Offers) and 5.2.2 (Subsequent Offers).
3223 RTC_DCHECK_EQ(session_options->media_description_options.size(), 0);
3224 const ContentInfos& local_contents =
3225 (local_description() ? local_description()->description()->contents()
3226 : ContentInfos());
3227 const ContentInfos& remote_contents =
3228 (remote_description() ? remote_description()->description()->contents()
3229 : ContentInfos());
3230 // The mline indices that can be recycled. New transceivers should reuse these
3231 // slots first.
3232 std::queue<size_t> recycleable_mline_indices;
3233 // Track the MIDs used in previous offer/answer exchanges and the current
3234 // offer so that new, unique MIDs are generated.
3235 std::set<std::string> used_mids = seen_mids_;
3236 // First, go through each media section that exists in either the local or
3237 // remote description and generate a media section in this offer for the
3238 // associated transceiver. If a media section can be recycled, generate a
3239 // default, rejected media section here that can be later overwritten.
3240 for (size_t i = 0;
3241 i < std::max(local_contents.size(), remote_contents.size()); ++i) {
3242 // Either |local_content| or |remote_content| is non-null.
3243 const ContentInfo* local_content =
3244 (i < local_contents.size() ? &local_contents[i] : nullptr);
3245 const ContentInfo* remote_content =
3246 (i < remote_contents.size() ? &remote_contents[i] : nullptr);
3247 bool had_been_rejected = (local_content && local_content->rejected) ||
3248 (remote_content && remote_content->rejected);
3249 const std::string& mid =
3250 (local_content ? local_content->name : remote_content->name);
3251 cricket::MediaType media_type =
3252 (local_content ? local_content->media_description()->type()
3253 : remote_content->media_description()->type());
3254 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
3255 media_type == cricket::MEDIA_TYPE_VIDEO) {
3256 auto transceiver = GetAssociatedTransceiver(mid);
3257 RTC_CHECK(transceiver);
3258 // A media section is considered eligible for recycling if it is marked as
3259 // rejected in either the local or remote description.
3260 if (had_been_rejected) {
3261 session_options->media_description_options.push_back(
3262 cricket::MediaDescriptionOptions(
3263 transceiver->internal()->media_type(), mid,
3264 RtpTransceiverDirection::kInactive,
3265 /*stopped=*/true));
3266 recycleable_mline_indices.push(i);
3267 } else {
3268 session_options->media_description_options.push_back(
3269 GetMediaDescriptionOptionsForTransceiver(transceiver, mid));
3270 // CreateOffer shouldn't really cause any state changes in
3271 // PeerConnection, but we need a way to match new transceivers to new
3272 // media sections in SetLocalDescription and JSEP specifies this is done
3273 // by recording the index of the media section generated for the
3274 // transceiver in the offer.
3275 transceiver->internal()->set_mline_index(i);
3276 }
3277 } else {
3278 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antonfa2260d2017-12-28 16:38:23 -08003279 RTC_CHECK(GetDataMid());
3280 if (had_been_rejected || mid != *GetDataMid()) {
3281 session_options->media_description_options.push_back(
3282 GetMediaDescriptionOptionsForRejectedData(mid));
3283 } else {
3284 session_options->media_description_options.push_back(
3285 GetMediaDescriptionOptionsForActiveData(mid));
3286 }
Steve Antondcc3c022017-12-22 16:02:54 -08003287 }
3288 }
3289 // Next, look for transceivers that are newly added (that is, are not stopped
3290 // and not associated). Reuse media sections marked as recyclable first,
3291 // otherwise append to the end of the offer. New media sections should be
3292 // added in the order they were added to the PeerConnection.
3293 for (auto transceiver : transceivers_) {
3294 if (transceiver->mid() || transceiver->stopped()) {
3295 continue;
3296 }
3297 size_t mline_index;
3298 if (!recycleable_mline_indices.empty()) {
3299 mline_index = recycleable_mline_indices.front();
3300 recycleable_mline_indices.pop();
3301 session_options->media_description_options[mline_index] =
3302 GetMediaDescriptionOptionsForTransceiver(transceiver,
3303 AllocateMid(&used_mids));
3304 } else {
3305 mline_index = session_options->media_description_options.size();
3306 session_options->media_description_options.push_back(
3307 GetMediaDescriptionOptionsForTransceiver(transceiver,
3308 AllocateMid(&used_mids)));
3309 }
3310 // See comment above for why CreateOffer changes the transceiver's state.
3311 transceiver->internal()->set_mline_index(mline_index);
3312 }
Steve Antonfa2260d2017-12-28 16:38:23 -08003313 // Lastly, add a m-section if we have local data channels and an m section
3314 // does not already exist.
3315 if (!GetDataMid() && HasDataChannels()) {
3316 session_options->media_description_options.push_back(
3317 GetMediaDescriptionOptionsForActiveData(AllocateMid(&used_mids)));
3318 }
Steve Antondcc3c022017-12-22 16:02:54 -08003319}
3320
3321void PeerConnection::GetOptionsForAnswer(
3322 const RTCOfferAnswerOptions& offer_answer_options,
3323 cricket::MediaSessionOptions* session_options) {
3324 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
3325
3326 if (IsUnifiedPlan()) {
3327 GetOptionsForUnifiedPlanAnswer(offer_answer_options, session_options);
3328 } else {
3329 GetOptionsForPlanBAnswer(offer_answer_options, session_options);
3330 }
3331
Steve Antonfa2260d2017-12-28 16:38:23 -08003332 // Intentionally unset the data channel type for RTP data channel. Otherwise
3333 // the RTP data channels would be successfully negotiated by default and the
3334 // unit tests in WebRtcDataBrowserTest will fail when building with chromium.
3335 // We want to leave RTP data channels broken, so people won't try to use them.
3336 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
3337 session_options->data_channel_type = data_channel_type();
3338 }
3339
Steve Antondcc3c022017-12-22 16:02:54 -08003340 // Apply ICE renomination flag.
3341 for (auto& options : session_options->media_description_options) {
3342 options.transport_options.enable_ice_renomination =
3343 configuration_.enable_ice_renomination;
3344 }
zhihuang8f65cdf2016-05-06 18:40:30 -07003345
3346 session_options->rtcp_cname = rtcp_cname_;
jbauchcb560652016-08-04 05:20:32 -07003347 session_options->crypto_options = factory_->options().crypto_options;
deadbeefab9b2d12015-10-14 11:33:11 -07003348}
3349
Steve Antondcc3c022017-12-22 16:02:54 -08003350void PeerConnection::GetOptionsForPlanBAnswer(
3351 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07003352 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07003353 // Figure out transceiver directional preferences.
3354 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
3355 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
3356
3357 // By default, generate sendrecv/recvonly m= sections. The direction is also
3358 // restricted by the direction in the offer.
3359 bool recv_audio = true;
3360 bool recv_video = true;
3361
3362 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-22 16:02:54 -08003363 if (offer_answer_options.offer_to_receive_audio !=
3364 RTCOfferAnswerOptions::kUndefined) {
3365 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
deadbeef0ed85b22016-02-23 17:24:52 -08003366 }
Steve Antondcc3c022017-12-22 16:02:54 -08003367 if (offer_answer_options.offer_to_receive_video !=
3368 RTCOfferAnswerOptions::kUndefined) {
3369 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003370 }
3371
3372 rtc::Optional<size_t> audio_index;
3373 rtc::Optional<size_t> video_index;
3374 rtc::Optional<size_t> data_index;
Taylor Brandstetter94d8cce2018-01-26 22:44:21 +00003375 if (remote_description()) {
3376 // The pending remote description should be an offer.
3377 RTC_DCHECK(remote_description()->GetType() == SdpType::kOffer);
3378 // Generate m= sections that match those in the offer.
3379 // Note that mediasession.cc will handle intersection our preferred
3380 // direction with the offered direction.
3381 GenerateMediaDescriptionOptions(
3382 remote_description(),
3383 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
3384 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
3385 &audio_index, &video_index, &data_index, session_options);
3386 }
zhihuang1c378ed2017-08-17 14:10:50 -07003387
3388 cricket::MediaDescriptionOptions* audio_media_description_options =
3389 !audio_index ? nullptr
3390 : &session_options->media_description_options[*audio_index];
3391 cricket::MediaDescriptionOptions* video_media_description_options =
3392 !video_index ? nullptr
3393 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 14:10:50 -07003394
Steve Anton4171afb2017-11-20 10:20:22 -08003395 AddRtpSenderOptions(GetSendersInternal(), audio_media_description_options,
zhihuang1c378ed2017-08-17 14:10:50 -07003396 video_media_description_options);
Steve Antondcc3c022017-12-22 16:02:54 -08003397}
zhihuangaf388472016-11-02 16:49:48 -07003398
Steve Antondcc3c022017-12-22 16:02:54 -08003399void PeerConnection::GetOptionsForUnifiedPlanAnswer(
3400 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
3401 cricket::MediaSessionOptions* session_options) {
3402 // Rules for generating an answer are dictated by JSEP sections 5.3.1 (Initial
3403 // Answers) and 5.3.2 (Subsequent Answers).
3404 RTC_DCHECK(remote_description());
3405 RTC_DCHECK(remote_description()->GetType() == SdpType::kOffer);
3406 for (const ContentInfo& content :
3407 remote_description()->description()->contents()) {
3408 cricket::MediaType media_type = content.media_description()->type();
3409 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
3410 media_type == cricket::MEDIA_TYPE_VIDEO) {
3411 auto transceiver = GetAssociatedTransceiver(content.name);
3412 RTC_CHECK(transceiver);
3413 session_options->media_description_options.push_back(
3414 GetMediaDescriptionOptionsForTransceiver(transceiver, content.name));
3415 } else {
3416 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antondbf9d032018-01-19 15:23:40 -08003417 // Reject all data sections if data channels are disabled.
3418 // Reject a data section if it has already been rejected.
3419 // Reject all data sections except for the first one.
3420 if (data_channel_type_ == cricket::DCT_NONE || content.rejected ||
3421 content.name != *GetDataMid()) {
Steve Antonfa2260d2017-12-28 16:38:23 -08003422 session_options->media_description_options.push_back(
3423 GetMediaDescriptionOptionsForRejectedData(content.name));
3424 } else {
3425 session_options->media_description_options.push_back(
3426 GetMediaDescriptionOptionsForActiveData(content.name));
3427 }
Steve Antondcc3c022017-12-22 16:02:54 -08003428 }
3429 }
htaa2a49d92016-03-04 02:51:39 -08003430}
3431
zhihuang1c378ed2017-08-17 14:10:50 -07003432void PeerConnection::GenerateMediaDescriptionOptions(
3433 const SessionDescriptionInterface* session_desc,
Steve Anton1d03a752017-11-27 14:30:09 -08003434 RtpTransceiverDirection audio_direction,
3435 RtpTransceiverDirection video_direction,
zhihuang1c378ed2017-08-17 14:10:50 -07003436 rtc::Optional<size_t>* audio_index,
3437 rtc::Optional<size_t>* video_index,
3438 rtc::Optional<size_t>* data_index,
htaa2a49d92016-03-04 02:51:39 -08003439 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07003440 for (const cricket::ContentInfo& content :
3441 session_desc->description()->contents()) {
3442 if (IsAudioContent(&content)) {
3443 // If we already have an audio m= section, reject this extra one.
3444 if (*audio_index) {
3445 session_options->media_description_options.push_back(
3446 cricket::MediaDescriptionOptions(
3447 cricket::MEDIA_TYPE_AUDIO, content.name,
Steve Anton1d03a752017-11-27 14:30:09 -08003448 RtpTransceiverDirection::kInactive, true));
zhihuang1c378ed2017-08-17 14:10:50 -07003449 } else {
3450 session_options->media_description_options.push_back(
3451 cricket::MediaDescriptionOptions(
3452 cricket::MEDIA_TYPE_AUDIO, content.name, audio_direction,
Steve Anton1d03a752017-11-27 14:30:09 -08003453 audio_direction == RtpTransceiverDirection::kInactive));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003454 *audio_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07003455 }
3456 } else if (IsVideoContent(&content)) {
3457 // If we already have an video m= section, reject this extra one.
3458 if (*video_index) {
3459 session_options->media_description_options.push_back(
3460 cricket::MediaDescriptionOptions(
3461 cricket::MEDIA_TYPE_VIDEO, content.name,
Steve Anton1d03a752017-11-27 14:30:09 -08003462 RtpTransceiverDirection::kInactive, true));
zhihuang1c378ed2017-08-17 14:10:50 -07003463 } else {
3464 session_options->media_description_options.push_back(
3465 cricket::MediaDescriptionOptions(
3466 cricket::MEDIA_TYPE_VIDEO, content.name, video_direction,
Steve Anton1d03a752017-11-27 14:30:09 -08003467 video_direction == RtpTransceiverDirection::kInactive));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003468 *video_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07003469 }
3470 } else {
3471 RTC_DCHECK(IsDataContent(&content));
3472 // If we already have an data m= section, reject this extra one.
3473 if (*data_index) {
3474 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08003475 GetMediaDescriptionOptionsForRejectedData(content.name));
zhihuang1c378ed2017-08-17 14:10:50 -07003476 } else {
3477 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08003478 GetMediaDescriptionOptionsForActiveData(content.name));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003479 *data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07003480 }
3481 }
htaa2a49d92016-03-04 02:51:39 -08003482 }
deadbeefab9b2d12015-10-14 11:33:11 -07003483}
3484
Steve Antonfa2260d2017-12-28 16:38:23 -08003485cricket::MediaDescriptionOptions
3486PeerConnection::GetMediaDescriptionOptionsForActiveData(
3487 const std::string& mid) const {
3488 // Direction for data sections is meaningless, but legacy endpoints might
3489 // expect sendrecv.
3490 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
3491 RtpTransceiverDirection::kSendRecv,
3492 /*stopped=*/false);
3493 AddRtpDataChannelOptions(rtp_data_channels_, &options);
3494 return options;
3495}
3496
3497cricket::MediaDescriptionOptions
3498PeerConnection::GetMediaDescriptionOptionsForRejectedData(
3499 const std::string& mid) const {
3500 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
3501 RtpTransceiverDirection::kInactive,
3502 /*stopped=*/true);
3503 AddRtpDataChannelOptions(rtp_data_channels_, &options);
3504 return options;
3505}
3506
3507rtc::Optional<std::string> PeerConnection::GetDataMid() const {
3508 switch (data_channel_type_) {
3509 case cricket::DCT_RTP:
3510 if (!rtp_data_channel_) {
3511 return rtc::nullopt;
3512 }
3513 return rtp_data_channel_->content_name();
3514 case cricket::DCT_SCTP:
3515 return sctp_content_name_;
3516 default:
3517 return rtc::nullopt;
3518 }
3519}
3520
Steve Anton4171afb2017-11-20 10:20:22 -08003521void PeerConnection::RemoveSenders(cricket::MediaType media_type) {
3522 UpdateLocalSenders(std::vector<cricket::StreamParams>(), media_type);
3523 UpdateRemoteSendersList(std::vector<cricket::StreamParams>(), false,
deadbeefbda7e0b2015-12-08 17:13:40 -08003524 media_type, nullptr);
deadbeeffaac4972015-11-12 15:33:07 -08003525}
3526
Steve Anton4171afb2017-11-20 10:20:22 -08003527void PeerConnection::UpdateRemoteSendersList(
deadbeefab9b2d12015-10-14 11:33:11 -07003528 const cricket::StreamParamsVec& streams,
Steve Anton4171afb2017-11-20 10:20:22 -08003529 bool default_sender_needed,
deadbeefab9b2d12015-10-14 11:33:11 -07003530 cricket::MediaType media_type,
3531 StreamCollection* new_streams) {
Steve Anton4171afb2017-11-20 10:20:22 -08003532 std::vector<RtpSenderInfo>* current_senders =
3533 GetRemoteSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07003534
Steve Anton4171afb2017-11-20 10:20:22 -08003535 // Find removed senders. I.e., senders where the sender id or ssrc don't match
deadbeeffac06552015-11-25 11:26:01 -08003536 // the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08003537 for (auto sender_it = current_senders->begin();
3538 sender_it != current_senders->end();
3539 /* incremented manually */) {
3540 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07003541 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08003542 cricket::GetStreamBySsrc(streams, info.first_ssrc);
3543 bool sender_exists = params && params->id == info.sender_id;
deadbeefbda7e0b2015-12-08 17:13:40 -08003544 // If this is a default track, and we still need it, don't remove it.
Steve Anton4171afb2017-11-20 10:20:22 -08003545 if ((info.stream_label == kDefaultStreamLabel && default_sender_needed) ||
3546 sender_exists) {
3547 ++sender_it;
deadbeefbda7e0b2015-12-08 17:13:40 -08003548 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08003549 OnRemoteSenderRemoved(info, media_type);
3550 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07003551 }
3552 }
3553
Steve Anton4171afb2017-11-20 10:20:22 -08003554 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07003555 for (const cricket::StreamParams& params : streams) {
3556 // The sync_label is the MediaStream label and the |stream.id| is the
Steve Anton4171afb2017-11-20 10:20:22 -08003557 // sender id.
deadbeefab9b2d12015-10-14 11:33:11 -07003558 const std::string& stream_label = params.sync_label;
Steve Anton4171afb2017-11-20 10:20:22 -08003559 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07003560 uint32_t ssrc = params.first_ssrc();
3561
3562 rtc::scoped_refptr<MediaStreamInterface> stream =
3563 remote_streams_->find(stream_label);
3564 if (!stream) {
3565 // This is a new MediaStream. Create a new remote MediaStream.
perkjd61bf802016-03-24 03:16:19 -07003566 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
3567 MediaStream::Create(stream_label));
deadbeefab9b2d12015-10-14 11:33:11 -07003568 remote_streams_->AddStream(stream);
3569 new_streams->AddStream(stream);
3570 }
3571
Steve Anton4171afb2017-11-20 10:20:22 -08003572 const RtpSenderInfo* sender_info =
3573 FindSenderInfo(*current_senders, stream_label, sender_id);
3574 if (!sender_info) {
3575 current_senders->push_back(RtpSenderInfo(stream_label, sender_id, ssrc));
3576 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07003577 }
3578 }
deadbeefbda7e0b2015-12-08 17:13:40 -08003579
Steve Anton4171afb2017-11-20 10:20:22 -08003580 // Add default sender if necessary.
3581 if (default_sender_needed) {
deadbeefbda7e0b2015-12-08 17:13:40 -08003582 rtc::scoped_refptr<MediaStreamInterface> default_stream =
3583 remote_streams_->find(kDefaultStreamLabel);
3584 if (!default_stream) {
3585 // Create the new default MediaStream.
perkjd61bf802016-03-24 03:16:19 -07003586 default_stream = MediaStreamProxy::Create(
3587 rtc::Thread::Current(), MediaStream::Create(kDefaultStreamLabel));
deadbeefbda7e0b2015-12-08 17:13:40 -08003588 remote_streams_->AddStream(default_stream);
3589 new_streams->AddStream(default_stream);
3590 }
Steve Anton4171afb2017-11-20 10:20:22 -08003591 std::string default_sender_id = (media_type == cricket::MEDIA_TYPE_AUDIO)
3592 ? kDefaultAudioSenderId
3593 : kDefaultVideoSenderId;
3594 const RtpSenderInfo* default_sender_info = FindSenderInfo(
3595 *current_senders, kDefaultStreamLabel, default_sender_id);
3596 if (!default_sender_info) {
3597 current_senders->push_back(
3598 RtpSenderInfo(kDefaultStreamLabel, default_sender_id, 0));
3599 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefbda7e0b2015-12-08 17:13:40 -08003600 }
3601 }
deadbeefab9b2d12015-10-14 11:33:11 -07003602}
3603
Steve Anton4171afb2017-11-20 10:20:22 -08003604void PeerConnection::OnRemoteSenderAdded(const RtpSenderInfo& sender_info,
3605 cricket::MediaType media_type) {
3606 MediaStreamInterface* stream =
3607 remote_streams_->find(sender_info.stream_label);
deadbeefab9b2d12015-10-14 11:33:11 -07003608
3609 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 10:20:22 -08003610 CreateAudioReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07003611 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 10:20:22 -08003612 CreateVideoReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07003613 } else {
nisseeb4ca4e2017-01-12 02:24:27 -08003614 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07003615 }
3616}
3617
Steve Anton4171afb2017-11-20 10:20:22 -08003618void PeerConnection::OnRemoteSenderRemoved(const RtpSenderInfo& sender_info,
3619 cricket::MediaType media_type) {
3620 MediaStreamInterface* stream =
3621 remote_streams_->find(sender_info.stream_label);
deadbeefab9b2d12015-10-14 11:33:11 -07003622
Henrik Boström933d8b02017-10-10 10:05:16 -07003623 rtc::scoped_refptr<RtpReceiverInterface> receiver;
deadbeefab9b2d12015-10-14 11:33:11 -07003624 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
perkjd61bf802016-03-24 03:16:19 -07003625 // When the MediaEngine audio channel is destroyed, the RemoteAudioSource
3626 // will be notified which will end the AudioRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08003627 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07003628 rtc::scoped_refptr<AudioTrackInterface> audio_track =
Steve Anton4171afb2017-11-20 10:20:22 -08003629 stream->FindAudioTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07003630 if (audio_track) {
deadbeefab9b2d12015-10-14 11:33:11 -07003631 stream->RemoveTrack(audio_track);
deadbeefab9b2d12015-10-14 11:33:11 -07003632 }
3633 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
perkjd61bf802016-03-24 03:16:19 -07003634 // Stopping or destroying a VideoRtpReceiver will end the
3635 // VideoRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08003636 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07003637 rtc::scoped_refptr<VideoTrackInterface> video_track =
Steve Anton4171afb2017-11-20 10:20:22 -08003638 stream->FindVideoTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07003639 if (video_track) {
perkjd61bf802016-03-24 03:16:19 -07003640 // There's no guarantee the track is still available, e.g. the track may
3641 // have been removed from the stream by an application.
deadbeefab9b2d12015-10-14 11:33:11 -07003642 stream->RemoveTrack(video_track);
deadbeefab9b2d12015-10-14 11:33:11 -07003643 }
3644 } else {
nisseede5da42017-01-12 05:15:36 -08003645 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07003646 }
Henrik Boström933d8b02017-10-10 10:05:16 -07003647 if (receiver) {
3648 observer_->OnRemoveTrack(receiver);
3649 }
deadbeefab9b2d12015-10-14 11:33:11 -07003650}
3651
3652void PeerConnection::UpdateEndedRemoteMediaStreams() {
3653 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams_to_remove;
3654 for (size_t i = 0; i < remote_streams_->count(); ++i) {
3655 MediaStreamInterface* stream = remote_streams_->at(i);
3656 if (stream->GetAudioTracks().empty() && stream->GetVideoTracks().empty()) {
3657 streams_to_remove.push_back(stream);
3658 }
3659 }
3660
Taylor Brandstetter98cde262016-05-31 13:02:21 -07003661 for (auto& stream : streams_to_remove) {
deadbeefab9b2d12015-10-14 11:33:11 -07003662 remote_streams_->RemoveStream(stream);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07003663 observer_->OnRemoveStream(std::move(stream));
deadbeefab9b2d12015-10-14 11:33:11 -07003664 }
3665}
3666
Steve Anton4171afb2017-11-20 10:20:22 -08003667void PeerConnection::UpdateLocalSenders(
deadbeefab9b2d12015-10-14 11:33:11 -07003668 const std::vector<cricket::StreamParams>& streams,
3669 cricket::MediaType media_type) {
Steve Anton4171afb2017-11-20 10:20:22 -08003670 std::vector<RtpSenderInfo>* current_senders = GetLocalSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07003671
3672 // Find removed tracks. I.e., tracks where the track id, stream label or ssrc
3673 // don't match the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08003674 for (auto sender_it = current_senders->begin();
3675 sender_it != current_senders->end();
3676 /* incremented manually */) {
3677 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07003678 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08003679 cricket::GetStreamBySsrc(streams, info.first_ssrc);
3680 if (!params || params->id != info.sender_id ||
deadbeefab9b2d12015-10-14 11:33:11 -07003681 params->sync_label != info.stream_label) {
Steve Anton4171afb2017-11-20 10:20:22 -08003682 OnLocalSenderRemoved(info, media_type);
3683 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07003684 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08003685 ++sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07003686 }
3687 }
3688
Steve Anton4171afb2017-11-20 10:20:22 -08003689 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07003690 for (const cricket::StreamParams& params : streams) {
3691 // The sync_label is the MediaStream label and the |stream.id| is the
Steve Anton4171afb2017-11-20 10:20:22 -08003692 // sender id.
deadbeefab9b2d12015-10-14 11:33:11 -07003693 const std::string& stream_label = params.sync_label;
Steve Anton4171afb2017-11-20 10:20:22 -08003694 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07003695 uint32_t ssrc = params.first_ssrc();
Steve Anton4171afb2017-11-20 10:20:22 -08003696 const RtpSenderInfo* sender_info =
3697 FindSenderInfo(*current_senders, stream_label, sender_id);
3698 if (!sender_info) {
3699 current_senders->push_back(RtpSenderInfo(stream_label, sender_id, ssrc));
3700 OnLocalSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07003701 }
3702 }
3703}
3704
Steve Anton4171afb2017-11-20 10:20:22 -08003705void PeerConnection::OnLocalSenderAdded(const RtpSenderInfo& sender_info,
3706 cricket::MediaType media_type) {
3707 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08003708 if (!sender) {
Steve Anton4171afb2017-11-20 10:20:22 -08003709 RTC_LOG(LS_WARNING) << "An unknown RtpSender with id "
3710 << sender_info.sender_id
Mirko Bonadei675513b2017-11-09 11:09:25 +01003711 << " has been configured in the local description.";
deadbeefab9b2d12015-10-14 11:33:11 -07003712 return;
3713 }
3714
deadbeeffac06552015-11-25 11:26:01 -08003715 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003716 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
3717 << " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08003718 return;
deadbeefab9b2d12015-10-14 11:33:11 -07003719 }
deadbeeffac06552015-11-25 11:26:01 -08003720
Steve Anton4171afb2017-11-20 10:20:22 -08003721 sender->internal()->set_stream_id(sender_info.stream_label);
3722 sender->internal()->SetSsrc(sender_info.first_ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07003723}
3724
Steve Anton4171afb2017-11-20 10:20:22 -08003725void PeerConnection::OnLocalSenderRemoved(const RtpSenderInfo& sender_info,
3726 cricket::MediaType media_type) {
3727 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08003728 if (!sender) {
3729 // This is the normal case. I.e., RemoveStream has been called and the
deadbeefab9b2d12015-10-14 11:33:11 -07003730 // SessionDescriptions has been renegotiated.
3731 return;
3732 }
deadbeeffac06552015-11-25 11:26:01 -08003733
3734 // A sender has been removed from the SessionDescription but it's still
3735 // associated with the PeerConnection. This only occurs if the SDP doesn't
3736 // match with the calls to CreateSender, AddStream and RemoveStream.
3737 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003738 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
3739 << " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08003740 return;
deadbeefab9b2d12015-10-14 11:33:11 -07003741 }
deadbeeffac06552015-11-25 11:26:01 -08003742
Steve Anton4171afb2017-11-20 10:20:22 -08003743 sender->internal()->SetSsrc(0);
deadbeefab9b2d12015-10-14 11:33:11 -07003744}
3745
3746void PeerConnection::UpdateLocalRtpDataChannels(
3747 const cricket::StreamParamsVec& streams) {
3748 std::vector<std::string> existing_channels;
3749
3750 // Find new and active data channels.
3751 for (const cricket::StreamParams& params : streams) {
3752 // |it->sync_label| is actually the data channel label. The reason is that
3753 // we use the same naming of data channels as we do for
3754 // MediaStreams and Tracks.
3755 // For MediaStreams, the sync_label is the MediaStream label and the
3756 // track label is the same as |streamid|.
3757 const std::string& channel_label = params.sync_label;
3758 auto data_channel_it = rtp_data_channels_.find(channel_label);
nisse7ce109a2017-01-31 00:57:56 -08003759 if (data_channel_it == rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003760 RTC_LOG(LS_ERROR) << "channel label not found";
deadbeefab9b2d12015-10-14 11:33:11 -07003761 continue;
3762 }
3763 // Set the SSRC the data channel should use for sending.
3764 data_channel_it->second->SetSendSsrc(params.first_ssrc());
3765 existing_channels.push_back(data_channel_it->first);
3766 }
3767
3768 UpdateClosingRtpDataChannels(existing_channels, true);
3769}
3770
3771void PeerConnection::UpdateRemoteRtpDataChannels(
3772 const cricket::StreamParamsVec& streams) {
3773 std::vector<std::string> existing_channels;
3774
3775 // Find new and active data channels.
3776 for (const cricket::StreamParams& params : streams) {
3777 // The data channel label is either the mslabel or the SSRC if the mslabel
3778 // does not exist. Ex a=ssrc:444330170 mslabel:test1.
3779 std::string label = params.sync_label.empty()
3780 ? rtc::ToString(params.first_ssrc())
3781 : params.sync_label;
3782 auto data_channel_it = rtp_data_channels_.find(label);
3783 if (data_channel_it == rtp_data_channels_.end()) {
3784 // This is a new data channel.
3785 CreateRemoteRtpDataChannel(label, params.first_ssrc());
3786 } else {
3787 data_channel_it->second->SetReceiveSsrc(params.first_ssrc());
3788 }
3789 existing_channels.push_back(label);
3790 }
3791
3792 UpdateClosingRtpDataChannels(existing_channels, false);
3793}
3794
3795void PeerConnection::UpdateClosingRtpDataChannels(
3796 const std::vector<std::string>& active_channels,
3797 bool is_local_update) {
3798 auto it = rtp_data_channels_.begin();
3799 while (it != rtp_data_channels_.end()) {
3800 DataChannel* data_channel = it->second;
3801 if (std::find(active_channels.begin(), active_channels.end(),
3802 data_channel->label()) != active_channels.end()) {
3803 ++it;
3804 continue;
3805 }
3806
3807 if (is_local_update) {
3808 data_channel->SetSendSsrc(0);
3809 } else {
3810 data_channel->RemotePeerRequestClose();
3811 }
3812
3813 if (data_channel->state() == DataChannel::kClosed) {
3814 rtp_data_channels_.erase(it);
3815 it = rtp_data_channels_.begin();
3816 } else {
3817 ++it;
3818 }
3819 }
3820}
3821
3822void PeerConnection::CreateRemoteRtpDataChannel(const std::string& label,
3823 uint32_t remote_ssrc) {
3824 rtc::scoped_refptr<DataChannel> channel(
3825 InternalCreateDataChannel(label, nullptr));
3826 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003827 RTC_LOG(LS_WARNING) << "Remote peer requested a DataChannel but"
3828 << "CreateDataChannel failed.";
deadbeefab9b2d12015-10-14 11:33:11 -07003829 return;
3830 }
3831 channel->SetReceiveSsrc(remote_ssrc);
deadbeefa601f5c2016-06-06 14:27:39 -07003832 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
3833 DataChannelProxy::Create(signaling_thread(), channel);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07003834 observer_->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07003835}
3836
3837rtc::scoped_refptr<DataChannel> PeerConnection::InternalCreateDataChannel(
3838 const std::string& label,
3839 const InternalDataChannelInit* config) {
3840 if (IsClosed()) {
3841 return nullptr;
3842 }
Steve Anton75737c02017-11-06 10:37:17 -08003843 if (data_channel_type() == cricket::DCT_NONE) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003844 RTC_LOG(LS_ERROR)
deadbeefab9b2d12015-10-14 11:33:11 -07003845 << "InternalCreateDataChannel: Data is not supported in this call.";
3846 return nullptr;
3847 }
3848 InternalDataChannelInit new_config =
3849 config ? (*config) : InternalDataChannelInit();
Steve Anton75737c02017-11-06 10:37:17 -08003850 if (data_channel_type() == cricket::DCT_SCTP) {
deadbeefab9b2d12015-10-14 11:33:11 -07003851 if (new_config.id < 0) {
3852 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08003853 if ((GetSctpSslRole(&role)) &&
deadbeefab9b2d12015-10-14 11:33:11 -07003854 !sid_allocator_.AllocateSid(role, &new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003855 RTC_LOG(LS_ERROR)
3856 << "No id can be allocated for the SCTP data channel.";
deadbeefab9b2d12015-10-14 11:33:11 -07003857 return nullptr;
3858 }
3859 } else if (!sid_allocator_.ReserveSid(new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003860 RTC_LOG(LS_ERROR) << "Failed to create a SCTP data channel "
3861 << "because the id is already in use or out of range.";
deadbeefab9b2d12015-10-14 11:33:11 -07003862 return nullptr;
3863 }
3864 }
3865
Steve Anton75737c02017-11-06 10:37:17 -08003866 rtc::scoped_refptr<DataChannel> channel(
3867 DataChannel::Create(this, data_channel_type(), label, new_config));
deadbeefab9b2d12015-10-14 11:33:11 -07003868 if (!channel) {
3869 sid_allocator_.ReleaseSid(new_config.id);
3870 return nullptr;
3871 }
3872
3873 if (channel->data_channel_type() == cricket::DCT_RTP) {
3874 if (rtp_data_channels_.find(channel->label()) != rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003875 RTC_LOG(LS_ERROR) << "DataChannel with label " << channel->label()
3876 << " already exists.";
deadbeefab9b2d12015-10-14 11:33:11 -07003877 return nullptr;
3878 }
3879 rtp_data_channels_[channel->label()] = channel;
3880 } else {
3881 RTC_DCHECK(channel->data_channel_type() == cricket::DCT_SCTP);
3882 sctp_data_channels_.push_back(channel);
3883 channel->SignalClosed.connect(this,
3884 &PeerConnection::OnSctpDataChannelClosed);
3885 }
3886
Steve Anton2d8609c2018-01-23 16:38:46 -08003887 SignalDataChannelCreated_(channel.get());
deadbeefab9b2d12015-10-14 11:33:11 -07003888 return channel;
3889}
3890
3891bool PeerConnection::HasDataChannels() const {
3892 return !rtp_data_channels_.empty() || !sctp_data_channels_.empty();
3893}
3894
3895void PeerConnection::AllocateSctpSids(rtc::SSLRole role) {
3896 for (const auto& channel : sctp_data_channels_) {
3897 if (channel->id() < 0) {
3898 int sid;
3899 if (!sid_allocator_.AllocateSid(role, &sid)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003900 RTC_LOG(LS_ERROR) << "Failed to allocate SCTP sid.";
deadbeefab9b2d12015-10-14 11:33:11 -07003901 continue;
3902 }
3903 channel->SetSctpSid(sid);
3904 }
3905 }
3906}
3907
3908void PeerConnection::OnSctpDataChannelClosed(DataChannel* channel) {
deadbeefbd292462015-12-14 18:15:29 -08003909 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeefab9b2d12015-10-14 11:33:11 -07003910 for (auto it = sctp_data_channels_.begin(); it != sctp_data_channels_.end();
3911 ++it) {
3912 if (it->get() == channel) {
3913 if (channel->id() >= 0) {
3914 sid_allocator_.ReleaseSid(channel->id());
3915 }
deadbeefbd292462015-12-14 18:15:29 -08003916 // Since this method is triggered by a signal from the DataChannel,
3917 // we can't free it directly here; we need to free it asynchronously.
3918 sctp_data_channels_to_free_.push_back(*it);
deadbeefab9b2d12015-10-14 11:33:11 -07003919 sctp_data_channels_.erase(it);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07003920 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_FREE_DATACHANNELS,
3921 nullptr);
deadbeefab9b2d12015-10-14 11:33:11 -07003922 return;
3923 }
3924 }
3925}
3926
deadbeefab9b2d12015-10-14 11:33:11 -07003927void PeerConnection::OnDataChannelDestroyed() {
3928 // Use a temporary copy of the RTP/SCTP DataChannel list because the
3929 // DataChannel may callback to us and try to modify the list.
3930 std::map<std::string, rtc::scoped_refptr<DataChannel>> temp_rtp_dcs;
3931 temp_rtp_dcs.swap(rtp_data_channels_);
3932 for (const auto& kv : temp_rtp_dcs) {
3933 kv.second->OnTransportChannelDestroyed();
3934 }
3935
3936 std::vector<rtc::scoped_refptr<DataChannel>> temp_sctp_dcs;
3937 temp_sctp_dcs.swap(sctp_data_channels_);
3938 for (const auto& channel : temp_sctp_dcs) {
3939 channel->OnTransportChannelDestroyed();
3940 }
3941}
3942
3943void PeerConnection::OnDataChannelOpenMessage(
3944 const std::string& label,
3945 const InternalDataChannelInit& config) {
3946 rtc::scoped_refptr<DataChannel> channel(
3947 InternalCreateDataChannel(label, &config));
3948 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003949 RTC_LOG(LS_ERROR) << "Failed to create DataChannel from the OPEN message.";
deadbeefab9b2d12015-10-14 11:33:11 -07003950 return;
3951 }
3952
deadbeefa601f5c2016-06-06 14:27:39 -07003953 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
3954 DataChannelProxy::Create(signaling_thread(), channel);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07003955 observer_->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07003956}
3957
Steve Anton4171afb2017-11-20 10:20:22 -08003958rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3959PeerConnection::GetAudioTransceiver() const {
3960 // This method only works with Plan B SDP, where there is a single
3961 // audio/video transceiver.
3962 RTC_DCHECK(!IsUnifiedPlan());
3963 for (auto transceiver : transceivers_) {
3964 if (transceiver->internal()->media_type() == cricket::MEDIA_TYPE_AUDIO) {
3965 return transceiver;
3966 }
3967 }
3968 RTC_NOTREACHED();
3969 return nullptr;
3970}
3971
3972rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3973PeerConnection::GetVideoTransceiver() const {
3974 // This method only works with Plan B SDP, where there is a single
3975 // audio/video transceiver.
3976 RTC_DCHECK(!IsUnifiedPlan());
3977 for (auto transceiver : transceivers_) {
3978 if (transceiver->internal()->media_type() == cricket::MEDIA_TYPE_VIDEO) {
3979 return transceiver;
3980 }
3981 }
3982 RTC_NOTREACHED();
3983 return nullptr;
3984}
3985
3986// TODO(bugs.webrtc.org/7600): Remove this when multiple transceivers with
3987// individual transceiver directions are supported.
zhihuang1c378ed2017-08-17 14:10:50 -07003988bool PeerConnection::HasRtpSender(cricket::MediaType type) const {
Steve Anton4171afb2017-11-20 10:20:22 -08003989 switch (type) {
3990 case cricket::MEDIA_TYPE_AUDIO:
3991 return !GetAudioTransceiver()->internal()->senders().empty();
3992 case cricket::MEDIA_TYPE_VIDEO:
3993 return !GetVideoTransceiver()->internal()->senders().empty();
3994 case cricket::MEDIA_TYPE_DATA:
3995 return false;
3996 }
3997 RTC_NOTREACHED();
3998 return false;
zhihuang1c378ed2017-08-17 14:10:50 -07003999}
4000
Steve Anton4171afb2017-11-20 10:20:22 -08004001rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
4002PeerConnection::FindSenderForTrack(MediaStreamTrackInterface* track) const {
4003 for (auto transceiver : transceivers_) {
4004 for (auto sender : transceiver->internal()->senders()) {
4005 if (sender->track() == track) {
4006 return sender;
4007 }
4008 }
4009 }
4010 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08004011}
4012
Steve Anton4171afb2017-11-20 10:20:22 -08004013rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
4014PeerConnection::FindSenderById(const std::string& sender_id) const {
4015 for (auto transceiver : transceivers_) {
4016 for (auto sender : transceiver->internal()->senders()) {
4017 if (sender->id() == sender_id) {
4018 return sender;
4019 }
4020 }
4021 }
4022 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07004023}
4024
Steve Anton4171afb2017-11-20 10:20:22 -08004025rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
4026PeerConnection::FindReceiverById(const std::string& receiver_id) const {
4027 for (auto transceiver : transceivers_) {
4028 for (auto receiver : transceiver->internal()->receivers()) {
4029 if (receiver->id() == receiver_id) {
4030 return receiver;
4031 }
4032 }
4033 }
4034 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07004035}
4036
Steve Anton4171afb2017-11-20 10:20:22 -08004037std::vector<PeerConnection::RtpSenderInfo>*
4038PeerConnection::GetRemoteSenderInfos(cricket::MediaType media_type) {
4039 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
4040 media_type == cricket::MEDIA_TYPE_VIDEO);
4041 return (media_type == cricket::MEDIA_TYPE_AUDIO)
4042 ? &remote_audio_sender_infos_
4043 : &remote_video_sender_infos_;
4044}
4045
4046std::vector<PeerConnection::RtpSenderInfo>* PeerConnection::GetLocalSenderInfos(
deadbeefab9b2d12015-10-14 11:33:11 -07004047 cricket::MediaType media_type) {
4048 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
4049 media_type == cricket::MEDIA_TYPE_VIDEO);
Steve Anton4171afb2017-11-20 10:20:22 -08004050 return (media_type == cricket::MEDIA_TYPE_AUDIO) ? &local_audio_sender_infos_
4051 : &local_video_sender_infos_;
deadbeefab9b2d12015-10-14 11:33:11 -07004052}
4053
Steve Anton4171afb2017-11-20 10:20:22 -08004054const PeerConnection::RtpSenderInfo* PeerConnection::FindSenderInfo(
4055 const std::vector<PeerConnection::RtpSenderInfo>& infos,
deadbeefab9b2d12015-10-14 11:33:11 -07004056 const std::string& stream_label,
Steve Anton4171afb2017-11-20 10:20:22 -08004057 const std::string sender_id) const {
4058 for (const RtpSenderInfo& sender_info : infos) {
4059 if (sender_info.stream_label == stream_label &&
4060 sender_info.sender_id == sender_id) {
4061 return &sender_info;
deadbeefab9b2d12015-10-14 11:33:11 -07004062 }
4063 }
4064 return nullptr;
4065}
4066
4067DataChannel* PeerConnection::FindDataChannelBySid(int sid) const {
4068 for (const auto& channel : sctp_data_channels_) {
4069 if (channel->id() == sid) {
4070 return channel;
4071 }
4072 }
4073 return nullptr;
4074}
4075
deadbeef91dd5672016-05-18 16:55:30 -07004076bool PeerConnection::InitializePortAllocator_n(
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004077 const RTCConfiguration& configuration) {
4078 cricket::ServerAddresses stun_servers;
4079 std::vector<cricket::RelayServerConfig> turn_servers;
deadbeef293e9262017-01-11 12:28:30 -08004080 if (ParseIceServers(configuration.servers, &stun_servers, &turn_servers) !=
4081 RTCErrorType::NONE) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004082 return false;
4083 }
4084
Taylor Brandstetterf8e65772016-06-27 17:20:15 -07004085 port_allocator_->Initialize();
4086
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004087 // To handle both internal and externally created port allocator, we will
4088 // enable BUNDLE here.
4089 int portallocator_flags = port_allocator_->flags();
4090 portallocator_flags |= cricket::PORTALLOCATOR_ENABLE_SHARED_SOCKET |
zhihuangb09b3f92017-03-07 14:40:51 -08004091 cricket::PORTALLOCATOR_ENABLE_IPV6 |
4092 cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI;
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004093 // If the disable-IPv6 flag was specified, we'll not override it
4094 // by experiment.
4095 if (configuration.disable_ipv6) {
4096 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
sprangc1b57a12017-02-28 08:50:47 -08004097 } else if (webrtc::field_trial::FindFullName("WebRTC-IPv6Default")
4098 .find("Disabled") == 0) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004099 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
4100 }
4101
zhihuangb09b3f92017-03-07 14:40:51 -08004102 if (configuration.disable_ipv6_on_wifi) {
4103 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI);
Mirko Bonadei675513b2017-11-09 11:09:25 +01004104 RTC_LOG(LS_INFO) << "IPv6 candidates on Wi-Fi are disabled.";
zhihuangb09b3f92017-03-07 14:40:51 -08004105 }
4106
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004107 if (configuration.tcp_candidate_policy == kTcpCandidatePolicyDisabled) {
4108 portallocator_flags |= cricket::PORTALLOCATOR_DISABLE_TCP;
Mirko Bonadei675513b2017-11-09 11:09:25 +01004109 RTC_LOG(LS_INFO) << "TCP candidates are disabled.";
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004110 }
4111
honghaiz60347052016-05-31 18:29:12 -07004112 if (configuration.candidate_network_policy ==
4113 kCandidateNetworkPolicyLowCost) {
4114 portallocator_flags |= cricket::PORTALLOCATOR_DISABLE_COSTLY_NETWORKS;
Mirko Bonadei675513b2017-11-09 11:09:25 +01004115 RTC_LOG(LS_INFO) << "Do not gather candidates on high-cost networks";
honghaiz60347052016-05-31 18:29:12 -07004116 }
4117
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004118 port_allocator_->set_flags(portallocator_flags);
4119 // No step delay is used while allocating ports.
4120 port_allocator_->set_step_delay(cricket::kMinimumStepDelay);
4121 port_allocator_->set_candidate_filter(
4122 ConvertIceTransportTypeToCandidateFilter(configuration.type));
deadbeefd21eab32017-07-26 16:50:11 -07004123 port_allocator_->set_max_ipv6_networks(configuration.max_ipv6_networks);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004124
4125 // Call this last since it may create pooled allocator sessions using the
4126 // properties set above.
4127 port_allocator_->SetConfiguration(stun_servers, turn_servers,
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -07004128 configuration.ice_candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02004129 configuration.prune_turn_ports,
4130 configuration.turn_customizer);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004131 return true;
4132}
4133
deadbeef91dd5672016-05-18 16:55:30 -07004134bool PeerConnection::ReconfigurePortAllocator_n(
deadbeef293e9262017-01-11 12:28:30 -08004135 const cricket::ServerAddresses& stun_servers,
4136 const std::vector<cricket::RelayServerConfig>& turn_servers,
4137 IceTransportsType type,
4138 int candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02004139 bool prune_turn_ports,
4140 webrtc::TurnCustomizer* turn_customizer) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004141 port_allocator_->set_candidate_filter(
deadbeef293e9262017-01-11 12:28:30 -08004142 ConvertIceTransportTypeToCandidateFilter(type));
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004143 // Call this last since it may create pooled allocator sessions using the
4144 // candidate filter set above.
deadbeef6de92f92016-12-12 18:49:32 -08004145 return port_allocator_->SetConfiguration(
Jonas Orelandbdcee282017-10-10 14:01:40 +02004146 stun_servers, turn_servers, candidate_pool_size, prune_turn_ports,
4147 turn_customizer);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004148}
4149
Steve Antonba818672017-11-06 10:21:57 -08004150cricket::ChannelManager* PeerConnection::channel_manager() const {
4151 return factory_->channel_manager();
4152}
4153
4154MetricsObserverInterface* PeerConnection::metrics_observer() const {
4155 return uma_observer_;
4156}
4157
Elad Alon99c3fe52017-10-13 16:29:40 +02004158bool PeerConnection::StartRtcEventLog_w(
Bjorn Tereliusde939432017-11-20 17:38:14 +01004159 std::unique_ptr<RtcEventLogOutput> output,
4160 int64_t output_period_ms) {
zhihuang77985012017-02-07 15:45:16 -08004161 if (!event_log_) {
4162 return false;
4163 }
Bjorn Tereliusde939432017-11-20 17:38:14 +01004164 return event_log_->StartLogging(std::move(output), output_period_ms);
ivoc14d5dbe2016-07-04 07:06:55 -07004165}
4166
4167void PeerConnection::StopRtcEventLog_w() {
zhihuang77985012017-02-07 15:45:16 -08004168 if (event_log_) {
4169 event_log_->StopLogging();
4170 }
ivoc14d5dbe2016-07-04 07:06:55 -07004171}
nisseeaabdf62017-05-05 02:23:02 -07004172
Steve Anton75737c02017-11-06 10:37:17 -08004173cricket::BaseChannel* PeerConnection::GetChannel(
4174 const std::string& content_name) {
Steve Antondcc3c022017-12-22 16:02:54 -08004175 for (auto transceiver : transceivers_) {
4176 cricket::BaseChannel* channel = transceiver->internal()->channel();
4177 if (channel && channel->content_name() == content_name) {
4178 return channel;
4179 }
Steve Anton75737c02017-11-06 10:37:17 -08004180 }
4181 if (rtp_data_channel() &&
4182 rtp_data_channel()->content_name() == content_name) {
4183 return rtp_data_channel();
4184 }
4185 return nullptr;
4186}
4187
4188bool PeerConnection::GetSctpSslRole(rtc::SSLRole* role) {
4189 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004190 RTC_LOG(LS_INFO)
4191 << "Local and Remote descriptions must be applied to get the "
4192 << "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08004193 return false;
4194 }
4195 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004196 RTC_LOG(LS_INFO) << "Non-rejected SCTP m= section is needed to get the "
4197 << "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08004198 return false;
4199 }
4200
4201 return transport_controller_->GetSslRole(*sctp_transport_name_, role);
4202}
4203
4204bool PeerConnection::GetSslRole(const std::string& content_name,
4205 rtc::SSLRole* role) {
4206 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004207 RTC_LOG(LS_INFO)
4208 << "Local and Remote descriptions must be applied to get the "
4209 << "SSL Role of the session.";
Steve Anton75737c02017-11-06 10:37:17 -08004210 return false;
4211 }
4212
4213 return transport_controller_->GetSslRole(GetTransportName(content_name),
4214 role);
4215}
4216
Steve Anton75737c02017-11-06 10:37:17 -08004217// TODO(steveanton): Eventually it'd be nice to store the channels as a single
4218// vector of BaseChannel pointers instead of separate voice and video channel
4219// vectors. At that point, this will become a simple getter.
4220std::vector<cricket::BaseChannel*> PeerConnection::Channels() const {
4221 std::vector<cricket::BaseChannel*> channels;
Steve Anton4171afb2017-11-20 10:20:22 -08004222 if (voice_channel()) {
4223 channels.push_back(voice_channel());
4224 }
4225 if (video_channel()) {
4226 channels.push_back(video_channel());
4227 }
Steve Anton75737c02017-11-06 10:37:17 -08004228 if (rtp_data_channel_) {
4229 channels.push_back(rtp_data_channel_);
4230 }
4231 return channels;
4232}
4233
Steve Antonf8470812017-12-04 10:46:21 -08004234void PeerConnection::SetSessionError(SessionError error,
4235 const std::string& error_desc) {
4236 RTC_DCHECK_RUN_ON(signaling_thread());
4237 if (error != session_error_) {
4238 session_error_ = error;
4239 session_error_desc_ = error_desc;
Steve Anton75737c02017-11-06 10:37:17 -08004240 }
4241}
4242
Steve Anton3828c062017-12-06 10:34:51 -08004243RTCError PeerConnection::UpdateSessionState(SdpType type,
Steve Anton8a006912017-12-04 15:25:56 -08004244 cricket::ContentSource source) {
4245 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08004246
4247 // If there's already a pending error then no state transition should happen.
4248 // But all call-sites should be verifying this before calling us!
Steve Antonf8470812017-12-04 10:46:21 -08004249 RTC_DCHECK(session_error() == SessionError::kNone);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004250
4251 // If this is an answer then we know whether to BUNDLE or not. If both the
4252 // local and remote side have agreed to BUNDLE, go ahead and enable it.
Steve Anton3828c062017-12-06 10:34:51 -08004253 if (type == SdpType::kAnswer) {
Steve Anton75737c02017-11-06 10:37:17 -08004254 const cricket::ContentGroup* local_bundle =
4255 local_description()->description()->GetGroupByName(
4256 cricket::GROUP_TYPE_BUNDLE);
4257 const cricket::ContentGroup* remote_bundle =
4258 remote_description()->description()->GetGroupByName(
4259 cricket::GROUP_TYPE_BUNDLE);
4260 if (local_bundle && remote_bundle) {
4261 // The answerer decides the transport to bundle on.
4262 const cricket::ContentGroup* answer_bundle =
4263 (source == cricket::CS_LOCAL ? local_bundle : remote_bundle);
4264 if (!EnableBundle(*answer_bundle)) {
Steve Anton8a006912017-12-04 15:25:56 -08004265 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
4266 kEnableBundleFailed);
Steve Anton75737c02017-11-06 10:37:17 -08004267 }
4268 }
Steve Anton75737c02017-11-06 10:37:17 -08004269 }
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004270
4271 // Only push down the transport description after potentially enabling BUNDLE;
4272 // we don't want to push down a description on a transport about to be
4273 // destroyed.
Steve Anton3828c062017-12-06 10:34:51 -08004274 RTCError error = PushdownTransportDescription(source, type);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004275 if (!error.ok()) {
4276 return error;
4277 }
4278
4279 // If this is answer-ish we're ready to let media flow.
Steve Anton3828c062017-12-06 10:34:51 -08004280 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Antoned10bd92017-12-05 10:52:59 -08004281 EnableSending();
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004282 }
4283
4284 // Update the signaling state according to the specified state machine (see
4285 // https://w3c.github.io/webrtc-pc/#rtcsignalingstate-enum).
Steve Anton3828c062017-12-06 10:34:51 -08004286 if (type == SdpType::kOffer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004287 ChangeSignalingState(source == cricket::CS_LOCAL
4288 ? PeerConnectionInterface::kHaveLocalOffer
4289 : PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton3828c062017-12-06 10:34:51 -08004290 } else if (type == SdpType::kPrAnswer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004291 ChangeSignalingState(source == cricket::CS_LOCAL
4292 ? PeerConnectionInterface::kHaveLocalPrAnswer
4293 : PeerConnectionInterface::kHaveRemotePrAnswer);
4294 } else {
Steve Anton3828c062017-12-06 10:34:51 -08004295 RTC_DCHECK(type == SdpType::kAnswer);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004296 ChangeSignalingState(PeerConnectionInterface::kStable);
4297 }
4298
4299 // Update internal objects according to the session description's media
4300 // descriptions.
Steve Anton3828c062017-12-06 10:34:51 -08004301 error = PushdownMediaDescription(type, source);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004302 if (!error.ok()) {
4303 SetSessionError(SessionError::kContent, error.message());
4304 }
4305 if (session_error() != SessionError::kNone) {
4306 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
4307 }
4308
Steve Anton8a006912017-12-04 15:25:56 -08004309 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08004310}
4311
Steve Anton8a006912017-12-04 15:25:56 -08004312RTCError PeerConnection::PushdownMediaDescription(
Steve Anton3828c062017-12-06 10:34:51 -08004313 SdpType type,
Steve Anton8a006912017-12-04 15:25:56 -08004314 cricket::ContentSource source) {
Steve Antoned10bd92017-12-05 10:52:59 -08004315 const SessionDescriptionInterface* sdesc =
4316 (source == cricket::CS_LOCAL ? local_description()
4317 : remote_description());
Steve Anton75737c02017-11-06 10:37:17 -08004318 RTC_DCHECK(sdesc);
Steve Antoned10bd92017-12-05 10:52:59 -08004319
4320 // Push down the new SDP media section for each audio/video transceiver.
4321 for (auto transceiver : transceivers_) {
Steve Anton75737c02017-11-06 10:37:17 -08004322 const ContentInfo* content_info =
Steve Antoned10bd92017-12-05 10:52:59 -08004323 FindMediaSectionForTransceiver(transceiver, sdesc);
4324 cricket::BaseChannel* channel = transceiver->internal()->channel();
4325 if (!channel || !content_info || content_info->rejected) {
Steve Anton75737c02017-11-06 10:37:17 -08004326 continue;
4327 }
4328 const MediaContentDescription* content_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08004329 content_info->media_description();
Steve Antoned10bd92017-12-05 10:52:59 -08004330 if (!content_desc) {
4331 continue;
4332 }
4333 std::string error;
4334 bool success =
4335 (source == cricket::CS_LOCAL)
Steve Anton3828c062017-12-06 10:34:51 -08004336 ? channel->SetLocalContent(content_desc, type, &error)
4337 : channel->SetRemoteContent(content_desc, type, &error);
Steve Antoned10bd92017-12-05 10:52:59 -08004338 if (!success) {
4339 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, std::move(error));
4340 }
4341 }
4342
4343 // If using the RtpDataChannel, push down the new SDP section for it too.
4344 if (rtp_data_channel_) {
4345 const ContentInfo* data_content =
4346 cricket::GetFirstDataContent(sdesc->description());
4347 if (data_content && !data_content->rejected) {
4348 const MediaContentDescription* data_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08004349 data_content->media_description();
Steve Antoned10bd92017-12-05 10:52:59 -08004350 if (data_desc) {
4351 std::string error;
4352 bool success =
4353 (source == cricket::CS_LOCAL)
Steve Anton3828c062017-12-06 10:34:51 -08004354 ? rtp_data_channel_->SetLocalContent(data_desc, type, &error)
4355 : rtp_data_channel_->SetRemoteContent(data_desc, type,
Steve Antoned10bd92017-12-05 10:52:59 -08004356 &error);
4357 if (!success) {
4358 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
4359 std::move(error));
4360 }
Steve Anton75737c02017-11-06 10:37:17 -08004361 }
4362 }
4363 }
Steve Antoned10bd92017-12-05 10:52:59 -08004364
Steve Anton75737c02017-11-06 10:37:17 -08004365 // Need complete offer/answer with an SCTP m= section before starting SCTP,
4366 // according to https://tools.ietf.org/html/draft-ietf-mmusic-sctp-sdp-19
4367 if (sctp_transport_ && local_description() && remote_description() &&
4368 cricket::GetFirstDataContent(local_description()->description()) &&
4369 cricket::GetFirstDataContent(remote_description()->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08004370 bool success = network_thread()->Invoke<bool>(
Steve Anton75737c02017-11-06 10:37:17 -08004371 RTC_FROM_HERE,
4372 rtc::Bind(&PeerConnection::PushdownSctpParameters_n, this, source));
Steve Anton8a006912017-12-04 15:25:56 -08004373 if (!success) {
4374 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
4375 "Failed to push down SCTP parameters.");
4376 }
Steve Anton75737c02017-11-06 10:37:17 -08004377 }
Steve Antoned10bd92017-12-05 10:52:59 -08004378
Steve Anton8a006912017-12-04 15:25:56 -08004379 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08004380}
4381
4382bool PeerConnection::PushdownSctpParameters_n(cricket::ContentSource source) {
4383 RTC_DCHECK(network_thread()->IsCurrent());
4384 RTC_DCHECK(local_description());
4385 RTC_DCHECK(remote_description());
4386 // Apply the SCTP port (which is hidden inside a DataCodec structure...)
4387 // When we support "max-message-size", that would also be pushed down here.
4388 return sctp_transport_->Start(
4389 GetSctpPort(local_description()->description()),
4390 GetSctpPort(remote_description()->description()));
4391}
4392
Steve Anton8a006912017-12-04 15:25:56 -08004393RTCError PeerConnection::PushdownTransportDescription(
4394 cricket::ContentSource source,
Steve Anton3828c062017-12-06 10:34:51 -08004395 SdpType type) {
Steve Anton8a006912017-12-04 15:25:56 -08004396 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08004397
Steve Anton8a006912017-12-04 15:25:56 -08004398 const SessionDescriptionInterface* sdesc =
4399 (source == cricket::CS_LOCAL ? local_description()
4400 : remote_description());
4401 RTC_DCHECK(sdesc);
4402 for (const cricket::TransportInfo& tinfo :
4403 sdesc->description()->transport_infos()) {
4404 std::string error;
4405 bool success;
4406 if (source == cricket::CS_LOCAL) {
4407 success = transport_controller_->SetLocalTransportDescription(
Steve Anton3828c062017-12-06 10:34:51 -08004408 tinfo.content_name, tinfo.description, type, &error);
Steve Anton8a006912017-12-04 15:25:56 -08004409 } else {
4410 success = transport_controller_->SetRemoteTransportDescription(
Steve Anton3828c062017-12-06 10:34:51 -08004411 tinfo.content_name, tinfo.description, type, &error);
Steve Anton8a006912017-12-04 15:25:56 -08004412 }
4413 if (!success) {
Steve Antondcc3c022017-12-22 16:02:54 -08004414 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
4415 "Failed to push down transport description for " +
4416 tinfo.content_name + ": " + error);
Steve Anton75737c02017-11-06 10:37:17 -08004417 }
4418 }
4419
Steve Anton8a006912017-12-04 15:25:56 -08004420 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08004421}
4422
4423bool PeerConnection::GetTransportDescription(
4424 const SessionDescription* description,
4425 const std::string& content_name,
4426 cricket::TransportDescription* tdesc) {
4427 if (!description || !tdesc) {
4428 return false;
4429 }
4430 const TransportInfo* transport_info =
4431 description->GetTransportInfoByName(content_name);
4432 if (!transport_info) {
4433 return false;
4434 }
4435 *tdesc = transport_info->description;
4436 return true;
4437}
4438
4439bool PeerConnection::EnableBundle(const cricket::ContentGroup& bundle) {
4440 const std::string* first_content_name = bundle.FirstContentName();
4441 if (!first_content_name) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004442 RTC_LOG(LS_WARNING) << "Tried to BUNDLE with no contents.";
Steve Anton75737c02017-11-06 10:37:17 -08004443 return false;
4444 }
4445 const std::string& transport_name = *first_content_name;
4446
4447 auto maybe_set_transport = [this, bundle,
4448 transport_name](cricket::BaseChannel* ch) {
4449 if (!ch || !bundle.HasContentName(ch->content_name())) {
Steve Antoned10bd92017-12-05 10:52:59 -08004450 return;
Steve Anton75737c02017-11-06 10:37:17 -08004451 }
4452
4453 std::string old_transport_name = ch->transport_name();
4454 if (old_transport_name == transport_name) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004455 RTC_LOG(LS_INFO) << "BUNDLE already enabled for " << ch->content_name()
4456 << " on " << transport_name << ".";
Steve Antoned10bd92017-12-05 10:52:59 -08004457 return;
Steve Anton75737c02017-11-06 10:37:17 -08004458 }
4459
4460 cricket::DtlsTransportInternal* rtp_dtls_transport =
4461 transport_controller_->CreateDtlsTransport(
4462 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4463 bool need_rtcp = (ch->rtcp_dtls_transport() != nullptr);
4464 cricket::DtlsTransportInternal* rtcp_dtls_transport = nullptr;
4465 if (need_rtcp) {
4466 rtcp_dtls_transport = transport_controller_->CreateDtlsTransport(
4467 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
4468 }
4469
4470 ch->SetTransports(rtp_dtls_transport, rtcp_dtls_transport);
Mirko Bonadei675513b2017-11-09 11:09:25 +01004471 RTC_LOG(LS_INFO) << "Enabled BUNDLE for " << ch->content_name() << " on "
4472 << transport_name << ".";
Steve Anton75737c02017-11-06 10:37:17 -08004473 transport_controller_->DestroyDtlsTransport(
4474 old_transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4475 // If the channel needs rtcp, it means that the channel used to have a
4476 // rtcp transport which needs to be deleted now.
4477 if (need_rtcp) {
4478 transport_controller_->DestroyDtlsTransport(
4479 old_transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
4480 }
Steve Anton75737c02017-11-06 10:37:17 -08004481 };
4482
Steve Antoned10bd92017-12-05 10:52:59 -08004483 for (auto transceiver : transceivers_) {
4484 maybe_set_transport(transceiver->internal()->channel());
Steve Anton75737c02017-11-06 10:37:17 -08004485 }
Steve Antoned10bd92017-12-05 10:52:59 -08004486 maybe_set_transport(rtp_data_channel_);
4487
Steve Anton75737c02017-11-06 10:37:17 -08004488 // For SCTP, transport creation/deletion happens here instead of in the
4489 // object itself.
4490 if (sctp_transport_) {
4491 RTC_DCHECK(sctp_transport_name_);
4492 RTC_DCHECK(sctp_content_name_);
4493 if (transport_name != *sctp_transport_name_ &&
4494 bundle.HasContentName(*sctp_content_name_)) {
4495 network_thread()->Invoke<void>(
4496 RTC_FROM_HERE, rtc::Bind(&PeerConnection::ChangeSctpTransport_n, this,
4497 transport_name));
4498 }
4499 }
4500
4501 return true;
4502}
4503
Steve Anton75737c02017-11-06 10:37:17 -08004504cricket::IceConfig PeerConnection::ParseIceConfig(
4505 const PeerConnectionInterface::RTCConfiguration& config) const {
4506 cricket::ContinualGatheringPolicy gathering_policy;
4507 // TODO(honghaiz): Add the third continual gathering policy in
4508 // PeerConnectionInterface and map it to GATHER_CONTINUALLY_AND_RECOVER.
4509 switch (config.continual_gathering_policy) {
4510 case PeerConnectionInterface::GATHER_ONCE:
4511 gathering_policy = cricket::GATHER_ONCE;
4512 break;
4513 case PeerConnectionInterface::GATHER_CONTINUALLY:
4514 gathering_policy = cricket::GATHER_CONTINUALLY;
4515 break;
4516 default:
4517 RTC_NOTREACHED();
4518 gathering_policy = cricket::GATHER_ONCE;
4519 }
4520 cricket::IceConfig ice_config;
4521 ice_config.receiving_timeout = config.ice_connection_receiving_timeout;
4522 ice_config.prioritize_most_likely_candidate_pairs =
4523 config.prioritize_most_likely_ice_candidate_pairs;
4524 ice_config.backup_connection_ping_interval =
4525 config.ice_backup_candidate_pair_ping_interval;
4526 ice_config.continual_gathering_policy = gathering_policy;
4527 ice_config.presume_writable_when_fully_relayed =
4528 config.presume_writable_when_fully_relayed;
4529 ice_config.ice_check_min_interval = config.ice_check_min_interval;
4530 ice_config.regather_all_networks_interval_range =
4531 config.ice_regather_interval_range;
4532 return ice_config;
4533}
4534
Steve Anton75737c02017-11-06 10:37:17 -08004535bool PeerConnection::GetLocalTrackIdBySsrc(uint32_t ssrc,
4536 std::string* track_id) {
4537 if (!local_description()) {
4538 return false;
4539 }
4540 return webrtc::GetTrackIdBySsrc(local_description()->description(), ssrc,
4541 track_id);
4542}
4543
4544bool PeerConnection::GetRemoteTrackIdBySsrc(uint32_t ssrc,
4545 std::string* track_id) {
4546 if (!remote_description()) {
4547 return false;
4548 }
4549 return webrtc::GetTrackIdBySsrc(remote_description()->description(), ssrc,
4550 track_id);
4551}
4552
4553bool PeerConnection::SendData(const cricket::SendDataParams& params,
4554 const rtc::CopyOnWriteBuffer& payload,
4555 cricket::SendDataResult* result) {
4556 if (!rtp_data_channel_ && !sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004557 RTC_LOG(LS_ERROR) << "SendData called when rtp_data_channel_ "
4558 << "and sctp_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08004559 return false;
4560 }
4561 return rtp_data_channel_
4562 ? rtp_data_channel_->SendData(params, payload, result)
4563 : network_thread()->Invoke<bool>(
4564 RTC_FROM_HERE,
4565 Bind(&cricket::SctpTransportInternal::SendData,
4566 sctp_transport_.get(), params, payload, result));
4567}
4568
4569bool PeerConnection::ConnectDataChannel(DataChannel* webrtc_data_channel) {
4570 if (!rtp_data_channel_ && !sctp_transport_) {
4571 // Don't log an error here, because DataChannels are expected to call
4572 // ConnectDataChannel in this state. It's the only way to initially tell
4573 // whether or not the underlying transport is ready.
4574 return false;
4575 }
4576 if (rtp_data_channel_) {
4577 rtp_data_channel_->SignalReadyToSendData.connect(
4578 webrtc_data_channel, &DataChannel::OnChannelReady);
4579 rtp_data_channel_->SignalDataReceived.connect(webrtc_data_channel,
4580 &DataChannel::OnDataReceived);
4581 } else {
4582 SignalSctpReadyToSendData.connect(webrtc_data_channel,
4583 &DataChannel::OnChannelReady);
4584 SignalSctpDataReceived.connect(webrtc_data_channel,
4585 &DataChannel::OnDataReceived);
4586 SignalSctpStreamClosedRemotely.connect(
4587 webrtc_data_channel, &DataChannel::OnStreamClosedRemotely);
4588 }
4589 return true;
4590}
4591
4592void PeerConnection::DisconnectDataChannel(DataChannel* webrtc_data_channel) {
4593 if (!rtp_data_channel_ && !sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004594 RTC_LOG(LS_ERROR)
4595 << "DisconnectDataChannel called when rtp_data_channel_ and "
4596 "sctp_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08004597 return;
4598 }
4599 if (rtp_data_channel_) {
4600 rtp_data_channel_->SignalReadyToSendData.disconnect(webrtc_data_channel);
4601 rtp_data_channel_->SignalDataReceived.disconnect(webrtc_data_channel);
4602 } else {
4603 SignalSctpReadyToSendData.disconnect(webrtc_data_channel);
4604 SignalSctpDataReceived.disconnect(webrtc_data_channel);
4605 SignalSctpStreamClosedRemotely.disconnect(webrtc_data_channel);
4606 }
4607}
4608
4609void PeerConnection::AddSctpDataStream(int sid) {
4610 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004611 RTC_LOG(LS_ERROR)
4612 << "AddSctpDataStream called when sctp_transport_ is NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08004613 return;
4614 }
4615 network_thread()->Invoke<void>(
4616 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::OpenStream,
4617 sctp_transport_.get(), sid));
4618}
4619
4620void PeerConnection::RemoveSctpDataStream(int sid) {
4621 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004622 RTC_LOG(LS_ERROR) << "RemoveSctpDataStream called when sctp_transport_ is "
4623 << "NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08004624 return;
4625 }
4626 network_thread()->Invoke<void>(
4627 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::ResetStream,
4628 sctp_transport_.get(), sid));
4629}
4630
4631bool PeerConnection::ReadyToSendData() const {
4632 return (rtp_data_channel_ && rtp_data_channel_->ready_to_send_data()) ||
4633 sctp_ready_to_send_data_;
4634}
4635
4636std::unique_ptr<SessionStats> PeerConnection::GetSessionStats_s() {
4637 RTC_DCHECK(signaling_thread()->IsCurrent());
4638 ChannelNamePairs channel_name_pairs;
4639 if (voice_channel()) {
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004640 channel_name_pairs.voice = ChannelNamePair(
4641 voice_channel()->content_name(), voice_channel()->transport_name());
Steve Anton75737c02017-11-06 10:37:17 -08004642 }
4643 if (video_channel()) {
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004644 channel_name_pairs.video = ChannelNamePair(
4645 video_channel()->content_name(), video_channel()->transport_name());
Steve Anton75737c02017-11-06 10:37:17 -08004646 }
4647 if (rtp_data_channel()) {
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004648 channel_name_pairs.data =
Steve Anton75737c02017-11-06 10:37:17 -08004649 ChannelNamePair(rtp_data_channel()->content_name(),
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004650 rtp_data_channel()->transport_name());
Steve Anton75737c02017-11-06 10:37:17 -08004651 }
4652 if (sctp_transport_) {
4653 RTC_DCHECK(sctp_content_name_);
4654 RTC_DCHECK(sctp_transport_name_);
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004655 channel_name_pairs.data =
4656 ChannelNamePair(*sctp_content_name_, *sctp_transport_name_);
Steve Anton75737c02017-11-06 10:37:17 -08004657 }
4658 return GetSessionStats(channel_name_pairs);
4659}
4660
4661std::unique_ptr<SessionStats> PeerConnection::GetSessionStats(
4662 const ChannelNamePairs& channel_name_pairs) {
4663 if (network_thread()->IsCurrent()) {
4664 return GetSessionStats_n(channel_name_pairs);
4665 }
4666 return network_thread()->Invoke<std::unique_ptr<SessionStats>>(
4667 RTC_FROM_HERE,
4668 rtc::Bind(&PeerConnection::GetSessionStats_n, this, channel_name_pairs));
4669}
4670
4671bool PeerConnection::GetLocalCertificate(
4672 const std::string& transport_name,
4673 rtc::scoped_refptr<rtc::RTCCertificate>* certificate) {
4674 return transport_controller_->GetLocalCertificate(transport_name,
4675 certificate);
4676}
4677
4678std::unique_ptr<rtc::SSLCertificate> PeerConnection::GetRemoteSSLCertificate(
4679 const std::string& transport_name) {
4680 return transport_controller_->GetRemoteSSLCertificate(transport_name);
4681}
4682
4683cricket::DataChannelType PeerConnection::data_channel_type() const {
4684 return data_channel_type_;
4685}
4686
4687bool PeerConnection::IceRestartPending(const std::string& content_name) const {
4688 return pending_ice_restarts_.find(content_name) !=
4689 pending_ice_restarts_.end();
4690}
4691
Steve Anton75737c02017-11-06 10:37:17 -08004692bool PeerConnection::NeedsIceRestart(const std::string& content_name) const {
4693 return transport_controller_->NeedsIceRestart(content_name);
4694}
4695
4696void PeerConnection::OnCertificateReady(
4697 const rtc::scoped_refptr<rtc::RTCCertificate>& certificate) {
4698 transport_controller_->SetLocalCertificate(certificate);
4699}
4700
4701void PeerConnection::OnDtlsSrtpSetupFailure(cricket::BaseChannel*, bool rtcp) {
Steve Antonf8470812017-12-04 10:46:21 -08004702 SetSessionError(SessionError::kTransport,
4703 rtcp ? kDtlsSrtpSetupFailureRtcp : kDtlsSrtpSetupFailureRtp);
Steve Anton75737c02017-11-06 10:37:17 -08004704}
4705
4706void PeerConnection::OnTransportControllerConnectionState(
4707 cricket::IceConnectionState state) {
4708 switch (state) {
4709 case cricket::kIceConnectionConnecting:
4710 // If the current state is Connected or Completed, then there were
4711 // writable channels but now there are not, so the next state must
4712 // be Disconnected.
4713 // kIceConnectionConnecting is currently used as the default,
4714 // un-connected state by the TransportController, so its only use is
4715 // detecting disconnections.
4716 if (ice_connection_state_ ==
4717 PeerConnectionInterface::kIceConnectionConnected ||
4718 ice_connection_state_ ==
4719 PeerConnectionInterface::kIceConnectionCompleted) {
4720 SetIceConnectionState(
4721 PeerConnectionInterface::kIceConnectionDisconnected);
4722 }
4723 break;
4724 case cricket::kIceConnectionFailed:
4725 SetIceConnectionState(PeerConnectionInterface::kIceConnectionFailed);
4726 break;
4727 case cricket::kIceConnectionConnected:
Mirko Bonadei675513b2017-11-09 11:09:25 +01004728 RTC_LOG(LS_INFO) << "Changing to ICE connected state because "
4729 << "all transports are writable.";
Steve Anton75737c02017-11-06 10:37:17 -08004730 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
4731 break;
4732 case cricket::kIceConnectionCompleted:
Mirko Bonadei675513b2017-11-09 11:09:25 +01004733 RTC_LOG(LS_INFO) << "Changing to ICE completed state because "
4734 << "all transports are complete.";
Steve Anton75737c02017-11-06 10:37:17 -08004735 if (ice_connection_state_ !=
4736 PeerConnectionInterface::kIceConnectionConnected) {
4737 // If jumping directly from "checking" to "connected",
4738 // signal "connected" first.
4739 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
4740 }
4741 SetIceConnectionState(PeerConnectionInterface::kIceConnectionCompleted);
4742 if (metrics_observer()) {
4743 ReportTransportStats();
4744 }
4745 break;
4746 default:
4747 RTC_NOTREACHED();
4748 }
4749}
4750
4751void PeerConnection::OnTransportControllerCandidatesGathered(
4752 const std::string& transport_name,
4753 const cricket::Candidates& candidates) {
4754 RTC_DCHECK(signaling_thread()->IsCurrent());
4755 int sdp_mline_index;
4756 if (!GetLocalCandidateMediaIndex(transport_name, &sdp_mline_index)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004757 RTC_LOG(LS_ERROR)
4758 << "OnTransportControllerCandidatesGathered: content name "
4759 << transport_name << " not found";
Steve Anton75737c02017-11-06 10:37:17 -08004760 return;
4761 }
4762
4763 for (cricket::Candidates::const_iterator citer = candidates.begin();
4764 citer != candidates.end(); ++citer) {
4765 // Use transport_name as the candidate media id.
4766 std::unique_ptr<JsepIceCandidate> candidate(
4767 new JsepIceCandidate(transport_name, sdp_mline_index, *citer));
4768 if (local_description()) {
4769 mutable_local_description()->AddCandidate(candidate.get());
4770 }
4771 OnIceCandidate(std::move(candidate));
4772 }
4773}
4774
4775void PeerConnection::OnTransportControllerCandidatesRemoved(
4776 const std::vector<cricket::Candidate>& candidates) {
4777 RTC_DCHECK(signaling_thread()->IsCurrent());
4778 // Sanity check.
4779 for (const cricket::Candidate& candidate : candidates) {
4780 if (candidate.transport_name().empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004781 RTC_LOG(LS_ERROR) << "OnTransportControllerCandidatesRemoved: "
4782 << "empty content name in candidate "
4783 << candidate.ToString();
Steve Anton75737c02017-11-06 10:37:17 -08004784 return;
4785 }
4786 }
4787
4788 if (local_description()) {
4789 mutable_local_description()->RemoveCandidates(candidates);
4790 }
4791 OnIceCandidatesRemoved(candidates);
4792}
4793
4794void PeerConnection::OnTransportControllerDtlsHandshakeError(
4795 rtc::SSLHandshakeError error) {
4796 if (metrics_observer()) {
4797 metrics_observer()->IncrementEnumCounter(
4798 webrtc::kEnumCounterDtlsHandshakeError, static_cast<int>(error),
4799 static_cast<int>(rtc::SSLHandshakeError::MAX_VALUE));
4800 }
4801}
4802
Steve Antoned10bd92017-12-05 10:52:59 -08004803void PeerConnection::EnableSending() {
4804 for (auto transceiver : transceivers_) {
4805 cricket::BaseChannel* channel = transceiver->internal()->channel();
4806 if (channel && !channel->enabled()) {
4807 channel->Enable(true);
4808 }
Steve Anton75737c02017-11-06 10:37:17 -08004809 }
4810
Steve Anton4171afb2017-11-20 10:20:22 -08004811 if (rtp_data_channel_ && !rtp_data_channel_->enabled()) {
Steve Anton75737c02017-11-06 10:37:17 -08004812 rtp_data_channel_->Enable(true);
Steve Anton4171afb2017-11-20 10:20:22 -08004813 }
Steve Anton75737c02017-11-06 10:37:17 -08004814}
4815
4816// Returns the media index for a local ice candidate given the content name.
4817bool PeerConnection::GetLocalCandidateMediaIndex(
4818 const std::string& content_name,
4819 int* sdp_mline_index) {
4820 if (!local_description() || !sdp_mline_index) {
4821 return false;
4822 }
4823
4824 bool content_found = false;
4825 const ContentInfos& contents = local_description()->description()->contents();
4826 for (size_t index = 0; index < contents.size(); ++index) {
4827 if (contents[index].name == content_name) {
4828 *sdp_mline_index = static_cast<int>(index);
4829 content_found = true;
4830 break;
4831 }
4832 }
4833 return content_found;
4834}
4835
4836bool PeerConnection::UseCandidatesInSessionDescription(
4837 const SessionDescriptionInterface* remote_desc) {
4838 if (!remote_desc) {
4839 return true;
4840 }
4841 bool ret = true;
4842
4843 for (size_t m = 0; m < remote_desc->number_of_mediasections(); ++m) {
4844 const IceCandidateCollection* candidates = remote_desc->candidates(m);
4845 for (size_t n = 0; n < candidates->count(); ++n) {
4846 const IceCandidateInterface* candidate = candidates->at(n);
4847 bool valid = false;
4848 if (!ReadyToUseRemoteCandidate(candidate, remote_desc, &valid)) {
4849 if (valid) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004850 RTC_LOG(LS_INFO)
4851 << "UseCandidatesInSessionDescription: Not ready to use "
4852 << "candidate.";
Steve Anton75737c02017-11-06 10:37:17 -08004853 }
4854 continue;
4855 }
4856 ret = UseCandidate(candidate);
4857 if (!ret) {
4858 break;
4859 }
4860 }
4861 }
4862 return ret;
4863}
4864
4865bool PeerConnection::UseCandidate(const IceCandidateInterface* candidate) {
4866 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
4867 size_t remote_content_size =
4868 remote_description()->description()->contents().size();
4869 if (mediacontent_index >= remote_content_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004870 RTC_LOG(LS_ERROR) << "UseCandidate: Invalid candidate media index.";
Steve Anton75737c02017-11-06 10:37:17 -08004871 return false;
4872 }
4873
4874 cricket::ContentInfo content =
4875 remote_description()->description()->contents()[mediacontent_index];
4876 std::vector<cricket::Candidate> candidates;
4877 candidates.push_back(candidate->candidate());
4878 // Invoking BaseSession method to handle remote candidates.
4879 std::string error;
4880 if (transport_controller_->AddRemoteCandidates(content.name, candidates,
4881 &error)) {
4882 // Candidates successfully submitted for checking.
4883 if (ice_connection_state_ == PeerConnectionInterface::kIceConnectionNew ||
4884 ice_connection_state_ ==
4885 PeerConnectionInterface::kIceConnectionDisconnected) {
4886 // If state is New, then the session has just gotten its first remote ICE
4887 // candidates, so go to Checking.
4888 // If state is Disconnected, the session is re-using old candidates or
4889 // receiving additional ones, so go to Checking.
4890 // If state is Connected, stay Connected.
4891 // TODO(bemasc): If state is Connected, and the new candidates are for a
4892 // newly added transport, then the state actually _should_ move to
4893 // checking. Add a way to distinguish that case.
4894 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
4895 }
4896 // TODO(bemasc): If state is Completed, go back to Connected.
4897 } else {
4898 if (!error.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004899 RTC_LOG(LS_WARNING) << error;
Steve Anton75737c02017-11-06 10:37:17 -08004900 }
4901 }
4902 return true;
4903}
4904
4905void PeerConnection::RemoveUnusedChannels(const SessionDescription* desc) {
Steve Anton75737c02017-11-06 10:37:17 -08004906 // Destroy video channel first since it may have a pointer to the
4907 // voice channel.
4908 const cricket::ContentInfo* video_info = cricket::GetFirstVideoContent(desc);
Steve Anton6fec8802017-12-04 10:37:29 -08004909 if (!video_info || video_info->rejected) {
4910 DestroyTransceiverChannel(GetVideoTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08004911 }
4912
Steve Anton6fec8802017-12-04 10:37:29 -08004913 const cricket::ContentInfo* audio_info = cricket::GetFirstAudioContent(desc);
4914 if (!audio_info || audio_info->rejected) {
4915 DestroyTransceiverChannel(GetAudioTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08004916 }
4917
4918 const cricket::ContentInfo* data_info = cricket::GetFirstDataContent(desc);
4919 if (!data_info || data_info->rejected) {
Steve Anton6fec8802017-12-04 10:37:29 -08004920 DestroyDataChannel();
Steve Anton75737c02017-11-06 10:37:17 -08004921 }
4922}
4923
Steve Antoneda6ccd2017-12-04 10:21:55 -08004924std::string PeerConnection::GetTransportNameForMediaSection(
4925 const std::string& mid,
4926 const cricket::ContentGroup* bundle_group) const {
4927 if (!bundle_group) {
4928 return mid;
Steve Anton75737c02017-11-06 10:37:17 -08004929 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08004930 const std::string* first_content_name = bundle_group->FirstContentName();
Steve Anton75737c02017-11-06 10:37:17 -08004931 if (!first_content_name) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004932 RTC_LOG(LS_WARNING) << "Tried to BUNDLE with no contents.";
Steve Antoneda6ccd2017-12-04 10:21:55 -08004933 return mid;
Steve Anton75737c02017-11-06 10:37:17 -08004934 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08004935 if (!bundle_group->HasContentName(mid)) {
4936 RTC_LOG(LS_WARNING) << mid << " is not part of any bundle group";
4937 return mid;
Steve Anton75737c02017-11-06 10:37:17 -08004938 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08004939 RTC_LOG(LS_INFO) << "Bundling " << mid << " on " << *first_content_name;
4940 return *first_content_name;
Steve Anton75737c02017-11-06 10:37:17 -08004941}
4942
Steve Antondcc3c022017-12-22 16:02:54 -08004943RTCErrorOr<const cricket::ContentGroup*> PeerConnection::GetEarlyBundleGroup(
4944 const SessionDescription& desc) const {
Steve Anton75737c02017-11-06 10:37:17 -08004945 const cricket::ContentGroup* bundle_group = nullptr;
4946 if (configuration_.bundle_policy ==
4947 PeerConnectionInterface::kBundlePolicyMaxBundle) {
Steve Antondcc3c022017-12-22 16:02:54 -08004948 bundle_group = desc.GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton75737c02017-11-06 10:37:17 -08004949 if (!bundle_group) {
Steve Anton8a006912017-12-04 15:25:56 -08004950 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
4951 "max-bundle configured but session description "
4952 "has no BUNDLE group");
Steve Anton75737c02017-11-06 10:37:17 -08004953 }
4954 }
Steve Antondcc3c022017-12-22 16:02:54 -08004955 return std::move(bundle_group);
4956}
4957
4958RTCError PeerConnection::CreateChannels(const SessionDescription& desc) {
4959 auto bundle_group_or_error = GetEarlyBundleGroup(desc);
4960 if (!bundle_group_or_error.ok()) {
4961 return bundle_group_or_error.MoveError();
4962 }
4963 const cricket::ContentGroup* bundle_group = bundle_group_or_error.MoveValue();
Steve Anton75737c02017-11-06 10:37:17 -08004964
Steve Antoneda6ccd2017-12-04 10:21:55 -08004965 // Creating the media channels and transport proxies.
Steve Antondcc3c022017-12-22 16:02:54 -08004966 const cricket::ContentInfo* voice = cricket::GetFirstAudioContent(&desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08004967 if (voice && !voice->rejected &&
4968 !GetAudioTransceiver()->internal()->channel()) {
4969 cricket::VoiceChannel* voice_channel = CreateVoiceChannel(
4970 voice->name,
4971 GetTransportNameForMediaSection(voice->name, bundle_group));
4972 if (!voice_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08004973 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
4974 "Failed to create voice channel.");
Steve Antoneda6ccd2017-12-04 10:21:55 -08004975 }
4976 GetAudioTransceiver()->internal()->SetChannel(voice_channel);
4977 }
4978
Steve Antondcc3c022017-12-22 16:02:54 -08004979 const cricket::ContentInfo* video = cricket::GetFirstVideoContent(&desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08004980 if (video && !video->rejected &&
4981 !GetVideoTransceiver()->internal()->channel()) {
4982 cricket::VideoChannel* video_channel = CreateVideoChannel(
4983 video->name,
4984 GetTransportNameForMediaSection(video->name, bundle_group));
4985 if (!video_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08004986 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
4987 "Failed to create video channel.");
Steve Anton75737c02017-11-06 10:37:17 -08004988 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08004989 GetVideoTransceiver()->internal()->SetChannel(video_channel);
Steve Anton75737c02017-11-06 10:37:17 -08004990 }
4991
Steve Antondcc3c022017-12-22 16:02:54 -08004992 const cricket::ContentInfo* data = cricket::GetFirstDataContent(&desc);
Steve Anton75737c02017-11-06 10:37:17 -08004993 if (data_channel_type_ != cricket::DCT_NONE && data && !data->rejected &&
4994 !rtp_data_channel_ && !sctp_transport_) {
Steve Antoneda6ccd2017-12-04 10:21:55 -08004995 if (!CreateDataChannel(data->name, GetTransportNameForMediaSection(
4996 data->name, bundle_group))) {
Steve Anton8a006912017-12-04 15:25:56 -08004997 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
4998 "Failed to create data channel.");
Steve Anton75737c02017-11-06 10:37:17 -08004999 }
5000 }
5001
Steve Anton8a006912017-12-04 15:25:56 -08005002 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08005003}
5004
Steve Anton4171afb2017-11-20 10:20:22 -08005005// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08005006cricket::VoiceChannel* PeerConnection::CreateVoiceChannel(
5007 const std::string& mid,
5008 const std::string& transport_name) {
Steve Anton75737c02017-11-06 10:37:17 -08005009 cricket::DtlsTransportInternal* rtp_dtls_transport =
5010 transport_controller_->CreateDtlsTransport(
5011 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5012 cricket::DtlsTransportInternal* rtcp_dtls_transport = nullptr;
5013 if (configuration_.rtcp_mux_policy !=
5014 PeerConnectionInterface::kRtcpMuxPolicyRequire) {
5015 rtcp_dtls_transport = transport_controller_->CreateDtlsTransport(
5016 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
5017 }
5018
5019 cricket::VoiceChannel* voice_channel = channel_manager()->CreateVoiceChannel(
5020 call_.get(), configuration_.media_config, rtp_dtls_transport,
Steve Antoneda6ccd2017-12-04 10:21:55 -08005021 rtcp_dtls_transport, signaling_thread(), mid, SrtpRequired(),
5022 audio_options_);
Steve Anton75737c02017-11-06 10:37:17 -08005023 if (!voice_channel) {
5024 transport_controller_->DestroyDtlsTransport(
5025 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5026 if (rtcp_dtls_transport) {
5027 transport_controller_->DestroyDtlsTransport(
5028 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
5029 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005030 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08005031 }
Steve Anton75737c02017-11-06 10:37:17 -08005032 voice_channel->SignalRtcpMuxFullyActive.connect(
5033 this, &PeerConnection::DestroyRtcpTransport_n);
5034 voice_channel->SignalDtlsSrtpSetupFailure.connect(
5035 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08005036 voice_channel->SignalSentPacket.connect(this,
5037 &PeerConnection::OnSentPacket_w);
Steve Anton4171afb2017-11-20 10:20:22 -08005038
Steve Antoneda6ccd2017-12-04 10:21:55 -08005039 return voice_channel;
Steve Anton75737c02017-11-06 10:37:17 -08005040}
5041
Steve Anton4171afb2017-11-20 10:20:22 -08005042// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08005043cricket::VideoChannel* PeerConnection::CreateVideoChannel(
5044 const std::string& mid,
5045 const std::string& transport_name) {
Steve Anton75737c02017-11-06 10:37:17 -08005046 cricket::DtlsTransportInternal* rtp_dtls_transport =
5047 transport_controller_->CreateDtlsTransport(
5048 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5049 cricket::DtlsTransportInternal* rtcp_dtls_transport = nullptr;
5050 if (configuration_.rtcp_mux_policy !=
5051 PeerConnectionInterface::kRtcpMuxPolicyRequire) {
5052 rtcp_dtls_transport = transport_controller_->CreateDtlsTransport(
5053 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
5054 }
5055
5056 cricket::VideoChannel* video_channel = channel_manager()->CreateVideoChannel(
5057 call_.get(), configuration_.media_config, rtp_dtls_transport,
Steve Antoneda6ccd2017-12-04 10:21:55 -08005058 rtcp_dtls_transport, signaling_thread(), mid, SrtpRequired(),
5059 video_options_);
Steve Anton75737c02017-11-06 10:37:17 -08005060
5061 if (!video_channel) {
5062 transport_controller_->DestroyDtlsTransport(
5063 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5064 if (rtcp_dtls_transport) {
5065 transport_controller_->DestroyDtlsTransport(
5066 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
5067 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005068 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08005069 }
Steve Anton75737c02017-11-06 10:37:17 -08005070 video_channel->SignalRtcpMuxFullyActive.connect(
5071 this, &PeerConnection::DestroyRtcpTransport_n);
5072 video_channel->SignalDtlsSrtpSetupFailure.connect(
5073 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08005074 video_channel->SignalSentPacket.connect(this,
5075 &PeerConnection::OnSentPacket_w);
Steve Anton4171afb2017-11-20 10:20:22 -08005076
Steve Antoneda6ccd2017-12-04 10:21:55 -08005077 return video_channel;
Steve Anton75737c02017-11-06 10:37:17 -08005078}
5079
Steve Antoneda6ccd2017-12-04 10:21:55 -08005080bool PeerConnection::CreateDataChannel(const std::string& mid,
5081 const std::string& transport_name) {
Steve Anton75737c02017-11-06 10:37:17 -08005082 bool sctp = (data_channel_type_ == cricket::DCT_SCTP);
5083 if (sctp) {
5084 if (!sctp_factory_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005085 RTC_LOG(LS_ERROR)
Steve Anton75737c02017-11-06 10:37:17 -08005086 << "Trying to create SCTP transport, but didn't compile with "
5087 "SCTP support (HAVE_SCTP)";
5088 return false;
5089 }
5090 if (!network_thread()->Invoke<bool>(
5091 RTC_FROM_HERE, rtc::Bind(&PeerConnection::CreateSctpTransport_n,
Steve Antoneda6ccd2017-12-04 10:21:55 -08005092 this, mid, transport_name))) {
Steve Anton75737c02017-11-06 10:37:17 -08005093 return false;
5094 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005095 for (const auto& channel : sctp_data_channels_) {
5096 channel->OnTransportChannelCreated();
5097 }
Steve Anton75737c02017-11-06 10:37:17 -08005098 } else {
Steve Anton75737c02017-11-06 10:37:17 -08005099 cricket::DtlsTransportInternal* rtp_dtls_transport =
5100 transport_controller_->CreateDtlsTransport(
5101 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5102 cricket::DtlsTransportInternal* rtcp_dtls_transport = nullptr;
5103 if (configuration_.rtcp_mux_policy !=
5104 PeerConnectionInterface::kRtcpMuxPolicyRequire) {
5105 rtcp_dtls_transport = transport_controller_->CreateDtlsTransport(
5106 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
5107 }
5108
5109 rtp_data_channel_ = channel_manager()->CreateRtpDataChannel(
5110 configuration_.media_config, rtp_dtls_transport, rtcp_dtls_transport,
Steve Antoneda6ccd2017-12-04 10:21:55 -08005111 signaling_thread(), mid, SrtpRequired());
Steve Anton75737c02017-11-06 10:37:17 -08005112
5113 if (!rtp_data_channel_) {
5114 transport_controller_->DestroyDtlsTransport(
5115 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5116 if (rtcp_dtls_transport) {
5117 transport_controller_->DestroyDtlsTransport(
5118 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
5119 }
5120 return false;
5121 }
5122
5123 rtp_data_channel_->SignalRtcpMuxFullyActive.connect(
5124 this, &PeerConnection::DestroyRtcpTransport_n);
5125 rtp_data_channel_->SignalDtlsSrtpSetupFailure.connect(
5126 this, &PeerConnection::OnDtlsSrtpSetupFailure);
5127 rtp_data_channel_->SignalSentPacket.connect(
5128 this, &PeerConnection::OnSentPacket_w);
5129 }
5130
Steve Anton75737c02017-11-06 10:37:17 -08005131 return true;
5132}
5133
5134Call::Stats PeerConnection::GetCallStats() {
5135 if (!worker_thread()->IsCurrent()) {
5136 return worker_thread()->Invoke<Call::Stats>(
5137 RTC_FROM_HERE, rtc::Bind(&PeerConnection::GetCallStats, this));
5138 }
5139 if (call_) {
5140 return call_->GetStats();
5141 } else {
5142 return Call::Stats();
5143 }
5144}
5145
5146std::unique_ptr<SessionStats> PeerConnection::GetSessionStats_n(
5147 const ChannelNamePairs& channel_name_pairs) {
5148 RTC_DCHECK(network_thread()->IsCurrent());
5149 std::unique_ptr<SessionStats> session_stats(new SessionStats());
5150 for (const auto channel_name_pair :
5151 {&channel_name_pairs.voice, &channel_name_pairs.video,
5152 &channel_name_pairs.data}) {
5153 if (*channel_name_pair) {
5154 cricket::TransportStats transport_stats;
5155 if (!transport_controller_->GetStats((*channel_name_pair)->transport_name,
5156 &transport_stats)) {
5157 return nullptr;
5158 }
Steve Anton75737c02017-11-06 10:37:17 -08005159 session_stats->transport_stats[(*channel_name_pair)->transport_name] =
5160 std::move(transport_stats);
5161 }
5162 }
5163 return session_stats;
5164}
5165
5166bool PeerConnection::CreateSctpTransport_n(const std::string& content_name,
5167 const std::string& transport_name) {
5168 RTC_DCHECK(network_thread()->IsCurrent());
5169 RTC_DCHECK(sctp_factory_);
5170 cricket::DtlsTransportInternal* tc =
5171 transport_controller_->CreateDtlsTransport_n(
5172 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5173 sctp_transport_ = sctp_factory_->CreateSctpTransport(tc);
5174 RTC_DCHECK(sctp_transport_);
5175 sctp_invoker_.reset(new rtc::AsyncInvoker());
5176 sctp_transport_->SignalReadyToSendData.connect(
5177 this, &PeerConnection::OnSctpTransportReadyToSendData_n);
5178 sctp_transport_->SignalDataReceived.connect(
5179 this, &PeerConnection::OnSctpTransportDataReceived_n);
5180 sctp_transport_->SignalStreamClosedRemotely.connect(
5181 this, &PeerConnection::OnSctpStreamClosedRemotely_n);
Oskar Sundbom9b28a032017-11-16 10:53:30 +01005182 sctp_transport_name_ = transport_name;
5183 sctp_content_name_ = content_name;
Steve Anton75737c02017-11-06 10:37:17 -08005184 return true;
5185}
5186
5187void PeerConnection::ChangeSctpTransport_n(const std::string& transport_name) {
5188 RTC_DCHECK(network_thread()->IsCurrent());
5189 RTC_DCHECK(sctp_transport_);
5190 RTC_DCHECK(sctp_transport_name_);
5191 std::string old_sctp_transport_name = *sctp_transport_name_;
Oskar Sundbom9b28a032017-11-16 10:53:30 +01005192 sctp_transport_name_ = transport_name;
Steve Anton75737c02017-11-06 10:37:17 -08005193 cricket::DtlsTransportInternal* tc =
5194 transport_controller_->CreateDtlsTransport_n(
5195 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5196 sctp_transport_->SetTransportChannel(tc);
5197 transport_controller_->DestroyDtlsTransport_n(
5198 old_sctp_transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5199}
5200
5201void PeerConnection::DestroySctpTransport_n() {
5202 RTC_DCHECK(network_thread()->IsCurrent());
5203 sctp_transport_.reset(nullptr);
Taylor Brandstetter389a97c2018-01-03 16:26:06 -08005204 transport_controller_->DestroyDtlsTransport_n(
5205 *sctp_transport_name_, cricket::ICE_CANDIDATE_COMPONENT_RTP);
Steve Anton75737c02017-11-06 10:37:17 -08005206 sctp_content_name_.reset();
5207 sctp_transport_name_.reset();
5208 sctp_invoker_.reset(nullptr);
5209 sctp_ready_to_send_data_ = false;
5210}
5211
5212void PeerConnection::OnSctpTransportReadyToSendData_n() {
5213 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5214 RTC_DCHECK(network_thread()->IsCurrent());
5215 // Note: Cannot use rtc::Bind here because it will grab a reference to
5216 // PeerConnection and potentially cause PeerConnection to live longer than
5217 // expected. It is safe not to grab a reference since the sctp_invoker_ will
5218 // be destroyed before PeerConnection is destroyed, and at that point all
5219 // pending tasks will be cleared.
5220 sctp_invoker_->AsyncInvoke<void>(RTC_FROM_HERE, signaling_thread(), [this] {
5221 OnSctpTransportReadyToSendData_s(true);
5222 });
5223}
5224
5225void PeerConnection::OnSctpTransportReadyToSendData_s(bool ready) {
5226 RTC_DCHECK(signaling_thread()->IsCurrent());
5227 sctp_ready_to_send_data_ = ready;
5228 SignalSctpReadyToSendData(ready);
5229}
5230
5231void PeerConnection::OnSctpTransportDataReceived_n(
5232 const cricket::ReceiveDataParams& params,
5233 const rtc::CopyOnWriteBuffer& payload) {
5234 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5235 RTC_DCHECK(network_thread()->IsCurrent());
5236 // Note: Cannot use rtc::Bind here because it will grab a reference to
5237 // PeerConnection and potentially cause PeerConnection to live longer than
5238 // expected. It is safe not to grab a reference since the sctp_invoker_ will
5239 // be destroyed before PeerConnection is destroyed, and at that point all
5240 // pending tasks will be cleared.
5241 sctp_invoker_->AsyncInvoke<void>(
5242 RTC_FROM_HERE, signaling_thread(), [this, params, payload] {
5243 OnSctpTransportDataReceived_s(params, payload);
5244 });
5245}
5246
5247void PeerConnection::OnSctpTransportDataReceived_s(
5248 const cricket::ReceiveDataParams& params,
5249 const rtc::CopyOnWriteBuffer& payload) {
5250 RTC_DCHECK(signaling_thread()->IsCurrent());
5251 if (params.type == cricket::DMT_CONTROL && IsOpenMessage(payload)) {
5252 // Received OPEN message; parse and signal that a new data channel should
5253 // be created.
5254 std::string label;
5255 InternalDataChannelInit config;
5256 config.id = params.ssrc;
5257 if (!ParseDataChannelOpenMessage(payload, &label, &config)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005258 RTC_LOG(LS_WARNING) << "Failed to parse the OPEN message for sid "
5259 << params.ssrc;
Steve Anton75737c02017-11-06 10:37:17 -08005260 return;
5261 }
5262 config.open_handshake_role = InternalDataChannelInit::kAcker;
5263 OnDataChannelOpenMessage(label, config);
5264 } else {
5265 // Otherwise just forward the signal.
5266 SignalSctpDataReceived(params, payload);
5267 }
5268}
5269
5270void PeerConnection::OnSctpStreamClosedRemotely_n(int sid) {
5271 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5272 RTC_DCHECK(network_thread()->IsCurrent());
5273 sctp_invoker_->AsyncInvoke<void>(
5274 RTC_FROM_HERE, signaling_thread(),
5275 rtc::Bind(&sigslot::signal1<int>::operator(),
5276 &SignalSctpStreamClosedRemotely, sid));
5277}
5278
5279// Returns false if bundle is enabled and rtcp_mux is disabled.
5280bool PeerConnection::ValidateBundleSettings(const SessionDescription* desc) {
5281 bool bundle_enabled = desc->HasGroup(cricket::GROUP_TYPE_BUNDLE);
5282 if (!bundle_enabled)
5283 return true;
5284
5285 const cricket::ContentGroup* bundle_group =
5286 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
5287 RTC_DCHECK(bundle_group != NULL);
5288
5289 const cricket::ContentInfos& contents = desc->contents();
5290 for (cricket::ContentInfos::const_iterator citer = contents.begin();
5291 citer != contents.end(); ++citer) {
5292 const cricket::ContentInfo* content = (&*citer);
5293 RTC_DCHECK(content != NULL);
5294 if (bundle_group->HasContentName(content->name) && !content->rejected &&
Steve Anton5adfafd2017-12-20 16:34:00 -08005295 content->type == MediaProtocolType::kRtp) {
Steve Anton75737c02017-11-06 10:37:17 -08005296 if (!HasRtcpMuxEnabled(content))
5297 return false;
5298 }
5299 }
5300 // RTCP-MUX is enabled in all the contents.
5301 return true;
5302}
5303
5304bool PeerConnection::HasRtcpMuxEnabled(const cricket::ContentInfo* content) {
Steve Antonb1c1de12017-12-21 15:14:30 -08005305 return content->media_description()->rtcp_mux();
Steve Anton75737c02017-11-06 10:37:17 -08005306}
5307
Steve Anton8a006912017-12-04 15:25:56 -08005308RTCError PeerConnection::ValidateSessionDescription(
Steve Anton75737c02017-11-06 10:37:17 -08005309 const SessionDescriptionInterface* sdesc,
Steve Anton8a006912017-12-04 15:25:56 -08005310 cricket::ContentSource source) {
Steve Antonf8470812017-12-04 10:46:21 -08005311 if (session_error() != SessionError::kNone) {
Steve Anton8a006912017-12-04 15:25:56 -08005312 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
Steve Anton75737c02017-11-06 10:37:17 -08005313 }
5314
5315 if (!sdesc || !sdesc->description()) {
Steve Anton8a006912017-12-04 15:25:56 -08005316 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidSdp);
Steve Anton75737c02017-11-06 10:37:17 -08005317 }
5318
Steve Anton3828c062017-12-06 10:34:51 -08005319 SdpType type = sdesc->GetType();
5320 if ((source == cricket::CS_LOCAL && !ExpectSetLocalDescription(type)) ||
5321 (source == cricket::CS_REMOTE && !ExpectSetRemoteDescription(type))) {
Steve Anton8a006912017-12-04 15:25:56 -08005322 LOG_AND_RETURN_ERROR(
5323 RTCErrorType::INVALID_PARAMETER,
5324 "Called in wrong state: " + GetSignalingStateString(signaling_state()));
Steve Anton75737c02017-11-06 10:37:17 -08005325 }
5326
5327 // Verify crypto settings.
5328 std::string crypto_error;
Steve Anton8a006912017-12-04 15:25:56 -08005329 if (webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED ||
5330 dtls_enabled_) {
Harald Alvestrand194939b2018-01-24 16:04:13 +01005331 RTCError crypto_error =
5332 VerifyCrypto(sdesc->description(), dtls_enabled_, uma_observer_);
Steve Anton8a006912017-12-04 15:25:56 -08005333 if (!crypto_error.ok()) {
5334 return crypto_error;
5335 }
Steve Anton75737c02017-11-06 10:37:17 -08005336 }
5337
5338 // Verify ice-ufrag and ice-pwd.
5339 if (!VerifyIceUfragPwdPresent(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08005340 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5341 kSdpWithoutIceUfragPwd);
Steve Anton75737c02017-11-06 10:37:17 -08005342 }
5343
5344 if (!ValidateBundleSettings(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08005345 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5346 kBundleWithoutRtcpMux);
Steve Anton75737c02017-11-06 10:37:17 -08005347 }
5348
5349 // TODO(skvlad): When the local rtcp-mux policy is Require, reject any
5350 // m-lines that do not rtcp-mux enabled.
5351
5352 // Verify m-lines in Answer when compared against Offer.
Steve Anton3828c062017-12-06 10:34:51 -08005353 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Anton75737c02017-11-06 10:37:17 -08005354 const cricket::SessionDescription* offer_desc =
5355 (source == cricket::CS_LOCAL) ? remote_description()->description()
5356 : local_description()->description();
5357 if (!MediaSectionsHaveSameCount(offer_desc, sdesc->description()) ||
5358 !MediaSectionsInSameOrder(offer_desc, sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08005359 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5360 kMlineMismatchInAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08005361 }
5362 } else {
5363 const cricket::SessionDescription* current_desc = nullptr;
5364 if (source == cricket::CS_LOCAL && local_description()) {
5365 current_desc = local_description()->description();
5366 } else if (source == cricket::CS_REMOTE && remote_description()) {
5367 current_desc = remote_description()->description();
5368 }
5369 // The re-offers should respect the order of m= sections in current
5370 // description. See RFC3264 Section 8 paragraph 4 for more details.
5371 if (current_desc &&
5372 !MediaSectionsInSameOrder(current_desc, sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08005373 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5374 kMlineMismatchInSubsequentOffer);
Steve Anton75737c02017-11-06 10:37:17 -08005375 }
5376 }
5377
Steve Anton02ee47c2018-01-10 16:26:06 -08005378 // Unified Plan SDP should have exactly one stream per m= section for audio
5379 // and video.
5380 if (IsUnifiedPlan()) {
5381 for (const ContentInfo& content : sdesc->description()->contents()) {
5382 if (content.rejected) {
5383 continue;
5384 }
5385 if (content.media_description()) {
5386 cricket::MediaType media_type = content.media_description()->type();
5387 if (!(media_type == cricket::MEDIA_TYPE_AUDIO ||
5388 media_type == cricket::MEDIA_TYPE_VIDEO)) {
5389 continue;
5390 }
5391 const cricket::StreamParamsVec& streams =
5392 content.media_description()->streams();
5393 if (streams.size() != 1u) {
5394 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5395 "Unified Plan SDP should have exactly one "
5396 "track per media section for audio and video.");
5397 }
5398 }
5399 }
5400 }
5401
Steve Anton8a006912017-12-04 15:25:56 -08005402 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08005403}
5404
Steve Anton3828c062017-12-06 10:34:51 -08005405bool PeerConnection::ExpectSetLocalDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08005406 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08005407 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08005408 return (state == PeerConnectionInterface::kStable) ||
5409 (state == PeerConnectionInterface::kHaveLocalOffer);
Steve Anton20393062017-12-04 16:24:52 -08005410 } else {
Steve Anton3828c062017-12-06 10:34:51 -08005411 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08005412 return (state == PeerConnectionInterface::kHaveRemoteOffer) ||
5413 (state == PeerConnectionInterface::kHaveLocalPrAnswer);
5414 }
5415}
5416
Steve Anton3828c062017-12-06 10:34:51 -08005417bool PeerConnection::ExpectSetRemoteDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08005418 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08005419 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08005420 return (state == PeerConnectionInterface::kStable) ||
5421 (state == PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton20393062017-12-04 16:24:52 -08005422 } else {
Steve Anton3828c062017-12-06 10:34:51 -08005423 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08005424 return (state == PeerConnectionInterface::kHaveLocalOffer) ||
5425 (state == PeerConnectionInterface::kHaveRemotePrAnswer);
5426 }
5427}
5428
Steve Antonf8470812017-12-04 10:46:21 -08005429const char* PeerConnection::SessionErrorToString(SessionError error) const {
5430 switch (error) {
5431 case SessionError::kNone:
5432 return "ERROR_NONE";
5433 case SessionError::kContent:
5434 return "ERROR_CONTENT";
5435 case SessionError::kTransport:
5436 return "ERROR_TRANSPORT";
5437 }
5438 RTC_NOTREACHED();
5439 return "";
5440}
5441
Steve Anton75737c02017-11-06 10:37:17 -08005442std::string PeerConnection::GetSessionErrorMsg() {
5443 std::ostringstream desc;
Steve Antonf8470812017-12-04 10:46:21 -08005444 desc << kSessionError << SessionErrorToString(session_error()) << ". ";
5445 desc << kSessionErrorDesc << session_error_desc() << ".";
Steve Anton75737c02017-11-06 10:37:17 -08005446 return desc.str();
5447}
5448
5449// We need to check the local/remote description for the Transport instead of
5450// the session, because a new Transport added during renegotiation may have
5451// them unset while the session has them set from the previous negotiation.
5452// Not doing so may trigger the auto generation of transport description and
5453// mess up DTLS identity information, ICE credential, etc.
5454bool PeerConnection::ReadyToUseRemoteCandidate(
5455 const IceCandidateInterface* candidate,
5456 const SessionDescriptionInterface* remote_desc,
5457 bool* valid) {
5458 *valid = true;
5459
5460 const SessionDescriptionInterface* current_remote_desc =
5461 remote_desc ? remote_desc : remote_description();
5462
5463 if (!current_remote_desc) {
5464 return false;
5465 }
5466
5467 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
5468 size_t remote_content_size =
5469 current_remote_desc->description()->contents().size();
5470 if (mediacontent_index >= remote_content_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005471 RTC_LOG(LS_ERROR)
5472 << "ReadyToUseRemoteCandidate: Invalid candidate media index "
5473 << mediacontent_index;
Steve Anton75737c02017-11-06 10:37:17 -08005474
5475 *valid = false;
5476 return false;
5477 }
5478
5479 cricket::ContentInfo content =
5480 current_remote_desc->description()->contents()[mediacontent_index];
5481
5482 const std::string transport_name = GetTransportName(content.name);
5483 if (transport_name.empty()) {
5484 return false;
5485 }
5486 return transport_controller_->ReadyForRemoteCandidates(transport_name);
5487}
5488
5489bool PeerConnection::SrtpRequired() const {
5490 return dtls_enabled_ ||
5491 webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED;
5492}
5493
5494void PeerConnection::OnTransportControllerGatheringState(
5495 cricket::IceGatheringState state) {
5496 RTC_DCHECK(signaling_thread()->IsCurrent());
5497 if (state == cricket::kIceGatheringGathering) {
5498 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringGathering);
5499 } else if (state == cricket::kIceGatheringComplete) {
5500 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringComplete);
5501 }
5502}
5503
5504void PeerConnection::ReportTransportStats() {
5505 // Use a set so we don't report the same stats twice if two channels share
5506 // a transport.
5507 std::set<std::string> transport_names;
5508 if (voice_channel()) {
5509 transport_names.insert(voice_channel()->transport_name());
5510 }
5511 if (video_channel()) {
5512 transport_names.insert(video_channel()->transport_name());
5513 }
5514 if (rtp_data_channel()) {
5515 transport_names.insert(rtp_data_channel()->transport_name());
5516 }
5517 if (sctp_transport_name_) {
5518 transport_names.insert(*sctp_transport_name_);
5519 }
5520 for (const auto& name : transport_names) {
5521 cricket::TransportStats stats;
5522 if (transport_controller_->GetStats(name, &stats)) {
5523 ReportBestConnectionState(stats);
5524 ReportNegotiatedCiphers(stats);
5525 }
5526 }
5527}
5528// Walk through the ConnectionInfos to gather best connection usage
5529// for IPv4 and IPv6.
5530void PeerConnection::ReportBestConnectionState(
5531 const cricket::TransportStats& stats) {
5532 RTC_DCHECK(metrics_observer());
5533 for (cricket::TransportChannelStatsList::const_iterator it =
5534 stats.channel_stats.begin();
5535 it != stats.channel_stats.end(); ++it) {
5536 for (cricket::ConnectionInfos::const_iterator it_info =
5537 it->connection_infos.begin();
5538 it_info != it->connection_infos.end(); ++it_info) {
5539 if (!it_info->best_connection) {
5540 continue;
5541 }
5542
5543 PeerConnectionEnumCounterType type = kPeerConnectionEnumCounterMax;
5544 const cricket::Candidate& local = it_info->local_candidate;
5545 const cricket::Candidate& remote = it_info->remote_candidate;
5546
5547 // Increment the counter for IceCandidatePairType.
5548 if (local.protocol() == cricket::TCP_PROTOCOL_NAME ||
5549 (local.type() == RELAY_PORT_TYPE &&
5550 local.relay_protocol() == cricket::TCP_PROTOCOL_NAME)) {
5551 type = kEnumCounterIceCandidatePairTypeTcp;
5552 } else if (local.protocol() == cricket::UDP_PROTOCOL_NAME) {
5553 type = kEnumCounterIceCandidatePairTypeUdp;
5554 } else {
5555 RTC_CHECK(0);
5556 }
5557 metrics_observer()->IncrementEnumCounter(
5558 type, GetIceCandidatePairCounter(local, remote),
5559 kIceCandidatePairMax);
5560
5561 // Increment the counter for IP type.
5562 if (local.address().family() == AF_INET) {
5563 metrics_observer()->IncrementEnumCounter(
5564 kEnumCounterAddressFamily, kBestConnections_IPv4,
5565 kPeerConnectionAddressFamilyCounter_Max);
5566
5567 } else if (local.address().family() == AF_INET6) {
5568 metrics_observer()->IncrementEnumCounter(
5569 kEnumCounterAddressFamily, kBestConnections_IPv6,
5570 kPeerConnectionAddressFamilyCounter_Max);
5571 } else {
5572 RTC_CHECK(0);
5573 }
5574
5575 return;
5576 }
5577 }
5578}
5579
5580void PeerConnection::ReportNegotiatedCiphers(
5581 const cricket::TransportStats& stats) {
5582 RTC_DCHECK(metrics_observer());
5583 if (!dtls_enabled_ || stats.channel_stats.empty()) {
5584 return;
5585 }
5586
5587 int srtp_crypto_suite = stats.channel_stats[0].srtp_crypto_suite;
5588 int ssl_cipher_suite = stats.channel_stats[0].ssl_cipher_suite;
5589 if (srtp_crypto_suite == rtc::SRTP_INVALID_CRYPTO_SUITE &&
5590 ssl_cipher_suite == rtc::TLS_NULL_WITH_NULL_NULL) {
5591 return;
5592 }
5593
5594 PeerConnectionEnumCounterType srtp_counter_type;
5595 PeerConnectionEnumCounterType ssl_counter_type;
5596 if (stats.transport_name == cricket::CN_AUDIO) {
5597 srtp_counter_type = kEnumCounterAudioSrtpCipher;
5598 ssl_counter_type = kEnumCounterAudioSslCipher;
5599 } else if (stats.transport_name == cricket::CN_VIDEO) {
5600 srtp_counter_type = kEnumCounterVideoSrtpCipher;
5601 ssl_counter_type = kEnumCounterVideoSslCipher;
5602 } else if (stats.transport_name == cricket::CN_DATA) {
5603 srtp_counter_type = kEnumCounterDataSrtpCipher;
5604 ssl_counter_type = kEnumCounterDataSslCipher;
5605 } else {
5606 RTC_NOTREACHED();
5607 return;
5608 }
5609
5610 if (srtp_crypto_suite != rtc::SRTP_INVALID_CRYPTO_SUITE) {
5611 metrics_observer()->IncrementSparseEnumCounter(srtp_counter_type,
5612 srtp_crypto_suite);
5613 }
5614 if (ssl_cipher_suite != rtc::TLS_NULL_WITH_NULL_NULL) {
5615 metrics_observer()->IncrementSparseEnumCounter(ssl_counter_type,
5616 ssl_cipher_suite);
5617 }
5618}
5619
5620void PeerConnection::OnSentPacket_w(const rtc::SentPacket& sent_packet) {
5621 RTC_DCHECK(worker_thread()->IsCurrent());
5622 RTC_DCHECK(call_);
5623 call_->OnSentPacket(sent_packet);
5624}
5625
5626const std::string PeerConnection::GetTransportName(
5627 const std::string& content_name) {
5628 cricket::BaseChannel* channel = GetChannel(content_name);
Steve Anton6fec8802017-12-04 10:37:29 -08005629 if (channel) {
5630 return channel->transport_name();
Steve Anton75737c02017-11-06 10:37:17 -08005631 }
Steve Anton6fec8802017-12-04 10:37:29 -08005632 if (sctp_transport_) {
5633 RTC_DCHECK(sctp_content_name_);
5634 RTC_DCHECK(sctp_transport_name_);
5635 if (content_name == *sctp_content_name_) {
5636 return *sctp_transport_name_;
5637 }
5638 }
5639 // Return an empty string if failed to retrieve the transport name.
5640 return "";
Steve Anton75737c02017-11-06 10:37:17 -08005641}
5642
5643void PeerConnection::DestroyRtcpTransport_n(const std::string& transport_name) {
5644 RTC_DCHECK(network_thread()->IsCurrent());
5645 transport_controller_->DestroyDtlsTransport_n(
5646 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
5647}
5648
Steve Anton6fec8802017-12-04 10:37:29 -08005649void PeerConnection::DestroyTransceiverChannel(
5650 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
5651 transceiver) {
5652 RTC_DCHECK(transceiver);
Steve Anton75737c02017-11-06 10:37:17 -08005653
Steve Anton6fec8802017-12-04 10:37:29 -08005654 cricket::BaseChannel* channel = transceiver->internal()->channel();
5655 if (channel) {
5656 transceiver->internal()->SetChannel(nullptr);
5657 DestroyBaseChannel(channel);
Steve Anton75737c02017-11-06 10:37:17 -08005658 }
5659}
5660
5661void PeerConnection::DestroyDataChannel() {
Steve Anton6fec8802017-12-04 10:37:29 -08005662 if (rtp_data_channel_) {
5663 OnDataChannelDestroyed();
5664 DestroyBaseChannel(rtp_data_channel_);
5665 rtp_data_channel_ = nullptr;
5666 }
5667
5668 // Note: Cannot use rtc::Bind to create a functor to invoke because it will
5669 // grab a reference to this PeerConnection. If this is called from the
5670 // PeerConnection destructor, the RefCountedObject vtable will have already
5671 // been destroyed (since it is a subclass of PeerConnection) and using
5672 // rtc::Bind will cause "Pure virtual function called" error to appear.
5673
5674 if (sctp_transport_) {
5675 OnDataChannelDestroyed();
5676 network_thread()->Invoke<void>(RTC_FROM_HERE,
5677 [this] { DestroySctpTransport_n(); });
5678 }
5679}
5680
5681void PeerConnection::DestroyBaseChannel(cricket::BaseChannel* channel) {
5682 RTC_DCHECK(channel);
5683 RTC_DCHECK(channel->rtp_dtls_transport());
5684
5685 // Need to cache these before destroying the base channel so that we do not
5686 // access uninitialized memory.
5687 const std::string transport_name =
5688 channel->rtp_dtls_transport()->transport_name();
5689 const bool need_to_delete_rtcp = (channel->rtcp_dtls_transport() != nullptr);
5690
5691 switch (channel->media_type()) {
5692 case cricket::MEDIA_TYPE_AUDIO:
5693 channel_manager()->DestroyVoiceChannel(
5694 static_cast<cricket::VoiceChannel*>(channel));
5695 break;
5696 case cricket::MEDIA_TYPE_VIDEO:
5697 channel_manager()->DestroyVideoChannel(
5698 static_cast<cricket::VideoChannel*>(channel));
5699 break;
5700 case cricket::MEDIA_TYPE_DATA:
5701 channel_manager()->DestroyRtpDataChannel(
5702 static_cast<cricket::RtpDataChannel*>(channel));
5703 break;
5704 default:
5705 RTC_NOTREACHED() << "Unknown media type: " << channel->media_type();
5706 break;
5707 }
5708
5709 // |channel| can no longer be used.
5710
Steve Anton75737c02017-11-06 10:37:17 -08005711 transport_controller_->DestroyDtlsTransport(
5712 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5713 if (need_to_delete_rtcp) {
5714 transport_controller_->DestroyDtlsTransport(
5715 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
5716 }
5717}
5718
Harald Alvestrand89061872018-01-02 14:08:34 +01005719void PeerConnection::ClearStatsCache() {
5720 if (stats_collector_) {
5721 stats_collector_->ClearCachedStatsReport();
5722 }
5723}
5724
henrike@webrtc.org28e20752013-07-10 00:45:36 +00005725} // namespace webrtc