blob: 73f79c8a111e6eba14d201407f71d7e2525f7a9a [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"
Qingsi Wang93a84392018-01-30 17:13:09 -080025#include "logging/rtc_event_log/icelogger.h"
Elad Alon83ccca12017-10-04 13:18:26 +020026#include "logging/rtc_event_log/output/rtc_event_log_output_file.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020027#include "logging/rtc_event_log/rtc_event_log.h"
28#include "media/sctp/sctptransport.h"
29#include "pc/audiotrack.h"
Steve Anton75737c02017-11-06 10:37:17 -080030#include "pc/channel.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020031#include "pc/channelmanager.h"
32#include "pc/dtmfsender.h"
33#include "pc/mediastream.h"
34#include "pc/mediastreamobserver.h"
35#include "pc/remoteaudiosource.h"
Steve Anton1d03a752017-11-27 14:30:09 -080036#include "pc/rtpmediautils.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020037#include "pc/rtpreceiver.h"
38#include "pc/rtpsender.h"
Steve Anton75737c02017-11-06 10:37:17 -080039#include "pc/sctputils.h"
Steve Antona3a92c22017-12-07 10:27:41 -080040#include "pc/sdputils.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020041#include "pc/streamcollection.h"
42#include "pc/videocapturertracksource.h"
43#include "pc/videotrack.h"
44#include "rtc_base/bind.h"
45#include "rtc_base/checks.h"
46#include "rtc_base/logging.h"
Karl Wiberge40468b2017-11-22 10:42:26 +010047#include "rtc_base/numerics/safe_conversions.h"
Elad Alon83ccca12017-10-04 13:18:26 +020048#include "rtc_base/ptr_util.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020049#include "rtc_base/stringencode.h"
50#include "rtc_base/stringutils.h"
51#include "rtc_base/trace_event.h"
52#include "system_wrappers/include/clock.h"
53#include "system_wrappers/include/field_trial.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000054
Steve Anton75737c02017-11-06 10:37:17 -080055using cricket::ContentInfo;
56using cricket::ContentInfos;
57using cricket::MediaContentDescription;
58using cricket::SessionDescription;
Steve Anton5adfafd2017-12-20 16:34:00 -080059using cricket::MediaProtocolType;
Steve Anton75737c02017-11-06 10:37:17 -080060using cricket::TransportInfo;
61
62using cricket::LOCAL_PORT_TYPE;
63using cricket::STUN_PORT_TYPE;
64using cricket::RELAY_PORT_TYPE;
65using cricket::PRFLX_PORT_TYPE;
66
Steve Antonba818672017-11-06 10:21:57 -080067namespace webrtc {
68
Steve Anton75737c02017-11-06 10:37:17 -080069// Error messages
70const char kBundleWithoutRtcpMux[] =
71 "rtcp-mux must be enabled when BUNDLE "
72 "is enabled.";
Steve Anton75737c02017-11-06 10:37:17 -080073const char kInvalidCandidates[] = "Description contains invalid candidates.";
74const char kInvalidSdp[] = "Invalid session description.";
75const char kMlineMismatchInAnswer[] =
76 "The order of m-lines in answer doesn't match order in offer. Rejecting "
77 "answer.";
78const char kMlineMismatchInSubsequentOffer[] =
79 "The order of m-lines in subsequent offer doesn't match order from "
80 "previous offer/answer.";
Steve Anton75737c02017-11-06 10:37:17 -080081const char kSdpWithoutDtlsFingerprint[] =
82 "Called with SDP without DTLS fingerprint.";
83const char kSdpWithoutSdesCrypto[] = "Called with SDP without SDES crypto.";
84const char kSdpWithoutIceUfragPwd[] =
85 "Called with SDP without ice-ufrag and ice-pwd.";
86const char kSessionError[] = "Session error code: ";
87const char kSessionErrorDesc[] = "Session error description: ";
88const char kDtlsSrtpSetupFailureRtp[] =
89 "Couldn't set up DTLS-SRTP on RTP channel.";
90const char kDtlsSrtpSetupFailureRtcp[] =
91 "Couldn't set up DTLS-SRTP on RTCP channel.";
92const char kEnableBundleFailed[] = "Failed to enable BUNDLE.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +000093
Steve Anton75737c02017-11-06 10:37:17 -080094namespace {
henrike@webrtc.org28e20752013-07-10 00:45:36 +000095
deadbeefab9b2d12015-10-14 11:33:11 -070096static const char kDefaultStreamLabel[] = "default";
Steve Anton4171afb2017-11-20 10:20:22 -080097static const char kDefaultAudioSenderId[] = "defaulta0";
98static const char kDefaultVideoSenderId[] = "defaultv0";
deadbeefab9b2d12015-10-14 11:33:11 -070099
zhihuang8f65cdf2016-05-06 18:40:30 -0700100// The length of RTCP CNAMEs.
101static const int kRtcpCnameLength = 16;
102
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000103enum {
wu@webrtc.org91053e72013-08-10 07:18:04 +0000104 MSG_SET_SESSIONDESCRIPTION_SUCCESS = 0,
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000105 MSG_SET_SESSIONDESCRIPTION_FAILED,
deadbeefab9b2d12015-10-14 11:33:11 -0700106 MSG_CREATE_SESSIONDESCRIPTION_FAILED,
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000107 MSG_GETSTATS,
deadbeefbd292462015-12-14 18:15:29 -0800108 MSG_FREE_DATACHANNELS,
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000109};
110
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000111struct SetSessionDescriptionMsg : public rtc::MessageData {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000112 explicit SetSessionDescriptionMsg(
113 webrtc::SetSessionDescriptionObserver* observer)
114 : observer(observer) {
115 }
116
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000117 rtc::scoped_refptr<webrtc::SetSessionDescriptionObserver> observer;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000118 std::string error;
119};
120
deadbeefab9b2d12015-10-14 11:33:11 -0700121struct CreateSessionDescriptionMsg : public rtc::MessageData {
122 explicit CreateSessionDescriptionMsg(
123 webrtc::CreateSessionDescriptionObserver* observer)
124 : observer(observer) {}
125
126 rtc::scoped_refptr<webrtc::CreateSessionDescriptionObserver> observer;
127 std::string error;
128};
129
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000130struct GetStatsMsg : public rtc::MessageData {
tommi@webrtc.org5b06b062014-08-15 08:38:30 +0000131 GetStatsMsg(webrtc::StatsObserver* observer,
132 webrtc::MediaStreamTrackInterface* track)
133 : observer(observer), track(track) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000134 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000135 rtc::scoped_refptr<webrtc::StatsObserver> observer;
tommi@webrtc.org5b06b062014-08-15 08:38:30 +0000136 rtc::scoped_refptr<webrtc::MediaStreamTrackInterface> track;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000137};
138
deadbeefab9b2d12015-10-14 11:33:11 -0700139// Check if we can send |new_stream| on a PeerConnection.
140bool CanAddLocalMediaStream(webrtc::StreamCollectionInterface* current_streams,
141 webrtc::MediaStreamInterface* new_stream) {
142 if (!new_stream || !current_streams) {
143 return false;
144 }
145 if (current_streams->find(new_stream->label()) != nullptr) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100146 RTC_LOG(LS_ERROR) << "MediaStream with label " << new_stream->label()
147 << " is already added.";
deadbeefab9b2d12015-10-14 11:33:11 -0700148 return false;
149 }
150 return true;
151}
152
deadbeef5e97fb52015-10-15 12:49:08 -0700153// If the direction is "recvonly" or "inactive", treat the description
154// as containing no streams.
155// See: https://code.google.com/p/webrtc/issues/detail?id=5054
156std::vector<cricket::StreamParams> GetActiveStreams(
157 const cricket::MediaContentDescription* desc) {
Steve Anton4e70a722017-11-28 14:57:10 -0800158 return RtpTransceiverDirectionHasSend(desc->direction())
deadbeef5e97fb52015-10-15 12:49:08 -0700159 ? desc->streams()
160 : std::vector<cricket::StreamParams>();
161}
162
deadbeefab9b2d12015-10-14 11:33:11 -0700163bool IsValidOfferToReceiveMedia(int value) {
164 typedef PeerConnectionInterface::RTCOfferAnswerOptions Options;
165 return (value >= Options::kUndefined) &&
166 (value <= Options::kMaxOfferToReceiveMedia);
167}
168
zhihuang1c378ed2017-08-17 14:10:50 -0700169// Add options to |[audio/video]_media_description_options| from |senders|.
170void AddRtpSenderOptions(
deadbeefa601f5c2016-06-06 14:27:39 -0700171 const std::vector<rtc::scoped_refptr<
172 RtpSenderProxyWithInternal<RtpSenderInternal>>>& senders,
zhihuang1c378ed2017-08-17 14:10:50 -0700173 cricket::MediaDescriptionOptions* audio_media_description_options,
174 cricket::MediaDescriptionOptions* video_media_description_options) {
olka3c747662017-08-17 06:50:32 -0700175 for (const auto& sender : senders) {
zhihuang1c378ed2017-08-17 14:10:50 -0700176 if (sender->media_type() == cricket::MEDIA_TYPE_AUDIO) {
177 if (audio_media_description_options) {
178 audio_media_description_options->AddAudioSender(
Steve Anton8ffb9c32017-08-31 15:45:38 -0700179 sender->id(), sender->internal()->stream_ids());
zhihuang1c378ed2017-08-17 14:10:50 -0700180 }
181 } else {
182 RTC_DCHECK(sender->media_type() == cricket::MEDIA_TYPE_VIDEO);
183 if (video_media_description_options) {
184 video_media_description_options->AddVideoSender(
Steve Anton8ffb9c32017-08-31 15:45:38 -0700185 sender->id(), sender->internal()->stream_ids(), 1);
zhihuang1c378ed2017-08-17 14:10:50 -0700186 }
187 }
zhihuanga77e6bb2017-08-14 18:17:48 -0700188 }
zhihuang1c378ed2017-08-17 14:10:50 -0700189}
olka3c747662017-08-17 06:50:32 -0700190
zhihuang1c378ed2017-08-17 14:10:50 -0700191// Add options to |session_options| from |rtp_data_channels|.
192void AddRtpDataChannelOptions(
193 const std::map<std::string, rtc::scoped_refptr<DataChannel>>&
194 rtp_data_channels,
195 cricket::MediaDescriptionOptions* data_media_description_options) {
196 if (!data_media_description_options) {
197 return;
198 }
deadbeefab9b2d12015-10-14 11:33:11 -0700199 // Check for data channels.
200 for (const auto& kv : rtp_data_channels) {
201 const DataChannel* channel = kv.second;
202 if (channel->state() == DataChannel::kConnecting ||
203 channel->state() == DataChannel::kOpen) {
zhihuang1c378ed2017-08-17 14:10:50 -0700204 // Legacy RTP data channels are signaled with the track/stream ID set to
205 // the data channel's label.
206 data_media_description_options->AddRtpDataChannel(channel->label(),
207 channel->label());
deadbeefab9b2d12015-10-14 11:33:11 -0700208 }
209 }
210}
211
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700212uint32_t ConvertIceTransportTypeToCandidateFilter(
213 PeerConnectionInterface::IceTransportsType type) {
214 switch (type) {
215 case PeerConnectionInterface::kNone:
216 return cricket::CF_NONE;
217 case PeerConnectionInterface::kRelay:
218 return cricket::CF_RELAY;
219 case PeerConnectionInterface::kNoHost:
220 return (cricket::CF_ALL & ~cricket::CF_HOST);
221 case PeerConnectionInterface::kAll:
222 return cricket::CF_ALL;
223 default:
nissec80e7412017-01-11 05:56:46 -0800224 RTC_NOTREACHED();
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700225 }
226 return cricket::CF_NONE;
227}
228
deadbeef293e9262017-01-11 12:28:30 -0800229// Helper to set an error and return from a method.
230bool SafeSetError(webrtc::RTCErrorType type, webrtc::RTCError* error) {
231 if (error) {
232 error->set_type(type);
233 }
234 return type == webrtc::RTCErrorType::NONE;
235}
236
Steve Anton038834f2017-07-14 15:59:59 -0700237bool SafeSetError(webrtc::RTCError error, webrtc::RTCError* error_out) {
238 if (error_out) {
239 *error_out = std::move(error);
240 }
241 return error.ok();
242}
243
Steve Antonba818672017-11-06 10:21:57 -0800244std::string GetSignalingStateString(
245 PeerConnectionInterface::SignalingState state) {
246 switch (state) {
247 case PeerConnectionInterface::kStable:
248 return "kStable";
249 case PeerConnectionInterface::kHaveLocalOffer:
250 return "kHaveLocalOffer";
251 case PeerConnectionInterface::kHaveLocalPrAnswer:
252 return "kHavePrAnswer";
253 case PeerConnectionInterface::kHaveRemoteOffer:
254 return "kHaveRemoteOffer";
255 case PeerConnectionInterface::kHaveRemotePrAnswer:
256 return "kHaveRemotePrAnswer";
257 case PeerConnectionInterface::kClosed:
258 return "kClosed";
259 }
260 RTC_NOTREACHED();
261 return "";
262}
deadbeef0a6c4ca2015-10-06 11:38:28 -0700263
Steve Anton75737c02017-11-06 10:37:17 -0800264IceCandidatePairType GetIceCandidatePairCounter(
265 const cricket::Candidate& local,
266 const cricket::Candidate& remote) {
267 const auto& l = local.type();
268 const auto& r = remote.type();
269 const auto& host = LOCAL_PORT_TYPE;
270 const auto& srflx = STUN_PORT_TYPE;
271 const auto& relay = RELAY_PORT_TYPE;
272 const auto& prflx = PRFLX_PORT_TYPE;
273 if (l == host && r == host) {
274 bool local_private = IPIsPrivate(local.address().ipaddr());
275 bool remote_private = IPIsPrivate(remote.address().ipaddr());
276 if (local_private) {
277 if (remote_private) {
278 return kIceCandidatePairHostPrivateHostPrivate;
279 } else {
280 return kIceCandidatePairHostPrivateHostPublic;
281 }
282 } else {
283 if (remote_private) {
284 return kIceCandidatePairHostPublicHostPrivate;
285 } else {
286 return kIceCandidatePairHostPublicHostPublic;
287 }
288 }
289 }
290 if (l == host && r == srflx)
291 return kIceCandidatePairHostSrflx;
292 if (l == host && r == relay)
293 return kIceCandidatePairHostRelay;
294 if (l == host && r == prflx)
295 return kIceCandidatePairHostPrflx;
296 if (l == srflx && r == host)
297 return kIceCandidatePairSrflxHost;
298 if (l == srflx && r == srflx)
299 return kIceCandidatePairSrflxSrflx;
300 if (l == srflx && r == relay)
301 return kIceCandidatePairSrflxRelay;
302 if (l == srflx && r == prflx)
303 return kIceCandidatePairSrflxPrflx;
304 if (l == relay && r == host)
305 return kIceCandidatePairRelayHost;
306 if (l == relay && r == srflx)
307 return kIceCandidatePairRelaySrflx;
308 if (l == relay && r == relay)
309 return kIceCandidatePairRelayRelay;
310 if (l == relay && r == prflx)
311 return kIceCandidatePairRelayPrflx;
312 if (l == prflx && r == host)
313 return kIceCandidatePairPrflxHost;
314 if (l == prflx && r == srflx)
315 return kIceCandidatePairPrflxSrflx;
316 if (l == prflx && r == relay)
317 return kIceCandidatePairPrflxRelay;
318 return kIceCandidatePairMax;
319}
320
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800321// Logic to decide if an m= section can be recycled. This means that the new
322// m= section is not rejected, but the old local or remote m= section is
323// rejected. |old_content_one| and |old_content_two| refer to the m= section
324// of the old remote and old local descriptions in no particular order.
325// We need to check both the old local and remote because either
326// could be the most current from the latest negotation.
327bool IsMediaSectionBeingRecycled(SdpType type,
328 const ContentInfo& content,
329 const ContentInfo* old_content_one,
330 const ContentInfo* old_content_two) {
331 return type == SdpType::kOffer && !content.rejected &&
332 ((old_content_one && old_content_one->rejected) ||
333 (old_content_two && old_content_two->rejected));
334}
335
Steve Anton75737c02017-11-06 10:37:17 -0800336// Verify that the order of media sections in |new_desc| matches
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800337// |current_desc|. The number of m= sections in |new_desc| should be no
338// less than |current_desc|. In the case of checking an answer's
339// |new_desc|, the |current_desc| is the last offer that was set as the
340// local or remote. In the case of checking an offer's |new_desc| we
341// check against the local and remote descriptions stored from the last
342// negotiation, because either of these could be the most up to date for
343// possible rejected m sections. These are the |current_desc| and
344// |secondary_current_desc|.
345bool MediaSectionsInSameOrder(const SessionDescription& current_desc,
346 const SessionDescription* secondary_current_desc,
347 const SessionDescription& new_desc,
348 const SdpType type) {
349 if (current_desc.contents().size() > new_desc.contents().size()) {
Steve Anton75737c02017-11-06 10:37:17 -0800350 return false;
351 }
352
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800353 for (size_t i = 0; i < current_desc.contents().size(); ++i) {
354 const cricket::ContentInfo* secondary_content_info = nullptr;
355 if (secondary_current_desc &&
356 i < secondary_current_desc->contents().size()) {
357 secondary_content_info = &secondary_current_desc->contents()[i];
358 }
359 if (IsMediaSectionBeingRecycled(type, new_desc.contents()[i],
360 &current_desc.contents()[i],
361 secondary_content_info)) {
362 // For new offer descriptions, if the media section can be recycled, it's
363 // valid for the MID and media type to change.
Steve Antondcc3c022017-12-22 16:02:54 -0800364 continue;
365 }
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800366 if (new_desc.contents()[i].name != current_desc.contents()[i].name) {
Steve Anton75737c02017-11-06 10:37:17 -0800367 return false;
368 }
369 const MediaContentDescription* new_desc_mdesc =
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800370 new_desc.contents()[i].media_description();
371 const MediaContentDescription* current_desc_mdesc =
372 current_desc.contents()[i].media_description();
373 if (new_desc_mdesc->type() != current_desc_mdesc->type()) {
Steve Anton75737c02017-11-06 10:37:17 -0800374 return false;
375 }
376 }
377 return true;
378}
379
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800380bool MediaSectionsHaveSameCount(const SessionDescription& desc1,
381 const SessionDescription& desc2) {
382 return desc1.contents().size() == desc2.contents().size();
Steve Anton75737c02017-11-06 10:37:17 -0800383}
384
385// Checks that each non-rejected content has SDES crypto keys or a DTLS
386// fingerprint, unless it's in a BUNDLE group, in which case only the
387// BUNDLE-tag section (first media section/description in the BUNDLE group)
388// needs a ufrag and pwd. Mismatches, such as replying with a DTLS fingerprint
389// to SDES keys, will be caught in JsepTransport negotiation, and backstopped
390// by Channel's |srtp_required| check.
Harald Alvestrand194939b2018-01-24 16:04:13 +0100391RTCError VerifyCrypto(const SessionDescription* desc,
392 bool dtls_enabled,
393 rtc::scoped_refptr<webrtc::UMAObserver> uma_observer) {
Steve Anton75737c02017-11-06 10:37:17 -0800394 const cricket::ContentGroup* bundle =
395 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton8a006912017-12-04 15:25:56 -0800396 for (const cricket::ContentInfo& content_info : desc->contents()) {
397 if (content_info.rejected) {
Steve Anton75737c02017-11-06 10:37:17 -0800398 continue;
399 }
Steve Anton8a006912017-12-04 15:25:56 -0800400 const std::string& mid = content_info.name;
401 if (bundle && bundle->HasContentName(mid) &&
402 mid != *(bundle->FirstContentName())) {
Steve Anton75737c02017-11-06 10:37:17 -0800403 // This isn't the first media section in the BUNDLE group, so it's not
404 // required to have crypto attributes, since only the crypto attributes
405 // from the first section actually get used.
406 continue;
407 }
408
409 // If the content isn't rejected or bundled into another m= section, crypto
410 // must be present.
Steve Antonb1c1de12017-12-21 15:14:30 -0800411 const MediaContentDescription* media = content_info.media_description();
Steve Anton8a006912017-12-04 15:25:56 -0800412 const TransportInfo* tinfo = desc->GetTransportInfoByName(mid);
Steve Anton75737c02017-11-06 10:37:17 -0800413 if (!media || !tinfo) {
414 // Something is not right.
Steve Anton8a006912017-12-04 15:25:56 -0800415 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidSdp);
Steve Anton75737c02017-11-06 10:37:17 -0800416 }
417 if (dtls_enabled) {
418 if (!tinfo->description.identity_fingerprint) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100419 RTC_LOG(LS_WARNING)
420 << "Session description must have DTLS fingerprint if "
421 "DTLS enabled.";
Steve Anton8a006912017-12-04 15:25:56 -0800422 return RTCError(RTCErrorType::INVALID_PARAMETER,
423 kSdpWithoutDtlsFingerprint);
Steve Anton75737c02017-11-06 10:37:17 -0800424 }
Harald Alvestrand194939b2018-01-24 16:04:13 +0100425 if (uma_observer) {
426 uma_observer->IncrementEnumCounter(webrtc::kEnumCounterKeyProtocol,
427 webrtc::kEnumCounterKeyProtocolDtls,
428 webrtc::kEnumCounterKeyProtocolMax);
429 }
Steve Anton75737c02017-11-06 10:37:17 -0800430 } else {
431 if (media->cryptos().empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100432 RTC_LOG(LS_WARNING)
Steve Anton75737c02017-11-06 10:37:17 -0800433 << "Session description must have SDES when DTLS disabled.";
Steve Anton8a006912017-12-04 15:25:56 -0800434 return RTCError(RTCErrorType::INVALID_PARAMETER, kSdpWithoutSdesCrypto);
Steve Anton75737c02017-11-06 10:37:17 -0800435 }
Harald Alvestrand194939b2018-01-24 16:04:13 +0100436 if (uma_observer) {
437 uma_observer->IncrementEnumCounter(webrtc::kEnumCounterKeyProtocol,
438 webrtc::kEnumCounterKeyProtocolSdes,
439 webrtc::kEnumCounterKeyProtocolMax);
440 }
Steve Anton75737c02017-11-06 10:37:17 -0800441 }
442 }
Steve Anton8a006912017-12-04 15:25:56 -0800443 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -0800444}
445
446// Checks that each non-rejected content has ice-ufrag and ice-pwd set, unless
447// it's in a BUNDLE group, in which case only the BUNDLE-tag section (first
448// media section/description in the BUNDLE group) needs a ufrag and pwd.
449bool VerifyIceUfragPwdPresent(const SessionDescription* desc) {
450 const cricket::ContentGroup* bundle =
451 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton8a006912017-12-04 15:25:56 -0800452 for (const cricket::ContentInfo& content_info : desc->contents()) {
453 if (content_info.rejected) {
Steve Anton75737c02017-11-06 10:37:17 -0800454 continue;
455 }
Steve Anton8a006912017-12-04 15:25:56 -0800456 const std::string& mid = content_info.name;
457 if (bundle && bundle->HasContentName(mid) &&
458 mid != *(bundle->FirstContentName())) {
Steve Anton75737c02017-11-06 10:37:17 -0800459 // This isn't the first media section in the BUNDLE group, so it's not
460 // required to have ufrag/password, since only the ufrag/password from
461 // the first section actually get used.
462 continue;
463 }
464
465 // If the content isn't rejected or bundled into another m= section,
466 // ice-ufrag and ice-pwd must be present.
Steve Anton8a006912017-12-04 15:25:56 -0800467 const TransportInfo* tinfo = desc->GetTransportInfoByName(mid);
Steve Anton75737c02017-11-06 10:37:17 -0800468 if (!tinfo) {
469 // Something is not right.
Mirko Bonadei675513b2017-11-09 11:09:25 +0100470 RTC_LOG(LS_ERROR) << kInvalidSdp;
Steve Anton75737c02017-11-06 10:37:17 -0800471 return false;
472 }
473 if (tinfo->description.ice_ufrag.empty() ||
474 tinfo->description.ice_pwd.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100475 RTC_LOG(LS_ERROR) << "Session description must have ice ufrag and pwd.";
Steve Anton75737c02017-11-06 10:37:17 -0800476 return false;
477 }
478 }
479 return true;
480}
481
482bool GetTrackIdBySsrc(const SessionDescription* session_description,
483 uint32_t ssrc,
484 std::string* track_id) {
485 RTC_DCHECK(track_id != NULL);
486
Steve Antonb1c1de12017-12-21 15:14:30 -0800487 const cricket::AudioContentDescription* audio_desc =
488 cricket::GetFirstAudioContentDescription(session_description);
489 if (audio_desc) {
490 const auto* found = cricket::GetStreamBySsrc(audio_desc->streams(), ssrc);
Steve Anton75737c02017-11-06 10:37:17 -0800491 if (found) {
492 *track_id = found->id;
493 return true;
494 }
495 }
496
Steve Antonb1c1de12017-12-21 15:14:30 -0800497 const cricket::VideoContentDescription* video_desc =
498 cricket::GetFirstVideoContentDescription(session_description);
499 if (video_desc) {
500 const auto* found = cricket::GetStreamBySsrc(video_desc->streams(), ssrc);
Steve Anton75737c02017-11-06 10:37:17 -0800501 if (found) {
502 *track_id = found->id;
503 return true;
504 }
505 }
506 return false;
507}
508
509// Get the SCTP port out of a SessionDescription.
510// Return -1 if not found.
511int GetSctpPort(const SessionDescription* session_description) {
Steve Antonb1c1de12017-12-21 15:14:30 -0800512 const cricket::DataContentDescription* data_desc =
513 GetFirstDataContentDescription(session_description);
514 RTC_DCHECK(data_desc);
515 if (!data_desc) {
Steve Anton75737c02017-11-06 10:37:17 -0800516 return -1;
517 }
Steve Anton75737c02017-11-06 10:37:17 -0800518 std::string value;
519 cricket::DataCodec match_pattern(cricket::kGoogleSctpDataCodecPlType,
520 cricket::kGoogleSctpDataCodecName);
Steve Antonb1c1de12017-12-21 15:14:30 -0800521 for (const cricket::DataCodec& codec : data_desc->codecs()) {
Steve Anton75737c02017-11-06 10:37:17 -0800522 if (!codec.Matches(match_pattern)) {
523 continue;
524 }
525 if (codec.GetParam(cricket::kCodecParamPort, &value)) {
526 return rtc::FromString<int>(value);
527 }
528 }
529 return -1;
530}
531
Steve Anton75737c02017-11-06 10:37:17 -0800532// Returns true if |new_desc| requests an ICE restart (i.e., new ufrag/pwd).
533bool CheckForRemoteIceRestart(const SessionDescriptionInterface* old_desc,
534 const SessionDescriptionInterface* new_desc,
535 const std::string& content_name) {
536 if (!old_desc) {
537 return false;
538 }
539 const SessionDescription* new_sd = new_desc->description();
540 const SessionDescription* old_sd = old_desc->description();
541 const ContentInfo* cinfo = new_sd->GetContentByName(content_name);
542 if (!cinfo || cinfo->rejected) {
543 return false;
544 }
545 // If the content isn't rejected, check if ufrag and password has changed.
546 const cricket::TransportDescription* new_transport_desc =
547 new_sd->GetTransportDescriptionByName(content_name);
548 const cricket::TransportDescription* old_transport_desc =
549 old_sd->GetTransportDescriptionByName(content_name);
550 if (!new_transport_desc || !old_transport_desc) {
551 // No transport description exists. This is not an ICE restart.
552 return false;
553 }
554 if (cricket::IceCredentialsChanged(
555 old_transport_desc->ice_ufrag, old_transport_desc->ice_pwd,
556 new_transport_desc->ice_ufrag, new_transport_desc->ice_pwd)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100557 RTC_LOG(LS_INFO) << "Remote peer requests ICE restart for " << content_name
558 << ".";
Steve Anton75737c02017-11-06 10:37:17 -0800559 return true;
560 }
561 return false;
562}
563
Steve Anton80dd7b52018-02-16 17:08:42 -0800564// Generates a string error message for SetLocalDescription/SetRemoteDescription
565// from an RTCError.
566std::string GetSetDescriptionErrorMessage(cricket::ContentSource source,
567 SdpType type,
568 const RTCError& error) {
569 std::ostringstream oss;
570 oss << "Failed to set " << (source == cricket::CS_LOCAL ? "local" : "remote")
571 << " " << SdpTypeToString(type) << " sdp: " << error.message();
572 return oss.str();
573}
574
Steve Anton75737c02017-11-06 10:37:17 -0800575} // namespace
576
Henrik Boström31638672017-11-23 17:48:32 +0100577// Upon completion, posts a task to execute the callback of the
578// SetSessionDescriptionObserver asynchronously on the same thread. At this
579// point, the state of the peer connection might no longer reflect the effects
580// of the SetRemoteDescription operation, as the peer connection could have been
581// modified during the post.
582// TODO(hbos): Remove this class once we remove the version of
583// PeerConnectionInterface::SetRemoteDescription() that takes a
584// SetSessionDescriptionObserver as an argument.
585class PeerConnection::SetRemoteDescriptionObserverAdapter
586 : public rtc::RefCountedObject<SetRemoteDescriptionObserverInterface> {
587 public:
588 SetRemoteDescriptionObserverAdapter(
589 rtc::scoped_refptr<PeerConnection> pc,
590 rtc::scoped_refptr<SetSessionDescriptionObserver> wrapper)
591 : pc_(std::move(pc)), wrapper_(std::move(wrapper)) {}
592
593 // SetRemoteDescriptionObserverInterface implementation.
594 void OnSetRemoteDescriptionComplete(RTCError error) override {
595 if (error.ok())
596 pc_->PostSetSessionDescriptionSuccess(wrapper_);
597 else
598 pc_->PostSetSessionDescriptionFailure(wrapper_, error.message());
599 }
600
601 private:
602 rtc::scoped_refptr<PeerConnection> pc_;
603 rtc::scoped_refptr<SetSessionDescriptionObserver> wrapper_;
604};
605
deadbeef293e9262017-01-11 12:28:30 -0800606bool PeerConnectionInterface::RTCConfiguration::operator==(
607 const PeerConnectionInterface::RTCConfiguration& o) const {
608 // This static_assert prevents us from accidentally breaking operator==.
Steve Anton300bf8e2017-07-14 10:13:10 -0700609 // Note: Order matters! Fields must be ordered the same as RTCConfiguration.
deadbeef293e9262017-01-11 12:28:30 -0800610 struct stuff_being_tested_for_equality {
Magnus Jedvert3beb2072017-07-14 14:23:56 +0000611 IceServers servers;
Steve Anton300bf8e2017-07-14 10:13:10 -0700612 IceTransportsType type;
deadbeef293e9262017-01-11 12:28:30 -0800613 BundlePolicy bundle_policy;
614 RtcpMuxPolicy rtcp_mux_policy;
Steve Anton300bf8e2017-07-14 10:13:10 -0700615 std::vector<rtc::scoped_refptr<rtc::RTCCertificate>> certificates;
616 int ice_candidate_pool_size;
617 bool disable_ipv6;
618 bool disable_ipv6_on_wifi;
deadbeefd21eab32017-07-26 16:50:11 -0700619 int max_ipv6_networks;
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +0100620 bool disable_link_local_networks;
Steve Anton300bf8e2017-07-14 10:13:10 -0700621 bool enable_rtp_data_channel;
622 rtc::Optional<int> screencast_min_bitrate;
623 rtc::Optional<bool> combined_audio_video_bwe;
624 rtc::Optional<bool> enable_dtls_srtp;
deadbeef293e9262017-01-11 12:28:30 -0800625 TcpCandidatePolicy tcp_candidate_policy;
626 CandidateNetworkPolicy candidate_network_policy;
627 int audio_jitter_buffer_max_packets;
628 bool audio_jitter_buffer_fast_accelerate;
629 int ice_connection_receiving_timeout;
630 int ice_backup_candidate_pair_ping_interval;
631 ContinualGatheringPolicy continual_gathering_policy;
deadbeef293e9262017-01-11 12:28:30 -0800632 bool prioritize_most_likely_ice_candidate_pairs;
633 struct cricket::MediaConfig media_config;
deadbeef293e9262017-01-11 12:28:30 -0800634 bool prune_turn_ports;
635 bool presume_writable_when_fully_relayed;
636 bool enable_ice_renomination;
637 bool redetermine_role_on_ice_restart;
skvlad51072462017-02-02 11:50:14 -0800638 rtc::Optional<int> ice_check_min_interval;
Steve Anton300bf8e2017-07-14 10:13:10 -0700639 rtc::Optional<rtc::IntervalRange> ice_regather_interval_range;
Jonas Orelandbdcee282017-10-10 14:01:40 +0200640 webrtc::TurnCustomizer* turn_customizer;
Steve Anton79e79602017-11-20 10:25:56 -0800641 SdpSemantics sdp_semantics;
Qingsi Wang9a5c6f82018-02-01 10:38:40 -0800642 rtc::Optional<rtc::AdapterType> network_preference;
deadbeef293e9262017-01-11 12:28:30 -0800643 };
644 static_assert(sizeof(stuff_being_tested_for_equality) == sizeof(*this),
645 "Did you add something to RTCConfiguration and forget to "
646 "update operator==?");
647 return type == o.type && servers == o.servers &&
648 bundle_policy == o.bundle_policy &&
649 rtcp_mux_policy == o.rtcp_mux_policy &&
650 tcp_candidate_policy == o.tcp_candidate_policy &&
651 candidate_network_policy == o.candidate_network_policy &&
652 audio_jitter_buffer_max_packets == o.audio_jitter_buffer_max_packets &&
653 audio_jitter_buffer_fast_accelerate ==
654 o.audio_jitter_buffer_fast_accelerate &&
655 ice_connection_receiving_timeout ==
656 o.ice_connection_receiving_timeout &&
657 ice_backup_candidate_pair_ping_interval ==
658 o.ice_backup_candidate_pair_ping_interval &&
659 continual_gathering_policy == o.continual_gathering_policy &&
660 certificates == o.certificates &&
661 prioritize_most_likely_ice_candidate_pairs ==
662 o.prioritize_most_likely_ice_candidate_pairs &&
663 media_config == o.media_config && disable_ipv6 == o.disable_ipv6 &&
zhihuangb09b3f92017-03-07 14:40:51 -0800664 disable_ipv6_on_wifi == o.disable_ipv6_on_wifi &&
deadbeefd21eab32017-07-26 16:50:11 -0700665 max_ipv6_networks == o.max_ipv6_networks &&
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +0100666 disable_link_local_networks == o.disable_link_local_networks &&
deadbeef293e9262017-01-11 12:28:30 -0800667 enable_rtp_data_channel == o.enable_rtp_data_channel &&
deadbeef293e9262017-01-11 12:28:30 -0800668 screencast_min_bitrate == o.screencast_min_bitrate &&
669 combined_audio_video_bwe == o.combined_audio_video_bwe &&
670 enable_dtls_srtp == o.enable_dtls_srtp &&
671 ice_candidate_pool_size == o.ice_candidate_pool_size &&
672 prune_turn_ports == o.prune_turn_ports &&
673 presume_writable_when_fully_relayed ==
674 o.presume_writable_when_fully_relayed &&
675 enable_ice_renomination == o.enable_ice_renomination &&
skvlad51072462017-02-02 11:50:14 -0800676 redetermine_role_on_ice_restart == o.redetermine_role_on_ice_restart &&
Steve Anton300bf8e2017-07-14 10:13:10 -0700677 ice_check_min_interval == o.ice_check_min_interval &&
Jonas Orelandbdcee282017-10-10 14:01:40 +0200678 ice_regather_interval_range == o.ice_regather_interval_range &&
Steve Anton79e79602017-11-20 10:25:56 -0800679 turn_customizer == o.turn_customizer &&
Qingsi Wang9a5c6f82018-02-01 10:38:40 -0800680 sdp_semantics == o.sdp_semantics &&
681 network_preference == o.network_preference;
deadbeef293e9262017-01-11 12:28:30 -0800682}
683
684bool PeerConnectionInterface::RTCConfiguration::operator!=(
685 const PeerConnectionInterface::RTCConfiguration& o) const {
686 return !(*this == o);
deadbeef3edec7c2016-12-10 11:44:26 -0800687}
688
zhihuang8f65cdf2016-05-06 18:40:30 -0700689// Generate a RTCP CNAME when a PeerConnection is created.
690std::string GenerateRtcpCname() {
691 std::string cname;
692 if (!rtc::CreateRandomString(kRtcpCnameLength, &cname)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100693 RTC_LOG(LS_ERROR) << "Failed to generate CNAME.";
nisseeb4ca4e2017-01-12 02:24:27 -0800694 RTC_NOTREACHED();
zhihuang8f65cdf2016-05-06 18:40:30 -0700695 }
696 return cname;
697}
698
zhihuang1c378ed2017-08-17 14:10:50 -0700699bool ValidateOfferAnswerOptions(
700 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options) {
701 return IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_audio) &&
702 IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_video);
olka3c747662017-08-17 06:50:32 -0700703}
704
zhihuang1c378ed2017-08-17 14:10:50 -0700705// From |rtc_options|, fill parts of |session_options| shared by all generated
706// m= sections (in other words, nothing that involves a map/array).
707void ExtractSharedMediaSessionOptions(
708 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options,
709 cricket::MediaSessionOptions* session_options) {
710 session_options->vad_enabled = rtc_options.voice_activity_detection;
711 session_options->bundle_enabled = rtc_options.use_rtp_mux;
712}
zhihuanga77e6bb2017-08-14 18:17:48 -0700713
zhihuang1c378ed2017-08-17 14:10:50 -0700714bool ConvertConstraintsToOfferAnswerOptions(
715 const MediaConstraintsInterface* constraints,
716 PeerConnectionInterface::RTCOfferAnswerOptions* offer_answer_options) {
olka3c747662017-08-17 06:50:32 -0700717 if (!constraints) {
718 return true;
719 }
zhihuang1c378ed2017-08-17 14:10:50 -0700720
721 bool value = false;
722 size_t mandatory_constraints_satisfied = 0;
723
724 if (FindConstraint(constraints,
725 MediaConstraintsInterface::kOfferToReceiveAudio, &value,
726 &mandatory_constraints_satisfied)) {
727 offer_answer_options->offer_to_receive_audio =
728 value ? PeerConnectionInterface::RTCOfferAnswerOptions::
729 kOfferToReceiveMediaTrue
730 : 0;
731 }
732
733 if (FindConstraint(constraints,
734 MediaConstraintsInterface::kOfferToReceiveVideo, &value,
735 &mandatory_constraints_satisfied)) {
736 offer_answer_options->offer_to_receive_video =
737 value ? PeerConnectionInterface::RTCOfferAnswerOptions::
738 kOfferToReceiveMediaTrue
739 : 0;
740 }
741 if (FindConstraint(constraints,
742 MediaConstraintsInterface::kVoiceActivityDetection, &value,
743 &mandatory_constraints_satisfied)) {
744 offer_answer_options->voice_activity_detection = value;
745 }
746 if (FindConstraint(constraints, MediaConstraintsInterface::kUseRtpMux, &value,
747 &mandatory_constraints_satisfied)) {
748 offer_answer_options->use_rtp_mux = value;
749 }
750 if (FindConstraint(constraints, MediaConstraintsInterface::kIceRestart,
751 &value, &mandatory_constraints_satisfied)) {
752 offer_answer_options->ice_restart = value;
753 }
754
deadbeefab9b2d12015-10-14 11:33:11 -0700755 return mandatory_constraints_satisfied == constraints->GetMandatory().size();
756}
757
zhihuang38ede132017-06-15 12:52:32 -0700758PeerConnection::PeerConnection(PeerConnectionFactory* factory,
759 std::unique_ptr<RtcEventLog> event_log,
760 std::unique_ptr<Call> call)
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000761 : factory_(factory),
zhihuang38ede132017-06-15 12:52:32 -0700762 event_log_(std::move(event_log)),
zhihuang8f65cdf2016-05-06 18:40:30 -0700763 rtcp_cname_(GenerateRtcpCname()),
deadbeefab9b2d12015-10-14 11:33:11 -0700764 local_streams_(StreamCollection::Create()),
zhihuang38ede132017-06-15 12:52:32 -0700765 remote_streams_(StreamCollection::Create()),
766 call_(std::move(call)) {}
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000767
768PeerConnection::~PeerConnection() {
Peter Boström1a9d6152015-12-08 22:15:17 +0100769 TRACE_EVENT0("webrtc", "PeerConnection::~PeerConnection");
Steve Anton4171afb2017-11-20 10:20:22 -0800770 RTC_DCHECK_RUN_ON(signaling_thread());
771
Steve Anton8af21862017-12-15 11:20:13 -0800772 // Need to stop transceivers before destroying the stats collector because
773 // AudioRtpSender has a reference to the StatsCollector it will update when
774 // stopping.
775 for (auto transceiver : transceivers_) {
776 transceiver->Stop();
777 }
Steve Anton4171afb2017-11-20 10:20:22 -0800778
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700779 stats_.reset(nullptr);
hbosb78306a2016-12-19 05:06:57 -0800780 if (stats_collector_) {
781 stats_collector_->WaitForPendingRequest();
782 stats_collector_ = nullptr;
783 }
Steve Anton75737c02017-11-06 10:37:17 -0800784
Steve Anton8af21862017-12-15 11:20:13 -0800785 // Don't destroy BaseChannels until after stats has been cleaned up so that
786 // the last stats request can still read from the channels.
787 DestroyAllChannels();
788
Mirko Bonadei675513b2017-11-09 11:09:25 +0100789 RTC_LOG(LS_INFO) << "Session: " << session_id() << " is destroyed.";
Steve Anton75737c02017-11-06 10:37:17 -0800790
791 webrtc_session_desc_factory_.reset();
792 sctp_invoker_.reset();
793 sctp_factory_.reset();
794 transport_controller_.reset();
795
deadbeef91dd5672016-05-18 16:55:30 -0700796 // port_allocator_ lives on the network thread and should be destroyed there.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700797 network_thread()->Invoke<void>(RTC_FROM_HERE,
nisseeaabdf62017-05-05 02:23:02 -0700798 [this] { port_allocator_.reset(); });
eladalon248fd4f2017-09-06 05:18:15 -0700799 // call_ and event_log_ must be destroyed on the worker thread.
Steve Anton978b8762017-09-29 12:15:02 -0700800 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
eladalon248fd4f2017-09-06 05:18:15 -0700801 call_.reset();
Qingsi Wang93a84392018-01-30 17:13:09 -0800802 // The event log must outlive call (and any other object that uses it).
eladalon248fd4f2017-09-06 05:18:15 -0700803 event_log_.reset();
804 });
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000805}
806
Steve Anton8af21862017-12-15 11:20:13 -0800807void PeerConnection::DestroyAllChannels() {
Steve Anton3fe1b152017-12-12 10:20:08 -0800808 // Destroy video channels first since they may have a pointer to a voice
809 // channel.
810 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -0800811 if (transceiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton3fe1b152017-12-12 10:20:08 -0800812 DestroyTransceiverChannel(transceiver);
813 }
814 }
815 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -0800816 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton3fe1b152017-12-12 10:20:08 -0800817 DestroyTransceiverChannel(transceiver);
818 }
819 }
820 DestroyDataChannel();
821}
822
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000823bool PeerConnection::Initialize(
buildbot@webrtc.org41451d42014-05-03 05:39:45 +0000824 const PeerConnectionInterface::RTCConfiguration& configuration,
kwibergd1fe2812016-04-27 06:47:29 -0700825 std::unique_ptr<cricket::PortAllocator> allocator,
Henrik Boströmd03c23b2016-06-01 11:44:18 +0200826 std::unique_ptr<rtc::RTCCertificateGeneratorInterface> cert_generator,
deadbeef653b8e02015-11-11 12:55:10 -0800827 PeerConnectionObserver* observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100828 TRACE_EVENT0("webrtc", "PeerConnection::Initialize");
Steve Anton038834f2017-07-14 15:59:59 -0700829
830 RTCError config_error = ValidateConfiguration(configuration);
831 if (!config_error.ok()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100832 RTC_LOG(LS_ERROR) << "Invalid configuration: " << config_error.message();
Steve Anton038834f2017-07-14 15:59:59 -0700833 return false;
834 }
835
deadbeef293e9262017-01-11 12:28:30 -0800836 if (!allocator) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100837 RTC_LOG(LS_ERROR)
838 << "PeerConnection initialized without a PortAllocator? "
Jonas Olsson45cc8902018-02-13 10:37:07 +0100839 "This shouldn't happen if using PeerConnectionFactory.";
deadbeef293e9262017-01-11 12:28:30 -0800840 return false;
841 }
Jonas Orelandbdcee282017-10-10 14:01:40 +0200842
deadbeef653b8e02015-11-11 12:55:10 -0800843 if (!observer) {
deadbeef293e9262017-01-11 12:28:30 -0800844 // TODO(deadbeef): Why do we do this?
Mirko Bonadei675513b2017-11-09 11:09:25 +0100845 RTC_LOG(LS_ERROR) << "PeerConnection initialized without a "
Jonas Olsson45cc8902018-02-13 10:37:07 +0100846 "PeerConnectionObserver";
deadbeef653b8e02015-11-11 12:55:10 -0800847 return false;
848 }
pthatcher@webrtc.org877ac762015-02-04 22:03:09 +0000849 observer_ = observer;
kwiberg0eb15ed2015-12-17 03:04:15 -0800850 port_allocator_ = std::move(allocator);
deadbeef653b8e02015-11-11 12:55:10 -0800851
deadbeef91dd5672016-05-18 16:55:30 -0700852 // The port allocator lives on the network thread and should be initialized
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700853 // there.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700854 if (!network_thread()->Invoke<bool>(
855 RTC_FROM_HERE, rtc::Bind(&PeerConnection::InitializePortAllocator_n,
856 this, configuration))) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000857 return false;
858 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000859
Steve Anton75737c02017-11-06 10:37:17 -0800860 // RFC 3264: The numeric value of the session id and version in the
861 // o line MUST be representable with a "64 bit signed integer".
862 // Due to this constraint session id |session_id_| is max limited to
863 // LLONG_MAX.
864 session_id_ = rtc::ToString(rtc::CreateRandomId64() & LLONG_MAX);
865 transport_controller_.reset(factory_->CreateTransportController(
Qingsi Wang93a84392018-01-30 17:13:09 -0800866 port_allocator_.get(), configuration.redetermine_role_on_ice_restart,
867 event_log_.get()));
Steve Anton75737c02017-11-06 10:37:17 -0800868 transport_controller_->SetIceRole(cricket::ICEROLE_CONTROLLED);
869 transport_controller_->SignalConnectionState.connect(
870 this, &PeerConnection::OnTransportControllerConnectionState);
871 transport_controller_->SignalGatheringState.connect(
872 this, &PeerConnection::OnTransportControllerGatheringState);
873 transport_controller_->SignalCandidatesGathered.connect(
874 this, &PeerConnection::OnTransportControllerCandidatesGathered);
875 transport_controller_->SignalCandidatesRemoved.connect(
876 this, &PeerConnection::OnTransportControllerCandidatesRemoved);
877 transport_controller_->SignalDtlsHandshakeError.connect(
878 this, &PeerConnection::OnTransportControllerDtlsHandshakeError);
879
880 sctp_factory_ = factory_->CreateSctpTransportInternalFactory();
zhihuang29ff8442016-07-27 11:07:25 -0700881
deadbeefab9b2d12015-10-14 11:33:11 -0700882 stats_.reset(new StatsCollector(this));
hbos74e1a4f2016-09-15 23:33:01 -0700883 stats_collector_ = RTCStatsCollector::Create(this);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000884
Steve Antonba818672017-11-06 10:21:57 -0800885 configuration_ = configuration;
886
Steve Anton75737c02017-11-06 10:37:17 -0800887 const PeerConnectionFactoryInterface::Options& options = factory_->options();
888
889 transport_controller_->SetSslMaxProtocolVersion(options.ssl_max_version);
890
891 // Obtain a certificate from RTCConfiguration if any were provided (optional).
892 rtc::scoped_refptr<rtc::RTCCertificate> certificate;
893 if (!configuration.certificates.empty()) {
894 // TODO(hbos,torbjorng): Decide on certificate-selection strategy instead of
895 // just picking the first one. The decision should be made based on the DTLS
896 // handshake. The DTLS negotiations need to know about all certificates.
897 certificate = configuration.certificates[0];
898 }
899
Steve Antond25da372017-11-06 14:50:29 -0800900 transport_controller_->SetIceConfig(ParseIceConfig(configuration));
Steve Anton75737c02017-11-06 10:37:17 -0800901
902 if (options.disable_encryption) {
903 dtls_enabled_ = false;
904 } else {
905 // Enable DTLS by default if we have an identity store or a certificate.
906 dtls_enabled_ = (cert_generator || certificate);
907 // |configuration| can override the default |dtls_enabled_| value.
908 if (configuration.enable_dtls_srtp) {
909 dtls_enabled_ = *(configuration.enable_dtls_srtp);
910 }
911 }
912
913 // Enable creation of RTP data channels if the kEnableRtpDataChannels is set.
914 // It takes precendence over the disable_sctp_data_channels
915 // PeerConnectionFactoryInterface::Options.
916 if (configuration.enable_rtp_data_channel) {
917 data_channel_type_ = cricket::DCT_RTP;
918 } else {
919 // DTLS has to be enabled to use SCTP.
920 if (!options.disable_sctp_data_channels && dtls_enabled_) {
921 data_channel_type_ = cricket::DCT_SCTP;
922 }
923 }
924
925 video_options_.screencast_min_bitrate_kbps =
926 configuration.screencast_min_bitrate;
927 audio_options_.combined_audio_video_bwe =
928 configuration.combined_audio_video_bwe;
929
930 audio_options_.audio_jitter_buffer_max_packets =
Oskar Sundbom9b28a032017-11-16 10:53:30 +0100931 configuration.audio_jitter_buffer_max_packets;
Steve Anton75737c02017-11-06 10:37:17 -0800932
933 audio_options_.audio_jitter_buffer_fast_accelerate =
Oskar Sundbom9b28a032017-11-16 10:53:30 +0100934 configuration.audio_jitter_buffer_fast_accelerate;
Steve Anton75737c02017-11-06 10:37:17 -0800935
936 // Whether the certificate generator/certificate is null or not determines
937 // what PeerConnectionDescriptionFactory will do, so make sure that we give it
938 // the right instructions by clearing the variables if needed.
939 if (!dtls_enabled_) {
940 cert_generator.reset();
941 certificate = nullptr;
942 } else if (certificate) {
943 // Favor generated certificate over the certificate generator.
944 cert_generator.reset();
945 }
946
947 webrtc_session_desc_factory_.reset(new WebRtcSessionDescriptionFactory(
948 signaling_thread(), channel_manager(), this, session_id(),
949 std::move(cert_generator), certificate));
950 webrtc_session_desc_factory_->SignalCertificateReady.connect(
951 this, &PeerConnection::OnCertificateReady);
952
953 if (options.disable_encryption) {
954 webrtc_session_desc_factory_->SetSdesPolicy(cricket::SEC_DISABLED);
955 }
956
957 webrtc_session_desc_factory_->set_enable_encrypted_rtp_header_extensions(
958 options.crypto_options.enable_encrypted_rtp_header_extensions);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000959
Steve Anton4171afb2017-11-20 10:20:22 -0800960 // Add default audio/video transceivers for Plan B SDP.
961 if (!IsUnifiedPlan()) {
962 transceivers_.push_back(
963 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
964 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_AUDIO)));
965 transceivers_.push_back(
966 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
967 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_VIDEO)));
968 }
969
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000970 return true;
971}
972
Steve Anton038834f2017-07-14 15:59:59 -0700973RTCError PeerConnection::ValidateConfiguration(
974 const RTCConfiguration& config) const {
975 if (config.ice_regather_interval_range &&
976 config.continual_gathering_policy == GATHER_ONCE) {
977 return RTCError(RTCErrorType::INVALID_PARAMETER,
978 "ice_regather_interval_range specified but continual "
979 "gathering policy is GATHER_ONCE");
980 }
981 return RTCError::OK();
982}
983
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000984rtc::scoped_refptr<StreamCollectionInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000985PeerConnection::local_streams() {
deadbeefab9b2d12015-10-14 11:33:11 -0700986 return local_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000987}
988
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000989rtc::scoped_refptr<StreamCollectionInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000990PeerConnection::remote_streams() {
deadbeefab9b2d12015-10-14 11:33:11 -0700991 return remote_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000992}
993
perkj@webrtc.orgc2dd5ee2014-11-04 11:31:29 +0000994bool PeerConnection::AddStream(MediaStreamInterface* local_stream) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100995 TRACE_EVENT0("webrtc", "PeerConnection::AddStream");
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000996 if (IsClosed()) {
997 return false;
998 }
deadbeefab9b2d12015-10-14 11:33:11 -0700999 if (!CanAddLocalMediaStream(local_streams_, local_stream)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001000 return false;
1001 }
deadbeefab9b2d12015-10-14 11:33:11 -07001002
1003 local_streams_->AddStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -08001004 MediaStreamObserver* observer = new MediaStreamObserver(local_stream);
1005 observer->SignalAudioTrackAdded.connect(this,
1006 &PeerConnection::OnAudioTrackAdded);
1007 observer->SignalAudioTrackRemoved.connect(
1008 this, &PeerConnection::OnAudioTrackRemoved);
1009 observer->SignalVideoTrackAdded.connect(this,
1010 &PeerConnection::OnVideoTrackAdded);
1011 observer->SignalVideoTrackRemoved.connect(
1012 this, &PeerConnection::OnVideoTrackRemoved);
kwibergd1fe2812016-04-27 06:47:29 -07001013 stream_observers_.push_back(std::unique_ptr<MediaStreamObserver>(observer));
deadbeefab9b2d12015-10-14 11:33:11 -07001014
deadbeefab9b2d12015-10-14 11:33:11 -07001015 for (const auto& track : local_stream->GetAudioTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001016 AddAudioTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -07001017 }
1018 for (const auto& track : local_stream->GetVideoTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001019 AddVideoTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -07001020 }
1021
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001022 stats_->AddStream(local_stream);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001023 observer_->OnRenegotiationNeeded();
1024 return true;
1025}
1026
1027void PeerConnection::RemoveStream(MediaStreamInterface* local_stream) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001028 TRACE_EVENT0("webrtc", "PeerConnection::RemoveStream");
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001029 if (!IsClosed()) {
1030 for (const auto& track : local_stream->GetAudioTracks()) {
1031 RemoveAudioTrack(track.get(), local_stream);
1032 }
1033 for (const auto& track : local_stream->GetVideoTracks()) {
1034 RemoveVideoTrack(track.get(), local_stream);
1035 }
deadbeefab9b2d12015-10-14 11:33:11 -07001036 }
deadbeefab9b2d12015-10-14 11:33:11 -07001037 local_streams_->RemoveStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -08001038 stream_observers_.erase(
1039 std::remove_if(
1040 stream_observers_.begin(), stream_observers_.end(),
kwibergd1fe2812016-04-27 06:47:29 -07001041 [local_stream](const std::unique_ptr<MediaStreamObserver>& observer) {
deadbeefeb459812015-12-15 19:24:43 -08001042 return observer->stream()->label().compare(local_stream->label()) ==
1043 0;
1044 }),
1045 stream_observers_.end());
deadbeefab9b2d12015-10-14 11:33:11 -07001046
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001047 if (IsClosed()) {
1048 return;
1049 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001050 observer_->OnRenegotiationNeeded();
1051}
1052
deadbeefe1f9d832016-01-14 15:35:42 -08001053rtc::scoped_refptr<RtpSenderInterface> PeerConnection::AddTrack(
1054 MediaStreamTrackInterface* track,
1055 std::vector<MediaStreamInterface*> streams) {
1056 TRACE_EVENT0("webrtc", "PeerConnection::AddTrack");
Steve Antonf9381f02017-12-14 10:23:57 -08001057 std::vector<std::string> stream_labels;
1058 for (auto* stream : streams) {
1059 if (!stream) {
1060 RTC_LOG(LS_ERROR) << "Stream list has null element.";
1061 return nullptr;
1062 }
1063 stream_labels.push_back(stream->label());
1064 }
Steve Anton2d6c76a2018-01-05 17:10:52 -08001065 auto sender_or_error = AddTrack(track, stream_labels);
Steve Antonf9381f02017-12-14 10:23:57 -08001066 if (!sender_or_error.ok()) {
deadbeefe1f9d832016-01-14 15:35:42 -08001067 return nullptr;
1068 }
Steve Antonf9381f02017-12-14 10:23:57 -08001069 return sender_or_error.MoveValue();
1070}
1071
Steve Anton2d6c76a2018-01-05 17:10:52 -08001072RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::AddTrack(
Steve Antonf9381f02017-12-14 10:23:57 -08001073 rtc::scoped_refptr<MediaStreamTrackInterface> track,
1074 const std::vector<std::string>& stream_labels) {
Steve Anton2d6c76a2018-01-05 17:10:52 -08001075 TRACE_EVENT0("webrtc", "PeerConnection::AddTrack");
Steve Antonf9381f02017-12-14 10:23:57 -08001076 if (!track) {
1077 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "Track is null.");
1078 }
1079 if (!(track->kind() == MediaStreamTrackInterface::kAudioKind ||
1080 track->kind() == MediaStreamTrackInterface::kVideoKind)) {
1081 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1082 "Track has invalid kind: " + track->kind());
1083 }
1084 // TODO(bugs.webrtc.org/7932): Support adding a track to multiple streams.
1085 if (stream_labels.size() > 1u) {
1086 LOG_AND_RETURN_ERROR(
1087 RTCErrorType::UNSUPPORTED_OPERATION,
1088 "AddTrack with more than one stream is not currently supported.");
1089 }
1090 if (IsClosed()) {
1091 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
1092 "PeerConnection is closed.");
deadbeefe1f9d832016-01-14 15:35:42 -08001093 }
Steve Anton4171afb2017-11-20 10:20:22 -08001094 if (FindSenderForTrack(track)) {
Steve Antonf9381f02017-12-14 10:23:57 -08001095 LOG_AND_RETURN_ERROR(
1096 RTCErrorType::INVALID_PARAMETER,
1097 "Sender already exists for track " + track->id() + ".");
deadbeefe1f9d832016-01-14 15:35:42 -08001098 }
Steve Antonf9381f02017-12-14 10:23:57 -08001099 // TODO(bugs.webrtc.org/7933): MediaSession expects the sender to have exactly
1100 // one stream. AddTrackInternal will return an error if there is more than one
1101 // stream, but if the caller specifies none then we need to generate a random
1102 // stream label.
1103 std::vector<std::string> adjusted_stream_labels = stream_labels;
1104 if (stream_labels.empty()) {
1105 adjusted_stream_labels.push_back(rtc::CreateRandomUuid());
1106 }
1107 RTC_DCHECK_EQ(1, adjusted_stream_labels.size());
1108 auto sender_or_error =
1109 (IsUnifiedPlan() ? AddTrackUnifiedPlan(track, adjusted_stream_labels)
1110 : AddTrackPlanB(track, adjusted_stream_labels));
1111 if (sender_or_error.ok()) {
1112 observer_->OnRenegotiationNeeded();
Steve Anton43a723a2018-01-04 15:48:17 -08001113 stats_->AddTrack(track);
Steve Antonf9381f02017-12-14 10:23:57 -08001114 }
1115 return sender_or_error;
1116}
deadbeefe1f9d832016-01-14 15:35:42 -08001117
Steve Antonf9381f02017-12-14 10:23:57 -08001118RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>>
1119PeerConnection::AddTrackPlanB(
1120 rtc::scoped_refptr<MediaStreamTrackInterface> track,
1121 const std::vector<std::string>& stream_labels) {
Steve Anton02ee47c2018-01-10 16:26:06 -08001122 cricket::MediaType media_type =
1123 (track->kind() == MediaStreamTrackInterface::kAudioKind
1124 ? cricket::MEDIA_TYPE_AUDIO
1125 : cricket::MEDIA_TYPE_VIDEO);
1126 auto new_sender = CreateSender(media_type, track, stream_labels);
deadbeefe1f9d832016-01-14 15:35:42 -08001127 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
Steve Anton57858b32018-02-15 15:19:50 -08001128 new_sender->internal()->SetVoiceMediaChannel(voice_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08001129 GetAudioTransceiver()->internal()->AddSender(new_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001130 const RtpSenderInfo* sender_info =
1131 FindSenderInfo(local_audio_sender_infos_,
1132 new_sender->internal()->stream_id(), track->id());
1133 if (sender_info) {
1134 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -08001135 }
Steve Antonf9381f02017-12-14 10:23:57 -08001136 } else {
1137 RTC_DCHECK_EQ(MediaStreamTrackInterface::kVideoKind, track->kind());
Steve Anton57858b32018-02-15 15:19:50 -08001138 new_sender->internal()->SetVideoMediaChannel(video_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08001139 GetVideoTransceiver()->internal()->AddSender(new_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001140 const RtpSenderInfo* sender_info =
1141 FindSenderInfo(local_video_sender_infos_,
1142 new_sender->internal()->stream_id(), track->id());
1143 if (sender_info) {
1144 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -08001145 }
deadbeefe1f9d832016-01-14 15:35:42 -08001146 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001147 return rtc::scoped_refptr<RtpSenderInterface>(new_sender);
Steve Antonf9381f02017-12-14 10:23:57 -08001148}
deadbeefe1f9d832016-01-14 15:35:42 -08001149
Steve Antonf9381f02017-12-14 10:23:57 -08001150RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>>
1151PeerConnection::AddTrackUnifiedPlan(
1152 rtc::scoped_refptr<MediaStreamTrackInterface> track,
1153 const std::vector<std::string>& stream_labels) {
1154 auto transceiver = FindFirstTransceiverForAddedTrack(track);
1155 if (transceiver) {
1156 if (transceiver->direction() == RtpTransceiverDirection::kRecvOnly) {
1157 transceiver->SetDirection(RtpTransceiverDirection::kSendRecv);
1158 } else if (transceiver->direction() == RtpTransceiverDirection::kInactive) {
1159 transceiver->SetDirection(RtpTransceiverDirection::kSendOnly);
1160 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001161 transceiver->sender()->SetTrack(track);
1162 transceiver->internal()->sender_internal()->set_stream_ids(stream_labels);
Steve Antonf9381f02017-12-14 10:23:57 -08001163 } else {
1164 cricket::MediaType media_type =
1165 (track->kind() == MediaStreamTrackInterface::kAudioKind
1166 ? cricket::MEDIA_TYPE_AUDIO
1167 : cricket::MEDIA_TYPE_VIDEO);
Steve Anton02ee47c2018-01-10 16:26:06 -08001168 auto sender = CreateSender(media_type, track, stream_labels);
1169 auto receiver = CreateReceiver(media_type, rtc::CreateRandomUuid());
1170 transceiver = CreateAndAddTransceiver(sender, receiver);
Steve Antonf9381f02017-12-14 10:23:57 -08001171 transceiver->internal()->set_created_by_addtrack(true);
1172 transceiver->SetDirection(RtpTransceiverDirection::kSendRecv);
1173 }
Steve Antonf9381f02017-12-14 10:23:57 -08001174 return transceiver->sender();
1175}
1176
1177rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1178PeerConnection::FindFirstTransceiverForAddedTrack(
1179 rtc::scoped_refptr<MediaStreamTrackInterface> track) {
1180 RTC_DCHECK(track);
1181 for (auto transceiver : transceivers_) {
1182 if (!transceiver->sender()->track() &&
Steve Anton69470252018-02-09 11:43:08 -08001183 cricket::MediaTypeToString(transceiver->media_type()) ==
Steve Antonf9381f02017-12-14 10:23:57 -08001184 track->kind() &&
1185 !transceiver->internal()->has_ever_been_used_to_send()) {
1186 return transceiver;
1187 }
1188 }
1189 return nullptr;
deadbeefe1f9d832016-01-14 15:35:42 -08001190}
1191
1192bool PeerConnection::RemoveTrack(RtpSenderInterface* sender) {
1193 TRACE_EVENT0("webrtc", "PeerConnection::RemoveTrack");
Steve Antonf9381f02017-12-14 10:23:57 -08001194 return RemoveTrackInternal(sender).ok();
1195}
1196
1197RTCError PeerConnection::RemoveTrackInternal(
1198 rtc::scoped_refptr<RtpSenderInterface> sender) {
1199 if (!sender) {
1200 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "Sender is null.");
1201 }
deadbeefe1f9d832016-01-14 15:35:42 -08001202 if (IsClosed()) {
Steve Antonf9381f02017-12-14 10:23:57 -08001203 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
1204 "PeerConnection is closed.");
deadbeefe1f9d832016-01-14 15:35:42 -08001205 }
Steve Antonf9381f02017-12-14 10:23:57 -08001206 if (IsUnifiedPlan()) {
1207 auto transceiver = FindTransceiverBySender(sender);
1208 if (!transceiver || !sender->track()) {
1209 return RTCError::OK();
1210 }
1211 sender->SetTrack(nullptr);
1212 if (transceiver->direction() == RtpTransceiverDirection::kSendRecv) {
1213 transceiver->internal()->SetDirection(RtpTransceiverDirection::kRecvOnly);
1214 } else if (transceiver->direction() == RtpTransceiverDirection::kSendOnly) {
1215 transceiver->internal()->SetDirection(RtpTransceiverDirection::kInactive);
1216 }
Steve Anton4171afb2017-11-20 10:20:22 -08001217 } else {
Steve Antonf9381f02017-12-14 10:23:57 -08001218 bool removed;
1219 if (sender->media_type() == cricket::MEDIA_TYPE_AUDIO) {
1220 removed = GetAudioTransceiver()->internal()->RemoveSender(sender);
1221 } else {
1222 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, sender->media_type());
1223 removed = GetVideoTransceiver()->internal()->RemoveSender(sender);
1224 }
1225 if (!removed) {
1226 LOG_AND_RETURN_ERROR(
1227 RTCErrorType::INVALID_PARAMETER,
1228 "Couldn't find sender " + sender->id() + " to remove.");
1229 }
Steve Anton4171afb2017-11-20 10:20:22 -08001230 }
deadbeefe1f9d832016-01-14 15:35:42 -08001231 observer_->OnRenegotiationNeeded();
Steve Antonf9381f02017-12-14 10:23:57 -08001232 return RTCError::OK();
1233}
1234
1235rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1236PeerConnection::FindTransceiverBySender(
1237 rtc::scoped_refptr<RtpSenderInterface> sender) {
1238 for (auto transceiver : transceivers_) {
1239 if (transceiver->sender() == sender) {
1240 return transceiver;
1241 }
1242 }
1243 return nullptr;
deadbeefe1f9d832016-01-14 15:35:42 -08001244}
1245
Steve Anton9158ef62017-11-27 13:01:52 -08001246RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1247PeerConnection::AddTransceiver(
1248 rtc::scoped_refptr<MediaStreamTrackInterface> track) {
1249 return AddTransceiver(track, RtpTransceiverInit());
1250}
1251
1252RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1253PeerConnection::AddTransceiver(
1254 rtc::scoped_refptr<MediaStreamTrackInterface> track,
1255 const RtpTransceiverInit& init) {
1256 if (!IsUnifiedPlan()) {
1257 LOG_AND_RETURN_ERROR(
1258 RTCErrorType::INTERNAL_ERROR,
1259 "AddTransceiver only supported when Unified Plan is enabled.");
1260 }
1261 if (!track) {
1262 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "track is null");
1263 }
1264 cricket::MediaType media_type;
1265 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
1266 media_type = cricket::MEDIA_TYPE_AUDIO;
1267 } else if (track->kind() == MediaStreamTrackInterface::kVideoKind) {
1268 media_type = cricket::MEDIA_TYPE_VIDEO;
1269 } else {
1270 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1271 "Track kind is not audio or video");
1272 }
1273 return AddTransceiver(media_type, track, init);
1274}
1275
1276RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1277PeerConnection::AddTransceiver(cricket::MediaType media_type) {
1278 return AddTransceiver(media_type, RtpTransceiverInit());
1279}
1280
1281RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1282PeerConnection::AddTransceiver(cricket::MediaType media_type,
1283 const RtpTransceiverInit& init) {
1284 if (!IsUnifiedPlan()) {
1285 LOG_AND_RETURN_ERROR(
1286 RTCErrorType::INTERNAL_ERROR,
1287 "AddTransceiver only supported when Unified Plan is enabled.");
1288 }
1289 if (!(media_type == cricket::MEDIA_TYPE_AUDIO ||
1290 media_type == cricket::MEDIA_TYPE_VIDEO)) {
1291 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1292 "media type is not audio or video");
1293 }
1294 return AddTransceiver(media_type, nullptr, init);
1295}
1296
1297RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1298PeerConnection::AddTransceiver(
1299 cricket::MediaType media_type,
1300 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Steve Anton22da89f2018-01-25 13:58:07 -08001301 const RtpTransceiverInit& init,
1302 bool fire_callback) {
Steve Anton9158ef62017-11-27 13:01:52 -08001303 RTC_DCHECK((media_type == cricket::MEDIA_TYPE_AUDIO ||
1304 media_type == cricket::MEDIA_TYPE_VIDEO));
1305 if (track) {
1306 RTC_DCHECK_EQ(media_type,
1307 (track->kind() == MediaStreamTrackInterface::kAudioKind
1308 ? cricket::MEDIA_TYPE_AUDIO
1309 : cricket::MEDIA_TYPE_VIDEO));
1310 }
1311
1312 // TODO(bugs.webrtc.org/7600): Verify init.
1313
Steve Anton02ee47c2018-01-10 16:26:06 -08001314 if (init.stream_labels.size() > 1u) {
1315 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
1316 "More than one stream is not yet supported.");
Steve Antonf9381f02017-12-14 10:23:57 -08001317 }
1318
Steve Anton02ee47c2018-01-10 16:26:06 -08001319 std::vector<std::string> stream_labels = {!init.stream_labels.empty()
1320 ? init.stream_labels[0]
1321 : rtc::CreateRandomUuid()};
1322
1323 auto sender = CreateSender(media_type, track, stream_labels);
1324 auto receiver = CreateReceiver(media_type, rtc::CreateRandomUuid());
1325 auto transceiver = CreateAndAddTransceiver(sender, receiver);
1326 transceiver->internal()->set_direction(init.direction);
1327
Steve Anton22da89f2018-01-25 13:58:07 -08001328 if (fire_callback) {
1329 observer_->OnRenegotiationNeeded();
1330 }
Steve Antonf9381f02017-12-14 10:23:57 -08001331
1332 return rtc::scoped_refptr<RtpTransceiverInterface>(transceiver);
1333}
1334
Steve Anton02ee47c2018-01-10 16:26:06 -08001335rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
1336PeerConnection::CreateSender(
1337 cricket::MediaType media_type,
1338 rtc::scoped_refptr<MediaStreamTrackInterface> track,
1339 const std::vector<std::string>& stream_labels) {
Steve Anton9158ef62017-11-27 13:01:52 -08001340 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> sender;
Steve Anton02ee47c2018-01-10 16:26:06 -08001341 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
1342 RTC_DCHECK(!track ||
1343 (track->kind() == MediaStreamTrackInterface::kAudioKind));
1344 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
1345 signaling_thread(),
Steve Anton47136dd2018-01-12 10:49:35 -08001346 new AudioRtpSender(worker_thread(),
1347 static_cast<AudioTrackInterface*>(track.get()),
Steve Anton02ee47c2018-01-10 16:26:06 -08001348 stream_labels, stats_.get()));
1349 } else {
1350 RTC_DCHECK_EQ(media_type, cricket::MEDIA_TYPE_VIDEO);
1351 RTC_DCHECK(!track ||
1352 (track->kind() == MediaStreamTrackInterface::kVideoKind));
1353 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
1354 signaling_thread(),
Steve Anton47136dd2018-01-12 10:49:35 -08001355 new VideoRtpSender(worker_thread(),
1356 static_cast<VideoTrackInterface*>(track.get()),
Steve Anton02ee47c2018-01-10 16:26:06 -08001357 stream_labels));
1358 }
1359 sender->internal()->set_stream_ids(stream_labels);
1360 return sender;
1361}
1362
1363rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1364PeerConnection::CreateReceiver(cricket::MediaType media_type,
1365 const std::string& receiver_id) {
Steve Anton9158ef62017-11-27 13:01:52 -08001366 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1367 receiver;
Steve Anton9158ef62017-11-27 13:01:52 -08001368 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton9158ef62017-11-27 13:01:52 -08001369 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
Steve Anton60776752018-01-10 11:51:34 -08001370 signaling_thread(),
Steve Antond3679212018-01-17 17:41:02 -08001371 new AudioRtpReceiver(worker_thread(), receiver_id, {}));
Steve Anton9158ef62017-11-27 13:01:52 -08001372 } else {
Steve Anton02ee47c2018-01-10 16:26:06 -08001373 RTC_DCHECK_EQ(media_type, cricket::MEDIA_TYPE_VIDEO);
Steve Anton9158ef62017-11-27 13:01:52 -08001374 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
1375 signaling_thread(),
Steve Antond3679212018-01-17 17:41:02 -08001376 new VideoRtpReceiver(worker_thread(), receiver_id, {}));
Steve Anton9158ef62017-11-27 13:01:52 -08001377 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001378 return receiver;
1379}
1380
1381rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1382PeerConnection::CreateAndAddTransceiver(
1383 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> sender,
1384 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1385 receiver) {
1386 auto transceiver = RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1387 signaling_thread(), new RtpTransceiver(sender, receiver));
Steve Anton9158ef62017-11-27 13:01:52 -08001388 transceivers_.push_back(transceiver);
Steve Antonf9381f02017-12-14 10:23:57 -08001389 return transceiver;
Steve Anton9158ef62017-11-27 13:01:52 -08001390}
1391
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001392rtc::scoped_refptr<DtmfSenderInterface> PeerConnection::CreateDtmfSender(
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001393 AudioTrackInterface* track) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001394 TRACE_EVENT0("webrtc", "PeerConnection::CreateDtmfSender");
zhihuang29ff8442016-07-27 11:07:25 -07001395 if (IsClosed()) {
1396 return nullptr;
1397 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001398 if (!track) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001399 RTC_LOG(LS_ERROR) << "CreateDtmfSender - track is NULL.";
deadbeef20cb0c12017-02-01 20:27:00 -08001400 return nullptr;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001401 }
Steve Anton4171afb2017-11-20 10:20:22 -08001402 auto track_sender = FindSenderForTrack(track);
1403 if (!track_sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001404 RTC_LOG(LS_ERROR) << "CreateDtmfSender called with a non-added track.";
deadbeef20cb0c12017-02-01 20:27:00 -08001405 return nullptr;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001406 }
1407
Steve Anton4171afb2017-11-20 10:20:22 -08001408 return track_sender->GetDtmfSender();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001409}
1410
deadbeeffac06552015-11-25 11:26:01 -08001411rtc::scoped_refptr<RtpSenderInterface> PeerConnection::CreateSender(
deadbeefbd7d8f72015-12-18 16:58:44 -08001412 const std::string& kind,
1413 const std::string& stream_id) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001414 TRACE_EVENT0("webrtc", "PeerConnection::CreateSender");
zhihuang29ff8442016-07-27 11:07:25 -07001415 if (IsClosed()) {
1416 return nullptr;
1417 }
Steve Anton4171afb2017-11-20 10:20:22 -08001418
Steve Anton02ee47c2018-01-10 16:26:06 -08001419 std::vector<std::string> stream_labels;
1420 if (!stream_id.empty()) {
1421 stream_labels.push_back(stream_id);
1422 }
1423
Steve Anton4171afb2017-11-20 10:20:22 -08001424 // TODO(steveanton): Move construction of the RtpSenders to RtpTransceiver.
deadbeefa601f5c2016-06-06 14:27:39 -07001425 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender;
deadbeeffac06552015-11-25 11:26:01 -08001426 if (kind == MediaStreamTrackInterface::kAudioKind) {
Steve Anton47136dd2018-01-12 10:49:35 -08001427 auto* audio_sender = new AudioRtpSender(worker_thread(), nullptr,
1428 stream_labels, stats_.get());
Steve Anton57858b32018-02-15 15:19:50 -08001429 audio_sender->SetVoiceMediaChannel(voice_media_channel());
deadbeefa601f5c2016-06-06 14:27:39 -07001430 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton02ee47c2018-01-10 16:26:06 -08001431 signaling_thread(), audio_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001432 GetAudioTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 11:26:01 -08001433 } else if (kind == MediaStreamTrackInterface::kVideoKind) {
Steve Anton47136dd2018-01-12 10:49:35 -08001434 auto* video_sender =
1435 new VideoRtpSender(worker_thread(), nullptr, stream_labels);
Steve Anton57858b32018-02-15 15:19:50 -08001436 video_sender->SetVideoMediaChannel(video_media_channel());
deadbeefa601f5c2016-06-06 14:27:39 -07001437 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton02ee47c2018-01-10 16:26:06 -08001438 signaling_thread(), video_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001439 GetVideoTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 11:26:01 -08001440 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001441 RTC_LOG(LS_ERROR) << "CreateSender called with invalid kind: " << kind;
Steve Anton4171afb2017-11-20 10:20:22 -08001442 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08001443 }
Steve Anton4171afb2017-11-20 10:20:22 -08001444
deadbeefe1f9d832016-01-14 15:35:42 -08001445 return new_sender;
deadbeeffac06552015-11-25 11:26:01 -08001446}
1447
deadbeef70ab1a12015-09-28 16:53:55 -07001448std::vector<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::GetSenders()
1449 const {
deadbeefa601f5c2016-06-06 14:27:39 -07001450 std::vector<rtc::scoped_refptr<RtpSenderInterface>> ret;
Steve Anton4171afb2017-11-20 10:20:22 -08001451 for (auto sender : GetSendersInternal()) {
1452 ret.push_back(sender);
deadbeefa601f5c2016-06-06 14:27:39 -07001453 }
1454 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -07001455}
1456
Steve Anton4171afb2017-11-20 10:20:22 -08001457std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1458PeerConnection::GetSendersInternal() const {
1459 std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1460 all_senders;
1461 for (auto transceiver : transceivers_) {
1462 auto senders = transceiver->internal()->senders();
1463 all_senders.insert(all_senders.end(), senders.begin(), senders.end());
1464 }
1465 return all_senders;
1466}
1467
deadbeef70ab1a12015-09-28 16:53:55 -07001468std::vector<rtc::scoped_refptr<RtpReceiverInterface>>
1469PeerConnection::GetReceivers() const {
deadbeefa601f5c2016-06-06 14:27:39 -07001470 std::vector<rtc::scoped_refptr<RtpReceiverInterface>> ret;
Steve Anton4171afb2017-11-20 10:20:22 -08001471 for (const auto& receiver : GetReceiversInternal()) {
1472 ret.push_back(receiver);
deadbeefa601f5c2016-06-06 14:27:39 -07001473 }
1474 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -07001475}
1476
Steve Anton4171afb2017-11-20 10:20:22 -08001477std::vector<
1478 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1479PeerConnection::GetReceiversInternal() const {
1480 std::vector<
1481 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1482 all_receivers;
1483 for (auto transceiver : transceivers_) {
1484 auto receivers = transceiver->internal()->receivers();
1485 all_receivers.insert(all_receivers.end(), receivers.begin(),
1486 receivers.end());
1487 }
1488 return all_receivers;
1489}
1490
Steve Anton9158ef62017-11-27 13:01:52 -08001491std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
1492PeerConnection::GetTransceivers() const {
1493 RTC_DCHECK(IsUnifiedPlan());
1494 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> all_transceivers;
1495 for (auto transceiver : transceivers_) {
1496 all_transceivers.push_back(transceiver);
1497 }
1498 return all_transceivers;
1499}
1500
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001501bool PeerConnection::GetStats(StatsObserver* observer,
wu@webrtc.orgb9a088b2014-02-13 23:18:49 +00001502 MediaStreamTrackInterface* track,
1503 StatsOutputLevel level) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001504 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
deadbeef0a6c4ca2015-10-06 11:38:28 -07001505 RTC_DCHECK(signaling_thread()->IsCurrent());
nisse7ce109a2017-01-31 00:57:56 -08001506 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001507 RTC_LOG(LS_ERROR) << "GetStats - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001508 return false;
1509 }
1510
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001511 stats_->UpdateStats(level);
zhihuange9e94c32016-11-04 11:38:15 -07001512 // The StatsCollector is used to tell if a track is valid because it may
1513 // remember tracks that the PeerConnection previously removed.
1514 if (track && !stats_->IsValidTrack(track->id())) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001515 RTC_LOG(LS_WARNING) << "GetStats is called with an invalid track: "
1516 << track->id();
zhihuange9e94c32016-11-04 11:38:15 -07001517 return false;
1518 }
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001519 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_GETSTATS,
tommi@webrtc.org5b06b062014-08-15 08:38:30 +00001520 new GetStatsMsg(observer, track));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001521 return true;
1522}
1523
hbos74e1a4f2016-09-15 23:33:01 -07001524void PeerConnection::GetStats(RTCStatsCollectorCallback* callback) {
1525 RTC_DCHECK(stats_collector_);
1526 stats_collector_->GetStatsReport(callback);
1527}
1528
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001529PeerConnectionInterface::SignalingState PeerConnection::signaling_state() {
1530 return signaling_state_;
1531}
1532
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001533PeerConnectionInterface::IceConnectionState
1534PeerConnection::ice_connection_state() {
1535 return ice_connection_state_;
1536}
1537
1538PeerConnectionInterface::IceGatheringState
1539PeerConnection::ice_gathering_state() {
1540 return ice_gathering_state_;
1541}
1542
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001543rtc::scoped_refptr<DataChannelInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001544PeerConnection::CreateDataChannel(
1545 const std::string& label,
1546 const DataChannelInit* config) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001547 TRACE_EVENT0("webrtc", "PeerConnection::CreateDataChannel");
zhihuang9763d562016-08-05 11:14:50 -07001548
deadbeefab9b2d12015-10-14 11:33:11 -07001549 bool first_datachannel = !HasDataChannels();
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001550
kwibergd1fe2812016-04-27 06:47:29 -07001551 std::unique_ptr<InternalDataChannelInit> internal_config;
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00001552 if (config) {
1553 internal_config.reset(new InternalDataChannelInit(*config));
1554 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001555 rtc::scoped_refptr<DataChannelInterface> channel(
deadbeefab9b2d12015-10-14 11:33:11 -07001556 InternalCreateDataChannel(label, internal_config.get()));
1557 if (!channel.get()) {
1558 return nullptr;
1559 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001560
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001561 // Trigger the onRenegotiationNeeded event for every new RTP DataChannel, or
1562 // the first SCTP DataChannel.
Steve Anton75737c02017-11-06 10:37:17 -08001563 if (data_channel_type() == cricket::DCT_RTP || first_datachannel) {
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001564 observer_->OnRenegotiationNeeded();
1565 }
wu@webrtc.org91053e72013-08-10 07:18:04 +00001566
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001567 return DataChannelProxy::Create(signaling_thread(), channel.get());
1568}
1569
1570void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
1571 const MediaConstraintsInterface* constraints) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001572 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
Steve Anton8d3444d2017-10-20 15:30:51 -07001573
zhihuang1c378ed2017-08-17 14:10:50 -07001574 PeerConnectionInterface::RTCOfferAnswerOptions offer_answer_options;
1575 // Always create an offer even if |ConvertConstraintsToOfferAnswerOptions|
1576 // returns false for now. Because |ConvertConstraintsToOfferAnswerOptions|
1577 // compares the mandatory fields parsed with the mandatory fields added in the
1578 // |constraints| and some downstream applications might create offers with
1579 // mandatory fields which would not be parsed in the helper method. For
1580 // example, in Chromium/remoting, |kEnableDtlsSrtp| is added to the
1581 // |constraints| as a mandatory field but it is not parsed.
1582 ConvertConstraintsToOfferAnswerOptions(constraints, &offer_answer_options);
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001583
zhihuang1c378ed2017-08-17 14:10:50 -07001584 CreateOffer(observer, offer_answer_options);
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001585}
1586
1587void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
1588 const RTCOfferAnswerOptions& options) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001589 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
Steve Anton8d3444d2017-10-20 15:30:51 -07001590
nisse7ce109a2017-01-31 00:57:56 -08001591 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001592 RTC_LOG(LS_ERROR) << "CreateOffer - observer is NULL.";
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001593 return;
1594 }
deadbeefab9b2d12015-10-14 11:33:11 -07001595
Steve Anton8d3444d2017-10-20 15:30:51 -07001596 if (IsClosed()) {
1597 std::string error = "CreateOffer called when PeerConnection is closed.";
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
zhihuang1c378ed2017-08-17 14:10:50 -07001603 if (!ValidateOfferAnswerOptions(options)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001604 std::string error = "CreateOffer called with invalid options.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001605 RTC_LOG(LS_ERROR) << error;
deadbeefab9b2d12015-10-14 11:33:11 -07001606 PostCreateSessionDescriptionFailure(observer, error);
1607 return;
1608 }
1609
Steve Anton22da89f2018-01-25 13:58:07 -08001610 // Legacy handling for offer_to_receive_audio and offer_to_receive_video.
1611 // Specified in WebRTC section 4.4.3.2 "Legacy configuration extensions".
1612 if (IsUnifiedPlan()) {
1613 RTCError error = HandleLegacyOfferOptions(options);
1614 if (!error.ok()) {
1615 PostCreateSessionDescriptionFailure(observer, error.message());
1616 return;
1617 }
1618 }
1619
zhihuang1c378ed2017-08-17 14:10:50 -07001620 cricket::MediaSessionOptions session_options;
1621 GetOptionsForOffer(options, &session_options);
Steve Antond25da372017-11-06 14:50:29 -08001622 webrtc_session_desc_factory_->CreateOffer(observer, options, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001623}
1624
Steve Anton22da89f2018-01-25 13:58:07 -08001625RTCError PeerConnection::HandleLegacyOfferOptions(
1626 const RTCOfferAnswerOptions& options) {
1627 RTC_DCHECK(IsUnifiedPlan());
1628
1629 if (options.offer_to_receive_audio == 0) {
1630 RemoveRecvDirectionFromReceivingTransceiversOfType(
1631 cricket::MEDIA_TYPE_AUDIO);
1632 } else if (options.offer_to_receive_audio == 1) {
1633 AddUpToOneReceivingTransceiverOfType(cricket::MEDIA_TYPE_AUDIO);
1634 } else if (options.offer_to_receive_audio > 1) {
1635 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
1636 "offer_to_receive_audio > 1 is not supported.");
1637 }
1638
1639 if (options.offer_to_receive_video == 0) {
1640 RemoveRecvDirectionFromReceivingTransceiversOfType(
1641 cricket::MEDIA_TYPE_VIDEO);
1642 } else if (options.offer_to_receive_video == 1) {
1643 AddUpToOneReceivingTransceiverOfType(cricket::MEDIA_TYPE_VIDEO);
1644 } else if (options.offer_to_receive_video > 1) {
1645 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
1646 "offer_to_receive_video > 1 is not supported.");
1647 }
1648
1649 return RTCError::OK();
1650}
1651
1652void PeerConnection::RemoveRecvDirectionFromReceivingTransceiversOfType(
1653 cricket::MediaType media_type) {
1654 for (auto transceiver : GetReceivingTransceiversOfType(media_type)) {
1655 transceiver->internal()->set_direction(
1656 RtpTransceiverDirectionWithRecvSet(transceiver->direction(), false));
1657 }
1658}
1659
1660void PeerConnection::AddUpToOneReceivingTransceiverOfType(
1661 cricket::MediaType media_type) {
1662 if (GetReceivingTransceiversOfType(media_type).empty()) {
1663 RtpTransceiverInit init;
1664 init.direction = RtpTransceiverDirection::kRecvOnly;
1665 AddTransceiver(media_type, nullptr, init, /*fire_callback=*/false);
1666 }
1667}
1668
1669std::vector<rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
1670PeerConnection::GetReceivingTransceiversOfType(cricket::MediaType media_type) {
1671 std::vector<
1672 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
1673 receiving_transceivers;
1674 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08001675 if (!transceiver->stopped() && transceiver->media_type() == media_type &&
Steve Anton22da89f2018-01-25 13:58:07 -08001676 RtpTransceiverDirectionHasRecv(transceiver->direction())) {
1677 receiving_transceivers.push_back(transceiver);
1678 }
1679 }
1680 return receiving_transceivers;
1681}
1682
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001683void PeerConnection::CreateAnswer(
1684 CreateSessionDescriptionObserver* observer,
1685 const MediaConstraintsInterface* constraints) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001686 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
Steve Anton8d3444d2017-10-20 15:30:51 -07001687
nisse7ce109a2017-01-31 00:57:56 -08001688 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001689 RTC_LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001690 return;
1691 }
deadbeefab9b2d12015-10-14 11:33:11 -07001692
zhihuang1c378ed2017-08-17 14:10:50 -07001693 PeerConnectionInterface::RTCOfferAnswerOptions offer_answer_options;
1694 if (!ConvertConstraintsToOfferAnswerOptions(constraints,
1695 &offer_answer_options)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001696 std::string error = "CreateAnswer called with invalid constraints.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001697 RTC_LOG(LS_ERROR) << error;
deadbeefab9b2d12015-10-14 11:33:11 -07001698 PostCreateSessionDescriptionFailure(observer, error);
1699 return;
1700 }
1701
Steve Anton8d3444d2017-10-20 15:30:51 -07001702 CreateAnswer(observer, offer_answer_options);
htaa2a49d92016-03-04 02:51:39 -08001703}
1704
1705void PeerConnection::CreateAnswer(CreateSessionDescriptionObserver* observer,
1706 const RTCOfferAnswerOptions& options) {
1707 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
nisse7ce109a2017-01-31 00:57:56 -08001708 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001709 RTC_LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
htaa2a49d92016-03-04 02:51:39 -08001710 return;
1711 }
1712
Steve Antondffead82018-02-06 10:31:29 -08001713 if (!(signaling_state_ == kHaveRemoteOffer ||
1714 signaling_state_ == kHaveLocalPrAnswer)) {
1715 std::string error =
1716 "PeerConnection cannot create an answer in a state other than "
1717 "have-remote-offer or have-local-pranswer.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001718 RTC_LOG(LS_ERROR) << error;
Steve Anton8d3444d2017-10-20 15:30:51 -07001719 PostCreateSessionDescriptionFailure(observer, error);
1720 return;
1721 }
1722
Steve Antondffead82018-02-06 10:31:29 -08001723 // The remote description should be set if we're in the right state.
1724 RTC_DCHECK(remote_description());
Steve Anton8d3444d2017-10-20 15:30:51 -07001725
Steve Anton22da89f2018-01-25 13:58:07 -08001726 if (IsUnifiedPlan()) {
1727 if (options.offer_to_receive_audio != RTCOfferAnswerOptions::kUndefined) {
1728 RTC_LOG(LS_WARNING) << "CreateAnswer: offer_to_receive_audio is not "
1729 "supported with Unified Plan semantics. Use the "
1730 "RtpTransceiver API instead.";
1731 }
1732 if (options.offer_to_receive_video != RTCOfferAnswerOptions::kUndefined) {
1733 RTC_LOG(LS_WARNING) << "CreateAnswer: offer_to_receive_video is not "
1734 "supported with Unified Plan semantics. Use the "
1735 "RtpTransceiver API instead.";
1736 }
1737 }
1738
htaa2a49d92016-03-04 02:51:39 -08001739 cricket::MediaSessionOptions session_options;
zhihuang1c378ed2017-08-17 14:10:50 -07001740 GetOptionsForAnswer(options, &session_options);
htaa2a49d92016-03-04 02:51:39 -08001741
Steve Antond25da372017-11-06 14:50:29 -08001742 webrtc_session_desc_factory_->CreateAnswer(observer, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001743}
1744
1745void PeerConnection::SetLocalDescription(
1746 SetSessionDescriptionObserver* observer,
Steve Anton80dd7b52018-02-16 17:08:42 -08001747 SessionDescriptionInterface* desc_ptr) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001748 TRACE_EVENT0("webrtc", "PeerConnection::SetLocalDescription");
Steve Anton8a006912017-12-04 15:25:56 -08001749
Steve Anton80dd7b52018-02-16 17:08:42 -08001750 // The SetLocalDescription contract is that we take ownership of the session
1751 // description regardless of the outcome, so wrap it in a unique_ptr right
1752 // away. Ideally, SetLocalDescription's signature will be changed to take the
1753 // description as a unique_ptr argument to formalize this agreement.
1754 std::unique_ptr<SessionDescriptionInterface> desc(desc_ptr);
1755
nisse7ce109a2017-01-31 00:57:56 -08001756 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001757 RTC_LOG(LS_ERROR) << "SetLocalDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001758 return;
1759 }
Steve Anton8a006912017-12-04 15:25:56 -08001760
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001761 if (!desc) {
1762 PostSetSessionDescriptionFailure(observer, "SessionDescription is NULL.");
1763 return;
1764 }
Steve Anton8d3444d2017-10-20 15:30:51 -07001765
Steve Anton80dd7b52018-02-16 17:08:42 -08001766 // If a session error has occurred the PeerConnection is in a possibly
1767 // inconsistent state so fail right away.
1768 if (session_error() != SessionError::kNone) {
1769 std::string error_message = GetSessionErrorMsg();
1770 RTC_LOG(LS_ERROR) << "SetLocalDescription: " << error_message;
1771 PostSetSessionDescriptionFailure(observer, std::move(error_message));
1772 return;
1773 }
Steve Anton8d3444d2017-10-20 15:30:51 -07001774
Steve Anton80dd7b52018-02-16 17:08:42 -08001775 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_LOCAL);
1776 if (!error.ok()) {
1777 std::string error_message = GetSetDescriptionErrorMessage(
1778 cricket::CS_LOCAL, desc->GetType(), error);
1779 RTC_LOG(LS_ERROR) << error_message;
1780 PostSetSessionDescriptionFailure(observer, std::move(error_message));
1781 return;
1782 }
1783
1784 // Grab the description type before moving ownership to ApplyLocalDescription,
1785 // which may destroy it before returning.
1786 const SdpType type = desc->GetType();
1787
1788 error = ApplyLocalDescription(std::move(desc));
Steve Anton8a006912017-12-04 15:25:56 -08001789 // |desc| may be destroyed at this point.
1790
1791 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08001792 // If ApplyLocalDescription fails, the PeerConnection could be in an
1793 // inconsistent state, so act conservatively here and set the session error
1794 // so that future calls to SetLocalDescription/SetRemoteDescription fail.
1795 SetSessionError(SessionError::kContent, error.message());
1796 std::string error_message =
1797 GetSetDescriptionErrorMessage(cricket::CS_LOCAL, type, error);
1798 RTC_LOG(LS_ERROR) << error_message;
Steve Anton8a006912017-12-04 15:25:56 -08001799 PostSetSessionDescriptionFailure(observer, std::move(error_message));
Steve Anton8d3444d2017-10-20 15:30:51 -07001800 return;
1801 }
Steve Anton8a006912017-12-04 15:25:56 -08001802 RTC_DCHECK(local_description());
1803
1804 PostSetSessionDescriptionSuccess(observer);
1805
1806 // According to JSEP, after setLocalDescription, changing the candidate pool
1807 // size is not allowed, and changing the set of ICE servers will not result
1808 // in new candidates being gathered.
1809 port_allocator_->FreezeCandidatePool();
1810
1811 // MaybeStartGathering needs to be called after posting
1812 // MSG_SET_SESSIONDESCRIPTION_SUCCESS, so that we don't signal any candidates
1813 // before signaling that SetLocalDescription completed.
1814 transport_controller_->MaybeStartGathering();
1815
Steve Antona3a92c22017-12-07 10:27:41 -08001816 if (local_description()->GetType() == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08001817 // TODO(deadbeef): We already had to hop to the network thread for
1818 // MaybeStartGathering...
1819 network_thread()->Invoke<void>(
1820 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
1821 port_allocator_.get()));
1822 }
1823}
1824
1825RTCError PeerConnection::ApplyLocalDescription(
1826 std::unique_ptr<SessionDescriptionInterface> desc) {
1827 RTC_DCHECK_RUN_ON(signaling_thread());
1828 RTC_DCHECK(desc);
1829
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001830 // Update stats here so that we have the most recent stats for tracks and
1831 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001832 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 15:25:56 -08001833
1834 // Update the initial_offerer flag if this session is the initial_offerer.
Steve Anton3828c062017-12-06 10:34:51 -08001835 SdpType type = desc->GetType();
Steve Anton8a006912017-12-04 15:25:56 -08001836 if (!initial_offerer_.has_value()) {
Steve Anton3828c062017-12-06 10:34:51 -08001837 initial_offerer_.emplace(type == SdpType::kOffer);
Steve Anton8a006912017-12-04 15:25:56 -08001838 if (*initial_offerer_) {
1839 transport_controller_->SetIceRole(cricket::ICEROLE_CONTROLLING);
1840 } else {
1841 transport_controller_->SetIceRole(cricket::ICEROLE_CONTROLLED);
1842 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001843 }
Steve Anton8a006912017-12-04 15:25:56 -08001844
Steve Antondcc3c022017-12-22 16:02:54 -08001845 // Take a reference to the old local description since it's used below to
1846 // compare against the new local description. When setting the new local
1847 // description, grab ownership of the replaced session description in case it
1848 // is the same as |old_local_description|, to keep it alive for the duration
1849 // of the method.
1850 const SessionDescriptionInterface* old_local_description =
1851 local_description();
1852 std::unique_ptr<SessionDescriptionInterface> replaced_local_description;
Steve Anton3828c062017-12-06 10:34:51 -08001853 if (type == SdpType::kAnswer) {
Steve Antondcc3c022017-12-22 16:02:54 -08001854 replaced_local_description = pending_local_description_
1855 ? std::move(pending_local_description_)
1856 : std::move(current_local_description_);
Steve Anton8a006912017-12-04 15:25:56 -08001857 current_local_description_ = std::move(desc);
1858 pending_local_description_ = nullptr;
1859 current_remote_description_ = std::move(pending_remote_description_);
1860 } else {
Steve Antondcc3c022017-12-22 16:02:54 -08001861 replaced_local_description = std::move(pending_local_description_);
Steve Anton8a006912017-12-04 15:25:56 -08001862 pending_local_description_ = std::move(desc);
1863 }
1864 // The session description to apply now must be accessed by
1865 // |local_description()|.
Henrik Boströmfdb92012017-11-09 19:55:44 +01001866 RTC_DCHECK(local_description());
deadbeefab9b2d12015-10-14 11:33:11 -07001867
Steve Antondcc3c022017-12-22 16:02:54 -08001868 if (IsUnifiedPlan()) {
1869 RTCError error = UpdateTransceiversAndDataChannels(
Seth Hampsonae8a90a2018-02-13 15:33:48 -08001870 cricket::CS_LOCAL, *local_description(), old_local_description,
1871 remote_description());
Steve Anton8a006912017-12-04 15:25:56 -08001872 if (!error.ok()) {
1873 return error;
1874 }
Steve Antondcc3c022017-12-22 16:02:54 -08001875 for (auto transceiver : transceivers_) {
1876 const ContentInfo* content =
1877 FindMediaSectionForTransceiver(transceiver, local_description());
1878 if (!content) {
1879 continue;
1880 }
1881 const MediaContentDescription* media_desc = content->media_description();
1882 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
1883 transceiver->internal()->set_current_direction(media_desc->direction());
1884 }
1885 if (content->rejected && !transceiver->stopped()) {
1886 transceiver->Stop();
1887 }
1888 }
1889 } else {
1890 // Transport and Media channels will be created only when offer is set.
1891 if (type == SdpType::kOffer) {
1892 // TODO(bugs.webrtc.org/4676) - Handle CreateChannel failure, as new local
1893 // description is applied. Restore back to old description.
1894 RTCError error = CreateChannels(*local_description()->description());
1895 if (!error.ok()) {
1896 return error;
1897 }
1898 }
Steve Anton8a006912017-12-04 15:25:56 -08001899
Steve Antondcc3c022017-12-22 16:02:54 -08001900 // Remove unused channels if MediaContentDescription is rejected.
1901 RemoveUnusedChannels(local_description()->description());
1902 }
Steve Anton8a006912017-12-04 15:25:56 -08001903
Steve Anton80dd7b52018-02-16 17:08:42 -08001904 RTCError error = UpdateSessionState(type, cricket::CS_LOCAL);
Steve Anton8a006912017-12-04 15:25:56 -08001905 if (!error.ok()) {
1906 return error;
1907 }
Steve Antondcc3c022017-12-22 16:02:54 -08001908
Steve Anton8a006912017-12-04 15:25:56 -08001909 if (remote_description()) {
1910 // Now that we have a local description, we can push down remote candidates.
1911 UseCandidatesInSessionDescription(remote_description());
1912 }
1913
1914 pending_ice_restarts_.clear();
1915 if (session_error() != SessionError::kNone) {
1916 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
1917 }
1918
deadbeefab9b2d12015-10-14 11:33:11 -07001919 // If setting the description decided our SSL role, allocate any necessary
1920 // SCTP sids.
1921 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08001922 if (data_channel_type() == cricket::DCT_SCTP && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001923 AllocateSctpSids(role);
1924 }
1925
Steve Antond3679212018-01-17 17:41:02 -08001926 if (IsUnifiedPlan()) {
1927 for (auto transceiver : transceivers_) {
1928 const ContentInfo* content =
1929 FindMediaSectionForTransceiver(transceiver, local_description());
1930 if (!content) {
1931 continue;
1932 }
1933 if (content->rejected && !transceiver->stopped()) {
1934 transceiver->Stop();
1935 }
Steve Anton74255ff2018-01-24 18:32:57 -08001936 const auto& streams = content->media_description()->streams();
1937 if (!content->rejected && !streams.empty()) {
Steve Antond3679212018-01-17 17:41:02 -08001938 transceiver->internal()->sender_internal()->set_stream_ids(
Steve Anton74255ff2018-01-24 18:32:57 -08001939 {streams[0].sync_label});
Steve Antond3679212018-01-17 17:41:02 -08001940 transceiver->internal()->sender_internal()->SetSsrc(
Steve Anton74255ff2018-01-24 18:32:57 -08001941 streams[0].first_ssrc());
Steve Antond3679212018-01-17 17:41:02 -08001942 }
1943 }
1944 } else {
1945 // Plan B semantics.
1946
Steve Antondcc3c022017-12-22 16:02:54 -08001947 // Update state and SSRC of local MediaStreams and DataChannels based on the
1948 // local session description.
1949 const cricket::ContentInfo* audio_content =
1950 GetFirstAudioContent(local_description()->description());
1951 if (audio_content) {
1952 if (audio_content->rejected) {
1953 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
1954 } else {
1955 const cricket::AudioContentDescription* audio_desc =
1956 audio_content->media_description()->as_audio();
1957 UpdateLocalSenders(audio_desc->streams(), audio_desc->type());
1958 }
deadbeeffaac4972015-11-12 15:33:07 -08001959 }
deadbeefab9b2d12015-10-14 11:33:11 -07001960
Steve Antondcc3c022017-12-22 16:02:54 -08001961 const cricket::ContentInfo* video_content =
1962 GetFirstVideoContent(local_description()->description());
1963 if (video_content) {
1964 if (video_content->rejected) {
1965 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
1966 } else {
1967 const cricket::VideoContentDescription* video_desc =
1968 video_content->media_description()->as_video();
1969 UpdateLocalSenders(video_desc->streams(), video_desc->type());
1970 }
deadbeeffaac4972015-11-12 15:33:07 -08001971 }
deadbeefab9b2d12015-10-14 11:33:11 -07001972 }
1973
1974 const cricket::ContentInfo* data_content =
Henrik Boströmfdb92012017-11-09 19:55:44 +01001975 GetFirstDataContent(local_description()->description());
deadbeefab9b2d12015-10-14 11:33:11 -07001976 if (data_content) {
1977 const cricket::DataContentDescription* data_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08001978 data_content->media_description()->as_data();
deadbeefab9b2d12015-10-14 11:33:11 -07001979 if (rtc::starts_with(data_desc->protocol().data(),
1980 cricket::kMediaProtocolRtpPrefix)) {
1981 UpdateLocalRtpDataChannels(data_desc->streams());
1982 }
1983 }
1984
Steve Anton8a006912017-12-04 15:25:56 -08001985 return RTCError::OK();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001986}
1987
1988void PeerConnection::SetRemoteDescription(
Henrik Boströma4ecf552017-11-23 14:17:07 +00001989 SetSessionDescriptionObserver* observer,
1990 SessionDescriptionInterface* desc) {
Henrik Boström31638672017-11-23 17:48:32 +01001991 SetRemoteDescription(
1992 std::unique_ptr<SessionDescriptionInterface>(desc),
1993 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface>(
1994 new SetRemoteDescriptionObserverAdapter(this, observer)));
1995}
1996
1997void PeerConnection::SetRemoteDescription(
1998 std::unique_ptr<SessionDescriptionInterface> desc,
1999 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface> observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +01002000 TRACE_EVENT0("webrtc", "PeerConnection::SetRemoteDescription");
Steve Anton8a006912017-12-04 15:25:56 -08002001
nisse7ce109a2017-01-31 00:57:56 -08002002 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002003 RTC_LOG(LS_ERROR) << "SetRemoteDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002004 return;
2005 }
Steve Anton8a006912017-12-04 15:25:56 -08002006
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002007 if (!desc) {
Henrik Boström31638672017-11-23 17:48:32 +01002008 observer->OnSetRemoteDescriptionComplete(RTCError(
Steve Anton8a006912017-12-04 15:25:56 -08002009 RTCErrorType::INVALID_PARAMETER, "SessionDescription is NULL."));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002010 return;
2011 }
Steve Anton8d3444d2017-10-20 15:30:51 -07002012
Steve Anton80dd7b52018-02-16 17:08:42 -08002013 // If a session error has occurred the PeerConnection is in a possibly
2014 // inconsistent state so fail right away.
2015 if (session_error() != SessionError::kNone) {
2016 std::string error_message = GetSessionErrorMsg();
2017 RTC_LOG(LS_ERROR) << "SetRemoteDescription: " << error_message;
2018 observer->OnSetRemoteDescriptionComplete(
2019 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
2020 return;
2021 }
Steve Anton71439a62018-02-15 11:53:06 -08002022
Steve Anton80dd7b52018-02-16 17:08:42 -08002023 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_REMOTE);
Steve Anton71439a62018-02-15 11:53:06 -08002024 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08002025 std::string error_message = GetSetDescriptionErrorMessage(
2026 cricket::CS_REMOTE, desc->GetType(), error);
2027 RTC_LOG(LS_ERROR) << error_message;
Steve Anton71439a62018-02-15 11:53:06 -08002028 observer->OnSetRemoteDescriptionComplete(
2029 RTCError(error.type(), std::move(error_message)));
2030 return;
2031 }
Steve Anton71439a62018-02-15 11:53:06 -08002032
Steve Anton80dd7b52018-02-16 17:08:42 -08002033 // Grab the description type before moving ownership to
2034 // ApplyRemoteDescription, which may destroy it before returning.
2035 const SdpType type = desc->GetType();
2036
2037 error = ApplyRemoteDescription(std::move(desc));
2038 // |desc| may be destroyed at this point.
2039
2040 if (!error.ok()) {
2041 // If ApplyRemoteDescription fails, the PeerConnection could be in an
2042 // inconsistent state, so act conservatively here and set the session error
2043 // so that future calls to SetLocalDescription/SetRemoteDescription fail.
2044 SetSessionError(SessionError::kContent, error.message());
2045 std::string error_message =
2046 GetSetDescriptionErrorMessage(cricket::CS_REMOTE, type, error);
2047 RTC_LOG(LS_ERROR) << error_message;
2048 observer->OnSetRemoteDescriptionComplete(
2049 RTCError(error.type(), std::move(error_message)));
2050 return;
2051 }
2052 RTC_DCHECK(remote_description());
2053
2054 if (type == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002055 // TODO(deadbeef): We already had to hop to the network thread for
2056 // MaybeStartGathering...
2057 network_thread()->Invoke<void>(
2058 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
2059 port_allocator_.get()));
Harald Alvestrand5dbb5862018-02-13 23:48:00 +01002060 // Make UMA notes about what was agreed to.
2061 if (uma_observer_) {
2062 switch (remote_description()->description()->msid_signaling()) {
2063 case 0:
2064 uma_observer_->IncrementEnumCounter(kEnumCounterSdpSemanticNegotiated,
2065 kSdpSemanticNegotiatedNone,
2066 kSdpSemanticNegotiatedMax);
2067 break;
2068 case cricket::kMsidSignalingMediaSection:
2069 uma_observer_->IncrementEnumCounter(kEnumCounterSdpSemanticNegotiated,
2070 kSdpSemanticNegotiatedUnifiedPlan,
2071 kSdpSemanticNegotiatedMax);
2072 break;
2073 case cricket::kMsidSignalingSsrcAttribute:
2074 uma_observer_->IncrementEnumCounter(kEnumCounterSdpSemanticNegotiated,
2075 kSdpSemanticNegotiatedPlanB,
2076 kSdpSemanticNegotiatedMax);
2077 break;
2078 case cricket::kMsidSignalingMediaSection |
2079 cricket::kMsidSignalingSsrcAttribute:
2080 uma_observer_->IncrementEnumCounter(kEnumCounterSdpSemanticNegotiated,
2081 kSdpSemanticNegotiatedMixed,
2082 kSdpSemanticNegotiatedMax);
2083 break;
2084 default:
2085 RTC_NOTREACHED();
2086 }
2087 }
Steve Anton8a006912017-12-04 15:25:56 -08002088 }
2089
2090 observer->OnSetRemoteDescriptionComplete(RTCError::OK());
2091}
2092
2093RTCError PeerConnection::ApplyRemoteDescription(
2094 std::unique_ptr<SessionDescriptionInterface> desc) {
2095 RTC_DCHECK_RUN_ON(signaling_thread());
2096 RTC_DCHECK(desc);
2097
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002098 // Update stats here so that we have the most recent stats for tracks and
2099 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00002100 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 15:25:56 -08002101
Steve Antondcc3c022017-12-22 16:02:54 -08002102 // Take a reference to the old remote description since it's used below to
2103 // compare against the new remote description. When setting the new remote
2104 // description, grab ownership of the replaced session description in case it
2105 // is the same as |old_remote_description|, to keep it alive for the duration
2106 // of the method.
Steve Anton8a006912017-12-04 15:25:56 -08002107 const SessionDescriptionInterface* old_remote_description =
2108 remote_description();
Steve Anton8a006912017-12-04 15:25:56 -08002109 std::unique_ptr<SessionDescriptionInterface> replaced_remote_description;
Steve Anton3828c062017-12-06 10:34:51 -08002110 SdpType type = desc->GetType();
2111 if (type == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002112 replaced_remote_description = pending_remote_description_
2113 ? std::move(pending_remote_description_)
2114 : std::move(current_remote_description_);
2115 current_remote_description_ = std::move(desc);
2116 pending_remote_description_ = nullptr;
2117 current_local_description_ = std::move(pending_local_description_);
2118 } else {
2119 replaced_remote_description = std::move(pending_remote_description_);
2120 pending_remote_description_ = std::move(desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002121 }
Steve Anton8a006912017-12-04 15:25:56 -08002122 // The session description to apply now must be accessed by
2123 // |remote_description()|.
Henrik Boströmfdb92012017-11-09 19:55:44 +01002124 RTC_DCHECK(remote_description());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002125
Steve Anton8a006912017-12-04 15:25:56 -08002126 // Transport and Media channels will be created only when offer is set.
Steve Antondcc3c022017-12-22 16:02:54 -08002127 if (IsUnifiedPlan()) {
2128 RTCError error = UpdateTransceiversAndDataChannels(
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002129 cricket::CS_REMOTE, *remote_description(), local_description(),
2130 old_remote_description);
Steve Anton8a006912017-12-04 15:25:56 -08002131 if (!error.ok()) {
2132 return error;
2133 }
Steve Antondcc3c022017-12-22 16:02:54 -08002134 } else {
2135 if (type == SdpType::kOffer) {
2136 // TODO(bugs.webrtc.org/4676) - Handle CreateChannel failure, as new local
2137 // description is applied. Restore back to old description.
2138 RTCError error = CreateChannels(*remote_description()->description());
2139 if (!error.ok()) {
2140 return error;
2141 }
2142 }
Steve Anton8a006912017-12-04 15:25:56 -08002143
Steve Antondcc3c022017-12-22 16:02:54 -08002144 // Remove unused channels if MediaContentDescription is rejected.
2145 RemoveUnusedChannels(remote_description()->description());
2146 }
Steve Anton8a006912017-12-04 15:25:56 -08002147
2148 // NOTE: Candidates allocation will be initiated only when SetLocalDescription
2149 // is called.
Steve Anton80dd7b52018-02-16 17:08:42 -08002150 RTCError error = UpdateSessionState(type, cricket::CS_REMOTE);
Steve Anton8a006912017-12-04 15:25:56 -08002151 if (!error.ok()) {
2152 return error;
2153 }
2154
2155 if (local_description() &&
2156 !UseCandidatesInSessionDescription(remote_description())) {
2157 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidCandidates);
2158 }
2159
2160 if (old_remote_description) {
2161 for (const cricket::ContentInfo& content :
2162 old_remote_description->description()->contents()) {
2163 // Check if this new SessionDescription contains new ICE ufrag and
2164 // password that indicates the remote peer requests an ICE restart.
2165 // TODO(deadbeef): When we start storing both the current and pending
2166 // remote description, this should reset pending_ice_restarts and compare
2167 // against the current description.
2168 if (CheckForRemoteIceRestart(old_remote_description, remote_description(),
2169 content.name)) {
Steve Anton3828c062017-12-06 10:34:51 -08002170 if (type == SdpType::kOffer) {
Steve Anton8a006912017-12-04 15:25:56 -08002171 pending_ice_restarts_.insert(content.name);
2172 }
2173 } else {
2174 // We retain all received candidates only if ICE is not restarted.
2175 // When ICE is restarted, all previous candidates belong to an old
2176 // generation and should not be kept.
2177 // TODO(deadbeef): This goes against the W3C spec which says the remote
2178 // description should only contain candidates from the last set remote
2179 // description plus any candidates added since then. We should remove
2180 // this once we're sure it won't break anything.
2181 WebRtcSessionDescriptionFactory::CopyCandidatesFromSessionDescription(
2182 old_remote_description, content.name, mutable_remote_description());
2183 }
2184 }
2185 }
2186
2187 if (session_error() != SessionError::kNone) {
2188 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
2189 }
2190
2191 // Set the the ICE connection state to connecting since the connection may
2192 // become writable with peer reflexive candidates before any remote candidate
2193 // is signaled.
2194 // TODO(pthatcher): This is a short-term solution for crbug/446908. A real fix
2195 // is to have a new signal the indicates a change in checking state from the
2196 // transport and expose a new checking() member from transport that can be
2197 // read to determine the current checking state. The existing SignalConnecting
2198 // actually means "gathering candidates", so cannot be be used here.
Steve Antona3a92c22017-12-07 10:27:41 -08002199 if (remote_description()->GetType() != SdpType::kOffer &&
Steve Anton8a006912017-12-04 15:25:56 -08002200 ice_connection_state() == PeerConnectionInterface::kIceConnectionNew) {
2201 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
2202 }
2203
deadbeefab9b2d12015-10-14 11:33:11 -07002204 // If setting the description decided our SSL role, allocate any necessary
2205 // SCTP sids.
2206 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08002207 if (data_channel_type() == cricket::DCT_SCTP && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07002208 AllocateSctpSids(role);
2209 }
2210
Steve Antondcc3c022017-12-22 16:02:54 -08002211 if (IsUnifiedPlan()) {
Steve Anton8b815cd2018-02-16 16:14:42 -08002212 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
2213 receiving_transceivers;
Steve Antonc49bcd92018-02-14 14:28:13 -08002214 std::vector<rtc::scoped_refptr<MediaStreamInterface>> added_streams;
Steve Antondcc3c022017-12-22 16:02:54 -08002215 for (auto transceiver : transceivers_) {
2216 const ContentInfo* content =
2217 FindMediaSectionForTransceiver(transceiver, remote_description());
2218 if (!content) {
2219 continue;
2220 }
2221 const MediaContentDescription* media_desc = content->media_description();
2222 RtpTransceiverDirection local_direction =
2223 RtpTransceiverDirectionReversed(media_desc->direction());
2224 // From the WebRTC specification, steps 2.2.8.5/6 of section 4.4.1.6 "Set
2225 // the RTCSessionDescription: If direction is sendrecv or recvonly, and
2226 // transceiver's current direction is neither sendrecv nor recvonly,
2227 // process the addition of a remote track for the media description.
2228 if (RtpTransceiverDirectionHasRecv(local_direction) &&
2229 (!transceiver->current_direction() ||
2230 !RtpTransceiverDirectionHasRecv(
Steve Anton74255ff2018-01-24 18:32:57 -08002231 *transceiver->current_direction())) &&
2232 !media_desc->streams().empty()) {
Steve Antonef65ef12018-01-10 17:15:20 -08002233 const std::string& sync_label = media_desc->streams()[0].sync_label;
2234 rtc::scoped_refptr<MediaStreamInterface> stream =
2235 remote_streams_->find(sync_label);
2236 if (!stream) {
2237 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
2238 MediaStream::Create(sync_label));
2239 remote_streams_->AddStream(stream);
Steve Antonc49bcd92018-02-14 14:28:13 -08002240 added_streams.push_back(stream);
Steve Antonef65ef12018-01-10 17:15:20 -08002241 }
2242 transceiver->internal()->receiver_internal()->SetStreams({stream});
Steve Anton8b815cd2018-02-16 16:14:42 -08002243 receiving_transceivers.push_back(transceiver);
Steve Antondcc3c022017-12-22 16:02:54 -08002244 }
2245 // If direction is sendonly or inactive, and transceiver's current
2246 // direction is neither sendonly nor inactive, process the removal of a
2247 // remote track for the media description.
2248 if (!RtpTransceiverDirectionHasRecv(local_direction) &&
Steve Antonef65ef12018-01-10 17:15:20 -08002249 (transceiver->current_direction() &&
Steve Antondcc3c022017-12-22 16:02:54 -08002250 RtpTransceiverDirectionHasRecv(*transceiver->current_direction()))) {
Steve Antonef65ef12018-01-10 17:15:20 -08002251 transceiver->internal()->receiver_internal()->SetStreams({});
Steve Antondcc3c022017-12-22 16:02:54 -08002252 }
2253 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
2254 transceiver->internal()->set_current_direction(local_direction);
2255 }
2256 if (content->rejected && !transceiver->stopped()) {
2257 transceiver->Stop();
2258 }
Steve Anton74255ff2018-01-24 18:32:57 -08002259 if (!content->rejected && !media_desc->streams().empty()) {
Steve Antond3679212018-01-17 17:41:02 -08002260 transceiver->internal()->receiver_internal()->SetupMediaChannel(
Steve Anton5f94aa22018-02-01 10:58:30 -08002261 media_desc->streams()[0].first_ssrc());
Steve Antond3679212018-01-17 17:41:02 -08002262 }
Steve Antondcc3c022017-12-22 16:02:54 -08002263 }
Steve Antonc49bcd92018-02-14 14:28:13 -08002264 // Once all processing has finished, fire off callbacks.
Steve Anton8b815cd2018-02-16 16:14:42 -08002265 for (auto transceiver : receiving_transceivers) {
2266 observer_->OnTrack(transceiver);
2267 observer_->OnAddTrack(transceiver->receiver(),
2268 transceiver->receiver()->streams());
Steve Antonef65ef12018-01-10 17:15:20 -08002269 }
Steve Antonc49bcd92018-02-14 14:28:13 -08002270 for (auto stream : added_streams) {
2271 observer_->OnAddStream(stream);
2272 }
Steve Antondcc3c022017-12-22 16:02:54 -08002273 }
2274
Henrik Boströmfdb92012017-11-09 19:55:44 +01002275 const cricket::ContentInfo* audio_content =
2276 GetFirstAudioContent(remote_description()->description());
2277 const cricket::ContentInfo* video_content =
2278 GetFirstVideoContent(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002279 const cricket::AudioContentDescription* audio_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002280 GetFirstAudioContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002281 const cricket::VideoContentDescription* video_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002282 GetFirstVideoContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002283 const cricket::DataContentDescription* data_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002284 GetFirstDataContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002285
2286 // Check if the descriptions include streams, just in case the peer supports
2287 // MSID, but doesn't indicate so with "a=msid-semantic".
Henrik Boströmfdb92012017-11-09 19:55:44 +01002288 if (remote_description()->description()->msid_supported() ||
deadbeefbda7e0b2015-12-08 17:13:40 -08002289 (audio_desc && !audio_desc->streams().empty()) ||
2290 (video_desc && !video_desc->streams().empty())) {
2291 remote_peer_supports_msid_ = true;
2292 }
deadbeefab9b2d12015-10-14 11:33:11 -07002293
2294 // We wait to signal new streams until we finish processing the description,
2295 // since only at that point will new streams have all their tracks.
2296 rtc::scoped_refptr<StreamCollection> new_streams(StreamCollection::Create());
2297
Steve Antondcc3c022017-12-22 16:02:54 -08002298 if (!IsUnifiedPlan()) {
2299 // TODO(steveanton): When removing RTP senders/receivers in response to a
2300 // rejected media section, there is some cleanup logic that expects the
2301 // voice/ video channel to still be set. But in this method the voice/video
2302 // channel would have been destroyed by the SetRemoteDescription caller
2303 // above so the cleanup that relies on them fails to run. The RemoveSenders
2304 // calls should be moved to right before the DestroyChannel calls to fix
2305 // this.
Steve Anton8d3444d2017-10-20 15:30:51 -07002306
Steve Antondcc3c022017-12-22 16:02:54 -08002307 // Find all audio rtp streams and create corresponding remote AudioTracks
2308 // and MediaStreams.
2309 if (audio_content) {
2310 if (audio_content->rejected) {
2311 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
2312 } else {
2313 bool default_audio_track_needed =
2314 !remote_peer_supports_msid_ &&
2315 RtpTransceiverDirectionHasSend(audio_desc->direction());
2316 UpdateRemoteSendersList(GetActiveStreams(audio_desc),
2317 default_audio_track_needed, audio_desc->type(),
2318 new_streams);
2319 }
deadbeeffaac4972015-11-12 15:33:07 -08002320 }
deadbeefab9b2d12015-10-14 11:33:11 -07002321
Steve Antondcc3c022017-12-22 16:02:54 -08002322 // Find all video rtp streams and create corresponding remote VideoTracks
2323 // and MediaStreams.
2324 if (video_content) {
2325 if (video_content->rejected) {
2326 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
2327 } else {
2328 bool default_video_track_needed =
2329 !remote_peer_supports_msid_ &&
2330 RtpTransceiverDirectionHasSend(video_desc->direction());
2331 UpdateRemoteSendersList(GetActiveStreams(video_desc),
2332 default_video_track_needed, video_desc->type(),
2333 new_streams);
2334 }
deadbeeffaac4972015-11-12 15:33:07 -08002335 }
deadbeefab9b2d12015-10-14 11:33:11 -07002336
Steve Antondcc3c022017-12-22 16:02:54 -08002337 // Update the DataChannels with the information from the remote peer.
2338 if (data_desc) {
2339 if (rtc::starts_with(data_desc->protocol().data(),
2340 cricket::kMediaProtocolRtpPrefix)) {
2341 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
2342 }
deadbeefab9b2d12015-10-14 11:33:11 -07002343 }
deadbeefab9b2d12015-10-14 11:33:11 -07002344
Steve Antondcc3c022017-12-22 16:02:54 -08002345 // Iterate new_streams and notify the observer about new MediaStreams.
2346 for (size_t i = 0; i < new_streams->count(); ++i) {
2347 MediaStreamInterface* new_stream = new_streams->at(i);
2348 stats_->AddStream(new_stream);
2349 observer_->OnAddStream(
2350 rtc::scoped_refptr<MediaStreamInterface>(new_stream));
2351 }
deadbeefab9b2d12015-10-14 11:33:11 -07002352
Steve Antondcc3c022017-12-22 16:02:54 -08002353 UpdateEndedRemoteMediaStreams();
2354 }
deadbeefab9b2d12015-10-14 11:33:11 -07002355
Steve Anton8a006912017-12-04 15:25:56 -08002356 return RTCError::OK();
deadbeeffc648b62015-10-13 16:42:33 -07002357}
2358
Steve Antondcc3c022017-12-22 16:02:54 -08002359RTCError PeerConnection::UpdateTransceiversAndDataChannels(
2360 cricket::ContentSource source,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002361 const SessionDescriptionInterface& new_session,
2362 const SessionDescriptionInterface* old_local_description,
2363 const SessionDescriptionInterface* old_remote_description) {
Steve Antondcc3c022017-12-22 16:02:54 -08002364 RTC_DCHECK(IsUnifiedPlan());
2365
Steve Anton7464fca2018-01-19 11:10:37 -08002366 const cricket::ContentGroup* bundle_group = nullptr;
2367 if (new_session.GetType() == SdpType::kOffer) {
2368 auto bundle_group_or_error =
2369 GetEarlyBundleGroup(*new_session.description());
2370 if (!bundle_group_or_error.ok()) {
2371 return bundle_group_or_error.MoveError();
2372 }
2373 bundle_group = bundle_group_or_error.MoveValue();
Steve Antondcc3c022017-12-22 16:02:54 -08002374 }
Steve Antondcc3c022017-12-22 16:02:54 -08002375
Steve Antondcc3c022017-12-22 16:02:54 -08002376 const ContentInfos& new_contents = new_session.description()->contents();
Steve Antondcc3c022017-12-22 16:02:54 -08002377 for (size_t i = 0; i < new_contents.size(); ++i) {
2378 const cricket::ContentInfo& new_content = new_contents[i];
Steve Antondcc3c022017-12-22 16:02:54 -08002379 cricket::MediaType media_type = new_content.media_description()->type();
2380 seen_mids_.insert(new_content.name);
2381 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
2382 media_type == cricket::MEDIA_TYPE_VIDEO) {
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002383 const cricket::ContentInfo* old_local_content = nullptr;
2384 if (old_local_description &&
2385 i < old_local_description->description()->contents().size()) {
2386 old_local_content =
2387 &old_local_description->description()->contents()[i];
2388 }
2389 const cricket::ContentInfo* old_remote_content = nullptr;
2390 if (old_remote_description &&
2391 i < old_remote_description->description()->contents().size()) {
2392 old_remote_content =
2393 &old_remote_description->description()->contents()[i];
2394 }
Steve Antondcc3c022017-12-22 16:02:54 -08002395 auto transceiver_or_error =
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002396 AssociateTransceiver(source, new_session.GetType(), i, new_content,
2397 old_local_content, old_remote_content);
Steve Antondcc3c022017-12-22 16:02:54 -08002398 if (!transceiver_or_error.ok()) {
2399 return transceiver_or_error.MoveError();
2400 }
2401 auto transceiver = transceiver_or_error.MoveValue();
Steve Antondcc3c022017-12-22 16:02:54 -08002402 RTCError error =
2403 UpdateTransceiverChannel(transceiver, new_content, bundle_group);
2404 if (!error.ok()) {
2405 return error;
2406 }
2407 } else if (media_type == cricket::MEDIA_TYPE_DATA) {
Steve Antonfa2260d2017-12-28 16:38:23 -08002408 if (GetDataMid() && new_content.name != *GetDataMid()) {
2409 // Ignore all but the first data section.
2410 continue;
2411 }
2412 RTCError error = UpdateDataChannel(source, new_content, bundle_group);
2413 if (!error.ok()) {
2414 return error;
2415 }
Steve Antondcc3c022017-12-22 16:02:54 -08002416 } else {
2417 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
2418 "Unknown section type.");
2419 }
2420 }
2421
2422 return RTCError::OK();
2423}
2424
2425RTCError PeerConnection::UpdateTransceiverChannel(
2426 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2427 transceiver,
2428 const cricket::ContentInfo& content,
2429 const cricket::ContentGroup* bundle_group) {
2430 RTC_DCHECK(IsUnifiedPlan());
2431 RTC_DCHECK(transceiver);
2432 cricket::BaseChannel* channel = transceiver->internal()->channel();
2433 if (content.rejected) {
2434 if (channel) {
2435 transceiver->internal()->SetChannel(nullptr);
2436 DestroyBaseChannel(channel);
2437 }
2438 } else {
2439 if (!channel) {
Steve Anton69470252018-02-09 11:43:08 -08002440 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Steve Antondcc3c022017-12-22 16:02:54 -08002441 channel = CreateVoiceChannel(
2442 content.name,
2443 GetTransportNameForMediaSection(content.name, bundle_group));
2444 } else {
Steve Anton69470252018-02-09 11:43:08 -08002445 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, transceiver->media_type());
Steve Antondcc3c022017-12-22 16:02:54 -08002446 channel = CreateVideoChannel(
2447 content.name,
2448 GetTransportNameForMediaSection(content.name, bundle_group));
2449 }
2450 if (!channel) {
2451 LOG_AND_RETURN_ERROR(
2452 RTCErrorType::INTERNAL_ERROR,
2453 "Failed to create channel for mid=" + content.name);
2454 }
2455 transceiver->internal()->SetChannel(channel);
2456 }
2457 }
2458 return RTCError::OK();
2459}
2460
Steve Antonfa2260d2017-12-28 16:38:23 -08002461RTCError PeerConnection::UpdateDataChannel(
2462 cricket::ContentSource source,
2463 const cricket::ContentInfo& content,
2464 const cricket::ContentGroup* bundle_group) {
2465 if (data_channel_type_ == cricket::DCT_NONE) {
Steve Antondbf9d032018-01-19 15:23:40 -08002466 // If data channels are disabled, ignore this media section. CreateAnswer
2467 // will take care of rejecting it.
2468 return RTCError::OK();
Steve Antonfa2260d2017-12-28 16:38:23 -08002469 }
2470 if (content.rejected) {
2471 DestroyDataChannel();
2472 } else {
2473 if (!rtp_data_channel_ && !sctp_transport_) {
2474 if (!CreateDataChannel(content.name, GetTransportNameForMediaSection(
2475 content.name, bundle_group))) {
2476 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
2477 "Failed to create data channel.");
2478 }
2479 }
2480 if (source == cricket::CS_REMOTE) {
2481 const MediaContentDescription* data_desc = content.media_description();
2482 if (data_desc && cricket::IsRtpProtocol(data_desc->protocol())) {
2483 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
2484 }
2485 }
2486 }
2487 return RTCError::OK();
2488}
2489
Steve Antondcc3c022017-12-22 16:02:54 -08002490RTCErrorOr<rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
2491PeerConnection::AssociateTransceiver(cricket::ContentSource source,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002492 SdpType type,
Steve Antondcc3c022017-12-22 16:02:54 -08002493 size_t mline_index,
2494 const ContentInfo& content,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002495 const ContentInfo* old_local_content,
2496 const ContentInfo* old_remote_content) {
Steve Antondcc3c022017-12-22 16:02:54 -08002497 RTC_DCHECK(IsUnifiedPlan());
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002498 // If this is an offer then the m= section might be recycled. If the m=
2499 // section is being recycled (defined as: rejected in the current local or
2500 // remote description and not rejected in new description), dissociate the
2501 // currently associated RtpTransceiver by setting its mid property to null,
2502 // and discard the mapping between the transceiver and its m= section index.
2503 if (IsMediaSectionBeingRecycled(type, content, old_local_content,
2504 old_remote_content)) {
2505 // We want to dissociate the transceiver that has the rejected mid.
2506 const std::string& old_mid =
2507 (old_local_content && old_local_content->rejected)
2508 ? old_local_content->name
2509 : old_remote_content->name;
2510 auto old_transceiver = GetAssociatedTransceiver(old_mid);
Steve Antondcc3c022017-12-22 16:02:54 -08002511 if (old_transceiver) {
2512 old_transceiver->internal()->set_mid(rtc::nullopt);
2513 old_transceiver->internal()->set_mline_index(rtc::nullopt);
2514 }
2515 }
2516 const MediaContentDescription* media_desc = content.media_description();
2517 auto transceiver = GetAssociatedTransceiver(content.name);
2518 if (source == cricket::CS_LOCAL) {
2519 // Find the RtpTransceiver that corresponds to this m= section, using the
2520 // mapping between transceivers and m= section indices established when
2521 // creating the offer.
2522 if (!transceiver) {
2523 transceiver = GetTransceiverByMLineIndex(mline_index);
2524 }
2525 if (!transceiver) {
2526 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2527 "Unknown transceiver");
2528 }
2529 } else {
2530 RTC_DCHECK_EQ(source, cricket::CS_REMOTE);
2531 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers
2532 // of the same type...
2533 if (!transceiver &&
2534 RtpTransceiverDirectionHasRecv(media_desc->direction())) {
2535 transceiver = FindAvailableTransceiverToReceive(media_desc->type());
2536 }
2537 // If no RtpTransceiver was found in the previous step, create one with a
2538 // recvonly direction.
2539 if (!transceiver) {
Steve Anton02ee47c2018-01-10 16:26:06 -08002540 auto sender =
2541 CreateSender(media_desc->type(), nullptr, {rtc::CreateRandomUuid()});
Steve Anton5f94aa22018-02-01 10:58:30 -08002542 std::string receiver_id;
2543 if (!media_desc->streams().empty()) {
2544 receiver_id = media_desc->streams()[0].id;
2545 } else {
2546 receiver_id = rtc::CreateRandomUuid();
2547 }
2548 auto receiver = CreateReceiver(media_desc->type(), receiver_id);
Steve Anton02ee47c2018-01-10 16:26:06 -08002549 transceiver = CreateAndAddTransceiver(sender, receiver);
Steve Antondcc3c022017-12-22 16:02:54 -08002550 transceiver->internal()->set_direction(
2551 RtpTransceiverDirection::kRecvOnly);
2552 }
2553 }
2554 RTC_DCHECK(transceiver);
Steve Anton69470252018-02-09 11:43:08 -08002555 if (transceiver->media_type() != media_desc->type()) {
Steve Antondcc3c022017-12-22 16:02:54 -08002556 LOG_AND_RETURN_ERROR(
2557 RTCErrorType::INVALID_PARAMETER,
2558 "Transceiver type does not match media description type.");
2559 }
2560 // Associate the found or created RtpTransceiver with the m= section by
2561 // setting the value of the RtpTransceiver's mid property to the MID of the m=
2562 // section, and establish a mapping between the transceiver and the index of
2563 // the m= section.
2564 transceiver->internal()->set_mid(content.name);
2565 transceiver->internal()->set_mline_index(mline_index);
2566 return std::move(transceiver);
2567}
2568
2569rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2570PeerConnection::GetAssociatedTransceiver(const std::string& mid) const {
2571 RTC_DCHECK(IsUnifiedPlan());
2572 for (auto transceiver : transceivers_) {
2573 if (transceiver->mid() == mid) {
2574 return transceiver;
2575 }
2576 }
2577 return nullptr;
2578}
2579
2580rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2581PeerConnection::GetTransceiverByMLineIndex(size_t mline_index) const {
2582 RTC_DCHECK(IsUnifiedPlan());
2583 for (auto transceiver : transceivers_) {
2584 if (transceiver->internal()->mline_index() == mline_index) {
2585 return transceiver;
2586 }
2587 }
2588 return nullptr;
2589}
2590
2591rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2592PeerConnection::FindAvailableTransceiverToReceive(
2593 cricket::MediaType media_type) const {
2594 RTC_DCHECK(IsUnifiedPlan());
2595 // From JSEP section 5.10 (Applying a Remote Description):
2596 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers of
2597 // the same type that were added to the PeerConnection by addTrack and are not
2598 // associated with any m= section and are not stopped, find the first such
2599 // RtpTransceiver.
2600 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08002601 if (transceiver->media_type() == media_type &&
Steve Antondcc3c022017-12-22 16:02:54 -08002602 transceiver->internal()->created_by_addtrack() && !transceiver->mid() &&
2603 !transceiver->stopped()) {
2604 return transceiver;
2605 }
2606 }
2607 return nullptr;
2608}
2609
Steve Antoned10bd92017-12-05 10:52:59 -08002610const cricket::ContentInfo* PeerConnection::FindMediaSectionForTransceiver(
2611 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2612 transceiver,
2613 const SessionDescriptionInterface* sdesc) const {
2614 RTC_DCHECK(transceiver);
2615 RTC_DCHECK(sdesc);
2616 if (IsUnifiedPlan()) {
2617 if (!transceiver->internal()->mid()) {
2618 // This transceiver is not associated with a media section yet.
2619 return nullptr;
2620 }
2621 return sdesc->description()->GetContentByName(
2622 *transceiver->internal()->mid());
2623 } else {
2624 // Plan B only allows at most one audio and one video section, so use the
2625 // first media section of that type.
2626 return cricket::GetFirstMediaContent(sdesc->description()->contents(),
Steve Anton69470252018-02-09 11:43:08 -08002627 transceiver->media_type());
Steve Antoned10bd92017-12-05 10:52:59 -08002628 }
2629}
2630
deadbeef46c73892016-11-16 19:42:04 -08002631PeerConnectionInterface::RTCConfiguration PeerConnection::GetConfiguration() {
2632 return configuration_;
2633}
2634
deadbeef293e9262017-01-11 12:28:30 -08002635bool PeerConnection::SetConfiguration(const RTCConfiguration& configuration,
2636 RTCError* error) {
Peter Boström1a9d6152015-12-08 22:15:17 +01002637 TRACE_EVENT0("webrtc", "PeerConnection::SetConfiguration");
deadbeef6de92f92016-12-12 18:49:32 -08002638
Steve Anton75737c02017-11-06 10:37:17 -08002639 if (local_description() && configuration.ice_candidate_pool_size !=
2640 configuration_.ice_candidate_pool_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002641 RTC_LOG(LS_ERROR) << "Can't change candidate pool size after calling "
2642 "SetLocalDescription.";
deadbeef293e9262017-01-11 12:28:30 -08002643 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00002644 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002645
deadbeef293e9262017-01-11 12:28:30 -08002646 // The simplest (and most future-compatible) way to tell if the config was
2647 // modified in an invalid way is to copy each property we do support
2648 // modifying, then use operator==. There are far more properties we don't
2649 // support modifying than those we do, and more could be added.
2650 RTCConfiguration modified_config = configuration_;
2651 modified_config.servers = configuration.servers;
2652 modified_config.type = configuration.type;
2653 modified_config.ice_candidate_pool_size =
2654 configuration.ice_candidate_pool_size;
2655 modified_config.prune_turn_ports = configuration.prune_turn_ports;
skvladd1f5fda2017-02-03 16:54:05 -08002656 modified_config.ice_check_min_interval = configuration.ice_check_min_interval;
Jonas Orelandbdcee282017-10-10 14:01:40 +02002657 modified_config.turn_customizer = configuration.turn_customizer;
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08002658 modified_config.network_preference = configuration.network_preference;
deadbeef293e9262017-01-11 12:28:30 -08002659 if (configuration != modified_config) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002660 RTC_LOG(LS_ERROR) << "Modifying the configuration in an unsupported way.";
deadbeef293e9262017-01-11 12:28:30 -08002661 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
2662 }
2663
Steve Anton038834f2017-07-14 15:59:59 -07002664 // Validate the modified configuration.
2665 RTCError validate_error = ValidateConfiguration(modified_config);
2666 if (!validate_error.ok()) {
2667 return SafeSetError(std::move(validate_error), error);
2668 }
2669
deadbeef293e9262017-01-11 12:28:30 -08002670 // Note that this isn't possible through chromium, since it's an unsigned
2671 // short in WebIDL.
2672 if (configuration.ice_candidate_pool_size < 0 ||
2673 configuration.ice_candidate_pool_size > UINT16_MAX) {
2674 return SafeSetError(RTCErrorType::INVALID_RANGE, error);
2675 }
2676
2677 // Parse ICE servers before hopping to network thread.
2678 cricket::ServerAddresses stun_servers;
2679 std::vector<cricket::RelayServerConfig> turn_servers;
2680 RTCErrorType parse_error =
2681 ParseIceServers(configuration.servers, &stun_servers, &turn_servers);
2682 if (parse_error != RTCErrorType::NONE) {
2683 return SafeSetError(parse_error, error);
2684 }
2685
2686 // In theory this shouldn't fail.
2687 if (!network_thread()->Invoke<bool>(
2688 RTC_FROM_HERE,
2689 rtc::Bind(&PeerConnection::ReconfigurePortAllocator_n, this,
2690 stun_servers, turn_servers, modified_config.type,
2691 modified_config.ice_candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02002692 modified_config.prune_turn_ports,
2693 modified_config.turn_customizer))) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002694 RTC_LOG(LS_ERROR) << "Failed to apply configuration to PortAllocator.";
deadbeef293e9262017-01-11 12:28:30 -08002695 return SafeSetError(RTCErrorType::INTERNAL_ERROR, error);
2696 }
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07002697
deadbeefd1a38b52016-12-10 13:15:33 -08002698 // As described in JSEP, calling setConfiguration with new ICE servers or
2699 // candidate policy must set a "needs-ice-restart" bit so that the next offer
2700 // triggers an ICE restart which will pick up the changes.
deadbeef293e9262017-01-11 12:28:30 -08002701 if (modified_config.servers != configuration_.servers ||
2702 modified_config.type != configuration_.type ||
2703 modified_config.prune_turn_ports != configuration_.prune_turn_ports) {
Steve Antond25da372017-11-06 14:50:29 -08002704 transport_controller_->SetNeedsIceRestartFlag();
deadbeefd1a38b52016-12-10 13:15:33 -08002705 }
skvladd1f5fda2017-02-03 16:54:05 -08002706
Qingsi Wang9c98f0c2018-02-15 15:10:59 -08002707 transport_controller_->SetIceConfig(ParseIceConfig(modified_config));
skvladd1f5fda2017-02-03 16:54:05 -08002708
deadbeef293e9262017-01-11 12:28:30 -08002709 configuration_ = modified_config;
2710 return SafeSetError(RTCErrorType::NONE, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00002711}
2712
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002713bool PeerConnection::AddIceCandidate(
2714 const IceCandidateInterface* ice_candidate) {
Peter Boström1a9d6152015-12-08 22:15:17 +01002715 TRACE_EVENT0("webrtc", "PeerConnection::AddIceCandidate");
zhihuang29ff8442016-07-27 11:07:25 -07002716 if (IsClosed()) {
2717 return false;
2718 }
Steve Antond25da372017-11-06 14:50:29 -08002719
2720 if (!remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002721 RTC_LOG(LS_ERROR) << "ProcessIceMessage: ICE candidates can't be added "
Jonas Olsson45cc8902018-02-13 10:37:07 +01002722 "without any remote session description.";
Steve Antond25da372017-11-06 14:50:29 -08002723 return false;
2724 }
2725
2726 if (!ice_candidate) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002727 RTC_LOG(LS_ERROR) << "ProcessIceMessage: Candidate is NULL.";
Steve Antond25da372017-11-06 14:50:29 -08002728 return false;
2729 }
2730
2731 bool valid = false;
2732 bool ready = ReadyToUseRemoteCandidate(ice_candidate, nullptr, &valid);
2733 if (!valid) {
2734 return false;
2735 }
2736
2737 // Add this candidate to the remote session description.
2738 if (!mutable_remote_description()->AddCandidate(ice_candidate)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002739 RTC_LOG(LS_ERROR) << "ProcessIceMessage: Candidate cannot be used.";
Steve Antond25da372017-11-06 14:50:29 -08002740 return false;
2741 }
2742
2743 if (ready) {
2744 return UseCandidate(ice_candidate);
2745 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002746 RTC_LOG(LS_INFO) << "ProcessIceMessage: Not ready to use candidate.";
Steve Antond25da372017-11-06 14:50:29 -08002747 return true;
2748 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002749}
2750
Honghai Zhang7fb69db2016-03-14 11:59:18 -07002751bool PeerConnection::RemoveIceCandidates(
2752 const std::vector<cricket::Candidate>& candidates) {
2753 TRACE_EVENT0("webrtc", "PeerConnection::RemoveIceCandidates");
Steve Antond25da372017-11-06 14:50:29 -08002754 if (!remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002755 RTC_LOG(LS_ERROR) << "RemoveRemoteIceCandidates: ICE candidates can't be "
Jonas Olsson45cc8902018-02-13 10:37:07 +01002756 "removed without any remote session description.";
Steve Antond25da372017-11-06 14:50:29 -08002757 return false;
2758 }
2759
2760 if (candidates.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002761 RTC_LOG(LS_ERROR) << "RemoveRemoteIceCandidates: candidates are empty.";
Steve Antond25da372017-11-06 14:50:29 -08002762 return false;
2763 }
2764
2765 size_t number_removed =
2766 mutable_remote_description()->RemoveCandidates(candidates);
2767 if (number_removed != candidates.size()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002768 RTC_LOG(LS_ERROR)
2769 << "RemoveRemoteIceCandidates: Failed to remove candidates. "
Jonas Olsson45cc8902018-02-13 10:37:07 +01002770 "Requested "
2771 << candidates.size() << " but only " << number_removed
Mirko Bonadei675513b2017-11-09 11:09:25 +01002772 << " are removed.";
Steve Antond25da372017-11-06 14:50:29 -08002773 }
2774
2775 // Remove the candidates from the transport controller.
2776 std::string error;
2777 bool res = transport_controller_->RemoveRemoteCandidates(candidates, &error);
2778 if (!res && !error.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002779 RTC_LOG(LS_ERROR) << "Error when removing remote candidates: " << error;
Steve Antond25da372017-11-06 14:50:29 -08002780 }
2781 return true;
Honghai Zhang7fb69db2016-03-14 11:59:18 -07002782}
2783
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00002784void PeerConnection::RegisterUMAObserver(UMAObserver* observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +01002785 TRACE_EVENT0("webrtc", "PeerConnection::RegisterUmaObserver");
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00002786 uma_observer_ = observer;
guoweis@webrtc.org7169afd2014-12-04 17:59:29 +00002787
Steve Anton75737c02017-11-06 10:37:17 -08002788 if (transport_controller()) {
2789 transport_controller()->SetMetricsObserver(uma_observer_);
guoweis@webrtc.org7169afd2014-12-04 17:59:29 +00002790 }
2791
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00002792 // Send information about IPv4/IPv6 status.
deadbeef293e9262017-01-11 12:28:30 -08002793 if (uma_observer_) {
Honghai Zhangd93f50c2016-10-05 11:47:22 -07002794 port_allocator_->SetMetricsObserver(uma_observer_);
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00002795 if (port_allocator_->flags() & cricket::PORTALLOCATOR_ENABLE_IPV6) {
Guo-wei Shiehdfbe6792015-09-03 17:12:07 -07002796 uma_observer_->IncrementEnumCounter(
2797 kEnumCounterAddressFamily, kPeerConnection_IPv6,
2798 kPeerConnectionAddressFamilyCounter_Max);
mallinath@webrtc.orgb445f262014-05-23 22:19:37 +00002799 } else {
Guo-wei Shiehdfbe6792015-09-03 17:12:07 -07002800 uma_observer_->IncrementEnumCounter(
2801 kEnumCounterAddressFamily, kPeerConnection_IPv4,
2802 kPeerConnectionAddressFamilyCounter_Max);
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00002803 }
Harald Alvestrand5dbb5862018-02-13 23:48:00 +01002804 // Send information about the requested SDP semantics.
2805 switch (configuration_.sdp_semantics) {
2806 case SdpSemantics::kDefault:
2807 uma_observer_->IncrementEnumCounter(kEnumCounterSdpSemanticRequested,
2808 kSdpSemanticRequestDefault,
2809 kSdpSemanticRequestMax);
2810
2811 break;
2812 case SdpSemantics::kPlanB:
2813 uma_observer_->IncrementEnumCounter(kEnumCounterSdpSemanticRequested,
2814 kSdpSemanticRequestPlanB,
2815 kSdpSemanticRequestMax);
2816 break;
2817 case SdpSemantics::kUnifiedPlan:
2818 uma_observer_->IncrementEnumCounter(kEnumCounterSdpSemanticRequested,
2819 kSdpSemanticRequestUnifiedPlan,
2820 kSdpSemanticRequestMax);
2821 break;
2822 default:
2823 RTC_NOTREACHED();
2824 }
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00002825 }
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00002826}
2827
zstein4b979802017-06-02 14:37:37 -07002828RTCError PeerConnection::SetBitrate(const BitrateParameters& bitrate) {
Steve Anton978b8762017-09-29 12:15:02 -07002829 if (!worker_thread()->IsCurrent()) {
2830 return worker_thread()->Invoke<RTCError>(
zstein4b979802017-06-02 14:37:37 -07002831 RTC_FROM_HERE, rtc::Bind(&PeerConnection::SetBitrate, this, bitrate));
2832 }
2833
2834 const bool has_min = static_cast<bool>(bitrate.min_bitrate_bps);
2835 const bool has_current = static_cast<bool>(bitrate.current_bitrate_bps);
2836 const bool has_max = static_cast<bool>(bitrate.max_bitrate_bps);
2837 if (has_min && *bitrate.min_bitrate_bps < 0) {
2838 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2839 "min_bitrate_bps <= 0");
2840 }
2841 if (has_current) {
2842 if (has_min && *bitrate.current_bitrate_bps < *bitrate.min_bitrate_bps) {
2843 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2844 "current_bitrate_bps < min_bitrate_bps");
2845 } else if (*bitrate.current_bitrate_bps < 0) {
2846 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2847 "curent_bitrate_bps < 0");
2848 }
2849 }
2850 if (has_max) {
2851 if (has_current &&
2852 *bitrate.max_bitrate_bps < *bitrate.current_bitrate_bps) {
2853 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2854 "max_bitrate_bps < current_bitrate_bps");
2855 } else if (has_min && *bitrate.max_bitrate_bps < *bitrate.min_bitrate_bps) {
2856 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2857 "max_bitrate_bps < min_bitrate_bps");
2858 } else if (*bitrate.max_bitrate_bps < 0) {
2859 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2860 "max_bitrate_bps < 0");
2861 }
2862 }
2863
2864 Call::Config::BitrateConfigMask mask;
2865 mask.min_bitrate_bps = bitrate.min_bitrate_bps;
2866 mask.start_bitrate_bps = bitrate.current_bitrate_bps;
2867 mask.max_bitrate_bps = bitrate.max_bitrate_bps;
2868
2869 RTC_DCHECK(call_.get());
2870 call_->SetBitrateConfigMask(mask);
2871
2872 return RTCError::OK();
2873}
2874
Alex Narest78609d52017-10-20 10:37:47 +02002875void PeerConnection::SetBitrateAllocationStrategy(
2876 std::unique_ptr<rtc::BitrateAllocationStrategy>
2877 bitrate_allocation_strategy) {
2878 rtc::Thread* worker_thread = factory_->worker_thread();
2879 if (!worker_thread->IsCurrent()) {
2880 rtc::BitrateAllocationStrategy* strategy_raw =
2881 bitrate_allocation_strategy.release();
2882 auto functor = [this, strategy_raw]() {
2883 call_->SetBitrateAllocationStrategy(
2884 rtc::WrapUnique<rtc::BitrateAllocationStrategy>(strategy_raw));
2885 };
2886 worker_thread->Invoke<void>(RTC_FROM_HERE, functor);
2887 return;
2888 }
2889 RTC_DCHECK(call_.get());
2890 call_->SetBitrateAllocationStrategy(std::move(bitrate_allocation_strategy));
2891}
2892
henrika5f6bf242017-11-01 11:06:56 +01002893void PeerConnection::SetAudioPlayout(bool playout) {
2894 if (!worker_thread()->IsCurrent()) {
2895 worker_thread()->Invoke<void>(
2896 RTC_FROM_HERE,
2897 rtc::Bind(&PeerConnection::SetAudioPlayout, this, playout));
2898 return;
2899 }
2900 auto audio_state =
2901 factory_->channel_manager()->media_engine()->GetAudioState();
2902 audio_state->SetPlayout(playout);
2903}
2904
2905void PeerConnection::SetAudioRecording(bool recording) {
2906 if (!worker_thread()->IsCurrent()) {
2907 worker_thread()->Invoke<void>(
2908 RTC_FROM_HERE,
2909 rtc::Bind(&PeerConnection::SetAudioRecording, this, recording));
2910 return;
2911 }
2912 auto audio_state =
2913 factory_->channel_manager()->media_engine()->GetAudioState();
2914 audio_state->SetRecording(recording);
2915}
2916
Steve Anton8c0f7a72017-10-03 10:03:10 -07002917std::unique_ptr<rtc::SSLCertificate>
2918PeerConnection::GetRemoteAudioSSLCertificate() {
Steve Anton75737c02017-11-06 10:37:17 -08002919 if (!voice_channel()) {
Steve Anton8c0f7a72017-10-03 10:03:10 -07002920 return nullptr;
2921 }
Steve Anton75737c02017-11-06 10:37:17 -08002922 return GetRemoteSSLCertificate(voice_channel()->transport_name());
Steve Anton8c0f7a72017-10-03 10:03:10 -07002923}
2924
Zhi Huang70b820f2018-01-27 14:16:15 -08002925std::unique_ptr<rtc::SSLCertChain>
2926PeerConnection::GetRemoteAudioSSLCertChain() {
2927 if (!voice_channel()) {
2928 return nullptr;
2929 }
2930
2931 return transport_controller_->GetRemoteSSLCertChain(
2932 voice_channel()->transport_name());
2933}
2934
ivoc14d5dbe2016-07-04 07:06:55 -07002935bool PeerConnection::StartRtcEventLog(rtc::PlatformFile file,
2936 int64_t max_size_bytes) {
Elad Alon99c3fe52017-10-13 16:29:40 +02002937 // TODO(eladalon): It would be better to not allow negative values into PC.
2938 const size_t max_size = (max_size_bytes < 0)
2939 ? RtcEventLog::kUnlimitedOutput
2940 : rtc::saturated_cast<size_t>(max_size_bytes);
2941 return StartRtcEventLog(
Bjorn Tereliusde939432017-11-20 17:38:14 +01002942 rtc::MakeUnique<RtcEventLogOutputFile>(file, max_size),
2943 webrtc::RtcEventLog::kImmediateOutput);
Elad Alon99c3fe52017-10-13 16:29:40 +02002944}
2945
Bjorn Tereliusde939432017-11-20 17:38:14 +01002946bool PeerConnection::StartRtcEventLog(std::unique_ptr<RtcEventLogOutput> output,
2947 int64_t output_period_ms) {
Karl Wibergd6b48192017-10-16 23:01:06 +02002948 // TODO(eladalon): In C++14, this can be done with a lambda.
2949 struct Functor {
Bjorn Tereliusde939432017-11-20 17:38:14 +01002950 bool operator()() {
2951 return pc->StartRtcEventLog_w(std::move(output), output_period_ms);
2952 }
Karl Wibergd6b48192017-10-16 23:01:06 +02002953 PeerConnection* const pc;
2954 std::unique_ptr<RtcEventLogOutput> output;
Bjorn Tereliusde939432017-11-20 17:38:14 +01002955 const int64_t output_period_ms;
Elad Alon99c3fe52017-10-13 16:29:40 +02002956 };
Bjorn Tereliusde939432017-11-20 17:38:14 +01002957 return worker_thread()->Invoke<bool>(
2958 RTC_FROM_HERE, Functor{this, std::move(output), output_period_ms});
ivoc14d5dbe2016-07-04 07:06:55 -07002959}
2960
2961void PeerConnection::StopRtcEventLog() {
Steve Anton978b8762017-09-29 12:15:02 -07002962 worker_thread()->Invoke<void>(
ivoc14d5dbe2016-07-04 07:06:55 -07002963 RTC_FROM_HERE, rtc::Bind(&PeerConnection::StopRtcEventLog_w, this));
2964}
2965
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002966const SessionDescriptionInterface* PeerConnection::local_description() const {
Steve Anton75737c02017-11-06 10:37:17 -08002967 return pending_local_description_ ? pending_local_description_.get()
2968 : current_local_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002969}
2970
2971const SessionDescriptionInterface* PeerConnection::remote_description() const {
Steve Anton75737c02017-11-06 10:37:17 -08002972 return pending_remote_description_ ? pending_remote_description_.get()
2973 : current_remote_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002974}
2975
deadbeeffe4a8a42016-12-20 17:56:17 -08002976const SessionDescriptionInterface* PeerConnection::current_local_description()
2977 const {
Steve Anton75737c02017-11-06 10:37:17 -08002978 return current_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08002979}
2980
2981const SessionDescriptionInterface* PeerConnection::current_remote_description()
2982 const {
Steve Anton75737c02017-11-06 10:37:17 -08002983 return current_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08002984}
2985
2986const SessionDescriptionInterface* PeerConnection::pending_local_description()
2987 const {
Steve Anton75737c02017-11-06 10:37:17 -08002988 return pending_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08002989}
2990
2991const SessionDescriptionInterface* PeerConnection::pending_remote_description()
2992 const {
Steve Anton75737c02017-11-06 10:37:17 -08002993 return pending_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08002994}
2995
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002996void PeerConnection::Close() {
Peter Boström1a9d6152015-12-08 22:15:17 +01002997 TRACE_EVENT0("webrtc", "PeerConnection::Close");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002998 // Update stats here so that we have the most recent stats for tracks and
2999 // streams before the channels are closed.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00003000 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003001
Steve Anton75737c02017-11-06 10:37:17 -08003002 ChangeSignalingState(PeerConnectionInterface::kClosed);
Steve Anton3fe1b152017-12-12 10:20:08 -08003003
Steve Anton8af21862017-12-15 11:20:13 -08003004 for (auto transceiver : transceivers_) {
3005 transceiver->Stop();
3006 }
3007 DestroyAllChannels();
Steve Anton75737c02017-11-06 10:37:17 -08003008
Qingsi Wang93a84392018-01-30 17:13:09 -08003009 // The event log is used in the transport controller, which must be outlived
3010 // by the former. CreateOffer by the peer connection is implemented
3011 // asynchronously and if the peer connection is closed without resetting the
3012 // WebRTC session description factory, the session description factory would
3013 // call the transport controller.
3014 webrtc_session_desc_factory_.reset();
3015 transport_controller_.reset();
3016
deadbeef42a42632017-03-10 15:18:00 -08003017 network_thread()->Invoke<void>(
3018 RTC_FROM_HERE,
3019 rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
3020 port_allocator_.get()));
nisseeaabdf62017-05-05 02:23:02 -07003021
Steve Anton978b8762017-09-29 12:15:02 -07003022 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
eladalon248fd4f2017-09-06 05:18:15 -07003023 call_.reset();
3024 // The event log must outlive call (and any other object that uses it).
3025 event_log_.reset();
3026 });
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003027}
3028
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003029void PeerConnection::OnMessage(rtc::Message* msg) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003030 switch (msg->message_id) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003031 case MSG_SET_SESSIONDESCRIPTION_SUCCESS: {
3032 SetSessionDescriptionMsg* param =
3033 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
3034 param->observer->OnSuccess();
3035 delete param;
3036 break;
3037 }
3038 case MSG_SET_SESSIONDESCRIPTION_FAILED: {
3039 SetSessionDescriptionMsg* param =
3040 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
3041 param->observer->OnFailure(param->error);
3042 delete param;
3043 break;
3044 }
deadbeefab9b2d12015-10-14 11:33:11 -07003045 case MSG_CREATE_SESSIONDESCRIPTION_FAILED: {
3046 CreateSessionDescriptionMsg* param =
3047 static_cast<CreateSessionDescriptionMsg*>(msg->pdata);
3048 param->observer->OnFailure(param->error);
3049 delete param;
3050 break;
3051 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003052 case MSG_GETSTATS: {
3053 GetStatsMsg* param = static_cast<GetStatsMsg*>(msg->pdata);
nissee8abe3e2017-01-18 05:00:34 -08003054 StatsReports reports;
3055 stats_->GetStats(param->track, &reports);
3056 param->observer->OnComplete(reports);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003057 delete param;
3058 break;
3059 }
deadbeefbd292462015-12-14 18:15:29 -08003060 case MSG_FREE_DATACHANNELS: {
3061 sctp_data_channels_to_free_.clear();
3062 break;
3063 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003064 default:
nisseeb4ca4e2017-01-12 02:24:27 -08003065 RTC_NOTREACHED() << "Not implemented";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003066 break;
3067 }
3068}
3069
Steve Anton4171afb2017-11-20 10:20:22 -08003070void PeerConnection::CreateAudioReceiver(
3071 MediaStreamInterface* stream,
3072 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01003073 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
3074 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Steve Antond3679212018-01-17 17:41:02 -08003075 auto* audio_receiver = new AudioRtpReceiver(
3076 worker_thread(), remote_sender_info.sender_id, streams);
Steve Anton57858b32018-02-15 15:19:50 -08003077 audio_receiver->SetVoiceMediaChannel(voice_media_channel());
Steve Antond3679212018-01-17 17:41:02 -08003078 audio_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
3079 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
3080 signaling_thread(), audio_receiver);
Steve Anton4171afb2017-11-20 10:20:22 -08003081 GetAudioTransceiver()->internal()->AddReceiver(receiver);
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01003082 observer_->OnAddTrack(receiver, std::move(streams));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003083}
3084
Steve Anton4171afb2017-11-20 10:20:22 -08003085void PeerConnection::CreateVideoReceiver(
3086 MediaStreamInterface* stream,
3087 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01003088 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
3089 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Steve Antond3679212018-01-17 17:41:02 -08003090 auto* video_receiver = new VideoRtpReceiver(
3091 worker_thread(), remote_sender_info.sender_id, streams);
Steve Anton57858b32018-02-15 15:19:50 -08003092 video_receiver->SetVideoMediaChannel(video_media_channel());
Steve Antond3679212018-01-17 17:41:02 -08003093 video_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
3094 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
3095 signaling_thread(), video_receiver);
Steve Anton4171afb2017-11-20 10:20:22 -08003096 GetVideoTransceiver()->internal()->AddReceiver(receiver);
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01003097 observer_->OnAddTrack(receiver, std::move(streams));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003098}
3099
deadbeef70ab1a12015-09-28 16:53:55 -07003100// TODO(deadbeef): Keep RtpReceivers around even if track goes away in remote
3101// description.
Henrik Boström933d8b02017-10-10 10:05:16 -07003102rtc::scoped_refptr<RtpReceiverInterface> PeerConnection::RemoveAndStopReceiver(
Steve Anton4171afb2017-11-20 10:20:22 -08003103 const RtpSenderInfo& remote_sender_info) {
3104 auto receiver = FindReceiverById(remote_sender_info.sender_id);
3105 if (!receiver) {
3106 RTC_LOG(LS_WARNING) << "RtpReceiver for track with id "
3107 << remote_sender_info.sender_id << " doesn't exist.";
Henrik Boström933d8b02017-10-10 10:05:16 -07003108 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07003109 }
Steve Anton4171afb2017-11-20 10:20:22 -08003110 if (receiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
3111 GetAudioTransceiver()->internal()->RemoveReceiver(receiver);
3112 } else {
3113 GetVideoTransceiver()->internal()->RemoveReceiver(receiver);
3114 }
Henrik Boström933d8b02017-10-10 10:05:16 -07003115 return receiver;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003116}
3117
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003118void PeerConnection::AddAudioTrack(AudioTrackInterface* track,
3119 MediaStreamInterface* stream) {
3120 RTC_DCHECK(!IsClosed());
3121 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003122 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003123 // We already have a sender for this track, so just change the stream_id
3124 // so that it's correct in the next call to CreateOffer.
Steve Anton4171afb2017-11-20 10:20:22 -08003125 sender->internal()->set_stream_id(stream->label());
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003126 return;
3127 }
3128
3129 // Normal case; we've never seen this track before.
Steve Anton02ee47c2018-01-10 16:26:06 -08003130 auto new_sender =
3131 CreateSender(cricket::MEDIA_TYPE_AUDIO, track, {stream->label()});
Steve Anton57858b32018-02-15 15:19:50 -08003132 new_sender->internal()->SetVoiceMediaChannel(voice_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08003133 GetAudioTransceiver()->internal()->AddSender(new_sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003134 // If the sender has already been configured in SDP, we call SetSsrc,
3135 // which will connect the sender to the underlying transport. This can
3136 // occur if a local session description that contains the ID of the sender
3137 // is set before AddStream is called. It can also occur if the local
3138 // session description is not changed and RemoveStream is called, and
3139 // later AddStream is called again with the same stream.
Steve Anton4171afb2017-11-20 10:20:22 -08003140 const RtpSenderInfo* sender_info =
3141 FindSenderInfo(local_audio_sender_infos_, stream->label(), track->id());
3142 if (sender_info) {
3143 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003144 }
3145}
3146
3147// TODO(deadbeef): Don't destroy RtpSenders here; they should be kept around
3148// indefinitely, when we have unified plan SDP.
3149void PeerConnection::RemoveAudioTrack(AudioTrackInterface* track,
3150 MediaStreamInterface* stream) {
3151 RTC_DCHECK(!IsClosed());
3152 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003153 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003154 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
3155 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003156 return;
3157 }
Steve Anton4171afb2017-11-20 10:20:22 -08003158 GetAudioTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003159}
3160
3161void PeerConnection::AddVideoTrack(VideoTrackInterface* track,
3162 MediaStreamInterface* stream) {
3163 RTC_DCHECK(!IsClosed());
3164 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003165 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003166 // We already have a sender for this track, so just change the stream_id
3167 // so that it's correct in the next call to CreateOffer.
Steve Anton4171afb2017-11-20 10:20:22 -08003168 sender->internal()->set_stream_id(stream->label());
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003169 return;
3170 }
3171
3172 // Normal case; we've never seen this track before.
Steve Anton02ee47c2018-01-10 16:26:06 -08003173 auto new_sender =
3174 CreateSender(cricket::MEDIA_TYPE_VIDEO, track, {stream->label()});
Steve Anton57858b32018-02-15 15:19:50 -08003175 new_sender->internal()->SetVideoMediaChannel(video_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08003176 GetVideoTransceiver()->internal()->AddSender(new_sender);
3177 const RtpSenderInfo* sender_info =
3178 FindSenderInfo(local_video_sender_infos_, stream->label(), track->id());
3179 if (sender_info) {
3180 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003181 }
3182}
3183
3184void PeerConnection::RemoveVideoTrack(VideoTrackInterface* track,
3185 MediaStreamInterface* stream) {
3186 RTC_DCHECK(!IsClosed());
3187 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003188 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003189 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
3190 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003191 return;
3192 }
Steve Anton4171afb2017-11-20 10:20:22 -08003193 GetVideoTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003194}
3195
Steve Antonba818672017-11-06 10:21:57 -08003196void PeerConnection::SetIceConnectionState(IceConnectionState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07003197 RTC_DCHECK(signaling_thread()->IsCurrent());
Steve Antonba818672017-11-06 10:21:57 -08003198 if (ice_connection_state_ == new_state) {
3199 return;
3200 }
3201
deadbeefcbecd352015-09-23 11:50:27 -07003202 // After transitioning to "closed", ignore any additional states from
Steve Antonba818672017-11-06 10:21:57 -08003203 // TransportController (such as "disconnected").
deadbeefab9b2d12015-10-14 11:33:11 -07003204 if (IsClosed()) {
deadbeefcbecd352015-09-23 11:50:27 -07003205 return;
3206 }
Steve Antonba818672017-11-06 10:21:57 -08003207
Mirko Bonadei675513b2017-11-09 11:09:25 +01003208 RTC_LOG(LS_INFO) << "Changing IceConnectionState " << ice_connection_state_
3209 << " => " << new_state;
Steve Antonba818672017-11-06 10:21:57 -08003210 RTC_DCHECK(ice_connection_state_ !=
3211 PeerConnectionInterface::kIceConnectionClosed);
3212
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003213 ice_connection_state_ = new_state;
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00003214 observer_->OnIceConnectionChange(ice_connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003215}
3216
3217void PeerConnection::OnIceGatheringChange(
3218 PeerConnectionInterface::IceGatheringState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07003219 RTC_DCHECK(signaling_thread()->IsCurrent());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003220 if (IsClosed()) {
3221 return;
3222 }
3223 ice_gathering_state_ = new_state;
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00003224 observer_->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003225}
3226
jbauch81bf7b02017-03-25 08:31:12 -07003227void PeerConnection::OnIceCandidate(
3228 std::unique_ptr<IceCandidateInterface> candidate) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07003229 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07003230 if (IsClosed()) {
3231 return;
3232 }
jbauch81bf7b02017-03-25 08:31:12 -07003233 observer_->OnIceCandidate(candidate.get());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003234}
3235
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003236void PeerConnection::OnIceCandidatesRemoved(
3237 const std::vector<cricket::Candidate>& candidates) {
3238 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07003239 if (IsClosed()) {
3240 return;
3241 }
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003242 observer_->OnIceCandidatesRemoved(candidates);
3243}
3244
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003245void PeerConnection::ChangeSignalingState(
3246 PeerConnectionInterface::SignalingState signaling_state) {
Steve Antonba818672017-11-06 10:21:57 -08003247 RTC_DCHECK(signaling_thread()->IsCurrent());
3248 if (signaling_state_ == signaling_state) {
3249 return;
3250 }
Mirko Bonadei675513b2017-11-09 11:09:25 +01003251 RTC_LOG(LS_INFO) << "Session: " << session_id() << " Old state: "
3252 << GetSignalingStateString(signaling_state_)
3253 << " New state: "
3254 << GetSignalingStateString(signaling_state);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003255 signaling_state_ = signaling_state;
3256 if (signaling_state == kClosed) {
3257 ice_connection_state_ = kIceConnectionClosed;
3258 observer_->OnIceConnectionChange(ice_connection_state_);
3259 if (ice_gathering_state_ != kIceGatheringComplete) {
3260 ice_gathering_state_ = kIceGatheringComplete;
3261 observer_->OnIceGatheringChange(ice_gathering_state_);
3262 }
3263 }
3264 observer_->OnSignalingChange(signaling_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003265}
3266
deadbeefeb459812015-12-15 19:24:43 -08003267void PeerConnection::OnAudioTrackAdded(AudioTrackInterface* track,
3268 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003269 if (IsClosed()) {
3270 return;
3271 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003272 AddAudioTrack(track, stream);
3273 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003274}
3275
deadbeefeb459812015-12-15 19:24:43 -08003276void PeerConnection::OnAudioTrackRemoved(AudioTrackInterface* track,
3277 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003278 if (IsClosed()) {
3279 return;
3280 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003281 RemoveAudioTrack(track, stream);
3282 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003283}
3284
3285void PeerConnection::OnVideoTrackAdded(VideoTrackInterface* track,
3286 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003287 if (IsClosed()) {
3288 return;
3289 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003290 AddVideoTrack(track, stream);
3291 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003292}
3293
3294void PeerConnection::OnVideoTrackRemoved(VideoTrackInterface* track,
3295 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003296 if (IsClosed()) {
3297 return;
3298 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003299 RemoveVideoTrack(track, stream);
3300 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003301}
3302
Henrik Boström31638672017-11-23 17:48:32 +01003303void PeerConnection::PostSetSessionDescriptionSuccess(
3304 SetSessionDescriptionObserver* observer) {
3305 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
3306 signaling_thread()->Post(RTC_FROM_HERE, this,
3307 MSG_SET_SESSIONDESCRIPTION_SUCCESS, msg);
3308}
3309
deadbeefab9b2d12015-10-14 11:33:11 -07003310void PeerConnection::PostSetSessionDescriptionFailure(
3311 SetSessionDescriptionObserver* observer,
3312 const std::string& error) {
3313 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
3314 msg->error = error;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07003315 signaling_thread()->Post(RTC_FROM_HERE, this,
3316 MSG_SET_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07003317}
3318
3319void PeerConnection::PostCreateSessionDescriptionFailure(
3320 CreateSessionDescriptionObserver* observer,
3321 const std::string& error) {
3322 CreateSessionDescriptionMsg* msg = new CreateSessionDescriptionMsg(observer);
3323 msg->error = error;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07003324 signaling_thread()->Post(RTC_FROM_HERE, this,
3325 MSG_CREATE_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07003326}
3327
zhihuang1c378ed2017-08-17 14:10:50 -07003328void PeerConnection::GetOptionsForOffer(
Steve Antondcc3c022017-12-22 16:02:54 -08003329 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
deadbeefab9b2d12015-10-14 11:33:11 -07003330 cricket::MediaSessionOptions* session_options) {
Steve Antondcc3c022017-12-22 16:02:54 -08003331 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
zhihuang1c378ed2017-08-17 14:10:50 -07003332
Steve Antondcc3c022017-12-22 16:02:54 -08003333 if (IsUnifiedPlan()) {
3334 GetOptionsForUnifiedPlanOffer(offer_answer_options, session_options);
3335 } else {
3336 GetOptionsForPlanBOffer(offer_answer_options, session_options);
3337 }
3338
Steve Antonfa2260d2017-12-28 16:38:23 -08003339 // Intentionally unset the data channel type for RTP data channel with the
3340 // second condition. Otherwise the RTP data channels would be successfully
3341 // negotiated by default and the unit tests in WebRtcDataBrowserTest will fail
3342 // when building with chromium. We want to leave RTP data channels broken, so
3343 // people won't try to use them.
3344 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
3345 session_options->data_channel_type = data_channel_type();
3346 }
3347
Steve Antondcc3c022017-12-22 16:02:54 -08003348 // Apply ICE restart flag and renomination flag.
3349 for (auto& options : session_options->media_description_options) {
3350 options.transport_options.ice_restart = offer_answer_options.ice_restart;
3351 options.transport_options.enable_ice_renomination =
3352 configuration_.enable_ice_renomination;
3353 }
3354
3355 session_options->rtcp_cname = rtcp_cname_;
3356 session_options->crypto_options = factory_->options().crypto_options;
Steve Antone831b8c2018-02-01 12:22:16 -08003357 session_options->is_unified_plan = IsUnifiedPlan();
Steve Antondcc3c022017-12-22 16:02:54 -08003358}
3359
3360void PeerConnection::GetOptionsForPlanBOffer(
3361 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
3362 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07003363 // Figure out transceiver directional preferences.
3364 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
3365 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
3366
3367 // By default, generate sendrecv/recvonly m= sections.
3368 bool recv_audio = true;
3369 bool recv_video = true;
3370
3371 // By default, only offer a new m= section if we have media to send with it.
3372 bool offer_new_audio_description = send_audio;
3373 bool offer_new_video_description = send_video;
3374 bool offer_new_data_description = HasDataChannels();
3375
3376 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-22 16:02:54 -08003377 if (offer_answer_options.offer_to_receive_audio !=
3378 RTCOfferAnswerOptions::kUndefined) {
3379 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003380 offer_new_audio_description =
Steve Antondcc3c022017-12-22 16:02:54 -08003381 offer_new_audio_description ||
3382 (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003383 }
Steve Antondcc3c022017-12-22 16:02:54 -08003384 if (offer_answer_options.offer_to_receive_video !=
3385 RTCOfferAnswerOptions::kUndefined) {
3386 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003387 offer_new_video_description =
Steve Antondcc3c022017-12-22 16:02:54 -08003388 offer_new_video_description ||
3389 (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003390 }
3391
3392 rtc::Optional<size_t> audio_index;
3393 rtc::Optional<size_t> video_index;
3394 rtc::Optional<size_t> data_index;
3395 // If a current description exists, generate m= sections in the same order,
3396 // using the first audio/video/data section that appears and rejecting
3397 // extraneous ones.
Steve Anton75737c02017-11-06 10:37:17 -08003398 if (local_description()) {
zhihuang1c378ed2017-08-17 14:10:50 -07003399 GenerateMediaDescriptionOptions(
Steve Anton75737c02017-11-06 10:37:17 -08003400 local_description(),
Steve Anton1d03a752017-11-27 14:30:09 -08003401 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
3402 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
3403 &audio_index, &video_index, &data_index, session_options);
deadbeefab9b2d12015-10-14 11:33:11 -07003404 }
3405
zhihuang1c378ed2017-08-17 14:10:50 -07003406 // Add audio/video/data m= sections to the end if needed.
3407 if (!audio_index && offer_new_audio_description) {
3408 session_options->media_description_options.push_back(
3409 cricket::MediaDescriptionOptions(
3410 cricket::MEDIA_TYPE_AUDIO, cricket::CN_AUDIO,
Steve Anton1d03a752017-11-27 14:30:09 -08003411 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
3412 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003413 audio_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07003414 }
zhihuang1c378ed2017-08-17 14:10:50 -07003415 if (!video_index && offer_new_video_description) {
3416 session_options->media_description_options.push_back(
3417 cricket::MediaDescriptionOptions(
3418 cricket::MEDIA_TYPE_VIDEO, cricket::CN_VIDEO,
Steve Anton1d03a752017-11-27 14:30:09 -08003419 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
3420 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003421 video_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07003422 }
zhihuang1c378ed2017-08-17 14:10:50 -07003423 if (!data_index && offer_new_data_description) {
3424 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08003425 GetMediaDescriptionOptionsForActiveData(cricket::CN_DATA));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003426 data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07003427 }
3428
3429 cricket::MediaDescriptionOptions* audio_media_description_options =
3430 !audio_index ? nullptr
3431 : &session_options->media_description_options[*audio_index];
3432 cricket::MediaDescriptionOptions* video_media_description_options =
3433 !video_index ? nullptr
3434 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 14:10:50 -07003435
Steve Anton4171afb2017-11-20 10:20:22 -08003436 AddRtpSenderOptions(GetSendersInternal(), audio_media_description_options,
zhihuang1c378ed2017-08-17 14:10:50 -07003437 video_media_description_options);
Steve Antondcc3c022017-12-22 16:02:54 -08003438}
3439
3440// Find a new MID that is not already in |used_mids|, then add it to |used_mids|
3441// and return a reference to it.
3442// Generated MIDs should be no more than 3 bytes long to take up less space in
3443// the RTP packet.
3444static const std::string& AllocateMid(std::set<std::string>* used_mids) {
3445 RTC_DCHECK(used_mids);
3446 // We're boring: just generate MIDs 0, 1, 2, ...
3447 size_t i = 0;
3448 std::set<std::string>::iterator it;
3449 bool inserted;
3450 do {
3451 std::string mid = rtc::ToString(i++);
3452 auto insert_result = used_mids->insert(mid);
3453 it = insert_result.first;
3454 inserted = insert_result.second;
3455 } while (!inserted);
3456 return *it;
3457}
3458
3459static cricket::MediaDescriptionOptions
3460GetMediaDescriptionOptionsForTransceiver(
3461 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3462 transceiver,
3463 const std::string& mid) {
3464 cricket::MediaDescriptionOptions media_description_options(
Steve Anton69470252018-02-09 11:43:08 -08003465 transceiver->media_type(), mid, transceiver->direction(),
Steve Antondcc3c022017-12-22 16:02:54 -08003466 transceiver->stopped());
Steve Anton5f94aa22018-02-01 10:58:30 -08003467 // This behavior is specified in JSEP. The gist is that:
3468 // 1. The MSID is included if the RtpTransceiver's direction is sendonly or
3469 // sendrecv.
3470 // 2. If the MSID is included, then it must be included in any subsequent
3471 // offer/answer exactly the same until the RtpTransceiver is stopped.
3472 if (!transceiver->stopped() &&
3473 (RtpTransceiverDirectionHasSend(transceiver->direction()) ||
3474 transceiver->internal()->has_ever_been_used_to_send())) {
3475 cricket::SenderOptions sender_options;
3476 sender_options.track_id = transceiver->sender()->id();
3477 sender_options.stream_ids = transceiver->sender()->stream_ids();
3478 // TODO(bugs.webrtc.org/7600): Set num_sim_layers to the number of encodings
3479 // set in the RTP parameters when the transceiver was added.
3480 sender_options.num_sim_layers = 1;
3481 media_description_options.sender_options.push_back(sender_options);
3482 }
Steve Antondcc3c022017-12-22 16:02:54 -08003483 return media_description_options;
3484}
3485
3486void PeerConnection::GetOptionsForUnifiedPlanOffer(
3487 const RTCOfferAnswerOptions& offer_answer_options,
3488 cricket::MediaSessionOptions* session_options) {
3489 // Rules for generating an offer are dictated by JSEP sections 5.2.1 (Initial
3490 // Offers) and 5.2.2 (Subsequent Offers).
3491 RTC_DCHECK_EQ(session_options->media_description_options.size(), 0);
3492 const ContentInfos& local_contents =
3493 (local_description() ? local_description()->description()->contents()
3494 : ContentInfos());
3495 const ContentInfos& remote_contents =
3496 (remote_description() ? remote_description()->description()->contents()
3497 : ContentInfos());
3498 // The mline indices that can be recycled. New transceivers should reuse these
3499 // slots first.
3500 std::queue<size_t> recycleable_mline_indices;
3501 // Track the MIDs used in previous offer/answer exchanges and the current
3502 // offer so that new, unique MIDs are generated.
3503 std::set<std::string> used_mids = seen_mids_;
3504 // First, go through each media section that exists in either the local or
3505 // remote description and generate a media section in this offer for the
3506 // associated transceiver. If a media section can be recycled, generate a
3507 // default, rejected media section here that can be later overwritten.
3508 for (size_t i = 0;
3509 i < std::max(local_contents.size(), remote_contents.size()); ++i) {
3510 // Either |local_content| or |remote_content| is non-null.
3511 const ContentInfo* local_content =
3512 (i < local_contents.size() ? &local_contents[i] : nullptr);
3513 const ContentInfo* remote_content =
3514 (i < remote_contents.size() ? &remote_contents[i] : nullptr);
3515 bool had_been_rejected = (local_content && local_content->rejected) ||
3516 (remote_content && remote_content->rejected);
3517 const std::string& mid =
3518 (local_content ? local_content->name : remote_content->name);
3519 cricket::MediaType media_type =
3520 (local_content ? local_content->media_description()->type()
3521 : remote_content->media_description()->type());
3522 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
3523 media_type == cricket::MEDIA_TYPE_VIDEO) {
3524 auto transceiver = GetAssociatedTransceiver(mid);
3525 RTC_CHECK(transceiver);
3526 // A media section is considered eligible for recycling if it is marked as
3527 // rejected in either the local or remote description.
Seth Hampsonae8a90a2018-02-13 15:33:48 -08003528 if (had_been_rejected && transceiver->stopped()) {
Steve Antondcc3c022017-12-22 16:02:54 -08003529 session_options->media_description_options.push_back(
Steve Anton69470252018-02-09 11:43:08 -08003530 cricket::MediaDescriptionOptions(transceiver->media_type(), mid,
3531 RtpTransceiverDirection::kInactive,
3532 /*stopped=*/true));
Steve Antondcc3c022017-12-22 16:02:54 -08003533 recycleable_mline_indices.push(i);
3534 } else {
3535 session_options->media_description_options.push_back(
3536 GetMediaDescriptionOptionsForTransceiver(transceiver, mid));
3537 // CreateOffer shouldn't really cause any state changes in
3538 // PeerConnection, but we need a way to match new transceivers to new
3539 // media sections in SetLocalDescription and JSEP specifies this is done
3540 // by recording the index of the media section generated for the
3541 // transceiver in the offer.
3542 transceiver->internal()->set_mline_index(i);
3543 }
3544 } else {
3545 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antonfa2260d2017-12-28 16:38:23 -08003546 RTC_CHECK(GetDataMid());
3547 if (had_been_rejected || mid != *GetDataMid()) {
3548 session_options->media_description_options.push_back(
3549 GetMediaDescriptionOptionsForRejectedData(mid));
3550 } else {
3551 session_options->media_description_options.push_back(
3552 GetMediaDescriptionOptionsForActiveData(mid));
3553 }
Steve Antondcc3c022017-12-22 16:02:54 -08003554 }
3555 }
3556 // Next, look for transceivers that are newly added (that is, are not stopped
3557 // and not associated). Reuse media sections marked as recyclable first,
3558 // otherwise append to the end of the offer. New media sections should be
3559 // added in the order they were added to the PeerConnection.
3560 for (auto transceiver : transceivers_) {
3561 if (transceiver->mid() || transceiver->stopped()) {
3562 continue;
3563 }
3564 size_t mline_index;
3565 if (!recycleable_mline_indices.empty()) {
3566 mline_index = recycleable_mline_indices.front();
3567 recycleable_mline_indices.pop();
3568 session_options->media_description_options[mline_index] =
3569 GetMediaDescriptionOptionsForTransceiver(transceiver,
3570 AllocateMid(&used_mids));
3571 } else {
3572 mline_index = session_options->media_description_options.size();
3573 session_options->media_description_options.push_back(
3574 GetMediaDescriptionOptionsForTransceiver(transceiver,
3575 AllocateMid(&used_mids)));
3576 }
3577 // See comment above for why CreateOffer changes the transceiver's state.
3578 transceiver->internal()->set_mline_index(mline_index);
3579 }
Steve Antonfa2260d2017-12-28 16:38:23 -08003580 // Lastly, add a m-section if we have local data channels and an m section
3581 // does not already exist.
3582 if (!GetDataMid() && HasDataChannels()) {
3583 session_options->media_description_options.push_back(
3584 GetMediaDescriptionOptionsForActiveData(AllocateMid(&used_mids)));
3585 }
Steve Antondcc3c022017-12-22 16:02:54 -08003586}
3587
3588void PeerConnection::GetOptionsForAnswer(
3589 const RTCOfferAnswerOptions& offer_answer_options,
3590 cricket::MediaSessionOptions* session_options) {
3591 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
3592
3593 if (IsUnifiedPlan()) {
3594 GetOptionsForUnifiedPlanAnswer(offer_answer_options, session_options);
3595 } else {
3596 GetOptionsForPlanBAnswer(offer_answer_options, session_options);
3597 }
3598
Steve Antonfa2260d2017-12-28 16:38:23 -08003599 // Intentionally unset the data channel type for RTP data channel. Otherwise
3600 // the RTP data channels would be successfully negotiated by default and the
3601 // unit tests in WebRtcDataBrowserTest will fail when building with chromium.
3602 // We want to leave RTP data channels broken, so people won't try to use them.
3603 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
3604 session_options->data_channel_type = data_channel_type();
3605 }
3606
Steve Antondcc3c022017-12-22 16:02:54 -08003607 // Apply ICE renomination flag.
3608 for (auto& options : session_options->media_description_options) {
3609 options.transport_options.enable_ice_renomination =
3610 configuration_.enable_ice_renomination;
3611 }
zhihuang8f65cdf2016-05-06 18:40:30 -07003612
3613 session_options->rtcp_cname = rtcp_cname_;
jbauchcb560652016-08-04 05:20:32 -07003614 session_options->crypto_options = factory_->options().crypto_options;
Steve Antone831b8c2018-02-01 12:22:16 -08003615 session_options->is_unified_plan = IsUnifiedPlan();
deadbeefab9b2d12015-10-14 11:33:11 -07003616}
3617
Steve Antondcc3c022017-12-22 16:02:54 -08003618void PeerConnection::GetOptionsForPlanBAnswer(
3619 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07003620 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07003621 // Figure out transceiver directional preferences.
3622 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
3623 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
3624
3625 // By default, generate sendrecv/recvonly m= sections. The direction is also
3626 // restricted by the direction in the offer.
3627 bool recv_audio = true;
3628 bool recv_video = true;
3629
3630 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-22 16:02:54 -08003631 if (offer_answer_options.offer_to_receive_audio !=
3632 RTCOfferAnswerOptions::kUndefined) {
3633 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
deadbeef0ed85b22016-02-23 17:24:52 -08003634 }
Steve Antondcc3c022017-12-22 16:02:54 -08003635 if (offer_answer_options.offer_to_receive_video !=
3636 RTCOfferAnswerOptions::kUndefined) {
3637 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003638 }
3639
3640 rtc::Optional<size_t> audio_index;
3641 rtc::Optional<size_t> video_index;
3642 rtc::Optional<size_t> data_index;
Steve Antondffead82018-02-06 10:31:29 -08003643
3644 // Generate m= sections that match those in the offer.
3645 // Note that mediasession.cc will handle intersection our preferred
3646 // direction with the offered direction.
3647 GenerateMediaDescriptionOptions(
3648 remote_description(),
3649 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
3650 RtpTransceiverDirectionFromSendRecv(send_video, recv_video), &audio_index,
3651 &video_index, &data_index, session_options);
zhihuang1c378ed2017-08-17 14:10:50 -07003652
3653 cricket::MediaDescriptionOptions* audio_media_description_options =
3654 !audio_index ? nullptr
3655 : &session_options->media_description_options[*audio_index];
3656 cricket::MediaDescriptionOptions* video_media_description_options =
3657 !video_index ? nullptr
3658 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 14:10:50 -07003659
Steve Anton4171afb2017-11-20 10:20:22 -08003660 AddRtpSenderOptions(GetSendersInternal(), audio_media_description_options,
zhihuang1c378ed2017-08-17 14:10:50 -07003661 video_media_description_options);
Steve Antondcc3c022017-12-22 16:02:54 -08003662}
zhihuangaf388472016-11-02 16:49:48 -07003663
Steve Antondcc3c022017-12-22 16:02:54 -08003664void PeerConnection::GetOptionsForUnifiedPlanAnswer(
3665 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
3666 cricket::MediaSessionOptions* session_options) {
3667 // Rules for generating an answer are dictated by JSEP sections 5.3.1 (Initial
3668 // Answers) and 5.3.2 (Subsequent Answers).
3669 RTC_DCHECK(remote_description());
3670 RTC_DCHECK(remote_description()->GetType() == SdpType::kOffer);
3671 for (const ContentInfo& content :
3672 remote_description()->description()->contents()) {
3673 cricket::MediaType media_type = content.media_description()->type();
3674 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
3675 media_type == cricket::MEDIA_TYPE_VIDEO) {
3676 auto transceiver = GetAssociatedTransceiver(content.name);
3677 RTC_CHECK(transceiver);
3678 session_options->media_description_options.push_back(
3679 GetMediaDescriptionOptionsForTransceiver(transceiver, content.name));
3680 } else {
3681 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antondbf9d032018-01-19 15:23:40 -08003682 // Reject all data sections if data channels are disabled.
3683 // Reject a data section if it has already been rejected.
3684 // Reject all data sections except for the first one.
3685 if (data_channel_type_ == cricket::DCT_NONE || content.rejected ||
3686 content.name != *GetDataMid()) {
Steve Antonfa2260d2017-12-28 16:38:23 -08003687 session_options->media_description_options.push_back(
3688 GetMediaDescriptionOptionsForRejectedData(content.name));
3689 } else {
3690 session_options->media_description_options.push_back(
3691 GetMediaDescriptionOptionsForActiveData(content.name));
3692 }
Steve Antondcc3c022017-12-22 16:02:54 -08003693 }
3694 }
htaa2a49d92016-03-04 02:51:39 -08003695}
3696
zhihuang1c378ed2017-08-17 14:10:50 -07003697void PeerConnection::GenerateMediaDescriptionOptions(
3698 const SessionDescriptionInterface* session_desc,
Steve Anton1d03a752017-11-27 14:30:09 -08003699 RtpTransceiverDirection audio_direction,
3700 RtpTransceiverDirection video_direction,
zhihuang1c378ed2017-08-17 14:10:50 -07003701 rtc::Optional<size_t>* audio_index,
3702 rtc::Optional<size_t>* video_index,
3703 rtc::Optional<size_t>* data_index,
htaa2a49d92016-03-04 02:51:39 -08003704 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07003705 for (const cricket::ContentInfo& content :
3706 session_desc->description()->contents()) {
3707 if (IsAudioContent(&content)) {
3708 // If we already have an audio m= section, reject this extra one.
3709 if (*audio_index) {
3710 session_options->media_description_options.push_back(
3711 cricket::MediaDescriptionOptions(
3712 cricket::MEDIA_TYPE_AUDIO, content.name,
Steve Anton1d03a752017-11-27 14:30:09 -08003713 RtpTransceiverDirection::kInactive, true));
zhihuang1c378ed2017-08-17 14:10:50 -07003714 } else {
3715 session_options->media_description_options.push_back(
3716 cricket::MediaDescriptionOptions(
3717 cricket::MEDIA_TYPE_AUDIO, content.name, audio_direction,
Steve Anton1d03a752017-11-27 14:30:09 -08003718 audio_direction == RtpTransceiverDirection::kInactive));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003719 *audio_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07003720 }
3721 } else if (IsVideoContent(&content)) {
3722 // If we already have an video m= section, reject this extra one.
3723 if (*video_index) {
3724 session_options->media_description_options.push_back(
3725 cricket::MediaDescriptionOptions(
3726 cricket::MEDIA_TYPE_VIDEO, content.name,
Steve Anton1d03a752017-11-27 14:30:09 -08003727 RtpTransceiverDirection::kInactive, true));
zhihuang1c378ed2017-08-17 14:10:50 -07003728 } else {
3729 session_options->media_description_options.push_back(
3730 cricket::MediaDescriptionOptions(
3731 cricket::MEDIA_TYPE_VIDEO, content.name, video_direction,
Steve Anton1d03a752017-11-27 14:30:09 -08003732 video_direction == RtpTransceiverDirection::kInactive));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003733 *video_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07003734 }
3735 } else {
3736 RTC_DCHECK(IsDataContent(&content));
3737 // If we already have an data m= section, reject this extra one.
3738 if (*data_index) {
3739 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08003740 GetMediaDescriptionOptionsForRejectedData(content.name));
zhihuang1c378ed2017-08-17 14:10:50 -07003741 } else {
3742 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08003743 GetMediaDescriptionOptionsForActiveData(content.name));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003744 *data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07003745 }
3746 }
htaa2a49d92016-03-04 02:51:39 -08003747 }
deadbeefab9b2d12015-10-14 11:33:11 -07003748}
3749
Steve Antonfa2260d2017-12-28 16:38:23 -08003750cricket::MediaDescriptionOptions
3751PeerConnection::GetMediaDescriptionOptionsForActiveData(
3752 const std::string& mid) const {
3753 // Direction for data sections is meaningless, but legacy endpoints might
3754 // expect sendrecv.
3755 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
3756 RtpTransceiverDirection::kSendRecv,
3757 /*stopped=*/false);
3758 AddRtpDataChannelOptions(rtp_data_channels_, &options);
3759 return options;
3760}
3761
3762cricket::MediaDescriptionOptions
3763PeerConnection::GetMediaDescriptionOptionsForRejectedData(
3764 const std::string& mid) const {
3765 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
3766 RtpTransceiverDirection::kInactive,
3767 /*stopped=*/true);
3768 AddRtpDataChannelOptions(rtp_data_channels_, &options);
3769 return options;
3770}
3771
3772rtc::Optional<std::string> PeerConnection::GetDataMid() const {
3773 switch (data_channel_type_) {
3774 case cricket::DCT_RTP:
3775 if (!rtp_data_channel_) {
3776 return rtc::nullopt;
3777 }
3778 return rtp_data_channel_->content_name();
3779 case cricket::DCT_SCTP:
3780 return sctp_content_name_;
3781 default:
3782 return rtc::nullopt;
3783 }
3784}
3785
Steve Anton4171afb2017-11-20 10:20:22 -08003786void PeerConnection::RemoveSenders(cricket::MediaType media_type) {
3787 UpdateLocalSenders(std::vector<cricket::StreamParams>(), media_type);
3788 UpdateRemoteSendersList(std::vector<cricket::StreamParams>(), false,
deadbeefbda7e0b2015-12-08 17:13:40 -08003789 media_type, nullptr);
deadbeeffaac4972015-11-12 15:33:07 -08003790}
3791
Steve Anton4171afb2017-11-20 10:20:22 -08003792void PeerConnection::UpdateRemoteSendersList(
deadbeefab9b2d12015-10-14 11:33:11 -07003793 const cricket::StreamParamsVec& streams,
Steve Anton4171afb2017-11-20 10:20:22 -08003794 bool default_sender_needed,
deadbeefab9b2d12015-10-14 11:33:11 -07003795 cricket::MediaType media_type,
3796 StreamCollection* new_streams) {
Steve Anton4171afb2017-11-20 10:20:22 -08003797 std::vector<RtpSenderInfo>* current_senders =
3798 GetRemoteSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07003799
Steve Anton4171afb2017-11-20 10:20:22 -08003800 // Find removed senders. I.e., senders where the sender id or ssrc don't match
deadbeeffac06552015-11-25 11:26:01 -08003801 // the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08003802 for (auto sender_it = current_senders->begin();
3803 sender_it != current_senders->end();
3804 /* incremented manually */) {
3805 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07003806 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08003807 cricket::GetStreamBySsrc(streams, info.first_ssrc);
3808 bool sender_exists = params && params->id == info.sender_id;
deadbeefbda7e0b2015-12-08 17:13:40 -08003809 // If this is a default track, and we still need it, don't remove it.
Steve Anton4171afb2017-11-20 10:20:22 -08003810 if ((info.stream_label == kDefaultStreamLabel && default_sender_needed) ||
3811 sender_exists) {
3812 ++sender_it;
deadbeefbda7e0b2015-12-08 17:13:40 -08003813 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08003814 OnRemoteSenderRemoved(info, media_type);
3815 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07003816 }
3817 }
3818
Steve Anton4171afb2017-11-20 10:20:22 -08003819 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07003820 for (const cricket::StreamParams& params : streams) {
3821 // The sync_label is the MediaStream label and the |stream.id| is the
Steve Anton4171afb2017-11-20 10:20:22 -08003822 // sender id.
deadbeefab9b2d12015-10-14 11:33:11 -07003823 const std::string& stream_label = params.sync_label;
Steve Anton4171afb2017-11-20 10:20:22 -08003824 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07003825 uint32_t ssrc = params.first_ssrc();
3826
3827 rtc::scoped_refptr<MediaStreamInterface> stream =
3828 remote_streams_->find(stream_label);
3829 if (!stream) {
3830 // This is a new MediaStream. Create a new remote MediaStream.
perkjd61bf802016-03-24 03:16:19 -07003831 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
3832 MediaStream::Create(stream_label));
deadbeefab9b2d12015-10-14 11:33:11 -07003833 remote_streams_->AddStream(stream);
3834 new_streams->AddStream(stream);
3835 }
3836
Steve Anton4171afb2017-11-20 10:20:22 -08003837 const RtpSenderInfo* sender_info =
3838 FindSenderInfo(*current_senders, stream_label, sender_id);
3839 if (!sender_info) {
3840 current_senders->push_back(RtpSenderInfo(stream_label, sender_id, ssrc));
3841 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07003842 }
3843 }
deadbeefbda7e0b2015-12-08 17:13:40 -08003844
Steve Anton4171afb2017-11-20 10:20:22 -08003845 // Add default sender if necessary.
3846 if (default_sender_needed) {
deadbeefbda7e0b2015-12-08 17:13:40 -08003847 rtc::scoped_refptr<MediaStreamInterface> default_stream =
3848 remote_streams_->find(kDefaultStreamLabel);
3849 if (!default_stream) {
3850 // Create the new default MediaStream.
perkjd61bf802016-03-24 03:16:19 -07003851 default_stream = MediaStreamProxy::Create(
3852 rtc::Thread::Current(), MediaStream::Create(kDefaultStreamLabel));
deadbeefbda7e0b2015-12-08 17:13:40 -08003853 remote_streams_->AddStream(default_stream);
3854 new_streams->AddStream(default_stream);
3855 }
Steve Anton4171afb2017-11-20 10:20:22 -08003856 std::string default_sender_id = (media_type == cricket::MEDIA_TYPE_AUDIO)
3857 ? kDefaultAudioSenderId
3858 : kDefaultVideoSenderId;
3859 const RtpSenderInfo* default_sender_info = FindSenderInfo(
3860 *current_senders, kDefaultStreamLabel, default_sender_id);
3861 if (!default_sender_info) {
3862 current_senders->push_back(
3863 RtpSenderInfo(kDefaultStreamLabel, default_sender_id, 0));
3864 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefbda7e0b2015-12-08 17:13:40 -08003865 }
3866 }
deadbeefab9b2d12015-10-14 11:33:11 -07003867}
3868
Steve Anton4171afb2017-11-20 10:20:22 -08003869void PeerConnection::OnRemoteSenderAdded(const RtpSenderInfo& sender_info,
3870 cricket::MediaType media_type) {
3871 MediaStreamInterface* stream =
3872 remote_streams_->find(sender_info.stream_label);
deadbeefab9b2d12015-10-14 11:33:11 -07003873
3874 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 10:20:22 -08003875 CreateAudioReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07003876 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 10:20:22 -08003877 CreateVideoReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07003878 } else {
nisseeb4ca4e2017-01-12 02:24:27 -08003879 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07003880 }
3881}
3882
Steve Anton4171afb2017-11-20 10:20:22 -08003883void PeerConnection::OnRemoteSenderRemoved(const RtpSenderInfo& sender_info,
3884 cricket::MediaType media_type) {
3885 MediaStreamInterface* stream =
3886 remote_streams_->find(sender_info.stream_label);
deadbeefab9b2d12015-10-14 11:33:11 -07003887
Henrik Boström933d8b02017-10-10 10:05:16 -07003888 rtc::scoped_refptr<RtpReceiverInterface> receiver;
deadbeefab9b2d12015-10-14 11:33:11 -07003889 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
perkjd61bf802016-03-24 03:16:19 -07003890 // When the MediaEngine audio channel is destroyed, the RemoteAudioSource
3891 // will be notified which will end the AudioRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08003892 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07003893 rtc::scoped_refptr<AudioTrackInterface> audio_track =
Steve Anton4171afb2017-11-20 10:20:22 -08003894 stream->FindAudioTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07003895 if (audio_track) {
deadbeefab9b2d12015-10-14 11:33:11 -07003896 stream->RemoveTrack(audio_track);
deadbeefab9b2d12015-10-14 11:33:11 -07003897 }
3898 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
perkjd61bf802016-03-24 03:16:19 -07003899 // Stopping or destroying a VideoRtpReceiver will end the
3900 // VideoRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08003901 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07003902 rtc::scoped_refptr<VideoTrackInterface> video_track =
Steve Anton4171afb2017-11-20 10:20:22 -08003903 stream->FindVideoTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07003904 if (video_track) {
perkjd61bf802016-03-24 03:16:19 -07003905 // There's no guarantee the track is still available, e.g. the track may
3906 // have been removed from the stream by an application.
deadbeefab9b2d12015-10-14 11:33:11 -07003907 stream->RemoveTrack(video_track);
deadbeefab9b2d12015-10-14 11:33:11 -07003908 }
3909 } else {
nisseede5da42017-01-12 05:15:36 -08003910 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07003911 }
Henrik Boström933d8b02017-10-10 10:05:16 -07003912 if (receiver) {
3913 observer_->OnRemoveTrack(receiver);
3914 }
deadbeefab9b2d12015-10-14 11:33:11 -07003915}
3916
3917void PeerConnection::UpdateEndedRemoteMediaStreams() {
3918 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams_to_remove;
3919 for (size_t i = 0; i < remote_streams_->count(); ++i) {
3920 MediaStreamInterface* stream = remote_streams_->at(i);
3921 if (stream->GetAudioTracks().empty() && stream->GetVideoTracks().empty()) {
3922 streams_to_remove.push_back(stream);
3923 }
3924 }
3925
Taylor Brandstetter98cde262016-05-31 13:02:21 -07003926 for (auto& stream : streams_to_remove) {
deadbeefab9b2d12015-10-14 11:33:11 -07003927 remote_streams_->RemoveStream(stream);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07003928 observer_->OnRemoveStream(std::move(stream));
deadbeefab9b2d12015-10-14 11:33:11 -07003929 }
3930}
3931
Steve Anton4171afb2017-11-20 10:20:22 -08003932void PeerConnection::UpdateLocalSenders(
deadbeefab9b2d12015-10-14 11:33:11 -07003933 const std::vector<cricket::StreamParams>& streams,
3934 cricket::MediaType media_type) {
Steve Anton4171afb2017-11-20 10:20:22 -08003935 std::vector<RtpSenderInfo>* current_senders = GetLocalSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07003936
3937 // Find removed tracks. I.e., tracks where the track id, stream label or ssrc
3938 // don't match the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08003939 for (auto sender_it = current_senders->begin();
3940 sender_it != current_senders->end();
3941 /* incremented manually */) {
3942 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07003943 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08003944 cricket::GetStreamBySsrc(streams, info.first_ssrc);
3945 if (!params || params->id != info.sender_id ||
deadbeefab9b2d12015-10-14 11:33:11 -07003946 params->sync_label != info.stream_label) {
Steve Anton4171afb2017-11-20 10:20:22 -08003947 OnLocalSenderRemoved(info, media_type);
3948 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07003949 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08003950 ++sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07003951 }
3952 }
3953
Steve Anton4171afb2017-11-20 10:20:22 -08003954 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07003955 for (const cricket::StreamParams& params : streams) {
3956 // The sync_label is the MediaStream label and the |stream.id| is the
Steve Anton4171afb2017-11-20 10:20:22 -08003957 // sender id.
deadbeefab9b2d12015-10-14 11:33:11 -07003958 const std::string& stream_label = params.sync_label;
Steve Anton4171afb2017-11-20 10:20:22 -08003959 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07003960 uint32_t ssrc = params.first_ssrc();
Steve Anton4171afb2017-11-20 10:20:22 -08003961 const RtpSenderInfo* sender_info =
3962 FindSenderInfo(*current_senders, stream_label, sender_id);
3963 if (!sender_info) {
3964 current_senders->push_back(RtpSenderInfo(stream_label, sender_id, ssrc));
3965 OnLocalSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07003966 }
3967 }
3968}
3969
Steve Anton4171afb2017-11-20 10:20:22 -08003970void PeerConnection::OnLocalSenderAdded(const RtpSenderInfo& sender_info,
3971 cricket::MediaType media_type) {
3972 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08003973 if (!sender) {
Steve Anton4171afb2017-11-20 10:20:22 -08003974 RTC_LOG(LS_WARNING) << "An unknown RtpSender with id "
3975 << sender_info.sender_id
Mirko Bonadei675513b2017-11-09 11:09:25 +01003976 << " has been configured in the local description.";
deadbeefab9b2d12015-10-14 11:33:11 -07003977 return;
3978 }
3979
deadbeeffac06552015-11-25 11:26:01 -08003980 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003981 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
Jonas Olsson45cc8902018-02-13 10:37:07 +01003982 " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08003983 return;
deadbeefab9b2d12015-10-14 11:33:11 -07003984 }
deadbeeffac06552015-11-25 11:26:01 -08003985
Steve Anton4171afb2017-11-20 10:20:22 -08003986 sender->internal()->set_stream_id(sender_info.stream_label);
3987 sender->internal()->SetSsrc(sender_info.first_ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07003988}
3989
Steve Anton4171afb2017-11-20 10:20:22 -08003990void PeerConnection::OnLocalSenderRemoved(const RtpSenderInfo& sender_info,
3991 cricket::MediaType media_type) {
3992 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08003993 if (!sender) {
3994 // This is the normal case. I.e., RemoveStream has been called and the
deadbeefab9b2d12015-10-14 11:33:11 -07003995 // SessionDescriptions has been renegotiated.
3996 return;
3997 }
deadbeeffac06552015-11-25 11:26:01 -08003998
3999 // A sender has been removed from the SessionDescription but it's still
4000 // associated with the PeerConnection. This only occurs if the SDP doesn't
4001 // match with the calls to CreateSender, AddStream and RemoveStream.
4002 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004003 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
Jonas Olsson45cc8902018-02-13 10:37:07 +01004004 " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08004005 return;
deadbeefab9b2d12015-10-14 11:33:11 -07004006 }
deadbeeffac06552015-11-25 11:26:01 -08004007
Steve Anton4171afb2017-11-20 10:20:22 -08004008 sender->internal()->SetSsrc(0);
deadbeefab9b2d12015-10-14 11:33:11 -07004009}
4010
4011void PeerConnection::UpdateLocalRtpDataChannels(
4012 const cricket::StreamParamsVec& streams) {
4013 std::vector<std::string> existing_channels;
4014
4015 // Find new and active data channels.
4016 for (const cricket::StreamParams& params : streams) {
4017 // |it->sync_label| is actually the data channel label. The reason is that
4018 // we use the same naming of data channels as we do for
4019 // MediaStreams and Tracks.
4020 // For MediaStreams, the sync_label is the MediaStream label and the
4021 // track label is the same as |streamid|.
4022 const std::string& channel_label = params.sync_label;
4023 auto data_channel_it = rtp_data_channels_.find(channel_label);
nisse7ce109a2017-01-31 00:57:56 -08004024 if (data_channel_it == rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004025 RTC_LOG(LS_ERROR) << "channel label not found";
deadbeefab9b2d12015-10-14 11:33:11 -07004026 continue;
4027 }
4028 // Set the SSRC the data channel should use for sending.
4029 data_channel_it->second->SetSendSsrc(params.first_ssrc());
4030 existing_channels.push_back(data_channel_it->first);
4031 }
4032
4033 UpdateClosingRtpDataChannels(existing_channels, true);
4034}
4035
4036void PeerConnection::UpdateRemoteRtpDataChannels(
4037 const cricket::StreamParamsVec& streams) {
4038 std::vector<std::string> existing_channels;
4039
4040 // Find new and active data channels.
4041 for (const cricket::StreamParams& params : streams) {
4042 // The data channel label is either the mslabel or the SSRC if the mslabel
4043 // does not exist. Ex a=ssrc:444330170 mslabel:test1.
4044 std::string label = params.sync_label.empty()
4045 ? rtc::ToString(params.first_ssrc())
4046 : params.sync_label;
4047 auto data_channel_it = rtp_data_channels_.find(label);
4048 if (data_channel_it == rtp_data_channels_.end()) {
4049 // This is a new data channel.
4050 CreateRemoteRtpDataChannel(label, params.first_ssrc());
4051 } else {
4052 data_channel_it->second->SetReceiveSsrc(params.first_ssrc());
4053 }
4054 existing_channels.push_back(label);
4055 }
4056
4057 UpdateClosingRtpDataChannels(existing_channels, false);
4058}
4059
4060void PeerConnection::UpdateClosingRtpDataChannels(
4061 const std::vector<std::string>& active_channels,
4062 bool is_local_update) {
4063 auto it = rtp_data_channels_.begin();
4064 while (it != rtp_data_channels_.end()) {
4065 DataChannel* data_channel = it->second;
4066 if (std::find(active_channels.begin(), active_channels.end(),
4067 data_channel->label()) != active_channels.end()) {
4068 ++it;
4069 continue;
4070 }
4071
4072 if (is_local_update) {
4073 data_channel->SetSendSsrc(0);
4074 } else {
4075 data_channel->RemotePeerRequestClose();
4076 }
4077
4078 if (data_channel->state() == DataChannel::kClosed) {
4079 rtp_data_channels_.erase(it);
4080 it = rtp_data_channels_.begin();
4081 } else {
4082 ++it;
4083 }
4084 }
4085}
4086
4087void PeerConnection::CreateRemoteRtpDataChannel(const std::string& label,
4088 uint32_t remote_ssrc) {
4089 rtc::scoped_refptr<DataChannel> channel(
4090 InternalCreateDataChannel(label, nullptr));
4091 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004092 RTC_LOG(LS_WARNING) << "Remote peer requested a DataChannel but"
Jonas Olsson45cc8902018-02-13 10:37:07 +01004093 "CreateDataChannel failed.";
deadbeefab9b2d12015-10-14 11:33:11 -07004094 return;
4095 }
4096 channel->SetReceiveSsrc(remote_ssrc);
deadbeefa601f5c2016-06-06 14:27:39 -07004097 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
4098 DataChannelProxy::Create(signaling_thread(), channel);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07004099 observer_->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07004100}
4101
4102rtc::scoped_refptr<DataChannel> PeerConnection::InternalCreateDataChannel(
4103 const std::string& label,
4104 const InternalDataChannelInit* config) {
4105 if (IsClosed()) {
4106 return nullptr;
4107 }
Steve Anton75737c02017-11-06 10:37:17 -08004108 if (data_channel_type() == cricket::DCT_NONE) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004109 RTC_LOG(LS_ERROR)
deadbeefab9b2d12015-10-14 11:33:11 -07004110 << "InternalCreateDataChannel: Data is not supported in this call.";
4111 return nullptr;
4112 }
4113 InternalDataChannelInit new_config =
4114 config ? (*config) : InternalDataChannelInit();
Steve Anton75737c02017-11-06 10:37:17 -08004115 if (data_channel_type() == cricket::DCT_SCTP) {
deadbeefab9b2d12015-10-14 11:33:11 -07004116 if (new_config.id < 0) {
4117 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08004118 if ((GetSctpSslRole(&role)) &&
deadbeefab9b2d12015-10-14 11:33:11 -07004119 !sid_allocator_.AllocateSid(role, &new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004120 RTC_LOG(LS_ERROR)
4121 << "No id can be allocated for the SCTP data channel.";
deadbeefab9b2d12015-10-14 11:33:11 -07004122 return nullptr;
4123 }
4124 } else if (!sid_allocator_.ReserveSid(new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004125 RTC_LOG(LS_ERROR) << "Failed to create a SCTP data channel "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004126 "because the id is already in use or out of range.";
deadbeefab9b2d12015-10-14 11:33:11 -07004127 return nullptr;
4128 }
4129 }
4130
Steve Anton75737c02017-11-06 10:37:17 -08004131 rtc::scoped_refptr<DataChannel> channel(
4132 DataChannel::Create(this, data_channel_type(), label, new_config));
deadbeefab9b2d12015-10-14 11:33:11 -07004133 if (!channel) {
4134 sid_allocator_.ReleaseSid(new_config.id);
4135 return nullptr;
4136 }
4137
4138 if (channel->data_channel_type() == cricket::DCT_RTP) {
4139 if (rtp_data_channels_.find(channel->label()) != rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004140 RTC_LOG(LS_ERROR) << "DataChannel with label " << channel->label()
4141 << " already exists.";
deadbeefab9b2d12015-10-14 11:33:11 -07004142 return nullptr;
4143 }
4144 rtp_data_channels_[channel->label()] = channel;
4145 } else {
4146 RTC_DCHECK(channel->data_channel_type() == cricket::DCT_SCTP);
4147 sctp_data_channels_.push_back(channel);
4148 channel->SignalClosed.connect(this,
4149 &PeerConnection::OnSctpDataChannelClosed);
4150 }
4151
Steve Anton2d8609c2018-01-23 16:38:46 -08004152 SignalDataChannelCreated_(channel.get());
deadbeefab9b2d12015-10-14 11:33:11 -07004153 return channel;
4154}
4155
4156bool PeerConnection::HasDataChannels() const {
4157 return !rtp_data_channels_.empty() || !sctp_data_channels_.empty();
4158}
4159
4160void PeerConnection::AllocateSctpSids(rtc::SSLRole role) {
4161 for (const auto& channel : sctp_data_channels_) {
4162 if (channel->id() < 0) {
4163 int sid;
4164 if (!sid_allocator_.AllocateSid(role, &sid)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004165 RTC_LOG(LS_ERROR) << "Failed to allocate SCTP sid.";
deadbeefab9b2d12015-10-14 11:33:11 -07004166 continue;
4167 }
4168 channel->SetSctpSid(sid);
4169 }
4170 }
4171}
4172
4173void PeerConnection::OnSctpDataChannelClosed(DataChannel* channel) {
deadbeefbd292462015-12-14 18:15:29 -08004174 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeefab9b2d12015-10-14 11:33:11 -07004175 for (auto it = sctp_data_channels_.begin(); it != sctp_data_channels_.end();
4176 ++it) {
4177 if (it->get() == channel) {
4178 if (channel->id() >= 0) {
4179 sid_allocator_.ReleaseSid(channel->id());
4180 }
deadbeefbd292462015-12-14 18:15:29 -08004181 // Since this method is triggered by a signal from the DataChannel,
4182 // we can't free it directly here; we need to free it asynchronously.
4183 sctp_data_channels_to_free_.push_back(*it);
deadbeefab9b2d12015-10-14 11:33:11 -07004184 sctp_data_channels_.erase(it);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07004185 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_FREE_DATACHANNELS,
4186 nullptr);
deadbeefab9b2d12015-10-14 11:33:11 -07004187 return;
4188 }
4189 }
4190}
4191
deadbeefab9b2d12015-10-14 11:33:11 -07004192void PeerConnection::OnDataChannelDestroyed() {
4193 // Use a temporary copy of the RTP/SCTP DataChannel list because the
4194 // DataChannel may callback to us and try to modify the list.
4195 std::map<std::string, rtc::scoped_refptr<DataChannel>> temp_rtp_dcs;
4196 temp_rtp_dcs.swap(rtp_data_channels_);
4197 for (const auto& kv : temp_rtp_dcs) {
4198 kv.second->OnTransportChannelDestroyed();
4199 }
4200
4201 std::vector<rtc::scoped_refptr<DataChannel>> temp_sctp_dcs;
4202 temp_sctp_dcs.swap(sctp_data_channels_);
4203 for (const auto& channel : temp_sctp_dcs) {
4204 channel->OnTransportChannelDestroyed();
4205 }
4206}
4207
4208void PeerConnection::OnDataChannelOpenMessage(
4209 const std::string& label,
4210 const InternalDataChannelInit& config) {
4211 rtc::scoped_refptr<DataChannel> channel(
4212 InternalCreateDataChannel(label, &config));
4213 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004214 RTC_LOG(LS_ERROR) << "Failed to create DataChannel from the OPEN message.";
deadbeefab9b2d12015-10-14 11:33:11 -07004215 return;
4216 }
4217
deadbeefa601f5c2016-06-06 14:27:39 -07004218 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
4219 DataChannelProxy::Create(signaling_thread(), channel);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07004220 observer_->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07004221}
4222
Steve Anton4171afb2017-11-20 10:20:22 -08004223rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
4224PeerConnection::GetAudioTransceiver() const {
4225 // This method only works with Plan B SDP, where there is a single
4226 // audio/video transceiver.
4227 RTC_DCHECK(!IsUnifiedPlan());
4228 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08004229 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004230 return transceiver;
4231 }
4232 }
4233 RTC_NOTREACHED();
4234 return nullptr;
4235}
4236
4237rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
4238PeerConnection::GetVideoTransceiver() const {
4239 // This method only works with Plan B SDP, where there is a single
4240 // audio/video transceiver.
4241 RTC_DCHECK(!IsUnifiedPlan());
4242 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08004243 if (transceiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004244 return transceiver;
4245 }
4246 }
4247 RTC_NOTREACHED();
4248 return nullptr;
4249}
4250
4251// TODO(bugs.webrtc.org/7600): Remove this when multiple transceivers with
4252// individual transceiver directions are supported.
zhihuang1c378ed2017-08-17 14:10:50 -07004253bool PeerConnection::HasRtpSender(cricket::MediaType type) const {
Steve Anton4171afb2017-11-20 10:20:22 -08004254 switch (type) {
4255 case cricket::MEDIA_TYPE_AUDIO:
4256 return !GetAudioTransceiver()->internal()->senders().empty();
4257 case cricket::MEDIA_TYPE_VIDEO:
4258 return !GetVideoTransceiver()->internal()->senders().empty();
4259 case cricket::MEDIA_TYPE_DATA:
4260 return false;
4261 }
4262 RTC_NOTREACHED();
4263 return false;
zhihuang1c378ed2017-08-17 14:10:50 -07004264}
4265
Steve Anton4171afb2017-11-20 10:20:22 -08004266rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
4267PeerConnection::FindSenderForTrack(MediaStreamTrackInterface* track) const {
4268 for (auto transceiver : transceivers_) {
4269 for (auto sender : transceiver->internal()->senders()) {
4270 if (sender->track() == track) {
4271 return sender;
4272 }
4273 }
4274 }
4275 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08004276}
4277
Steve Anton4171afb2017-11-20 10:20:22 -08004278rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
4279PeerConnection::FindSenderById(const std::string& sender_id) const {
4280 for (auto transceiver : transceivers_) {
4281 for (auto sender : transceiver->internal()->senders()) {
4282 if (sender->id() == sender_id) {
4283 return sender;
4284 }
4285 }
4286 }
4287 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07004288}
4289
Steve Anton4171afb2017-11-20 10:20:22 -08004290rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
4291PeerConnection::FindReceiverById(const std::string& receiver_id) const {
4292 for (auto transceiver : transceivers_) {
4293 for (auto receiver : transceiver->internal()->receivers()) {
4294 if (receiver->id() == receiver_id) {
4295 return receiver;
4296 }
4297 }
4298 }
4299 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07004300}
4301
Steve Anton4171afb2017-11-20 10:20:22 -08004302std::vector<PeerConnection::RtpSenderInfo>*
4303PeerConnection::GetRemoteSenderInfos(cricket::MediaType media_type) {
4304 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
4305 media_type == cricket::MEDIA_TYPE_VIDEO);
4306 return (media_type == cricket::MEDIA_TYPE_AUDIO)
4307 ? &remote_audio_sender_infos_
4308 : &remote_video_sender_infos_;
4309}
4310
4311std::vector<PeerConnection::RtpSenderInfo>* PeerConnection::GetLocalSenderInfos(
deadbeefab9b2d12015-10-14 11:33:11 -07004312 cricket::MediaType media_type) {
4313 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
4314 media_type == cricket::MEDIA_TYPE_VIDEO);
Steve Anton4171afb2017-11-20 10:20:22 -08004315 return (media_type == cricket::MEDIA_TYPE_AUDIO) ? &local_audio_sender_infos_
4316 : &local_video_sender_infos_;
deadbeefab9b2d12015-10-14 11:33:11 -07004317}
4318
Steve Anton4171afb2017-11-20 10:20:22 -08004319const PeerConnection::RtpSenderInfo* PeerConnection::FindSenderInfo(
4320 const std::vector<PeerConnection::RtpSenderInfo>& infos,
deadbeefab9b2d12015-10-14 11:33:11 -07004321 const std::string& stream_label,
Steve Anton4171afb2017-11-20 10:20:22 -08004322 const std::string sender_id) const {
4323 for (const RtpSenderInfo& sender_info : infos) {
4324 if (sender_info.stream_label == stream_label &&
4325 sender_info.sender_id == sender_id) {
4326 return &sender_info;
deadbeefab9b2d12015-10-14 11:33:11 -07004327 }
4328 }
4329 return nullptr;
4330}
4331
4332DataChannel* PeerConnection::FindDataChannelBySid(int sid) const {
4333 for (const auto& channel : sctp_data_channels_) {
4334 if (channel->id() == sid) {
4335 return channel;
4336 }
4337 }
4338 return nullptr;
4339}
4340
deadbeef91dd5672016-05-18 16:55:30 -07004341bool PeerConnection::InitializePortAllocator_n(
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004342 const RTCConfiguration& configuration) {
4343 cricket::ServerAddresses stun_servers;
4344 std::vector<cricket::RelayServerConfig> turn_servers;
deadbeef293e9262017-01-11 12:28:30 -08004345 if (ParseIceServers(configuration.servers, &stun_servers, &turn_servers) !=
4346 RTCErrorType::NONE) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004347 return false;
4348 }
4349
Taylor Brandstetterf8e65772016-06-27 17:20:15 -07004350 port_allocator_->Initialize();
4351
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004352 // To handle both internal and externally created port allocator, we will
4353 // enable BUNDLE here.
4354 int portallocator_flags = port_allocator_->flags();
4355 portallocator_flags |= cricket::PORTALLOCATOR_ENABLE_SHARED_SOCKET |
zhihuangb09b3f92017-03-07 14:40:51 -08004356 cricket::PORTALLOCATOR_ENABLE_IPV6 |
4357 cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI;
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004358 // If the disable-IPv6 flag was specified, we'll not override it
4359 // by experiment.
4360 if (configuration.disable_ipv6) {
4361 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
sprangc1b57a12017-02-28 08:50:47 -08004362 } else if (webrtc::field_trial::FindFullName("WebRTC-IPv6Default")
4363 .find("Disabled") == 0) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004364 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
4365 }
4366
zhihuangb09b3f92017-03-07 14:40:51 -08004367 if (configuration.disable_ipv6_on_wifi) {
4368 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI);
Mirko Bonadei675513b2017-11-09 11:09:25 +01004369 RTC_LOG(LS_INFO) << "IPv6 candidates on Wi-Fi are disabled.";
zhihuangb09b3f92017-03-07 14:40:51 -08004370 }
4371
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004372 if (configuration.tcp_candidate_policy == kTcpCandidatePolicyDisabled) {
4373 portallocator_flags |= cricket::PORTALLOCATOR_DISABLE_TCP;
Mirko Bonadei675513b2017-11-09 11:09:25 +01004374 RTC_LOG(LS_INFO) << "TCP candidates are disabled.";
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004375 }
4376
honghaiz60347052016-05-31 18:29:12 -07004377 if (configuration.candidate_network_policy ==
4378 kCandidateNetworkPolicyLowCost) {
4379 portallocator_flags |= cricket::PORTALLOCATOR_DISABLE_COSTLY_NETWORKS;
Mirko Bonadei675513b2017-11-09 11:09:25 +01004380 RTC_LOG(LS_INFO) << "Do not gather candidates on high-cost networks";
honghaiz60347052016-05-31 18:29:12 -07004381 }
4382
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +01004383 if (configuration.disable_link_local_networks) {
4384 portallocator_flags |= cricket::PORTALLOCATOR_DISABLE_LINK_LOCAL_NETWORKS;
4385 RTC_LOG(LS_INFO) << "Disable candidates on link-local network interfaces.";
4386 }
4387
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004388 port_allocator_->set_flags(portallocator_flags);
4389 // No step delay is used while allocating ports.
4390 port_allocator_->set_step_delay(cricket::kMinimumStepDelay);
4391 port_allocator_->set_candidate_filter(
4392 ConvertIceTransportTypeToCandidateFilter(configuration.type));
deadbeefd21eab32017-07-26 16:50:11 -07004393 port_allocator_->set_max_ipv6_networks(configuration.max_ipv6_networks);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004394
4395 // Call this last since it may create pooled allocator sessions using the
4396 // properties set above.
4397 port_allocator_->SetConfiguration(stun_servers, turn_servers,
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -07004398 configuration.ice_candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02004399 configuration.prune_turn_ports,
4400 configuration.turn_customizer);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004401 return true;
4402}
4403
deadbeef91dd5672016-05-18 16:55:30 -07004404bool PeerConnection::ReconfigurePortAllocator_n(
deadbeef293e9262017-01-11 12:28:30 -08004405 const cricket::ServerAddresses& stun_servers,
4406 const std::vector<cricket::RelayServerConfig>& turn_servers,
4407 IceTransportsType type,
4408 int candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02004409 bool prune_turn_ports,
4410 webrtc::TurnCustomizer* turn_customizer) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004411 port_allocator_->set_candidate_filter(
deadbeef293e9262017-01-11 12:28:30 -08004412 ConvertIceTransportTypeToCandidateFilter(type));
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004413 // Call this last since it may create pooled allocator sessions using the
4414 // candidate filter set above.
deadbeef6de92f92016-12-12 18:49:32 -08004415 return port_allocator_->SetConfiguration(
Jonas Orelandbdcee282017-10-10 14:01:40 +02004416 stun_servers, turn_servers, candidate_pool_size, prune_turn_ports,
4417 turn_customizer);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004418}
4419
Steve Antonba818672017-11-06 10:21:57 -08004420cricket::ChannelManager* PeerConnection::channel_manager() const {
4421 return factory_->channel_manager();
4422}
4423
4424MetricsObserverInterface* PeerConnection::metrics_observer() const {
4425 return uma_observer_;
4426}
4427
Elad Alon99c3fe52017-10-13 16:29:40 +02004428bool PeerConnection::StartRtcEventLog_w(
Bjorn Tereliusde939432017-11-20 17:38:14 +01004429 std::unique_ptr<RtcEventLogOutput> output,
4430 int64_t output_period_ms) {
zhihuang77985012017-02-07 15:45:16 -08004431 if (!event_log_) {
4432 return false;
4433 }
Bjorn Tereliusde939432017-11-20 17:38:14 +01004434 return event_log_->StartLogging(std::move(output), output_period_ms);
ivoc14d5dbe2016-07-04 07:06:55 -07004435}
4436
4437void PeerConnection::StopRtcEventLog_w() {
zhihuang77985012017-02-07 15:45:16 -08004438 if (event_log_) {
4439 event_log_->StopLogging();
4440 }
ivoc14d5dbe2016-07-04 07:06:55 -07004441}
nisseeaabdf62017-05-05 02:23:02 -07004442
Steve Anton75737c02017-11-06 10:37:17 -08004443cricket::BaseChannel* PeerConnection::GetChannel(
4444 const std::string& content_name) {
Steve Antondcc3c022017-12-22 16:02:54 -08004445 for (auto transceiver : transceivers_) {
4446 cricket::BaseChannel* channel = transceiver->internal()->channel();
4447 if (channel && channel->content_name() == content_name) {
4448 return channel;
4449 }
Steve Anton75737c02017-11-06 10:37:17 -08004450 }
4451 if (rtp_data_channel() &&
4452 rtp_data_channel()->content_name() == content_name) {
4453 return rtp_data_channel();
4454 }
4455 return nullptr;
4456}
4457
4458bool PeerConnection::GetSctpSslRole(rtc::SSLRole* role) {
4459 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004460 RTC_LOG(LS_INFO)
4461 << "Local and Remote descriptions must be applied to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004462 "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08004463 return false;
4464 }
4465 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004466 RTC_LOG(LS_INFO) << "Non-rejected SCTP m= section is needed to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004467 "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08004468 return false;
4469 }
4470
4471 return transport_controller_->GetSslRole(*sctp_transport_name_, role);
4472}
4473
4474bool PeerConnection::GetSslRole(const std::string& content_name,
4475 rtc::SSLRole* role) {
4476 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004477 RTC_LOG(LS_INFO)
4478 << "Local and Remote descriptions must be applied to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004479 "SSL Role of the session.";
Steve Anton75737c02017-11-06 10:37:17 -08004480 return false;
4481 }
4482
4483 return transport_controller_->GetSslRole(GetTransportName(content_name),
4484 role);
4485}
4486
Steve Antonf8470812017-12-04 10:46:21 -08004487void PeerConnection::SetSessionError(SessionError error,
4488 const std::string& error_desc) {
4489 RTC_DCHECK_RUN_ON(signaling_thread());
4490 if (error != session_error_) {
4491 session_error_ = error;
4492 session_error_desc_ = error_desc;
Steve Anton75737c02017-11-06 10:37:17 -08004493 }
4494}
4495
Steve Anton3828c062017-12-06 10:34:51 -08004496RTCError PeerConnection::UpdateSessionState(SdpType type,
Steve Anton8a006912017-12-04 15:25:56 -08004497 cricket::ContentSource source) {
4498 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08004499
4500 // If there's already a pending error then no state transition should happen.
4501 // But all call-sites should be verifying this before calling us!
Steve Antonf8470812017-12-04 10:46:21 -08004502 RTC_DCHECK(session_error() == SessionError::kNone);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004503
4504 // If this is an answer then we know whether to BUNDLE or not. If both the
4505 // local and remote side have agreed to BUNDLE, go ahead and enable it.
Steve Anton3828c062017-12-06 10:34:51 -08004506 if (type == SdpType::kAnswer) {
Steve Anton75737c02017-11-06 10:37:17 -08004507 const cricket::ContentGroup* local_bundle =
4508 local_description()->description()->GetGroupByName(
4509 cricket::GROUP_TYPE_BUNDLE);
4510 const cricket::ContentGroup* remote_bundle =
4511 remote_description()->description()->GetGroupByName(
4512 cricket::GROUP_TYPE_BUNDLE);
4513 if (local_bundle && remote_bundle) {
4514 // The answerer decides the transport to bundle on.
4515 const cricket::ContentGroup* answer_bundle =
4516 (source == cricket::CS_LOCAL ? local_bundle : remote_bundle);
4517 if (!EnableBundle(*answer_bundle)) {
Steve Anton8a006912017-12-04 15:25:56 -08004518 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
4519 kEnableBundleFailed);
Steve Anton75737c02017-11-06 10:37:17 -08004520 }
4521 }
Steve Anton75737c02017-11-06 10:37:17 -08004522 }
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004523
4524 // Only push down the transport description after potentially enabling BUNDLE;
4525 // we don't want to push down a description on a transport about to be
4526 // destroyed.
Steve Anton3828c062017-12-06 10:34:51 -08004527 RTCError error = PushdownTransportDescription(source, type);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004528 if (!error.ok()) {
4529 return error;
4530 }
4531
4532 // If this is answer-ish we're ready to let media flow.
Steve Anton3828c062017-12-06 10:34:51 -08004533 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Antoned10bd92017-12-05 10:52:59 -08004534 EnableSending();
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004535 }
4536
4537 // Update the signaling state according to the specified state machine (see
4538 // https://w3c.github.io/webrtc-pc/#rtcsignalingstate-enum).
Steve Anton3828c062017-12-06 10:34:51 -08004539 if (type == SdpType::kOffer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004540 ChangeSignalingState(source == cricket::CS_LOCAL
4541 ? PeerConnectionInterface::kHaveLocalOffer
4542 : PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton3828c062017-12-06 10:34:51 -08004543 } else if (type == SdpType::kPrAnswer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004544 ChangeSignalingState(source == cricket::CS_LOCAL
4545 ? PeerConnectionInterface::kHaveLocalPrAnswer
4546 : PeerConnectionInterface::kHaveRemotePrAnswer);
4547 } else {
Steve Anton3828c062017-12-06 10:34:51 -08004548 RTC_DCHECK(type == SdpType::kAnswer);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004549 ChangeSignalingState(PeerConnectionInterface::kStable);
4550 }
4551
4552 // Update internal objects according to the session description's media
4553 // descriptions.
Steve Anton3828c062017-12-06 10:34:51 -08004554 error = PushdownMediaDescription(type, source);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004555 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08004556 return error;
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004557 }
4558
Steve Anton8a006912017-12-04 15:25:56 -08004559 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08004560}
4561
Steve Anton8a006912017-12-04 15:25:56 -08004562RTCError PeerConnection::PushdownMediaDescription(
Steve Anton3828c062017-12-06 10:34:51 -08004563 SdpType type,
Steve Anton8a006912017-12-04 15:25:56 -08004564 cricket::ContentSource source) {
Steve Antoned10bd92017-12-05 10:52:59 -08004565 const SessionDescriptionInterface* sdesc =
4566 (source == cricket::CS_LOCAL ? local_description()
4567 : remote_description());
Steve Anton75737c02017-11-06 10:37:17 -08004568 RTC_DCHECK(sdesc);
Steve Antoned10bd92017-12-05 10:52:59 -08004569
4570 // Push down the new SDP media section for each audio/video transceiver.
4571 for (auto transceiver : transceivers_) {
Steve Anton75737c02017-11-06 10:37:17 -08004572 const ContentInfo* content_info =
Steve Antoned10bd92017-12-05 10:52:59 -08004573 FindMediaSectionForTransceiver(transceiver, sdesc);
4574 cricket::BaseChannel* channel = transceiver->internal()->channel();
4575 if (!channel || !content_info || content_info->rejected) {
Steve Anton75737c02017-11-06 10:37:17 -08004576 continue;
4577 }
4578 const MediaContentDescription* content_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08004579 content_info->media_description();
Steve Antoned10bd92017-12-05 10:52:59 -08004580 if (!content_desc) {
4581 continue;
4582 }
4583 std::string error;
4584 bool success =
4585 (source == cricket::CS_LOCAL)
Steve Anton3828c062017-12-06 10:34:51 -08004586 ? channel->SetLocalContent(content_desc, type, &error)
4587 : channel->SetRemoteContent(content_desc, type, &error);
Steve Antoned10bd92017-12-05 10:52:59 -08004588 if (!success) {
4589 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, std::move(error));
4590 }
4591 }
4592
4593 // If using the RtpDataChannel, push down the new SDP section for it too.
4594 if (rtp_data_channel_) {
4595 const ContentInfo* data_content =
4596 cricket::GetFirstDataContent(sdesc->description());
4597 if (data_content && !data_content->rejected) {
4598 const MediaContentDescription* data_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08004599 data_content->media_description();
Steve Antoned10bd92017-12-05 10:52:59 -08004600 if (data_desc) {
4601 std::string error;
4602 bool success =
4603 (source == cricket::CS_LOCAL)
Steve Anton3828c062017-12-06 10:34:51 -08004604 ? rtp_data_channel_->SetLocalContent(data_desc, type, &error)
4605 : rtp_data_channel_->SetRemoteContent(data_desc, type,
Steve Antoned10bd92017-12-05 10:52:59 -08004606 &error);
4607 if (!success) {
4608 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
4609 std::move(error));
4610 }
Steve Anton75737c02017-11-06 10:37:17 -08004611 }
4612 }
4613 }
Steve Antoned10bd92017-12-05 10:52:59 -08004614
Steve Anton75737c02017-11-06 10:37:17 -08004615 // Need complete offer/answer with an SCTP m= section before starting SCTP,
4616 // according to https://tools.ietf.org/html/draft-ietf-mmusic-sctp-sdp-19
4617 if (sctp_transport_ && local_description() && remote_description() &&
4618 cricket::GetFirstDataContent(local_description()->description()) &&
4619 cricket::GetFirstDataContent(remote_description()->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08004620 bool success = network_thread()->Invoke<bool>(
Steve Anton75737c02017-11-06 10:37:17 -08004621 RTC_FROM_HERE,
4622 rtc::Bind(&PeerConnection::PushdownSctpParameters_n, this, source));
Steve Anton8a006912017-12-04 15:25:56 -08004623 if (!success) {
4624 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
4625 "Failed to push down SCTP parameters.");
4626 }
Steve Anton75737c02017-11-06 10:37:17 -08004627 }
Steve Antoned10bd92017-12-05 10:52:59 -08004628
Steve Anton8a006912017-12-04 15:25:56 -08004629 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08004630}
4631
4632bool PeerConnection::PushdownSctpParameters_n(cricket::ContentSource source) {
4633 RTC_DCHECK(network_thread()->IsCurrent());
4634 RTC_DCHECK(local_description());
4635 RTC_DCHECK(remote_description());
4636 // Apply the SCTP port (which is hidden inside a DataCodec structure...)
4637 // When we support "max-message-size", that would also be pushed down here.
4638 return sctp_transport_->Start(
4639 GetSctpPort(local_description()->description()),
4640 GetSctpPort(remote_description()->description()));
4641}
4642
Steve Anton8a006912017-12-04 15:25:56 -08004643RTCError PeerConnection::PushdownTransportDescription(
4644 cricket::ContentSource source,
Steve Anton3828c062017-12-06 10:34:51 -08004645 SdpType type) {
Steve Anton8a006912017-12-04 15:25:56 -08004646 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08004647
Steve Anton8a006912017-12-04 15:25:56 -08004648 const SessionDescriptionInterface* sdesc =
4649 (source == cricket::CS_LOCAL ? local_description()
4650 : remote_description());
4651 RTC_DCHECK(sdesc);
4652 for (const cricket::TransportInfo& tinfo :
4653 sdesc->description()->transport_infos()) {
4654 std::string error;
4655 bool success;
4656 if (source == cricket::CS_LOCAL) {
4657 success = transport_controller_->SetLocalTransportDescription(
Steve Anton3828c062017-12-06 10:34:51 -08004658 tinfo.content_name, tinfo.description, type, &error);
Steve Anton8a006912017-12-04 15:25:56 -08004659 } else {
4660 success = transport_controller_->SetRemoteTransportDescription(
Steve Anton3828c062017-12-06 10:34:51 -08004661 tinfo.content_name, tinfo.description, type, &error);
Steve Anton8a006912017-12-04 15:25:56 -08004662 }
4663 if (!success) {
Steve Antondcc3c022017-12-22 16:02:54 -08004664 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
4665 "Failed to push down transport description for " +
4666 tinfo.content_name + ": " + error);
Steve Anton75737c02017-11-06 10:37:17 -08004667 }
4668 }
4669
Steve Anton8a006912017-12-04 15:25:56 -08004670 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08004671}
4672
4673bool PeerConnection::GetTransportDescription(
4674 const SessionDescription* description,
4675 const std::string& content_name,
4676 cricket::TransportDescription* tdesc) {
4677 if (!description || !tdesc) {
4678 return false;
4679 }
4680 const TransportInfo* transport_info =
4681 description->GetTransportInfoByName(content_name);
4682 if (!transport_info) {
4683 return false;
4684 }
4685 *tdesc = transport_info->description;
4686 return true;
4687}
4688
4689bool PeerConnection::EnableBundle(const cricket::ContentGroup& bundle) {
4690 const std::string* first_content_name = bundle.FirstContentName();
4691 if (!first_content_name) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004692 RTC_LOG(LS_WARNING) << "Tried to BUNDLE with no contents.";
Steve Anton75737c02017-11-06 10:37:17 -08004693 return false;
4694 }
4695 const std::string& transport_name = *first_content_name;
4696
4697 auto maybe_set_transport = [this, bundle,
4698 transport_name](cricket::BaseChannel* ch) {
4699 if (!ch || !bundle.HasContentName(ch->content_name())) {
Steve Antoned10bd92017-12-05 10:52:59 -08004700 return;
Steve Anton75737c02017-11-06 10:37:17 -08004701 }
4702
4703 std::string old_transport_name = ch->transport_name();
4704 if (old_transport_name == transport_name) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004705 RTC_LOG(LS_INFO) << "BUNDLE already enabled for " << ch->content_name()
4706 << " on " << transport_name << ".";
Steve Antoned10bd92017-12-05 10:52:59 -08004707 return;
Steve Anton75737c02017-11-06 10:37:17 -08004708 }
4709
4710 cricket::DtlsTransportInternal* rtp_dtls_transport =
4711 transport_controller_->CreateDtlsTransport(
4712 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4713 bool need_rtcp = (ch->rtcp_dtls_transport() != nullptr);
4714 cricket::DtlsTransportInternal* rtcp_dtls_transport = nullptr;
4715 if (need_rtcp) {
4716 rtcp_dtls_transport = transport_controller_->CreateDtlsTransport(
4717 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
4718 }
4719
4720 ch->SetTransports(rtp_dtls_transport, rtcp_dtls_transport);
Mirko Bonadei675513b2017-11-09 11:09:25 +01004721 RTC_LOG(LS_INFO) << "Enabled BUNDLE for " << ch->content_name() << " on "
4722 << transport_name << ".";
Steve Anton75737c02017-11-06 10:37:17 -08004723 transport_controller_->DestroyDtlsTransport(
4724 old_transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4725 // If the channel needs rtcp, it means that the channel used to have a
4726 // rtcp transport which needs to be deleted now.
4727 if (need_rtcp) {
4728 transport_controller_->DestroyDtlsTransport(
4729 old_transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
4730 }
Steve Anton75737c02017-11-06 10:37:17 -08004731 };
4732
Steve Antoned10bd92017-12-05 10:52:59 -08004733 for (auto transceiver : transceivers_) {
4734 maybe_set_transport(transceiver->internal()->channel());
Steve Anton75737c02017-11-06 10:37:17 -08004735 }
Steve Antoned10bd92017-12-05 10:52:59 -08004736 maybe_set_transport(rtp_data_channel_);
4737
Steve Anton75737c02017-11-06 10:37:17 -08004738 // For SCTP, transport creation/deletion happens here instead of in the
4739 // object itself.
4740 if (sctp_transport_) {
4741 RTC_DCHECK(sctp_transport_name_);
4742 RTC_DCHECK(sctp_content_name_);
4743 if (transport_name != *sctp_transport_name_ &&
4744 bundle.HasContentName(*sctp_content_name_)) {
4745 network_thread()->Invoke<void>(
4746 RTC_FROM_HERE, rtc::Bind(&PeerConnection::ChangeSctpTransport_n, this,
4747 transport_name));
4748 }
4749 }
4750
4751 return true;
4752}
4753
Steve Anton75737c02017-11-06 10:37:17 -08004754cricket::IceConfig PeerConnection::ParseIceConfig(
4755 const PeerConnectionInterface::RTCConfiguration& config) const {
4756 cricket::ContinualGatheringPolicy gathering_policy;
4757 // TODO(honghaiz): Add the third continual gathering policy in
4758 // PeerConnectionInterface and map it to GATHER_CONTINUALLY_AND_RECOVER.
4759 switch (config.continual_gathering_policy) {
4760 case PeerConnectionInterface::GATHER_ONCE:
4761 gathering_policy = cricket::GATHER_ONCE;
4762 break;
4763 case PeerConnectionInterface::GATHER_CONTINUALLY:
4764 gathering_policy = cricket::GATHER_CONTINUALLY;
4765 break;
4766 default:
4767 RTC_NOTREACHED();
4768 gathering_policy = cricket::GATHER_ONCE;
4769 }
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08004770
Steve Anton75737c02017-11-06 10:37:17 -08004771 cricket::IceConfig ice_config;
4772 ice_config.receiving_timeout = config.ice_connection_receiving_timeout;
4773 ice_config.prioritize_most_likely_candidate_pairs =
4774 config.prioritize_most_likely_ice_candidate_pairs;
4775 ice_config.backup_connection_ping_interval =
4776 config.ice_backup_candidate_pair_ping_interval;
4777 ice_config.continual_gathering_policy = gathering_policy;
4778 ice_config.presume_writable_when_fully_relayed =
4779 config.presume_writable_when_fully_relayed;
4780 ice_config.ice_check_min_interval = config.ice_check_min_interval;
4781 ice_config.regather_all_networks_interval_range =
4782 config.ice_regather_interval_range;
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08004783 ice_config.network_preference = config.network_preference;
Steve Anton75737c02017-11-06 10:37:17 -08004784 return ice_config;
4785}
4786
Steve Anton75737c02017-11-06 10:37:17 -08004787bool PeerConnection::GetLocalTrackIdBySsrc(uint32_t ssrc,
4788 std::string* track_id) {
4789 if (!local_description()) {
4790 return false;
4791 }
4792 return webrtc::GetTrackIdBySsrc(local_description()->description(), ssrc,
4793 track_id);
4794}
4795
4796bool PeerConnection::GetRemoteTrackIdBySsrc(uint32_t ssrc,
4797 std::string* track_id) {
4798 if (!remote_description()) {
4799 return false;
4800 }
4801 return webrtc::GetTrackIdBySsrc(remote_description()->description(), ssrc,
4802 track_id);
4803}
4804
4805bool PeerConnection::SendData(const cricket::SendDataParams& params,
4806 const rtc::CopyOnWriteBuffer& payload,
4807 cricket::SendDataResult* result) {
4808 if (!rtp_data_channel_ && !sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004809 RTC_LOG(LS_ERROR) << "SendData called when rtp_data_channel_ "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004810 "and sctp_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08004811 return false;
4812 }
4813 return rtp_data_channel_
4814 ? rtp_data_channel_->SendData(params, payload, result)
4815 : network_thread()->Invoke<bool>(
4816 RTC_FROM_HERE,
4817 Bind(&cricket::SctpTransportInternal::SendData,
4818 sctp_transport_.get(), params, payload, result));
4819}
4820
4821bool PeerConnection::ConnectDataChannel(DataChannel* webrtc_data_channel) {
4822 if (!rtp_data_channel_ && !sctp_transport_) {
4823 // Don't log an error here, because DataChannels are expected to call
4824 // ConnectDataChannel in this state. It's the only way to initially tell
4825 // whether or not the underlying transport is ready.
4826 return false;
4827 }
4828 if (rtp_data_channel_) {
4829 rtp_data_channel_->SignalReadyToSendData.connect(
4830 webrtc_data_channel, &DataChannel::OnChannelReady);
4831 rtp_data_channel_->SignalDataReceived.connect(webrtc_data_channel,
4832 &DataChannel::OnDataReceived);
4833 } else {
4834 SignalSctpReadyToSendData.connect(webrtc_data_channel,
4835 &DataChannel::OnChannelReady);
4836 SignalSctpDataReceived.connect(webrtc_data_channel,
4837 &DataChannel::OnDataReceived);
4838 SignalSctpStreamClosedRemotely.connect(
4839 webrtc_data_channel, &DataChannel::OnStreamClosedRemotely);
4840 }
4841 return true;
4842}
4843
4844void PeerConnection::DisconnectDataChannel(DataChannel* webrtc_data_channel) {
4845 if (!rtp_data_channel_ && !sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004846 RTC_LOG(LS_ERROR)
4847 << "DisconnectDataChannel called when rtp_data_channel_ and "
4848 "sctp_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08004849 return;
4850 }
4851 if (rtp_data_channel_) {
4852 rtp_data_channel_->SignalReadyToSendData.disconnect(webrtc_data_channel);
4853 rtp_data_channel_->SignalDataReceived.disconnect(webrtc_data_channel);
4854 } else {
4855 SignalSctpReadyToSendData.disconnect(webrtc_data_channel);
4856 SignalSctpDataReceived.disconnect(webrtc_data_channel);
4857 SignalSctpStreamClosedRemotely.disconnect(webrtc_data_channel);
4858 }
4859}
4860
4861void PeerConnection::AddSctpDataStream(int sid) {
4862 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004863 RTC_LOG(LS_ERROR)
4864 << "AddSctpDataStream called when sctp_transport_ is NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08004865 return;
4866 }
4867 network_thread()->Invoke<void>(
4868 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::OpenStream,
4869 sctp_transport_.get(), sid));
4870}
4871
4872void PeerConnection::RemoveSctpDataStream(int sid) {
4873 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004874 RTC_LOG(LS_ERROR) << "RemoveSctpDataStream called when sctp_transport_ is "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004875 "NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08004876 return;
4877 }
4878 network_thread()->Invoke<void>(
4879 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::ResetStream,
4880 sctp_transport_.get(), sid));
4881}
4882
4883bool PeerConnection::ReadyToSendData() const {
4884 return (rtp_data_channel_ && rtp_data_channel_->ready_to_send_data()) ||
4885 sctp_ready_to_send_data_;
4886}
4887
Steve Anton5dfde182018-02-06 10:34:40 -08004888std::map<std::string, std::string> PeerConnection::GetTransportNamesByMid()
4889 const {
4890 std::map<std::string, std::string> transport_names_by_mid;
4891 for (auto transceiver : transceivers_) {
4892 cricket::BaseChannel* channel = transceiver->internal()->channel();
4893 if (channel) {
4894 transport_names_by_mid[channel->content_name()] =
4895 channel->transport_name();
4896 }
Steve Anton75737c02017-11-06 10:37:17 -08004897 }
Steve Anton5dfde182018-02-06 10:34:40 -08004898 if (rtp_data_channel_) {
4899 transport_names_by_mid[rtp_data_channel_->content_name()] =
4900 rtp_data_channel_->transport_name();
Steve Anton75737c02017-11-06 10:37:17 -08004901 }
4902 if (sctp_transport_) {
Steve Anton5dfde182018-02-06 10:34:40 -08004903 transport_names_by_mid[*sctp_content_name_] = *sctp_transport_name_;
Steve Anton75737c02017-11-06 10:37:17 -08004904 }
Steve Anton5dfde182018-02-06 10:34:40 -08004905 return transport_names_by_mid;
Steve Anton75737c02017-11-06 10:37:17 -08004906}
4907
Steve Anton5dfde182018-02-06 10:34:40 -08004908std::map<std::string, cricket::TransportStats>
4909PeerConnection::GetTransportStatsByNames(
4910 const std::set<std::string>& transport_names) {
4911 if (!network_thread()->IsCurrent()) {
4912 return network_thread()
4913 ->Invoke<std::map<std::string, cricket::TransportStats>>(
4914 RTC_FROM_HERE,
4915 [&] { return GetTransportStatsByNames(transport_names); });
Steve Anton75737c02017-11-06 10:37:17 -08004916 }
Steve Anton5dfde182018-02-06 10:34:40 -08004917 std::map<std::string, cricket::TransportStats> transport_stats_by_name;
4918 for (const std::string& transport_name : transport_names) {
4919 cricket::TransportStats transport_stats;
4920 bool success =
4921 transport_controller_->GetStats(transport_name, &transport_stats);
4922 if (success) {
4923 transport_stats_by_name[transport_name] = std::move(transport_stats);
4924 } else {
4925 RTC_LOG(LS_ERROR) << "Failed to get transport stats for transport_name="
4926 << transport_name;
4927 }
4928 }
4929 return transport_stats_by_name;
Steve Anton75737c02017-11-06 10:37:17 -08004930}
4931
4932bool PeerConnection::GetLocalCertificate(
4933 const std::string& transport_name,
4934 rtc::scoped_refptr<rtc::RTCCertificate>* certificate) {
4935 return transport_controller_->GetLocalCertificate(transport_name,
4936 certificate);
4937}
4938
4939std::unique_ptr<rtc::SSLCertificate> PeerConnection::GetRemoteSSLCertificate(
4940 const std::string& transport_name) {
4941 return transport_controller_->GetRemoteSSLCertificate(transport_name);
4942}
4943
4944cricket::DataChannelType PeerConnection::data_channel_type() const {
4945 return data_channel_type_;
4946}
4947
4948bool PeerConnection::IceRestartPending(const std::string& content_name) const {
4949 return pending_ice_restarts_.find(content_name) !=
4950 pending_ice_restarts_.end();
4951}
4952
Steve Anton75737c02017-11-06 10:37:17 -08004953bool PeerConnection::NeedsIceRestart(const std::string& content_name) const {
4954 return transport_controller_->NeedsIceRestart(content_name);
4955}
4956
4957void PeerConnection::OnCertificateReady(
4958 const rtc::scoped_refptr<rtc::RTCCertificate>& certificate) {
4959 transport_controller_->SetLocalCertificate(certificate);
4960}
4961
4962void PeerConnection::OnDtlsSrtpSetupFailure(cricket::BaseChannel*, bool rtcp) {
Steve Antonf8470812017-12-04 10:46:21 -08004963 SetSessionError(SessionError::kTransport,
4964 rtcp ? kDtlsSrtpSetupFailureRtcp : kDtlsSrtpSetupFailureRtp);
Steve Anton75737c02017-11-06 10:37:17 -08004965}
4966
4967void PeerConnection::OnTransportControllerConnectionState(
4968 cricket::IceConnectionState state) {
4969 switch (state) {
4970 case cricket::kIceConnectionConnecting:
4971 // If the current state is Connected or Completed, then there were
4972 // writable channels but now there are not, so the next state must
4973 // be Disconnected.
4974 // kIceConnectionConnecting is currently used as the default,
4975 // un-connected state by the TransportController, so its only use is
4976 // detecting disconnections.
4977 if (ice_connection_state_ ==
4978 PeerConnectionInterface::kIceConnectionConnected ||
4979 ice_connection_state_ ==
4980 PeerConnectionInterface::kIceConnectionCompleted) {
4981 SetIceConnectionState(
4982 PeerConnectionInterface::kIceConnectionDisconnected);
4983 }
4984 break;
4985 case cricket::kIceConnectionFailed:
4986 SetIceConnectionState(PeerConnectionInterface::kIceConnectionFailed);
4987 break;
4988 case cricket::kIceConnectionConnected:
Mirko Bonadei675513b2017-11-09 11:09:25 +01004989 RTC_LOG(LS_INFO) << "Changing to ICE connected state because "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004990 "all transports are writable.";
Steve Anton75737c02017-11-06 10:37:17 -08004991 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
4992 break;
4993 case cricket::kIceConnectionCompleted:
Mirko Bonadei675513b2017-11-09 11:09:25 +01004994 RTC_LOG(LS_INFO) << "Changing to ICE completed state because "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004995 "all transports are complete.";
Steve Anton75737c02017-11-06 10:37:17 -08004996 if (ice_connection_state_ !=
4997 PeerConnectionInterface::kIceConnectionConnected) {
4998 // If jumping directly from "checking" to "connected",
4999 // signal "connected" first.
5000 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
5001 }
5002 SetIceConnectionState(PeerConnectionInterface::kIceConnectionCompleted);
5003 if (metrics_observer()) {
5004 ReportTransportStats();
5005 }
5006 break;
5007 default:
5008 RTC_NOTREACHED();
5009 }
5010}
5011
5012void PeerConnection::OnTransportControllerCandidatesGathered(
5013 const std::string& transport_name,
5014 const cricket::Candidates& candidates) {
5015 RTC_DCHECK(signaling_thread()->IsCurrent());
5016 int sdp_mline_index;
5017 if (!GetLocalCandidateMediaIndex(transport_name, &sdp_mline_index)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005018 RTC_LOG(LS_ERROR)
5019 << "OnTransportControllerCandidatesGathered: content name "
5020 << transport_name << " not found";
Steve Anton75737c02017-11-06 10:37:17 -08005021 return;
5022 }
5023
5024 for (cricket::Candidates::const_iterator citer = candidates.begin();
5025 citer != candidates.end(); ++citer) {
5026 // Use transport_name as the candidate media id.
5027 std::unique_ptr<JsepIceCandidate> candidate(
5028 new JsepIceCandidate(transport_name, sdp_mline_index, *citer));
5029 if (local_description()) {
5030 mutable_local_description()->AddCandidate(candidate.get());
5031 }
5032 OnIceCandidate(std::move(candidate));
5033 }
5034}
5035
5036void PeerConnection::OnTransportControllerCandidatesRemoved(
5037 const std::vector<cricket::Candidate>& candidates) {
5038 RTC_DCHECK(signaling_thread()->IsCurrent());
5039 // Sanity check.
5040 for (const cricket::Candidate& candidate : candidates) {
5041 if (candidate.transport_name().empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005042 RTC_LOG(LS_ERROR) << "OnTransportControllerCandidatesRemoved: "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005043 "empty content name in candidate "
Mirko Bonadei675513b2017-11-09 11:09:25 +01005044 << candidate.ToString();
Steve Anton75737c02017-11-06 10:37:17 -08005045 return;
5046 }
5047 }
5048
5049 if (local_description()) {
5050 mutable_local_description()->RemoveCandidates(candidates);
5051 }
5052 OnIceCandidatesRemoved(candidates);
5053}
5054
5055void PeerConnection::OnTransportControllerDtlsHandshakeError(
5056 rtc::SSLHandshakeError error) {
5057 if (metrics_observer()) {
5058 metrics_observer()->IncrementEnumCounter(
5059 webrtc::kEnumCounterDtlsHandshakeError, static_cast<int>(error),
5060 static_cast<int>(rtc::SSLHandshakeError::MAX_VALUE));
5061 }
5062}
5063
Steve Antoned10bd92017-12-05 10:52:59 -08005064void PeerConnection::EnableSending() {
5065 for (auto transceiver : transceivers_) {
5066 cricket::BaseChannel* channel = transceiver->internal()->channel();
5067 if (channel && !channel->enabled()) {
5068 channel->Enable(true);
5069 }
Steve Anton75737c02017-11-06 10:37:17 -08005070 }
5071
Steve Anton4171afb2017-11-20 10:20:22 -08005072 if (rtp_data_channel_ && !rtp_data_channel_->enabled()) {
Steve Anton75737c02017-11-06 10:37:17 -08005073 rtp_data_channel_->Enable(true);
Steve Anton4171afb2017-11-20 10:20:22 -08005074 }
Steve Anton75737c02017-11-06 10:37:17 -08005075}
5076
5077// Returns the media index for a local ice candidate given the content name.
5078bool PeerConnection::GetLocalCandidateMediaIndex(
5079 const std::string& content_name,
5080 int* sdp_mline_index) {
5081 if (!local_description() || !sdp_mline_index) {
5082 return false;
5083 }
5084
5085 bool content_found = false;
5086 const ContentInfos& contents = local_description()->description()->contents();
5087 for (size_t index = 0; index < contents.size(); ++index) {
5088 if (contents[index].name == content_name) {
5089 *sdp_mline_index = static_cast<int>(index);
5090 content_found = true;
5091 break;
5092 }
5093 }
5094 return content_found;
5095}
5096
5097bool PeerConnection::UseCandidatesInSessionDescription(
5098 const SessionDescriptionInterface* remote_desc) {
5099 if (!remote_desc) {
5100 return true;
5101 }
5102 bool ret = true;
5103
5104 for (size_t m = 0; m < remote_desc->number_of_mediasections(); ++m) {
5105 const IceCandidateCollection* candidates = remote_desc->candidates(m);
5106 for (size_t n = 0; n < candidates->count(); ++n) {
5107 const IceCandidateInterface* candidate = candidates->at(n);
5108 bool valid = false;
5109 if (!ReadyToUseRemoteCandidate(candidate, remote_desc, &valid)) {
5110 if (valid) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005111 RTC_LOG(LS_INFO)
5112 << "UseCandidatesInSessionDescription: Not ready to use "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005113 "candidate.";
Steve Anton75737c02017-11-06 10:37:17 -08005114 }
5115 continue;
5116 }
5117 ret = UseCandidate(candidate);
5118 if (!ret) {
5119 break;
5120 }
5121 }
5122 }
5123 return ret;
5124}
5125
5126bool PeerConnection::UseCandidate(const IceCandidateInterface* candidate) {
5127 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
5128 size_t remote_content_size =
5129 remote_description()->description()->contents().size();
5130 if (mediacontent_index >= remote_content_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005131 RTC_LOG(LS_ERROR) << "UseCandidate: Invalid candidate media index.";
Steve Anton75737c02017-11-06 10:37:17 -08005132 return false;
5133 }
5134
5135 cricket::ContentInfo content =
5136 remote_description()->description()->contents()[mediacontent_index];
5137 std::vector<cricket::Candidate> candidates;
5138 candidates.push_back(candidate->candidate());
5139 // Invoking BaseSession method to handle remote candidates.
5140 std::string error;
5141 if (transport_controller_->AddRemoteCandidates(content.name, candidates,
5142 &error)) {
5143 // Candidates successfully submitted for checking.
5144 if (ice_connection_state_ == PeerConnectionInterface::kIceConnectionNew ||
5145 ice_connection_state_ ==
5146 PeerConnectionInterface::kIceConnectionDisconnected) {
5147 // If state is New, then the session has just gotten its first remote ICE
5148 // candidates, so go to Checking.
5149 // If state is Disconnected, the session is re-using old candidates or
5150 // receiving additional ones, so go to Checking.
5151 // If state is Connected, stay Connected.
5152 // TODO(bemasc): If state is Connected, and the new candidates are for a
5153 // newly added transport, then the state actually _should_ move to
5154 // checking. Add a way to distinguish that case.
5155 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
5156 }
5157 // TODO(bemasc): If state is Completed, go back to Connected.
5158 } else {
5159 if (!error.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005160 RTC_LOG(LS_WARNING) << error;
Steve Anton75737c02017-11-06 10:37:17 -08005161 }
5162 }
5163 return true;
5164}
5165
5166void PeerConnection::RemoveUnusedChannels(const SessionDescription* desc) {
Steve Anton75737c02017-11-06 10:37:17 -08005167 // Destroy video channel first since it may have a pointer to the
5168 // voice channel.
5169 const cricket::ContentInfo* video_info = cricket::GetFirstVideoContent(desc);
Steve Anton6fec8802017-12-04 10:37:29 -08005170 if (!video_info || video_info->rejected) {
5171 DestroyTransceiverChannel(GetVideoTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08005172 }
5173
Steve Anton6fec8802017-12-04 10:37:29 -08005174 const cricket::ContentInfo* audio_info = cricket::GetFirstAudioContent(desc);
5175 if (!audio_info || audio_info->rejected) {
5176 DestroyTransceiverChannel(GetAudioTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08005177 }
5178
5179 const cricket::ContentInfo* data_info = cricket::GetFirstDataContent(desc);
5180 if (!data_info || data_info->rejected) {
Steve Anton6fec8802017-12-04 10:37:29 -08005181 DestroyDataChannel();
Steve Anton75737c02017-11-06 10:37:17 -08005182 }
5183}
5184
Steve Antoneda6ccd2017-12-04 10:21:55 -08005185std::string PeerConnection::GetTransportNameForMediaSection(
5186 const std::string& mid,
5187 const cricket::ContentGroup* bundle_group) const {
5188 if (!bundle_group) {
5189 return mid;
Steve Anton75737c02017-11-06 10:37:17 -08005190 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005191 const std::string* first_content_name = bundle_group->FirstContentName();
Steve Anton75737c02017-11-06 10:37:17 -08005192 if (!first_content_name) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005193 RTC_LOG(LS_WARNING) << "Tried to BUNDLE with no contents.";
Steve Antoneda6ccd2017-12-04 10:21:55 -08005194 return mid;
Steve Anton75737c02017-11-06 10:37:17 -08005195 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005196 if (!bundle_group->HasContentName(mid)) {
5197 RTC_LOG(LS_WARNING) << mid << " is not part of any bundle group";
5198 return mid;
Steve Anton75737c02017-11-06 10:37:17 -08005199 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005200 RTC_LOG(LS_INFO) << "Bundling " << mid << " on " << *first_content_name;
5201 return *first_content_name;
Steve Anton75737c02017-11-06 10:37:17 -08005202}
5203
Steve Antondcc3c022017-12-22 16:02:54 -08005204RTCErrorOr<const cricket::ContentGroup*> PeerConnection::GetEarlyBundleGroup(
5205 const SessionDescription& desc) const {
Steve Anton75737c02017-11-06 10:37:17 -08005206 const cricket::ContentGroup* bundle_group = nullptr;
5207 if (configuration_.bundle_policy ==
5208 PeerConnectionInterface::kBundlePolicyMaxBundle) {
Steve Antondcc3c022017-12-22 16:02:54 -08005209 bundle_group = desc.GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton75737c02017-11-06 10:37:17 -08005210 if (!bundle_group) {
Steve Anton8a006912017-12-04 15:25:56 -08005211 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5212 "max-bundle configured but session description "
5213 "has no BUNDLE group");
Steve Anton75737c02017-11-06 10:37:17 -08005214 }
5215 }
Steve Antondcc3c022017-12-22 16:02:54 -08005216 return std::move(bundle_group);
5217}
5218
5219RTCError PeerConnection::CreateChannels(const SessionDescription& desc) {
5220 auto bundle_group_or_error = GetEarlyBundleGroup(desc);
5221 if (!bundle_group_or_error.ok()) {
5222 return bundle_group_or_error.MoveError();
5223 }
5224 const cricket::ContentGroup* bundle_group = bundle_group_or_error.MoveValue();
Steve Anton75737c02017-11-06 10:37:17 -08005225
Steve Antoneda6ccd2017-12-04 10:21:55 -08005226 // Creating the media channels and transport proxies.
Steve Antondcc3c022017-12-22 16:02:54 -08005227 const cricket::ContentInfo* voice = cricket::GetFirstAudioContent(&desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08005228 if (voice && !voice->rejected &&
5229 !GetAudioTransceiver()->internal()->channel()) {
5230 cricket::VoiceChannel* voice_channel = CreateVoiceChannel(
5231 voice->name,
5232 GetTransportNameForMediaSection(voice->name, bundle_group));
5233 if (!voice_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08005234 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5235 "Failed to create voice channel.");
Steve Antoneda6ccd2017-12-04 10:21:55 -08005236 }
5237 GetAudioTransceiver()->internal()->SetChannel(voice_channel);
5238 }
5239
Steve Antondcc3c022017-12-22 16:02:54 -08005240 const cricket::ContentInfo* video = cricket::GetFirstVideoContent(&desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08005241 if (video && !video->rejected &&
5242 !GetVideoTransceiver()->internal()->channel()) {
5243 cricket::VideoChannel* video_channel = CreateVideoChannel(
5244 video->name,
5245 GetTransportNameForMediaSection(video->name, bundle_group));
5246 if (!video_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08005247 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5248 "Failed to create video channel.");
Steve Anton75737c02017-11-06 10:37:17 -08005249 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005250 GetVideoTransceiver()->internal()->SetChannel(video_channel);
Steve Anton75737c02017-11-06 10:37:17 -08005251 }
5252
Steve Antondcc3c022017-12-22 16:02:54 -08005253 const cricket::ContentInfo* data = cricket::GetFirstDataContent(&desc);
Steve Anton75737c02017-11-06 10:37:17 -08005254 if (data_channel_type_ != cricket::DCT_NONE && data && !data->rejected &&
5255 !rtp_data_channel_ && !sctp_transport_) {
Steve Antoneda6ccd2017-12-04 10:21:55 -08005256 if (!CreateDataChannel(data->name, GetTransportNameForMediaSection(
5257 data->name, bundle_group))) {
Steve Anton8a006912017-12-04 15:25:56 -08005258 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5259 "Failed to create data channel.");
Steve Anton75737c02017-11-06 10:37:17 -08005260 }
5261 }
5262
Steve Anton8a006912017-12-04 15:25:56 -08005263 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08005264}
5265
Steve Anton4171afb2017-11-20 10:20:22 -08005266// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08005267cricket::VoiceChannel* PeerConnection::CreateVoiceChannel(
5268 const std::string& mid,
5269 const std::string& transport_name) {
Steve Anton75737c02017-11-06 10:37:17 -08005270 cricket::DtlsTransportInternal* rtp_dtls_transport =
5271 transport_controller_->CreateDtlsTransport(
5272 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5273 cricket::DtlsTransportInternal* rtcp_dtls_transport = nullptr;
5274 if (configuration_.rtcp_mux_policy !=
5275 PeerConnectionInterface::kRtcpMuxPolicyRequire) {
5276 rtcp_dtls_transport = transport_controller_->CreateDtlsTransport(
5277 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
5278 }
5279
5280 cricket::VoiceChannel* voice_channel = channel_manager()->CreateVoiceChannel(
5281 call_.get(), configuration_.media_config, rtp_dtls_transport,
Steve Antoneda6ccd2017-12-04 10:21:55 -08005282 rtcp_dtls_transport, signaling_thread(), mid, SrtpRequired(),
5283 audio_options_);
Steve Anton75737c02017-11-06 10:37:17 -08005284 if (!voice_channel) {
5285 transport_controller_->DestroyDtlsTransport(
5286 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5287 if (rtcp_dtls_transport) {
5288 transport_controller_->DestroyDtlsTransport(
5289 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
5290 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005291 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08005292 }
Steve Anton75737c02017-11-06 10:37:17 -08005293 voice_channel->SignalRtcpMuxFullyActive.connect(
5294 this, &PeerConnection::DestroyRtcpTransport_n);
5295 voice_channel->SignalDtlsSrtpSetupFailure.connect(
5296 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08005297 voice_channel->SignalSentPacket.connect(this,
5298 &PeerConnection::OnSentPacket_w);
Steve Anton4171afb2017-11-20 10:20:22 -08005299
Steve Antoneda6ccd2017-12-04 10:21:55 -08005300 return voice_channel;
Steve Anton75737c02017-11-06 10:37:17 -08005301}
5302
Steve Anton4171afb2017-11-20 10:20:22 -08005303// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08005304cricket::VideoChannel* PeerConnection::CreateVideoChannel(
5305 const std::string& mid,
5306 const std::string& transport_name) {
Steve Anton75737c02017-11-06 10:37:17 -08005307 cricket::DtlsTransportInternal* rtp_dtls_transport =
5308 transport_controller_->CreateDtlsTransport(
5309 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5310 cricket::DtlsTransportInternal* rtcp_dtls_transport = nullptr;
5311 if (configuration_.rtcp_mux_policy !=
5312 PeerConnectionInterface::kRtcpMuxPolicyRequire) {
5313 rtcp_dtls_transport = transport_controller_->CreateDtlsTransport(
5314 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
5315 }
5316
5317 cricket::VideoChannel* video_channel = channel_manager()->CreateVideoChannel(
5318 call_.get(), configuration_.media_config, rtp_dtls_transport,
Steve Antoneda6ccd2017-12-04 10:21:55 -08005319 rtcp_dtls_transport, signaling_thread(), mid, SrtpRequired(),
5320 video_options_);
Steve Anton75737c02017-11-06 10:37:17 -08005321
5322 if (!video_channel) {
5323 transport_controller_->DestroyDtlsTransport(
5324 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5325 if (rtcp_dtls_transport) {
5326 transport_controller_->DestroyDtlsTransport(
5327 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
5328 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005329 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08005330 }
Steve Anton75737c02017-11-06 10:37:17 -08005331 video_channel->SignalRtcpMuxFullyActive.connect(
5332 this, &PeerConnection::DestroyRtcpTransport_n);
5333 video_channel->SignalDtlsSrtpSetupFailure.connect(
5334 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08005335 video_channel->SignalSentPacket.connect(this,
5336 &PeerConnection::OnSentPacket_w);
Steve Anton4171afb2017-11-20 10:20:22 -08005337
Steve Antoneda6ccd2017-12-04 10:21:55 -08005338 return video_channel;
Steve Anton75737c02017-11-06 10:37:17 -08005339}
5340
Steve Antoneda6ccd2017-12-04 10:21:55 -08005341bool PeerConnection::CreateDataChannel(const std::string& mid,
5342 const std::string& transport_name) {
Steve Anton75737c02017-11-06 10:37:17 -08005343 bool sctp = (data_channel_type_ == cricket::DCT_SCTP);
5344 if (sctp) {
5345 if (!sctp_factory_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005346 RTC_LOG(LS_ERROR)
Steve Anton75737c02017-11-06 10:37:17 -08005347 << "Trying to create SCTP transport, but didn't compile with "
5348 "SCTP support (HAVE_SCTP)";
5349 return false;
5350 }
5351 if (!network_thread()->Invoke<bool>(
5352 RTC_FROM_HERE, rtc::Bind(&PeerConnection::CreateSctpTransport_n,
Steve Antoneda6ccd2017-12-04 10:21:55 -08005353 this, mid, transport_name))) {
Steve Anton75737c02017-11-06 10:37:17 -08005354 return false;
5355 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005356 for (const auto& channel : sctp_data_channels_) {
5357 channel->OnTransportChannelCreated();
5358 }
Steve Anton75737c02017-11-06 10:37:17 -08005359 } else {
Steve Anton75737c02017-11-06 10:37:17 -08005360 cricket::DtlsTransportInternal* rtp_dtls_transport =
5361 transport_controller_->CreateDtlsTransport(
5362 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5363 cricket::DtlsTransportInternal* rtcp_dtls_transport = nullptr;
5364 if (configuration_.rtcp_mux_policy !=
5365 PeerConnectionInterface::kRtcpMuxPolicyRequire) {
5366 rtcp_dtls_transport = transport_controller_->CreateDtlsTransport(
5367 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
5368 }
5369
5370 rtp_data_channel_ = channel_manager()->CreateRtpDataChannel(
5371 configuration_.media_config, rtp_dtls_transport, rtcp_dtls_transport,
Steve Antoneda6ccd2017-12-04 10:21:55 -08005372 signaling_thread(), mid, SrtpRequired());
Steve Anton75737c02017-11-06 10:37:17 -08005373
5374 if (!rtp_data_channel_) {
5375 transport_controller_->DestroyDtlsTransport(
5376 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5377 if (rtcp_dtls_transport) {
5378 transport_controller_->DestroyDtlsTransport(
5379 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
5380 }
5381 return false;
5382 }
5383
5384 rtp_data_channel_->SignalRtcpMuxFullyActive.connect(
5385 this, &PeerConnection::DestroyRtcpTransport_n);
5386 rtp_data_channel_->SignalDtlsSrtpSetupFailure.connect(
5387 this, &PeerConnection::OnDtlsSrtpSetupFailure);
5388 rtp_data_channel_->SignalSentPacket.connect(
5389 this, &PeerConnection::OnSentPacket_w);
5390 }
5391
Steve Anton75737c02017-11-06 10:37:17 -08005392 return true;
5393}
5394
5395Call::Stats PeerConnection::GetCallStats() {
5396 if (!worker_thread()->IsCurrent()) {
5397 return worker_thread()->Invoke<Call::Stats>(
5398 RTC_FROM_HERE, rtc::Bind(&PeerConnection::GetCallStats, this));
5399 }
5400 if (call_) {
5401 return call_->GetStats();
5402 } else {
5403 return Call::Stats();
5404 }
5405}
5406
Steve Anton75737c02017-11-06 10:37:17 -08005407bool PeerConnection::CreateSctpTransport_n(const std::string& content_name,
5408 const std::string& transport_name) {
5409 RTC_DCHECK(network_thread()->IsCurrent());
5410 RTC_DCHECK(sctp_factory_);
5411 cricket::DtlsTransportInternal* tc =
5412 transport_controller_->CreateDtlsTransport_n(
5413 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5414 sctp_transport_ = sctp_factory_->CreateSctpTransport(tc);
5415 RTC_DCHECK(sctp_transport_);
5416 sctp_invoker_.reset(new rtc::AsyncInvoker());
5417 sctp_transport_->SignalReadyToSendData.connect(
5418 this, &PeerConnection::OnSctpTransportReadyToSendData_n);
5419 sctp_transport_->SignalDataReceived.connect(
5420 this, &PeerConnection::OnSctpTransportDataReceived_n);
5421 sctp_transport_->SignalStreamClosedRemotely.connect(
5422 this, &PeerConnection::OnSctpStreamClosedRemotely_n);
Oskar Sundbom9b28a032017-11-16 10:53:30 +01005423 sctp_transport_name_ = transport_name;
5424 sctp_content_name_ = content_name;
Steve Anton75737c02017-11-06 10:37:17 -08005425 return true;
5426}
5427
5428void PeerConnection::ChangeSctpTransport_n(const std::string& transport_name) {
5429 RTC_DCHECK(network_thread()->IsCurrent());
5430 RTC_DCHECK(sctp_transport_);
5431 RTC_DCHECK(sctp_transport_name_);
5432 std::string old_sctp_transport_name = *sctp_transport_name_;
Oskar Sundbom9b28a032017-11-16 10:53:30 +01005433 sctp_transport_name_ = transport_name;
Steve Anton75737c02017-11-06 10:37:17 -08005434 cricket::DtlsTransportInternal* tc =
5435 transport_controller_->CreateDtlsTransport_n(
5436 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5437 sctp_transport_->SetTransportChannel(tc);
5438 transport_controller_->DestroyDtlsTransport_n(
5439 old_sctp_transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5440}
5441
5442void PeerConnection::DestroySctpTransport_n() {
5443 RTC_DCHECK(network_thread()->IsCurrent());
5444 sctp_transport_.reset(nullptr);
Taylor Brandstetter389a97c2018-01-03 16:26:06 -08005445 transport_controller_->DestroyDtlsTransport_n(
5446 *sctp_transport_name_, cricket::ICE_CANDIDATE_COMPONENT_RTP);
Steve Anton75737c02017-11-06 10:37:17 -08005447 sctp_content_name_.reset();
5448 sctp_transport_name_.reset();
5449 sctp_invoker_.reset(nullptr);
5450 sctp_ready_to_send_data_ = false;
5451}
5452
5453void PeerConnection::OnSctpTransportReadyToSendData_n() {
5454 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5455 RTC_DCHECK(network_thread()->IsCurrent());
5456 // Note: Cannot use rtc::Bind here because it will grab a reference to
5457 // PeerConnection and potentially cause PeerConnection to live longer than
5458 // expected. It is safe not to grab a reference since the sctp_invoker_ will
5459 // be destroyed before PeerConnection is destroyed, and at that point all
5460 // pending tasks will be cleared.
5461 sctp_invoker_->AsyncInvoke<void>(RTC_FROM_HERE, signaling_thread(), [this] {
5462 OnSctpTransportReadyToSendData_s(true);
5463 });
5464}
5465
5466void PeerConnection::OnSctpTransportReadyToSendData_s(bool ready) {
5467 RTC_DCHECK(signaling_thread()->IsCurrent());
5468 sctp_ready_to_send_data_ = ready;
5469 SignalSctpReadyToSendData(ready);
5470}
5471
5472void PeerConnection::OnSctpTransportDataReceived_n(
5473 const cricket::ReceiveDataParams& params,
5474 const rtc::CopyOnWriteBuffer& payload) {
5475 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5476 RTC_DCHECK(network_thread()->IsCurrent());
5477 // Note: Cannot use rtc::Bind here because it will grab a reference to
5478 // PeerConnection and potentially cause PeerConnection to live longer than
5479 // expected. It is safe not to grab a reference since the sctp_invoker_ will
5480 // be destroyed before PeerConnection is destroyed, and at that point all
5481 // pending tasks will be cleared.
5482 sctp_invoker_->AsyncInvoke<void>(
5483 RTC_FROM_HERE, signaling_thread(), [this, params, payload] {
5484 OnSctpTransportDataReceived_s(params, payload);
5485 });
5486}
5487
5488void PeerConnection::OnSctpTransportDataReceived_s(
5489 const cricket::ReceiveDataParams& params,
5490 const rtc::CopyOnWriteBuffer& payload) {
5491 RTC_DCHECK(signaling_thread()->IsCurrent());
5492 if (params.type == cricket::DMT_CONTROL && IsOpenMessage(payload)) {
5493 // Received OPEN message; parse and signal that a new data channel should
5494 // be created.
5495 std::string label;
5496 InternalDataChannelInit config;
5497 config.id = params.ssrc;
5498 if (!ParseDataChannelOpenMessage(payload, &label, &config)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005499 RTC_LOG(LS_WARNING) << "Failed to parse the OPEN message for sid "
5500 << params.ssrc;
Steve Anton75737c02017-11-06 10:37:17 -08005501 return;
5502 }
5503 config.open_handshake_role = InternalDataChannelInit::kAcker;
5504 OnDataChannelOpenMessage(label, config);
5505 } else {
5506 // Otherwise just forward the signal.
5507 SignalSctpDataReceived(params, payload);
5508 }
5509}
5510
5511void PeerConnection::OnSctpStreamClosedRemotely_n(int sid) {
5512 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5513 RTC_DCHECK(network_thread()->IsCurrent());
5514 sctp_invoker_->AsyncInvoke<void>(
5515 RTC_FROM_HERE, signaling_thread(),
5516 rtc::Bind(&sigslot::signal1<int>::operator(),
5517 &SignalSctpStreamClosedRemotely, sid));
5518}
5519
5520// Returns false if bundle is enabled and rtcp_mux is disabled.
5521bool PeerConnection::ValidateBundleSettings(const SessionDescription* desc) {
5522 bool bundle_enabled = desc->HasGroup(cricket::GROUP_TYPE_BUNDLE);
5523 if (!bundle_enabled)
5524 return true;
5525
5526 const cricket::ContentGroup* bundle_group =
5527 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
5528 RTC_DCHECK(bundle_group != NULL);
5529
5530 const cricket::ContentInfos& contents = desc->contents();
5531 for (cricket::ContentInfos::const_iterator citer = contents.begin();
5532 citer != contents.end(); ++citer) {
5533 const cricket::ContentInfo* content = (&*citer);
5534 RTC_DCHECK(content != NULL);
5535 if (bundle_group->HasContentName(content->name) && !content->rejected &&
Steve Anton5adfafd2017-12-20 16:34:00 -08005536 content->type == MediaProtocolType::kRtp) {
Steve Anton75737c02017-11-06 10:37:17 -08005537 if (!HasRtcpMuxEnabled(content))
5538 return false;
5539 }
5540 }
5541 // RTCP-MUX is enabled in all the contents.
5542 return true;
5543}
5544
5545bool PeerConnection::HasRtcpMuxEnabled(const cricket::ContentInfo* content) {
Steve Antonb1c1de12017-12-21 15:14:30 -08005546 return content->media_description()->rtcp_mux();
Steve Anton75737c02017-11-06 10:37:17 -08005547}
5548
Steve Anton8a006912017-12-04 15:25:56 -08005549RTCError PeerConnection::ValidateSessionDescription(
Steve Anton75737c02017-11-06 10:37:17 -08005550 const SessionDescriptionInterface* sdesc,
Steve Anton8a006912017-12-04 15:25:56 -08005551 cricket::ContentSource source) {
Steve Antonf8470812017-12-04 10:46:21 -08005552 if (session_error() != SessionError::kNone) {
Steve Anton8a006912017-12-04 15:25:56 -08005553 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
Steve Anton75737c02017-11-06 10:37:17 -08005554 }
5555
5556 if (!sdesc || !sdesc->description()) {
Steve Anton8a006912017-12-04 15:25:56 -08005557 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidSdp);
Steve Anton75737c02017-11-06 10:37:17 -08005558 }
5559
Steve Anton3828c062017-12-06 10:34:51 -08005560 SdpType type = sdesc->GetType();
5561 if ((source == cricket::CS_LOCAL && !ExpectSetLocalDescription(type)) ||
5562 (source == cricket::CS_REMOTE && !ExpectSetRemoteDescription(type))) {
Steve Anton8a006912017-12-04 15:25:56 -08005563 LOG_AND_RETURN_ERROR(
5564 RTCErrorType::INVALID_PARAMETER,
5565 "Called in wrong state: " + GetSignalingStateString(signaling_state()));
Steve Anton75737c02017-11-06 10:37:17 -08005566 }
5567
5568 // Verify crypto settings.
5569 std::string crypto_error;
Steve Anton8a006912017-12-04 15:25:56 -08005570 if (webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED ||
5571 dtls_enabled_) {
Harald Alvestrand194939b2018-01-24 16:04:13 +01005572 RTCError crypto_error =
5573 VerifyCrypto(sdesc->description(), dtls_enabled_, uma_observer_);
Steve Anton8a006912017-12-04 15:25:56 -08005574 if (!crypto_error.ok()) {
5575 return crypto_error;
5576 }
Steve Anton75737c02017-11-06 10:37:17 -08005577 }
5578
5579 // Verify ice-ufrag and ice-pwd.
5580 if (!VerifyIceUfragPwdPresent(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08005581 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5582 kSdpWithoutIceUfragPwd);
Steve Anton75737c02017-11-06 10:37:17 -08005583 }
5584
5585 if (!ValidateBundleSettings(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08005586 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5587 kBundleWithoutRtcpMux);
Steve Anton75737c02017-11-06 10:37:17 -08005588 }
5589
5590 // TODO(skvlad): When the local rtcp-mux policy is Require, reject any
5591 // m-lines that do not rtcp-mux enabled.
5592
5593 // Verify m-lines in Answer when compared against Offer.
Steve Anton3828c062017-12-06 10:34:51 -08005594 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Seth Hampsonae8a90a2018-02-13 15:33:48 -08005595 // With an answer we want to compare the new answer session description with
5596 // the offer's session description from the current negotiation.
Steve Anton75737c02017-11-06 10:37:17 -08005597 const cricket::SessionDescription* offer_desc =
5598 (source == cricket::CS_LOCAL) ? remote_description()->description()
5599 : local_description()->description();
Seth Hampsonae8a90a2018-02-13 15:33:48 -08005600 if (!MediaSectionsHaveSameCount(*offer_desc, *sdesc->description()) ||
5601 !MediaSectionsInSameOrder(*offer_desc, nullptr, *sdesc->description(),
5602 type)) {
Steve Anton8a006912017-12-04 15:25:56 -08005603 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5604 kMlineMismatchInAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08005605 }
5606 } else {
Steve Anton75737c02017-11-06 10:37:17 -08005607 // The re-offers should respect the order of m= sections in current
5608 // description. See RFC3264 Section 8 paragraph 4 for more details.
Seth Hampsonae8a90a2018-02-13 15:33:48 -08005609 // With a re-offer, either the current local or current remote descriptions
5610 // could be the most up to date, so we would like to check against both of
5611 // them if they exist. It could be the case that one of them has a 0 port
5612 // for a media section, but the other does not. This is important to check
5613 // against in the case that we are recycling an m= section.
5614 const cricket::SessionDescription* current_desc = nullptr;
5615 const cricket::SessionDescription* secondary_current_desc = nullptr;
5616 if (local_description()) {
5617 current_desc = local_description()->description();
5618 if (remote_description()) {
5619 secondary_current_desc = remote_description()->description();
5620 }
5621 } else if (remote_description()) {
5622 current_desc = remote_description()->description();
5623 }
Steve Anton75737c02017-11-06 10:37:17 -08005624 if (current_desc &&
Seth Hampsonae8a90a2018-02-13 15:33:48 -08005625 !MediaSectionsInSameOrder(*current_desc, secondary_current_desc,
5626 *sdesc->description(), type)) {
Steve Anton8a006912017-12-04 15:25:56 -08005627 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5628 kMlineMismatchInSubsequentOffer);
Steve Anton75737c02017-11-06 10:37:17 -08005629 }
5630 }
5631
Steve Anton8a006912017-12-04 15:25:56 -08005632 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08005633}
5634
Steve Anton3828c062017-12-06 10:34:51 -08005635bool PeerConnection::ExpectSetLocalDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08005636 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08005637 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08005638 return (state == PeerConnectionInterface::kStable) ||
5639 (state == PeerConnectionInterface::kHaveLocalOffer);
Steve Anton20393062017-12-04 16:24:52 -08005640 } else {
Steve Anton3828c062017-12-06 10:34:51 -08005641 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08005642 return (state == PeerConnectionInterface::kHaveRemoteOffer) ||
5643 (state == PeerConnectionInterface::kHaveLocalPrAnswer);
5644 }
5645}
5646
Steve Anton3828c062017-12-06 10:34:51 -08005647bool PeerConnection::ExpectSetRemoteDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08005648 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08005649 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08005650 return (state == PeerConnectionInterface::kStable) ||
5651 (state == PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton20393062017-12-04 16:24:52 -08005652 } else {
Steve Anton3828c062017-12-06 10:34:51 -08005653 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08005654 return (state == PeerConnectionInterface::kHaveLocalOffer) ||
5655 (state == PeerConnectionInterface::kHaveRemotePrAnswer);
5656 }
5657}
5658
Steve Antonf8470812017-12-04 10:46:21 -08005659const char* PeerConnection::SessionErrorToString(SessionError error) const {
5660 switch (error) {
5661 case SessionError::kNone:
5662 return "ERROR_NONE";
5663 case SessionError::kContent:
5664 return "ERROR_CONTENT";
5665 case SessionError::kTransport:
5666 return "ERROR_TRANSPORT";
5667 }
5668 RTC_NOTREACHED();
5669 return "";
5670}
5671
Steve Anton75737c02017-11-06 10:37:17 -08005672std::string PeerConnection::GetSessionErrorMsg() {
5673 std::ostringstream desc;
Steve Antonf8470812017-12-04 10:46:21 -08005674 desc << kSessionError << SessionErrorToString(session_error()) << ". ";
5675 desc << kSessionErrorDesc << session_error_desc() << ".";
Steve Anton75737c02017-11-06 10:37:17 -08005676 return desc.str();
5677}
5678
5679// We need to check the local/remote description for the Transport instead of
5680// the session, because a new Transport added during renegotiation may have
5681// them unset while the session has them set from the previous negotiation.
5682// Not doing so may trigger the auto generation of transport description and
5683// mess up DTLS identity information, ICE credential, etc.
5684bool PeerConnection::ReadyToUseRemoteCandidate(
5685 const IceCandidateInterface* candidate,
5686 const SessionDescriptionInterface* remote_desc,
5687 bool* valid) {
5688 *valid = true;
5689
5690 const SessionDescriptionInterface* current_remote_desc =
5691 remote_desc ? remote_desc : remote_description();
5692
5693 if (!current_remote_desc) {
5694 return false;
5695 }
5696
5697 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
5698 size_t remote_content_size =
5699 current_remote_desc->description()->contents().size();
5700 if (mediacontent_index >= remote_content_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005701 RTC_LOG(LS_ERROR)
5702 << "ReadyToUseRemoteCandidate: Invalid candidate media index "
5703 << mediacontent_index;
Steve Anton75737c02017-11-06 10:37:17 -08005704
5705 *valid = false;
5706 return false;
5707 }
5708
5709 cricket::ContentInfo content =
5710 current_remote_desc->description()->contents()[mediacontent_index];
5711
5712 const std::string transport_name = GetTransportName(content.name);
5713 if (transport_name.empty()) {
5714 return false;
5715 }
5716 return transport_controller_->ReadyForRemoteCandidates(transport_name);
5717}
5718
5719bool PeerConnection::SrtpRequired() const {
5720 return dtls_enabled_ ||
5721 webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED;
5722}
5723
5724void PeerConnection::OnTransportControllerGatheringState(
5725 cricket::IceGatheringState state) {
5726 RTC_DCHECK(signaling_thread()->IsCurrent());
5727 if (state == cricket::kIceGatheringGathering) {
5728 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringGathering);
5729 } else if (state == cricket::kIceGatheringComplete) {
5730 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringComplete);
5731 }
5732}
5733
5734void PeerConnection::ReportTransportStats() {
Steve Antonc7b964c2018-02-01 14:39:45 -08005735 std::map<std::string, std::set<cricket::MediaType>>
5736 media_types_by_transport_name;
5737 for (auto transceiver : transceivers_) {
5738 if (transceiver->internal()->channel()) {
5739 const std::string& transport_name =
5740 transceiver->internal()->channel()->transport_name();
5741 media_types_by_transport_name[transport_name].insert(
Steve Anton69470252018-02-09 11:43:08 -08005742 transceiver->media_type());
Steve Antonc7b964c2018-02-01 14:39:45 -08005743 }
Steve Anton75737c02017-11-06 10:37:17 -08005744 }
5745 if (rtp_data_channel()) {
Steve Antonc7b964c2018-02-01 14:39:45 -08005746 media_types_by_transport_name[rtp_data_channel()->transport_name()].insert(
5747 cricket::MEDIA_TYPE_DATA);
Steve Anton75737c02017-11-06 10:37:17 -08005748 }
5749 if (sctp_transport_name_) {
Steve Antonc7b964c2018-02-01 14:39:45 -08005750 media_types_by_transport_name[*sctp_transport_name_].insert(
5751 cricket::MEDIA_TYPE_DATA);
Steve Anton75737c02017-11-06 10:37:17 -08005752 }
Steve Antonc7b964c2018-02-01 14:39:45 -08005753 for (const auto& entry : media_types_by_transport_name) {
5754 const std::string& transport_name = entry.first;
5755 const std::set<cricket::MediaType> media_types = entry.second;
Steve Anton75737c02017-11-06 10:37:17 -08005756 cricket::TransportStats stats;
Steve Antonc7b964c2018-02-01 14:39:45 -08005757 if (transport_controller_->GetStats(transport_name, &stats)) {
Steve Anton75737c02017-11-06 10:37:17 -08005758 ReportBestConnectionState(stats);
Steve Antonc7b964c2018-02-01 14:39:45 -08005759 ReportNegotiatedCiphers(stats, media_types);
Steve Anton75737c02017-11-06 10:37:17 -08005760 }
5761 }
5762}
5763// Walk through the ConnectionInfos to gather best connection usage
5764// for IPv4 and IPv6.
5765void PeerConnection::ReportBestConnectionState(
5766 const cricket::TransportStats& stats) {
5767 RTC_DCHECK(metrics_observer());
Steve Antonc7b964c2018-02-01 14:39:45 -08005768 for (const cricket::TransportChannelStats& channel_stats :
5769 stats.channel_stats) {
5770 for (const cricket::ConnectionInfo& connection_info :
5771 channel_stats.connection_infos) {
5772 if (!connection_info.best_connection) {
Steve Anton75737c02017-11-06 10:37:17 -08005773 continue;
5774 }
5775
5776 PeerConnectionEnumCounterType type = kPeerConnectionEnumCounterMax;
Steve Antonc7b964c2018-02-01 14:39:45 -08005777 const cricket::Candidate& local = connection_info.local_candidate;
5778 const cricket::Candidate& remote = connection_info.remote_candidate;
Steve Anton75737c02017-11-06 10:37:17 -08005779
5780 // Increment the counter for IceCandidatePairType.
5781 if (local.protocol() == cricket::TCP_PROTOCOL_NAME ||
5782 (local.type() == RELAY_PORT_TYPE &&
5783 local.relay_protocol() == cricket::TCP_PROTOCOL_NAME)) {
5784 type = kEnumCounterIceCandidatePairTypeTcp;
5785 } else if (local.protocol() == cricket::UDP_PROTOCOL_NAME) {
5786 type = kEnumCounterIceCandidatePairTypeUdp;
5787 } else {
5788 RTC_CHECK(0);
5789 }
5790 metrics_observer()->IncrementEnumCounter(
5791 type, GetIceCandidatePairCounter(local, remote),
5792 kIceCandidatePairMax);
5793
5794 // Increment the counter for IP type.
5795 if (local.address().family() == AF_INET) {
5796 metrics_observer()->IncrementEnumCounter(
5797 kEnumCounterAddressFamily, kBestConnections_IPv4,
5798 kPeerConnectionAddressFamilyCounter_Max);
5799
5800 } else if (local.address().family() == AF_INET6) {
5801 metrics_observer()->IncrementEnumCounter(
5802 kEnumCounterAddressFamily, kBestConnections_IPv6,
5803 kPeerConnectionAddressFamilyCounter_Max);
5804 } else {
5805 RTC_CHECK(0);
5806 }
5807
5808 return;
5809 }
5810 }
5811}
5812
5813void PeerConnection::ReportNegotiatedCiphers(
Steve Antonc7b964c2018-02-01 14:39:45 -08005814 const cricket::TransportStats& stats,
5815 const std::set<cricket::MediaType>& media_types) {
Steve Anton75737c02017-11-06 10:37:17 -08005816 RTC_DCHECK(metrics_observer());
5817 if (!dtls_enabled_ || stats.channel_stats.empty()) {
5818 return;
5819 }
5820
5821 int srtp_crypto_suite = stats.channel_stats[0].srtp_crypto_suite;
5822 int ssl_cipher_suite = stats.channel_stats[0].ssl_cipher_suite;
5823 if (srtp_crypto_suite == rtc::SRTP_INVALID_CRYPTO_SUITE &&
5824 ssl_cipher_suite == rtc::TLS_NULL_WITH_NULL_NULL) {
5825 return;
5826 }
5827
Steve Antonc7b964c2018-02-01 14:39:45 -08005828 for (cricket::MediaType media_type : media_types) {
5829 PeerConnectionEnumCounterType srtp_counter_type;
5830 PeerConnectionEnumCounterType ssl_counter_type;
5831 switch (media_type) {
5832 case cricket::MEDIA_TYPE_AUDIO:
5833 srtp_counter_type = kEnumCounterAudioSrtpCipher;
5834 ssl_counter_type = kEnumCounterAudioSslCipher;
5835 break;
5836 case cricket::MEDIA_TYPE_VIDEO:
5837 srtp_counter_type = kEnumCounterVideoSrtpCipher;
5838 ssl_counter_type = kEnumCounterVideoSslCipher;
5839 break;
5840 case cricket::MEDIA_TYPE_DATA:
5841 srtp_counter_type = kEnumCounterDataSrtpCipher;
5842 ssl_counter_type = kEnumCounterDataSslCipher;
5843 break;
5844 default:
5845 RTC_NOTREACHED();
5846 continue;
5847 }
5848 if (srtp_crypto_suite != rtc::SRTP_INVALID_CRYPTO_SUITE) {
5849 metrics_observer()->IncrementSparseEnumCounter(srtp_counter_type,
5850 srtp_crypto_suite);
5851 }
5852 if (ssl_cipher_suite != rtc::TLS_NULL_WITH_NULL_NULL) {
5853 metrics_observer()->IncrementSparseEnumCounter(ssl_counter_type,
5854 ssl_cipher_suite);
5855 }
Steve Anton75737c02017-11-06 10:37:17 -08005856 }
5857}
5858
5859void PeerConnection::OnSentPacket_w(const rtc::SentPacket& sent_packet) {
5860 RTC_DCHECK(worker_thread()->IsCurrent());
5861 RTC_DCHECK(call_);
5862 call_->OnSentPacket(sent_packet);
5863}
5864
5865const std::string PeerConnection::GetTransportName(
5866 const std::string& content_name) {
5867 cricket::BaseChannel* channel = GetChannel(content_name);
Steve Anton6fec8802017-12-04 10:37:29 -08005868 if (channel) {
5869 return channel->transport_name();
Steve Anton75737c02017-11-06 10:37:17 -08005870 }
Steve Anton6fec8802017-12-04 10:37:29 -08005871 if (sctp_transport_) {
5872 RTC_DCHECK(sctp_content_name_);
5873 RTC_DCHECK(sctp_transport_name_);
5874 if (content_name == *sctp_content_name_) {
5875 return *sctp_transport_name_;
5876 }
5877 }
5878 // Return an empty string if failed to retrieve the transport name.
5879 return "";
Steve Anton75737c02017-11-06 10:37:17 -08005880}
5881
5882void PeerConnection::DestroyRtcpTransport_n(const std::string& transport_name) {
5883 RTC_DCHECK(network_thread()->IsCurrent());
5884 transport_controller_->DestroyDtlsTransport_n(
5885 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
5886}
5887
Steve Anton6fec8802017-12-04 10:37:29 -08005888void PeerConnection::DestroyTransceiverChannel(
5889 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
5890 transceiver) {
5891 RTC_DCHECK(transceiver);
Steve Anton75737c02017-11-06 10:37:17 -08005892
Steve Anton6fec8802017-12-04 10:37:29 -08005893 cricket::BaseChannel* channel = transceiver->internal()->channel();
5894 if (channel) {
5895 transceiver->internal()->SetChannel(nullptr);
5896 DestroyBaseChannel(channel);
Steve Anton75737c02017-11-06 10:37:17 -08005897 }
5898}
5899
5900void PeerConnection::DestroyDataChannel() {
Steve Anton6fec8802017-12-04 10:37:29 -08005901 if (rtp_data_channel_) {
5902 OnDataChannelDestroyed();
5903 DestroyBaseChannel(rtp_data_channel_);
5904 rtp_data_channel_ = nullptr;
5905 }
5906
5907 // Note: Cannot use rtc::Bind to create a functor to invoke because it will
5908 // grab a reference to this PeerConnection. If this is called from the
5909 // PeerConnection destructor, the RefCountedObject vtable will have already
5910 // been destroyed (since it is a subclass of PeerConnection) and using
5911 // rtc::Bind will cause "Pure virtual function called" error to appear.
5912
5913 if (sctp_transport_) {
5914 OnDataChannelDestroyed();
5915 network_thread()->Invoke<void>(RTC_FROM_HERE,
5916 [this] { DestroySctpTransport_n(); });
5917 }
5918}
5919
5920void PeerConnection::DestroyBaseChannel(cricket::BaseChannel* channel) {
5921 RTC_DCHECK(channel);
5922 RTC_DCHECK(channel->rtp_dtls_transport());
5923
5924 // Need to cache these before destroying the base channel so that we do not
5925 // access uninitialized memory.
5926 const std::string transport_name =
5927 channel->rtp_dtls_transport()->transport_name();
5928 const bool need_to_delete_rtcp = (channel->rtcp_dtls_transport() != nullptr);
5929
5930 switch (channel->media_type()) {
5931 case cricket::MEDIA_TYPE_AUDIO:
5932 channel_manager()->DestroyVoiceChannel(
5933 static_cast<cricket::VoiceChannel*>(channel));
5934 break;
5935 case cricket::MEDIA_TYPE_VIDEO:
5936 channel_manager()->DestroyVideoChannel(
5937 static_cast<cricket::VideoChannel*>(channel));
5938 break;
5939 case cricket::MEDIA_TYPE_DATA:
5940 channel_manager()->DestroyRtpDataChannel(
5941 static_cast<cricket::RtpDataChannel*>(channel));
5942 break;
5943 default:
5944 RTC_NOTREACHED() << "Unknown media type: " << channel->media_type();
5945 break;
5946 }
5947
5948 // |channel| can no longer be used.
5949
Steve Anton75737c02017-11-06 10:37:17 -08005950 transport_controller_->DestroyDtlsTransport(
5951 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5952 if (need_to_delete_rtcp) {
5953 transport_controller_->DestroyDtlsTransport(
5954 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
5955 }
5956}
5957
Harald Alvestrand89061872018-01-02 14:08:34 +01005958void PeerConnection::ClearStatsCache() {
5959 if (stats_collector_) {
5960 stats_collector_->ClearCachedStatsReport();
5961 }
5962}
5963
henrike@webrtc.org28e20752013-07-10 00:45:36 +00005964} // namespace webrtc