blob: a6297616b90048f8376d4e867364985b4bc0201b [file] [log] [blame]
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001/*
kjellanderb24317b2016-02-10 07:54:43 -08002 * Copyright 2012 The WebRTC project authors. All Rights Reserved.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003 *
kjellanderb24317b2016-02-10 07:54:43 -08004 * Use of this source code is governed by a BSD-style license
5 * that can be found in the LICENSE file in the root of the source
6 * tree. An additional intellectual property rights grant can be found
7 * in the file PATENTS. All contributing project authors may
8 * be found in the AUTHORS file in the root of the source tree.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00009 */
10
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020011#include "pc/peerconnection.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000012
deadbeefeb459812015-12-15 19:24:43 -080013#include <algorithm>
Steve Antondcc3c022017-12-22 16:02:54 -080014#include <queue>
Steve Anton75737c02017-11-06 10:37:17 -080015#include <set>
kwiberg0eb15ed2015-12-17 03:04:15 -080016#include <utility>
17#include <vector>
henrike@webrtc.org28e20752013-07-10 00:45:36 +000018
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020019#include "api/jsepicecandidate.h"
20#include "api/jsepsessiondescription.h"
21#include "api/mediaconstraintsinterface.h"
22#include "api/mediastreamproxy.h"
23#include "api/mediastreamtrackproxy.h"
24#include "call/call.h"
Elad Alon83ccca12017-10-04 13:18:26 +020025#include "logging/rtc_event_log/output/rtc_event_log_output_file.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020026#include "logging/rtc_event_log/rtc_event_log.h"
27#include "media/sctp/sctptransport.h"
28#include "pc/audiotrack.h"
Steve Anton75737c02017-11-06 10:37:17 -080029#include "pc/channel.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020030#include "pc/channelmanager.h"
31#include "pc/dtmfsender.h"
32#include "pc/mediastream.h"
33#include "pc/mediastreamobserver.h"
34#include "pc/remoteaudiosource.h"
Steve Anton1d03a752017-11-27 14:30:09 -080035#include "pc/rtpmediautils.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020036#include "pc/rtpreceiver.h"
37#include "pc/rtpsender.h"
Steve Anton75737c02017-11-06 10:37:17 -080038#include "pc/sctputils.h"
Steve Antona3a92c22017-12-07 10:27:41 -080039#include "pc/sdputils.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020040#include "pc/streamcollection.h"
41#include "pc/videocapturertracksource.h"
42#include "pc/videotrack.h"
43#include "rtc_base/bind.h"
44#include "rtc_base/checks.h"
45#include "rtc_base/logging.h"
Karl Wiberge40468b2017-11-22 10:42:26 +010046#include "rtc_base/numerics/safe_conversions.h"
Elad Alon83ccca12017-10-04 13:18:26 +020047#include "rtc_base/ptr_util.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020048#include "rtc_base/stringencode.h"
49#include "rtc_base/stringutils.h"
50#include "rtc_base/trace_event.h"
51#include "system_wrappers/include/clock.h"
52#include "system_wrappers/include/field_trial.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000053
Steve Anton75737c02017-11-06 10:37:17 -080054using cricket::ContentInfo;
55using cricket::ContentInfos;
56using cricket::MediaContentDescription;
57using cricket::SessionDescription;
Steve Anton5adfafd2017-12-20 16:34:00 -080058using cricket::MediaProtocolType;
Steve Anton75737c02017-11-06 10:37:17 -080059using cricket::TransportInfo;
60
61using cricket::LOCAL_PORT_TYPE;
62using cricket::STUN_PORT_TYPE;
63using cricket::RELAY_PORT_TYPE;
64using cricket::PRFLX_PORT_TYPE;
65
Steve Antonba818672017-11-06 10:21:57 -080066namespace webrtc {
67
Steve Anton75737c02017-11-06 10:37:17 -080068// Error messages
69const char kBundleWithoutRtcpMux[] =
70 "rtcp-mux must be enabled when BUNDLE "
71 "is enabled.";
Steve Anton75737c02017-11-06 10:37:17 -080072const char kInvalidCandidates[] = "Description contains invalid candidates.";
73const char kInvalidSdp[] = "Invalid session description.";
74const char kMlineMismatchInAnswer[] =
75 "The order of m-lines in answer doesn't match order in offer. Rejecting "
76 "answer.";
77const char kMlineMismatchInSubsequentOffer[] =
78 "The order of m-lines in subsequent offer doesn't match order from "
79 "previous offer/answer.";
Steve Anton75737c02017-11-06 10:37:17 -080080const char kSdpWithoutDtlsFingerprint[] =
81 "Called with SDP without DTLS fingerprint.";
82const char kSdpWithoutSdesCrypto[] = "Called with SDP without SDES crypto.";
83const char kSdpWithoutIceUfragPwd[] =
84 "Called with SDP without ice-ufrag and ice-pwd.";
85const char kSessionError[] = "Session error code: ";
86const char kSessionErrorDesc[] = "Session error description: ";
87const char kDtlsSrtpSetupFailureRtp[] =
88 "Couldn't set up DTLS-SRTP on RTP channel.";
89const char kDtlsSrtpSetupFailureRtcp[] =
90 "Couldn't set up DTLS-SRTP on RTCP channel.";
91const char kEnableBundleFailed[] = "Failed to enable BUNDLE.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +000092
Steve Anton75737c02017-11-06 10:37:17 -080093namespace {
henrike@webrtc.org28e20752013-07-10 00:45:36 +000094
deadbeefab9b2d12015-10-14 11:33:11 -070095static const char kDefaultStreamLabel[] = "default";
Steve Anton4171afb2017-11-20 10:20:22 -080096static const char kDefaultAudioSenderId[] = "defaulta0";
97static const char kDefaultVideoSenderId[] = "defaultv0";
deadbeefab9b2d12015-10-14 11:33:11 -070098
zhihuang8f65cdf2016-05-06 18:40:30 -070099// The length of RTCP CNAMEs.
100static const int kRtcpCnameLength = 16;
101
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000102enum {
wu@webrtc.org91053e72013-08-10 07:18:04 +0000103 MSG_SET_SESSIONDESCRIPTION_SUCCESS = 0,
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000104 MSG_SET_SESSIONDESCRIPTION_FAILED,
deadbeefab9b2d12015-10-14 11:33:11 -0700105 MSG_CREATE_SESSIONDESCRIPTION_FAILED,
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000106 MSG_GETSTATS,
deadbeefbd292462015-12-14 18:15:29 -0800107 MSG_FREE_DATACHANNELS,
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000108};
109
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000110struct SetSessionDescriptionMsg : public rtc::MessageData {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000111 explicit SetSessionDescriptionMsg(
112 webrtc::SetSessionDescriptionObserver* observer)
113 : observer(observer) {
114 }
115
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000116 rtc::scoped_refptr<webrtc::SetSessionDescriptionObserver> observer;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000117 std::string error;
118};
119
deadbeefab9b2d12015-10-14 11:33:11 -0700120struct CreateSessionDescriptionMsg : public rtc::MessageData {
121 explicit CreateSessionDescriptionMsg(
122 webrtc::CreateSessionDescriptionObserver* observer)
123 : observer(observer) {}
124
125 rtc::scoped_refptr<webrtc::CreateSessionDescriptionObserver> observer;
126 std::string error;
127};
128
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000129struct GetStatsMsg : public rtc::MessageData {
tommi@webrtc.org5b06b062014-08-15 08:38:30 +0000130 GetStatsMsg(webrtc::StatsObserver* observer,
131 webrtc::MediaStreamTrackInterface* track)
132 : observer(observer), track(track) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000133 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000134 rtc::scoped_refptr<webrtc::StatsObserver> observer;
tommi@webrtc.org5b06b062014-08-15 08:38:30 +0000135 rtc::scoped_refptr<webrtc::MediaStreamTrackInterface> track;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000136};
137
deadbeefab9b2d12015-10-14 11:33:11 -0700138// Check if we can send |new_stream| on a PeerConnection.
139bool CanAddLocalMediaStream(webrtc::StreamCollectionInterface* current_streams,
140 webrtc::MediaStreamInterface* new_stream) {
141 if (!new_stream || !current_streams) {
142 return false;
143 }
144 if (current_streams->find(new_stream->label()) != nullptr) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100145 RTC_LOG(LS_ERROR) << "MediaStream with label " << new_stream->label()
146 << " is already added.";
deadbeefab9b2d12015-10-14 11:33:11 -0700147 return false;
148 }
149 return true;
150}
151
deadbeef5e97fb52015-10-15 12:49:08 -0700152// If the direction is "recvonly" or "inactive", treat the description
153// as containing no streams.
154// See: https://code.google.com/p/webrtc/issues/detail?id=5054
155std::vector<cricket::StreamParams> GetActiveStreams(
156 const cricket::MediaContentDescription* desc) {
Steve Anton4e70a722017-11-28 14:57:10 -0800157 return RtpTransceiverDirectionHasSend(desc->direction())
deadbeef5e97fb52015-10-15 12:49:08 -0700158 ? desc->streams()
159 : std::vector<cricket::StreamParams>();
160}
161
deadbeefab9b2d12015-10-14 11:33:11 -0700162bool IsValidOfferToReceiveMedia(int value) {
163 typedef PeerConnectionInterface::RTCOfferAnswerOptions Options;
164 return (value >= Options::kUndefined) &&
165 (value <= Options::kMaxOfferToReceiveMedia);
166}
167
zhihuang1c378ed2017-08-17 14:10:50 -0700168// Add options to |[audio/video]_media_description_options| from |senders|.
169void AddRtpSenderOptions(
deadbeefa601f5c2016-06-06 14:27:39 -0700170 const std::vector<rtc::scoped_refptr<
171 RtpSenderProxyWithInternal<RtpSenderInternal>>>& senders,
zhihuang1c378ed2017-08-17 14:10:50 -0700172 cricket::MediaDescriptionOptions* audio_media_description_options,
173 cricket::MediaDescriptionOptions* video_media_description_options) {
olka3c747662017-08-17 06:50:32 -0700174 for (const auto& sender : senders) {
zhihuang1c378ed2017-08-17 14:10:50 -0700175 if (sender->media_type() == cricket::MEDIA_TYPE_AUDIO) {
176 if (audio_media_description_options) {
177 audio_media_description_options->AddAudioSender(
Steve Anton8ffb9c32017-08-31 15:45:38 -0700178 sender->id(), sender->internal()->stream_ids());
zhihuang1c378ed2017-08-17 14:10:50 -0700179 }
180 } else {
181 RTC_DCHECK(sender->media_type() == cricket::MEDIA_TYPE_VIDEO);
182 if (video_media_description_options) {
183 video_media_description_options->AddVideoSender(
Steve Anton8ffb9c32017-08-31 15:45:38 -0700184 sender->id(), sender->internal()->stream_ids(), 1);
zhihuang1c378ed2017-08-17 14:10:50 -0700185 }
186 }
zhihuanga77e6bb2017-08-14 18:17:48 -0700187 }
zhihuang1c378ed2017-08-17 14:10:50 -0700188}
olka3c747662017-08-17 06:50:32 -0700189
zhihuang1c378ed2017-08-17 14:10:50 -0700190// Add options to |session_options| from |rtp_data_channels|.
191void AddRtpDataChannelOptions(
192 const std::map<std::string, rtc::scoped_refptr<DataChannel>>&
193 rtp_data_channels,
194 cricket::MediaDescriptionOptions* data_media_description_options) {
195 if (!data_media_description_options) {
196 return;
197 }
deadbeefab9b2d12015-10-14 11:33:11 -0700198 // Check for data channels.
199 for (const auto& kv : rtp_data_channels) {
200 const DataChannel* channel = kv.second;
201 if (channel->state() == DataChannel::kConnecting ||
202 channel->state() == DataChannel::kOpen) {
zhihuang1c378ed2017-08-17 14:10:50 -0700203 // Legacy RTP data channels are signaled with the track/stream ID set to
204 // the data channel's label.
205 data_media_description_options->AddRtpDataChannel(channel->label(),
206 channel->label());
deadbeefab9b2d12015-10-14 11:33:11 -0700207 }
208 }
209}
210
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700211uint32_t ConvertIceTransportTypeToCandidateFilter(
212 PeerConnectionInterface::IceTransportsType type) {
213 switch (type) {
214 case PeerConnectionInterface::kNone:
215 return cricket::CF_NONE;
216 case PeerConnectionInterface::kRelay:
217 return cricket::CF_RELAY;
218 case PeerConnectionInterface::kNoHost:
219 return (cricket::CF_ALL & ~cricket::CF_HOST);
220 case PeerConnectionInterface::kAll:
221 return cricket::CF_ALL;
222 default:
nissec80e7412017-01-11 05:56:46 -0800223 RTC_NOTREACHED();
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700224 }
225 return cricket::CF_NONE;
226}
227
deadbeef293e9262017-01-11 12:28:30 -0800228// Helper to set an error and return from a method.
229bool SafeSetError(webrtc::RTCErrorType type, webrtc::RTCError* error) {
230 if (error) {
231 error->set_type(type);
232 }
233 return type == webrtc::RTCErrorType::NONE;
234}
235
Steve Anton038834f2017-07-14 15:59:59 -0700236bool SafeSetError(webrtc::RTCError error, webrtc::RTCError* error_out) {
237 if (error_out) {
238 *error_out = std::move(error);
239 }
240 return error.ok();
241}
242
Steve Antonba818672017-11-06 10:21:57 -0800243std::string GetSignalingStateString(
244 PeerConnectionInterface::SignalingState state) {
245 switch (state) {
246 case PeerConnectionInterface::kStable:
247 return "kStable";
248 case PeerConnectionInterface::kHaveLocalOffer:
249 return "kHaveLocalOffer";
250 case PeerConnectionInterface::kHaveLocalPrAnswer:
251 return "kHavePrAnswer";
252 case PeerConnectionInterface::kHaveRemoteOffer:
253 return "kHaveRemoteOffer";
254 case PeerConnectionInterface::kHaveRemotePrAnswer:
255 return "kHaveRemotePrAnswer";
256 case PeerConnectionInterface::kClosed:
257 return "kClosed";
258 }
259 RTC_NOTREACHED();
260 return "";
261}
deadbeef0a6c4ca2015-10-06 11:38:28 -0700262
Steve Anton75737c02017-11-06 10:37:17 -0800263IceCandidatePairType GetIceCandidatePairCounter(
264 const cricket::Candidate& local,
265 const cricket::Candidate& remote) {
266 const auto& l = local.type();
267 const auto& r = remote.type();
268 const auto& host = LOCAL_PORT_TYPE;
269 const auto& srflx = STUN_PORT_TYPE;
270 const auto& relay = RELAY_PORT_TYPE;
271 const auto& prflx = PRFLX_PORT_TYPE;
272 if (l == host && r == host) {
273 bool local_private = IPIsPrivate(local.address().ipaddr());
274 bool remote_private = IPIsPrivate(remote.address().ipaddr());
275 if (local_private) {
276 if (remote_private) {
277 return kIceCandidatePairHostPrivateHostPrivate;
278 } else {
279 return kIceCandidatePairHostPrivateHostPublic;
280 }
281 } else {
282 if (remote_private) {
283 return kIceCandidatePairHostPublicHostPrivate;
284 } else {
285 return kIceCandidatePairHostPublicHostPublic;
286 }
287 }
288 }
289 if (l == host && r == srflx)
290 return kIceCandidatePairHostSrflx;
291 if (l == host && r == relay)
292 return kIceCandidatePairHostRelay;
293 if (l == host && r == prflx)
294 return kIceCandidatePairHostPrflx;
295 if (l == srflx && r == host)
296 return kIceCandidatePairSrflxHost;
297 if (l == srflx && r == srflx)
298 return kIceCandidatePairSrflxSrflx;
299 if (l == srflx && r == relay)
300 return kIceCandidatePairSrflxRelay;
301 if (l == srflx && r == prflx)
302 return kIceCandidatePairSrflxPrflx;
303 if (l == relay && r == host)
304 return kIceCandidatePairRelayHost;
305 if (l == relay && r == srflx)
306 return kIceCandidatePairRelaySrflx;
307 if (l == relay && r == relay)
308 return kIceCandidatePairRelayRelay;
309 if (l == relay && r == prflx)
310 return kIceCandidatePairRelayPrflx;
311 if (l == prflx && r == host)
312 return kIceCandidatePairPrflxHost;
313 if (l == prflx && r == srflx)
314 return kIceCandidatePairPrflxSrflx;
315 if (l == prflx && r == relay)
316 return kIceCandidatePairPrflxRelay;
317 return kIceCandidatePairMax;
318}
319
320// Verify that the order of media sections in |new_desc| matches
321// |existing_desc|. The number of m= sections in |new_desc| should be no less
322// than |existing_desc|.
323bool MediaSectionsInSameOrder(const SessionDescription* existing_desc,
324 const SessionDescription* new_desc) {
325 if (!existing_desc || !new_desc) {
326 return false;
327 }
328
329 if (existing_desc->contents().size() > new_desc->contents().size()) {
330 return false;
331 }
332
333 for (size_t i = 0; i < existing_desc->contents().size(); ++i) {
Steve Antondcc3c022017-12-22 16:02:54 -0800334 if (existing_desc->contents()[i].rejected) {
335 // If the media section can be recycled, it's valid for the MID and media
336 // type to change.
337 continue;
338 }
Steve Anton75737c02017-11-06 10:37:17 -0800339 if (new_desc->contents()[i].name != existing_desc->contents()[i].name) {
340 return false;
341 }
342 const MediaContentDescription* new_desc_mdesc =
Steve Antonb1c1de12017-12-21 15:14:30 -0800343 new_desc->contents()[i].media_description();
Steve Anton75737c02017-11-06 10:37:17 -0800344 const MediaContentDescription* existing_desc_mdesc =
Steve Antonb1c1de12017-12-21 15:14:30 -0800345 existing_desc->contents()[i].media_description();
Steve Anton75737c02017-11-06 10:37:17 -0800346 if (new_desc_mdesc->type() != existing_desc_mdesc->type()) {
347 return false;
348 }
349 }
350 return true;
351}
352
353bool MediaSectionsHaveSameCount(const SessionDescription* desc1,
354 const SessionDescription* desc2) {
355 if (!desc1 || !desc2) {
356 return false;
357 }
358 return desc1->contents().size() == desc2->contents().size();
359}
360
361// Checks that each non-rejected content has SDES crypto keys or a DTLS
362// fingerprint, unless it's in a BUNDLE group, in which case only the
363// BUNDLE-tag section (first media section/description in the BUNDLE group)
364// needs a ufrag and pwd. Mismatches, such as replying with a DTLS fingerprint
365// to SDES keys, will be caught in JsepTransport negotiation, and backstopped
366// by Channel's |srtp_required| check.
Harald Alvestrand194939b2018-01-24 16:04:13 +0100367RTCError VerifyCrypto(const SessionDescription* desc,
368 bool dtls_enabled,
369 rtc::scoped_refptr<webrtc::UMAObserver> uma_observer) {
Steve Anton75737c02017-11-06 10:37:17 -0800370 const cricket::ContentGroup* bundle =
371 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton8a006912017-12-04 15:25:56 -0800372 for (const cricket::ContentInfo& content_info : desc->contents()) {
373 if (content_info.rejected) {
Steve Anton75737c02017-11-06 10:37:17 -0800374 continue;
375 }
Steve Anton8a006912017-12-04 15:25:56 -0800376 const std::string& mid = content_info.name;
377 if (bundle && bundle->HasContentName(mid) &&
378 mid != *(bundle->FirstContentName())) {
Steve Anton75737c02017-11-06 10:37:17 -0800379 // This isn't the first media section in the BUNDLE group, so it's not
380 // required to have crypto attributes, since only the crypto attributes
381 // from the first section actually get used.
382 continue;
383 }
384
385 // If the content isn't rejected or bundled into another m= section, crypto
386 // must be present.
Steve Antonb1c1de12017-12-21 15:14:30 -0800387 const MediaContentDescription* media = content_info.media_description();
Steve Anton8a006912017-12-04 15:25:56 -0800388 const TransportInfo* tinfo = desc->GetTransportInfoByName(mid);
Steve Anton75737c02017-11-06 10:37:17 -0800389 if (!media || !tinfo) {
390 // Something is not right.
Steve Anton8a006912017-12-04 15:25:56 -0800391 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidSdp);
Steve Anton75737c02017-11-06 10:37:17 -0800392 }
393 if (dtls_enabled) {
394 if (!tinfo->description.identity_fingerprint) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100395 RTC_LOG(LS_WARNING)
396 << "Session description must have DTLS fingerprint if "
397 "DTLS enabled.";
Steve Anton8a006912017-12-04 15:25:56 -0800398 return RTCError(RTCErrorType::INVALID_PARAMETER,
399 kSdpWithoutDtlsFingerprint);
Steve Anton75737c02017-11-06 10:37:17 -0800400 }
Harald Alvestrand194939b2018-01-24 16:04:13 +0100401 if (uma_observer) {
402 uma_observer->IncrementEnumCounter(webrtc::kEnumCounterKeyProtocol,
403 webrtc::kEnumCounterKeyProtocolDtls,
404 webrtc::kEnumCounterKeyProtocolMax);
405 }
Steve Anton75737c02017-11-06 10:37:17 -0800406 } else {
407 if (media->cryptos().empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100408 RTC_LOG(LS_WARNING)
Steve Anton75737c02017-11-06 10:37:17 -0800409 << "Session description must have SDES when DTLS disabled.";
Steve Anton8a006912017-12-04 15:25:56 -0800410 return RTCError(RTCErrorType::INVALID_PARAMETER, kSdpWithoutSdesCrypto);
Steve Anton75737c02017-11-06 10:37:17 -0800411 }
Harald Alvestrand194939b2018-01-24 16:04:13 +0100412 if (uma_observer) {
413 uma_observer->IncrementEnumCounter(webrtc::kEnumCounterKeyProtocol,
414 webrtc::kEnumCounterKeyProtocolSdes,
415 webrtc::kEnumCounterKeyProtocolMax);
416 }
Steve Anton75737c02017-11-06 10:37:17 -0800417 }
418 }
Steve Anton8a006912017-12-04 15:25:56 -0800419 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -0800420}
421
422// Checks that each non-rejected content has ice-ufrag and ice-pwd set, unless
423// it's in a BUNDLE group, in which case only the BUNDLE-tag section (first
424// media section/description in the BUNDLE group) needs a ufrag and pwd.
425bool VerifyIceUfragPwdPresent(const SessionDescription* desc) {
426 const cricket::ContentGroup* bundle =
427 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton8a006912017-12-04 15:25:56 -0800428 for (const cricket::ContentInfo& content_info : desc->contents()) {
429 if (content_info.rejected) {
Steve Anton75737c02017-11-06 10:37:17 -0800430 continue;
431 }
Steve Anton8a006912017-12-04 15:25:56 -0800432 const std::string& mid = content_info.name;
433 if (bundle && bundle->HasContentName(mid) &&
434 mid != *(bundle->FirstContentName())) {
Steve Anton75737c02017-11-06 10:37:17 -0800435 // This isn't the first media section in the BUNDLE group, so it's not
436 // required to have ufrag/password, since only the ufrag/password from
437 // the first section actually get used.
438 continue;
439 }
440
441 // If the content isn't rejected or bundled into another m= section,
442 // ice-ufrag and ice-pwd must be present.
Steve Anton8a006912017-12-04 15:25:56 -0800443 const TransportInfo* tinfo = desc->GetTransportInfoByName(mid);
Steve Anton75737c02017-11-06 10:37:17 -0800444 if (!tinfo) {
445 // Something is not right.
Mirko Bonadei675513b2017-11-09 11:09:25 +0100446 RTC_LOG(LS_ERROR) << kInvalidSdp;
Steve Anton75737c02017-11-06 10:37:17 -0800447 return false;
448 }
449 if (tinfo->description.ice_ufrag.empty() ||
450 tinfo->description.ice_pwd.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100451 RTC_LOG(LS_ERROR) << "Session description must have ice ufrag and pwd.";
Steve Anton75737c02017-11-06 10:37:17 -0800452 return false;
453 }
454 }
455 return true;
456}
457
458bool GetTrackIdBySsrc(const SessionDescription* session_description,
459 uint32_t ssrc,
460 std::string* track_id) {
461 RTC_DCHECK(track_id != NULL);
462
Steve Antonb1c1de12017-12-21 15:14:30 -0800463 const cricket::AudioContentDescription* audio_desc =
464 cricket::GetFirstAudioContentDescription(session_description);
465 if (audio_desc) {
466 const auto* found = cricket::GetStreamBySsrc(audio_desc->streams(), ssrc);
Steve Anton75737c02017-11-06 10:37:17 -0800467 if (found) {
468 *track_id = found->id;
469 return true;
470 }
471 }
472
Steve Antonb1c1de12017-12-21 15:14:30 -0800473 const cricket::VideoContentDescription* video_desc =
474 cricket::GetFirstVideoContentDescription(session_description);
475 if (video_desc) {
476 const auto* found = cricket::GetStreamBySsrc(video_desc->streams(), ssrc);
Steve Anton75737c02017-11-06 10:37:17 -0800477 if (found) {
478 *track_id = found->id;
479 return true;
480 }
481 }
482 return false;
483}
484
485// Get the SCTP port out of a SessionDescription.
486// Return -1 if not found.
487int GetSctpPort(const SessionDescription* session_description) {
Steve Antonb1c1de12017-12-21 15:14:30 -0800488 const cricket::DataContentDescription* data_desc =
489 GetFirstDataContentDescription(session_description);
490 RTC_DCHECK(data_desc);
491 if (!data_desc) {
Steve Anton75737c02017-11-06 10:37:17 -0800492 return -1;
493 }
Steve Anton75737c02017-11-06 10:37:17 -0800494 std::string value;
495 cricket::DataCodec match_pattern(cricket::kGoogleSctpDataCodecPlType,
496 cricket::kGoogleSctpDataCodecName);
Steve Antonb1c1de12017-12-21 15:14:30 -0800497 for (const cricket::DataCodec& codec : data_desc->codecs()) {
Steve Anton75737c02017-11-06 10:37:17 -0800498 if (!codec.Matches(match_pattern)) {
499 continue;
500 }
501 if (codec.GetParam(cricket::kCodecParamPort, &value)) {
502 return rtc::FromString<int>(value);
503 }
504 }
505 return -1;
506}
507
Steve Anton75737c02017-11-06 10:37:17 -0800508// Returns true if |new_desc| requests an ICE restart (i.e., new ufrag/pwd).
509bool CheckForRemoteIceRestart(const SessionDescriptionInterface* old_desc,
510 const SessionDescriptionInterface* new_desc,
511 const std::string& content_name) {
512 if (!old_desc) {
513 return false;
514 }
515 const SessionDescription* new_sd = new_desc->description();
516 const SessionDescription* old_sd = old_desc->description();
517 const ContentInfo* cinfo = new_sd->GetContentByName(content_name);
518 if (!cinfo || cinfo->rejected) {
519 return false;
520 }
521 // If the content isn't rejected, check if ufrag and password has changed.
522 const cricket::TransportDescription* new_transport_desc =
523 new_sd->GetTransportDescriptionByName(content_name);
524 const cricket::TransportDescription* old_transport_desc =
525 old_sd->GetTransportDescriptionByName(content_name);
526 if (!new_transport_desc || !old_transport_desc) {
527 // No transport description exists. This is not an ICE restart.
528 return false;
529 }
530 if (cricket::IceCredentialsChanged(
531 old_transport_desc->ice_ufrag, old_transport_desc->ice_pwd,
532 new_transport_desc->ice_ufrag, new_transport_desc->ice_pwd)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100533 RTC_LOG(LS_INFO) << "Remote peer requests ICE restart for " << content_name
534 << ".";
Steve Anton75737c02017-11-06 10:37:17 -0800535 return true;
536 }
537 return false;
538}
539
540} // namespace
541
Henrik Boström31638672017-11-23 17:48:32 +0100542// Upon completion, posts a task to execute the callback of the
543// SetSessionDescriptionObserver asynchronously on the same thread. At this
544// point, the state of the peer connection might no longer reflect the effects
545// of the SetRemoteDescription operation, as the peer connection could have been
546// modified during the post.
547// TODO(hbos): Remove this class once we remove the version of
548// PeerConnectionInterface::SetRemoteDescription() that takes a
549// SetSessionDescriptionObserver as an argument.
550class PeerConnection::SetRemoteDescriptionObserverAdapter
551 : public rtc::RefCountedObject<SetRemoteDescriptionObserverInterface> {
552 public:
553 SetRemoteDescriptionObserverAdapter(
554 rtc::scoped_refptr<PeerConnection> pc,
555 rtc::scoped_refptr<SetSessionDescriptionObserver> wrapper)
556 : pc_(std::move(pc)), wrapper_(std::move(wrapper)) {}
557
558 // SetRemoteDescriptionObserverInterface implementation.
559 void OnSetRemoteDescriptionComplete(RTCError error) override {
560 if (error.ok())
561 pc_->PostSetSessionDescriptionSuccess(wrapper_);
562 else
563 pc_->PostSetSessionDescriptionFailure(wrapper_, error.message());
564 }
565
566 private:
567 rtc::scoped_refptr<PeerConnection> pc_;
568 rtc::scoped_refptr<SetSessionDescriptionObserver> wrapper_;
569};
570
deadbeef293e9262017-01-11 12:28:30 -0800571bool PeerConnectionInterface::RTCConfiguration::operator==(
572 const PeerConnectionInterface::RTCConfiguration& o) const {
573 // This static_assert prevents us from accidentally breaking operator==.
Steve Anton300bf8e2017-07-14 10:13:10 -0700574 // Note: Order matters! Fields must be ordered the same as RTCConfiguration.
deadbeef293e9262017-01-11 12:28:30 -0800575 struct stuff_being_tested_for_equality {
Magnus Jedvert3beb2072017-07-14 14:23:56 +0000576 IceServers servers;
Steve Anton300bf8e2017-07-14 10:13:10 -0700577 IceTransportsType type;
deadbeef293e9262017-01-11 12:28:30 -0800578 BundlePolicy bundle_policy;
579 RtcpMuxPolicy rtcp_mux_policy;
Steve Anton300bf8e2017-07-14 10:13:10 -0700580 std::vector<rtc::scoped_refptr<rtc::RTCCertificate>> certificates;
581 int ice_candidate_pool_size;
582 bool disable_ipv6;
583 bool disable_ipv6_on_wifi;
deadbeefd21eab32017-07-26 16:50:11 -0700584 int max_ipv6_networks;
Steve Anton300bf8e2017-07-14 10:13:10 -0700585 bool enable_rtp_data_channel;
586 rtc::Optional<int> screencast_min_bitrate;
587 rtc::Optional<bool> combined_audio_video_bwe;
588 rtc::Optional<bool> enable_dtls_srtp;
deadbeef293e9262017-01-11 12:28:30 -0800589 TcpCandidatePolicy tcp_candidate_policy;
590 CandidateNetworkPolicy candidate_network_policy;
591 int audio_jitter_buffer_max_packets;
592 bool audio_jitter_buffer_fast_accelerate;
593 int ice_connection_receiving_timeout;
594 int ice_backup_candidate_pair_ping_interval;
595 ContinualGatheringPolicy continual_gathering_policy;
deadbeef293e9262017-01-11 12:28:30 -0800596 bool prioritize_most_likely_ice_candidate_pairs;
597 struct cricket::MediaConfig media_config;
deadbeef293e9262017-01-11 12:28:30 -0800598 bool prune_turn_ports;
599 bool presume_writable_when_fully_relayed;
600 bool enable_ice_renomination;
601 bool redetermine_role_on_ice_restart;
skvlad51072462017-02-02 11:50:14 -0800602 rtc::Optional<int> ice_check_min_interval;
Steve Anton300bf8e2017-07-14 10:13:10 -0700603 rtc::Optional<rtc::IntervalRange> ice_regather_interval_range;
Jonas Orelandbdcee282017-10-10 14:01:40 +0200604 webrtc::TurnCustomizer* turn_customizer;
Steve Anton79e79602017-11-20 10:25:56 -0800605 SdpSemantics sdp_semantics;
deadbeef293e9262017-01-11 12:28:30 -0800606 };
607 static_assert(sizeof(stuff_being_tested_for_equality) == sizeof(*this),
608 "Did you add something to RTCConfiguration and forget to "
609 "update operator==?");
610 return type == o.type && servers == o.servers &&
611 bundle_policy == o.bundle_policy &&
612 rtcp_mux_policy == o.rtcp_mux_policy &&
613 tcp_candidate_policy == o.tcp_candidate_policy &&
614 candidate_network_policy == o.candidate_network_policy &&
615 audio_jitter_buffer_max_packets == o.audio_jitter_buffer_max_packets &&
616 audio_jitter_buffer_fast_accelerate ==
617 o.audio_jitter_buffer_fast_accelerate &&
618 ice_connection_receiving_timeout ==
619 o.ice_connection_receiving_timeout &&
620 ice_backup_candidate_pair_ping_interval ==
621 o.ice_backup_candidate_pair_ping_interval &&
622 continual_gathering_policy == o.continual_gathering_policy &&
623 certificates == o.certificates &&
624 prioritize_most_likely_ice_candidate_pairs ==
625 o.prioritize_most_likely_ice_candidate_pairs &&
626 media_config == o.media_config && disable_ipv6 == o.disable_ipv6 &&
zhihuangb09b3f92017-03-07 14:40:51 -0800627 disable_ipv6_on_wifi == o.disable_ipv6_on_wifi &&
deadbeefd21eab32017-07-26 16:50:11 -0700628 max_ipv6_networks == o.max_ipv6_networks &&
deadbeef293e9262017-01-11 12:28:30 -0800629 enable_rtp_data_channel == o.enable_rtp_data_channel &&
deadbeef293e9262017-01-11 12:28:30 -0800630 screencast_min_bitrate == o.screencast_min_bitrate &&
631 combined_audio_video_bwe == o.combined_audio_video_bwe &&
632 enable_dtls_srtp == o.enable_dtls_srtp &&
633 ice_candidate_pool_size == o.ice_candidate_pool_size &&
634 prune_turn_ports == o.prune_turn_ports &&
635 presume_writable_when_fully_relayed ==
636 o.presume_writable_when_fully_relayed &&
637 enable_ice_renomination == o.enable_ice_renomination &&
skvlad51072462017-02-02 11:50:14 -0800638 redetermine_role_on_ice_restart == o.redetermine_role_on_ice_restart &&
Steve Anton300bf8e2017-07-14 10:13:10 -0700639 ice_check_min_interval == o.ice_check_min_interval &&
Jonas Orelandbdcee282017-10-10 14:01:40 +0200640 ice_regather_interval_range == o.ice_regather_interval_range &&
Steve Anton79e79602017-11-20 10:25:56 -0800641 turn_customizer == o.turn_customizer &&
642 sdp_semantics == o.sdp_semantics;
deadbeef293e9262017-01-11 12:28:30 -0800643}
644
645bool PeerConnectionInterface::RTCConfiguration::operator!=(
646 const PeerConnectionInterface::RTCConfiguration& o) const {
647 return !(*this == o);
deadbeef3edec7c2016-12-10 11:44:26 -0800648}
649
zhihuang8f65cdf2016-05-06 18:40:30 -0700650// Generate a RTCP CNAME when a PeerConnection is created.
651std::string GenerateRtcpCname() {
652 std::string cname;
653 if (!rtc::CreateRandomString(kRtcpCnameLength, &cname)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100654 RTC_LOG(LS_ERROR) << "Failed to generate CNAME.";
nisseeb4ca4e2017-01-12 02:24:27 -0800655 RTC_NOTREACHED();
zhihuang8f65cdf2016-05-06 18:40:30 -0700656 }
657 return cname;
658}
659
zhihuang1c378ed2017-08-17 14:10:50 -0700660bool ValidateOfferAnswerOptions(
661 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options) {
662 return IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_audio) &&
663 IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_video);
olka3c747662017-08-17 06:50:32 -0700664}
665
zhihuang1c378ed2017-08-17 14:10:50 -0700666// From |rtc_options|, fill parts of |session_options| shared by all generated
667// m= sections (in other words, nothing that involves a map/array).
668void ExtractSharedMediaSessionOptions(
669 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options,
670 cricket::MediaSessionOptions* session_options) {
671 session_options->vad_enabled = rtc_options.voice_activity_detection;
672 session_options->bundle_enabled = rtc_options.use_rtp_mux;
673}
zhihuanga77e6bb2017-08-14 18:17:48 -0700674
zhihuang1c378ed2017-08-17 14:10:50 -0700675bool ConvertConstraintsToOfferAnswerOptions(
676 const MediaConstraintsInterface* constraints,
677 PeerConnectionInterface::RTCOfferAnswerOptions* offer_answer_options) {
olka3c747662017-08-17 06:50:32 -0700678 if (!constraints) {
679 return true;
680 }
zhihuang1c378ed2017-08-17 14:10:50 -0700681
682 bool value = false;
683 size_t mandatory_constraints_satisfied = 0;
684
685 if (FindConstraint(constraints,
686 MediaConstraintsInterface::kOfferToReceiveAudio, &value,
687 &mandatory_constraints_satisfied)) {
688 offer_answer_options->offer_to_receive_audio =
689 value ? PeerConnectionInterface::RTCOfferAnswerOptions::
690 kOfferToReceiveMediaTrue
691 : 0;
692 }
693
694 if (FindConstraint(constraints,
695 MediaConstraintsInterface::kOfferToReceiveVideo, &value,
696 &mandatory_constraints_satisfied)) {
697 offer_answer_options->offer_to_receive_video =
698 value ? PeerConnectionInterface::RTCOfferAnswerOptions::
699 kOfferToReceiveMediaTrue
700 : 0;
701 }
702 if (FindConstraint(constraints,
703 MediaConstraintsInterface::kVoiceActivityDetection, &value,
704 &mandatory_constraints_satisfied)) {
705 offer_answer_options->voice_activity_detection = value;
706 }
707 if (FindConstraint(constraints, MediaConstraintsInterface::kUseRtpMux, &value,
708 &mandatory_constraints_satisfied)) {
709 offer_answer_options->use_rtp_mux = value;
710 }
711 if (FindConstraint(constraints, MediaConstraintsInterface::kIceRestart,
712 &value, &mandatory_constraints_satisfied)) {
713 offer_answer_options->ice_restart = value;
714 }
715
deadbeefab9b2d12015-10-14 11:33:11 -0700716 return mandatory_constraints_satisfied == constraints->GetMandatory().size();
717}
718
zhihuang38ede132017-06-15 12:52:32 -0700719PeerConnection::PeerConnection(PeerConnectionFactory* factory,
720 std::unique_ptr<RtcEventLog> event_log,
721 std::unique_ptr<Call> call)
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000722 : factory_(factory),
zhihuang38ede132017-06-15 12:52:32 -0700723 event_log_(std::move(event_log)),
zhihuang8f65cdf2016-05-06 18:40:30 -0700724 rtcp_cname_(GenerateRtcpCname()),
deadbeefab9b2d12015-10-14 11:33:11 -0700725 local_streams_(StreamCollection::Create()),
zhihuang38ede132017-06-15 12:52:32 -0700726 remote_streams_(StreamCollection::Create()),
727 call_(std::move(call)) {}
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000728
729PeerConnection::~PeerConnection() {
Peter Boström1a9d6152015-12-08 22:15:17 +0100730 TRACE_EVENT0("webrtc", "PeerConnection::~PeerConnection");
Steve Anton4171afb2017-11-20 10:20:22 -0800731 RTC_DCHECK_RUN_ON(signaling_thread());
732
Steve Anton8af21862017-12-15 11:20:13 -0800733 // Need to stop transceivers before destroying the stats collector because
734 // AudioRtpSender has a reference to the StatsCollector it will update when
735 // stopping.
736 for (auto transceiver : transceivers_) {
737 transceiver->Stop();
738 }
Steve Anton4171afb2017-11-20 10:20:22 -0800739
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700740 stats_.reset(nullptr);
hbosb78306a2016-12-19 05:06:57 -0800741 if (stats_collector_) {
742 stats_collector_->WaitForPendingRequest();
743 stats_collector_ = nullptr;
744 }
Steve Anton75737c02017-11-06 10:37:17 -0800745
Steve Anton8af21862017-12-15 11:20:13 -0800746 // Don't destroy BaseChannels until after stats has been cleaned up so that
747 // the last stats request can still read from the channels.
748 DestroyAllChannels();
749
Mirko Bonadei675513b2017-11-09 11:09:25 +0100750 RTC_LOG(LS_INFO) << "Session: " << session_id() << " is destroyed.";
Steve Anton75737c02017-11-06 10:37:17 -0800751
752 webrtc_session_desc_factory_.reset();
753 sctp_invoker_.reset();
754 sctp_factory_.reset();
755 transport_controller_.reset();
756
deadbeef91dd5672016-05-18 16:55:30 -0700757 // port_allocator_ lives on the network thread and should be destroyed there.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700758 network_thread()->Invoke<void>(RTC_FROM_HERE,
nisseeaabdf62017-05-05 02:23:02 -0700759 [this] { port_allocator_.reset(); });
eladalon248fd4f2017-09-06 05:18:15 -0700760 // call_ and event_log_ must be destroyed on the worker thread.
Steve Anton978b8762017-09-29 12:15:02 -0700761 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
eladalon248fd4f2017-09-06 05:18:15 -0700762 call_.reset();
763 event_log_.reset();
764 });
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000765}
766
Steve Anton8af21862017-12-15 11:20:13 -0800767void PeerConnection::DestroyAllChannels() {
Steve Anton3fe1b152017-12-12 10:20:08 -0800768 // Destroy video channels first since they may have a pointer to a voice
769 // channel.
770 for (auto transceiver : transceivers_) {
771 if (transceiver->internal()->media_type() == cricket::MEDIA_TYPE_VIDEO) {
772 DestroyTransceiverChannel(transceiver);
773 }
774 }
775 for (auto transceiver : transceivers_) {
776 if (transceiver->internal()->media_type() == cricket::MEDIA_TYPE_AUDIO) {
777 DestroyTransceiverChannel(transceiver);
778 }
779 }
780 DestroyDataChannel();
781}
782
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000783bool PeerConnection::Initialize(
buildbot@webrtc.org41451d42014-05-03 05:39:45 +0000784 const PeerConnectionInterface::RTCConfiguration& configuration,
kwibergd1fe2812016-04-27 06:47:29 -0700785 std::unique_ptr<cricket::PortAllocator> allocator,
Henrik Boströmd03c23b2016-06-01 11:44:18 +0200786 std::unique_ptr<rtc::RTCCertificateGeneratorInterface> cert_generator,
deadbeef653b8e02015-11-11 12:55:10 -0800787 PeerConnectionObserver* observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100788 TRACE_EVENT0("webrtc", "PeerConnection::Initialize");
Steve Anton038834f2017-07-14 15:59:59 -0700789
790 RTCError config_error = ValidateConfiguration(configuration);
791 if (!config_error.ok()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100792 RTC_LOG(LS_ERROR) << "Invalid configuration: " << config_error.message();
Steve Anton038834f2017-07-14 15:59:59 -0700793 return false;
794 }
795
deadbeef293e9262017-01-11 12:28:30 -0800796 if (!allocator) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100797 RTC_LOG(LS_ERROR)
798 << "PeerConnection initialized without a PortAllocator? "
799 << "This shouldn't happen if using PeerConnectionFactory.";
deadbeef293e9262017-01-11 12:28:30 -0800800 return false;
801 }
Jonas Orelandbdcee282017-10-10 14:01:40 +0200802
deadbeef653b8e02015-11-11 12:55:10 -0800803 if (!observer) {
deadbeef293e9262017-01-11 12:28:30 -0800804 // TODO(deadbeef): Why do we do this?
Mirko Bonadei675513b2017-11-09 11:09:25 +0100805 RTC_LOG(LS_ERROR) << "PeerConnection initialized without a "
806 << "PeerConnectionObserver";
deadbeef653b8e02015-11-11 12:55:10 -0800807 return false;
808 }
pthatcher@webrtc.org877ac762015-02-04 22:03:09 +0000809 observer_ = observer;
kwiberg0eb15ed2015-12-17 03:04:15 -0800810 port_allocator_ = std::move(allocator);
deadbeef653b8e02015-11-11 12:55:10 -0800811
deadbeef91dd5672016-05-18 16:55:30 -0700812 // The port allocator lives on the network thread and should be initialized
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700813 // there.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700814 if (!network_thread()->Invoke<bool>(
815 RTC_FROM_HERE, rtc::Bind(&PeerConnection::InitializePortAllocator_n,
816 this, configuration))) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000817 return false;
818 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000819
Steve Anton75737c02017-11-06 10:37:17 -0800820 // RFC 3264: The numeric value of the session id and version in the
821 // o line MUST be representable with a "64 bit signed integer".
822 // Due to this constraint session id |session_id_| is max limited to
823 // LLONG_MAX.
824 session_id_ = rtc::ToString(rtc::CreateRandomId64() & LLONG_MAX);
825 transport_controller_.reset(factory_->CreateTransportController(
826 port_allocator_.get(), configuration.redetermine_role_on_ice_restart));
827 transport_controller_->SetIceRole(cricket::ICEROLE_CONTROLLED);
828 transport_controller_->SignalConnectionState.connect(
829 this, &PeerConnection::OnTransportControllerConnectionState);
830 transport_controller_->SignalGatheringState.connect(
831 this, &PeerConnection::OnTransportControllerGatheringState);
832 transport_controller_->SignalCandidatesGathered.connect(
833 this, &PeerConnection::OnTransportControllerCandidatesGathered);
834 transport_controller_->SignalCandidatesRemoved.connect(
835 this, &PeerConnection::OnTransportControllerCandidatesRemoved);
836 transport_controller_->SignalDtlsHandshakeError.connect(
837 this, &PeerConnection::OnTransportControllerDtlsHandshakeError);
838
839 sctp_factory_ = factory_->CreateSctpTransportInternalFactory();
zhihuang29ff8442016-07-27 11:07:25 -0700840
deadbeefab9b2d12015-10-14 11:33:11 -0700841 stats_.reset(new StatsCollector(this));
hbos74e1a4f2016-09-15 23:33:01 -0700842 stats_collector_ = RTCStatsCollector::Create(this);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000843
Steve Antonba818672017-11-06 10:21:57 -0800844 configuration_ = configuration;
845
Steve Anton75737c02017-11-06 10:37:17 -0800846 const PeerConnectionFactoryInterface::Options& options = factory_->options();
847
848 transport_controller_->SetSslMaxProtocolVersion(options.ssl_max_version);
849
850 // Obtain a certificate from RTCConfiguration if any were provided (optional).
851 rtc::scoped_refptr<rtc::RTCCertificate> certificate;
852 if (!configuration.certificates.empty()) {
853 // TODO(hbos,torbjorng): Decide on certificate-selection strategy instead of
854 // just picking the first one. The decision should be made based on the DTLS
855 // handshake. The DTLS negotiations need to know about all certificates.
856 certificate = configuration.certificates[0];
857 }
858
Steve Antond25da372017-11-06 14:50:29 -0800859 transport_controller_->SetIceConfig(ParseIceConfig(configuration));
Steve Anton75737c02017-11-06 10:37:17 -0800860
861 if (options.disable_encryption) {
862 dtls_enabled_ = false;
863 } else {
864 // Enable DTLS by default if we have an identity store or a certificate.
865 dtls_enabled_ = (cert_generator || certificate);
866 // |configuration| can override the default |dtls_enabled_| value.
867 if (configuration.enable_dtls_srtp) {
868 dtls_enabled_ = *(configuration.enable_dtls_srtp);
869 }
870 }
871
872 // Enable creation of RTP data channels if the kEnableRtpDataChannels is set.
873 // It takes precendence over the disable_sctp_data_channels
874 // PeerConnectionFactoryInterface::Options.
875 if (configuration.enable_rtp_data_channel) {
876 data_channel_type_ = cricket::DCT_RTP;
877 } else {
878 // DTLS has to be enabled to use SCTP.
879 if (!options.disable_sctp_data_channels && dtls_enabled_) {
880 data_channel_type_ = cricket::DCT_SCTP;
881 }
882 }
883
884 video_options_.screencast_min_bitrate_kbps =
885 configuration.screencast_min_bitrate;
886 audio_options_.combined_audio_video_bwe =
887 configuration.combined_audio_video_bwe;
888
889 audio_options_.audio_jitter_buffer_max_packets =
Oskar Sundbom9b28a032017-11-16 10:53:30 +0100890 configuration.audio_jitter_buffer_max_packets;
Steve Anton75737c02017-11-06 10:37:17 -0800891
892 audio_options_.audio_jitter_buffer_fast_accelerate =
Oskar Sundbom9b28a032017-11-16 10:53:30 +0100893 configuration.audio_jitter_buffer_fast_accelerate;
Steve Anton75737c02017-11-06 10:37:17 -0800894
895 // Whether the certificate generator/certificate is null or not determines
896 // what PeerConnectionDescriptionFactory will do, so make sure that we give it
897 // the right instructions by clearing the variables if needed.
898 if (!dtls_enabled_) {
899 cert_generator.reset();
900 certificate = nullptr;
901 } else if (certificate) {
902 // Favor generated certificate over the certificate generator.
903 cert_generator.reset();
904 }
905
906 webrtc_session_desc_factory_.reset(new WebRtcSessionDescriptionFactory(
907 signaling_thread(), channel_manager(), this, session_id(),
908 std::move(cert_generator), certificate));
909 webrtc_session_desc_factory_->SignalCertificateReady.connect(
910 this, &PeerConnection::OnCertificateReady);
911
912 if (options.disable_encryption) {
913 webrtc_session_desc_factory_->SetSdesPolicy(cricket::SEC_DISABLED);
914 }
915
916 webrtc_session_desc_factory_->set_enable_encrypted_rtp_header_extensions(
917 options.crypto_options.enable_encrypted_rtp_header_extensions);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000918
Steve Anton4171afb2017-11-20 10:20:22 -0800919 // Add default audio/video transceivers for Plan B SDP.
920 if (!IsUnifiedPlan()) {
921 transceivers_.push_back(
922 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
923 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_AUDIO)));
924 transceivers_.push_back(
925 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
926 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_VIDEO)));
927 }
928
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000929 return true;
930}
931
Steve Anton038834f2017-07-14 15:59:59 -0700932RTCError PeerConnection::ValidateConfiguration(
933 const RTCConfiguration& config) const {
934 if (config.ice_regather_interval_range &&
935 config.continual_gathering_policy == GATHER_ONCE) {
936 return RTCError(RTCErrorType::INVALID_PARAMETER,
937 "ice_regather_interval_range specified but continual "
938 "gathering policy is GATHER_ONCE");
939 }
940 return RTCError::OK();
941}
942
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000943rtc::scoped_refptr<StreamCollectionInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000944PeerConnection::local_streams() {
deadbeefab9b2d12015-10-14 11:33:11 -0700945 return local_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000946}
947
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000948rtc::scoped_refptr<StreamCollectionInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000949PeerConnection::remote_streams() {
deadbeefab9b2d12015-10-14 11:33:11 -0700950 return remote_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000951}
952
perkj@webrtc.orgc2dd5ee2014-11-04 11:31:29 +0000953bool PeerConnection::AddStream(MediaStreamInterface* local_stream) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100954 TRACE_EVENT0("webrtc", "PeerConnection::AddStream");
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000955 if (IsClosed()) {
956 return false;
957 }
deadbeefab9b2d12015-10-14 11:33:11 -0700958 if (!CanAddLocalMediaStream(local_streams_, local_stream)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000959 return false;
960 }
deadbeefab9b2d12015-10-14 11:33:11 -0700961
962 local_streams_->AddStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -0800963 MediaStreamObserver* observer = new MediaStreamObserver(local_stream);
964 observer->SignalAudioTrackAdded.connect(this,
965 &PeerConnection::OnAudioTrackAdded);
966 observer->SignalAudioTrackRemoved.connect(
967 this, &PeerConnection::OnAudioTrackRemoved);
968 observer->SignalVideoTrackAdded.connect(this,
969 &PeerConnection::OnVideoTrackAdded);
970 observer->SignalVideoTrackRemoved.connect(
971 this, &PeerConnection::OnVideoTrackRemoved);
kwibergd1fe2812016-04-27 06:47:29 -0700972 stream_observers_.push_back(std::unique_ptr<MediaStreamObserver>(observer));
deadbeefab9b2d12015-10-14 11:33:11 -0700973
deadbeefab9b2d12015-10-14 11:33:11 -0700974 for (const auto& track : local_stream->GetAudioTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -0700975 AddAudioTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -0700976 }
977 for (const auto& track : local_stream->GetVideoTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -0700978 AddVideoTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -0700979 }
980
tommi@webrtc.org03505bc2014-07-14 20:15:26 +0000981 stats_->AddStream(local_stream);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000982 observer_->OnRenegotiationNeeded();
983 return true;
984}
985
986void PeerConnection::RemoveStream(MediaStreamInterface* local_stream) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100987 TRACE_EVENT0("webrtc", "PeerConnection::RemoveStream");
korniltsev.anatolyec390b52017-07-24 17:00:25 -0700988 if (!IsClosed()) {
989 for (const auto& track : local_stream->GetAudioTracks()) {
990 RemoveAudioTrack(track.get(), local_stream);
991 }
992 for (const auto& track : local_stream->GetVideoTracks()) {
993 RemoveVideoTrack(track.get(), local_stream);
994 }
deadbeefab9b2d12015-10-14 11:33:11 -0700995 }
deadbeefab9b2d12015-10-14 11:33:11 -0700996 local_streams_->RemoveStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -0800997 stream_observers_.erase(
998 std::remove_if(
999 stream_observers_.begin(), stream_observers_.end(),
kwibergd1fe2812016-04-27 06:47:29 -07001000 [local_stream](const std::unique_ptr<MediaStreamObserver>& observer) {
deadbeefeb459812015-12-15 19:24:43 -08001001 return observer->stream()->label().compare(local_stream->label()) ==
1002 0;
1003 }),
1004 stream_observers_.end());
deadbeefab9b2d12015-10-14 11:33:11 -07001005
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001006 if (IsClosed()) {
1007 return;
1008 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001009 observer_->OnRenegotiationNeeded();
1010}
1011
deadbeefe1f9d832016-01-14 15:35:42 -08001012rtc::scoped_refptr<RtpSenderInterface> PeerConnection::AddTrack(
1013 MediaStreamTrackInterface* track,
1014 std::vector<MediaStreamInterface*> streams) {
1015 TRACE_EVENT0("webrtc", "PeerConnection::AddTrack");
Steve Antonf9381f02017-12-14 10:23:57 -08001016 std::vector<std::string> stream_labels;
1017 for (auto* stream : streams) {
1018 if (!stream) {
1019 RTC_LOG(LS_ERROR) << "Stream list has null element.";
1020 return nullptr;
1021 }
1022 stream_labels.push_back(stream->label());
1023 }
Steve Anton2d6c76a2018-01-05 17:10:52 -08001024 auto sender_or_error = AddTrack(track, stream_labels);
Steve Antonf9381f02017-12-14 10:23:57 -08001025 if (!sender_or_error.ok()) {
deadbeefe1f9d832016-01-14 15:35:42 -08001026 return nullptr;
1027 }
Steve Antonf9381f02017-12-14 10:23:57 -08001028 return sender_or_error.MoveValue();
1029}
1030
Steve Anton2d6c76a2018-01-05 17:10:52 -08001031RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::AddTrack(
Steve Antonf9381f02017-12-14 10:23:57 -08001032 rtc::scoped_refptr<MediaStreamTrackInterface> track,
1033 const std::vector<std::string>& stream_labels) {
Steve Anton2d6c76a2018-01-05 17:10:52 -08001034 TRACE_EVENT0("webrtc", "PeerConnection::AddTrack");
Steve Antonf9381f02017-12-14 10:23:57 -08001035 if (!track) {
1036 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "Track is null.");
1037 }
1038 if (!(track->kind() == MediaStreamTrackInterface::kAudioKind ||
1039 track->kind() == MediaStreamTrackInterface::kVideoKind)) {
1040 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1041 "Track has invalid kind: " + track->kind());
1042 }
1043 // TODO(bugs.webrtc.org/7932): Support adding a track to multiple streams.
1044 if (stream_labels.size() > 1u) {
1045 LOG_AND_RETURN_ERROR(
1046 RTCErrorType::UNSUPPORTED_OPERATION,
1047 "AddTrack with more than one stream is not currently supported.");
1048 }
1049 if (IsClosed()) {
1050 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
1051 "PeerConnection is closed.");
deadbeefe1f9d832016-01-14 15:35:42 -08001052 }
Steve Anton4171afb2017-11-20 10:20:22 -08001053 if (FindSenderForTrack(track)) {
Steve Antonf9381f02017-12-14 10:23:57 -08001054 LOG_AND_RETURN_ERROR(
1055 RTCErrorType::INVALID_PARAMETER,
1056 "Sender already exists for track " + track->id() + ".");
deadbeefe1f9d832016-01-14 15:35:42 -08001057 }
Steve Antonf9381f02017-12-14 10:23:57 -08001058 // TODO(bugs.webrtc.org/7933): MediaSession expects the sender to have exactly
1059 // one stream. AddTrackInternal will return an error if there is more than one
1060 // stream, but if the caller specifies none then we need to generate a random
1061 // stream label.
1062 std::vector<std::string> adjusted_stream_labels = stream_labels;
1063 if (stream_labels.empty()) {
1064 adjusted_stream_labels.push_back(rtc::CreateRandomUuid());
1065 }
1066 RTC_DCHECK_EQ(1, adjusted_stream_labels.size());
1067 auto sender_or_error =
1068 (IsUnifiedPlan() ? AddTrackUnifiedPlan(track, adjusted_stream_labels)
1069 : AddTrackPlanB(track, adjusted_stream_labels));
1070 if (sender_or_error.ok()) {
1071 observer_->OnRenegotiationNeeded();
Steve Anton43a723a2018-01-04 15:48:17 -08001072 stats_->AddTrack(track);
Steve Antonf9381f02017-12-14 10:23:57 -08001073 }
1074 return sender_or_error;
1075}
deadbeefe1f9d832016-01-14 15:35:42 -08001076
Steve Antonf9381f02017-12-14 10:23:57 -08001077RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>>
1078PeerConnection::AddTrackPlanB(
1079 rtc::scoped_refptr<MediaStreamTrackInterface> track,
1080 const std::vector<std::string>& stream_labels) {
Steve Anton02ee47c2018-01-10 16:26:06 -08001081 cricket::MediaType media_type =
1082 (track->kind() == MediaStreamTrackInterface::kAudioKind
1083 ? cricket::MEDIA_TYPE_AUDIO
1084 : cricket::MEDIA_TYPE_VIDEO);
1085 auto new_sender = CreateSender(media_type, track, stream_labels);
deadbeefe1f9d832016-01-14 15:35:42 -08001086 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
Steve Anton02ee47c2018-01-10 16:26:06 -08001087 static_cast<AudioRtpSender*>(new_sender->internal())
Steve Anton47136dd2018-01-12 10:49:35 -08001088 ->SetMediaChannel(voice_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08001089 GetAudioTransceiver()->internal()->AddSender(new_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001090 const RtpSenderInfo* sender_info =
1091 FindSenderInfo(local_audio_sender_infos_,
1092 new_sender->internal()->stream_id(), track->id());
1093 if (sender_info) {
1094 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -08001095 }
Steve Antonf9381f02017-12-14 10:23:57 -08001096 } else {
1097 RTC_DCHECK_EQ(MediaStreamTrackInterface::kVideoKind, track->kind());
Steve Anton02ee47c2018-01-10 16:26:06 -08001098 static_cast<VideoRtpSender*>(new_sender->internal())
Steve Anton47136dd2018-01-12 10:49:35 -08001099 ->SetMediaChannel(video_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08001100 GetVideoTransceiver()->internal()->AddSender(new_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001101 const RtpSenderInfo* sender_info =
1102 FindSenderInfo(local_video_sender_infos_,
1103 new_sender->internal()->stream_id(), track->id());
1104 if (sender_info) {
1105 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -08001106 }
deadbeefe1f9d832016-01-14 15:35:42 -08001107 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001108 return rtc::scoped_refptr<RtpSenderInterface>(new_sender);
Steve Antonf9381f02017-12-14 10:23:57 -08001109}
deadbeefe1f9d832016-01-14 15:35:42 -08001110
Steve Antonf9381f02017-12-14 10:23:57 -08001111RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>>
1112PeerConnection::AddTrackUnifiedPlan(
1113 rtc::scoped_refptr<MediaStreamTrackInterface> track,
1114 const std::vector<std::string>& stream_labels) {
1115 auto transceiver = FindFirstTransceiverForAddedTrack(track);
1116 if (transceiver) {
1117 if (transceiver->direction() == RtpTransceiverDirection::kRecvOnly) {
1118 transceiver->SetDirection(RtpTransceiverDirection::kSendRecv);
1119 } else if (transceiver->direction() == RtpTransceiverDirection::kInactive) {
1120 transceiver->SetDirection(RtpTransceiverDirection::kSendOnly);
1121 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001122 transceiver->sender()->SetTrack(track);
1123 transceiver->internal()->sender_internal()->set_stream_ids(stream_labels);
Steve Antonf9381f02017-12-14 10:23:57 -08001124 } else {
1125 cricket::MediaType media_type =
1126 (track->kind() == MediaStreamTrackInterface::kAudioKind
1127 ? cricket::MEDIA_TYPE_AUDIO
1128 : cricket::MEDIA_TYPE_VIDEO);
Steve Anton02ee47c2018-01-10 16:26:06 -08001129 auto sender = CreateSender(media_type, track, stream_labels);
1130 auto receiver = CreateReceiver(media_type, rtc::CreateRandomUuid());
1131 transceiver = CreateAndAddTransceiver(sender, receiver);
Steve Antonf9381f02017-12-14 10:23:57 -08001132 transceiver->internal()->set_created_by_addtrack(true);
1133 transceiver->SetDirection(RtpTransceiverDirection::kSendRecv);
1134 }
Steve Antonf9381f02017-12-14 10:23:57 -08001135 return transceiver->sender();
1136}
1137
1138rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1139PeerConnection::FindFirstTransceiverForAddedTrack(
1140 rtc::scoped_refptr<MediaStreamTrackInterface> track) {
1141 RTC_DCHECK(track);
1142 for (auto transceiver : transceivers_) {
1143 if (!transceiver->sender()->track() &&
1144 cricket::MediaTypeToString(transceiver->internal()->media_type()) ==
1145 track->kind() &&
1146 !transceiver->internal()->has_ever_been_used_to_send()) {
1147 return transceiver;
1148 }
1149 }
1150 return nullptr;
deadbeefe1f9d832016-01-14 15:35:42 -08001151}
1152
1153bool PeerConnection::RemoveTrack(RtpSenderInterface* sender) {
1154 TRACE_EVENT0("webrtc", "PeerConnection::RemoveTrack");
Steve Antonf9381f02017-12-14 10:23:57 -08001155 return RemoveTrackInternal(sender).ok();
1156}
1157
1158RTCError PeerConnection::RemoveTrackInternal(
1159 rtc::scoped_refptr<RtpSenderInterface> sender) {
1160 if (!sender) {
1161 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "Sender is null.");
1162 }
deadbeefe1f9d832016-01-14 15:35:42 -08001163 if (IsClosed()) {
Steve Antonf9381f02017-12-14 10:23:57 -08001164 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
1165 "PeerConnection is closed.");
deadbeefe1f9d832016-01-14 15:35:42 -08001166 }
Steve Antonf9381f02017-12-14 10:23:57 -08001167 if (IsUnifiedPlan()) {
1168 auto transceiver = FindTransceiverBySender(sender);
1169 if (!transceiver || !sender->track()) {
1170 return RTCError::OK();
1171 }
1172 sender->SetTrack(nullptr);
1173 if (transceiver->direction() == RtpTransceiverDirection::kSendRecv) {
1174 transceiver->internal()->SetDirection(RtpTransceiverDirection::kRecvOnly);
1175 } else if (transceiver->direction() == RtpTransceiverDirection::kSendOnly) {
1176 transceiver->internal()->SetDirection(RtpTransceiverDirection::kInactive);
1177 }
Steve Anton4171afb2017-11-20 10:20:22 -08001178 } else {
Steve Antonf9381f02017-12-14 10:23:57 -08001179 bool removed;
1180 if (sender->media_type() == cricket::MEDIA_TYPE_AUDIO) {
1181 removed = GetAudioTransceiver()->internal()->RemoveSender(sender);
1182 } else {
1183 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, sender->media_type());
1184 removed = GetVideoTransceiver()->internal()->RemoveSender(sender);
1185 }
1186 if (!removed) {
1187 LOG_AND_RETURN_ERROR(
1188 RTCErrorType::INVALID_PARAMETER,
1189 "Couldn't find sender " + sender->id() + " to remove.");
1190 }
Steve Anton4171afb2017-11-20 10:20:22 -08001191 }
deadbeefe1f9d832016-01-14 15:35:42 -08001192 observer_->OnRenegotiationNeeded();
Steve Antonf9381f02017-12-14 10:23:57 -08001193 return RTCError::OK();
1194}
1195
1196rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1197PeerConnection::FindTransceiverBySender(
1198 rtc::scoped_refptr<RtpSenderInterface> sender) {
1199 for (auto transceiver : transceivers_) {
1200 if (transceiver->sender() == sender) {
1201 return transceiver;
1202 }
1203 }
1204 return nullptr;
deadbeefe1f9d832016-01-14 15:35:42 -08001205}
1206
Steve Anton9158ef62017-11-27 13:01:52 -08001207RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1208PeerConnection::AddTransceiver(
1209 rtc::scoped_refptr<MediaStreamTrackInterface> track) {
1210 return AddTransceiver(track, RtpTransceiverInit());
1211}
1212
1213RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1214PeerConnection::AddTransceiver(
1215 rtc::scoped_refptr<MediaStreamTrackInterface> track,
1216 const RtpTransceiverInit& init) {
1217 if (!IsUnifiedPlan()) {
1218 LOG_AND_RETURN_ERROR(
1219 RTCErrorType::INTERNAL_ERROR,
1220 "AddTransceiver only supported when Unified Plan is enabled.");
1221 }
1222 if (!track) {
1223 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "track is null");
1224 }
1225 cricket::MediaType media_type;
1226 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
1227 media_type = cricket::MEDIA_TYPE_AUDIO;
1228 } else if (track->kind() == MediaStreamTrackInterface::kVideoKind) {
1229 media_type = cricket::MEDIA_TYPE_VIDEO;
1230 } else {
1231 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1232 "Track kind is not audio or video");
1233 }
1234 return AddTransceiver(media_type, track, init);
1235}
1236
1237RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1238PeerConnection::AddTransceiver(cricket::MediaType media_type) {
1239 return AddTransceiver(media_type, RtpTransceiverInit());
1240}
1241
1242RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1243PeerConnection::AddTransceiver(cricket::MediaType media_type,
1244 const RtpTransceiverInit& init) {
1245 if (!IsUnifiedPlan()) {
1246 LOG_AND_RETURN_ERROR(
1247 RTCErrorType::INTERNAL_ERROR,
1248 "AddTransceiver only supported when Unified Plan is enabled.");
1249 }
1250 if (!(media_type == cricket::MEDIA_TYPE_AUDIO ||
1251 media_type == cricket::MEDIA_TYPE_VIDEO)) {
1252 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1253 "media type is not audio or video");
1254 }
1255 return AddTransceiver(media_type, nullptr, init);
1256}
1257
1258RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1259PeerConnection::AddTransceiver(
1260 cricket::MediaType media_type,
1261 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Steve Anton22da89f2018-01-25 13:58:07 -08001262 const RtpTransceiverInit& init,
1263 bool fire_callback) {
Steve Anton9158ef62017-11-27 13:01:52 -08001264 RTC_DCHECK((media_type == cricket::MEDIA_TYPE_AUDIO ||
1265 media_type == cricket::MEDIA_TYPE_VIDEO));
1266 if (track) {
1267 RTC_DCHECK_EQ(media_type,
1268 (track->kind() == MediaStreamTrackInterface::kAudioKind
1269 ? cricket::MEDIA_TYPE_AUDIO
1270 : cricket::MEDIA_TYPE_VIDEO));
1271 }
1272
1273 // TODO(bugs.webrtc.org/7600): Verify init.
1274
Steve Anton02ee47c2018-01-10 16:26:06 -08001275 if (init.stream_labels.size() > 1u) {
1276 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
1277 "More than one stream is not yet supported.");
Steve Antonf9381f02017-12-14 10:23:57 -08001278 }
1279
Steve Anton02ee47c2018-01-10 16:26:06 -08001280 std::vector<std::string> stream_labels = {!init.stream_labels.empty()
1281 ? init.stream_labels[0]
1282 : rtc::CreateRandomUuid()};
1283
1284 auto sender = CreateSender(media_type, track, stream_labels);
1285 auto receiver = CreateReceiver(media_type, rtc::CreateRandomUuid());
1286 auto transceiver = CreateAndAddTransceiver(sender, receiver);
1287 transceiver->internal()->set_direction(init.direction);
1288
Steve Anton22da89f2018-01-25 13:58:07 -08001289 if (fire_callback) {
1290 observer_->OnRenegotiationNeeded();
1291 }
Steve Antonf9381f02017-12-14 10:23:57 -08001292
1293 return rtc::scoped_refptr<RtpTransceiverInterface>(transceiver);
1294}
1295
Steve Anton02ee47c2018-01-10 16:26:06 -08001296rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
1297PeerConnection::CreateSender(
1298 cricket::MediaType media_type,
1299 rtc::scoped_refptr<MediaStreamTrackInterface> track,
1300 const std::vector<std::string>& stream_labels) {
Steve Anton9158ef62017-11-27 13:01:52 -08001301 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> sender;
Steve Anton02ee47c2018-01-10 16:26:06 -08001302 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
1303 RTC_DCHECK(!track ||
1304 (track->kind() == MediaStreamTrackInterface::kAudioKind));
1305 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
1306 signaling_thread(),
Steve Anton47136dd2018-01-12 10:49:35 -08001307 new AudioRtpSender(worker_thread(),
1308 static_cast<AudioTrackInterface*>(track.get()),
Steve Anton02ee47c2018-01-10 16:26:06 -08001309 stream_labels, stats_.get()));
1310 } else {
1311 RTC_DCHECK_EQ(media_type, cricket::MEDIA_TYPE_VIDEO);
1312 RTC_DCHECK(!track ||
1313 (track->kind() == MediaStreamTrackInterface::kVideoKind));
1314 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
1315 signaling_thread(),
Steve Anton47136dd2018-01-12 10:49:35 -08001316 new VideoRtpSender(worker_thread(),
1317 static_cast<VideoTrackInterface*>(track.get()),
Steve Anton02ee47c2018-01-10 16:26:06 -08001318 stream_labels));
1319 }
1320 sender->internal()->set_stream_ids(stream_labels);
1321 return sender;
1322}
1323
1324rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1325PeerConnection::CreateReceiver(cricket::MediaType media_type,
1326 const std::string& receiver_id) {
Steve Anton9158ef62017-11-27 13:01:52 -08001327 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1328 receiver;
Steve Anton9158ef62017-11-27 13:01:52 -08001329 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton9158ef62017-11-27 13:01:52 -08001330 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
Steve Anton60776752018-01-10 11:51:34 -08001331 signaling_thread(),
Steve Antond3679212018-01-17 17:41:02 -08001332 new AudioRtpReceiver(worker_thread(), receiver_id, {}));
Steve Anton9158ef62017-11-27 13:01:52 -08001333 } else {
Steve Anton02ee47c2018-01-10 16:26:06 -08001334 RTC_DCHECK_EQ(media_type, cricket::MEDIA_TYPE_VIDEO);
Steve Anton9158ef62017-11-27 13:01:52 -08001335 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
1336 signaling_thread(),
Steve Antond3679212018-01-17 17:41:02 -08001337 new VideoRtpReceiver(worker_thread(), receiver_id, {}));
Steve Anton9158ef62017-11-27 13:01:52 -08001338 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001339 return receiver;
1340}
1341
1342rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1343PeerConnection::CreateAndAddTransceiver(
1344 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> sender,
1345 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1346 receiver) {
1347 auto transceiver = RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1348 signaling_thread(), new RtpTransceiver(sender, receiver));
Steve Anton9158ef62017-11-27 13:01:52 -08001349 transceivers_.push_back(transceiver);
Steve Antonf9381f02017-12-14 10:23:57 -08001350 return transceiver;
Steve Anton9158ef62017-11-27 13:01:52 -08001351}
1352
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001353rtc::scoped_refptr<DtmfSenderInterface> PeerConnection::CreateDtmfSender(
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001354 AudioTrackInterface* track) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001355 TRACE_EVENT0("webrtc", "PeerConnection::CreateDtmfSender");
zhihuang29ff8442016-07-27 11:07:25 -07001356 if (IsClosed()) {
1357 return nullptr;
1358 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001359 if (!track) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001360 RTC_LOG(LS_ERROR) << "CreateDtmfSender - track is NULL.";
deadbeef20cb0c12017-02-01 20:27:00 -08001361 return nullptr;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001362 }
Steve Anton4171afb2017-11-20 10:20:22 -08001363 auto track_sender = FindSenderForTrack(track);
1364 if (!track_sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001365 RTC_LOG(LS_ERROR) << "CreateDtmfSender called with a non-added track.";
deadbeef20cb0c12017-02-01 20:27:00 -08001366 return nullptr;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001367 }
1368
Steve Anton4171afb2017-11-20 10:20:22 -08001369 return track_sender->GetDtmfSender();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001370}
1371
deadbeeffac06552015-11-25 11:26:01 -08001372rtc::scoped_refptr<RtpSenderInterface> PeerConnection::CreateSender(
deadbeefbd7d8f72015-12-18 16:58:44 -08001373 const std::string& kind,
1374 const std::string& stream_id) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001375 TRACE_EVENT0("webrtc", "PeerConnection::CreateSender");
zhihuang29ff8442016-07-27 11:07:25 -07001376 if (IsClosed()) {
1377 return nullptr;
1378 }
Steve Anton4171afb2017-11-20 10:20:22 -08001379
Steve Anton02ee47c2018-01-10 16:26:06 -08001380 std::vector<std::string> stream_labels;
1381 if (!stream_id.empty()) {
1382 stream_labels.push_back(stream_id);
1383 }
1384
Steve Anton4171afb2017-11-20 10:20:22 -08001385 // TODO(steveanton): Move construction of the RtpSenders to RtpTransceiver.
deadbeefa601f5c2016-06-06 14:27:39 -07001386 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender;
deadbeeffac06552015-11-25 11:26:01 -08001387 if (kind == MediaStreamTrackInterface::kAudioKind) {
Steve Anton47136dd2018-01-12 10:49:35 -08001388 auto* audio_sender = new AudioRtpSender(worker_thread(), nullptr,
1389 stream_labels, stats_.get());
1390 audio_sender->SetMediaChannel(voice_media_channel());
deadbeefa601f5c2016-06-06 14:27:39 -07001391 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton02ee47c2018-01-10 16:26:06 -08001392 signaling_thread(), audio_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001393 GetAudioTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 11:26:01 -08001394 } else if (kind == MediaStreamTrackInterface::kVideoKind) {
Steve Anton47136dd2018-01-12 10:49:35 -08001395 auto* video_sender =
1396 new VideoRtpSender(worker_thread(), nullptr, stream_labels);
1397 video_sender->SetMediaChannel(video_media_channel());
deadbeefa601f5c2016-06-06 14:27:39 -07001398 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton02ee47c2018-01-10 16:26:06 -08001399 signaling_thread(), video_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001400 GetVideoTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 11:26:01 -08001401 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001402 RTC_LOG(LS_ERROR) << "CreateSender called with invalid kind: " << kind;
Steve Anton4171afb2017-11-20 10:20:22 -08001403 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08001404 }
Steve Anton4171afb2017-11-20 10:20:22 -08001405
deadbeefe1f9d832016-01-14 15:35:42 -08001406 return new_sender;
deadbeeffac06552015-11-25 11:26:01 -08001407}
1408
deadbeef70ab1a12015-09-28 16:53:55 -07001409std::vector<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::GetSenders()
1410 const {
deadbeefa601f5c2016-06-06 14:27:39 -07001411 std::vector<rtc::scoped_refptr<RtpSenderInterface>> ret;
Steve Anton4171afb2017-11-20 10:20:22 -08001412 for (auto sender : GetSendersInternal()) {
1413 ret.push_back(sender);
deadbeefa601f5c2016-06-06 14:27:39 -07001414 }
1415 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -07001416}
1417
Steve Anton4171afb2017-11-20 10:20:22 -08001418std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1419PeerConnection::GetSendersInternal() const {
1420 std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1421 all_senders;
1422 for (auto transceiver : transceivers_) {
1423 auto senders = transceiver->internal()->senders();
1424 all_senders.insert(all_senders.end(), senders.begin(), senders.end());
1425 }
1426 return all_senders;
1427}
1428
deadbeef70ab1a12015-09-28 16:53:55 -07001429std::vector<rtc::scoped_refptr<RtpReceiverInterface>>
1430PeerConnection::GetReceivers() const {
deadbeefa601f5c2016-06-06 14:27:39 -07001431 std::vector<rtc::scoped_refptr<RtpReceiverInterface>> ret;
Steve Anton4171afb2017-11-20 10:20:22 -08001432 for (const auto& receiver : GetReceiversInternal()) {
1433 ret.push_back(receiver);
deadbeefa601f5c2016-06-06 14:27:39 -07001434 }
1435 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -07001436}
1437
Steve Anton4171afb2017-11-20 10:20:22 -08001438std::vector<
1439 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1440PeerConnection::GetReceiversInternal() const {
1441 std::vector<
1442 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1443 all_receivers;
1444 for (auto transceiver : transceivers_) {
1445 auto receivers = transceiver->internal()->receivers();
1446 all_receivers.insert(all_receivers.end(), receivers.begin(),
1447 receivers.end());
1448 }
1449 return all_receivers;
1450}
1451
Steve Anton9158ef62017-11-27 13:01:52 -08001452std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
1453PeerConnection::GetTransceivers() const {
1454 RTC_DCHECK(IsUnifiedPlan());
1455 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> all_transceivers;
1456 for (auto transceiver : transceivers_) {
1457 all_transceivers.push_back(transceiver);
1458 }
1459 return all_transceivers;
1460}
1461
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001462bool PeerConnection::GetStats(StatsObserver* observer,
wu@webrtc.orgb9a088b2014-02-13 23:18:49 +00001463 MediaStreamTrackInterface* track,
1464 StatsOutputLevel level) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001465 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
deadbeef0a6c4ca2015-10-06 11:38:28 -07001466 RTC_DCHECK(signaling_thread()->IsCurrent());
nisse7ce109a2017-01-31 00:57:56 -08001467 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001468 RTC_LOG(LS_ERROR) << "GetStats - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001469 return false;
1470 }
1471
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001472 stats_->UpdateStats(level);
zhihuange9e94c32016-11-04 11:38:15 -07001473 // The StatsCollector is used to tell if a track is valid because it may
1474 // remember tracks that the PeerConnection previously removed.
1475 if (track && !stats_->IsValidTrack(track->id())) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001476 RTC_LOG(LS_WARNING) << "GetStats is called with an invalid track: "
1477 << track->id();
zhihuange9e94c32016-11-04 11:38:15 -07001478 return false;
1479 }
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001480 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_GETSTATS,
tommi@webrtc.org5b06b062014-08-15 08:38:30 +00001481 new GetStatsMsg(observer, track));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001482 return true;
1483}
1484
hbos74e1a4f2016-09-15 23:33:01 -07001485void PeerConnection::GetStats(RTCStatsCollectorCallback* callback) {
1486 RTC_DCHECK(stats_collector_);
1487 stats_collector_->GetStatsReport(callback);
1488}
1489
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001490PeerConnectionInterface::SignalingState PeerConnection::signaling_state() {
1491 return signaling_state_;
1492}
1493
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001494PeerConnectionInterface::IceConnectionState
1495PeerConnection::ice_connection_state() {
1496 return ice_connection_state_;
1497}
1498
1499PeerConnectionInterface::IceGatheringState
1500PeerConnection::ice_gathering_state() {
1501 return ice_gathering_state_;
1502}
1503
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001504rtc::scoped_refptr<DataChannelInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001505PeerConnection::CreateDataChannel(
1506 const std::string& label,
1507 const DataChannelInit* config) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001508 TRACE_EVENT0("webrtc", "PeerConnection::CreateDataChannel");
zhihuang9763d562016-08-05 11:14:50 -07001509
deadbeefab9b2d12015-10-14 11:33:11 -07001510 bool first_datachannel = !HasDataChannels();
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001511
kwibergd1fe2812016-04-27 06:47:29 -07001512 std::unique_ptr<InternalDataChannelInit> internal_config;
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00001513 if (config) {
1514 internal_config.reset(new InternalDataChannelInit(*config));
1515 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001516 rtc::scoped_refptr<DataChannelInterface> channel(
deadbeefab9b2d12015-10-14 11:33:11 -07001517 InternalCreateDataChannel(label, internal_config.get()));
1518 if (!channel.get()) {
1519 return nullptr;
1520 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001521
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001522 // Trigger the onRenegotiationNeeded event for every new RTP DataChannel, or
1523 // the first SCTP DataChannel.
Steve Anton75737c02017-11-06 10:37:17 -08001524 if (data_channel_type() == cricket::DCT_RTP || first_datachannel) {
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001525 observer_->OnRenegotiationNeeded();
1526 }
wu@webrtc.org91053e72013-08-10 07:18:04 +00001527
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001528 return DataChannelProxy::Create(signaling_thread(), channel.get());
1529}
1530
1531void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
1532 const MediaConstraintsInterface* constraints) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001533 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
Steve Anton8d3444d2017-10-20 15:30:51 -07001534
zhihuang1c378ed2017-08-17 14:10:50 -07001535 PeerConnectionInterface::RTCOfferAnswerOptions offer_answer_options;
1536 // Always create an offer even if |ConvertConstraintsToOfferAnswerOptions|
1537 // returns false for now. Because |ConvertConstraintsToOfferAnswerOptions|
1538 // compares the mandatory fields parsed with the mandatory fields added in the
1539 // |constraints| and some downstream applications might create offers with
1540 // mandatory fields which would not be parsed in the helper method. For
1541 // example, in Chromium/remoting, |kEnableDtlsSrtp| is added to the
1542 // |constraints| as a mandatory field but it is not parsed.
1543 ConvertConstraintsToOfferAnswerOptions(constraints, &offer_answer_options);
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001544
zhihuang1c378ed2017-08-17 14:10:50 -07001545 CreateOffer(observer, offer_answer_options);
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001546}
1547
1548void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
1549 const RTCOfferAnswerOptions& options) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001550 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
Steve Anton8d3444d2017-10-20 15:30:51 -07001551
nisse7ce109a2017-01-31 00:57:56 -08001552 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001553 RTC_LOG(LS_ERROR) << "CreateOffer - observer is NULL.";
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001554 return;
1555 }
deadbeefab9b2d12015-10-14 11:33:11 -07001556
Steve Anton8d3444d2017-10-20 15:30:51 -07001557 if (IsClosed()) {
1558 std::string error = "CreateOffer called when PeerConnection is closed.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001559 RTC_LOG(LS_ERROR) << error;
Steve Anton8d3444d2017-10-20 15:30:51 -07001560 PostCreateSessionDescriptionFailure(observer, error);
1561 return;
1562 }
1563
zhihuang1c378ed2017-08-17 14:10:50 -07001564 if (!ValidateOfferAnswerOptions(options)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001565 std::string error = "CreateOffer called with invalid options.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001566 RTC_LOG(LS_ERROR) << error;
deadbeefab9b2d12015-10-14 11:33:11 -07001567 PostCreateSessionDescriptionFailure(observer, error);
1568 return;
1569 }
1570
Steve Anton22da89f2018-01-25 13:58:07 -08001571 // Legacy handling for offer_to_receive_audio and offer_to_receive_video.
1572 // Specified in WebRTC section 4.4.3.2 "Legacy configuration extensions".
1573 if (IsUnifiedPlan()) {
1574 RTCError error = HandleLegacyOfferOptions(options);
1575 if (!error.ok()) {
1576 PostCreateSessionDescriptionFailure(observer, error.message());
1577 return;
1578 }
1579 }
1580
zhihuang1c378ed2017-08-17 14:10:50 -07001581 cricket::MediaSessionOptions session_options;
1582 GetOptionsForOffer(options, &session_options);
Steve Antond25da372017-11-06 14:50:29 -08001583 webrtc_session_desc_factory_->CreateOffer(observer, options, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001584}
1585
Steve Anton22da89f2018-01-25 13:58:07 -08001586RTCError PeerConnection::HandleLegacyOfferOptions(
1587 const RTCOfferAnswerOptions& options) {
1588 RTC_DCHECK(IsUnifiedPlan());
1589
1590 if (options.offer_to_receive_audio == 0) {
1591 RemoveRecvDirectionFromReceivingTransceiversOfType(
1592 cricket::MEDIA_TYPE_AUDIO);
1593 } else if (options.offer_to_receive_audio == 1) {
1594 AddUpToOneReceivingTransceiverOfType(cricket::MEDIA_TYPE_AUDIO);
1595 } else if (options.offer_to_receive_audio > 1) {
1596 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
1597 "offer_to_receive_audio > 1 is not supported.");
1598 }
1599
1600 if (options.offer_to_receive_video == 0) {
1601 RemoveRecvDirectionFromReceivingTransceiversOfType(
1602 cricket::MEDIA_TYPE_VIDEO);
1603 } else if (options.offer_to_receive_video == 1) {
1604 AddUpToOneReceivingTransceiverOfType(cricket::MEDIA_TYPE_VIDEO);
1605 } else if (options.offer_to_receive_video > 1) {
1606 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
1607 "offer_to_receive_video > 1 is not supported.");
1608 }
1609
1610 return RTCError::OK();
1611}
1612
1613void PeerConnection::RemoveRecvDirectionFromReceivingTransceiversOfType(
1614 cricket::MediaType media_type) {
1615 for (auto transceiver : GetReceivingTransceiversOfType(media_type)) {
1616 transceiver->internal()->set_direction(
1617 RtpTransceiverDirectionWithRecvSet(transceiver->direction(), false));
1618 }
1619}
1620
1621void PeerConnection::AddUpToOneReceivingTransceiverOfType(
1622 cricket::MediaType media_type) {
1623 if (GetReceivingTransceiversOfType(media_type).empty()) {
1624 RtpTransceiverInit init;
1625 init.direction = RtpTransceiverDirection::kRecvOnly;
1626 AddTransceiver(media_type, nullptr, init, /*fire_callback=*/false);
1627 }
1628}
1629
1630std::vector<rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
1631PeerConnection::GetReceivingTransceiversOfType(cricket::MediaType media_type) {
1632 std::vector<
1633 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
1634 receiving_transceivers;
1635 for (auto transceiver : transceivers_) {
1636 if (!transceiver->stopped() &&
1637 transceiver->internal()->media_type() == media_type &&
1638 RtpTransceiverDirectionHasRecv(transceiver->direction())) {
1639 receiving_transceivers.push_back(transceiver);
1640 }
1641 }
1642 return receiving_transceivers;
1643}
1644
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001645void PeerConnection::CreateAnswer(
1646 CreateSessionDescriptionObserver* observer,
1647 const MediaConstraintsInterface* constraints) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001648 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
Steve Anton8d3444d2017-10-20 15:30:51 -07001649
nisse7ce109a2017-01-31 00:57:56 -08001650 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001651 RTC_LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001652 return;
1653 }
deadbeefab9b2d12015-10-14 11:33:11 -07001654
zhihuang1c378ed2017-08-17 14:10:50 -07001655 PeerConnectionInterface::RTCOfferAnswerOptions offer_answer_options;
1656 if (!ConvertConstraintsToOfferAnswerOptions(constraints,
1657 &offer_answer_options)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001658 std::string error = "CreateAnswer called with invalid constraints.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001659 RTC_LOG(LS_ERROR) << error;
deadbeefab9b2d12015-10-14 11:33:11 -07001660 PostCreateSessionDescriptionFailure(observer, error);
1661 return;
1662 }
1663
Steve Anton8d3444d2017-10-20 15:30:51 -07001664 CreateAnswer(observer, offer_answer_options);
htaa2a49d92016-03-04 02:51:39 -08001665}
1666
1667void PeerConnection::CreateAnswer(CreateSessionDescriptionObserver* observer,
1668 const RTCOfferAnswerOptions& options) {
1669 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
nisse7ce109a2017-01-31 00:57:56 -08001670 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001671 RTC_LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
htaa2a49d92016-03-04 02:51:39 -08001672 return;
1673 }
1674
Taylor Brandstetter94d8cce2018-01-26 22:44:21 +00001675 if (IsClosed()) {
1676 std::string error = "CreateAnswer called when PeerConnection is closed.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001677 RTC_LOG(LS_ERROR) << error;
Steve Anton8d3444d2017-10-20 15:30:51 -07001678 PostCreateSessionDescriptionFailure(observer, error);
1679 return;
1680 }
1681
Taylor Brandstetter94d8cce2018-01-26 22:44:21 +00001682 if (remote_description() &&
1683 remote_description()->GetType() != SdpType::kOffer) {
1684 std::string error = "CreateAnswer called without remote offer.";
1685 RTC_LOG(LS_ERROR) << error;
1686 PostCreateSessionDescriptionFailure(observer, error);
1687 return;
1688 }
Steve Anton8d3444d2017-10-20 15:30:51 -07001689
Steve Anton22da89f2018-01-25 13:58:07 -08001690 if (IsUnifiedPlan()) {
1691 if (options.offer_to_receive_audio != RTCOfferAnswerOptions::kUndefined) {
1692 RTC_LOG(LS_WARNING) << "CreateAnswer: offer_to_receive_audio is not "
1693 "supported with Unified Plan semantics. Use the "
1694 "RtpTransceiver API instead.";
1695 }
1696 if (options.offer_to_receive_video != RTCOfferAnswerOptions::kUndefined) {
1697 RTC_LOG(LS_WARNING) << "CreateAnswer: offer_to_receive_video is not "
1698 "supported with Unified Plan semantics. Use the "
1699 "RtpTransceiver API instead.";
1700 }
1701 }
1702
htaa2a49d92016-03-04 02:51:39 -08001703 cricket::MediaSessionOptions session_options;
zhihuang1c378ed2017-08-17 14:10:50 -07001704 GetOptionsForAnswer(options, &session_options);
htaa2a49d92016-03-04 02:51:39 -08001705
Steve Antond25da372017-11-06 14:50:29 -08001706 webrtc_session_desc_factory_->CreateAnswer(observer, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001707}
1708
1709void PeerConnection::SetLocalDescription(
1710 SetSessionDescriptionObserver* observer,
1711 SessionDescriptionInterface* desc) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001712 TRACE_EVENT0("webrtc", "PeerConnection::SetLocalDescription");
Steve Anton8a006912017-12-04 15:25:56 -08001713
nisse7ce109a2017-01-31 00:57:56 -08001714 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001715 RTC_LOG(LS_ERROR) << "SetLocalDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001716 return;
1717 }
Steve Anton8a006912017-12-04 15:25:56 -08001718
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001719 if (!desc) {
1720 PostSetSessionDescriptionFailure(observer, "SessionDescription is NULL.");
1721 return;
1722 }
Steve Anton8d3444d2017-10-20 15:30:51 -07001723
Steve Antona3a92c22017-12-07 10:27:41 -08001724 SdpType type = desc->GetType();
Steve Anton8d3444d2017-10-20 15:30:51 -07001725
Steve Anton8a006912017-12-04 15:25:56 -08001726 RTCError error = ApplyLocalDescription(rtc::WrapUnique(desc));
1727 // |desc| may be destroyed at this point.
1728
1729 if (!error.ok()) {
Steve Antona3a92c22017-12-07 10:27:41 -08001730 std::ostringstream oss;
1731 oss << "Failed to set local " << SdpTypeToString(type)
1732 << " sdp: " << error.message();
1733 std::string error_message = oss.str();
Steve Anton8a006912017-12-04 15:25:56 -08001734 RTC_LOG(LS_ERROR) << error_message << " (" << error.type() << ")";
1735 PostSetSessionDescriptionFailure(observer, std::move(error_message));
Steve Anton8d3444d2017-10-20 15:30:51 -07001736 return;
1737 }
Steve Anton8a006912017-12-04 15:25:56 -08001738 RTC_DCHECK(local_description());
1739
1740 PostSetSessionDescriptionSuccess(observer);
1741
1742 // According to JSEP, after setLocalDescription, changing the candidate pool
1743 // size is not allowed, and changing the set of ICE servers will not result
1744 // in new candidates being gathered.
1745 port_allocator_->FreezeCandidatePool();
1746
1747 // MaybeStartGathering needs to be called after posting
1748 // MSG_SET_SESSIONDESCRIPTION_SUCCESS, so that we don't signal any candidates
1749 // before signaling that SetLocalDescription completed.
1750 transport_controller_->MaybeStartGathering();
1751
Steve Antona3a92c22017-12-07 10:27:41 -08001752 if (local_description()->GetType() == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08001753 // TODO(deadbeef): We already had to hop to the network thread for
1754 // MaybeStartGathering...
1755 network_thread()->Invoke<void>(
1756 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
1757 port_allocator_.get()));
1758 }
1759}
1760
1761RTCError PeerConnection::ApplyLocalDescription(
1762 std::unique_ptr<SessionDescriptionInterface> desc) {
1763 RTC_DCHECK_RUN_ON(signaling_thread());
1764 RTC_DCHECK(desc);
1765
1766 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_LOCAL);
1767 if (!error.ok()) {
1768 return error;
1769 }
Steve Anton8d3444d2017-10-20 15:30:51 -07001770
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001771 // Update stats here so that we have the most recent stats for tracks and
1772 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001773 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 15:25:56 -08001774
1775 // Update the initial_offerer flag if this session is the initial_offerer.
Steve Anton3828c062017-12-06 10:34:51 -08001776 SdpType type = desc->GetType();
Steve Anton8a006912017-12-04 15:25:56 -08001777 if (!initial_offerer_.has_value()) {
Steve Anton3828c062017-12-06 10:34:51 -08001778 initial_offerer_.emplace(type == SdpType::kOffer);
Steve Anton8a006912017-12-04 15:25:56 -08001779 if (*initial_offerer_) {
1780 transport_controller_->SetIceRole(cricket::ICEROLE_CONTROLLING);
1781 } else {
1782 transport_controller_->SetIceRole(cricket::ICEROLE_CONTROLLED);
1783 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001784 }
Steve Anton8a006912017-12-04 15:25:56 -08001785
Steve Antondcc3c022017-12-22 16:02:54 -08001786 // Take a reference to the old local description since it's used below to
1787 // compare against the new local description. When setting the new local
1788 // description, grab ownership of the replaced session description in case it
1789 // is the same as |old_local_description|, to keep it alive for the duration
1790 // of the method.
1791 const SessionDescriptionInterface* old_local_description =
1792 local_description();
1793 std::unique_ptr<SessionDescriptionInterface> replaced_local_description;
Steve Anton3828c062017-12-06 10:34:51 -08001794 if (type == SdpType::kAnswer) {
Steve Antondcc3c022017-12-22 16:02:54 -08001795 replaced_local_description = pending_local_description_
1796 ? std::move(pending_local_description_)
1797 : std::move(current_local_description_);
Steve Anton8a006912017-12-04 15:25:56 -08001798 current_local_description_ = std::move(desc);
1799 pending_local_description_ = nullptr;
1800 current_remote_description_ = std::move(pending_remote_description_);
1801 } else {
Steve Antondcc3c022017-12-22 16:02:54 -08001802 replaced_local_description = std::move(pending_local_description_);
Steve Anton8a006912017-12-04 15:25:56 -08001803 pending_local_description_ = std::move(desc);
1804 }
1805 // The session description to apply now must be accessed by
1806 // |local_description()|.
Henrik Boströmfdb92012017-11-09 19:55:44 +01001807 RTC_DCHECK(local_description());
deadbeefab9b2d12015-10-14 11:33:11 -07001808
Steve Antondcc3c022017-12-22 16:02:54 -08001809 if (IsUnifiedPlan()) {
1810 RTCError error = UpdateTransceiversAndDataChannels(
1811 cricket::CS_LOCAL, old_local_description, *local_description());
Steve Anton8a006912017-12-04 15:25:56 -08001812 if (!error.ok()) {
1813 return error;
1814 }
Steve Antondcc3c022017-12-22 16:02:54 -08001815 for (auto transceiver : transceivers_) {
1816 const ContentInfo* content =
1817 FindMediaSectionForTransceiver(transceiver, local_description());
1818 if (!content) {
1819 continue;
1820 }
1821 const MediaContentDescription* media_desc = content->media_description();
1822 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
1823 transceiver->internal()->set_current_direction(media_desc->direction());
1824 }
1825 if (content->rejected && !transceiver->stopped()) {
1826 transceiver->Stop();
1827 }
1828 }
1829 } else {
1830 // Transport and Media channels will be created only when offer is set.
1831 if (type == SdpType::kOffer) {
1832 // TODO(bugs.webrtc.org/4676) - Handle CreateChannel failure, as new local
1833 // description is applied. Restore back to old description.
1834 RTCError error = CreateChannels(*local_description()->description());
1835 if (!error.ok()) {
1836 return error;
1837 }
1838 }
Steve Anton8a006912017-12-04 15:25:56 -08001839
Steve Antondcc3c022017-12-22 16:02:54 -08001840 // Remove unused channels if MediaContentDescription is rejected.
1841 RemoveUnusedChannels(local_description()->description());
1842 }
Steve Anton8a006912017-12-04 15:25:56 -08001843
Steve Anton3828c062017-12-06 10:34:51 -08001844 error = UpdateSessionState(type, cricket::CS_LOCAL);
Steve Anton8a006912017-12-04 15:25:56 -08001845 if (!error.ok()) {
1846 return error;
1847 }
Steve Antondcc3c022017-12-22 16:02:54 -08001848
Steve Anton8a006912017-12-04 15:25:56 -08001849 if (remote_description()) {
1850 // Now that we have a local description, we can push down remote candidates.
1851 UseCandidatesInSessionDescription(remote_description());
1852 }
1853
1854 pending_ice_restarts_.clear();
1855 if (session_error() != SessionError::kNone) {
1856 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
1857 }
1858
deadbeefab9b2d12015-10-14 11:33:11 -07001859 // If setting the description decided our SSL role, allocate any necessary
1860 // SCTP sids.
1861 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08001862 if (data_channel_type() == cricket::DCT_SCTP && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001863 AllocateSctpSids(role);
1864 }
1865
Steve Antond3679212018-01-17 17:41:02 -08001866 if (IsUnifiedPlan()) {
1867 for (auto transceiver : transceivers_) {
1868 const ContentInfo* content =
1869 FindMediaSectionForTransceiver(transceiver, local_description());
1870 if (!content) {
1871 continue;
1872 }
1873 if (content->rejected && !transceiver->stopped()) {
1874 transceiver->Stop();
1875 }
Steve Anton74255ff2018-01-24 18:32:57 -08001876 const auto& streams = content->media_description()->streams();
1877 if (!content->rejected && !streams.empty()) {
Steve Antond3679212018-01-17 17:41:02 -08001878 transceiver->internal()->sender_internal()->set_stream_ids(
Steve Anton74255ff2018-01-24 18:32:57 -08001879 {streams[0].sync_label});
Steve Antond3679212018-01-17 17:41:02 -08001880 transceiver->internal()->sender_internal()->SetSsrc(
Steve Anton74255ff2018-01-24 18:32:57 -08001881 streams[0].first_ssrc());
Steve Antond3679212018-01-17 17:41:02 -08001882 }
1883 }
1884 } else {
1885 // Plan B semantics.
1886
Steve Antondcc3c022017-12-22 16:02:54 -08001887 // Update state and SSRC of local MediaStreams and DataChannels based on the
1888 // local session description.
1889 const cricket::ContentInfo* audio_content =
1890 GetFirstAudioContent(local_description()->description());
1891 if (audio_content) {
1892 if (audio_content->rejected) {
1893 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
1894 } else {
1895 const cricket::AudioContentDescription* audio_desc =
1896 audio_content->media_description()->as_audio();
1897 UpdateLocalSenders(audio_desc->streams(), audio_desc->type());
1898 }
deadbeeffaac4972015-11-12 15:33:07 -08001899 }
deadbeefab9b2d12015-10-14 11:33:11 -07001900
Steve Antondcc3c022017-12-22 16:02:54 -08001901 const cricket::ContentInfo* video_content =
1902 GetFirstVideoContent(local_description()->description());
1903 if (video_content) {
1904 if (video_content->rejected) {
1905 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
1906 } else {
1907 const cricket::VideoContentDescription* video_desc =
1908 video_content->media_description()->as_video();
1909 UpdateLocalSenders(video_desc->streams(), video_desc->type());
1910 }
deadbeeffaac4972015-11-12 15:33:07 -08001911 }
deadbeefab9b2d12015-10-14 11:33:11 -07001912 }
1913
1914 const cricket::ContentInfo* data_content =
Henrik Boströmfdb92012017-11-09 19:55:44 +01001915 GetFirstDataContent(local_description()->description());
deadbeefab9b2d12015-10-14 11:33:11 -07001916 if (data_content) {
1917 const cricket::DataContentDescription* data_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08001918 data_content->media_description()->as_data();
deadbeefab9b2d12015-10-14 11:33:11 -07001919 if (rtc::starts_with(data_desc->protocol().data(),
1920 cricket::kMediaProtocolRtpPrefix)) {
1921 UpdateLocalRtpDataChannels(data_desc->streams());
1922 }
1923 }
1924
Steve Anton8a006912017-12-04 15:25:56 -08001925 return RTCError::OK();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001926}
1927
1928void PeerConnection::SetRemoteDescription(
Henrik Boströma4ecf552017-11-23 14:17:07 +00001929 SetSessionDescriptionObserver* observer,
1930 SessionDescriptionInterface* desc) {
Henrik Boström31638672017-11-23 17:48:32 +01001931 SetRemoteDescription(
1932 std::unique_ptr<SessionDescriptionInterface>(desc),
1933 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface>(
1934 new SetRemoteDescriptionObserverAdapter(this, observer)));
1935}
1936
1937void PeerConnection::SetRemoteDescription(
1938 std::unique_ptr<SessionDescriptionInterface> desc,
1939 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface> observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001940 TRACE_EVENT0("webrtc", "PeerConnection::SetRemoteDescription");
Steve Anton8a006912017-12-04 15:25:56 -08001941
nisse7ce109a2017-01-31 00:57:56 -08001942 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001943 RTC_LOG(LS_ERROR) << "SetRemoteDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001944 return;
1945 }
Steve Anton8a006912017-12-04 15:25:56 -08001946
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001947 if (!desc) {
Henrik Boström31638672017-11-23 17:48:32 +01001948 observer->OnSetRemoteDescriptionComplete(RTCError(
Steve Anton8a006912017-12-04 15:25:56 -08001949 RTCErrorType::INVALID_PARAMETER, "SessionDescription is NULL."));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001950 return;
1951 }
Steve Anton8d3444d2017-10-20 15:30:51 -07001952
Steve Antona3a92c22017-12-07 10:27:41 -08001953 const SdpType type = desc->GetType();
Steve Anton8a006912017-12-04 15:25:56 -08001954
1955 RTCError error = ApplyRemoteDescription(std::move(desc));
1956 // |desc| may be destroyed at this point.
1957
1958 if (!error.ok()) {
Steve Antona3a92c22017-12-07 10:27:41 -08001959 std::ostringstream oss;
1960 oss << "Failed to set remote " << SdpTypeToString(type)
1961 << " sdp: " << error.message();
1962 std::string error_message = oss.str();
Steve Anton8a006912017-12-04 15:25:56 -08001963 RTC_LOG(LS_ERROR) << error_message << " (" << error.type() << ")";
Henrik Boström31638672017-11-23 17:48:32 +01001964 observer->OnSetRemoteDescriptionComplete(
Steve Anton8a006912017-12-04 15:25:56 -08001965 RTCError(error.type(), std::move(error_message)));
Steve Anton8d3444d2017-10-20 15:30:51 -07001966 return;
1967 }
1968
Steve Antona3a92c22017-12-07 10:27:41 -08001969 if (remote_description()->GetType() == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08001970 // TODO(deadbeef): We already had to hop to the network thread for
1971 // MaybeStartGathering...
1972 network_thread()->Invoke<void>(
1973 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
1974 port_allocator_.get()));
1975 }
1976
1977 observer->OnSetRemoteDescriptionComplete(RTCError::OK());
1978}
1979
1980RTCError PeerConnection::ApplyRemoteDescription(
1981 std::unique_ptr<SessionDescriptionInterface> desc) {
1982 RTC_DCHECK_RUN_ON(signaling_thread());
1983 RTC_DCHECK(desc);
1984
1985 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_REMOTE);
1986 if (!error.ok()) {
1987 return error;
1988 }
1989
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001990 // Update stats here so that we have the most recent stats for tracks and
1991 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001992 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 15:25:56 -08001993
Steve Antondcc3c022017-12-22 16:02:54 -08001994 // Take a reference to the old remote description since it's used below to
1995 // compare against the new remote description. When setting the new remote
1996 // description, grab ownership of the replaced session description in case it
1997 // is the same as |old_remote_description|, to keep it alive for the duration
1998 // of the method.
Steve Anton8a006912017-12-04 15:25:56 -08001999 const SessionDescriptionInterface* old_remote_description =
2000 remote_description();
Steve Anton8a006912017-12-04 15:25:56 -08002001 std::unique_ptr<SessionDescriptionInterface> replaced_remote_description;
Steve Anton3828c062017-12-06 10:34:51 -08002002 SdpType type = desc->GetType();
2003 if (type == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002004 replaced_remote_description = pending_remote_description_
2005 ? std::move(pending_remote_description_)
2006 : std::move(current_remote_description_);
2007 current_remote_description_ = std::move(desc);
2008 pending_remote_description_ = nullptr;
2009 current_local_description_ = std::move(pending_local_description_);
2010 } else {
2011 replaced_remote_description = std::move(pending_remote_description_);
2012 pending_remote_description_ = std::move(desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002013 }
Steve Anton8a006912017-12-04 15:25:56 -08002014 // The session description to apply now must be accessed by
2015 // |remote_description()|.
Henrik Boströmfdb92012017-11-09 19:55:44 +01002016 RTC_DCHECK(remote_description());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002017
Steve Anton8a006912017-12-04 15:25:56 -08002018 // Transport and Media channels will be created only when offer is set.
Steve Antondcc3c022017-12-22 16:02:54 -08002019 if (IsUnifiedPlan()) {
2020 RTCError error = UpdateTransceiversAndDataChannels(
2021 cricket::CS_REMOTE, old_remote_description, *remote_description());
Steve Anton8a006912017-12-04 15:25:56 -08002022 if (!error.ok()) {
2023 return error;
2024 }
Steve Antondcc3c022017-12-22 16:02:54 -08002025 } else {
2026 if (type == SdpType::kOffer) {
2027 // TODO(bugs.webrtc.org/4676) - Handle CreateChannel failure, as new local
2028 // description is applied. Restore back to old description.
2029 RTCError error = CreateChannels(*remote_description()->description());
2030 if (!error.ok()) {
2031 return error;
2032 }
2033 }
Steve Anton8a006912017-12-04 15:25:56 -08002034
Steve Antondcc3c022017-12-22 16:02:54 -08002035 // Remove unused channels if MediaContentDescription is rejected.
2036 RemoveUnusedChannels(remote_description()->description());
2037 }
Steve Anton8a006912017-12-04 15:25:56 -08002038
2039 // NOTE: Candidates allocation will be initiated only when SetLocalDescription
2040 // is called.
Steve Anton3828c062017-12-06 10:34:51 -08002041 error = UpdateSessionState(type, cricket::CS_REMOTE);
Steve Anton8a006912017-12-04 15:25:56 -08002042 if (!error.ok()) {
2043 return error;
2044 }
2045
2046 if (local_description() &&
2047 !UseCandidatesInSessionDescription(remote_description())) {
2048 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidCandidates);
2049 }
2050
2051 if (old_remote_description) {
2052 for (const cricket::ContentInfo& content :
2053 old_remote_description->description()->contents()) {
2054 // Check if this new SessionDescription contains new ICE ufrag and
2055 // password that indicates the remote peer requests an ICE restart.
2056 // TODO(deadbeef): When we start storing both the current and pending
2057 // remote description, this should reset pending_ice_restarts and compare
2058 // against the current description.
2059 if (CheckForRemoteIceRestart(old_remote_description, remote_description(),
2060 content.name)) {
Steve Anton3828c062017-12-06 10:34:51 -08002061 if (type == SdpType::kOffer) {
Steve Anton8a006912017-12-04 15:25:56 -08002062 pending_ice_restarts_.insert(content.name);
2063 }
2064 } else {
2065 // We retain all received candidates only if ICE is not restarted.
2066 // When ICE is restarted, all previous candidates belong to an old
2067 // generation and should not be kept.
2068 // TODO(deadbeef): This goes against the W3C spec which says the remote
2069 // description should only contain candidates from the last set remote
2070 // description plus any candidates added since then. We should remove
2071 // this once we're sure it won't break anything.
2072 WebRtcSessionDescriptionFactory::CopyCandidatesFromSessionDescription(
2073 old_remote_description, content.name, mutable_remote_description());
2074 }
2075 }
2076 }
2077
2078 if (session_error() != SessionError::kNone) {
2079 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
2080 }
2081
2082 // Set the the ICE connection state to connecting since the connection may
2083 // become writable with peer reflexive candidates before any remote candidate
2084 // is signaled.
2085 // TODO(pthatcher): This is a short-term solution for crbug/446908. A real fix
2086 // is to have a new signal the indicates a change in checking state from the
2087 // transport and expose a new checking() member from transport that can be
2088 // read to determine the current checking state. The existing SignalConnecting
2089 // actually means "gathering candidates", so cannot be be used here.
Steve Antona3a92c22017-12-07 10:27:41 -08002090 if (remote_description()->GetType() != SdpType::kOffer &&
Steve Anton8a006912017-12-04 15:25:56 -08002091 ice_connection_state() == PeerConnectionInterface::kIceConnectionNew) {
2092 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
2093 }
2094
deadbeefab9b2d12015-10-14 11:33:11 -07002095 // If setting the description decided our SSL role, allocate any necessary
2096 // SCTP sids.
2097 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08002098 if (data_channel_type() == cricket::DCT_SCTP && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07002099 AllocateSctpSids(role);
2100 }
2101
Steve Antondcc3c022017-12-22 16:02:54 -08002102 if (IsUnifiedPlan()) {
Steve Antonef65ef12018-01-10 17:15:20 -08002103 std::vector<TrackEvent> track_events;
Steve Antondcc3c022017-12-22 16:02:54 -08002104 for (auto transceiver : transceivers_) {
2105 const ContentInfo* content =
2106 FindMediaSectionForTransceiver(transceiver, remote_description());
2107 if (!content) {
2108 continue;
2109 }
2110 const MediaContentDescription* media_desc = content->media_description();
2111 RtpTransceiverDirection local_direction =
2112 RtpTransceiverDirectionReversed(media_desc->direction());
2113 // From the WebRTC specification, steps 2.2.8.5/6 of section 4.4.1.6 "Set
2114 // the RTCSessionDescription: If direction is sendrecv or recvonly, and
2115 // transceiver's current direction is neither sendrecv nor recvonly,
2116 // process the addition of a remote track for the media description.
2117 if (RtpTransceiverDirectionHasRecv(local_direction) &&
2118 (!transceiver->current_direction() ||
2119 !RtpTransceiverDirectionHasRecv(
Steve Anton74255ff2018-01-24 18:32:57 -08002120 *transceiver->current_direction())) &&
2121 !media_desc->streams().empty()) {
Steve Antonef65ef12018-01-10 17:15:20 -08002122 const std::string& sync_label = media_desc->streams()[0].sync_label;
2123 rtc::scoped_refptr<MediaStreamInterface> stream =
2124 remote_streams_->find(sync_label);
2125 if (!stream) {
2126 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
2127 MediaStream::Create(sync_label));
2128 remote_streams_->AddStream(stream);
2129 }
2130 transceiver->internal()->receiver_internal()->SetStreams({stream});
2131 TrackEvent track_event;
2132 track_event.receiver = transceiver->receiver();
2133 track_event.streams = transceiver->receiver()->streams();
2134 track_events.push_back(std::move(track_event));
Steve Antondcc3c022017-12-22 16:02:54 -08002135 }
2136 // If direction is sendonly or inactive, and transceiver's current
2137 // direction is neither sendonly nor inactive, process the removal of a
2138 // remote track for the media description.
2139 if (!RtpTransceiverDirectionHasRecv(local_direction) &&
Steve Antonef65ef12018-01-10 17:15:20 -08002140 (transceiver->current_direction() &&
Steve Antondcc3c022017-12-22 16:02:54 -08002141 RtpTransceiverDirectionHasRecv(*transceiver->current_direction()))) {
Steve Antonef65ef12018-01-10 17:15:20 -08002142 transceiver->internal()->receiver_internal()->SetStreams({});
Steve Antondcc3c022017-12-22 16:02:54 -08002143 }
2144 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
2145 transceiver->internal()->set_current_direction(local_direction);
2146 }
2147 if (content->rejected && !transceiver->stopped()) {
2148 transceiver->Stop();
2149 }
Steve Anton74255ff2018-01-24 18:32:57 -08002150 if (!content->rejected && !media_desc->streams().empty()) {
Steve Antond3679212018-01-17 17:41:02 -08002151 const auto& stream = content->media_description()->streams()[0];
2152 transceiver->internal()->receiver_internal()->SetupMediaChannel(
2153 stream.first_ssrc());
2154 }
Steve Antondcc3c022017-12-22 16:02:54 -08002155 }
Steve Antonef65ef12018-01-10 17:15:20 -08002156 for (auto event : track_events) {
2157 observer_->OnAddTrack(event.receiver, event.streams);
2158 }
Steve Antondcc3c022017-12-22 16:02:54 -08002159 }
2160
Henrik Boströmfdb92012017-11-09 19:55:44 +01002161 const cricket::ContentInfo* audio_content =
2162 GetFirstAudioContent(remote_description()->description());
2163 const cricket::ContentInfo* video_content =
2164 GetFirstVideoContent(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002165 const cricket::AudioContentDescription* audio_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002166 GetFirstAudioContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002167 const cricket::VideoContentDescription* video_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002168 GetFirstVideoContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002169 const cricket::DataContentDescription* data_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002170 GetFirstDataContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002171
2172 // Check if the descriptions include streams, just in case the peer supports
2173 // MSID, but doesn't indicate so with "a=msid-semantic".
Henrik Boströmfdb92012017-11-09 19:55:44 +01002174 if (remote_description()->description()->msid_supported() ||
deadbeefbda7e0b2015-12-08 17:13:40 -08002175 (audio_desc && !audio_desc->streams().empty()) ||
2176 (video_desc && !video_desc->streams().empty())) {
2177 remote_peer_supports_msid_ = true;
2178 }
deadbeefab9b2d12015-10-14 11:33:11 -07002179
2180 // We wait to signal new streams until we finish processing the description,
2181 // since only at that point will new streams have all their tracks.
2182 rtc::scoped_refptr<StreamCollection> new_streams(StreamCollection::Create());
2183
Steve Antondcc3c022017-12-22 16:02:54 -08002184 if (!IsUnifiedPlan()) {
2185 // TODO(steveanton): When removing RTP senders/receivers in response to a
2186 // rejected media section, there is some cleanup logic that expects the
2187 // voice/ video channel to still be set. But in this method the voice/video
2188 // channel would have been destroyed by the SetRemoteDescription caller
2189 // above so the cleanup that relies on them fails to run. The RemoveSenders
2190 // calls should be moved to right before the DestroyChannel calls to fix
2191 // this.
Steve Anton8d3444d2017-10-20 15:30:51 -07002192
Steve Antondcc3c022017-12-22 16:02:54 -08002193 // Find all audio rtp streams and create corresponding remote AudioTracks
2194 // and MediaStreams.
2195 if (audio_content) {
2196 if (audio_content->rejected) {
2197 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
2198 } else {
2199 bool default_audio_track_needed =
2200 !remote_peer_supports_msid_ &&
2201 RtpTransceiverDirectionHasSend(audio_desc->direction());
2202 UpdateRemoteSendersList(GetActiveStreams(audio_desc),
2203 default_audio_track_needed, audio_desc->type(),
2204 new_streams);
2205 }
deadbeeffaac4972015-11-12 15:33:07 -08002206 }
deadbeefab9b2d12015-10-14 11:33:11 -07002207
Steve Antondcc3c022017-12-22 16:02:54 -08002208 // Find all video rtp streams and create corresponding remote VideoTracks
2209 // and MediaStreams.
2210 if (video_content) {
2211 if (video_content->rejected) {
2212 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
2213 } else {
2214 bool default_video_track_needed =
2215 !remote_peer_supports_msid_ &&
2216 RtpTransceiverDirectionHasSend(video_desc->direction());
2217 UpdateRemoteSendersList(GetActiveStreams(video_desc),
2218 default_video_track_needed, video_desc->type(),
2219 new_streams);
2220 }
deadbeeffaac4972015-11-12 15:33:07 -08002221 }
deadbeefab9b2d12015-10-14 11:33:11 -07002222
Steve Antondcc3c022017-12-22 16:02:54 -08002223 // Update the DataChannels with the information from the remote peer.
2224 if (data_desc) {
2225 if (rtc::starts_with(data_desc->protocol().data(),
2226 cricket::kMediaProtocolRtpPrefix)) {
2227 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
2228 }
deadbeefab9b2d12015-10-14 11:33:11 -07002229 }
deadbeefab9b2d12015-10-14 11:33:11 -07002230
Steve Antondcc3c022017-12-22 16:02:54 -08002231 // Iterate new_streams and notify the observer about new MediaStreams.
2232 for (size_t i = 0; i < new_streams->count(); ++i) {
2233 MediaStreamInterface* new_stream = new_streams->at(i);
2234 stats_->AddStream(new_stream);
2235 observer_->OnAddStream(
2236 rtc::scoped_refptr<MediaStreamInterface>(new_stream));
2237 }
deadbeefab9b2d12015-10-14 11:33:11 -07002238
Steve Antondcc3c022017-12-22 16:02:54 -08002239 UpdateEndedRemoteMediaStreams();
2240 }
deadbeefab9b2d12015-10-14 11:33:11 -07002241
Steve Anton8a006912017-12-04 15:25:56 -08002242 return RTCError::OK();
deadbeeffc648b62015-10-13 16:42:33 -07002243}
2244
Steve Antondcc3c022017-12-22 16:02:54 -08002245RTCError PeerConnection::UpdateTransceiversAndDataChannels(
2246 cricket::ContentSource source,
2247 const SessionDescriptionInterface* old_session,
2248 const SessionDescriptionInterface& new_session) {
2249 RTC_DCHECK(IsUnifiedPlan());
2250
Steve Anton7464fca2018-01-19 11:10:37 -08002251 const cricket::ContentGroup* bundle_group = nullptr;
2252 if (new_session.GetType() == SdpType::kOffer) {
2253 auto bundle_group_or_error =
2254 GetEarlyBundleGroup(*new_session.description());
2255 if (!bundle_group_or_error.ok()) {
2256 return bundle_group_or_error.MoveError();
2257 }
2258 bundle_group = bundle_group_or_error.MoveValue();
Steve Antondcc3c022017-12-22 16:02:54 -08002259 }
Steve Antondcc3c022017-12-22 16:02:54 -08002260
2261 const ContentInfos& old_contents =
2262 (old_session ? old_session->description()->contents() : ContentInfos());
2263 const ContentInfos& new_contents = new_session.description()->contents();
2264
2265 for (size_t i = 0; i < new_contents.size(); ++i) {
2266 const cricket::ContentInfo& new_content = new_contents[i];
2267 const cricket::ContentInfo* old_content =
2268 (i < old_contents.size() ? &old_contents[i] : nullptr);
2269 cricket::MediaType media_type = new_content.media_description()->type();
2270 seen_mids_.insert(new_content.name);
2271 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
2272 media_type == cricket::MEDIA_TYPE_VIDEO) {
2273 auto transceiver_or_error =
2274 AssociateTransceiver(source, i, new_content, old_content);
2275 if (!transceiver_or_error.ok()) {
2276 return transceiver_or_error.MoveError();
2277 }
2278 auto transceiver = transceiver_or_error.MoveValue();
Steve Antondcc3c022017-12-22 16:02:54 -08002279 RTCError error =
2280 UpdateTransceiverChannel(transceiver, new_content, bundle_group);
2281 if (!error.ok()) {
2282 return error;
2283 }
2284 } else if (media_type == cricket::MEDIA_TYPE_DATA) {
Steve Antonfa2260d2017-12-28 16:38:23 -08002285 if (GetDataMid() && new_content.name != *GetDataMid()) {
2286 // Ignore all but the first data section.
2287 continue;
2288 }
2289 RTCError error = UpdateDataChannel(source, new_content, bundle_group);
2290 if (!error.ok()) {
2291 return error;
2292 }
Steve Antondcc3c022017-12-22 16:02:54 -08002293 } else {
2294 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
2295 "Unknown section type.");
2296 }
2297 }
2298
2299 return RTCError::OK();
2300}
2301
2302RTCError PeerConnection::UpdateTransceiverChannel(
2303 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2304 transceiver,
2305 const cricket::ContentInfo& content,
2306 const cricket::ContentGroup* bundle_group) {
2307 RTC_DCHECK(IsUnifiedPlan());
2308 RTC_DCHECK(transceiver);
2309 cricket::BaseChannel* channel = transceiver->internal()->channel();
2310 if (content.rejected) {
2311 if (channel) {
2312 transceiver->internal()->SetChannel(nullptr);
2313 DestroyBaseChannel(channel);
2314 }
2315 } else {
2316 if (!channel) {
2317 if (transceiver->internal()->media_type() == cricket::MEDIA_TYPE_AUDIO) {
2318 channel = CreateVoiceChannel(
2319 content.name,
2320 GetTransportNameForMediaSection(content.name, bundle_group));
2321 } else {
2322 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO,
2323 transceiver->internal()->media_type());
2324 channel = CreateVideoChannel(
2325 content.name,
2326 GetTransportNameForMediaSection(content.name, bundle_group));
2327 }
2328 if (!channel) {
2329 LOG_AND_RETURN_ERROR(
2330 RTCErrorType::INTERNAL_ERROR,
2331 "Failed to create channel for mid=" + content.name);
2332 }
2333 transceiver->internal()->SetChannel(channel);
2334 }
2335 }
2336 return RTCError::OK();
2337}
2338
Steve Antonfa2260d2017-12-28 16:38:23 -08002339RTCError PeerConnection::UpdateDataChannel(
2340 cricket::ContentSource source,
2341 const cricket::ContentInfo& content,
2342 const cricket::ContentGroup* bundle_group) {
2343 if (data_channel_type_ == cricket::DCT_NONE) {
Steve Antondbf9d032018-01-19 15:23:40 -08002344 // If data channels are disabled, ignore this media section. CreateAnswer
2345 // will take care of rejecting it.
2346 return RTCError::OK();
Steve Antonfa2260d2017-12-28 16:38:23 -08002347 }
2348 if (content.rejected) {
2349 DestroyDataChannel();
2350 } else {
2351 if (!rtp_data_channel_ && !sctp_transport_) {
2352 if (!CreateDataChannel(content.name, GetTransportNameForMediaSection(
2353 content.name, bundle_group))) {
2354 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
2355 "Failed to create data channel.");
2356 }
2357 }
2358 if (source == cricket::CS_REMOTE) {
2359 const MediaContentDescription* data_desc = content.media_description();
2360 if (data_desc && cricket::IsRtpProtocol(data_desc->protocol())) {
2361 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
2362 }
2363 }
2364 }
2365 return RTCError::OK();
2366}
2367
Steve Antondcc3c022017-12-22 16:02:54 -08002368RTCErrorOr<rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
2369PeerConnection::AssociateTransceiver(cricket::ContentSource source,
2370 size_t mline_index,
2371 const ContentInfo& content,
2372 const ContentInfo* old_content) {
2373 RTC_DCHECK(IsUnifiedPlan());
2374 // If the m= section is being recycled (rejected in previous remote
2375 // description, not rejected in current description), dissociate the currently
2376 // associated RtpTransceiver by setting its mid property to null, and discard
2377 // the mapping between the transceiver and its m= section index.
2378 if (old_content && old_content->rejected && !content.rejected) {
2379 auto old_transceiver = GetAssociatedTransceiver(old_content->name);
2380 if (old_transceiver) {
2381 old_transceiver->internal()->set_mid(rtc::nullopt);
2382 old_transceiver->internal()->set_mline_index(rtc::nullopt);
2383 }
2384 }
2385 const MediaContentDescription* media_desc = content.media_description();
2386 auto transceiver = GetAssociatedTransceiver(content.name);
2387 if (source == cricket::CS_LOCAL) {
2388 // Find the RtpTransceiver that corresponds to this m= section, using the
2389 // mapping between transceivers and m= section indices established when
2390 // creating the offer.
2391 if (!transceiver) {
2392 transceiver = GetTransceiverByMLineIndex(mline_index);
2393 }
2394 if (!transceiver) {
2395 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2396 "Unknown transceiver");
2397 }
2398 } else {
2399 RTC_DCHECK_EQ(source, cricket::CS_REMOTE);
2400 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers
2401 // of the same type...
2402 if (!transceiver &&
2403 RtpTransceiverDirectionHasRecv(media_desc->direction())) {
2404 transceiver = FindAvailableTransceiverToReceive(media_desc->type());
2405 }
2406 // If no RtpTransceiver was found in the previous step, create one with a
2407 // recvonly direction.
2408 if (!transceiver) {
Steve Anton02ee47c2018-01-10 16:26:06 -08002409 auto sender =
2410 CreateSender(media_desc->type(), nullptr, {rtc::CreateRandomUuid()});
2411 auto receiver =
2412 CreateReceiver(media_desc->type(), media_desc->streams()[0].id);
2413 transceiver = CreateAndAddTransceiver(sender, receiver);
Steve Antondcc3c022017-12-22 16:02:54 -08002414 transceiver->internal()->set_direction(
2415 RtpTransceiverDirection::kRecvOnly);
2416 }
2417 }
2418 RTC_DCHECK(transceiver);
2419 if (transceiver->internal()->media_type() != media_desc->type()) {
2420 LOG_AND_RETURN_ERROR(
2421 RTCErrorType::INVALID_PARAMETER,
2422 "Transceiver type does not match media description type.");
2423 }
2424 // Associate the found or created RtpTransceiver with the m= section by
2425 // setting the value of the RtpTransceiver's mid property to the MID of the m=
2426 // section, and establish a mapping between the transceiver and the index of
2427 // the m= section.
2428 transceiver->internal()->set_mid(content.name);
2429 transceiver->internal()->set_mline_index(mline_index);
2430 return std::move(transceiver);
2431}
2432
2433rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2434PeerConnection::GetAssociatedTransceiver(const std::string& mid) const {
2435 RTC_DCHECK(IsUnifiedPlan());
2436 for (auto transceiver : transceivers_) {
2437 if (transceiver->mid() == mid) {
2438 return transceiver;
2439 }
2440 }
2441 return nullptr;
2442}
2443
2444rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2445PeerConnection::GetTransceiverByMLineIndex(size_t mline_index) const {
2446 RTC_DCHECK(IsUnifiedPlan());
2447 for (auto transceiver : transceivers_) {
2448 if (transceiver->internal()->mline_index() == mline_index) {
2449 return transceiver;
2450 }
2451 }
2452 return nullptr;
2453}
2454
2455rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2456PeerConnection::FindAvailableTransceiverToReceive(
2457 cricket::MediaType media_type) const {
2458 RTC_DCHECK(IsUnifiedPlan());
2459 // From JSEP section 5.10 (Applying a Remote Description):
2460 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers of
2461 // the same type that were added to the PeerConnection by addTrack and are not
2462 // associated with any m= section and are not stopped, find the first such
2463 // RtpTransceiver.
2464 for (auto transceiver : transceivers_) {
2465 if (transceiver->internal()->media_type() == media_type &&
2466 transceiver->internal()->created_by_addtrack() && !transceiver->mid() &&
2467 !transceiver->stopped()) {
2468 return transceiver;
2469 }
2470 }
2471 return nullptr;
2472}
2473
Steve Antoned10bd92017-12-05 10:52:59 -08002474const cricket::ContentInfo* PeerConnection::FindMediaSectionForTransceiver(
2475 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2476 transceiver,
2477 const SessionDescriptionInterface* sdesc) const {
2478 RTC_DCHECK(transceiver);
2479 RTC_DCHECK(sdesc);
2480 if (IsUnifiedPlan()) {
2481 if (!transceiver->internal()->mid()) {
2482 // This transceiver is not associated with a media section yet.
2483 return nullptr;
2484 }
2485 return sdesc->description()->GetContentByName(
2486 *transceiver->internal()->mid());
2487 } else {
2488 // Plan B only allows at most one audio and one video section, so use the
2489 // first media section of that type.
2490 return cricket::GetFirstMediaContent(sdesc->description()->contents(),
2491 transceiver->internal()->media_type());
2492 }
2493}
2494
deadbeef46c73892016-11-16 19:42:04 -08002495PeerConnectionInterface::RTCConfiguration PeerConnection::GetConfiguration() {
2496 return configuration_;
2497}
2498
deadbeef293e9262017-01-11 12:28:30 -08002499bool PeerConnection::SetConfiguration(const RTCConfiguration& configuration,
2500 RTCError* error) {
Peter Boström1a9d6152015-12-08 22:15:17 +01002501 TRACE_EVENT0("webrtc", "PeerConnection::SetConfiguration");
deadbeef6de92f92016-12-12 18:49:32 -08002502
Steve Anton75737c02017-11-06 10:37:17 -08002503 if (local_description() && configuration.ice_candidate_pool_size !=
2504 configuration_.ice_candidate_pool_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002505 RTC_LOG(LS_ERROR) << "Can't change candidate pool size after calling "
2506 "SetLocalDescription.";
deadbeef293e9262017-01-11 12:28:30 -08002507 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00002508 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002509
deadbeef293e9262017-01-11 12:28:30 -08002510 // The simplest (and most future-compatible) way to tell if the config was
2511 // modified in an invalid way is to copy each property we do support
2512 // modifying, then use operator==. There are far more properties we don't
2513 // support modifying than those we do, and more could be added.
2514 RTCConfiguration modified_config = configuration_;
2515 modified_config.servers = configuration.servers;
2516 modified_config.type = configuration.type;
2517 modified_config.ice_candidate_pool_size =
2518 configuration.ice_candidate_pool_size;
2519 modified_config.prune_turn_ports = configuration.prune_turn_ports;
skvladd1f5fda2017-02-03 16:54:05 -08002520 modified_config.ice_check_min_interval = configuration.ice_check_min_interval;
Jonas Orelandbdcee282017-10-10 14:01:40 +02002521 modified_config.turn_customizer = configuration.turn_customizer;
deadbeef293e9262017-01-11 12:28:30 -08002522 if (configuration != modified_config) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002523 RTC_LOG(LS_ERROR) << "Modifying the configuration in an unsupported way.";
deadbeef293e9262017-01-11 12:28:30 -08002524 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
2525 }
2526
Steve Anton038834f2017-07-14 15:59:59 -07002527 // Validate the modified configuration.
2528 RTCError validate_error = ValidateConfiguration(modified_config);
2529 if (!validate_error.ok()) {
2530 return SafeSetError(std::move(validate_error), error);
2531 }
2532
deadbeef293e9262017-01-11 12:28:30 -08002533 // Note that this isn't possible through chromium, since it's an unsigned
2534 // short in WebIDL.
2535 if (configuration.ice_candidate_pool_size < 0 ||
2536 configuration.ice_candidate_pool_size > UINT16_MAX) {
2537 return SafeSetError(RTCErrorType::INVALID_RANGE, error);
2538 }
2539
2540 // Parse ICE servers before hopping to network thread.
2541 cricket::ServerAddresses stun_servers;
2542 std::vector<cricket::RelayServerConfig> turn_servers;
2543 RTCErrorType parse_error =
2544 ParseIceServers(configuration.servers, &stun_servers, &turn_servers);
2545 if (parse_error != RTCErrorType::NONE) {
2546 return SafeSetError(parse_error, error);
2547 }
2548
2549 // In theory this shouldn't fail.
2550 if (!network_thread()->Invoke<bool>(
2551 RTC_FROM_HERE,
2552 rtc::Bind(&PeerConnection::ReconfigurePortAllocator_n, this,
2553 stun_servers, turn_servers, modified_config.type,
2554 modified_config.ice_candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02002555 modified_config.prune_turn_ports,
2556 modified_config.turn_customizer))) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002557 RTC_LOG(LS_ERROR) << "Failed to apply configuration to PortAllocator.";
deadbeef293e9262017-01-11 12:28:30 -08002558 return SafeSetError(RTCErrorType::INTERNAL_ERROR, error);
2559 }
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07002560
deadbeefd1a38b52016-12-10 13:15:33 -08002561 // As described in JSEP, calling setConfiguration with new ICE servers or
2562 // candidate policy must set a "needs-ice-restart" bit so that the next offer
2563 // triggers an ICE restart which will pick up the changes.
deadbeef293e9262017-01-11 12:28:30 -08002564 if (modified_config.servers != configuration_.servers ||
2565 modified_config.type != configuration_.type ||
2566 modified_config.prune_turn_ports != configuration_.prune_turn_ports) {
Steve Antond25da372017-11-06 14:50:29 -08002567 transport_controller_->SetNeedsIceRestartFlag();
deadbeefd1a38b52016-12-10 13:15:33 -08002568 }
skvladd1f5fda2017-02-03 16:54:05 -08002569
2570 if (modified_config.ice_check_min_interval !=
2571 configuration_.ice_check_min_interval) {
Steve Antond25da372017-11-06 14:50:29 -08002572 transport_controller_->SetIceConfig(ParseIceConfig(modified_config));
skvladd1f5fda2017-02-03 16:54:05 -08002573 }
2574
deadbeef293e9262017-01-11 12:28:30 -08002575 configuration_ = modified_config;
2576 return SafeSetError(RTCErrorType::NONE, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00002577}
2578
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002579bool PeerConnection::AddIceCandidate(
2580 const IceCandidateInterface* ice_candidate) {
Peter Boström1a9d6152015-12-08 22:15:17 +01002581 TRACE_EVENT0("webrtc", "PeerConnection::AddIceCandidate");
zhihuang29ff8442016-07-27 11:07:25 -07002582 if (IsClosed()) {
2583 return false;
2584 }
Steve Antond25da372017-11-06 14:50:29 -08002585
2586 if (!remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002587 RTC_LOG(LS_ERROR) << "ProcessIceMessage: ICE candidates can't be added "
2588 << "without any remote session description.";
Steve Antond25da372017-11-06 14:50:29 -08002589 return false;
2590 }
2591
2592 if (!ice_candidate) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002593 RTC_LOG(LS_ERROR) << "ProcessIceMessage: Candidate is NULL.";
Steve Antond25da372017-11-06 14:50:29 -08002594 return false;
2595 }
2596
2597 bool valid = false;
2598 bool ready = ReadyToUseRemoteCandidate(ice_candidate, nullptr, &valid);
2599 if (!valid) {
2600 return false;
2601 }
2602
2603 // Add this candidate to the remote session description.
2604 if (!mutable_remote_description()->AddCandidate(ice_candidate)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002605 RTC_LOG(LS_ERROR) << "ProcessIceMessage: Candidate cannot be used.";
Steve Antond25da372017-11-06 14:50:29 -08002606 return false;
2607 }
2608
2609 if (ready) {
2610 return UseCandidate(ice_candidate);
2611 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002612 RTC_LOG(LS_INFO) << "ProcessIceMessage: Not ready to use candidate.";
Steve Antond25da372017-11-06 14:50:29 -08002613 return true;
2614 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002615}
2616
Honghai Zhang7fb69db2016-03-14 11:59:18 -07002617bool PeerConnection::RemoveIceCandidates(
2618 const std::vector<cricket::Candidate>& candidates) {
2619 TRACE_EVENT0("webrtc", "PeerConnection::RemoveIceCandidates");
Steve Antond25da372017-11-06 14:50:29 -08002620 if (!remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002621 RTC_LOG(LS_ERROR) << "RemoveRemoteIceCandidates: ICE candidates can't be "
2622 << "removed without any remote session description.";
Steve Antond25da372017-11-06 14:50:29 -08002623 return false;
2624 }
2625
2626 if (candidates.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002627 RTC_LOG(LS_ERROR) << "RemoveRemoteIceCandidates: candidates are empty.";
Steve Antond25da372017-11-06 14:50:29 -08002628 return false;
2629 }
2630
2631 size_t number_removed =
2632 mutable_remote_description()->RemoveCandidates(candidates);
2633 if (number_removed != candidates.size()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002634 RTC_LOG(LS_ERROR)
2635 << "RemoveRemoteIceCandidates: Failed to remove candidates. "
2636 << "Requested " << candidates.size() << " but only " << number_removed
2637 << " are removed.";
Steve Antond25da372017-11-06 14:50:29 -08002638 }
2639
2640 // Remove the candidates from the transport controller.
2641 std::string error;
2642 bool res = transport_controller_->RemoveRemoteCandidates(candidates, &error);
2643 if (!res && !error.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002644 RTC_LOG(LS_ERROR) << "Error when removing remote candidates: " << error;
Steve Antond25da372017-11-06 14:50:29 -08002645 }
2646 return true;
Honghai Zhang7fb69db2016-03-14 11:59:18 -07002647}
2648
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00002649void PeerConnection::RegisterUMAObserver(UMAObserver* observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +01002650 TRACE_EVENT0("webrtc", "PeerConnection::RegisterUmaObserver");
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00002651 uma_observer_ = observer;
guoweis@webrtc.org7169afd2014-12-04 17:59:29 +00002652
Steve Anton75737c02017-11-06 10:37:17 -08002653 if (transport_controller()) {
2654 transport_controller()->SetMetricsObserver(uma_observer_);
guoweis@webrtc.org7169afd2014-12-04 17:59:29 +00002655 }
2656
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00002657 // Send information about IPv4/IPv6 status.
deadbeef293e9262017-01-11 12:28:30 -08002658 if (uma_observer_) {
Honghai Zhangd93f50c2016-10-05 11:47:22 -07002659 port_allocator_->SetMetricsObserver(uma_observer_);
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00002660 if (port_allocator_->flags() & cricket::PORTALLOCATOR_ENABLE_IPV6) {
Guo-wei Shiehdfbe6792015-09-03 17:12:07 -07002661 uma_observer_->IncrementEnumCounter(
2662 kEnumCounterAddressFamily, kPeerConnection_IPv6,
2663 kPeerConnectionAddressFamilyCounter_Max);
mallinath@webrtc.orgb445f262014-05-23 22:19:37 +00002664 } else {
Guo-wei Shiehdfbe6792015-09-03 17:12:07 -07002665 uma_observer_->IncrementEnumCounter(
2666 kEnumCounterAddressFamily, kPeerConnection_IPv4,
2667 kPeerConnectionAddressFamilyCounter_Max);
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00002668 }
2669 }
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00002670}
2671
zstein4b979802017-06-02 14:37:37 -07002672RTCError PeerConnection::SetBitrate(const BitrateParameters& bitrate) {
Steve Anton978b8762017-09-29 12:15:02 -07002673 if (!worker_thread()->IsCurrent()) {
2674 return worker_thread()->Invoke<RTCError>(
zstein4b979802017-06-02 14:37:37 -07002675 RTC_FROM_HERE, rtc::Bind(&PeerConnection::SetBitrate, this, bitrate));
2676 }
2677
2678 const bool has_min = static_cast<bool>(bitrate.min_bitrate_bps);
2679 const bool has_current = static_cast<bool>(bitrate.current_bitrate_bps);
2680 const bool has_max = static_cast<bool>(bitrate.max_bitrate_bps);
2681 if (has_min && *bitrate.min_bitrate_bps < 0) {
2682 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2683 "min_bitrate_bps <= 0");
2684 }
2685 if (has_current) {
2686 if (has_min && *bitrate.current_bitrate_bps < *bitrate.min_bitrate_bps) {
2687 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2688 "current_bitrate_bps < min_bitrate_bps");
2689 } else if (*bitrate.current_bitrate_bps < 0) {
2690 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2691 "curent_bitrate_bps < 0");
2692 }
2693 }
2694 if (has_max) {
2695 if (has_current &&
2696 *bitrate.max_bitrate_bps < *bitrate.current_bitrate_bps) {
2697 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2698 "max_bitrate_bps < current_bitrate_bps");
2699 } else if (has_min && *bitrate.max_bitrate_bps < *bitrate.min_bitrate_bps) {
2700 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2701 "max_bitrate_bps < min_bitrate_bps");
2702 } else if (*bitrate.max_bitrate_bps < 0) {
2703 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2704 "max_bitrate_bps < 0");
2705 }
2706 }
2707
2708 Call::Config::BitrateConfigMask mask;
2709 mask.min_bitrate_bps = bitrate.min_bitrate_bps;
2710 mask.start_bitrate_bps = bitrate.current_bitrate_bps;
2711 mask.max_bitrate_bps = bitrate.max_bitrate_bps;
2712
2713 RTC_DCHECK(call_.get());
2714 call_->SetBitrateConfigMask(mask);
2715
2716 return RTCError::OK();
2717}
2718
Alex Narest78609d52017-10-20 10:37:47 +02002719void PeerConnection::SetBitrateAllocationStrategy(
2720 std::unique_ptr<rtc::BitrateAllocationStrategy>
2721 bitrate_allocation_strategy) {
2722 rtc::Thread* worker_thread = factory_->worker_thread();
2723 if (!worker_thread->IsCurrent()) {
2724 rtc::BitrateAllocationStrategy* strategy_raw =
2725 bitrate_allocation_strategy.release();
2726 auto functor = [this, strategy_raw]() {
2727 call_->SetBitrateAllocationStrategy(
2728 rtc::WrapUnique<rtc::BitrateAllocationStrategy>(strategy_raw));
2729 };
2730 worker_thread->Invoke<void>(RTC_FROM_HERE, functor);
2731 return;
2732 }
2733 RTC_DCHECK(call_.get());
2734 call_->SetBitrateAllocationStrategy(std::move(bitrate_allocation_strategy));
2735}
2736
henrika5f6bf242017-11-01 11:06:56 +01002737void PeerConnection::SetAudioPlayout(bool playout) {
2738 if (!worker_thread()->IsCurrent()) {
2739 worker_thread()->Invoke<void>(
2740 RTC_FROM_HERE,
2741 rtc::Bind(&PeerConnection::SetAudioPlayout, this, playout));
2742 return;
2743 }
2744 auto audio_state =
2745 factory_->channel_manager()->media_engine()->GetAudioState();
2746 audio_state->SetPlayout(playout);
2747}
2748
2749void PeerConnection::SetAudioRecording(bool recording) {
2750 if (!worker_thread()->IsCurrent()) {
2751 worker_thread()->Invoke<void>(
2752 RTC_FROM_HERE,
2753 rtc::Bind(&PeerConnection::SetAudioRecording, this, recording));
2754 return;
2755 }
2756 auto audio_state =
2757 factory_->channel_manager()->media_engine()->GetAudioState();
2758 audio_state->SetRecording(recording);
2759}
2760
Steve Anton8c0f7a72017-10-03 10:03:10 -07002761std::unique_ptr<rtc::SSLCertificate>
2762PeerConnection::GetRemoteAudioSSLCertificate() {
Steve Anton75737c02017-11-06 10:37:17 -08002763 if (!voice_channel()) {
Steve Anton8c0f7a72017-10-03 10:03:10 -07002764 return nullptr;
2765 }
Steve Anton75737c02017-11-06 10:37:17 -08002766 return GetRemoteSSLCertificate(voice_channel()->transport_name());
Steve Anton8c0f7a72017-10-03 10:03:10 -07002767}
2768
Zhi Huang70b820f2018-01-27 14:16:15 -08002769std::unique_ptr<rtc::SSLCertChain>
2770PeerConnection::GetRemoteAudioSSLCertChain() {
2771 if (!voice_channel()) {
2772 return nullptr;
2773 }
2774
2775 return transport_controller_->GetRemoteSSLCertChain(
2776 voice_channel()->transport_name());
2777}
2778
ivoc14d5dbe2016-07-04 07:06:55 -07002779bool PeerConnection::StartRtcEventLog(rtc::PlatformFile file,
2780 int64_t max_size_bytes) {
Elad Alon99c3fe52017-10-13 16:29:40 +02002781 // TODO(eladalon): It would be better to not allow negative values into PC.
2782 const size_t max_size = (max_size_bytes < 0)
2783 ? RtcEventLog::kUnlimitedOutput
2784 : rtc::saturated_cast<size_t>(max_size_bytes);
2785 return StartRtcEventLog(
Bjorn Tereliusde939432017-11-20 17:38:14 +01002786 rtc::MakeUnique<RtcEventLogOutputFile>(file, max_size),
2787 webrtc::RtcEventLog::kImmediateOutput);
Elad Alon99c3fe52017-10-13 16:29:40 +02002788}
2789
Bjorn Tereliusde939432017-11-20 17:38:14 +01002790bool PeerConnection::StartRtcEventLog(std::unique_ptr<RtcEventLogOutput> output,
2791 int64_t output_period_ms) {
Karl Wibergd6b48192017-10-16 23:01:06 +02002792 // TODO(eladalon): In C++14, this can be done with a lambda.
2793 struct Functor {
Bjorn Tereliusde939432017-11-20 17:38:14 +01002794 bool operator()() {
2795 return pc->StartRtcEventLog_w(std::move(output), output_period_ms);
2796 }
Karl Wibergd6b48192017-10-16 23:01:06 +02002797 PeerConnection* const pc;
2798 std::unique_ptr<RtcEventLogOutput> output;
Bjorn Tereliusde939432017-11-20 17:38:14 +01002799 const int64_t output_period_ms;
Elad Alon99c3fe52017-10-13 16:29:40 +02002800 };
Bjorn Tereliusde939432017-11-20 17:38:14 +01002801 return worker_thread()->Invoke<bool>(
2802 RTC_FROM_HERE, Functor{this, std::move(output), output_period_ms});
ivoc14d5dbe2016-07-04 07:06:55 -07002803}
2804
2805void PeerConnection::StopRtcEventLog() {
Steve Anton978b8762017-09-29 12:15:02 -07002806 worker_thread()->Invoke<void>(
ivoc14d5dbe2016-07-04 07:06:55 -07002807 RTC_FROM_HERE, rtc::Bind(&PeerConnection::StopRtcEventLog_w, this));
2808}
2809
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002810const SessionDescriptionInterface* PeerConnection::local_description() const {
Steve Anton75737c02017-11-06 10:37:17 -08002811 return pending_local_description_ ? pending_local_description_.get()
2812 : current_local_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002813}
2814
2815const SessionDescriptionInterface* PeerConnection::remote_description() const {
Steve Anton75737c02017-11-06 10:37:17 -08002816 return pending_remote_description_ ? pending_remote_description_.get()
2817 : current_remote_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002818}
2819
deadbeeffe4a8a42016-12-20 17:56:17 -08002820const SessionDescriptionInterface* PeerConnection::current_local_description()
2821 const {
Steve Anton75737c02017-11-06 10:37:17 -08002822 return current_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08002823}
2824
2825const SessionDescriptionInterface* PeerConnection::current_remote_description()
2826 const {
Steve Anton75737c02017-11-06 10:37:17 -08002827 return current_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08002828}
2829
2830const SessionDescriptionInterface* PeerConnection::pending_local_description()
2831 const {
Steve Anton75737c02017-11-06 10:37:17 -08002832 return pending_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08002833}
2834
2835const SessionDescriptionInterface* PeerConnection::pending_remote_description()
2836 const {
Steve Anton75737c02017-11-06 10:37:17 -08002837 return pending_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08002838}
2839
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002840void PeerConnection::Close() {
Peter Boström1a9d6152015-12-08 22:15:17 +01002841 TRACE_EVENT0("webrtc", "PeerConnection::Close");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002842 // Update stats here so that we have the most recent stats for tracks and
2843 // streams before the channels are closed.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00002844 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002845
Steve Anton75737c02017-11-06 10:37:17 -08002846 ChangeSignalingState(PeerConnectionInterface::kClosed);
Steve Anton3fe1b152017-12-12 10:20:08 -08002847
Steve Anton8af21862017-12-15 11:20:13 -08002848 for (auto transceiver : transceivers_) {
2849 transceiver->Stop();
2850 }
2851 DestroyAllChannels();
Steve Anton75737c02017-11-06 10:37:17 -08002852
deadbeef42a42632017-03-10 15:18:00 -08002853 network_thread()->Invoke<void>(
2854 RTC_FROM_HERE,
2855 rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
2856 port_allocator_.get()));
nisseeaabdf62017-05-05 02:23:02 -07002857
Steve Anton978b8762017-09-29 12:15:02 -07002858 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
eladalon248fd4f2017-09-06 05:18:15 -07002859 call_.reset();
2860 // The event log must outlive call (and any other object that uses it).
2861 event_log_.reset();
2862 });
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002863}
2864
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002865void PeerConnection::OnMessage(rtc::Message* msg) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002866 switch (msg->message_id) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002867 case MSG_SET_SESSIONDESCRIPTION_SUCCESS: {
2868 SetSessionDescriptionMsg* param =
2869 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
2870 param->observer->OnSuccess();
2871 delete param;
2872 break;
2873 }
2874 case MSG_SET_SESSIONDESCRIPTION_FAILED: {
2875 SetSessionDescriptionMsg* param =
2876 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
2877 param->observer->OnFailure(param->error);
2878 delete param;
2879 break;
2880 }
deadbeefab9b2d12015-10-14 11:33:11 -07002881 case MSG_CREATE_SESSIONDESCRIPTION_FAILED: {
2882 CreateSessionDescriptionMsg* param =
2883 static_cast<CreateSessionDescriptionMsg*>(msg->pdata);
2884 param->observer->OnFailure(param->error);
2885 delete param;
2886 break;
2887 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002888 case MSG_GETSTATS: {
2889 GetStatsMsg* param = static_cast<GetStatsMsg*>(msg->pdata);
nissee8abe3e2017-01-18 05:00:34 -08002890 StatsReports reports;
2891 stats_->GetStats(param->track, &reports);
2892 param->observer->OnComplete(reports);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002893 delete param;
2894 break;
2895 }
deadbeefbd292462015-12-14 18:15:29 -08002896 case MSG_FREE_DATACHANNELS: {
2897 sctp_data_channels_to_free_.clear();
2898 break;
2899 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002900 default:
nisseeb4ca4e2017-01-12 02:24:27 -08002901 RTC_NOTREACHED() << "Not implemented";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002902 break;
2903 }
2904}
2905
Steve Anton4171afb2017-11-20 10:20:22 -08002906void PeerConnection::CreateAudioReceiver(
2907 MediaStreamInterface* stream,
2908 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01002909 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
2910 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Steve Antond3679212018-01-17 17:41:02 -08002911 auto* audio_receiver = new AudioRtpReceiver(
2912 worker_thread(), remote_sender_info.sender_id, streams);
2913 audio_receiver->SetMediaChannel(voice_media_channel());
2914 audio_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
2915 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
2916 signaling_thread(), audio_receiver);
Steve Anton4171afb2017-11-20 10:20:22 -08002917 GetAudioTransceiver()->internal()->AddReceiver(receiver);
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01002918 observer_->OnAddTrack(receiver, std::move(streams));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002919}
2920
Steve Anton4171afb2017-11-20 10:20:22 -08002921void PeerConnection::CreateVideoReceiver(
2922 MediaStreamInterface* stream,
2923 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01002924 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
2925 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Steve Antond3679212018-01-17 17:41:02 -08002926 auto* video_receiver = new VideoRtpReceiver(
2927 worker_thread(), remote_sender_info.sender_id, streams);
2928 video_receiver->SetMediaChannel(video_media_channel());
2929 video_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
2930 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
2931 signaling_thread(), video_receiver);
Steve Anton4171afb2017-11-20 10:20:22 -08002932 GetVideoTransceiver()->internal()->AddReceiver(receiver);
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01002933 observer_->OnAddTrack(receiver, std::move(streams));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002934}
2935
deadbeef70ab1a12015-09-28 16:53:55 -07002936// TODO(deadbeef): Keep RtpReceivers around even if track goes away in remote
2937// description.
Henrik Boström933d8b02017-10-10 10:05:16 -07002938rtc::scoped_refptr<RtpReceiverInterface> PeerConnection::RemoveAndStopReceiver(
Steve Anton4171afb2017-11-20 10:20:22 -08002939 const RtpSenderInfo& remote_sender_info) {
2940 auto receiver = FindReceiverById(remote_sender_info.sender_id);
2941 if (!receiver) {
2942 RTC_LOG(LS_WARNING) << "RtpReceiver for track with id "
2943 << remote_sender_info.sender_id << " doesn't exist.";
Henrik Boström933d8b02017-10-10 10:05:16 -07002944 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07002945 }
Steve Anton4171afb2017-11-20 10:20:22 -08002946 if (receiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
2947 GetAudioTransceiver()->internal()->RemoveReceiver(receiver);
2948 } else {
2949 GetVideoTransceiver()->internal()->RemoveReceiver(receiver);
2950 }
Henrik Boström933d8b02017-10-10 10:05:16 -07002951 return receiver;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002952}
2953
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002954void PeerConnection::AddAudioTrack(AudioTrackInterface* track,
2955 MediaStreamInterface* stream) {
2956 RTC_DCHECK(!IsClosed());
2957 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08002958 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002959 // We already have a sender for this track, so just change the stream_id
2960 // so that it's correct in the next call to CreateOffer.
Steve Anton4171afb2017-11-20 10:20:22 -08002961 sender->internal()->set_stream_id(stream->label());
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002962 return;
2963 }
2964
2965 // Normal case; we've never seen this track before.
Steve Anton02ee47c2018-01-10 16:26:06 -08002966 auto new_sender =
2967 CreateSender(cricket::MEDIA_TYPE_AUDIO, track, {stream->label()});
2968 static_cast<AudioRtpSender*>(new_sender->internal())
Steve Anton47136dd2018-01-12 10:49:35 -08002969 ->SetMediaChannel(voice_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08002970 GetAudioTransceiver()->internal()->AddSender(new_sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002971 // If the sender has already been configured in SDP, we call SetSsrc,
2972 // which will connect the sender to the underlying transport. This can
2973 // occur if a local session description that contains the ID of the sender
2974 // is set before AddStream is called. It can also occur if the local
2975 // session description is not changed and RemoveStream is called, and
2976 // later AddStream is called again with the same stream.
Steve Anton4171afb2017-11-20 10:20:22 -08002977 const RtpSenderInfo* sender_info =
2978 FindSenderInfo(local_audio_sender_infos_, stream->label(), track->id());
2979 if (sender_info) {
2980 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002981 }
2982}
2983
2984// TODO(deadbeef): Don't destroy RtpSenders here; they should be kept around
2985// indefinitely, when we have unified plan SDP.
2986void PeerConnection::RemoveAudioTrack(AudioTrackInterface* track,
2987 MediaStreamInterface* stream) {
2988 RTC_DCHECK(!IsClosed());
2989 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08002990 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002991 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
2992 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002993 return;
2994 }
Steve Anton4171afb2017-11-20 10:20:22 -08002995 GetAudioTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002996}
2997
2998void PeerConnection::AddVideoTrack(VideoTrackInterface* track,
2999 MediaStreamInterface* stream) {
3000 RTC_DCHECK(!IsClosed());
3001 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003002 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003003 // We already have a sender for this track, so just change the stream_id
3004 // so that it's correct in the next call to CreateOffer.
Steve Anton4171afb2017-11-20 10:20:22 -08003005 sender->internal()->set_stream_id(stream->label());
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003006 return;
3007 }
3008
3009 // Normal case; we've never seen this track before.
Steve Anton02ee47c2018-01-10 16:26:06 -08003010 auto new_sender =
3011 CreateSender(cricket::MEDIA_TYPE_VIDEO, track, {stream->label()});
3012 static_cast<VideoRtpSender*>(new_sender->internal())
Steve Anton47136dd2018-01-12 10:49:35 -08003013 ->SetMediaChannel(video_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08003014 GetVideoTransceiver()->internal()->AddSender(new_sender);
3015 const RtpSenderInfo* sender_info =
3016 FindSenderInfo(local_video_sender_infos_, stream->label(), track->id());
3017 if (sender_info) {
3018 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003019 }
3020}
3021
3022void PeerConnection::RemoveVideoTrack(VideoTrackInterface* track,
3023 MediaStreamInterface* stream) {
3024 RTC_DCHECK(!IsClosed());
3025 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003026 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003027 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
3028 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003029 return;
3030 }
Steve Anton4171afb2017-11-20 10:20:22 -08003031 GetVideoTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003032}
3033
Steve Antonba818672017-11-06 10:21:57 -08003034void PeerConnection::SetIceConnectionState(IceConnectionState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07003035 RTC_DCHECK(signaling_thread()->IsCurrent());
Steve Antonba818672017-11-06 10:21:57 -08003036 if (ice_connection_state_ == new_state) {
3037 return;
3038 }
3039
deadbeefcbecd352015-09-23 11:50:27 -07003040 // After transitioning to "closed", ignore any additional states from
Steve Antonba818672017-11-06 10:21:57 -08003041 // TransportController (such as "disconnected").
deadbeefab9b2d12015-10-14 11:33:11 -07003042 if (IsClosed()) {
deadbeefcbecd352015-09-23 11:50:27 -07003043 return;
3044 }
Steve Antonba818672017-11-06 10:21:57 -08003045
Mirko Bonadei675513b2017-11-09 11:09:25 +01003046 RTC_LOG(LS_INFO) << "Changing IceConnectionState " << ice_connection_state_
3047 << " => " << new_state;
Steve Antonba818672017-11-06 10:21:57 -08003048 RTC_DCHECK(ice_connection_state_ !=
3049 PeerConnectionInterface::kIceConnectionClosed);
3050
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003051 ice_connection_state_ = new_state;
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00003052 observer_->OnIceConnectionChange(ice_connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003053}
3054
3055void PeerConnection::OnIceGatheringChange(
3056 PeerConnectionInterface::IceGatheringState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07003057 RTC_DCHECK(signaling_thread()->IsCurrent());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003058 if (IsClosed()) {
3059 return;
3060 }
3061 ice_gathering_state_ = new_state;
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00003062 observer_->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003063}
3064
jbauch81bf7b02017-03-25 08:31:12 -07003065void PeerConnection::OnIceCandidate(
3066 std::unique_ptr<IceCandidateInterface> candidate) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07003067 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07003068 if (IsClosed()) {
3069 return;
3070 }
jbauch81bf7b02017-03-25 08:31:12 -07003071 observer_->OnIceCandidate(candidate.get());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003072}
3073
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003074void PeerConnection::OnIceCandidatesRemoved(
3075 const std::vector<cricket::Candidate>& candidates) {
3076 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07003077 if (IsClosed()) {
3078 return;
3079 }
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003080 observer_->OnIceCandidatesRemoved(candidates);
3081}
3082
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003083void PeerConnection::ChangeSignalingState(
3084 PeerConnectionInterface::SignalingState signaling_state) {
Steve Antonba818672017-11-06 10:21:57 -08003085 RTC_DCHECK(signaling_thread()->IsCurrent());
3086 if (signaling_state_ == signaling_state) {
3087 return;
3088 }
Mirko Bonadei675513b2017-11-09 11:09:25 +01003089 RTC_LOG(LS_INFO) << "Session: " << session_id() << " Old state: "
3090 << GetSignalingStateString(signaling_state_)
3091 << " New state: "
3092 << GetSignalingStateString(signaling_state);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003093 signaling_state_ = signaling_state;
3094 if (signaling_state == kClosed) {
3095 ice_connection_state_ = kIceConnectionClosed;
3096 observer_->OnIceConnectionChange(ice_connection_state_);
3097 if (ice_gathering_state_ != kIceGatheringComplete) {
3098 ice_gathering_state_ = kIceGatheringComplete;
3099 observer_->OnIceGatheringChange(ice_gathering_state_);
3100 }
3101 }
3102 observer_->OnSignalingChange(signaling_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003103}
3104
deadbeefeb459812015-12-15 19:24:43 -08003105void PeerConnection::OnAudioTrackAdded(AudioTrackInterface* track,
3106 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003107 if (IsClosed()) {
3108 return;
3109 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003110 AddAudioTrack(track, stream);
3111 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003112}
3113
deadbeefeb459812015-12-15 19:24:43 -08003114void PeerConnection::OnAudioTrackRemoved(AudioTrackInterface* track,
3115 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003116 if (IsClosed()) {
3117 return;
3118 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003119 RemoveAudioTrack(track, stream);
3120 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003121}
3122
3123void PeerConnection::OnVideoTrackAdded(VideoTrackInterface* track,
3124 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003125 if (IsClosed()) {
3126 return;
3127 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003128 AddVideoTrack(track, stream);
3129 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003130}
3131
3132void PeerConnection::OnVideoTrackRemoved(VideoTrackInterface* track,
3133 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003134 if (IsClosed()) {
3135 return;
3136 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003137 RemoveVideoTrack(track, stream);
3138 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003139}
3140
Henrik Boström31638672017-11-23 17:48:32 +01003141void PeerConnection::PostSetSessionDescriptionSuccess(
3142 SetSessionDescriptionObserver* observer) {
3143 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
3144 signaling_thread()->Post(RTC_FROM_HERE, this,
3145 MSG_SET_SESSIONDESCRIPTION_SUCCESS, msg);
3146}
3147
deadbeefab9b2d12015-10-14 11:33:11 -07003148void PeerConnection::PostSetSessionDescriptionFailure(
3149 SetSessionDescriptionObserver* observer,
3150 const std::string& error) {
3151 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
3152 msg->error = error;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07003153 signaling_thread()->Post(RTC_FROM_HERE, this,
3154 MSG_SET_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07003155}
3156
3157void PeerConnection::PostCreateSessionDescriptionFailure(
3158 CreateSessionDescriptionObserver* observer,
3159 const std::string& error) {
3160 CreateSessionDescriptionMsg* msg = new CreateSessionDescriptionMsg(observer);
3161 msg->error = error;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07003162 signaling_thread()->Post(RTC_FROM_HERE, this,
3163 MSG_CREATE_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07003164}
3165
zhihuang1c378ed2017-08-17 14:10:50 -07003166void PeerConnection::GetOptionsForOffer(
Steve Antondcc3c022017-12-22 16:02:54 -08003167 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
deadbeefab9b2d12015-10-14 11:33:11 -07003168 cricket::MediaSessionOptions* session_options) {
Steve Antondcc3c022017-12-22 16:02:54 -08003169 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
zhihuang1c378ed2017-08-17 14:10:50 -07003170
Steve Antondcc3c022017-12-22 16:02:54 -08003171 if (IsUnifiedPlan()) {
3172 GetOptionsForUnifiedPlanOffer(offer_answer_options, session_options);
3173 } else {
3174 GetOptionsForPlanBOffer(offer_answer_options, session_options);
3175 }
3176
Steve Antonfa2260d2017-12-28 16:38:23 -08003177 // Intentionally unset the data channel type for RTP data channel with the
3178 // second condition. Otherwise the RTP data channels would be successfully
3179 // negotiated by default and the unit tests in WebRtcDataBrowserTest will fail
3180 // when building with chromium. We want to leave RTP data channels broken, so
3181 // people won't try to use them.
3182 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
3183 session_options->data_channel_type = data_channel_type();
3184 }
3185
Steve Antondcc3c022017-12-22 16:02:54 -08003186 // Apply ICE restart flag and renomination flag.
3187 for (auto& options : session_options->media_description_options) {
3188 options.transport_options.ice_restart = offer_answer_options.ice_restart;
3189 options.transport_options.enable_ice_renomination =
3190 configuration_.enable_ice_renomination;
3191 }
3192
3193 session_options->rtcp_cname = rtcp_cname_;
3194 session_options->crypto_options = factory_->options().crypto_options;
3195}
3196
3197void PeerConnection::GetOptionsForPlanBOffer(
3198 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
3199 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07003200 // Figure out transceiver directional preferences.
3201 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
3202 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
3203
3204 // By default, generate sendrecv/recvonly m= sections.
3205 bool recv_audio = true;
3206 bool recv_video = true;
3207
3208 // By default, only offer a new m= section if we have media to send with it.
3209 bool offer_new_audio_description = send_audio;
3210 bool offer_new_video_description = send_video;
3211 bool offer_new_data_description = HasDataChannels();
3212
3213 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-22 16:02:54 -08003214 if (offer_answer_options.offer_to_receive_audio !=
3215 RTCOfferAnswerOptions::kUndefined) {
3216 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003217 offer_new_audio_description =
Steve Antondcc3c022017-12-22 16:02:54 -08003218 offer_new_audio_description ||
3219 (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003220 }
Steve Antondcc3c022017-12-22 16:02:54 -08003221 if (offer_answer_options.offer_to_receive_video !=
3222 RTCOfferAnswerOptions::kUndefined) {
3223 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003224 offer_new_video_description =
Steve Antondcc3c022017-12-22 16:02:54 -08003225 offer_new_video_description ||
3226 (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003227 }
3228
3229 rtc::Optional<size_t> audio_index;
3230 rtc::Optional<size_t> video_index;
3231 rtc::Optional<size_t> data_index;
3232 // If a current description exists, generate m= sections in the same order,
3233 // using the first audio/video/data section that appears and rejecting
3234 // extraneous ones.
Steve Anton75737c02017-11-06 10:37:17 -08003235 if (local_description()) {
zhihuang1c378ed2017-08-17 14:10:50 -07003236 GenerateMediaDescriptionOptions(
Steve Anton75737c02017-11-06 10:37:17 -08003237 local_description(),
Steve Anton1d03a752017-11-27 14:30:09 -08003238 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
3239 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
3240 &audio_index, &video_index, &data_index, session_options);
deadbeefab9b2d12015-10-14 11:33:11 -07003241 }
3242
zhihuang1c378ed2017-08-17 14:10:50 -07003243 // Add audio/video/data m= sections to the end if needed.
3244 if (!audio_index && offer_new_audio_description) {
3245 session_options->media_description_options.push_back(
3246 cricket::MediaDescriptionOptions(
3247 cricket::MEDIA_TYPE_AUDIO, cricket::CN_AUDIO,
Steve Anton1d03a752017-11-27 14:30:09 -08003248 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
3249 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003250 audio_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07003251 }
zhihuang1c378ed2017-08-17 14:10:50 -07003252 if (!video_index && offer_new_video_description) {
3253 session_options->media_description_options.push_back(
3254 cricket::MediaDescriptionOptions(
3255 cricket::MEDIA_TYPE_VIDEO, cricket::CN_VIDEO,
Steve Anton1d03a752017-11-27 14:30:09 -08003256 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
3257 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003258 video_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07003259 }
zhihuang1c378ed2017-08-17 14:10:50 -07003260 if (!data_index && offer_new_data_description) {
3261 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08003262 GetMediaDescriptionOptionsForActiveData(cricket::CN_DATA));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003263 data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07003264 }
3265
3266 cricket::MediaDescriptionOptions* audio_media_description_options =
3267 !audio_index ? nullptr
3268 : &session_options->media_description_options[*audio_index];
3269 cricket::MediaDescriptionOptions* video_media_description_options =
3270 !video_index ? nullptr
3271 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 14:10:50 -07003272
Steve Anton4171afb2017-11-20 10:20:22 -08003273 AddRtpSenderOptions(GetSendersInternal(), audio_media_description_options,
zhihuang1c378ed2017-08-17 14:10:50 -07003274 video_media_description_options);
Steve Antondcc3c022017-12-22 16:02:54 -08003275}
3276
3277// Find a new MID that is not already in |used_mids|, then add it to |used_mids|
3278// and return a reference to it.
3279// Generated MIDs should be no more than 3 bytes long to take up less space in
3280// the RTP packet.
3281static const std::string& AllocateMid(std::set<std::string>* used_mids) {
3282 RTC_DCHECK(used_mids);
3283 // We're boring: just generate MIDs 0, 1, 2, ...
3284 size_t i = 0;
3285 std::set<std::string>::iterator it;
3286 bool inserted;
3287 do {
3288 std::string mid = rtc::ToString(i++);
3289 auto insert_result = used_mids->insert(mid);
3290 it = insert_result.first;
3291 inserted = insert_result.second;
3292 } while (!inserted);
3293 return *it;
3294}
3295
3296static cricket::MediaDescriptionOptions
3297GetMediaDescriptionOptionsForTransceiver(
3298 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3299 transceiver,
3300 const std::string& mid) {
3301 cricket::MediaDescriptionOptions media_description_options(
3302 transceiver->internal()->media_type(), mid, transceiver->direction(),
3303 transceiver->stopped());
3304 cricket::SenderOptions sender_options;
3305 sender_options.track_id = transceiver->sender()->id();
3306 sender_options.stream_ids = transceiver->sender()->stream_ids();
3307 // TODO(bugs.webrtc.org/7600): Set num_sim_layers to the number of encodings
3308 // set in the RTP parameters when the transceiver was added.
3309 sender_options.num_sim_layers = 1;
3310 media_description_options.sender_options.push_back(sender_options);
3311 return media_description_options;
3312}
3313
3314void PeerConnection::GetOptionsForUnifiedPlanOffer(
3315 const RTCOfferAnswerOptions& offer_answer_options,
3316 cricket::MediaSessionOptions* session_options) {
3317 // Rules for generating an offer are dictated by JSEP sections 5.2.1 (Initial
3318 // Offers) and 5.2.2 (Subsequent Offers).
3319 RTC_DCHECK_EQ(session_options->media_description_options.size(), 0);
3320 const ContentInfos& local_contents =
3321 (local_description() ? local_description()->description()->contents()
3322 : ContentInfos());
3323 const ContentInfos& remote_contents =
3324 (remote_description() ? remote_description()->description()->contents()
3325 : ContentInfos());
3326 // The mline indices that can be recycled. New transceivers should reuse these
3327 // slots first.
3328 std::queue<size_t> recycleable_mline_indices;
3329 // Track the MIDs used in previous offer/answer exchanges and the current
3330 // offer so that new, unique MIDs are generated.
3331 std::set<std::string> used_mids = seen_mids_;
3332 // First, go through each media section that exists in either the local or
3333 // remote description and generate a media section in this offer for the
3334 // associated transceiver. If a media section can be recycled, generate a
3335 // default, rejected media section here that can be later overwritten.
3336 for (size_t i = 0;
3337 i < std::max(local_contents.size(), remote_contents.size()); ++i) {
3338 // Either |local_content| or |remote_content| is non-null.
3339 const ContentInfo* local_content =
3340 (i < local_contents.size() ? &local_contents[i] : nullptr);
3341 const ContentInfo* remote_content =
3342 (i < remote_contents.size() ? &remote_contents[i] : nullptr);
3343 bool had_been_rejected = (local_content && local_content->rejected) ||
3344 (remote_content && remote_content->rejected);
3345 const std::string& mid =
3346 (local_content ? local_content->name : remote_content->name);
3347 cricket::MediaType media_type =
3348 (local_content ? local_content->media_description()->type()
3349 : remote_content->media_description()->type());
3350 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
3351 media_type == cricket::MEDIA_TYPE_VIDEO) {
3352 auto transceiver = GetAssociatedTransceiver(mid);
3353 RTC_CHECK(transceiver);
3354 // A media section is considered eligible for recycling if it is marked as
3355 // rejected in either the local or remote description.
3356 if (had_been_rejected) {
3357 session_options->media_description_options.push_back(
3358 cricket::MediaDescriptionOptions(
3359 transceiver->internal()->media_type(), mid,
3360 RtpTransceiverDirection::kInactive,
3361 /*stopped=*/true));
3362 recycleable_mline_indices.push(i);
3363 } else {
3364 session_options->media_description_options.push_back(
3365 GetMediaDescriptionOptionsForTransceiver(transceiver, mid));
3366 // CreateOffer shouldn't really cause any state changes in
3367 // PeerConnection, but we need a way to match new transceivers to new
3368 // media sections in SetLocalDescription and JSEP specifies this is done
3369 // by recording the index of the media section generated for the
3370 // transceiver in the offer.
3371 transceiver->internal()->set_mline_index(i);
3372 }
3373 } else {
3374 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antonfa2260d2017-12-28 16:38:23 -08003375 RTC_CHECK(GetDataMid());
3376 if (had_been_rejected || mid != *GetDataMid()) {
3377 session_options->media_description_options.push_back(
3378 GetMediaDescriptionOptionsForRejectedData(mid));
3379 } else {
3380 session_options->media_description_options.push_back(
3381 GetMediaDescriptionOptionsForActiveData(mid));
3382 }
Steve Antondcc3c022017-12-22 16:02:54 -08003383 }
3384 }
3385 // Next, look for transceivers that are newly added (that is, are not stopped
3386 // and not associated). Reuse media sections marked as recyclable first,
3387 // otherwise append to the end of the offer. New media sections should be
3388 // added in the order they were added to the PeerConnection.
3389 for (auto transceiver : transceivers_) {
3390 if (transceiver->mid() || transceiver->stopped()) {
3391 continue;
3392 }
3393 size_t mline_index;
3394 if (!recycleable_mline_indices.empty()) {
3395 mline_index = recycleable_mline_indices.front();
3396 recycleable_mline_indices.pop();
3397 session_options->media_description_options[mline_index] =
3398 GetMediaDescriptionOptionsForTransceiver(transceiver,
3399 AllocateMid(&used_mids));
3400 } else {
3401 mline_index = session_options->media_description_options.size();
3402 session_options->media_description_options.push_back(
3403 GetMediaDescriptionOptionsForTransceiver(transceiver,
3404 AllocateMid(&used_mids)));
3405 }
3406 // See comment above for why CreateOffer changes the transceiver's state.
3407 transceiver->internal()->set_mline_index(mline_index);
3408 }
Steve Antonfa2260d2017-12-28 16:38:23 -08003409 // Lastly, add a m-section if we have local data channels and an m section
3410 // does not already exist.
3411 if (!GetDataMid() && HasDataChannels()) {
3412 session_options->media_description_options.push_back(
3413 GetMediaDescriptionOptionsForActiveData(AllocateMid(&used_mids)));
3414 }
Steve Antondcc3c022017-12-22 16:02:54 -08003415}
3416
3417void PeerConnection::GetOptionsForAnswer(
3418 const RTCOfferAnswerOptions& offer_answer_options,
3419 cricket::MediaSessionOptions* session_options) {
3420 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
3421
3422 if (IsUnifiedPlan()) {
3423 GetOptionsForUnifiedPlanAnswer(offer_answer_options, session_options);
3424 } else {
3425 GetOptionsForPlanBAnswer(offer_answer_options, session_options);
3426 }
3427
Steve Antonfa2260d2017-12-28 16:38:23 -08003428 // Intentionally unset the data channel type for RTP data channel. Otherwise
3429 // the RTP data channels would be successfully negotiated by default and the
3430 // unit tests in WebRtcDataBrowserTest will fail when building with chromium.
3431 // We want to leave RTP data channels broken, so people won't try to use them.
3432 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
3433 session_options->data_channel_type = data_channel_type();
3434 }
3435
Steve Antondcc3c022017-12-22 16:02:54 -08003436 // Apply ICE renomination flag.
3437 for (auto& options : session_options->media_description_options) {
3438 options.transport_options.enable_ice_renomination =
3439 configuration_.enable_ice_renomination;
3440 }
zhihuang8f65cdf2016-05-06 18:40:30 -07003441
3442 session_options->rtcp_cname = rtcp_cname_;
jbauchcb560652016-08-04 05:20:32 -07003443 session_options->crypto_options = factory_->options().crypto_options;
deadbeefab9b2d12015-10-14 11:33:11 -07003444}
3445
Steve Antondcc3c022017-12-22 16:02:54 -08003446void PeerConnection::GetOptionsForPlanBAnswer(
3447 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07003448 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07003449 // Figure out transceiver directional preferences.
3450 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
3451 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
3452
3453 // By default, generate sendrecv/recvonly m= sections. The direction is also
3454 // restricted by the direction in the offer.
3455 bool recv_audio = true;
3456 bool recv_video = true;
3457
3458 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-22 16:02:54 -08003459 if (offer_answer_options.offer_to_receive_audio !=
3460 RTCOfferAnswerOptions::kUndefined) {
3461 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
deadbeef0ed85b22016-02-23 17:24:52 -08003462 }
Steve Antondcc3c022017-12-22 16:02:54 -08003463 if (offer_answer_options.offer_to_receive_video !=
3464 RTCOfferAnswerOptions::kUndefined) {
3465 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003466 }
3467
3468 rtc::Optional<size_t> audio_index;
3469 rtc::Optional<size_t> video_index;
3470 rtc::Optional<size_t> data_index;
Taylor Brandstetter94d8cce2018-01-26 22:44:21 +00003471 if (remote_description()) {
3472 // The pending remote description should be an offer.
3473 RTC_DCHECK(remote_description()->GetType() == SdpType::kOffer);
3474 // Generate m= sections that match those in the offer.
3475 // Note that mediasession.cc will handle intersection our preferred
3476 // direction with the offered direction.
3477 GenerateMediaDescriptionOptions(
3478 remote_description(),
3479 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
3480 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
3481 &audio_index, &video_index, &data_index, session_options);
3482 }
zhihuang1c378ed2017-08-17 14:10:50 -07003483
3484 cricket::MediaDescriptionOptions* audio_media_description_options =
3485 !audio_index ? nullptr
3486 : &session_options->media_description_options[*audio_index];
3487 cricket::MediaDescriptionOptions* video_media_description_options =
3488 !video_index ? nullptr
3489 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 14:10:50 -07003490
Steve Anton4171afb2017-11-20 10:20:22 -08003491 AddRtpSenderOptions(GetSendersInternal(), audio_media_description_options,
zhihuang1c378ed2017-08-17 14:10:50 -07003492 video_media_description_options);
Steve Antondcc3c022017-12-22 16:02:54 -08003493}
zhihuangaf388472016-11-02 16:49:48 -07003494
Steve Antondcc3c022017-12-22 16:02:54 -08003495void PeerConnection::GetOptionsForUnifiedPlanAnswer(
3496 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
3497 cricket::MediaSessionOptions* session_options) {
3498 // Rules for generating an answer are dictated by JSEP sections 5.3.1 (Initial
3499 // Answers) and 5.3.2 (Subsequent Answers).
3500 RTC_DCHECK(remote_description());
3501 RTC_DCHECK(remote_description()->GetType() == SdpType::kOffer);
3502 for (const ContentInfo& content :
3503 remote_description()->description()->contents()) {
3504 cricket::MediaType media_type = content.media_description()->type();
3505 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
3506 media_type == cricket::MEDIA_TYPE_VIDEO) {
3507 auto transceiver = GetAssociatedTransceiver(content.name);
3508 RTC_CHECK(transceiver);
3509 session_options->media_description_options.push_back(
3510 GetMediaDescriptionOptionsForTransceiver(transceiver, content.name));
3511 } else {
3512 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antondbf9d032018-01-19 15:23:40 -08003513 // Reject all data sections if data channels are disabled.
3514 // Reject a data section if it has already been rejected.
3515 // Reject all data sections except for the first one.
3516 if (data_channel_type_ == cricket::DCT_NONE || content.rejected ||
3517 content.name != *GetDataMid()) {
Steve Antonfa2260d2017-12-28 16:38:23 -08003518 session_options->media_description_options.push_back(
3519 GetMediaDescriptionOptionsForRejectedData(content.name));
3520 } else {
3521 session_options->media_description_options.push_back(
3522 GetMediaDescriptionOptionsForActiveData(content.name));
3523 }
Steve Antondcc3c022017-12-22 16:02:54 -08003524 }
3525 }
htaa2a49d92016-03-04 02:51:39 -08003526}
3527
zhihuang1c378ed2017-08-17 14:10:50 -07003528void PeerConnection::GenerateMediaDescriptionOptions(
3529 const SessionDescriptionInterface* session_desc,
Steve Anton1d03a752017-11-27 14:30:09 -08003530 RtpTransceiverDirection audio_direction,
3531 RtpTransceiverDirection video_direction,
zhihuang1c378ed2017-08-17 14:10:50 -07003532 rtc::Optional<size_t>* audio_index,
3533 rtc::Optional<size_t>* video_index,
3534 rtc::Optional<size_t>* data_index,
htaa2a49d92016-03-04 02:51:39 -08003535 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07003536 for (const cricket::ContentInfo& content :
3537 session_desc->description()->contents()) {
3538 if (IsAudioContent(&content)) {
3539 // If we already have an audio m= section, reject this extra one.
3540 if (*audio_index) {
3541 session_options->media_description_options.push_back(
3542 cricket::MediaDescriptionOptions(
3543 cricket::MEDIA_TYPE_AUDIO, content.name,
Steve Anton1d03a752017-11-27 14:30:09 -08003544 RtpTransceiverDirection::kInactive, true));
zhihuang1c378ed2017-08-17 14:10:50 -07003545 } else {
3546 session_options->media_description_options.push_back(
3547 cricket::MediaDescriptionOptions(
3548 cricket::MEDIA_TYPE_AUDIO, content.name, audio_direction,
Steve Anton1d03a752017-11-27 14:30:09 -08003549 audio_direction == RtpTransceiverDirection::kInactive));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003550 *audio_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07003551 }
3552 } else if (IsVideoContent(&content)) {
3553 // If we already have an video m= section, reject this extra one.
3554 if (*video_index) {
3555 session_options->media_description_options.push_back(
3556 cricket::MediaDescriptionOptions(
3557 cricket::MEDIA_TYPE_VIDEO, content.name,
Steve Anton1d03a752017-11-27 14:30:09 -08003558 RtpTransceiverDirection::kInactive, true));
zhihuang1c378ed2017-08-17 14:10:50 -07003559 } else {
3560 session_options->media_description_options.push_back(
3561 cricket::MediaDescriptionOptions(
3562 cricket::MEDIA_TYPE_VIDEO, content.name, video_direction,
Steve Anton1d03a752017-11-27 14:30:09 -08003563 video_direction == RtpTransceiverDirection::kInactive));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003564 *video_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07003565 }
3566 } else {
3567 RTC_DCHECK(IsDataContent(&content));
3568 // If we already have an data m= section, reject this extra one.
3569 if (*data_index) {
3570 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08003571 GetMediaDescriptionOptionsForRejectedData(content.name));
zhihuang1c378ed2017-08-17 14:10:50 -07003572 } else {
3573 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08003574 GetMediaDescriptionOptionsForActiveData(content.name));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003575 *data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07003576 }
3577 }
htaa2a49d92016-03-04 02:51:39 -08003578 }
deadbeefab9b2d12015-10-14 11:33:11 -07003579}
3580
Steve Antonfa2260d2017-12-28 16:38:23 -08003581cricket::MediaDescriptionOptions
3582PeerConnection::GetMediaDescriptionOptionsForActiveData(
3583 const std::string& mid) const {
3584 // Direction for data sections is meaningless, but legacy endpoints might
3585 // expect sendrecv.
3586 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
3587 RtpTransceiverDirection::kSendRecv,
3588 /*stopped=*/false);
3589 AddRtpDataChannelOptions(rtp_data_channels_, &options);
3590 return options;
3591}
3592
3593cricket::MediaDescriptionOptions
3594PeerConnection::GetMediaDescriptionOptionsForRejectedData(
3595 const std::string& mid) const {
3596 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
3597 RtpTransceiverDirection::kInactive,
3598 /*stopped=*/true);
3599 AddRtpDataChannelOptions(rtp_data_channels_, &options);
3600 return options;
3601}
3602
3603rtc::Optional<std::string> PeerConnection::GetDataMid() const {
3604 switch (data_channel_type_) {
3605 case cricket::DCT_RTP:
3606 if (!rtp_data_channel_) {
3607 return rtc::nullopt;
3608 }
3609 return rtp_data_channel_->content_name();
3610 case cricket::DCT_SCTP:
3611 return sctp_content_name_;
3612 default:
3613 return rtc::nullopt;
3614 }
3615}
3616
Steve Anton4171afb2017-11-20 10:20:22 -08003617void PeerConnection::RemoveSenders(cricket::MediaType media_type) {
3618 UpdateLocalSenders(std::vector<cricket::StreamParams>(), media_type);
3619 UpdateRemoteSendersList(std::vector<cricket::StreamParams>(), false,
deadbeefbda7e0b2015-12-08 17:13:40 -08003620 media_type, nullptr);
deadbeeffaac4972015-11-12 15:33:07 -08003621}
3622
Steve Anton4171afb2017-11-20 10:20:22 -08003623void PeerConnection::UpdateRemoteSendersList(
deadbeefab9b2d12015-10-14 11:33:11 -07003624 const cricket::StreamParamsVec& streams,
Steve Anton4171afb2017-11-20 10:20:22 -08003625 bool default_sender_needed,
deadbeefab9b2d12015-10-14 11:33:11 -07003626 cricket::MediaType media_type,
3627 StreamCollection* new_streams) {
Steve Anton4171afb2017-11-20 10:20:22 -08003628 std::vector<RtpSenderInfo>* current_senders =
3629 GetRemoteSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07003630
Steve Anton4171afb2017-11-20 10:20:22 -08003631 // Find removed senders. I.e., senders where the sender id or ssrc don't match
deadbeeffac06552015-11-25 11:26:01 -08003632 // the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08003633 for (auto sender_it = current_senders->begin();
3634 sender_it != current_senders->end();
3635 /* incremented manually */) {
3636 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07003637 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08003638 cricket::GetStreamBySsrc(streams, info.first_ssrc);
3639 bool sender_exists = params && params->id == info.sender_id;
deadbeefbda7e0b2015-12-08 17:13:40 -08003640 // If this is a default track, and we still need it, don't remove it.
Steve Anton4171afb2017-11-20 10:20:22 -08003641 if ((info.stream_label == kDefaultStreamLabel && default_sender_needed) ||
3642 sender_exists) {
3643 ++sender_it;
deadbeefbda7e0b2015-12-08 17:13:40 -08003644 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08003645 OnRemoteSenderRemoved(info, media_type);
3646 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07003647 }
3648 }
3649
Steve Anton4171afb2017-11-20 10:20:22 -08003650 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07003651 for (const cricket::StreamParams& params : streams) {
3652 // The sync_label is the MediaStream label and the |stream.id| is the
Steve Anton4171afb2017-11-20 10:20:22 -08003653 // sender id.
deadbeefab9b2d12015-10-14 11:33:11 -07003654 const std::string& stream_label = params.sync_label;
Steve Anton4171afb2017-11-20 10:20:22 -08003655 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07003656 uint32_t ssrc = params.first_ssrc();
3657
3658 rtc::scoped_refptr<MediaStreamInterface> stream =
3659 remote_streams_->find(stream_label);
3660 if (!stream) {
3661 // This is a new MediaStream. Create a new remote MediaStream.
perkjd61bf802016-03-24 03:16:19 -07003662 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
3663 MediaStream::Create(stream_label));
deadbeefab9b2d12015-10-14 11:33:11 -07003664 remote_streams_->AddStream(stream);
3665 new_streams->AddStream(stream);
3666 }
3667
Steve Anton4171afb2017-11-20 10:20:22 -08003668 const RtpSenderInfo* sender_info =
3669 FindSenderInfo(*current_senders, stream_label, sender_id);
3670 if (!sender_info) {
3671 current_senders->push_back(RtpSenderInfo(stream_label, sender_id, ssrc));
3672 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07003673 }
3674 }
deadbeefbda7e0b2015-12-08 17:13:40 -08003675
Steve Anton4171afb2017-11-20 10:20:22 -08003676 // Add default sender if necessary.
3677 if (default_sender_needed) {
deadbeefbda7e0b2015-12-08 17:13:40 -08003678 rtc::scoped_refptr<MediaStreamInterface> default_stream =
3679 remote_streams_->find(kDefaultStreamLabel);
3680 if (!default_stream) {
3681 // Create the new default MediaStream.
perkjd61bf802016-03-24 03:16:19 -07003682 default_stream = MediaStreamProxy::Create(
3683 rtc::Thread::Current(), MediaStream::Create(kDefaultStreamLabel));
deadbeefbda7e0b2015-12-08 17:13:40 -08003684 remote_streams_->AddStream(default_stream);
3685 new_streams->AddStream(default_stream);
3686 }
Steve Anton4171afb2017-11-20 10:20:22 -08003687 std::string default_sender_id = (media_type == cricket::MEDIA_TYPE_AUDIO)
3688 ? kDefaultAudioSenderId
3689 : kDefaultVideoSenderId;
3690 const RtpSenderInfo* default_sender_info = FindSenderInfo(
3691 *current_senders, kDefaultStreamLabel, default_sender_id);
3692 if (!default_sender_info) {
3693 current_senders->push_back(
3694 RtpSenderInfo(kDefaultStreamLabel, default_sender_id, 0));
3695 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefbda7e0b2015-12-08 17:13:40 -08003696 }
3697 }
deadbeefab9b2d12015-10-14 11:33:11 -07003698}
3699
Steve Anton4171afb2017-11-20 10:20:22 -08003700void PeerConnection::OnRemoteSenderAdded(const RtpSenderInfo& sender_info,
3701 cricket::MediaType media_type) {
3702 MediaStreamInterface* stream =
3703 remote_streams_->find(sender_info.stream_label);
deadbeefab9b2d12015-10-14 11:33:11 -07003704
3705 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 10:20:22 -08003706 CreateAudioReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07003707 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 10:20:22 -08003708 CreateVideoReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07003709 } else {
nisseeb4ca4e2017-01-12 02:24:27 -08003710 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07003711 }
3712}
3713
Steve Anton4171afb2017-11-20 10:20:22 -08003714void PeerConnection::OnRemoteSenderRemoved(const RtpSenderInfo& sender_info,
3715 cricket::MediaType media_type) {
3716 MediaStreamInterface* stream =
3717 remote_streams_->find(sender_info.stream_label);
deadbeefab9b2d12015-10-14 11:33:11 -07003718
Henrik Boström933d8b02017-10-10 10:05:16 -07003719 rtc::scoped_refptr<RtpReceiverInterface> receiver;
deadbeefab9b2d12015-10-14 11:33:11 -07003720 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
perkjd61bf802016-03-24 03:16:19 -07003721 // When the MediaEngine audio channel is destroyed, the RemoteAudioSource
3722 // will be notified which will end the AudioRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08003723 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07003724 rtc::scoped_refptr<AudioTrackInterface> audio_track =
Steve Anton4171afb2017-11-20 10:20:22 -08003725 stream->FindAudioTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07003726 if (audio_track) {
deadbeefab9b2d12015-10-14 11:33:11 -07003727 stream->RemoveTrack(audio_track);
deadbeefab9b2d12015-10-14 11:33:11 -07003728 }
3729 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
perkjd61bf802016-03-24 03:16:19 -07003730 // Stopping or destroying a VideoRtpReceiver will end the
3731 // VideoRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08003732 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07003733 rtc::scoped_refptr<VideoTrackInterface> video_track =
Steve Anton4171afb2017-11-20 10:20:22 -08003734 stream->FindVideoTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07003735 if (video_track) {
perkjd61bf802016-03-24 03:16:19 -07003736 // There's no guarantee the track is still available, e.g. the track may
3737 // have been removed from the stream by an application.
deadbeefab9b2d12015-10-14 11:33:11 -07003738 stream->RemoveTrack(video_track);
deadbeefab9b2d12015-10-14 11:33:11 -07003739 }
3740 } else {
nisseede5da42017-01-12 05:15:36 -08003741 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07003742 }
Henrik Boström933d8b02017-10-10 10:05:16 -07003743 if (receiver) {
3744 observer_->OnRemoveTrack(receiver);
3745 }
deadbeefab9b2d12015-10-14 11:33:11 -07003746}
3747
3748void PeerConnection::UpdateEndedRemoteMediaStreams() {
3749 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams_to_remove;
3750 for (size_t i = 0; i < remote_streams_->count(); ++i) {
3751 MediaStreamInterface* stream = remote_streams_->at(i);
3752 if (stream->GetAudioTracks().empty() && stream->GetVideoTracks().empty()) {
3753 streams_to_remove.push_back(stream);
3754 }
3755 }
3756
Taylor Brandstetter98cde262016-05-31 13:02:21 -07003757 for (auto& stream : streams_to_remove) {
deadbeefab9b2d12015-10-14 11:33:11 -07003758 remote_streams_->RemoveStream(stream);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07003759 observer_->OnRemoveStream(std::move(stream));
deadbeefab9b2d12015-10-14 11:33:11 -07003760 }
3761}
3762
Steve Anton4171afb2017-11-20 10:20:22 -08003763void PeerConnection::UpdateLocalSenders(
deadbeefab9b2d12015-10-14 11:33:11 -07003764 const std::vector<cricket::StreamParams>& streams,
3765 cricket::MediaType media_type) {
Steve Anton4171afb2017-11-20 10:20:22 -08003766 std::vector<RtpSenderInfo>* current_senders = GetLocalSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07003767
3768 // Find removed tracks. I.e., tracks where the track id, stream label or ssrc
3769 // don't match the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08003770 for (auto sender_it = current_senders->begin();
3771 sender_it != current_senders->end();
3772 /* incremented manually */) {
3773 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07003774 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08003775 cricket::GetStreamBySsrc(streams, info.first_ssrc);
3776 if (!params || params->id != info.sender_id ||
deadbeefab9b2d12015-10-14 11:33:11 -07003777 params->sync_label != info.stream_label) {
Steve Anton4171afb2017-11-20 10:20:22 -08003778 OnLocalSenderRemoved(info, media_type);
3779 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07003780 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08003781 ++sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07003782 }
3783 }
3784
Steve Anton4171afb2017-11-20 10:20:22 -08003785 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07003786 for (const cricket::StreamParams& params : streams) {
3787 // The sync_label is the MediaStream label and the |stream.id| is the
Steve Anton4171afb2017-11-20 10:20:22 -08003788 // sender id.
deadbeefab9b2d12015-10-14 11:33:11 -07003789 const std::string& stream_label = params.sync_label;
Steve Anton4171afb2017-11-20 10:20:22 -08003790 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07003791 uint32_t ssrc = params.first_ssrc();
Steve Anton4171afb2017-11-20 10:20:22 -08003792 const RtpSenderInfo* sender_info =
3793 FindSenderInfo(*current_senders, stream_label, sender_id);
3794 if (!sender_info) {
3795 current_senders->push_back(RtpSenderInfo(stream_label, sender_id, ssrc));
3796 OnLocalSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07003797 }
3798 }
3799}
3800
Steve Anton4171afb2017-11-20 10:20:22 -08003801void PeerConnection::OnLocalSenderAdded(const RtpSenderInfo& sender_info,
3802 cricket::MediaType media_type) {
3803 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08003804 if (!sender) {
Steve Anton4171afb2017-11-20 10:20:22 -08003805 RTC_LOG(LS_WARNING) << "An unknown RtpSender with id "
3806 << sender_info.sender_id
Mirko Bonadei675513b2017-11-09 11:09:25 +01003807 << " has been configured in the local description.";
deadbeefab9b2d12015-10-14 11:33:11 -07003808 return;
3809 }
3810
deadbeeffac06552015-11-25 11:26:01 -08003811 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003812 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
3813 << " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08003814 return;
deadbeefab9b2d12015-10-14 11:33:11 -07003815 }
deadbeeffac06552015-11-25 11:26:01 -08003816
Steve Anton4171afb2017-11-20 10:20:22 -08003817 sender->internal()->set_stream_id(sender_info.stream_label);
3818 sender->internal()->SetSsrc(sender_info.first_ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07003819}
3820
Steve Anton4171afb2017-11-20 10:20:22 -08003821void PeerConnection::OnLocalSenderRemoved(const RtpSenderInfo& sender_info,
3822 cricket::MediaType media_type) {
3823 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08003824 if (!sender) {
3825 // This is the normal case. I.e., RemoveStream has been called and the
deadbeefab9b2d12015-10-14 11:33:11 -07003826 // SessionDescriptions has been renegotiated.
3827 return;
3828 }
deadbeeffac06552015-11-25 11:26:01 -08003829
3830 // A sender has been removed from the SessionDescription but it's still
3831 // associated with the PeerConnection. This only occurs if the SDP doesn't
3832 // match with the calls to CreateSender, AddStream and RemoveStream.
3833 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003834 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
3835 << " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08003836 return;
deadbeefab9b2d12015-10-14 11:33:11 -07003837 }
deadbeeffac06552015-11-25 11:26:01 -08003838
Steve Anton4171afb2017-11-20 10:20:22 -08003839 sender->internal()->SetSsrc(0);
deadbeefab9b2d12015-10-14 11:33:11 -07003840}
3841
3842void PeerConnection::UpdateLocalRtpDataChannels(
3843 const cricket::StreamParamsVec& streams) {
3844 std::vector<std::string> existing_channels;
3845
3846 // Find new and active data channels.
3847 for (const cricket::StreamParams& params : streams) {
3848 // |it->sync_label| is actually the data channel label. The reason is that
3849 // we use the same naming of data channels as we do for
3850 // MediaStreams and Tracks.
3851 // For MediaStreams, the sync_label is the MediaStream label and the
3852 // track label is the same as |streamid|.
3853 const std::string& channel_label = params.sync_label;
3854 auto data_channel_it = rtp_data_channels_.find(channel_label);
nisse7ce109a2017-01-31 00:57:56 -08003855 if (data_channel_it == rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003856 RTC_LOG(LS_ERROR) << "channel label not found";
deadbeefab9b2d12015-10-14 11:33:11 -07003857 continue;
3858 }
3859 // Set the SSRC the data channel should use for sending.
3860 data_channel_it->second->SetSendSsrc(params.first_ssrc());
3861 existing_channels.push_back(data_channel_it->first);
3862 }
3863
3864 UpdateClosingRtpDataChannels(existing_channels, true);
3865}
3866
3867void PeerConnection::UpdateRemoteRtpDataChannels(
3868 const cricket::StreamParamsVec& streams) {
3869 std::vector<std::string> existing_channels;
3870
3871 // Find new and active data channels.
3872 for (const cricket::StreamParams& params : streams) {
3873 // The data channel label is either the mslabel or the SSRC if the mslabel
3874 // does not exist. Ex a=ssrc:444330170 mslabel:test1.
3875 std::string label = params.sync_label.empty()
3876 ? rtc::ToString(params.first_ssrc())
3877 : params.sync_label;
3878 auto data_channel_it = rtp_data_channels_.find(label);
3879 if (data_channel_it == rtp_data_channels_.end()) {
3880 // This is a new data channel.
3881 CreateRemoteRtpDataChannel(label, params.first_ssrc());
3882 } else {
3883 data_channel_it->second->SetReceiveSsrc(params.first_ssrc());
3884 }
3885 existing_channels.push_back(label);
3886 }
3887
3888 UpdateClosingRtpDataChannels(existing_channels, false);
3889}
3890
3891void PeerConnection::UpdateClosingRtpDataChannels(
3892 const std::vector<std::string>& active_channels,
3893 bool is_local_update) {
3894 auto it = rtp_data_channels_.begin();
3895 while (it != rtp_data_channels_.end()) {
3896 DataChannel* data_channel = it->second;
3897 if (std::find(active_channels.begin(), active_channels.end(),
3898 data_channel->label()) != active_channels.end()) {
3899 ++it;
3900 continue;
3901 }
3902
3903 if (is_local_update) {
3904 data_channel->SetSendSsrc(0);
3905 } else {
3906 data_channel->RemotePeerRequestClose();
3907 }
3908
3909 if (data_channel->state() == DataChannel::kClosed) {
3910 rtp_data_channels_.erase(it);
3911 it = rtp_data_channels_.begin();
3912 } else {
3913 ++it;
3914 }
3915 }
3916}
3917
3918void PeerConnection::CreateRemoteRtpDataChannel(const std::string& label,
3919 uint32_t remote_ssrc) {
3920 rtc::scoped_refptr<DataChannel> channel(
3921 InternalCreateDataChannel(label, nullptr));
3922 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003923 RTC_LOG(LS_WARNING) << "Remote peer requested a DataChannel but"
3924 << "CreateDataChannel failed.";
deadbeefab9b2d12015-10-14 11:33:11 -07003925 return;
3926 }
3927 channel->SetReceiveSsrc(remote_ssrc);
deadbeefa601f5c2016-06-06 14:27:39 -07003928 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
3929 DataChannelProxy::Create(signaling_thread(), channel);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07003930 observer_->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07003931}
3932
3933rtc::scoped_refptr<DataChannel> PeerConnection::InternalCreateDataChannel(
3934 const std::string& label,
3935 const InternalDataChannelInit* config) {
3936 if (IsClosed()) {
3937 return nullptr;
3938 }
Steve Anton75737c02017-11-06 10:37:17 -08003939 if (data_channel_type() == cricket::DCT_NONE) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003940 RTC_LOG(LS_ERROR)
deadbeefab9b2d12015-10-14 11:33:11 -07003941 << "InternalCreateDataChannel: Data is not supported in this call.";
3942 return nullptr;
3943 }
3944 InternalDataChannelInit new_config =
3945 config ? (*config) : InternalDataChannelInit();
Steve Anton75737c02017-11-06 10:37:17 -08003946 if (data_channel_type() == cricket::DCT_SCTP) {
deadbeefab9b2d12015-10-14 11:33:11 -07003947 if (new_config.id < 0) {
3948 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08003949 if ((GetSctpSslRole(&role)) &&
deadbeefab9b2d12015-10-14 11:33:11 -07003950 !sid_allocator_.AllocateSid(role, &new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003951 RTC_LOG(LS_ERROR)
3952 << "No id can be allocated for the SCTP data channel.";
deadbeefab9b2d12015-10-14 11:33:11 -07003953 return nullptr;
3954 }
3955 } else if (!sid_allocator_.ReserveSid(new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003956 RTC_LOG(LS_ERROR) << "Failed to create a SCTP data channel "
3957 << "because the id is already in use or out of range.";
deadbeefab9b2d12015-10-14 11:33:11 -07003958 return nullptr;
3959 }
3960 }
3961
Steve Anton75737c02017-11-06 10:37:17 -08003962 rtc::scoped_refptr<DataChannel> channel(
3963 DataChannel::Create(this, data_channel_type(), label, new_config));
deadbeefab9b2d12015-10-14 11:33:11 -07003964 if (!channel) {
3965 sid_allocator_.ReleaseSid(new_config.id);
3966 return nullptr;
3967 }
3968
3969 if (channel->data_channel_type() == cricket::DCT_RTP) {
3970 if (rtp_data_channels_.find(channel->label()) != rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003971 RTC_LOG(LS_ERROR) << "DataChannel with label " << channel->label()
3972 << " already exists.";
deadbeefab9b2d12015-10-14 11:33:11 -07003973 return nullptr;
3974 }
3975 rtp_data_channels_[channel->label()] = channel;
3976 } else {
3977 RTC_DCHECK(channel->data_channel_type() == cricket::DCT_SCTP);
3978 sctp_data_channels_.push_back(channel);
3979 channel->SignalClosed.connect(this,
3980 &PeerConnection::OnSctpDataChannelClosed);
3981 }
3982
Steve Anton2d8609c2018-01-23 16:38:46 -08003983 SignalDataChannelCreated_(channel.get());
deadbeefab9b2d12015-10-14 11:33:11 -07003984 return channel;
3985}
3986
3987bool PeerConnection::HasDataChannels() const {
3988 return !rtp_data_channels_.empty() || !sctp_data_channels_.empty();
3989}
3990
3991void PeerConnection::AllocateSctpSids(rtc::SSLRole role) {
3992 for (const auto& channel : sctp_data_channels_) {
3993 if (channel->id() < 0) {
3994 int sid;
3995 if (!sid_allocator_.AllocateSid(role, &sid)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003996 RTC_LOG(LS_ERROR) << "Failed to allocate SCTP sid.";
deadbeefab9b2d12015-10-14 11:33:11 -07003997 continue;
3998 }
3999 channel->SetSctpSid(sid);
4000 }
4001 }
4002}
4003
4004void PeerConnection::OnSctpDataChannelClosed(DataChannel* channel) {
deadbeefbd292462015-12-14 18:15:29 -08004005 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeefab9b2d12015-10-14 11:33:11 -07004006 for (auto it = sctp_data_channels_.begin(); it != sctp_data_channels_.end();
4007 ++it) {
4008 if (it->get() == channel) {
4009 if (channel->id() >= 0) {
4010 sid_allocator_.ReleaseSid(channel->id());
4011 }
deadbeefbd292462015-12-14 18:15:29 -08004012 // Since this method is triggered by a signal from the DataChannel,
4013 // we can't free it directly here; we need to free it asynchronously.
4014 sctp_data_channels_to_free_.push_back(*it);
deadbeefab9b2d12015-10-14 11:33:11 -07004015 sctp_data_channels_.erase(it);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07004016 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_FREE_DATACHANNELS,
4017 nullptr);
deadbeefab9b2d12015-10-14 11:33:11 -07004018 return;
4019 }
4020 }
4021}
4022
deadbeefab9b2d12015-10-14 11:33:11 -07004023void PeerConnection::OnDataChannelDestroyed() {
4024 // Use a temporary copy of the RTP/SCTP DataChannel list because the
4025 // DataChannel may callback to us and try to modify the list.
4026 std::map<std::string, rtc::scoped_refptr<DataChannel>> temp_rtp_dcs;
4027 temp_rtp_dcs.swap(rtp_data_channels_);
4028 for (const auto& kv : temp_rtp_dcs) {
4029 kv.second->OnTransportChannelDestroyed();
4030 }
4031
4032 std::vector<rtc::scoped_refptr<DataChannel>> temp_sctp_dcs;
4033 temp_sctp_dcs.swap(sctp_data_channels_);
4034 for (const auto& channel : temp_sctp_dcs) {
4035 channel->OnTransportChannelDestroyed();
4036 }
4037}
4038
4039void PeerConnection::OnDataChannelOpenMessage(
4040 const std::string& label,
4041 const InternalDataChannelInit& config) {
4042 rtc::scoped_refptr<DataChannel> channel(
4043 InternalCreateDataChannel(label, &config));
4044 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004045 RTC_LOG(LS_ERROR) << "Failed to create DataChannel from the OPEN message.";
deadbeefab9b2d12015-10-14 11:33:11 -07004046 return;
4047 }
4048
deadbeefa601f5c2016-06-06 14:27:39 -07004049 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
4050 DataChannelProxy::Create(signaling_thread(), channel);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07004051 observer_->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07004052}
4053
Steve Anton4171afb2017-11-20 10:20:22 -08004054rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
4055PeerConnection::GetAudioTransceiver() const {
4056 // This method only works with Plan B SDP, where there is a single
4057 // audio/video transceiver.
4058 RTC_DCHECK(!IsUnifiedPlan());
4059 for (auto transceiver : transceivers_) {
4060 if (transceiver->internal()->media_type() == cricket::MEDIA_TYPE_AUDIO) {
4061 return transceiver;
4062 }
4063 }
4064 RTC_NOTREACHED();
4065 return nullptr;
4066}
4067
4068rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
4069PeerConnection::GetVideoTransceiver() const {
4070 // This method only works with Plan B SDP, where there is a single
4071 // audio/video transceiver.
4072 RTC_DCHECK(!IsUnifiedPlan());
4073 for (auto transceiver : transceivers_) {
4074 if (transceiver->internal()->media_type() == cricket::MEDIA_TYPE_VIDEO) {
4075 return transceiver;
4076 }
4077 }
4078 RTC_NOTREACHED();
4079 return nullptr;
4080}
4081
4082// TODO(bugs.webrtc.org/7600): Remove this when multiple transceivers with
4083// individual transceiver directions are supported.
zhihuang1c378ed2017-08-17 14:10:50 -07004084bool PeerConnection::HasRtpSender(cricket::MediaType type) const {
Steve Anton4171afb2017-11-20 10:20:22 -08004085 switch (type) {
4086 case cricket::MEDIA_TYPE_AUDIO:
4087 return !GetAudioTransceiver()->internal()->senders().empty();
4088 case cricket::MEDIA_TYPE_VIDEO:
4089 return !GetVideoTransceiver()->internal()->senders().empty();
4090 case cricket::MEDIA_TYPE_DATA:
4091 return false;
4092 }
4093 RTC_NOTREACHED();
4094 return false;
zhihuang1c378ed2017-08-17 14:10:50 -07004095}
4096
Steve Anton4171afb2017-11-20 10:20:22 -08004097rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
4098PeerConnection::FindSenderForTrack(MediaStreamTrackInterface* track) const {
4099 for (auto transceiver : transceivers_) {
4100 for (auto sender : transceiver->internal()->senders()) {
4101 if (sender->track() == track) {
4102 return sender;
4103 }
4104 }
4105 }
4106 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08004107}
4108
Steve Anton4171afb2017-11-20 10:20:22 -08004109rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
4110PeerConnection::FindSenderById(const std::string& sender_id) const {
4111 for (auto transceiver : transceivers_) {
4112 for (auto sender : transceiver->internal()->senders()) {
4113 if (sender->id() == sender_id) {
4114 return sender;
4115 }
4116 }
4117 }
4118 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07004119}
4120
Steve Anton4171afb2017-11-20 10:20:22 -08004121rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
4122PeerConnection::FindReceiverById(const std::string& receiver_id) const {
4123 for (auto transceiver : transceivers_) {
4124 for (auto receiver : transceiver->internal()->receivers()) {
4125 if (receiver->id() == receiver_id) {
4126 return receiver;
4127 }
4128 }
4129 }
4130 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07004131}
4132
Steve Anton4171afb2017-11-20 10:20:22 -08004133std::vector<PeerConnection::RtpSenderInfo>*
4134PeerConnection::GetRemoteSenderInfos(cricket::MediaType media_type) {
4135 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
4136 media_type == cricket::MEDIA_TYPE_VIDEO);
4137 return (media_type == cricket::MEDIA_TYPE_AUDIO)
4138 ? &remote_audio_sender_infos_
4139 : &remote_video_sender_infos_;
4140}
4141
4142std::vector<PeerConnection::RtpSenderInfo>* PeerConnection::GetLocalSenderInfos(
deadbeefab9b2d12015-10-14 11:33:11 -07004143 cricket::MediaType media_type) {
4144 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
4145 media_type == cricket::MEDIA_TYPE_VIDEO);
Steve Anton4171afb2017-11-20 10:20:22 -08004146 return (media_type == cricket::MEDIA_TYPE_AUDIO) ? &local_audio_sender_infos_
4147 : &local_video_sender_infos_;
deadbeefab9b2d12015-10-14 11:33:11 -07004148}
4149
Steve Anton4171afb2017-11-20 10:20:22 -08004150const PeerConnection::RtpSenderInfo* PeerConnection::FindSenderInfo(
4151 const std::vector<PeerConnection::RtpSenderInfo>& infos,
deadbeefab9b2d12015-10-14 11:33:11 -07004152 const std::string& stream_label,
Steve Anton4171afb2017-11-20 10:20:22 -08004153 const std::string sender_id) const {
4154 for (const RtpSenderInfo& sender_info : infos) {
4155 if (sender_info.stream_label == stream_label &&
4156 sender_info.sender_id == sender_id) {
4157 return &sender_info;
deadbeefab9b2d12015-10-14 11:33:11 -07004158 }
4159 }
4160 return nullptr;
4161}
4162
4163DataChannel* PeerConnection::FindDataChannelBySid(int sid) const {
4164 for (const auto& channel : sctp_data_channels_) {
4165 if (channel->id() == sid) {
4166 return channel;
4167 }
4168 }
4169 return nullptr;
4170}
4171
deadbeef91dd5672016-05-18 16:55:30 -07004172bool PeerConnection::InitializePortAllocator_n(
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004173 const RTCConfiguration& configuration) {
4174 cricket::ServerAddresses stun_servers;
4175 std::vector<cricket::RelayServerConfig> turn_servers;
deadbeef293e9262017-01-11 12:28:30 -08004176 if (ParseIceServers(configuration.servers, &stun_servers, &turn_servers) !=
4177 RTCErrorType::NONE) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004178 return false;
4179 }
4180
Taylor Brandstetterf8e65772016-06-27 17:20:15 -07004181 port_allocator_->Initialize();
4182
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004183 // To handle both internal and externally created port allocator, we will
4184 // enable BUNDLE here.
4185 int portallocator_flags = port_allocator_->flags();
4186 portallocator_flags |= cricket::PORTALLOCATOR_ENABLE_SHARED_SOCKET |
zhihuangb09b3f92017-03-07 14:40:51 -08004187 cricket::PORTALLOCATOR_ENABLE_IPV6 |
4188 cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI;
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004189 // If the disable-IPv6 flag was specified, we'll not override it
4190 // by experiment.
4191 if (configuration.disable_ipv6) {
4192 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
sprangc1b57a12017-02-28 08:50:47 -08004193 } else if (webrtc::field_trial::FindFullName("WebRTC-IPv6Default")
4194 .find("Disabled") == 0) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004195 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
4196 }
4197
zhihuangb09b3f92017-03-07 14:40:51 -08004198 if (configuration.disable_ipv6_on_wifi) {
4199 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI);
Mirko Bonadei675513b2017-11-09 11:09:25 +01004200 RTC_LOG(LS_INFO) << "IPv6 candidates on Wi-Fi are disabled.";
zhihuangb09b3f92017-03-07 14:40:51 -08004201 }
4202
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004203 if (configuration.tcp_candidate_policy == kTcpCandidatePolicyDisabled) {
4204 portallocator_flags |= cricket::PORTALLOCATOR_DISABLE_TCP;
Mirko Bonadei675513b2017-11-09 11:09:25 +01004205 RTC_LOG(LS_INFO) << "TCP candidates are disabled.";
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004206 }
4207
honghaiz60347052016-05-31 18:29:12 -07004208 if (configuration.candidate_network_policy ==
4209 kCandidateNetworkPolicyLowCost) {
4210 portallocator_flags |= cricket::PORTALLOCATOR_DISABLE_COSTLY_NETWORKS;
Mirko Bonadei675513b2017-11-09 11:09:25 +01004211 RTC_LOG(LS_INFO) << "Do not gather candidates on high-cost networks";
honghaiz60347052016-05-31 18:29:12 -07004212 }
4213
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004214 port_allocator_->set_flags(portallocator_flags);
4215 // No step delay is used while allocating ports.
4216 port_allocator_->set_step_delay(cricket::kMinimumStepDelay);
4217 port_allocator_->set_candidate_filter(
4218 ConvertIceTransportTypeToCandidateFilter(configuration.type));
deadbeefd21eab32017-07-26 16:50:11 -07004219 port_allocator_->set_max_ipv6_networks(configuration.max_ipv6_networks);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004220
4221 // Call this last since it may create pooled allocator sessions using the
4222 // properties set above.
4223 port_allocator_->SetConfiguration(stun_servers, turn_servers,
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -07004224 configuration.ice_candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02004225 configuration.prune_turn_ports,
4226 configuration.turn_customizer);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004227 return true;
4228}
4229
deadbeef91dd5672016-05-18 16:55:30 -07004230bool PeerConnection::ReconfigurePortAllocator_n(
deadbeef293e9262017-01-11 12:28:30 -08004231 const cricket::ServerAddresses& stun_servers,
4232 const std::vector<cricket::RelayServerConfig>& turn_servers,
4233 IceTransportsType type,
4234 int candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02004235 bool prune_turn_ports,
4236 webrtc::TurnCustomizer* turn_customizer) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004237 port_allocator_->set_candidate_filter(
deadbeef293e9262017-01-11 12:28:30 -08004238 ConvertIceTransportTypeToCandidateFilter(type));
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004239 // Call this last since it may create pooled allocator sessions using the
4240 // candidate filter set above.
deadbeef6de92f92016-12-12 18:49:32 -08004241 return port_allocator_->SetConfiguration(
Jonas Orelandbdcee282017-10-10 14:01:40 +02004242 stun_servers, turn_servers, candidate_pool_size, prune_turn_ports,
4243 turn_customizer);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004244}
4245
Steve Antonba818672017-11-06 10:21:57 -08004246cricket::ChannelManager* PeerConnection::channel_manager() const {
4247 return factory_->channel_manager();
4248}
4249
4250MetricsObserverInterface* PeerConnection::metrics_observer() const {
4251 return uma_observer_;
4252}
4253
Elad Alon99c3fe52017-10-13 16:29:40 +02004254bool PeerConnection::StartRtcEventLog_w(
Bjorn Tereliusde939432017-11-20 17:38:14 +01004255 std::unique_ptr<RtcEventLogOutput> output,
4256 int64_t output_period_ms) {
zhihuang77985012017-02-07 15:45:16 -08004257 if (!event_log_) {
4258 return false;
4259 }
Bjorn Tereliusde939432017-11-20 17:38:14 +01004260 return event_log_->StartLogging(std::move(output), output_period_ms);
ivoc14d5dbe2016-07-04 07:06:55 -07004261}
4262
4263void PeerConnection::StopRtcEventLog_w() {
zhihuang77985012017-02-07 15:45:16 -08004264 if (event_log_) {
4265 event_log_->StopLogging();
4266 }
ivoc14d5dbe2016-07-04 07:06:55 -07004267}
nisseeaabdf62017-05-05 02:23:02 -07004268
Steve Anton75737c02017-11-06 10:37:17 -08004269cricket::BaseChannel* PeerConnection::GetChannel(
4270 const std::string& content_name) {
Steve Antondcc3c022017-12-22 16:02:54 -08004271 for (auto transceiver : transceivers_) {
4272 cricket::BaseChannel* channel = transceiver->internal()->channel();
4273 if (channel && channel->content_name() == content_name) {
4274 return channel;
4275 }
Steve Anton75737c02017-11-06 10:37:17 -08004276 }
4277 if (rtp_data_channel() &&
4278 rtp_data_channel()->content_name() == content_name) {
4279 return rtp_data_channel();
4280 }
4281 return nullptr;
4282}
4283
4284bool PeerConnection::GetSctpSslRole(rtc::SSLRole* role) {
4285 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004286 RTC_LOG(LS_INFO)
4287 << "Local and Remote descriptions must be applied to get the "
4288 << "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08004289 return false;
4290 }
4291 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004292 RTC_LOG(LS_INFO) << "Non-rejected SCTP m= section is needed to get the "
4293 << "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08004294 return false;
4295 }
4296
4297 return transport_controller_->GetSslRole(*sctp_transport_name_, role);
4298}
4299
4300bool PeerConnection::GetSslRole(const std::string& content_name,
4301 rtc::SSLRole* role) {
4302 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004303 RTC_LOG(LS_INFO)
4304 << "Local and Remote descriptions must be applied to get the "
4305 << "SSL Role of the session.";
Steve Anton75737c02017-11-06 10:37:17 -08004306 return false;
4307 }
4308
4309 return transport_controller_->GetSslRole(GetTransportName(content_name),
4310 role);
4311}
4312
Steve Anton75737c02017-11-06 10:37:17 -08004313// TODO(steveanton): Eventually it'd be nice to store the channels as a single
4314// vector of BaseChannel pointers instead of separate voice and video channel
4315// vectors. At that point, this will become a simple getter.
4316std::vector<cricket::BaseChannel*> PeerConnection::Channels() const {
4317 std::vector<cricket::BaseChannel*> channels;
Steve Anton4171afb2017-11-20 10:20:22 -08004318 if (voice_channel()) {
4319 channels.push_back(voice_channel());
4320 }
4321 if (video_channel()) {
4322 channels.push_back(video_channel());
4323 }
Steve Anton75737c02017-11-06 10:37:17 -08004324 if (rtp_data_channel_) {
4325 channels.push_back(rtp_data_channel_);
4326 }
4327 return channels;
4328}
4329
Steve Antonf8470812017-12-04 10:46:21 -08004330void PeerConnection::SetSessionError(SessionError error,
4331 const std::string& error_desc) {
4332 RTC_DCHECK_RUN_ON(signaling_thread());
4333 if (error != session_error_) {
4334 session_error_ = error;
4335 session_error_desc_ = error_desc;
Steve Anton75737c02017-11-06 10:37:17 -08004336 }
4337}
4338
Steve Anton3828c062017-12-06 10:34:51 -08004339RTCError PeerConnection::UpdateSessionState(SdpType type,
Steve Anton8a006912017-12-04 15:25:56 -08004340 cricket::ContentSource source) {
4341 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08004342
4343 // If there's already a pending error then no state transition should happen.
4344 // But all call-sites should be verifying this before calling us!
Steve Antonf8470812017-12-04 10:46:21 -08004345 RTC_DCHECK(session_error() == SessionError::kNone);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004346
4347 // If this is an answer then we know whether to BUNDLE or not. If both the
4348 // local and remote side have agreed to BUNDLE, go ahead and enable it.
Steve Anton3828c062017-12-06 10:34:51 -08004349 if (type == SdpType::kAnswer) {
Steve Anton75737c02017-11-06 10:37:17 -08004350 const cricket::ContentGroup* local_bundle =
4351 local_description()->description()->GetGroupByName(
4352 cricket::GROUP_TYPE_BUNDLE);
4353 const cricket::ContentGroup* remote_bundle =
4354 remote_description()->description()->GetGroupByName(
4355 cricket::GROUP_TYPE_BUNDLE);
4356 if (local_bundle && remote_bundle) {
4357 // The answerer decides the transport to bundle on.
4358 const cricket::ContentGroup* answer_bundle =
4359 (source == cricket::CS_LOCAL ? local_bundle : remote_bundle);
4360 if (!EnableBundle(*answer_bundle)) {
Steve Anton8a006912017-12-04 15:25:56 -08004361 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
4362 kEnableBundleFailed);
Steve Anton75737c02017-11-06 10:37:17 -08004363 }
4364 }
Steve Anton75737c02017-11-06 10:37:17 -08004365 }
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004366
4367 // Only push down the transport description after potentially enabling BUNDLE;
4368 // we don't want to push down a description on a transport about to be
4369 // destroyed.
Steve Anton3828c062017-12-06 10:34:51 -08004370 RTCError error = PushdownTransportDescription(source, type);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004371 if (!error.ok()) {
4372 return error;
4373 }
4374
4375 // If this is answer-ish we're ready to let media flow.
Steve Anton3828c062017-12-06 10:34:51 -08004376 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Antoned10bd92017-12-05 10:52:59 -08004377 EnableSending();
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004378 }
4379
4380 // Update the signaling state according to the specified state machine (see
4381 // https://w3c.github.io/webrtc-pc/#rtcsignalingstate-enum).
Steve Anton3828c062017-12-06 10:34:51 -08004382 if (type == SdpType::kOffer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004383 ChangeSignalingState(source == cricket::CS_LOCAL
4384 ? PeerConnectionInterface::kHaveLocalOffer
4385 : PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton3828c062017-12-06 10:34:51 -08004386 } else if (type == SdpType::kPrAnswer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004387 ChangeSignalingState(source == cricket::CS_LOCAL
4388 ? PeerConnectionInterface::kHaveLocalPrAnswer
4389 : PeerConnectionInterface::kHaveRemotePrAnswer);
4390 } else {
Steve Anton3828c062017-12-06 10:34:51 -08004391 RTC_DCHECK(type == SdpType::kAnswer);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004392 ChangeSignalingState(PeerConnectionInterface::kStable);
4393 }
4394
4395 // Update internal objects according to the session description's media
4396 // descriptions.
Steve Anton3828c062017-12-06 10:34:51 -08004397 error = PushdownMediaDescription(type, source);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004398 if (!error.ok()) {
4399 SetSessionError(SessionError::kContent, error.message());
4400 }
4401 if (session_error() != SessionError::kNone) {
4402 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
4403 }
4404
Steve Anton8a006912017-12-04 15:25:56 -08004405 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08004406}
4407
Steve Anton8a006912017-12-04 15:25:56 -08004408RTCError PeerConnection::PushdownMediaDescription(
Steve Anton3828c062017-12-06 10:34:51 -08004409 SdpType type,
Steve Anton8a006912017-12-04 15:25:56 -08004410 cricket::ContentSource source) {
Steve Antoned10bd92017-12-05 10:52:59 -08004411 const SessionDescriptionInterface* sdesc =
4412 (source == cricket::CS_LOCAL ? local_description()
4413 : remote_description());
Steve Anton75737c02017-11-06 10:37:17 -08004414 RTC_DCHECK(sdesc);
Steve Antoned10bd92017-12-05 10:52:59 -08004415
4416 // Push down the new SDP media section for each audio/video transceiver.
4417 for (auto transceiver : transceivers_) {
Steve Anton75737c02017-11-06 10:37:17 -08004418 const ContentInfo* content_info =
Steve Antoned10bd92017-12-05 10:52:59 -08004419 FindMediaSectionForTransceiver(transceiver, sdesc);
4420 cricket::BaseChannel* channel = transceiver->internal()->channel();
4421 if (!channel || !content_info || content_info->rejected) {
Steve Anton75737c02017-11-06 10:37:17 -08004422 continue;
4423 }
4424 const MediaContentDescription* content_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08004425 content_info->media_description();
Steve Antoned10bd92017-12-05 10:52:59 -08004426 if (!content_desc) {
4427 continue;
4428 }
4429 std::string error;
4430 bool success =
4431 (source == cricket::CS_LOCAL)
Steve Anton3828c062017-12-06 10:34:51 -08004432 ? channel->SetLocalContent(content_desc, type, &error)
4433 : channel->SetRemoteContent(content_desc, type, &error);
Steve Antoned10bd92017-12-05 10:52:59 -08004434 if (!success) {
4435 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, std::move(error));
4436 }
4437 }
4438
4439 // If using the RtpDataChannel, push down the new SDP section for it too.
4440 if (rtp_data_channel_) {
4441 const ContentInfo* data_content =
4442 cricket::GetFirstDataContent(sdesc->description());
4443 if (data_content && !data_content->rejected) {
4444 const MediaContentDescription* data_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08004445 data_content->media_description();
Steve Antoned10bd92017-12-05 10:52:59 -08004446 if (data_desc) {
4447 std::string error;
4448 bool success =
4449 (source == cricket::CS_LOCAL)
Steve Anton3828c062017-12-06 10:34:51 -08004450 ? rtp_data_channel_->SetLocalContent(data_desc, type, &error)
4451 : rtp_data_channel_->SetRemoteContent(data_desc, type,
Steve Antoned10bd92017-12-05 10:52:59 -08004452 &error);
4453 if (!success) {
4454 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
4455 std::move(error));
4456 }
Steve Anton75737c02017-11-06 10:37:17 -08004457 }
4458 }
4459 }
Steve Antoned10bd92017-12-05 10:52:59 -08004460
Steve Anton75737c02017-11-06 10:37:17 -08004461 // Need complete offer/answer with an SCTP m= section before starting SCTP,
4462 // according to https://tools.ietf.org/html/draft-ietf-mmusic-sctp-sdp-19
4463 if (sctp_transport_ && local_description() && remote_description() &&
4464 cricket::GetFirstDataContent(local_description()->description()) &&
4465 cricket::GetFirstDataContent(remote_description()->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08004466 bool success = network_thread()->Invoke<bool>(
Steve Anton75737c02017-11-06 10:37:17 -08004467 RTC_FROM_HERE,
4468 rtc::Bind(&PeerConnection::PushdownSctpParameters_n, this, source));
Steve Anton8a006912017-12-04 15:25:56 -08004469 if (!success) {
4470 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
4471 "Failed to push down SCTP parameters.");
4472 }
Steve Anton75737c02017-11-06 10:37:17 -08004473 }
Steve Antoned10bd92017-12-05 10:52:59 -08004474
Steve Anton8a006912017-12-04 15:25:56 -08004475 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08004476}
4477
4478bool PeerConnection::PushdownSctpParameters_n(cricket::ContentSource source) {
4479 RTC_DCHECK(network_thread()->IsCurrent());
4480 RTC_DCHECK(local_description());
4481 RTC_DCHECK(remote_description());
4482 // Apply the SCTP port (which is hidden inside a DataCodec structure...)
4483 // When we support "max-message-size", that would also be pushed down here.
4484 return sctp_transport_->Start(
4485 GetSctpPort(local_description()->description()),
4486 GetSctpPort(remote_description()->description()));
4487}
4488
Steve Anton8a006912017-12-04 15:25:56 -08004489RTCError PeerConnection::PushdownTransportDescription(
4490 cricket::ContentSource source,
Steve Anton3828c062017-12-06 10:34:51 -08004491 SdpType type) {
Steve Anton8a006912017-12-04 15:25:56 -08004492 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08004493
Steve Anton8a006912017-12-04 15:25:56 -08004494 const SessionDescriptionInterface* sdesc =
4495 (source == cricket::CS_LOCAL ? local_description()
4496 : remote_description());
4497 RTC_DCHECK(sdesc);
4498 for (const cricket::TransportInfo& tinfo :
4499 sdesc->description()->transport_infos()) {
4500 std::string error;
4501 bool success;
4502 if (source == cricket::CS_LOCAL) {
4503 success = transport_controller_->SetLocalTransportDescription(
Steve Anton3828c062017-12-06 10:34:51 -08004504 tinfo.content_name, tinfo.description, type, &error);
Steve Anton8a006912017-12-04 15:25:56 -08004505 } else {
4506 success = transport_controller_->SetRemoteTransportDescription(
Steve Anton3828c062017-12-06 10:34:51 -08004507 tinfo.content_name, tinfo.description, type, &error);
Steve Anton8a006912017-12-04 15:25:56 -08004508 }
4509 if (!success) {
Steve Antondcc3c022017-12-22 16:02:54 -08004510 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
4511 "Failed to push down transport description for " +
4512 tinfo.content_name + ": " + error);
Steve Anton75737c02017-11-06 10:37:17 -08004513 }
4514 }
4515
Steve Anton8a006912017-12-04 15:25:56 -08004516 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08004517}
4518
4519bool PeerConnection::GetTransportDescription(
4520 const SessionDescription* description,
4521 const std::string& content_name,
4522 cricket::TransportDescription* tdesc) {
4523 if (!description || !tdesc) {
4524 return false;
4525 }
4526 const TransportInfo* transport_info =
4527 description->GetTransportInfoByName(content_name);
4528 if (!transport_info) {
4529 return false;
4530 }
4531 *tdesc = transport_info->description;
4532 return true;
4533}
4534
4535bool PeerConnection::EnableBundle(const cricket::ContentGroup& bundle) {
4536 const std::string* first_content_name = bundle.FirstContentName();
4537 if (!first_content_name) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004538 RTC_LOG(LS_WARNING) << "Tried to BUNDLE with no contents.";
Steve Anton75737c02017-11-06 10:37:17 -08004539 return false;
4540 }
4541 const std::string& transport_name = *first_content_name;
4542
4543 auto maybe_set_transport = [this, bundle,
4544 transport_name](cricket::BaseChannel* ch) {
4545 if (!ch || !bundle.HasContentName(ch->content_name())) {
Steve Antoned10bd92017-12-05 10:52:59 -08004546 return;
Steve Anton75737c02017-11-06 10:37:17 -08004547 }
4548
4549 std::string old_transport_name = ch->transport_name();
4550 if (old_transport_name == transport_name) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004551 RTC_LOG(LS_INFO) << "BUNDLE already enabled for " << ch->content_name()
4552 << " on " << transport_name << ".";
Steve Antoned10bd92017-12-05 10:52:59 -08004553 return;
Steve Anton75737c02017-11-06 10:37:17 -08004554 }
4555
4556 cricket::DtlsTransportInternal* rtp_dtls_transport =
4557 transport_controller_->CreateDtlsTransport(
4558 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4559 bool need_rtcp = (ch->rtcp_dtls_transport() != nullptr);
4560 cricket::DtlsTransportInternal* rtcp_dtls_transport = nullptr;
4561 if (need_rtcp) {
4562 rtcp_dtls_transport = transport_controller_->CreateDtlsTransport(
4563 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
4564 }
4565
4566 ch->SetTransports(rtp_dtls_transport, rtcp_dtls_transport);
Mirko Bonadei675513b2017-11-09 11:09:25 +01004567 RTC_LOG(LS_INFO) << "Enabled BUNDLE for " << ch->content_name() << " on "
4568 << transport_name << ".";
Steve Anton75737c02017-11-06 10:37:17 -08004569 transport_controller_->DestroyDtlsTransport(
4570 old_transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4571 // If the channel needs rtcp, it means that the channel used to have a
4572 // rtcp transport which needs to be deleted now.
4573 if (need_rtcp) {
4574 transport_controller_->DestroyDtlsTransport(
4575 old_transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
4576 }
Steve Anton75737c02017-11-06 10:37:17 -08004577 };
4578
Steve Antoned10bd92017-12-05 10:52:59 -08004579 for (auto transceiver : transceivers_) {
4580 maybe_set_transport(transceiver->internal()->channel());
Steve Anton75737c02017-11-06 10:37:17 -08004581 }
Steve Antoned10bd92017-12-05 10:52:59 -08004582 maybe_set_transport(rtp_data_channel_);
4583
Steve Anton75737c02017-11-06 10:37:17 -08004584 // For SCTP, transport creation/deletion happens here instead of in the
4585 // object itself.
4586 if (sctp_transport_) {
4587 RTC_DCHECK(sctp_transport_name_);
4588 RTC_DCHECK(sctp_content_name_);
4589 if (transport_name != *sctp_transport_name_ &&
4590 bundle.HasContentName(*sctp_content_name_)) {
4591 network_thread()->Invoke<void>(
4592 RTC_FROM_HERE, rtc::Bind(&PeerConnection::ChangeSctpTransport_n, this,
4593 transport_name));
4594 }
4595 }
4596
4597 return true;
4598}
4599
Steve Anton75737c02017-11-06 10:37:17 -08004600cricket::IceConfig PeerConnection::ParseIceConfig(
4601 const PeerConnectionInterface::RTCConfiguration& config) const {
4602 cricket::ContinualGatheringPolicy gathering_policy;
4603 // TODO(honghaiz): Add the third continual gathering policy in
4604 // PeerConnectionInterface and map it to GATHER_CONTINUALLY_AND_RECOVER.
4605 switch (config.continual_gathering_policy) {
4606 case PeerConnectionInterface::GATHER_ONCE:
4607 gathering_policy = cricket::GATHER_ONCE;
4608 break;
4609 case PeerConnectionInterface::GATHER_CONTINUALLY:
4610 gathering_policy = cricket::GATHER_CONTINUALLY;
4611 break;
4612 default:
4613 RTC_NOTREACHED();
4614 gathering_policy = cricket::GATHER_ONCE;
4615 }
4616 cricket::IceConfig ice_config;
4617 ice_config.receiving_timeout = config.ice_connection_receiving_timeout;
4618 ice_config.prioritize_most_likely_candidate_pairs =
4619 config.prioritize_most_likely_ice_candidate_pairs;
4620 ice_config.backup_connection_ping_interval =
4621 config.ice_backup_candidate_pair_ping_interval;
4622 ice_config.continual_gathering_policy = gathering_policy;
4623 ice_config.presume_writable_when_fully_relayed =
4624 config.presume_writable_when_fully_relayed;
4625 ice_config.ice_check_min_interval = config.ice_check_min_interval;
4626 ice_config.regather_all_networks_interval_range =
4627 config.ice_regather_interval_range;
4628 return ice_config;
4629}
4630
Steve Anton75737c02017-11-06 10:37:17 -08004631bool PeerConnection::GetLocalTrackIdBySsrc(uint32_t ssrc,
4632 std::string* track_id) {
4633 if (!local_description()) {
4634 return false;
4635 }
4636 return webrtc::GetTrackIdBySsrc(local_description()->description(), ssrc,
4637 track_id);
4638}
4639
4640bool PeerConnection::GetRemoteTrackIdBySsrc(uint32_t ssrc,
4641 std::string* track_id) {
4642 if (!remote_description()) {
4643 return false;
4644 }
4645 return webrtc::GetTrackIdBySsrc(remote_description()->description(), ssrc,
4646 track_id);
4647}
4648
4649bool PeerConnection::SendData(const cricket::SendDataParams& params,
4650 const rtc::CopyOnWriteBuffer& payload,
4651 cricket::SendDataResult* result) {
4652 if (!rtp_data_channel_ && !sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004653 RTC_LOG(LS_ERROR) << "SendData called when rtp_data_channel_ "
4654 << "and sctp_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08004655 return false;
4656 }
4657 return rtp_data_channel_
4658 ? rtp_data_channel_->SendData(params, payload, result)
4659 : network_thread()->Invoke<bool>(
4660 RTC_FROM_HERE,
4661 Bind(&cricket::SctpTransportInternal::SendData,
4662 sctp_transport_.get(), params, payload, result));
4663}
4664
4665bool PeerConnection::ConnectDataChannel(DataChannel* webrtc_data_channel) {
4666 if (!rtp_data_channel_ && !sctp_transport_) {
4667 // Don't log an error here, because DataChannels are expected to call
4668 // ConnectDataChannel in this state. It's the only way to initially tell
4669 // whether or not the underlying transport is ready.
4670 return false;
4671 }
4672 if (rtp_data_channel_) {
4673 rtp_data_channel_->SignalReadyToSendData.connect(
4674 webrtc_data_channel, &DataChannel::OnChannelReady);
4675 rtp_data_channel_->SignalDataReceived.connect(webrtc_data_channel,
4676 &DataChannel::OnDataReceived);
4677 } else {
4678 SignalSctpReadyToSendData.connect(webrtc_data_channel,
4679 &DataChannel::OnChannelReady);
4680 SignalSctpDataReceived.connect(webrtc_data_channel,
4681 &DataChannel::OnDataReceived);
4682 SignalSctpStreamClosedRemotely.connect(
4683 webrtc_data_channel, &DataChannel::OnStreamClosedRemotely);
4684 }
4685 return true;
4686}
4687
4688void PeerConnection::DisconnectDataChannel(DataChannel* webrtc_data_channel) {
4689 if (!rtp_data_channel_ && !sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004690 RTC_LOG(LS_ERROR)
4691 << "DisconnectDataChannel called when rtp_data_channel_ and "
4692 "sctp_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08004693 return;
4694 }
4695 if (rtp_data_channel_) {
4696 rtp_data_channel_->SignalReadyToSendData.disconnect(webrtc_data_channel);
4697 rtp_data_channel_->SignalDataReceived.disconnect(webrtc_data_channel);
4698 } else {
4699 SignalSctpReadyToSendData.disconnect(webrtc_data_channel);
4700 SignalSctpDataReceived.disconnect(webrtc_data_channel);
4701 SignalSctpStreamClosedRemotely.disconnect(webrtc_data_channel);
4702 }
4703}
4704
4705void PeerConnection::AddSctpDataStream(int sid) {
4706 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004707 RTC_LOG(LS_ERROR)
4708 << "AddSctpDataStream called when sctp_transport_ is NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08004709 return;
4710 }
4711 network_thread()->Invoke<void>(
4712 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::OpenStream,
4713 sctp_transport_.get(), sid));
4714}
4715
4716void PeerConnection::RemoveSctpDataStream(int sid) {
4717 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004718 RTC_LOG(LS_ERROR) << "RemoveSctpDataStream called when sctp_transport_ is "
4719 << "NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08004720 return;
4721 }
4722 network_thread()->Invoke<void>(
4723 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::ResetStream,
4724 sctp_transport_.get(), sid));
4725}
4726
4727bool PeerConnection::ReadyToSendData() const {
4728 return (rtp_data_channel_ && rtp_data_channel_->ready_to_send_data()) ||
4729 sctp_ready_to_send_data_;
4730}
4731
4732std::unique_ptr<SessionStats> PeerConnection::GetSessionStats_s() {
4733 RTC_DCHECK(signaling_thread()->IsCurrent());
4734 ChannelNamePairs channel_name_pairs;
4735 if (voice_channel()) {
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004736 channel_name_pairs.voice = ChannelNamePair(
4737 voice_channel()->content_name(), voice_channel()->transport_name());
Steve Anton75737c02017-11-06 10:37:17 -08004738 }
4739 if (video_channel()) {
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004740 channel_name_pairs.video = ChannelNamePair(
4741 video_channel()->content_name(), video_channel()->transport_name());
Steve Anton75737c02017-11-06 10:37:17 -08004742 }
4743 if (rtp_data_channel()) {
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004744 channel_name_pairs.data =
Steve Anton75737c02017-11-06 10:37:17 -08004745 ChannelNamePair(rtp_data_channel()->content_name(),
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004746 rtp_data_channel()->transport_name());
Steve Anton75737c02017-11-06 10:37:17 -08004747 }
4748 if (sctp_transport_) {
4749 RTC_DCHECK(sctp_content_name_);
4750 RTC_DCHECK(sctp_transport_name_);
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004751 channel_name_pairs.data =
4752 ChannelNamePair(*sctp_content_name_, *sctp_transport_name_);
Steve Anton75737c02017-11-06 10:37:17 -08004753 }
4754 return GetSessionStats(channel_name_pairs);
4755}
4756
4757std::unique_ptr<SessionStats> PeerConnection::GetSessionStats(
4758 const ChannelNamePairs& channel_name_pairs) {
4759 if (network_thread()->IsCurrent()) {
4760 return GetSessionStats_n(channel_name_pairs);
4761 }
4762 return network_thread()->Invoke<std::unique_ptr<SessionStats>>(
4763 RTC_FROM_HERE,
4764 rtc::Bind(&PeerConnection::GetSessionStats_n, this, channel_name_pairs));
4765}
4766
4767bool PeerConnection::GetLocalCertificate(
4768 const std::string& transport_name,
4769 rtc::scoped_refptr<rtc::RTCCertificate>* certificate) {
4770 return transport_controller_->GetLocalCertificate(transport_name,
4771 certificate);
4772}
4773
4774std::unique_ptr<rtc::SSLCertificate> PeerConnection::GetRemoteSSLCertificate(
4775 const std::string& transport_name) {
4776 return transport_controller_->GetRemoteSSLCertificate(transport_name);
4777}
4778
4779cricket::DataChannelType PeerConnection::data_channel_type() const {
4780 return data_channel_type_;
4781}
4782
4783bool PeerConnection::IceRestartPending(const std::string& content_name) const {
4784 return pending_ice_restarts_.find(content_name) !=
4785 pending_ice_restarts_.end();
4786}
4787
Steve Anton75737c02017-11-06 10:37:17 -08004788bool PeerConnection::NeedsIceRestart(const std::string& content_name) const {
4789 return transport_controller_->NeedsIceRestart(content_name);
4790}
4791
4792void PeerConnection::OnCertificateReady(
4793 const rtc::scoped_refptr<rtc::RTCCertificate>& certificate) {
4794 transport_controller_->SetLocalCertificate(certificate);
4795}
4796
4797void PeerConnection::OnDtlsSrtpSetupFailure(cricket::BaseChannel*, bool rtcp) {
Steve Antonf8470812017-12-04 10:46:21 -08004798 SetSessionError(SessionError::kTransport,
4799 rtcp ? kDtlsSrtpSetupFailureRtcp : kDtlsSrtpSetupFailureRtp);
Steve Anton75737c02017-11-06 10:37:17 -08004800}
4801
4802void PeerConnection::OnTransportControllerConnectionState(
4803 cricket::IceConnectionState state) {
4804 switch (state) {
4805 case cricket::kIceConnectionConnecting:
4806 // If the current state is Connected or Completed, then there were
4807 // writable channels but now there are not, so the next state must
4808 // be Disconnected.
4809 // kIceConnectionConnecting is currently used as the default,
4810 // un-connected state by the TransportController, so its only use is
4811 // detecting disconnections.
4812 if (ice_connection_state_ ==
4813 PeerConnectionInterface::kIceConnectionConnected ||
4814 ice_connection_state_ ==
4815 PeerConnectionInterface::kIceConnectionCompleted) {
4816 SetIceConnectionState(
4817 PeerConnectionInterface::kIceConnectionDisconnected);
4818 }
4819 break;
4820 case cricket::kIceConnectionFailed:
4821 SetIceConnectionState(PeerConnectionInterface::kIceConnectionFailed);
4822 break;
4823 case cricket::kIceConnectionConnected:
Mirko Bonadei675513b2017-11-09 11:09:25 +01004824 RTC_LOG(LS_INFO) << "Changing to ICE connected state because "
4825 << "all transports are writable.";
Steve Anton75737c02017-11-06 10:37:17 -08004826 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
4827 break;
4828 case cricket::kIceConnectionCompleted:
Mirko Bonadei675513b2017-11-09 11:09:25 +01004829 RTC_LOG(LS_INFO) << "Changing to ICE completed state because "
4830 << "all transports are complete.";
Steve Anton75737c02017-11-06 10:37:17 -08004831 if (ice_connection_state_ !=
4832 PeerConnectionInterface::kIceConnectionConnected) {
4833 // If jumping directly from "checking" to "connected",
4834 // signal "connected" first.
4835 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
4836 }
4837 SetIceConnectionState(PeerConnectionInterface::kIceConnectionCompleted);
4838 if (metrics_observer()) {
4839 ReportTransportStats();
4840 }
4841 break;
4842 default:
4843 RTC_NOTREACHED();
4844 }
4845}
4846
4847void PeerConnection::OnTransportControllerCandidatesGathered(
4848 const std::string& transport_name,
4849 const cricket::Candidates& candidates) {
4850 RTC_DCHECK(signaling_thread()->IsCurrent());
4851 int sdp_mline_index;
4852 if (!GetLocalCandidateMediaIndex(transport_name, &sdp_mline_index)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004853 RTC_LOG(LS_ERROR)
4854 << "OnTransportControllerCandidatesGathered: content name "
4855 << transport_name << " not found";
Steve Anton75737c02017-11-06 10:37:17 -08004856 return;
4857 }
4858
4859 for (cricket::Candidates::const_iterator citer = candidates.begin();
4860 citer != candidates.end(); ++citer) {
4861 // Use transport_name as the candidate media id.
4862 std::unique_ptr<JsepIceCandidate> candidate(
4863 new JsepIceCandidate(transport_name, sdp_mline_index, *citer));
4864 if (local_description()) {
4865 mutable_local_description()->AddCandidate(candidate.get());
4866 }
4867 OnIceCandidate(std::move(candidate));
4868 }
4869}
4870
4871void PeerConnection::OnTransportControllerCandidatesRemoved(
4872 const std::vector<cricket::Candidate>& candidates) {
4873 RTC_DCHECK(signaling_thread()->IsCurrent());
4874 // Sanity check.
4875 for (const cricket::Candidate& candidate : candidates) {
4876 if (candidate.transport_name().empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004877 RTC_LOG(LS_ERROR) << "OnTransportControllerCandidatesRemoved: "
4878 << "empty content name in candidate "
4879 << candidate.ToString();
Steve Anton75737c02017-11-06 10:37:17 -08004880 return;
4881 }
4882 }
4883
4884 if (local_description()) {
4885 mutable_local_description()->RemoveCandidates(candidates);
4886 }
4887 OnIceCandidatesRemoved(candidates);
4888}
4889
4890void PeerConnection::OnTransportControllerDtlsHandshakeError(
4891 rtc::SSLHandshakeError error) {
4892 if (metrics_observer()) {
4893 metrics_observer()->IncrementEnumCounter(
4894 webrtc::kEnumCounterDtlsHandshakeError, static_cast<int>(error),
4895 static_cast<int>(rtc::SSLHandshakeError::MAX_VALUE));
4896 }
4897}
4898
Steve Antoned10bd92017-12-05 10:52:59 -08004899void PeerConnection::EnableSending() {
4900 for (auto transceiver : transceivers_) {
4901 cricket::BaseChannel* channel = transceiver->internal()->channel();
4902 if (channel && !channel->enabled()) {
4903 channel->Enable(true);
4904 }
Steve Anton75737c02017-11-06 10:37:17 -08004905 }
4906
Steve Anton4171afb2017-11-20 10:20:22 -08004907 if (rtp_data_channel_ && !rtp_data_channel_->enabled()) {
Steve Anton75737c02017-11-06 10:37:17 -08004908 rtp_data_channel_->Enable(true);
Steve Anton4171afb2017-11-20 10:20:22 -08004909 }
Steve Anton75737c02017-11-06 10:37:17 -08004910}
4911
4912// Returns the media index for a local ice candidate given the content name.
4913bool PeerConnection::GetLocalCandidateMediaIndex(
4914 const std::string& content_name,
4915 int* sdp_mline_index) {
4916 if (!local_description() || !sdp_mline_index) {
4917 return false;
4918 }
4919
4920 bool content_found = false;
4921 const ContentInfos& contents = local_description()->description()->contents();
4922 for (size_t index = 0; index < contents.size(); ++index) {
4923 if (contents[index].name == content_name) {
4924 *sdp_mline_index = static_cast<int>(index);
4925 content_found = true;
4926 break;
4927 }
4928 }
4929 return content_found;
4930}
4931
4932bool PeerConnection::UseCandidatesInSessionDescription(
4933 const SessionDescriptionInterface* remote_desc) {
4934 if (!remote_desc) {
4935 return true;
4936 }
4937 bool ret = true;
4938
4939 for (size_t m = 0; m < remote_desc->number_of_mediasections(); ++m) {
4940 const IceCandidateCollection* candidates = remote_desc->candidates(m);
4941 for (size_t n = 0; n < candidates->count(); ++n) {
4942 const IceCandidateInterface* candidate = candidates->at(n);
4943 bool valid = false;
4944 if (!ReadyToUseRemoteCandidate(candidate, remote_desc, &valid)) {
4945 if (valid) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004946 RTC_LOG(LS_INFO)
4947 << "UseCandidatesInSessionDescription: Not ready to use "
4948 << "candidate.";
Steve Anton75737c02017-11-06 10:37:17 -08004949 }
4950 continue;
4951 }
4952 ret = UseCandidate(candidate);
4953 if (!ret) {
4954 break;
4955 }
4956 }
4957 }
4958 return ret;
4959}
4960
4961bool PeerConnection::UseCandidate(const IceCandidateInterface* candidate) {
4962 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
4963 size_t remote_content_size =
4964 remote_description()->description()->contents().size();
4965 if (mediacontent_index >= remote_content_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004966 RTC_LOG(LS_ERROR) << "UseCandidate: Invalid candidate media index.";
Steve Anton75737c02017-11-06 10:37:17 -08004967 return false;
4968 }
4969
4970 cricket::ContentInfo content =
4971 remote_description()->description()->contents()[mediacontent_index];
4972 std::vector<cricket::Candidate> candidates;
4973 candidates.push_back(candidate->candidate());
4974 // Invoking BaseSession method to handle remote candidates.
4975 std::string error;
4976 if (transport_controller_->AddRemoteCandidates(content.name, candidates,
4977 &error)) {
4978 // Candidates successfully submitted for checking.
4979 if (ice_connection_state_ == PeerConnectionInterface::kIceConnectionNew ||
4980 ice_connection_state_ ==
4981 PeerConnectionInterface::kIceConnectionDisconnected) {
4982 // If state is New, then the session has just gotten its first remote ICE
4983 // candidates, so go to Checking.
4984 // If state is Disconnected, the session is re-using old candidates or
4985 // receiving additional ones, so go to Checking.
4986 // If state is Connected, stay Connected.
4987 // TODO(bemasc): If state is Connected, and the new candidates are for a
4988 // newly added transport, then the state actually _should_ move to
4989 // checking. Add a way to distinguish that case.
4990 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
4991 }
4992 // TODO(bemasc): If state is Completed, go back to Connected.
4993 } else {
4994 if (!error.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004995 RTC_LOG(LS_WARNING) << error;
Steve Anton75737c02017-11-06 10:37:17 -08004996 }
4997 }
4998 return true;
4999}
5000
5001void PeerConnection::RemoveUnusedChannels(const SessionDescription* desc) {
Steve Anton75737c02017-11-06 10:37:17 -08005002 // Destroy video channel first since it may have a pointer to the
5003 // voice channel.
5004 const cricket::ContentInfo* video_info = cricket::GetFirstVideoContent(desc);
Steve Anton6fec8802017-12-04 10:37:29 -08005005 if (!video_info || video_info->rejected) {
5006 DestroyTransceiverChannel(GetVideoTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08005007 }
5008
Steve Anton6fec8802017-12-04 10:37:29 -08005009 const cricket::ContentInfo* audio_info = cricket::GetFirstAudioContent(desc);
5010 if (!audio_info || audio_info->rejected) {
5011 DestroyTransceiverChannel(GetAudioTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08005012 }
5013
5014 const cricket::ContentInfo* data_info = cricket::GetFirstDataContent(desc);
5015 if (!data_info || data_info->rejected) {
Steve Anton6fec8802017-12-04 10:37:29 -08005016 DestroyDataChannel();
Steve Anton75737c02017-11-06 10:37:17 -08005017 }
5018}
5019
Steve Antoneda6ccd2017-12-04 10:21:55 -08005020std::string PeerConnection::GetTransportNameForMediaSection(
5021 const std::string& mid,
5022 const cricket::ContentGroup* bundle_group) const {
5023 if (!bundle_group) {
5024 return mid;
Steve Anton75737c02017-11-06 10:37:17 -08005025 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005026 const std::string* first_content_name = bundle_group->FirstContentName();
Steve Anton75737c02017-11-06 10:37:17 -08005027 if (!first_content_name) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005028 RTC_LOG(LS_WARNING) << "Tried to BUNDLE with no contents.";
Steve Antoneda6ccd2017-12-04 10:21:55 -08005029 return mid;
Steve Anton75737c02017-11-06 10:37:17 -08005030 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005031 if (!bundle_group->HasContentName(mid)) {
5032 RTC_LOG(LS_WARNING) << mid << " is not part of any bundle group";
5033 return mid;
Steve Anton75737c02017-11-06 10:37:17 -08005034 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005035 RTC_LOG(LS_INFO) << "Bundling " << mid << " on " << *first_content_name;
5036 return *first_content_name;
Steve Anton75737c02017-11-06 10:37:17 -08005037}
5038
Steve Antondcc3c022017-12-22 16:02:54 -08005039RTCErrorOr<const cricket::ContentGroup*> PeerConnection::GetEarlyBundleGroup(
5040 const SessionDescription& desc) const {
Steve Anton75737c02017-11-06 10:37:17 -08005041 const cricket::ContentGroup* bundle_group = nullptr;
5042 if (configuration_.bundle_policy ==
5043 PeerConnectionInterface::kBundlePolicyMaxBundle) {
Steve Antondcc3c022017-12-22 16:02:54 -08005044 bundle_group = desc.GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton75737c02017-11-06 10:37:17 -08005045 if (!bundle_group) {
Steve Anton8a006912017-12-04 15:25:56 -08005046 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5047 "max-bundle configured but session description "
5048 "has no BUNDLE group");
Steve Anton75737c02017-11-06 10:37:17 -08005049 }
5050 }
Steve Antondcc3c022017-12-22 16:02:54 -08005051 return std::move(bundle_group);
5052}
5053
5054RTCError PeerConnection::CreateChannels(const SessionDescription& desc) {
5055 auto bundle_group_or_error = GetEarlyBundleGroup(desc);
5056 if (!bundle_group_or_error.ok()) {
5057 return bundle_group_or_error.MoveError();
5058 }
5059 const cricket::ContentGroup* bundle_group = bundle_group_or_error.MoveValue();
Steve Anton75737c02017-11-06 10:37:17 -08005060
Steve Antoneda6ccd2017-12-04 10:21:55 -08005061 // Creating the media channels and transport proxies.
Steve Antondcc3c022017-12-22 16:02:54 -08005062 const cricket::ContentInfo* voice = cricket::GetFirstAudioContent(&desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08005063 if (voice && !voice->rejected &&
5064 !GetAudioTransceiver()->internal()->channel()) {
5065 cricket::VoiceChannel* voice_channel = CreateVoiceChannel(
5066 voice->name,
5067 GetTransportNameForMediaSection(voice->name, bundle_group));
5068 if (!voice_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08005069 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5070 "Failed to create voice channel.");
Steve Antoneda6ccd2017-12-04 10:21:55 -08005071 }
5072 GetAudioTransceiver()->internal()->SetChannel(voice_channel);
5073 }
5074
Steve Antondcc3c022017-12-22 16:02:54 -08005075 const cricket::ContentInfo* video = cricket::GetFirstVideoContent(&desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08005076 if (video && !video->rejected &&
5077 !GetVideoTransceiver()->internal()->channel()) {
5078 cricket::VideoChannel* video_channel = CreateVideoChannel(
5079 video->name,
5080 GetTransportNameForMediaSection(video->name, bundle_group));
5081 if (!video_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08005082 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5083 "Failed to create video channel.");
Steve Anton75737c02017-11-06 10:37:17 -08005084 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005085 GetVideoTransceiver()->internal()->SetChannel(video_channel);
Steve Anton75737c02017-11-06 10:37:17 -08005086 }
5087
Steve Antondcc3c022017-12-22 16:02:54 -08005088 const cricket::ContentInfo* data = cricket::GetFirstDataContent(&desc);
Steve Anton75737c02017-11-06 10:37:17 -08005089 if (data_channel_type_ != cricket::DCT_NONE && data && !data->rejected &&
5090 !rtp_data_channel_ && !sctp_transport_) {
Steve Antoneda6ccd2017-12-04 10:21:55 -08005091 if (!CreateDataChannel(data->name, GetTransportNameForMediaSection(
5092 data->name, bundle_group))) {
Steve Anton8a006912017-12-04 15:25:56 -08005093 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5094 "Failed to create data channel.");
Steve Anton75737c02017-11-06 10:37:17 -08005095 }
5096 }
5097
Steve Anton8a006912017-12-04 15:25:56 -08005098 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08005099}
5100
Steve Anton4171afb2017-11-20 10:20:22 -08005101// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08005102cricket::VoiceChannel* PeerConnection::CreateVoiceChannel(
5103 const std::string& mid,
5104 const std::string& transport_name) {
Steve Anton75737c02017-11-06 10:37:17 -08005105 cricket::DtlsTransportInternal* rtp_dtls_transport =
5106 transport_controller_->CreateDtlsTransport(
5107 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5108 cricket::DtlsTransportInternal* rtcp_dtls_transport = nullptr;
5109 if (configuration_.rtcp_mux_policy !=
5110 PeerConnectionInterface::kRtcpMuxPolicyRequire) {
5111 rtcp_dtls_transport = transport_controller_->CreateDtlsTransport(
5112 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
5113 }
5114
5115 cricket::VoiceChannel* voice_channel = channel_manager()->CreateVoiceChannel(
5116 call_.get(), configuration_.media_config, rtp_dtls_transport,
Steve Antoneda6ccd2017-12-04 10:21:55 -08005117 rtcp_dtls_transport, signaling_thread(), mid, SrtpRequired(),
5118 audio_options_);
Steve Anton75737c02017-11-06 10:37:17 -08005119 if (!voice_channel) {
5120 transport_controller_->DestroyDtlsTransport(
5121 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5122 if (rtcp_dtls_transport) {
5123 transport_controller_->DestroyDtlsTransport(
5124 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
5125 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005126 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08005127 }
Steve Anton75737c02017-11-06 10:37:17 -08005128 voice_channel->SignalRtcpMuxFullyActive.connect(
5129 this, &PeerConnection::DestroyRtcpTransport_n);
5130 voice_channel->SignalDtlsSrtpSetupFailure.connect(
5131 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08005132 voice_channel->SignalSentPacket.connect(this,
5133 &PeerConnection::OnSentPacket_w);
Steve Anton4171afb2017-11-20 10:20:22 -08005134
Steve Antoneda6ccd2017-12-04 10:21:55 -08005135 return voice_channel;
Steve Anton75737c02017-11-06 10:37:17 -08005136}
5137
Steve Anton4171afb2017-11-20 10:20:22 -08005138// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08005139cricket::VideoChannel* PeerConnection::CreateVideoChannel(
5140 const std::string& mid,
5141 const std::string& transport_name) {
Steve Anton75737c02017-11-06 10:37:17 -08005142 cricket::DtlsTransportInternal* rtp_dtls_transport =
5143 transport_controller_->CreateDtlsTransport(
5144 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5145 cricket::DtlsTransportInternal* rtcp_dtls_transport = nullptr;
5146 if (configuration_.rtcp_mux_policy !=
5147 PeerConnectionInterface::kRtcpMuxPolicyRequire) {
5148 rtcp_dtls_transport = transport_controller_->CreateDtlsTransport(
5149 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
5150 }
5151
5152 cricket::VideoChannel* video_channel = channel_manager()->CreateVideoChannel(
5153 call_.get(), configuration_.media_config, rtp_dtls_transport,
Steve Antoneda6ccd2017-12-04 10:21:55 -08005154 rtcp_dtls_transport, signaling_thread(), mid, SrtpRequired(),
5155 video_options_);
Steve Anton75737c02017-11-06 10:37:17 -08005156
5157 if (!video_channel) {
5158 transport_controller_->DestroyDtlsTransport(
5159 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5160 if (rtcp_dtls_transport) {
5161 transport_controller_->DestroyDtlsTransport(
5162 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
5163 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005164 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08005165 }
Steve Anton75737c02017-11-06 10:37:17 -08005166 video_channel->SignalRtcpMuxFullyActive.connect(
5167 this, &PeerConnection::DestroyRtcpTransport_n);
5168 video_channel->SignalDtlsSrtpSetupFailure.connect(
5169 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08005170 video_channel->SignalSentPacket.connect(this,
5171 &PeerConnection::OnSentPacket_w);
Steve Anton4171afb2017-11-20 10:20:22 -08005172
Steve Antoneda6ccd2017-12-04 10:21:55 -08005173 return video_channel;
Steve Anton75737c02017-11-06 10:37:17 -08005174}
5175
Steve Antoneda6ccd2017-12-04 10:21:55 -08005176bool PeerConnection::CreateDataChannel(const std::string& mid,
5177 const std::string& transport_name) {
Steve Anton75737c02017-11-06 10:37:17 -08005178 bool sctp = (data_channel_type_ == cricket::DCT_SCTP);
5179 if (sctp) {
5180 if (!sctp_factory_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005181 RTC_LOG(LS_ERROR)
Steve Anton75737c02017-11-06 10:37:17 -08005182 << "Trying to create SCTP transport, but didn't compile with "
5183 "SCTP support (HAVE_SCTP)";
5184 return false;
5185 }
5186 if (!network_thread()->Invoke<bool>(
5187 RTC_FROM_HERE, rtc::Bind(&PeerConnection::CreateSctpTransport_n,
Steve Antoneda6ccd2017-12-04 10:21:55 -08005188 this, mid, transport_name))) {
Steve Anton75737c02017-11-06 10:37:17 -08005189 return false;
5190 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005191 for (const auto& channel : sctp_data_channels_) {
5192 channel->OnTransportChannelCreated();
5193 }
Steve Anton75737c02017-11-06 10:37:17 -08005194 } else {
Steve Anton75737c02017-11-06 10:37:17 -08005195 cricket::DtlsTransportInternal* rtp_dtls_transport =
5196 transport_controller_->CreateDtlsTransport(
5197 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5198 cricket::DtlsTransportInternal* rtcp_dtls_transport = nullptr;
5199 if (configuration_.rtcp_mux_policy !=
5200 PeerConnectionInterface::kRtcpMuxPolicyRequire) {
5201 rtcp_dtls_transport = transport_controller_->CreateDtlsTransport(
5202 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
5203 }
5204
5205 rtp_data_channel_ = channel_manager()->CreateRtpDataChannel(
5206 configuration_.media_config, rtp_dtls_transport, rtcp_dtls_transport,
Steve Antoneda6ccd2017-12-04 10:21:55 -08005207 signaling_thread(), mid, SrtpRequired());
Steve Anton75737c02017-11-06 10:37:17 -08005208
5209 if (!rtp_data_channel_) {
5210 transport_controller_->DestroyDtlsTransport(
5211 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5212 if (rtcp_dtls_transport) {
5213 transport_controller_->DestroyDtlsTransport(
5214 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
5215 }
5216 return false;
5217 }
5218
5219 rtp_data_channel_->SignalRtcpMuxFullyActive.connect(
5220 this, &PeerConnection::DestroyRtcpTransport_n);
5221 rtp_data_channel_->SignalDtlsSrtpSetupFailure.connect(
5222 this, &PeerConnection::OnDtlsSrtpSetupFailure);
5223 rtp_data_channel_->SignalSentPacket.connect(
5224 this, &PeerConnection::OnSentPacket_w);
5225 }
5226
Steve Anton75737c02017-11-06 10:37:17 -08005227 return true;
5228}
5229
5230Call::Stats PeerConnection::GetCallStats() {
5231 if (!worker_thread()->IsCurrent()) {
5232 return worker_thread()->Invoke<Call::Stats>(
5233 RTC_FROM_HERE, rtc::Bind(&PeerConnection::GetCallStats, this));
5234 }
5235 if (call_) {
5236 return call_->GetStats();
5237 } else {
5238 return Call::Stats();
5239 }
5240}
5241
5242std::unique_ptr<SessionStats> PeerConnection::GetSessionStats_n(
5243 const ChannelNamePairs& channel_name_pairs) {
5244 RTC_DCHECK(network_thread()->IsCurrent());
5245 std::unique_ptr<SessionStats> session_stats(new SessionStats());
5246 for (const auto channel_name_pair :
5247 {&channel_name_pairs.voice, &channel_name_pairs.video,
5248 &channel_name_pairs.data}) {
5249 if (*channel_name_pair) {
5250 cricket::TransportStats transport_stats;
5251 if (!transport_controller_->GetStats((*channel_name_pair)->transport_name,
5252 &transport_stats)) {
5253 return nullptr;
5254 }
Steve Anton75737c02017-11-06 10:37:17 -08005255 session_stats->transport_stats[(*channel_name_pair)->transport_name] =
5256 std::move(transport_stats);
5257 }
5258 }
5259 return session_stats;
5260}
5261
5262bool PeerConnection::CreateSctpTransport_n(const std::string& content_name,
5263 const std::string& transport_name) {
5264 RTC_DCHECK(network_thread()->IsCurrent());
5265 RTC_DCHECK(sctp_factory_);
5266 cricket::DtlsTransportInternal* tc =
5267 transport_controller_->CreateDtlsTransport_n(
5268 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5269 sctp_transport_ = sctp_factory_->CreateSctpTransport(tc);
5270 RTC_DCHECK(sctp_transport_);
5271 sctp_invoker_.reset(new rtc::AsyncInvoker());
5272 sctp_transport_->SignalReadyToSendData.connect(
5273 this, &PeerConnection::OnSctpTransportReadyToSendData_n);
5274 sctp_transport_->SignalDataReceived.connect(
5275 this, &PeerConnection::OnSctpTransportDataReceived_n);
5276 sctp_transport_->SignalStreamClosedRemotely.connect(
5277 this, &PeerConnection::OnSctpStreamClosedRemotely_n);
Oskar Sundbom9b28a032017-11-16 10:53:30 +01005278 sctp_transport_name_ = transport_name;
5279 sctp_content_name_ = content_name;
Steve Anton75737c02017-11-06 10:37:17 -08005280 return true;
5281}
5282
5283void PeerConnection::ChangeSctpTransport_n(const std::string& transport_name) {
5284 RTC_DCHECK(network_thread()->IsCurrent());
5285 RTC_DCHECK(sctp_transport_);
5286 RTC_DCHECK(sctp_transport_name_);
5287 std::string old_sctp_transport_name = *sctp_transport_name_;
Oskar Sundbom9b28a032017-11-16 10:53:30 +01005288 sctp_transport_name_ = transport_name;
Steve Anton75737c02017-11-06 10:37:17 -08005289 cricket::DtlsTransportInternal* tc =
5290 transport_controller_->CreateDtlsTransport_n(
5291 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5292 sctp_transport_->SetTransportChannel(tc);
5293 transport_controller_->DestroyDtlsTransport_n(
5294 old_sctp_transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5295}
5296
5297void PeerConnection::DestroySctpTransport_n() {
5298 RTC_DCHECK(network_thread()->IsCurrent());
5299 sctp_transport_.reset(nullptr);
Taylor Brandstetter389a97c2018-01-03 16:26:06 -08005300 transport_controller_->DestroyDtlsTransport_n(
5301 *sctp_transport_name_, cricket::ICE_CANDIDATE_COMPONENT_RTP);
Steve Anton75737c02017-11-06 10:37:17 -08005302 sctp_content_name_.reset();
5303 sctp_transport_name_.reset();
5304 sctp_invoker_.reset(nullptr);
5305 sctp_ready_to_send_data_ = false;
5306}
5307
5308void PeerConnection::OnSctpTransportReadyToSendData_n() {
5309 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5310 RTC_DCHECK(network_thread()->IsCurrent());
5311 // Note: Cannot use rtc::Bind here because it will grab a reference to
5312 // PeerConnection and potentially cause PeerConnection to live longer than
5313 // expected. It is safe not to grab a reference since the sctp_invoker_ will
5314 // be destroyed before PeerConnection is destroyed, and at that point all
5315 // pending tasks will be cleared.
5316 sctp_invoker_->AsyncInvoke<void>(RTC_FROM_HERE, signaling_thread(), [this] {
5317 OnSctpTransportReadyToSendData_s(true);
5318 });
5319}
5320
5321void PeerConnection::OnSctpTransportReadyToSendData_s(bool ready) {
5322 RTC_DCHECK(signaling_thread()->IsCurrent());
5323 sctp_ready_to_send_data_ = ready;
5324 SignalSctpReadyToSendData(ready);
5325}
5326
5327void PeerConnection::OnSctpTransportDataReceived_n(
5328 const cricket::ReceiveDataParams& params,
5329 const rtc::CopyOnWriteBuffer& payload) {
5330 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5331 RTC_DCHECK(network_thread()->IsCurrent());
5332 // Note: Cannot use rtc::Bind here because it will grab a reference to
5333 // PeerConnection and potentially cause PeerConnection to live longer than
5334 // expected. It is safe not to grab a reference since the sctp_invoker_ will
5335 // be destroyed before PeerConnection is destroyed, and at that point all
5336 // pending tasks will be cleared.
5337 sctp_invoker_->AsyncInvoke<void>(
5338 RTC_FROM_HERE, signaling_thread(), [this, params, payload] {
5339 OnSctpTransportDataReceived_s(params, payload);
5340 });
5341}
5342
5343void PeerConnection::OnSctpTransportDataReceived_s(
5344 const cricket::ReceiveDataParams& params,
5345 const rtc::CopyOnWriteBuffer& payload) {
5346 RTC_DCHECK(signaling_thread()->IsCurrent());
5347 if (params.type == cricket::DMT_CONTROL && IsOpenMessage(payload)) {
5348 // Received OPEN message; parse and signal that a new data channel should
5349 // be created.
5350 std::string label;
5351 InternalDataChannelInit config;
5352 config.id = params.ssrc;
5353 if (!ParseDataChannelOpenMessage(payload, &label, &config)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005354 RTC_LOG(LS_WARNING) << "Failed to parse the OPEN message for sid "
5355 << params.ssrc;
Steve Anton75737c02017-11-06 10:37:17 -08005356 return;
5357 }
5358 config.open_handshake_role = InternalDataChannelInit::kAcker;
5359 OnDataChannelOpenMessage(label, config);
5360 } else {
5361 // Otherwise just forward the signal.
5362 SignalSctpDataReceived(params, payload);
5363 }
5364}
5365
5366void PeerConnection::OnSctpStreamClosedRemotely_n(int sid) {
5367 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5368 RTC_DCHECK(network_thread()->IsCurrent());
5369 sctp_invoker_->AsyncInvoke<void>(
5370 RTC_FROM_HERE, signaling_thread(),
5371 rtc::Bind(&sigslot::signal1<int>::operator(),
5372 &SignalSctpStreamClosedRemotely, sid));
5373}
5374
5375// Returns false if bundle is enabled and rtcp_mux is disabled.
5376bool PeerConnection::ValidateBundleSettings(const SessionDescription* desc) {
5377 bool bundle_enabled = desc->HasGroup(cricket::GROUP_TYPE_BUNDLE);
5378 if (!bundle_enabled)
5379 return true;
5380
5381 const cricket::ContentGroup* bundle_group =
5382 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
5383 RTC_DCHECK(bundle_group != NULL);
5384
5385 const cricket::ContentInfos& contents = desc->contents();
5386 for (cricket::ContentInfos::const_iterator citer = contents.begin();
5387 citer != contents.end(); ++citer) {
5388 const cricket::ContentInfo* content = (&*citer);
5389 RTC_DCHECK(content != NULL);
5390 if (bundle_group->HasContentName(content->name) && !content->rejected &&
Steve Anton5adfafd2017-12-20 16:34:00 -08005391 content->type == MediaProtocolType::kRtp) {
Steve Anton75737c02017-11-06 10:37:17 -08005392 if (!HasRtcpMuxEnabled(content))
5393 return false;
5394 }
5395 }
5396 // RTCP-MUX is enabled in all the contents.
5397 return true;
5398}
5399
5400bool PeerConnection::HasRtcpMuxEnabled(const cricket::ContentInfo* content) {
Steve Antonb1c1de12017-12-21 15:14:30 -08005401 return content->media_description()->rtcp_mux();
Steve Anton75737c02017-11-06 10:37:17 -08005402}
5403
Steve Anton8a006912017-12-04 15:25:56 -08005404RTCError PeerConnection::ValidateSessionDescription(
Steve Anton75737c02017-11-06 10:37:17 -08005405 const SessionDescriptionInterface* sdesc,
Steve Anton8a006912017-12-04 15:25:56 -08005406 cricket::ContentSource source) {
Steve Antonf8470812017-12-04 10:46:21 -08005407 if (session_error() != SessionError::kNone) {
Steve Anton8a006912017-12-04 15:25:56 -08005408 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
Steve Anton75737c02017-11-06 10:37:17 -08005409 }
5410
5411 if (!sdesc || !sdesc->description()) {
Steve Anton8a006912017-12-04 15:25:56 -08005412 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidSdp);
Steve Anton75737c02017-11-06 10:37:17 -08005413 }
5414
Steve Anton3828c062017-12-06 10:34:51 -08005415 SdpType type = sdesc->GetType();
5416 if ((source == cricket::CS_LOCAL && !ExpectSetLocalDescription(type)) ||
5417 (source == cricket::CS_REMOTE && !ExpectSetRemoteDescription(type))) {
Steve Anton8a006912017-12-04 15:25:56 -08005418 LOG_AND_RETURN_ERROR(
5419 RTCErrorType::INVALID_PARAMETER,
5420 "Called in wrong state: " + GetSignalingStateString(signaling_state()));
Steve Anton75737c02017-11-06 10:37:17 -08005421 }
5422
5423 // Verify crypto settings.
5424 std::string crypto_error;
Steve Anton8a006912017-12-04 15:25:56 -08005425 if (webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED ||
5426 dtls_enabled_) {
Harald Alvestrand194939b2018-01-24 16:04:13 +01005427 RTCError crypto_error =
5428 VerifyCrypto(sdesc->description(), dtls_enabled_, uma_observer_);
Steve Anton8a006912017-12-04 15:25:56 -08005429 if (!crypto_error.ok()) {
5430 return crypto_error;
5431 }
Steve Anton75737c02017-11-06 10:37:17 -08005432 }
5433
5434 // Verify ice-ufrag and ice-pwd.
5435 if (!VerifyIceUfragPwdPresent(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08005436 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5437 kSdpWithoutIceUfragPwd);
Steve Anton75737c02017-11-06 10:37:17 -08005438 }
5439
5440 if (!ValidateBundleSettings(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08005441 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5442 kBundleWithoutRtcpMux);
Steve Anton75737c02017-11-06 10:37:17 -08005443 }
5444
5445 // TODO(skvlad): When the local rtcp-mux policy is Require, reject any
5446 // m-lines that do not rtcp-mux enabled.
5447
5448 // Verify m-lines in Answer when compared against Offer.
Steve Anton3828c062017-12-06 10:34:51 -08005449 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Anton75737c02017-11-06 10:37:17 -08005450 const cricket::SessionDescription* offer_desc =
5451 (source == cricket::CS_LOCAL) ? remote_description()->description()
5452 : local_description()->description();
5453 if (!MediaSectionsHaveSameCount(offer_desc, sdesc->description()) ||
5454 !MediaSectionsInSameOrder(offer_desc, sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08005455 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5456 kMlineMismatchInAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08005457 }
5458 } else {
5459 const cricket::SessionDescription* current_desc = nullptr;
5460 if (source == cricket::CS_LOCAL && local_description()) {
5461 current_desc = local_description()->description();
5462 } else if (source == cricket::CS_REMOTE && remote_description()) {
5463 current_desc = remote_description()->description();
5464 }
5465 // The re-offers should respect the order of m= sections in current
5466 // description. See RFC3264 Section 8 paragraph 4 for more details.
5467 if (current_desc &&
5468 !MediaSectionsInSameOrder(current_desc, sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08005469 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5470 kMlineMismatchInSubsequentOffer);
Steve Anton75737c02017-11-06 10:37:17 -08005471 }
5472 }
5473
Steve Anton8a006912017-12-04 15:25:56 -08005474 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08005475}
5476
Steve Anton3828c062017-12-06 10:34:51 -08005477bool PeerConnection::ExpectSetLocalDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08005478 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08005479 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08005480 return (state == PeerConnectionInterface::kStable) ||
5481 (state == PeerConnectionInterface::kHaveLocalOffer);
Steve Anton20393062017-12-04 16:24:52 -08005482 } else {
Steve Anton3828c062017-12-06 10:34:51 -08005483 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08005484 return (state == PeerConnectionInterface::kHaveRemoteOffer) ||
5485 (state == PeerConnectionInterface::kHaveLocalPrAnswer);
5486 }
5487}
5488
Steve Anton3828c062017-12-06 10:34:51 -08005489bool PeerConnection::ExpectSetRemoteDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08005490 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08005491 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08005492 return (state == PeerConnectionInterface::kStable) ||
5493 (state == PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton20393062017-12-04 16:24:52 -08005494 } else {
Steve Anton3828c062017-12-06 10:34:51 -08005495 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08005496 return (state == PeerConnectionInterface::kHaveLocalOffer) ||
5497 (state == PeerConnectionInterface::kHaveRemotePrAnswer);
5498 }
5499}
5500
Steve Antonf8470812017-12-04 10:46:21 -08005501const char* PeerConnection::SessionErrorToString(SessionError error) const {
5502 switch (error) {
5503 case SessionError::kNone:
5504 return "ERROR_NONE";
5505 case SessionError::kContent:
5506 return "ERROR_CONTENT";
5507 case SessionError::kTransport:
5508 return "ERROR_TRANSPORT";
5509 }
5510 RTC_NOTREACHED();
5511 return "";
5512}
5513
Steve Anton75737c02017-11-06 10:37:17 -08005514std::string PeerConnection::GetSessionErrorMsg() {
5515 std::ostringstream desc;
Steve Antonf8470812017-12-04 10:46:21 -08005516 desc << kSessionError << SessionErrorToString(session_error()) << ". ";
5517 desc << kSessionErrorDesc << session_error_desc() << ".";
Steve Anton75737c02017-11-06 10:37:17 -08005518 return desc.str();
5519}
5520
5521// We need to check the local/remote description for the Transport instead of
5522// the session, because a new Transport added during renegotiation may have
5523// them unset while the session has them set from the previous negotiation.
5524// Not doing so may trigger the auto generation of transport description and
5525// mess up DTLS identity information, ICE credential, etc.
5526bool PeerConnection::ReadyToUseRemoteCandidate(
5527 const IceCandidateInterface* candidate,
5528 const SessionDescriptionInterface* remote_desc,
5529 bool* valid) {
5530 *valid = true;
5531
5532 const SessionDescriptionInterface* current_remote_desc =
5533 remote_desc ? remote_desc : remote_description();
5534
5535 if (!current_remote_desc) {
5536 return false;
5537 }
5538
5539 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
5540 size_t remote_content_size =
5541 current_remote_desc->description()->contents().size();
5542 if (mediacontent_index >= remote_content_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005543 RTC_LOG(LS_ERROR)
5544 << "ReadyToUseRemoteCandidate: Invalid candidate media index "
5545 << mediacontent_index;
Steve Anton75737c02017-11-06 10:37:17 -08005546
5547 *valid = false;
5548 return false;
5549 }
5550
5551 cricket::ContentInfo content =
5552 current_remote_desc->description()->contents()[mediacontent_index];
5553
5554 const std::string transport_name = GetTransportName(content.name);
5555 if (transport_name.empty()) {
5556 return false;
5557 }
5558 return transport_controller_->ReadyForRemoteCandidates(transport_name);
5559}
5560
5561bool PeerConnection::SrtpRequired() const {
5562 return dtls_enabled_ ||
5563 webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED;
5564}
5565
5566void PeerConnection::OnTransportControllerGatheringState(
5567 cricket::IceGatheringState state) {
5568 RTC_DCHECK(signaling_thread()->IsCurrent());
5569 if (state == cricket::kIceGatheringGathering) {
5570 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringGathering);
5571 } else if (state == cricket::kIceGatheringComplete) {
5572 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringComplete);
5573 }
5574}
5575
5576void PeerConnection::ReportTransportStats() {
5577 // Use a set so we don't report the same stats twice if two channels share
5578 // a transport.
5579 std::set<std::string> transport_names;
5580 if (voice_channel()) {
5581 transport_names.insert(voice_channel()->transport_name());
5582 }
5583 if (video_channel()) {
5584 transport_names.insert(video_channel()->transport_name());
5585 }
5586 if (rtp_data_channel()) {
5587 transport_names.insert(rtp_data_channel()->transport_name());
5588 }
5589 if (sctp_transport_name_) {
5590 transport_names.insert(*sctp_transport_name_);
5591 }
5592 for (const auto& name : transport_names) {
5593 cricket::TransportStats stats;
5594 if (transport_controller_->GetStats(name, &stats)) {
5595 ReportBestConnectionState(stats);
5596 ReportNegotiatedCiphers(stats);
5597 }
5598 }
5599}
5600// Walk through the ConnectionInfos to gather best connection usage
5601// for IPv4 and IPv6.
5602void PeerConnection::ReportBestConnectionState(
5603 const cricket::TransportStats& stats) {
5604 RTC_DCHECK(metrics_observer());
5605 for (cricket::TransportChannelStatsList::const_iterator it =
5606 stats.channel_stats.begin();
5607 it != stats.channel_stats.end(); ++it) {
5608 for (cricket::ConnectionInfos::const_iterator it_info =
5609 it->connection_infos.begin();
5610 it_info != it->connection_infos.end(); ++it_info) {
5611 if (!it_info->best_connection) {
5612 continue;
5613 }
5614
5615 PeerConnectionEnumCounterType type = kPeerConnectionEnumCounterMax;
5616 const cricket::Candidate& local = it_info->local_candidate;
5617 const cricket::Candidate& remote = it_info->remote_candidate;
5618
5619 // Increment the counter for IceCandidatePairType.
5620 if (local.protocol() == cricket::TCP_PROTOCOL_NAME ||
5621 (local.type() == RELAY_PORT_TYPE &&
5622 local.relay_protocol() == cricket::TCP_PROTOCOL_NAME)) {
5623 type = kEnumCounterIceCandidatePairTypeTcp;
5624 } else if (local.protocol() == cricket::UDP_PROTOCOL_NAME) {
5625 type = kEnumCounterIceCandidatePairTypeUdp;
5626 } else {
5627 RTC_CHECK(0);
5628 }
5629 metrics_observer()->IncrementEnumCounter(
5630 type, GetIceCandidatePairCounter(local, remote),
5631 kIceCandidatePairMax);
5632
5633 // Increment the counter for IP type.
5634 if (local.address().family() == AF_INET) {
5635 metrics_observer()->IncrementEnumCounter(
5636 kEnumCounterAddressFamily, kBestConnections_IPv4,
5637 kPeerConnectionAddressFamilyCounter_Max);
5638
5639 } else if (local.address().family() == AF_INET6) {
5640 metrics_observer()->IncrementEnumCounter(
5641 kEnumCounterAddressFamily, kBestConnections_IPv6,
5642 kPeerConnectionAddressFamilyCounter_Max);
5643 } else {
5644 RTC_CHECK(0);
5645 }
5646
5647 return;
5648 }
5649 }
5650}
5651
5652void PeerConnection::ReportNegotiatedCiphers(
5653 const cricket::TransportStats& stats) {
5654 RTC_DCHECK(metrics_observer());
5655 if (!dtls_enabled_ || stats.channel_stats.empty()) {
5656 return;
5657 }
5658
5659 int srtp_crypto_suite = stats.channel_stats[0].srtp_crypto_suite;
5660 int ssl_cipher_suite = stats.channel_stats[0].ssl_cipher_suite;
5661 if (srtp_crypto_suite == rtc::SRTP_INVALID_CRYPTO_SUITE &&
5662 ssl_cipher_suite == rtc::TLS_NULL_WITH_NULL_NULL) {
5663 return;
5664 }
5665
5666 PeerConnectionEnumCounterType srtp_counter_type;
5667 PeerConnectionEnumCounterType ssl_counter_type;
5668 if (stats.transport_name == cricket::CN_AUDIO) {
5669 srtp_counter_type = kEnumCounterAudioSrtpCipher;
5670 ssl_counter_type = kEnumCounterAudioSslCipher;
5671 } else if (stats.transport_name == cricket::CN_VIDEO) {
5672 srtp_counter_type = kEnumCounterVideoSrtpCipher;
5673 ssl_counter_type = kEnumCounterVideoSslCipher;
5674 } else if (stats.transport_name == cricket::CN_DATA) {
5675 srtp_counter_type = kEnumCounterDataSrtpCipher;
5676 ssl_counter_type = kEnumCounterDataSslCipher;
5677 } else {
5678 RTC_NOTREACHED();
5679 return;
5680 }
5681
5682 if (srtp_crypto_suite != rtc::SRTP_INVALID_CRYPTO_SUITE) {
5683 metrics_observer()->IncrementSparseEnumCounter(srtp_counter_type,
5684 srtp_crypto_suite);
5685 }
5686 if (ssl_cipher_suite != rtc::TLS_NULL_WITH_NULL_NULL) {
5687 metrics_observer()->IncrementSparseEnumCounter(ssl_counter_type,
5688 ssl_cipher_suite);
5689 }
5690}
5691
5692void PeerConnection::OnSentPacket_w(const rtc::SentPacket& sent_packet) {
5693 RTC_DCHECK(worker_thread()->IsCurrent());
5694 RTC_DCHECK(call_);
5695 call_->OnSentPacket(sent_packet);
5696}
5697
5698const std::string PeerConnection::GetTransportName(
5699 const std::string& content_name) {
5700 cricket::BaseChannel* channel = GetChannel(content_name);
Steve Anton6fec8802017-12-04 10:37:29 -08005701 if (channel) {
5702 return channel->transport_name();
Steve Anton75737c02017-11-06 10:37:17 -08005703 }
Steve Anton6fec8802017-12-04 10:37:29 -08005704 if (sctp_transport_) {
5705 RTC_DCHECK(sctp_content_name_);
5706 RTC_DCHECK(sctp_transport_name_);
5707 if (content_name == *sctp_content_name_) {
5708 return *sctp_transport_name_;
5709 }
5710 }
5711 // Return an empty string if failed to retrieve the transport name.
5712 return "";
Steve Anton75737c02017-11-06 10:37:17 -08005713}
5714
5715void PeerConnection::DestroyRtcpTransport_n(const std::string& transport_name) {
5716 RTC_DCHECK(network_thread()->IsCurrent());
5717 transport_controller_->DestroyDtlsTransport_n(
5718 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
5719}
5720
Steve Anton6fec8802017-12-04 10:37:29 -08005721void PeerConnection::DestroyTransceiverChannel(
5722 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
5723 transceiver) {
5724 RTC_DCHECK(transceiver);
Steve Anton75737c02017-11-06 10:37:17 -08005725
Steve Anton6fec8802017-12-04 10:37:29 -08005726 cricket::BaseChannel* channel = transceiver->internal()->channel();
5727 if (channel) {
5728 transceiver->internal()->SetChannel(nullptr);
5729 DestroyBaseChannel(channel);
Steve Anton75737c02017-11-06 10:37:17 -08005730 }
5731}
5732
5733void PeerConnection::DestroyDataChannel() {
Steve Anton6fec8802017-12-04 10:37:29 -08005734 if (rtp_data_channel_) {
5735 OnDataChannelDestroyed();
5736 DestroyBaseChannel(rtp_data_channel_);
5737 rtp_data_channel_ = nullptr;
5738 }
5739
5740 // Note: Cannot use rtc::Bind to create a functor to invoke because it will
5741 // grab a reference to this PeerConnection. If this is called from the
5742 // PeerConnection destructor, the RefCountedObject vtable will have already
5743 // been destroyed (since it is a subclass of PeerConnection) and using
5744 // rtc::Bind will cause "Pure virtual function called" error to appear.
5745
5746 if (sctp_transport_) {
5747 OnDataChannelDestroyed();
5748 network_thread()->Invoke<void>(RTC_FROM_HERE,
5749 [this] { DestroySctpTransport_n(); });
5750 }
5751}
5752
5753void PeerConnection::DestroyBaseChannel(cricket::BaseChannel* channel) {
5754 RTC_DCHECK(channel);
5755 RTC_DCHECK(channel->rtp_dtls_transport());
5756
5757 // Need to cache these before destroying the base channel so that we do not
5758 // access uninitialized memory.
5759 const std::string transport_name =
5760 channel->rtp_dtls_transport()->transport_name();
5761 const bool need_to_delete_rtcp = (channel->rtcp_dtls_transport() != nullptr);
5762
5763 switch (channel->media_type()) {
5764 case cricket::MEDIA_TYPE_AUDIO:
5765 channel_manager()->DestroyVoiceChannel(
5766 static_cast<cricket::VoiceChannel*>(channel));
5767 break;
5768 case cricket::MEDIA_TYPE_VIDEO:
5769 channel_manager()->DestroyVideoChannel(
5770 static_cast<cricket::VideoChannel*>(channel));
5771 break;
5772 case cricket::MEDIA_TYPE_DATA:
5773 channel_manager()->DestroyRtpDataChannel(
5774 static_cast<cricket::RtpDataChannel*>(channel));
5775 break;
5776 default:
5777 RTC_NOTREACHED() << "Unknown media type: " << channel->media_type();
5778 break;
5779 }
5780
5781 // |channel| can no longer be used.
5782
Steve Anton75737c02017-11-06 10:37:17 -08005783 transport_controller_->DestroyDtlsTransport(
5784 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5785 if (need_to_delete_rtcp) {
5786 transport_controller_->DestroyDtlsTransport(
5787 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
5788 }
5789}
5790
Harald Alvestrand89061872018-01-02 14:08:34 +01005791void PeerConnection::ClearStatsCache() {
5792 if (stats_collector_) {
5793 stats_collector_->ClearCachedStatsReport();
5794 }
5795}
5796
henrike@webrtc.org28e20752013-07-10 00:45:36 +00005797} // namespace webrtc