blob: d6b441426e63e0a12492a0c6142a3919a69c3606 [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.
Steve Anton8a006912017-12-04 15:25:56 -0800367RTCError VerifyCrypto(const SessionDescription* desc, bool dtls_enabled) {
Steve Anton75737c02017-11-06 10:37:17 -0800368 const cricket::ContentGroup* bundle =
369 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton8a006912017-12-04 15:25:56 -0800370 for (const cricket::ContentInfo& content_info : desc->contents()) {
371 if (content_info.rejected) {
Steve Anton75737c02017-11-06 10:37:17 -0800372 continue;
373 }
Steve Anton8a006912017-12-04 15:25:56 -0800374 const std::string& mid = content_info.name;
375 if (bundle && bundle->HasContentName(mid) &&
376 mid != *(bundle->FirstContentName())) {
Steve Anton75737c02017-11-06 10:37:17 -0800377 // This isn't the first media section in the BUNDLE group, so it's not
378 // required to have crypto attributes, since only the crypto attributes
379 // from the first section actually get used.
380 continue;
381 }
382
383 // If the content isn't rejected or bundled into another m= section, crypto
384 // must be present.
Steve Antonb1c1de12017-12-21 15:14:30 -0800385 const MediaContentDescription* media = content_info.media_description();
Steve Anton8a006912017-12-04 15:25:56 -0800386 const TransportInfo* tinfo = desc->GetTransportInfoByName(mid);
Steve Anton75737c02017-11-06 10:37:17 -0800387 if (!media || !tinfo) {
388 // Something is not right.
Steve Anton8a006912017-12-04 15:25:56 -0800389 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidSdp);
Steve Anton75737c02017-11-06 10:37:17 -0800390 }
391 if (dtls_enabled) {
392 if (!tinfo->description.identity_fingerprint) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100393 RTC_LOG(LS_WARNING)
394 << "Session description must have DTLS fingerprint if "
395 "DTLS enabled.";
Steve Anton8a006912017-12-04 15:25:56 -0800396 return RTCError(RTCErrorType::INVALID_PARAMETER,
397 kSdpWithoutDtlsFingerprint);
Steve Anton75737c02017-11-06 10:37:17 -0800398 }
399 } else {
400 if (media->cryptos().empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100401 RTC_LOG(LS_WARNING)
Steve Anton75737c02017-11-06 10:37:17 -0800402 << "Session description must have SDES when DTLS disabled.";
Steve Anton8a006912017-12-04 15:25:56 -0800403 return RTCError(RTCErrorType::INVALID_PARAMETER, kSdpWithoutSdesCrypto);
Steve Anton75737c02017-11-06 10:37:17 -0800404 }
405 }
406 }
Steve Anton8a006912017-12-04 15:25:56 -0800407 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -0800408}
409
410// Checks that each non-rejected content has ice-ufrag and ice-pwd set, unless
411// it's in a BUNDLE group, in which case only the BUNDLE-tag section (first
412// media section/description in the BUNDLE group) needs a ufrag and pwd.
413bool VerifyIceUfragPwdPresent(const SessionDescription* desc) {
414 const cricket::ContentGroup* bundle =
415 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton8a006912017-12-04 15:25:56 -0800416 for (const cricket::ContentInfo& content_info : desc->contents()) {
417 if (content_info.rejected) {
Steve Anton75737c02017-11-06 10:37:17 -0800418 continue;
419 }
Steve Anton8a006912017-12-04 15:25:56 -0800420 const std::string& mid = content_info.name;
421 if (bundle && bundle->HasContentName(mid) &&
422 mid != *(bundle->FirstContentName())) {
Steve Anton75737c02017-11-06 10:37:17 -0800423 // This isn't the first media section in the BUNDLE group, so it's not
424 // required to have ufrag/password, since only the ufrag/password from
425 // the first section actually get used.
426 continue;
427 }
428
429 // If the content isn't rejected or bundled into another m= section,
430 // ice-ufrag and ice-pwd must be present.
Steve Anton8a006912017-12-04 15:25:56 -0800431 const TransportInfo* tinfo = desc->GetTransportInfoByName(mid);
Steve Anton75737c02017-11-06 10:37:17 -0800432 if (!tinfo) {
433 // Something is not right.
Mirko Bonadei675513b2017-11-09 11:09:25 +0100434 RTC_LOG(LS_ERROR) << kInvalidSdp;
Steve Anton75737c02017-11-06 10:37:17 -0800435 return false;
436 }
437 if (tinfo->description.ice_ufrag.empty() ||
438 tinfo->description.ice_pwd.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100439 RTC_LOG(LS_ERROR) << "Session description must have ice ufrag and pwd.";
Steve Anton75737c02017-11-06 10:37:17 -0800440 return false;
441 }
442 }
443 return true;
444}
445
446bool GetTrackIdBySsrc(const SessionDescription* session_description,
447 uint32_t ssrc,
448 std::string* track_id) {
449 RTC_DCHECK(track_id != NULL);
450
Steve Antonb1c1de12017-12-21 15:14:30 -0800451 const cricket::AudioContentDescription* audio_desc =
452 cricket::GetFirstAudioContentDescription(session_description);
453 if (audio_desc) {
454 const auto* found = cricket::GetStreamBySsrc(audio_desc->streams(), ssrc);
Steve Anton75737c02017-11-06 10:37:17 -0800455 if (found) {
456 *track_id = found->id;
457 return true;
458 }
459 }
460
Steve Antonb1c1de12017-12-21 15:14:30 -0800461 const cricket::VideoContentDescription* video_desc =
462 cricket::GetFirstVideoContentDescription(session_description);
463 if (video_desc) {
464 const auto* found = cricket::GetStreamBySsrc(video_desc->streams(), ssrc);
Steve Anton75737c02017-11-06 10:37:17 -0800465 if (found) {
466 *track_id = found->id;
467 return true;
468 }
469 }
470 return false;
471}
472
473// Get the SCTP port out of a SessionDescription.
474// Return -1 if not found.
475int GetSctpPort(const SessionDescription* session_description) {
Steve Antonb1c1de12017-12-21 15:14:30 -0800476 const cricket::DataContentDescription* data_desc =
477 GetFirstDataContentDescription(session_description);
478 RTC_DCHECK(data_desc);
479 if (!data_desc) {
Steve Anton75737c02017-11-06 10:37:17 -0800480 return -1;
481 }
Steve Anton75737c02017-11-06 10:37:17 -0800482 std::string value;
483 cricket::DataCodec match_pattern(cricket::kGoogleSctpDataCodecPlType,
484 cricket::kGoogleSctpDataCodecName);
Steve Antonb1c1de12017-12-21 15:14:30 -0800485 for (const cricket::DataCodec& codec : data_desc->codecs()) {
Steve Anton75737c02017-11-06 10:37:17 -0800486 if (!codec.Matches(match_pattern)) {
487 continue;
488 }
489 if (codec.GetParam(cricket::kCodecParamPort, &value)) {
490 return rtc::FromString<int>(value);
491 }
492 }
493 return -1;
494}
495
Steve Anton75737c02017-11-06 10:37:17 -0800496// Returns true if |new_desc| requests an ICE restart (i.e., new ufrag/pwd).
497bool CheckForRemoteIceRestart(const SessionDescriptionInterface* old_desc,
498 const SessionDescriptionInterface* new_desc,
499 const std::string& content_name) {
500 if (!old_desc) {
501 return false;
502 }
503 const SessionDescription* new_sd = new_desc->description();
504 const SessionDescription* old_sd = old_desc->description();
505 const ContentInfo* cinfo = new_sd->GetContentByName(content_name);
506 if (!cinfo || cinfo->rejected) {
507 return false;
508 }
509 // If the content isn't rejected, check if ufrag and password has changed.
510 const cricket::TransportDescription* new_transport_desc =
511 new_sd->GetTransportDescriptionByName(content_name);
512 const cricket::TransportDescription* old_transport_desc =
513 old_sd->GetTransportDescriptionByName(content_name);
514 if (!new_transport_desc || !old_transport_desc) {
515 // No transport description exists. This is not an ICE restart.
516 return false;
517 }
518 if (cricket::IceCredentialsChanged(
519 old_transport_desc->ice_ufrag, old_transport_desc->ice_pwd,
520 new_transport_desc->ice_ufrag, new_transport_desc->ice_pwd)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100521 RTC_LOG(LS_INFO) << "Remote peer requests ICE restart for " << content_name
522 << ".";
Steve Anton75737c02017-11-06 10:37:17 -0800523 return true;
524 }
525 return false;
526}
527
528} // namespace
529
Henrik Boström31638672017-11-23 17:48:32 +0100530// Upon completion, posts a task to execute the callback of the
531// SetSessionDescriptionObserver asynchronously on the same thread. At this
532// point, the state of the peer connection might no longer reflect the effects
533// of the SetRemoteDescription operation, as the peer connection could have been
534// modified during the post.
535// TODO(hbos): Remove this class once we remove the version of
536// PeerConnectionInterface::SetRemoteDescription() that takes a
537// SetSessionDescriptionObserver as an argument.
538class PeerConnection::SetRemoteDescriptionObserverAdapter
539 : public rtc::RefCountedObject<SetRemoteDescriptionObserverInterface> {
540 public:
541 SetRemoteDescriptionObserverAdapter(
542 rtc::scoped_refptr<PeerConnection> pc,
543 rtc::scoped_refptr<SetSessionDescriptionObserver> wrapper)
544 : pc_(std::move(pc)), wrapper_(std::move(wrapper)) {}
545
546 // SetRemoteDescriptionObserverInterface implementation.
547 void OnSetRemoteDescriptionComplete(RTCError error) override {
548 if (error.ok())
549 pc_->PostSetSessionDescriptionSuccess(wrapper_);
550 else
551 pc_->PostSetSessionDescriptionFailure(wrapper_, error.message());
552 }
553
554 private:
555 rtc::scoped_refptr<PeerConnection> pc_;
556 rtc::scoped_refptr<SetSessionDescriptionObserver> wrapper_;
557};
558
deadbeef293e9262017-01-11 12:28:30 -0800559bool PeerConnectionInterface::RTCConfiguration::operator==(
560 const PeerConnectionInterface::RTCConfiguration& o) const {
561 // This static_assert prevents us from accidentally breaking operator==.
Steve Anton300bf8e2017-07-14 10:13:10 -0700562 // Note: Order matters! Fields must be ordered the same as RTCConfiguration.
deadbeef293e9262017-01-11 12:28:30 -0800563 struct stuff_being_tested_for_equality {
Magnus Jedvert3beb2072017-07-14 14:23:56 +0000564 IceServers servers;
Steve Anton300bf8e2017-07-14 10:13:10 -0700565 IceTransportsType type;
deadbeef293e9262017-01-11 12:28:30 -0800566 BundlePolicy bundle_policy;
567 RtcpMuxPolicy rtcp_mux_policy;
Steve Anton300bf8e2017-07-14 10:13:10 -0700568 std::vector<rtc::scoped_refptr<rtc::RTCCertificate>> certificates;
569 int ice_candidate_pool_size;
570 bool disable_ipv6;
571 bool disable_ipv6_on_wifi;
deadbeefd21eab32017-07-26 16:50:11 -0700572 int max_ipv6_networks;
Steve Anton300bf8e2017-07-14 10:13:10 -0700573 bool enable_rtp_data_channel;
574 rtc::Optional<int> screencast_min_bitrate;
575 rtc::Optional<bool> combined_audio_video_bwe;
576 rtc::Optional<bool> enable_dtls_srtp;
deadbeef293e9262017-01-11 12:28:30 -0800577 TcpCandidatePolicy tcp_candidate_policy;
578 CandidateNetworkPolicy candidate_network_policy;
579 int audio_jitter_buffer_max_packets;
580 bool audio_jitter_buffer_fast_accelerate;
581 int ice_connection_receiving_timeout;
582 int ice_backup_candidate_pair_ping_interval;
583 ContinualGatheringPolicy continual_gathering_policy;
deadbeef293e9262017-01-11 12:28:30 -0800584 bool prioritize_most_likely_ice_candidate_pairs;
585 struct cricket::MediaConfig media_config;
deadbeef293e9262017-01-11 12:28:30 -0800586 bool prune_turn_ports;
587 bool presume_writable_when_fully_relayed;
588 bool enable_ice_renomination;
589 bool redetermine_role_on_ice_restart;
skvlad51072462017-02-02 11:50:14 -0800590 rtc::Optional<int> ice_check_min_interval;
Steve Anton300bf8e2017-07-14 10:13:10 -0700591 rtc::Optional<rtc::IntervalRange> ice_regather_interval_range;
Jonas Orelandbdcee282017-10-10 14:01:40 +0200592 webrtc::TurnCustomizer* turn_customizer;
Steve Anton79e79602017-11-20 10:25:56 -0800593 SdpSemantics sdp_semantics;
deadbeef293e9262017-01-11 12:28:30 -0800594 };
595 static_assert(sizeof(stuff_being_tested_for_equality) == sizeof(*this),
596 "Did you add something to RTCConfiguration and forget to "
597 "update operator==?");
598 return type == o.type && servers == o.servers &&
599 bundle_policy == o.bundle_policy &&
600 rtcp_mux_policy == o.rtcp_mux_policy &&
601 tcp_candidate_policy == o.tcp_candidate_policy &&
602 candidate_network_policy == o.candidate_network_policy &&
603 audio_jitter_buffer_max_packets == o.audio_jitter_buffer_max_packets &&
604 audio_jitter_buffer_fast_accelerate ==
605 o.audio_jitter_buffer_fast_accelerate &&
606 ice_connection_receiving_timeout ==
607 o.ice_connection_receiving_timeout &&
608 ice_backup_candidate_pair_ping_interval ==
609 o.ice_backup_candidate_pair_ping_interval &&
610 continual_gathering_policy == o.continual_gathering_policy &&
611 certificates == o.certificates &&
612 prioritize_most_likely_ice_candidate_pairs ==
613 o.prioritize_most_likely_ice_candidate_pairs &&
614 media_config == o.media_config && disable_ipv6 == o.disable_ipv6 &&
zhihuangb09b3f92017-03-07 14:40:51 -0800615 disable_ipv6_on_wifi == o.disable_ipv6_on_wifi &&
deadbeefd21eab32017-07-26 16:50:11 -0700616 max_ipv6_networks == o.max_ipv6_networks &&
deadbeef293e9262017-01-11 12:28:30 -0800617 enable_rtp_data_channel == o.enable_rtp_data_channel &&
deadbeef293e9262017-01-11 12:28:30 -0800618 screencast_min_bitrate == o.screencast_min_bitrate &&
619 combined_audio_video_bwe == o.combined_audio_video_bwe &&
620 enable_dtls_srtp == o.enable_dtls_srtp &&
621 ice_candidate_pool_size == o.ice_candidate_pool_size &&
622 prune_turn_ports == o.prune_turn_ports &&
623 presume_writable_when_fully_relayed ==
624 o.presume_writable_when_fully_relayed &&
625 enable_ice_renomination == o.enable_ice_renomination &&
skvlad51072462017-02-02 11:50:14 -0800626 redetermine_role_on_ice_restart == o.redetermine_role_on_ice_restart &&
Steve Anton300bf8e2017-07-14 10:13:10 -0700627 ice_check_min_interval == o.ice_check_min_interval &&
Jonas Orelandbdcee282017-10-10 14:01:40 +0200628 ice_regather_interval_range == o.ice_regather_interval_range &&
Steve Anton79e79602017-11-20 10:25:56 -0800629 turn_customizer == o.turn_customizer &&
630 sdp_semantics == o.sdp_semantics;
deadbeef293e9262017-01-11 12:28:30 -0800631}
632
633bool PeerConnectionInterface::RTCConfiguration::operator!=(
634 const PeerConnectionInterface::RTCConfiguration& o) const {
635 return !(*this == o);
deadbeef3edec7c2016-12-10 11:44:26 -0800636}
637
zhihuang8f65cdf2016-05-06 18:40:30 -0700638// Generate a RTCP CNAME when a PeerConnection is created.
639std::string GenerateRtcpCname() {
640 std::string cname;
641 if (!rtc::CreateRandomString(kRtcpCnameLength, &cname)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100642 RTC_LOG(LS_ERROR) << "Failed to generate CNAME.";
nisseeb4ca4e2017-01-12 02:24:27 -0800643 RTC_NOTREACHED();
zhihuang8f65cdf2016-05-06 18:40:30 -0700644 }
645 return cname;
646}
647
zhihuang1c378ed2017-08-17 14:10:50 -0700648bool ValidateOfferAnswerOptions(
649 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options) {
650 return IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_audio) &&
651 IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_video);
olka3c747662017-08-17 06:50:32 -0700652}
653
zhihuang1c378ed2017-08-17 14:10:50 -0700654// From |rtc_options|, fill parts of |session_options| shared by all generated
655// m= sections (in other words, nothing that involves a map/array).
656void ExtractSharedMediaSessionOptions(
657 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options,
658 cricket::MediaSessionOptions* session_options) {
659 session_options->vad_enabled = rtc_options.voice_activity_detection;
660 session_options->bundle_enabled = rtc_options.use_rtp_mux;
661}
zhihuanga77e6bb2017-08-14 18:17:48 -0700662
zhihuang1c378ed2017-08-17 14:10:50 -0700663bool ConvertConstraintsToOfferAnswerOptions(
664 const MediaConstraintsInterface* constraints,
665 PeerConnectionInterface::RTCOfferAnswerOptions* offer_answer_options) {
olka3c747662017-08-17 06:50:32 -0700666 if (!constraints) {
667 return true;
668 }
zhihuang1c378ed2017-08-17 14:10:50 -0700669
670 bool value = false;
671 size_t mandatory_constraints_satisfied = 0;
672
673 if (FindConstraint(constraints,
674 MediaConstraintsInterface::kOfferToReceiveAudio, &value,
675 &mandatory_constraints_satisfied)) {
676 offer_answer_options->offer_to_receive_audio =
677 value ? PeerConnectionInterface::RTCOfferAnswerOptions::
678 kOfferToReceiveMediaTrue
679 : 0;
680 }
681
682 if (FindConstraint(constraints,
683 MediaConstraintsInterface::kOfferToReceiveVideo, &value,
684 &mandatory_constraints_satisfied)) {
685 offer_answer_options->offer_to_receive_video =
686 value ? PeerConnectionInterface::RTCOfferAnswerOptions::
687 kOfferToReceiveMediaTrue
688 : 0;
689 }
690 if (FindConstraint(constraints,
691 MediaConstraintsInterface::kVoiceActivityDetection, &value,
692 &mandatory_constraints_satisfied)) {
693 offer_answer_options->voice_activity_detection = value;
694 }
695 if (FindConstraint(constraints, MediaConstraintsInterface::kUseRtpMux, &value,
696 &mandatory_constraints_satisfied)) {
697 offer_answer_options->use_rtp_mux = value;
698 }
699 if (FindConstraint(constraints, MediaConstraintsInterface::kIceRestart,
700 &value, &mandatory_constraints_satisfied)) {
701 offer_answer_options->ice_restart = value;
702 }
703
deadbeefab9b2d12015-10-14 11:33:11 -0700704 return mandatory_constraints_satisfied == constraints->GetMandatory().size();
705}
706
zhihuang38ede132017-06-15 12:52:32 -0700707PeerConnection::PeerConnection(PeerConnectionFactory* factory,
708 std::unique_ptr<RtcEventLog> event_log,
709 std::unique_ptr<Call> call)
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000710 : factory_(factory),
zhihuang38ede132017-06-15 12:52:32 -0700711 event_log_(std::move(event_log)),
zhihuang8f65cdf2016-05-06 18:40:30 -0700712 rtcp_cname_(GenerateRtcpCname()),
deadbeefab9b2d12015-10-14 11:33:11 -0700713 local_streams_(StreamCollection::Create()),
zhihuang38ede132017-06-15 12:52:32 -0700714 remote_streams_(StreamCollection::Create()),
715 call_(std::move(call)) {}
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000716
717PeerConnection::~PeerConnection() {
Peter Boström1a9d6152015-12-08 22:15:17 +0100718 TRACE_EVENT0("webrtc", "PeerConnection::~PeerConnection");
Steve Anton4171afb2017-11-20 10:20:22 -0800719 RTC_DCHECK_RUN_ON(signaling_thread());
720
Steve Anton8af21862017-12-15 11:20:13 -0800721 // Need to stop transceivers before destroying the stats collector because
722 // AudioRtpSender has a reference to the StatsCollector it will update when
723 // stopping.
724 for (auto transceiver : transceivers_) {
725 transceiver->Stop();
726 }
Steve Anton4171afb2017-11-20 10:20:22 -0800727
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700728 stats_.reset(nullptr);
hbosb78306a2016-12-19 05:06:57 -0800729 if (stats_collector_) {
730 stats_collector_->WaitForPendingRequest();
731 stats_collector_ = nullptr;
732 }
Steve Anton75737c02017-11-06 10:37:17 -0800733
Steve Anton8af21862017-12-15 11:20:13 -0800734 // Don't destroy BaseChannels until after stats has been cleaned up so that
735 // the last stats request can still read from the channels.
736 DestroyAllChannels();
737
Mirko Bonadei675513b2017-11-09 11:09:25 +0100738 RTC_LOG(LS_INFO) << "Session: " << session_id() << " is destroyed.";
Steve Anton75737c02017-11-06 10:37:17 -0800739
740 webrtc_session_desc_factory_.reset();
741 sctp_invoker_.reset();
742 sctp_factory_.reset();
743 transport_controller_.reset();
744
deadbeef91dd5672016-05-18 16:55:30 -0700745 // port_allocator_ lives on the network thread and should be destroyed there.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700746 network_thread()->Invoke<void>(RTC_FROM_HERE,
nisseeaabdf62017-05-05 02:23:02 -0700747 [this] { port_allocator_.reset(); });
eladalon248fd4f2017-09-06 05:18:15 -0700748 // call_ and event_log_ must be destroyed on the worker thread.
Steve Anton978b8762017-09-29 12:15:02 -0700749 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
eladalon248fd4f2017-09-06 05:18:15 -0700750 call_.reset();
751 event_log_.reset();
752 });
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000753}
754
Steve Anton8af21862017-12-15 11:20:13 -0800755void PeerConnection::DestroyAllChannels() {
Steve Anton3fe1b152017-12-12 10:20:08 -0800756 // Destroy video channels first since they may have a pointer to a voice
757 // channel.
758 for (auto transceiver : transceivers_) {
759 if (transceiver->internal()->media_type() == cricket::MEDIA_TYPE_VIDEO) {
760 DestroyTransceiverChannel(transceiver);
761 }
762 }
763 for (auto transceiver : transceivers_) {
764 if (transceiver->internal()->media_type() == cricket::MEDIA_TYPE_AUDIO) {
765 DestroyTransceiverChannel(transceiver);
766 }
767 }
768 DestroyDataChannel();
769}
770
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000771bool PeerConnection::Initialize(
buildbot@webrtc.org41451d42014-05-03 05:39:45 +0000772 const PeerConnectionInterface::RTCConfiguration& configuration,
kwibergd1fe2812016-04-27 06:47:29 -0700773 std::unique_ptr<cricket::PortAllocator> allocator,
Henrik Boströmd03c23b2016-06-01 11:44:18 +0200774 std::unique_ptr<rtc::RTCCertificateGeneratorInterface> cert_generator,
deadbeef653b8e02015-11-11 12:55:10 -0800775 PeerConnectionObserver* observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100776 TRACE_EVENT0("webrtc", "PeerConnection::Initialize");
Steve Anton038834f2017-07-14 15:59:59 -0700777
778 RTCError config_error = ValidateConfiguration(configuration);
779 if (!config_error.ok()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100780 RTC_LOG(LS_ERROR) << "Invalid configuration: " << config_error.message();
Steve Anton038834f2017-07-14 15:59:59 -0700781 return false;
782 }
783
deadbeef293e9262017-01-11 12:28:30 -0800784 if (!allocator) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100785 RTC_LOG(LS_ERROR)
786 << "PeerConnection initialized without a PortAllocator? "
787 << "This shouldn't happen if using PeerConnectionFactory.";
deadbeef293e9262017-01-11 12:28:30 -0800788 return false;
789 }
Jonas Orelandbdcee282017-10-10 14:01:40 +0200790
deadbeef653b8e02015-11-11 12:55:10 -0800791 if (!observer) {
deadbeef293e9262017-01-11 12:28:30 -0800792 // TODO(deadbeef): Why do we do this?
Mirko Bonadei675513b2017-11-09 11:09:25 +0100793 RTC_LOG(LS_ERROR) << "PeerConnection initialized without a "
794 << "PeerConnectionObserver";
deadbeef653b8e02015-11-11 12:55:10 -0800795 return false;
796 }
pthatcher@webrtc.org877ac762015-02-04 22:03:09 +0000797 observer_ = observer;
kwiberg0eb15ed2015-12-17 03:04:15 -0800798 port_allocator_ = std::move(allocator);
deadbeef653b8e02015-11-11 12:55:10 -0800799
deadbeef91dd5672016-05-18 16:55:30 -0700800 // The port allocator lives on the network thread and should be initialized
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700801 // there.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700802 if (!network_thread()->Invoke<bool>(
803 RTC_FROM_HERE, rtc::Bind(&PeerConnection::InitializePortAllocator_n,
804 this, configuration))) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000805 return false;
806 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000807
Steve Anton75737c02017-11-06 10:37:17 -0800808 // RFC 3264: The numeric value of the session id and version in the
809 // o line MUST be representable with a "64 bit signed integer".
810 // Due to this constraint session id |session_id_| is max limited to
811 // LLONG_MAX.
812 session_id_ = rtc::ToString(rtc::CreateRandomId64() & LLONG_MAX);
813 transport_controller_.reset(factory_->CreateTransportController(
814 port_allocator_.get(), configuration.redetermine_role_on_ice_restart));
815 transport_controller_->SetIceRole(cricket::ICEROLE_CONTROLLED);
816 transport_controller_->SignalConnectionState.connect(
817 this, &PeerConnection::OnTransportControllerConnectionState);
818 transport_controller_->SignalGatheringState.connect(
819 this, &PeerConnection::OnTransportControllerGatheringState);
820 transport_controller_->SignalCandidatesGathered.connect(
821 this, &PeerConnection::OnTransportControllerCandidatesGathered);
822 transport_controller_->SignalCandidatesRemoved.connect(
823 this, &PeerConnection::OnTransportControllerCandidatesRemoved);
824 transport_controller_->SignalDtlsHandshakeError.connect(
825 this, &PeerConnection::OnTransportControllerDtlsHandshakeError);
826
827 sctp_factory_ = factory_->CreateSctpTransportInternalFactory();
zhihuang29ff8442016-07-27 11:07:25 -0700828
deadbeefab9b2d12015-10-14 11:33:11 -0700829 stats_.reset(new StatsCollector(this));
hbos74e1a4f2016-09-15 23:33:01 -0700830 stats_collector_ = RTCStatsCollector::Create(this);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000831
Steve Antonba818672017-11-06 10:21:57 -0800832 configuration_ = configuration;
833
Steve Anton75737c02017-11-06 10:37:17 -0800834 const PeerConnectionFactoryInterface::Options& options = factory_->options();
835
836 transport_controller_->SetSslMaxProtocolVersion(options.ssl_max_version);
837
838 // Obtain a certificate from RTCConfiguration if any were provided (optional).
839 rtc::scoped_refptr<rtc::RTCCertificate> certificate;
840 if (!configuration.certificates.empty()) {
841 // TODO(hbos,torbjorng): Decide on certificate-selection strategy instead of
842 // just picking the first one. The decision should be made based on the DTLS
843 // handshake. The DTLS negotiations need to know about all certificates.
844 certificate = configuration.certificates[0];
845 }
846
Steve Antond25da372017-11-06 14:50:29 -0800847 transport_controller_->SetIceConfig(ParseIceConfig(configuration));
Steve Anton75737c02017-11-06 10:37:17 -0800848
849 if (options.disable_encryption) {
850 dtls_enabled_ = false;
851 } else {
852 // Enable DTLS by default if we have an identity store or a certificate.
853 dtls_enabled_ = (cert_generator || certificate);
854 // |configuration| can override the default |dtls_enabled_| value.
855 if (configuration.enable_dtls_srtp) {
856 dtls_enabled_ = *(configuration.enable_dtls_srtp);
857 }
858 }
859
860 // Enable creation of RTP data channels if the kEnableRtpDataChannels is set.
861 // It takes precendence over the disable_sctp_data_channels
862 // PeerConnectionFactoryInterface::Options.
863 if (configuration.enable_rtp_data_channel) {
864 data_channel_type_ = cricket::DCT_RTP;
865 } else {
866 // DTLS has to be enabled to use SCTP.
867 if (!options.disable_sctp_data_channels && dtls_enabled_) {
868 data_channel_type_ = cricket::DCT_SCTP;
869 }
870 }
871
872 video_options_.screencast_min_bitrate_kbps =
873 configuration.screencast_min_bitrate;
874 audio_options_.combined_audio_video_bwe =
875 configuration.combined_audio_video_bwe;
876
877 audio_options_.audio_jitter_buffer_max_packets =
Oskar Sundbom9b28a032017-11-16 10:53:30 +0100878 configuration.audio_jitter_buffer_max_packets;
Steve Anton75737c02017-11-06 10:37:17 -0800879
880 audio_options_.audio_jitter_buffer_fast_accelerate =
Oskar Sundbom9b28a032017-11-16 10:53:30 +0100881 configuration.audio_jitter_buffer_fast_accelerate;
Steve Anton75737c02017-11-06 10:37:17 -0800882
883 // Whether the certificate generator/certificate is null or not determines
884 // what PeerConnectionDescriptionFactory will do, so make sure that we give it
885 // the right instructions by clearing the variables if needed.
886 if (!dtls_enabled_) {
887 cert_generator.reset();
888 certificate = nullptr;
889 } else if (certificate) {
890 // Favor generated certificate over the certificate generator.
891 cert_generator.reset();
892 }
893
894 webrtc_session_desc_factory_.reset(new WebRtcSessionDescriptionFactory(
895 signaling_thread(), channel_manager(), this, session_id(),
896 std::move(cert_generator), certificate));
897 webrtc_session_desc_factory_->SignalCertificateReady.connect(
898 this, &PeerConnection::OnCertificateReady);
899
900 if (options.disable_encryption) {
901 webrtc_session_desc_factory_->SetSdesPolicy(cricket::SEC_DISABLED);
902 }
903
904 webrtc_session_desc_factory_->set_enable_encrypted_rtp_header_extensions(
905 options.crypto_options.enable_encrypted_rtp_header_extensions);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000906
Steve Anton4171afb2017-11-20 10:20:22 -0800907 // Add default audio/video transceivers for Plan B SDP.
908 if (!IsUnifiedPlan()) {
909 transceivers_.push_back(
910 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
911 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_AUDIO)));
912 transceivers_.push_back(
913 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
914 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_VIDEO)));
915 }
916
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000917 return true;
918}
919
Steve Anton038834f2017-07-14 15:59:59 -0700920RTCError PeerConnection::ValidateConfiguration(
921 const RTCConfiguration& config) const {
922 if (config.ice_regather_interval_range &&
923 config.continual_gathering_policy == GATHER_ONCE) {
924 return RTCError(RTCErrorType::INVALID_PARAMETER,
925 "ice_regather_interval_range specified but continual "
926 "gathering policy is GATHER_ONCE");
927 }
928 return RTCError::OK();
929}
930
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000931rtc::scoped_refptr<StreamCollectionInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000932PeerConnection::local_streams() {
deadbeefab9b2d12015-10-14 11:33:11 -0700933 return local_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000934}
935
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000936rtc::scoped_refptr<StreamCollectionInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000937PeerConnection::remote_streams() {
deadbeefab9b2d12015-10-14 11:33:11 -0700938 return remote_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000939}
940
perkj@webrtc.orgc2dd5ee2014-11-04 11:31:29 +0000941bool PeerConnection::AddStream(MediaStreamInterface* local_stream) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100942 TRACE_EVENT0("webrtc", "PeerConnection::AddStream");
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000943 if (IsClosed()) {
944 return false;
945 }
deadbeefab9b2d12015-10-14 11:33:11 -0700946 if (!CanAddLocalMediaStream(local_streams_, local_stream)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000947 return false;
948 }
deadbeefab9b2d12015-10-14 11:33:11 -0700949
950 local_streams_->AddStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -0800951 MediaStreamObserver* observer = new MediaStreamObserver(local_stream);
952 observer->SignalAudioTrackAdded.connect(this,
953 &PeerConnection::OnAudioTrackAdded);
954 observer->SignalAudioTrackRemoved.connect(
955 this, &PeerConnection::OnAudioTrackRemoved);
956 observer->SignalVideoTrackAdded.connect(this,
957 &PeerConnection::OnVideoTrackAdded);
958 observer->SignalVideoTrackRemoved.connect(
959 this, &PeerConnection::OnVideoTrackRemoved);
kwibergd1fe2812016-04-27 06:47:29 -0700960 stream_observers_.push_back(std::unique_ptr<MediaStreamObserver>(observer));
deadbeefab9b2d12015-10-14 11:33:11 -0700961
deadbeefab9b2d12015-10-14 11:33:11 -0700962 for (const auto& track : local_stream->GetAudioTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -0700963 AddAudioTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -0700964 }
965 for (const auto& track : local_stream->GetVideoTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -0700966 AddVideoTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -0700967 }
968
tommi@webrtc.org03505bc2014-07-14 20:15:26 +0000969 stats_->AddStream(local_stream);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000970 observer_->OnRenegotiationNeeded();
971 return true;
972}
973
974void PeerConnection::RemoveStream(MediaStreamInterface* local_stream) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100975 TRACE_EVENT0("webrtc", "PeerConnection::RemoveStream");
korniltsev.anatolyec390b52017-07-24 17:00:25 -0700976 if (!IsClosed()) {
977 for (const auto& track : local_stream->GetAudioTracks()) {
978 RemoveAudioTrack(track.get(), local_stream);
979 }
980 for (const auto& track : local_stream->GetVideoTracks()) {
981 RemoveVideoTrack(track.get(), local_stream);
982 }
deadbeefab9b2d12015-10-14 11:33:11 -0700983 }
deadbeefab9b2d12015-10-14 11:33:11 -0700984 local_streams_->RemoveStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -0800985 stream_observers_.erase(
986 std::remove_if(
987 stream_observers_.begin(), stream_observers_.end(),
kwibergd1fe2812016-04-27 06:47:29 -0700988 [local_stream](const std::unique_ptr<MediaStreamObserver>& observer) {
deadbeefeb459812015-12-15 19:24:43 -0800989 return observer->stream()->label().compare(local_stream->label()) ==
990 0;
991 }),
992 stream_observers_.end());
deadbeefab9b2d12015-10-14 11:33:11 -0700993
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000994 if (IsClosed()) {
995 return;
996 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000997 observer_->OnRenegotiationNeeded();
998}
999
deadbeefe1f9d832016-01-14 15:35:42 -08001000rtc::scoped_refptr<RtpSenderInterface> PeerConnection::AddTrack(
1001 MediaStreamTrackInterface* track,
1002 std::vector<MediaStreamInterface*> streams) {
1003 TRACE_EVENT0("webrtc", "PeerConnection::AddTrack");
Steve Antonf9381f02017-12-14 10:23:57 -08001004 std::vector<std::string> stream_labels;
1005 for (auto* stream : streams) {
1006 if (!stream) {
1007 RTC_LOG(LS_ERROR) << "Stream list has null element.";
1008 return nullptr;
1009 }
1010 stream_labels.push_back(stream->label());
1011 }
Steve Anton2d6c76a2018-01-05 17:10:52 -08001012 auto sender_or_error = AddTrack(track, stream_labels);
Steve Antonf9381f02017-12-14 10:23:57 -08001013 if (!sender_or_error.ok()) {
deadbeefe1f9d832016-01-14 15:35:42 -08001014 return nullptr;
1015 }
Steve Antonf9381f02017-12-14 10:23:57 -08001016 return sender_or_error.MoveValue();
1017}
1018
Steve Anton2d6c76a2018-01-05 17:10:52 -08001019RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::AddTrack(
Steve Antonf9381f02017-12-14 10:23:57 -08001020 rtc::scoped_refptr<MediaStreamTrackInterface> track,
1021 const std::vector<std::string>& stream_labels) {
Steve Anton2d6c76a2018-01-05 17:10:52 -08001022 TRACE_EVENT0("webrtc", "PeerConnection::AddTrack");
Steve Antonf9381f02017-12-14 10:23:57 -08001023 if (!track) {
1024 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "Track is null.");
1025 }
1026 if (!(track->kind() == MediaStreamTrackInterface::kAudioKind ||
1027 track->kind() == MediaStreamTrackInterface::kVideoKind)) {
1028 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1029 "Track has invalid kind: " + track->kind());
1030 }
1031 // TODO(bugs.webrtc.org/7932): Support adding a track to multiple streams.
1032 if (stream_labels.size() > 1u) {
1033 LOG_AND_RETURN_ERROR(
1034 RTCErrorType::UNSUPPORTED_OPERATION,
1035 "AddTrack with more than one stream is not currently supported.");
1036 }
1037 if (IsClosed()) {
1038 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
1039 "PeerConnection is closed.");
deadbeefe1f9d832016-01-14 15:35:42 -08001040 }
Steve Anton4171afb2017-11-20 10:20:22 -08001041 if (FindSenderForTrack(track)) {
Steve Antonf9381f02017-12-14 10:23:57 -08001042 LOG_AND_RETURN_ERROR(
1043 RTCErrorType::INVALID_PARAMETER,
1044 "Sender already exists for track " + track->id() + ".");
deadbeefe1f9d832016-01-14 15:35:42 -08001045 }
Steve Antonf9381f02017-12-14 10:23:57 -08001046 // TODO(bugs.webrtc.org/7933): MediaSession expects the sender to have exactly
1047 // one stream. AddTrackInternal will return an error if there is more than one
1048 // stream, but if the caller specifies none then we need to generate a random
1049 // stream label.
1050 std::vector<std::string> adjusted_stream_labels = stream_labels;
1051 if (stream_labels.empty()) {
1052 adjusted_stream_labels.push_back(rtc::CreateRandomUuid());
1053 }
1054 RTC_DCHECK_EQ(1, adjusted_stream_labels.size());
1055 auto sender_or_error =
1056 (IsUnifiedPlan() ? AddTrackUnifiedPlan(track, adjusted_stream_labels)
1057 : AddTrackPlanB(track, adjusted_stream_labels));
1058 if (sender_or_error.ok()) {
1059 observer_->OnRenegotiationNeeded();
Steve Anton43a723a2018-01-04 15:48:17 -08001060 stats_->AddTrack(track);
Steve Antonf9381f02017-12-14 10:23:57 -08001061 }
1062 return sender_or_error;
1063}
deadbeefe1f9d832016-01-14 15:35:42 -08001064
Steve Antonf9381f02017-12-14 10:23:57 -08001065RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>>
1066PeerConnection::AddTrackPlanB(
1067 rtc::scoped_refptr<MediaStreamTrackInterface> track,
1068 const std::vector<std::string>& stream_labels) {
Steve Anton02ee47c2018-01-10 16:26:06 -08001069 cricket::MediaType media_type =
1070 (track->kind() == MediaStreamTrackInterface::kAudioKind
1071 ? cricket::MEDIA_TYPE_AUDIO
1072 : cricket::MEDIA_TYPE_VIDEO);
1073 auto new_sender = CreateSender(media_type, track, stream_labels);
deadbeefe1f9d832016-01-14 15:35:42 -08001074 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
Steve Anton02ee47c2018-01-10 16:26:06 -08001075 static_cast<AudioRtpSender*>(new_sender->internal())
1076 ->SetChannel(voice_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08001077 GetAudioTransceiver()->internal()->AddSender(new_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001078 const RtpSenderInfo* sender_info =
1079 FindSenderInfo(local_audio_sender_infos_,
1080 new_sender->internal()->stream_id(), track->id());
1081 if (sender_info) {
1082 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -08001083 }
Steve Antonf9381f02017-12-14 10:23:57 -08001084 } else {
1085 RTC_DCHECK_EQ(MediaStreamTrackInterface::kVideoKind, track->kind());
Steve Anton02ee47c2018-01-10 16:26:06 -08001086 static_cast<VideoRtpSender*>(new_sender->internal())
1087 ->SetChannel(video_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08001088 GetVideoTransceiver()->internal()->AddSender(new_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001089 const RtpSenderInfo* sender_info =
1090 FindSenderInfo(local_video_sender_infos_,
1091 new_sender->internal()->stream_id(), track->id());
1092 if (sender_info) {
1093 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -08001094 }
deadbeefe1f9d832016-01-14 15:35:42 -08001095 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001096 return rtc::scoped_refptr<RtpSenderInterface>(new_sender);
Steve Antonf9381f02017-12-14 10:23:57 -08001097}
deadbeefe1f9d832016-01-14 15:35:42 -08001098
Steve Antonf9381f02017-12-14 10:23:57 -08001099RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>>
1100PeerConnection::AddTrackUnifiedPlan(
1101 rtc::scoped_refptr<MediaStreamTrackInterface> track,
1102 const std::vector<std::string>& stream_labels) {
1103 auto transceiver = FindFirstTransceiverForAddedTrack(track);
1104 if (transceiver) {
1105 if (transceiver->direction() == RtpTransceiverDirection::kRecvOnly) {
1106 transceiver->SetDirection(RtpTransceiverDirection::kSendRecv);
1107 } else if (transceiver->direction() == RtpTransceiverDirection::kInactive) {
1108 transceiver->SetDirection(RtpTransceiverDirection::kSendOnly);
1109 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001110 transceiver->sender()->SetTrack(track);
1111 transceiver->internal()->sender_internal()->set_stream_ids(stream_labels);
Steve Antonf9381f02017-12-14 10:23:57 -08001112 } else {
1113 cricket::MediaType media_type =
1114 (track->kind() == MediaStreamTrackInterface::kAudioKind
1115 ? cricket::MEDIA_TYPE_AUDIO
1116 : cricket::MEDIA_TYPE_VIDEO);
Steve Anton02ee47c2018-01-10 16:26:06 -08001117 auto sender = CreateSender(media_type, track, stream_labels);
1118 auto receiver = CreateReceiver(media_type, rtc::CreateRandomUuid());
1119 transceiver = CreateAndAddTransceiver(sender, receiver);
Steve Antonf9381f02017-12-14 10:23:57 -08001120 transceiver->internal()->set_created_by_addtrack(true);
1121 transceiver->SetDirection(RtpTransceiverDirection::kSendRecv);
1122 }
Steve Antonf9381f02017-12-14 10:23:57 -08001123 return transceiver->sender();
1124}
1125
1126rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1127PeerConnection::FindFirstTransceiverForAddedTrack(
1128 rtc::scoped_refptr<MediaStreamTrackInterface> track) {
1129 RTC_DCHECK(track);
1130 for (auto transceiver : transceivers_) {
1131 if (!transceiver->sender()->track() &&
1132 cricket::MediaTypeToString(transceiver->internal()->media_type()) ==
1133 track->kind() &&
1134 !transceiver->internal()->has_ever_been_used_to_send()) {
1135 return transceiver;
1136 }
1137 }
1138 return nullptr;
deadbeefe1f9d832016-01-14 15:35:42 -08001139}
1140
1141bool PeerConnection::RemoveTrack(RtpSenderInterface* sender) {
1142 TRACE_EVENT0("webrtc", "PeerConnection::RemoveTrack");
Steve Antonf9381f02017-12-14 10:23:57 -08001143 return RemoveTrackInternal(sender).ok();
1144}
1145
1146RTCError PeerConnection::RemoveTrackInternal(
1147 rtc::scoped_refptr<RtpSenderInterface> sender) {
1148 if (!sender) {
1149 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "Sender is null.");
1150 }
deadbeefe1f9d832016-01-14 15:35:42 -08001151 if (IsClosed()) {
Steve Antonf9381f02017-12-14 10:23:57 -08001152 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
1153 "PeerConnection is closed.");
deadbeefe1f9d832016-01-14 15:35:42 -08001154 }
Steve Antonf9381f02017-12-14 10:23:57 -08001155 if (IsUnifiedPlan()) {
1156 auto transceiver = FindTransceiverBySender(sender);
1157 if (!transceiver || !sender->track()) {
1158 return RTCError::OK();
1159 }
1160 sender->SetTrack(nullptr);
1161 if (transceiver->direction() == RtpTransceiverDirection::kSendRecv) {
1162 transceiver->internal()->SetDirection(RtpTransceiverDirection::kRecvOnly);
1163 } else if (transceiver->direction() == RtpTransceiverDirection::kSendOnly) {
1164 transceiver->internal()->SetDirection(RtpTransceiverDirection::kInactive);
1165 }
Steve Anton4171afb2017-11-20 10:20:22 -08001166 } else {
Steve Antonf9381f02017-12-14 10:23:57 -08001167 bool removed;
1168 if (sender->media_type() == cricket::MEDIA_TYPE_AUDIO) {
1169 removed = GetAudioTransceiver()->internal()->RemoveSender(sender);
1170 } else {
1171 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, sender->media_type());
1172 removed = GetVideoTransceiver()->internal()->RemoveSender(sender);
1173 }
1174 if (!removed) {
1175 LOG_AND_RETURN_ERROR(
1176 RTCErrorType::INVALID_PARAMETER,
1177 "Couldn't find sender " + sender->id() + " to remove.");
1178 }
Steve Anton4171afb2017-11-20 10:20:22 -08001179 }
deadbeefe1f9d832016-01-14 15:35:42 -08001180 observer_->OnRenegotiationNeeded();
Steve Antonf9381f02017-12-14 10:23:57 -08001181 return RTCError::OK();
1182}
1183
1184rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1185PeerConnection::FindTransceiverBySender(
1186 rtc::scoped_refptr<RtpSenderInterface> sender) {
1187 for (auto transceiver : transceivers_) {
1188 if (transceiver->sender() == sender) {
1189 return transceiver;
1190 }
1191 }
1192 return nullptr;
deadbeefe1f9d832016-01-14 15:35:42 -08001193}
1194
Steve Anton9158ef62017-11-27 13:01:52 -08001195RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1196PeerConnection::AddTransceiver(
1197 rtc::scoped_refptr<MediaStreamTrackInterface> track) {
1198 return AddTransceiver(track, RtpTransceiverInit());
1199}
1200
1201RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1202PeerConnection::AddTransceiver(
1203 rtc::scoped_refptr<MediaStreamTrackInterface> track,
1204 const RtpTransceiverInit& init) {
1205 if (!IsUnifiedPlan()) {
1206 LOG_AND_RETURN_ERROR(
1207 RTCErrorType::INTERNAL_ERROR,
1208 "AddTransceiver only supported when Unified Plan is enabled.");
1209 }
1210 if (!track) {
1211 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "track is null");
1212 }
1213 cricket::MediaType media_type;
1214 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
1215 media_type = cricket::MEDIA_TYPE_AUDIO;
1216 } else if (track->kind() == MediaStreamTrackInterface::kVideoKind) {
1217 media_type = cricket::MEDIA_TYPE_VIDEO;
1218 } else {
1219 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1220 "Track kind is not audio or video");
1221 }
1222 return AddTransceiver(media_type, track, init);
1223}
1224
1225RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1226PeerConnection::AddTransceiver(cricket::MediaType media_type) {
1227 return AddTransceiver(media_type, RtpTransceiverInit());
1228}
1229
1230RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1231PeerConnection::AddTransceiver(cricket::MediaType media_type,
1232 const RtpTransceiverInit& init) {
1233 if (!IsUnifiedPlan()) {
1234 LOG_AND_RETURN_ERROR(
1235 RTCErrorType::INTERNAL_ERROR,
1236 "AddTransceiver only supported when Unified Plan is enabled.");
1237 }
1238 if (!(media_type == cricket::MEDIA_TYPE_AUDIO ||
1239 media_type == cricket::MEDIA_TYPE_VIDEO)) {
1240 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1241 "media type is not audio or video");
1242 }
1243 return AddTransceiver(media_type, nullptr, init);
1244}
1245
1246RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1247PeerConnection::AddTransceiver(
1248 cricket::MediaType media_type,
1249 rtc::scoped_refptr<MediaStreamTrackInterface> track,
1250 const RtpTransceiverInit& init) {
1251 RTC_DCHECK((media_type == cricket::MEDIA_TYPE_AUDIO ||
1252 media_type == cricket::MEDIA_TYPE_VIDEO));
1253 if (track) {
1254 RTC_DCHECK_EQ(media_type,
1255 (track->kind() == MediaStreamTrackInterface::kAudioKind
1256 ? cricket::MEDIA_TYPE_AUDIO
1257 : cricket::MEDIA_TYPE_VIDEO));
1258 }
1259
1260 // TODO(bugs.webrtc.org/7600): Verify init.
1261
Steve Anton02ee47c2018-01-10 16:26:06 -08001262 if (init.stream_labels.size() > 1u) {
1263 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
1264 "More than one stream is not yet supported.");
Steve Antonf9381f02017-12-14 10:23:57 -08001265 }
1266
Steve Anton02ee47c2018-01-10 16:26:06 -08001267 std::vector<std::string> stream_labels = {!init.stream_labels.empty()
1268 ? init.stream_labels[0]
1269 : rtc::CreateRandomUuid()};
1270
1271 auto sender = CreateSender(media_type, track, stream_labels);
1272 auto receiver = CreateReceiver(media_type, rtc::CreateRandomUuid());
1273 auto transceiver = CreateAndAddTransceiver(sender, receiver);
1274 transceiver->internal()->set_direction(init.direction);
1275
Steve Antonf9381f02017-12-14 10:23:57 -08001276 observer_->OnRenegotiationNeeded();
1277
1278 return rtc::scoped_refptr<RtpTransceiverInterface>(transceiver);
1279}
1280
Steve Anton02ee47c2018-01-10 16:26:06 -08001281rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
1282PeerConnection::CreateSender(
1283 cricket::MediaType media_type,
1284 rtc::scoped_refptr<MediaStreamTrackInterface> track,
1285 const std::vector<std::string>& stream_labels) {
Steve Anton9158ef62017-11-27 13:01:52 -08001286 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> sender;
Steve Anton02ee47c2018-01-10 16:26:06 -08001287 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
1288 RTC_DCHECK(!track ||
1289 (track->kind() == MediaStreamTrackInterface::kAudioKind));
1290 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
1291 signaling_thread(),
1292 new AudioRtpSender(static_cast<AudioTrackInterface*>(track.get()),
1293 stream_labels, stats_.get()));
1294 } else {
1295 RTC_DCHECK_EQ(media_type, cricket::MEDIA_TYPE_VIDEO);
1296 RTC_DCHECK(!track ||
1297 (track->kind() == MediaStreamTrackInterface::kVideoKind));
1298 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
1299 signaling_thread(),
1300 new VideoRtpSender(static_cast<VideoTrackInterface*>(track.get()),
1301 stream_labels));
1302 }
1303 sender->internal()->set_stream_ids(stream_labels);
1304 return sender;
1305}
1306
1307rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1308PeerConnection::CreateReceiver(cricket::MediaType media_type,
1309 const std::string& receiver_id) {
Steve Anton9158ef62017-11-27 13:01:52 -08001310 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1311 receiver;
Steve Anton9158ef62017-11-27 13:01:52 -08001312 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton9158ef62017-11-27 13:01:52 -08001313 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
Steve Anton60776752018-01-10 11:51:34 -08001314 signaling_thread(),
1315 new AudioRtpReceiver(worker_thread(), receiver_id, {}, 0, nullptr));
Steve Anton9158ef62017-11-27 13:01:52 -08001316 } else {
Steve Anton02ee47c2018-01-10 16:26:06 -08001317 RTC_DCHECK_EQ(media_type, cricket::MEDIA_TYPE_VIDEO);
Steve Anton9158ef62017-11-27 13:01:52 -08001318 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
1319 signaling_thread(),
Steve Anton60776752018-01-10 11:51:34 -08001320 new VideoRtpReceiver(worker_thread(), receiver_id, {}, 0, nullptr));
Steve Anton9158ef62017-11-27 13:01:52 -08001321 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001322 return receiver;
1323}
1324
1325rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1326PeerConnection::CreateAndAddTransceiver(
1327 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> sender,
1328 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1329 receiver) {
1330 auto transceiver = RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1331 signaling_thread(), new RtpTransceiver(sender, receiver));
Steve Anton9158ef62017-11-27 13:01:52 -08001332 transceivers_.push_back(transceiver);
Steve Antonf9381f02017-12-14 10:23:57 -08001333 return transceiver;
Steve Anton9158ef62017-11-27 13:01:52 -08001334}
1335
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001336rtc::scoped_refptr<DtmfSenderInterface> PeerConnection::CreateDtmfSender(
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001337 AudioTrackInterface* track) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001338 TRACE_EVENT0("webrtc", "PeerConnection::CreateDtmfSender");
zhihuang29ff8442016-07-27 11:07:25 -07001339 if (IsClosed()) {
1340 return nullptr;
1341 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001342 if (!track) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001343 RTC_LOG(LS_ERROR) << "CreateDtmfSender - track is NULL.";
deadbeef20cb0c12017-02-01 20:27:00 -08001344 return nullptr;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001345 }
Steve Anton4171afb2017-11-20 10:20:22 -08001346 auto track_sender = FindSenderForTrack(track);
1347 if (!track_sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001348 RTC_LOG(LS_ERROR) << "CreateDtmfSender called with a non-added track.";
deadbeef20cb0c12017-02-01 20:27:00 -08001349 return nullptr;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001350 }
1351
Steve Anton4171afb2017-11-20 10:20:22 -08001352 return track_sender->GetDtmfSender();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001353}
1354
deadbeeffac06552015-11-25 11:26:01 -08001355rtc::scoped_refptr<RtpSenderInterface> PeerConnection::CreateSender(
deadbeefbd7d8f72015-12-18 16:58:44 -08001356 const std::string& kind,
1357 const std::string& stream_id) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001358 TRACE_EVENT0("webrtc", "PeerConnection::CreateSender");
zhihuang29ff8442016-07-27 11:07:25 -07001359 if (IsClosed()) {
1360 return nullptr;
1361 }
Steve Anton4171afb2017-11-20 10:20:22 -08001362
Steve Anton02ee47c2018-01-10 16:26:06 -08001363 std::vector<std::string> stream_labels;
1364 if (!stream_id.empty()) {
1365 stream_labels.push_back(stream_id);
1366 }
1367
Steve Anton4171afb2017-11-20 10:20:22 -08001368 // TODO(steveanton): Move construction of the RtpSenders to RtpTransceiver.
deadbeefa601f5c2016-06-06 14:27:39 -07001369 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender;
deadbeeffac06552015-11-25 11:26:01 -08001370 if (kind == MediaStreamTrackInterface::kAudioKind) {
Steve Anton02ee47c2018-01-10 16:26:06 -08001371 auto* audio_sender =
1372 new AudioRtpSender(nullptr, stream_labels, stats_.get());
1373 audio_sender->SetChannel(voice_channel());
deadbeefa601f5c2016-06-06 14:27:39 -07001374 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton02ee47c2018-01-10 16:26:06 -08001375 signaling_thread(), audio_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001376 GetAudioTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 11:26:01 -08001377 } else if (kind == MediaStreamTrackInterface::kVideoKind) {
Steve Anton02ee47c2018-01-10 16:26:06 -08001378 auto* video_sender = new VideoRtpSender(nullptr, stream_labels);
1379 video_sender->SetChannel(video_channel());
deadbeefa601f5c2016-06-06 14:27:39 -07001380 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton02ee47c2018-01-10 16:26:06 -08001381 signaling_thread(), video_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001382 GetVideoTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 11:26:01 -08001383 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001384 RTC_LOG(LS_ERROR) << "CreateSender called with invalid kind: " << kind;
Steve Anton4171afb2017-11-20 10:20:22 -08001385 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08001386 }
Steve Anton4171afb2017-11-20 10:20:22 -08001387
deadbeefe1f9d832016-01-14 15:35:42 -08001388 return new_sender;
deadbeeffac06552015-11-25 11:26:01 -08001389}
1390
deadbeef70ab1a12015-09-28 16:53:55 -07001391std::vector<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::GetSenders()
1392 const {
deadbeefa601f5c2016-06-06 14:27:39 -07001393 std::vector<rtc::scoped_refptr<RtpSenderInterface>> ret;
Steve Anton4171afb2017-11-20 10:20:22 -08001394 for (auto sender : GetSendersInternal()) {
1395 ret.push_back(sender);
deadbeefa601f5c2016-06-06 14:27:39 -07001396 }
1397 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -07001398}
1399
Steve Anton4171afb2017-11-20 10:20:22 -08001400std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1401PeerConnection::GetSendersInternal() const {
1402 std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1403 all_senders;
1404 for (auto transceiver : transceivers_) {
1405 auto senders = transceiver->internal()->senders();
1406 all_senders.insert(all_senders.end(), senders.begin(), senders.end());
1407 }
1408 return all_senders;
1409}
1410
deadbeef70ab1a12015-09-28 16:53:55 -07001411std::vector<rtc::scoped_refptr<RtpReceiverInterface>>
1412PeerConnection::GetReceivers() const {
deadbeefa601f5c2016-06-06 14:27:39 -07001413 std::vector<rtc::scoped_refptr<RtpReceiverInterface>> ret;
Steve Anton4171afb2017-11-20 10:20:22 -08001414 for (const auto& receiver : GetReceiversInternal()) {
1415 ret.push_back(receiver);
deadbeefa601f5c2016-06-06 14:27:39 -07001416 }
1417 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -07001418}
1419
Steve Anton4171afb2017-11-20 10:20:22 -08001420std::vector<
1421 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1422PeerConnection::GetReceiversInternal() const {
1423 std::vector<
1424 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1425 all_receivers;
1426 for (auto transceiver : transceivers_) {
1427 auto receivers = transceiver->internal()->receivers();
1428 all_receivers.insert(all_receivers.end(), receivers.begin(),
1429 receivers.end());
1430 }
1431 return all_receivers;
1432}
1433
Steve Anton9158ef62017-11-27 13:01:52 -08001434std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
1435PeerConnection::GetTransceivers() const {
1436 RTC_DCHECK(IsUnifiedPlan());
1437 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> all_transceivers;
1438 for (auto transceiver : transceivers_) {
1439 all_transceivers.push_back(transceiver);
1440 }
1441 return all_transceivers;
1442}
1443
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001444bool PeerConnection::GetStats(StatsObserver* observer,
wu@webrtc.orgb9a088b2014-02-13 23:18:49 +00001445 MediaStreamTrackInterface* track,
1446 StatsOutputLevel level) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001447 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
deadbeef0a6c4ca2015-10-06 11:38:28 -07001448 RTC_DCHECK(signaling_thread()->IsCurrent());
nisse7ce109a2017-01-31 00:57:56 -08001449 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001450 RTC_LOG(LS_ERROR) << "GetStats - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001451 return false;
1452 }
1453
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001454 stats_->UpdateStats(level);
zhihuange9e94c32016-11-04 11:38:15 -07001455 // The StatsCollector is used to tell if a track is valid because it may
1456 // remember tracks that the PeerConnection previously removed.
1457 if (track && !stats_->IsValidTrack(track->id())) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001458 RTC_LOG(LS_WARNING) << "GetStats is called with an invalid track: "
1459 << track->id();
zhihuange9e94c32016-11-04 11:38:15 -07001460 return false;
1461 }
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001462 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_GETSTATS,
tommi@webrtc.org5b06b062014-08-15 08:38:30 +00001463 new GetStatsMsg(observer, track));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001464 return true;
1465}
1466
hbos74e1a4f2016-09-15 23:33:01 -07001467void PeerConnection::GetStats(RTCStatsCollectorCallback* callback) {
1468 RTC_DCHECK(stats_collector_);
1469 stats_collector_->GetStatsReport(callback);
1470}
1471
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001472PeerConnectionInterface::SignalingState PeerConnection::signaling_state() {
1473 return signaling_state_;
1474}
1475
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001476PeerConnectionInterface::IceConnectionState
1477PeerConnection::ice_connection_state() {
1478 return ice_connection_state_;
1479}
1480
1481PeerConnectionInterface::IceGatheringState
1482PeerConnection::ice_gathering_state() {
1483 return ice_gathering_state_;
1484}
1485
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001486rtc::scoped_refptr<DataChannelInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001487PeerConnection::CreateDataChannel(
1488 const std::string& label,
1489 const DataChannelInit* config) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001490 TRACE_EVENT0("webrtc", "PeerConnection::CreateDataChannel");
zhihuang9763d562016-08-05 11:14:50 -07001491
deadbeefab9b2d12015-10-14 11:33:11 -07001492 bool first_datachannel = !HasDataChannels();
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001493
kwibergd1fe2812016-04-27 06:47:29 -07001494 std::unique_ptr<InternalDataChannelInit> internal_config;
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00001495 if (config) {
1496 internal_config.reset(new InternalDataChannelInit(*config));
1497 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001498 rtc::scoped_refptr<DataChannelInterface> channel(
deadbeefab9b2d12015-10-14 11:33:11 -07001499 InternalCreateDataChannel(label, internal_config.get()));
1500 if (!channel.get()) {
1501 return nullptr;
1502 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001503
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001504 // Trigger the onRenegotiationNeeded event for every new RTP DataChannel, or
1505 // the first SCTP DataChannel.
Steve Anton75737c02017-11-06 10:37:17 -08001506 if (data_channel_type() == cricket::DCT_RTP || first_datachannel) {
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001507 observer_->OnRenegotiationNeeded();
1508 }
wu@webrtc.org91053e72013-08-10 07:18:04 +00001509
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001510 return DataChannelProxy::Create(signaling_thread(), channel.get());
1511}
1512
1513void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
1514 const MediaConstraintsInterface* constraints) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001515 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
Steve Anton8d3444d2017-10-20 15:30:51 -07001516
zhihuang1c378ed2017-08-17 14:10:50 -07001517 PeerConnectionInterface::RTCOfferAnswerOptions offer_answer_options;
1518 // Always create an offer even if |ConvertConstraintsToOfferAnswerOptions|
1519 // returns false for now. Because |ConvertConstraintsToOfferAnswerOptions|
1520 // compares the mandatory fields parsed with the mandatory fields added in the
1521 // |constraints| and some downstream applications might create offers with
1522 // mandatory fields which would not be parsed in the helper method. For
1523 // example, in Chromium/remoting, |kEnableDtlsSrtp| is added to the
1524 // |constraints| as a mandatory field but it is not parsed.
1525 ConvertConstraintsToOfferAnswerOptions(constraints, &offer_answer_options);
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001526
zhihuang1c378ed2017-08-17 14:10:50 -07001527 CreateOffer(observer, offer_answer_options);
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001528}
1529
1530void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
1531 const RTCOfferAnswerOptions& options) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001532 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
Steve Anton8d3444d2017-10-20 15:30:51 -07001533
nisse7ce109a2017-01-31 00:57:56 -08001534 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001535 RTC_LOG(LS_ERROR) << "CreateOffer - observer is NULL.";
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001536 return;
1537 }
deadbeefab9b2d12015-10-14 11:33:11 -07001538
Steve Anton8d3444d2017-10-20 15:30:51 -07001539 if (IsClosed()) {
1540 std::string error = "CreateOffer called when PeerConnection is closed.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001541 RTC_LOG(LS_ERROR) << error;
Steve Anton8d3444d2017-10-20 15:30:51 -07001542 PostCreateSessionDescriptionFailure(observer, error);
1543 return;
1544 }
1545
zhihuang1c378ed2017-08-17 14:10:50 -07001546 if (!ValidateOfferAnswerOptions(options)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001547 std::string error = "CreateOffer called with invalid options.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001548 RTC_LOG(LS_ERROR) << error;
deadbeefab9b2d12015-10-14 11:33:11 -07001549 PostCreateSessionDescriptionFailure(observer, error);
1550 return;
1551 }
1552
zhihuang1c378ed2017-08-17 14:10:50 -07001553 cricket::MediaSessionOptions session_options;
1554 GetOptionsForOffer(options, &session_options);
Steve Antond25da372017-11-06 14:50:29 -08001555 webrtc_session_desc_factory_->CreateOffer(observer, options, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001556}
1557
1558void PeerConnection::CreateAnswer(
1559 CreateSessionDescriptionObserver* observer,
1560 const MediaConstraintsInterface* constraints) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001561 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
Steve Anton8d3444d2017-10-20 15:30:51 -07001562
nisse7ce109a2017-01-31 00:57:56 -08001563 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001564 RTC_LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001565 return;
1566 }
deadbeefab9b2d12015-10-14 11:33:11 -07001567
zhihuang1c378ed2017-08-17 14:10:50 -07001568 PeerConnectionInterface::RTCOfferAnswerOptions offer_answer_options;
1569 if (!ConvertConstraintsToOfferAnswerOptions(constraints,
1570 &offer_answer_options)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001571 std::string error = "CreateAnswer called with invalid constraints.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001572 RTC_LOG(LS_ERROR) << error;
deadbeefab9b2d12015-10-14 11:33:11 -07001573 PostCreateSessionDescriptionFailure(observer, error);
1574 return;
1575 }
1576
Steve Anton8d3444d2017-10-20 15:30:51 -07001577 CreateAnswer(observer, offer_answer_options);
htaa2a49d92016-03-04 02:51:39 -08001578}
1579
1580void PeerConnection::CreateAnswer(CreateSessionDescriptionObserver* observer,
1581 const RTCOfferAnswerOptions& options) {
1582 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
nisse7ce109a2017-01-31 00:57:56 -08001583 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001584 RTC_LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
htaa2a49d92016-03-04 02:51:39 -08001585 return;
1586 }
1587
Steve Anton8d3444d2017-10-20 15:30:51 -07001588 if (IsClosed()) {
1589 std::string error = "CreateAnswer called when PeerConnection is closed.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001590 RTC_LOG(LS_ERROR) << error;
Steve Anton8d3444d2017-10-20 15:30:51 -07001591 PostCreateSessionDescriptionFailure(observer, error);
1592 return;
1593 }
1594
Steve Anton75737c02017-11-06 10:37:17 -08001595 if (remote_description() &&
Steve Antona3a92c22017-12-07 10:27:41 -08001596 remote_description()->GetType() != SdpType::kOffer) {
Steve Anton8d3444d2017-10-20 15:30:51 -07001597 std::string error = "CreateAnswer called without remote offer.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001598 RTC_LOG(LS_ERROR) << error;
Steve Anton8d3444d2017-10-20 15:30:51 -07001599 PostCreateSessionDescriptionFailure(observer, error);
1600 return;
1601 }
1602
htaa2a49d92016-03-04 02:51:39 -08001603 cricket::MediaSessionOptions session_options;
zhihuang1c378ed2017-08-17 14:10:50 -07001604 GetOptionsForAnswer(options, &session_options);
htaa2a49d92016-03-04 02:51:39 -08001605
Steve Antond25da372017-11-06 14:50:29 -08001606 webrtc_session_desc_factory_->CreateAnswer(observer, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001607}
1608
1609void PeerConnection::SetLocalDescription(
1610 SetSessionDescriptionObserver* observer,
1611 SessionDescriptionInterface* desc) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001612 TRACE_EVENT0("webrtc", "PeerConnection::SetLocalDescription");
Steve Anton8a006912017-12-04 15:25:56 -08001613
nisse7ce109a2017-01-31 00:57:56 -08001614 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001615 RTC_LOG(LS_ERROR) << "SetLocalDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001616 return;
1617 }
Steve Anton8a006912017-12-04 15:25:56 -08001618
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001619 if (!desc) {
1620 PostSetSessionDescriptionFailure(observer, "SessionDescription is NULL.");
1621 return;
1622 }
Steve Anton8d3444d2017-10-20 15:30:51 -07001623
Steve Antona3a92c22017-12-07 10:27:41 -08001624 SdpType type = desc->GetType();
Steve Anton8d3444d2017-10-20 15:30:51 -07001625
Steve Anton8a006912017-12-04 15:25:56 -08001626 RTCError error = ApplyLocalDescription(rtc::WrapUnique(desc));
1627 // |desc| may be destroyed at this point.
1628
1629 if (!error.ok()) {
Steve Antona3a92c22017-12-07 10:27:41 -08001630 std::ostringstream oss;
1631 oss << "Failed to set local " << SdpTypeToString(type)
1632 << " sdp: " << error.message();
1633 std::string error_message = oss.str();
Steve Anton8a006912017-12-04 15:25:56 -08001634 RTC_LOG(LS_ERROR) << error_message << " (" << error.type() << ")";
1635 PostSetSessionDescriptionFailure(observer, std::move(error_message));
Steve Anton8d3444d2017-10-20 15:30:51 -07001636 return;
1637 }
Steve Anton8a006912017-12-04 15:25:56 -08001638 RTC_DCHECK(local_description());
1639
1640 PostSetSessionDescriptionSuccess(observer);
1641
1642 // According to JSEP, after setLocalDescription, changing the candidate pool
1643 // size is not allowed, and changing the set of ICE servers will not result
1644 // in new candidates being gathered.
1645 port_allocator_->FreezeCandidatePool();
1646
1647 // MaybeStartGathering needs to be called after posting
1648 // MSG_SET_SESSIONDESCRIPTION_SUCCESS, so that we don't signal any candidates
1649 // before signaling that SetLocalDescription completed.
1650 transport_controller_->MaybeStartGathering();
1651
Steve Antona3a92c22017-12-07 10:27:41 -08001652 if (local_description()->GetType() == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08001653 // TODO(deadbeef): We already had to hop to the network thread for
1654 // MaybeStartGathering...
1655 network_thread()->Invoke<void>(
1656 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
1657 port_allocator_.get()));
1658 }
1659}
1660
1661RTCError PeerConnection::ApplyLocalDescription(
1662 std::unique_ptr<SessionDescriptionInterface> desc) {
1663 RTC_DCHECK_RUN_ON(signaling_thread());
1664 RTC_DCHECK(desc);
1665
1666 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_LOCAL);
1667 if (!error.ok()) {
1668 return error;
1669 }
Steve Anton8d3444d2017-10-20 15:30:51 -07001670
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001671 // Update stats here so that we have the most recent stats for tracks and
1672 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001673 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 15:25:56 -08001674
1675 // Update the initial_offerer flag if this session is the initial_offerer.
Steve Anton3828c062017-12-06 10:34:51 -08001676 SdpType type = desc->GetType();
Steve Anton8a006912017-12-04 15:25:56 -08001677 if (!initial_offerer_.has_value()) {
Steve Anton3828c062017-12-06 10:34:51 -08001678 initial_offerer_.emplace(type == SdpType::kOffer);
Steve Anton8a006912017-12-04 15:25:56 -08001679 if (*initial_offerer_) {
1680 transport_controller_->SetIceRole(cricket::ICEROLE_CONTROLLING);
1681 } else {
1682 transport_controller_->SetIceRole(cricket::ICEROLE_CONTROLLED);
1683 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001684 }
Steve Anton8a006912017-12-04 15:25:56 -08001685
Steve Antondcc3c022017-12-22 16:02:54 -08001686 // Take a reference to the old local description since it's used below to
1687 // compare against the new local description. When setting the new local
1688 // description, grab ownership of the replaced session description in case it
1689 // is the same as |old_local_description|, to keep it alive for the duration
1690 // of the method.
1691 const SessionDescriptionInterface* old_local_description =
1692 local_description();
1693 std::unique_ptr<SessionDescriptionInterface> replaced_local_description;
Steve Anton3828c062017-12-06 10:34:51 -08001694 if (type == SdpType::kAnswer) {
Steve Antondcc3c022017-12-22 16:02:54 -08001695 replaced_local_description = pending_local_description_
1696 ? std::move(pending_local_description_)
1697 : std::move(current_local_description_);
Steve Anton8a006912017-12-04 15:25:56 -08001698 current_local_description_ = std::move(desc);
1699 pending_local_description_ = nullptr;
1700 current_remote_description_ = std::move(pending_remote_description_);
1701 } else {
Steve Antondcc3c022017-12-22 16:02:54 -08001702 replaced_local_description = std::move(pending_local_description_);
Steve Anton8a006912017-12-04 15:25:56 -08001703 pending_local_description_ = std::move(desc);
1704 }
1705 // The session description to apply now must be accessed by
1706 // |local_description()|.
Henrik Boströmfdb92012017-11-09 19:55:44 +01001707 RTC_DCHECK(local_description());
deadbeefab9b2d12015-10-14 11:33:11 -07001708
Steve Antondcc3c022017-12-22 16:02:54 -08001709 if (IsUnifiedPlan()) {
1710 RTCError error = UpdateTransceiversAndDataChannels(
1711 cricket::CS_LOCAL, old_local_description, *local_description());
Steve Anton8a006912017-12-04 15:25:56 -08001712 if (!error.ok()) {
1713 return error;
1714 }
Steve Antondcc3c022017-12-22 16:02:54 -08001715 for (auto transceiver : transceivers_) {
1716 const ContentInfo* content =
1717 FindMediaSectionForTransceiver(transceiver, local_description());
1718 if (!content) {
1719 continue;
1720 }
1721 const MediaContentDescription* media_desc = content->media_description();
1722 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
1723 transceiver->internal()->set_current_direction(media_desc->direction());
1724 }
1725 if (content->rejected && !transceiver->stopped()) {
1726 transceiver->Stop();
1727 }
1728 }
1729 } else {
1730 // Transport and Media channels will be created only when offer is set.
1731 if (type == SdpType::kOffer) {
1732 // TODO(bugs.webrtc.org/4676) - Handle CreateChannel failure, as new local
1733 // description is applied. Restore back to old description.
1734 RTCError error = CreateChannels(*local_description()->description());
1735 if (!error.ok()) {
1736 return error;
1737 }
1738 }
Steve Anton8a006912017-12-04 15:25:56 -08001739
Steve Antondcc3c022017-12-22 16:02:54 -08001740 // Remove unused channels if MediaContentDescription is rejected.
1741 RemoveUnusedChannels(local_description()->description());
1742 }
Steve Anton8a006912017-12-04 15:25:56 -08001743
Steve Anton3828c062017-12-06 10:34:51 -08001744 error = UpdateSessionState(type, cricket::CS_LOCAL);
Steve Anton8a006912017-12-04 15:25:56 -08001745 if (!error.ok()) {
1746 return error;
1747 }
Steve Antondcc3c022017-12-22 16:02:54 -08001748
Steve Anton8a006912017-12-04 15:25:56 -08001749 if (remote_description()) {
1750 // Now that we have a local description, we can push down remote candidates.
1751 UseCandidatesInSessionDescription(remote_description());
1752 }
1753
1754 pending_ice_restarts_.clear();
1755 if (session_error() != SessionError::kNone) {
1756 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
1757 }
1758
deadbeefab9b2d12015-10-14 11:33:11 -07001759 // If setting the description decided our SSL role, allocate any necessary
1760 // SCTP sids.
1761 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08001762 if (data_channel_type() == cricket::DCT_SCTP && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001763 AllocateSctpSids(role);
1764 }
1765
Steve Antondcc3c022017-12-22 16:02:54 -08001766 if (!IsUnifiedPlan()) {
1767 // Update state and SSRC of local MediaStreams and DataChannels based on the
1768 // local session description.
1769 const cricket::ContentInfo* audio_content =
1770 GetFirstAudioContent(local_description()->description());
1771 if (audio_content) {
1772 if (audio_content->rejected) {
1773 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
1774 } else {
1775 const cricket::AudioContentDescription* audio_desc =
1776 audio_content->media_description()->as_audio();
1777 UpdateLocalSenders(audio_desc->streams(), audio_desc->type());
1778 }
deadbeeffaac4972015-11-12 15:33:07 -08001779 }
deadbeefab9b2d12015-10-14 11:33:11 -07001780
Steve Antondcc3c022017-12-22 16:02:54 -08001781 const cricket::ContentInfo* video_content =
1782 GetFirstVideoContent(local_description()->description());
1783 if (video_content) {
1784 if (video_content->rejected) {
1785 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
1786 } else {
1787 const cricket::VideoContentDescription* video_desc =
1788 video_content->media_description()->as_video();
1789 UpdateLocalSenders(video_desc->streams(), video_desc->type());
1790 }
deadbeeffaac4972015-11-12 15:33:07 -08001791 }
deadbeefab9b2d12015-10-14 11:33:11 -07001792 }
1793
1794 const cricket::ContentInfo* data_content =
Henrik Boströmfdb92012017-11-09 19:55:44 +01001795 GetFirstDataContent(local_description()->description());
deadbeefab9b2d12015-10-14 11:33:11 -07001796 if (data_content) {
1797 const cricket::DataContentDescription* data_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08001798 data_content->media_description()->as_data();
deadbeefab9b2d12015-10-14 11:33:11 -07001799 if (rtc::starts_with(data_desc->protocol().data(),
1800 cricket::kMediaProtocolRtpPrefix)) {
1801 UpdateLocalRtpDataChannels(data_desc->streams());
1802 }
1803 }
1804
Steve Anton8a006912017-12-04 15:25:56 -08001805 return RTCError::OK();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001806}
1807
1808void PeerConnection::SetRemoteDescription(
Henrik Boströma4ecf552017-11-23 14:17:07 +00001809 SetSessionDescriptionObserver* observer,
1810 SessionDescriptionInterface* desc) {
Henrik Boström31638672017-11-23 17:48:32 +01001811 SetRemoteDescription(
1812 std::unique_ptr<SessionDescriptionInterface>(desc),
1813 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface>(
1814 new SetRemoteDescriptionObserverAdapter(this, observer)));
1815}
1816
1817void PeerConnection::SetRemoteDescription(
1818 std::unique_ptr<SessionDescriptionInterface> desc,
1819 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface> observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001820 TRACE_EVENT0("webrtc", "PeerConnection::SetRemoteDescription");
Steve Anton8a006912017-12-04 15:25:56 -08001821
nisse7ce109a2017-01-31 00:57:56 -08001822 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001823 RTC_LOG(LS_ERROR) << "SetRemoteDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001824 return;
1825 }
Steve Anton8a006912017-12-04 15:25:56 -08001826
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001827 if (!desc) {
Henrik Boström31638672017-11-23 17:48:32 +01001828 observer->OnSetRemoteDescriptionComplete(RTCError(
Steve Anton8a006912017-12-04 15:25:56 -08001829 RTCErrorType::INVALID_PARAMETER, "SessionDescription is NULL."));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001830 return;
1831 }
Steve Anton8d3444d2017-10-20 15:30:51 -07001832
Steve Antona3a92c22017-12-07 10:27:41 -08001833 const SdpType type = desc->GetType();
Steve Anton8a006912017-12-04 15:25:56 -08001834
1835 RTCError error = ApplyRemoteDescription(std::move(desc));
1836 // |desc| may be destroyed at this point.
1837
1838 if (!error.ok()) {
Steve Antona3a92c22017-12-07 10:27:41 -08001839 std::ostringstream oss;
1840 oss << "Failed to set remote " << SdpTypeToString(type)
1841 << " sdp: " << error.message();
1842 std::string error_message = oss.str();
Steve Anton8a006912017-12-04 15:25:56 -08001843 RTC_LOG(LS_ERROR) << error_message << " (" << error.type() << ")";
Henrik Boström31638672017-11-23 17:48:32 +01001844 observer->OnSetRemoteDescriptionComplete(
Steve Anton8a006912017-12-04 15:25:56 -08001845 RTCError(error.type(), std::move(error_message)));
Steve Anton8d3444d2017-10-20 15:30:51 -07001846 return;
1847 }
1848
Steve Antona3a92c22017-12-07 10:27:41 -08001849 if (remote_description()->GetType() == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08001850 // TODO(deadbeef): We already had to hop to the network thread for
1851 // MaybeStartGathering...
1852 network_thread()->Invoke<void>(
1853 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
1854 port_allocator_.get()));
1855 }
1856
1857 observer->OnSetRemoteDescriptionComplete(RTCError::OK());
1858}
1859
1860RTCError PeerConnection::ApplyRemoteDescription(
1861 std::unique_ptr<SessionDescriptionInterface> desc) {
1862 RTC_DCHECK_RUN_ON(signaling_thread());
1863 RTC_DCHECK(desc);
1864
1865 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_REMOTE);
1866 if (!error.ok()) {
1867 return error;
1868 }
1869
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001870 // Update stats here so that we have the most recent stats for tracks and
1871 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001872 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 15:25:56 -08001873
Steve Antondcc3c022017-12-22 16:02:54 -08001874 // Take a reference to the old remote description since it's used below to
1875 // compare against the new remote description. When setting the new remote
1876 // description, grab ownership of the replaced session description in case it
1877 // is the same as |old_remote_description|, to keep it alive for the duration
1878 // of the method.
Steve Anton8a006912017-12-04 15:25:56 -08001879 const SessionDescriptionInterface* old_remote_description =
1880 remote_description();
Steve Anton8a006912017-12-04 15:25:56 -08001881 std::unique_ptr<SessionDescriptionInterface> replaced_remote_description;
Steve Anton3828c062017-12-06 10:34:51 -08001882 SdpType type = desc->GetType();
1883 if (type == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08001884 replaced_remote_description = pending_remote_description_
1885 ? std::move(pending_remote_description_)
1886 : std::move(current_remote_description_);
1887 current_remote_description_ = std::move(desc);
1888 pending_remote_description_ = nullptr;
1889 current_local_description_ = std::move(pending_local_description_);
1890 } else {
1891 replaced_remote_description = std::move(pending_remote_description_);
1892 pending_remote_description_ = std::move(desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001893 }
Steve Anton8a006912017-12-04 15:25:56 -08001894 // The session description to apply now must be accessed by
1895 // |remote_description()|.
Henrik Boströmfdb92012017-11-09 19:55:44 +01001896 RTC_DCHECK(remote_description());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001897
Steve Anton8a006912017-12-04 15:25:56 -08001898 // Transport and Media channels will be created only when offer is set.
Steve Antondcc3c022017-12-22 16:02:54 -08001899 if (IsUnifiedPlan()) {
1900 RTCError error = UpdateTransceiversAndDataChannels(
1901 cricket::CS_REMOTE, old_remote_description, *remote_description());
Steve Anton8a006912017-12-04 15:25:56 -08001902 if (!error.ok()) {
1903 return error;
1904 }
Steve Antondcc3c022017-12-22 16:02:54 -08001905 } else {
1906 if (type == SdpType::kOffer) {
1907 // TODO(bugs.webrtc.org/4676) - Handle CreateChannel failure, as new local
1908 // description is applied. Restore back to old description.
1909 RTCError error = CreateChannels(*remote_description()->description());
1910 if (!error.ok()) {
1911 return error;
1912 }
1913 }
Steve Anton8a006912017-12-04 15:25:56 -08001914
Steve Antondcc3c022017-12-22 16:02:54 -08001915 // Remove unused channels if MediaContentDescription is rejected.
1916 RemoveUnusedChannels(remote_description()->description());
1917 }
Steve Anton8a006912017-12-04 15:25:56 -08001918
1919 // NOTE: Candidates allocation will be initiated only when SetLocalDescription
1920 // is called.
Steve Anton3828c062017-12-06 10:34:51 -08001921 error = UpdateSessionState(type, cricket::CS_REMOTE);
Steve Anton8a006912017-12-04 15:25:56 -08001922 if (!error.ok()) {
1923 return error;
1924 }
1925
1926 if (local_description() &&
1927 !UseCandidatesInSessionDescription(remote_description())) {
1928 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidCandidates);
1929 }
1930
1931 if (old_remote_description) {
1932 for (const cricket::ContentInfo& content :
1933 old_remote_description->description()->contents()) {
1934 // Check if this new SessionDescription contains new ICE ufrag and
1935 // password that indicates the remote peer requests an ICE restart.
1936 // TODO(deadbeef): When we start storing both the current and pending
1937 // remote description, this should reset pending_ice_restarts and compare
1938 // against the current description.
1939 if (CheckForRemoteIceRestart(old_remote_description, remote_description(),
1940 content.name)) {
Steve Anton3828c062017-12-06 10:34:51 -08001941 if (type == SdpType::kOffer) {
Steve Anton8a006912017-12-04 15:25:56 -08001942 pending_ice_restarts_.insert(content.name);
1943 }
1944 } else {
1945 // We retain all received candidates only if ICE is not restarted.
1946 // When ICE is restarted, all previous candidates belong to an old
1947 // generation and should not be kept.
1948 // TODO(deadbeef): This goes against the W3C spec which says the remote
1949 // description should only contain candidates from the last set remote
1950 // description plus any candidates added since then. We should remove
1951 // this once we're sure it won't break anything.
1952 WebRtcSessionDescriptionFactory::CopyCandidatesFromSessionDescription(
1953 old_remote_description, content.name, mutable_remote_description());
1954 }
1955 }
1956 }
1957
1958 if (session_error() != SessionError::kNone) {
1959 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
1960 }
1961
1962 // Set the the ICE connection state to connecting since the connection may
1963 // become writable with peer reflexive candidates before any remote candidate
1964 // is signaled.
1965 // TODO(pthatcher): This is a short-term solution for crbug/446908. A real fix
1966 // is to have a new signal the indicates a change in checking state from the
1967 // transport and expose a new checking() member from transport that can be
1968 // read to determine the current checking state. The existing SignalConnecting
1969 // actually means "gathering candidates", so cannot be be used here.
Steve Antona3a92c22017-12-07 10:27:41 -08001970 if (remote_description()->GetType() != SdpType::kOffer &&
Steve Anton8a006912017-12-04 15:25:56 -08001971 ice_connection_state() == PeerConnectionInterface::kIceConnectionNew) {
1972 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
1973 }
1974
deadbeefab9b2d12015-10-14 11:33:11 -07001975 // If setting the description decided our SSL role, allocate any necessary
1976 // SCTP sids.
1977 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08001978 if (data_channel_type() == cricket::DCT_SCTP && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001979 AllocateSctpSids(role);
1980 }
1981
Steve Antondcc3c022017-12-22 16:02:54 -08001982 if (IsUnifiedPlan()) {
1983 for (auto transceiver : transceivers_) {
1984 const ContentInfo* content =
1985 FindMediaSectionForTransceiver(transceiver, remote_description());
1986 if (!content) {
1987 continue;
1988 }
1989 const MediaContentDescription* media_desc = content->media_description();
1990 RtpTransceiverDirection local_direction =
1991 RtpTransceiverDirectionReversed(media_desc->direction());
1992 // From the WebRTC specification, steps 2.2.8.5/6 of section 4.4.1.6 "Set
1993 // the RTCSessionDescription: If direction is sendrecv or recvonly, and
1994 // transceiver's current direction is neither sendrecv nor recvonly,
1995 // process the addition of a remote track for the media description.
1996 if (RtpTransceiverDirectionHasRecv(local_direction) &&
1997 (!transceiver->current_direction() ||
1998 !RtpTransceiverDirectionHasRecv(
1999 *transceiver->current_direction()))) {
2000 // TODO(bugs.webrtc.org/7600): Process the addition of a remote track.
2001 }
2002 // If direction is sendonly or inactive, and transceiver's current
2003 // direction is neither sendonly nor inactive, process the removal of a
2004 // remote track for the media description.
2005 if (!RtpTransceiverDirectionHasRecv(local_direction) &&
2006 (!transceiver->current_direction() ||
2007 RtpTransceiverDirectionHasRecv(*transceiver->current_direction()))) {
2008 // TODO(bugs.webrtc.org/7600): Process the removal of a remote track.
2009 }
2010 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
2011 transceiver->internal()->set_current_direction(local_direction);
2012 }
2013 if (content->rejected && !transceiver->stopped()) {
2014 transceiver->Stop();
2015 }
2016 }
2017 }
2018
Henrik Boströmfdb92012017-11-09 19:55:44 +01002019 const cricket::ContentInfo* audio_content =
2020 GetFirstAudioContent(remote_description()->description());
2021 const cricket::ContentInfo* video_content =
2022 GetFirstVideoContent(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002023 const cricket::AudioContentDescription* audio_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002024 GetFirstAudioContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002025 const cricket::VideoContentDescription* video_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002026 GetFirstVideoContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002027 const cricket::DataContentDescription* data_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002028 GetFirstDataContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002029
2030 // Check if the descriptions include streams, just in case the peer supports
2031 // MSID, but doesn't indicate so with "a=msid-semantic".
Henrik Boströmfdb92012017-11-09 19:55:44 +01002032 if (remote_description()->description()->msid_supported() ||
deadbeefbda7e0b2015-12-08 17:13:40 -08002033 (audio_desc && !audio_desc->streams().empty()) ||
2034 (video_desc && !video_desc->streams().empty())) {
2035 remote_peer_supports_msid_ = true;
2036 }
deadbeefab9b2d12015-10-14 11:33:11 -07002037
2038 // We wait to signal new streams until we finish processing the description,
2039 // since only at that point will new streams have all their tracks.
2040 rtc::scoped_refptr<StreamCollection> new_streams(StreamCollection::Create());
2041
Steve Antondcc3c022017-12-22 16:02:54 -08002042 if (!IsUnifiedPlan()) {
2043 // TODO(steveanton): When removing RTP senders/receivers in response to a
2044 // rejected media section, there is some cleanup logic that expects the
2045 // voice/ video channel to still be set. But in this method the voice/video
2046 // channel would have been destroyed by the SetRemoteDescription caller
2047 // above so the cleanup that relies on them fails to run. The RemoveSenders
2048 // calls should be moved to right before the DestroyChannel calls to fix
2049 // this.
Steve Anton8d3444d2017-10-20 15:30:51 -07002050
Steve Antondcc3c022017-12-22 16:02:54 -08002051 // Find all audio rtp streams and create corresponding remote AudioTracks
2052 // and MediaStreams.
2053 if (audio_content) {
2054 if (audio_content->rejected) {
2055 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
2056 } else {
2057 bool default_audio_track_needed =
2058 !remote_peer_supports_msid_ &&
2059 RtpTransceiverDirectionHasSend(audio_desc->direction());
2060 UpdateRemoteSendersList(GetActiveStreams(audio_desc),
2061 default_audio_track_needed, audio_desc->type(),
2062 new_streams);
2063 }
deadbeeffaac4972015-11-12 15:33:07 -08002064 }
deadbeefab9b2d12015-10-14 11:33:11 -07002065
Steve Antondcc3c022017-12-22 16:02:54 -08002066 // Find all video rtp streams and create corresponding remote VideoTracks
2067 // and MediaStreams.
2068 if (video_content) {
2069 if (video_content->rejected) {
2070 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
2071 } else {
2072 bool default_video_track_needed =
2073 !remote_peer_supports_msid_ &&
2074 RtpTransceiverDirectionHasSend(video_desc->direction());
2075 UpdateRemoteSendersList(GetActiveStreams(video_desc),
2076 default_video_track_needed, video_desc->type(),
2077 new_streams);
2078 }
deadbeeffaac4972015-11-12 15:33:07 -08002079 }
deadbeefab9b2d12015-10-14 11:33:11 -07002080
Steve Antondcc3c022017-12-22 16:02:54 -08002081 // Update the DataChannels with the information from the remote peer.
2082 if (data_desc) {
2083 if (rtc::starts_with(data_desc->protocol().data(),
2084 cricket::kMediaProtocolRtpPrefix)) {
2085 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
2086 }
deadbeefab9b2d12015-10-14 11:33:11 -07002087 }
deadbeefab9b2d12015-10-14 11:33:11 -07002088
Steve Antondcc3c022017-12-22 16:02:54 -08002089 // Iterate new_streams and notify the observer about new MediaStreams.
2090 for (size_t i = 0; i < new_streams->count(); ++i) {
2091 MediaStreamInterface* new_stream = new_streams->at(i);
2092 stats_->AddStream(new_stream);
2093 observer_->OnAddStream(
2094 rtc::scoped_refptr<MediaStreamInterface>(new_stream));
2095 }
deadbeefab9b2d12015-10-14 11:33:11 -07002096
Steve Antondcc3c022017-12-22 16:02:54 -08002097 UpdateEndedRemoteMediaStreams();
2098 }
deadbeefab9b2d12015-10-14 11:33:11 -07002099
Steve Anton8a006912017-12-04 15:25:56 -08002100 return RTCError::OK();
deadbeeffc648b62015-10-13 16:42:33 -07002101}
2102
Steve Antondcc3c022017-12-22 16:02:54 -08002103RTCError PeerConnection::UpdateTransceiversAndDataChannels(
2104 cricket::ContentSource source,
2105 const SessionDescriptionInterface* old_session,
2106 const SessionDescriptionInterface& new_session) {
2107 RTC_DCHECK(IsUnifiedPlan());
2108
2109 auto bundle_group_or_error = GetEarlyBundleGroup(*new_session.description());
2110 if (!bundle_group_or_error.ok()) {
2111 return bundle_group_or_error.MoveError();
2112 }
2113 const cricket::ContentGroup* bundle_group = bundle_group_or_error.MoveValue();
2114
2115 const ContentInfos& old_contents =
2116 (old_session ? old_session->description()->contents() : ContentInfos());
2117 const ContentInfos& new_contents = new_session.description()->contents();
2118
2119 for (size_t i = 0; i < new_contents.size(); ++i) {
2120 const cricket::ContentInfo& new_content = new_contents[i];
2121 const cricket::ContentInfo* old_content =
2122 (i < old_contents.size() ? &old_contents[i] : nullptr);
2123 cricket::MediaType media_type = new_content.media_description()->type();
2124 seen_mids_.insert(new_content.name);
2125 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
2126 media_type == cricket::MEDIA_TYPE_VIDEO) {
2127 auto transceiver_or_error =
2128 AssociateTransceiver(source, i, new_content, old_content);
2129 if (!transceiver_or_error.ok()) {
2130 return transceiver_or_error.MoveError();
2131 }
2132 auto transceiver = transceiver_or_error.MoveValue();
2133 if (source == cricket::CS_LOCAL && transceiver->stopped()) {
2134 continue;
2135 }
2136 RTCError error =
2137 UpdateTransceiverChannel(transceiver, new_content, bundle_group);
2138 if (!error.ok()) {
2139 return error;
2140 }
2141 } else if (media_type == cricket::MEDIA_TYPE_DATA) {
Steve Antonfa2260d2017-12-28 16:38:23 -08002142 if (GetDataMid() && new_content.name != *GetDataMid()) {
2143 // Ignore all but the first data section.
2144 continue;
2145 }
2146 RTCError error = UpdateDataChannel(source, new_content, bundle_group);
2147 if (!error.ok()) {
2148 return error;
2149 }
Steve Antondcc3c022017-12-22 16:02:54 -08002150 } else {
2151 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
2152 "Unknown section type.");
2153 }
2154 }
2155
2156 return RTCError::OK();
2157}
2158
2159RTCError PeerConnection::UpdateTransceiverChannel(
2160 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2161 transceiver,
2162 const cricket::ContentInfo& content,
2163 const cricket::ContentGroup* bundle_group) {
2164 RTC_DCHECK(IsUnifiedPlan());
2165 RTC_DCHECK(transceiver);
2166 cricket::BaseChannel* channel = transceiver->internal()->channel();
2167 if (content.rejected) {
2168 if (channel) {
2169 transceiver->internal()->SetChannel(nullptr);
2170 DestroyBaseChannel(channel);
2171 }
2172 } else {
2173 if (!channel) {
2174 if (transceiver->internal()->media_type() == cricket::MEDIA_TYPE_AUDIO) {
2175 channel = CreateVoiceChannel(
2176 content.name,
2177 GetTransportNameForMediaSection(content.name, bundle_group));
2178 } else {
2179 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO,
2180 transceiver->internal()->media_type());
2181 channel = CreateVideoChannel(
2182 content.name,
2183 GetTransportNameForMediaSection(content.name, bundle_group));
2184 }
2185 if (!channel) {
2186 LOG_AND_RETURN_ERROR(
2187 RTCErrorType::INTERNAL_ERROR,
2188 "Failed to create channel for mid=" + content.name);
2189 }
2190 transceiver->internal()->SetChannel(channel);
2191 }
2192 }
2193 return RTCError::OK();
2194}
2195
Steve Antonfa2260d2017-12-28 16:38:23 -08002196RTCError PeerConnection::UpdateDataChannel(
2197 cricket::ContentSource source,
2198 const cricket::ContentInfo& content,
2199 const cricket::ContentGroup* bundle_group) {
2200 if (data_channel_type_ == cricket::DCT_NONE) {
2201 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2202 "Data channels are not supported.");
2203 }
2204 if (content.rejected) {
2205 DestroyDataChannel();
2206 } else {
2207 if (!rtp_data_channel_ && !sctp_transport_) {
2208 if (!CreateDataChannel(content.name, GetTransportNameForMediaSection(
2209 content.name, bundle_group))) {
2210 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
2211 "Failed to create data channel.");
2212 }
2213 }
2214 if (source == cricket::CS_REMOTE) {
2215 const MediaContentDescription* data_desc = content.media_description();
2216 if (data_desc && cricket::IsRtpProtocol(data_desc->protocol())) {
2217 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
2218 }
2219 }
2220 }
2221 return RTCError::OK();
2222}
2223
Steve Antondcc3c022017-12-22 16:02:54 -08002224RTCErrorOr<rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
2225PeerConnection::AssociateTransceiver(cricket::ContentSource source,
2226 size_t mline_index,
2227 const ContentInfo& content,
2228 const ContentInfo* old_content) {
2229 RTC_DCHECK(IsUnifiedPlan());
2230 // If the m= section is being recycled (rejected in previous remote
2231 // description, not rejected in current description), dissociate the currently
2232 // associated RtpTransceiver by setting its mid property to null, and discard
2233 // the mapping between the transceiver and its m= section index.
2234 if (old_content && old_content->rejected && !content.rejected) {
2235 auto old_transceiver = GetAssociatedTransceiver(old_content->name);
2236 if (old_transceiver) {
2237 old_transceiver->internal()->set_mid(rtc::nullopt);
2238 old_transceiver->internal()->set_mline_index(rtc::nullopt);
2239 }
2240 }
2241 const MediaContentDescription* media_desc = content.media_description();
2242 auto transceiver = GetAssociatedTransceiver(content.name);
2243 if (source == cricket::CS_LOCAL) {
2244 // Find the RtpTransceiver that corresponds to this m= section, using the
2245 // mapping between transceivers and m= section indices established when
2246 // creating the offer.
2247 if (!transceiver) {
2248 transceiver = GetTransceiverByMLineIndex(mline_index);
2249 }
2250 if (!transceiver) {
2251 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2252 "Unknown transceiver");
2253 }
2254 } else {
2255 RTC_DCHECK_EQ(source, cricket::CS_REMOTE);
2256 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers
2257 // of the same type...
2258 if (!transceiver &&
2259 RtpTransceiverDirectionHasRecv(media_desc->direction())) {
2260 transceiver = FindAvailableTransceiverToReceive(media_desc->type());
2261 }
2262 // If no RtpTransceiver was found in the previous step, create one with a
2263 // recvonly direction.
2264 if (!transceiver) {
Steve Anton02ee47c2018-01-10 16:26:06 -08002265 auto sender =
2266 CreateSender(media_desc->type(), nullptr, {rtc::CreateRandomUuid()});
2267 auto receiver =
2268 CreateReceiver(media_desc->type(), media_desc->streams()[0].id);
2269 transceiver = CreateAndAddTransceiver(sender, receiver);
Steve Antondcc3c022017-12-22 16:02:54 -08002270 transceiver->internal()->set_direction(
2271 RtpTransceiverDirection::kRecvOnly);
2272 }
2273 }
2274 RTC_DCHECK(transceiver);
2275 if (transceiver->internal()->media_type() != media_desc->type()) {
2276 LOG_AND_RETURN_ERROR(
2277 RTCErrorType::INVALID_PARAMETER,
2278 "Transceiver type does not match media description type.");
2279 }
2280 // Associate the found or created RtpTransceiver with the m= section by
2281 // setting the value of the RtpTransceiver's mid property to the MID of the m=
2282 // section, and establish a mapping between the transceiver and the index of
2283 // the m= section.
2284 transceiver->internal()->set_mid(content.name);
2285 transceiver->internal()->set_mline_index(mline_index);
2286 return std::move(transceiver);
2287}
2288
2289rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2290PeerConnection::GetAssociatedTransceiver(const std::string& mid) const {
2291 RTC_DCHECK(IsUnifiedPlan());
2292 for (auto transceiver : transceivers_) {
2293 if (transceiver->mid() == mid) {
2294 return transceiver;
2295 }
2296 }
2297 return nullptr;
2298}
2299
2300rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2301PeerConnection::GetTransceiverByMLineIndex(size_t mline_index) const {
2302 RTC_DCHECK(IsUnifiedPlan());
2303 for (auto transceiver : transceivers_) {
2304 if (transceiver->internal()->mline_index() == mline_index) {
2305 return transceiver;
2306 }
2307 }
2308 return nullptr;
2309}
2310
2311rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2312PeerConnection::FindAvailableTransceiverToReceive(
2313 cricket::MediaType media_type) const {
2314 RTC_DCHECK(IsUnifiedPlan());
2315 // From JSEP section 5.10 (Applying a Remote Description):
2316 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers of
2317 // the same type that were added to the PeerConnection by addTrack and are not
2318 // associated with any m= section and are not stopped, find the first such
2319 // RtpTransceiver.
2320 for (auto transceiver : transceivers_) {
2321 if (transceiver->internal()->media_type() == media_type &&
2322 transceiver->internal()->created_by_addtrack() && !transceiver->mid() &&
2323 !transceiver->stopped()) {
2324 return transceiver;
2325 }
2326 }
2327 return nullptr;
2328}
2329
Steve Antoned10bd92017-12-05 10:52:59 -08002330const cricket::ContentInfo* PeerConnection::FindMediaSectionForTransceiver(
2331 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2332 transceiver,
2333 const SessionDescriptionInterface* sdesc) const {
2334 RTC_DCHECK(transceiver);
2335 RTC_DCHECK(sdesc);
2336 if (IsUnifiedPlan()) {
2337 if (!transceiver->internal()->mid()) {
2338 // This transceiver is not associated with a media section yet.
2339 return nullptr;
2340 }
2341 return sdesc->description()->GetContentByName(
2342 *transceiver->internal()->mid());
2343 } else {
2344 // Plan B only allows at most one audio and one video section, so use the
2345 // first media section of that type.
2346 return cricket::GetFirstMediaContent(sdesc->description()->contents(),
2347 transceiver->internal()->media_type());
2348 }
2349}
2350
deadbeef46c73892016-11-16 19:42:04 -08002351PeerConnectionInterface::RTCConfiguration PeerConnection::GetConfiguration() {
2352 return configuration_;
2353}
2354
deadbeef293e9262017-01-11 12:28:30 -08002355bool PeerConnection::SetConfiguration(const RTCConfiguration& configuration,
2356 RTCError* error) {
Peter Boström1a9d6152015-12-08 22:15:17 +01002357 TRACE_EVENT0("webrtc", "PeerConnection::SetConfiguration");
deadbeef6de92f92016-12-12 18:49:32 -08002358
Steve Anton75737c02017-11-06 10:37:17 -08002359 if (local_description() && configuration.ice_candidate_pool_size !=
2360 configuration_.ice_candidate_pool_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002361 RTC_LOG(LS_ERROR) << "Can't change candidate pool size after calling "
2362 "SetLocalDescription.";
deadbeef293e9262017-01-11 12:28:30 -08002363 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00002364 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002365
deadbeef293e9262017-01-11 12:28:30 -08002366 // The simplest (and most future-compatible) way to tell if the config was
2367 // modified in an invalid way is to copy each property we do support
2368 // modifying, then use operator==. There are far more properties we don't
2369 // support modifying than those we do, and more could be added.
2370 RTCConfiguration modified_config = configuration_;
2371 modified_config.servers = configuration.servers;
2372 modified_config.type = configuration.type;
2373 modified_config.ice_candidate_pool_size =
2374 configuration.ice_candidate_pool_size;
2375 modified_config.prune_turn_ports = configuration.prune_turn_ports;
skvladd1f5fda2017-02-03 16:54:05 -08002376 modified_config.ice_check_min_interval = configuration.ice_check_min_interval;
Jonas Orelandbdcee282017-10-10 14:01:40 +02002377 modified_config.turn_customizer = configuration.turn_customizer;
deadbeef293e9262017-01-11 12:28:30 -08002378 if (configuration != modified_config) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002379 RTC_LOG(LS_ERROR) << "Modifying the configuration in an unsupported way.";
deadbeef293e9262017-01-11 12:28:30 -08002380 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
2381 }
2382
Steve Anton038834f2017-07-14 15:59:59 -07002383 // Validate the modified configuration.
2384 RTCError validate_error = ValidateConfiguration(modified_config);
2385 if (!validate_error.ok()) {
2386 return SafeSetError(std::move(validate_error), error);
2387 }
2388
deadbeef293e9262017-01-11 12:28:30 -08002389 // Note that this isn't possible through chromium, since it's an unsigned
2390 // short in WebIDL.
2391 if (configuration.ice_candidate_pool_size < 0 ||
2392 configuration.ice_candidate_pool_size > UINT16_MAX) {
2393 return SafeSetError(RTCErrorType::INVALID_RANGE, error);
2394 }
2395
2396 // Parse ICE servers before hopping to network thread.
2397 cricket::ServerAddresses stun_servers;
2398 std::vector<cricket::RelayServerConfig> turn_servers;
2399 RTCErrorType parse_error =
2400 ParseIceServers(configuration.servers, &stun_servers, &turn_servers);
2401 if (parse_error != RTCErrorType::NONE) {
2402 return SafeSetError(parse_error, error);
2403 }
2404
2405 // In theory this shouldn't fail.
2406 if (!network_thread()->Invoke<bool>(
2407 RTC_FROM_HERE,
2408 rtc::Bind(&PeerConnection::ReconfigurePortAllocator_n, this,
2409 stun_servers, turn_servers, modified_config.type,
2410 modified_config.ice_candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02002411 modified_config.prune_turn_ports,
2412 modified_config.turn_customizer))) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002413 RTC_LOG(LS_ERROR) << "Failed to apply configuration to PortAllocator.";
deadbeef293e9262017-01-11 12:28:30 -08002414 return SafeSetError(RTCErrorType::INTERNAL_ERROR, error);
2415 }
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07002416
deadbeefd1a38b52016-12-10 13:15:33 -08002417 // As described in JSEP, calling setConfiguration with new ICE servers or
2418 // candidate policy must set a "needs-ice-restart" bit so that the next offer
2419 // triggers an ICE restart which will pick up the changes.
deadbeef293e9262017-01-11 12:28:30 -08002420 if (modified_config.servers != configuration_.servers ||
2421 modified_config.type != configuration_.type ||
2422 modified_config.prune_turn_ports != configuration_.prune_turn_ports) {
Steve Antond25da372017-11-06 14:50:29 -08002423 transport_controller_->SetNeedsIceRestartFlag();
deadbeefd1a38b52016-12-10 13:15:33 -08002424 }
skvladd1f5fda2017-02-03 16:54:05 -08002425
2426 if (modified_config.ice_check_min_interval !=
2427 configuration_.ice_check_min_interval) {
Steve Antond25da372017-11-06 14:50:29 -08002428 transport_controller_->SetIceConfig(ParseIceConfig(modified_config));
skvladd1f5fda2017-02-03 16:54:05 -08002429 }
2430
deadbeef293e9262017-01-11 12:28:30 -08002431 configuration_ = modified_config;
2432 return SafeSetError(RTCErrorType::NONE, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00002433}
2434
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002435bool PeerConnection::AddIceCandidate(
2436 const IceCandidateInterface* ice_candidate) {
Peter Boström1a9d6152015-12-08 22:15:17 +01002437 TRACE_EVENT0("webrtc", "PeerConnection::AddIceCandidate");
zhihuang29ff8442016-07-27 11:07:25 -07002438 if (IsClosed()) {
2439 return false;
2440 }
Steve Antond25da372017-11-06 14:50:29 -08002441
2442 if (!remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002443 RTC_LOG(LS_ERROR) << "ProcessIceMessage: ICE candidates can't be added "
2444 << "without any remote session description.";
Steve Antond25da372017-11-06 14:50:29 -08002445 return false;
2446 }
2447
2448 if (!ice_candidate) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002449 RTC_LOG(LS_ERROR) << "ProcessIceMessage: Candidate is NULL.";
Steve Antond25da372017-11-06 14:50:29 -08002450 return false;
2451 }
2452
2453 bool valid = false;
2454 bool ready = ReadyToUseRemoteCandidate(ice_candidate, nullptr, &valid);
2455 if (!valid) {
2456 return false;
2457 }
2458
2459 // Add this candidate to the remote session description.
2460 if (!mutable_remote_description()->AddCandidate(ice_candidate)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002461 RTC_LOG(LS_ERROR) << "ProcessIceMessage: Candidate cannot be used.";
Steve Antond25da372017-11-06 14:50:29 -08002462 return false;
2463 }
2464
2465 if (ready) {
2466 return UseCandidate(ice_candidate);
2467 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002468 RTC_LOG(LS_INFO) << "ProcessIceMessage: Not ready to use candidate.";
Steve Antond25da372017-11-06 14:50:29 -08002469 return true;
2470 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002471}
2472
Honghai Zhang7fb69db2016-03-14 11:59:18 -07002473bool PeerConnection::RemoveIceCandidates(
2474 const std::vector<cricket::Candidate>& candidates) {
2475 TRACE_EVENT0("webrtc", "PeerConnection::RemoveIceCandidates");
Steve Antond25da372017-11-06 14:50:29 -08002476 if (!remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002477 RTC_LOG(LS_ERROR) << "RemoveRemoteIceCandidates: ICE candidates can't be "
2478 << "removed without any remote session description.";
Steve Antond25da372017-11-06 14:50:29 -08002479 return false;
2480 }
2481
2482 if (candidates.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002483 RTC_LOG(LS_ERROR) << "RemoveRemoteIceCandidates: candidates are empty.";
Steve Antond25da372017-11-06 14:50:29 -08002484 return false;
2485 }
2486
2487 size_t number_removed =
2488 mutable_remote_description()->RemoveCandidates(candidates);
2489 if (number_removed != candidates.size()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002490 RTC_LOG(LS_ERROR)
2491 << "RemoveRemoteIceCandidates: Failed to remove candidates. "
2492 << "Requested " << candidates.size() << " but only " << number_removed
2493 << " are removed.";
Steve Antond25da372017-11-06 14:50:29 -08002494 }
2495
2496 // Remove the candidates from the transport controller.
2497 std::string error;
2498 bool res = transport_controller_->RemoveRemoteCandidates(candidates, &error);
2499 if (!res && !error.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002500 RTC_LOG(LS_ERROR) << "Error when removing remote candidates: " << error;
Steve Antond25da372017-11-06 14:50:29 -08002501 }
2502 return true;
Honghai Zhang7fb69db2016-03-14 11:59:18 -07002503}
2504
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00002505void PeerConnection::RegisterUMAObserver(UMAObserver* observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +01002506 TRACE_EVENT0("webrtc", "PeerConnection::RegisterUmaObserver");
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00002507 uma_observer_ = observer;
guoweis@webrtc.org7169afd2014-12-04 17:59:29 +00002508
Steve Anton75737c02017-11-06 10:37:17 -08002509 if (transport_controller()) {
2510 transport_controller()->SetMetricsObserver(uma_observer_);
guoweis@webrtc.org7169afd2014-12-04 17:59:29 +00002511 }
2512
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00002513 // Send information about IPv4/IPv6 status.
deadbeef293e9262017-01-11 12:28:30 -08002514 if (uma_observer_) {
Honghai Zhangd93f50c2016-10-05 11:47:22 -07002515 port_allocator_->SetMetricsObserver(uma_observer_);
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00002516 if (port_allocator_->flags() & cricket::PORTALLOCATOR_ENABLE_IPV6) {
Guo-wei Shiehdfbe6792015-09-03 17:12:07 -07002517 uma_observer_->IncrementEnumCounter(
2518 kEnumCounterAddressFamily, kPeerConnection_IPv6,
2519 kPeerConnectionAddressFamilyCounter_Max);
mallinath@webrtc.orgb445f262014-05-23 22:19:37 +00002520 } else {
Guo-wei Shiehdfbe6792015-09-03 17:12:07 -07002521 uma_observer_->IncrementEnumCounter(
2522 kEnumCounterAddressFamily, kPeerConnection_IPv4,
2523 kPeerConnectionAddressFamilyCounter_Max);
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00002524 }
2525 }
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00002526}
2527
zstein4b979802017-06-02 14:37:37 -07002528RTCError PeerConnection::SetBitrate(const BitrateParameters& bitrate) {
Steve Anton978b8762017-09-29 12:15:02 -07002529 if (!worker_thread()->IsCurrent()) {
2530 return worker_thread()->Invoke<RTCError>(
zstein4b979802017-06-02 14:37:37 -07002531 RTC_FROM_HERE, rtc::Bind(&PeerConnection::SetBitrate, this, bitrate));
2532 }
2533
2534 const bool has_min = static_cast<bool>(bitrate.min_bitrate_bps);
2535 const bool has_current = static_cast<bool>(bitrate.current_bitrate_bps);
2536 const bool has_max = static_cast<bool>(bitrate.max_bitrate_bps);
2537 if (has_min && *bitrate.min_bitrate_bps < 0) {
2538 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2539 "min_bitrate_bps <= 0");
2540 }
2541 if (has_current) {
2542 if (has_min && *bitrate.current_bitrate_bps < *bitrate.min_bitrate_bps) {
2543 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2544 "current_bitrate_bps < min_bitrate_bps");
2545 } else if (*bitrate.current_bitrate_bps < 0) {
2546 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2547 "curent_bitrate_bps < 0");
2548 }
2549 }
2550 if (has_max) {
2551 if (has_current &&
2552 *bitrate.max_bitrate_bps < *bitrate.current_bitrate_bps) {
2553 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2554 "max_bitrate_bps < current_bitrate_bps");
2555 } else if (has_min && *bitrate.max_bitrate_bps < *bitrate.min_bitrate_bps) {
2556 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2557 "max_bitrate_bps < min_bitrate_bps");
2558 } else if (*bitrate.max_bitrate_bps < 0) {
2559 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2560 "max_bitrate_bps < 0");
2561 }
2562 }
2563
2564 Call::Config::BitrateConfigMask mask;
2565 mask.min_bitrate_bps = bitrate.min_bitrate_bps;
2566 mask.start_bitrate_bps = bitrate.current_bitrate_bps;
2567 mask.max_bitrate_bps = bitrate.max_bitrate_bps;
2568
2569 RTC_DCHECK(call_.get());
2570 call_->SetBitrateConfigMask(mask);
2571
2572 return RTCError::OK();
2573}
2574
Alex Narest78609d52017-10-20 10:37:47 +02002575void PeerConnection::SetBitrateAllocationStrategy(
2576 std::unique_ptr<rtc::BitrateAllocationStrategy>
2577 bitrate_allocation_strategy) {
2578 rtc::Thread* worker_thread = factory_->worker_thread();
2579 if (!worker_thread->IsCurrent()) {
2580 rtc::BitrateAllocationStrategy* strategy_raw =
2581 bitrate_allocation_strategy.release();
2582 auto functor = [this, strategy_raw]() {
2583 call_->SetBitrateAllocationStrategy(
2584 rtc::WrapUnique<rtc::BitrateAllocationStrategy>(strategy_raw));
2585 };
2586 worker_thread->Invoke<void>(RTC_FROM_HERE, functor);
2587 return;
2588 }
2589 RTC_DCHECK(call_.get());
2590 call_->SetBitrateAllocationStrategy(std::move(bitrate_allocation_strategy));
2591}
2592
henrika5f6bf242017-11-01 11:06:56 +01002593void PeerConnection::SetAudioPlayout(bool playout) {
2594 if (!worker_thread()->IsCurrent()) {
2595 worker_thread()->Invoke<void>(
2596 RTC_FROM_HERE,
2597 rtc::Bind(&PeerConnection::SetAudioPlayout, this, playout));
2598 return;
2599 }
2600 auto audio_state =
2601 factory_->channel_manager()->media_engine()->GetAudioState();
2602 audio_state->SetPlayout(playout);
2603}
2604
2605void PeerConnection::SetAudioRecording(bool recording) {
2606 if (!worker_thread()->IsCurrent()) {
2607 worker_thread()->Invoke<void>(
2608 RTC_FROM_HERE,
2609 rtc::Bind(&PeerConnection::SetAudioRecording, this, recording));
2610 return;
2611 }
2612 auto audio_state =
2613 factory_->channel_manager()->media_engine()->GetAudioState();
2614 audio_state->SetRecording(recording);
2615}
2616
Steve Anton8c0f7a72017-10-03 10:03:10 -07002617std::unique_ptr<rtc::SSLCertificate>
2618PeerConnection::GetRemoteAudioSSLCertificate() {
Steve Anton75737c02017-11-06 10:37:17 -08002619 if (!voice_channel()) {
Steve Anton8c0f7a72017-10-03 10:03:10 -07002620 return nullptr;
2621 }
Steve Anton75737c02017-11-06 10:37:17 -08002622 return GetRemoteSSLCertificate(voice_channel()->transport_name());
Steve Anton8c0f7a72017-10-03 10:03:10 -07002623}
2624
ivoc14d5dbe2016-07-04 07:06:55 -07002625bool PeerConnection::StartRtcEventLog(rtc::PlatformFile file,
2626 int64_t max_size_bytes) {
Elad Alon99c3fe52017-10-13 16:29:40 +02002627 // TODO(eladalon): It would be better to not allow negative values into PC.
2628 const size_t max_size = (max_size_bytes < 0)
2629 ? RtcEventLog::kUnlimitedOutput
2630 : rtc::saturated_cast<size_t>(max_size_bytes);
2631 return StartRtcEventLog(
Bjorn Tereliusde939432017-11-20 17:38:14 +01002632 rtc::MakeUnique<RtcEventLogOutputFile>(file, max_size),
2633 webrtc::RtcEventLog::kImmediateOutput);
Elad Alon99c3fe52017-10-13 16:29:40 +02002634}
2635
Bjorn Tereliusde939432017-11-20 17:38:14 +01002636bool PeerConnection::StartRtcEventLog(std::unique_ptr<RtcEventLogOutput> output,
2637 int64_t output_period_ms) {
Karl Wibergd6b48192017-10-16 23:01:06 +02002638 // TODO(eladalon): In C++14, this can be done with a lambda.
2639 struct Functor {
Bjorn Tereliusde939432017-11-20 17:38:14 +01002640 bool operator()() {
2641 return pc->StartRtcEventLog_w(std::move(output), output_period_ms);
2642 }
Karl Wibergd6b48192017-10-16 23:01:06 +02002643 PeerConnection* const pc;
2644 std::unique_ptr<RtcEventLogOutput> output;
Bjorn Tereliusde939432017-11-20 17:38:14 +01002645 const int64_t output_period_ms;
Elad Alon99c3fe52017-10-13 16:29:40 +02002646 };
Bjorn Tereliusde939432017-11-20 17:38:14 +01002647 return worker_thread()->Invoke<bool>(
2648 RTC_FROM_HERE, Functor{this, std::move(output), output_period_ms});
ivoc14d5dbe2016-07-04 07:06:55 -07002649}
2650
2651void PeerConnection::StopRtcEventLog() {
Steve Anton978b8762017-09-29 12:15:02 -07002652 worker_thread()->Invoke<void>(
ivoc14d5dbe2016-07-04 07:06:55 -07002653 RTC_FROM_HERE, rtc::Bind(&PeerConnection::StopRtcEventLog_w, this));
2654}
2655
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002656const SessionDescriptionInterface* PeerConnection::local_description() const {
Steve Anton75737c02017-11-06 10:37:17 -08002657 return pending_local_description_ ? pending_local_description_.get()
2658 : current_local_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002659}
2660
2661const SessionDescriptionInterface* PeerConnection::remote_description() const {
Steve Anton75737c02017-11-06 10:37:17 -08002662 return pending_remote_description_ ? pending_remote_description_.get()
2663 : current_remote_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002664}
2665
deadbeeffe4a8a42016-12-20 17:56:17 -08002666const SessionDescriptionInterface* PeerConnection::current_local_description()
2667 const {
Steve Anton75737c02017-11-06 10:37:17 -08002668 return current_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08002669}
2670
2671const SessionDescriptionInterface* PeerConnection::current_remote_description()
2672 const {
Steve Anton75737c02017-11-06 10:37:17 -08002673 return current_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08002674}
2675
2676const SessionDescriptionInterface* PeerConnection::pending_local_description()
2677 const {
Steve Anton75737c02017-11-06 10:37:17 -08002678 return pending_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08002679}
2680
2681const SessionDescriptionInterface* PeerConnection::pending_remote_description()
2682 const {
Steve Anton75737c02017-11-06 10:37:17 -08002683 return pending_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08002684}
2685
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002686void PeerConnection::Close() {
Peter Boström1a9d6152015-12-08 22:15:17 +01002687 TRACE_EVENT0("webrtc", "PeerConnection::Close");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002688 // Update stats here so that we have the most recent stats for tracks and
2689 // streams before the channels are closed.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00002690 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002691
Steve Anton75737c02017-11-06 10:37:17 -08002692 ChangeSignalingState(PeerConnectionInterface::kClosed);
Steve Anton3fe1b152017-12-12 10:20:08 -08002693
Steve Anton8af21862017-12-15 11:20:13 -08002694 for (auto transceiver : transceivers_) {
2695 transceiver->Stop();
2696 }
2697 DestroyAllChannels();
Steve Anton75737c02017-11-06 10:37:17 -08002698
deadbeef42a42632017-03-10 15:18:00 -08002699 network_thread()->Invoke<void>(
2700 RTC_FROM_HERE,
2701 rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
2702 port_allocator_.get()));
nisseeaabdf62017-05-05 02:23:02 -07002703
Steve Anton978b8762017-09-29 12:15:02 -07002704 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
eladalon248fd4f2017-09-06 05:18:15 -07002705 call_.reset();
2706 // The event log must outlive call (and any other object that uses it).
2707 event_log_.reset();
2708 });
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002709}
2710
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002711void PeerConnection::OnMessage(rtc::Message* msg) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002712 switch (msg->message_id) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002713 case MSG_SET_SESSIONDESCRIPTION_SUCCESS: {
2714 SetSessionDescriptionMsg* param =
2715 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
2716 param->observer->OnSuccess();
2717 delete param;
2718 break;
2719 }
2720 case MSG_SET_SESSIONDESCRIPTION_FAILED: {
2721 SetSessionDescriptionMsg* param =
2722 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
2723 param->observer->OnFailure(param->error);
2724 delete param;
2725 break;
2726 }
deadbeefab9b2d12015-10-14 11:33:11 -07002727 case MSG_CREATE_SESSIONDESCRIPTION_FAILED: {
2728 CreateSessionDescriptionMsg* param =
2729 static_cast<CreateSessionDescriptionMsg*>(msg->pdata);
2730 param->observer->OnFailure(param->error);
2731 delete param;
2732 break;
2733 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002734 case MSG_GETSTATS: {
2735 GetStatsMsg* param = static_cast<GetStatsMsg*>(msg->pdata);
nissee8abe3e2017-01-18 05:00:34 -08002736 StatsReports reports;
2737 stats_->GetStats(param->track, &reports);
2738 param->observer->OnComplete(reports);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002739 delete param;
2740 break;
2741 }
deadbeefbd292462015-12-14 18:15:29 -08002742 case MSG_FREE_DATACHANNELS: {
2743 sctp_data_channels_to_free_.clear();
2744 break;
2745 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002746 default:
nisseeb4ca4e2017-01-12 02:24:27 -08002747 RTC_NOTREACHED() << "Not implemented";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002748 break;
2749 }
2750}
2751
Steve Anton4171afb2017-11-20 10:20:22 -08002752void PeerConnection::CreateAudioReceiver(
2753 MediaStreamInterface* stream,
2754 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01002755 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
2756 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
zhihuang81c3a032016-11-17 12:06:24 -08002757 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
2758 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
deadbeefe814a0d2017-02-25 18:15:09 -08002759 signaling_thread(),
Steve Anton60776752018-01-10 11:51:34 -08002760 new AudioRtpReceiver(worker_thread(), remote_sender_info.sender_id,
2761 streams, remote_sender_info.first_ssrc,
2762 voice_media_channel()));
deadbeefe814a0d2017-02-25 18:15:09 -08002763 stream->AddTrack(
2764 static_cast<AudioTrackInterface*>(receiver->internal()->track().get()));
Steve Anton4171afb2017-11-20 10:20:22 -08002765 GetAudioTransceiver()->internal()->AddReceiver(receiver);
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01002766 observer_->OnAddTrack(receiver, std::move(streams));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002767}
2768
Steve Anton4171afb2017-11-20 10:20:22 -08002769void PeerConnection::CreateVideoReceiver(
2770 MediaStreamInterface* stream,
2771 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01002772 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
2773 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
zhihuang81c3a032016-11-17 12:06:24 -08002774 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
2775 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
Steve Anton4171afb2017-11-20 10:20:22 -08002776 signaling_thread(),
Steve Anton60776752018-01-10 11:51:34 -08002777 new VideoRtpReceiver(worker_thread(), remote_sender_info.sender_id,
2778 streams, remote_sender_info.first_ssrc,
2779 video_media_channel()));
deadbeefe814a0d2017-02-25 18:15:09 -08002780 stream->AddTrack(
2781 static_cast<VideoTrackInterface*>(receiver->internal()->track().get()));
Steve Anton4171afb2017-11-20 10:20:22 -08002782 GetVideoTransceiver()->internal()->AddReceiver(receiver);
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01002783 observer_->OnAddTrack(receiver, std::move(streams));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002784}
2785
deadbeef70ab1a12015-09-28 16:53:55 -07002786// TODO(deadbeef): Keep RtpReceivers around even if track goes away in remote
2787// description.
Henrik Boström933d8b02017-10-10 10:05:16 -07002788rtc::scoped_refptr<RtpReceiverInterface> PeerConnection::RemoveAndStopReceiver(
Steve Anton4171afb2017-11-20 10:20:22 -08002789 const RtpSenderInfo& remote_sender_info) {
2790 auto receiver = FindReceiverById(remote_sender_info.sender_id);
2791 if (!receiver) {
2792 RTC_LOG(LS_WARNING) << "RtpReceiver for track with id "
2793 << remote_sender_info.sender_id << " doesn't exist.";
Henrik Boström933d8b02017-10-10 10:05:16 -07002794 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07002795 }
Steve Anton4171afb2017-11-20 10:20:22 -08002796 if (receiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
2797 GetAudioTransceiver()->internal()->RemoveReceiver(receiver);
2798 } else {
2799 GetVideoTransceiver()->internal()->RemoveReceiver(receiver);
2800 }
Henrik Boström933d8b02017-10-10 10:05:16 -07002801 return receiver;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002802}
2803
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002804void PeerConnection::AddAudioTrack(AudioTrackInterface* track,
2805 MediaStreamInterface* stream) {
2806 RTC_DCHECK(!IsClosed());
2807 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08002808 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002809 // We already have a sender for this track, so just change the stream_id
2810 // so that it's correct in the next call to CreateOffer.
Steve Anton4171afb2017-11-20 10:20:22 -08002811 sender->internal()->set_stream_id(stream->label());
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002812 return;
2813 }
2814
2815 // Normal case; we've never seen this track before.
Steve Anton02ee47c2018-01-10 16:26:06 -08002816 auto new_sender =
2817 CreateSender(cricket::MEDIA_TYPE_AUDIO, track, {stream->label()});
2818 static_cast<AudioRtpSender*>(new_sender->internal())
2819 ->SetChannel(voice_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08002820 GetAudioTransceiver()->internal()->AddSender(new_sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002821 // If the sender has already been configured in SDP, we call SetSsrc,
2822 // which will connect the sender to the underlying transport. This can
2823 // occur if a local session description that contains the ID of the sender
2824 // is set before AddStream is called. It can also occur if the local
2825 // session description is not changed and RemoveStream is called, and
2826 // later AddStream is called again with the same stream.
Steve Anton4171afb2017-11-20 10:20:22 -08002827 const RtpSenderInfo* sender_info =
2828 FindSenderInfo(local_audio_sender_infos_, stream->label(), track->id());
2829 if (sender_info) {
2830 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002831 }
2832}
2833
2834// TODO(deadbeef): Don't destroy RtpSenders here; they should be kept around
2835// indefinitely, when we have unified plan SDP.
2836void PeerConnection::RemoveAudioTrack(AudioTrackInterface* track,
2837 MediaStreamInterface* stream) {
2838 RTC_DCHECK(!IsClosed());
2839 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08002840 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002841 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
2842 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002843 return;
2844 }
Steve Anton4171afb2017-11-20 10:20:22 -08002845 GetAudioTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002846}
2847
2848void PeerConnection::AddVideoTrack(VideoTrackInterface* track,
2849 MediaStreamInterface* stream) {
2850 RTC_DCHECK(!IsClosed());
2851 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08002852 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002853 // We already have a sender for this track, so just change the stream_id
2854 // so that it's correct in the next call to CreateOffer.
Steve Anton4171afb2017-11-20 10:20:22 -08002855 sender->internal()->set_stream_id(stream->label());
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002856 return;
2857 }
2858
2859 // Normal case; we've never seen this track before.
Steve Anton02ee47c2018-01-10 16:26:06 -08002860 auto new_sender =
2861 CreateSender(cricket::MEDIA_TYPE_VIDEO, track, {stream->label()});
2862 static_cast<VideoRtpSender*>(new_sender->internal())
2863 ->SetChannel(video_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08002864 GetVideoTransceiver()->internal()->AddSender(new_sender);
2865 const RtpSenderInfo* sender_info =
2866 FindSenderInfo(local_video_sender_infos_, stream->label(), track->id());
2867 if (sender_info) {
2868 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002869 }
2870}
2871
2872void PeerConnection::RemoveVideoTrack(VideoTrackInterface* track,
2873 MediaStreamInterface* stream) {
2874 RTC_DCHECK(!IsClosed());
2875 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08002876 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002877 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
2878 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002879 return;
2880 }
Steve Anton4171afb2017-11-20 10:20:22 -08002881 GetVideoTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002882}
2883
Steve Antonba818672017-11-06 10:21:57 -08002884void PeerConnection::SetIceConnectionState(IceConnectionState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07002885 RTC_DCHECK(signaling_thread()->IsCurrent());
Steve Antonba818672017-11-06 10:21:57 -08002886 if (ice_connection_state_ == new_state) {
2887 return;
2888 }
2889
deadbeefcbecd352015-09-23 11:50:27 -07002890 // After transitioning to "closed", ignore any additional states from
Steve Antonba818672017-11-06 10:21:57 -08002891 // TransportController (such as "disconnected").
deadbeefab9b2d12015-10-14 11:33:11 -07002892 if (IsClosed()) {
deadbeefcbecd352015-09-23 11:50:27 -07002893 return;
2894 }
Steve Antonba818672017-11-06 10:21:57 -08002895
Mirko Bonadei675513b2017-11-09 11:09:25 +01002896 RTC_LOG(LS_INFO) << "Changing IceConnectionState " << ice_connection_state_
2897 << " => " << new_state;
Steve Antonba818672017-11-06 10:21:57 -08002898 RTC_DCHECK(ice_connection_state_ !=
2899 PeerConnectionInterface::kIceConnectionClosed);
2900
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002901 ice_connection_state_ = new_state;
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00002902 observer_->OnIceConnectionChange(ice_connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002903}
2904
2905void PeerConnection::OnIceGatheringChange(
2906 PeerConnectionInterface::IceGatheringState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07002907 RTC_DCHECK(signaling_thread()->IsCurrent());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002908 if (IsClosed()) {
2909 return;
2910 }
2911 ice_gathering_state_ = new_state;
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00002912 observer_->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002913}
2914
jbauch81bf7b02017-03-25 08:31:12 -07002915void PeerConnection::OnIceCandidate(
2916 std::unique_ptr<IceCandidateInterface> candidate) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07002917 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07002918 if (IsClosed()) {
2919 return;
2920 }
jbauch81bf7b02017-03-25 08:31:12 -07002921 observer_->OnIceCandidate(candidate.get());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002922}
2923
Honghai Zhang7fb69db2016-03-14 11:59:18 -07002924void PeerConnection::OnIceCandidatesRemoved(
2925 const std::vector<cricket::Candidate>& candidates) {
2926 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07002927 if (IsClosed()) {
2928 return;
2929 }
Honghai Zhang7fb69db2016-03-14 11:59:18 -07002930 observer_->OnIceCandidatesRemoved(candidates);
2931}
2932
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002933void PeerConnection::ChangeSignalingState(
2934 PeerConnectionInterface::SignalingState signaling_state) {
Steve Antonba818672017-11-06 10:21:57 -08002935 RTC_DCHECK(signaling_thread()->IsCurrent());
2936 if (signaling_state_ == signaling_state) {
2937 return;
2938 }
Mirko Bonadei675513b2017-11-09 11:09:25 +01002939 RTC_LOG(LS_INFO) << "Session: " << session_id() << " Old state: "
2940 << GetSignalingStateString(signaling_state_)
2941 << " New state: "
2942 << GetSignalingStateString(signaling_state);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002943 signaling_state_ = signaling_state;
2944 if (signaling_state == kClosed) {
2945 ice_connection_state_ = kIceConnectionClosed;
2946 observer_->OnIceConnectionChange(ice_connection_state_);
2947 if (ice_gathering_state_ != kIceGatheringComplete) {
2948 ice_gathering_state_ = kIceGatheringComplete;
2949 observer_->OnIceGatheringChange(ice_gathering_state_);
2950 }
2951 }
2952 observer_->OnSignalingChange(signaling_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002953}
2954
deadbeefeb459812015-12-15 19:24:43 -08002955void PeerConnection::OnAudioTrackAdded(AudioTrackInterface* track,
2956 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07002957 if (IsClosed()) {
2958 return;
2959 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002960 AddAudioTrack(track, stream);
2961 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08002962}
2963
deadbeefeb459812015-12-15 19:24:43 -08002964void PeerConnection::OnAudioTrackRemoved(AudioTrackInterface* track,
2965 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07002966 if (IsClosed()) {
2967 return;
2968 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002969 RemoveAudioTrack(track, stream);
2970 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08002971}
2972
2973void PeerConnection::OnVideoTrackAdded(VideoTrackInterface* track,
2974 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07002975 if (IsClosed()) {
2976 return;
2977 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002978 AddVideoTrack(track, stream);
2979 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08002980}
2981
2982void PeerConnection::OnVideoTrackRemoved(VideoTrackInterface* track,
2983 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07002984 if (IsClosed()) {
2985 return;
2986 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002987 RemoveVideoTrack(track, stream);
2988 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08002989}
2990
Henrik Boström31638672017-11-23 17:48:32 +01002991void PeerConnection::PostSetSessionDescriptionSuccess(
2992 SetSessionDescriptionObserver* observer) {
2993 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
2994 signaling_thread()->Post(RTC_FROM_HERE, this,
2995 MSG_SET_SESSIONDESCRIPTION_SUCCESS, msg);
2996}
2997
deadbeefab9b2d12015-10-14 11:33:11 -07002998void PeerConnection::PostSetSessionDescriptionFailure(
2999 SetSessionDescriptionObserver* observer,
3000 const std::string& error) {
3001 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
3002 msg->error = error;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07003003 signaling_thread()->Post(RTC_FROM_HERE, this,
3004 MSG_SET_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07003005}
3006
3007void PeerConnection::PostCreateSessionDescriptionFailure(
3008 CreateSessionDescriptionObserver* observer,
3009 const std::string& error) {
3010 CreateSessionDescriptionMsg* msg = new CreateSessionDescriptionMsg(observer);
3011 msg->error = error;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07003012 signaling_thread()->Post(RTC_FROM_HERE, this,
3013 MSG_CREATE_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07003014}
3015
zhihuang1c378ed2017-08-17 14:10:50 -07003016void PeerConnection::GetOptionsForOffer(
Steve Antondcc3c022017-12-22 16:02:54 -08003017 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
deadbeefab9b2d12015-10-14 11:33:11 -07003018 cricket::MediaSessionOptions* session_options) {
Steve Antondcc3c022017-12-22 16:02:54 -08003019 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
zhihuang1c378ed2017-08-17 14:10:50 -07003020
Steve Antondcc3c022017-12-22 16:02:54 -08003021 if (IsUnifiedPlan()) {
3022 GetOptionsForUnifiedPlanOffer(offer_answer_options, session_options);
3023 } else {
3024 GetOptionsForPlanBOffer(offer_answer_options, session_options);
3025 }
3026
Steve Antonfa2260d2017-12-28 16:38:23 -08003027 // Intentionally unset the data channel type for RTP data channel with the
3028 // second condition. Otherwise the RTP data channels would be successfully
3029 // negotiated by default and the unit tests in WebRtcDataBrowserTest will fail
3030 // when building with chromium. We want to leave RTP data channels broken, so
3031 // people won't try to use them.
3032 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
3033 session_options->data_channel_type = data_channel_type();
3034 }
3035
Steve Antondcc3c022017-12-22 16:02:54 -08003036 // Apply ICE restart flag and renomination flag.
3037 for (auto& options : session_options->media_description_options) {
3038 options.transport_options.ice_restart = offer_answer_options.ice_restart;
3039 options.transport_options.enable_ice_renomination =
3040 configuration_.enable_ice_renomination;
3041 }
3042
3043 session_options->rtcp_cname = rtcp_cname_;
3044 session_options->crypto_options = factory_->options().crypto_options;
3045}
3046
3047void PeerConnection::GetOptionsForPlanBOffer(
3048 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
3049 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07003050 // Figure out transceiver directional preferences.
3051 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
3052 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
3053
3054 // By default, generate sendrecv/recvonly m= sections.
3055 bool recv_audio = true;
3056 bool recv_video = true;
3057
3058 // By default, only offer a new m= section if we have media to send with it.
3059 bool offer_new_audio_description = send_audio;
3060 bool offer_new_video_description = send_video;
3061 bool offer_new_data_description = HasDataChannels();
3062
3063 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-22 16:02:54 -08003064 if (offer_answer_options.offer_to_receive_audio !=
3065 RTCOfferAnswerOptions::kUndefined) {
3066 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003067 offer_new_audio_description =
Steve Antondcc3c022017-12-22 16:02:54 -08003068 offer_new_audio_description ||
3069 (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003070 }
Steve Antondcc3c022017-12-22 16:02:54 -08003071 if (offer_answer_options.offer_to_receive_video !=
3072 RTCOfferAnswerOptions::kUndefined) {
3073 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003074 offer_new_video_description =
Steve Antondcc3c022017-12-22 16:02:54 -08003075 offer_new_video_description ||
3076 (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003077 }
3078
3079 rtc::Optional<size_t> audio_index;
3080 rtc::Optional<size_t> video_index;
3081 rtc::Optional<size_t> data_index;
3082 // If a current description exists, generate m= sections in the same order,
3083 // using the first audio/video/data section that appears and rejecting
3084 // extraneous ones.
Steve Anton75737c02017-11-06 10:37:17 -08003085 if (local_description()) {
zhihuang1c378ed2017-08-17 14:10:50 -07003086 GenerateMediaDescriptionOptions(
Steve Anton75737c02017-11-06 10:37:17 -08003087 local_description(),
Steve Anton1d03a752017-11-27 14:30:09 -08003088 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
3089 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
3090 &audio_index, &video_index, &data_index, session_options);
deadbeefab9b2d12015-10-14 11:33:11 -07003091 }
3092
zhihuang1c378ed2017-08-17 14:10:50 -07003093 // Add audio/video/data m= sections to the end if needed.
3094 if (!audio_index && offer_new_audio_description) {
3095 session_options->media_description_options.push_back(
3096 cricket::MediaDescriptionOptions(
3097 cricket::MEDIA_TYPE_AUDIO, cricket::CN_AUDIO,
Steve Anton1d03a752017-11-27 14:30:09 -08003098 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
3099 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003100 audio_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07003101 }
zhihuang1c378ed2017-08-17 14:10:50 -07003102 if (!video_index && offer_new_video_description) {
3103 session_options->media_description_options.push_back(
3104 cricket::MediaDescriptionOptions(
3105 cricket::MEDIA_TYPE_VIDEO, cricket::CN_VIDEO,
Steve Anton1d03a752017-11-27 14:30:09 -08003106 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
3107 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003108 video_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07003109 }
zhihuang1c378ed2017-08-17 14:10:50 -07003110 if (!data_index && offer_new_data_description) {
3111 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08003112 GetMediaDescriptionOptionsForActiveData(cricket::CN_DATA));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003113 data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07003114 }
3115
3116 cricket::MediaDescriptionOptions* audio_media_description_options =
3117 !audio_index ? nullptr
3118 : &session_options->media_description_options[*audio_index];
3119 cricket::MediaDescriptionOptions* video_media_description_options =
3120 !video_index ? nullptr
3121 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 14:10:50 -07003122
Steve Anton4171afb2017-11-20 10:20:22 -08003123 AddRtpSenderOptions(GetSendersInternal(), audio_media_description_options,
zhihuang1c378ed2017-08-17 14:10:50 -07003124 video_media_description_options);
Steve Antondcc3c022017-12-22 16:02:54 -08003125}
3126
3127// Find a new MID that is not already in |used_mids|, then add it to |used_mids|
3128// and return a reference to it.
3129// Generated MIDs should be no more than 3 bytes long to take up less space in
3130// the RTP packet.
3131static const std::string& AllocateMid(std::set<std::string>* used_mids) {
3132 RTC_DCHECK(used_mids);
3133 // We're boring: just generate MIDs 0, 1, 2, ...
3134 size_t i = 0;
3135 std::set<std::string>::iterator it;
3136 bool inserted;
3137 do {
3138 std::string mid = rtc::ToString(i++);
3139 auto insert_result = used_mids->insert(mid);
3140 it = insert_result.first;
3141 inserted = insert_result.second;
3142 } while (!inserted);
3143 return *it;
3144}
3145
3146static cricket::MediaDescriptionOptions
3147GetMediaDescriptionOptionsForTransceiver(
3148 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3149 transceiver,
3150 const std::string& mid) {
3151 cricket::MediaDescriptionOptions media_description_options(
3152 transceiver->internal()->media_type(), mid, transceiver->direction(),
3153 transceiver->stopped());
3154 cricket::SenderOptions sender_options;
3155 sender_options.track_id = transceiver->sender()->id();
3156 sender_options.stream_ids = transceiver->sender()->stream_ids();
3157 // TODO(bugs.webrtc.org/7600): Set num_sim_layers to the number of encodings
3158 // set in the RTP parameters when the transceiver was added.
3159 sender_options.num_sim_layers = 1;
3160 media_description_options.sender_options.push_back(sender_options);
3161 return media_description_options;
3162}
3163
3164void PeerConnection::GetOptionsForUnifiedPlanOffer(
3165 const RTCOfferAnswerOptions& offer_answer_options,
3166 cricket::MediaSessionOptions* session_options) {
3167 // Rules for generating an offer are dictated by JSEP sections 5.2.1 (Initial
3168 // Offers) and 5.2.2 (Subsequent Offers).
3169 RTC_DCHECK_EQ(session_options->media_description_options.size(), 0);
3170 const ContentInfos& local_contents =
3171 (local_description() ? local_description()->description()->contents()
3172 : ContentInfos());
3173 const ContentInfos& remote_contents =
3174 (remote_description() ? remote_description()->description()->contents()
3175 : ContentInfos());
3176 // The mline indices that can be recycled. New transceivers should reuse these
3177 // slots first.
3178 std::queue<size_t> recycleable_mline_indices;
3179 // Track the MIDs used in previous offer/answer exchanges and the current
3180 // offer so that new, unique MIDs are generated.
3181 std::set<std::string> used_mids = seen_mids_;
3182 // First, go through each media section that exists in either the local or
3183 // remote description and generate a media section in this offer for the
3184 // associated transceiver. If a media section can be recycled, generate a
3185 // default, rejected media section here that can be later overwritten.
3186 for (size_t i = 0;
3187 i < std::max(local_contents.size(), remote_contents.size()); ++i) {
3188 // Either |local_content| or |remote_content| is non-null.
3189 const ContentInfo* local_content =
3190 (i < local_contents.size() ? &local_contents[i] : nullptr);
3191 const ContentInfo* remote_content =
3192 (i < remote_contents.size() ? &remote_contents[i] : nullptr);
3193 bool had_been_rejected = (local_content && local_content->rejected) ||
3194 (remote_content && remote_content->rejected);
3195 const std::string& mid =
3196 (local_content ? local_content->name : remote_content->name);
3197 cricket::MediaType media_type =
3198 (local_content ? local_content->media_description()->type()
3199 : remote_content->media_description()->type());
3200 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
3201 media_type == cricket::MEDIA_TYPE_VIDEO) {
3202 auto transceiver = GetAssociatedTransceiver(mid);
3203 RTC_CHECK(transceiver);
3204 // A media section is considered eligible for recycling if it is marked as
3205 // rejected in either the local or remote description.
3206 if (had_been_rejected) {
3207 session_options->media_description_options.push_back(
3208 cricket::MediaDescriptionOptions(
3209 transceiver->internal()->media_type(), mid,
3210 RtpTransceiverDirection::kInactive,
3211 /*stopped=*/true));
3212 recycleable_mline_indices.push(i);
3213 } else {
3214 session_options->media_description_options.push_back(
3215 GetMediaDescriptionOptionsForTransceiver(transceiver, mid));
3216 // CreateOffer shouldn't really cause any state changes in
3217 // PeerConnection, but we need a way to match new transceivers to new
3218 // media sections in SetLocalDescription and JSEP specifies this is done
3219 // by recording the index of the media section generated for the
3220 // transceiver in the offer.
3221 transceiver->internal()->set_mline_index(i);
3222 }
3223 } else {
3224 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antonfa2260d2017-12-28 16:38:23 -08003225 RTC_CHECK(GetDataMid());
3226 if (had_been_rejected || mid != *GetDataMid()) {
3227 session_options->media_description_options.push_back(
3228 GetMediaDescriptionOptionsForRejectedData(mid));
3229 } else {
3230 session_options->media_description_options.push_back(
3231 GetMediaDescriptionOptionsForActiveData(mid));
3232 }
Steve Antondcc3c022017-12-22 16:02:54 -08003233 }
3234 }
3235 // Next, look for transceivers that are newly added (that is, are not stopped
3236 // and not associated). Reuse media sections marked as recyclable first,
3237 // otherwise append to the end of the offer. New media sections should be
3238 // added in the order they were added to the PeerConnection.
3239 for (auto transceiver : transceivers_) {
3240 if (transceiver->mid() || transceiver->stopped()) {
3241 continue;
3242 }
3243 size_t mline_index;
3244 if (!recycleable_mline_indices.empty()) {
3245 mline_index = recycleable_mline_indices.front();
3246 recycleable_mline_indices.pop();
3247 session_options->media_description_options[mline_index] =
3248 GetMediaDescriptionOptionsForTransceiver(transceiver,
3249 AllocateMid(&used_mids));
3250 } else {
3251 mline_index = session_options->media_description_options.size();
3252 session_options->media_description_options.push_back(
3253 GetMediaDescriptionOptionsForTransceiver(transceiver,
3254 AllocateMid(&used_mids)));
3255 }
3256 // See comment above for why CreateOffer changes the transceiver's state.
3257 transceiver->internal()->set_mline_index(mline_index);
3258 }
Steve Antonfa2260d2017-12-28 16:38:23 -08003259 // Lastly, add a m-section if we have local data channels and an m section
3260 // does not already exist.
3261 if (!GetDataMid() && HasDataChannels()) {
3262 session_options->media_description_options.push_back(
3263 GetMediaDescriptionOptionsForActiveData(AllocateMid(&used_mids)));
3264 }
Steve Antondcc3c022017-12-22 16:02:54 -08003265}
3266
3267void PeerConnection::GetOptionsForAnswer(
3268 const RTCOfferAnswerOptions& offer_answer_options,
3269 cricket::MediaSessionOptions* session_options) {
3270 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
3271
3272 if (IsUnifiedPlan()) {
3273 GetOptionsForUnifiedPlanAnswer(offer_answer_options, session_options);
3274 } else {
3275 GetOptionsForPlanBAnswer(offer_answer_options, session_options);
3276 }
3277
Steve Antonfa2260d2017-12-28 16:38:23 -08003278 // Intentionally unset the data channel type for RTP data channel. Otherwise
3279 // the RTP data channels would be successfully negotiated by default and the
3280 // unit tests in WebRtcDataBrowserTest will fail when building with chromium.
3281 // We want to leave RTP data channels broken, so people won't try to use them.
3282 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
3283 session_options->data_channel_type = data_channel_type();
3284 }
3285
Steve Antondcc3c022017-12-22 16:02:54 -08003286 // Apply ICE renomination flag.
3287 for (auto& options : session_options->media_description_options) {
3288 options.transport_options.enable_ice_renomination =
3289 configuration_.enable_ice_renomination;
3290 }
zhihuang8f65cdf2016-05-06 18:40:30 -07003291
3292 session_options->rtcp_cname = rtcp_cname_;
jbauchcb560652016-08-04 05:20:32 -07003293 session_options->crypto_options = factory_->options().crypto_options;
deadbeefab9b2d12015-10-14 11:33:11 -07003294}
3295
Steve Antondcc3c022017-12-22 16:02:54 -08003296void PeerConnection::GetOptionsForPlanBAnswer(
3297 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07003298 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07003299 // Figure out transceiver directional preferences.
3300 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
3301 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
3302
3303 // By default, generate sendrecv/recvonly m= sections. The direction is also
3304 // restricted by the direction in the offer.
3305 bool recv_audio = true;
3306 bool recv_video = true;
3307
3308 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-22 16:02:54 -08003309 if (offer_answer_options.offer_to_receive_audio !=
3310 RTCOfferAnswerOptions::kUndefined) {
3311 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
deadbeef0ed85b22016-02-23 17:24:52 -08003312 }
Steve Antondcc3c022017-12-22 16:02:54 -08003313 if (offer_answer_options.offer_to_receive_video !=
3314 RTCOfferAnswerOptions::kUndefined) {
3315 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003316 }
3317
3318 rtc::Optional<size_t> audio_index;
3319 rtc::Optional<size_t> video_index;
3320 rtc::Optional<size_t> data_index;
Steve Anton75737c02017-11-06 10:37:17 -08003321 if (remote_description()) {
zhihuang141aacb2017-08-29 13:23:53 -07003322 // The pending remote description should be an offer.
Steve Antona3a92c22017-12-07 10:27:41 -08003323 RTC_DCHECK(remote_description()->GetType() == SdpType::kOffer);
zhihuang141aacb2017-08-29 13:23:53 -07003324 // Generate m= sections that match those in the offer.
3325 // Note that mediasession.cc will handle intersection our preferred
3326 // direction with the offered direction.
3327 GenerateMediaDescriptionOptions(
Steve Anton75737c02017-11-06 10:37:17 -08003328 remote_description(),
Steve Anton1d03a752017-11-27 14:30:09 -08003329 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
3330 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
3331 &audio_index, &video_index, &data_index, session_options);
zhihuang141aacb2017-08-29 13:23:53 -07003332 }
zhihuang1c378ed2017-08-17 14:10:50 -07003333
3334 cricket::MediaDescriptionOptions* audio_media_description_options =
3335 !audio_index ? nullptr
3336 : &session_options->media_description_options[*audio_index];
3337 cricket::MediaDescriptionOptions* video_media_description_options =
3338 !video_index ? nullptr
3339 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 14:10:50 -07003340
Steve Anton4171afb2017-11-20 10:20:22 -08003341 AddRtpSenderOptions(GetSendersInternal(), audio_media_description_options,
zhihuang1c378ed2017-08-17 14:10:50 -07003342 video_media_description_options);
Steve Antondcc3c022017-12-22 16:02:54 -08003343}
zhihuangaf388472016-11-02 16:49:48 -07003344
Steve Antondcc3c022017-12-22 16:02:54 -08003345void PeerConnection::GetOptionsForUnifiedPlanAnswer(
3346 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
3347 cricket::MediaSessionOptions* session_options) {
3348 // Rules for generating an answer are dictated by JSEP sections 5.3.1 (Initial
3349 // Answers) and 5.3.2 (Subsequent Answers).
3350 RTC_DCHECK(remote_description());
3351 RTC_DCHECK(remote_description()->GetType() == SdpType::kOffer);
3352 for (const ContentInfo& content :
3353 remote_description()->description()->contents()) {
3354 cricket::MediaType media_type = content.media_description()->type();
3355 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
3356 media_type == cricket::MEDIA_TYPE_VIDEO) {
3357 auto transceiver = GetAssociatedTransceiver(content.name);
3358 RTC_CHECK(transceiver);
3359 session_options->media_description_options.push_back(
3360 GetMediaDescriptionOptionsForTransceiver(transceiver, content.name));
3361 } else {
3362 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antonfa2260d2017-12-28 16:38:23 -08003363 RTC_CHECK(GetDataMid());
3364 // Always reject a data section if it has already been rejected.
3365 // Additionally, reject all data sections except for the first one.
3366 if (content.rejected || content.name != *GetDataMid()) {
3367 session_options->media_description_options.push_back(
3368 GetMediaDescriptionOptionsForRejectedData(content.name));
3369 } else {
3370 session_options->media_description_options.push_back(
3371 GetMediaDescriptionOptionsForActiveData(content.name));
3372 }
Steve Antondcc3c022017-12-22 16:02:54 -08003373 }
3374 }
htaa2a49d92016-03-04 02:51:39 -08003375}
3376
zhihuang1c378ed2017-08-17 14:10:50 -07003377void PeerConnection::GenerateMediaDescriptionOptions(
3378 const SessionDescriptionInterface* session_desc,
Steve Anton1d03a752017-11-27 14:30:09 -08003379 RtpTransceiverDirection audio_direction,
3380 RtpTransceiverDirection video_direction,
zhihuang1c378ed2017-08-17 14:10:50 -07003381 rtc::Optional<size_t>* audio_index,
3382 rtc::Optional<size_t>* video_index,
3383 rtc::Optional<size_t>* data_index,
htaa2a49d92016-03-04 02:51:39 -08003384 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07003385 for (const cricket::ContentInfo& content :
3386 session_desc->description()->contents()) {
3387 if (IsAudioContent(&content)) {
3388 // If we already have an audio m= section, reject this extra one.
3389 if (*audio_index) {
3390 session_options->media_description_options.push_back(
3391 cricket::MediaDescriptionOptions(
3392 cricket::MEDIA_TYPE_AUDIO, content.name,
Steve Anton1d03a752017-11-27 14:30:09 -08003393 RtpTransceiverDirection::kInactive, true));
zhihuang1c378ed2017-08-17 14:10:50 -07003394 } else {
3395 session_options->media_description_options.push_back(
3396 cricket::MediaDescriptionOptions(
3397 cricket::MEDIA_TYPE_AUDIO, content.name, audio_direction,
Steve Anton1d03a752017-11-27 14:30:09 -08003398 audio_direction == RtpTransceiverDirection::kInactive));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003399 *audio_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07003400 }
3401 } else if (IsVideoContent(&content)) {
3402 // If we already have an video m= section, reject this extra one.
3403 if (*video_index) {
3404 session_options->media_description_options.push_back(
3405 cricket::MediaDescriptionOptions(
3406 cricket::MEDIA_TYPE_VIDEO, content.name,
Steve Anton1d03a752017-11-27 14:30:09 -08003407 RtpTransceiverDirection::kInactive, true));
zhihuang1c378ed2017-08-17 14:10:50 -07003408 } else {
3409 session_options->media_description_options.push_back(
3410 cricket::MediaDescriptionOptions(
3411 cricket::MEDIA_TYPE_VIDEO, content.name, video_direction,
Steve Anton1d03a752017-11-27 14:30:09 -08003412 video_direction == RtpTransceiverDirection::kInactive));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003413 *video_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07003414 }
3415 } else {
3416 RTC_DCHECK(IsDataContent(&content));
3417 // If we already have an data m= section, reject this extra one.
3418 if (*data_index) {
3419 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08003420 GetMediaDescriptionOptionsForRejectedData(content.name));
zhihuang1c378ed2017-08-17 14:10:50 -07003421 } else {
3422 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08003423 GetMediaDescriptionOptionsForActiveData(content.name));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003424 *data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07003425 }
3426 }
htaa2a49d92016-03-04 02:51:39 -08003427 }
deadbeefab9b2d12015-10-14 11:33:11 -07003428}
3429
Steve Antonfa2260d2017-12-28 16:38:23 -08003430cricket::MediaDescriptionOptions
3431PeerConnection::GetMediaDescriptionOptionsForActiveData(
3432 const std::string& mid) const {
3433 // Direction for data sections is meaningless, but legacy endpoints might
3434 // expect sendrecv.
3435 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
3436 RtpTransceiverDirection::kSendRecv,
3437 /*stopped=*/false);
3438 AddRtpDataChannelOptions(rtp_data_channels_, &options);
3439 return options;
3440}
3441
3442cricket::MediaDescriptionOptions
3443PeerConnection::GetMediaDescriptionOptionsForRejectedData(
3444 const std::string& mid) const {
3445 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
3446 RtpTransceiverDirection::kInactive,
3447 /*stopped=*/true);
3448 AddRtpDataChannelOptions(rtp_data_channels_, &options);
3449 return options;
3450}
3451
3452rtc::Optional<std::string> PeerConnection::GetDataMid() const {
3453 switch (data_channel_type_) {
3454 case cricket::DCT_RTP:
3455 if (!rtp_data_channel_) {
3456 return rtc::nullopt;
3457 }
3458 return rtp_data_channel_->content_name();
3459 case cricket::DCT_SCTP:
3460 return sctp_content_name_;
3461 default:
3462 return rtc::nullopt;
3463 }
3464}
3465
Steve Anton4171afb2017-11-20 10:20:22 -08003466void PeerConnection::RemoveSenders(cricket::MediaType media_type) {
3467 UpdateLocalSenders(std::vector<cricket::StreamParams>(), media_type);
3468 UpdateRemoteSendersList(std::vector<cricket::StreamParams>(), false,
deadbeefbda7e0b2015-12-08 17:13:40 -08003469 media_type, nullptr);
deadbeeffaac4972015-11-12 15:33:07 -08003470}
3471
Steve Anton4171afb2017-11-20 10:20:22 -08003472void PeerConnection::UpdateRemoteSendersList(
deadbeefab9b2d12015-10-14 11:33:11 -07003473 const cricket::StreamParamsVec& streams,
Steve Anton4171afb2017-11-20 10:20:22 -08003474 bool default_sender_needed,
deadbeefab9b2d12015-10-14 11:33:11 -07003475 cricket::MediaType media_type,
3476 StreamCollection* new_streams) {
Steve Anton4171afb2017-11-20 10:20:22 -08003477 std::vector<RtpSenderInfo>* current_senders =
3478 GetRemoteSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07003479
Steve Anton4171afb2017-11-20 10:20:22 -08003480 // Find removed senders. I.e., senders where the sender id or ssrc don't match
deadbeeffac06552015-11-25 11:26:01 -08003481 // the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08003482 for (auto sender_it = current_senders->begin();
3483 sender_it != current_senders->end();
3484 /* incremented manually */) {
3485 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07003486 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08003487 cricket::GetStreamBySsrc(streams, info.first_ssrc);
3488 bool sender_exists = params && params->id == info.sender_id;
deadbeefbda7e0b2015-12-08 17:13:40 -08003489 // If this is a default track, and we still need it, don't remove it.
Steve Anton4171afb2017-11-20 10:20:22 -08003490 if ((info.stream_label == kDefaultStreamLabel && default_sender_needed) ||
3491 sender_exists) {
3492 ++sender_it;
deadbeefbda7e0b2015-12-08 17:13:40 -08003493 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08003494 OnRemoteSenderRemoved(info, media_type);
3495 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07003496 }
3497 }
3498
Steve Anton4171afb2017-11-20 10:20:22 -08003499 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07003500 for (const cricket::StreamParams& params : streams) {
3501 // The sync_label is the MediaStream label and the |stream.id| is the
Steve Anton4171afb2017-11-20 10:20:22 -08003502 // sender id.
deadbeefab9b2d12015-10-14 11:33:11 -07003503 const std::string& stream_label = params.sync_label;
Steve Anton4171afb2017-11-20 10:20:22 -08003504 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07003505 uint32_t ssrc = params.first_ssrc();
3506
3507 rtc::scoped_refptr<MediaStreamInterface> stream =
3508 remote_streams_->find(stream_label);
3509 if (!stream) {
3510 // This is a new MediaStream. Create a new remote MediaStream.
perkjd61bf802016-03-24 03:16:19 -07003511 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
3512 MediaStream::Create(stream_label));
deadbeefab9b2d12015-10-14 11:33:11 -07003513 remote_streams_->AddStream(stream);
3514 new_streams->AddStream(stream);
3515 }
3516
Steve Anton4171afb2017-11-20 10:20:22 -08003517 const RtpSenderInfo* sender_info =
3518 FindSenderInfo(*current_senders, stream_label, sender_id);
3519 if (!sender_info) {
3520 current_senders->push_back(RtpSenderInfo(stream_label, sender_id, ssrc));
3521 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07003522 }
3523 }
deadbeefbda7e0b2015-12-08 17:13:40 -08003524
Steve Anton4171afb2017-11-20 10:20:22 -08003525 // Add default sender if necessary.
3526 if (default_sender_needed) {
deadbeefbda7e0b2015-12-08 17:13:40 -08003527 rtc::scoped_refptr<MediaStreamInterface> default_stream =
3528 remote_streams_->find(kDefaultStreamLabel);
3529 if (!default_stream) {
3530 // Create the new default MediaStream.
perkjd61bf802016-03-24 03:16:19 -07003531 default_stream = MediaStreamProxy::Create(
3532 rtc::Thread::Current(), MediaStream::Create(kDefaultStreamLabel));
deadbeefbda7e0b2015-12-08 17:13:40 -08003533 remote_streams_->AddStream(default_stream);
3534 new_streams->AddStream(default_stream);
3535 }
Steve Anton4171afb2017-11-20 10:20:22 -08003536 std::string default_sender_id = (media_type == cricket::MEDIA_TYPE_AUDIO)
3537 ? kDefaultAudioSenderId
3538 : kDefaultVideoSenderId;
3539 const RtpSenderInfo* default_sender_info = FindSenderInfo(
3540 *current_senders, kDefaultStreamLabel, default_sender_id);
3541 if (!default_sender_info) {
3542 current_senders->push_back(
3543 RtpSenderInfo(kDefaultStreamLabel, default_sender_id, 0));
3544 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefbda7e0b2015-12-08 17:13:40 -08003545 }
3546 }
deadbeefab9b2d12015-10-14 11:33:11 -07003547}
3548
Steve Anton4171afb2017-11-20 10:20:22 -08003549void PeerConnection::OnRemoteSenderAdded(const RtpSenderInfo& sender_info,
3550 cricket::MediaType media_type) {
3551 MediaStreamInterface* stream =
3552 remote_streams_->find(sender_info.stream_label);
deadbeefab9b2d12015-10-14 11:33:11 -07003553
3554 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 10:20:22 -08003555 CreateAudioReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07003556 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 10:20:22 -08003557 CreateVideoReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07003558 } else {
nisseeb4ca4e2017-01-12 02:24:27 -08003559 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07003560 }
3561}
3562
Steve Anton4171afb2017-11-20 10:20:22 -08003563void PeerConnection::OnRemoteSenderRemoved(const RtpSenderInfo& sender_info,
3564 cricket::MediaType media_type) {
3565 MediaStreamInterface* stream =
3566 remote_streams_->find(sender_info.stream_label);
deadbeefab9b2d12015-10-14 11:33:11 -07003567
Henrik Boström933d8b02017-10-10 10:05:16 -07003568 rtc::scoped_refptr<RtpReceiverInterface> receiver;
deadbeefab9b2d12015-10-14 11:33:11 -07003569 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
perkjd61bf802016-03-24 03:16:19 -07003570 // When the MediaEngine audio channel is destroyed, the RemoteAudioSource
3571 // will be notified which will end the AudioRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08003572 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07003573 rtc::scoped_refptr<AudioTrackInterface> audio_track =
Steve Anton4171afb2017-11-20 10:20:22 -08003574 stream->FindAudioTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07003575 if (audio_track) {
deadbeefab9b2d12015-10-14 11:33:11 -07003576 stream->RemoveTrack(audio_track);
deadbeefab9b2d12015-10-14 11:33:11 -07003577 }
3578 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
perkjd61bf802016-03-24 03:16:19 -07003579 // Stopping or destroying a VideoRtpReceiver will end the
3580 // VideoRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08003581 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07003582 rtc::scoped_refptr<VideoTrackInterface> video_track =
Steve Anton4171afb2017-11-20 10:20:22 -08003583 stream->FindVideoTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07003584 if (video_track) {
perkjd61bf802016-03-24 03:16:19 -07003585 // There's no guarantee the track is still available, e.g. the track may
3586 // have been removed from the stream by an application.
deadbeefab9b2d12015-10-14 11:33:11 -07003587 stream->RemoveTrack(video_track);
deadbeefab9b2d12015-10-14 11:33:11 -07003588 }
3589 } else {
nisseede5da42017-01-12 05:15:36 -08003590 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07003591 }
Henrik Boström933d8b02017-10-10 10:05:16 -07003592 if (receiver) {
3593 observer_->OnRemoveTrack(receiver);
3594 }
deadbeefab9b2d12015-10-14 11:33:11 -07003595}
3596
3597void PeerConnection::UpdateEndedRemoteMediaStreams() {
3598 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams_to_remove;
3599 for (size_t i = 0; i < remote_streams_->count(); ++i) {
3600 MediaStreamInterface* stream = remote_streams_->at(i);
3601 if (stream->GetAudioTracks().empty() && stream->GetVideoTracks().empty()) {
3602 streams_to_remove.push_back(stream);
3603 }
3604 }
3605
Taylor Brandstetter98cde262016-05-31 13:02:21 -07003606 for (auto& stream : streams_to_remove) {
deadbeefab9b2d12015-10-14 11:33:11 -07003607 remote_streams_->RemoveStream(stream);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07003608 observer_->OnRemoveStream(std::move(stream));
deadbeefab9b2d12015-10-14 11:33:11 -07003609 }
3610}
3611
Steve Anton4171afb2017-11-20 10:20:22 -08003612void PeerConnection::UpdateLocalSenders(
deadbeefab9b2d12015-10-14 11:33:11 -07003613 const std::vector<cricket::StreamParams>& streams,
3614 cricket::MediaType media_type) {
Steve Anton4171afb2017-11-20 10:20:22 -08003615 std::vector<RtpSenderInfo>* current_senders = GetLocalSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07003616
3617 // Find removed tracks. I.e., tracks where the track id, stream label or ssrc
3618 // don't match the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08003619 for (auto sender_it = current_senders->begin();
3620 sender_it != current_senders->end();
3621 /* incremented manually */) {
3622 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07003623 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08003624 cricket::GetStreamBySsrc(streams, info.first_ssrc);
3625 if (!params || params->id != info.sender_id ||
deadbeefab9b2d12015-10-14 11:33:11 -07003626 params->sync_label != info.stream_label) {
Steve Anton4171afb2017-11-20 10:20:22 -08003627 OnLocalSenderRemoved(info, media_type);
3628 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07003629 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08003630 ++sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07003631 }
3632 }
3633
Steve Anton4171afb2017-11-20 10:20:22 -08003634 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07003635 for (const cricket::StreamParams& params : streams) {
3636 // The sync_label is the MediaStream label and the |stream.id| is the
Steve Anton4171afb2017-11-20 10:20:22 -08003637 // sender id.
deadbeefab9b2d12015-10-14 11:33:11 -07003638 const std::string& stream_label = params.sync_label;
Steve Anton4171afb2017-11-20 10:20:22 -08003639 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07003640 uint32_t ssrc = params.first_ssrc();
Steve Anton4171afb2017-11-20 10:20:22 -08003641 const RtpSenderInfo* sender_info =
3642 FindSenderInfo(*current_senders, stream_label, sender_id);
3643 if (!sender_info) {
3644 current_senders->push_back(RtpSenderInfo(stream_label, sender_id, ssrc));
3645 OnLocalSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07003646 }
3647 }
3648}
3649
Steve Anton4171afb2017-11-20 10:20:22 -08003650void PeerConnection::OnLocalSenderAdded(const RtpSenderInfo& sender_info,
3651 cricket::MediaType media_type) {
3652 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08003653 if (!sender) {
Steve Anton4171afb2017-11-20 10:20:22 -08003654 RTC_LOG(LS_WARNING) << "An unknown RtpSender with id "
3655 << sender_info.sender_id
Mirko Bonadei675513b2017-11-09 11:09:25 +01003656 << " has been configured in the local description.";
deadbeefab9b2d12015-10-14 11:33:11 -07003657 return;
3658 }
3659
deadbeeffac06552015-11-25 11:26:01 -08003660 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003661 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
3662 << " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08003663 return;
deadbeefab9b2d12015-10-14 11:33:11 -07003664 }
deadbeeffac06552015-11-25 11:26:01 -08003665
Steve Anton4171afb2017-11-20 10:20:22 -08003666 sender->internal()->set_stream_id(sender_info.stream_label);
3667 sender->internal()->SetSsrc(sender_info.first_ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07003668}
3669
Steve Anton4171afb2017-11-20 10:20:22 -08003670void PeerConnection::OnLocalSenderRemoved(const RtpSenderInfo& sender_info,
3671 cricket::MediaType media_type) {
3672 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08003673 if (!sender) {
3674 // This is the normal case. I.e., RemoveStream has been called and the
deadbeefab9b2d12015-10-14 11:33:11 -07003675 // SessionDescriptions has been renegotiated.
3676 return;
3677 }
deadbeeffac06552015-11-25 11:26:01 -08003678
3679 // A sender has been removed from the SessionDescription but it's still
3680 // associated with the PeerConnection. This only occurs if the SDP doesn't
3681 // match with the calls to CreateSender, AddStream and RemoveStream.
3682 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003683 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
3684 << " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08003685 return;
deadbeefab9b2d12015-10-14 11:33:11 -07003686 }
deadbeeffac06552015-11-25 11:26:01 -08003687
Steve Anton4171afb2017-11-20 10:20:22 -08003688 sender->internal()->SetSsrc(0);
deadbeefab9b2d12015-10-14 11:33:11 -07003689}
3690
3691void PeerConnection::UpdateLocalRtpDataChannels(
3692 const cricket::StreamParamsVec& streams) {
3693 std::vector<std::string> existing_channels;
3694
3695 // Find new and active data channels.
3696 for (const cricket::StreamParams& params : streams) {
3697 // |it->sync_label| is actually the data channel label. The reason is that
3698 // we use the same naming of data channels as we do for
3699 // MediaStreams and Tracks.
3700 // For MediaStreams, the sync_label is the MediaStream label and the
3701 // track label is the same as |streamid|.
3702 const std::string& channel_label = params.sync_label;
3703 auto data_channel_it = rtp_data_channels_.find(channel_label);
nisse7ce109a2017-01-31 00:57:56 -08003704 if (data_channel_it == rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003705 RTC_LOG(LS_ERROR) << "channel label not found";
deadbeefab9b2d12015-10-14 11:33:11 -07003706 continue;
3707 }
3708 // Set the SSRC the data channel should use for sending.
3709 data_channel_it->second->SetSendSsrc(params.first_ssrc());
3710 existing_channels.push_back(data_channel_it->first);
3711 }
3712
3713 UpdateClosingRtpDataChannels(existing_channels, true);
3714}
3715
3716void PeerConnection::UpdateRemoteRtpDataChannels(
3717 const cricket::StreamParamsVec& streams) {
3718 std::vector<std::string> existing_channels;
3719
3720 // Find new and active data channels.
3721 for (const cricket::StreamParams& params : streams) {
3722 // The data channel label is either the mslabel or the SSRC if the mslabel
3723 // does not exist. Ex a=ssrc:444330170 mslabel:test1.
3724 std::string label = params.sync_label.empty()
3725 ? rtc::ToString(params.first_ssrc())
3726 : params.sync_label;
3727 auto data_channel_it = rtp_data_channels_.find(label);
3728 if (data_channel_it == rtp_data_channels_.end()) {
3729 // This is a new data channel.
3730 CreateRemoteRtpDataChannel(label, params.first_ssrc());
3731 } else {
3732 data_channel_it->second->SetReceiveSsrc(params.first_ssrc());
3733 }
3734 existing_channels.push_back(label);
3735 }
3736
3737 UpdateClosingRtpDataChannels(existing_channels, false);
3738}
3739
3740void PeerConnection::UpdateClosingRtpDataChannels(
3741 const std::vector<std::string>& active_channels,
3742 bool is_local_update) {
3743 auto it = rtp_data_channels_.begin();
3744 while (it != rtp_data_channels_.end()) {
3745 DataChannel* data_channel = it->second;
3746 if (std::find(active_channels.begin(), active_channels.end(),
3747 data_channel->label()) != active_channels.end()) {
3748 ++it;
3749 continue;
3750 }
3751
3752 if (is_local_update) {
3753 data_channel->SetSendSsrc(0);
3754 } else {
3755 data_channel->RemotePeerRequestClose();
3756 }
3757
3758 if (data_channel->state() == DataChannel::kClosed) {
3759 rtp_data_channels_.erase(it);
3760 it = rtp_data_channels_.begin();
3761 } else {
3762 ++it;
3763 }
3764 }
3765}
3766
3767void PeerConnection::CreateRemoteRtpDataChannel(const std::string& label,
3768 uint32_t remote_ssrc) {
3769 rtc::scoped_refptr<DataChannel> channel(
3770 InternalCreateDataChannel(label, nullptr));
3771 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003772 RTC_LOG(LS_WARNING) << "Remote peer requested a DataChannel but"
3773 << "CreateDataChannel failed.";
deadbeefab9b2d12015-10-14 11:33:11 -07003774 return;
3775 }
3776 channel->SetReceiveSsrc(remote_ssrc);
deadbeefa601f5c2016-06-06 14:27:39 -07003777 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
3778 DataChannelProxy::Create(signaling_thread(), channel);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07003779 observer_->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07003780}
3781
3782rtc::scoped_refptr<DataChannel> PeerConnection::InternalCreateDataChannel(
3783 const std::string& label,
3784 const InternalDataChannelInit* config) {
3785 if (IsClosed()) {
3786 return nullptr;
3787 }
Steve Anton75737c02017-11-06 10:37:17 -08003788 if (data_channel_type() == cricket::DCT_NONE) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003789 RTC_LOG(LS_ERROR)
deadbeefab9b2d12015-10-14 11:33:11 -07003790 << "InternalCreateDataChannel: Data is not supported in this call.";
3791 return nullptr;
3792 }
3793 InternalDataChannelInit new_config =
3794 config ? (*config) : InternalDataChannelInit();
Steve Anton75737c02017-11-06 10:37:17 -08003795 if (data_channel_type() == cricket::DCT_SCTP) {
deadbeefab9b2d12015-10-14 11:33:11 -07003796 if (new_config.id < 0) {
3797 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08003798 if ((GetSctpSslRole(&role)) &&
deadbeefab9b2d12015-10-14 11:33:11 -07003799 !sid_allocator_.AllocateSid(role, &new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003800 RTC_LOG(LS_ERROR)
3801 << "No id can be allocated for the SCTP data channel.";
deadbeefab9b2d12015-10-14 11:33:11 -07003802 return nullptr;
3803 }
3804 } else if (!sid_allocator_.ReserveSid(new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003805 RTC_LOG(LS_ERROR) << "Failed to create a SCTP data channel "
3806 << "because the id is already in use or out of range.";
deadbeefab9b2d12015-10-14 11:33:11 -07003807 return nullptr;
3808 }
3809 }
3810
Steve Anton75737c02017-11-06 10:37:17 -08003811 rtc::scoped_refptr<DataChannel> channel(
3812 DataChannel::Create(this, data_channel_type(), label, new_config));
deadbeefab9b2d12015-10-14 11:33:11 -07003813 if (!channel) {
3814 sid_allocator_.ReleaseSid(new_config.id);
3815 return nullptr;
3816 }
3817
3818 if (channel->data_channel_type() == cricket::DCT_RTP) {
3819 if (rtp_data_channels_.find(channel->label()) != rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003820 RTC_LOG(LS_ERROR) << "DataChannel with label " << channel->label()
3821 << " already exists.";
deadbeefab9b2d12015-10-14 11:33:11 -07003822 return nullptr;
3823 }
3824 rtp_data_channels_[channel->label()] = channel;
3825 } else {
3826 RTC_DCHECK(channel->data_channel_type() == cricket::DCT_SCTP);
3827 sctp_data_channels_.push_back(channel);
3828 channel->SignalClosed.connect(this,
3829 &PeerConnection::OnSctpDataChannelClosed);
3830 }
3831
hbos82ebe022016-11-14 01:41:09 -08003832 SignalDataChannelCreated(channel.get());
deadbeefab9b2d12015-10-14 11:33:11 -07003833 return channel;
3834}
3835
3836bool PeerConnection::HasDataChannels() const {
3837 return !rtp_data_channels_.empty() || !sctp_data_channels_.empty();
3838}
3839
3840void PeerConnection::AllocateSctpSids(rtc::SSLRole role) {
3841 for (const auto& channel : sctp_data_channels_) {
3842 if (channel->id() < 0) {
3843 int sid;
3844 if (!sid_allocator_.AllocateSid(role, &sid)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003845 RTC_LOG(LS_ERROR) << "Failed to allocate SCTP sid.";
deadbeefab9b2d12015-10-14 11:33:11 -07003846 continue;
3847 }
3848 channel->SetSctpSid(sid);
3849 }
3850 }
3851}
3852
3853void PeerConnection::OnSctpDataChannelClosed(DataChannel* channel) {
deadbeefbd292462015-12-14 18:15:29 -08003854 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeefab9b2d12015-10-14 11:33:11 -07003855 for (auto it = sctp_data_channels_.begin(); it != sctp_data_channels_.end();
3856 ++it) {
3857 if (it->get() == channel) {
3858 if (channel->id() >= 0) {
3859 sid_allocator_.ReleaseSid(channel->id());
3860 }
deadbeefbd292462015-12-14 18:15:29 -08003861 // Since this method is triggered by a signal from the DataChannel,
3862 // we can't free it directly here; we need to free it asynchronously.
3863 sctp_data_channels_to_free_.push_back(*it);
deadbeefab9b2d12015-10-14 11:33:11 -07003864 sctp_data_channels_.erase(it);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07003865 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_FREE_DATACHANNELS,
3866 nullptr);
deadbeefab9b2d12015-10-14 11:33:11 -07003867 return;
3868 }
3869 }
3870}
3871
deadbeefab9b2d12015-10-14 11:33:11 -07003872void PeerConnection::OnDataChannelDestroyed() {
3873 // Use a temporary copy of the RTP/SCTP DataChannel list because the
3874 // DataChannel may callback to us and try to modify the list.
3875 std::map<std::string, rtc::scoped_refptr<DataChannel>> temp_rtp_dcs;
3876 temp_rtp_dcs.swap(rtp_data_channels_);
3877 for (const auto& kv : temp_rtp_dcs) {
3878 kv.second->OnTransportChannelDestroyed();
3879 }
3880
3881 std::vector<rtc::scoped_refptr<DataChannel>> temp_sctp_dcs;
3882 temp_sctp_dcs.swap(sctp_data_channels_);
3883 for (const auto& channel : temp_sctp_dcs) {
3884 channel->OnTransportChannelDestroyed();
3885 }
3886}
3887
3888void PeerConnection::OnDataChannelOpenMessage(
3889 const std::string& label,
3890 const InternalDataChannelInit& config) {
3891 rtc::scoped_refptr<DataChannel> channel(
3892 InternalCreateDataChannel(label, &config));
3893 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003894 RTC_LOG(LS_ERROR) << "Failed to create DataChannel from the OPEN message.";
deadbeefab9b2d12015-10-14 11:33:11 -07003895 return;
3896 }
3897
deadbeefa601f5c2016-06-06 14:27:39 -07003898 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
3899 DataChannelProxy::Create(signaling_thread(), channel);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07003900 observer_->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07003901}
3902
Steve Anton4171afb2017-11-20 10:20:22 -08003903rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3904PeerConnection::GetAudioTransceiver() const {
3905 // This method only works with Plan B SDP, where there is a single
3906 // audio/video transceiver.
3907 RTC_DCHECK(!IsUnifiedPlan());
3908 for (auto transceiver : transceivers_) {
3909 if (transceiver->internal()->media_type() == cricket::MEDIA_TYPE_AUDIO) {
3910 return transceiver;
3911 }
3912 }
3913 RTC_NOTREACHED();
3914 return nullptr;
3915}
3916
3917rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3918PeerConnection::GetVideoTransceiver() const {
3919 // This method only works with Plan B SDP, where there is a single
3920 // audio/video transceiver.
3921 RTC_DCHECK(!IsUnifiedPlan());
3922 for (auto transceiver : transceivers_) {
3923 if (transceiver->internal()->media_type() == cricket::MEDIA_TYPE_VIDEO) {
3924 return transceiver;
3925 }
3926 }
3927 RTC_NOTREACHED();
3928 return nullptr;
3929}
3930
3931// TODO(bugs.webrtc.org/7600): Remove this when multiple transceivers with
3932// individual transceiver directions are supported.
zhihuang1c378ed2017-08-17 14:10:50 -07003933bool PeerConnection::HasRtpSender(cricket::MediaType type) const {
Steve Anton4171afb2017-11-20 10:20:22 -08003934 switch (type) {
3935 case cricket::MEDIA_TYPE_AUDIO:
3936 return !GetAudioTransceiver()->internal()->senders().empty();
3937 case cricket::MEDIA_TYPE_VIDEO:
3938 return !GetVideoTransceiver()->internal()->senders().empty();
3939 case cricket::MEDIA_TYPE_DATA:
3940 return false;
3941 }
3942 RTC_NOTREACHED();
3943 return false;
zhihuang1c378ed2017-08-17 14:10:50 -07003944}
3945
Steve Anton4171afb2017-11-20 10:20:22 -08003946rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
3947PeerConnection::FindSenderForTrack(MediaStreamTrackInterface* track) const {
3948 for (auto transceiver : transceivers_) {
3949 for (auto sender : transceiver->internal()->senders()) {
3950 if (sender->track() == track) {
3951 return sender;
3952 }
3953 }
3954 }
3955 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08003956}
3957
Steve Anton4171afb2017-11-20 10:20:22 -08003958rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
3959PeerConnection::FindSenderById(const std::string& sender_id) const {
3960 for (auto transceiver : transceivers_) {
3961 for (auto sender : transceiver->internal()->senders()) {
3962 if (sender->id() == sender_id) {
3963 return sender;
3964 }
3965 }
3966 }
3967 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07003968}
3969
Steve Anton4171afb2017-11-20 10:20:22 -08003970rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
3971PeerConnection::FindReceiverById(const std::string& receiver_id) const {
3972 for (auto transceiver : transceivers_) {
3973 for (auto receiver : transceiver->internal()->receivers()) {
3974 if (receiver->id() == receiver_id) {
3975 return receiver;
3976 }
3977 }
3978 }
3979 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07003980}
3981
Steve Anton4171afb2017-11-20 10:20:22 -08003982std::vector<PeerConnection::RtpSenderInfo>*
3983PeerConnection::GetRemoteSenderInfos(cricket::MediaType media_type) {
3984 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
3985 media_type == cricket::MEDIA_TYPE_VIDEO);
3986 return (media_type == cricket::MEDIA_TYPE_AUDIO)
3987 ? &remote_audio_sender_infos_
3988 : &remote_video_sender_infos_;
3989}
3990
3991std::vector<PeerConnection::RtpSenderInfo>* PeerConnection::GetLocalSenderInfos(
deadbeefab9b2d12015-10-14 11:33:11 -07003992 cricket::MediaType media_type) {
3993 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
3994 media_type == cricket::MEDIA_TYPE_VIDEO);
Steve Anton4171afb2017-11-20 10:20:22 -08003995 return (media_type == cricket::MEDIA_TYPE_AUDIO) ? &local_audio_sender_infos_
3996 : &local_video_sender_infos_;
deadbeefab9b2d12015-10-14 11:33:11 -07003997}
3998
Steve Anton4171afb2017-11-20 10:20:22 -08003999const PeerConnection::RtpSenderInfo* PeerConnection::FindSenderInfo(
4000 const std::vector<PeerConnection::RtpSenderInfo>& infos,
deadbeefab9b2d12015-10-14 11:33:11 -07004001 const std::string& stream_label,
Steve Anton4171afb2017-11-20 10:20:22 -08004002 const std::string sender_id) const {
4003 for (const RtpSenderInfo& sender_info : infos) {
4004 if (sender_info.stream_label == stream_label &&
4005 sender_info.sender_id == sender_id) {
4006 return &sender_info;
deadbeefab9b2d12015-10-14 11:33:11 -07004007 }
4008 }
4009 return nullptr;
4010}
4011
4012DataChannel* PeerConnection::FindDataChannelBySid(int sid) const {
4013 for (const auto& channel : sctp_data_channels_) {
4014 if (channel->id() == sid) {
4015 return channel;
4016 }
4017 }
4018 return nullptr;
4019}
4020
deadbeef91dd5672016-05-18 16:55:30 -07004021bool PeerConnection::InitializePortAllocator_n(
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004022 const RTCConfiguration& configuration) {
4023 cricket::ServerAddresses stun_servers;
4024 std::vector<cricket::RelayServerConfig> turn_servers;
deadbeef293e9262017-01-11 12:28:30 -08004025 if (ParseIceServers(configuration.servers, &stun_servers, &turn_servers) !=
4026 RTCErrorType::NONE) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004027 return false;
4028 }
4029
Taylor Brandstetterf8e65772016-06-27 17:20:15 -07004030 port_allocator_->Initialize();
4031
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004032 // To handle both internal and externally created port allocator, we will
4033 // enable BUNDLE here.
4034 int portallocator_flags = port_allocator_->flags();
4035 portallocator_flags |= cricket::PORTALLOCATOR_ENABLE_SHARED_SOCKET |
zhihuangb09b3f92017-03-07 14:40:51 -08004036 cricket::PORTALLOCATOR_ENABLE_IPV6 |
4037 cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI;
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004038 // If the disable-IPv6 flag was specified, we'll not override it
4039 // by experiment.
4040 if (configuration.disable_ipv6) {
4041 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
sprangc1b57a12017-02-28 08:50:47 -08004042 } else if (webrtc::field_trial::FindFullName("WebRTC-IPv6Default")
4043 .find("Disabled") == 0) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004044 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
4045 }
4046
zhihuangb09b3f92017-03-07 14:40:51 -08004047 if (configuration.disable_ipv6_on_wifi) {
4048 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI);
Mirko Bonadei675513b2017-11-09 11:09:25 +01004049 RTC_LOG(LS_INFO) << "IPv6 candidates on Wi-Fi are disabled.";
zhihuangb09b3f92017-03-07 14:40:51 -08004050 }
4051
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004052 if (configuration.tcp_candidate_policy == kTcpCandidatePolicyDisabled) {
4053 portallocator_flags |= cricket::PORTALLOCATOR_DISABLE_TCP;
Mirko Bonadei675513b2017-11-09 11:09:25 +01004054 RTC_LOG(LS_INFO) << "TCP candidates are disabled.";
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004055 }
4056
honghaiz60347052016-05-31 18:29:12 -07004057 if (configuration.candidate_network_policy ==
4058 kCandidateNetworkPolicyLowCost) {
4059 portallocator_flags |= cricket::PORTALLOCATOR_DISABLE_COSTLY_NETWORKS;
Mirko Bonadei675513b2017-11-09 11:09:25 +01004060 RTC_LOG(LS_INFO) << "Do not gather candidates on high-cost networks";
honghaiz60347052016-05-31 18:29:12 -07004061 }
4062
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004063 port_allocator_->set_flags(portallocator_flags);
4064 // No step delay is used while allocating ports.
4065 port_allocator_->set_step_delay(cricket::kMinimumStepDelay);
4066 port_allocator_->set_candidate_filter(
4067 ConvertIceTransportTypeToCandidateFilter(configuration.type));
deadbeefd21eab32017-07-26 16:50:11 -07004068 port_allocator_->set_max_ipv6_networks(configuration.max_ipv6_networks);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004069
4070 // Call this last since it may create pooled allocator sessions using the
4071 // properties set above.
4072 port_allocator_->SetConfiguration(stun_servers, turn_servers,
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -07004073 configuration.ice_candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02004074 configuration.prune_turn_ports,
4075 configuration.turn_customizer);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004076 return true;
4077}
4078
deadbeef91dd5672016-05-18 16:55:30 -07004079bool PeerConnection::ReconfigurePortAllocator_n(
deadbeef293e9262017-01-11 12:28:30 -08004080 const cricket::ServerAddresses& stun_servers,
4081 const std::vector<cricket::RelayServerConfig>& turn_servers,
4082 IceTransportsType type,
4083 int candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02004084 bool prune_turn_ports,
4085 webrtc::TurnCustomizer* turn_customizer) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004086 port_allocator_->set_candidate_filter(
deadbeef293e9262017-01-11 12:28:30 -08004087 ConvertIceTransportTypeToCandidateFilter(type));
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004088 // Call this last since it may create pooled allocator sessions using the
4089 // candidate filter set above.
deadbeef6de92f92016-12-12 18:49:32 -08004090 return port_allocator_->SetConfiguration(
Jonas Orelandbdcee282017-10-10 14:01:40 +02004091 stun_servers, turn_servers, candidate_pool_size, prune_turn_ports,
4092 turn_customizer);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004093}
4094
Steve Antonba818672017-11-06 10:21:57 -08004095cricket::ChannelManager* PeerConnection::channel_manager() const {
4096 return factory_->channel_manager();
4097}
4098
4099MetricsObserverInterface* PeerConnection::metrics_observer() const {
4100 return uma_observer_;
4101}
4102
Elad Alon99c3fe52017-10-13 16:29:40 +02004103bool PeerConnection::StartRtcEventLog_w(
Bjorn Tereliusde939432017-11-20 17:38:14 +01004104 std::unique_ptr<RtcEventLogOutput> output,
4105 int64_t output_period_ms) {
zhihuang77985012017-02-07 15:45:16 -08004106 if (!event_log_) {
4107 return false;
4108 }
Bjorn Tereliusde939432017-11-20 17:38:14 +01004109 return event_log_->StartLogging(std::move(output), output_period_ms);
ivoc14d5dbe2016-07-04 07:06:55 -07004110}
4111
4112void PeerConnection::StopRtcEventLog_w() {
zhihuang77985012017-02-07 15:45:16 -08004113 if (event_log_) {
4114 event_log_->StopLogging();
4115 }
ivoc14d5dbe2016-07-04 07:06:55 -07004116}
nisseeaabdf62017-05-05 02:23:02 -07004117
Steve Anton75737c02017-11-06 10:37:17 -08004118cricket::BaseChannel* PeerConnection::GetChannel(
4119 const std::string& content_name) {
Steve Antondcc3c022017-12-22 16:02:54 -08004120 for (auto transceiver : transceivers_) {
4121 cricket::BaseChannel* channel = transceiver->internal()->channel();
4122 if (channel && channel->content_name() == content_name) {
4123 return channel;
4124 }
Steve Anton75737c02017-11-06 10:37:17 -08004125 }
4126 if (rtp_data_channel() &&
4127 rtp_data_channel()->content_name() == content_name) {
4128 return rtp_data_channel();
4129 }
4130 return nullptr;
4131}
4132
4133bool PeerConnection::GetSctpSslRole(rtc::SSLRole* role) {
4134 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004135 RTC_LOG(LS_INFO)
4136 << "Local and Remote descriptions must be applied to get the "
4137 << "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08004138 return false;
4139 }
4140 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004141 RTC_LOG(LS_INFO) << "Non-rejected SCTP m= section is needed to get the "
4142 << "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08004143 return false;
4144 }
4145
4146 return transport_controller_->GetSslRole(*sctp_transport_name_, role);
4147}
4148
4149bool PeerConnection::GetSslRole(const std::string& content_name,
4150 rtc::SSLRole* role) {
4151 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004152 RTC_LOG(LS_INFO)
4153 << "Local and Remote descriptions must be applied to get the "
4154 << "SSL Role of the session.";
Steve Anton75737c02017-11-06 10:37:17 -08004155 return false;
4156 }
4157
4158 return transport_controller_->GetSslRole(GetTransportName(content_name),
4159 role);
4160}
4161
Steve Anton75737c02017-11-06 10:37:17 -08004162// TODO(steveanton): Eventually it'd be nice to store the channels as a single
4163// vector of BaseChannel pointers instead of separate voice and video channel
4164// vectors. At that point, this will become a simple getter.
4165std::vector<cricket::BaseChannel*> PeerConnection::Channels() const {
4166 std::vector<cricket::BaseChannel*> channels;
Steve Anton4171afb2017-11-20 10:20:22 -08004167 if (voice_channel()) {
4168 channels.push_back(voice_channel());
4169 }
4170 if (video_channel()) {
4171 channels.push_back(video_channel());
4172 }
Steve Anton75737c02017-11-06 10:37:17 -08004173 if (rtp_data_channel_) {
4174 channels.push_back(rtp_data_channel_);
4175 }
4176 return channels;
4177}
4178
Steve Antonf8470812017-12-04 10:46:21 -08004179void PeerConnection::SetSessionError(SessionError error,
4180 const std::string& error_desc) {
4181 RTC_DCHECK_RUN_ON(signaling_thread());
4182 if (error != session_error_) {
4183 session_error_ = error;
4184 session_error_desc_ = error_desc;
Steve Anton75737c02017-11-06 10:37:17 -08004185 }
4186}
4187
Steve Anton3828c062017-12-06 10:34:51 -08004188RTCError PeerConnection::UpdateSessionState(SdpType type,
Steve Anton8a006912017-12-04 15:25:56 -08004189 cricket::ContentSource source) {
4190 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08004191
4192 // If there's already a pending error then no state transition should happen.
4193 // But all call-sites should be verifying this before calling us!
Steve Antonf8470812017-12-04 10:46:21 -08004194 RTC_DCHECK(session_error() == SessionError::kNone);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004195
4196 // If this is an answer then we know whether to BUNDLE or not. If both the
4197 // local and remote side have agreed to BUNDLE, go ahead and enable it.
Steve Anton3828c062017-12-06 10:34:51 -08004198 if (type == SdpType::kAnswer) {
Steve Anton75737c02017-11-06 10:37:17 -08004199 const cricket::ContentGroup* local_bundle =
4200 local_description()->description()->GetGroupByName(
4201 cricket::GROUP_TYPE_BUNDLE);
4202 const cricket::ContentGroup* remote_bundle =
4203 remote_description()->description()->GetGroupByName(
4204 cricket::GROUP_TYPE_BUNDLE);
4205 if (local_bundle && remote_bundle) {
4206 // The answerer decides the transport to bundle on.
4207 const cricket::ContentGroup* answer_bundle =
4208 (source == cricket::CS_LOCAL ? local_bundle : remote_bundle);
4209 if (!EnableBundle(*answer_bundle)) {
Steve Anton8a006912017-12-04 15:25:56 -08004210 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
4211 kEnableBundleFailed);
Steve Anton75737c02017-11-06 10:37:17 -08004212 }
4213 }
Steve Anton75737c02017-11-06 10:37:17 -08004214 }
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004215
4216 // Only push down the transport description after potentially enabling BUNDLE;
4217 // we don't want to push down a description on a transport about to be
4218 // destroyed.
Steve Anton3828c062017-12-06 10:34:51 -08004219 RTCError error = PushdownTransportDescription(source, type);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004220 if (!error.ok()) {
4221 return error;
4222 }
4223
4224 // If this is answer-ish we're ready to let media flow.
Steve Anton3828c062017-12-06 10:34:51 -08004225 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Antoned10bd92017-12-05 10:52:59 -08004226 EnableSending();
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004227 }
4228
4229 // Update the signaling state according to the specified state machine (see
4230 // https://w3c.github.io/webrtc-pc/#rtcsignalingstate-enum).
Steve Anton3828c062017-12-06 10:34:51 -08004231 if (type == SdpType::kOffer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004232 ChangeSignalingState(source == cricket::CS_LOCAL
4233 ? PeerConnectionInterface::kHaveLocalOffer
4234 : PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton3828c062017-12-06 10:34:51 -08004235 } else if (type == SdpType::kPrAnswer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004236 ChangeSignalingState(source == cricket::CS_LOCAL
4237 ? PeerConnectionInterface::kHaveLocalPrAnswer
4238 : PeerConnectionInterface::kHaveRemotePrAnswer);
4239 } else {
Steve Anton3828c062017-12-06 10:34:51 -08004240 RTC_DCHECK(type == SdpType::kAnswer);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004241 ChangeSignalingState(PeerConnectionInterface::kStable);
4242 }
4243
4244 // Update internal objects according to the session description's media
4245 // descriptions.
Steve Anton3828c062017-12-06 10:34:51 -08004246 error = PushdownMediaDescription(type, source);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004247 if (!error.ok()) {
4248 SetSessionError(SessionError::kContent, error.message());
4249 }
4250 if (session_error() != SessionError::kNone) {
4251 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
4252 }
4253
Steve Anton8a006912017-12-04 15:25:56 -08004254 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08004255}
4256
Steve Anton8a006912017-12-04 15:25:56 -08004257RTCError PeerConnection::PushdownMediaDescription(
Steve Anton3828c062017-12-06 10:34:51 -08004258 SdpType type,
Steve Anton8a006912017-12-04 15:25:56 -08004259 cricket::ContentSource source) {
Steve Antoned10bd92017-12-05 10:52:59 -08004260 const SessionDescriptionInterface* sdesc =
4261 (source == cricket::CS_LOCAL ? local_description()
4262 : remote_description());
Steve Anton75737c02017-11-06 10:37:17 -08004263 RTC_DCHECK(sdesc);
Steve Antoned10bd92017-12-05 10:52:59 -08004264
4265 // Push down the new SDP media section for each audio/video transceiver.
4266 for (auto transceiver : transceivers_) {
Steve Anton75737c02017-11-06 10:37:17 -08004267 const ContentInfo* content_info =
Steve Antoned10bd92017-12-05 10:52:59 -08004268 FindMediaSectionForTransceiver(transceiver, sdesc);
4269 cricket::BaseChannel* channel = transceiver->internal()->channel();
4270 if (!channel || !content_info || content_info->rejected) {
Steve Anton75737c02017-11-06 10:37:17 -08004271 continue;
4272 }
4273 const MediaContentDescription* content_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08004274 content_info->media_description();
Steve Antoned10bd92017-12-05 10:52:59 -08004275 if (!content_desc) {
4276 continue;
4277 }
4278 std::string error;
4279 bool success =
4280 (source == cricket::CS_LOCAL)
Steve Anton3828c062017-12-06 10:34:51 -08004281 ? channel->SetLocalContent(content_desc, type, &error)
4282 : channel->SetRemoteContent(content_desc, type, &error);
Steve Antoned10bd92017-12-05 10:52:59 -08004283 if (!success) {
4284 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, std::move(error));
4285 }
4286 }
4287
4288 // If using the RtpDataChannel, push down the new SDP section for it too.
4289 if (rtp_data_channel_) {
4290 const ContentInfo* data_content =
4291 cricket::GetFirstDataContent(sdesc->description());
4292 if (data_content && !data_content->rejected) {
4293 const MediaContentDescription* data_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08004294 data_content->media_description();
Steve Antoned10bd92017-12-05 10:52:59 -08004295 if (data_desc) {
4296 std::string error;
4297 bool success =
4298 (source == cricket::CS_LOCAL)
Steve Anton3828c062017-12-06 10:34:51 -08004299 ? rtp_data_channel_->SetLocalContent(data_desc, type, &error)
4300 : rtp_data_channel_->SetRemoteContent(data_desc, type,
Steve Antoned10bd92017-12-05 10:52:59 -08004301 &error);
4302 if (!success) {
4303 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
4304 std::move(error));
4305 }
Steve Anton75737c02017-11-06 10:37:17 -08004306 }
4307 }
4308 }
Steve Antoned10bd92017-12-05 10:52:59 -08004309
Steve Anton75737c02017-11-06 10:37:17 -08004310 // Need complete offer/answer with an SCTP m= section before starting SCTP,
4311 // according to https://tools.ietf.org/html/draft-ietf-mmusic-sctp-sdp-19
4312 if (sctp_transport_ && local_description() && remote_description() &&
4313 cricket::GetFirstDataContent(local_description()->description()) &&
4314 cricket::GetFirstDataContent(remote_description()->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08004315 bool success = network_thread()->Invoke<bool>(
Steve Anton75737c02017-11-06 10:37:17 -08004316 RTC_FROM_HERE,
4317 rtc::Bind(&PeerConnection::PushdownSctpParameters_n, this, source));
Steve Anton8a006912017-12-04 15:25:56 -08004318 if (!success) {
4319 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
4320 "Failed to push down SCTP parameters.");
4321 }
Steve Anton75737c02017-11-06 10:37:17 -08004322 }
Steve Antoned10bd92017-12-05 10:52:59 -08004323
Steve Anton8a006912017-12-04 15:25:56 -08004324 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08004325}
4326
4327bool PeerConnection::PushdownSctpParameters_n(cricket::ContentSource source) {
4328 RTC_DCHECK(network_thread()->IsCurrent());
4329 RTC_DCHECK(local_description());
4330 RTC_DCHECK(remote_description());
4331 // Apply the SCTP port (which is hidden inside a DataCodec structure...)
4332 // When we support "max-message-size", that would also be pushed down here.
4333 return sctp_transport_->Start(
4334 GetSctpPort(local_description()->description()),
4335 GetSctpPort(remote_description()->description()));
4336}
4337
Steve Anton8a006912017-12-04 15:25:56 -08004338RTCError PeerConnection::PushdownTransportDescription(
4339 cricket::ContentSource source,
Steve Anton3828c062017-12-06 10:34:51 -08004340 SdpType type) {
Steve Anton8a006912017-12-04 15:25:56 -08004341 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08004342
Steve Anton8a006912017-12-04 15:25:56 -08004343 const SessionDescriptionInterface* sdesc =
4344 (source == cricket::CS_LOCAL ? local_description()
4345 : remote_description());
4346 RTC_DCHECK(sdesc);
4347 for (const cricket::TransportInfo& tinfo :
4348 sdesc->description()->transport_infos()) {
4349 std::string error;
4350 bool success;
4351 if (source == cricket::CS_LOCAL) {
4352 success = transport_controller_->SetLocalTransportDescription(
Steve Anton3828c062017-12-06 10:34:51 -08004353 tinfo.content_name, tinfo.description, type, &error);
Steve Anton8a006912017-12-04 15:25:56 -08004354 } else {
4355 success = transport_controller_->SetRemoteTransportDescription(
Steve Anton3828c062017-12-06 10:34:51 -08004356 tinfo.content_name, tinfo.description, type, &error);
Steve Anton8a006912017-12-04 15:25:56 -08004357 }
4358 if (!success) {
Steve Antondcc3c022017-12-22 16:02:54 -08004359 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
4360 "Failed to push down transport description for " +
4361 tinfo.content_name + ": " + error);
Steve Anton75737c02017-11-06 10:37:17 -08004362 }
4363 }
4364
Steve Anton8a006912017-12-04 15:25:56 -08004365 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08004366}
4367
4368bool PeerConnection::GetTransportDescription(
4369 const SessionDescription* description,
4370 const std::string& content_name,
4371 cricket::TransportDescription* tdesc) {
4372 if (!description || !tdesc) {
4373 return false;
4374 }
4375 const TransportInfo* transport_info =
4376 description->GetTransportInfoByName(content_name);
4377 if (!transport_info) {
4378 return false;
4379 }
4380 *tdesc = transport_info->description;
4381 return true;
4382}
4383
4384bool PeerConnection::EnableBundle(const cricket::ContentGroup& bundle) {
4385 const std::string* first_content_name = bundle.FirstContentName();
4386 if (!first_content_name) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004387 RTC_LOG(LS_WARNING) << "Tried to BUNDLE with no contents.";
Steve Anton75737c02017-11-06 10:37:17 -08004388 return false;
4389 }
4390 const std::string& transport_name = *first_content_name;
4391
4392 auto maybe_set_transport = [this, bundle,
4393 transport_name](cricket::BaseChannel* ch) {
4394 if (!ch || !bundle.HasContentName(ch->content_name())) {
Steve Antoned10bd92017-12-05 10:52:59 -08004395 return;
Steve Anton75737c02017-11-06 10:37:17 -08004396 }
4397
4398 std::string old_transport_name = ch->transport_name();
4399 if (old_transport_name == transport_name) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004400 RTC_LOG(LS_INFO) << "BUNDLE already enabled for " << ch->content_name()
4401 << " on " << transport_name << ".";
Steve Antoned10bd92017-12-05 10:52:59 -08004402 return;
Steve Anton75737c02017-11-06 10:37:17 -08004403 }
4404
4405 cricket::DtlsTransportInternal* rtp_dtls_transport =
4406 transport_controller_->CreateDtlsTransport(
4407 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4408 bool need_rtcp = (ch->rtcp_dtls_transport() != nullptr);
4409 cricket::DtlsTransportInternal* rtcp_dtls_transport = nullptr;
4410 if (need_rtcp) {
4411 rtcp_dtls_transport = transport_controller_->CreateDtlsTransport(
4412 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
4413 }
4414
4415 ch->SetTransports(rtp_dtls_transport, rtcp_dtls_transport);
Mirko Bonadei675513b2017-11-09 11:09:25 +01004416 RTC_LOG(LS_INFO) << "Enabled BUNDLE for " << ch->content_name() << " on "
4417 << transport_name << ".";
Steve Anton75737c02017-11-06 10:37:17 -08004418 transport_controller_->DestroyDtlsTransport(
4419 old_transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4420 // If the channel needs rtcp, it means that the channel used to have a
4421 // rtcp transport which needs to be deleted now.
4422 if (need_rtcp) {
4423 transport_controller_->DestroyDtlsTransport(
4424 old_transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
4425 }
Steve Anton75737c02017-11-06 10:37:17 -08004426 };
4427
Steve Antoned10bd92017-12-05 10:52:59 -08004428 for (auto transceiver : transceivers_) {
4429 maybe_set_transport(transceiver->internal()->channel());
Steve Anton75737c02017-11-06 10:37:17 -08004430 }
Steve Antoned10bd92017-12-05 10:52:59 -08004431 maybe_set_transport(rtp_data_channel_);
4432
Steve Anton75737c02017-11-06 10:37:17 -08004433 // For SCTP, transport creation/deletion happens here instead of in the
4434 // object itself.
4435 if (sctp_transport_) {
4436 RTC_DCHECK(sctp_transport_name_);
4437 RTC_DCHECK(sctp_content_name_);
4438 if (transport_name != *sctp_transport_name_ &&
4439 bundle.HasContentName(*sctp_content_name_)) {
4440 network_thread()->Invoke<void>(
4441 RTC_FROM_HERE, rtc::Bind(&PeerConnection::ChangeSctpTransport_n, this,
4442 transport_name));
4443 }
4444 }
4445
4446 return true;
4447}
4448
Steve Anton75737c02017-11-06 10:37:17 -08004449cricket::IceConfig PeerConnection::ParseIceConfig(
4450 const PeerConnectionInterface::RTCConfiguration& config) const {
4451 cricket::ContinualGatheringPolicy gathering_policy;
4452 // TODO(honghaiz): Add the third continual gathering policy in
4453 // PeerConnectionInterface and map it to GATHER_CONTINUALLY_AND_RECOVER.
4454 switch (config.continual_gathering_policy) {
4455 case PeerConnectionInterface::GATHER_ONCE:
4456 gathering_policy = cricket::GATHER_ONCE;
4457 break;
4458 case PeerConnectionInterface::GATHER_CONTINUALLY:
4459 gathering_policy = cricket::GATHER_CONTINUALLY;
4460 break;
4461 default:
4462 RTC_NOTREACHED();
4463 gathering_policy = cricket::GATHER_ONCE;
4464 }
4465 cricket::IceConfig ice_config;
4466 ice_config.receiving_timeout = config.ice_connection_receiving_timeout;
4467 ice_config.prioritize_most_likely_candidate_pairs =
4468 config.prioritize_most_likely_ice_candidate_pairs;
4469 ice_config.backup_connection_ping_interval =
4470 config.ice_backup_candidate_pair_ping_interval;
4471 ice_config.continual_gathering_policy = gathering_policy;
4472 ice_config.presume_writable_when_fully_relayed =
4473 config.presume_writable_when_fully_relayed;
4474 ice_config.ice_check_min_interval = config.ice_check_min_interval;
4475 ice_config.regather_all_networks_interval_range =
4476 config.ice_regather_interval_range;
4477 return ice_config;
4478}
4479
Steve Anton75737c02017-11-06 10:37:17 -08004480bool PeerConnection::GetLocalTrackIdBySsrc(uint32_t ssrc,
4481 std::string* track_id) {
4482 if (!local_description()) {
4483 return false;
4484 }
4485 return webrtc::GetTrackIdBySsrc(local_description()->description(), ssrc,
4486 track_id);
4487}
4488
4489bool PeerConnection::GetRemoteTrackIdBySsrc(uint32_t ssrc,
4490 std::string* track_id) {
4491 if (!remote_description()) {
4492 return false;
4493 }
4494 return webrtc::GetTrackIdBySsrc(remote_description()->description(), ssrc,
4495 track_id);
4496}
4497
4498bool PeerConnection::SendData(const cricket::SendDataParams& params,
4499 const rtc::CopyOnWriteBuffer& payload,
4500 cricket::SendDataResult* result) {
4501 if (!rtp_data_channel_ && !sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004502 RTC_LOG(LS_ERROR) << "SendData called when rtp_data_channel_ "
4503 << "and sctp_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08004504 return false;
4505 }
4506 return rtp_data_channel_
4507 ? rtp_data_channel_->SendData(params, payload, result)
4508 : network_thread()->Invoke<bool>(
4509 RTC_FROM_HERE,
4510 Bind(&cricket::SctpTransportInternal::SendData,
4511 sctp_transport_.get(), params, payload, result));
4512}
4513
4514bool PeerConnection::ConnectDataChannel(DataChannel* webrtc_data_channel) {
4515 if (!rtp_data_channel_ && !sctp_transport_) {
4516 // Don't log an error here, because DataChannels are expected to call
4517 // ConnectDataChannel in this state. It's the only way to initially tell
4518 // whether or not the underlying transport is ready.
4519 return false;
4520 }
4521 if (rtp_data_channel_) {
4522 rtp_data_channel_->SignalReadyToSendData.connect(
4523 webrtc_data_channel, &DataChannel::OnChannelReady);
4524 rtp_data_channel_->SignalDataReceived.connect(webrtc_data_channel,
4525 &DataChannel::OnDataReceived);
4526 } else {
4527 SignalSctpReadyToSendData.connect(webrtc_data_channel,
4528 &DataChannel::OnChannelReady);
4529 SignalSctpDataReceived.connect(webrtc_data_channel,
4530 &DataChannel::OnDataReceived);
4531 SignalSctpStreamClosedRemotely.connect(
4532 webrtc_data_channel, &DataChannel::OnStreamClosedRemotely);
4533 }
4534 return true;
4535}
4536
4537void PeerConnection::DisconnectDataChannel(DataChannel* webrtc_data_channel) {
4538 if (!rtp_data_channel_ && !sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004539 RTC_LOG(LS_ERROR)
4540 << "DisconnectDataChannel called when rtp_data_channel_ and "
4541 "sctp_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08004542 return;
4543 }
4544 if (rtp_data_channel_) {
4545 rtp_data_channel_->SignalReadyToSendData.disconnect(webrtc_data_channel);
4546 rtp_data_channel_->SignalDataReceived.disconnect(webrtc_data_channel);
4547 } else {
4548 SignalSctpReadyToSendData.disconnect(webrtc_data_channel);
4549 SignalSctpDataReceived.disconnect(webrtc_data_channel);
4550 SignalSctpStreamClosedRemotely.disconnect(webrtc_data_channel);
4551 }
4552}
4553
4554void PeerConnection::AddSctpDataStream(int sid) {
4555 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004556 RTC_LOG(LS_ERROR)
4557 << "AddSctpDataStream called when sctp_transport_ is NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08004558 return;
4559 }
4560 network_thread()->Invoke<void>(
4561 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::OpenStream,
4562 sctp_transport_.get(), sid));
4563}
4564
4565void PeerConnection::RemoveSctpDataStream(int sid) {
4566 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004567 RTC_LOG(LS_ERROR) << "RemoveSctpDataStream called when sctp_transport_ is "
4568 << "NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08004569 return;
4570 }
4571 network_thread()->Invoke<void>(
4572 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::ResetStream,
4573 sctp_transport_.get(), sid));
4574}
4575
4576bool PeerConnection::ReadyToSendData() const {
4577 return (rtp_data_channel_ && rtp_data_channel_->ready_to_send_data()) ||
4578 sctp_ready_to_send_data_;
4579}
4580
4581std::unique_ptr<SessionStats> PeerConnection::GetSessionStats_s() {
4582 RTC_DCHECK(signaling_thread()->IsCurrent());
4583 ChannelNamePairs channel_name_pairs;
4584 if (voice_channel()) {
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004585 channel_name_pairs.voice = ChannelNamePair(
4586 voice_channel()->content_name(), voice_channel()->transport_name());
Steve Anton75737c02017-11-06 10:37:17 -08004587 }
4588 if (video_channel()) {
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004589 channel_name_pairs.video = ChannelNamePair(
4590 video_channel()->content_name(), video_channel()->transport_name());
Steve Anton75737c02017-11-06 10:37:17 -08004591 }
4592 if (rtp_data_channel()) {
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004593 channel_name_pairs.data =
Steve Anton75737c02017-11-06 10:37:17 -08004594 ChannelNamePair(rtp_data_channel()->content_name(),
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004595 rtp_data_channel()->transport_name());
Steve Anton75737c02017-11-06 10:37:17 -08004596 }
4597 if (sctp_transport_) {
4598 RTC_DCHECK(sctp_content_name_);
4599 RTC_DCHECK(sctp_transport_name_);
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004600 channel_name_pairs.data =
4601 ChannelNamePair(*sctp_content_name_, *sctp_transport_name_);
Steve Anton75737c02017-11-06 10:37:17 -08004602 }
4603 return GetSessionStats(channel_name_pairs);
4604}
4605
4606std::unique_ptr<SessionStats> PeerConnection::GetSessionStats(
4607 const ChannelNamePairs& channel_name_pairs) {
4608 if (network_thread()->IsCurrent()) {
4609 return GetSessionStats_n(channel_name_pairs);
4610 }
4611 return network_thread()->Invoke<std::unique_ptr<SessionStats>>(
4612 RTC_FROM_HERE,
4613 rtc::Bind(&PeerConnection::GetSessionStats_n, this, channel_name_pairs));
4614}
4615
4616bool PeerConnection::GetLocalCertificate(
4617 const std::string& transport_name,
4618 rtc::scoped_refptr<rtc::RTCCertificate>* certificate) {
4619 return transport_controller_->GetLocalCertificate(transport_name,
4620 certificate);
4621}
4622
4623std::unique_ptr<rtc::SSLCertificate> PeerConnection::GetRemoteSSLCertificate(
4624 const std::string& transport_name) {
4625 return transport_controller_->GetRemoteSSLCertificate(transport_name);
4626}
4627
4628cricket::DataChannelType PeerConnection::data_channel_type() const {
4629 return data_channel_type_;
4630}
4631
4632bool PeerConnection::IceRestartPending(const std::string& content_name) const {
4633 return pending_ice_restarts_.find(content_name) !=
4634 pending_ice_restarts_.end();
4635}
4636
Steve Anton75737c02017-11-06 10:37:17 -08004637bool PeerConnection::NeedsIceRestart(const std::string& content_name) const {
4638 return transport_controller_->NeedsIceRestart(content_name);
4639}
4640
4641void PeerConnection::OnCertificateReady(
4642 const rtc::scoped_refptr<rtc::RTCCertificate>& certificate) {
4643 transport_controller_->SetLocalCertificate(certificate);
4644}
4645
4646void PeerConnection::OnDtlsSrtpSetupFailure(cricket::BaseChannel*, bool rtcp) {
Steve Antonf8470812017-12-04 10:46:21 -08004647 SetSessionError(SessionError::kTransport,
4648 rtcp ? kDtlsSrtpSetupFailureRtcp : kDtlsSrtpSetupFailureRtp);
Steve Anton75737c02017-11-06 10:37:17 -08004649}
4650
4651void PeerConnection::OnTransportControllerConnectionState(
4652 cricket::IceConnectionState state) {
4653 switch (state) {
4654 case cricket::kIceConnectionConnecting:
4655 // If the current state is Connected or Completed, then there were
4656 // writable channels but now there are not, so the next state must
4657 // be Disconnected.
4658 // kIceConnectionConnecting is currently used as the default,
4659 // un-connected state by the TransportController, so its only use is
4660 // detecting disconnections.
4661 if (ice_connection_state_ ==
4662 PeerConnectionInterface::kIceConnectionConnected ||
4663 ice_connection_state_ ==
4664 PeerConnectionInterface::kIceConnectionCompleted) {
4665 SetIceConnectionState(
4666 PeerConnectionInterface::kIceConnectionDisconnected);
4667 }
4668 break;
4669 case cricket::kIceConnectionFailed:
4670 SetIceConnectionState(PeerConnectionInterface::kIceConnectionFailed);
4671 break;
4672 case cricket::kIceConnectionConnected:
Mirko Bonadei675513b2017-11-09 11:09:25 +01004673 RTC_LOG(LS_INFO) << "Changing to ICE connected state because "
4674 << "all transports are writable.";
Steve Anton75737c02017-11-06 10:37:17 -08004675 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
4676 break;
4677 case cricket::kIceConnectionCompleted:
Mirko Bonadei675513b2017-11-09 11:09:25 +01004678 RTC_LOG(LS_INFO) << "Changing to ICE completed state because "
4679 << "all transports are complete.";
Steve Anton75737c02017-11-06 10:37:17 -08004680 if (ice_connection_state_ !=
4681 PeerConnectionInterface::kIceConnectionConnected) {
4682 // If jumping directly from "checking" to "connected",
4683 // signal "connected" first.
4684 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
4685 }
4686 SetIceConnectionState(PeerConnectionInterface::kIceConnectionCompleted);
4687 if (metrics_observer()) {
4688 ReportTransportStats();
4689 }
4690 break;
4691 default:
4692 RTC_NOTREACHED();
4693 }
4694}
4695
4696void PeerConnection::OnTransportControllerCandidatesGathered(
4697 const std::string& transport_name,
4698 const cricket::Candidates& candidates) {
4699 RTC_DCHECK(signaling_thread()->IsCurrent());
4700 int sdp_mline_index;
4701 if (!GetLocalCandidateMediaIndex(transport_name, &sdp_mline_index)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004702 RTC_LOG(LS_ERROR)
4703 << "OnTransportControllerCandidatesGathered: content name "
4704 << transport_name << " not found";
Steve Anton75737c02017-11-06 10:37:17 -08004705 return;
4706 }
4707
4708 for (cricket::Candidates::const_iterator citer = candidates.begin();
4709 citer != candidates.end(); ++citer) {
4710 // Use transport_name as the candidate media id.
4711 std::unique_ptr<JsepIceCandidate> candidate(
4712 new JsepIceCandidate(transport_name, sdp_mline_index, *citer));
4713 if (local_description()) {
4714 mutable_local_description()->AddCandidate(candidate.get());
4715 }
4716 OnIceCandidate(std::move(candidate));
4717 }
4718}
4719
4720void PeerConnection::OnTransportControllerCandidatesRemoved(
4721 const std::vector<cricket::Candidate>& candidates) {
4722 RTC_DCHECK(signaling_thread()->IsCurrent());
4723 // Sanity check.
4724 for (const cricket::Candidate& candidate : candidates) {
4725 if (candidate.transport_name().empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004726 RTC_LOG(LS_ERROR) << "OnTransportControllerCandidatesRemoved: "
4727 << "empty content name in candidate "
4728 << candidate.ToString();
Steve Anton75737c02017-11-06 10:37:17 -08004729 return;
4730 }
4731 }
4732
4733 if (local_description()) {
4734 mutable_local_description()->RemoveCandidates(candidates);
4735 }
4736 OnIceCandidatesRemoved(candidates);
4737}
4738
4739void PeerConnection::OnTransportControllerDtlsHandshakeError(
4740 rtc::SSLHandshakeError error) {
4741 if (metrics_observer()) {
4742 metrics_observer()->IncrementEnumCounter(
4743 webrtc::kEnumCounterDtlsHandshakeError, static_cast<int>(error),
4744 static_cast<int>(rtc::SSLHandshakeError::MAX_VALUE));
4745 }
4746}
4747
Steve Antoned10bd92017-12-05 10:52:59 -08004748void PeerConnection::EnableSending() {
4749 for (auto transceiver : transceivers_) {
4750 cricket::BaseChannel* channel = transceiver->internal()->channel();
4751 if (channel && !channel->enabled()) {
4752 channel->Enable(true);
4753 }
Steve Anton75737c02017-11-06 10:37:17 -08004754 }
4755
Steve Anton4171afb2017-11-20 10:20:22 -08004756 if (rtp_data_channel_ && !rtp_data_channel_->enabled()) {
Steve Anton75737c02017-11-06 10:37:17 -08004757 rtp_data_channel_->Enable(true);
Steve Anton4171afb2017-11-20 10:20:22 -08004758 }
Steve Anton75737c02017-11-06 10:37:17 -08004759}
4760
4761// Returns the media index for a local ice candidate given the content name.
4762bool PeerConnection::GetLocalCandidateMediaIndex(
4763 const std::string& content_name,
4764 int* sdp_mline_index) {
4765 if (!local_description() || !sdp_mline_index) {
4766 return false;
4767 }
4768
4769 bool content_found = false;
4770 const ContentInfos& contents = local_description()->description()->contents();
4771 for (size_t index = 0; index < contents.size(); ++index) {
4772 if (contents[index].name == content_name) {
4773 *sdp_mline_index = static_cast<int>(index);
4774 content_found = true;
4775 break;
4776 }
4777 }
4778 return content_found;
4779}
4780
4781bool PeerConnection::UseCandidatesInSessionDescription(
4782 const SessionDescriptionInterface* remote_desc) {
4783 if (!remote_desc) {
4784 return true;
4785 }
4786 bool ret = true;
4787
4788 for (size_t m = 0; m < remote_desc->number_of_mediasections(); ++m) {
4789 const IceCandidateCollection* candidates = remote_desc->candidates(m);
4790 for (size_t n = 0; n < candidates->count(); ++n) {
4791 const IceCandidateInterface* candidate = candidates->at(n);
4792 bool valid = false;
4793 if (!ReadyToUseRemoteCandidate(candidate, remote_desc, &valid)) {
4794 if (valid) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004795 RTC_LOG(LS_INFO)
4796 << "UseCandidatesInSessionDescription: Not ready to use "
4797 << "candidate.";
Steve Anton75737c02017-11-06 10:37:17 -08004798 }
4799 continue;
4800 }
4801 ret = UseCandidate(candidate);
4802 if (!ret) {
4803 break;
4804 }
4805 }
4806 }
4807 return ret;
4808}
4809
4810bool PeerConnection::UseCandidate(const IceCandidateInterface* candidate) {
4811 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
4812 size_t remote_content_size =
4813 remote_description()->description()->contents().size();
4814 if (mediacontent_index >= remote_content_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004815 RTC_LOG(LS_ERROR) << "UseCandidate: Invalid candidate media index.";
Steve Anton75737c02017-11-06 10:37:17 -08004816 return false;
4817 }
4818
4819 cricket::ContentInfo content =
4820 remote_description()->description()->contents()[mediacontent_index];
4821 std::vector<cricket::Candidate> candidates;
4822 candidates.push_back(candidate->candidate());
4823 // Invoking BaseSession method to handle remote candidates.
4824 std::string error;
4825 if (transport_controller_->AddRemoteCandidates(content.name, candidates,
4826 &error)) {
4827 // Candidates successfully submitted for checking.
4828 if (ice_connection_state_ == PeerConnectionInterface::kIceConnectionNew ||
4829 ice_connection_state_ ==
4830 PeerConnectionInterface::kIceConnectionDisconnected) {
4831 // If state is New, then the session has just gotten its first remote ICE
4832 // candidates, so go to Checking.
4833 // If state is Disconnected, the session is re-using old candidates or
4834 // receiving additional ones, so go to Checking.
4835 // If state is Connected, stay Connected.
4836 // TODO(bemasc): If state is Connected, and the new candidates are for a
4837 // newly added transport, then the state actually _should_ move to
4838 // checking. Add a way to distinguish that case.
4839 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
4840 }
4841 // TODO(bemasc): If state is Completed, go back to Connected.
4842 } else {
4843 if (!error.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004844 RTC_LOG(LS_WARNING) << error;
Steve Anton75737c02017-11-06 10:37:17 -08004845 }
4846 }
4847 return true;
4848}
4849
4850void PeerConnection::RemoveUnusedChannels(const SessionDescription* desc) {
Steve Anton75737c02017-11-06 10:37:17 -08004851 // Destroy video channel first since it may have a pointer to the
4852 // voice channel.
4853 const cricket::ContentInfo* video_info = cricket::GetFirstVideoContent(desc);
Steve Anton6fec8802017-12-04 10:37:29 -08004854 if (!video_info || video_info->rejected) {
4855 DestroyTransceiverChannel(GetVideoTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08004856 }
4857
Steve Anton6fec8802017-12-04 10:37:29 -08004858 const cricket::ContentInfo* audio_info = cricket::GetFirstAudioContent(desc);
4859 if (!audio_info || audio_info->rejected) {
4860 DestroyTransceiverChannel(GetAudioTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08004861 }
4862
4863 const cricket::ContentInfo* data_info = cricket::GetFirstDataContent(desc);
4864 if (!data_info || data_info->rejected) {
Steve Anton6fec8802017-12-04 10:37:29 -08004865 DestroyDataChannel();
Steve Anton75737c02017-11-06 10:37:17 -08004866 }
4867}
4868
Steve Antoneda6ccd2017-12-04 10:21:55 -08004869std::string PeerConnection::GetTransportNameForMediaSection(
4870 const std::string& mid,
4871 const cricket::ContentGroup* bundle_group) const {
4872 if (!bundle_group) {
4873 return mid;
Steve Anton75737c02017-11-06 10:37:17 -08004874 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08004875 const std::string* first_content_name = bundle_group->FirstContentName();
Steve Anton75737c02017-11-06 10:37:17 -08004876 if (!first_content_name) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004877 RTC_LOG(LS_WARNING) << "Tried to BUNDLE with no contents.";
Steve Antoneda6ccd2017-12-04 10:21:55 -08004878 return mid;
Steve Anton75737c02017-11-06 10:37:17 -08004879 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08004880 if (!bundle_group->HasContentName(mid)) {
4881 RTC_LOG(LS_WARNING) << mid << " is not part of any bundle group";
4882 return mid;
Steve Anton75737c02017-11-06 10:37:17 -08004883 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08004884 RTC_LOG(LS_INFO) << "Bundling " << mid << " on " << *first_content_name;
4885 return *first_content_name;
Steve Anton75737c02017-11-06 10:37:17 -08004886}
4887
Steve Antondcc3c022017-12-22 16:02:54 -08004888RTCErrorOr<const cricket::ContentGroup*> PeerConnection::GetEarlyBundleGroup(
4889 const SessionDescription& desc) const {
Steve Anton75737c02017-11-06 10:37:17 -08004890 const cricket::ContentGroup* bundle_group = nullptr;
4891 if (configuration_.bundle_policy ==
4892 PeerConnectionInterface::kBundlePolicyMaxBundle) {
Steve Antondcc3c022017-12-22 16:02:54 -08004893 bundle_group = desc.GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton75737c02017-11-06 10:37:17 -08004894 if (!bundle_group) {
Steve Anton8a006912017-12-04 15:25:56 -08004895 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
4896 "max-bundle configured but session description "
4897 "has no BUNDLE group");
Steve Anton75737c02017-11-06 10:37:17 -08004898 }
4899 }
Steve Antondcc3c022017-12-22 16:02:54 -08004900 return std::move(bundle_group);
4901}
4902
4903RTCError PeerConnection::CreateChannels(const SessionDescription& desc) {
4904 auto bundle_group_or_error = GetEarlyBundleGroup(desc);
4905 if (!bundle_group_or_error.ok()) {
4906 return bundle_group_or_error.MoveError();
4907 }
4908 const cricket::ContentGroup* bundle_group = bundle_group_or_error.MoveValue();
Steve Anton75737c02017-11-06 10:37:17 -08004909
Steve Antoneda6ccd2017-12-04 10:21:55 -08004910 // Creating the media channels and transport proxies.
Steve Antondcc3c022017-12-22 16:02:54 -08004911 const cricket::ContentInfo* voice = cricket::GetFirstAudioContent(&desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08004912 if (voice && !voice->rejected &&
4913 !GetAudioTransceiver()->internal()->channel()) {
4914 cricket::VoiceChannel* voice_channel = CreateVoiceChannel(
4915 voice->name,
4916 GetTransportNameForMediaSection(voice->name, bundle_group));
4917 if (!voice_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08004918 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
4919 "Failed to create voice channel.");
Steve Antoneda6ccd2017-12-04 10:21:55 -08004920 }
4921 GetAudioTransceiver()->internal()->SetChannel(voice_channel);
4922 }
4923
Steve Antondcc3c022017-12-22 16:02:54 -08004924 const cricket::ContentInfo* video = cricket::GetFirstVideoContent(&desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08004925 if (video && !video->rejected &&
4926 !GetVideoTransceiver()->internal()->channel()) {
4927 cricket::VideoChannel* video_channel = CreateVideoChannel(
4928 video->name,
4929 GetTransportNameForMediaSection(video->name, bundle_group));
4930 if (!video_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08004931 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
4932 "Failed to create video channel.");
Steve Anton75737c02017-11-06 10:37:17 -08004933 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08004934 GetVideoTransceiver()->internal()->SetChannel(video_channel);
Steve Anton75737c02017-11-06 10:37:17 -08004935 }
4936
Steve Antondcc3c022017-12-22 16:02:54 -08004937 const cricket::ContentInfo* data = cricket::GetFirstDataContent(&desc);
Steve Anton75737c02017-11-06 10:37:17 -08004938 if (data_channel_type_ != cricket::DCT_NONE && data && !data->rejected &&
4939 !rtp_data_channel_ && !sctp_transport_) {
Steve Antoneda6ccd2017-12-04 10:21:55 -08004940 if (!CreateDataChannel(data->name, GetTransportNameForMediaSection(
4941 data->name, bundle_group))) {
Steve Anton8a006912017-12-04 15:25:56 -08004942 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
4943 "Failed to create data channel.");
Steve Anton75737c02017-11-06 10:37:17 -08004944 }
4945 }
4946
Steve Anton8a006912017-12-04 15:25:56 -08004947 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08004948}
4949
Steve Anton4171afb2017-11-20 10:20:22 -08004950// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08004951cricket::VoiceChannel* PeerConnection::CreateVoiceChannel(
4952 const std::string& mid,
4953 const std::string& transport_name) {
Steve Anton75737c02017-11-06 10:37:17 -08004954 cricket::DtlsTransportInternal* rtp_dtls_transport =
4955 transport_controller_->CreateDtlsTransport(
4956 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4957 cricket::DtlsTransportInternal* rtcp_dtls_transport = nullptr;
4958 if (configuration_.rtcp_mux_policy !=
4959 PeerConnectionInterface::kRtcpMuxPolicyRequire) {
4960 rtcp_dtls_transport = transport_controller_->CreateDtlsTransport(
4961 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
4962 }
4963
4964 cricket::VoiceChannel* voice_channel = channel_manager()->CreateVoiceChannel(
4965 call_.get(), configuration_.media_config, rtp_dtls_transport,
Steve Antoneda6ccd2017-12-04 10:21:55 -08004966 rtcp_dtls_transport, signaling_thread(), mid, SrtpRequired(),
4967 audio_options_);
Steve Anton75737c02017-11-06 10:37:17 -08004968 if (!voice_channel) {
4969 transport_controller_->DestroyDtlsTransport(
4970 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4971 if (rtcp_dtls_transport) {
4972 transport_controller_->DestroyDtlsTransport(
4973 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
4974 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08004975 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08004976 }
Steve Anton75737c02017-11-06 10:37:17 -08004977 voice_channel->SignalRtcpMuxFullyActive.connect(
4978 this, &PeerConnection::DestroyRtcpTransport_n);
4979 voice_channel->SignalDtlsSrtpSetupFailure.connect(
4980 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08004981 voice_channel->SignalSentPacket.connect(this,
4982 &PeerConnection::OnSentPacket_w);
Steve Anton4171afb2017-11-20 10:20:22 -08004983
Steve Antoneda6ccd2017-12-04 10:21:55 -08004984 return voice_channel;
Steve Anton75737c02017-11-06 10:37:17 -08004985}
4986
Steve Anton4171afb2017-11-20 10:20:22 -08004987// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08004988cricket::VideoChannel* PeerConnection::CreateVideoChannel(
4989 const std::string& mid,
4990 const std::string& transport_name) {
Steve Anton75737c02017-11-06 10:37:17 -08004991 cricket::DtlsTransportInternal* rtp_dtls_transport =
4992 transport_controller_->CreateDtlsTransport(
4993 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4994 cricket::DtlsTransportInternal* rtcp_dtls_transport = nullptr;
4995 if (configuration_.rtcp_mux_policy !=
4996 PeerConnectionInterface::kRtcpMuxPolicyRequire) {
4997 rtcp_dtls_transport = transport_controller_->CreateDtlsTransport(
4998 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
4999 }
5000
5001 cricket::VideoChannel* video_channel = channel_manager()->CreateVideoChannel(
5002 call_.get(), configuration_.media_config, rtp_dtls_transport,
Steve Antoneda6ccd2017-12-04 10:21:55 -08005003 rtcp_dtls_transport, signaling_thread(), mid, SrtpRequired(),
5004 video_options_);
Steve Anton75737c02017-11-06 10:37:17 -08005005
5006 if (!video_channel) {
5007 transport_controller_->DestroyDtlsTransport(
5008 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5009 if (rtcp_dtls_transport) {
5010 transport_controller_->DestroyDtlsTransport(
5011 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
5012 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005013 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08005014 }
Steve Anton75737c02017-11-06 10:37:17 -08005015 video_channel->SignalRtcpMuxFullyActive.connect(
5016 this, &PeerConnection::DestroyRtcpTransport_n);
5017 video_channel->SignalDtlsSrtpSetupFailure.connect(
5018 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08005019 video_channel->SignalSentPacket.connect(this,
5020 &PeerConnection::OnSentPacket_w);
Steve Anton4171afb2017-11-20 10:20:22 -08005021
Steve Antoneda6ccd2017-12-04 10:21:55 -08005022 return video_channel;
Steve Anton75737c02017-11-06 10:37:17 -08005023}
5024
Steve Antoneda6ccd2017-12-04 10:21:55 -08005025bool PeerConnection::CreateDataChannel(const std::string& mid,
5026 const std::string& transport_name) {
Steve Anton75737c02017-11-06 10:37:17 -08005027 bool sctp = (data_channel_type_ == cricket::DCT_SCTP);
5028 if (sctp) {
5029 if (!sctp_factory_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005030 RTC_LOG(LS_ERROR)
Steve Anton75737c02017-11-06 10:37:17 -08005031 << "Trying to create SCTP transport, but didn't compile with "
5032 "SCTP support (HAVE_SCTP)";
5033 return false;
5034 }
5035 if (!network_thread()->Invoke<bool>(
5036 RTC_FROM_HERE, rtc::Bind(&PeerConnection::CreateSctpTransport_n,
Steve Antoneda6ccd2017-12-04 10:21:55 -08005037 this, mid, transport_name))) {
Steve Anton75737c02017-11-06 10:37:17 -08005038 return false;
5039 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005040 for (const auto& channel : sctp_data_channels_) {
5041 channel->OnTransportChannelCreated();
5042 }
Steve Anton75737c02017-11-06 10:37:17 -08005043 } else {
Steve Anton75737c02017-11-06 10:37:17 -08005044 cricket::DtlsTransportInternal* rtp_dtls_transport =
5045 transport_controller_->CreateDtlsTransport(
5046 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5047 cricket::DtlsTransportInternal* rtcp_dtls_transport = nullptr;
5048 if (configuration_.rtcp_mux_policy !=
5049 PeerConnectionInterface::kRtcpMuxPolicyRequire) {
5050 rtcp_dtls_transport = transport_controller_->CreateDtlsTransport(
5051 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
5052 }
5053
5054 rtp_data_channel_ = channel_manager()->CreateRtpDataChannel(
5055 configuration_.media_config, rtp_dtls_transport, rtcp_dtls_transport,
Steve Antoneda6ccd2017-12-04 10:21:55 -08005056 signaling_thread(), mid, SrtpRequired());
Steve Anton75737c02017-11-06 10:37:17 -08005057
5058 if (!rtp_data_channel_) {
5059 transport_controller_->DestroyDtlsTransport(
5060 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5061 if (rtcp_dtls_transport) {
5062 transport_controller_->DestroyDtlsTransport(
5063 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
5064 }
5065 return false;
5066 }
5067
5068 rtp_data_channel_->SignalRtcpMuxFullyActive.connect(
5069 this, &PeerConnection::DestroyRtcpTransport_n);
5070 rtp_data_channel_->SignalDtlsSrtpSetupFailure.connect(
5071 this, &PeerConnection::OnDtlsSrtpSetupFailure);
5072 rtp_data_channel_->SignalSentPacket.connect(
5073 this, &PeerConnection::OnSentPacket_w);
5074 }
5075
Steve Anton75737c02017-11-06 10:37:17 -08005076 return true;
5077}
5078
5079Call::Stats PeerConnection::GetCallStats() {
5080 if (!worker_thread()->IsCurrent()) {
5081 return worker_thread()->Invoke<Call::Stats>(
5082 RTC_FROM_HERE, rtc::Bind(&PeerConnection::GetCallStats, this));
5083 }
5084 if (call_) {
5085 return call_->GetStats();
5086 } else {
5087 return Call::Stats();
5088 }
5089}
5090
5091std::unique_ptr<SessionStats> PeerConnection::GetSessionStats_n(
5092 const ChannelNamePairs& channel_name_pairs) {
5093 RTC_DCHECK(network_thread()->IsCurrent());
5094 std::unique_ptr<SessionStats> session_stats(new SessionStats());
5095 for (const auto channel_name_pair :
5096 {&channel_name_pairs.voice, &channel_name_pairs.video,
5097 &channel_name_pairs.data}) {
5098 if (*channel_name_pair) {
5099 cricket::TransportStats transport_stats;
5100 if (!transport_controller_->GetStats((*channel_name_pair)->transport_name,
5101 &transport_stats)) {
5102 return nullptr;
5103 }
Steve Anton75737c02017-11-06 10:37:17 -08005104 session_stats->transport_stats[(*channel_name_pair)->transport_name] =
5105 std::move(transport_stats);
5106 }
5107 }
5108 return session_stats;
5109}
5110
5111bool PeerConnection::CreateSctpTransport_n(const std::string& content_name,
5112 const std::string& transport_name) {
5113 RTC_DCHECK(network_thread()->IsCurrent());
5114 RTC_DCHECK(sctp_factory_);
5115 cricket::DtlsTransportInternal* tc =
5116 transport_controller_->CreateDtlsTransport_n(
5117 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5118 sctp_transport_ = sctp_factory_->CreateSctpTransport(tc);
5119 RTC_DCHECK(sctp_transport_);
5120 sctp_invoker_.reset(new rtc::AsyncInvoker());
5121 sctp_transport_->SignalReadyToSendData.connect(
5122 this, &PeerConnection::OnSctpTransportReadyToSendData_n);
5123 sctp_transport_->SignalDataReceived.connect(
5124 this, &PeerConnection::OnSctpTransportDataReceived_n);
5125 sctp_transport_->SignalStreamClosedRemotely.connect(
5126 this, &PeerConnection::OnSctpStreamClosedRemotely_n);
Oskar Sundbom9b28a032017-11-16 10:53:30 +01005127 sctp_transport_name_ = transport_name;
5128 sctp_content_name_ = content_name;
Steve Anton75737c02017-11-06 10:37:17 -08005129 return true;
5130}
5131
5132void PeerConnection::ChangeSctpTransport_n(const std::string& transport_name) {
5133 RTC_DCHECK(network_thread()->IsCurrent());
5134 RTC_DCHECK(sctp_transport_);
5135 RTC_DCHECK(sctp_transport_name_);
5136 std::string old_sctp_transport_name = *sctp_transport_name_;
Oskar Sundbom9b28a032017-11-16 10:53:30 +01005137 sctp_transport_name_ = transport_name;
Steve Anton75737c02017-11-06 10:37:17 -08005138 cricket::DtlsTransportInternal* tc =
5139 transport_controller_->CreateDtlsTransport_n(
5140 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5141 sctp_transport_->SetTransportChannel(tc);
5142 transport_controller_->DestroyDtlsTransport_n(
5143 old_sctp_transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5144}
5145
5146void PeerConnection::DestroySctpTransport_n() {
5147 RTC_DCHECK(network_thread()->IsCurrent());
5148 sctp_transport_.reset(nullptr);
Taylor Brandstetter389a97c2018-01-03 16:26:06 -08005149 transport_controller_->DestroyDtlsTransport_n(
5150 *sctp_transport_name_, cricket::ICE_CANDIDATE_COMPONENT_RTP);
Steve Anton75737c02017-11-06 10:37:17 -08005151 sctp_content_name_.reset();
5152 sctp_transport_name_.reset();
5153 sctp_invoker_.reset(nullptr);
5154 sctp_ready_to_send_data_ = false;
5155}
5156
5157void PeerConnection::OnSctpTransportReadyToSendData_n() {
5158 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5159 RTC_DCHECK(network_thread()->IsCurrent());
5160 // Note: Cannot use rtc::Bind here because it will grab a reference to
5161 // PeerConnection and potentially cause PeerConnection to live longer than
5162 // expected. It is safe not to grab a reference since the sctp_invoker_ will
5163 // be destroyed before PeerConnection is destroyed, and at that point all
5164 // pending tasks will be cleared.
5165 sctp_invoker_->AsyncInvoke<void>(RTC_FROM_HERE, signaling_thread(), [this] {
5166 OnSctpTransportReadyToSendData_s(true);
5167 });
5168}
5169
5170void PeerConnection::OnSctpTransportReadyToSendData_s(bool ready) {
5171 RTC_DCHECK(signaling_thread()->IsCurrent());
5172 sctp_ready_to_send_data_ = ready;
5173 SignalSctpReadyToSendData(ready);
5174}
5175
5176void PeerConnection::OnSctpTransportDataReceived_n(
5177 const cricket::ReceiveDataParams& params,
5178 const rtc::CopyOnWriteBuffer& payload) {
5179 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5180 RTC_DCHECK(network_thread()->IsCurrent());
5181 // Note: Cannot use rtc::Bind here because it will grab a reference to
5182 // PeerConnection and potentially cause PeerConnection to live longer than
5183 // expected. It is safe not to grab a reference since the sctp_invoker_ will
5184 // be destroyed before PeerConnection is destroyed, and at that point all
5185 // pending tasks will be cleared.
5186 sctp_invoker_->AsyncInvoke<void>(
5187 RTC_FROM_HERE, signaling_thread(), [this, params, payload] {
5188 OnSctpTransportDataReceived_s(params, payload);
5189 });
5190}
5191
5192void PeerConnection::OnSctpTransportDataReceived_s(
5193 const cricket::ReceiveDataParams& params,
5194 const rtc::CopyOnWriteBuffer& payload) {
5195 RTC_DCHECK(signaling_thread()->IsCurrent());
5196 if (params.type == cricket::DMT_CONTROL && IsOpenMessage(payload)) {
5197 // Received OPEN message; parse and signal that a new data channel should
5198 // be created.
5199 std::string label;
5200 InternalDataChannelInit config;
5201 config.id = params.ssrc;
5202 if (!ParseDataChannelOpenMessage(payload, &label, &config)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005203 RTC_LOG(LS_WARNING) << "Failed to parse the OPEN message for sid "
5204 << params.ssrc;
Steve Anton75737c02017-11-06 10:37:17 -08005205 return;
5206 }
5207 config.open_handshake_role = InternalDataChannelInit::kAcker;
5208 OnDataChannelOpenMessage(label, config);
5209 } else {
5210 // Otherwise just forward the signal.
5211 SignalSctpDataReceived(params, payload);
5212 }
5213}
5214
5215void PeerConnection::OnSctpStreamClosedRemotely_n(int sid) {
5216 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5217 RTC_DCHECK(network_thread()->IsCurrent());
5218 sctp_invoker_->AsyncInvoke<void>(
5219 RTC_FROM_HERE, signaling_thread(),
5220 rtc::Bind(&sigslot::signal1<int>::operator(),
5221 &SignalSctpStreamClosedRemotely, sid));
5222}
5223
5224// Returns false if bundle is enabled and rtcp_mux is disabled.
5225bool PeerConnection::ValidateBundleSettings(const SessionDescription* desc) {
5226 bool bundle_enabled = desc->HasGroup(cricket::GROUP_TYPE_BUNDLE);
5227 if (!bundle_enabled)
5228 return true;
5229
5230 const cricket::ContentGroup* bundle_group =
5231 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
5232 RTC_DCHECK(bundle_group != NULL);
5233
5234 const cricket::ContentInfos& contents = desc->contents();
5235 for (cricket::ContentInfos::const_iterator citer = contents.begin();
5236 citer != contents.end(); ++citer) {
5237 const cricket::ContentInfo* content = (&*citer);
5238 RTC_DCHECK(content != NULL);
5239 if (bundle_group->HasContentName(content->name) && !content->rejected &&
Steve Anton5adfafd2017-12-20 16:34:00 -08005240 content->type == MediaProtocolType::kRtp) {
Steve Anton75737c02017-11-06 10:37:17 -08005241 if (!HasRtcpMuxEnabled(content))
5242 return false;
5243 }
5244 }
5245 // RTCP-MUX is enabled in all the contents.
5246 return true;
5247}
5248
5249bool PeerConnection::HasRtcpMuxEnabled(const cricket::ContentInfo* content) {
Steve Antonb1c1de12017-12-21 15:14:30 -08005250 return content->media_description()->rtcp_mux();
Steve Anton75737c02017-11-06 10:37:17 -08005251}
5252
Steve Anton8a006912017-12-04 15:25:56 -08005253RTCError PeerConnection::ValidateSessionDescription(
Steve Anton75737c02017-11-06 10:37:17 -08005254 const SessionDescriptionInterface* sdesc,
Steve Anton8a006912017-12-04 15:25:56 -08005255 cricket::ContentSource source) {
Steve Antonf8470812017-12-04 10:46:21 -08005256 if (session_error() != SessionError::kNone) {
Steve Anton8a006912017-12-04 15:25:56 -08005257 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
Steve Anton75737c02017-11-06 10:37:17 -08005258 }
5259
5260 if (!sdesc || !sdesc->description()) {
Steve Anton8a006912017-12-04 15:25:56 -08005261 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidSdp);
Steve Anton75737c02017-11-06 10:37:17 -08005262 }
5263
Steve Anton3828c062017-12-06 10:34:51 -08005264 SdpType type = sdesc->GetType();
5265 if ((source == cricket::CS_LOCAL && !ExpectSetLocalDescription(type)) ||
5266 (source == cricket::CS_REMOTE && !ExpectSetRemoteDescription(type))) {
Steve Anton8a006912017-12-04 15:25:56 -08005267 LOG_AND_RETURN_ERROR(
5268 RTCErrorType::INVALID_PARAMETER,
5269 "Called in wrong state: " + GetSignalingStateString(signaling_state()));
Steve Anton75737c02017-11-06 10:37:17 -08005270 }
5271
5272 // Verify crypto settings.
5273 std::string crypto_error;
Steve Anton8a006912017-12-04 15:25:56 -08005274 if (webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED ||
5275 dtls_enabled_) {
5276 RTCError crypto_error = VerifyCrypto(sdesc->description(), dtls_enabled_);
5277 if (!crypto_error.ok()) {
5278 return crypto_error;
5279 }
Steve Anton75737c02017-11-06 10:37:17 -08005280 }
5281
5282 // Verify ice-ufrag and ice-pwd.
5283 if (!VerifyIceUfragPwdPresent(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08005284 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5285 kSdpWithoutIceUfragPwd);
Steve Anton75737c02017-11-06 10:37:17 -08005286 }
5287
5288 if (!ValidateBundleSettings(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08005289 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5290 kBundleWithoutRtcpMux);
Steve Anton75737c02017-11-06 10:37:17 -08005291 }
5292
5293 // TODO(skvlad): When the local rtcp-mux policy is Require, reject any
5294 // m-lines that do not rtcp-mux enabled.
5295
5296 // Verify m-lines in Answer when compared against Offer.
Steve Anton3828c062017-12-06 10:34:51 -08005297 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Anton75737c02017-11-06 10:37:17 -08005298 const cricket::SessionDescription* offer_desc =
5299 (source == cricket::CS_LOCAL) ? remote_description()->description()
5300 : local_description()->description();
5301 if (!MediaSectionsHaveSameCount(offer_desc, sdesc->description()) ||
5302 !MediaSectionsInSameOrder(offer_desc, sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08005303 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5304 kMlineMismatchInAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08005305 }
5306 } else {
5307 const cricket::SessionDescription* current_desc = nullptr;
5308 if (source == cricket::CS_LOCAL && local_description()) {
5309 current_desc = local_description()->description();
5310 } else if (source == cricket::CS_REMOTE && remote_description()) {
5311 current_desc = remote_description()->description();
5312 }
5313 // The re-offers should respect the order of m= sections in current
5314 // description. See RFC3264 Section 8 paragraph 4 for more details.
5315 if (current_desc &&
5316 !MediaSectionsInSameOrder(current_desc, sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08005317 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5318 kMlineMismatchInSubsequentOffer);
Steve Anton75737c02017-11-06 10:37:17 -08005319 }
5320 }
5321
Steve Anton02ee47c2018-01-10 16:26:06 -08005322 // Unified Plan SDP should have exactly one stream per m= section for audio
5323 // and video.
5324 if (IsUnifiedPlan()) {
5325 for (const ContentInfo& content : sdesc->description()->contents()) {
5326 if (content.rejected) {
5327 continue;
5328 }
5329 if (content.media_description()) {
5330 cricket::MediaType media_type = content.media_description()->type();
5331 if (!(media_type == cricket::MEDIA_TYPE_AUDIO ||
5332 media_type == cricket::MEDIA_TYPE_VIDEO)) {
5333 continue;
5334 }
5335 const cricket::StreamParamsVec& streams =
5336 content.media_description()->streams();
5337 if (streams.size() != 1u) {
5338 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5339 "Unified Plan SDP should have exactly one "
5340 "track per media section for audio and video.");
5341 }
5342 }
5343 }
5344 }
5345
Steve Anton8a006912017-12-04 15:25:56 -08005346 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08005347}
5348
Steve Anton3828c062017-12-06 10:34:51 -08005349bool PeerConnection::ExpectSetLocalDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08005350 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08005351 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08005352 return (state == PeerConnectionInterface::kStable) ||
5353 (state == PeerConnectionInterface::kHaveLocalOffer);
Steve Anton20393062017-12-04 16:24:52 -08005354 } else {
Steve Anton3828c062017-12-06 10:34:51 -08005355 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08005356 return (state == PeerConnectionInterface::kHaveRemoteOffer) ||
5357 (state == PeerConnectionInterface::kHaveLocalPrAnswer);
5358 }
5359}
5360
Steve Anton3828c062017-12-06 10:34:51 -08005361bool PeerConnection::ExpectSetRemoteDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08005362 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08005363 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08005364 return (state == PeerConnectionInterface::kStable) ||
5365 (state == PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton20393062017-12-04 16:24:52 -08005366 } else {
Steve Anton3828c062017-12-06 10:34:51 -08005367 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08005368 return (state == PeerConnectionInterface::kHaveLocalOffer) ||
5369 (state == PeerConnectionInterface::kHaveRemotePrAnswer);
5370 }
5371}
5372
Steve Antonf8470812017-12-04 10:46:21 -08005373const char* PeerConnection::SessionErrorToString(SessionError error) const {
5374 switch (error) {
5375 case SessionError::kNone:
5376 return "ERROR_NONE";
5377 case SessionError::kContent:
5378 return "ERROR_CONTENT";
5379 case SessionError::kTransport:
5380 return "ERROR_TRANSPORT";
5381 }
5382 RTC_NOTREACHED();
5383 return "";
5384}
5385
Steve Anton75737c02017-11-06 10:37:17 -08005386std::string PeerConnection::GetSessionErrorMsg() {
5387 std::ostringstream desc;
Steve Antonf8470812017-12-04 10:46:21 -08005388 desc << kSessionError << SessionErrorToString(session_error()) << ". ";
5389 desc << kSessionErrorDesc << session_error_desc() << ".";
Steve Anton75737c02017-11-06 10:37:17 -08005390 return desc.str();
5391}
5392
5393// We need to check the local/remote description for the Transport instead of
5394// the session, because a new Transport added during renegotiation may have
5395// them unset while the session has them set from the previous negotiation.
5396// Not doing so may trigger the auto generation of transport description and
5397// mess up DTLS identity information, ICE credential, etc.
5398bool PeerConnection::ReadyToUseRemoteCandidate(
5399 const IceCandidateInterface* candidate,
5400 const SessionDescriptionInterface* remote_desc,
5401 bool* valid) {
5402 *valid = true;
5403
5404 const SessionDescriptionInterface* current_remote_desc =
5405 remote_desc ? remote_desc : remote_description();
5406
5407 if (!current_remote_desc) {
5408 return false;
5409 }
5410
5411 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
5412 size_t remote_content_size =
5413 current_remote_desc->description()->contents().size();
5414 if (mediacontent_index >= remote_content_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005415 RTC_LOG(LS_ERROR)
5416 << "ReadyToUseRemoteCandidate: Invalid candidate media index "
5417 << mediacontent_index;
Steve Anton75737c02017-11-06 10:37:17 -08005418
5419 *valid = false;
5420 return false;
5421 }
5422
5423 cricket::ContentInfo content =
5424 current_remote_desc->description()->contents()[mediacontent_index];
5425
5426 const std::string transport_name = GetTransportName(content.name);
5427 if (transport_name.empty()) {
5428 return false;
5429 }
5430 return transport_controller_->ReadyForRemoteCandidates(transport_name);
5431}
5432
5433bool PeerConnection::SrtpRequired() const {
5434 return dtls_enabled_ ||
5435 webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED;
5436}
5437
5438void PeerConnection::OnTransportControllerGatheringState(
5439 cricket::IceGatheringState state) {
5440 RTC_DCHECK(signaling_thread()->IsCurrent());
5441 if (state == cricket::kIceGatheringGathering) {
5442 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringGathering);
5443 } else if (state == cricket::kIceGatheringComplete) {
5444 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringComplete);
5445 }
5446}
5447
5448void PeerConnection::ReportTransportStats() {
5449 // Use a set so we don't report the same stats twice if two channels share
5450 // a transport.
5451 std::set<std::string> transport_names;
5452 if (voice_channel()) {
5453 transport_names.insert(voice_channel()->transport_name());
5454 }
5455 if (video_channel()) {
5456 transport_names.insert(video_channel()->transport_name());
5457 }
5458 if (rtp_data_channel()) {
5459 transport_names.insert(rtp_data_channel()->transport_name());
5460 }
5461 if (sctp_transport_name_) {
5462 transport_names.insert(*sctp_transport_name_);
5463 }
5464 for (const auto& name : transport_names) {
5465 cricket::TransportStats stats;
5466 if (transport_controller_->GetStats(name, &stats)) {
5467 ReportBestConnectionState(stats);
5468 ReportNegotiatedCiphers(stats);
5469 }
5470 }
5471}
5472// Walk through the ConnectionInfos to gather best connection usage
5473// for IPv4 and IPv6.
5474void PeerConnection::ReportBestConnectionState(
5475 const cricket::TransportStats& stats) {
5476 RTC_DCHECK(metrics_observer());
5477 for (cricket::TransportChannelStatsList::const_iterator it =
5478 stats.channel_stats.begin();
5479 it != stats.channel_stats.end(); ++it) {
5480 for (cricket::ConnectionInfos::const_iterator it_info =
5481 it->connection_infos.begin();
5482 it_info != it->connection_infos.end(); ++it_info) {
5483 if (!it_info->best_connection) {
5484 continue;
5485 }
5486
5487 PeerConnectionEnumCounterType type = kPeerConnectionEnumCounterMax;
5488 const cricket::Candidate& local = it_info->local_candidate;
5489 const cricket::Candidate& remote = it_info->remote_candidate;
5490
5491 // Increment the counter for IceCandidatePairType.
5492 if (local.protocol() == cricket::TCP_PROTOCOL_NAME ||
5493 (local.type() == RELAY_PORT_TYPE &&
5494 local.relay_protocol() == cricket::TCP_PROTOCOL_NAME)) {
5495 type = kEnumCounterIceCandidatePairTypeTcp;
5496 } else if (local.protocol() == cricket::UDP_PROTOCOL_NAME) {
5497 type = kEnumCounterIceCandidatePairTypeUdp;
5498 } else {
5499 RTC_CHECK(0);
5500 }
5501 metrics_observer()->IncrementEnumCounter(
5502 type, GetIceCandidatePairCounter(local, remote),
5503 kIceCandidatePairMax);
5504
5505 // Increment the counter for IP type.
5506 if (local.address().family() == AF_INET) {
5507 metrics_observer()->IncrementEnumCounter(
5508 kEnumCounterAddressFamily, kBestConnections_IPv4,
5509 kPeerConnectionAddressFamilyCounter_Max);
5510
5511 } else if (local.address().family() == AF_INET6) {
5512 metrics_observer()->IncrementEnumCounter(
5513 kEnumCounterAddressFamily, kBestConnections_IPv6,
5514 kPeerConnectionAddressFamilyCounter_Max);
5515 } else {
5516 RTC_CHECK(0);
5517 }
5518
5519 return;
5520 }
5521 }
5522}
5523
5524void PeerConnection::ReportNegotiatedCiphers(
5525 const cricket::TransportStats& stats) {
5526 RTC_DCHECK(metrics_observer());
5527 if (!dtls_enabled_ || stats.channel_stats.empty()) {
5528 return;
5529 }
5530
5531 int srtp_crypto_suite = stats.channel_stats[0].srtp_crypto_suite;
5532 int ssl_cipher_suite = stats.channel_stats[0].ssl_cipher_suite;
5533 if (srtp_crypto_suite == rtc::SRTP_INVALID_CRYPTO_SUITE &&
5534 ssl_cipher_suite == rtc::TLS_NULL_WITH_NULL_NULL) {
5535 return;
5536 }
5537
5538 PeerConnectionEnumCounterType srtp_counter_type;
5539 PeerConnectionEnumCounterType ssl_counter_type;
5540 if (stats.transport_name == cricket::CN_AUDIO) {
5541 srtp_counter_type = kEnumCounterAudioSrtpCipher;
5542 ssl_counter_type = kEnumCounterAudioSslCipher;
5543 } else if (stats.transport_name == cricket::CN_VIDEO) {
5544 srtp_counter_type = kEnumCounterVideoSrtpCipher;
5545 ssl_counter_type = kEnumCounterVideoSslCipher;
5546 } else if (stats.transport_name == cricket::CN_DATA) {
5547 srtp_counter_type = kEnumCounterDataSrtpCipher;
5548 ssl_counter_type = kEnumCounterDataSslCipher;
5549 } else {
5550 RTC_NOTREACHED();
5551 return;
5552 }
5553
5554 if (srtp_crypto_suite != rtc::SRTP_INVALID_CRYPTO_SUITE) {
5555 metrics_observer()->IncrementSparseEnumCounter(srtp_counter_type,
5556 srtp_crypto_suite);
5557 }
5558 if (ssl_cipher_suite != rtc::TLS_NULL_WITH_NULL_NULL) {
5559 metrics_observer()->IncrementSparseEnumCounter(ssl_counter_type,
5560 ssl_cipher_suite);
5561 }
5562}
5563
5564void PeerConnection::OnSentPacket_w(const rtc::SentPacket& sent_packet) {
5565 RTC_DCHECK(worker_thread()->IsCurrent());
5566 RTC_DCHECK(call_);
5567 call_->OnSentPacket(sent_packet);
5568}
5569
5570const std::string PeerConnection::GetTransportName(
5571 const std::string& content_name) {
5572 cricket::BaseChannel* channel = GetChannel(content_name);
Steve Anton6fec8802017-12-04 10:37:29 -08005573 if (channel) {
5574 return channel->transport_name();
Steve Anton75737c02017-11-06 10:37:17 -08005575 }
Steve Anton6fec8802017-12-04 10:37:29 -08005576 if (sctp_transport_) {
5577 RTC_DCHECK(sctp_content_name_);
5578 RTC_DCHECK(sctp_transport_name_);
5579 if (content_name == *sctp_content_name_) {
5580 return *sctp_transport_name_;
5581 }
5582 }
5583 // Return an empty string if failed to retrieve the transport name.
5584 return "";
Steve Anton75737c02017-11-06 10:37:17 -08005585}
5586
5587void PeerConnection::DestroyRtcpTransport_n(const std::string& transport_name) {
5588 RTC_DCHECK(network_thread()->IsCurrent());
5589 transport_controller_->DestroyDtlsTransport_n(
5590 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
5591}
5592
Steve Anton6fec8802017-12-04 10:37:29 -08005593void PeerConnection::DestroyTransceiverChannel(
5594 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
5595 transceiver) {
5596 RTC_DCHECK(transceiver);
Steve Anton75737c02017-11-06 10:37:17 -08005597
Steve Anton6fec8802017-12-04 10:37:29 -08005598 cricket::BaseChannel* channel = transceiver->internal()->channel();
5599 if (channel) {
5600 transceiver->internal()->SetChannel(nullptr);
5601 DestroyBaseChannel(channel);
Steve Anton75737c02017-11-06 10:37:17 -08005602 }
5603}
5604
5605void PeerConnection::DestroyDataChannel() {
Steve Anton6fec8802017-12-04 10:37:29 -08005606 if (rtp_data_channel_) {
5607 OnDataChannelDestroyed();
5608 DestroyBaseChannel(rtp_data_channel_);
5609 rtp_data_channel_ = nullptr;
5610 }
5611
5612 // Note: Cannot use rtc::Bind to create a functor to invoke because it will
5613 // grab a reference to this PeerConnection. If this is called from the
5614 // PeerConnection destructor, the RefCountedObject vtable will have already
5615 // been destroyed (since it is a subclass of PeerConnection) and using
5616 // rtc::Bind will cause "Pure virtual function called" error to appear.
5617
5618 if (sctp_transport_) {
5619 OnDataChannelDestroyed();
5620 network_thread()->Invoke<void>(RTC_FROM_HERE,
5621 [this] { DestroySctpTransport_n(); });
5622 }
5623}
5624
5625void PeerConnection::DestroyBaseChannel(cricket::BaseChannel* channel) {
5626 RTC_DCHECK(channel);
5627 RTC_DCHECK(channel->rtp_dtls_transport());
5628
5629 // Need to cache these before destroying the base channel so that we do not
5630 // access uninitialized memory.
5631 const std::string transport_name =
5632 channel->rtp_dtls_transport()->transport_name();
5633 const bool need_to_delete_rtcp = (channel->rtcp_dtls_transport() != nullptr);
5634
5635 switch (channel->media_type()) {
5636 case cricket::MEDIA_TYPE_AUDIO:
5637 channel_manager()->DestroyVoiceChannel(
5638 static_cast<cricket::VoiceChannel*>(channel));
5639 break;
5640 case cricket::MEDIA_TYPE_VIDEO:
5641 channel_manager()->DestroyVideoChannel(
5642 static_cast<cricket::VideoChannel*>(channel));
5643 break;
5644 case cricket::MEDIA_TYPE_DATA:
5645 channel_manager()->DestroyRtpDataChannel(
5646 static_cast<cricket::RtpDataChannel*>(channel));
5647 break;
5648 default:
5649 RTC_NOTREACHED() << "Unknown media type: " << channel->media_type();
5650 break;
5651 }
5652
5653 // |channel| can no longer be used.
5654
Steve Anton75737c02017-11-06 10:37:17 -08005655 transport_controller_->DestroyDtlsTransport(
5656 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5657 if (need_to_delete_rtcp) {
5658 transport_controller_->DestroyDtlsTransport(
5659 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
5660 }
5661}
5662
Harald Alvestrand89061872018-01-02 14:08:34 +01005663void PeerConnection::ClearStatsCache() {
5664 if (stats_collector_) {
5665 stats_collector_->ClearCachedStatsReport();
5666 }
5667}
5668
henrike@webrtc.org28e20752013-07-10 00:45:36 +00005669} // namespace webrtc