blob: 6ffe561a7591740dc2cb8f766b94612382be17ef [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 }
Steve Anton74255ff2018-01-24 18:32:57 -08001791 const auto& streams = content->media_description()->streams();
1792 if (!content->rejected && !streams.empty()) {
Steve Antond3679212018-01-17 17:41:02 -08001793 transceiver->internal()->sender_internal()->set_stream_ids(
Steve Anton74255ff2018-01-24 18:32:57 -08001794 {streams[0].sync_label});
Steve Antond3679212018-01-17 17:41:02 -08001795 transceiver->internal()->sender_internal()->SetSsrc(
Steve Anton74255ff2018-01-24 18:32:57 -08001796 streams[0].first_ssrc());
Steve Antond3679212018-01-17 17:41:02 -08001797 }
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(
Steve Anton74255ff2018-01-24 18:32:57 -08002035 *transceiver->current_direction())) &&
2036 !media_desc->streams().empty()) {
Steve Antonef65ef12018-01-10 17:15:20 -08002037 const std::string& sync_label = media_desc->streams()[0].sync_label;
2038 rtc::scoped_refptr<MediaStreamInterface> stream =
2039 remote_streams_->find(sync_label);
2040 if (!stream) {
2041 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
2042 MediaStream::Create(sync_label));
2043 remote_streams_->AddStream(stream);
2044 }
2045 transceiver->internal()->receiver_internal()->SetStreams({stream});
2046 TrackEvent track_event;
2047 track_event.receiver = transceiver->receiver();
2048 track_event.streams = transceiver->receiver()->streams();
2049 track_events.push_back(std::move(track_event));
Steve Antondcc3c022017-12-22 16:02:54 -08002050 }
2051 // If direction is sendonly or inactive, and transceiver's current
2052 // direction is neither sendonly nor inactive, process the removal of a
2053 // remote track for the media description.
2054 if (!RtpTransceiverDirectionHasRecv(local_direction) &&
Steve Antonef65ef12018-01-10 17:15:20 -08002055 (transceiver->current_direction() &&
Steve Antondcc3c022017-12-22 16:02:54 -08002056 RtpTransceiverDirectionHasRecv(*transceiver->current_direction()))) {
Steve Antonef65ef12018-01-10 17:15:20 -08002057 transceiver->internal()->receiver_internal()->SetStreams({});
Steve Antondcc3c022017-12-22 16:02:54 -08002058 }
2059 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
2060 transceiver->internal()->set_current_direction(local_direction);
2061 }
2062 if (content->rejected && !transceiver->stopped()) {
2063 transceiver->Stop();
2064 }
Steve Anton74255ff2018-01-24 18:32:57 -08002065 if (!content->rejected && !media_desc->streams().empty()) {
Steve Antond3679212018-01-17 17:41:02 -08002066 const auto& stream = content->media_description()->streams()[0];
2067 transceiver->internal()->receiver_internal()->SetupMediaChannel(
2068 stream.first_ssrc());
2069 }
Steve Antondcc3c022017-12-22 16:02:54 -08002070 }
Steve Antonef65ef12018-01-10 17:15:20 -08002071 for (auto event : track_events) {
2072 observer_->OnAddTrack(event.receiver, event.streams);
2073 }
Steve Antondcc3c022017-12-22 16:02:54 -08002074 }
2075
Henrik Boströmfdb92012017-11-09 19:55:44 +01002076 const cricket::ContentInfo* audio_content =
2077 GetFirstAudioContent(remote_description()->description());
2078 const cricket::ContentInfo* video_content =
2079 GetFirstVideoContent(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002080 const cricket::AudioContentDescription* audio_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002081 GetFirstAudioContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002082 const cricket::VideoContentDescription* video_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002083 GetFirstVideoContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002084 const cricket::DataContentDescription* data_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002085 GetFirstDataContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002086
2087 // Check if the descriptions include streams, just in case the peer supports
2088 // MSID, but doesn't indicate so with "a=msid-semantic".
Henrik Boströmfdb92012017-11-09 19:55:44 +01002089 if (remote_description()->description()->msid_supported() ||
deadbeefbda7e0b2015-12-08 17:13:40 -08002090 (audio_desc && !audio_desc->streams().empty()) ||
2091 (video_desc && !video_desc->streams().empty())) {
2092 remote_peer_supports_msid_ = true;
2093 }
deadbeefab9b2d12015-10-14 11:33:11 -07002094
2095 // We wait to signal new streams until we finish processing the description,
2096 // since only at that point will new streams have all their tracks.
2097 rtc::scoped_refptr<StreamCollection> new_streams(StreamCollection::Create());
2098
Steve Antondcc3c022017-12-22 16:02:54 -08002099 if (!IsUnifiedPlan()) {
2100 // TODO(steveanton): When removing RTP senders/receivers in response to a
2101 // rejected media section, there is some cleanup logic that expects the
2102 // voice/ video channel to still be set. But in this method the voice/video
2103 // channel would have been destroyed by the SetRemoteDescription caller
2104 // above so the cleanup that relies on them fails to run. The RemoveSenders
2105 // calls should be moved to right before the DestroyChannel calls to fix
2106 // this.
Steve Anton8d3444d2017-10-20 15:30:51 -07002107
Steve Antondcc3c022017-12-22 16:02:54 -08002108 // Find all audio rtp streams and create corresponding remote AudioTracks
2109 // and MediaStreams.
2110 if (audio_content) {
2111 if (audio_content->rejected) {
2112 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
2113 } else {
2114 bool default_audio_track_needed =
2115 !remote_peer_supports_msid_ &&
2116 RtpTransceiverDirectionHasSend(audio_desc->direction());
2117 UpdateRemoteSendersList(GetActiveStreams(audio_desc),
2118 default_audio_track_needed, audio_desc->type(),
2119 new_streams);
2120 }
deadbeeffaac4972015-11-12 15:33:07 -08002121 }
deadbeefab9b2d12015-10-14 11:33:11 -07002122
Steve Antondcc3c022017-12-22 16:02:54 -08002123 // Find all video rtp streams and create corresponding remote VideoTracks
2124 // and MediaStreams.
2125 if (video_content) {
2126 if (video_content->rejected) {
2127 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
2128 } else {
2129 bool default_video_track_needed =
2130 !remote_peer_supports_msid_ &&
2131 RtpTransceiverDirectionHasSend(video_desc->direction());
2132 UpdateRemoteSendersList(GetActiveStreams(video_desc),
2133 default_video_track_needed, video_desc->type(),
2134 new_streams);
2135 }
deadbeeffaac4972015-11-12 15:33:07 -08002136 }
deadbeefab9b2d12015-10-14 11:33:11 -07002137
Steve Antondcc3c022017-12-22 16:02:54 -08002138 // Update the DataChannels with the information from the remote peer.
2139 if (data_desc) {
2140 if (rtc::starts_with(data_desc->protocol().data(),
2141 cricket::kMediaProtocolRtpPrefix)) {
2142 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
2143 }
deadbeefab9b2d12015-10-14 11:33:11 -07002144 }
deadbeefab9b2d12015-10-14 11:33:11 -07002145
Steve Antondcc3c022017-12-22 16:02:54 -08002146 // Iterate new_streams and notify the observer about new MediaStreams.
2147 for (size_t i = 0; i < new_streams->count(); ++i) {
2148 MediaStreamInterface* new_stream = new_streams->at(i);
2149 stats_->AddStream(new_stream);
2150 observer_->OnAddStream(
2151 rtc::scoped_refptr<MediaStreamInterface>(new_stream));
2152 }
deadbeefab9b2d12015-10-14 11:33:11 -07002153
Steve Antondcc3c022017-12-22 16:02:54 -08002154 UpdateEndedRemoteMediaStreams();
2155 }
deadbeefab9b2d12015-10-14 11:33:11 -07002156
Steve Anton8a006912017-12-04 15:25:56 -08002157 return RTCError::OK();
deadbeeffc648b62015-10-13 16:42:33 -07002158}
2159
Steve Antondcc3c022017-12-22 16:02:54 -08002160RTCError PeerConnection::UpdateTransceiversAndDataChannels(
2161 cricket::ContentSource source,
2162 const SessionDescriptionInterface* old_session,
2163 const SessionDescriptionInterface& new_session) {
2164 RTC_DCHECK(IsUnifiedPlan());
2165
Steve Anton7464fca2018-01-19 11:10:37 -08002166 const cricket::ContentGroup* bundle_group = nullptr;
2167 if (new_session.GetType() == SdpType::kOffer) {
2168 auto bundle_group_or_error =
2169 GetEarlyBundleGroup(*new_session.description());
2170 if (!bundle_group_or_error.ok()) {
2171 return bundle_group_or_error.MoveError();
2172 }
2173 bundle_group = bundle_group_or_error.MoveValue();
Steve Antondcc3c022017-12-22 16:02:54 -08002174 }
Steve Antondcc3c022017-12-22 16:02:54 -08002175
2176 const ContentInfos& old_contents =
2177 (old_session ? old_session->description()->contents() : ContentInfos());
2178 const ContentInfos& new_contents = new_session.description()->contents();
2179
2180 for (size_t i = 0; i < new_contents.size(); ++i) {
2181 const cricket::ContentInfo& new_content = new_contents[i];
2182 const cricket::ContentInfo* old_content =
2183 (i < old_contents.size() ? &old_contents[i] : nullptr);
2184 cricket::MediaType media_type = new_content.media_description()->type();
2185 seen_mids_.insert(new_content.name);
2186 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
2187 media_type == cricket::MEDIA_TYPE_VIDEO) {
2188 auto transceiver_or_error =
2189 AssociateTransceiver(source, i, new_content, old_content);
2190 if (!transceiver_or_error.ok()) {
2191 return transceiver_or_error.MoveError();
2192 }
2193 auto transceiver = transceiver_or_error.MoveValue();
Steve Antondcc3c022017-12-22 16:02:54 -08002194 RTCError error =
2195 UpdateTransceiverChannel(transceiver, new_content, bundle_group);
2196 if (!error.ok()) {
2197 return error;
2198 }
2199 } else if (media_type == cricket::MEDIA_TYPE_DATA) {
Steve Antonfa2260d2017-12-28 16:38:23 -08002200 if (GetDataMid() && new_content.name != *GetDataMid()) {
2201 // Ignore all but the first data section.
2202 continue;
2203 }
2204 RTCError error = UpdateDataChannel(source, new_content, bundle_group);
2205 if (!error.ok()) {
2206 return error;
2207 }
Steve Antondcc3c022017-12-22 16:02:54 -08002208 } else {
2209 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
2210 "Unknown section type.");
2211 }
2212 }
2213
2214 return RTCError::OK();
2215}
2216
2217RTCError PeerConnection::UpdateTransceiverChannel(
2218 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2219 transceiver,
2220 const cricket::ContentInfo& content,
2221 const cricket::ContentGroup* bundle_group) {
2222 RTC_DCHECK(IsUnifiedPlan());
2223 RTC_DCHECK(transceiver);
2224 cricket::BaseChannel* channel = transceiver->internal()->channel();
2225 if (content.rejected) {
2226 if (channel) {
2227 transceiver->internal()->SetChannel(nullptr);
2228 DestroyBaseChannel(channel);
2229 }
2230 } else {
2231 if (!channel) {
2232 if (transceiver->internal()->media_type() == cricket::MEDIA_TYPE_AUDIO) {
2233 channel = CreateVoiceChannel(
2234 content.name,
2235 GetTransportNameForMediaSection(content.name, bundle_group));
2236 } else {
2237 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO,
2238 transceiver->internal()->media_type());
2239 channel = CreateVideoChannel(
2240 content.name,
2241 GetTransportNameForMediaSection(content.name, bundle_group));
2242 }
2243 if (!channel) {
2244 LOG_AND_RETURN_ERROR(
2245 RTCErrorType::INTERNAL_ERROR,
2246 "Failed to create channel for mid=" + content.name);
2247 }
2248 transceiver->internal()->SetChannel(channel);
2249 }
2250 }
2251 return RTCError::OK();
2252}
2253
Steve Antonfa2260d2017-12-28 16:38:23 -08002254RTCError PeerConnection::UpdateDataChannel(
2255 cricket::ContentSource source,
2256 const cricket::ContentInfo& content,
2257 const cricket::ContentGroup* bundle_group) {
2258 if (data_channel_type_ == cricket::DCT_NONE) {
Steve Antondbf9d032018-01-19 15:23:40 -08002259 // If data channels are disabled, ignore this media section. CreateAnswer
2260 // will take care of rejecting it.
2261 return RTCError::OK();
Steve Antonfa2260d2017-12-28 16:38:23 -08002262 }
2263 if (content.rejected) {
2264 DestroyDataChannel();
2265 } else {
2266 if (!rtp_data_channel_ && !sctp_transport_) {
2267 if (!CreateDataChannel(content.name, GetTransportNameForMediaSection(
2268 content.name, bundle_group))) {
2269 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
2270 "Failed to create data channel.");
2271 }
2272 }
2273 if (source == cricket::CS_REMOTE) {
2274 const MediaContentDescription* data_desc = content.media_description();
2275 if (data_desc && cricket::IsRtpProtocol(data_desc->protocol())) {
2276 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
2277 }
2278 }
2279 }
2280 return RTCError::OK();
2281}
2282
Steve Antondcc3c022017-12-22 16:02:54 -08002283RTCErrorOr<rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
2284PeerConnection::AssociateTransceiver(cricket::ContentSource source,
2285 size_t mline_index,
2286 const ContentInfo& content,
2287 const ContentInfo* old_content) {
2288 RTC_DCHECK(IsUnifiedPlan());
2289 // If the m= section is being recycled (rejected in previous remote
2290 // description, not rejected in current description), dissociate the currently
2291 // associated RtpTransceiver by setting its mid property to null, and discard
2292 // the mapping between the transceiver and its m= section index.
2293 if (old_content && old_content->rejected && !content.rejected) {
2294 auto old_transceiver = GetAssociatedTransceiver(old_content->name);
2295 if (old_transceiver) {
2296 old_transceiver->internal()->set_mid(rtc::nullopt);
2297 old_transceiver->internal()->set_mline_index(rtc::nullopt);
2298 }
2299 }
2300 const MediaContentDescription* media_desc = content.media_description();
2301 auto transceiver = GetAssociatedTransceiver(content.name);
2302 if (source == cricket::CS_LOCAL) {
2303 // Find the RtpTransceiver that corresponds to this m= section, using the
2304 // mapping between transceivers and m= section indices established when
2305 // creating the offer.
2306 if (!transceiver) {
2307 transceiver = GetTransceiverByMLineIndex(mline_index);
2308 }
2309 if (!transceiver) {
2310 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2311 "Unknown transceiver");
2312 }
2313 } else {
2314 RTC_DCHECK_EQ(source, cricket::CS_REMOTE);
2315 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers
2316 // of the same type...
2317 if (!transceiver &&
2318 RtpTransceiverDirectionHasRecv(media_desc->direction())) {
2319 transceiver = FindAvailableTransceiverToReceive(media_desc->type());
2320 }
2321 // If no RtpTransceiver was found in the previous step, create one with a
2322 // recvonly direction.
2323 if (!transceiver) {
Steve Anton02ee47c2018-01-10 16:26:06 -08002324 auto sender =
2325 CreateSender(media_desc->type(), nullptr, {rtc::CreateRandomUuid()});
2326 auto receiver =
2327 CreateReceiver(media_desc->type(), media_desc->streams()[0].id);
2328 transceiver = CreateAndAddTransceiver(sender, receiver);
Steve Antondcc3c022017-12-22 16:02:54 -08002329 transceiver->internal()->set_direction(
2330 RtpTransceiverDirection::kRecvOnly);
2331 }
2332 }
2333 RTC_DCHECK(transceiver);
2334 if (transceiver->internal()->media_type() != media_desc->type()) {
2335 LOG_AND_RETURN_ERROR(
2336 RTCErrorType::INVALID_PARAMETER,
2337 "Transceiver type does not match media description type.");
2338 }
2339 // Associate the found or created RtpTransceiver with the m= section by
2340 // setting the value of the RtpTransceiver's mid property to the MID of the m=
2341 // section, and establish a mapping between the transceiver and the index of
2342 // the m= section.
2343 transceiver->internal()->set_mid(content.name);
2344 transceiver->internal()->set_mline_index(mline_index);
2345 return std::move(transceiver);
2346}
2347
2348rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2349PeerConnection::GetAssociatedTransceiver(const std::string& mid) const {
2350 RTC_DCHECK(IsUnifiedPlan());
2351 for (auto transceiver : transceivers_) {
2352 if (transceiver->mid() == mid) {
2353 return transceiver;
2354 }
2355 }
2356 return nullptr;
2357}
2358
2359rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2360PeerConnection::GetTransceiverByMLineIndex(size_t mline_index) const {
2361 RTC_DCHECK(IsUnifiedPlan());
2362 for (auto transceiver : transceivers_) {
2363 if (transceiver->internal()->mline_index() == mline_index) {
2364 return transceiver;
2365 }
2366 }
2367 return nullptr;
2368}
2369
2370rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2371PeerConnection::FindAvailableTransceiverToReceive(
2372 cricket::MediaType media_type) const {
2373 RTC_DCHECK(IsUnifiedPlan());
2374 // From JSEP section 5.10 (Applying a Remote Description):
2375 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers of
2376 // the same type that were added to the PeerConnection by addTrack and are not
2377 // associated with any m= section and are not stopped, find the first such
2378 // RtpTransceiver.
2379 for (auto transceiver : transceivers_) {
2380 if (transceiver->internal()->media_type() == media_type &&
2381 transceiver->internal()->created_by_addtrack() && !transceiver->mid() &&
2382 !transceiver->stopped()) {
2383 return transceiver;
2384 }
2385 }
2386 return nullptr;
2387}
2388
Steve Antoned10bd92017-12-05 10:52:59 -08002389const cricket::ContentInfo* PeerConnection::FindMediaSectionForTransceiver(
2390 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2391 transceiver,
2392 const SessionDescriptionInterface* sdesc) const {
2393 RTC_DCHECK(transceiver);
2394 RTC_DCHECK(sdesc);
2395 if (IsUnifiedPlan()) {
2396 if (!transceiver->internal()->mid()) {
2397 // This transceiver is not associated with a media section yet.
2398 return nullptr;
2399 }
2400 return sdesc->description()->GetContentByName(
2401 *transceiver->internal()->mid());
2402 } else {
2403 // Plan B only allows at most one audio and one video section, so use the
2404 // first media section of that type.
2405 return cricket::GetFirstMediaContent(sdesc->description()->contents(),
2406 transceiver->internal()->media_type());
2407 }
2408}
2409
deadbeef46c73892016-11-16 19:42:04 -08002410PeerConnectionInterface::RTCConfiguration PeerConnection::GetConfiguration() {
2411 return configuration_;
2412}
2413
deadbeef293e9262017-01-11 12:28:30 -08002414bool PeerConnection::SetConfiguration(const RTCConfiguration& configuration,
2415 RTCError* error) {
Peter Boström1a9d6152015-12-08 22:15:17 +01002416 TRACE_EVENT0("webrtc", "PeerConnection::SetConfiguration");
deadbeef6de92f92016-12-12 18:49:32 -08002417
Steve Anton75737c02017-11-06 10:37:17 -08002418 if (local_description() && configuration.ice_candidate_pool_size !=
2419 configuration_.ice_candidate_pool_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002420 RTC_LOG(LS_ERROR) << "Can't change candidate pool size after calling "
2421 "SetLocalDescription.";
deadbeef293e9262017-01-11 12:28:30 -08002422 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00002423 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002424
deadbeef293e9262017-01-11 12:28:30 -08002425 // The simplest (and most future-compatible) way to tell if the config was
2426 // modified in an invalid way is to copy each property we do support
2427 // modifying, then use operator==. There are far more properties we don't
2428 // support modifying than those we do, and more could be added.
2429 RTCConfiguration modified_config = configuration_;
2430 modified_config.servers = configuration.servers;
2431 modified_config.type = configuration.type;
2432 modified_config.ice_candidate_pool_size =
2433 configuration.ice_candidate_pool_size;
2434 modified_config.prune_turn_ports = configuration.prune_turn_ports;
skvladd1f5fda2017-02-03 16:54:05 -08002435 modified_config.ice_check_min_interval = configuration.ice_check_min_interval;
Jonas Orelandbdcee282017-10-10 14:01:40 +02002436 modified_config.turn_customizer = configuration.turn_customizer;
deadbeef293e9262017-01-11 12:28:30 -08002437 if (configuration != modified_config) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002438 RTC_LOG(LS_ERROR) << "Modifying the configuration in an unsupported way.";
deadbeef293e9262017-01-11 12:28:30 -08002439 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
2440 }
2441
Steve Anton038834f2017-07-14 15:59:59 -07002442 // Validate the modified configuration.
2443 RTCError validate_error = ValidateConfiguration(modified_config);
2444 if (!validate_error.ok()) {
2445 return SafeSetError(std::move(validate_error), error);
2446 }
2447
deadbeef293e9262017-01-11 12:28:30 -08002448 // Note that this isn't possible through chromium, since it's an unsigned
2449 // short in WebIDL.
2450 if (configuration.ice_candidate_pool_size < 0 ||
2451 configuration.ice_candidate_pool_size > UINT16_MAX) {
2452 return SafeSetError(RTCErrorType::INVALID_RANGE, error);
2453 }
2454
2455 // Parse ICE servers before hopping to network thread.
2456 cricket::ServerAddresses stun_servers;
2457 std::vector<cricket::RelayServerConfig> turn_servers;
2458 RTCErrorType parse_error =
2459 ParseIceServers(configuration.servers, &stun_servers, &turn_servers);
2460 if (parse_error != RTCErrorType::NONE) {
2461 return SafeSetError(parse_error, error);
2462 }
2463
2464 // In theory this shouldn't fail.
2465 if (!network_thread()->Invoke<bool>(
2466 RTC_FROM_HERE,
2467 rtc::Bind(&PeerConnection::ReconfigurePortAllocator_n, this,
2468 stun_servers, turn_servers, modified_config.type,
2469 modified_config.ice_candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02002470 modified_config.prune_turn_ports,
2471 modified_config.turn_customizer))) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002472 RTC_LOG(LS_ERROR) << "Failed to apply configuration to PortAllocator.";
deadbeef293e9262017-01-11 12:28:30 -08002473 return SafeSetError(RTCErrorType::INTERNAL_ERROR, error);
2474 }
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07002475
deadbeefd1a38b52016-12-10 13:15:33 -08002476 // As described in JSEP, calling setConfiguration with new ICE servers or
2477 // candidate policy must set a "needs-ice-restart" bit so that the next offer
2478 // triggers an ICE restart which will pick up the changes.
deadbeef293e9262017-01-11 12:28:30 -08002479 if (modified_config.servers != configuration_.servers ||
2480 modified_config.type != configuration_.type ||
2481 modified_config.prune_turn_ports != configuration_.prune_turn_ports) {
Steve Antond25da372017-11-06 14:50:29 -08002482 transport_controller_->SetNeedsIceRestartFlag();
deadbeefd1a38b52016-12-10 13:15:33 -08002483 }
skvladd1f5fda2017-02-03 16:54:05 -08002484
2485 if (modified_config.ice_check_min_interval !=
2486 configuration_.ice_check_min_interval) {
Steve Antond25da372017-11-06 14:50:29 -08002487 transport_controller_->SetIceConfig(ParseIceConfig(modified_config));
skvladd1f5fda2017-02-03 16:54:05 -08002488 }
2489
deadbeef293e9262017-01-11 12:28:30 -08002490 configuration_ = modified_config;
2491 return SafeSetError(RTCErrorType::NONE, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00002492}
2493
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002494bool PeerConnection::AddIceCandidate(
2495 const IceCandidateInterface* ice_candidate) {
Peter Boström1a9d6152015-12-08 22:15:17 +01002496 TRACE_EVENT0("webrtc", "PeerConnection::AddIceCandidate");
zhihuang29ff8442016-07-27 11:07:25 -07002497 if (IsClosed()) {
2498 return false;
2499 }
Steve Antond25da372017-11-06 14:50:29 -08002500
2501 if (!remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002502 RTC_LOG(LS_ERROR) << "ProcessIceMessage: ICE candidates can't be added "
2503 << "without any remote session description.";
Steve Antond25da372017-11-06 14:50:29 -08002504 return false;
2505 }
2506
2507 if (!ice_candidate) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002508 RTC_LOG(LS_ERROR) << "ProcessIceMessage: Candidate is NULL.";
Steve Antond25da372017-11-06 14:50:29 -08002509 return false;
2510 }
2511
2512 bool valid = false;
2513 bool ready = ReadyToUseRemoteCandidate(ice_candidate, nullptr, &valid);
2514 if (!valid) {
2515 return false;
2516 }
2517
2518 // Add this candidate to the remote session description.
2519 if (!mutable_remote_description()->AddCandidate(ice_candidate)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002520 RTC_LOG(LS_ERROR) << "ProcessIceMessage: Candidate cannot be used.";
Steve Antond25da372017-11-06 14:50:29 -08002521 return false;
2522 }
2523
2524 if (ready) {
2525 return UseCandidate(ice_candidate);
2526 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002527 RTC_LOG(LS_INFO) << "ProcessIceMessage: Not ready to use candidate.";
Steve Antond25da372017-11-06 14:50:29 -08002528 return true;
2529 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002530}
2531
Honghai Zhang7fb69db2016-03-14 11:59:18 -07002532bool PeerConnection::RemoveIceCandidates(
2533 const std::vector<cricket::Candidate>& candidates) {
2534 TRACE_EVENT0("webrtc", "PeerConnection::RemoveIceCandidates");
Steve Antond25da372017-11-06 14:50:29 -08002535 if (!remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002536 RTC_LOG(LS_ERROR) << "RemoveRemoteIceCandidates: ICE candidates can't be "
2537 << "removed without any remote session description.";
Steve Antond25da372017-11-06 14:50:29 -08002538 return false;
2539 }
2540
2541 if (candidates.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002542 RTC_LOG(LS_ERROR) << "RemoveRemoteIceCandidates: candidates are empty.";
Steve Antond25da372017-11-06 14:50:29 -08002543 return false;
2544 }
2545
2546 size_t number_removed =
2547 mutable_remote_description()->RemoveCandidates(candidates);
2548 if (number_removed != candidates.size()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002549 RTC_LOG(LS_ERROR)
2550 << "RemoveRemoteIceCandidates: Failed to remove candidates. "
2551 << "Requested " << candidates.size() << " but only " << number_removed
2552 << " are removed.";
Steve Antond25da372017-11-06 14:50:29 -08002553 }
2554
2555 // Remove the candidates from the transport controller.
2556 std::string error;
2557 bool res = transport_controller_->RemoveRemoteCandidates(candidates, &error);
2558 if (!res && !error.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002559 RTC_LOG(LS_ERROR) << "Error when removing remote candidates: " << error;
Steve Antond25da372017-11-06 14:50:29 -08002560 }
2561 return true;
Honghai Zhang7fb69db2016-03-14 11:59:18 -07002562}
2563
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00002564void PeerConnection::RegisterUMAObserver(UMAObserver* observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +01002565 TRACE_EVENT0("webrtc", "PeerConnection::RegisterUmaObserver");
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00002566 uma_observer_ = observer;
guoweis@webrtc.org7169afd2014-12-04 17:59:29 +00002567
Steve Anton75737c02017-11-06 10:37:17 -08002568 if (transport_controller()) {
2569 transport_controller()->SetMetricsObserver(uma_observer_);
guoweis@webrtc.org7169afd2014-12-04 17:59:29 +00002570 }
2571
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00002572 // Send information about IPv4/IPv6 status.
deadbeef293e9262017-01-11 12:28:30 -08002573 if (uma_observer_) {
Honghai Zhangd93f50c2016-10-05 11:47:22 -07002574 port_allocator_->SetMetricsObserver(uma_observer_);
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00002575 if (port_allocator_->flags() & cricket::PORTALLOCATOR_ENABLE_IPV6) {
Guo-wei Shiehdfbe6792015-09-03 17:12:07 -07002576 uma_observer_->IncrementEnumCounter(
2577 kEnumCounterAddressFamily, kPeerConnection_IPv6,
2578 kPeerConnectionAddressFamilyCounter_Max);
mallinath@webrtc.orgb445f262014-05-23 22:19:37 +00002579 } else {
Guo-wei Shiehdfbe6792015-09-03 17:12:07 -07002580 uma_observer_->IncrementEnumCounter(
2581 kEnumCounterAddressFamily, kPeerConnection_IPv4,
2582 kPeerConnectionAddressFamilyCounter_Max);
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00002583 }
2584 }
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00002585}
2586
zstein4b979802017-06-02 14:37:37 -07002587RTCError PeerConnection::SetBitrate(const BitrateParameters& bitrate) {
Steve Anton978b8762017-09-29 12:15:02 -07002588 if (!worker_thread()->IsCurrent()) {
2589 return worker_thread()->Invoke<RTCError>(
zstein4b979802017-06-02 14:37:37 -07002590 RTC_FROM_HERE, rtc::Bind(&PeerConnection::SetBitrate, this, bitrate));
2591 }
2592
2593 const bool has_min = static_cast<bool>(bitrate.min_bitrate_bps);
2594 const bool has_current = static_cast<bool>(bitrate.current_bitrate_bps);
2595 const bool has_max = static_cast<bool>(bitrate.max_bitrate_bps);
2596 if (has_min && *bitrate.min_bitrate_bps < 0) {
2597 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2598 "min_bitrate_bps <= 0");
2599 }
2600 if (has_current) {
2601 if (has_min && *bitrate.current_bitrate_bps < *bitrate.min_bitrate_bps) {
2602 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2603 "current_bitrate_bps < min_bitrate_bps");
2604 } else if (*bitrate.current_bitrate_bps < 0) {
2605 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2606 "curent_bitrate_bps < 0");
2607 }
2608 }
2609 if (has_max) {
2610 if (has_current &&
2611 *bitrate.max_bitrate_bps < *bitrate.current_bitrate_bps) {
2612 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2613 "max_bitrate_bps < current_bitrate_bps");
2614 } else if (has_min && *bitrate.max_bitrate_bps < *bitrate.min_bitrate_bps) {
2615 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2616 "max_bitrate_bps < min_bitrate_bps");
2617 } else if (*bitrate.max_bitrate_bps < 0) {
2618 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2619 "max_bitrate_bps < 0");
2620 }
2621 }
2622
2623 Call::Config::BitrateConfigMask mask;
2624 mask.min_bitrate_bps = bitrate.min_bitrate_bps;
2625 mask.start_bitrate_bps = bitrate.current_bitrate_bps;
2626 mask.max_bitrate_bps = bitrate.max_bitrate_bps;
2627
2628 RTC_DCHECK(call_.get());
2629 call_->SetBitrateConfigMask(mask);
2630
2631 return RTCError::OK();
2632}
2633
Alex Narest78609d52017-10-20 10:37:47 +02002634void PeerConnection::SetBitrateAllocationStrategy(
2635 std::unique_ptr<rtc::BitrateAllocationStrategy>
2636 bitrate_allocation_strategy) {
2637 rtc::Thread* worker_thread = factory_->worker_thread();
2638 if (!worker_thread->IsCurrent()) {
2639 rtc::BitrateAllocationStrategy* strategy_raw =
2640 bitrate_allocation_strategy.release();
2641 auto functor = [this, strategy_raw]() {
2642 call_->SetBitrateAllocationStrategy(
2643 rtc::WrapUnique<rtc::BitrateAllocationStrategy>(strategy_raw));
2644 };
2645 worker_thread->Invoke<void>(RTC_FROM_HERE, functor);
2646 return;
2647 }
2648 RTC_DCHECK(call_.get());
2649 call_->SetBitrateAllocationStrategy(std::move(bitrate_allocation_strategy));
2650}
2651
henrika5f6bf242017-11-01 11:06:56 +01002652void PeerConnection::SetAudioPlayout(bool playout) {
2653 if (!worker_thread()->IsCurrent()) {
2654 worker_thread()->Invoke<void>(
2655 RTC_FROM_HERE,
2656 rtc::Bind(&PeerConnection::SetAudioPlayout, this, playout));
2657 return;
2658 }
2659 auto audio_state =
2660 factory_->channel_manager()->media_engine()->GetAudioState();
2661 audio_state->SetPlayout(playout);
2662}
2663
2664void PeerConnection::SetAudioRecording(bool recording) {
2665 if (!worker_thread()->IsCurrent()) {
2666 worker_thread()->Invoke<void>(
2667 RTC_FROM_HERE,
2668 rtc::Bind(&PeerConnection::SetAudioRecording, this, recording));
2669 return;
2670 }
2671 auto audio_state =
2672 factory_->channel_manager()->media_engine()->GetAudioState();
2673 audio_state->SetRecording(recording);
2674}
2675
Steve Anton8c0f7a72017-10-03 10:03:10 -07002676std::unique_ptr<rtc::SSLCertificate>
2677PeerConnection::GetRemoteAudioSSLCertificate() {
Steve Anton75737c02017-11-06 10:37:17 -08002678 if (!voice_channel()) {
Steve Anton8c0f7a72017-10-03 10:03:10 -07002679 return nullptr;
2680 }
Steve Anton75737c02017-11-06 10:37:17 -08002681 return GetRemoteSSLCertificate(voice_channel()->transport_name());
Steve Anton8c0f7a72017-10-03 10:03:10 -07002682}
2683
ivoc14d5dbe2016-07-04 07:06:55 -07002684bool PeerConnection::StartRtcEventLog(rtc::PlatformFile file,
2685 int64_t max_size_bytes) {
Elad Alon99c3fe52017-10-13 16:29:40 +02002686 // TODO(eladalon): It would be better to not allow negative values into PC.
2687 const size_t max_size = (max_size_bytes < 0)
2688 ? RtcEventLog::kUnlimitedOutput
2689 : rtc::saturated_cast<size_t>(max_size_bytes);
2690 return StartRtcEventLog(
Bjorn Tereliusde939432017-11-20 17:38:14 +01002691 rtc::MakeUnique<RtcEventLogOutputFile>(file, max_size),
2692 webrtc::RtcEventLog::kImmediateOutput);
Elad Alon99c3fe52017-10-13 16:29:40 +02002693}
2694
Bjorn Tereliusde939432017-11-20 17:38:14 +01002695bool PeerConnection::StartRtcEventLog(std::unique_ptr<RtcEventLogOutput> output,
2696 int64_t output_period_ms) {
Karl Wibergd6b48192017-10-16 23:01:06 +02002697 // TODO(eladalon): In C++14, this can be done with a lambda.
2698 struct Functor {
Bjorn Tereliusde939432017-11-20 17:38:14 +01002699 bool operator()() {
2700 return pc->StartRtcEventLog_w(std::move(output), output_period_ms);
2701 }
Karl Wibergd6b48192017-10-16 23:01:06 +02002702 PeerConnection* const pc;
2703 std::unique_ptr<RtcEventLogOutput> output;
Bjorn Tereliusde939432017-11-20 17:38:14 +01002704 const int64_t output_period_ms;
Elad Alon99c3fe52017-10-13 16:29:40 +02002705 };
Bjorn Tereliusde939432017-11-20 17:38:14 +01002706 return worker_thread()->Invoke<bool>(
2707 RTC_FROM_HERE, Functor{this, std::move(output), output_period_ms});
ivoc14d5dbe2016-07-04 07:06:55 -07002708}
2709
2710void PeerConnection::StopRtcEventLog() {
Steve Anton978b8762017-09-29 12:15:02 -07002711 worker_thread()->Invoke<void>(
ivoc14d5dbe2016-07-04 07:06:55 -07002712 RTC_FROM_HERE, rtc::Bind(&PeerConnection::StopRtcEventLog_w, this));
2713}
2714
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002715const SessionDescriptionInterface* PeerConnection::local_description() const {
Steve Anton75737c02017-11-06 10:37:17 -08002716 return pending_local_description_ ? pending_local_description_.get()
2717 : current_local_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002718}
2719
2720const SessionDescriptionInterface* PeerConnection::remote_description() const {
Steve Anton75737c02017-11-06 10:37:17 -08002721 return pending_remote_description_ ? pending_remote_description_.get()
2722 : current_remote_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002723}
2724
deadbeeffe4a8a42016-12-20 17:56:17 -08002725const SessionDescriptionInterface* PeerConnection::current_local_description()
2726 const {
Steve Anton75737c02017-11-06 10:37:17 -08002727 return current_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08002728}
2729
2730const SessionDescriptionInterface* PeerConnection::current_remote_description()
2731 const {
Steve Anton75737c02017-11-06 10:37:17 -08002732 return current_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08002733}
2734
2735const SessionDescriptionInterface* PeerConnection::pending_local_description()
2736 const {
Steve Anton75737c02017-11-06 10:37:17 -08002737 return pending_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08002738}
2739
2740const SessionDescriptionInterface* PeerConnection::pending_remote_description()
2741 const {
Steve Anton75737c02017-11-06 10:37:17 -08002742 return pending_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08002743}
2744
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002745void PeerConnection::Close() {
Peter Boström1a9d6152015-12-08 22:15:17 +01002746 TRACE_EVENT0("webrtc", "PeerConnection::Close");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002747 // Update stats here so that we have the most recent stats for tracks and
2748 // streams before the channels are closed.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00002749 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002750
Steve Anton75737c02017-11-06 10:37:17 -08002751 ChangeSignalingState(PeerConnectionInterface::kClosed);
Steve Anton3fe1b152017-12-12 10:20:08 -08002752
Steve Anton8af21862017-12-15 11:20:13 -08002753 for (auto transceiver : transceivers_) {
2754 transceiver->Stop();
2755 }
2756 DestroyAllChannels();
Steve Anton75737c02017-11-06 10:37:17 -08002757
deadbeef42a42632017-03-10 15:18:00 -08002758 network_thread()->Invoke<void>(
2759 RTC_FROM_HERE,
2760 rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
2761 port_allocator_.get()));
nisseeaabdf62017-05-05 02:23:02 -07002762
Steve Anton978b8762017-09-29 12:15:02 -07002763 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
eladalon248fd4f2017-09-06 05:18:15 -07002764 call_.reset();
2765 // The event log must outlive call (and any other object that uses it).
2766 event_log_.reset();
2767 });
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002768}
2769
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002770void PeerConnection::OnMessage(rtc::Message* msg) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002771 switch (msg->message_id) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002772 case MSG_SET_SESSIONDESCRIPTION_SUCCESS: {
2773 SetSessionDescriptionMsg* param =
2774 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
2775 param->observer->OnSuccess();
2776 delete param;
2777 break;
2778 }
2779 case MSG_SET_SESSIONDESCRIPTION_FAILED: {
2780 SetSessionDescriptionMsg* param =
2781 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
2782 param->observer->OnFailure(param->error);
2783 delete param;
2784 break;
2785 }
deadbeefab9b2d12015-10-14 11:33:11 -07002786 case MSG_CREATE_SESSIONDESCRIPTION_FAILED: {
2787 CreateSessionDescriptionMsg* param =
2788 static_cast<CreateSessionDescriptionMsg*>(msg->pdata);
2789 param->observer->OnFailure(param->error);
2790 delete param;
2791 break;
2792 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002793 case MSG_GETSTATS: {
2794 GetStatsMsg* param = static_cast<GetStatsMsg*>(msg->pdata);
nissee8abe3e2017-01-18 05:00:34 -08002795 StatsReports reports;
2796 stats_->GetStats(param->track, &reports);
2797 param->observer->OnComplete(reports);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002798 delete param;
2799 break;
2800 }
deadbeefbd292462015-12-14 18:15:29 -08002801 case MSG_FREE_DATACHANNELS: {
2802 sctp_data_channels_to_free_.clear();
2803 break;
2804 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002805 default:
nisseeb4ca4e2017-01-12 02:24:27 -08002806 RTC_NOTREACHED() << "Not implemented";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002807 break;
2808 }
2809}
2810
Steve Anton4171afb2017-11-20 10:20:22 -08002811void PeerConnection::CreateAudioReceiver(
2812 MediaStreamInterface* stream,
2813 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01002814 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
2815 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Steve Antond3679212018-01-17 17:41:02 -08002816 auto* audio_receiver = new AudioRtpReceiver(
2817 worker_thread(), remote_sender_info.sender_id, streams);
2818 audio_receiver->SetMediaChannel(voice_media_channel());
2819 audio_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
2820 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
2821 signaling_thread(), audio_receiver);
Steve Anton4171afb2017-11-20 10:20:22 -08002822 GetAudioTransceiver()->internal()->AddReceiver(receiver);
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01002823 observer_->OnAddTrack(receiver, std::move(streams));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002824}
2825
Steve Anton4171afb2017-11-20 10:20:22 -08002826void PeerConnection::CreateVideoReceiver(
2827 MediaStreamInterface* stream,
2828 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01002829 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
2830 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Steve Antond3679212018-01-17 17:41:02 -08002831 auto* video_receiver = new VideoRtpReceiver(
2832 worker_thread(), remote_sender_info.sender_id, streams);
2833 video_receiver->SetMediaChannel(video_media_channel());
2834 video_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
2835 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
2836 signaling_thread(), video_receiver);
Steve Anton4171afb2017-11-20 10:20:22 -08002837 GetVideoTransceiver()->internal()->AddReceiver(receiver);
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01002838 observer_->OnAddTrack(receiver, std::move(streams));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002839}
2840
deadbeef70ab1a12015-09-28 16:53:55 -07002841// TODO(deadbeef): Keep RtpReceivers around even if track goes away in remote
2842// description.
Henrik Boström933d8b02017-10-10 10:05:16 -07002843rtc::scoped_refptr<RtpReceiverInterface> PeerConnection::RemoveAndStopReceiver(
Steve Anton4171afb2017-11-20 10:20:22 -08002844 const RtpSenderInfo& remote_sender_info) {
2845 auto receiver = FindReceiverById(remote_sender_info.sender_id);
2846 if (!receiver) {
2847 RTC_LOG(LS_WARNING) << "RtpReceiver for track with id "
2848 << remote_sender_info.sender_id << " doesn't exist.";
Henrik Boström933d8b02017-10-10 10:05:16 -07002849 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07002850 }
Steve Anton4171afb2017-11-20 10:20:22 -08002851 if (receiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
2852 GetAudioTransceiver()->internal()->RemoveReceiver(receiver);
2853 } else {
2854 GetVideoTransceiver()->internal()->RemoveReceiver(receiver);
2855 }
Henrik Boström933d8b02017-10-10 10:05:16 -07002856 return receiver;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002857}
2858
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002859void PeerConnection::AddAudioTrack(AudioTrackInterface* track,
2860 MediaStreamInterface* stream) {
2861 RTC_DCHECK(!IsClosed());
2862 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08002863 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002864 // We already have a sender for this track, so just change the stream_id
2865 // so that it's correct in the next call to CreateOffer.
Steve Anton4171afb2017-11-20 10:20:22 -08002866 sender->internal()->set_stream_id(stream->label());
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002867 return;
2868 }
2869
2870 // Normal case; we've never seen this track before.
Steve Anton02ee47c2018-01-10 16:26:06 -08002871 auto new_sender =
2872 CreateSender(cricket::MEDIA_TYPE_AUDIO, track, {stream->label()});
2873 static_cast<AudioRtpSender*>(new_sender->internal())
Steve Anton47136dd2018-01-12 10:49:35 -08002874 ->SetMediaChannel(voice_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08002875 GetAudioTransceiver()->internal()->AddSender(new_sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002876 // If the sender has already been configured in SDP, we call SetSsrc,
2877 // which will connect the sender to the underlying transport. This can
2878 // occur if a local session description that contains the ID of the sender
2879 // is set before AddStream is called. It can also occur if the local
2880 // session description is not changed and RemoveStream is called, and
2881 // later AddStream is called again with the same stream.
Steve Anton4171afb2017-11-20 10:20:22 -08002882 const RtpSenderInfo* sender_info =
2883 FindSenderInfo(local_audio_sender_infos_, stream->label(), track->id());
2884 if (sender_info) {
2885 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002886 }
2887}
2888
2889// TODO(deadbeef): Don't destroy RtpSenders here; they should be kept around
2890// indefinitely, when we have unified plan SDP.
2891void PeerConnection::RemoveAudioTrack(AudioTrackInterface* track,
2892 MediaStreamInterface* stream) {
2893 RTC_DCHECK(!IsClosed());
2894 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08002895 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002896 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
2897 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002898 return;
2899 }
Steve Anton4171afb2017-11-20 10:20:22 -08002900 GetAudioTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002901}
2902
2903void PeerConnection::AddVideoTrack(VideoTrackInterface* track,
2904 MediaStreamInterface* stream) {
2905 RTC_DCHECK(!IsClosed());
2906 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08002907 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002908 // We already have a sender for this track, so just change the stream_id
2909 // so that it's correct in the next call to CreateOffer.
Steve Anton4171afb2017-11-20 10:20:22 -08002910 sender->internal()->set_stream_id(stream->label());
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002911 return;
2912 }
2913
2914 // Normal case; we've never seen this track before.
Steve Anton02ee47c2018-01-10 16:26:06 -08002915 auto new_sender =
2916 CreateSender(cricket::MEDIA_TYPE_VIDEO, track, {stream->label()});
2917 static_cast<VideoRtpSender*>(new_sender->internal())
Steve Anton47136dd2018-01-12 10:49:35 -08002918 ->SetMediaChannel(video_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08002919 GetVideoTransceiver()->internal()->AddSender(new_sender);
2920 const RtpSenderInfo* sender_info =
2921 FindSenderInfo(local_video_sender_infos_, stream->label(), track->id());
2922 if (sender_info) {
2923 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002924 }
2925}
2926
2927void PeerConnection::RemoveVideoTrack(VideoTrackInterface* track,
2928 MediaStreamInterface* stream) {
2929 RTC_DCHECK(!IsClosed());
2930 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08002931 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002932 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
2933 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002934 return;
2935 }
Steve Anton4171afb2017-11-20 10:20:22 -08002936 GetVideoTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002937}
2938
Steve Antonba818672017-11-06 10:21:57 -08002939void PeerConnection::SetIceConnectionState(IceConnectionState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07002940 RTC_DCHECK(signaling_thread()->IsCurrent());
Steve Antonba818672017-11-06 10:21:57 -08002941 if (ice_connection_state_ == new_state) {
2942 return;
2943 }
2944
deadbeefcbecd352015-09-23 11:50:27 -07002945 // After transitioning to "closed", ignore any additional states from
Steve Antonba818672017-11-06 10:21:57 -08002946 // TransportController (such as "disconnected").
deadbeefab9b2d12015-10-14 11:33:11 -07002947 if (IsClosed()) {
deadbeefcbecd352015-09-23 11:50:27 -07002948 return;
2949 }
Steve Antonba818672017-11-06 10:21:57 -08002950
Mirko Bonadei675513b2017-11-09 11:09:25 +01002951 RTC_LOG(LS_INFO) << "Changing IceConnectionState " << ice_connection_state_
2952 << " => " << new_state;
Steve Antonba818672017-11-06 10:21:57 -08002953 RTC_DCHECK(ice_connection_state_ !=
2954 PeerConnectionInterface::kIceConnectionClosed);
2955
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002956 ice_connection_state_ = new_state;
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00002957 observer_->OnIceConnectionChange(ice_connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002958}
2959
2960void PeerConnection::OnIceGatheringChange(
2961 PeerConnectionInterface::IceGatheringState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07002962 RTC_DCHECK(signaling_thread()->IsCurrent());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002963 if (IsClosed()) {
2964 return;
2965 }
2966 ice_gathering_state_ = new_state;
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00002967 observer_->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002968}
2969
jbauch81bf7b02017-03-25 08:31:12 -07002970void PeerConnection::OnIceCandidate(
2971 std::unique_ptr<IceCandidateInterface> candidate) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07002972 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07002973 if (IsClosed()) {
2974 return;
2975 }
jbauch81bf7b02017-03-25 08:31:12 -07002976 observer_->OnIceCandidate(candidate.get());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002977}
2978
Honghai Zhang7fb69db2016-03-14 11:59:18 -07002979void PeerConnection::OnIceCandidatesRemoved(
2980 const std::vector<cricket::Candidate>& candidates) {
2981 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07002982 if (IsClosed()) {
2983 return;
2984 }
Honghai Zhang7fb69db2016-03-14 11:59:18 -07002985 observer_->OnIceCandidatesRemoved(candidates);
2986}
2987
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002988void PeerConnection::ChangeSignalingState(
2989 PeerConnectionInterface::SignalingState signaling_state) {
Steve Antonba818672017-11-06 10:21:57 -08002990 RTC_DCHECK(signaling_thread()->IsCurrent());
2991 if (signaling_state_ == signaling_state) {
2992 return;
2993 }
Mirko Bonadei675513b2017-11-09 11:09:25 +01002994 RTC_LOG(LS_INFO) << "Session: " << session_id() << " Old state: "
2995 << GetSignalingStateString(signaling_state_)
2996 << " New state: "
2997 << GetSignalingStateString(signaling_state);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002998 signaling_state_ = signaling_state;
2999 if (signaling_state == kClosed) {
3000 ice_connection_state_ = kIceConnectionClosed;
3001 observer_->OnIceConnectionChange(ice_connection_state_);
3002 if (ice_gathering_state_ != kIceGatheringComplete) {
3003 ice_gathering_state_ = kIceGatheringComplete;
3004 observer_->OnIceGatheringChange(ice_gathering_state_);
3005 }
3006 }
3007 observer_->OnSignalingChange(signaling_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003008}
3009
deadbeefeb459812015-12-15 19:24:43 -08003010void PeerConnection::OnAudioTrackAdded(AudioTrackInterface* track,
3011 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003012 if (IsClosed()) {
3013 return;
3014 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003015 AddAudioTrack(track, stream);
3016 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003017}
3018
deadbeefeb459812015-12-15 19:24:43 -08003019void PeerConnection::OnAudioTrackRemoved(AudioTrackInterface* track,
3020 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003021 if (IsClosed()) {
3022 return;
3023 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003024 RemoveAudioTrack(track, stream);
3025 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003026}
3027
3028void PeerConnection::OnVideoTrackAdded(VideoTrackInterface* track,
3029 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003030 if (IsClosed()) {
3031 return;
3032 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003033 AddVideoTrack(track, stream);
3034 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003035}
3036
3037void PeerConnection::OnVideoTrackRemoved(VideoTrackInterface* track,
3038 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003039 if (IsClosed()) {
3040 return;
3041 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003042 RemoveVideoTrack(track, stream);
3043 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003044}
3045
Henrik Boström31638672017-11-23 17:48:32 +01003046void PeerConnection::PostSetSessionDescriptionSuccess(
3047 SetSessionDescriptionObserver* observer) {
3048 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
3049 signaling_thread()->Post(RTC_FROM_HERE, this,
3050 MSG_SET_SESSIONDESCRIPTION_SUCCESS, msg);
3051}
3052
deadbeefab9b2d12015-10-14 11:33:11 -07003053void PeerConnection::PostSetSessionDescriptionFailure(
3054 SetSessionDescriptionObserver* observer,
3055 const std::string& error) {
3056 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
3057 msg->error = error;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07003058 signaling_thread()->Post(RTC_FROM_HERE, this,
3059 MSG_SET_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07003060}
3061
3062void PeerConnection::PostCreateSessionDescriptionFailure(
3063 CreateSessionDescriptionObserver* observer,
3064 const std::string& error) {
3065 CreateSessionDescriptionMsg* msg = new CreateSessionDescriptionMsg(observer);
3066 msg->error = error;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07003067 signaling_thread()->Post(RTC_FROM_HERE, this,
3068 MSG_CREATE_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07003069}
3070
zhihuang1c378ed2017-08-17 14:10:50 -07003071void PeerConnection::GetOptionsForOffer(
Steve Antondcc3c022017-12-22 16:02:54 -08003072 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
deadbeefab9b2d12015-10-14 11:33:11 -07003073 cricket::MediaSessionOptions* session_options) {
Steve Antondcc3c022017-12-22 16:02:54 -08003074 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
zhihuang1c378ed2017-08-17 14:10:50 -07003075
Steve Antondcc3c022017-12-22 16:02:54 -08003076 if (IsUnifiedPlan()) {
3077 GetOptionsForUnifiedPlanOffer(offer_answer_options, session_options);
3078 } else {
3079 GetOptionsForPlanBOffer(offer_answer_options, session_options);
3080 }
3081
Steve Antonfa2260d2017-12-28 16:38:23 -08003082 // Intentionally unset the data channel type for RTP data channel with the
3083 // second condition. Otherwise the RTP data channels would be successfully
3084 // negotiated by default and the unit tests in WebRtcDataBrowserTest will fail
3085 // when building with chromium. We want to leave RTP data channels broken, so
3086 // people won't try to use them.
3087 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
3088 session_options->data_channel_type = data_channel_type();
3089 }
3090
Steve Antondcc3c022017-12-22 16:02:54 -08003091 // Apply ICE restart flag and renomination flag.
3092 for (auto& options : session_options->media_description_options) {
3093 options.transport_options.ice_restart = offer_answer_options.ice_restart;
3094 options.transport_options.enable_ice_renomination =
3095 configuration_.enable_ice_renomination;
3096 }
3097
3098 session_options->rtcp_cname = rtcp_cname_;
3099 session_options->crypto_options = factory_->options().crypto_options;
3100}
3101
3102void PeerConnection::GetOptionsForPlanBOffer(
3103 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
3104 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07003105 // Figure out transceiver directional preferences.
3106 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
3107 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
3108
3109 // By default, generate sendrecv/recvonly m= sections.
3110 bool recv_audio = true;
3111 bool recv_video = true;
3112
3113 // By default, only offer a new m= section if we have media to send with it.
3114 bool offer_new_audio_description = send_audio;
3115 bool offer_new_video_description = send_video;
3116 bool offer_new_data_description = HasDataChannels();
3117
3118 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-22 16:02:54 -08003119 if (offer_answer_options.offer_to_receive_audio !=
3120 RTCOfferAnswerOptions::kUndefined) {
3121 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003122 offer_new_audio_description =
Steve Antondcc3c022017-12-22 16:02:54 -08003123 offer_new_audio_description ||
3124 (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003125 }
Steve Antondcc3c022017-12-22 16:02:54 -08003126 if (offer_answer_options.offer_to_receive_video !=
3127 RTCOfferAnswerOptions::kUndefined) {
3128 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003129 offer_new_video_description =
Steve Antondcc3c022017-12-22 16:02:54 -08003130 offer_new_video_description ||
3131 (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003132 }
3133
3134 rtc::Optional<size_t> audio_index;
3135 rtc::Optional<size_t> video_index;
3136 rtc::Optional<size_t> data_index;
3137 // If a current description exists, generate m= sections in the same order,
3138 // using the first audio/video/data section that appears and rejecting
3139 // extraneous ones.
Steve Anton75737c02017-11-06 10:37:17 -08003140 if (local_description()) {
zhihuang1c378ed2017-08-17 14:10:50 -07003141 GenerateMediaDescriptionOptions(
Steve Anton75737c02017-11-06 10:37:17 -08003142 local_description(),
Steve Anton1d03a752017-11-27 14:30:09 -08003143 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
3144 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
3145 &audio_index, &video_index, &data_index, session_options);
deadbeefab9b2d12015-10-14 11:33:11 -07003146 }
3147
zhihuang1c378ed2017-08-17 14:10:50 -07003148 // Add audio/video/data m= sections to the end if needed.
3149 if (!audio_index && offer_new_audio_description) {
3150 session_options->media_description_options.push_back(
3151 cricket::MediaDescriptionOptions(
3152 cricket::MEDIA_TYPE_AUDIO, cricket::CN_AUDIO,
Steve Anton1d03a752017-11-27 14:30:09 -08003153 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
3154 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003155 audio_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07003156 }
zhihuang1c378ed2017-08-17 14:10:50 -07003157 if (!video_index && offer_new_video_description) {
3158 session_options->media_description_options.push_back(
3159 cricket::MediaDescriptionOptions(
3160 cricket::MEDIA_TYPE_VIDEO, cricket::CN_VIDEO,
Steve Anton1d03a752017-11-27 14:30:09 -08003161 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
3162 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003163 video_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07003164 }
zhihuang1c378ed2017-08-17 14:10:50 -07003165 if (!data_index && offer_new_data_description) {
3166 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08003167 GetMediaDescriptionOptionsForActiveData(cricket::CN_DATA));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003168 data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07003169 }
3170
3171 cricket::MediaDescriptionOptions* audio_media_description_options =
3172 !audio_index ? nullptr
3173 : &session_options->media_description_options[*audio_index];
3174 cricket::MediaDescriptionOptions* video_media_description_options =
3175 !video_index ? nullptr
3176 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 14:10:50 -07003177
Steve Anton4171afb2017-11-20 10:20:22 -08003178 AddRtpSenderOptions(GetSendersInternal(), audio_media_description_options,
zhihuang1c378ed2017-08-17 14:10:50 -07003179 video_media_description_options);
Steve Antondcc3c022017-12-22 16:02:54 -08003180}
3181
3182// Find a new MID that is not already in |used_mids|, then add it to |used_mids|
3183// and return a reference to it.
3184// Generated MIDs should be no more than 3 bytes long to take up less space in
3185// the RTP packet.
3186static const std::string& AllocateMid(std::set<std::string>* used_mids) {
3187 RTC_DCHECK(used_mids);
3188 // We're boring: just generate MIDs 0, 1, 2, ...
3189 size_t i = 0;
3190 std::set<std::string>::iterator it;
3191 bool inserted;
3192 do {
3193 std::string mid = rtc::ToString(i++);
3194 auto insert_result = used_mids->insert(mid);
3195 it = insert_result.first;
3196 inserted = insert_result.second;
3197 } while (!inserted);
3198 return *it;
3199}
3200
3201static cricket::MediaDescriptionOptions
3202GetMediaDescriptionOptionsForTransceiver(
3203 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3204 transceiver,
3205 const std::string& mid) {
3206 cricket::MediaDescriptionOptions media_description_options(
3207 transceiver->internal()->media_type(), mid, transceiver->direction(),
3208 transceiver->stopped());
3209 cricket::SenderOptions sender_options;
3210 sender_options.track_id = transceiver->sender()->id();
3211 sender_options.stream_ids = transceiver->sender()->stream_ids();
3212 // TODO(bugs.webrtc.org/7600): Set num_sim_layers to the number of encodings
3213 // set in the RTP parameters when the transceiver was added.
3214 sender_options.num_sim_layers = 1;
3215 media_description_options.sender_options.push_back(sender_options);
3216 return media_description_options;
3217}
3218
3219void PeerConnection::GetOptionsForUnifiedPlanOffer(
3220 const RTCOfferAnswerOptions& offer_answer_options,
3221 cricket::MediaSessionOptions* session_options) {
3222 // Rules for generating an offer are dictated by JSEP sections 5.2.1 (Initial
3223 // Offers) and 5.2.2 (Subsequent Offers).
3224 RTC_DCHECK_EQ(session_options->media_description_options.size(), 0);
3225 const ContentInfos& local_contents =
3226 (local_description() ? local_description()->description()->contents()
3227 : ContentInfos());
3228 const ContentInfos& remote_contents =
3229 (remote_description() ? remote_description()->description()->contents()
3230 : ContentInfos());
3231 // The mline indices that can be recycled. New transceivers should reuse these
3232 // slots first.
3233 std::queue<size_t> recycleable_mline_indices;
3234 // Track the MIDs used in previous offer/answer exchanges and the current
3235 // offer so that new, unique MIDs are generated.
3236 std::set<std::string> used_mids = seen_mids_;
3237 // First, go through each media section that exists in either the local or
3238 // remote description and generate a media section in this offer for the
3239 // associated transceiver. If a media section can be recycled, generate a
3240 // default, rejected media section here that can be later overwritten.
3241 for (size_t i = 0;
3242 i < std::max(local_contents.size(), remote_contents.size()); ++i) {
3243 // Either |local_content| or |remote_content| is non-null.
3244 const ContentInfo* local_content =
3245 (i < local_contents.size() ? &local_contents[i] : nullptr);
3246 const ContentInfo* remote_content =
3247 (i < remote_contents.size() ? &remote_contents[i] : nullptr);
3248 bool had_been_rejected = (local_content && local_content->rejected) ||
3249 (remote_content && remote_content->rejected);
3250 const std::string& mid =
3251 (local_content ? local_content->name : remote_content->name);
3252 cricket::MediaType media_type =
3253 (local_content ? local_content->media_description()->type()
3254 : remote_content->media_description()->type());
3255 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
3256 media_type == cricket::MEDIA_TYPE_VIDEO) {
3257 auto transceiver = GetAssociatedTransceiver(mid);
3258 RTC_CHECK(transceiver);
3259 // A media section is considered eligible for recycling if it is marked as
3260 // rejected in either the local or remote description.
3261 if (had_been_rejected) {
3262 session_options->media_description_options.push_back(
3263 cricket::MediaDescriptionOptions(
3264 transceiver->internal()->media_type(), mid,
3265 RtpTransceiverDirection::kInactive,
3266 /*stopped=*/true));
3267 recycleable_mline_indices.push(i);
3268 } else {
3269 session_options->media_description_options.push_back(
3270 GetMediaDescriptionOptionsForTransceiver(transceiver, mid));
3271 // CreateOffer shouldn't really cause any state changes in
3272 // PeerConnection, but we need a way to match new transceivers to new
3273 // media sections in SetLocalDescription and JSEP specifies this is done
3274 // by recording the index of the media section generated for the
3275 // transceiver in the offer.
3276 transceiver->internal()->set_mline_index(i);
3277 }
3278 } else {
3279 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antonfa2260d2017-12-28 16:38:23 -08003280 RTC_CHECK(GetDataMid());
3281 if (had_been_rejected || mid != *GetDataMid()) {
3282 session_options->media_description_options.push_back(
3283 GetMediaDescriptionOptionsForRejectedData(mid));
3284 } else {
3285 session_options->media_description_options.push_back(
3286 GetMediaDescriptionOptionsForActiveData(mid));
3287 }
Steve Antondcc3c022017-12-22 16:02:54 -08003288 }
3289 }
3290 // Next, look for transceivers that are newly added (that is, are not stopped
3291 // and not associated). Reuse media sections marked as recyclable first,
3292 // otherwise append to the end of the offer. New media sections should be
3293 // added in the order they were added to the PeerConnection.
3294 for (auto transceiver : transceivers_) {
3295 if (transceiver->mid() || transceiver->stopped()) {
3296 continue;
3297 }
3298 size_t mline_index;
3299 if (!recycleable_mline_indices.empty()) {
3300 mline_index = recycleable_mline_indices.front();
3301 recycleable_mline_indices.pop();
3302 session_options->media_description_options[mline_index] =
3303 GetMediaDescriptionOptionsForTransceiver(transceiver,
3304 AllocateMid(&used_mids));
3305 } else {
3306 mline_index = session_options->media_description_options.size();
3307 session_options->media_description_options.push_back(
3308 GetMediaDescriptionOptionsForTransceiver(transceiver,
3309 AllocateMid(&used_mids)));
3310 }
3311 // See comment above for why CreateOffer changes the transceiver's state.
3312 transceiver->internal()->set_mline_index(mline_index);
3313 }
Steve Antonfa2260d2017-12-28 16:38:23 -08003314 // Lastly, add a m-section if we have local data channels and an m section
3315 // does not already exist.
3316 if (!GetDataMid() && HasDataChannels()) {
3317 session_options->media_description_options.push_back(
3318 GetMediaDescriptionOptionsForActiveData(AllocateMid(&used_mids)));
3319 }
Steve Antondcc3c022017-12-22 16:02:54 -08003320}
3321
3322void PeerConnection::GetOptionsForAnswer(
3323 const RTCOfferAnswerOptions& offer_answer_options,
3324 cricket::MediaSessionOptions* session_options) {
3325 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
3326
3327 if (IsUnifiedPlan()) {
3328 GetOptionsForUnifiedPlanAnswer(offer_answer_options, session_options);
3329 } else {
3330 GetOptionsForPlanBAnswer(offer_answer_options, session_options);
3331 }
3332
Steve Antonfa2260d2017-12-28 16:38:23 -08003333 // Intentionally unset the data channel type for RTP data channel. Otherwise
3334 // the RTP data channels would be successfully negotiated by default and the
3335 // unit tests in WebRtcDataBrowserTest will fail when building with chromium.
3336 // We want to leave RTP data channels broken, so people won't try to use them.
3337 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
3338 session_options->data_channel_type = data_channel_type();
3339 }
3340
Steve Antondcc3c022017-12-22 16:02:54 -08003341 // Apply ICE renomination flag.
3342 for (auto& options : session_options->media_description_options) {
3343 options.transport_options.enable_ice_renomination =
3344 configuration_.enable_ice_renomination;
3345 }
zhihuang8f65cdf2016-05-06 18:40:30 -07003346
3347 session_options->rtcp_cname = rtcp_cname_;
jbauchcb560652016-08-04 05:20:32 -07003348 session_options->crypto_options = factory_->options().crypto_options;
deadbeefab9b2d12015-10-14 11:33:11 -07003349}
3350
Steve Antondcc3c022017-12-22 16:02:54 -08003351void PeerConnection::GetOptionsForPlanBAnswer(
3352 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07003353 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07003354 // Figure out transceiver directional preferences.
3355 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
3356 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
3357
3358 // By default, generate sendrecv/recvonly m= sections. The direction is also
3359 // restricted by the direction in the offer.
3360 bool recv_audio = true;
3361 bool recv_video = true;
3362
3363 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-22 16:02:54 -08003364 if (offer_answer_options.offer_to_receive_audio !=
3365 RTCOfferAnswerOptions::kUndefined) {
3366 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
deadbeef0ed85b22016-02-23 17:24:52 -08003367 }
Steve Antondcc3c022017-12-22 16:02:54 -08003368 if (offer_answer_options.offer_to_receive_video !=
3369 RTCOfferAnswerOptions::kUndefined) {
3370 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003371 }
3372
3373 rtc::Optional<size_t> audio_index;
3374 rtc::Optional<size_t> video_index;
3375 rtc::Optional<size_t> data_index;
Taylor Brandstetter94d8cce2018-01-26 22:44:21 +00003376 if (remote_description()) {
3377 // The pending remote description should be an offer.
3378 RTC_DCHECK(remote_description()->GetType() == SdpType::kOffer);
3379 // Generate m= sections that match those in the offer.
3380 // Note that mediasession.cc will handle intersection our preferred
3381 // direction with the offered direction.
3382 GenerateMediaDescriptionOptions(
3383 remote_description(),
3384 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
3385 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
3386 &audio_index, &video_index, &data_index, session_options);
3387 }
zhihuang1c378ed2017-08-17 14:10:50 -07003388
3389 cricket::MediaDescriptionOptions* audio_media_description_options =
3390 !audio_index ? nullptr
3391 : &session_options->media_description_options[*audio_index];
3392 cricket::MediaDescriptionOptions* video_media_description_options =
3393 !video_index ? nullptr
3394 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 14:10:50 -07003395
Steve Anton4171afb2017-11-20 10:20:22 -08003396 AddRtpSenderOptions(GetSendersInternal(), audio_media_description_options,
zhihuang1c378ed2017-08-17 14:10:50 -07003397 video_media_description_options);
Steve Antondcc3c022017-12-22 16:02:54 -08003398}
zhihuangaf388472016-11-02 16:49:48 -07003399
Steve Antondcc3c022017-12-22 16:02:54 -08003400void PeerConnection::GetOptionsForUnifiedPlanAnswer(
3401 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
3402 cricket::MediaSessionOptions* session_options) {
3403 // Rules for generating an answer are dictated by JSEP sections 5.3.1 (Initial
3404 // Answers) and 5.3.2 (Subsequent Answers).
3405 RTC_DCHECK(remote_description());
3406 RTC_DCHECK(remote_description()->GetType() == SdpType::kOffer);
3407 for (const ContentInfo& content :
3408 remote_description()->description()->contents()) {
3409 cricket::MediaType media_type = content.media_description()->type();
3410 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
3411 media_type == cricket::MEDIA_TYPE_VIDEO) {
3412 auto transceiver = GetAssociatedTransceiver(content.name);
3413 RTC_CHECK(transceiver);
3414 session_options->media_description_options.push_back(
3415 GetMediaDescriptionOptionsForTransceiver(transceiver, content.name));
3416 } else {
3417 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antondbf9d032018-01-19 15:23:40 -08003418 // Reject all data sections if data channels are disabled.
3419 // Reject a data section if it has already been rejected.
3420 // Reject all data sections except for the first one.
3421 if (data_channel_type_ == cricket::DCT_NONE || content.rejected ||
3422 content.name != *GetDataMid()) {
Steve Antonfa2260d2017-12-28 16:38:23 -08003423 session_options->media_description_options.push_back(
3424 GetMediaDescriptionOptionsForRejectedData(content.name));
3425 } else {
3426 session_options->media_description_options.push_back(
3427 GetMediaDescriptionOptionsForActiveData(content.name));
3428 }
Steve Antondcc3c022017-12-22 16:02:54 -08003429 }
3430 }
htaa2a49d92016-03-04 02:51:39 -08003431}
3432
zhihuang1c378ed2017-08-17 14:10:50 -07003433void PeerConnection::GenerateMediaDescriptionOptions(
3434 const SessionDescriptionInterface* session_desc,
Steve Anton1d03a752017-11-27 14:30:09 -08003435 RtpTransceiverDirection audio_direction,
3436 RtpTransceiverDirection video_direction,
zhihuang1c378ed2017-08-17 14:10:50 -07003437 rtc::Optional<size_t>* audio_index,
3438 rtc::Optional<size_t>* video_index,
3439 rtc::Optional<size_t>* data_index,
htaa2a49d92016-03-04 02:51:39 -08003440 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07003441 for (const cricket::ContentInfo& content :
3442 session_desc->description()->contents()) {
3443 if (IsAudioContent(&content)) {
3444 // If we already have an audio m= section, reject this extra one.
3445 if (*audio_index) {
3446 session_options->media_description_options.push_back(
3447 cricket::MediaDescriptionOptions(
3448 cricket::MEDIA_TYPE_AUDIO, content.name,
Steve Anton1d03a752017-11-27 14:30:09 -08003449 RtpTransceiverDirection::kInactive, true));
zhihuang1c378ed2017-08-17 14:10:50 -07003450 } else {
3451 session_options->media_description_options.push_back(
3452 cricket::MediaDescriptionOptions(
3453 cricket::MEDIA_TYPE_AUDIO, content.name, audio_direction,
Steve Anton1d03a752017-11-27 14:30:09 -08003454 audio_direction == RtpTransceiverDirection::kInactive));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003455 *audio_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07003456 }
3457 } else if (IsVideoContent(&content)) {
3458 // If we already have an video m= section, reject this extra one.
3459 if (*video_index) {
3460 session_options->media_description_options.push_back(
3461 cricket::MediaDescriptionOptions(
3462 cricket::MEDIA_TYPE_VIDEO, content.name,
Steve Anton1d03a752017-11-27 14:30:09 -08003463 RtpTransceiverDirection::kInactive, true));
zhihuang1c378ed2017-08-17 14:10:50 -07003464 } else {
3465 session_options->media_description_options.push_back(
3466 cricket::MediaDescriptionOptions(
3467 cricket::MEDIA_TYPE_VIDEO, content.name, video_direction,
Steve Anton1d03a752017-11-27 14:30:09 -08003468 video_direction == RtpTransceiverDirection::kInactive));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003469 *video_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07003470 }
3471 } else {
3472 RTC_DCHECK(IsDataContent(&content));
3473 // If we already have an data m= section, reject this extra one.
3474 if (*data_index) {
3475 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08003476 GetMediaDescriptionOptionsForRejectedData(content.name));
zhihuang1c378ed2017-08-17 14:10:50 -07003477 } else {
3478 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08003479 GetMediaDescriptionOptionsForActiveData(content.name));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003480 *data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07003481 }
3482 }
htaa2a49d92016-03-04 02:51:39 -08003483 }
deadbeefab9b2d12015-10-14 11:33:11 -07003484}
3485
Steve Antonfa2260d2017-12-28 16:38:23 -08003486cricket::MediaDescriptionOptions
3487PeerConnection::GetMediaDescriptionOptionsForActiveData(
3488 const std::string& mid) const {
3489 // Direction for data sections is meaningless, but legacy endpoints might
3490 // expect sendrecv.
3491 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
3492 RtpTransceiverDirection::kSendRecv,
3493 /*stopped=*/false);
3494 AddRtpDataChannelOptions(rtp_data_channels_, &options);
3495 return options;
3496}
3497
3498cricket::MediaDescriptionOptions
3499PeerConnection::GetMediaDescriptionOptionsForRejectedData(
3500 const std::string& mid) const {
3501 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
3502 RtpTransceiverDirection::kInactive,
3503 /*stopped=*/true);
3504 AddRtpDataChannelOptions(rtp_data_channels_, &options);
3505 return options;
3506}
3507
3508rtc::Optional<std::string> PeerConnection::GetDataMid() const {
3509 switch (data_channel_type_) {
3510 case cricket::DCT_RTP:
3511 if (!rtp_data_channel_) {
3512 return rtc::nullopt;
3513 }
3514 return rtp_data_channel_->content_name();
3515 case cricket::DCT_SCTP:
3516 return sctp_content_name_;
3517 default:
3518 return rtc::nullopt;
3519 }
3520}
3521
Steve Anton4171afb2017-11-20 10:20:22 -08003522void PeerConnection::RemoveSenders(cricket::MediaType media_type) {
3523 UpdateLocalSenders(std::vector<cricket::StreamParams>(), media_type);
3524 UpdateRemoteSendersList(std::vector<cricket::StreamParams>(), false,
deadbeefbda7e0b2015-12-08 17:13:40 -08003525 media_type, nullptr);
deadbeeffaac4972015-11-12 15:33:07 -08003526}
3527
Steve Anton4171afb2017-11-20 10:20:22 -08003528void PeerConnection::UpdateRemoteSendersList(
deadbeefab9b2d12015-10-14 11:33:11 -07003529 const cricket::StreamParamsVec& streams,
Steve Anton4171afb2017-11-20 10:20:22 -08003530 bool default_sender_needed,
deadbeefab9b2d12015-10-14 11:33:11 -07003531 cricket::MediaType media_type,
3532 StreamCollection* new_streams) {
Steve Anton4171afb2017-11-20 10:20:22 -08003533 std::vector<RtpSenderInfo>* current_senders =
3534 GetRemoteSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07003535
Steve Anton4171afb2017-11-20 10:20:22 -08003536 // Find removed senders. I.e., senders where the sender id or ssrc don't match
deadbeeffac06552015-11-25 11:26:01 -08003537 // the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08003538 for (auto sender_it = current_senders->begin();
3539 sender_it != current_senders->end();
3540 /* incremented manually */) {
3541 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07003542 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08003543 cricket::GetStreamBySsrc(streams, info.first_ssrc);
3544 bool sender_exists = params && params->id == info.sender_id;
deadbeefbda7e0b2015-12-08 17:13:40 -08003545 // If this is a default track, and we still need it, don't remove it.
Steve Anton4171afb2017-11-20 10:20:22 -08003546 if ((info.stream_label == kDefaultStreamLabel && default_sender_needed) ||
3547 sender_exists) {
3548 ++sender_it;
deadbeefbda7e0b2015-12-08 17:13:40 -08003549 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08003550 OnRemoteSenderRemoved(info, media_type);
3551 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07003552 }
3553 }
3554
Steve Anton4171afb2017-11-20 10:20:22 -08003555 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07003556 for (const cricket::StreamParams& params : streams) {
3557 // The sync_label is the MediaStream label and the |stream.id| is the
Steve Anton4171afb2017-11-20 10:20:22 -08003558 // sender id.
deadbeefab9b2d12015-10-14 11:33:11 -07003559 const std::string& stream_label = params.sync_label;
Steve Anton4171afb2017-11-20 10:20:22 -08003560 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07003561 uint32_t ssrc = params.first_ssrc();
3562
3563 rtc::scoped_refptr<MediaStreamInterface> stream =
3564 remote_streams_->find(stream_label);
3565 if (!stream) {
3566 // This is a new MediaStream. Create a new remote MediaStream.
perkjd61bf802016-03-24 03:16:19 -07003567 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
3568 MediaStream::Create(stream_label));
deadbeefab9b2d12015-10-14 11:33:11 -07003569 remote_streams_->AddStream(stream);
3570 new_streams->AddStream(stream);
3571 }
3572
Steve Anton4171afb2017-11-20 10:20:22 -08003573 const RtpSenderInfo* sender_info =
3574 FindSenderInfo(*current_senders, stream_label, sender_id);
3575 if (!sender_info) {
3576 current_senders->push_back(RtpSenderInfo(stream_label, sender_id, ssrc));
3577 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07003578 }
3579 }
deadbeefbda7e0b2015-12-08 17:13:40 -08003580
Steve Anton4171afb2017-11-20 10:20:22 -08003581 // Add default sender if necessary.
3582 if (default_sender_needed) {
deadbeefbda7e0b2015-12-08 17:13:40 -08003583 rtc::scoped_refptr<MediaStreamInterface> default_stream =
3584 remote_streams_->find(kDefaultStreamLabel);
3585 if (!default_stream) {
3586 // Create the new default MediaStream.
perkjd61bf802016-03-24 03:16:19 -07003587 default_stream = MediaStreamProxy::Create(
3588 rtc::Thread::Current(), MediaStream::Create(kDefaultStreamLabel));
deadbeefbda7e0b2015-12-08 17:13:40 -08003589 remote_streams_->AddStream(default_stream);
3590 new_streams->AddStream(default_stream);
3591 }
Steve Anton4171afb2017-11-20 10:20:22 -08003592 std::string default_sender_id = (media_type == cricket::MEDIA_TYPE_AUDIO)
3593 ? kDefaultAudioSenderId
3594 : kDefaultVideoSenderId;
3595 const RtpSenderInfo* default_sender_info = FindSenderInfo(
3596 *current_senders, kDefaultStreamLabel, default_sender_id);
3597 if (!default_sender_info) {
3598 current_senders->push_back(
3599 RtpSenderInfo(kDefaultStreamLabel, default_sender_id, 0));
3600 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefbda7e0b2015-12-08 17:13:40 -08003601 }
3602 }
deadbeefab9b2d12015-10-14 11:33:11 -07003603}
3604
Steve Anton4171afb2017-11-20 10:20:22 -08003605void PeerConnection::OnRemoteSenderAdded(const RtpSenderInfo& sender_info,
3606 cricket::MediaType media_type) {
3607 MediaStreamInterface* stream =
3608 remote_streams_->find(sender_info.stream_label);
deadbeefab9b2d12015-10-14 11:33:11 -07003609
3610 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 10:20:22 -08003611 CreateAudioReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07003612 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 10:20:22 -08003613 CreateVideoReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07003614 } else {
nisseeb4ca4e2017-01-12 02:24:27 -08003615 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07003616 }
3617}
3618
Steve Anton4171afb2017-11-20 10:20:22 -08003619void PeerConnection::OnRemoteSenderRemoved(const RtpSenderInfo& sender_info,
3620 cricket::MediaType media_type) {
3621 MediaStreamInterface* stream =
3622 remote_streams_->find(sender_info.stream_label);
deadbeefab9b2d12015-10-14 11:33:11 -07003623
Henrik Boström933d8b02017-10-10 10:05:16 -07003624 rtc::scoped_refptr<RtpReceiverInterface> receiver;
deadbeefab9b2d12015-10-14 11:33:11 -07003625 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
perkjd61bf802016-03-24 03:16:19 -07003626 // When the MediaEngine audio channel is destroyed, the RemoteAudioSource
3627 // will be notified which will end the AudioRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08003628 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07003629 rtc::scoped_refptr<AudioTrackInterface> audio_track =
Steve Anton4171afb2017-11-20 10:20:22 -08003630 stream->FindAudioTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07003631 if (audio_track) {
deadbeefab9b2d12015-10-14 11:33:11 -07003632 stream->RemoveTrack(audio_track);
deadbeefab9b2d12015-10-14 11:33:11 -07003633 }
3634 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
perkjd61bf802016-03-24 03:16:19 -07003635 // Stopping or destroying a VideoRtpReceiver will end the
3636 // VideoRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08003637 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07003638 rtc::scoped_refptr<VideoTrackInterface> video_track =
Steve Anton4171afb2017-11-20 10:20:22 -08003639 stream->FindVideoTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07003640 if (video_track) {
perkjd61bf802016-03-24 03:16:19 -07003641 // There's no guarantee the track is still available, e.g. the track may
3642 // have been removed from the stream by an application.
deadbeefab9b2d12015-10-14 11:33:11 -07003643 stream->RemoveTrack(video_track);
deadbeefab9b2d12015-10-14 11:33:11 -07003644 }
3645 } else {
nisseede5da42017-01-12 05:15:36 -08003646 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07003647 }
Henrik Boström933d8b02017-10-10 10:05:16 -07003648 if (receiver) {
3649 observer_->OnRemoveTrack(receiver);
3650 }
deadbeefab9b2d12015-10-14 11:33:11 -07003651}
3652
3653void PeerConnection::UpdateEndedRemoteMediaStreams() {
3654 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams_to_remove;
3655 for (size_t i = 0; i < remote_streams_->count(); ++i) {
3656 MediaStreamInterface* stream = remote_streams_->at(i);
3657 if (stream->GetAudioTracks().empty() && stream->GetVideoTracks().empty()) {
3658 streams_to_remove.push_back(stream);
3659 }
3660 }
3661
Taylor Brandstetter98cde262016-05-31 13:02:21 -07003662 for (auto& stream : streams_to_remove) {
deadbeefab9b2d12015-10-14 11:33:11 -07003663 remote_streams_->RemoveStream(stream);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07003664 observer_->OnRemoveStream(std::move(stream));
deadbeefab9b2d12015-10-14 11:33:11 -07003665 }
3666}
3667
Steve Anton4171afb2017-11-20 10:20:22 -08003668void PeerConnection::UpdateLocalSenders(
deadbeefab9b2d12015-10-14 11:33:11 -07003669 const std::vector<cricket::StreamParams>& streams,
3670 cricket::MediaType media_type) {
Steve Anton4171afb2017-11-20 10:20:22 -08003671 std::vector<RtpSenderInfo>* current_senders = GetLocalSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07003672
3673 // Find removed tracks. I.e., tracks where the track id, stream label or ssrc
3674 // don't match the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08003675 for (auto sender_it = current_senders->begin();
3676 sender_it != current_senders->end();
3677 /* incremented manually */) {
3678 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07003679 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08003680 cricket::GetStreamBySsrc(streams, info.first_ssrc);
3681 if (!params || params->id != info.sender_id ||
deadbeefab9b2d12015-10-14 11:33:11 -07003682 params->sync_label != info.stream_label) {
Steve Anton4171afb2017-11-20 10:20:22 -08003683 OnLocalSenderRemoved(info, media_type);
3684 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07003685 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08003686 ++sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07003687 }
3688 }
3689
Steve Anton4171afb2017-11-20 10:20:22 -08003690 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07003691 for (const cricket::StreamParams& params : streams) {
3692 // The sync_label is the MediaStream label and the |stream.id| is the
Steve Anton4171afb2017-11-20 10:20:22 -08003693 // sender id.
deadbeefab9b2d12015-10-14 11:33:11 -07003694 const std::string& stream_label = params.sync_label;
Steve Anton4171afb2017-11-20 10:20:22 -08003695 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07003696 uint32_t ssrc = params.first_ssrc();
Steve Anton4171afb2017-11-20 10:20:22 -08003697 const RtpSenderInfo* sender_info =
3698 FindSenderInfo(*current_senders, stream_label, sender_id);
3699 if (!sender_info) {
3700 current_senders->push_back(RtpSenderInfo(stream_label, sender_id, ssrc));
3701 OnLocalSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07003702 }
3703 }
3704}
3705
Steve Anton4171afb2017-11-20 10:20:22 -08003706void PeerConnection::OnLocalSenderAdded(const RtpSenderInfo& sender_info,
3707 cricket::MediaType media_type) {
3708 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08003709 if (!sender) {
Steve Anton4171afb2017-11-20 10:20:22 -08003710 RTC_LOG(LS_WARNING) << "An unknown RtpSender with id "
3711 << sender_info.sender_id
Mirko Bonadei675513b2017-11-09 11:09:25 +01003712 << " has been configured in the local description.";
deadbeefab9b2d12015-10-14 11:33:11 -07003713 return;
3714 }
3715
deadbeeffac06552015-11-25 11:26:01 -08003716 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003717 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
3718 << " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08003719 return;
deadbeefab9b2d12015-10-14 11:33:11 -07003720 }
deadbeeffac06552015-11-25 11:26:01 -08003721
Steve Anton4171afb2017-11-20 10:20:22 -08003722 sender->internal()->set_stream_id(sender_info.stream_label);
3723 sender->internal()->SetSsrc(sender_info.first_ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07003724}
3725
Steve Anton4171afb2017-11-20 10:20:22 -08003726void PeerConnection::OnLocalSenderRemoved(const RtpSenderInfo& sender_info,
3727 cricket::MediaType media_type) {
3728 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08003729 if (!sender) {
3730 // This is the normal case. I.e., RemoveStream has been called and the
deadbeefab9b2d12015-10-14 11:33:11 -07003731 // SessionDescriptions has been renegotiated.
3732 return;
3733 }
deadbeeffac06552015-11-25 11:26:01 -08003734
3735 // A sender has been removed from the SessionDescription but it's still
3736 // associated with the PeerConnection. This only occurs if the SDP doesn't
3737 // match with the calls to CreateSender, AddStream and RemoveStream.
3738 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003739 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
3740 << " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08003741 return;
deadbeefab9b2d12015-10-14 11:33:11 -07003742 }
deadbeeffac06552015-11-25 11:26:01 -08003743
Steve Anton4171afb2017-11-20 10:20:22 -08003744 sender->internal()->SetSsrc(0);
deadbeefab9b2d12015-10-14 11:33:11 -07003745}
3746
3747void PeerConnection::UpdateLocalRtpDataChannels(
3748 const cricket::StreamParamsVec& streams) {
3749 std::vector<std::string> existing_channels;
3750
3751 // Find new and active data channels.
3752 for (const cricket::StreamParams& params : streams) {
3753 // |it->sync_label| is actually the data channel label. The reason is that
3754 // we use the same naming of data channels as we do for
3755 // MediaStreams and Tracks.
3756 // For MediaStreams, the sync_label is the MediaStream label and the
3757 // track label is the same as |streamid|.
3758 const std::string& channel_label = params.sync_label;
3759 auto data_channel_it = rtp_data_channels_.find(channel_label);
nisse7ce109a2017-01-31 00:57:56 -08003760 if (data_channel_it == rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003761 RTC_LOG(LS_ERROR) << "channel label not found";
deadbeefab9b2d12015-10-14 11:33:11 -07003762 continue;
3763 }
3764 // Set the SSRC the data channel should use for sending.
3765 data_channel_it->second->SetSendSsrc(params.first_ssrc());
3766 existing_channels.push_back(data_channel_it->first);
3767 }
3768
3769 UpdateClosingRtpDataChannels(existing_channels, true);
3770}
3771
3772void PeerConnection::UpdateRemoteRtpDataChannels(
3773 const cricket::StreamParamsVec& streams) {
3774 std::vector<std::string> existing_channels;
3775
3776 // Find new and active data channels.
3777 for (const cricket::StreamParams& params : streams) {
3778 // The data channel label is either the mslabel or the SSRC if the mslabel
3779 // does not exist. Ex a=ssrc:444330170 mslabel:test1.
3780 std::string label = params.sync_label.empty()
3781 ? rtc::ToString(params.first_ssrc())
3782 : params.sync_label;
3783 auto data_channel_it = rtp_data_channels_.find(label);
3784 if (data_channel_it == rtp_data_channels_.end()) {
3785 // This is a new data channel.
3786 CreateRemoteRtpDataChannel(label, params.first_ssrc());
3787 } else {
3788 data_channel_it->second->SetReceiveSsrc(params.first_ssrc());
3789 }
3790 existing_channels.push_back(label);
3791 }
3792
3793 UpdateClosingRtpDataChannels(existing_channels, false);
3794}
3795
3796void PeerConnection::UpdateClosingRtpDataChannels(
3797 const std::vector<std::string>& active_channels,
3798 bool is_local_update) {
3799 auto it = rtp_data_channels_.begin();
3800 while (it != rtp_data_channels_.end()) {
3801 DataChannel* data_channel = it->second;
3802 if (std::find(active_channels.begin(), active_channels.end(),
3803 data_channel->label()) != active_channels.end()) {
3804 ++it;
3805 continue;
3806 }
3807
3808 if (is_local_update) {
3809 data_channel->SetSendSsrc(0);
3810 } else {
3811 data_channel->RemotePeerRequestClose();
3812 }
3813
3814 if (data_channel->state() == DataChannel::kClosed) {
3815 rtp_data_channels_.erase(it);
3816 it = rtp_data_channels_.begin();
3817 } else {
3818 ++it;
3819 }
3820 }
3821}
3822
3823void PeerConnection::CreateRemoteRtpDataChannel(const std::string& label,
3824 uint32_t remote_ssrc) {
3825 rtc::scoped_refptr<DataChannel> channel(
3826 InternalCreateDataChannel(label, nullptr));
3827 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003828 RTC_LOG(LS_WARNING) << "Remote peer requested a DataChannel but"
3829 << "CreateDataChannel failed.";
deadbeefab9b2d12015-10-14 11:33:11 -07003830 return;
3831 }
3832 channel->SetReceiveSsrc(remote_ssrc);
deadbeefa601f5c2016-06-06 14:27:39 -07003833 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
3834 DataChannelProxy::Create(signaling_thread(), channel);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07003835 observer_->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07003836}
3837
3838rtc::scoped_refptr<DataChannel> PeerConnection::InternalCreateDataChannel(
3839 const std::string& label,
3840 const InternalDataChannelInit* config) {
3841 if (IsClosed()) {
3842 return nullptr;
3843 }
Steve Anton75737c02017-11-06 10:37:17 -08003844 if (data_channel_type() == cricket::DCT_NONE) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003845 RTC_LOG(LS_ERROR)
deadbeefab9b2d12015-10-14 11:33:11 -07003846 << "InternalCreateDataChannel: Data is not supported in this call.";
3847 return nullptr;
3848 }
3849 InternalDataChannelInit new_config =
3850 config ? (*config) : InternalDataChannelInit();
Steve Anton75737c02017-11-06 10:37:17 -08003851 if (data_channel_type() == cricket::DCT_SCTP) {
deadbeefab9b2d12015-10-14 11:33:11 -07003852 if (new_config.id < 0) {
3853 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08003854 if ((GetSctpSslRole(&role)) &&
deadbeefab9b2d12015-10-14 11:33:11 -07003855 !sid_allocator_.AllocateSid(role, &new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003856 RTC_LOG(LS_ERROR)
3857 << "No id can be allocated for the SCTP data channel.";
deadbeefab9b2d12015-10-14 11:33:11 -07003858 return nullptr;
3859 }
3860 } else if (!sid_allocator_.ReserveSid(new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003861 RTC_LOG(LS_ERROR) << "Failed to create a SCTP data channel "
3862 << "because the id is already in use or out of range.";
deadbeefab9b2d12015-10-14 11:33:11 -07003863 return nullptr;
3864 }
3865 }
3866
Steve Anton75737c02017-11-06 10:37:17 -08003867 rtc::scoped_refptr<DataChannel> channel(
3868 DataChannel::Create(this, data_channel_type(), label, new_config));
deadbeefab9b2d12015-10-14 11:33:11 -07003869 if (!channel) {
3870 sid_allocator_.ReleaseSid(new_config.id);
3871 return nullptr;
3872 }
3873
3874 if (channel->data_channel_type() == cricket::DCT_RTP) {
3875 if (rtp_data_channels_.find(channel->label()) != rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003876 RTC_LOG(LS_ERROR) << "DataChannel with label " << channel->label()
3877 << " already exists.";
deadbeefab9b2d12015-10-14 11:33:11 -07003878 return nullptr;
3879 }
3880 rtp_data_channels_[channel->label()] = channel;
3881 } else {
3882 RTC_DCHECK(channel->data_channel_type() == cricket::DCT_SCTP);
3883 sctp_data_channels_.push_back(channel);
3884 channel->SignalClosed.connect(this,
3885 &PeerConnection::OnSctpDataChannelClosed);
3886 }
3887
Steve Anton2d8609c2018-01-23 16:38:46 -08003888 SignalDataChannelCreated_(channel.get());
deadbeefab9b2d12015-10-14 11:33:11 -07003889 return channel;
3890}
3891
3892bool PeerConnection::HasDataChannels() const {
3893 return !rtp_data_channels_.empty() || !sctp_data_channels_.empty();
3894}
3895
3896void PeerConnection::AllocateSctpSids(rtc::SSLRole role) {
3897 for (const auto& channel : sctp_data_channels_) {
3898 if (channel->id() < 0) {
3899 int sid;
3900 if (!sid_allocator_.AllocateSid(role, &sid)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003901 RTC_LOG(LS_ERROR) << "Failed to allocate SCTP sid.";
deadbeefab9b2d12015-10-14 11:33:11 -07003902 continue;
3903 }
3904 channel->SetSctpSid(sid);
3905 }
3906 }
3907}
3908
3909void PeerConnection::OnSctpDataChannelClosed(DataChannel* channel) {
deadbeefbd292462015-12-14 18:15:29 -08003910 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeefab9b2d12015-10-14 11:33:11 -07003911 for (auto it = sctp_data_channels_.begin(); it != sctp_data_channels_.end();
3912 ++it) {
3913 if (it->get() == channel) {
3914 if (channel->id() >= 0) {
3915 sid_allocator_.ReleaseSid(channel->id());
3916 }
deadbeefbd292462015-12-14 18:15:29 -08003917 // Since this method is triggered by a signal from the DataChannel,
3918 // we can't free it directly here; we need to free it asynchronously.
3919 sctp_data_channels_to_free_.push_back(*it);
deadbeefab9b2d12015-10-14 11:33:11 -07003920 sctp_data_channels_.erase(it);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07003921 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_FREE_DATACHANNELS,
3922 nullptr);
deadbeefab9b2d12015-10-14 11:33:11 -07003923 return;
3924 }
3925 }
3926}
3927
deadbeefab9b2d12015-10-14 11:33:11 -07003928void PeerConnection::OnDataChannelDestroyed() {
3929 // Use a temporary copy of the RTP/SCTP DataChannel list because the
3930 // DataChannel may callback to us and try to modify the list.
3931 std::map<std::string, rtc::scoped_refptr<DataChannel>> temp_rtp_dcs;
3932 temp_rtp_dcs.swap(rtp_data_channels_);
3933 for (const auto& kv : temp_rtp_dcs) {
3934 kv.second->OnTransportChannelDestroyed();
3935 }
3936
3937 std::vector<rtc::scoped_refptr<DataChannel>> temp_sctp_dcs;
3938 temp_sctp_dcs.swap(sctp_data_channels_);
3939 for (const auto& channel : temp_sctp_dcs) {
3940 channel->OnTransportChannelDestroyed();
3941 }
3942}
3943
3944void PeerConnection::OnDataChannelOpenMessage(
3945 const std::string& label,
3946 const InternalDataChannelInit& config) {
3947 rtc::scoped_refptr<DataChannel> channel(
3948 InternalCreateDataChannel(label, &config));
3949 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003950 RTC_LOG(LS_ERROR) << "Failed to create DataChannel from the OPEN message.";
deadbeefab9b2d12015-10-14 11:33:11 -07003951 return;
3952 }
3953
deadbeefa601f5c2016-06-06 14:27:39 -07003954 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
3955 DataChannelProxy::Create(signaling_thread(), channel);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07003956 observer_->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07003957}
3958
Steve Anton4171afb2017-11-20 10:20:22 -08003959rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3960PeerConnection::GetAudioTransceiver() const {
3961 // This method only works with Plan B SDP, where there is a single
3962 // audio/video transceiver.
3963 RTC_DCHECK(!IsUnifiedPlan());
3964 for (auto transceiver : transceivers_) {
3965 if (transceiver->internal()->media_type() == cricket::MEDIA_TYPE_AUDIO) {
3966 return transceiver;
3967 }
3968 }
3969 RTC_NOTREACHED();
3970 return nullptr;
3971}
3972
3973rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3974PeerConnection::GetVideoTransceiver() const {
3975 // This method only works with Plan B SDP, where there is a single
3976 // audio/video transceiver.
3977 RTC_DCHECK(!IsUnifiedPlan());
3978 for (auto transceiver : transceivers_) {
3979 if (transceiver->internal()->media_type() == cricket::MEDIA_TYPE_VIDEO) {
3980 return transceiver;
3981 }
3982 }
3983 RTC_NOTREACHED();
3984 return nullptr;
3985}
3986
3987// TODO(bugs.webrtc.org/7600): Remove this when multiple transceivers with
3988// individual transceiver directions are supported.
zhihuang1c378ed2017-08-17 14:10:50 -07003989bool PeerConnection::HasRtpSender(cricket::MediaType type) const {
Steve Anton4171afb2017-11-20 10:20:22 -08003990 switch (type) {
3991 case cricket::MEDIA_TYPE_AUDIO:
3992 return !GetAudioTransceiver()->internal()->senders().empty();
3993 case cricket::MEDIA_TYPE_VIDEO:
3994 return !GetVideoTransceiver()->internal()->senders().empty();
3995 case cricket::MEDIA_TYPE_DATA:
3996 return false;
3997 }
3998 RTC_NOTREACHED();
3999 return false;
zhihuang1c378ed2017-08-17 14:10:50 -07004000}
4001
Steve Anton4171afb2017-11-20 10:20:22 -08004002rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
4003PeerConnection::FindSenderForTrack(MediaStreamTrackInterface* track) const {
4004 for (auto transceiver : transceivers_) {
4005 for (auto sender : transceiver->internal()->senders()) {
4006 if (sender->track() == track) {
4007 return sender;
4008 }
4009 }
4010 }
4011 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08004012}
4013
Steve Anton4171afb2017-11-20 10:20:22 -08004014rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
4015PeerConnection::FindSenderById(const std::string& sender_id) const {
4016 for (auto transceiver : transceivers_) {
4017 for (auto sender : transceiver->internal()->senders()) {
4018 if (sender->id() == sender_id) {
4019 return sender;
4020 }
4021 }
4022 }
4023 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07004024}
4025
Steve Anton4171afb2017-11-20 10:20:22 -08004026rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
4027PeerConnection::FindReceiverById(const std::string& receiver_id) const {
4028 for (auto transceiver : transceivers_) {
4029 for (auto receiver : transceiver->internal()->receivers()) {
4030 if (receiver->id() == receiver_id) {
4031 return receiver;
4032 }
4033 }
4034 }
4035 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07004036}
4037
Steve Anton4171afb2017-11-20 10:20:22 -08004038std::vector<PeerConnection::RtpSenderInfo>*
4039PeerConnection::GetRemoteSenderInfos(cricket::MediaType media_type) {
4040 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
4041 media_type == cricket::MEDIA_TYPE_VIDEO);
4042 return (media_type == cricket::MEDIA_TYPE_AUDIO)
4043 ? &remote_audio_sender_infos_
4044 : &remote_video_sender_infos_;
4045}
4046
4047std::vector<PeerConnection::RtpSenderInfo>* PeerConnection::GetLocalSenderInfos(
deadbeefab9b2d12015-10-14 11:33:11 -07004048 cricket::MediaType media_type) {
4049 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
4050 media_type == cricket::MEDIA_TYPE_VIDEO);
Steve Anton4171afb2017-11-20 10:20:22 -08004051 return (media_type == cricket::MEDIA_TYPE_AUDIO) ? &local_audio_sender_infos_
4052 : &local_video_sender_infos_;
deadbeefab9b2d12015-10-14 11:33:11 -07004053}
4054
Steve Anton4171afb2017-11-20 10:20:22 -08004055const PeerConnection::RtpSenderInfo* PeerConnection::FindSenderInfo(
4056 const std::vector<PeerConnection::RtpSenderInfo>& infos,
deadbeefab9b2d12015-10-14 11:33:11 -07004057 const std::string& stream_label,
Steve Anton4171afb2017-11-20 10:20:22 -08004058 const std::string sender_id) const {
4059 for (const RtpSenderInfo& sender_info : infos) {
4060 if (sender_info.stream_label == stream_label &&
4061 sender_info.sender_id == sender_id) {
4062 return &sender_info;
deadbeefab9b2d12015-10-14 11:33:11 -07004063 }
4064 }
4065 return nullptr;
4066}
4067
4068DataChannel* PeerConnection::FindDataChannelBySid(int sid) const {
4069 for (const auto& channel : sctp_data_channels_) {
4070 if (channel->id() == sid) {
4071 return channel;
4072 }
4073 }
4074 return nullptr;
4075}
4076
deadbeef91dd5672016-05-18 16:55:30 -07004077bool PeerConnection::InitializePortAllocator_n(
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004078 const RTCConfiguration& configuration) {
4079 cricket::ServerAddresses stun_servers;
4080 std::vector<cricket::RelayServerConfig> turn_servers;
deadbeef293e9262017-01-11 12:28:30 -08004081 if (ParseIceServers(configuration.servers, &stun_servers, &turn_servers) !=
4082 RTCErrorType::NONE) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004083 return false;
4084 }
4085
Taylor Brandstetterf8e65772016-06-27 17:20:15 -07004086 port_allocator_->Initialize();
4087
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004088 // To handle both internal and externally created port allocator, we will
4089 // enable BUNDLE here.
4090 int portallocator_flags = port_allocator_->flags();
4091 portallocator_flags |= cricket::PORTALLOCATOR_ENABLE_SHARED_SOCKET |
zhihuangb09b3f92017-03-07 14:40:51 -08004092 cricket::PORTALLOCATOR_ENABLE_IPV6 |
4093 cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI;
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004094 // If the disable-IPv6 flag was specified, we'll not override it
4095 // by experiment.
4096 if (configuration.disable_ipv6) {
4097 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
sprangc1b57a12017-02-28 08:50:47 -08004098 } else if (webrtc::field_trial::FindFullName("WebRTC-IPv6Default")
4099 .find("Disabled") == 0) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004100 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
4101 }
4102
zhihuangb09b3f92017-03-07 14:40:51 -08004103 if (configuration.disable_ipv6_on_wifi) {
4104 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI);
Mirko Bonadei675513b2017-11-09 11:09:25 +01004105 RTC_LOG(LS_INFO) << "IPv6 candidates on Wi-Fi are disabled.";
zhihuangb09b3f92017-03-07 14:40:51 -08004106 }
4107
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004108 if (configuration.tcp_candidate_policy == kTcpCandidatePolicyDisabled) {
4109 portallocator_flags |= cricket::PORTALLOCATOR_DISABLE_TCP;
Mirko Bonadei675513b2017-11-09 11:09:25 +01004110 RTC_LOG(LS_INFO) << "TCP candidates are disabled.";
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004111 }
4112
honghaiz60347052016-05-31 18:29:12 -07004113 if (configuration.candidate_network_policy ==
4114 kCandidateNetworkPolicyLowCost) {
4115 portallocator_flags |= cricket::PORTALLOCATOR_DISABLE_COSTLY_NETWORKS;
Mirko Bonadei675513b2017-11-09 11:09:25 +01004116 RTC_LOG(LS_INFO) << "Do not gather candidates on high-cost networks";
honghaiz60347052016-05-31 18:29:12 -07004117 }
4118
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004119 port_allocator_->set_flags(portallocator_flags);
4120 // No step delay is used while allocating ports.
4121 port_allocator_->set_step_delay(cricket::kMinimumStepDelay);
4122 port_allocator_->set_candidate_filter(
4123 ConvertIceTransportTypeToCandidateFilter(configuration.type));
deadbeefd21eab32017-07-26 16:50:11 -07004124 port_allocator_->set_max_ipv6_networks(configuration.max_ipv6_networks);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004125
4126 // Call this last since it may create pooled allocator sessions using the
4127 // properties set above.
4128 port_allocator_->SetConfiguration(stun_servers, turn_servers,
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -07004129 configuration.ice_candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02004130 configuration.prune_turn_ports,
4131 configuration.turn_customizer);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004132 return true;
4133}
4134
deadbeef91dd5672016-05-18 16:55:30 -07004135bool PeerConnection::ReconfigurePortAllocator_n(
deadbeef293e9262017-01-11 12:28:30 -08004136 const cricket::ServerAddresses& stun_servers,
4137 const std::vector<cricket::RelayServerConfig>& turn_servers,
4138 IceTransportsType type,
4139 int candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02004140 bool prune_turn_ports,
4141 webrtc::TurnCustomizer* turn_customizer) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004142 port_allocator_->set_candidate_filter(
deadbeef293e9262017-01-11 12:28:30 -08004143 ConvertIceTransportTypeToCandidateFilter(type));
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004144 // Call this last since it may create pooled allocator sessions using the
4145 // candidate filter set above.
deadbeef6de92f92016-12-12 18:49:32 -08004146 return port_allocator_->SetConfiguration(
Jonas Orelandbdcee282017-10-10 14:01:40 +02004147 stun_servers, turn_servers, candidate_pool_size, prune_turn_ports,
4148 turn_customizer);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004149}
4150
Steve Antonba818672017-11-06 10:21:57 -08004151cricket::ChannelManager* PeerConnection::channel_manager() const {
4152 return factory_->channel_manager();
4153}
4154
4155MetricsObserverInterface* PeerConnection::metrics_observer() const {
4156 return uma_observer_;
4157}
4158
Elad Alon99c3fe52017-10-13 16:29:40 +02004159bool PeerConnection::StartRtcEventLog_w(
Bjorn Tereliusde939432017-11-20 17:38:14 +01004160 std::unique_ptr<RtcEventLogOutput> output,
4161 int64_t output_period_ms) {
zhihuang77985012017-02-07 15:45:16 -08004162 if (!event_log_) {
4163 return false;
4164 }
Bjorn Tereliusde939432017-11-20 17:38:14 +01004165 return event_log_->StartLogging(std::move(output), output_period_ms);
ivoc14d5dbe2016-07-04 07:06:55 -07004166}
4167
4168void PeerConnection::StopRtcEventLog_w() {
zhihuang77985012017-02-07 15:45:16 -08004169 if (event_log_) {
4170 event_log_->StopLogging();
4171 }
ivoc14d5dbe2016-07-04 07:06:55 -07004172}
nisseeaabdf62017-05-05 02:23:02 -07004173
Steve Anton75737c02017-11-06 10:37:17 -08004174cricket::BaseChannel* PeerConnection::GetChannel(
4175 const std::string& content_name) {
Steve Antondcc3c022017-12-22 16:02:54 -08004176 for (auto transceiver : transceivers_) {
4177 cricket::BaseChannel* channel = transceiver->internal()->channel();
4178 if (channel && channel->content_name() == content_name) {
4179 return channel;
4180 }
Steve Anton75737c02017-11-06 10:37:17 -08004181 }
4182 if (rtp_data_channel() &&
4183 rtp_data_channel()->content_name() == content_name) {
4184 return rtp_data_channel();
4185 }
4186 return nullptr;
4187}
4188
4189bool PeerConnection::GetSctpSslRole(rtc::SSLRole* role) {
4190 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004191 RTC_LOG(LS_INFO)
4192 << "Local and Remote descriptions must be applied to get the "
4193 << "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08004194 return false;
4195 }
4196 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004197 RTC_LOG(LS_INFO) << "Non-rejected SCTP m= section is needed to get the "
4198 << "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08004199 return false;
4200 }
4201
4202 return transport_controller_->GetSslRole(*sctp_transport_name_, role);
4203}
4204
4205bool PeerConnection::GetSslRole(const std::string& content_name,
4206 rtc::SSLRole* role) {
4207 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004208 RTC_LOG(LS_INFO)
4209 << "Local and Remote descriptions must be applied to get the "
4210 << "SSL Role of the session.";
Steve Anton75737c02017-11-06 10:37:17 -08004211 return false;
4212 }
4213
4214 return transport_controller_->GetSslRole(GetTransportName(content_name),
4215 role);
4216}
4217
Steve Anton75737c02017-11-06 10:37:17 -08004218// TODO(steveanton): Eventually it'd be nice to store the channels as a single
4219// vector of BaseChannel pointers instead of separate voice and video channel
4220// vectors. At that point, this will become a simple getter.
4221std::vector<cricket::BaseChannel*> PeerConnection::Channels() const {
4222 std::vector<cricket::BaseChannel*> channels;
Steve Anton4171afb2017-11-20 10:20:22 -08004223 if (voice_channel()) {
4224 channels.push_back(voice_channel());
4225 }
4226 if (video_channel()) {
4227 channels.push_back(video_channel());
4228 }
Steve Anton75737c02017-11-06 10:37:17 -08004229 if (rtp_data_channel_) {
4230 channels.push_back(rtp_data_channel_);
4231 }
4232 return channels;
4233}
4234
Steve Antonf8470812017-12-04 10:46:21 -08004235void PeerConnection::SetSessionError(SessionError error,
4236 const std::string& error_desc) {
4237 RTC_DCHECK_RUN_ON(signaling_thread());
4238 if (error != session_error_) {
4239 session_error_ = error;
4240 session_error_desc_ = error_desc;
Steve Anton75737c02017-11-06 10:37:17 -08004241 }
4242}
4243
Steve Anton3828c062017-12-06 10:34:51 -08004244RTCError PeerConnection::UpdateSessionState(SdpType type,
Steve Anton8a006912017-12-04 15:25:56 -08004245 cricket::ContentSource source) {
4246 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08004247
4248 // If there's already a pending error then no state transition should happen.
4249 // But all call-sites should be verifying this before calling us!
Steve Antonf8470812017-12-04 10:46:21 -08004250 RTC_DCHECK(session_error() == SessionError::kNone);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004251
4252 // If this is an answer then we know whether to BUNDLE or not. If both the
4253 // local and remote side have agreed to BUNDLE, go ahead and enable it.
Steve Anton3828c062017-12-06 10:34:51 -08004254 if (type == SdpType::kAnswer) {
Steve Anton75737c02017-11-06 10:37:17 -08004255 const cricket::ContentGroup* local_bundle =
4256 local_description()->description()->GetGroupByName(
4257 cricket::GROUP_TYPE_BUNDLE);
4258 const cricket::ContentGroup* remote_bundle =
4259 remote_description()->description()->GetGroupByName(
4260 cricket::GROUP_TYPE_BUNDLE);
4261 if (local_bundle && remote_bundle) {
4262 // The answerer decides the transport to bundle on.
4263 const cricket::ContentGroup* answer_bundle =
4264 (source == cricket::CS_LOCAL ? local_bundle : remote_bundle);
4265 if (!EnableBundle(*answer_bundle)) {
Steve Anton8a006912017-12-04 15:25:56 -08004266 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
4267 kEnableBundleFailed);
Steve Anton75737c02017-11-06 10:37:17 -08004268 }
4269 }
Steve Anton75737c02017-11-06 10:37:17 -08004270 }
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004271
4272 // Only push down the transport description after potentially enabling BUNDLE;
4273 // we don't want to push down a description on a transport about to be
4274 // destroyed.
Steve Anton3828c062017-12-06 10:34:51 -08004275 RTCError error = PushdownTransportDescription(source, type);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004276 if (!error.ok()) {
4277 return error;
4278 }
4279
4280 // If this is answer-ish we're ready to let media flow.
Steve Anton3828c062017-12-06 10:34:51 -08004281 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Antoned10bd92017-12-05 10:52:59 -08004282 EnableSending();
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004283 }
4284
4285 // Update the signaling state according to the specified state machine (see
4286 // https://w3c.github.io/webrtc-pc/#rtcsignalingstate-enum).
Steve Anton3828c062017-12-06 10:34:51 -08004287 if (type == SdpType::kOffer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004288 ChangeSignalingState(source == cricket::CS_LOCAL
4289 ? PeerConnectionInterface::kHaveLocalOffer
4290 : PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton3828c062017-12-06 10:34:51 -08004291 } else if (type == SdpType::kPrAnswer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004292 ChangeSignalingState(source == cricket::CS_LOCAL
4293 ? PeerConnectionInterface::kHaveLocalPrAnswer
4294 : PeerConnectionInterface::kHaveRemotePrAnswer);
4295 } else {
Steve Anton3828c062017-12-06 10:34:51 -08004296 RTC_DCHECK(type == SdpType::kAnswer);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004297 ChangeSignalingState(PeerConnectionInterface::kStable);
4298 }
4299
4300 // Update internal objects according to the session description's media
4301 // descriptions.
Steve Anton3828c062017-12-06 10:34:51 -08004302 error = PushdownMediaDescription(type, source);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004303 if (!error.ok()) {
4304 SetSessionError(SessionError::kContent, error.message());
4305 }
4306 if (session_error() != SessionError::kNone) {
4307 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
4308 }
4309
Steve Anton8a006912017-12-04 15:25:56 -08004310 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08004311}
4312
Steve Anton8a006912017-12-04 15:25:56 -08004313RTCError PeerConnection::PushdownMediaDescription(
Steve Anton3828c062017-12-06 10:34:51 -08004314 SdpType type,
Steve Anton8a006912017-12-04 15:25:56 -08004315 cricket::ContentSource source) {
Steve Antoned10bd92017-12-05 10:52:59 -08004316 const SessionDescriptionInterface* sdesc =
4317 (source == cricket::CS_LOCAL ? local_description()
4318 : remote_description());
Steve Anton75737c02017-11-06 10:37:17 -08004319 RTC_DCHECK(sdesc);
Steve Antoned10bd92017-12-05 10:52:59 -08004320
4321 // Push down the new SDP media section for each audio/video transceiver.
4322 for (auto transceiver : transceivers_) {
Steve Anton75737c02017-11-06 10:37:17 -08004323 const ContentInfo* content_info =
Steve Antoned10bd92017-12-05 10:52:59 -08004324 FindMediaSectionForTransceiver(transceiver, sdesc);
4325 cricket::BaseChannel* channel = transceiver->internal()->channel();
4326 if (!channel || !content_info || content_info->rejected) {
Steve Anton75737c02017-11-06 10:37:17 -08004327 continue;
4328 }
4329 const MediaContentDescription* content_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08004330 content_info->media_description();
Steve Antoned10bd92017-12-05 10:52:59 -08004331 if (!content_desc) {
4332 continue;
4333 }
4334 std::string error;
4335 bool success =
4336 (source == cricket::CS_LOCAL)
Steve Anton3828c062017-12-06 10:34:51 -08004337 ? channel->SetLocalContent(content_desc, type, &error)
4338 : channel->SetRemoteContent(content_desc, type, &error);
Steve Antoned10bd92017-12-05 10:52:59 -08004339 if (!success) {
4340 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, std::move(error));
4341 }
4342 }
4343
4344 // If using the RtpDataChannel, push down the new SDP section for it too.
4345 if (rtp_data_channel_) {
4346 const ContentInfo* data_content =
4347 cricket::GetFirstDataContent(sdesc->description());
4348 if (data_content && !data_content->rejected) {
4349 const MediaContentDescription* data_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08004350 data_content->media_description();
Steve Antoned10bd92017-12-05 10:52:59 -08004351 if (data_desc) {
4352 std::string error;
4353 bool success =
4354 (source == cricket::CS_LOCAL)
Steve Anton3828c062017-12-06 10:34:51 -08004355 ? rtp_data_channel_->SetLocalContent(data_desc, type, &error)
4356 : rtp_data_channel_->SetRemoteContent(data_desc, type,
Steve Antoned10bd92017-12-05 10:52:59 -08004357 &error);
4358 if (!success) {
4359 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
4360 std::move(error));
4361 }
Steve Anton75737c02017-11-06 10:37:17 -08004362 }
4363 }
4364 }
Steve Antoned10bd92017-12-05 10:52:59 -08004365
Steve Anton75737c02017-11-06 10:37:17 -08004366 // Need complete offer/answer with an SCTP m= section before starting SCTP,
4367 // according to https://tools.ietf.org/html/draft-ietf-mmusic-sctp-sdp-19
4368 if (sctp_transport_ && local_description() && remote_description() &&
4369 cricket::GetFirstDataContent(local_description()->description()) &&
4370 cricket::GetFirstDataContent(remote_description()->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08004371 bool success = network_thread()->Invoke<bool>(
Steve Anton75737c02017-11-06 10:37:17 -08004372 RTC_FROM_HERE,
4373 rtc::Bind(&PeerConnection::PushdownSctpParameters_n, this, source));
Steve Anton8a006912017-12-04 15:25:56 -08004374 if (!success) {
4375 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
4376 "Failed to push down SCTP parameters.");
4377 }
Steve Anton75737c02017-11-06 10:37:17 -08004378 }
Steve Antoned10bd92017-12-05 10:52:59 -08004379
Steve Anton8a006912017-12-04 15:25:56 -08004380 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08004381}
4382
4383bool PeerConnection::PushdownSctpParameters_n(cricket::ContentSource source) {
4384 RTC_DCHECK(network_thread()->IsCurrent());
4385 RTC_DCHECK(local_description());
4386 RTC_DCHECK(remote_description());
4387 // Apply the SCTP port (which is hidden inside a DataCodec structure...)
4388 // When we support "max-message-size", that would also be pushed down here.
4389 return sctp_transport_->Start(
4390 GetSctpPort(local_description()->description()),
4391 GetSctpPort(remote_description()->description()));
4392}
4393
Steve Anton8a006912017-12-04 15:25:56 -08004394RTCError PeerConnection::PushdownTransportDescription(
4395 cricket::ContentSource source,
Steve Anton3828c062017-12-06 10:34:51 -08004396 SdpType type) {
Steve Anton8a006912017-12-04 15:25:56 -08004397 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08004398
Steve Anton8a006912017-12-04 15:25:56 -08004399 const SessionDescriptionInterface* sdesc =
4400 (source == cricket::CS_LOCAL ? local_description()
4401 : remote_description());
4402 RTC_DCHECK(sdesc);
4403 for (const cricket::TransportInfo& tinfo :
4404 sdesc->description()->transport_infos()) {
4405 std::string error;
4406 bool success;
4407 if (source == cricket::CS_LOCAL) {
4408 success = transport_controller_->SetLocalTransportDescription(
Steve Anton3828c062017-12-06 10:34:51 -08004409 tinfo.content_name, tinfo.description, type, &error);
Steve Anton8a006912017-12-04 15:25:56 -08004410 } else {
4411 success = transport_controller_->SetRemoteTransportDescription(
Steve Anton3828c062017-12-06 10:34:51 -08004412 tinfo.content_name, tinfo.description, type, &error);
Steve Anton8a006912017-12-04 15:25:56 -08004413 }
4414 if (!success) {
Steve Antondcc3c022017-12-22 16:02:54 -08004415 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
4416 "Failed to push down transport description for " +
4417 tinfo.content_name + ": " + error);
Steve Anton75737c02017-11-06 10:37:17 -08004418 }
4419 }
4420
Steve Anton8a006912017-12-04 15:25:56 -08004421 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08004422}
4423
4424bool PeerConnection::GetTransportDescription(
4425 const SessionDescription* description,
4426 const std::string& content_name,
4427 cricket::TransportDescription* tdesc) {
4428 if (!description || !tdesc) {
4429 return false;
4430 }
4431 const TransportInfo* transport_info =
4432 description->GetTransportInfoByName(content_name);
4433 if (!transport_info) {
4434 return false;
4435 }
4436 *tdesc = transport_info->description;
4437 return true;
4438}
4439
4440bool PeerConnection::EnableBundle(const cricket::ContentGroup& bundle) {
4441 const std::string* first_content_name = bundle.FirstContentName();
4442 if (!first_content_name) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004443 RTC_LOG(LS_WARNING) << "Tried to BUNDLE with no contents.";
Steve Anton75737c02017-11-06 10:37:17 -08004444 return false;
4445 }
4446 const std::string& transport_name = *first_content_name;
4447
4448 auto maybe_set_transport = [this, bundle,
4449 transport_name](cricket::BaseChannel* ch) {
4450 if (!ch || !bundle.HasContentName(ch->content_name())) {
Steve Antoned10bd92017-12-05 10:52:59 -08004451 return;
Steve Anton75737c02017-11-06 10:37:17 -08004452 }
4453
4454 std::string old_transport_name = ch->transport_name();
4455 if (old_transport_name == transport_name) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004456 RTC_LOG(LS_INFO) << "BUNDLE already enabled for " << ch->content_name()
4457 << " on " << transport_name << ".";
Steve Antoned10bd92017-12-05 10:52:59 -08004458 return;
Steve Anton75737c02017-11-06 10:37:17 -08004459 }
4460
4461 cricket::DtlsTransportInternal* rtp_dtls_transport =
4462 transport_controller_->CreateDtlsTransport(
4463 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4464 bool need_rtcp = (ch->rtcp_dtls_transport() != nullptr);
4465 cricket::DtlsTransportInternal* rtcp_dtls_transport = nullptr;
4466 if (need_rtcp) {
4467 rtcp_dtls_transport = transport_controller_->CreateDtlsTransport(
4468 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
4469 }
4470
4471 ch->SetTransports(rtp_dtls_transport, rtcp_dtls_transport);
Mirko Bonadei675513b2017-11-09 11:09:25 +01004472 RTC_LOG(LS_INFO) << "Enabled BUNDLE for " << ch->content_name() << " on "
4473 << transport_name << ".";
Steve Anton75737c02017-11-06 10:37:17 -08004474 transport_controller_->DestroyDtlsTransport(
4475 old_transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4476 // If the channel needs rtcp, it means that the channel used to have a
4477 // rtcp transport which needs to be deleted now.
4478 if (need_rtcp) {
4479 transport_controller_->DestroyDtlsTransport(
4480 old_transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
4481 }
Steve Anton75737c02017-11-06 10:37:17 -08004482 };
4483
Steve Antoned10bd92017-12-05 10:52:59 -08004484 for (auto transceiver : transceivers_) {
4485 maybe_set_transport(transceiver->internal()->channel());
Steve Anton75737c02017-11-06 10:37:17 -08004486 }
Steve Antoned10bd92017-12-05 10:52:59 -08004487 maybe_set_transport(rtp_data_channel_);
4488
Steve Anton75737c02017-11-06 10:37:17 -08004489 // For SCTP, transport creation/deletion happens here instead of in the
4490 // object itself.
4491 if (sctp_transport_) {
4492 RTC_DCHECK(sctp_transport_name_);
4493 RTC_DCHECK(sctp_content_name_);
4494 if (transport_name != *sctp_transport_name_ &&
4495 bundle.HasContentName(*sctp_content_name_)) {
4496 network_thread()->Invoke<void>(
4497 RTC_FROM_HERE, rtc::Bind(&PeerConnection::ChangeSctpTransport_n, this,
4498 transport_name));
4499 }
4500 }
4501
4502 return true;
4503}
4504
Steve Anton75737c02017-11-06 10:37:17 -08004505cricket::IceConfig PeerConnection::ParseIceConfig(
4506 const PeerConnectionInterface::RTCConfiguration& config) const {
4507 cricket::ContinualGatheringPolicy gathering_policy;
4508 // TODO(honghaiz): Add the third continual gathering policy in
4509 // PeerConnectionInterface and map it to GATHER_CONTINUALLY_AND_RECOVER.
4510 switch (config.continual_gathering_policy) {
4511 case PeerConnectionInterface::GATHER_ONCE:
4512 gathering_policy = cricket::GATHER_ONCE;
4513 break;
4514 case PeerConnectionInterface::GATHER_CONTINUALLY:
4515 gathering_policy = cricket::GATHER_CONTINUALLY;
4516 break;
4517 default:
4518 RTC_NOTREACHED();
4519 gathering_policy = cricket::GATHER_ONCE;
4520 }
4521 cricket::IceConfig ice_config;
4522 ice_config.receiving_timeout = config.ice_connection_receiving_timeout;
4523 ice_config.prioritize_most_likely_candidate_pairs =
4524 config.prioritize_most_likely_ice_candidate_pairs;
4525 ice_config.backup_connection_ping_interval =
4526 config.ice_backup_candidate_pair_ping_interval;
4527 ice_config.continual_gathering_policy = gathering_policy;
4528 ice_config.presume_writable_when_fully_relayed =
4529 config.presume_writable_when_fully_relayed;
4530 ice_config.ice_check_min_interval = config.ice_check_min_interval;
4531 ice_config.regather_all_networks_interval_range =
4532 config.ice_regather_interval_range;
4533 return ice_config;
4534}
4535
Steve Anton75737c02017-11-06 10:37:17 -08004536bool PeerConnection::GetLocalTrackIdBySsrc(uint32_t ssrc,
4537 std::string* track_id) {
4538 if (!local_description()) {
4539 return false;
4540 }
4541 return webrtc::GetTrackIdBySsrc(local_description()->description(), ssrc,
4542 track_id);
4543}
4544
4545bool PeerConnection::GetRemoteTrackIdBySsrc(uint32_t ssrc,
4546 std::string* track_id) {
4547 if (!remote_description()) {
4548 return false;
4549 }
4550 return webrtc::GetTrackIdBySsrc(remote_description()->description(), ssrc,
4551 track_id);
4552}
4553
4554bool PeerConnection::SendData(const cricket::SendDataParams& params,
4555 const rtc::CopyOnWriteBuffer& payload,
4556 cricket::SendDataResult* result) {
4557 if (!rtp_data_channel_ && !sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004558 RTC_LOG(LS_ERROR) << "SendData called when rtp_data_channel_ "
4559 << "and sctp_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08004560 return false;
4561 }
4562 return rtp_data_channel_
4563 ? rtp_data_channel_->SendData(params, payload, result)
4564 : network_thread()->Invoke<bool>(
4565 RTC_FROM_HERE,
4566 Bind(&cricket::SctpTransportInternal::SendData,
4567 sctp_transport_.get(), params, payload, result));
4568}
4569
4570bool PeerConnection::ConnectDataChannel(DataChannel* webrtc_data_channel) {
4571 if (!rtp_data_channel_ && !sctp_transport_) {
4572 // Don't log an error here, because DataChannels are expected to call
4573 // ConnectDataChannel in this state. It's the only way to initially tell
4574 // whether or not the underlying transport is ready.
4575 return false;
4576 }
4577 if (rtp_data_channel_) {
4578 rtp_data_channel_->SignalReadyToSendData.connect(
4579 webrtc_data_channel, &DataChannel::OnChannelReady);
4580 rtp_data_channel_->SignalDataReceived.connect(webrtc_data_channel,
4581 &DataChannel::OnDataReceived);
4582 } else {
4583 SignalSctpReadyToSendData.connect(webrtc_data_channel,
4584 &DataChannel::OnChannelReady);
4585 SignalSctpDataReceived.connect(webrtc_data_channel,
4586 &DataChannel::OnDataReceived);
4587 SignalSctpStreamClosedRemotely.connect(
4588 webrtc_data_channel, &DataChannel::OnStreamClosedRemotely);
4589 }
4590 return true;
4591}
4592
4593void PeerConnection::DisconnectDataChannel(DataChannel* webrtc_data_channel) {
4594 if (!rtp_data_channel_ && !sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004595 RTC_LOG(LS_ERROR)
4596 << "DisconnectDataChannel called when rtp_data_channel_ and "
4597 "sctp_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08004598 return;
4599 }
4600 if (rtp_data_channel_) {
4601 rtp_data_channel_->SignalReadyToSendData.disconnect(webrtc_data_channel);
4602 rtp_data_channel_->SignalDataReceived.disconnect(webrtc_data_channel);
4603 } else {
4604 SignalSctpReadyToSendData.disconnect(webrtc_data_channel);
4605 SignalSctpDataReceived.disconnect(webrtc_data_channel);
4606 SignalSctpStreamClosedRemotely.disconnect(webrtc_data_channel);
4607 }
4608}
4609
4610void PeerConnection::AddSctpDataStream(int sid) {
4611 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004612 RTC_LOG(LS_ERROR)
4613 << "AddSctpDataStream called when sctp_transport_ is NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08004614 return;
4615 }
4616 network_thread()->Invoke<void>(
4617 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::OpenStream,
4618 sctp_transport_.get(), sid));
4619}
4620
4621void PeerConnection::RemoveSctpDataStream(int sid) {
4622 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004623 RTC_LOG(LS_ERROR) << "RemoveSctpDataStream called when sctp_transport_ is "
4624 << "NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08004625 return;
4626 }
4627 network_thread()->Invoke<void>(
4628 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::ResetStream,
4629 sctp_transport_.get(), sid));
4630}
4631
4632bool PeerConnection::ReadyToSendData() const {
4633 return (rtp_data_channel_ && rtp_data_channel_->ready_to_send_data()) ||
4634 sctp_ready_to_send_data_;
4635}
4636
4637std::unique_ptr<SessionStats> PeerConnection::GetSessionStats_s() {
4638 RTC_DCHECK(signaling_thread()->IsCurrent());
4639 ChannelNamePairs channel_name_pairs;
4640 if (voice_channel()) {
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004641 channel_name_pairs.voice = ChannelNamePair(
4642 voice_channel()->content_name(), voice_channel()->transport_name());
Steve Anton75737c02017-11-06 10:37:17 -08004643 }
4644 if (video_channel()) {
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004645 channel_name_pairs.video = ChannelNamePair(
4646 video_channel()->content_name(), video_channel()->transport_name());
Steve Anton75737c02017-11-06 10:37:17 -08004647 }
4648 if (rtp_data_channel()) {
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004649 channel_name_pairs.data =
Steve Anton75737c02017-11-06 10:37:17 -08004650 ChannelNamePair(rtp_data_channel()->content_name(),
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004651 rtp_data_channel()->transport_name());
Steve Anton75737c02017-11-06 10:37:17 -08004652 }
4653 if (sctp_transport_) {
4654 RTC_DCHECK(sctp_content_name_);
4655 RTC_DCHECK(sctp_transport_name_);
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004656 channel_name_pairs.data =
4657 ChannelNamePair(*sctp_content_name_, *sctp_transport_name_);
Steve Anton75737c02017-11-06 10:37:17 -08004658 }
4659 return GetSessionStats(channel_name_pairs);
4660}
4661
4662std::unique_ptr<SessionStats> PeerConnection::GetSessionStats(
4663 const ChannelNamePairs& channel_name_pairs) {
4664 if (network_thread()->IsCurrent()) {
4665 return GetSessionStats_n(channel_name_pairs);
4666 }
4667 return network_thread()->Invoke<std::unique_ptr<SessionStats>>(
4668 RTC_FROM_HERE,
4669 rtc::Bind(&PeerConnection::GetSessionStats_n, this, channel_name_pairs));
4670}
4671
4672bool PeerConnection::GetLocalCertificate(
4673 const std::string& transport_name,
4674 rtc::scoped_refptr<rtc::RTCCertificate>* certificate) {
4675 return transport_controller_->GetLocalCertificate(transport_name,
4676 certificate);
4677}
4678
4679std::unique_ptr<rtc::SSLCertificate> PeerConnection::GetRemoteSSLCertificate(
4680 const std::string& transport_name) {
4681 return transport_controller_->GetRemoteSSLCertificate(transport_name);
4682}
4683
4684cricket::DataChannelType PeerConnection::data_channel_type() const {
4685 return data_channel_type_;
4686}
4687
4688bool PeerConnection::IceRestartPending(const std::string& content_name) const {
4689 return pending_ice_restarts_.find(content_name) !=
4690 pending_ice_restarts_.end();
4691}
4692
Steve Anton75737c02017-11-06 10:37:17 -08004693bool PeerConnection::NeedsIceRestart(const std::string& content_name) const {
4694 return transport_controller_->NeedsIceRestart(content_name);
4695}
4696
4697void PeerConnection::OnCertificateReady(
4698 const rtc::scoped_refptr<rtc::RTCCertificate>& certificate) {
4699 transport_controller_->SetLocalCertificate(certificate);
4700}
4701
4702void PeerConnection::OnDtlsSrtpSetupFailure(cricket::BaseChannel*, bool rtcp) {
Steve Antonf8470812017-12-04 10:46:21 -08004703 SetSessionError(SessionError::kTransport,
4704 rtcp ? kDtlsSrtpSetupFailureRtcp : kDtlsSrtpSetupFailureRtp);
Steve Anton75737c02017-11-06 10:37:17 -08004705}
4706
4707void PeerConnection::OnTransportControllerConnectionState(
4708 cricket::IceConnectionState state) {
4709 switch (state) {
4710 case cricket::kIceConnectionConnecting:
4711 // If the current state is Connected or Completed, then there were
4712 // writable channels but now there are not, so the next state must
4713 // be Disconnected.
4714 // kIceConnectionConnecting is currently used as the default,
4715 // un-connected state by the TransportController, so its only use is
4716 // detecting disconnections.
4717 if (ice_connection_state_ ==
4718 PeerConnectionInterface::kIceConnectionConnected ||
4719 ice_connection_state_ ==
4720 PeerConnectionInterface::kIceConnectionCompleted) {
4721 SetIceConnectionState(
4722 PeerConnectionInterface::kIceConnectionDisconnected);
4723 }
4724 break;
4725 case cricket::kIceConnectionFailed:
4726 SetIceConnectionState(PeerConnectionInterface::kIceConnectionFailed);
4727 break;
4728 case cricket::kIceConnectionConnected:
Mirko Bonadei675513b2017-11-09 11:09:25 +01004729 RTC_LOG(LS_INFO) << "Changing to ICE connected state because "
4730 << "all transports are writable.";
Steve Anton75737c02017-11-06 10:37:17 -08004731 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
4732 break;
4733 case cricket::kIceConnectionCompleted:
Mirko Bonadei675513b2017-11-09 11:09:25 +01004734 RTC_LOG(LS_INFO) << "Changing to ICE completed state because "
4735 << "all transports are complete.";
Steve Anton75737c02017-11-06 10:37:17 -08004736 if (ice_connection_state_ !=
4737 PeerConnectionInterface::kIceConnectionConnected) {
4738 // If jumping directly from "checking" to "connected",
4739 // signal "connected" first.
4740 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
4741 }
4742 SetIceConnectionState(PeerConnectionInterface::kIceConnectionCompleted);
4743 if (metrics_observer()) {
4744 ReportTransportStats();
4745 }
4746 break;
4747 default:
4748 RTC_NOTREACHED();
4749 }
4750}
4751
4752void PeerConnection::OnTransportControllerCandidatesGathered(
4753 const std::string& transport_name,
4754 const cricket::Candidates& candidates) {
4755 RTC_DCHECK(signaling_thread()->IsCurrent());
4756 int sdp_mline_index;
4757 if (!GetLocalCandidateMediaIndex(transport_name, &sdp_mline_index)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004758 RTC_LOG(LS_ERROR)
4759 << "OnTransportControllerCandidatesGathered: content name "
4760 << transport_name << " not found";
Steve Anton75737c02017-11-06 10:37:17 -08004761 return;
4762 }
4763
4764 for (cricket::Candidates::const_iterator citer = candidates.begin();
4765 citer != candidates.end(); ++citer) {
4766 // Use transport_name as the candidate media id.
4767 std::unique_ptr<JsepIceCandidate> candidate(
4768 new JsepIceCandidate(transport_name, sdp_mline_index, *citer));
4769 if (local_description()) {
4770 mutable_local_description()->AddCandidate(candidate.get());
4771 }
4772 OnIceCandidate(std::move(candidate));
4773 }
4774}
4775
4776void PeerConnection::OnTransportControllerCandidatesRemoved(
4777 const std::vector<cricket::Candidate>& candidates) {
4778 RTC_DCHECK(signaling_thread()->IsCurrent());
4779 // Sanity check.
4780 for (const cricket::Candidate& candidate : candidates) {
4781 if (candidate.transport_name().empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004782 RTC_LOG(LS_ERROR) << "OnTransportControllerCandidatesRemoved: "
4783 << "empty content name in candidate "
4784 << candidate.ToString();
Steve Anton75737c02017-11-06 10:37:17 -08004785 return;
4786 }
4787 }
4788
4789 if (local_description()) {
4790 mutable_local_description()->RemoveCandidates(candidates);
4791 }
4792 OnIceCandidatesRemoved(candidates);
4793}
4794
4795void PeerConnection::OnTransportControllerDtlsHandshakeError(
4796 rtc::SSLHandshakeError error) {
4797 if (metrics_observer()) {
4798 metrics_observer()->IncrementEnumCounter(
4799 webrtc::kEnumCounterDtlsHandshakeError, static_cast<int>(error),
4800 static_cast<int>(rtc::SSLHandshakeError::MAX_VALUE));
4801 }
4802}
4803
Steve Antoned10bd92017-12-05 10:52:59 -08004804void PeerConnection::EnableSending() {
4805 for (auto transceiver : transceivers_) {
4806 cricket::BaseChannel* channel = transceiver->internal()->channel();
4807 if (channel && !channel->enabled()) {
4808 channel->Enable(true);
4809 }
Steve Anton75737c02017-11-06 10:37:17 -08004810 }
4811
Steve Anton4171afb2017-11-20 10:20:22 -08004812 if (rtp_data_channel_ && !rtp_data_channel_->enabled()) {
Steve Anton75737c02017-11-06 10:37:17 -08004813 rtp_data_channel_->Enable(true);
Steve Anton4171afb2017-11-20 10:20:22 -08004814 }
Steve Anton75737c02017-11-06 10:37:17 -08004815}
4816
4817// Returns the media index for a local ice candidate given the content name.
4818bool PeerConnection::GetLocalCandidateMediaIndex(
4819 const std::string& content_name,
4820 int* sdp_mline_index) {
4821 if (!local_description() || !sdp_mline_index) {
4822 return false;
4823 }
4824
4825 bool content_found = false;
4826 const ContentInfos& contents = local_description()->description()->contents();
4827 for (size_t index = 0; index < contents.size(); ++index) {
4828 if (contents[index].name == content_name) {
4829 *sdp_mline_index = static_cast<int>(index);
4830 content_found = true;
4831 break;
4832 }
4833 }
4834 return content_found;
4835}
4836
4837bool PeerConnection::UseCandidatesInSessionDescription(
4838 const SessionDescriptionInterface* remote_desc) {
4839 if (!remote_desc) {
4840 return true;
4841 }
4842 bool ret = true;
4843
4844 for (size_t m = 0; m < remote_desc->number_of_mediasections(); ++m) {
4845 const IceCandidateCollection* candidates = remote_desc->candidates(m);
4846 for (size_t n = 0; n < candidates->count(); ++n) {
4847 const IceCandidateInterface* candidate = candidates->at(n);
4848 bool valid = false;
4849 if (!ReadyToUseRemoteCandidate(candidate, remote_desc, &valid)) {
4850 if (valid) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004851 RTC_LOG(LS_INFO)
4852 << "UseCandidatesInSessionDescription: Not ready to use "
4853 << "candidate.";
Steve Anton75737c02017-11-06 10:37:17 -08004854 }
4855 continue;
4856 }
4857 ret = UseCandidate(candidate);
4858 if (!ret) {
4859 break;
4860 }
4861 }
4862 }
4863 return ret;
4864}
4865
4866bool PeerConnection::UseCandidate(const IceCandidateInterface* candidate) {
4867 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
4868 size_t remote_content_size =
4869 remote_description()->description()->contents().size();
4870 if (mediacontent_index >= remote_content_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004871 RTC_LOG(LS_ERROR) << "UseCandidate: Invalid candidate media index.";
Steve Anton75737c02017-11-06 10:37:17 -08004872 return false;
4873 }
4874
4875 cricket::ContentInfo content =
4876 remote_description()->description()->contents()[mediacontent_index];
4877 std::vector<cricket::Candidate> candidates;
4878 candidates.push_back(candidate->candidate());
4879 // Invoking BaseSession method to handle remote candidates.
4880 std::string error;
4881 if (transport_controller_->AddRemoteCandidates(content.name, candidates,
4882 &error)) {
4883 // Candidates successfully submitted for checking.
4884 if (ice_connection_state_ == PeerConnectionInterface::kIceConnectionNew ||
4885 ice_connection_state_ ==
4886 PeerConnectionInterface::kIceConnectionDisconnected) {
4887 // If state is New, then the session has just gotten its first remote ICE
4888 // candidates, so go to Checking.
4889 // If state is Disconnected, the session is re-using old candidates or
4890 // receiving additional ones, so go to Checking.
4891 // If state is Connected, stay Connected.
4892 // TODO(bemasc): If state is Connected, and the new candidates are for a
4893 // newly added transport, then the state actually _should_ move to
4894 // checking. Add a way to distinguish that case.
4895 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
4896 }
4897 // TODO(bemasc): If state is Completed, go back to Connected.
4898 } else {
4899 if (!error.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004900 RTC_LOG(LS_WARNING) << error;
Steve Anton75737c02017-11-06 10:37:17 -08004901 }
4902 }
4903 return true;
4904}
4905
4906void PeerConnection::RemoveUnusedChannels(const SessionDescription* desc) {
Steve Anton75737c02017-11-06 10:37:17 -08004907 // Destroy video channel first since it may have a pointer to the
4908 // voice channel.
4909 const cricket::ContentInfo* video_info = cricket::GetFirstVideoContent(desc);
Steve Anton6fec8802017-12-04 10:37:29 -08004910 if (!video_info || video_info->rejected) {
4911 DestroyTransceiverChannel(GetVideoTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08004912 }
4913
Steve Anton6fec8802017-12-04 10:37:29 -08004914 const cricket::ContentInfo* audio_info = cricket::GetFirstAudioContent(desc);
4915 if (!audio_info || audio_info->rejected) {
4916 DestroyTransceiverChannel(GetAudioTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08004917 }
4918
4919 const cricket::ContentInfo* data_info = cricket::GetFirstDataContent(desc);
4920 if (!data_info || data_info->rejected) {
Steve Anton6fec8802017-12-04 10:37:29 -08004921 DestroyDataChannel();
Steve Anton75737c02017-11-06 10:37:17 -08004922 }
4923}
4924
Steve Antoneda6ccd2017-12-04 10:21:55 -08004925std::string PeerConnection::GetTransportNameForMediaSection(
4926 const std::string& mid,
4927 const cricket::ContentGroup* bundle_group) const {
4928 if (!bundle_group) {
4929 return mid;
Steve Anton75737c02017-11-06 10:37:17 -08004930 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08004931 const std::string* first_content_name = bundle_group->FirstContentName();
Steve Anton75737c02017-11-06 10:37:17 -08004932 if (!first_content_name) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004933 RTC_LOG(LS_WARNING) << "Tried to BUNDLE with no contents.";
Steve Antoneda6ccd2017-12-04 10:21:55 -08004934 return mid;
Steve Anton75737c02017-11-06 10:37:17 -08004935 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08004936 if (!bundle_group->HasContentName(mid)) {
4937 RTC_LOG(LS_WARNING) << mid << " is not part of any bundle group";
4938 return mid;
Steve Anton75737c02017-11-06 10:37:17 -08004939 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08004940 RTC_LOG(LS_INFO) << "Bundling " << mid << " on " << *first_content_name;
4941 return *first_content_name;
Steve Anton75737c02017-11-06 10:37:17 -08004942}
4943
Steve Antondcc3c022017-12-22 16:02:54 -08004944RTCErrorOr<const cricket::ContentGroup*> PeerConnection::GetEarlyBundleGroup(
4945 const SessionDescription& desc) const {
Steve Anton75737c02017-11-06 10:37:17 -08004946 const cricket::ContentGroup* bundle_group = nullptr;
4947 if (configuration_.bundle_policy ==
4948 PeerConnectionInterface::kBundlePolicyMaxBundle) {
Steve Antondcc3c022017-12-22 16:02:54 -08004949 bundle_group = desc.GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton75737c02017-11-06 10:37:17 -08004950 if (!bundle_group) {
Steve Anton8a006912017-12-04 15:25:56 -08004951 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
4952 "max-bundle configured but session description "
4953 "has no BUNDLE group");
Steve Anton75737c02017-11-06 10:37:17 -08004954 }
4955 }
Steve Antondcc3c022017-12-22 16:02:54 -08004956 return std::move(bundle_group);
4957}
4958
4959RTCError PeerConnection::CreateChannels(const SessionDescription& desc) {
4960 auto bundle_group_or_error = GetEarlyBundleGroup(desc);
4961 if (!bundle_group_or_error.ok()) {
4962 return bundle_group_or_error.MoveError();
4963 }
4964 const cricket::ContentGroup* bundle_group = bundle_group_or_error.MoveValue();
Steve Anton75737c02017-11-06 10:37:17 -08004965
Steve Antoneda6ccd2017-12-04 10:21:55 -08004966 // Creating the media channels and transport proxies.
Steve Antondcc3c022017-12-22 16:02:54 -08004967 const cricket::ContentInfo* voice = cricket::GetFirstAudioContent(&desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08004968 if (voice && !voice->rejected &&
4969 !GetAudioTransceiver()->internal()->channel()) {
4970 cricket::VoiceChannel* voice_channel = CreateVoiceChannel(
4971 voice->name,
4972 GetTransportNameForMediaSection(voice->name, bundle_group));
4973 if (!voice_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08004974 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
4975 "Failed to create voice channel.");
Steve Antoneda6ccd2017-12-04 10:21:55 -08004976 }
4977 GetAudioTransceiver()->internal()->SetChannel(voice_channel);
4978 }
4979
Steve Antondcc3c022017-12-22 16:02:54 -08004980 const cricket::ContentInfo* video = cricket::GetFirstVideoContent(&desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08004981 if (video && !video->rejected &&
4982 !GetVideoTransceiver()->internal()->channel()) {
4983 cricket::VideoChannel* video_channel = CreateVideoChannel(
4984 video->name,
4985 GetTransportNameForMediaSection(video->name, bundle_group));
4986 if (!video_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08004987 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
4988 "Failed to create video channel.");
Steve Anton75737c02017-11-06 10:37:17 -08004989 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08004990 GetVideoTransceiver()->internal()->SetChannel(video_channel);
Steve Anton75737c02017-11-06 10:37:17 -08004991 }
4992
Steve Antondcc3c022017-12-22 16:02:54 -08004993 const cricket::ContentInfo* data = cricket::GetFirstDataContent(&desc);
Steve Anton75737c02017-11-06 10:37:17 -08004994 if (data_channel_type_ != cricket::DCT_NONE && data && !data->rejected &&
4995 !rtp_data_channel_ && !sctp_transport_) {
Steve Antoneda6ccd2017-12-04 10:21:55 -08004996 if (!CreateDataChannel(data->name, GetTransportNameForMediaSection(
4997 data->name, bundle_group))) {
Steve Anton8a006912017-12-04 15:25:56 -08004998 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
4999 "Failed to create data channel.");
Steve Anton75737c02017-11-06 10:37:17 -08005000 }
5001 }
5002
Steve Anton8a006912017-12-04 15:25:56 -08005003 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08005004}
5005
Steve Anton4171afb2017-11-20 10:20:22 -08005006// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08005007cricket::VoiceChannel* PeerConnection::CreateVoiceChannel(
5008 const std::string& mid,
5009 const std::string& transport_name) {
Steve Anton75737c02017-11-06 10:37:17 -08005010 cricket::DtlsTransportInternal* rtp_dtls_transport =
5011 transport_controller_->CreateDtlsTransport(
5012 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5013 cricket::DtlsTransportInternal* rtcp_dtls_transport = nullptr;
5014 if (configuration_.rtcp_mux_policy !=
5015 PeerConnectionInterface::kRtcpMuxPolicyRequire) {
5016 rtcp_dtls_transport = transport_controller_->CreateDtlsTransport(
5017 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
5018 }
5019
5020 cricket::VoiceChannel* voice_channel = channel_manager()->CreateVoiceChannel(
5021 call_.get(), configuration_.media_config, rtp_dtls_transport,
Steve Antoneda6ccd2017-12-04 10:21:55 -08005022 rtcp_dtls_transport, signaling_thread(), mid, SrtpRequired(),
5023 audio_options_);
Steve Anton75737c02017-11-06 10:37:17 -08005024 if (!voice_channel) {
5025 transport_controller_->DestroyDtlsTransport(
5026 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5027 if (rtcp_dtls_transport) {
5028 transport_controller_->DestroyDtlsTransport(
5029 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
5030 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005031 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08005032 }
Steve Anton75737c02017-11-06 10:37:17 -08005033 voice_channel->SignalRtcpMuxFullyActive.connect(
5034 this, &PeerConnection::DestroyRtcpTransport_n);
5035 voice_channel->SignalDtlsSrtpSetupFailure.connect(
5036 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08005037 voice_channel->SignalSentPacket.connect(this,
5038 &PeerConnection::OnSentPacket_w);
Steve Anton4171afb2017-11-20 10:20:22 -08005039
Steve Antoneda6ccd2017-12-04 10:21:55 -08005040 return voice_channel;
Steve Anton75737c02017-11-06 10:37:17 -08005041}
5042
Steve Anton4171afb2017-11-20 10:20:22 -08005043// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08005044cricket::VideoChannel* PeerConnection::CreateVideoChannel(
5045 const std::string& mid,
5046 const std::string& transport_name) {
Steve Anton75737c02017-11-06 10:37:17 -08005047 cricket::DtlsTransportInternal* rtp_dtls_transport =
5048 transport_controller_->CreateDtlsTransport(
5049 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5050 cricket::DtlsTransportInternal* rtcp_dtls_transport = nullptr;
5051 if (configuration_.rtcp_mux_policy !=
5052 PeerConnectionInterface::kRtcpMuxPolicyRequire) {
5053 rtcp_dtls_transport = transport_controller_->CreateDtlsTransport(
5054 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
5055 }
5056
5057 cricket::VideoChannel* video_channel = channel_manager()->CreateVideoChannel(
5058 call_.get(), configuration_.media_config, rtp_dtls_transport,
Steve Antoneda6ccd2017-12-04 10:21:55 -08005059 rtcp_dtls_transport, signaling_thread(), mid, SrtpRequired(),
5060 video_options_);
Steve Anton75737c02017-11-06 10:37:17 -08005061
5062 if (!video_channel) {
5063 transport_controller_->DestroyDtlsTransport(
5064 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5065 if (rtcp_dtls_transport) {
5066 transport_controller_->DestroyDtlsTransport(
5067 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
5068 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005069 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08005070 }
Steve Anton75737c02017-11-06 10:37:17 -08005071 video_channel->SignalRtcpMuxFullyActive.connect(
5072 this, &PeerConnection::DestroyRtcpTransport_n);
5073 video_channel->SignalDtlsSrtpSetupFailure.connect(
5074 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08005075 video_channel->SignalSentPacket.connect(this,
5076 &PeerConnection::OnSentPacket_w);
Steve Anton4171afb2017-11-20 10:20:22 -08005077
Steve Antoneda6ccd2017-12-04 10:21:55 -08005078 return video_channel;
Steve Anton75737c02017-11-06 10:37:17 -08005079}
5080
Steve Antoneda6ccd2017-12-04 10:21:55 -08005081bool PeerConnection::CreateDataChannel(const std::string& mid,
5082 const std::string& transport_name) {
Steve Anton75737c02017-11-06 10:37:17 -08005083 bool sctp = (data_channel_type_ == cricket::DCT_SCTP);
5084 if (sctp) {
5085 if (!sctp_factory_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005086 RTC_LOG(LS_ERROR)
Steve Anton75737c02017-11-06 10:37:17 -08005087 << "Trying to create SCTP transport, but didn't compile with "
5088 "SCTP support (HAVE_SCTP)";
5089 return false;
5090 }
5091 if (!network_thread()->Invoke<bool>(
5092 RTC_FROM_HERE, rtc::Bind(&PeerConnection::CreateSctpTransport_n,
Steve Antoneda6ccd2017-12-04 10:21:55 -08005093 this, mid, transport_name))) {
Steve Anton75737c02017-11-06 10:37:17 -08005094 return false;
5095 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005096 for (const auto& channel : sctp_data_channels_) {
5097 channel->OnTransportChannelCreated();
5098 }
Steve Anton75737c02017-11-06 10:37:17 -08005099 } else {
Steve Anton75737c02017-11-06 10:37:17 -08005100 cricket::DtlsTransportInternal* rtp_dtls_transport =
5101 transport_controller_->CreateDtlsTransport(
5102 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5103 cricket::DtlsTransportInternal* rtcp_dtls_transport = nullptr;
5104 if (configuration_.rtcp_mux_policy !=
5105 PeerConnectionInterface::kRtcpMuxPolicyRequire) {
5106 rtcp_dtls_transport = transport_controller_->CreateDtlsTransport(
5107 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
5108 }
5109
5110 rtp_data_channel_ = channel_manager()->CreateRtpDataChannel(
5111 configuration_.media_config, rtp_dtls_transport, rtcp_dtls_transport,
Steve Antoneda6ccd2017-12-04 10:21:55 -08005112 signaling_thread(), mid, SrtpRequired());
Steve Anton75737c02017-11-06 10:37:17 -08005113
5114 if (!rtp_data_channel_) {
5115 transport_controller_->DestroyDtlsTransport(
5116 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5117 if (rtcp_dtls_transport) {
5118 transport_controller_->DestroyDtlsTransport(
5119 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
5120 }
5121 return false;
5122 }
5123
5124 rtp_data_channel_->SignalRtcpMuxFullyActive.connect(
5125 this, &PeerConnection::DestroyRtcpTransport_n);
5126 rtp_data_channel_->SignalDtlsSrtpSetupFailure.connect(
5127 this, &PeerConnection::OnDtlsSrtpSetupFailure);
5128 rtp_data_channel_->SignalSentPacket.connect(
5129 this, &PeerConnection::OnSentPacket_w);
5130 }
5131
Steve Anton75737c02017-11-06 10:37:17 -08005132 return true;
5133}
5134
5135Call::Stats PeerConnection::GetCallStats() {
5136 if (!worker_thread()->IsCurrent()) {
5137 return worker_thread()->Invoke<Call::Stats>(
5138 RTC_FROM_HERE, rtc::Bind(&PeerConnection::GetCallStats, this));
5139 }
5140 if (call_) {
5141 return call_->GetStats();
5142 } else {
5143 return Call::Stats();
5144 }
5145}
5146
5147std::unique_ptr<SessionStats> PeerConnection::GetSessionStats_n(
5148 const ChannelNamePairs& channel_name_pairs) {
5149 RTC_DCHECK(network_thread()->IsCurrent());
5150 std::unique_ptr<SessionStats> session_stats(new SessionStats());
5151 for (const auto channel_name_pair :
5152 {&channel_name_pairs.voice, &channel_name_pairs.video,
5153 &channel_name_pairs.data}) {
5154 if (*channel_name_pair) {
5155 cricket::TransportStats transport_stats;
5156 if (!transport_controller_->GetStats((*channel_name_pair)->transport_name,
5157 &transport_stats)) {
5158 return nullptr;
5159 }
Steve Anton75737c02017-11-06 10:37:17 -08005160 session_stats->transport_stats[(*channel_name_pair)->transport_name] =
5161 std::move(transport_stats);
5162 }
5163 }
5164 return session_stats;
5165}
5166
5167bool PeerConnection::CreateSctpTransport_n(const std::string& content_name,
5168 const std::string& transport_name) {
5169 RTC_DCHECK(network_thread()->IsCurrent());
5170 RTC_DCHECK(sctp_factory_);
5171 cricket::DtlsTransportInternal* tc =
5172 transport_controller_->CreateDtlsTransport_n(
5173 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5174 sctp_transport_ = sctp_factory_->CreateSctpTransport(tc);
5175 RTC_DCHECK(sctp_transport_);
5176 sctp_invoker_.reset(new rtc::AsyncInvoker());
5177 sctp_transport_->SignalReadyToSendData.connect(
5178 this, &PeerConnection::OnSctpTransportReadyToSendData_n);
5179 sctp_transport_->SignalDataReceived.connect(
5180 this, &PeerConnection::OnSctpTransportDataReceived_n);
5181 sctp_transport_->SignalStreamClosedRemotely.connect(
5182 this, &PeerConnection::OnSctpStreamClosedRemotely_n);
Oskar Sundbom9b28a032017-11-16 10:53:30 +01005183 sctp_transport_name_ = transport_name;
5184 sctp_content_name_ = content_name;
Steve Anton75737c02017-11-06 10:37:17 -08005185 return true;
5186}
5187
5188void PeerConnection::ChangeSctpTransport_n(const std::string& transport_name) {
5189 RTC_DCHECK(network_thread()->IsCurrent());
5190 RTC_DCHECK(sctp_transport_);
5191 RTC_DCHECK(sctp_transport_name_);
5192 std::string old_sctp_transport_name = *sctp_transport_name_;
Oskar Sundbom9b28a032017-11-16 10:53:30 +01005193 sctp_transport_name_ = transport_name;
Steve Anton75737c02017-11-06 10:37:17 -08005194 cricket::DtlsTransportInternal* tc =
5195 transport_controller_->CreateDtlsTransport_n(
5196 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5197 sctp_transport_->SetTransportChannel(tc);
5198 transport_controller_->DestroyDtlsTransport_n(
5199 old_sctp_transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5200}
5201
5202void PeerConnection::DestroySctpTransport_n() {
5203 RTC_DCHECK(network_thread()->IsCurrent());
5204 sctp_transport_.reset(nullptr);
Taylor Brandstetter389a97c2018-01-03 16:26:06 -08005205 transport_controller_->DestroyDtlsTransport_n(
5206 *sctp_transport_name_, cricket::ICE_CANDIDATE_COMPONENT_RTP);
Steve Anton75737c02017-11-06 10:37:17 -08005207 sctp_content_name_.reset();
5208 sctp_transport_name_.reset();
5209 sctp_invoker_.reset(nullptr);
5210 sctp_ready_to_send_data_ = false;
5211}
5212
5213void PeerConnection::OnSctpTransportReadyToSendData_n() {
5214 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5215 RTC_DCHECK(network_thread()->IsCurrent());
5216 // Note: Cannot use rtc::Bind here because it will grab a reference to
5217 // PeerConnection and potentially cause PeerConnection to live longer than
5218 // expected. It is safe not to grab a reference since the sctp_invoker_ will
5219 // be destroyed before PeerConnection is destroyed, and at that point all
5220 // pending tasks will be cleared.
5221 sctp_invoker_->AsyncInvoke<void>(RTC_FROM_HERE, signaling_thread(), [this] {
5222 OnSctpTransportReadyToSendData_s(true);
5223 });
5224}
5225
5226void PeerConnection::OnSctpTransportReadyToSendData_s(bool ready) {
5227 RTC_DCHECK(signaling_thread()->IsCurrent());
5228 sctp_ready_to_send_data_ = ready;
5229 SignalSctpReadyToSendData(ready);
5230}
5231
5232void PeerConnection::OnSctpTransportDataReceived_n(
5233 const cricket::ReceiveDataParams& params,
5234 const rtc::CopyOnWriteBuffer& payload) {
5235 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5236 RTC_DCHECK(network_thread()->IsCurrent());
5237 // Note: Cannot use rtc::Bind here because it will grab a reference to
5238 // PeerConnection and potentially cause PeerConnection to live longer than
5239 // expected. It is safe not to grab a reference since the sctp_invoker_ will
5240 // be destroyed before PeerConnection is destroyed, and at that point all
5241 // pending tasks will be cleared.
5242 sctp_invoker_->AsyncInvoke<void>(
5243 RTC_FROM_HERE, signaling_thread(), [this, params, payload] {
5244 OnSctpTransportDataReceived_s(params, payload);
5245 });
5246}
5247
5248void PeerConnection::OnSctpTransportDataReceived_s(
5249 const cricket::ReceiveDataParams& params,
5250 const rtc::CopyOnWriteBuffer& payload) {
5251 RTC_DCHECK(signaling_thread()->IsCurrent());
5252 if (params.type == cricket::DMT_CONTROL && IsOpenMessage(payload)) {
5253 // Received OPEN message; parse and signal that a new data channel should
5254 // be created.
5255 std::string label;
5256 InternalDataChannelInit config;
5257 config.id = params.ssrc;
5258 if (!ParseDataChannelOpenMessage(payload, &label, &config)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005259 RTC_LOG(LS_WARNING) << "Failed to parse the OPEN message for sid "
5260 << params.ssrc;
Steve Anton75737c02017-11-06 10:37:17 -08005261 return;
5262 }
5263 config.open_handshake_role = InternalDataChannelInit::kAcker;
5264 OnDataChannelOpenMessage(label, config);
5265 } else {
5266 // Otherwise just forward the signal.
5267 SignalSctpDataReceived(params, payload);
5268 }
5269}
5270
5271void PeerConnection::OnSctpStreamClosedRemotely_n(int sid) {
5272 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5273 RTC_DCHECK(network_thread()->IsCurrent());
5274 sctp_invoker_->AsyncInvoke<void>(
5275 RTC_FROM_HERE, signaling_thread(),
5276 rtc::Bind(&sigslot::signal1<int>::operator(),
5277 &SignalSctpStreamClosedRemotely, sid));
5278}
5279
5280// Returns false if bundle is enabled and rtcp_mux is disabled.
5281bool PeerConnection::ValidateBundleSettings(const SessionDescription* desc) {
5282 bool bundle_enabled = desc->HasGroup(cricket::GROUP_TYPE_BUNDLE);
5283 if (!bundle_enabled)
5284 return true;
5285
5286 const cricket::ContentGroup* bundle_group =
5287 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
5288 RTC_DCHECK(bundle_group != NULL);
5289
5290 const cricket::ContentInfos& contents = desc->contents();
5291 for (cricket::ContentInfos::const_iterator citer = contents.begin();
5292 citer != contents.end(); ++citer) {
5293 const cricket::ContentInfo* content = (&*citer);
5294 RTC_DCHECK(content != NULL);
5295 if (bundle_group->HasContentName(content->name) && !content->rejected &&
Steve Anton5adfafd2017-12-20 16:34:00 -08005296 content->type == MediaProtocolType::kRtp) {
Steve Anton75737c02017-11-06 10:37:17 -08005297 if (!HasRtcpMuxEnabled(content))
5298 return false;
5299 }
5300 }
5301 // RTCP-MUX is enabled in all the contents.
5302 return true;
5303}
5304
5305bool PeerConnection::HasRtcpMuxEnabled(const cricket::ContentInfo* content) {
Steve Antonb1c1de12017-12-21 15:14:30 -08005306 return content->media_description()->rtcp_mux();
Steve Anton75737c02017-11-06 10:37:17 -08005307}
5308
Steve Anton8a006912017-12-04 15:25:56 -08005309RTCError PeerConnection::ValidateSessionDescription(
Steve Anton75737c02017-11-06 10:37:17 -08005310 const SessionDescriptionInterface* sdesc,
Steve Anton8a006912017-12-04 15:25:56 -08005311 cricket::ContentSource source) {
Steve Antonf8470812017-12-04 10:46:21 -08005312 if (session_error() != SessionError::kNone) {
Steve Anton8a006912017-12-04 15:25:56 -08005313 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
Steve Anton75737c02017-11-06 10:37:17 -08005314 }
5315
5316 if (!sdesc || !sdesc->description()) {
Steve Anton8a006912017-12-04 15:25:56 -08005317 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidSdp);
Steve Anton75737c02017-11-06 10:37:17 -08005318 }
5319
Steve Anton3828c062017-12-06 10:34:51 -08005320 SdpType type = sdesc->GetType();
5321 if ((source == cricket::CS_LOCAL && !ExpectSetLocalDescription(type)) ||
5322 (source == cricket::CS_REMOTE && !ExpectSetRemoteDescription(type))) {
Steve Anton8a006912017-12-04 15:25:56 -08005323 LOG_AND_RETURN_ERROR(
5324 RTCErrorType::INVALID_PARAMETER,
5325 "Called in wrong state: " + GetSignalingStateString(signaling_state()));
Steve Anton75737c02017-11-06 10:37:17 -08005326 }
5327
5328 // Verify crypto settings.
5329 std::string crypto_error;
Steve Anton8a006912017-12-04 15:25:56 -08005330 if (webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED ||
5331 dtls_enabled_) {
Harald Alvestrand194939b2018-01-24 16:04:13 +01005332 RTCError crypto_error =
5333 VerifyCrypto(sdesc->description(), dtls_enabled_, uma_observer_);
Steve Anton8a006912017-12-04 15:25:56 -08005334 if (!crypto_error.ok()) {
5335 return crypto_error;
5336 }
Steve Anton75737c02017-11-06 10:37:17 -08005337 }
5338
5339 // Verify ice-ufrag and ice-pwd.
5340 if (!VerifyIceUfragPwdPresent(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08005341 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5342 kSdpWithoutIceUfragPwd);
Steve Anton75737c02017-11-06 10:37:17 -08005343 }
5344
5345 if (!ValidateBundleSettings(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08005346 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5347 kBundleWithoutRtcpMux);
Steve Anton75737c02017-11-06 10:37:17 -08005348 }
5349
5350 // TODO(skvlad): When the local rtcp-mux policy is Require, reject any
5351 // m-lines that do not rtcp-mux enabled.
5352
5353 // Verify m-lines in Answer when compared against Offer.
Steve Anton3828c062017-12-06 10:34:51 -08005354 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Anton75737c02017-11-06 10:37:17 -08005355 const cricket::SessionDescription* offer_desc =
5356 (source == cricket::CS_LOCAL) ? remote_description()->description()
5357 : local_description()->description();
5358 if (!MediaSectionsHaveSameCount(offer_desc, sdesc->description()) ||
5359 !MediaSectionsInSameOrder(offer_desc, sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08005360 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5361 kMlineMismatchInAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08005362 }
5363 } else {
5364 const cricket::SessionDescription* current_desc = nullptr;
5365 if (source == cricket::CS_LOCAL && local_description()) {
5366 current_desc = local_description()->description();
5367 } else if (source == cricket::CS_REMOTE && remote_description()) {
5368 current_desc = remote_description()->description();
5369 }
5370 // The re-offers should respect the order of m= sections in current
5371 // description. See RFC3264 Section 8 paragraph 4 for more details.
5372 if (current_desc &&
5373 !MediaSectionsInSameOrder(current_desc, sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08005374 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5375 kMlineMismatchInSubsequentOffer);
Steve Anton75737c02017-11-06 10:37:17 -08005376 }
5377 }
5378
Steve Anton8a006912017-12-04 15:25:56 -08005379 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08005380}
5381
Steve Anton3828c062017-12-06 10:34:51 -08005382bool PeerConnection::ExpectSetLocalDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08005383 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08005384 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08005385 return (state == PeerConnectionInterface::kStable) ||
5386 (state == PeerConnectionInterface::kHaveLocalOffer);
Steve Anton20393062017-12-04 16:24:52 -08005387 } else {
Steve Anton3828c062017-12-06 10:34:51 -08005388 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08005389 return (state == PeerConnectionInterface::kHaveRemoteOffer) ||
5390 (state == PeerConnectionInterface::kHaveLocalPrAnswer);
5391 }
5392}
5393
Steve Anton3828c062017-12-06 10:34:51 -08005394bool PeerConnection::ExpectSetRemoteDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08005395 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08005396 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08005397 return (state == PeerConnectionInterface::kStable) ||
5398 (state == PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton20393062017-12-04 16:24:52 -08005399 } else {
Steve Anton3828c062017-12-06 10:34:51 -08005400 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08005401 return (state == PeerConnectionInterface::kHaveLocalOffer) ||
5402 (state == PeerConnectionInterface::kHaveRemotePrAnswer);
5403 }
5404}
5405
Steve Antonf8470812017-12-04 10:46:21 -08005406const char* PeerConnection::SessionErrorToString(SessionError error) const {
5407 switch (error) {
5408 case SessionError::kNone:
5409 return "ERROR_NONE";
5410 case SessionError::kContent:
5411 return "ERROR_CONTENT";
5412 case SessionError::kTransport:
5413 return "ERROR_TRANSPORT";
5414 }
5415 RTC_NOTREACHED();
5416 return "";
5417}
5418
Steve Anton75737c02017-11-06 10:37:17 -08005419std::string PeerConnection::GetSessionErrorMsg() {
5420 std::ostringstream desc;
Steve Antonf8470812017-12-04 10:46:21 -08005421 desc << kSessionError << SessionErrorToString(session_error()) << ". ";
5422 desc << kSessionErrorDesc << session_error_desc() << ".";
Steve Anton75737c02017-11-06 10:37:17 -08005423 return desc.str();
5424}
5425
5426// We need to check the local/remote description for the Transport instead of
5427// the session, because a new Transport added during renegotiation may have
5428// them unset while the session has them set from the previous negotiation.
5429// Not doing so may trigger the auto generation of transport description and
5430// mess up DTLS identity information, ICE credential, etc.
5431bool PeerConnection::ReadyToUseRemoteCandidate(
5432 const IceCandidateInterface* candidate,
5433 const SessionDescriptionInterface* remote_desc,
5434 bool* valid) {
5435 *valid = true;
5436
5437 const SessionDescriptionInterface* current_remote_desc =
5438 remote_desc ? remote_desc : remote_description();
5439
5440 if (!current_remote_desc) {
5441 return false;
5442 }
5443
5444 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
5445 size_t remote_content_size =
5446 current_remote_desc->description()->contents().size();
5447 if (mediacontent_index >= remote_content_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005448 RTC_LOG(LS_ERROR)
5449 << "ReadyToUseRemoteCandidate: Invalid candidate media index "
5450 << mediacontent_index;
Steve Anton75737c02017-11-06 10:37:17 -08005451
5452 *valid = false;
5453 return false;
5454 }
5455
5456 cricket::ContentInfo content =
5457 current_remote_desc->description()->contents()[mediacontent_index];
5458
5459 const std::string transport_name = GetTransportName(content.name);
5460 if (transport_name.empty()) {
5461 return false;
5462 }
5463 return transport_controller_->ReadyForRemoteCandidates(transport_name);
5464}
5465
5466bool PeerConnection::SrtpRequired() const {
5467 return dtls_enabled_ ||
5468 webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED;
5469}
5470
5471void PeerConnection::OnTransportControllerGatheringState(
5472 cricket::IceGatheringState state) {
5473 RTC_DCHECK(signaling_thread()->IsCurrent());
5474 if (state == cricket::kIceGatheringGathering) {
5475 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringGathering);
5476 } else if (state == cricket::kIceGatheringComplete) {
5477 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringComplete);
5478 }
5479}
5480
5481void PeerConnection::ReportTransportStats() {
5482 // Use a set so we don't report the same stats twice if two channels share
5483 // a transport.
5484 std::set<std::string> transport_names;
5485 if (voice_channel()) {
5486 transport_names.insert(voice_channel()->transport_name());
5487 }
5488 if (video_channel()) {
5489 transport_names.insert(video_channel()->transport_name());
5490 }
5491 if (rtp_data_channel()) {
5492 transport_names.insert(rtp_data_channel()->transport_name());
5493 }
5494 if (sctp_transport_name_) {
5495 transport_names.insert(*sctp_transport_name_);
5496 }
5497 for (const auto& name : transport_names) {
5498 cricket::TransportStats stats;
5499 if (transport_controller_->GetStats(name, &stats)) {
5500 ReportBestConnectionState(stats);
5501 ReportNegotiatedCiphers(stats);
5502 }
5503 }
5504}
5505// Walk through the ConnectionInfos to gather best connection usage
5506// for IPv4 and IPv6.
5507void PeerConnection::ReportBestConnectionState(
5508 const cricket::TransportStats& stats) {
5509 RTC_DCHECK(metrics_observer());
5510 for (cricket::TransportChannelStatsList::const_iterator it =
5511 stats.channel_stats.begin();
5512 it != stats.channel_stats.end(); ++it) {
5513 for (cricket::ConnectionInfos::const_iterator it_info =
5514 it->connection_infos.begin();
5515 it_info != it->connection_infos.end(); ++it_info) {
5516 if (!it_info->best_connection) {
5517 continue;
5518 }
5519
5520 PeerConnectionEnumCounterType type = kPeerConnectionEnumCounterMax;
5521 const cricket::Candidate& local = it_info->local_candidate;
5522 const cricket::Candidate& remote = it_info->remote_candidate;
5523
5524 // Increment the counter for IceCandidatePairType.
5525 if (local.protocol() == cricket::TCP_PROTOCOL_NAME ||
5526 (local.type() == RELAY_PORT_TYPE &&
5527 local.relay_protocol() == cricket::TCP_PROTOCOL_NAME)) {
5528 type = kEnumCounterIceCandidatePairTypeTcp;
5529 } else if (local.protocol() == cricket::UDP_PROTOCOL_NAME) {
5530 type = kEnumCounterIceCandidatePairTypeUdp;
5531 } else {
5532 RTC_CHECK(0);
5533 }
5534 metrics_observer()->IncrementEnumCounter(
5535 type, GetIceCandidatePairCounter(local, remote),
5536 kIceCandidatePairMax);
5537
5538 // Increment the counter for IP type.
5539 if (local.address().family() == AF_INET) {
5540 metrics_observer()->IncrementEnumCounter(
5541 kEnumCounterAddressFamily, kBestConnections_IPv4,
5542 kPeerConnectionAddressFamilyCounter_Max);
5543
5544 } else if (local.address().family() == AF_INET6) {
5545 metrics_observer()->IncrementEnumCounter(
5546 kEnumCounterAddressFamily, kBestConnections_IPv6,
5547 kPeerConnectionAddressFamilyCounter_Max);
5548 } else {
5549 RTC_CHECK(0);
5550 }
5551
5552 return;
5553 }
5554 }
5555}
5556
5557void PeerConnection::ReportNegotiatedCiphers(
5558 const cricket::TransportStats& stats) {
5559 RTC_DCHECK(metrics_observer());
5560 if (!dtls_enabled_ || stats.channel_stats.empty()) {
5561 return;
5562 }
5563
5564 int srtp_crypto_suite = stats.channel_stats[0].srtp_crypto_suite;
5565 int ssl_cipher_suite = stats.channel_stats[0].ssl_cipher_suite;
5566 if (srtp_crypto_suite == rtc::SRTP_INVALID_CRYPTO_SUITE &&
5567 ssl_cipher_suite == rtc::TLS_NULL_WITH_NULL_NULL) {
5568 return;
5569 }
5570
5571 PeerConnectionEnumCounterType srtp_counter_type;
5572 PeerConnectionEnumCounterType ssl_counter_type;
5573 if (stats.transport_name == cricket::CN_AUDIO) {
5574 srtp_counter_type = kEnumCounterAudioSrtpCipher;
5575 ssl_counter_type = kEnumCounterAudioSslCipher;
5576 } else if (stats.transport_name == cricket::CN_VIDEO) {
5577 srtp_counter_type = kEnumCounterVideoSrtpCipher;
5578 ssl_counter_type = kEnumCounterVideoSslCipher;
5579 } else if (stats.transport_name == cricket::CN_DATA) {
5580 srtp_counter_type = kEnumCounterDataSrtpCipher;
5581 ssl_counter_type = kEnumCounterDataSslCipher;
5582 } else {
5583 RTC_NOTREACHED();
5584 return;
5585 }
5586
5587 if (srtp_crypto_suite != rtc::SRTP_INVALID_CRYPTO_SUITE) {
5588 metrics_observer()->IncrementSparseEnumCounter(srtp_counter_type,
5589 srtp_crypto_suite);
5590 }
5591 if (ssl_cipher_suite != rtc::TLS_NULL_WITH_NULL_NULL) {
5592 metrics_observer()->IncrementSparseEnumCounter(ssl_counter_type,
5593 ssl_cipher_suite);
5594 }
5595}
5596
5597void PeerConnection::OnSentPacket_w(const rtc::SentPacket& sent_packet) {
5598 RTC_DCHECK(worker_thread()->IsCurrent());
5599 RTC_DCHECK(call_);
5600 call_->OnSentPacket(sent_packet);
5601}
5602
5603const std::string PeerConnection::GetTransportName(
5604 const std::string& content_name) {
5605 cricket::BaseChannel* channel = GetChannel(content_name);
Steve Anton6fec8802017-12-04 10:37:29 -08005606 if (channel) {
5607 return channel->transport_name();
Steve Anton75737c02017-11-06 10:37:17 -08005608 }
Steve Anton6fec8802017-12-04 10:37:29 -08005609 if (sctp_transport_) {
5610 RTC_DCHECK(sctp_content_name_);
5611 RTC_DCHECK(sctp_transport_name_);
5612 if (content_name == *sctp_content_name_) {
5613 return *sctp_transport_name_;
5614 }
5615 }
5616 // Return an empty string if failed to retrieve the transport name.
5617 return "";
Steve Anton75737c02017-11-06 10:37:17 -08005618}
5619
5620void PeerConnection::DestroyRtcpTransport_n(const std::string& transport_name) {
5621 RTC_DCHECK(network_thread()->IsCurrent());
5622 transport_controller_->DestroyDtlsTransport_n(
5623 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
5624}
5625
Steve Anton6fec8802017-12-04 10:37:29 -08005626void PeerConnection::DestroyTransceiverChannel(
5627 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
5628 transceiver) {
5629 RTC_DCHECK(transceiver);
Steve Anton75737c02017-11-06 10:37:17 -08005630
Steve Anton6fec8802017-12-04 10:37:29 -08005631 cricket::BaseChannel* channel = transceiver->internal()->channel();
5632 if (channel) {
5633 transceiver->internal()->SetChannel(nullptr);
5634 DestroyBaseChannel(channel);
Steve Anton75737c02017-11-06 10:37:17 -08005635 }
5636}
5637
5638void PeerConnection::DestroyDataChannel() {
Steve Anton6fec8802017-12-04 10:37:29 -08005639 if (rtp_data_channel_) {
5640 OnDataChannelDestroyed();
5641 DestroyBaseChannel(rtp_data_channel_);
5642 rtp_data_channel_ = nullptr;
5643 }
5644
5645 // Note: Cannot use rtc::Bind to create a functor to invoke because it will
5646 // grab a reference to this PeerConnection. If this is called from the
5647 // PeerConnection destructor, the RefCountedObject vtable will have already
5648 // been destroyed (since it is a subclass of PeerConnection) and using
5649 // rtc::Bind will cause "Pure virtual function called" error to appear.
5650
5651 if (sctp_transport_) {
5652 OnDataChannelDestroyed();
5653 network_thread()->Invoke<void>(RTC_FROM_HERE,
5654 [this] { DestroySctpTransport_n(); });
5655 }
5656}
5657
5658void PeerConnection::DestroyBaseChannel(cricket::BaseChannel* channel) {
5659 RTC_DCHECK(channel);
5660 RTC_DCHECK(channel->rtp_dtls_transport());
5661
5662 // Need to cache these before destroying the base channel so that we do not
5663 // access uninitialized memory.
5664 const std::string transport_name =
5665 channel->rtp_dtls_transport()->transport_name();
5666 const bool need_to_delete_rtcp = (channel->rtcp_dtls_transport() != nullptr);
5667
5668 switch (channel->media_type()) {
5669 case cricket::MEDIA_TYPE_AUDIO:
5670 channel_manager()->DestroyVoiceChannel(
5671 static_cast<cricket::VoiceChannel*>(channel));
5672 break;
5673 case cricket::MEDIA_TYPE_VIDEO:
5674 channel_manager()->DestroyVideoChannel(
5675 static_cast<cricket::VideoChannel*>(channel));
5676 break;
5677 case cricket::MEDIA_TYPE_DATA:
5678 channel_manager()->DestroyRtpDataChannel(
5679 static_cast<cricket::RtpDataChannel*>(channel));
5680 break;
5681 default:
5682 RTC_NOTREACHED() << "Unknown media type: " << channel->media_type();
5683 break;
5684 }
5685
5686 // |channel| can no longer be used.
5687
Steve Anton75737c02017-11-06 10:37:17 -08005688 transport_controller_->DestroyDtlsTransport(
5689 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5690 if (need_to_delete_rtcp) {
5691 transport_controller_->DestroyDtlsTransport(
5692 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
5693 }
5694}
5695
Harald Alvestrand89061872018-01-02 14:08:34 +01005696void PeerConnection::ClearStatsCache() {
5697 if (stats_collector_) {
5698 stats_collector_->ClearCachedStatsReport();
5699 }
5700}
5701
henrike@webrtc.org28e20752013-07-10 00:45:36 +00005702} // namespace webrtc