blob: 0681acbb4abcfc88051335bb12296cb444fd64e1 [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;
Qingsi Wangdb53f8e2018-02-20 14:45:49 -0800639 rtc::Optional<int> stun_candidate_keepalive_interval;
Steve Anton300bf8e2017-07-14 10:13:10 -0700640 rtc::Optional<rtc::IntervalRange> ice_regather_interval_range;
Jonas Orelandbdcee282017-10-10 14:01:40 +0200641 webrtc::TurnCustomizer* turn_customizer;
Steve Anton79e79602017-11-20 10:25:56 -0800642 SdpSemantics sdp_semantics;
Qingsi Wang9a5c6f82018-02-01 10:38:40 -0800643 rtc::Optional<rtc::AdapterType> network_preference;
deadbeef293e9262017-01-11 12:28:30 -0800644 };
645 static_assert(sizeof(stuff_being_tested_for_equality) == sizeof(*this),
646 "Did you add something to RTCConfiguration and forget to "
647 "update operator==?");
648 return type == o.type && servers == o.servers &&
649 bundle_policy == o.bundle_policy &&
650 rtcp_mux_policy == o.rtcp_mux_policy &&
651 tcp_candidate_policy == o.tcp_candidate_policy &&
652 candidate_network_policy == o.candidate_network_policy &&
653 audio_jitter_buffer_max_packets == o.audio_jitter_buffer_max_packets &&
654 audio_jitter_buffer_fast_accelerate ==
655 o.audio_jitter_buffer_fast_accelerate &&
656 ice_connection_receiving_timeout ==
657 o.ice_connection_receiving_timeout &&
658 ice_backup_candidate_pair_ping_interval ==
659 o.ice_backup_candidate_pair_ping_interval &&
660 continual_gathering_policy == o.continual_gathering_policy &&
661 certificates == o.certificates &&
662 prioritize_most_likely_ice_candidate_pairs ==
663 o.prioritize_most_likely_ice_candidate_pairs &&
664 media_config == o.media_config && disable_ipv6 == o.disable_ipv6 &&
zhihuangb09b3f92017-03-07 14:40:51 -0800665 disable_ipv6_on_wifi == o.disable_ipv6_on_wifi &&
deadbeefd21eab32017-07-26 16:50:11 -0700666 max_ipv6_networks == o.max_ipv6_networks &&
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +0100667 disable_link_local_networks == o.disable_link_local_networks &&
deadbeef293e9262017-01-11 12:28:30 -0800668 enable_rtp_data_channel == o.enable_rtp_data_channel &&
deadbeef293e9262017-01-11 12:28:30 -0800669 screencast_min_bitrate == o.screencast_min_bitrate &&
670 combined_audio_video_bwe == o.combined_audio_video_bwe &&
671 enable_dtls_srtp == o.enable_dtls_srtp &&
672 ice_candidate_pool_size == o.ice_candidate_pool_size &&
673 prune_turn_ports == o.prune_turn_ports &&
674 presume_writable_when_fully_relayed ==
675 o.presume_writable_when_fully_relayed &&
676 enable_ice_renomination == o.enable_ice_renomination &&
skvlad51072462017-02-02 11:50:14 -0800677 redetermine_role_on_ice_restart == o.redetermine_role_on_ice_restart &&
Steve Anton300bf8e2017-07-14 10:13:10 -0700678 ice_check_min_interval == o.ice_check_min_interval &&
Qingsi Wangdb53f8e2018-02-20 14:45:49 -0800679 stun_candidate_keepalive_interval ==
680 o.stun_candidate_keepalive_interval &&
Jonas Orelandbdcee282017-10-10 14:01:40 +0200681 ice_regather_interval_range == o.ice_regather_interval_range &&
Steve Anton79e79602017-11-20 10:25:56 -0800682 turn_customizer == o.turn_customizer &&
Qingsi Wang9a5c6f82018-02-01 10:38:40 -0800683 sdp_semantics == o.sdp_semantics &&
684 network_preference == o.network_preference;
deadbeef293e9262017-01-11 12:28:30 -0800685}
686
687bool PeerConnectionInterface::RTCConfiguration::operator!=(
688 const PeerConnectionInterface::RTCConfiguration& o) const {
689 return !(*this == o);
deadbeef3edec7c2016-12-10 11:44:26 -0800690}
691
zhihuang8f65cdf2016-05-06 18:40:30 -0700692// Generate a RTCP CNAME when a PeerConnection is created.
693std::string GenerateRtcpCname() {
694 std::string cname;
695 if (!rtc::CreateRandomString(kRtcpCnameLength, &cname)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100696 RTC_LOG(LS_ERROR) << "Failed to generate CNAME.";
nisseeb4ca4e2017-01-12 02:24:27 -0800697 RTC_NOTREACHED();
zhihuang8f65cdf2016-05-06 18:40:30 -0700698 }
699 return cname;
700}
701
zhihuang1c378ed2017-08-17 14:10:50 -0700702bool ValidateOfferAnswerOptions(
703 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options) {
704 return IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_audio) &&
705 IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_video);
olka3c747662017-08-17 06:50:32 -0700706}
707
zhihuang1c378ed2017-08-17 14:10:50 -0700708// From |rtc_options|, fill parts of |session_options| shared by all generated
709// m= sections (in other words, nothing that involves a map/array).
710void ExtractSharedMediaSessionOptions(
711 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options,
712 cricket::MediaSessionOptions* session_options) {
713 session_options->vad_enabled = rtc_options.voice_activity_detection;
714 session_options->bundle_enabled = rtc_options.use_rtp_mux;
715}
zhihuanga77e6bb2017-08-14 18:17:48 -0700716
zhihuang1c378ed2017-08-17 14:10:50 -0700717bool ConvertConstraintsToOfferAnswerOptions(
718 const MediaConstraintsInterface* constraints,
719 PeerConnectionInterface::RTCOfferAnswerOptions* offer_answer_options) {
olka3c747662017-08-17 06:50:32 -0700720 if (!constraints) {
721 return true;
722 }
zhihuang1c378ed2017-08-17 14:10:50 -0700723
724 bool value = false;
725 size_t mandatory_constraints_satisfied = 0;
726
727 if (FindConstraint(constraints,
728 MediaConstraintsInterface::kOfferToReceiveAudio, &value,
729 &mandatory_constraints_satisfied)) {
730 offer_answer_options->offer_to_receive_audio =
731 value ? PeerConnectionInterface::RTCOfferAnswerOptions::
732 kOfferToReceiveMediaTrue
733 : 0;
734 }
735
736 if (FindConstraint(constraints,
737 MediaConstraintsInterface::kOfferToReceiveVideo, &value,
738 &mandatory_constraints_satisfied)) {
739 offer_answer_options->offer_to_receive_video =
740 value ? PeerConnectionInterface::RTCOfferAnswerOptions::
741 kOfferToReceiveMediaTrue
742 : 0;
743 }
744 if (FindConstraint(constraints,
745 MediaConstraintsInterface::kVoiceActivityDetection, &value,
746 &mandatory_constraints_satisfied)) {
747 offer_answer_options->voice_activity_detection = value;
748 }
749 if (FindConstraint(constraints, MediaConstraintsInterface::kUseRtpMux, &value,
750 &mandatory_constraints_satisfied)) {
751 offer_answer_options->use_rtp_mux = value;
752 }
753 if (FindConstraint(constraints, MediaConstraintsInterface::kIceRestart,
754 &value, &mandatory_constraints_satisfied)) {
755 offer_answer_options->ice_restart = value;
756 }
757
deadbeefab9b2d12015-10-14 11:33:11 -0700758 return mandatory_constraints_satisfied == constraints->GetMandatory().size();
759}
760
zhihuang38ede132017-06-15 12:52:32 -0700761PeerConnection::PeerConnection(PeerConnectionFactory* factory,
762 std::unique_ptr<RtcEventLog> event_log,
763 std::unique_ptr<Call> call)
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000764 : factory_(factory),
zhihuang38ede132017-06-15 12:52:32 -0700765 event_log_(std::move(event_log)),
zhihuang8f65cdf2016-05-06 18:40:30 -0700766 rtcp_cname_(GenerateRtcpCname()),
deadbeefab9b2d12015-10-14 11:33:11 -0700767 local_streams_(StreamCollection::Create()),
zhihuang38ede132017-06-15 12:52:32 -0700768 remote_streams_(StreamCollection::Create()),
769 call_(std::move(call)) {}
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000770
771PeerConnection::~PeerConnection() {
Peter Boström1a9d6152015-12-08 22:15:17 +0100772 TRACE_EVENT0("webrtc", "PeerConnection::~PeerConnection");
Steve Anton4171afb2017-11-20 10:20:22 -0800773 RTC_DCHECK_RUN_ON(signaling_thread());
774
Steve Anton8af21862017-12-15 11:20:13 -0800775 // Need to stop transceivers before destroying the stats collector because
776 // AudioRtpSender has a reference to the StatsCollector it will update when
777 // stopping.
778 for (auto transceiver : transceivers_) {
779 transceiver->Stop();
780 }
Steve Anton4171afb2017-11-20 10:20:22 -0800781
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700782 stats_.reset(nullptr);
hbosb78306a2016-12-19 05:06:57 -0800783 if (stats_collector_) {
784 stats_collector_->WaitForPendingRequest();
785 stats_collector_ = nullptr;
786 }
Steve Anton75737c02017-11-06 10:37:17 -0800787
Steve Anton8af21862017-12-15 11:20:13 -0800788 // Don't destroy BaseChannels until after stats has been cleaned up so that
789 // the last stats request can still read from the channels.
790 DestroyAllChannels();
791
Mirko Bonadei675513b2017-11-09 11:09:25 +0100792 RTC_LOG(LS_INFO) << "Session: " << session_id() << " is destroyed.";
Steve Anton75737c02017-11-06 10:37:17 -0800793
794 webrtc_session_desc_factory_.reset();
795 sctp_invoker_.reset();
796 sctp_factory_.reset();
797 transport_controller_.reset();
798
deadbeef91dd5672016-05-18 16:55:30 -0700799 // port_allocator_ lives on the network thread and should be destroyed there.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700800 network_thread()->Invoke<void>(RTC_FROM_HERE,
nisseeaabdf62017-05-05 02:23:02 -0700801 [this] { port_allocator_.reset(); });
eladalon248fd4f2017-09-06 05:18:15 -0700802 // call_ and event_log_ must be destroyed on the worker thread.
Steve Anton978b8762017-09-29 12:15:02 -0700803 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
eladalon248fd4f2017-09-06 05:18:15 -0700804 call_.reset();
Qingsi Wang93a84392018-01-30 17:13:09 -0800805 // The event log must outlive call (and any other object that uses it).
eladalon248fd4f2017-09-06 05:18:15 -0700806 event_log_.reset();
807 });
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000808}
809
Steve Anton8af21862017-12-15 11:20:13 -0800810void PeerConnection::DestroyAllChannels() {
Steve Anton3fe1b152017-12-12 10:20:08 -0800811 // Destroy video channels first since they may have a pointer to a voice
812 // channel.
813 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -0800814 if (transceiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton3fe1b152017-12-12 10:20:08 -0800815 DestroyTransceiverChannel(transceiver);
816 }
817 }
818 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -0800819 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton3fe1b152017-12-12 10:20:08 -0800820 DestroyTransceiverChannel(transceiver);
821 }
822 }
823 DestroyDataChannel();
824}
825
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000826bool PeerConnection::Initialize(
buildbot@webrtc.org41451d42014-05-03 05:39:45 +0000827 const PeerConnectionInterface::RTCConfiguration& configuration,
kwibergd1fe2812016-04-27 06:47:29 -0700828 std::unique_ptr<cricket::PortAllocator> allocator,
Henrik Boströmd03c23b2016-06-01 11:44:18 +0200829 std::unique_ptr<rtc::RTCCertificateGeneratorInterface> cert_generator,
deadbeef653b8e02015-11-11 12:55:10 -0800830 PeerConnectionObserver* observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100831 TRACE_EVENT0("webrtc", "PeerConnection::Initialize");
Steve Anton038834f2017-07-14 15:59:59 -0700832
833 RTCError config_error = ValidateConfiguration(configuration);
834 if (!config_error.ok()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100835 RTC_LOG(LS_ERROR) << "Invalid configuration: " << config_error.message();
Steve Anton038834f2017-07-14 15:59:59 -0700836 return false;
837 }
838
deadbeef293e9262017-01-11 12:28:30 -0800839 if (!allocator) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100840 RTC_LOG(LS_ERROR)
841 << "PeerConnection initialized without a PortAllocator? "
Jonas Olsson45cc8902018-02-13 10:37:07 +0100842 "This shouldn't happen if using PeerConnectionFactory.";
deadbeef293e9262017-01-11 12:28:30 -0800843 return false;
844 }
Jonas Orelandbdcee282017-10-10 14:01:40 +0200845
deadbeef653b8e02015-11-11 12:55:10 -0800846 if (!observer) {
deadbeef293e9262017-01-11 12:28:30 -0800847 // TODO(deadbeef): Why do we do this?
Mirko Bonadei675513b2017-11-09 11:09:25 +0100848 RTC_LOG(LS_ERROR) << "PeerConnection initialized without a "
Jonas Olsson45cc8902018-02-13 10:37:07 +0100849 "PeerConnectionObserver";
deadbeef653b8e02015-11-11 12:55:10 -0800850 return false;
851 }
pthatcher@webrtc.org877ac762015-02-04 22:03:09 +0000852 observer_ = observer;
kwiberg0eb15ed2015-12-17 03:04:15 -0800853 port_allocator_ = std::move(allocator);
deadbeef653b8e02015-11-11 12:55:10 -0800854
deadbeef91dd5672016-05-18 16:55:30 -0700855 // The port allocator lives on the network thread and should be initialized
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700856 // there.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700857 if (!network_thread()->Invoke<bool>(
858 RTC_FROM_HERE, rtc::Bind(&PeerConnection::InitializePortAllocator_n,
859 this, configuration))) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000860 return false;
861 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000862
Steve Anton75737c02017-11-06 10:37:17 -0800863 // RFC 3264: The numeric value of the session id and version in the
864 // o line MUST be representable with a "64 bit signed integer".
865 // Due to this constraint session id |session_id_| is max limited to
866 // LLONG_MAX.
867 session_id_ = rtc::ToString(rtc::CreateRandomId64() & LLONG_MAX);
868 transport_controller_.reset(factory_->CreateTransportController(
Qingsi Wang93a84392018-01-30 17:13:09 -0800869 port_allocator_.get(), configuration.redetermine_role_on_ice_restart,
870 event_log_.get()));
Steve Anton75737c02017-11-06 10:37:17 -0800871 transport_controller_->SetIceRole(cricket::ICEROLE_CONTROLLED);
872 transport_controller_->SignalConnectionState.connect(
873 this, &PeerConnection::OnTransportControllerConnectionState);
874 transport_controller_->SignalGatheringState.connect(
875 this, &PeerConnection::OnTransportControllerGatheringState);
876 transport_controller_->SignalCandidatesGathered.connect(
877 this, &PeerConnection::OnTransportControllerCandidatesGathered);
878 transport_controller_->SignalCandidatesRemoved.connect(
879 this, &PeerConnection::OnTransportControllerCandidatesRemoved);
880 transport_controller_->SignalDtlsHandshakeError.connect(
881 this, &PeerConnection::OnTransportControllerDtlsHandshakeError);
882
883 sctp_factory_ = factory_->CreateSctpTransportInternalFactory();
zhihuang29ff8442016-07-27 11:07:25 -0700884
deadbeefab9b2d12015-10-14 11:33:11 -0700885 stats_.reset(new StatsCollector(this));
hbos74e1a4f2016-09-15 23:33:01 -0700886 stats_collector_ = RTCStatsCollector::Create(this);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000887
Steve Antonba818672017-11-06 10:21:57 -0800888 configuration_ = configuration;
889
Steve Anton75737c02017-11-06 10:37:17 -0800890 const PeerConnectionFactoryInterface::Options& options = factory_->options();
891
892 transport_controller_->SetSslMaxProtocolVersion(options.ssl_max_version);
893
894 // Obtain a certificate from RTCConfiguration if any were provided (optional).
895 rtc::scoped_refptr<rtc::RTCCertificate> certificate;
896 if (!configuration.certificates.empty()) {
897 // TODO(hbos,torbjorng): Decide on certificate-selection strategy instead of
898 // just picking the first one. The decision should be made based on the DTLS
899 // handshake. The DTLS negotiations need to know about all certificates.
900 certificate = configuration.certificates[0];
901 }
902
Steve Antond25da372017-11-06 14:50:29 -0800903 transport_controller_->SetIceConfig(ParseIceConfig(configuration));
Steve Anton75737c02017-11-06 10:37:17 -0800904
905 if (options.disable_encryption) {
906 dtls_enabled_ = false;
907 } else {
908 // Enable DTLS by default if we have an identity store or a certificate.
909 dtls_enabled_ = (cert_generator || certificate);
910 // |configuration| can override the default |dtls_enabled_| value.
911 if (configuration.enable_dtls_srtp) {
912 dtls_enabled_ = *(configuration.enable_dtls_srtp);
913 }
914 }
915
916 // Enable creation of RTP data channels if the kEnableRtpDataChannels is set.
917 // It takes precendence over the disable_sctp_data_channels
918 // PeerConnectionFactoryInterface::Options.
919 if (configuration.enable_rtp_data_channel) {
920 data_channel_type_ = cricket::DCT_RTP;
921 } else {
922 // DTLS has to be enabled to use SCTP.
923 if (!options.disable_sctp_data_channels && dtls_enabled_) {
924 data_channel_type_ = cricket::DCT_SCTP;
925 }
926 }
927
928 video_options_.screencast_min_bitrate_kbps =
929 configuration.screencast_min_bitrate;
930 audio_options_.combined_audio_video_bwe =
931 configuration.combined_audio_video_bwe;
932
933 audio_options_.audio_jitter_buffer_max_packets =
Oskar Sundbom9b28a032017-11-16 10:53:30 +0100934 configuration.audio_jitter_buffer_max_packets;
Steve Anton75737c02017-11-06 10:37:17 -0800935
936 audio_options_.audio_jitter_buffer_fast_accelerate =
Oskar Sundbom9b28a032017-11-16 10:53:30 +0100937 configuration.audio_jitter_buffer_fast_accelerate;
Steve Anton75737c02017-11-06 10:37:17 -0800938
939 // Whether the certificate generator/certificate is null or not determines
940 // what PeerConnectionDescriptionFactory will do, so make sure that we give it
941 // the right instructions by clearing the variables if needed.
942 if (!dtls_enabled_) {
943 cert_generator.reset();
944 certificate = nullptr;
945 } else if (certificate) {
946 // Favor generated certificate over the certificate generator.
947 cert_generator.reset();
948 }
949
950 webrtc_session_desc_factory_.reset(new WebRtcSessionDescriptionFactory(
951 signaling_thread(), channel_manager(), this, session_id(),
952 std::move(cert_generator), certificate));
953 webrtc_session_desc_factory_->SignalCertificateReady.connect(
954 this, &PeerConnection::OnCertificateReady);
955
956 if (options.disable_encryption) {
957 webrtc_session_desc_factory_->SetSdesPolicy(cricket::SEC_DISABLED);
958 }
959
960 webrtc_session_desc_factory_->set_enable_encrypted_rtp_header_extensions(
961 options.crypto_options.enable_encrypted_rtp_header_extensions);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000962
Steve Anton4171afb2017-11-20 10:20:22 -0800963 // Add default audio/video transceivers for Plan B SDP.
964 if (!IsUnifiedPlan()) {
965 transceivers_.push_back(
966 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
967 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_AUDIO)));
968 transceivers_.push_back(
969 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
970 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_VIDEO)));
971 }
972
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000973 return true;
974}
975
Steve Anton038834f2017-07-14 15:59:59 -0700976RTCError PeerConnection::ValidateConfiguration(
977 const RTCConfiguration& config) const {
978 if (config.ice_regather_interval_range &&
979 config.continual_gathering_policy == GATHER_ONCE) {
980 return RTCError(RTCErrorType::INVALID_PARAMETER,
981 "ice_regather_interval_range specified but continual "
982 "gathering policy is GATHER_ONCE");
983 }
984 return RTCError::OK();
985}
986
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000987rtc::scoped_refptr<StreamCollectionInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000988PeerConnection::local_streams() {
deadbeefab9b2d12015-10-14 11:33:11 -0700989 return local_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000990}
991
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000992rtc::scoped_refptr<StreamCollectionInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000993PeerConnection::remote_streams() {
deadbeefab9b2d12015-10-14 11:33:11 -0700994 return remote_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000995}
996
perkj@webrtc.orgc2dd5ee2014-11-04 11:31:29 +0000997bool PeerConnection::AddStream(MediaStreamInterface* local_stream) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100998 TRACE_EVENT0("webrtc", "PeerConnection::AddStream");
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000999 if (IsClosed()) {
1000 return false;
1001 }
deadbeefab9b2d12015-10-14 11:33:11 -07001002 if (!CanAddLocalMediaStream(local_streams_, local_stream)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001003 return false;
1004 }
deadbeefab9b2d12015-10-14 11:33:11 -07001005
1006 local_streams_->AddStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -08001007 MediaStreamObserver* observer = new MediaStreamObserver(local_stream);
1008 observer->SignalAudioTrackAdded.connect(this,
1009 &PeerConnection::OnAudioTrackAdded);
1010 observer->SignalAudioTrackRemoved.connect(
1011 this, &PeerConnection::OnAudioTrackRemoved);
1012 observer->SignalVideoTrackAdded.connect(this,
1013 &PeerConnection::OnVideoTrackAdded);
1014 observer->SignalVideoTrackRemoved.connect(
1015 this, &PeerConnection::OnVideoTrackRemoved);
kwibergd1fe2812016-04-27 06:47:29 -07001016 stream_observers_.push_back(std::unique_ptr<MediaStreamObserver>(observer));
deadbeefab9b2d12015-10-14 11:33:11 -07001017
deadbeefab9b2d12015-10-14 11:33:11 -07001018 for (const auto& track : local_stream->GetAudioTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001019 AddAudioTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -07001020 }
1021 for (const auto& track : local_stream->GetVideoTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001022 AddVideoTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -07001023 }
1024
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001025 stats_->AddStream(local_stream);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001026 observer_->OnRenegotiationNeeded();
1027 return true;
1028}
1029
1030void PeerConnection::RemoveStream(MediaStreamInterface* local_stream) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001031 TRACE_EVENT0("webrtc", "PeerConnection::RemoveStream");
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001032 if (!IsClosed()) {
1033 for (const auto& track : local_stream->GetAudioTracks()) {
1034 RemoveAudioTrack(track.get(), local_stream);
1035 }
1036 for (const auto& track : local_stream->GetVideoTracks()) {
1037 RemoveVideoTrack(track.get(), local_stream);
1038 }
deadbeefab9b2d12015-10-14 11:33:11 -07001039 }
deadbeefab9b2d12015-10-14 11:33:11 -07001040 local_streams_->RemoveStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -08001041 stream_observers_.erase(
1042 std::remove_if(
1043 stream_observers_.begin(), stream_observers_.end(),
kwibergd1fe2812016-04-27 06:47:29 -07001044 [local_stream](const std::unique_ptr<MediaStreamObserver>& observer) {
deadbeefeb459812015-12-15 19:24:43 -08001045 return observer->stream()->label().compare(local_stream->label()) ==
1046 0;
1047 }),
1048 stream_observers_.end());
deadbeefab9b2d12015-10-14 11:33:11 -07001049
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001050 if (IsClosed()) {
1051 return;
1052 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001053 observer_->OnRenegotiationNeeded();
1054}
1055
deadbeefe1f9d832016-01-14 15:35:42 -08001056rtc::scoped_refptr<RtpSenderInterface> PeerConnection::AddTrack(
1057 MediaStreamTrackInterface* track,
1058 std::vector<MediaStreamInterface*> streams) {
1059 TRACE_EVENT0("webrtc", "PeerConnection::AddTrack");
Steve Antonf9381f02017-12-14 10:23:57 -08001060 std::vector<std::string> stream_labels;
1061 for (auto* stream : streams) {
1062 if (!stream) {
1063 RTC_LOG(LS_ERROR) << "Stream list has null element.";
1064 return nullptr;
1065 }
1066 stream_labels.push_back(stream->label());
1067 }
Steve Anton2d6c76a2018-01-05 17:10:52 -08001068 auto sender_or_error = AddTrack(track, stream_labels);
Steve Antonf9381f02017-12-14 10:23:57 -08001069 if (!sender_or_error.ok()) {
deadbeefe1f9d832016-01-14 15:35:42 -08001070 return nullptr;
1071 }
Steve Antonf9381f02017-12-14 10:23:57 -08001072 return sender_or_error.MoveValue();
1073}
1074
Steve Anton2d6c76a2018-01-05 17:10:52 -08001075RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::AddTrack(
Steve Antonf9381f02017-12-14 10:23:57 -08001076 rtc::scoped_refptr<MediaStreamTrackInterface> track,
1077 const std::vector<std::string>& stream_labels) {
Steve Anton2d6c76a2018-01-05 17:10:52 -08001078 TRACE_EVENT0("webrtc", "PeerConnection::AddTrack");
Steve Antonf9381f02017-12-14 10:23:57 -08001079 if (!track) {
1080 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "Track is null.");
1081 }
1082 if (!(track->kind() == MediaStreamTrackInterface::kAudioKind ||
1083 track->kind() == MediaStreamTrackInterface::kVideoKind)) {
1084 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1085 "Track has invalid kind: " + track->kind());
1086 }
1087 // TODO(bugs.webrtc.org/7932): Support adding a track to multiple streams.
1088 if (stream_labels.size() > 1u) {
1089 LOG_AND_RETURN_ERROR(
1090 RTCErrorType::UNSUPPORTED_OPERATION,
1091 "AddTrack with more than one stream is not currently supported.");
1092 }
1093 if (IsClosed()) {
1094 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
1095 "PeerConnection is closed.");
deadbeefe1f9d832016-01-14 15:35:42 -08001096 }
Steve Anton4171afb2017-11-20 10:20:22 -08001097 if (FindSenderForTrack(track)) {
Steve Antonf9381f02017-12-14 10:23:57 -08001098 LOG_AND_RETURN_ERROR(
1099 RTCErrorType::INVALID_PARAMETER,
1100 "Sender already exists for track " + track->id() + ".");
deadbeefe1f9d832016-01-14 15:35:42 -08001101 }
Steve Antonf9381f02017-12-14 10:23:57 -08001102 // TODO(bugs.webrtc.org/7933): MediaSession expects the sender to have exactly
1103 // one stream. AddTrackInternal will return an error if there is more than one
1104 // stream, but if the caller specifies none then we need to generate a random
1105 // stream label.
1106 std::vector<std::string> adjusted_stream_labels = stream_labels;
1107 if (stream_labels.empty()) {
1108 adjusted_stream_labels.push_back(rtc::CreateRandomUuid());
1109 }
1110 RTC_DCHECK_EQ(1, adjusted_stream_labels.size());
1111 auto sender_or_error =
1112 (IsUnifiedPlan() ? AddTrackUnifiedPlan(track, adjusted_stream_labels)
1113 : AddTrackPlanB(track, adjusted_stream_labels));
1114 if (sender_or_error.ok()) {
1115 observer_->OnRenegotiationNeeded();
Steve Anton43a723a2018-01-04 15:48:17 -08001116 stats_->AddTrack(track);
Steve Antonf9381f02017-12-14 10:23:57 -08001117 }
1118 return sender_or_error;
1119}
deadbeefe1f9d832016-01-14 15:35:42 -08001120
Steve Antonf9381f02017-12-14 10:23:57 -08001121RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>>
1122PeerConnection::AddTrackPlanB(
1123 rtc::scoped_refptr<MediaStreamTrackInterface> track,
1124 const std::vector<std::string>& stream_labels) {
Steve Anton02ee47c2018-01-10 16:26:06 -08001125 cricket::MediaType media_type =
1126 (track->kind() == MediaStreamTrackInterface::kAudioKind
1127 ? cricket::MEDIA_TYPE_AUDIO
1128 : cricket::MEDIA_TYPE_VIDEO);
1129 auto new_sender = CreateSender(media_type, track, stream_labels);
deadbeefe1f9d832016-01-14 15:35:42 -08001130 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
Steve Anton57858b32018-02-15 15:19:50 -08001131 new_sender->internal()->SetVoiceMediaChannel(voice_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08001132 GetAudioTransceiver()->internal()->AddSender(new_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001133 const RtpSenderInfo* sender_info =
1134 FindSenderInfo(local_audio_sender_infos_,
1135 new_sender->internal()->stream_id(), track->id());
1136 if (sender_info) {
1137 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -08001138 }
Steve Antonf9381f02017-12-14 10:23:57 -08001139 } else {
1140 RTC_DCHECK_EQ(MediaStreamTrackInterface::kVideoKind, track->kind());
Steve Anton57858b32018-02-15 15:19:50 -08001141 new_sender->internal()->SetVideoMediaChannel(video_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08001142 GetVideoTransceiver()->internal()->AddSender(new_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001143 const RtpSenderInfo* sender_info =
1144 FindSenderInfo(local_video_sender_infos_,
1145 new_sender->internal()->stream_id(), track->id());
1146 if (sender_info) {
1147 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -08001148 }
deadbeefe1f9d832016-01-14 15:35:42 -08001149 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001150 return rtc::scoped_refptr<RtpSenderInterface>(new_sender);
Steve Antonf9381f02017-12-14 10:23:57 -08001151}
deadbeefe1f9d832016-01-14 15:35:42 -08001152
Steve Antonf9381f02017-12-14 10:23:57 -08001153RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>>
1154PeerConnection::AddTrackUnifiedPlan(
1155 rtc::scoped_refptr<MediaStreamTrackInterface> track,
1156 const std::vector<std::string>& stream_labels) {
1157 auto transceiver = FindFirstTransceiverForAddedTrack(track);
1158 if (transceiver) {
1159 if (transceiver->direction() == RtpTransceiverDirection::kRecvOnly) {
Steve Anton52d86772018-02-20 15:48:12 -08001160 transceiver->internal()->set_direction(
1161 RtpTransceiverDirection::kSendRecv);
Steve Antonf9381f02017-12-14 10:23:57 -08001162 } else if (transceiver->direction() == RtpTransceiverDirection::kInactive) {
Steve Anton52d86772018-02-20 15:48:12 -08001163 transceiver->internal()->set_direction(
1164 RtpTransceiverDirection::kSendOnly);
Steve Antonf9381f02017-12-14 10:23:57 -08001165 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001166 transceiver->sender()->SetTrack(track);
1167 transceiver->internal()->sender_internal()->set_stream_ids(stream_labels);
Steve Antonf9381f02017-12-14 10:23:57 -08001168 } else {
1169 cricket::MediaType media_type =
1170 (track->kind() == MediaStreamTrackInterface::kAudioKind
1171 ? cricket::MEDIA_TYPE_AUDIO
1172 : cricket::MEDIA_TYPE_VIDEO);
Steve Anton02ee47c2018-01-10 16:26:06 -08001173 auto sender = CreateSender(media_type, track, stream_labels);
1174 auto receiver = CreateReceiver(media_type, rtc::CreateRandomUuid());
1175 transceiver = CreateAndAddTransceiver(sender, receiver);
Steve Antonf9381f02017-12-14 10:23:57 -08001176 transceiver->internal()->set_created_by_addtrack(true);
Steve Anton52d86772018-02-20 15:48:12 -08001177 transceiver->internal()->set_direction(RtpTransceiverDirection::kSendRecv);
Steve Antonf9381f02017-12-14 10:23:57 -08001178 }
Steve Antonf9381f02017-12-14 10:23:57 -08001179 return transceiver->sender();
1180}
1181
1182rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1183PeerConnection::FindFirstTransceiverForAddedTrack(
1184 rtc::scoped_refptr<MediaStreamTrackInterface> track) {
1185 RTC_DCHECK(track);
1186 for (auto transceiver : transceivers_) {
1187 if (!transceiver->sender()->track() &&
Steve Anton69470252018-02-09 11:43:08 -08001188 cricket::MediaTypeToString(transceiver->media_type()) ==
Steve Antonf9381f02017-12-14 10:23:57 -08001189 track->kind() &&
Seth Hampson2f0d7022018-02-20 11:54:42 -08001190 !transceiver->internal()->has_ever_been_used_to_send() &&
1191 !transceiver->stopped()) {
Steve Antonf9381f02017-12-14 10:23:57 -08001192 return transceiver;
1193 }
1194 }
1195 return nullptr;
deadbeefe1f9d832016-01-14 15:35:42 -08001196}
1197
1198bool PeerConnection::RemoveTrack(RtpSenderInterface* sender) {
1199 TRACE_EVENT0("webrtc", "PeerConnection::RemoveTrack");
Steve Antonf9381f02017-12-14 10:23:57 -08001200 return RemoveTrackInternal(sender).ok();
1201}
1202
1203RTCError PeerConnection::RemoveTrackInternal(
1204 rtc::scoped_refptr<RtpSenderInterface> sender) {
1205 if (!sender) {
1206 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "Sender is null.");
1207 }
deadbeefe1f9d832016-01-14 15:35:42 -08001208 if (IsClosed()) {
Steve Antonf9381f02017-12-14 10:23:57 -08001209 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
1210 "PeerConnection is closed.");
deadbeefe1f9d832016-01-14 15:35:42 -08001211 }
Steve Antonf9381f02017-12-14 10:23:57 -08001212 if (IsUnifiedPlan()) {
1213 auto transceiver = FindTransceiverBySender(sender);
1214 if (!transceiver || !sender->track()) {
1215 return RTCError::OK();
1216 }
1217 sender->SetTrack(nullptr);
1218 if (transceiver->direction() == RtpTransceiverDirection::kSendRecv) {
Steve Anton52d86772018-02-20 15:48:12 -08001219 transceiver->internal()->set_direction(
1220 RtpTransceiverDirection::kRecvOnly);
Steve Antonf9381f02017-12-14 10:23:57 -08001221 } else if (transceiver->direction() == RtpTransceiverDirection::kSendOnly) {
Steve Anton52d86772018-02-20 15:48:12 -08001222 transceiver->internal()->set_direction(
1223 RtpTransceiverDirection::kInactive);
Steve Antonf9381f02017-12-14 10:23:57 -08001224 }
Steve Anton4171afb2017-11-20 10:20:22 -08001225 } else {
Steve Antonf9381f02017-12-14 10:23:57 -08001226 bool removed;
1227 if (sender->media_type() == cricket::MEDIA_TYPE_AUDIO) {
1228 removed = GetAudioTransceiver()->internal()->RemoveSender(sender);
1229 } else {
1230 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, sender->media_type());
1231 removed = GetVideoTransceiver()->internal()->RemoveSender(sender);
1232 }
1233 if (!removed) {
1234 LOG_AND_RETURN_ERROR(
1235 RTCErrorType::INVALID_PARAMETER,
1236 "Couldn't find sender " + sender->id() + " to remove.");
1237 }
Steve Anton4171afb2017-11-20 10:20:22 -08001238 }
deadbeefe1f9d832016-01-14 15:35:42 -08001239 observer_->OnRenegotiationNeeded();
Steve Antonf9381f02017-12-14 10:23:57 -08001240 return RTCError::OK();
1241}
1242
1243rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1244PeerConnection::FindTransceiverBySender(
1245 rtc::scoped_refptr<RtpSenderInterface> sender) {
1246 for (auto transceiver : transceivers_) {
1247 if (transceiver->sender() == sender) {
1248 return transceiver;
1249 }
1250 }
1251 return nullptr;
deadbeefe1f9d832016-01-14 15:35:42 -08001252}
1253
Steve Anton9158ef62017-11-27 13:01:52 -08001254RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1255PeerConnection::AddTransceiver(
1256 rtc::scoped_refptr<MediaStreamTrackInterface> track) {
1257 return AddTransceiver(track, RtpTransceiverInit());
1258}
1259
1260RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1261PeerConnection::AddTransceiver(
1262 rtc::scoped_refptr<MediaStreamTrackInterface> track,
1263 const RtpTransceiverInit& init) {
1264 if (!IsUnifiedPlan()) {
1265 LOG_AND_RETURN_ERROR(
1266 RTCErrorType::INTERNAL_ERROR,
1267 "AddTransceiver only supported when Unified Plan is enabled.");
1268 }
1269 if (!track) {
1270 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "track is null");
1271 }
1272 cricket::MediaType media_type;
1273 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
1274 media_type = cricket::MEDIA_TYPE_AUDIO;
1275 } else if (track->kind() == MediaStreamTrackInterface::kVideoKind) {
1276 media_type = cricket::MEDIA_TYPE_VIDEO;
1277 } else {
1278 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1279 "Track kind is not audio or video");
1280 }
1281 return AddTransceiver(media_type, track, init);
1282}
1283
1284RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1285PeerConnection::AddTransceiver(cricket::MediaType media_type) {
1286 return AddTransceiver(media_type, RtpTransceiverInit());
1287}
1288
1289RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1290PeerConnection::AddTransceiver(cricket::MediaType media_type,
1291 const RtpTransceiverInit& init) {
1292 if (!IsUnifiedPlan()) {
1293 LOG_AND_RETURN_ERROR(
1294 RTCErrorType::INTERNAL_ERROR,
1295 "AddTransceiver only supported when Unified Plan is enabled.");
1296 }
1297 if (!(media_type == cricket::MEDIA_TYPE_AUDIO ||
1298 media_type == cricket::MEDIA_TYPE_VIDEO)) {
1299 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1300 "media type is not audio or video");
1301 }
1302 return AddTransceiver(media_type, nullptr, init);
1303}
1304
1305RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1306PeerConnection::AddTransceiver(
1307 cricket::MediaType media_type,
1308 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Steve Anton22da89f2018-01-25 13:58:07 -08001309 const RtpTransceiverInit& init,
1310 bool fire_callback) {
Steve Anton9158ef62017-11-27 13:01:52 -08001311 RTC_DCHECK((media_type == cricket::MEDIA_TYPE_AUDIO ||
1312 media_type == cricket::MEDIA_TYPE_VIDEO));
1313 if (track) {
1314 RTC_DCHECK_EQ(media_type,
1315 (track->kind() == MediaStreamTrackInterface::kAudioKind
1316 ? cricket::MEDIA_TYPE_AUDIO
1317 : cricket::MEDIA_TYPE_VIDEO));
1318 }
1319
1320 // TODO(bugs.webrtc.org/7600): Verify init.
1321
Steve Anton02ee47c2018-01-10 16:26:06 -08001322 if (init.stream_labels.size() > 1u) {
1323 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
1324 "More than one stream is not yet supported.");
Steve Antonf9381f02017-12-14 10:23:57 -08001325 }
1326
Steve Anton02ee47c2018-01-10 16:26:06 -08001327 std::vector<std::string> stream_labels = {!init.stream_labels.empty()
1328 ? init.stream_labels[0]
1329 : rtc::CreateRandomUuid()};
1330
1331 auto sender = CreateSender(media_type, track, stream_labels);
1332 auto receiver = CreateReceiver(media_type, rtc::CreateRandomUuid());
1333 auto transceiver = CreateAndAddTransceiver(sender, receiver);
1334 transceiver->internal()->set_direction(init.direction);
1335
Steve Anton22da89f2018-01-25 13:58:07 -08001336 if (fire_callback) {
1337 observer_->OnRenegotiationNeeded();
1338 }
Steve Antonf9381f02017-12-14 10:23:57 -08001339
1340 return rtc::scoped_refptr<RtpTransceiverInterface>(transceiver);
1341}
1342
Steve Anton02ee47c2018-01-10 16:26:06 -08001343rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
1344PeerConnection::CreateSender(
1345 cricket::MediaType media_type,
1346 rtc::scoped_refptr<MediaStreamTrackInterface> track,
1347 const std::vector<std::string>& stream_labels) {
Steve Anton9158ef62017-11-27 13:01:52 -08001348 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> sender;
Steve Anton02ee47c2018-01-10 16:26:06 -08001349 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
1350 RTC_DCHECK(!track ||
1351 (track->kind() == MediaStreamTrackInterface::kAudioKind));
1352 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
1353 signaling_thread(),
Steve Anton47136dd2018-01-12 10:49:35 -08001354 new AudioRtpSender(worker_thread(),
1355 static_cast<AudioTrackInterface*>(track.get()),
Steve Anton02ee47c2018-01-10 16:26:06 -08001356 stream_labels, stats_.get()));
1357 } else {
1358 RTC_DCHECK_EQ(media_type, cricket::MEDIA_TYPE_VIDEO);
1359 RTC_DCHECK(!track ||
1360 (track->kind() == MediaStreamTrackInterface::kVideoKind));
1361 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
1362 signaling_thread(),
Steve Anton47136dd2018-01-12 10:49:35 -08001363 new VideoRtpSender(worker_thread(),
1364 static_cast<VideoTrackInterface*>(track.get()),
Steve Anton02ee47c2018-01-10 16:26:06 -08001365 stream_labels));
1366 }
1367 sender->internal()->set_stream_ids(stream_labels);
1368 return sender;
1369}
1370
1371rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1372PeerConnection::CreateReceiver(cricket::MediaType media_type,
1373 const std::string& receiver_id) {
Steve Anton9158ef62017-11-27 13:01:52 -08001374 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1375 receiver;
Steve Anton9158ef62017-11-27 13:01:52 -08001376 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton9158ef62017-11-27 13:01:52 -08001377 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
Steve Anton60776752018-01-10 11:51:34 -08001378 signaling_thread(),
Steve Antond3679212018-01-17 17:41:02 -08001379 new AudioRtpReceiver(worker_thread(), receiver_id, {}));
Steve Anton9158ef62017-11-27 13:01:52 -08001380 } else {
Steve Anton02ee47c2018-01-10 16:26:06 -08001381 RTC_DCHECK_EQ(media_type, cricket::MEDIA_TYPE_VIDEO);
Steve Anton9158ef62017-11-27 13:01:52 -08001382 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
1383 signaling_thread(),
Steve Antond3679212018-01-17 17:41:02 -08001384 new VideoRtpReceiver(worker_thread(), receiver_id, {}));
Steve Anton9158ef62017-11-27 13:01:52 -08001385 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001386 return receiver;
1387}
1388
1389rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1390PeerConnection::CreateAndAddTransceiver(
1391 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> sender,
1392 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1393 receiver) {
1394 auto transceiver = RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1395 signaling_thread(), new RtpTransceiver(sender, receiver));
Steve Anton9158ef62017-11-27 13:01:52 -08001396 transceivers_.push_back(transceiver);
Steve Anton52d86772018-02-20 15:48:12 -08001397 transceiver->internal()->SignalNegotiationNeeded.connect(
1398 this, &PeerConnection::OnNegotiationNeeded);
Steve Antonf9381f02017-12-14 10:23:57 -08001399 return transceiver;
Steve Anton9158ef62017-11-27 13:01:52 -08001400}
1401
Steve Anton52d86772018-02-20 15:48:12 -08001402void PeerConnection::OnNegotiationNeeded() {
1403 RTC_DCHECK_RUN_ON(signaling_thread());
1404 RTC_DCHECK(!IsClosed());
1405 observer_->OnRenegotiationNeeded();
1406}
1407
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001408rtc::scoped_refptr<DtmfSenderInterface> PeerConnection::CreateDtmfSender(
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001409 AudioTrackInterface* track) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001410 TRACE_EVENT0("webrtc", "PeerConnection::CreateDtmfSender");
zhihuang29ff8442016-07-27 11:07:25 -07001411 if (IsClosed()) {
1412 return nullptr;
1413 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001414 if (!track) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001415 RTC_LOG(LS_ERROR) << "CreateDtmfSender - track is NULL.";
deadbeef20cb0c12017-02-01 20:27:00 -08001416 return nullptr;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001417 }
Steve Anton4171afb2017-11-20 10:20:22 -08001418 auto track_sender = FindSenderForTrack(track);
1419 if (!track_sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001420 RTC_LOG(LS_ERROR) << "CreateDtmfSender called with a non-added track.";
deadbeef20cb0c12017-02-01 20:27:00 -08001421 return nullptr;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001422 }
1423
Steve Anton4171afb2017-11-20 10:20:22 -08001424 return track_sender->GetDtmfSender();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001425}
1426
deadbeeffac06552015-11-25 11:26:01 -08001427rtc::scoped_refptr<RtpSenderInterface> PeerConnection::CreateSender(
deadbeefbd7d8f72015-12-18 16:58:44 -08001428 const std::string& kind,
1429 const std::string& stream_id) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001430 TRACE_EVENT0("webrtc", "PeerConnection::CreateSender");
zhihuang29ff8442016-07-27 11:07:25 -07001431 if (IsClosed()) {
1432 return nullptr;
1433 }
Steve Anton4171afb2017-11-20 10:20:22 -08001434
Steve Anton02ee47c2018-01-10 16:26:06 -08001435 std::vector<std::string> stream_labels;
1436 if (!stream_id.empty()) {
1437 stream_labels.push_back(stream_id);
1438 }
1439
Steve Anton4171afb2017-11-20 10:20:22 -08001440 // TODO(steveanton): Move construction of the RtpSenders to RtpTransceiver.
deadbeefa601f5c2016-06-06 14:27:39 -07001441 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender;
deadbeeffac06552015-11-25 11:26:01 -08001442 if (kind == MediaStreamTrackInterface::kAudioKind) {
Steve Anton47136dd2018-01-12 10:49:35 -08001443 auto* audio_sender = new AudioRtpSender(worker_thread(), nullptr,
1444 stream_labels, stats_.get());
Steve Anton57858b32018-02-15 15:19:50 -08001445 audio_sender->SetVoiceMediaChannel(voice_media_channel());
deadbeefa601f5c2016-06-06 14:27:39 -07001446 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton02ee47c2018-01-10 16:26:06 -08001447 signaling_thread(), audio_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001448 GetAudioTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 11:26:01 -08001449 } else if (kind == MediaStreamTrackInterface::kVideoKind) {
Steve Anton47136dd2018-01-12 10:49:35 -08001450 auto* video_sender =
1451 new VideoRtpSender(worker_thread(), nullptr, stream_labels);
Steve Anton57858b32018-02-15 15:19:50 -08001452 video_sender->SetVideoMediaChannel(video_media_channel());
deadbeefa601f5c2016-06-06 14:27:39 -07001453 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton02ee47c2018-01-10 16:26:06 -08001454 signaling_thread(), video_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001455 GetVideoTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 11:26:01 -08001456 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001457 RTC_LOG(LS_ERROR) << "CreateSender called with invalid kind: " << kind;
Steve Anton4171afb2017-11-20 10:20:22 -08001458 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08001459 }
Steve Anton4171afb2017-11-20 10:20:22 -08001460
deadbeefe1f9d832016-01-14 15:35:42 -08001461 return new_sender;
deadbeeffac06552015-11-25 11:26:01 -08001462}
1463
deadbeef70ab1a12015-09-28 16:53:55 -07001464std::vector<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::GetSenders()
1465 const {
deadbeefa601f5c2016-06-06 14:27:39 -07001466 std::vector<rtc::scoped_refptr<RtpSenderInterface>> ret;
Steve Anton4171afb2017-11-20 10:20:22 -08001467 for (auto sender : GetSendersInternal()) {
1468 ret.push_back(sender);
deadbeefa601f5c2016-06-06 14:27:39 -07001469 }
1470 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -07001471}
1472
Steve Anton4171afb2017-11-20 10:20:22 -08001473std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1474PeerConnection::GetSendersInternal() const {
1475 std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1476 all_senders;
1477 for (auto transceiver : transceivers_) {
1478 auto senders = transceiver->internal()->senders();
1479 all_senders.insert(all_senders.end(), senders.begin(), senders.end());
1480 }
1481 return all_senders;
1482}
1483
deadbeef70ab1a12015-09-28 16:53:55 -07001484std::vector<rtc::scoped_refptr<RtpReceiverInterface>>
1485PeerConnection::GetReceivers() const {
deadbeefa601f5c2016-06-06 14:27:39 -07001486 std::vector<rtc::scoped_refptr<RtpReceiverInterface>> ret;
Steve Anton4171afb2017-11-20 10:20:22 -08001487 for (const auto& receiver : GetReceiversInternal()) {
1488 ret.push_back(receiver);
deadbeefa601f5c2016-06-06 14:27:39 -07001489 }
1490 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -07001491}
1492
Steve Anton4171afb2017-11-20 10:20:22 -08001493std::vector<
1494 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1495PeerConnection::GetReceiversInternal() const {
1496 std::vector<
1497 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1498 all_receivers;
1499 for (auto transceiver : transceivers_) {
1500 auto receivers = transceiver->internal()->receivers();
1501 all_receivers.insert(all_receivers.end(), receivers.begin(),
1502 receivers.end());
1503 }
1504 return all_receivers;
1505}
1506
Steve Anton9158ef62017-11-27 13:01:52 -08001507std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
1508PeerConnection::GetTransceivers() const {
1509 RTC_DCHECK(IsUnifiedPlan());
1510 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> all_transceivers;
1511 for (auto transceiver : transceivers_) {
1512 all_transceivers.push_back(transceiver);
1513 }
1514 return all_transceivers;
1515}
1516
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001517bool PeerConnection::GetStats(StatsObserver* observer,
wu@webrtc.orgb9a088b2014-02-13 23:18:49 +00001518 MediaStreamTrackInterface* track,
1519 StatsOutputLevel level) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001520 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
deadbeef0a6c4ca2015-10-06 11:38:28 -07001521 RTC_DCHECK(signaling_thread()->IsCurrent());
nisse7ce109a2017-01-31 00:57:56 -08001522 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001523 RTC_LOG(LS_ERROR) << "GetStats - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001524 return false;
1525 }
1526
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001527 stats_->UpdateStats(level);
zhihuange9e94c32016-11-04 11:38:15 -07001528 // The StatsCollector is used to tell if a track is valid because it may
1529 // remember tracks that the PeerConnection previously removed.
1530 if (track && !stats_->IsValidTrack(track->id())) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001531 RTC_LOG(LS_WARNING) << "GetStats is called with an invalid track: "
1532 << track->id();
zhihuange9e94c32016-11-04 11:38:15 -07001533 return false;
1534 }
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001535 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_GETSTATS,
tommi@webrtc.org5b06b062014-08-15 08:38:30 +00001536 new GetStatsMsg(observer, track));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001537 return true;
1538}
1539
hbos74e1a4f2016-09-15 23:33:01 -07001540void PeerConnection::GetStats(RTCStatsCollectorCallback* callback) {
1541 RTC_DCHECK(stats_collector_);
1542 stats_collector_->GetStatsReport(callback);
1543}
1544
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001545PeerConnectionInterface::SignalingState PeerConnection::signaling_state() {
1546 return signaling_state_;
1547}
1548
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001549PeerConnectionInterface::IceConnectionState
1550PeerConnection::ice_connection_state() {
1551 return ice_connection_state_;
1552}
1553
1554PeerConnectionInterface::IceGatheringState
1555PeerConnection::ice_gathering_state() {
1556 return ice_gathering_state_;
1557}
1558
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001559rtc::scoped_refptr<DataChannelInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001560PeerConnection::CreateDataChannel(
1561 const std::string& label,
1562 const DataChannelInit* config) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001563 TRACE_EVENT0("webrtc", "PeerConnection::CreateDataChannel");
zhihuang9763d562016-08-05 11:14:50 -07001564
deadbeefab9b2d12015-10-14 11:33:11 -07001565 bool first_datachannel = !HasDataChannels();
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001566
kwibergd1fe2812016-04-27 06:47:29 -07001567 std::unique_ptr<InternalDataChannelInit> internal_config;
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00001568 if (config) {
1569 internal_config.reset(new InternalDataChannelInit(*config));
1570 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001571 rtc::scoped_refptr<DataChannelInterface> channel(
deadbeefab9b2d12015-10-14 11:33:11 -07001572 InternalCreateDataChannel(label, internal_config.get()));
1573 if (!channel.get()) {
1574 return nullptr;
1575 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001576
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001577 // Trigger the onRenegotiationNeeded event for every new RTP DataChannel, or
1578 // the first SCTP DataChannel.
Steve Anton75737c02017-11-06 10:37:17 -08001579 if (data_channel_type() == cricket::DCT_RTP || first_datachannel) {
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001580 observer_->OnRenegotiationNeeded();
1581 }
wu@webrtc.org91053e72013-08-10 07:18:04 +00001582
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001583 return DataChannelProxy::Create(signaling_thread(), channel.get());
1584}
1585
1586void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
1587 const MediaConstraintsInterface* constraints) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001588 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
Steve Anton8d3444d2017-10-20 15:30:51 -07001589
zhihuang1c378ed2017-08-17 14:10:50 -07001590 PeerConnectionInterface::RTCOfferAnswerOptions offer_answer_options;
1591 // Always create an offer even if |ConvertConstraintsToOfferAnswerOptions|
1592 // returns false for now. Because |ConvertConstraintsToOfferAnswerOptions|
1593 // compares the mandatory fields parsed with the mandatory fields added in the
1594 // |constraints| and some downstream applications might create offers with
1595 // mandatory fields which would not be parsed in the helper method. For
1596 // example, in Chromium/remoting, |kEnableDtlsSrtp| is added to the
1597 // |constraints| as a mandatory field but it is not parsed.
1598 ConvertConstraintsToOfferAnswerOptions(constraints, &offer_answer_options);
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001599
zhihuang1c378ed2017-08-17 14:10:50 -07001600 CreateOffer(observer, offer_answer_options);
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001601}
1602
1603void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
1604 const RTCOfferAnswerOptions& options) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001605 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
Steve Anton8d3444d2017-10-20 15:30:51 -07001606
nisse7ce109a2017-01-31 00:57:56 -08001607 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001608 RTC_LOG(LS_ERROR) << "CreateOffer - observer is NULL.";
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001609 return;
1610 }
deadbeefab9b2d12015-10-14 11:33:11 -07001611
Steve Anton8d3444d2017-10-20 15:30:51 -07001612 if (IsClosed()) {
1613 std::string error = "CreateOffer called when PeerConnection is closed.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001614 RTC_LOG(LS_ERROR) << error;
Steve Anton8d3444d2017-10-20 15:30:51 -07001615 PostCreateSessionDescriptionFailure(observer, error);
1616 return;
1617 }
1618
zhihuang1c378ed2017-08-17 14:10:50 -07001619 if (!ValidateOfferAnswerOptions(options)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001620 std::string error = "CreateOffer called with invalid options.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001621 RTC_LOG(LS_ERROR) << error;
deadbeefab9b2d12015-10-14 11:33:11 -07001622 PostCreateSessionDescriptionFailure(observer, error);
1623 return;
1624 }
1625
Steve Anton22da89f2018-01-25 13:58:07 -08001626 // Legacy handling for offer_to_receive_audio and offer_to_receive_video.
1627 // Specified in WebRTC section 4.4.3.2 "Legacy configuration extensions".
1628 if (IsUnifiedPlan()) {
1629 RTCError error = HandleLegacyOfferOptions(options);
1630 if (!error.ok()) {
1631 PostCreateSessionDescriptionFailure(observer, error.message());
1632 return;
1633 }
1634 }
1635
zhihuang1c378ed2017-08-17 14:10:50 -07001636 cricket::MediaSessionOptions session_options;
1637 GetOptionsForOffer(options, &session_options);
Steve Antond25da372017-11-06 14:50:29 -08001638 webrtc_session_desc_factory_->CreateOffer(observer, options, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001639}
1640
Steve Anton22da89f2018-01-25 13:58:07 -08001641RTCError PeerConnection::HandleLegacyOfferOptions(
1642 const RTCOfferAnswerOptions& options) {
1643 RTC_DCHECK(IsUnifiedPlan());
1644
1645 if (options.offer_to_receive_audio == 0) {
1646 RemoveRecvDirectionFromReceivingTransceiversOfType(
1647 cricket::MEDIA_TYPE_AUDIO);
1648 } else if (options.offer_to_receive_audio == 1) {
1649 AddUpToOneReceivingTransceiverOfType(cricket::MEDIA_TYPE_AUDIO);
1650 } else if (options.offer_to_receive_audio > 1) {
1651 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
1652 "offer_to_receive_audio > 1 is not supported.");
1653 }
1654
1655 if (options.offer_to_receive_video == 0) {
1656 RemoveRecvDirectionFromReceivingTransceiversOfType(
1657 cricket::MEDIA_TYPE_VIDEO);
1658 } else if (options.offer_to_receive_video == 1) {
1659 AddUpToOneReceivingTransceiverOfType(cricket::MEDIA_TYPE_VIDEO);
1660 } else if (options.offer_to_receive_video > 1) {
1661 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
1662 "offer_to_receive_video > 1 is not supported.");
1663 }
1664
1665 return RTCError::OK();
1666}
1667
1668void PeerConnection::RemoveRecvDirectionFromReceivingTransceiversOfType(
1669 cricket::MediaType media_type) {
1670 for (auto transceiver : GetReceivingTransceiversOfType(media_type)) {
1671 transceiver->internal()->set_direction(
1672 RtpTransceiverDirectionWithRecvSet(transceiver->direction(), false));
1673 }
1674}
1675
1676void PeerConnection::AddUpToOneReceivingTransceiverOfType(
1677 cricket::MediaType media_type) {
1678 if (GetReceivingTransceiversOfType(media_type).empty()) {
1679 RtpTransceiverInit init;
1680 init.direction = RtpTransceiverDirection::kRecvOnly;
1681 AddTransceiver(media_type, nullptr, init, /*fire_callback=*/false);
1682 }
1683}
1684
1685std::vector<rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
1686PeerConnection::GetReceivingTransceiversOfType(cricket::MediaType media_type) {
1687 std::vector<
1688 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
1689 receiving_transceivers;
1690 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08001691 if (!transceiver->stopped() && transceiver->media_type() == media_type &&
Steve Anton22da89f2018-01-25 13:58:07 -08001692 RtpTransceiverDirectionHasRecv(transceiver->direction())) {
1693 receiving_transceivers.push_back(transceiver);
1694 }
1695 }
1696 return receiving_transceivers;
1697}
1698
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001699void PeerConnection::CreateAnswer(
1700 CreateSessionDescriptionObserver* observer,
1701 const MediaConstraintsInterface* constraints) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001702 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
Steve Anton8d3444d2017-10-20 15:30:51 -07001703
nisse7ce109a2017-01-31 00:57:56 -08001704 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001705 RTC_LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001706 return;
1707 }
deadbeefab9b2d12015-10-14 11:33:11 -07001708
zhihuang1c378ed2017-08-17 14:10:50 -07001709 PeerConnectionInterface::RTCOfferAnswerOptions offer_answer_options;
1710 if (!ConvertConstraintsToOfferAnswerOptions(constraints,
1711 &offer_answer_options)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001712 std::string error = "CreateAnswer called with invalid constraints.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001713 RTC_LOG(LS_ERROR) << error;
deadbeefab9b2d12015-10-14 11:33:11 -07001714 PostCreateSessionDescriptionFailure(observer, error);
1715 return;
1716 }
1717
Steve Anton8d3444d2017-10-20 15:30:51 -07001718 CreateAnswer(observer, offer_answer_options);
htaa2a49d92016-03-04 02:51:39 -08001719}
1720
1721void PeerConnection::CreateAnswer(CreateSessionDescriptionObserver* observer,
1722 const RTCOfferAnswerOptions& options) {
1723 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
nisse7ce109a2017-01-31 00:57:56 -08001724 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001725 RTC_LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
htaa2a49d92016-03-04 02:51:39 -08001726 return;
1727 }
1728
Steve Antondffead82018-02-06 10:31:29 -08001729 if (!(signaling_state_ == kHaveRemoteOffer ||
1730 signaling_state_ == kHaveLocalPrAnswer)) {
1731 std::string error =
1732 "PeerConnection cannot create an answer in a state other than "
1733 "have-remote-offer or have-local-pranswer.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001734 RTC_LOG(LS_ERROR) << error;
Steve Anton8d3444d2017-10-20 15:30:51 -07001735 PostCreateSessionDescriptionFailure(observer, error);
1736 return;
1737 }
1738
Steve Antondffead82018-02-06 10:31:29 -08001739 // The remote description should be set if we're in the right state.
1740 RTC_DCHECK(remote_description());
Steve Anton8d3444d2017-10-20 15:30:51 -07001741
Steve Anton22da89f2018-01-25 13:58:07 -08001742 if (IsUnifiedPlan()) {
1743 if (options.offer_to_receive_audio != RTCOfferAnswerOptions::kUndefined) {
1744 RTC_LOG(LS_WARNING) << "CreateAnswer: offer_to_receive_audio is not "
1745 "supported with Unified Plan semantics. Use the "
1746 "RtpTransceiver API instead.";
1747 }
1748 if (options.offer_to_receive_video != RTCOfferAnswerOptions::kUndefined) {
1749 RTC_LOG(LS_WARNING) << "CreateAnswer: offer_to_receive_video is not "
1750 "supported with Unified Plan semantics. Use the "
1751 "RtpTransceiver API instead.";
1752 }
1753 }
1754
htaa2a49d92016-03-04 02:51:39 -08001755 cricket::MediaSessionOptions session_options;
zhihuang1c378ed2017-08-17 14:10:50 -07001756 GetOptionsForAnswer(options, &session_options);
htaa2a49d92016-03-04 02:51:39 -08001757
Steve Antond25da372017-11-06 14:50:29 -08001758 webrtc_session_desc_factory_->CreateAnswer(observer, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001759}
1760
1761void PeerConnection::SetLocalDescription(
1762 SetSessionDescriptionObserver* observer,
Steve Anton80dd7b52018-02-16 17:08:42 -08001763 SessionDescriptionInterface* desc_ptr) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001764 TRACE_EVENT0("webrtc", "PeerConnection::SetLocalDescription");
Steve Anton8a006912017-12-04 15:25:56 -08001765
Steve Anton80dd7b52018-02-16 17:08:42 -08001766 // The SetLocalDescription contract is that we take ownership of the session
1767 // description regardless of the outcome, so wrap it in a unique_ptr right
1768 // away. Ideally, SetLocalDescription's signature will be changed to take the
1769 // description as a unique_ptr argument to formalize this agreement.
1770 std::unique_ptr<SessionDescriptionInterface> desc(desc_ptr);
1771
nisse7ce109a2017-01-31 00:57:56 -08001772 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001773 RTC_LOG(LS_ERROR) << "SetLocalDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001774 return;
1775 }
Steve Anton8a006912017-12-04 15:25:56 -08001776
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001777 if (!desc) {
1778 PostSetSessionDescriptionFailure(observer, "SessionDescription is NULL.");
1779 return;
1780 }
Steve Anton8d3444d2017-10-20 15:30:51 -07001781
Steve Anton80dd7b52018-02-16 17:08:42 -08001782 // If a session error has occurred the PeerConnection is in a possibly
1783 // inconsistent state so fail right away.
1784 if (session_error() != SessionError::kNone) {
1785 std::string error_message = GetSessionErrorMsg();
1786 RTC_LOG(LS_ERROR) << "SetLocalDescription: " << error_message;
1787 PostSetSessionDescriptionFailure(observer, std::move(error_message));
1788 return;
1789 }
Steve Anton8d3444d2017-10-20 15:30:51 -07001790
Steve Anton80dd7b52018-02-16 17:08:42 -08001791 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_LOCAL);
1792 if (!error.ok()) {
1793 std::string error_message = GetSetDescriptionErrorMessage(
1794 cricket::CS_LOCAL, desc->GetType(), error);
1795 RTC_LOG(LS_ERROR) << error_message;
1796 PostSetSessionDescriptionFailure(observer, std::move(error_message));
1797 return;
1798 }
1799
1800 // Grab the description type before moving ownership to ApplyLocalDescription,
1801 // which may destroy it before returning.
1802 const SdpType type = desc->GetType();
1803
1804 error = ApplyLocalDescription(std::move(desc));
Steve Anton8a006912017-12-04 15:25:56 -08001805 // |desc| may be destroyed at this point.
1806
1807 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08001808 // If ApplyLocalDescription fails, the PeerConnection could be in an
1809 // inconsistent state, so act conservatively here and set the session error
1810 // so that future calls to SetLocalDescription/SetRemoteDescription fail.
1811 SetSessionError(SessionError::kContent, error.message());
1812 std::string error_message =
1813 GetSetDescriptionErrorMessage(cricket::CS_LOCAL, type, error);
1814 RTC_LOG(LS_ERROR) << error_message;
Steve Anton8a006912017-12-04 15:25:56 -08001815 PostSetSessionDescriptionFailure(observer, std::move(error_message));
Steve Anton8d3444d2017-10-20 15:30:51 -07001816 return;
1817 }
Steve Anton8a006912017-12-04 15:25:56 -08001818 RTC_DCHECK(local_description());
1819
1820 PostSetSessionDescriptionSuccess(observer);
1821
1822 // According to JSEP, after setLocalDescription, changing the candidate pool
1823 // size is not allowed, and changing the set of ICE servers will not result
1824 // in new candidates being gathered.
1825 port_allocator_->FreezeCandidatePool();
1826
1827 // MaybeStartGathering needs to be called after posting
1828 // MSG_SET_SESSIONDESCRIPTION_SUCCESS, so that we don't signal any candidates
1829 // before signaling that SetLocalDescription completed.
1830 transport_controller_->MaybeStartGathering();
1831
Steve Antona3a92c22017-12-07 10:27:41 -08001832 if (local_description()->GetType() == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08001833 // TODO(deadbeef): We already had to hop to the network thread for
1834 // MaybeStartGathering...
1835 network_thread()->Invoke<void>(
1836 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
1837 port_allocator_.get()));
1838 }
1839}
1840
1841RTCError PeerConnection::ApplyLocalDescription(
1842 std::unique_ptr<SessionDescriptionInterface> desc) {
1843 RTC_DCHECK_RUN_ON(signaling_thread());
1844 RTC_DCHECK(desc);
1845
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001846 // Update stats here so that we have the most recent stats for tracks and
1847 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001848 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 15:25:56 -08001849
1850 // Update the initial_offerer flag if this session is the initial_offerer.
Steve Anton3828c062017-12-06 10:34:51 -08001851 SdpType type = desc->GetType();
Steve Anton8a006912017-12-04 15:25:56 -08001852 if (!initial_offerer_.has_value()) {
Steve Anton3828c062017-12-06 10:34:51 -08001853 initial_offerer_.emplace(type == SdpType::kOffer);
Steve Anton8a006912017-12-04 15:25:56 -08001854 if (*initial_offerer_) {
1855 transport_controller_->SetIceRole(cricket::ICEROLE_CONTROLLING);
1856 } else {
1857 transport_controller_->SetIceRole(cricket::ICEROLE_CONTROLLED);
1858 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001859 }
Steve Anton8a006912017-12-04 15:25:56 -08001860
Steve Antondcc3c022017-12-22 16:02:54 -08001861 // Take a reference to the old local description since it's used below to
1862 // compare against the new local description. When setting the new local
1863 // description, grab ownership of the replaced session description in case it
1864 // is the same as |old_local_description|, to keep it alive for the duration
1865 // of the method.
1866 const SessionDescriptionInterface* old_local_description =
1867 local_description();
1868 std::unique_ptr<SessionDescriptionInterface> replaced_local_description;
Steve Anton3828c062017-12-06 10:34:51 -08001869 if (type == SdpType::kAnswer) {
Steve Antondcc3c022017-12-22 16:02:54 -08001870 replaced_local_description = pending_local_description_
1871 ? std::move(pending_local_description_)
1872 : std::move(current_local_description_);
Steve Anton8a006912017-12-04 15:25:56 -08001873 current_local_description_ = std::move(desc);
1874 pending_local_description_ = nullptr;
1875 current_remote_description_ = std::move(pending_remote_description_);
1876 } else {
Steve Antondcc3c022017-12-22 16:02:54 -08001877 replaced_local_description = std::move(pending_local_description_);
Steve Anton8a006912017-12-04 15:25:56 -08001878 pending_local_description_ = std::move(desc);
1879 }
1880 // The session description to apply now must be accessed by
1881 // |local_description()|.
Henrik Boströmfdb92012017-11-09 19:55:44 +01001882 RTC_DCHECK(local_description());
deadbeefab9b2d12015-10-14 11:33:11 -07001883
Steve Antondcc3c022017-12-22 16:02:54 -08001884 if (IsUnifiedPlan()) {
1885 RTCError error = UpdateTransceiversAndDataChannels(
Seth Hampsonae8a90a2018-02-13 15:33:48 -08001886 cricket::CS_LOCAL, *local_description(), old_local_description,
1887 remote_description());
Steve Anton8a006912017-12-04 15:25:56 -08001888 if (!error.ok()) {
1889 return error;
1890 }
Steve Antondcc3c022017-12-22 16:02:54 -08001891 for (auto transceiver : transceivers_) {
1892 const ContentInfo* content =
1893 FindMediaSectionForTransceiver(transceiver, local_description());
1894 if (!content) {
1895 continue;
1896 }
1897 const MediaContentDescription* media_desc = content->media_description();
1898 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
1899 transceiver->internal()->set_current_direction(media_desc->direction());
1900 }
1901 if (content->rejected && !transceiver->stopped()) {
1902 transceiver->Stop();
1903 }
1904 }
1905 } else {
1906 // Transport and Media channels will be created only when offer is set.
1907 if (type == SdpType::kOffer) {
1908 // TODO(bugs.webrtc.org/4676) - Handle CreateChannel failure, as new local
1909 // description is applied. Restore back to old description.
1910 RTCError error = CreateChannels(*local_description()->description());
1911 if (!error.ok()) {
1912 return error;
1913 }
1914 }
Steve Anton8a006912017-12-04 15:25:56 -08001915
Steve Antondcc3c022017-12-22 16:02:54 -08001916 // Remove unused channels if MediaContentDescription is rejected.
1917 RemoveUnusedChannels(local_description()->description());
1918 }
Steve Anton8a006912017-12-04 15:25:56 -08001919
Steve Anton80dd7b52018-02-16 17:08:42 -08001920 RTCError error = UpdateSessionState(type, cricket::CS_LOCAL);
Steve Anton8a006912017-12-04 15:25:56 -08001921 if (!error.ok()) {
1922 return error;
1923 }
Steve Antondcc3c022017-12-22 16:02:54 -08001924
Steve Anton8a006912017-12-04 15:25:56 -08001925 if (remote_description()) {
1926 // Now that we have a local description, we can push down remote candidates.
1927 UseCandidatesInSessionDescription(remote_description());
1928 }
1929
1930 pending_ice_restarts_.clear();
1931 if (session_error() != SessionError::kNone) {
1932 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
1933 }
1934
deadbeefab9b2d12015-10-14 11:33:11 -07001935 // If setting the description decided our SSL role, allocate any necessary
1936 // SCTP sids.
1937 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08001938 if (data_channel_type() == cricket::DCT_SCTP && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001939 AllocateSctpSids(role);
1940 }
1941
Steve Antond3679212018-01-17 17:41:02 -08001942 if (IsUnifiedPlan()) {
1943 for (auto transceiver : transceivers_) {
1944 const ContentInfo* content =
1945 FindMediaSectionForTransceiver(transceiver, local_description());
1946 if (!content) {
1947 continue;
1948 }
1949 if (content->rejected && !transceiver->stopped()) {
1950 transceiver->Stop();
1951 }
Steve Anton74255ff2018-01-24 18:32:57 -08001952 const auto& streams = content->media_description()->streams();
1953 if (!content->rejected && !streams.empty()) {
Steve Antond3679212018-01-17 17:41:02 -08001954 transceiver->internal()->sender_internal()->set_stream_ids(
Steve Anton74255ff2018-01-24 18:32:57 -08001955 {streams[0].sync_label});
Steve Antond3679212018-01-17 17:41:02 -08001956 transceiver->internal()->sender_internal()->SetSsrc(
Steve Anton74255ff2018-01-24 18:32:57 -08001957 streams[0].first_ssrc());
Steve Antond3679212018-01-17 17:41:02 -08001958 }
1959 }
1960 } else {
1961 // Plan B semantics.
1962
Steve Antondcc3c022017-12-22 16:02:54 -08001963 // Update state and SSRC of local MediaStreams and DataChannels based on the
1964 // local session description.
1965 const cricket::ContentInfo* audio_content =
1966 GetFirstAudioContent(local_description()->description());
1967 if (audio_content) {
1968 if (audio_content->rejected) {
1969 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
1970 } else {
1971 const cricket::AudioContentDescription* audio_desc =
1972 audio_content->media_description()->as_audio();
1973 UpdateLocalSenders(audio_desc->streams(), audio_desc->type());
1974 }
deadbeeffaac4972015-11-12 15:33:07 -08001975 }
deadbeefab9b2d12015-10-14 11:33:11 -07001976
Steve Antondcc3c022017-12-22 16:02:54 -08001977 const cricket::ContentInfo* video_content =
1978 GetFirstVideoContent(local_description()->description());
1979 if (video_content) {
1980 if (video_content->rejected) {
1981 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
1982 } else {
1983 const cricket::VideoContentDescription* video_desc =
1984 video_content->media_description()->as_video();
1985 UpdateLocalSenders(video_desc->streams(), video_desc->type());
1986 }
deadbeeffaac4972015-11-12 15:33:07 -08001987 }
deadbeefab9b2d12015-10-14 11:33:11 -07001988 }
1989
1990 const cricket::ContentInfo* data_content =
Henrik Boströmfdb92012017-11-09 19:55:44 +01001991 GetFirstDataContent(local_description()->description());
deadbeefab9b2d12015-10-14 11:33:11 -07001992 if (data_content) {
1993 const cricket::DataContentDescription* data_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08001994 data_content->media_description()->as_data();
deadbeefab9b2d12015-10-14 11:33:11 -07001995 if (rtc::starts_with(data_desc->protocol().data(),
1996 cricket::kMediaProtocolRtpPrefix)) {
1997 UpdateLocalRtpDataChannels(data_desc->streams());
1998 }
1999 }
2000
Steve Anton8a006912017-12-04 15:25:56 -08002001 return RTCError::OK();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002002}
2003
2004void PeerConnection::SetRemoteDescription(
Henrik Boströma4ecf552017-11-23 14:17:07 +00002005 SetSessionDescriptionObserver* observer,
2006 SessionDescriptionInterface* desc) {
Henrik Boström31638672017-11-23 17:48:32 +01002007 SetRemoteDescription(
2008 std::unique_ptr<SessionDescriptionInterface>(desc),
2009 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface>(
2010 new SetRemoteDescriptionObserverAdapter(this, observer)));
2011}
2012
2013void PeerConnection::SetRemoteDescription(
2014 std::unique_ptr<SessionDescriptionInterface> desc,
2015 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface> observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +01002016 TRACE_EVENT0("webrtc", "PeerConnection::SetRemoteDescription");
Steve Anton8a006912017-12-04 15:25:56 -08002017
nisse7ce109a2017-01-31 00:57:56 -08002018 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002019 RTC_LOG(LS_ERROR) << "SetRemoteDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002020 return;
2021 }
Steve Anton8a006912017-12-04 15:25:56 -08002022
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002023 if (!desc) {
Henrik Boström31638672017-11-23 17:48:32 +01002024 observer->OnSetRemoteDescriptionComplete(RTCError(
Steve Anton8a006912017-12-04 15:25:56 -08002025 RTCErrorType::INVALID_PARAMETER, "SessionDescription is NULL."));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002026 return;
2027 }
Steve Anton8d3444d2017-10-20 15:30:51 -07002028
Steve Anton80dd7b52018-02-16 17:08:42 -08002029 // If a session error has occurred the PeerConnection is in a possibly
2030 // inconsistent state so fail right away.
2031 if (session_error() != SessionError::kNone) {
2032 std::string error_message = GetSessionErrorMsg();
2033 RTC_LOG(LS_ERROR) << "SetRemoteDescription: " << error_message;
2034 observer->OnSetRemoteDescriptionComplete(
2035 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
2036 return;
2037 }
Steve Anton71439a62018-02-15 11:53:06 -08002038
Steve Anton80dd7b52018-02-16 17:08:42 -08002039 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_REMOTE);
Steve Anton71439a62018-02-15 11:53:06 -08002040 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08002041 std::string error_message = GetSetDescriptionErrorMessage(
2042 cricket::CS_REMOTE, desc->GetType(), error);
2043 RTC_LOG(LS_ERROR) << error_message;
Steve Anton71439a62018-02-15 11:53:06 -08002044 observer->OnSetRemoteDescriptionComplete(
2045 RTCError(error.type(), std::move(error_message)));
2046 return;
2047 }
Steve Anton71439a62018-02-15 11:53:06 -08002048
Steve Anton80dd7b52018-02-16 17:08:42 -08002049 // Grab the description type before moving ownership to
2050 // ApplyRemoteDescription, which may destroy it before returning.
2051 const SdpType type = desc->GetType();
2052
2053 error = ApplyRemoteDescription(std::move(desc));
2054 // |desc| may be destroyed at this point.
2055
2056 if (!error.ok()) {
2057 // If ApplyRemoteDescription fails, the PeerConnection could be in an
2058 // inconsistent state, so act conservatively here and set the session error
2059 // so that future calls to SetLocalDescription/SetRemoteDescription fail.
2060 SetSessionError(SessionError::kContent, error.message());
2061 std::string error_message =
2062 GetSetDescriptionErrorMessage(cricket::CS_REMOTE, type, error);
2063 RTC_LOG(LS_ERROR) << error_message;
2064 observer->OnSetRemoteDescriptionComplete(
2065 RTCError(error.type(), std::move(error_message)));
2066 return;
2067 }
2068 RTC_DCHECK(remote_description());
2069
2070 if (type == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002071 // TODO(deadbeef): We already had to hop to the network thread for
2072 // MaybeStartGathering...
2073 network_thread()->Invoke<void>(
2074 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
2075 port_allocator_.get()));
Harald Alvestrand5dbb5862018-02-13 23:48:00 +01002076 // Make UMA notes about what was agreed to.
2077 if (uma_observer_) {
2078 switch (remote_description()->description()->msid_signaling()) {
2079 case 0:
2080 uma_observer_->IncrementEnumCounter(kEnumCounterSdpSemanticNegotiated,
2081 kSdpSemanticNegotiatedNone,
2082 kSdpSemanticNegotiatedMax);
2083 break;
2084 case cricket::kMsidSignalingMediaSection:
2085 uma_observer_->IncrementEnumCounter(kEnumCounterSdpSemanticNegotiated,
2086 kSdpSemanticNegotiatedUnifiedPlan,
2087 kSdpSemanticNegotiatedMax);
2088 break;
2089 case cricket::kMsidSignalingSsrcAttribute:
2090 uma_observer_->IncrementEnumCounter(kEnumCounterSdpSemanticNegotiated,
2091 kSdpSemanticNegotiatedPlanB,
2092 kSdpSemanticNegotiatedMax);
2093 break;
2094 case cricket::kMsidSignalingMediaSection |
2095 cricket::kMsidSignalingSsrcAttribute:
2096 uma_observer_->IncrementEnumCounter(kEnumCounterSdpSemanticNegotiated,
2097 kSdpSemanticNegotiatedMixed,
2098 kSdpSemanticNegotiatedMax);
2099 break;
2100 default:
2101 RTC_NOTREACHED();
2102 }
2103 }
Steve Anton8a006912017-12-04 15:25:56 -08002104 }
2105
2106 observer->OnSetRemoteDescriptionComplete(RTCError::OK());
2107}
2108
2109RTCError PeerConnection::ApplyRemoteDescription(
2110 std::unique_ptr<SessionDescriptionInterface> desc) {
2111 RTC_DCHECK_RUN_ON(signaling_thread());
2112 RTC_DCHECK(desc);
2113
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002114 // Update stats here so that we have the most recent stats for tracks and
2115 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00002116 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 15:25:56 -08002117
Steve Antondcc3c022017-12-22 16:02:54 -08002118 // Take a reference to the old remote description since it's used below to
2119 // compare against the new remote description. When setting the new remote
2120 // description, grab ownership of the replaced session description in case it
2121 // is the same as |old_remote_description|, to keep it alive for the duration
2122 // of the method.
Steve Anton8a006912017-12-04 15:25:56 -08002123 const SessionDescriptionInterface* old_remote_description =
2124 remote_description();
Steve Anton8a006912017-12-04 15:25:56 -08002125 std::unique_ptr<SessionDescriptionInterface> replaced_remote_description;
Steve Anton3828c062017-12-06 10:34:51 -08002126 SdpType type = desc->GetType();
2127 if (type == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002128 replaced_remote_description = pending_remote_description_
2129 ? std::move(pending_remote_description_)
2130 : std::move(current_remote_description_);
2131 current_remote_description_ = std::move(desc);
2132 pending_remote_description_ = nullptr;
2133 current_local_description_ = std::move(pending_local_description_);
2134 } else {
2135 replaced_remote_description = std::move(pending_remote_description_);
2136 pending_remote_description_ = std::move(desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002137 }
Steve Anton8a006912017-12-04 15:25:56 -08002138 // The session description to apply now must be accessed by
2139 // |remote_description()|.
Henrik Boströmfdb92012017-11-09 19:55:44 +01002140 RTC_DCHECK(remote_description());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002141
Steve Anton8a006912017-12-04 15:25:56 -08002142 // Transport and Media channels will be created only when offer is set.
Steve Antondcc3c022017-12-22 16:02:54 -08002143 if (IsUnifiedPlan()) {
2144 RTCError error = UpdateTransceiversAndDataChannels(
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002145 cricket::CS_REMOTE, *remote_description(), local_description(),
2146 old_remote_description);
Steve Anton8a006912017-12-04 15:25:56 -08002147 if (!error.ok()) {
2148 return error;
2149 }
Steve Antondcc3c022017-12-22 16:02:54 -08002150 } else {
2151 if (type == SdpType::kOffer) {
2152 // TODO(bugs.webrtc.org/4676) - Handle CreateChannel failure, as new local
2153 // description is applied. Restore back to old description.
2154 RTCError error = CreateChannels(*remote_description()->description());
2155 if (!error.ok()) {
2156 return error;
2157 }
2158 }
Steve Anton8a006912017-12-04 15:25:56 -08002159
Steve Antondcc3c022017-12-22 16:02:54 -08002160 // Remove unused channels if MediaContentDescription is rejected.
2161 RemoveUnusedChannels(remote_description()->description());
2162 }
Steve Anton8a006912017-12-04 15:25:56 -08002163
2164 // NOTE: Candidates allocation will be initiated only when SetLocalDescription
2165 // is called.
Steve Anton80dd7b52018-02-16 17:08:42 -08002166 RTCError error = UpdateSessionState(type, cricket::CS_REMOTE);
Steve Anton8a006912017-12-04 15:25:56 -08002167 if (!error.ok()) {
2168 return error;
2169 }
2170
2171 if (local_description() &&
2172 !UseCandidatesInSessionDescription(remote_description())) {
2173 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidCandidates);
2174 }
2175
2176 if (old_remote_description) {
2177 for (const cricket::ContentInfo& content :
2178 old_remote_description->description()->contents()) {
2179 // Check if this new SessionDescription contains new ICE ufrag and
2180 // password that indicates the remote peer requests an ICE restart.
2181 // TODO(deadbeef): When we start storing both the current and pending
2182 // remote description, this should reset pending_ice_restarts and compare
2183 // against the current description.
2184 if (CheckForRemoteIceRestart(old_remote_description, remote_description(),
2185 content.name)) {
Steve Anton3828c062017-12-06 10:34:51 -08002186 if (type == SdpType::kOffer) {
Steve Anton8a006912017-12-04 15:25:56 -08002187 pending_ice_restarts_.insert(content.name);
2188 }
2189 } else {
2190 // We retain all received candidates only if ICE is not restarted.
2191 // When ICE is restarted, all previous candidates belong to an old
2192 // generation and should not be kept.
2193 // TODO(deadbeef): This goes against the W3C spec which says the remote
2194 // description should only contain candidates from the last set remote
2195 // description plus any candidates added since then. We should remove
2196 // this once we're sure it won't break anything.
2197 WebRtcSessionDescriptionFactory::CopyCandidatesFromSessionDescription(
2198 old_remote_description, content.name, mutable_remote_description());
2199 }
2200 }
2201 }
2202
2203 if (session_error() != SessionError::kNone) {
2204 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
2205 }
2206
2207 // Set the the ICE connection state to connecting since the connection may
2208 // become writable with peer reflexive candidates before any remote candidate
2209 // is signaled.
2210 // TODO(pthatcher): This is a short-term solution for crbug/446908. A real fix
2211 // is to have a new signal the indicates a change in checking state from the
2212 // transport and expose a new checking() member from transport that can be
2213 // read to determine the current checking state. The existing SignalConnecting
2214 // actually means "gathering candidates", so cannot be be used here.
Steve Antona3a92c22017-12-07 10:27:41 -08002215 if (remote_description()->GetType() != SdpType::kOffer &&
Steve Anton8a006912017-12-04 15:25:56 -08002216 ice_connection_state() == PeerConnectionInterface::kIceConnectionNew) {
2217 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
2218 }
2219
deadbeefab9b2d12015-10-14 11:33:11 -07002220 // If setting the description decided our SSL role, allocate any necessary
2221 // SCTP sids.
2222 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08002223 if (data_channel_type() == cricket::DCT_SCTP && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07002224 AllocateSctpSids(role);
2225 }
2226
Steve Antondcc3c022017-12-22 16:02:54 -08002227 if (IsUnifiedPlan()) {
Steve Anton8b815cd2018-02-16 16:14:42 -08002228 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
2229 receiving_transceivers;
Steve Antonc49bcd92018-02-14 14:28:13 -08002230 std::vector<rtc::scoped_refptr<MediaStreamInterface>> added_streams;
Steve Antondcc3c022017-12-22 16:02:54 -08002231 for (auto transceiver : transceivers_) {
2232 const ContentInfo* content =
2233 FindMediaSectionForTransceiver(transceiver, remote_description());
2234 if (!content) {
2235 continue;
2236 }
2237 const MediaContentDescription* media_desc = content->media_description();
2238 RtpTransceiverDirection local_direction =
2239 RtpTransceiverDirectionReversed(media_desc->direction());
2240 // From the WebRTC specification, steps 2.2.8.5/6 of section 4.4.1.6 "Set
2241 // the RTCSessionDescription: If direction is sendrecv or recvonly, and
2242 // transceiver's current direction is neither sendrecv nor recvonly,
2243 // process the addition of a remote track for the media description.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002244 //
2245 // Create a sync label in the case of an unsignalled msid.
2246 std::string sync_label = rtc::CreateRandomUuid();
2247 if (!media_desc->streams().empty()) {
2248 sync_label = media_desc->streams()[0].sync_label;
2249 }
Steve Antondcc3c022017-12-22 16:02:54 -08002250 if (RtpTransceiverDirectionHasRecv(local_direction) &&
2251 (!transceiver->current_direction() ||
2252 !RtpTransceiverDirectionHasRecv(
Seth Hampson2f0d7022018-02-20 11:54:42 -08002253 *transceiver->current_direction()))) {
Steve Antonef65ef12018-01-10 17:15:20 -08002254 rtc::scoped_refptr<MediaStreamInterface> stream =
2255 remote_streams_->find(sync_label);
2256 if (!stream) {
2257 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
2258 MediaStream::Create(sync_label));
2259 remote_streams_->AddStream(stream);
Steve Antonc49bcd92018-02-14 14:28:13 -08002260 added_streams.push_back(stream);
Steve Antonef65ef12018-01-10 17:15:20 -08002261 }
2262 transceiver->internal()->receiver_internal()->SetStreams({stream});
Steve Anton8b815cd2018-02-16 16:14:42 -08002263 receiving_transceivers.push_back(transceiver);
Steve Antondcc3c022017-12-22 16:02:54 -08002264 }
2265 // If direction is sendonly or inactive, and transceiver's current
2266 // direction is neither sendonly nor inactive, process the removal of a
2267 // remote track for the media description.
2268 if (!RtpTransceiverDirectionHasRecv(local_direction) &&
Steve Antonef65ef12018-01-10 17:15:20 -08002269 (transceiver->current_direction() &&
Steve Antondcc3c022017-12-22 16:02:54 -08002270 RtpTransceiverDirectionHasRecv(*transceiver->current_direction()))) {
Steve Antonef65ef12018-01-10 17:15:20 -08002271 transceiver->internal()->receiver_internal()->SetStreams({});
Steve Antondcc3c022017-12-22 16:02:54 -08002272 }
2273 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
2274 transceiver->internal()->set_current_direction(local_direction);
2275 }
2276 if (content->rejected && !transceiver->stopped()) {
2277 transceiver->Stop();
2278 }
Seth Hampson2f0d7022018-02-20 11:54:42 -08002279 if (!content->rejected &&
2280 RtpTransceiverDirectionHasRecv(local_direction)) {
2281 // Set ssrc to 0 in the case of an unsignalled ssrc.
2282 uint32_t ssrc = 0;
2283 if (!media_desc->streams().empty()) {
2284 ssrc = media_desc->streams()[0].first_ssrc();
2285 }
2286 transceiver->internal()->receiver_internal()->SetupMediaChannel(ssrc);
Steve Antond3679212018-01-17 17:41:02 -08002287 }
Steve Antondcc3c022017-12-22 16:02:54 -08002288 }
Steve Antonc49bcd92018-02-14 14:28:13 -08002289 // Once all processing has finished, fire off callbacks.
Steve Anton8b815cd2018-02-16 16:14:42 -08002290 for (auto transceiver : receiving_transceivers) {
Steve Anton6e221372018-02-20 12:59:16 -08002291 stats_->AddTrack(transceiver->receiver()->track());
Steve Anton8b815cd2018-02-16 16:14:42 -08002292 observer_->OnTrack(transceiver);
2293 observer_->OnAddTrack(transceiver->receiver(),
2294 transceiver->receiver()->streams());
Steve Antonef65ef12018-01-10 17:15:20 -08002295 }
Steve Antonc49bcd92018-02-14 14:28:13 -08002296 for (auto stream : added_streams) {
2297 observer_->OnAddStream(stream);
2298 }
Steve Antondcc3c022017-12-22 16:02:54 -08002299 }
2300
Henrik Boströmfdb92012017-11-09 19:55:44 +01002301 const cricket::ContentInfo* audio_content =
2302 GetFirstAudioContent(remote_description()->description());
2303 const cricket::ContentInfo* video_content =
2304 GetFirstVideoContent(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002305 const cricket::AudioContentDescription* audio_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002306 GetFirstAudioContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002307 const cricket::VideoContentDescription* video_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002308 GetFirstVideoContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002309 const cricket::DataContentDescription* data_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002310 GetFirstDataContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002311
2312 // Check if the descriptions include streams, just in case the peer supports
2313 // MSID, but doesn't indicate so with "a=msid-semantic".
Henrik Boströmfdb92012017-11-09 19:55:44 +01002314 if (remote_description()->description()->msid_supported() ||
deadbeefbda7e0b2015-12-08 17:13:40 -08002315 (audio_desc && !audio_desc->streams().empty()) ||
2316 (video_desc && !video_desc->streams().empty())) {
2317 remote_peer_supports_msid_ = true;
2318 }
deadbeefab9b2d12015-10-14 11:33:11 -07002319
2320 // We wait to signal new streams until we finish processing the description,
2321 // since only at that point will new streams have all their tracks.
2322 rtc::scoped_refptr<StreamCollection> new_streams(StreamCollection::Create());
2323
Steve Antondcc3c022017-12-22 16:02:54 -08002324 if (!IsUnifiedPlan()) {
2325 // TODO(steveanton): When removing RTP senders/receivers in response to a
2326 // rejected media section, there is some cleanup logic that expects the
2327 // voice/ video channel to still be set. But in this method the voice/video
2328 // channel would have been destroyed by the SetRemoteDescription caller
2329 // above so the cleanup that relies on them fails to run. The RemoveSenders
2330 // calls should be moved to right before the DestroyChannel calls to fix
2331 // this.
Steve Anton8d3444d2017-10-20 15:30:51 -07002332
Steve Antondcc3c022017-12-22 16:02:54 -08002333 // Find all audio rtp streams and create corresponding remote AudioTracks
2334 // and MediaStreams.
2335 if (audio_content) {
2336 if (audio_content->rejected) {
2337 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
2338 } else {
2339 bool default_audio_track_needed =
2340 !remote_peer_supports_msid_ &&
2341 RtpTransceiverDirectionHasSend(audio_desc->direction());
2342 UpdateRemoteSendersList(GetActiveStreams(audio_desc),
2343 default_audio_track_needed, audio_desc->type(),
2344 new_streams);
2345 }
deadbeeffaac4972015-11-12 15:33:07 -08002346 }
deadbeefab9b2d12015-10-14 11:33:11 -07002347
Steve Antondcc3c022017-12-22 16:02:54 -08002348 // Find all video rtp streams and create corresponding remote VideoTracks
2349 // and MediaStreams.
2350 if (video_content) {
2351 if (video_content->rejected) {
2352 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
2353 } else {
2354 bool default_video_track_needed =
2355 !remote_peer_supports_msid_ &&
2356 RtpTransceiverDirectionHasSend(video_desc->direction());
2357 UpdateRemoteSendersList(GetActiveStreams(video_desc),
2358 default_video_track_needed, video_desc->type(),
2359 new_streams);
2360 }
deadbeeffaac4972015-11-12 15:33:07 -08002361 }
deadbeefab9b2d12015-10-14 11:33:11 -07002362
Steve Antondcc3c022017-12-22 16:02:54 -08002363 // Update the DataChannels with the information from the remote peer.
2364 if (data_desc) {
2365 if (rtc::starts_with(data_desc->protocol().data(),
2366 cricket::kMediaProtocolRtpPrefix)) {
2367 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
2368 }
deadbeefab9b2d12015-10-14 11:33:11 -07002369 }
deadbeefab9b2d12015-10-14 11:33:11 -07002370
Steve Antondcc3c022017-12-22 16:02:54 -08002371 // Iterate new_streams and notify the observer about new MediaStreams.
2372 for (size_t i = 0; i < new_streams->count(); ++i) {
2373 MediaStreamInterface* new_stream = new_streams->at(i);
2374 stats_->AddStream(new_stream);
2375 observer_->OnAddStream(
2376 rtc::scoped_refptr<MediaStreamInterface>(new_stream));
2377 }
deadbeefab9b2d12015-10-14 11:33:11 -07002378
Steve Antondcc3c022017-12-22 16:02:54 -08002379 UpdateEndedRemoteMediaStreams();
2380 }
deadbeefab9b2d12015-10-14 11:33:11 -07002381
Steve Anton8a006912017-12-04 15:25:56 -08002382 return RTCError::OK();
deadbeeffc648b62015-10-13 16:42:33 -07002383}
2384
Steve Antondcc3c022017-12-22 16:02:54 -08002385RTCError PeerConnection::UpdateTransceiversAndDataChannels(
2386 cricket::ContentSource source,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002387 const SessionDescriptionInterface& new_session,
2388 const SessionDescriptionInterface* old_local_description,
2389 const SessionDescriptionInterface* old_remote_description) {
Steve Antondcc3c022017-12-22 16:02:54 -08002390 RTC_DCHECK(IsUnifiedPlan());
2391
Steve Anton7464fca2018-01-19 11:10:37 -08002392 const cricket::ContentGroup* bundle_group = nullptr;
2393 if (new_session.GetType() == SdpType::kOffer) {
2394 auto bundle_group_or_error =
2395 GetEarlyBundleGroup(*new_session.description());
2396 if (!bundle_group_or_error.ok()) {
2397 return bundle_group_or_error.MoveError();
2398 }
2399 bundle_group = bundle_group_or_error.MoveValue();
Steve Antondcc3c022017-12-22 16:02:54 -08002400 }
Steve Antondcc3c022017-12-22 16:02:54 -08002401
Steve Antondcc3c022017-12-22 16:02:54 -08002402 const ContentInfos& new_contents = new_session.description()->contents();
Steve Antondcc3c022017-12-22 16:02:54 -08002403 for (size_t i = 0; i < new_contents.size(); ++i) {
2404 const cricket::ContentInfo& new_content = new_contents[i];
Steve Antondcc3c022017-12-22 16:02:54 -08002405 cricket::MediaType media_type = new_content.media_description()->type();
2406 seen_mids_.insert(new_content.name);
2407 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
2408 media_type == cricket::MEDIA_TYPE_VIDEO) {
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002409 const cricket::ContentInfo* old_local_content = nullptr;
2410 if (old_local_description &&
2411 i < old_local_description->description()->contents().size()) {
2412 old_local_content =
2413 &old_local_description->description()->contents()[i];
2414 }
2415 const cricket::ContentInfo* old_remote_content = nullptr;
2416 if (old_remote_description &&
2417 i < old_remote_description->description()->contents().size()) {
2418 old_remote_content =
2419 &old_remote_description->description()->contents()[i];
2420 }
Steve Antondcc3c022017-12-22 16:02:54 -08002421 auto transceiver_or_error =
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002422 AssociateTransceiver(source, new_session.GetType(), i, new_content,
2423 old_local_content, old_remote_content);
Steve Antondcc3c022017-12-22 16:02:54 -08002424 if (!transceiver_or_error.ok()) {
2425 return transceiver_or_error.MoveError();
2426 }
2427 auto transceiver = transceiver_or_error.MoveValue();
Steve Antondcc3c022017-12-22 16:02:54 -08002428 RTCError error =
2429 UpdateTransceiverChannel(transceiver, new_content, bundle_group);
2430 if (!error.ok()) {
2431 return error;
2432 }
2433 } else if (media_type == cricket::MEDIA_TYPE_DATA) {
Steve Antonfa2260d2017-12-28 16:38:23 -08002434 if (GetDataMid() && new_content.name != *GetDataMid()) {
2435 // Ignore all but the first data section.
2436 continue;
2437 }
2438 RTCError error = UpdateDataChannel(source, new_content, bundle_group);
2439 if (!error.ok()) {
2440 return error;
2441 }
Steve Antondcc3c022017-12-22 16:02:54 -08002442 } else {
2443 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
2444 "Unknown section type.");
2445 }
2446 }
2447
2448 return RTCError::OK();
2449}
2450
2451RTCError PeerConnection::UpdateTransceiverChannel(
2452 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2453 transceiver,
2454 const cricket::ContentInfo& content,
2455 const cricket::ContentGroup* bundle_group) {
2456 RTC_DCHECK(IsUnifiedPlan());
2457 RTC_DCHECK(transceiver);
2458 cricket::BaseChannel* channel = transceiver->internal()->channel();
2459 if (content.rejected) {
2460 if (channel) {
2461 transceiver->internal()->SetChannel(nullptr);
2462 DestroyBaseChannel(channel);
2463 }
2464 } else {
2465 if (!channel) {
Steve Anton69470252018-02-09 11:43:08 -08002466 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Steve Antondcc3c022017-12-22 16:02:54 -08002467 channel = CreateVoiceChannel(
2468 content.name,
2469 GetTransportNameForMediaSection(content.name, bundle_group));
2470 } else {
Steve Anton69470252018-02-09 11:43:08 -08002471 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, transceiver->media_type());
Steve Antondcc3c022017-12-22 16:02:54 -08002472 channel = CreateVideoChannel(
2473 content.name,
2474 GetTransportNameForMediaSection(content.name, bundle_group));
2475 }
2476 if (!channel) {
2477 LOG_AND_RETURN_ERROR(
2478 RTCErrorType::INTERNAL_ERROR,
2479 "Failed to create channel for mid=" + content.name);
2480 }
2481 transceiver->internal()->SetChannel(channel);
2482 }
2483 }
2484 return RTCError::OK();
2485}
2486
Steve Antonfa2260d2017-12-28 16:38:23 -08002487RTCError PeerConnection::UpdateDataChannel(
2488 cricket::ContentSource source,
2489 const cricket::ContentInfo& content,
2490 const cricket::ContentGroup* bundle_group) {
2491 if (data_channel_type_ == cricket::DCT_NONE) {
Steve Antondbf9d032018-01-19 15:23:40 -08002492 // If data channels are disabled, ignore this media section. CreateAnswer
2493 // will take care of rejecting it.
2494 return RTCError::OK();
Steve Antonfa2260d2017-12-28 16:38:23 -08002495 }
2496 if (content.rejected) {
2497 DestroyDataChannel();
2498 } else {
2499 if (!rtp_data_channel_ && !sctp_transport_) {
2500 if (!CreateDataChannel(content.name, GetTransportNameForMediaSection(
2501 content.name, bundle_group))) {
2502 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
2503 "Failed to create data channel.");
2504 }
2505 }
2506 if (source == cricket::CS_REMOTE) {
2507 const MediaContentDescription* data_desc = content.media_description();
2508 if (data_desc && cricket::IsRtpProtocol(data_desc->protocol())) {
2509 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
2510 }
2511 }
2512 }
2513 return RTCError::OK();
2514}
2515
Steve Antondcc3c022017-12-22 16:02:54 -08002516RTCErrorOr<rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
2517PeerConnection::AssociateTransceiver(cricket::ContentSource source,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002518 SdpType type,
Steve Antondcc3c022017-12-22 16:02:54 -08002519 size_t mline_index,
2520 const ContentInfo& content,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002521 const ContentInfo* old_local_content,
2522 const ContentInfo* old_remote_content) {
Steve Antondcc3c022017-12-22 16:02:54 -08002523 RTC_DCHECK(IsUnifiedPlan());
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002524 // If this is an offer then the m= section might be recycled. If the m=
2525 // section is being recycled (defined as: rejected in the current local or
2526 // remote description and not rejected in new description), dissociate the
2527 // currently associated RtpTransceiver by setting its mid property to null,
2528 // and discard the mapping between the transceiver and its m= section index.
2529 if (IsMediaSectionBeingRecycled(type, content, old_local_content,
2530 old_remote_content)) {
2531 // We want to dissociate the transceiver that has the rejected mid.
2532 const std::string& old_mid =
2533 (old_local_content && old_local_content->rejected)
2534 ? old_local_content->name
2535 : old_remote_content->name;
2536 auto old_transceiver = GetAssociatedTransceiver(old_mid);
Steve Antondcc3c022017-12-22 16:02:54 -08002537 if (old_transceiver) {
2538 old_transceiver->internal()->set_mid(rtc::nullopt);
2539 old_transceiver->internal()->set_mline_index(rtc::nullopt);
2540 }
2541 }
2542 const MediaContentDescription* media_desc = content.media_description();
2543 auto transceiver = GetAssociatedTransceiver(content.name);
2544 if (source == cricket::CS_LOCAL) {
2545 // Find the RtpTransceiver that corresponds to this m= section, using the
2546 // mapping between transceivers and m= section indices established when
2547 // creating the offer.
2548 if (!transceiver) {
2549 transceiver = GetTransceiverByMLineIndex(mline_index);
2550 }
2551 if (!transceiver) {
2552 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2553 "Unknown transceiver");
2554 }
2555 } else {
2556 RTC_DCHECK_EQ(source, cricket::CS_REMOTE);
2557 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers
2558 // of the same type...
2559 if (!transceiver &&
2560 RtpTransceiverDirectionHasRecv(media_desc->direction())) {
2561 transceiver = FindAvailableTransceiverToReceive(media_desc->type());
2562 }
2563 // If no RtpTransceiver was found in the previous step, create one with a
2564 // recvonly direction.
2565 if (!transceiver) {
Steve Anton02ee47c2018-01-10 16:26:06 -08002566 auto sender =
2567 CreateSender(media_desc->type(), nullptr, {rtc::CreateRandomUuid()});
Steve Anton5f94aa22018-02-01 10:58:30 -08002568 std::string receiver_id;
2569 if (!media_desc->streams().empty()) {
2570 receiver_id = media_desc->streams()[0].id;
2571 } else {
2572 receiver_id = rtc::CreateRandomUuid();
2573 }
2574 auto receiver = CreateReceiver(media_desc->type(), receiver_id);
Steve Anton02ee47c2018-01-10 16:26:06 -08002575 transceiver = CreateAndAddTransceiver(sender, receiver);
Steve Antondcc3c022017-12-22 16:02:54 -08002576 transceiver->internal()->set_direction(
2577 RtpTransceiverDirection::kRecvOnly);
2578 }
2579 }
2580 RTC_DCHECK(transceiver);
Steve Anton69470252018-02-09 11:43:08 -08002581 if (transceiver->media_type() != media_desc->type()) {
Steve Antondcc3c022017-12-22 16:02:54 -08002582 LOG_AND_RETURN_ERROR(
2583 RTCErrorType::INVALID_PARAMETER,
2584 "Transceiver type does not match media description type.");
2585 }
2586 // Associate the found or created RtpTransceiver with the m= section by
2587 // setting the value of the RtpTransceiver's mid property to the MID of the m=
2588 // section, and establish a mapping between the transceiver and the index of
2589 // the m= section.
2590 transceiver->internal()->set_mid(content.name);
2591 transceiver->internal()->set_mline_index(mline_index);
2592 return std::move(transceiver);
2593}
2594
2595rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2596PeerConnection::GetAssociatedTransceiver(const std::string& mid) const {
2597 RTC_DCHECK(IsUnifiedPlan());
2598 for (auto transceiver : transceivers_) {
2599 if (transceiver->mid() == mid) {
2600 return transceiver;
2601 }
2602 }
2603 return nullptr;
2604}
2605
2606rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2607PeerConnection::GetTransceiverByMLineIndex(size_t mline_index) const {
2608 RTC_DCHECK(IsUnifiedPlan());
2609 for (auto transceiver : transceivers_) {
2610 if (transceiver->internal()->mline_index() == mline_index) {
2611 return transceiver;
2612 }
2613 }
2614 return nullptr;
2615}
2616
2617rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2618PeerConnection::FindAvailableTransceiverToReceive(
2619 cricket::MediaType media_type) const {
2620 RTC_DCHECK(IsUnifiedPlan());
2621 // From JSEP section 5.10 (Applying a Remote Description):
2622 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers of
2623 // the same type that were added to the PeerConnection by addTrack and are not
2624 // associated with any m= section and are not stopped, find the first such
2625 // RtpTransceiver.
2626 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08002627 if (transceiver->media_type() == media_type &&
Steve Antondcc3c022017-12-22 16:02:54 -08002628 transceiver->internal()->created_by_addtrack() && !transceiver->mid() &&
2629 !transceiver->stopped()) {
2630 return transceiver;
2631 }
2632 }
2633 return nullptr;
2634}
2635
Steve Antoned10bd92017-12-05 10:52:59 -08002636const cricket::ContentInfo* PeerConnection::FindMediaSectionForTransceiver(
2637 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2638 transceiver,
2639 const SessionDescriptionInterface* sdesc) const {
2640 RTC_DCHECK(transceiver);
2641 RTC_DCHECK(sdesc);
2642 if (IsUnifiedPlan()) {
2643 if (!transceiver->internal()->mid()) {
2644 // This transceiver is not associated with a media section yet.
2645 return nullptr;
2646 }
2647 return sdesc->description()->GetContentByName(
2648 *transceiver->internal()->mid());
2649 } else {
2650 // Plan B only allows at most one audio and one video section, so use the
2651 // first media section of that type.
2652 return cricket::GetFirstMediaContent(sdesc->description()->contents(),
Steve Anton69470252018-02-09 11:43:08 -08002653 transceiver->media_type());
Steve Antoned10bd92017-12-05 10:52:59 -08002654 }
2655}
2656
deadbeef46c73892016-11-16 19:42:04 -08002657PeerConnectionInterface::RTCConfiguration PeerConnection::GetConfiguration() {
2658 return configuration_;
2659}
2660
deadbeef293e9262017-01-11 12:28:30 -08002661bool PeerConnection::SetConfiguration(const RTCConfiguration& configuration,
2662 RTCError* error) {
Peter Boström1a9d6152015-12-08 22:15:17 +01002663 TRACE_EVENT0("webrtc", "PeerConnection::SetConfiguration");
deadbeef6de92f92016-12-12 18:49:32 -08002664
Steve Anton75737c02017-11-06 10:37:17 -08002665 if (local_description() && configuration.ice_candidate_pool_size !=
2666 configuration_.ice_candidate_pool_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002667 RTC_LOG(LS_ERROR) << "Can't change candidate pool size after calling "
2668 "SetLocalDescription.";
deadbeef293e9262017-01-11 12:28:30 -08002669 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00002670 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002671
deadbeef293e9262017-01-11 12:28:30 -08002672 // The simplest (and most future-compatible) way to tell if the config was
2673 // modified in an invalid way is to copy each property we do support
2674 // modifying, then use operator==. There are far more properties we don't
2675 // support modifying than those we do, and more could be added.
2676 RTCConfiguration modified_config = configuration_;
2677 modified_config.servers = configuration.servers;
2678 modified_config.type = configuration.type;
2679 modified_config.ice_candidate_pool_size =
2680 configuration.ice_candidate_pool_size;
2681 modified_config.prune_turn_ports = configuration.prune_turn_ports;
skvladd1f5fda2017-02-03 16:54:05 -08002682 modified_config.ice_check_min_interval = configuration.ice_check_min_interval;
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08002683 modified_config.stun_candidate_keepalive_interval =
2684 configuration.stun_candidate_keepalive_interval;
Jonas Orelandbdcee282017-10-10 14:01:40 +02002685 modified_config.turn_customizer = configuration.turn_customizer;
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08002686 modified_config.network_preference = configuration.network_preference;
deadbeef293e9262017-01-11 12:28:30 -08002687 if (configuration != modified_config) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002688 RTC_LOG(LS_ERROR) << "Modifying the configuration in an unsupported way.";
deadbeef293e9262017-01-11 12:28:30 -08002689 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
2690 }
2691
Steve Anton038834f2017-07-14 15:59:59 -07002692 // Validate the modified configuration.
2693 RTCError validate_error = ValidateConfiguration(modified_config);
2694 if (!validate_error.ok()) {
2695 return SafeSetError(std::move(validate_error), error);
2696 }
2697
deadbeef293e9262017-01-11 12:28:30 -08002698 // Note that this isn't possible through chromium, since it's an unsigned
2699 // short in WebIDL.
2700 if (configuration.ice_candidate_pool_size < 0 ||
2701 configuration.ice_candidate_pool_size > UINT16_MAX) {
2702 return SafeSetError(RTCErrorType::INVALID_RANGE, error);
2703 }
2704
2705 // Parse ICE servers before hopping to network thread.
2706 cricket::ServerAddresses stun_servers;
2707 std::vector<cricket::RelayServerConfig> turn_servers;
2708 RTCErrorType parse_error =
2709 ParseIceServers(configuration.servers, &stun_servers, &turn_servers);
2710 if (parse_error != RTCErrorType::NONE) {
2711 return SafeSetError(parse_error, error);
2712 }
2713
2714 // In theory this shouldn't fail.
2715 if (!network_thread()->Invoke<bool>(
2716 RTC_FROM_HERE,
2717 rtc::Bind(&PeerConnection::ReconfigurePortAllocator_n, this,
2718 stun_servers, turn_servers, modified_config.type,
2719 modified_config.ice_candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02002720 modified_config.prune_turn_ports,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08002721 modified_config.turn_customizer,
2722 modified_config.stun_candidate_keepalive_interval))) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002723 RTC_LOG(LS_ERROR) << "Failed to apply configuration to PortAllocator.";
deadbeef293e9262017-01-11 12:28:30 -08002724 return SafeSetError(RTCErrorType::INTERNAL_ERROR, error);
2725 }
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07002726
deadbeefd1a38b52016-12-10 13:15:33 -08002727 // As described in JSEP, calling setConfiguration with new ICE servers or
2728 // candidate policy must set a "needs-ice-restart" bit so that the next offer
2729 // triggers an ICE restart which will pick up the changes.
deadbeef293e9262017-01-11 12:28:30 -08002730 if (modified_config.servers != configuration_.servers ||
2731 modified_config.type != configuration_.type ||
2732 modified_config.prune_turn_ports != configuration_.prune_turn_ports) {
Steve Antond25da372017-11-06 14:50:29 -08002733 transport_controller_->SetNeedsIceRestartFlag();
deadbeefd1a38b52016-12-10 13:15:33 -08002734 }
skvladd1f5fda2017-02-03 16:54:05 -08002735
Qingsi Wang9c98f0c2018-02-15 15:10:59 -08002736 transport_controller_->SetIceConfig(ParseIceConfig(modified_config));
skvladd1f5fda2017-02-03 16:54:05 -08002737
deadbeef293e9262017-01-11 12:28:30 -08002738 configuration_ = modified_config;
2739 return SafeSetError(RTCErrorType::NONE, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00002740}
2741
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002742bool PeerConnection::AddIceCandidate(
2743 const IceCandidateInterface* ice_candidate) {
Peter Boström1a9d6152015-12-08 22:15:17 +01002744 TRACE_EVENT0("webrtc", "PeerConnection::AddIceCandidate");
zhihuang29ff8442016-07-27 11:07:25 -07002745 if (IsClosed()) {
2746 return false;
2747 }
Steve Antond25da372017-11-06 14:50:29 -08002748
2749 if (!remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002750 RTC_LOG(LS_ERROR) << "ProcessIceMessage: ICE candidates can't be added "
Jonas Olsson45cc8902018-02-13 10:37:07 +01002751 "without any remote session description.";
Steve Antond25da372017-11-06 14:50:29 -08002752 return false;
2753 }
2754
2755 if (!ice_candidate) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002756 RTC_LOG(LS_ERROR) << "ProcessIceMessage: Candidate is NULL.";
Steve Antond25da372017-11-06 14:50:29 -08002757 return false;
2758 }
2759
2760 bool valid = false;
2761 bool ready = ReadyToUseRemoteCandidate(ice_candidate, nullptr, &valid);
2762 if (!valid) {
2763 return false;
2764 }
2765
2766 // Add this candidate to the remote session description.
2767 if (!mutable_remote_description()->AddCandidate(ice_candidate)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002768 RTC_LOG(LS_ERROR) << "ProcessIceMessage: Candidate cannot be used.";
Steve Antond25da372017-11-06 14:50:29 -08002769 return false;
2770 }
2771
2772 if (ready) {
2773 return UseCandidate(ice_candidate);
2774 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002775 RTC_LOG(LS_INFO) << "ProcessIceMessage: Not ready to use candidate.";
Steve Antond25da372017-11-06 14:50:29 -08002776 return true;
2777 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002778}
2779
Honghai Zhang7fb69db2016-03-14 11:59:18 -07002780bool PeerConnection::RemoveIceCandidates(
2781 const std::vector<cricket::Candidate>& candidates) {
2782 TRACE_EVENT0("webrtc", "PeerConnection::RemoveIceCandidates");
Steve Antond25da372017-11-06 14:50:29 -08002783 if (!remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002784 RTC_LOG(LS_ERROR) << "RemoveRemoteIceCandidates: ICE candidates can't be "
Jonas Olsson45cc8902018-02-13 10:37:07 +01002785 "removed without any remote session description.";
Steve Antond25da372017-11-06 14:50:29 -08002786 return false;
2787 }
2788
2789 if (candidates.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002790 RTC_LOG(LS_ERROR) << "RemoveRemoteIceCandidates: candidates are empty.";
Steve Antond25da372017-11-06 14:50:29 -08002791 return false;
2792 }
2793
2794 size_t number_removed =
2795 mutable_remote_description()->RemoveCandidates(candidates);
2796 if (number_removed != candidates.size()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002797 RTC_LOG(LS_ERROR)
2798 << "RemoveRemoteIceCandidates: Failed to remove candidates. "
Jonas Olsson45cc8902018-02-13 10:37:07 +01002799 "Requested "
2800 << candidates.size() << " but only " << number_removed
Mirko Bonadei675513b2017-11-09 11:09:25 +01002801 << " are removed.";
Steve Antond25da372017-11-06 14:50:29 -08002802 }
2803
2804 // Remove the candidates from the transport controller.
2805 std::string error;
2806 bool res = transport_controller_->RemoveRemoteCandidates(candidates, &error);
2807 if (!res && !error.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002808 RTC_LOG(LS_ERROR) << "Error when removing remote candidates: " << error;
Steve Antond25da372017-11-06 14:50:29 -08002809 }
2810 return true;
Honghai Zhang7fb69db2016-03-14 11:59:18 -07002811}
2812
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00002813void PeerConnection::RegisterUMAObserver(UMAObserver* observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +01002814 TRACE_EVENT0("webrtc", "PeerConnection::RegisterUmaObserver");
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00002815 uma_observer_ = observer;
guoweis@webrtc.org7169afd2014-12-04 17:59:29 +00002816
Steve Anton75737c02017-11-06 10:37:17 -08002817 if (transport_controller()) {
2818 transport_controller()->SetMetricsObserver(uma_observer_);
guoweis@webrtc.org7169afd2014-12-04 17:59:29 +00002819 }
2820
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00002821 // Send information about IPv4/IPv6 status.
deadbeef293e9262017-01-11 12:28:30 -08002822 if (uma_observer_) {
Honghai Zhangd93f50c2016-10-05 11:47:22 -07002823 port_allocator_->SetMetricsObserver(uma_observer_);
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00002824 if (port_allocator_->flags() & cricket::PORTALLOCATOR_ENABLE_IPV6) {
Guo-wei Shiehdfbe6792015-09-03 17:12:07 -07002825 uma_observer_->IncrementEnumCounter(
2826 kEnumCounterAddressFamily, kPeerConnection_IPv6,
2827 kPeerConnectionAddressFamilyCounter_Max);
mallinath@webrtc.orgb445f262014-05-23 22:19:37 +00002828 } else {
Guo-wei Shiehdfbe6792015-09-03 17:12:07 -07002829 uma_observer_->IncrementEnumCounter(
2830 kEnumCounterAddressFamily, kPeerConnection_IPv4,
2831 kPeerConnectionAddressFamilyCounter_Max);
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00002832 }
Harald Alvestrand5dbb5862018-02-13 23:48:00 +01002833 // Send information about the requested SDP semantics.
2834 switch (configuration_.sdp_semantics) {
2835 case SdpSemantics::kDefault:
2836 uma_observer_->IncrementEnumCounter(kEnumCounterSdpSemanticRequested,
2837 kSdpSemanticRequestDefault,
2838 kSdpSemanticRequestMax);
2839
2840 break;
2841 case SdpSemantics::kPlanB:
2842 uma_observer_->IncrementEnumCounter(kEnumCounterSdpSemanticRequested,
2843 kSdpSemanticRequestPlanB,
2844 kSdpSemanticRequestMax);
2845 break;
2846 case SdpSemantics::kUnifiedPlan:
2847 uma_observer_->IncrementEnumCounter(kEnumCounterSdpSemanticRequested,
2848 kSdpSemanticRequestUnifiedPlan,
2849 kSdpSemanticRequestMax);
2850 break;
2851 default:
2852 RTC_NOTREACHED();
2853 }
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00002854 }
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00002855}
2856
zstein4b979802017-06-02 14:37:37 -07002857RTCError PeerConnection::SetBitrate(const BitrateParameters& bitrate) {
Steve Anton978b8762017-09-29 12:15:02 -07002858 if (!worker_thread()->IsCurrent()) {
2859 return worker_thread()->Invoke<RTCError>(
zstein4b979802017-06-02 14:37:37 -07002860 RTC_FROM_HERE, rtc::Bind(&PeerConnection::SetBitrate, this, bitrate));
2861 }
2862
2863 const bool has_min = static_cast<bool>(bitrate.min_bitrate_bps);
2864 const bool has_current = static_cast<bool>(bitrate.current_bitrate_bps);
2865 const bool has_max = static_cast<bool>(bitrate.max_bitrate_bps);
2866 if (has_min && *bitrate.min_bitrate_bps < 0) {
2867 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2868 "min_bitrate_bps <= 0");
2869 }
2870 if (has_current) {
2871 if (has_min && *bitrate.current_bitrate_bps < *bitrate.min_bitrate_bps) {
2872 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2873 "current_bitrate_bps < min_bitrate_bps");
2874 } else if (*bitrate.current_bitrate_bps < 0) {
2875 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2876 "curent_bitrate_bps < 0");
2877 }
2878 }
2879 if (has_max) {
2880 if (has_current &&
2881 *bitrate.max_bitrate_bps < *bitrate.current_bitrate_bps) {
2882 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2883 "max_bitrate_bps < current_bitrate_bps");
2884 } else if (has_min && *bitrate.max_bitrate_bps < *bitrate.min_bitrate_bps) {
2885 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2886 "max_bitrate_bps < min_bitrate_bps");
2887 } else if (*bitrate.max_bitrate_bps < 0) {
2888 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2889 "max_bitrate_bps < 0");
2890 }
2891 }
2892
Sebastian Janssonfc8d26b2018-02-21 09:52:06 +01002893 BitrateConstraintsMask mask;
zstein4b979802017-06-02 14:37:37 -07002894 mask.min_bitrate_bps = bitrate.min_bitrate_bps;
2895 mask.start_bitrate_bps = bitrate.current_bitrate_bps;
2896 mask.max_bitrate_bps = bitrate.max_bitrate_bps;
2897
2898 RTC_DCHECK(call_.get());
Sebastian Jansson8f83b422018-02-21 13:07:13 +01002899 call_->GetTransportControllerSend()->SetClientBitratePreferences(mask);
zstein4b979802017-06-02 14:37:37 -07002900
2901 return RTCError::OK();
2902}
2903
Alex Narest78609d52017-10-20 10:37:47 +02002904void PeerConnection::SetBitrateAllocationStrategy(
2905 std::unique_ptr<rtc::BitrateAllocationStrategy>
2906 bitrate_allocation_strategy) {
2907 rtc::Thread* worker_thread = factory_->worker_thread();
2908 if (!worker_thread->IsCurrent()) {
2909 rtc::BitrateAllocationStrategy* strategy_raw =
2910 bitrate_allocation_strategy.release();
2911 auto functor = [this, strategy_raw]() {
2912 call_->SetBitrateAllocationStrategy(
2913 rtc::WrapUnique<rtc::BitrateAllocationStrategy>(strategy_raw));
2914 };
2915 worker_thread->Invoke<void>(RTC_FROM_HERE, functor);
2916 return;
2917 }
2918 RTC_DCHECK(call_.get());
2919 call_->SetBitrateAllocationStrategy(std::move(bitrate_allocation_strategy));
2920}
2921
henrika5f6bf242017-11-01 11:06:56 +01002922void PeerConnection::SetAudioPlayout(bool playout) {
2923 if (!worker_thread()->IsCurrent()) {
2924 worker_thread()->Invoke<void>(
2925 RTC_FROM_HERE,
2926 rtc::Bind(&PeerConnection::SetAudioPlayout, this, playout));
2927 return;
2928 }
2929 auto audio_state =
2930 factory_->channel_manager()->media_engine()->GetAudioState();
2931 audio_state->SetPlayout(playout);
2932}
2933
2934void PeerConnection::SetAudioRecording(bool recording) {
2935 if (!worker_thread()->IsCurrent()) {
2936 worker_thread()->Invoke<void>(
2937 RTC_FROM_HERE,
2938 rtc::Bind(&PeerConnection::SetAudioRecording, this, recording));
2939 return;
2940 }
2941 auto audio_state =
2942 factory_->channel_manager()->media_engine()->GetAudioState();
2943 audio_state->SetRecording(recording);
2944}
2945
Steve Anton8c0f7a72017-10-03 10:03:10 -07002946std::unique_ptr<rtc::SSLCertificate>
2947PeerConnection::GetRemoteAudioSSLCertificate() {
Taylor Brandstetterc3928662018-02-23 13:04:51 -08002948 std::unique_ptr<rtc::SSLCertChain> chain = GetRemoteAudioSSLCertChain();
2949 if (!chain || !chain->GetSize()) {
Steve Anton8c0f7a72017-10-03 10:03:10 -07002950 return nullptr;
2951 }
Taylor Brandstetterc3928662018-02-23 13:04:51 -08002952 return chain->Get(0).GetUniqueReference();
Steve Anton8c0f7a72017-10-03 10:03:10 -07002953}
2954
Zhi Huang70b820f2018-01-27 14:16:15 -08002955std::unique_ptr<rtc::SSLCertChain>
2956PeerConnection::GetRemoteAudioSSLCertChain() {
Steve Antonafb0bb72018-02-20 11:35:37 -08002957 auto audio_transceiver = GetFirstAudioTransceiver();
2958 if (!audio_transceiver || !audio_transceiver->internal()->channel()) {
Zhi Huang70b820f2018-01-27 14:16:15 -08002959 return nullptr;
2960 }
Zhi Huang70b820f2018-01-27 14:16:15 -08002961 return transport_controller_->GetRemoteSSLCertChain(
Steve Antonafb0bb72018-02-20 11:35:37 -08002962 audio_transceiver->internal()->channel()->transport_name());
2963}
2964
2965rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2966PeerConnection::GetFirstAudioTransceiver() const {
2967 for (auto transceiver : transceivers_) {
2968 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
2969 return transceiver;
2970 }
2971 }
2972 return nullptr;
Zhi Huang70b820f2018-01-27 14:16:15 -08002973}
2974
ivoc14d5dbe2016-07-04 07:06:55 -07002975bool PeerConnection::StartRtcEventLog(rtc::PlatformFile file,
2976 int64_t max_size_bytes) {
Elad Alon99c3fe52017-10-13 16:29:40 +02002977 // TODO(eladalon): It would be better to not allow negative values into PC.
2978 const size_t max_size = (max_size_bytes < 0)
2979 ? RtcEventLog::kUnlimitedOutput
2980 : rtc::saturated_cast<size_t>(max_size_bytes);
2981 return StartRtcEventLog(
Bjorn Tereliusde939432017-11-20 17:38:14 +01002982 rtc::MakeUnique<RtcEventLogOutputFile>(file, max_size),
2983 webrtc::RtcEventLog::kImmediateOutput);
Elad Alon99c3fe52017-10-13 16:29:40 +02002984}
2985
Bjorn Tereliusde939432017-11-20 17:38:14 +01002986bool PeerConnection::StartRtcEventLog(std::unique_ptr<RtcEventLogOutput> output,
2987 int64_t output_period_ms) {
Karl Wibergd6b48192017-10-16 23:01:06 +02002988 // TODO(eladalon): In C++14, this can be done with a lambda.
2989 struct Functor {
Bjorn Tereliusde939432017-11-20 17:38:14 +01002990 bool operator()() {
2991 return pc->StartRtcEventLog_w(std::move(output), output_period_ms);
2992 }
Karl Wibergd6b48192017-10-16 23:01:06 +02002993 PeerConnection* const pc;
2994 std::unique_ptr<RtcEventLogOutput> output;
Bjorn Tereliusde939432017-11-20 17:38:14 +01002995 const int64_t output_period_ms;
Elad Alon99c3fe52017-10-13 16:29:40 +02002996 };
Bjorn Tereliusde939432017-11-20 17:38:14 +01002997 return worker_thread()->Invoke<bool>(
2998 RTC_FROM_HERE, Functor{this, std::move(output), output_period_ms});
ivoc14d5dbe2016-07-04 07:06:55 -07002999}
3000
3001void PeerConnection::StopRtcEventLog() {
Steve Anton978b8762017-09-29 12:15:02 -07003002 worker_thread()->Invoke<void>(
ivoc14d5dbe2016-07-04 07:06:55 -07003003 RTC_FROM_HERE, rtc::Bind(&PeerConnection::StopRtcEventLog_w, this));
3004}
3005
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003006const SessionDescriptionInterface* PeerConnection::local_description() const {
Steve Anton75737c02017-11-06 10:37:17 -08003007 return pending_local_description_ ? pending_local_description_.get()
3008 : current_local_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003009}
3010
3011const SessionDescriptionInterface* PeerConnection::remote_description() const {
Steve Anton75737c02017-11-06 10:37:17 -08003012 return pending_remote_description_ ? pending_remote_description_.get()
3013 : current_remote_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003014}
3015
deadbeeffe4a8a42016-12-20 17:56:17 -08003016const SessionDescriptionInterface* PeerConnection::current_local_description()
3017 const {
Steve Anton75737c02017-11-06 10:37:17 -08003018 return current_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003019}
3020
3021const SessionDescriptionInterface* PeerConnection::current_remote_description()
3022 const {
Steve Anton75737c02017-11-06 10:37:17 -08003023 return current_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003024}
3025
3026const SessionDescriptionInterface* PeerConnection::pending_local_description()
3027 const {
Steve Anton75737c02017-11-06 10:37:17 -08003028 return pending_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003029}
3030
3031const SessionDescriptionInterface* PeerConnection::pending_remote_description()
3032 const {
Steve Anton75737c02017-11-06 10:37:17 -08003033 return pending_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003034}
3035
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003036void PeerConnection::Close() {
Peter Boström1a9d6152015-12-08 22:15:17 +01003037 TRACE_EVENT0("webrtc", "PeerConnection::Close");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003038 // Update stats here so that we have the most recent stats for tracks and
3039 // streams before the channels are closed.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00003040 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003041
Steve Anton75737c02017-11-06 10:37:17 -08003042 ChangeSignalingState(PeerConnectionInterface::kClosed);
Steve Anton3fe1b152017-12-12 10:20:08 -08003043
Steve Anton8af21862017-12-15 11:20:13 -08003044 for (auto transceiver : transceivers_) {
3045 transceiver->Stop();
3046 }
3047 DestroyAllChannels();
Steve Anton75737c02017-11-06 10:37:17 -08003048
Qingsi Wang93a84392018-01-30 17:13:09 -08003049 // The event log is used in the transport controller, which must be outlived
3050 // by the former. CreateOffer by the peer connection is implemented
3051 // asynchronously and if the peer connection is closed without resetting the
3052 // WebRTC session description factory, the session description factory would
3053 // call the transport controller.
3054 webrtc_session_desc_factory_.reset();
3055 transport_controller_.reset();
3056
deadbeef42a42632017-03-10 15:18:00 -08003057 network_thread()->Invoke<void>(
3058 RTC_FROM_HERE,
3059 rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
3060 port_allocator_.get()));
nisseeaabdf62017-05-05 02:23:02 -07003061
Steve Anton978b8762017-09-29 12:15:02 -07003062 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
eladalon248fd4f2017-09-06 05:18:15 -07003063 call_.reset();
3064 // The event log must outlive call (and any other object that uses it).
3065 event_log_.reset();
3066 });
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003067}
3068
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003069void PeerConnection::OnMessage(rtc::Message* msg) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003070 switch (msg->message_id) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003071 case MSG_SET_SESSIONDESCRIPTION_SUCCESS: {
3072 SetSessionDescriptionMsg* param =
3073 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
3074 param->observer->OnSuccess();
3075 delete param;
3076 break;
3077 }
3078 case MSG_SET_SESSIONDESCRIPTION_FAILED: {
3079 SetSessionDescriptionMsg* param =
3080 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
3081 param->observer->OnFailure(param->error);
3082 delete param;
3083 break;
3084 }
deadbeefab9b2d12015-10-14 11:33:11 -07003085 case MSG_CREATE_SESSIONDESCRIPTION_FAILED: {
3086 CreateSessionDescriptionMsg* param =
3087 static_cast<CreateSessionDescriptionMsg*>(msg->pdata);
3088 param->observer->OnFailure(param->error);
3089 delete param;
3090 break;
3091 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003092 case MSG_GETSTATS: {
3093 GetStatsMsg* param = static_cast<GetStatsMsg*>(msg->pdata);
nissee8abe3e2017-01-18 05:00:34 -08003094 StatsReports reports;
3095 stats_->GetStats(param->track, &reports);
3096 param->observer->OnComplete(reports);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003097 delete param;
3098 break;
3099 }
deadbeefbd292462015-12-14 18:15:29 -08003100 case MSG_FREE_DATACHANNELS: {
3101 sctp_data_channels_to_free_.clear();
3102 break;
3103 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003104 default:
nisseeb4ca4e2017-01-12 02:24:27 -08003105 RTC_NOTREACHED() << "Not implemented";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003106 break;
3107 }
3108}
3109
Steve Antonafb0bb72018-02-20 11:35:37 -08003110cricket::VoiceMediaChannel* PeerConnection::voice_media_channel() const {
3111 RTC_DCHECK(!IsUnifiedPlan());
3112 auto* voice_channel = static_cast<cricket::VoiceChannel*>(
3113 GetAudioTransceiver()->internal()->channel());
3114 if (voice_channel) {
3115 return voice_channel->media_channel();
3116 } else {
3117 return nullptr;
3118 }
3119}
3120
3121cricket::VideoMediaChannel* PeerConnection::video_media_channel() const {
3122 RTC_DCHECK(!IsUnifiedPlan());
3123 auto* video_channel = static_cast<cricket::VideoChannel*>(
3124 GetVideoTransceiver()->internal()->channel());
3125 if (video_channel) {
3126 return video_channel->media_channel();
3127 } else {
3128 return nullptr;
3129 }
3130}
3131
Steve Anton4171afb2017-11-20 10:20:22 -08003132void PeerConnection::CreateAudioReceiver(
3133 MediaStreamInterface* stream,
3134 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01003135 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
3136 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Steve Antond3679212018-01-17 17:41:02 -08003137 auto* audio_receiver = new AudioRtpReceiver(
3138 worker_thread(), remote_sender_info.sender_id, streams);
Steve Anton57858b32018-02-15 15:19:50 -08003139 audio_receiver->SetVoiceMediaChannel(voice_media_channel());
Steve Antond3679212018-01-17 17:41:02 -08003140 audio_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
3141 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
3142 signaling_thread(), audio_receiver);
Steve Anton4171afb2017-11-20 10:20:22 -08003143 GetAudioTransceiver()->internal()->AddReceiver(receiver);
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01003144 observer_->OnAddTrack(receiver, std::move(streams));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003145}
3146
Steve Anton4171afb2017-11-20 10:20:22 -08003147void PeerConnection::CreateVideoReceiver(
3148 MediaStreamInterface* stream,
3149 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01003150 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
3151 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Steve Antond3679212018-01-17 17:41:02 -08003152 auto* video_receiver = new VideoRtpReceiver(
3153 worker_thread(), remote_sender_info.sender_id, streams);
Steve Anton57858b32018-02-15 15:19:50 -08003154 video_receiver->SetVideoMediaChannel(video_media_channel());
Steve Antond3679212018-01-17 17:41:02 -08003155 video_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
3156 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
3157 signaling_thread(), video_receiver);
Steve Anton4171afb2017-11-20 10:20:22 -08003158 GetVideoTransceiver()->internal()->AddReceiver(receiver);
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01003159 observer_->OnAddTrack(receiver, std::move(streams));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003160}
3161
deadbeef70ab1a12015-09-28 16:53:55 -07003162// TODO(deadbeef): Keep RtpReceivers around even if track goes away in remote
3163// description.
Henrik Boström933d8b02017-10-10 10:05:16 -07003164rtc::scoped_refptr<RtpReceiverInterface> PeerConnection::RemoveAndStopReceiver(
Steve Anton4171afb2017-11-20 10:20:22 -08003165 const RtpSenderInfo& remote_sender_info) {
3166 auto receiver = FindReceiverById(remote_sender_info.sender_id);
3167 if (!receiver) {
3168 RTC_LOG(LS_WARNING) << "RtpReceiver for track with id "
3169 << remote_sender_info.sender_id << " doesn't exist.";
Henrik Boström933d8b02017-10-10 10:05:16 -07003170 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07003171 }
Steve Anton4171afb2017-11-20 10:20:22 -08003172 if (receiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
3173 GetAudioTransceiver()->internal()->RemoveReceiver(receiver);
3174 } else {
3175 GetVideoTransceiver()->internal()->RemoveReceiver(receiver);
3176 }
Henrik Boström933d8b02017-10-10 10:05:16 -07003177 return receiver;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003178}
3179
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003180void PeerConnection::AddAudioTrack(AudioTrackInterface* track,
3181 MediaStreamInterface* stream) {
3182 RTC_DCHECK(!IsClosed());
3183 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003184 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003185 // We already have a sender for this track, so just change the stream_id
3186 // so that it's correct in the next call to CreateOffer.
Steve Anton4171afb2017-11-20 10:20:22 -08003187 sender->internal()->set_stream_id(stream->label());
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003188 return;
3189 }
3190
3191 // Normal case; we've never seen this track before.
Steve Anton02ee47c2018-01-10 16:26:06 -08003192 auto new_sender =
3193 CreateSender(cricket::MEDIA_TYPE_AUDIO, track, {stream->label()});
Steve Anton57858b32018-02-15 15:19:50 -08003194 new_sender->internal()->SetVoiceMediaChannel(voice_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08003195 GetAudioTransceiver()->internal()->AddSender(new_sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003196 // If the sender has already been configured in SDP, we call SetSsrc,
3197 // which will connect the sender to the underlying transport. This can
3198 // occur if a local session description that contains the ID of the sender
3199 // is set before AddStream is called. It can also occur if the local
3200 // session description is not changed and RemoveStream is called, and
3201 // later AddStream is called again with the same stream.
Steve Anton4171afb2017-11-20 10:20:22 -08003202 const RtpSenderInfo* sender_info =
3203 FindSenderInfo(local_audio_sender_infos_, stream->label(), track->id());
3204 if (sender_info) {
3205 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003206 }
3207}
3208
3209// TODO(deadbeef): Don't destroy RtpSenders here; they should be kept around
3210// indefinitely, when we have unified plan SDP.
3211void PeerConnection::RemoveAudioTrack(AudioTrackInterface* track,
3212 MediaStreamInterface* stream) {
3213 RTC_DCHECK(!IsClosed());
3214 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003215 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003216 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
3217 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003218 return;
3219 }
Steve Anton4171afb2017-11-20 10:20:22 -08003220 GetAudioTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003221}
3222
3223void PeerConnection::AddVideoTrack(VideoTrackInterface* track,
3224 MediaStreamInterface* stream) {
3225 RTC_DCHECK(!IsClosed());
3226 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003227 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003228 // We already have a sender for this track, so just change the stream_id
3229 // so that it's correct in the next call to CreateOffer.
Steve Anton4171afb2017-11-20 10:20:22 -08003230 sender->internal()->set_stream_id(stream->label());
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003231 return;
3232 }
3233
3234 // Normal case; we've never seen this track before.
Steve Anton02ee47c2018-01-10 16:26:06 -08003235 auto new_sender =
3236 CreateSender(cricket::MEDIA_TYPE_VIDEO, track, {stream->label()});
Steve Anton57858b32018-02-15 15:19:50 -08003237 new_sender->internal()->SetVideoMediaChannel(video_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08003238 GetVideoTransceiver()->internal()->AddSender(new_sender);
3239 const RtpSenderInfo* sender_info =
3240 FindSenderInfo(local_video_sender_infos_, stream->label(), track->id());
3241 if (sender_info) {
3242 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003243 }
3244}
3245
3246void PeerConnection::RemoveVideoTrack(VideoTrackInterface* track,
3247 MediaStreamInterface* stream) {
3248 RTC_DCHECK(!IsClosed());
3249 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003250 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003251 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
3252 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003253 return;
3254 }
Steve Anton4171afb2017-11-20 10:20:22 -08003255 GetVideoTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003256}
3257
Steve Antonba818672017-11-06 10:21:57 -08003258void PeerConnection::SetIceConnectionState(IceConnectionState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07003259 RTC_DCHECK(signaling_thread()->IsCurrent());
Steve Antonba818672017-11-06 10:21:57 -08003260 if (ice_connection_state_ == new_state) {
3261 return;
3262 }
3263
deadbeefcbecd352015-09-23 11:50:27 -07003264 // After transitioning to "closed", ignore any additional states from
Steve Antonba818672017-11-06 10:21:57 -08003265 // TransportController (such as "disconnected").
deadbeefab9b2d12015-10-14 11:33:11 -07003266 if (IsClosed()) {
deadbeefcbecd352015-09-23 11:50:27 -07003267 return;
3268 }
Steve Antonba818672017-11-06 10:21:57 -08003269
Mirko Bonadei675513b2017-11-09 11:09:25 +01003270 RTC_LOG(LS_INFO) << "Changing IceConnectionState " << ice_connection_state_
3271 << " => " << new_state;
Steve Antonba818672017-11-06 10:21:57 -08003272 RTC_DCHECK(ice_connection_state_ !=
3273 PeerConnectionInterface::kIceConnectionClosed);
3274
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003275 ice_connection_state_ = new_state;
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00003276 observer_->OnIceConnectionChange(ice_connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003277}
3278
3279void PeerConnection::OnIceGatheringChange(
3280 PeerConnectionInterface::IceGatheringState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07003281 RTC_DCHECK(signaling_thread()->IsCurrent());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003282 if (IsClosed()) {
3283 return;
3284 }
3285 ice_gathering_state_ = new_state;
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00003286 observer_->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003287}
3288
jbauch81bf7b02017-03-25 08:31:12 -07003289void PeerConnection::OnIceCandidate(
3290 std::unique_ptr<IceCandidateInterface> candidate) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07003291 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07003292 if (IsClosed()) {
3293 return;
3294 }
jbauch81bf7b02017-03-25 08:31:12 -07003295 observer_->OnIceCandidate(candidate.get());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003296}
3297
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003298void PeerConnection::OnIceCandidatesRemoved(
3299 const std::vector<cricket::Candidate>& candidates) {
3300 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07003301 if (IsClosed()) {
3302 return;
3303 }
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003304 observer_->OnIceCandidatesRemoved(candidates);
3305}
3306
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003307void PeerConnection::ChangeSignalingState(
3308 PeerConnectionInterface::SignalingState signaling_state) {
Steve Antonba818672017-11-06 10:21:57 -08003309 RTC_DCHECK(signaling_thread()->IsCurrent());
3310 if (signaling_state_ == signaling_state) {
3311 return;
3312 }
Mirko Bonadei675513b2017-11-09 11:09:25 +01003313 RTC_LOG(LS_INFO) << "Session: " << session_id() << " Old state: "
3314 << GetSignalingStateString(signaling_state_)
3315 << " New state: "
3316 << GetSignalingStateString(signaling_state);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003317 signaling_state_ = signaling_state;
3318 if (signaling_state == kClosed) {
3319 ice_connection_state_ = kIceConnectionClosed;
3320 observer_->OnIceConnectionChange(ice_connection_state_);
3321 if (ice_gathering_state_ != kIceGatheringComplete) {
3322 ice_gathering_state_ = kIceGatheringComplete;
3323 observer_->OnIceGatheringChange(ice_gathering_state_);
3324 }
3325 }
3326 observer_->OnSignalingChange(signaling_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003327}
3328
deadbeefeb459812015-12-15 19:24:43 -08003329void PeerConnection::OnAudioTrackAdded(AudioTrackInterface* track,
3330 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003331 if (IsClosed()) {
3332 return;
3333 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003334 AddAudioTrack(track, stream);
3335 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003336}
3337
deadbeefeb459812015-12-15 19:24:43 -08003338void PeerConnection::OnAudioTrackRemoved(AudioTrackInterface* track,
3339 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003340 if (IsClosed()) {
3341 return;
3342 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003343 RemoveAudioTrack(track, stream);
3344 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003345}
3346
3347void PeerConnection::OnVideoTrackAdded(VideoTrackInterface* track,
3348 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003349 if (IsClosed()) {
3350 return;
3351 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003352 AddVideoTrack(track, stream);
3353 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003354}
3355
3356void PeerConnection::OnVideoTrackRemoved(VideoTrackInterface* track,
3357 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003358 if (IsClosed()) {
3359 return;
3360 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003361 RemoveVideoTrack(track, stream);
3362 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003363}
3364
Henrik Boström31638672017-11-23 17:48:32 +01003365void PeerConnection::PostSetSessionDescriptionSuccess(
3366 SetSessionDescriptionObserver* observer) {
3367 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
3368 signaling_thread()->Post(RTC_FROM_HERE, this,
3369 MSG_SET_SESSIONDESCRIPTION_SUCCESS, msg);
3370}
3371
deadbeefab9b2d12015-10-14 11:33:11 -07003372void PeerConnection::PostSetSessionDescriptionFailure(
3373 SetSessionDescriptionObserver* observer,
3374 const std::string& error) {
3375 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
3376 msg->error = error;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07003377 signaling_thread()->Post(RTC_FROM_HERE, this,
3378 MSG_SET_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07003379}
3380
3381void PeerConnection::PostCreateSessionDescriptionFailure(
3382 CreateSessionDescriptionObserver* observer,
3383 const std::string& error) {
3384 CreateSessionDescriptionMsg* msg = new CreateSessionDescriptionMsg(observer);
3385 msg->error = error;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07003386 signaling_thread()->Post(RTC_FROM_HERE, this,
3387 MSG_CREATE_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07003388}
3389
zhihuang1c378ed2017-08-17 14:10:50 -07003390void PeerConnection::GetOptionsForOffer(
Steve Antondcc3c022017-12-22 16:02:54 -08003391 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
deadbeefab9b2d12015-10-14 11:33:11 -07003392 cricket::MediaSessionOptions* session_options) {
Steve Antondcc3c022017-12-22 16:02:54 -08003393 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
zhihuang1c378ed2017-08-17 14:10:50 -07003394
Steve Antondcc3c022017-12-22 16:02:54 -08003395 if (IsUnifiedPlan()) {
3396 GetOptionsForUnifiedPlanOffer(offer_answer_options, session_options);
3397 } else {
3398 GetOptionsForPlanBOffer(offer_answer_options, session_options);
3399 }
3400
Steve Antonfa2260d2017-12-28 16:38:23 -08003401 // Intentionally unset the data channel type for RTP data channel with the
3402 // second condition. Otherwise the RTP data channels would be successfully
3403 // negotiated by default and the unit tests in WebRtcDataBrowserTest will fail
3404 // when building with chromium. We want to leave RTP data channels broken, so
3405 // people won't try to use them.
3406 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
3407 session_options->data_channel_type = data_channel_type();
3408 }
3409
Steve Antondcc3c022017-12-22 16:02:54 -08003410 // Apply ICE restart flag and renomination flag.
3411 for (auto& options : session_options->media_description_options) {
3412 options.transport_options.ice_restart = offer_answer_options.ice_restart;
3413 options.transport_options.enable_ice_renomination =
3414 configuration_.enable_ice_renomination;
3415 }
3416
3417 session_options->rtcp_cname = rtcp_cname_;
3418 session_options->crypto_options = factory_->options().crypto_options;
Steve Antone831b8c2018-02-01 12:22:16 -08003419 session_options->is_unified_plan = IsUnifiedPlan();
Steve Antondcc3c022017-12-22 16:02:54 -08003420}
3421
3422void PeerConnection::GetOptionsForPlanBOffer(
3423 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
3424 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07003425 // Figure out transceiver directional preferences.
3426 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
3427 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
3428
3429 // By default, generate sendrecv/recvonly m= sections.
3430 bool recv_audio = true;
3431 bool recv_video = true;
3432
3433 // By default, only offer a new m= section if we have media to send with it.
3434 bool offer_new_audio_description = send_audio;
3435 bool offer_new_video_description = send_video;
3436 bool offer_new_data_description = HasDataChannels();
3437
3438 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-22 16:02:54 -08003439 if (offer_answer_options.offer_to_receive_audio !=
3440 RTCOfferAnswerOptions::kUndefined) {
3441 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003442 offer_new_audio_description =
Steve Antondcc3c022017-12-22 16:02:54 -08003443 offer_new_audio_description ||
3444 (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003445 }
Steve Antondcc3c022017-12-22 16:02:54 -08003446 if (offer_answer_options.offer_to_receive_video !=
3447 RTCOfferAnswerOptions::kUndefined) {
3448 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003449 offer_new_video_description =
Steve Antondcc3c022017-12-22 16:02:54 -08003450 offer_new_video_description ||
3451 (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003452 }
3453
3454 rtc::Optional<size_t> audio_index;
3455 rtc::Optional<size_t> video_index;
3456 rtc::Optional<size_t> data_index;
3457 // If a current description exists, generate m= sections in the same order,
3458 // using the first audio/video/data section that appears and rejecting
3459 // extraneous ones.
Steve Anton75737c02017-11-06 10:37:17 -08003460 if (local_description()) {
zhihuang1c378ed2017-08-17 14:10:50 -07003461 GenerateMediaDescriptionOptions(
Steve Anton75737c02017-11-06 10:37:17 -08003462 local_description(),
Steve Anton1d03a752017-11-27 14:30:09 -08003463 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
3464 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
3465 &audio_index, &video_index, &data_index, session_options);
deadbeefab9b2d12015-10-14 11:33:11 -07003466 }
3467
zhihuang1c378ed2017-08-17 14:10:50 -07003468 // Add audio/video/data m= sections to the end if needed.
3469 if (!audio_index && offer_new_audio_description) {
3470 session_options->media_description_options.push_back(
3471 cricket::MediaDescriptionOptions(
3472 cricket::MEDIA_TYPE_AUDIO, cricket::CN_AUDIO,
Steve Anton1d03a752017-11-27 14:30:09 -08003473 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
3474 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003475 audio_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07003476 }
zhihuang1c378ed2017-08-17 14:10:50 -07003477 if (!video_index && offer_new_video_description) {
3478 session_options->media_description_options.push_back(
3479 cricket::MediaDescriptionOptions(
3480 cricket::MEDIA_TYPE_VIDEO, cricket::CN_VIDEO,
Steve Anton1d03a752017-11-27 14:30:09 -08003481 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
3482 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003483 video_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07003484 }
zhihuang1c378ed2017-08-17 14:10:50 -07003485 if (!data_index && offer_new_data_description) {
3486 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08003487 GetMediaDescriptionOptionsForActiveData(cricket::CN_DATA));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003488 data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07003489 }
3490
3491 cricket::MediaDescriptionOptions* audio_media_description_options =
3492 !audio_index ? nullptr
3493 : &session_options->media_description_options[*audio_index];
3494 cricket::MediaDescriptionOptions* video_media_description_options =
3495 !video_index ? nullptr
3496 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 14:10:50 -07003497
Steve Anton4171afb2017-11-20 10:20:22 -08003498 AddRtpSenderOptions(GetSendersInternal(), audio_media_description_options,
zhihuang1c378ed2017-08-17 14:10:50 -07003499 video_media_description_options);
Steve Antondcc3c022017-12-22 16:02:54 -08003500}
3501
3502// Find a new MID that is not already in |used_mids|, then add it to |used_mids|
3503// and return a reference to it.
3504// Generated MIDs should be no more than 3 bytes long to take up less space in
3505// the RTP packet.
3506static const std::string& AllocateMid(std::set<std::string>* used_mids) {
3507 RTC_DCHECK(used_mids);
3508 // We're boring: just generate MIDs 0, 1, 2, ...
3509 size_t i = 0;
3510 std::set<std::string>::iterator it;
3511 bool inserted;
3512 do {
3513 std::string mid = rtc::ToString(i++);
3514 auto insert_result = used_mids->insert(mid);
3515 it = insert_result.first;
3516 inserted = insert_result.second;
3517 } while (!inserted);
3518 return *it;
3519}
3520
3521static cricket::MediaDescriptionOptions
3522GetMediaDescriptionOptionsForTransceiver(
3523 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3524 transceiver,
3525 const std::string& mid) {
3526 cricket::MediaDescriptionOptions media_description_options(
Steve Anton69470252018-02-09 11:43:08 -08003527 transceiver->media_type(), mid, transceiver->direction(),
Steve Antondcc3c022017-12-22 16:02:54 -08003528 transceiver->stopped());
Steve Anton5f94aa22018-02-01 10:58:30 -08003529 // This behavior is specified in JSEP. The gist is that:
3530 // 1. The MSID is included if the RtpTransceiver's direction is sendonly or
3531 // sendrecv.
3532 // 2. If the MSID is included, then it must be included in any subsequent
3533 // offer/answer exactly the same until the RtpTransceiver is stopped.
3534 if (!transceiver->stopped() &&
3535 (RtpTransceiverDirectionHasSend(transceiver->direction()) ||
3536 transceiver->internal()->has_ever_been_used_to_send())) {
3537 cricket::SenderOptions sender_options;
3538 sender_options.track_id = transceiver->sender()->id();
3539 sender_options.stream_ids = transceiver->sender()->stream_ids();
3540 // TODO(bugs.webrtc.org/7600): Set num_sim_layers to the number of encodings
3541 // set in the RTP parameters when the transceiver was added.
3542 sender_options.num_sim_layers = 1;
3543 media_description_options.sender_options.push_back(sender_options);
3544 }
Steve Antondcc3c022017-12-22 16:02:54 -08003545 return media_description_options;
3546}
3547
3548void PeerConnection::GetOptionsForUnifiedPlanOffer(
3549 const RTCOfferAnswerOptions& offer_answer_options,
3550 cricket::MediaSessionOptions* session_options) {
3551 // Rules for generating an offer are dictated by JSEP sections 5.2.1 (Initial
3552 // Offers) and 5.2.2 (Subsequent Offers).
3553 RTC_DCHECK_EQ(session_options->media_description_options.size(), 0);
3554 const ContentInfos& local_contents =
3555 (local_description() ? local_description()->description()->contents()
3556 : ContentInfos());
3557 const ContentInfos& remote_contents =
3558 (remote_description() ? remote_description()->description()->contents()
3559 : ContentInfos());
3560 // The mline indices that can be recycled. New transceivers should reuse these
3561 // slots first.
3562 std::queue<size_t> recycleable_mline_indices;
3563 // Track the MIDs used in previous offer/answer exchanges and the current
3564 // offer so that new, unique MIDs are generated.
3565 std::set<std::string> used_mids = seen_mids_;
3566 // First, go through each media section that exists in either the local or
3567 // remote description and generate a media section in this offer for the
3568 // associated transceiver. If a media section can be recycled, generate a
3569 // default, rejected media section here that can be later overwritten.
3570 for (size_t i = 0;
3571 i < std::max(local_contents.size(), remote_contents.size()); ++i) {
3572 // Either |local_content| or |remote_content| is non-null.
3573 const ContentInfo* local_content =
3574 (i < local_contents.size() ? &local_contents[i] : nullptr);
3575 const ContentInfo* remote_content =
3576 (i < remote_contents.size() ? &remote_contents[i] : nullptr);
3577 bool had_been_rejected = (local_content && local_content->rejected) ||
3578 (remote_content && remote_content->rejected);
3579 const std::string& mid =
3580 (local_content ? local_content->name : remote_content->name);
3581 cricket::MediaType media_type =
3582 (local_content ? local_content->media_description()->type()
3583 : remote_content->media_description()->type());
3584 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
3585 media_type == cricket::MEDIA_TYPE_VIDEO) {
3586 auto transceiver = GetAssociatedTransceiver(mid);
3587 RTC_CHECK(transceiver);
3588 // A media section is considered eligible for recycling if it is marked as
3589 // rejected in either the local or remote description.
Seth Hampsonae8a90a2018-02-13 15:33:48 -08003590 if (had_been_rejected && transceiver->stopped()) {
Steve Antondcc3c022017-12-22 16:02:54 -08003591 session_options->media_description_options.push_back(
Steve Anton69470252018-02-09 11:43:08 -08003592 cricket::MediaDescriptionOptions(transceiver->media_type(), mid,
3593 RtpTransceiverDirection::kInactive,
3594 /*stopped=*/true));
Steve Antondcc3c022017-12-22 16:02:54 -08003595 recycleable_mline_indices.push(i);
3596 } else {
3597 session_options->media_description_options.push_back(
3598 GetMediaDescriptionOptionsForTransceiver(transceiver, mid));
3599 // CreateOffer shouldn't really cause any state changes in
3600 // PeerConnection, but we need a way to match new transceivers to new
3601 // media sections in SetLocalDescription and JSEP specifies this is done
3602 // by recording the index of the media section generated for the
3603 // transceiver in the offer.
3604 transceiver->internal()->set_mline_index(i);
3605 }
3606 } else {
3607 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antonfa2260d2017-12-28 16:38:23 -08003608 RTC_CHECK(GetDataMid());
3609 if (had_been_rejected || mid != *GetDataMid()) {
3610 session_options->media_description_options.push_back(
3611 GetMediaDescriptionOptionsForRejectedData(mid));
3612 } else {
3613 session_options->media_description_options.push_back(
3614 GetMediaDescriptionOptionsForActiveData(mid));
3615 }
Steve Antondcc3c022017-12-22 16:02:54 -08003616 }
3617 }
3618 // Next, look for transceivers that are newly added (that is, are not stopped
3619 // and not associated). Reuse media sections marked as recyclable first,
3620 // otherwise append to the end of the offer. New media sections should be
3621 // added in the order they were added to the PeerConnection.
3622 for (auto transceiver : transceivers_) {
3623 if (transceiver->mid() || transceiver->stopped()) {
3624 continue;
3625 }
3626 size_t mline_index;
3627 if (!recycleable_mline_indices.empty()) {
3628 mline_index = recycleable_mline_indices.front();
3629 recycleable_mline_indices.pop();
3630 session_options->media_description_options[mline_index] =
3631 GetMediaDescriptionOptionsForTransceiver(transceiver,
3632 AllocateMid(&used_mids));
3633 } else {
3634 mline_index = session_options->media_description_options.size();
3635 session_options->media_description_options.push_back(
3636 GetMediaDescriptionOptionsForTransceiver(transceiver,
3637 AllocateMid(&used_mids)));
3638 }
3639 // See comment above for why CreateOffer changes the transceiver's state.
3640 transceiver->internal()->set_mline_index(mline_index);
3641 }
Steve Antonfa2260d2017-12-28 16:38:23 -08003642 // Lastly, add a m-section if we have local data channels and an m section
3643 // does not already exist.
3644 if (!GetDataMid() && HasDataChannels()) {
3645 session_options->media_description_options.push_back(
3646 GetMediaDescriptionOptionsForActiveData(AllocateMid(&used_mids)));
3647 }
Steve Antondcc3c022017-12-22 16:02:54 -08003648}
3649
3650void PeerConnection::GetOptionsForAnswer(
3651 const RTCOfferAnswerOptions& offer_answer_options,
3652 cricket::MediaSessionOptions* session_options) {
3653 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
3654
3655 if (IsUnifiedPlan()) {
3656 GetOptionsForUnifiedPlanAnswer(offer_answer_options, session_options);
3657 } else {
3658 GetOptionsForPlanBAnswer(offer_answer_options, session_options);
3659 }
3660
Steve Antonfa2260d2017-12-28 16:38:23 -08003661 // Intentionally unset the data channel type for RTP data channel. Otherwise
3662 // the RTP data channels would be successfully negotiated by default and the
3663 // unit tests in WebRtcDataBrowserTest will fail when building with chromium.
3664 // We want to leave RTP data channels broken, so people won't try to use them.
3665 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
3666 session_options->data_channel_type = data_channel_type();
3667 }
3668
Steve Antondcc3c022017-12-22 16:02:54 -08003669 // Apply ICE renomination flag.
3670 for (auto& options : session_options->media_description_options) {
3671 options.transport_options.enable_ice_renomination =
3672 configuration_.enable_ice_renomination;
3673 }
zhihuang8f65cdf2016-05-06 18:40:30 -07003674
3675 session_options->rtcp_cname = rtcp_cname_;
jbauchcb560652016-08-04 05:20:32 -07003676 session_options->crypto_options = factory_->options().crypto_options;
Steve Antone831b8c2018-02-01 12:22:16 -08003677 session_options->is_unified_plan = IsUnifiedPlan();
deadbeefab9b2d12015-10-14 11:33:11 -07003678}
3679
Steve Antondcc3c022017-12-22 16:02:54 -08003680void PeerConnection::GetOptionsForPlanBAnswer(
3681 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07003682 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07003683 // Figure out transceiver directional preferences.
3684 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
3685 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
3686
3687 // By default, generate sendrecv/recvonly m= sections. The direction is also
3688 // restricted by the direction in the offer.
3689 bool recv_audio = true;
3690 bool recv_video = true;
3691
3692 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-22 16:02:54 -08003693 if (offer_answer_options.offer_to_receive_audio !=
3694 RTCOfferAnswerOptions::kUndefined) {
3695 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
deadbeef0ed85b22016-02-23 17:24:52 -08003696 }
Steve Antondcc3c022017-12-22 16:02:54 -08003697 if (offer_answer_options.offer_to_receive_video !=
3698 RTCOfferAnswerOptions::kUndefined) {
3699 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003700 }
3701
3702 rtc::Optional<size_t> audio_index;
3703 rtc::Optional<size_t> video_index;
3704 rtc::Optional<size_t> data_index;
Steve Antondffead82018-02-06 10:31:29 -08003705
3706 // Generate m= sections that match those in the offer.
3707 // Note that mediasession.cc will handle intersection our preferred
3708 // direction with the offered direction.
3709 GenerateMediaDescriptionOptions(
3710 remote_description(),
3711 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
3712 RtpTransceiverDirectionFromSendRecv(send_video, recv_video), &audio_index,
3713 &video_index, &data_index, session_options);
zhihuang1c378ed2017-08-17 14:10:50 -07003714
3715 cricket::MediaDescriptionOptions* audio_media_description_options =
3716 !audio_index ? nullptr
3717 : &session_options->media_description_options[*audio_index];
3718 cricket::MediaDescriptionOptions* video_media_description_options =
3719 !video_index ? nullptr
3720 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 14:10:50 -07003721
Steve Anton4171afb2017-11-20 10:20:22 -08003722 AddRtpSenderOptions(GetSendersInternal(), audio_media_description_options,
zhihuang1c378ed2017-08-17 14:10:50 -07003723 video_media_description_options);
Steve Antondcc3c022017-12-22 16:02:54 -08003724}
zhihuangaf388472016-11-02 16:49:48 -07003725
Steve Antondcc3c022017-12-22 16:02:54 -08003726void PeerConnection::GetOptionsForUnifiedPlanAnswer(
3727 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
3728 cricket::MediaSessionOptions* session_options) {
3729 // Rules for generating an answer are dictated by JSEP sections 5.3.1 (Initial
3730 // Answers) and 5.3.2 (Subsequent Answers).
3731 RTC_DCHECK(remote_description());
3732 RTC_DCHECK(remote_description()->GetType() == SdpType::kOffer);
3733 for (const ContentInfo& content :
3734 remote_description()->description()->contents()) {
3735 cricket::MediaType media_type = content.media_description()->type();
3736 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
3737 media_type == cricket::MEDIA_TYPE_VIDEO) {
3738 auto transceiver = GetAssociatedTransceiver(content.name);
3739 RTC_CHECK(transceiver);
3740 session_options->media_description_options.push_back(
3741 GetMediaDescriptionOptionsForTransceiver(transceiver, content.name));
3742 } else {
3743 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antondbf9d032018-01-19 15:23:40 -08003744 // Reject all data sections if data channels are disabled.
3745 // Reject a data section if it has already been rejected.
3746 // Reject all data sections except for the first one.
3747 if (data_channel_type_ == cricket::DCT_NONE || content.rejected ||
3748 content.name != *GetDataMid()) {
Steve Antonfa2260d2017-12-28 16:38:23 -08003749 session_options->media_description_options.push_back(
3750 GetMediaDescriptionOptionsForRejectedData(content.name));
3751 } else {
3752 session_options->media_description_options.push_back(
3753 GetMediaDescriptionOptionsForActiveData(content.name));
3754 }
Steve Antondcc3c022017-12-22 16:02:54 -08003755 }
3756 }
htaa2a49d92016-03-04 02:51:39 -08003757}
3758
zhihuang1c378ed2017-08-17 14:10:50 -07003759void PeerConnection::GenerateMediaDescriptionOptions(
3760 const SessionDescriptionInterface* session_desc,
Steve Anton1d03a752017-11-27 14:30:09 -08003761 RtpTransceiverDirection audio_direction,
3762 RtpTransceiverDirection video_direction,
zhihuang1c378ed2017-08-17 14:10:50 -07003763 rtc::Optional<size_t>* audio_index,
3764 rtc::Optional<size_t>* video_index,
3765 rtc::Optional<size_t>* data_index,
htaa2a49d92016-03-04 02:51:39 -08003766 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07003767 for (const cricket::ContentInfo& content :
3768 session_desc->description()->contents()) {
3769 if (IsAudioContent(&content)) {
3770 // If we already have an audio m= section, reject this extra one.
3771 if (*audio_index) {
3772 session_options->media_description_options.push_back(
3773 cricket::MediaDescriptionOptions(
3774 cricket::MEDIA_TYPE_AUDIO, content.name,
Steve Anton1d03a752017-11-27 14:30:09 -08003775 RtpTransceiverDirection::kInactive, true));
zhihuang1c378ed2017-08-17 14:10:50 -07003776 } else {
3777 session_options->media_description_options.push_back(
3778 cricket::MediaDescriptionOptions(
3779 cricket::MEDIA_TYPE_AUDIO, content.name, audio_direction,
Steve Anton1d03a752017-11-27 14:30:09 -08003780 audio_direction == RtpTransceiverDirection::kInactive));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003781 *audio_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07003782 }
3783 } else if (IsVideoContent(&content)) {
3784 // If we already have an video m= section, reject this extra one.
3785 if (*video_index) {
3786 session_options->media_description_options.push_back(
3787 cricket::MediaDescriptionOptions(
3788 cricket::MEDIA_TYPE_VIDEO, content.name,
Steve Anton1d03a752017-11-27 14:30:09 -08003789 RtpTransceiverDirection::kInactive, true));
zhihuang1c378ed2017-08-17 14:10:50 -07003790 } else {
3791 session_options->media_description_options.push_back(
3792 cricket::MediaDescriptionOptions(
3793 cricket::MEDIA_TYPE_VIDEO, content.name, video_direction,
Steve Anton1d03a752017-11-27 14:30:09 -08003794 video_direction == RtpTransceiverDirection::kInactive));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003795 *video_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07003796 }
3797 } else {
3798 RTC_DCHECK(IsDataContent(&content));
3799 // If we already have an data m= section, reject this extra one.
3800 if (*data_index) {
3801 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08003802 GetMediaDescriptionOptionsForRejectedData(content.name));
zhihuang1c378ed2017-08-17 14:10:50 -07003803 } else {
3804 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08003805 GetMediaDescriptionOptionsForActiveData(content.name));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003806 *data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07003807 }
3808 }
htaa2a49d92016-03-04 02:51:39 -08003809 }
deadbeefab9b2d12015-10-14 11:33:11 -07003810}
3811
Steve Antonfa2260d2017-12-28 16:38:23 -08003812cricket::MediaDescriptionOptions
3813PeerConnection::GetMediaDescriptionOptionsForActiveData(
3814 const std::string& mid) const {
3815 // Direction for data sections is meaningless, but legacy endpoints might
3816 // expect sendrecv.
3817 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
3818 RtpTransceiverDirection::kSendRecv,
3819 /*stopped=*/false);
3820 AddRtpDataChannelOptions(rtp_data_channels_, &options);
3821 return options;
3822}
3823
3824cricket::MediaDescriptionOptions
3825PeerConnection::GetMediaDescriptionOptionsForRejectedData(
3826 const std::string& mid) const {
3827 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
3828 RtpTransceiverDirection::kInactive,
3829 /*stopped=*/true);
3830 AddRtpDataChannelOptions(rtp_data_channels_, &options);
3831 return options;
3832}
3833
3834rtc::Optional<std::string> PeerConnection::GetDataMid() const {
3835 switch (data_channel_type_) {
3836 case cricket::DCT_RTP:
3837 if (!rtp_data_channel_) {
3838 return rtc::nullopt;
3839 }
3840 return rtp_data_channel_->content_name();
3841 case cricket::DCT_SCTP:
3842 return sctp_content_name_;
3843 default:
3844 return rtc::nullopt;
3845 }
3846}
3847
Steve Anton4171afb2017-11-20 10:20:22 -08003848void PeerConnection::RemoveSenders(cricket::MediaType media_type) {
3849 UpdateLocalSenders(std::vector<cricket::StreamParams>(), media_type);
3850 UpdateRemoteSendersList(std::vector<cricket::StreamParams>(), false,
deadbeefbda7e0b2015-12-08 17:13:40 -08003851 media_type, nullptr);
deadbeeffaac4972015-11-12 15:33:07 -08003852}
3853
Steve Anton4171afb2017-11-20 10:20:22 -08003854void PeerConnection::UpdateRemoteSendersList(
deadbeefab9b2d12015-10-14 11:33:11 -07003855 const cricket::StreamParamsVec& streams,
Steve Anton4171afb2017-11-20 10:20:22 -08003856 bool default_sender_needed,
deadbeefab9b2d12015-10-14 11:33:11 -07003857 cricket::MediaType media_type,
3858 StreamCollection* new_streams) {
Steve Anton4171afb2017-11-20 10:20:22 -08003859 std::vector<RtpSenderInfo>* current_senders =
3860 GetRemoteSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07003861
Steve Anton4171afb2017-11-20 10:20:22 -08003862 // Find removed senders. I.e., senders where the sender id or ssrc don't match
deadbeeffac06552015-11-25 11:26:01 -08003863 // the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08003864 for (auto sender_it = current_senders->begin();
3865 sender_it != current_senders->end();
3866 /* incremented manually */) {
3867 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07003868 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08003869 cricket::GetStreamBySsrc(streams, info.first_ssrc);
3870 bool sender_exists = params && params->id == info.sender_id;
deadbeefbda7e0b2015-12-08 17:13:40 -08003871 // If this is a default track, and we still need it, don't remove it.
Steve Anton4171afb2017-11-20 10:20:22 -08003872 if ((info.stream_label == kDefaultStreamLabel && default_sender_needed) ||
3873 sender_exists) {
3874 ++sender_it;
deadbeefbda7e0b2015-12-08 17:13:40 -08003875 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08003876 OnRemoteSenderRemoved(info, media_type);
3877 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07003878 }
3879 }
3880
Steve Anton4171afb2017-11-20 10:20:22 -08003881 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07003882 for (const cricket::StreamParams& params : streams) {
3883 // The sync_label is the MediaStream label and the |stream.id| is the
Steve Anton4171afb2017-11-20 10:20:22 -08003884 // sender id.
deadbeefab9b2d12015-10-14 11:33:11 -07003885 const std::string& stream_label = params.sync_label;
Steve Anton4171afb2017-11-20 10:20:22 -08003886 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07003887 uint32_t ssrc = params.first_ssrc();
3888
3889 rtc::scoped_refptr<MediaStreamInterface> stream =
3890 remote_streams_->find(stream_label);
3891 if (!stream) {
3892 // This is a new MediaStream. Create a new remote MediaStream.
perkjd61bf802016-03-24 03:16:19 -07003893 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
3894 MediaStream::Create(stream_label));
deadbeefab9b2d12015-10-14 11:33:11 -07003895 remote_streams_->AddStream(stream);
3896 new_streams->AddStream(stream);
3897 }
3898
Steve Anton4171afb2017-11-20 10:20:22 -08003899 const RtpSenderInfo* sender_info =
3900 FindSenderInfo(*current_senders, stream_label, sender_id);
3901 if (!sender_info) {
3902 current_senders->push_back(RtpSenderInfo(stream_label, sender_id, ssrc));
3903 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07003904 }
3905 }
deadbeefbda7e0b2015-12-08 17:13:40 -08003906
Steve Anton4171afb2017-11-20 10:20:22 -08003907 // Add default sender if necessary.
3908 if (default_sender_needed) {
deadbeefbda7e0b2015-12-08 17:13:40 -08003909 rtc::scoped_refptr<MediaStreamInterface> default_stream =
3910 remote_streams_->find(kDefaultStreamLabel);
3911 if (!default_stream) {
3912 // Create the new default MediaStream.
perkjd61bf802016-03-24 03:16:19 -07003913 default_stream = MediaStreamProxy::Create(
3914 rtc::Thread::Current(), MediaStream::Create(kDefaultStreamLabel));
deadbeefbda7e0b2015-12-08 17:13:40 -08003915 remote_streams_->AddStream(default_stream);
3916 new_streams->AddStream(default_stream);
3917 }
Steve Anton4171afb2017-11-20 10:20:22 -08003918 std::string default_sender_id = (media_type == cricket::MEDIA_TYPE_AUDIO)
3919 ? kDefaultAudioSenderId
3920 : kDefaultVideoSenderId;
3921 const RtpSenderInfo* default_sender_info = FindSenderInfo(
3922 *current_senders, kDefaultStreamLabel, default_sender_id);
3923 if (!default_sender_info) {
3924 current_senders->push_back(
3925 RtpSenderInfo(kDefaultStreamLabel, default_sender_id, 0));
3926 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefbda7e0b2015-12-08 17:13:40 -08003927 }
3928 }
deadbeefab9b2d12015-10-14 11:33:11 -07003929}
3930
Steve Anton4171afb2017-11-20 10:20:22 -08003931void PeerConnection::OnRemoteSenderAdded(const RtpSenderInfo& sender_info,
3932 cricket::MediaType media_type) {
3933 MediaStreamInterface* stream =
3934 remote_streams_->find(sender_info.stream_label);
deadbeefab9b2d12015-10-14 11:33:11 -07003935
3936 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 10:20:22 -08003937 CreateAudioReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07003938 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 10:20:22 -08003939 CreateVideoReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07003940 } else {
nisseeb4ca4e2017-01-12 02:24:27 -08003941 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07003942 }
3943}
3944
Steve Anton4171afb2017-11-20 10:20:22 -08003945void PeerConnection::OnRemoteSenderRemoved(const RtpSenderInfo& sender_info,
3946 cricket::MediaType media_type) {
3947 MediaStreamInterface* stream =
3948 remote_streams_->find(sender_info.stream_label);
deadbeefab9b2d12015-10-14 11:33:11 -07003949
Henrik Boström933d8b02017-10-10 10:05:16 -07003950 rtc::scoped_refptr<RtpReceiverInterface> receiver;
deadbeefab9b2d12015-10-14 11:33:11 -07003951 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
perkjd61bf802016-03-24 03:16:19 -07003952 // When the MediaEngine audio channel is destroyed, the RemoteAudioSource
3953 // will be notified which will end the AudioRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08003954 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07003955 rtc::scoped_refptr<AudioTrackInterface> audio_track =
Steve Anton4171afb2017-11-20 10:20:22 -08003956 stream->FindAudioTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07003957 if (audio_track) {
deadbeefab9b2d12015-10-14 11:33:11 -07003958 stream->RemoveTrack(audio_track);
deadbeefab9b2d12015-10-14 11:33:11 -07003959 }
3960 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
perkjd61bf802016-03-24 03:16:19 -07003961 // Stopping or destroying a VideoRtpReceiver will end the
3962 // VideoRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08003963 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07003964 rtc::scoped_refptr<VideoTrackInterface> video_track =
Steve Anton4171afb2017-11-20 10:20:22 -08003965 stream->FindVideoTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07003966 if (video_track) {
perkjd61bf802016-03-24 03:16:19 -07003967 // There's no guarantee the track is still available, e.g. the track may
3968 // have been removed from the stream by an application.
deadbeefab9b2d12015-10-14 11:33:11 -07003969 stream->RemoveTrack(video_track);
deadbeefab9b2d12015-10-14 11:33:11 -07003970 }
3971 } else {
nisseede5da42017-01-12 05:15:36 -08003972 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07003973 }
Henrik Boström933d8b02017-10-10 10:05:16 -07003974 if (receiver) {
3975 observer_->OnRemoveTrack(receiver);
3976 }
deadbeefab9b2d12015-10-14 11:33:11 -07003977}
3978
3979void PeerConnection::UpdateEndedRemoteMediaStreams() {
3980 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams_to_remove;
3981 for (size_t i = 0; i < remote_streams_->count(); ++i) {
3982 MediaStreamInterface* stream = remote_streams_->at(i);
3983 if (stream->GetAudioTracks().empty() && stream->GetVideoTracks().empty()) {
3984 streams_to_remove.push_back(stream);
3985 }
3986 }
3987
Taylor Brandstetter98cde262016-05-31 13:02:21 -07003988 for (auto& stream : streams_to_remove) {
deadbeefab9b2d12015-10-14 11:33:11 -07003989 remote_streams_->RemoveStream(stream);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07003990 observer_->OnRemoveStream(std::move(stream));
deadbeefab9b2d12015-10-14 11:33:11 -07003991 }
3992}
3993
Steve Anton4171afb2017-11-20 10:20:22 -08003994void PeerConnection::UpdateLocalSenders(
deadbeefab9b2d12015-10-14 11:33:11 -07003995 const std::vector<cricket::StreamParams>& streams,
3996 cricket::MediaType media_type) {
Steve Anton4171afb2017-11-20 10:20:22 -08003997 std::vector<RtpSenderInfo>* current_senders = GetLocalSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07003998
3999 // Find removed tracks. I.e., tracks where the track id, stream label or ssrc
4000 // don't match the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08004001 for (auto sender_it = current_senders->begin();
4002 sender_it != current_senders->end();
4003 /* incremented manually */) {
4004 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07004005 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08004006 cricket::GetStreamBySsrc(streams, info.first_ssrc);
4007 if (!params || params->id != info.sender_id ||
deadbeefab9b2d12015-10-14 11:33:11 -07004008 params->sync_label != info.stream_label) {
Steve Anton4171afb2017-11-20 10:20:22 -08004009 OnLocalSenderRemoved(info, media_type);
4010 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07004011 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08004012 ++sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07004013 }
4014 }
4015
Steve Anton4171afb2017-11-20 10:20:22 -08004016 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07004017 for (const cricket::StreamParams& params : streams) {
4018 // The sync_label is the MediaStream label and the |stream.id| is the
Steve Anton4171afb2017-11-20 10:20:22 -08004019 // sender id.
deadbeefab9b2d12015-10-14 11:33:11 -07004020 const std::string& stream_label = params.sync_label;
Steve Anton4171afb2017-11-20 10:20:22 -08004021 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07004022 uint32_t ssrc = params.first_ssrc();
Steve Anton4171afb2017-11-20 10:20:22 -08004023 const RtpSenderInfo* sender_info =
4024 FindSenderInfo(*current_senders, stream_label, sender_id);
4025 if (!sender_info) {
4026 current_senders->push_back(RtpSenderInfo(stream_label, sender_id, ssrc));
4027 OnLocalSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004028 }
4029 }
4030}
4031
Steve Anton4171afb2017-11-20 10:20:22 -08004032void PeerConnection::OnLocalSenderAdded(const RtpSenderInfo& sender_info,
4033 cricket::MediaType media_type) {
4034 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08004035 if (!sender) {
Steve Anton4171afb2017-11-20 10:20:22 -08004036 RTC_LOG(LS_WARNING) << "An unknown RtpSender with id "
4037 << sender_info.sender_id
Mirko Bonadei675513b2017-11-09 11:09:25 +01004038 << " has been configured in the local description.";
deadbeefab9b2d12015-10-14 11:33:11 -07004039 return;
4040 }
4041
deadbeeffac06552015-11-25 11:26:01 -08004042 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004043 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
Jonas Olsson45cc8902018-02-13 10:37:07 +01004044 " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08004045 return;
deadbeefab9b2d12015-10-14 11:33:11 -07004046 }
deadbeeffac06552015-11-25 11:26:01 -08004047
Steve Anton4171afb2017-11-20 10:20:22 -08004048 sender->internal()->set_stream_id(sender_info.stream_label);
4049 sender->internal()->SetSsrc(sender_info.first_ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07004050}
4051
Steve Anton4171afb2017-11-20 10:20:22 -08004052void PeerConnection::OnLocalSenderRemoved(const RtpSenderInfo& sender_info,
4053 cricket::MediaType media_type) {
4054 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08004055 if (!sender) {
4056 // This is the normal case. I.e., RemoveStream has been called and the
deadbeefab9b2d12015-10-14 11:33:11 -07004057 // SessionDescriptions has been renegotiated.
4058 return;
4059 }
deadbeeffac06552015-11-25 11:26:01 -08004060
4061 // A sender has been removed from the SessionDescription but it's still
4062 // associated with the PeerConnection. This only occurs if the SDP doesn't
4063 // match with the calls to CreateSender, AddStream and RemoveStream.
4064 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004065 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
Jonas Olsson45cc8902018-02-13 10:37:07 +01004066 " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08004067 return;
deadbeefab9b2d12015-10-14 11:33:11 -07004068 }
deadbeeffac06552015-11-25 11:26:01 -08004069
Steve Anton4171afb2017-11-20 10:20:22 -08004070 sender->internal()->SetSsrc(0);
deadbeefab9b2d12015-10-14 11:33:11 -07004071}
4072
4073void PeerConnection::UpdateLocalRtpDataChannels(
4074 const cricket::StreamParamsVec& streams) {
4075 std::vector<std::string> existing_channels;
4076
4077 // Find new and active data channels.
4078 for (const cricket::StreamParams& params : streams) {
4079 // |it->sync_label| is actually the data channel label. The reason is that
4080 // we use the same naming of data channels as we do for
4081 // MediaStreams and Tracks.
4082 // For MediaStreams, the sync_label is the MediaStream label and the
4083 // track label is the same as |streamid|.
4084 const std::string& channel_label = params.sync_label;
4085 auto data_channel_it = rtp_data_channels_.find(channel_label);
nisse7ce109a2017-01-31 00:57:56 -08004086 if (data_channel_it == rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004087 RTC_LOG(LS_ERROR) << "channel label not found";
deadbeefab9b2d12015-10-14 11:33:11 -07004088 continue;
4089 }
4090 // Set the SSRC the data channel should use for sending.
4091 data_channel_it->second->SetSendSsrc(params.first_ssrc());
4092 existing_channels.push_back(data_channel_it->first);
4093 }
4094
4095 UpdateClosingRtpDataChannels(existing_channels, true);
4096}
4097
4098void PeerConnection::UpdateRemoteRtpDataChannels(
4099 const cricket::StreamParamsVec& streams) {
4100 std::vector<std::string> existing_channels;
4101
4102 // Find new and active data channels.
4103 for (const cricket::StreamParams& params : streams) {
4104 // The data channel label is either the mslabel or the SSRC if the mslabel
4105 // does not exist. Ex a=ssrc:444330170 mslabel:test1.
4106 std::string label = params.sync_label.empty()
4107 ? rtc::ToString(params.first_ssrc())
4108 : params.sync_label;
4109 auto data_channel_it = rtp_data_channels_.find(label);
4110 if (data_channel_it == rtp_data_channels_.end()) {
4111 // This is a new data channel.
4112 CreateRemoteRtpDataChannel(label, params.first_ssrc());
4113 } else {
4114 data_channel_it->second->SetReceiveSsrc(params.first_ssrc());
4115 }
4116 existing_channels.push_back(label);
4117 }
4118
4119 UpdateClosingRtpDataChannels(existing_channels, false);
4120}
4121
4122void PeerConnection::UpdateClosingRtpDataChannels(
4123 const std::vector<std::string>& active_channels,
4124 bool is_local_update) {
4125 auto it = rtp_data_channels_.begin();
4126 while (it != rtp_data_channels_.end()) {
4127 DataChannel* data_channel = it->second;
4128 if (std::find(active_channels.begin(), active_channels.end(),
4129 data_channel->label()) != active_channels.end()) {
4130 ++it;
4131 continue;
4132 }
4133
4134 if (is_local_update) {
4135 data_channel->SetSendSsrc(0);
4136 } else {
4137 data_channel->RemotePeerRequestClose();
4138 }
4139
4140 if (data_channel->state() == DataChannel::kClosed) {
4141 rtp_data_channels_.erase(it);
4142 it = rtp_data_channels_.begin();
4143 } else {
4144 ++it;
4145 }
4146 }
4147}
4148
4149void PeerConnection::CreateRemoteRtpDataChannel(const std::string& label,
4150 uint32_t remote_ssrc) {
4151 rtc::scoped_refptr<DataChannel> channel(
4152 InternalCreateDataChannel(label, nullptr));
4153 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004154 RTC_LOG(LS_WARNING) << "Remote peer requested a DataChannel but"
Jonas Olsson45cc8902018-02-13 10:37:07 +01004155 "CreateDataChannel failed.";
deadbeefab9b2d12015-10-14 11:33:11 -07004156 return;
4157 }
4158 channel->SetReceiveSsrc(remote_ssrc);
deadbeefa601f5c2016-06-06 14:27:39 -07004159 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
4160 DataChannelProxy::Create(signaling_thread(), channel);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07004161 observer_->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07004162}
4163
4164rtc::scoped_refptr<DataChannel> PeerConnection::InternalCreateDataChannel(
4165 const std::string& label,
4166 const InternalDataChannelInit* config) {
4167 if (IsClosed()) {
4168 return nullptr;
4169 }
Steve Anton75737c02017-11-06 10:37:17 -08004170 if (data_channel_type() == cricket::DCT_NONE) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004171 RTC_LOG(LS_ERROR)
deadbeefab9b2d12015-10-14 11:33:11 -07004172 << "InternalCreateDataChannel: Data is not supported in this call.";
4173 return nullptr;
4174 }
4175 InternalDataChannelInit new_config =
4176 config ? (*config) : InternalDataChannelInit();
Steve Anton75737c02017-11-06 10:37:17 -08004177 if (data_channel_type() == cricket::DCT_SCTP) {
deadbeefab9b2d12015-10-14 11:33:11 -07004178 if (new_config.id < 0) {
4179 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08004180 if ((GetSctpSslRole(&role)) &&
deadbeefab9b2d12015-10-14 11:33:11 -07004181 !sid_allocator_.AllocateSid(role, &new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004182 RTC_LOG(LS_ERROR)
4183 << "No id can be allocated for the SCTP data channel.";
deadbeefab9b2d12015-10-14 11:33:11 -07004184 return nullptr;
4185 }
4186 } else if (!sid_allocator_.ReserveSid(new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004187 RTC_LOG(LS_ERROR) << "Failed to create a SCTP data channel "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004188 "because the id is already in use or out of range.";
deadbeefab9b2d12015-10-14 11:33:11 -07004189 return nullptr;
4190 }
4191 }
4192
Steve Anton75737c02017-11-06 10:37:17 -08004193 rtc::scoped_refptr<DataChannel> channel(
4194 DataChannel::Create(this, data_channel_type(), label, new_config));
deadbeefab9b2d12015-10-14 11:33:11 -07004195 if (!channel) {
4196 sid_allocator_.ReleaseSid(new_config.id);
4197 return nullptr;
4198 }
4199
4200 if (channel->data_channel_type() == cricket::DCT_RTP) {
4201 if (rtp_data_channels_.find(channel->label()) != rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004202 RTC_LOG(LS_ERROR) << "DataChannel with label " << channel->label()
4203 << " already exists.";
deadbeefab9b2d12015-10-14 11:33:11 -07004204 return nullptr;
4205 }
4206 rtp_data_channels_[channel->label()] = channel;
4207 } else {
4208 RTC_DCHECK(channel->data_channel_type() == cricket::DCT_SCTP);
4209 sctp_data_channels_.push_back(channel);
4210 channel->SignalClosed.connect(this,
4211 &PeerConnection::OnSctpDataChannelClosed);
4212 }
4213
Steve Anton2d8609c2018-01-23 16:38:46 -08004214 SignalDataChannelCreated_(channel.get());
deadbeefab9b2d12015-10-14 11:33:11 -07004215 return channel;
4216}
4217
4218bool PeerConnection::HasDataChannels() const {
4219 return !rtp_data_channels_.empty() || !sctp_data_channels_.empty();
4220}
4221
4222void PeerConnection::AllocateSctpSids(rtc::SSLRole role) {
4223 for (const auto& channel : sctp_data_channels_) {
4224 if (channel->id() < 0) {
4225 int sid;
4226 if (!sid_allocator_.AllocateSid(role, &sid)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004227 RTC_LOG(LS_ERROR) << "Failed to allocate SCTP sid.";
deadbeefab9b2d12015-10-14 11:33:11 -07004228 continue;
4229 }
4230 channel->SetSctpSid(sid);
4231 }
4232 }
4233}
4234
4235void PeerConnection::OnSctpDataChannelClosed(DataChannel* channel) {
deadbeefbd292462015-12-14 18:15:29 -08004236 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeefab9b2d12015-10-14 11:33:11 -07004237 for (auto it = sctp_data_channels_.begin(); it != sctp_data_channels_.end();
4238 ++it) {
4239 if (it->get() == channel) {
4240 if (channel->id() >= 0) {
4241 sid_allocator_.ReleaseSid(channel->id());
4242 }
deadbeefbd292462015-12-14 18:15:29 -08004243 // Since this method is triggered by a signal from the DataChannel,
4244 // we can't free it directly here; we need to free it asynchronously.
4245 sctp_data_channels_to_free_.push_back(*it);
deadbeefab9b2d12015-10-14 11:33:11 -07004246 sctp_data_channels_.erase(it);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07004247 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_FREE_DATACHANNELS,
4248 nullptr);
deadbeefab9b2d12015-10-14 11:33:11 -07004249 return;
4250 }
4251 }
4252}
4253
deadbeefab9b2d12015-10-14 11:33:11 -07004254void PeerConnection::OnDataChannelDestroyed() {
4255 // Use a temporary copy of the RTP/SCTP DataChannel list because the
4256 // DataChannel may callback to us and try to modify the list.
4257 std::map<std::string, rtc::scoped_refptr<DataChannel>> temp_rtp_dcs;
4258 temp_rtp_dcs.swap(rtp_data_channels_);
4259 for (const auto& kv : temp_rtp_dcs) {
4260 kv.second->OnTransportChannelDestroyed();
4261 }
4262
4263 std::vector<rtc::scoped_refptr<DataChannel>> temp_sctp_dcs;
4264 temp_sctp_dcs.swap(sctp_data_channels_);
4265 for (const auto& channel : temp_sctp_dcs) {
4266 channel->OnTransportChannelDestroyed();
4267 }
4268}
4269
4270void PeerConnection::OnDataChannelOpenMessage(
4271 const std::string& label,
4272 const InternalDataChannelInit& config) {
4273 rtc::scoped_refptr<DataChannel> channel(
4274 InternalCreateDataChannel(label, &config));
4275 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004276 RTC_LOG(LS_ERROR) << "Failed to create DataChannel from the OPEN message.";
deadbeefab9b2d12015-10-14 11:33:11 -07004277 return;
4278 }
4279
deadbeefa601f5c2016-06-06 14:27:39 -07004280 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
4281 DataChannelProxy::Create(signaling_thread(), channel);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07004282 observer_->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07004283}
4284
Steve Anton4171afb2017-11-20 10:20:22 -08004285rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
4286PeerConnection::GetAudioTransceiver() const {
4287 // This method only works with Plan B SDP, where there is a single
4288 // audio/video transceiver.
4289 RTC_DCHECK(!IsUnifiedPlan());
4290 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08004291 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004292 return transceiver;
4293 }
4294 }
4295 RTC_NOTREACHED();
4296 return nullptr;
4297}
4298
4299rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
4300PeerConnection::GetVideoTransceiver() const {
4301 // This method only works with Plan B SDP, where there is a single
4302 // audio/video transceiver.
4303 RTC_DCHECK(!IsUnifiedPlan());
4304 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08004305 if (transceiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004306 return transceiver;
4307 }
4308 }
4309 RTC_NOTREACHED();
4310 return nullptr;
4311}
4312
4313// TODO(bugs.webrtc.org/7600): Remove this when multiple transceivers with
4314// individual transceiver directions are supported.
zhihuang1c378ed2017-08-17 14:10:50 -07004315bool PeerConnection::HasRtpSender(cricket::MediaType type) const {
Steve Anton4171afb2017-11-20 10:20:22 -08004316 switch (type) {
4317 case cricket::MEDIA_TYPE_AUDIO:
4318 return !GetAudioTransceiver()->internal()->senders().empty();
4319 case cricket::MEDIA_TYPE_VIDEO:
4320 return !GetVideoTransceiver()->internal()->senders().empty();
4321 case cricket::MEDIA_TYPE_DATA:
4322 return false;
4323 }
4324 RTC_NOTREACHED();
4325 return false;
zhihuang1c378ed2017-08-17 14:10:50 -07004326}
4327
Steve Anton4171afb2017-11-20 10:20:22 -08004328rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
4329PeerConnection::FindSenderForTrack(MediaStreamTrackInterface* track) const {
4330 for (auto transceiver : transceivers_) {
4331 for (auto sender : transceiver->internal()->senders()) {
4332 if (sender->track() == track) {
4333 return sender;
4334 }
4335 }
4336 }
4337 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08004338}
4339
Steve Anton4171afb2017-11-20 10:20:22 -08004340rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
4341PeerConnection::FindSenderById(const std::string& sender_id) const {
4342 for (auto transceiver : transceivers_) {
4343 for (auto sender : transceiver->internal()->senders()) {
4344 if (sender->id() == sender_id) {
4345 return sender;
4346 }
4347 }
4348 }
4349 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07004350}
4351
Steve Anton4171afb2017-11-20 10:20:22 -08004352rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
4353PeerConnection::FindReceiverById(const std::string& receiver_id) const {
4354 for (auto transceiver : transceivers_) {
4355 for (auto receiver : transceiver->internal()->receivers()) {
4356 if (receiver->id() == receiver_id) {
4357 return receiver;
4358 }
4359 }
4360 }
4361 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07004362}
4363
Steve Anton4171afb2017-11-20 10:20:22 -08004364std::vector<PeerConnection::RtpSenderInfo>*
4365PeerConnection::GetRemoteSenderInfos(cricket::MediaType media_type) {
4366 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
4367 media_type == cricket::MEDIA_TYPE_VIDEO);
4368 return (media_type == cricket::MEDIA_TYPE_AUDIO)
4369 ? &remote_audio_sender_infos_
4370 : &remote_video_sender_infos_;
4371}
4372
4373std::vector<PeerConnection::RtpSenderInfo>* PeerConnection::GetLocalSenderInfos(
deadbeefab9b2d12015-10-14 11:33:11 -07004374 cricket::MediaType media_type) {
4375 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
4376 media_type == cricket::MEDIA_TYPE_VIDEO);
Steve Anton4171afb2017-11-20 10:20:22 -08004377 return (media_type == cricket::MEDIA_TYPE_AUDIO) ? &local_audio_sender_infos_
4378 : &local_video_sender_infos_;
deadbeefab9b2d12015-10-14 11:33:11 -07004379}
4380
Steve Anton4171afb2017-11-20 10:20:22 -08004381const PeerConnection::RtpSenderInfo* PeerConnection::FindSenderInfo(
4382 const std::vector<PeerConnection::RtpSenderInfo>& infos,
deadbeefab9b2d12015-10-14 11:33:11 -07004383 const std::string& stream_label,
Steve Anton4171afb2017-11-20 10:20:22 -08004384 const std::string sender_id) const {
4385 for (const RtpSenderInfo& sender_info : infos) {
4386 if (sender_info.stream_label == stream_label &&
4387 sender_info.sender_id == sender_id) {
4388 return &sender_info;
deadbeefab9b2d12015-10-14 11:33:11 -07004389 }
4390 }
4391 return nullptr;
4392}
4393
4394DataChannel* PeerConnection::FindDataChannelBySid(int sid) const {
4395 for (const auto& channel : sctp_data_channels_) {
4396 if (channel->id() == sid) {
4397 return channel;
4398 }
4399 }
4400 return nullptr;
4401}
4402
deadbeef91dd5672016-05-18 16:55:30 -07004403bool PeerConnection::InitializePortAllocator_n(
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004404 const RTCConfiguration& configuration) {
4405 cricket::ServerAddresses stun_servers;
4406 std::vector<cricket::RelayServerConfig> turn_servers;
deadbeef293e9262017-01-11 12:28:30 -08004407 if (ParseIceServers(configuration.servers, &stun_servers, &turn_servers) !=
4408 RTCErrorType::NONE) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004409 return false;
4410 }
4411
Taylor Brandstetterf8e65772016-06-27 17:20:15 -07004412 port_allocator_->Initialize();
4413
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004414 // To handle both internal and externally created port allocator, we will
4415 // enable BUNDLE here.
4416 int portallocator_flags = port_allocator_->flags();
4417 portallocator_flags |= cricket::PORTALLOCATOR_ENABLE_SHARED_SOCKET |
zhihuangb09b3f92017-03-07 14:40:51 -08004418 cricket::PORTALLOCATOR_ENABLE_IPV6 |
4419 cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI;
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004420 // If the disable-IPv6 flag was specified, we'll not override it
4421 // by experiment.
4422 if (configuration.disable_ipv6) {
4423 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
sprangc1b57a12017-02-28 08:50:47 -08004424 } else if (webrtc::field_trial::FindFullName("WebRTC-IPv6Default")
4425 .find("Disabled") == 0) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004426 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
4427 }
4428
zhihuangb09b3f92017-03-07 14:40:51 -08004429 if (configuration.disable_ipv6_on_wifi) {
4430 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI);
Mirko Bonadei675513b2017-11-09 11:09:25 +01004431 RTC_LOG(LS_INFO) << "IPv6 candidates on Wi-Fi are disabled.";
zhihuangb09b3f92017-03-07 14:40:51 -08004432 }
4433
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004434 if (configuration.tcp_candidate_policy == kTcpCandidatePolicyDisabled) {
4435 portallocator_flags |= cricket::PORTALLOCATOR_DISABLE_TCP;
Mirko Bonadei675513b2017-11-09 11:09:25 +01004436 RTC_LOG(LS_INFO) << "TCP candidates are disabled.";
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004437 }
4438
honghaiz60347052016-05-31 18:29:12 -07004439 if (configuration.candidate_network_policy ==
4440 kCandidateNetworkPolicyLowCost) {
4441 portallocator_flags |= cricket::PORTALLOCATOR_DISABLE_COSTLY_NETWORKS;
Mirko Bonadei675513b2017-11-09 11:09:25 +01004442 RTC_LOG(LS_INFO) << "Do not gather candidates on high-cost networks";
honghaiz60347052016-05-31 18:29:12 -07004443 }
4444
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +01004445 if (configuration.disable_link_local_networks) {
4446 portallocator_flags |= cricket::PORTALLOCATOR_DISABLE_LINK_LOCAL_NETWORKS;
4447 RTC_LOG(LS_INFO) << "Disable candidates on link-local network interfaces.";
4448 }
4449
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004450 port_allocator_->set_flags(portallocator_flags);
4451 // No step delay is used while allocating ports.
4452 port_allocator_->set_step_delay(cricket::kMinimumStepDelay);
4453 port_allocator_->set_candidate_filter(
4454 ConvertIceTransportTypeToCandidateFilter(configuration.type));
deadbeefd21eab32017-07-26 16:50:11 -07004455 port_allocator_->set_max_ipv6_networks(configuration.max_ipv6_networks);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004456
4457 // Call this last since it may create pooled allocator sessions using the
4458 // properties set above.
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08004459 port_allocator_->SetConfiguration(
4460 stun_servers, turn_servers, configuration.ice_candidate_pool_size,
4461 configuration.prune_turn_ports, configuration.turn_customizer,
4462 configuration.stun_candidate_keepalive_interval);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004463 return true;
4464}
4465
deadbeef91dd5672016-05-18 16:55:30 -07004466bool PeerConnection::ReconfigurePortAllocator_n(
deadbeef293e9262017-01-11 12:28:30 -08004467 const cricket::ServerAddresses& stun_servers,
4468 const std::vector<cricket::RelayServerConfig>& turn_servers,
4469 IceTransportsType type,
4470 int candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02004471 bool prune_turn_ports,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08004472 webrtc::TurnCustomizer* turn_customizer,
4473 rtc::Optional<int> stun_candidate_keepalive_interval) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004474 port_allocator_->set_candidate_filter(
deadbeef293e9262017-01-11 12:28:30 -08004475 ConvertIceTransportTypeToCandidateFilter(type));
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004476 // Call this last since it may create pooled allocator sessions using the
4477 // candidate filter set above.
deadbeef6de92f92016-12-12 18:49:32 -08004478 return port_allocator_->SetConfiguration(
Jonas Orelandbdcee282017-10-10 14:01:40 +02004479 stun_servers, turn_servers, candidate_pool_size, prune_turn_ports,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08004480 turn_customizer, stun_candidate_keepalive_interval);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004481}
4482
Steve Antonba818672017-11-06 10:21:57 -08004483cricket::ChannelManager* PeerConnection::channel_manager() const {
4484 return factory_->channel_manager();
4485}
4486
4487MetricsObserverInterface* PeerConnection::metrics_observer() const {
4488 return uma_observer_;
4489}
4490
Elad Alon99c3fe52017-10-13 16:29:40 +02004491bool PeerConnection::StartRtcEventLog_w(
Bjorn Tereliusde939432017-11-20 17:38:14 +01004492 std::unique_ptr<RtcEventLogOutput> output,
4493 int64_t output_period_ms) {
zhihuang77985012017-02-07 15:45:16 -08004494 if (!event_log_) {
4495 return false;
4496 }
Bjorn Tereliusde939432017-11-20 17:38:14 +01004497 return event_log_->StartLogging(std::move(output), output_period_ms);
ivoc14d5dbe2016-07-04 07:06:55 -07004498}
4499
4500void PeerConnection::StopRtcEventLog_w() {
zhihuang77985012017-02-07 15:45:16 -08004501 if (event_log_) {
4502 event_log_->StopLogging();
4503 }
ivoc14d5dbe2016-07-04 07:06:55 -07004504}
nisseeaabdf62017-05-05 02:23:02 -07004505
Steve Anton75737c02017-11-06 10:37:17 -08004506cricket::BaseChannel* PeerConnection::GetChannel(
4507 const std::string& content_name) {
Steve Antondcc3c022017-12-22 16:02:54 -08004508 for (auto transceiver : transceivers_) {
4509 cricket::BaseChannel* channel = transceiver->internal()->channel();
4510 if (channel && channel->content_name() == content_name) {
4511 return channel;
4512 }
Steve Anton75737c02017-11-06 10:37:17 -08004513 }
4514 if (rtp_data_channel() &&
4515 rtp_data_channel()->content_name() == content_name) {
4516 return rtp_data_channel();
4517 }
4518 return nullptr;
4519}
4520
4521bool PeerConnection::GetSctpSslRole(rtc::SSLRole* role) {
4522 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004523 RTC_LOG(LS_INFO)
4524 << "Local and Remote descriptions must be applied to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004525 "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08004526 return false;
4527 }
4528 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004529 RTC_LOG(LS_INFO) << "Non-rejected SCTP m= section is needed to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004530 "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08004531 return false;
4532 }
4533
4534 return transport_controller_->GetSslRole(*sctp_transport_name_, role);
4535}
4536
4537bool PeerConnection::GetSslRole(const std::string& content_name,
4538 rtc::SSLRole* role) {
4539 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004540 RTC_LOG(LS_INFO)
4541 << "Local and Remote descriptions must be applied to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004542 "SSL Role of the session.";
Steve Anton75737c02017-11-06 10:37:17 -08004543 return false;
4544 }
4545
4546 return transport_controller_->GetSslRole(GetTransportName(content_name),
4547 role);
4548}
4549
Steve Antonf8470812017-12-04 10:46:21 -08004550void PeerConnection::SetSessionError(SessionError error,
4551 const std::string& error_desc) {
4552 RTC_DCHECK_RUN_ON(signaling_thread());
4553 if (error != session_error_) {
4554 session_error_ = error;
4555 session_error_desc_ = error_desc;
Steve Anton75737c02017-11-06 10:37:17 -08004556 }
4557}
4558
Steve Anton3828c062017-12-06 10:34:51 -08004559RTCError PeerConnection::UpdateSessionState(SdpType type,
Steve Anton8a006912017-12-04 15:25:56 -08004560 cricket::ContentSource source) {
4561 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08004562
4563 // If there's already a pending error then no state transition should happen.
4564 // But all call-sites should be verifying this before calling us!
Steve Antonf8470812017-12-04 10:46:21 -08004565 RTC_DCHECK(session_error() == SessionError::kNone);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004566
4567 // If this is an answer then we know whether to BUNDLE or not. If both the
4568 // local and remote side have agreed to BUNDLE, go ahead and enable it.
Steve Anton3828c062017-12-06 10:34:51 -08004569 if (type == SdpType::kAnswer) {
Steve Anton75737c02017-11-06 10:37:17 -08004570 const cricket::ContentGroup* local_bundle =
4571 local_description()->description()->GetGroupByName(
4572 cricket::GROUP_TYPE_BUNDLE);
4573 const cricket::ContentGroup* remote_bundle =
4574 remote_description()->description()->GetGroupByName(
4575 cricket::GROUP_TYPE_BUNDLE);
4576 if (local_bundle && remote_bundle) {
4577 // The answerer decides the transport to bundle on.
4578 const cricket::ContentGroup* answer_bundle =
4579 (source == cricket::CS_LOCAL ? local_bundle : remote_bundle);
4580 if (!EnableBundle(*answer_bundle)) {
Steve Anton8a006912017-12-04 15:25:56 -08004581 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
4582 kEnableBundleFailed);
Steve Anton75737c02017-11-06 10:37:17 -08004583 }
4584 }
Steve Anton75737c02017-11-06 10:37:17 -08004585 }
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004586
4587 // Only push down the transport description after potentially enabling BUNDLE;
4588 // we don't want to push down a description on a transport about to be
4589 // destroyed.
Steve Anton3828c062017-12-06 10:34:51 -08004590 RTCError error = PushdownTransportDescription(source, type);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004591 if (!error.ok()) {
4592 return error;
4593 }
4594
4595 // If this is answer-ish we're ready to let media flow.
Steve Anton3828c062017-12-06 10:34:51 -08004596 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Antoned10bd92017-12-05 10:52:59 -08004597 EnableSending();
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004598 }
4599
4600 // Update the signaling state according to the specified state machine (see
4601 // https://w3c.github.io/webrtc-pc/#rtcsignalingstate-enum).
Steve Anton3828c062017-12-06 10:34:51 -08004602 if (type == SdpType::kOffer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004603 ChangeSignalingState(source == cricket::CS_LOCAL
4604 ? PeerConnectionInterface::kHaveLocalOffer
4605 : PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton3828c062017-12-06 10:34:51 -08004606 } else if (type == SdpType::kPrAnswer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004607 ChangeSignalingState(source == cricket::CS_LOCAL
4608 ? PeerConnectionInterface::kHaveLocalPrAnswer
4609 : PeerConnectionInterface::kHaveRemotePrAnswer);
4610 } else {
Steve Anton3828c062017-12-06 10:34:51 -08004611 RTC_DCHECK(type == SdpType::kAnswer);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004612 ChangeSignalingState(PeerConnectionInterface::kStable);
4613 }
4614
4615 // Update internal objects according to the session description's media
4616 // descriptions.
Steve Anton3828c062017-12-06 10:34:51 -08004617 error = PushdownMediaDescription(type, source);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004618 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08004619 return error;
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004620 }
4621
Steve Anton8a006912017-12-04 15:25:56 -08004622 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08004623}
4624
Steve Anton8a006912017-12-04 15:25:56 -08004625RTCError PeerConnection::PushdownMediaDescription(
Steve Anton3828c062017-12-06 10:34:51 -08004626 SdpType type,
Steve Anton8a006912017-12-04 15:25:56 -08004627 cricket::ContentSource source) {
Steve Antoned10bd92017-12-05 10:52:59 -08004628 const SessionDescriptionInterface* sdesc =
4629 (source == cricket::CS_LOCAL ? local_description()
4630 : remote_description());
Steve Anton75737c02017-11-06 10:37:17 -08004631 RTC_DCHECK(sdesc);
Steve Antoned10bd92017-12-05 10:52:59 -08004632
4633 // Push down the new SDP media section for each audio/video transceiver.
4634 for (auto transceiver : transceivers_) {
Steve Anton75737c02017-11-06 10:37:17 -08004635 const ContentInfo* content_info =
Steve Antoned10bd92017-12-05 10:52:59 -08004636 FindMediaSectionForTransceiver(transceiver, sdesc);
4637 cricket::BaseChannel* channel = transceiver->internal()->channel();
4638 if (!channel || !content_info || content_info->rejected) {
Steve Anton75737c02017-11-06 10:37:17 -08004639 continue;
4640 }
4641 const MediaContentDescription* content_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08004642 content_info->media_description();
Steve Antoned10bd92017-12-05 10:52:59 -08004643 if (!content_desc) {
4644 continue;
4645 }
4646 std::string error;
4647 bool success =
4648 (source == cricket::CS_LOCAL)
Steve Anton3828c062017-12-06 10:34:51 -08004649 ? channel->SetLocalContent(content_desc, type, &error)
4650 : channel->SetRemoteContent(content_desc, type, &error);
Steve Antoned10bd92017-12-05 10:52:59 -08004651 if (!success) {
4652 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, std::move(error));
4653 }
4654 }
4655
4656 // If using the RtpDataChannel, push down the new SDP section for it too.
4657 if (rtp_data_channel_) {
4658 const ContentInfo* data_content =
4659 cricket::GetFirstDataContent(sdesc->description());
4660 if (data_content && !data_content->rejected) {
4661 const MediaContentDescription* data_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08004662 data_content->media_description();
Steve Antoned10bd92017-12-05 10:52:59 -08004663 if (data_desc) {
4664 std::string error;
4665 bool success =
4666 (source == cricket::CS_LOCAL)
Steve Anton3828c062017-12-06 10:34:51 -08004667 ? rtp_data_channel_->SetLocalContent(data_desc, type, &error)
4668 : rtp_data_channel_->SetRemoteContent(data_desc, type,
Steve Antoned10bd92017-12-05 10:52:59 -08004669 &error);
4670 if (!success) {
4671 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
4672 std::move(error));
4673 }
Steve Anton75737c02017-11-06 10:37:17 -08004674 }
4675 }
4676 }
Steve Antoned10bd92017-12-05 10:52:59 -08004677
Steve Anton75737c02017-11-06 10:37:17 -08004678 // Need complete offer/answer with an SCTP m= section before starting SCTP,
4679 // according to https://tools.ietf.org/html/draft-ietf-mmusic-sctp-sdp-19
4680 if (sctp_transport_ && local_description() && remote_description() &&
4681 cricket::GetFirstDataContent(local_description()->description()) &&
4682 cricket::GetFirstDataContent(remote_description()->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08004683 bool success = network_thread()->Invoke<bool>(
Steve Anton75737c02017-11-06 10:37:17 -08004684 RTC_FROM_HERE,
4685 rtc::Bind(&PeerConnection::PushdownSctpParameters_n, this, source));
Steve Anton8a006912017-12-04 15:25:56 -08004686 if (!success) {
4687 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
4688 "Failed to push down SCTP parameters.");
4689 }
Steve Anton75737c02017-11-06 10:37:17 -08004690 }
Steve Antoned10bd92017-12-05 10:52:59 -08004691
Steve Anton8a006912017-12-04 15:25:56 -08004692 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08004693}
4694
4695bool PeerConnection::PushdownSctpParameters_n(cricket::ContentSource source) {
4696 RTC_DCHECK(network_thread()->IsCurrent());
4697 RTC_DCHECK(local_description());
4698 RTC_DCHECK(remote_description());
4699 // Apply the SCTP port (which is hidden inside a DataCodec structure...)
4700 // When we support "max-message-size", that would also be pushed down here.
4701 return sctp_transport_->Start(
4702 GetSctpPort(local_description()->description()),
4703 GetSctpPort(remote_description()->description()));
4704}
4705
Steve Anton8a006912017-12-04 15:25:56 -08004706RTCError PeerConnection::PushdownTransportDescription(
4707 cricket::ContentSource source,
Steve Anton3828c062017-12-06 10:34:51 -08004708 SdpType type) {
Steve Anton8a006912017-12-04 15:25:56 -08004709 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08004710
Steve Anton8a006912017-12-04 15:25:56 -08004711 const SessionDescriptionInterface* sdesc =
4712 (source == cricket::CS_LOCAL ? local_description()
4713 : remote_description());
4714 RTC_DCHECK(sdesc);
4715 for (const cricket::TransportInfo& tinfo :
4716 sdesc->description()->transport_infos()) {
4717 std::string error;
4718 bool success;
4719 if (source == cricket::CS_LOCAL) {
4720 success = transport_controller_->SetLocalTransportDescription(
Steve Anton3828c062017-12-06 10:34:51 -08004721 tinfo.content_name, tinfo.description, type, &error);
Steve Anton8a006912017-12-04 15:25:56 -08004722 } else {
4723 success = transport_controller_->SetRemoteTransportDescription(
Steve Anton3828c062017-12-06 10:34:51 -08004724 tinfo.content_name, tinfo.description, type, &error);
Steve Anton8a006912017-12-04 15:25:56 -08004725 }
4726 if (!success) {
Steve Antondcc3c022017-12-22 16:02:54 -08004727 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
4728 "Failed to push down transport description for " +
4729 tinfo.content_name + ": " + error);
Steve Anton75737c02017-11-06 10:37:17 -08004730 }
4731 }
4732
Steve Anton8a006912017-12-04 15:25:56 -08004733 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08004734}
4735
4736bool PeerConnection::GetTransportDescription(
4737 const SessionDescription* description,
4738 const std::string& content_name,
4739 cricket::TransportDescription* tdesc) {
4740 if (!description || !tdesc) {
4741 return false;
4742 }
4743 const TransportInfo* transport_info =
4744 description->GetTransportInfoByName(content_name);
4745 if (!transport_info) {
4746 return false;
4747 }
4748 *tdesc = transport_info->description;
4749 return true;
4750}
4751
4752bool PeerConnection::EnableBundle(const cricket::ContentGroup& bundle) {
4753 const std::string* first_content_name = bundle.FirstContentName();
4754 if (!first_content_name) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004755 RTC_LOG(LS_WARNING) << "Tried to BUNDLE with no contents.";
Steve Anton75737c02017-11-06 10:37:17 -08004756 return false;
4757 }
4758 const std::string& transport_name = *first_content_name;
4759
4760 auto maybe_set_transport = [this, bundle,
4761 transport_name](cricket::BaseChannel* ch) {
4762 if (!ch || !bundle.HasContentName(ch->content_name())) {
Steve Antoned10bd92017-12-05 10:52:59 -08004763 return;
Steve Anton75737c02017-11-06 10:37:17 -08004764 }
4765
4766 std::string old_transport_name = ch->transport_name();
4767 if (old_transport_name == transport_name) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004768 RTC_LOG(LS_INFO) << "BUNDLE already enabled for " << ch->content_name()
4769 << " on " << transport_name << ".";
Steve Antoned10bd92017-12-05 10:52:59 -08004770 return;
Steve Anton75737c02017-11-06 10:37:17 -08004771 }
4772
4773 cricket::DtlsTransportInternal* rtp_dtls_transport =
4774 transport_controller_->CreateDtlsTransport(
4775 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4776 bool need_rtcp = (ch->rtcp_dtls_transport() != nullptr);
4777 cricket::DtlsTransportInternal* rtcp_dtls_transport = nullptr;
4778 if (need_rtcp) {
4779 rtcp_dtls_transport = transport_controller_->CreateDtlsTransport(
4780 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
4781 }
4782
4783 ch->SetTransports(rtp_dtls_transport, rtcp_dtls_transport);
Mirko Bonadei675513b2017-11-09 11:09:25 +01004784 RTC_LOG(LS_INFO) << "Enabled BUNDLE for " << ch->content_name() << " on "
4785 << transport_name << ".";
Steve Anton75737c02017-11-06 10:37:17 -08004786 transport_controller_->DestroyDtlsTransport(
4787 old_transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4788 // If the channel needs rtcp, it means that the channel used to have a
4789 // rtcp transport which needs to be deleted now.
4790 if (need_rtcp) {
4791 transport_controller_->DestroyDtlsTransport(
4792 old_transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
4793 }
Steve Anton75737c02017-11-06 10:37:17 -08004794 };
4795
Steve Antoned10bd92017-12-05 10:52:59 -08004796 for (auto transceiver : transceivers_) {
4797 maybe_set_transport(transceiver->internal()->channel());
Steve Anton75737c02017-11-06 10:37:17 -08004798 }
Steve Antoned10bd92017-12-05 10:52:59 -08004799 maybe_set_transport(rtp_data_channel_);
4800
Steve Anton75737c02017-11-06 10:37:17 -08004801 // For SCTP, transport creation/deletion happens here instead of in the
4802 // object itself.
4803 if (sctp_transport_) {
4804 RTC_DCHECK(sctp_transport_name_);
4805 RTC_DCHECK(sctp_content_name_);
4806 if (transport_name != *sctp_transport_name_ &&
4807 bundle.HasContentName(*sctp_content_name_)) {
4808 network_thread()->Invoke<void>(
4809 RTC_FROM_HERE, rtc::Bind(&PeerConnection::ChangeSctpTransport_n, this,
4810 transport_name));
4811 }
4812 }
4813
4814 return true;
4815}
4816
Steve Anton75737c02017-11-06 10:37:17 -08004817cricket::IceConfig PeerConnection::ParseIceConfig(
4818 const PeerConnectionInterface::RTCConfiguration& config) const {
4819 cricket::ContinualGatheringPolicy gathering_policy;
4820 // TODO(honghaiz): Add the third continual gathering policy in
4821 // PeerConnectionInterface and map it to GATHER_CONTINUALLY_AND_RECOVER.
4822 switch (config.continual_gathering_policy) {
4823 case PeerConnectionInterface::GATHER_ONCE:
4824 gathering_policy = cricket::GATHER_ONCE;
4825 break;
4826 case PeerConnectionInterface::GATHER_CONTINUALLY:
4827 gathering_policy = cricket::GATHER_CONTINUALLY;
4828 break;
4829 default:
4830 RTC_NOTREACHED();
4831 gathering_policy = cricket::GATHER_ONCE;
4832 }
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08004833
Steve Anton75737c02017-11-06 10:37:17 -08004834 cricket::IceConfig ice_config;
4835 ice_config.receiving_timeout = config.ice_connection_receiving_timeout;
4836 ice_config.prioritize_most_likely_candidate_pairs =
4837 config.prioritize_most_likely_ice_candidate_pairs;
4838 ice_config.backup_connection_ping_interval =
4839 config.ice_backup_candidate_pair_ping_interval;
4840 ice_config.continual_gathering_policy = gathering_policy;
4841 ice_config.presume_writable_when_fully_relayed =
4842 config.presume_writable_when_fully_relayed;
4843 ice_config.ice_check_min_interval = config.ice_check_min_interval;
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08004844 ice_config.stun_keepalive_interval = config.stun_candidate_keepalive_interval;
Steve Anton75737c02017-11-06 10:37:17 -08004845 ice_config.regather_all_networks_interval_range =
4846 config.ice_regather_interval_range;
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08004847 ice_config.network_preference = config.network_preference;
Steve Anton75737c02017-11-06 10:37:17 -08004848 return ice_config;
4849}
4850
Steve Anton75737c02017-11-06 10:37:17 -08004851bool PeerConnection::GetLocalTrackIdBySsrc(uint32_t ssrc,
4852 std::string* track_id) {
4853 if (!local_description()) {
4854 return false;
4855 }
4856 return webrtc::GetTrackIdBySsrc(local_description()->description(), ssrc,
4857 track_id);
4858}
4859
4860bool PeerConnection::GetRemoteTrackIdBySsrc(uint32_t ssrc,
4861 std::string* track_id) {
4862 if (!remote_description()) {
4863 return false;
4864 }
4865 return webrtc::GetTrackIdBySsrc(remote_description()->description(), ssrc,
4866 track_id);
4867}
4868
4869bool PeerConnection::SendData(const cricket::SendDataParams& params,
4870 const rtc::CopyOnWriteBuffer& payload,
4871 cricket::SendDataResult* result) {
4872 if (!rtp_data_channel_ && !sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004873 RTC_LOG(LS_ERROR) << "SendData called when rtp_data_channel_ "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004874 "and sctp_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08004875 return false;
4876 }
4877 return rtp_data_channel_
4878 ? rtp_data_channel_->SendData(params, payload, result)
4879 : network_thread()->Invoke<bool>(
4880 RTC_FROM_HERE,
4881 Bind(&cricket::SctpTransportInternal::SendData,
4882 sctp_transport_.get(), params, payload, result));
4883}
4884
4885bool PeerConnection::ConnectDataChannel(DataChannel* webrtc_data_channel) {
4886 if (!rtp_data_channel_ && !sctp_transport_) {
4887 // Don't log an error here, because DataChannels are expected to call
4888 // ConnectDataChannel in this state. It's the only way to initially tell
4889 // whether or not the underlying transport is ready.
4890 return false;
4891 }
4892 if (rtp_data_channel_) {
4893 rtp_data_channel_->SignalReadyToSendData.connect(
4894 webrtc_data_channel, &DataChannel::OnChannelReady);
4895 rtp_data_channel_->SignalDataReceived.connect(webrtc_data_channel,
4896 &DataChannel::OnDataReceived);
4897 } else {
4898 SignalSctpReadyToSendData.connect(webrtc_data_channel,
4899 &DataChannel::OnChannelReady);
4900 SignalSctpDataReceived.connect(webrtc_data_channel,
4901 &DataChannel::OnDataReceived);
4902 SignalSctpStreamClosedRemotely.connect(
4903 webrtc_data_channel, &DataChannel::OnStreamClosedRemotely);
4904 }
4905 return true;
4906}
4907
4908void PeerConnection::DisconnectDataChannel(DataChannel* webrtc_data_channel) {
4909 if (!rtp_data_channel_ && !sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004910 RTC_LOG(LS_ERROR)
4911 << "DisconnectDataChannel called when rtp_data_channel_ and "
4912 "sctp_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08004913 return;
4914 }
4915 if (rtp_data_channel_) {
4916 rtp_data_channel_->SignalReadyToSendData.disconnect(webrtc_data_channel);
4917 rtp_data_channel_->SignalDataReceived.disconnect(webrtc_data_channel);
4918 } else {
4919 SignalSctpReadyToSendData.disconnect(webrtc_data_channel);
4920 SignalSctpDataReceived.disconnect(webrtc_data_channel);
4921 SignalSctpStreamClosedRemotely.disconnect(webrtc_data_channel);
4922 }
4923}
4924
4925void PeerConnection::AddSctpDataStream(int sid) {
4926 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004927 RTC_LOG(LS_ERROR)
4928 << "AddSctpDataStream called when sctp_transport_ is NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08004929 return;
4930 }
4931 network_thread()->Invoke<void>(
4932 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::OpenStream,
4933 sctp_transport_.get(), sid));
4934}
4935
4936void PeerConnection::RemoveSctpDataStream(int sid) {
4937 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004938 RTC_LOG(LS_ERROR) << "RemoveSctpDataStream called when sctp_transport_ is "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004939 "NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08004940 return;
4941 }
4942 network_thread()->Invoke<void>(
4943 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::ResetStream,
4944 sctp_transport_.get(), sid));
4945}
4946
4947bool PeerConnection::ReadyToSendData() const {
4948 return (rtp_data_channel_ && rtp_data_channel_->ready_to_send_data()) ||
4949 sctp_ready_to_send_data_;
4950}
4951
Qingsi Wang72a43a12018-02-20 16:03:18 -08004952cricket::CandidateStatsList PeerConnection::GetPooledCandidateStats() const {
4953 cricket::CandidateStatsList candidate_states_list;
4954 port_allocator_->GetCandidateStatsFromPooledSessions(&candidate_states_list);
4955 return candidate_states_list;
4956}
4957
Steve Anton5dfde182018-02-06 10:34:40 -08004958std::map<std::string, std::string> PeerConnection::GetTransportNamesByMid()
4959 const {
4960 std::map<std::string, std::string> transport_names_by_mid;
4961 for (auto transceiver : transceivers_) {
4962 cricket::BaseChannel* channel = transceiver->internal()->channel();
4963 if (channel) {
4964 transport_names_by_mid[channel->content_name()] =
4965 channel->transport_name();
4966 }
Steve Anton75737c02017-11-06 10:37:17 -08004967 }
Steve Anton5dfde182018-02-06 10:34:40 -08004968 if (rtp_data_channel_) {
4969 transport_names_by_mid[rtp_data_channel_->content_name()] =
4970 rtp_data_channel_->transport_name();
Steve Anton75737c02017-11-06 10:37:17 -08004971 }
4972 if (sctp_transport_) {
Steve Anton5dfde182018-02-06 10:34:40 -08004973 transport_names_by_mid[*sctp_content_name_] = *sctp_transport_name_;
Steve Anton75737c02017-11-06 10:37:17 -08004974 }
Steve Anton5dfde182018-02-06 10:34:40 -08004975 return transport_names_by_mid;
Steve Anton75737c02017-11-06 10:37:17 -08004976}
4977
Steve Anton5dfde182018-02-06 10:34:40 -08004978std::map<std::string, cricket::TransportStats>
4979PeerConnection::GetTransportStatsByNames(
4980 const std::set<std::string>& transport_names) {
4981 if (!network_thread()->IsCurrent()) {
4982 return network_thread()
4983 ->Invoke<std::map<std::string, cricket::TransportStats>>(
4984 RTC_FROM_HERE,
4985 [&] { return GetTransportStatsByNames(transport_names); });
Steve Anton75737c02017-11-06 10:37:17 -08004986 }
Steve Anton5dfde182018-02-06 10:34:40 -08004987 std::map<std::string, cricket::TransportStats> transport_stats_by_name;
4988 for (const std::string& transport_name : transport_names) {
4989 cricket::TransportStats transport_stats;
4990 bool success =
4991 transport_controller_->GetStats(transport_name, &transport_stats);
4992 if (success) {
4993 transport_stats_by_name[transport_name] = std::move(transport_stats);
4994 } else {
4995 RTC_LOG(LS_ERROR) << "Failed to get transport stats for transport_name="
4996 << transport_name;
4997 }
4998 }
4999 return transport_stats_by_name;
Steve Anton75737c02017-11-06 10:37:17 -08005000}
5001
5002bool PeerConnection::GetLocalCertificate(
5003 const std::string& transport_name,
5004 rtc::scoped_refptr<rtc::RTCCertificate>* certificate) {
5005 return transport_controller_->GetLocalCertificate(transport_name,
5006 certificate);
5007}
5008
Taylor Brandstetterc3928662018-02-23 13:04:51 -08005009std::unique_ptr<rtc::SSLCertChain> PeerConnection::GetRemoteSSLCertChain(
Steve Anton75737c02017-11-06 10:37:17 -08005010 const std::string& transport_name) {
Taylor Brandstetterc3928662018-02-23 13:04:51 -08005011 return transport_controller_->GetRemoteSSLCertChain(transport_name);
Steve Anton75737c02017-11-06 10:37:17 -08005012}
5013
5014cricket::DataChannelType PeerConnection::data_channel_type() const {
5015 return data_channel_type_;
5016}
5017
5018bool PeerConnection::IceRestartPending(const std::string& content_name) const {
5019 return pending_ice_restarts_.find(content_name) !=
5020 pending_ice_restarts_.end();
5021}
5022
Steve Anton75737c02017-11-06 10:37:17 -08005023bool PeerConnection::NeedsIceRestart(const std::string& content_name) const {
5024 return transport_controller_->NeedsIceRestart(content_name);
5025}
5026
5027void PeerConnection::OnCertificateReady(
5028 const rtc::scoped_refptr<rtc::RTCCertificate>& certificate) {
5029 transport_controller_->SetLocalCertificate(certificate);
5030}
5031
5032void PeerConnection::OnDtlsSrtpSetupFailure(cricket::BaseChannel*, bool rtcp) {
Steve Antonf8470812017-12-04 10:46:21 -08005033 SetSessionError(SessionError::kTransport,
5034 rtcp ? kDtlsSrtpSetupFailureRtcp : kDtlsSrtpSetupFailureRtp);
Steve Anton75737c02017-11-06 10:37:17 -08005035}
5036
5037void PeerConnection::OnTransportControllerConnectionState(
5038 cricket::IceConnectionState state) {
5039 switch (state) {
5040 case cricket::kIceConnectionConnecting:
5041 // If the current state is Connected or Completed, then there were
5042 // writable channels but now there are not, so the next state must
5043 // be Disconnected.
5044 // kIceConnectionConnecting is currently used as the default,
5045 // un-connected state by the TransportController, so its only use is
5046 // detecting disconnections.
5047 if (ice_connection_state_ ==
5048 PeerConnectionInterface::kIceConnectionConnected ||
5049 ice_connection_state_ ==
5050 PeerConnectionInterface::kIceConnectionCompleted) {
5051 SetIceConnectionState(
5052 PeerConnectionInterface::kIceConnectionDisconnected);
5053 }
5054 break;
5055 case cricket::kIceConnectionFailed:
5056 SetIceConnectionState(PeerConnectionInterface::kIceConnectionFailed);
5057 break;
5058 case cricket::kIceConnectionConnected:
Mirko Bonadei675513b2017-11-09 11:09:25 +01005059 RTC_LOG(LS_INFO) << "Changing to ICE connected state because "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005060 "all transports are writable.";
Steve Anton75737c02017-11-06 10:37:17 -08005061 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
5062 break;
5063 case cricket::kIceConnectionCompleted:
Mirko Bonadei675513b2017-11-09 11:09:25 +01005064 RTC_LOG(LS_INFO) << "Changing to ICE completed state because "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005065 "all transports are complete.";
Steve Anton75737c02017-11-06 10:37:17 -08005066 if (ice_connection_state_ !=
5067 PeerConnectionInterface::kIceConnectionConnected) {
5068 // If jumping directly from "checking" to "connected",
5069 // signal "connected" first.
5070 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
5071 }
5072 SetIceConnectionState(PeerConnectionInterface::kIceConnectionCompleted);
5073 if (metrics_observer()) {
5074 ReportTransportStats();
5075 }
5076 break;
5077 default:
5078 RTC_NOTREACHED();
5079 }
5080}
5081
5082void PeerConnection::OnTransportControllerCandidatesGathered(
5083 const std::string& transport_name,
5084 const cricket::Candidates& candidates) {
5085 RTC_DCHECK(signaling_thread()->IsCurrent());
5086 int sdp_mline_index;
5087 if (!GetLocalCandidateMediaIndex(transport_name, &sdp_mline_index)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005088 RTC_LOG(LS_ERROR)
5089 << "OnTransportControllerCandidatesGathered: content name "
5090 << transport_name << " not found";
Steve Anton75737c02017-11-06 10:37:17 -08005091 return;
5092 }
5093
5094 for (cricket::Candidates::const_iterator citer = candidates.begin();
5095 citer != candidates.end(); ++citer) {
5096 // Use transport_name as the candidate media id.
5097 std::unique_ptr<JsepIceCandidate> candidate(
5098 new JsepIceCandidate(transport_name, sdp_mline_index, *citer));
5099 if (local_description()) {
5100 mutable_local_description()->AddCandidate(candidate.get());
5101 }
5102 OnIceCandidate(std::move(candidate));
5103 }
5104}
5105
5106void PeerConnection::OnTransportControllerCandidatesRemoved(
5107 const std::vector<cricket::Candidate>& candidates) {
5108 RTC_DCHECK(signaling_thread()->IsCurrent());
5109 // Sanity check.
5110 for (const cricket::Candidate& candidate : candidates) {
5111 if (candidate.transport_name().empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005112 RTC_LOG(LS_ERROR) << "OnTransportControllerCandidatesRemoved: "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005113 "empty content name in candidate "
Mirko Bonadei675513b2017-11-09 11:09:25 +01005114 << candidate.ToString();
Steve Anton75737c02017-11-06 10:37:17 -08005115 return;
5116 }
5117 }
5118
5119 if (local_description()) {
5120 mutable_local_description()->RemoveCandidates(candidates);
5121 }
5122 OnIceCandidatesRemoved(candidates);
5123}
5124
5125void PeerConnection::OnTransportControllerDtlsHandshakeError(
5126 rtc::SSLHandshakeError error) {
5127 if (metrics_observer()) {
5128 metrics_observer()->IncrementEnumCounter(
5129 webrtc::kEnumCounterDtlsHandshakeError, static_cast<int>(error),
5130 static_cast<int>(rtc::SSLHandshakeError::MAX_VALUE));
5131 }
5132}
5133
Steve Antoned10bd92017-12-05 10:52:59 -08005134void PeerConnection::EnableSending() {
5135 for (auto transceiver : transceivers_) {
5136 cricket::BaseChannel* channel = transceiver->internal()->channel();
5137 if (channel && !channel->enabled()) {
5138 channel->Enable(true);
5139 }
Steve Anton75737c02017-11-06 10:37:17 -08005140 }
5141
Steve Anton4171afb2017-11-20 10:20:22 -08005142 if (rtp_data_channel_ && !rtp_data_channel_->enabled()) {
Steve Anton75737c02017-11-06 10:37:17 -08005143 rtp_data_channel_->Enable(true);
Steve Anton4171afb2017-11-20 10:20:22 -08005144 }
Steve Anton75737c02017-11-06 10:37:17 -08005145}
5146
5147// Returns the media index for a local ice candidate given the content name.
5148bool PeerConnection::GetLocalCandidateMediaIndex(
5149 const std::string& content_name,
5150 int* sdp_mline_index) {
5151 if (!local_description() || !sdp_mline_index) {
5152 return false;
5153 }
5154
5155 bool content_found = false;
5156 const ContentInfos& contents = local_description()->description()->contents();
5157 for (size_t index = 0; index < contents.size(); ++index) {
5158 if (contents[index].name == content_name) {
5159 *sdp_mline_index = static_cast<int>(index);
5160 content_found = true;
5161 break;
5162 }
5163 }
5164 return content_found;
5165}
5166
5167bool PeerConnection::UseCandidatesInSessionDescription(
5168 const SessionDescriptionInterface* remote_desc) {
5169 if (!remote_desc) {
5170 return true;
5171 }
5172 bool ret = true;
5173
5174 for (size_t m = 0; m < remote_desc->number_of_mediasections(); ++m) {
5175 const IceCandidateCollection* candidates = remote_desc->candidates(m);
5176 for (size_t n = 0; n < candidates->count(); ++n) {
5177 const IceCandidateInterface* candidate = candidates->at(n);
5178 bool valid = false;
5179 if (!ReadyToUseRemoteCandidate(candidate, remote_desc, &valid)) {
5180 if (valid) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005181 RTC_LOG(LS_INFO)
5182 << "UseCandidatesInSessionDescription: Not ready to use "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005183 "candidate.";
Steve Anton75737c02017-11-06 10:37:17 -08005184 }
5185 continue;
5186 }
5187 ret = UseCandidate(candidate);
5188 if (!ret) {
5189 break;
5190 }
5191 }
5192 }
5193 return ret;
5194}
5195
5196bool PeerConnection::UseCandidate(const IceCandidateInterface* candidate) {
5197 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
5198 size_t remote_content_size =
5199 remote_description()->description()->contents().size();
5200 if (mediacontent_index >= remote_content_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005201 RTC_LOG(LS_ERROR) << "UseCandidate: Invalid candidate media index.";
Steve Anton75737c02017-11-06 10:37:17 -08005202 return false;
5203 }
5204
5205 cricket::ContentInfo content =
5206 remote_description()->description()->contents()[mediacontent_index];
5207 std::vector<cricket::Candidate> candidates;
5208 candidates.push_back(candidate->candidate());
5209 // Invoking BaseSession method to handle remote candidates.
5210 std::string error;
5211 if (transport_controller_->AddRemoteCandidates(content.name, candidates,
5212 &error)) {
5213 // Candidates successfully submitted for checking.
5214 if (ice_connection_state_ == PeerConnectionInterface::kIceConnectionNew ||
5215 ice_connection_state_ ==
5216 PeerConnectionInterface::kIceConnectionDisconnected) {
5217 // If state is New, then the session has just gotten its first remote ICE
5218 // candidates, so go to Checking.
5219 // If state is Disconnected, the session is re-using old candidates or
5220 // receiving additional ones, so go to Checking.
5221 // If state is Connected, stay Connected.
5222 // TODO(bemasc): If state is Connected, and the new candidates are for a
5223 // newly added transport, then the state actually _should_ move to
5224 // checking. Add a way to distinguish that case.
5225 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
5226 }
5227 // TODO(bemasc): If state is Completed, go back to Connected.
5228 } else {
5229 if (!error.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005230 RTC_LOG(LS_WARNING) << error;
Steve Anton75737c02017-11-06 10:37:17 -08005231 }
5232 }
5233 return true;
5234}
5235
5236void PeerConnection::RemoveUnusedChannels(const SessionDescription* desc) {
Steve Anton75737c02017-11-06 10:37:17 -08005237 // Destroy video channel first since it may have a pointer to the
5238 // voice channel.
5239 const cricket::ContentInfo* video_info = cricket::GetFirstVideoContent(desc);
Steve Anton6fec8802017-12-04 10:37:29 -08005240 if (!video_info || video_info->rejected) {
5241 DestroyTransceiverChannel(GetVideoTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08005242 }
5243
Steve Anton6fec8802017-12-04 10:37:29 -08005244 const cricket::ContentInfo* audio_info = cricket::GetFirstAudioContent(desc);
5245 if (!audio_info || audio_info->rejected) {
5246 DestroyTransceiverChannel(GetAudioTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08005247 }
5248
5249 const cricket::ContentInfo* data_info = cricket::GetFirstDataContent(desc);
5250 if (!data_info || data_info->rejected) {
Steve Anton6fec8802017-12-04 10:37:29 -08005251 DestroyDataChannel();
Steve Anton75737c02017-11-06 10:37:17 -08005252 }
5253}
5254
Steve Antoneda6ccd2017-12-04 10:21:55 -08005255std::string PeerConnection::GetTransportNameForMediaSection(
5256 const std::string& mid,
5257 const cricket::ContentGroup* bundle_group) const {
5258 if (!bundle_group) {
5259 return mid;
Steve Anton75737c02017-11-06 10:37:17 -08005260 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005261 const std::string* first_content_name = bundle_group->FirstContentName();
Steve Anton75737c02017-11-06 10:37:17 -08005262 if (!first_content_name) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005263 RTC_LOG(LS_WARNING) << "Tried to BUNDLE with no contents.";
Steve Antoneda6ccd2017-12-04 10:21:55 -08005264 return mid;
Steve Anton75737c02017-11-06 10:37:17 -08005265 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005266 if (!bundle_group->HasContentName(mid)) {
5267 RTC_LOG(LS_WARNING) << mid << " is not part of any bundle group";
5268 return mid;
Steve Anton75737c02017-11-06 10:37:17 -08005269 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005270 RTC_LOG(LS_INFO) << "Bundling " << mid << " on " << *first_content_name;
5271 return *first_content_name;
Steve Anton75737c02017-11-06 10:37:17 -08005272}
5273
Steve Antondcc3c022017-12-22 16:02:54 -08005274RTCErrorOr<const cricket::ContentGroup*> PeerConnection::GetEarlyBundleGroup(
5275 const SessionDescription& desc) const {
Steve Anton75737c02017-11-06 10:37:17 -08005276 const cricket::ContentGroup* bundle_group = nullptr;
5277 if (configuration_.bundle_policy ==
5278 PeerConnectionInterface::kBundlePolicyMaxBundle) {
Steve Antondcc3c022017-12-22 16:02:54 -08005279 bundle_group = desc.GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton75737c02017-11-06 10:37:17 -08005280 if (!bundle_group) {
Steve Anton8a006912017-12-04 15:25:56 -08005281 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5282 "max-bundle configured but session description "
5283 "has no BUNDLE group");
Steve Anton75737c02017-11-06 10:37:17 -08005284 }
5285 }
Steve Antondcc3c022017-12-22 16:02:54 -08005286 return std::move(bundle_group);
5287}
5288
5289RTCError PeerConnection::CreateChannels(const SessionDescription& desc) {
5290 auto bundle_group_or_error = GetEarlyBundleGroup(desc);
5291 if (!bundle_group_or_error.ok()) {
5292 return bundle_group_or_error.MoveError();
5293 }
5294 const cricket::ContentGroup* bundle_group = bundle_group_or_error.MoveValue();
Steve Anton75737c02017-11-06 10:37:17 -08005295
Steve Antoneda6ccd2017-12-04 10:21:55 -08005296 // Creating the media channels and transport proxies.
Steve Antondcc3c022017-12-22 16:02:54 -08005297 const cricket::ContentInfo* voice = cricket::GetFirstAudioContent(&desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08005298 if (voice && !voice->rejected &&
5299 !GetAudioTransceiver()->internal()->channel()) {
5300 cricket::VoiceChannel* voice_channel = CreateVoiceChannel(
5301 voice->name,
5302 GetTransportNameForMediaSection(voice->name, bundle_group));
5303 if (!voice_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08005304 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5305 "Failed to create voice channel.");
Steve Antoneda6ccd2017-12-04 10:21:55 -08005306 }
5307 GetAudioTransceiver()->internal()->SetChannel(voice_channel);
5308 }
5309
Steve Antondcc3c022017-12-22 16:02:54 -08005310 const cricket::ContentInfo* video = cricket::GetFirstVideoContent(&desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08005311 if (video && !video->rejected &&
5312 !GetVideoTransceiver()->internal()->channel()) {
5313 cricket::VideoChannel* video_channel = CreateVideoChannel(
5314 video->name,
5315 GetTransportNameForMediaSection(video->name, bundle_group));
5316 if (!video_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08005317 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5318 "Failed to create video channel.");
Steve Anton75737c02017-11-06 10:37:17 -08005319 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005320 GetVideoTransceiver()->internal()->SetChannel(video_channel);
Steve Anton75737c02017-11-06 10:37:17 -08005321 }
5322
Steve Antondcc3c022017-12-22 16:02:54 -08005323 const cricket::ContentInfo* data = cricket::GetFirstDataContent(&desc);
Steve Anton75737c02017-11-06 10:37:17 -08005324 if (data_channel_type_ != cricket::DCT_NONE && data && !data->rejected &&
5325 !rtp_data_channel_ && !sctp_transport_) {
Steve Antoneda6ccd2017-12-04 10:21:55 -08005326 if (!CreateDataChannel(data->name, GetTransportNameForMediaSection(
5327 data->name, bundle_group))) {
Steve Anton8a006912017-12-04 15:25:56 -08005328 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5329 "Failed to create data channel.");
Steve Anton75737c02017-11-06 10:37:17 -08005330 }
5331 }
5332
Steve Anton8a006912017-12-04 15:25:56 -08005333 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08005334}
5335
Steve Anton4171afb2017-11-20 10:20:22 -08005336// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08005337cricket::VoiceChannel* PeerConnection::CreateVoiceChannel(
5338 const std::string& mid,
5339 const std::string& transport_name) {
Steve Anton75737c02017-11-06 10:37:17 -08005340 cricket::DtlsTransportInternal* rtp_dtls_transport =
5341 transport_controller_->CreateDtlsTransport(
5342 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5343 cricket::DtlsTransportInternal* rtcp_dtls_transport = nullptr;
5344 if (configuration_.rtcp_mux_policy !=
5345 PeerConnectionInterface::kRtcpMuxPolicyRequire) {
5346 rtcp_dtls_transport = transport_controller_->CreateDtlsTransport(
5347 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
5348 }
5349
5350 cricket::VoiceChannel* voice_channel = channel_manager()->CreateVoiceChannel(
5351 call_.get(), configuration_.media_config, rtp_dtls_transport,
Steve Antoneda6ccd2017-12-04 10:21:55 -08005352 rtcp_dtls_transport, signaling_thread(), mid, SrtpRequired(),
5353 audio_options_);
Steve Anton75737c02017-11-06 10:37:17 -08005354 if (!voice_channel) {
5355 transport_controller_->DestroyDtlsTransport(
5356 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5357 if (rtcp_dtls_transport) {
5358 transport_controller_->DestroyDtlsTransport(
5359 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
5360 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005361 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08005362 }
Steve Anton75737c02017-11-06 10:37:17 -08005363 voice_channel->SignalRtcpMuxFullyActive.connect(
5364 this, &PeerConnection::DestroyRtcpTransport_n);
5365 voice_channel->SignalDtlsSrtpSetupFailure.connect(
5366 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08005367 voice_channel->SignalSentPacket.connect(this,
5368 &PeerConnection::OnSentPacket_w);
Steve Anton4171afb2017-11-20 10:20:22 -08005369
Steve Antoneda6ccd2017-12-04 10:21:55 -08005370 return voice_channel;
Steve Anton75737c02017-11-06 10:37:17 -08005371}
5372
Steve Anton4171afb2017-11-20 10:20:22 -08005373// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08005374cricket::VideoChannel* PeerConnection::CreateVideoChannel(
5375 const std::string& mid,
5376 const std::string& transport_name) {
Steve Anton75737c02017-11-06 10:37:17 -08005377 cricket::DtlsTransportInternal* rtp_dtls_transport =
5378 transport_controller_->CreateDtlsTransport(
5379 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5380 cricket::DtlsTransportInternal* rtcp_dtls_transport = nullptr;
5381 if (configuration_.rtcp_mux_policy !=
5382 PeerConnectionInterface::kRtcpMuxPolicyRequire) {
5383 rtcp_dtls_transport = transport_controller_->CreateDtlsTransport(
5384 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
5385 }
5386
5387 cricket::VideoChannel* video_channel = channel_manager()->CreateVideoChannel(
5388 call_.get(), configuration_.media_config, rtp_dtls_transport,
Steve Antoneda6ccd2017-12-04 10:21:55 -08005389 rtcp_dtls_transport, signaling_thread(), mid, SrtpRequired(),
5390 video_options_);
Steve Anton75737c02017-11-06 10:37:17 -08005391
5392 if (!video_channel) {
5393 transport_controller_->DestroyDtlsTransport(
5394 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5395 if (rtcp_dtls_transport) {
5396 transport_controller_->DestroyDtlsTransport(
5397 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
5398 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005399 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08005400 }
Steve Anton75737c02017-11-06 10:37:17 -08005401 video_channel->SignalRtcpMuxFullyActive.connect(
5402 this, &PeerConnection::DestroyRtcpTransport_n);
5403 video_channel->SignalDtlsSrtpSetupFailure.connect(
5404 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08005405 video_channel->SignalSentPacket.connect(this,
5406 &PeerConnection::OnSentPacket_w);
Steve Anton4171afb2017-11-20 10:20:22 -08005407
Steve Antoneda6ccd2017-12-04 10:21:55 -08005408 return video_channel;
Steve Anton75737c02017-11-06 10:37:17 -08005409}
5410
Steve Antoneda6ccd2017-12-04 10:21:55 -08005411bool PeerConnection::CreateDataChannel(const std::string& mid,
5412 const std::string& transport_name) {
Steve Anton75737c02017-11-06 10:37:17 -08005413 bool sctp = (data_channel_type_ == cricket::DCT_SCTP);
5414 if (sctp) {
5415 if (!sctp_factory_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005416 RTC_LOG(LS_ERROR)
Steve Anton75737c02017-11-06 10:37:17 -08005417 << "Trying to create SCTP transport, but didn't compile with "
5418 "SCTP support (HAVE_SCTP)";
5419 return false;
5420 }
5421 if (!network_thread()->Invoke<bool>(
5422 RTC_FROM_HERE, rtc::Bind(&PeerConnection::CreateSctpTransport_n,
Steve Antoneda6ccd2017-12-04 10:21:55 -08005423 this, mid, transport_name))) {
Steve Anton75737c02017-11-06 10:37:17 -08005424 return false;
5425 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005426 for (const auto& channel : sctp_data_channels_) {
5427 channel->OnTransportChannelCreated();
5428 }
Steve Anton75737c02017-11-06 10:37:17 -08005429 } else {
Steve Anton75737c02017-11-06 10:37:17 -08005430 cricket::DtlsTransportInternal* rtp_dtls_transport =
5431 transport_controller_->CreateDtlsTransport(
5432 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5433 cricket::DtlsTransportInternal* rtcp_dtls_transport = nullptr;
5434 if (configuration_.rtcp_mux_policy !=
5435 PeerConnectionInterface::kRtcpMuxPolicyRequire) {
5436 rtcp_dtls_transport = transport_controller_->CreateDtlsTransport(
5437 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
5438 }
5439
5440 rtp_data_channel_ = channel_manager()->CreateRtpDataChannel(
5441 configuration_.media_config, rtp_dtls_transport, rtcp_dtls_transport,
Steve Antoneda6ccd2017-12-04 10:21:55 -08005442 signaling_thread(), mid, SrtpRequired());
Steve Anton75737c02017-11-06 10:37:17 -08005443
5444 if (!rtp_data_channel_) {
5445 transport_controller_->DestroyDtlsTransport(
5446 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5447 if (rtcp_dtls_transport) {
5448 transport_controller_->DestroyDtlsTransport(
5449 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
5450 }
5451 return false;
5452 }
5453
5454 rtp_data_channel_->SignalRtcpMuxFullyActive.connect(
5455 this, &PeerConnection::DestroyRtcpTransport_n);
5456 rtp_data_channel_->SignalDtlsSrtpSetupFailure.connect(
5457 this, &PeerConnection::OnDtlsSrtpSetupFailure);
5458 rtp_data_channel_->SignalSentPacket.connect(
5459 this, &PeerConnection::OnSentPacket_w);
5460 }
5461
Steve Anton75737c02017-11-06 10:37:17 -08005462 return true;
5463}
5464
5465Call::Stats PeerConnection::GetCallStats() {
5466 if (!worker_thread()->IsCurrent()) {
5467 return worker_thread()->Invoke<Call::Stats>(
5468 RTC_FROM_HERE, rtc::Bind(&PeerConnection::GetCallStats, this));
5469 }
5470 if (call_) {
5471 return call_->GetStats();
5472 } else {
5473 return Call::Stats();
5474 }
5475}
5476
Steve Anton75737c02017-11-06 10:37:17 -08005477bool PeerConnection::CreateSctpTransport_n(const std::string& content_name,
5478 const std::string& transport_name) {
5479 RTC_DCHECK(network_thread()->IsCurrent());
5480 RTC_DCHECK(sctp_factory_);
5481 cricket::DtlsTransportInternal* tc =
5482 transport_controller_->CreateDtlsTransport_n(
5483 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5484 sctp_transport_ = sctp_factory_->CreateSctpTransport(tc);
5485 RTC_DCHECK(sctp_transport_);
5486 sctp_invoker_.reset(new rtc::AsyncInvoker());
5487 sctp_transport_->SignalReadyToSendData.connect(
5488 this, &PeerConnection::OnSctpTransportReadyToSendData_n);
5489 sctp_transport_->SignalDataReceived.connect(
5490 this, &PeerConnection::OnSctpTransportDataReceived_n);
5491 sctp_transport_->SignalStreamClosedRemotely.connect(
5492 this, &PeerConnection::OnSctpStreamClosedRemotely_n);
Oskar Sundbom9b28a032017-11-16 10:53:30 +01005493 sctp_transport_name_ = transport_name;
5494 sctp_content_name_ = content_name;
Steve Anton75737c02017-11-06 10:37:17 -08005495 return true;
5496}
5497
5498void PeerConnection::ChangeSctpTransport_n(const std::string& transport_name) {
5499 RTC_DCHECK(network_thread()->IsCurrent());
5500 RTC_DCHECK(sctp_transport_);
5501 RTC_DCHECK(sctp_transport_name_);
5502 std::string old_sctp_transport_name = *sctp_transport_name_;
Oskar Sundbom9b28a032017-11-16 10:53:30 +01005503 sctp_transport_name_ = transport_name;
Steve Anton75737c02017-11-06 10:37:17 -08005504 cricket::DtlsTransportInternal* tc =
5505 transport_controller_->CreateDtlsTransport_n(
5506 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5507 sctp_transport_->SetTransportChannel(tc);
5508 transport_controller_->DestroyDtlsTransport_n(
5509 old_sctp_transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5510}
5511
5512void PeerConnection::DestroySctpTransport_n() {
5513 RTC_DCHECK(network_thread()->IsCurrent());
5514 sctp_transport_.reset(nullptr);
Taylor Brandstetter389a97c2018-01-03 16:26:06 -08005515 transport_controller_->DestroyDtlsTransport_n(
5516 *sctp_transport_name_, cricket::ICE_CANDIDATE_COMPONENT_RTP);
Steve Anton75737c02017-11-06 10:37:17 -08005517 sctp_content_name_.reset();
5518 sctp_transport_name_.reset();
5519 sctp_invoker_.reset(nullptr);
5520 sctp_ready_to_send_data_ = false;
5521}
5522
5523void PeerConnection::OnSctpTransportReadyToSendData_n() {
5524 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5525 RTC_DCHECK(network_thread()->IsCurrent());
5526 // Note: Cannot use rtc::Bind here because it will grab a reference to
5527 // PeerConnection and potentially cause PeerConnection to live longer than
5528 // expected. It is safe not to grab a reference since the sctp_invoker_ will
5529 // be destroyed before PeerConnection is destroyed, and at that point all
5530 // pending tasks will be cleared.
5531 sctp_invoker_->AsyncInvoke<void>(RTC_FROM_HERE, signaling_thread(), [this] {
5532 OnSctpTransportReadyToSendData_s(true);
5533 });
5534}
5535
5536void PeerConnection::OnSctpTransportReadyToSendData_s(bool ready) {
5537 RTC_DCHECK(signaling_thread()->IsCurrent());
5538 sctp_ready_to_send_data_ = ready;
5539 SignalSctpReadyToSendData(ready);
5540}
5541
5542void PeerConnection::OnSctpTransportDataReceived_n(
5543 const cricket::ReceiveDataParams& params,
5544 const rtc::CopyOnWriteBuffer& payload) {
5545 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5546 RTC_DCHECK(network_thread()->IsCurrent());
5547 // Note: Cannot use rtc::Bind here because it will grab a reference to
5548 // PeerConnection and potentially cause PeerConnection to live longer than
5549 // expected. It is safe not to grab a reference since the sctp_invoker_ will
5550 // be destroyed before PeerConnection is destroyed, and at that point all
5551 // pending tasks will be cleared.
5552 sctp_invoker_->AsyncInvoke<void>(
5553 RTC_FROM_HERE, signaling_thread(), [this, params, payload] {
5554 OnSctpTransportDataReceived_s(params, payload);
5555 });
5556}
5557
5558void PeerConnection::OnSctpTransportDataReceived_s(
5559 const cricket::ReceiveDataParams& params,
5560 const rtc::CopyOnWriteBuffer& payload) {
5561 RTC_DCHECK(signaling_thread()->IsCurrent());
5562 if (params.type == cricket::DMT_CONTROL && IsOpenMessage(payload)) {
5563 // Received OPEN message; parse and signal that a new data channel should
5564 // be created.
5565 std::string label;
5566 InternalDataChannelInit config;
5567 config.id = params.ssrc;
5568 if (!ParseDataChannelOpenMessage(payload, &label, &config)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005569 RTC_LOG(LS_WARNING) << "Failed to parse the OPEN message for sid "
5570 << params.ssrc;
Steve Anton75737c02017-11-06 10:37:17 -08005571 return;
5572 }
5573 config.open_handshake_role = InternalDataChannelInit::kAcker;
5574 OnDataChannelOpenMessage(label, config);
5575 } else {
5576 // Otherwise just forward the signal.
5577 SignalSctpDataReceived(params, payload);
5578 }
5579}
5580
5581void PeerConnection::OnSctpStreamClosedRemotely_n(int sid) {
5582 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5583 RTC_DCHECK(network_thread()->IsCurrent());
5584 sctp_invoker_->AsyncInvoke<void>(
5585 RTC_FROM_HERE, signaling_thread(),
5586 rtc::Bind(&sigslot::signal1<int>::operator(),
5587 &SignalSctpStreamClosedRemotely, sid));
5588}
5589
5590// Returns false if bundle is enabled and rtcp_mux is disabled.
5591bool PeerConnection::ValidateBundleSettings(const SessionDescription* desc) {
5592 bool bundle_enabled = desc->HasGroup(cricket::GROUP_TYPE_BUNDLE);
5593 if (!bundle_enabled)
5594 return true;
5595
5596 const cricket::ContentGroup* bundle_group =
5597 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
5598 RTC_DCHECK(bundle_group != NULL);
5599
5600 const cricket::ContentInfos& contents = desc->contents();
5601 for (cricket::ContentInfos::const_iterator citer = contents.begin();
5602 citer != contents.end(); ++citer) {
5603 const cricket::ContentInfo* content = (&*citer);
5604 RTC_DCHECK(content != NULL);
5605 if (bundle_group->HasContentName(content->name) && !content->rejected &&
Steve Anton5adfafd2017-12-20 16:34:00 -08005606 content->type == MediaProtocolType::kRtp) {
Steve Anton75737c02017-11-06 10:37:17 -08005607 if (!HasRtcpMuxEnabled(content))
5608 return false;
5609 }
5610 }
5611 // RTCP-MUX is enabled in all the contents.
5612 return true;
5613}
5614
5615bool PeerConnection::HasRtcpMuxEnabled(const cricket::ContentInfo* content) {
Steve Antonb1c1de12017-12-21 15:14:30 -08005616 return content->media_description()->rtcp_mux();
Steve Anton75737c02017-11-06 10:37:17 -08005617}
5618
Steve Anton8a006912017-12-04 15:25:56 -08005619RTCError PeerConnection::ValidateSessionDescription(
Steve Anton75737c02017-11-06 10:37:17 -08005620 const SessionDescriptionInterface* sdesc,
Steve Anton8a006912017-12-04 15:25:56 -08005621 cricket::ContentSource source) {
Steve Antonf8470812017-12-04 10:46:21 -08005622 if (session_error() != SessionError::kNone) {
Steve Anton8a006912017-12-04 15:25:56 -08005623 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
Steve Anton75737c02017-11-06 10:37:17 -08005624 }
5625
5626 if (!sdesc || !sdesc->description()) {
Steve Anton8a006912017-12-04 15:25:56 -08005627 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidSdp);
Steve Anton75737c02017-11-06 10:37:17 -08005628 }
5629
Steve Anton3828c062017-12-06 10:34:51 -08005630 SdpType type = sdesc->GetType();
5631 if ((source == cricket::CS_LOCAL && !ExpectSetLocalDescription(type)) ||
5632 (source == cricket::CS_REMOTE && !ExpectSetRemoteDescription(type))) {
Steve Anton8a006912017-12-04 15:25:56 -08005633 LOG_AND_RETURN_ERROR(
5634 RTCErrorType::INVALID_PARAMETER,
5635 "Called in wrong state: " + GetSignalingStateString(signaling_state()));
Steve Anton75737c02017-11-06 10:37:17 -08005636 }
5637
5638 // Verify crypto settings.
5639 std::string crypto_error;
Steve Anton8a006912017-12-04 15:25:56 -08005640 if (webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED ||
5641 dtls_enabled_) {
Harald Alvestrand194939b2018-01-24 16:04:13 +01005642 RTCError crypto_error =
5643 VerifyCrypto(sdesc->description(), dtls_enabled_, uma_observer_);
Steve Anton8a006912017-12-04 15:25:56 -08005644 if (!crypto_error.ok()) {
5645 return crypto_error;
5646 }
Steve Anton75737c02017-11-06 10:37:17 -08005647 }
5648
5649 // Verify ice-ufrag and ice-pwd.
5650 if (!VerifyIceUfragPwdPresent(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08005651 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5652 kSdpWithoutIceUfragPwd);
Steve Anton75737c02017-11-06 10:37:17 -08005653 }
5654
5655 if (!ValidateBundleSettings(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08005656 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5657 kBundleWithoutRtcpMux);
Steve Anton75737c02017-11-06 10:37:17 -08005658 }
5659
5660 // TODO(skvlad): When the local rtcp-mux policy is Require, reject any
5661 // m-lines that do not rtcp-mux enabled.
5662
5663 // Verify m-lines in Answer when compared against Offer.
Steve Anton3828c062017-12-06 10:34:51 -08005664 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Seth Hampsonae8a90a2018-02-13 15:33:48 -08005665 // With an answer we want to compare the new answer session description with
5666 // the offer's session description from the current negotiation.
Steve Anton75737c02017-11-06 10:37:17 -08005667 const cricket::SessionDescription* offer_desc =
5668 (source == cricket::CS_LOCAL) ? remote_description()->description()
5669 : local_description()->description();
Seth Hampsonae8a90a2018-02-13 15:33:48 -08005670 if (!MediaSectionsHaveSameCount(*offer_desc, *sdesc->description()) ||
5671 !MediaSectionsInSameOrder(*offer_desc, nullptr, *sdesc->description(),
5672 type)) {
Steve Anton8a006912017-12-04 15:25:56 -08005673 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5674 kMlineMismatchInAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08005675 }
5676 } else {
Steve Anton75737c02017-11-06 10:37:17 -08005677 // The re-offers should respect the order of m= sections in current
5678 // description. See RFC3264 Section 8 paragraph 4 for more details.
Seth Hampsonae8a90a2018-02-13 15:33:48 -08005679 // With a re-offer, either the current local or current remote descriptions
5680 // could be the most up to date, so we would like to check against both of
5681 // them if they exist. It could be the case that one of them has a 0 port
5682 // for a media section, but the other does not. This is important to check
5683 // against in the case that we are recycling an m= section.
5684 const cricket::SessionDescription* current_desc = nullptr;
5685 const cricket::SessionDescription* secondary_current_desc = nullptr;
5686 if (local_description()) {
5687 current_desc = local_description()->description();
5688 if (remote_description()) {
5689 secondary_current_desc = remote_description()->description();
5690 }
5691 } else if (remote_description()) {
5692 current_desc = remote_description()->description();
5693 }
Steve Anton75737c02017-11-06 10:37:17 -08005694 if (current_desc &&
Seth Hampsonae8a90a2018-02-13 15:33:48 -08005695 !MediaSectionsInSameOrder(*current_desc, secondary_current_desc,
5696 *sdesc->description(), type)) {
Steve Anton8a006912017-12-04 15:25:56 -08005697 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5698 kMlineMismatchInSubsequentOffer);
Steve Anton75737c02017-11-06 10:37:17 -08005699 }
5700 }
5701
Steve Anton8a006912017-12-04 15:25:56 -08005702 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08005703}
5704
Steve Anton3828c062017-12-06 10:34:51 -08005705bool PeerConnection::ExpectSetLocalDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08005706 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08005707 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08005708 return (state == PeerConnectionInterface::kStable) ||
5709 (state == PeerConnectionInterface::kHaveLocalOffer);
Steve Anton20393062017-12-04 16:24:52 -08005710 } else {
Steve Anton3828c062017-12-06 10:34:51 -08005711 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08005712 return (state == PeerConnectionInterface::kHaveRemoteOffer) ||
5713 (state == PeerConnectionInterface::kHaveLocalPrAnswer);
5714 }
5715}
5716
Steve Anton3828c062017-12-06 10:34:51 -08005717bool PeerConnection::ExpectSetRemoteDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08005718 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08005719 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08005720 return (state == PeerConnectionInterface::kStable) ||
5721 (state == PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton20393062017-12-04 16:24:52 -08005722 } else {
Steve Anton3828c062017-12-06 10:34:51 -08005723 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08005724 return (state == PeerConnectionInterface::kHaveLocalOffer) ||
5725 (state == PeerConnectionInterface::kHaveRemotePrAnswer);
5726 }
5727}
5728
Steve Antonf8470812017-12-04 10:46:21 -08005729const char* PeerConnection::SessionErrorToString(SessionError error) const {
5730 switch (error) {
5731 case SessionError::kNone:
5732 return "ERROR_NONE";
5733 case SessionError::kContent:
5734 return "ERROR_CONTENT";
5735 case SessionError::kTransport:
5736 return "ERROR_TRANSPORT";
5737 }
5738 RTC_NOTREACHED();
5739 return "";
5740}
5741
Steve Anton75737c02017-11-06 10:37:17 -08005742std::string PeerConnection::GetSessionErrorMsg() {
5743 std::ostringstream desc;
Steve Antonf8470812017-12-04 10:46:21 -08005744 desc << kSessionError << SessionErrorToString(session_error()) << ". ";
5745 desc << kSessionErrorDesc << session_error_desc() << ".";
Steve Anton75737c02017-11-06 10:37:17 -08005746 return desc.str();
5747}
5748
5749// We need to check the local/remote description for the Transport instead of
5750// the session, because a new Transport added during renegotiation may have
5751// them unset while the session has them set from the previous negotiation.
5752// Not doing so may trigger the auto generation of transport description and
5753// mess up DTLS identity information, ICE credential, etc.
5754bool PeerConnection::ReadyToUseRemoteCandidate(
5755 const IceCandidateInterface* candidate,
5756 const SessionDescriptionInterface* remote_desc,
5757 bool* valid) {
5758 *valid = true;
5759
5760 const SessionDescriptionInterface* current_remote_desc =
5761 remote_desc ? remote_desc : remote_description();
5762
5763 if (!current_remote_desc) {
5764 return false;
5765 }
5766
5767 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
5768 size_t remote_content_size =
5769 current_remote_desc->description()->contents().size();
5770 if (mediacontent_index >= remote_content_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005771 RTC_LOG(LS_ERROR)
5772 << "ReadyToUseRemoteCandidate: Invalid candidate media index "
5773 << mediacontent_index;
Steve Anton75737c02017-11-06 10:37:17 -08005774
5775 *valid = false;
5776 return false;
5777 }
5778
5779 cricket::ContentInfo content =
5780 current_remote_desc->description()->contents()[mediacontent_index];
5781
5782 const std::string transport_name = GetTransportName(content.name);
5783 if (transport_name.empty()) {
5784 return false;
5785 }
5786 return transport_controller_->ReadyForRemoteCandidates(transport_name);
5787}
5788
5789bool PeerConnection::SrtpRequired() const {
5790 return dtls_enabled_ ||
5791 webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED;
5792}
5793
5794void PeerConnection::OnTransportControllerGatheringState(
5795 cricket::IceGatheringState state) {
5796 RTC_DCHECK(signaling_thread()->IsCurrent());
5797 if (state == cricket::kIceGatheringGathering) {
5798 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringGathering);
5799 } else if (state == cricket::kIceGatheringComplete) {
5800 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringComplete);
5801 }
5802}
5803
5804void PeerConnection::ReportTransportStats() {
Steve Antonc7b964c2018-02-01 14:39:45 -08005805 std::map<std::string, std::set<cricket::MediaType>>
5806 media_types_by_transport_name;
5807 for (auto transceiver : transceivers_) {
5808 if (transceiver->internal()->channel()) {
5809 const std::string& transport_name =
5810 transceiver->internal()->channel()->transport_name();
5811 media_types_by_transport_name[transport_name].insert(
Steve Anton69470252018-02-09 11:43:08 -08005812 transceiver->media_type());
Steve Antonc7b964c2018-02-01 14:39:45 -08005813 }
Steve Anton75737c02017-11-06 10:37:17 -08005814 }
5815 if (rtp_data_channel()) {
Steve Antonc7b964c2018-02-01 14:39:45 -08005816 media_types_by_transport_name[rtp_data_channel()->transport_name()].insert(
5817 cricket::MEDIA_TYPE_DATA);
Steve Anton75737c02017-11-06 10:37:17 -08005818 }
5819 if (sctp_transport_name_) {
Steve Antonc7b964c2018-02-01 14:39:45 -08005820 media_types_by_transport_name[*sctp_transport_name_].insert(
5821 cricket::MEDIA_TYPE_DATA);
Steve Anton75737c02017-11-06 10:37:17 -08005822 }
Steve Antonc7b964c2018-02-01 14:39:45 -08005823 for (const auto& entry : media_types_by_transport_name) {
5824 const std::string& transport_name = entry.first;
5825 const std::set<cricket::MediaType> media_types = entry.second;
Steve Anton75737c02017-11-06 10:37:17 -08005826 cricket::TransportStats stats;
Steve Antonc7b964c2018-02-01 14:39:45 -08005827 if (transport_controller_->GetStats(transport_name, &stats)) {
Steve Anton75737c02017-11-06 10:37:17 -08005828 ReportBestConnectionState(stats);
Steve Antonc7b964c2018-02-01 14:39:45 -08005829 ReportNegotiatedCiphers(stats, media_types);
Steve Anton75737c02017-11-06 10:37:17 -08005830 }
5831 }
5832}
5833// Walk through the ConnectionInfos to gather best connection usage
5834// for IPv4 and IPv6.
5835void PeerConnection::ReportBestConnectionState(
5836 const cricket::TransportStats& stats) {
5837 RTC_DCHECK(metrics_observer());
Steve Antonc7b964c2018-02-01 14:39:45 -08005838 for (const cricket::TransportChannelStats& channel_stats :
5839 stats.channel_stats) {
5840 for (const cricket::ConnectionInfo& connection_info :
5841 channel_stats.connection_infos) {
5842 if (!connection_info.best_connection) {
Steve Anton75737c02017-11-06 10:37:17 -08005843 continue;
5844 }
5845
5846 PeerConnectionEnumCounterType type = kPeerConnectionEnumCounterMax;
Steve Antonc7b964c2018-02-01 14:39:45 -08005847 const cricket::Candidate& local = connection_info.local_candidate;
5848 const cricket::Candidate& remote = connection_info.remote_candidate;
Steve Anton75737c02017-11-06 10:37:17 -08005849
5850 // Increment the counter for IceCandidatePairType.
5851 if (local.protocol() == cricket::TCP_PROTOCOL_NAME ||
5852 (local.type() == RELAY_PORT_TYPE &&
5853 local.relay_protocol() == cricket::TCP_PROTOCOL_NAME)) {
5854 type = kEnumCounterIceCandidatePairTypeTcp;
5855 } else if (local.protocol() == cricket::UDP_PROTOCOL_NAME) {
5856 type = kEnumCounterIceCandidatePairTypeUdp;
5857 } else {
5858 RTC_CHECK(0);
5859 }
5860 metrics_observer()->IncrementEnumCounter(
5861 type, GetIceCandidatePairCounter(local, remote),
5862 kIceCandidatePairMax);
5863
5864 // Increment the counter for IP type.
5865 if (local.address().family() == AF_INET) {
5866 metrics_observer()->IncrementEnumCounter(
5867 kEnumCounterAddressFamily, kBestConnections_IPv4,
5868 kPeerConnectionAddressFamilyCounter_Max);
5869
5870 } else if (local.address().family() == AF_INET6) {
5871 metrics_observer()->IncrementEnumCounter(
5872 kEnumCounterAddressFamily, kBestConnections_IPv6,
5873 kPeerConnectionAddressFamilyCounter_Max);
5874 } else {
5875 RTC_CHECK(0);
5876 }
5877
5878 return;
5879 }
5880 }
5881}
5882
5883void PeerConnection::ReportNegotiatedCiphers(
Steve Antonc7b964c2018-02-01 14:39:45 -08005884 const cricket::TransportStats& stats,
5885 const std::set<cricket::MediaType>& media_types) {
Steve Anton75737c02017-11-06 10:37:17 -08005886 RTC_DCHECK(metrics_observer());
5887 if (!dtls_enabled_ || stats.channel_stats.empty()) {
5888 return;
5889 }
5890
5891 int srtp_crypto_suite = stats.channel_stats[0].srtp_crypto_suite;
5892 int ssl_cipher_suite = stats.channel_stats[0].ssl_cipher_suite;
5893 if (srtp_crypto_suite == rtc::SRTP_INVALID_CRYPTO_SUITE &&
5894 ssl_cipher_suite == rtc::TLS_NULL_WITH_NULL_NULL) {
5895 return;
5896 }
5897
Steve Antonc7b964c2018-02-01 14:39:45 -08005898 for (cricket::MediaType media_type : media_types) {
5899 PeerConnectionEnumCounterType srtp_counter_type;
5900 PeerConnectionEnumCounterType ssl_counter_type;
5901 switch (media_type) {
5902 case cricket::MEDIA_TYPE_AUDIO:
5903 srtp_counter_type = kEnumCounterAudioSrtpCipher;
5904 ssl_counter_type = kEnumCounterAudioSslCipher;
5905 break;
5906 case cricket::MEDIA_TYPE_VIDEO:
5907 srtp_counter_type = kEnumCounterVideoSrtpCipher;
5908 ssl_counter_type = kEnumCounterVideoSslCipher;
5909 break;
5910 case cricket::MEDIA_TYPE_DATA:
5911 srtp_counter_type = kEnumCounterDataSrtpCipher;
5912 ssl_counter_type = kEnumCounterDataSslCipher;
5913 break;
5914 default:
5915 RTC_NOTREACHED();
5916 continue;
5917 }
5918 if (srtp_crypto_suite != rtc::SRTP_INVALID_CRYPTO_SUITE) {
5919 metrics_observer()->IncrementSparseEnumCounter(srtp_counter_type,
5920 srtp_crypto_suite);
5921 }
5922 if (ssl_cipher_suite != rtc::TLS_NULL_WITH_NULL_NULL) {
5923 metrics_observer()->IncrementSparseEnumCounter(ssl_counter_type,
5924 ssl_cipher_suite);
5925 }
Steve Anton75737c02017-11-06 10:37:17 -08005926 }
5927}
5928
5929void PeerConnection::OnSentPacket_w(const rtc::SentPacket& sent_packet) {
5930 RTC_DCHECK(worker_thread()->IsCurrent());
5931 RTC_DCHECK(call_);
5932 call_->OnSentPacket(sent_packet);
5933}
5934
5935const std::string PeerConnection::GetTransportName(
5936 const std::string& content_name) {
5937 cricket::BaseChannel* channel = GetChannel(content_name);
Steve Anton6fec8802017-12-04 10:37:29 -08005938 if (channel) {
5939 return channel->transport_name();
Steve Anton75737c02017-11-06 10:37:17 -08005940 }
Steve Anton6fec8802017-12-04 10:37:29 -08005941 if (sctp_transport_) {
5942 RTC_DCHECK(sctp_content_name_);
5943 RTC_DCHECK(sctp_transport_name_);
5944 if (content_name == *sctp_content_name_) {
5945 return *sctp_transport_name_;
5946 }
5947 }
5948 // Return an empty string if failed to retrieve the transport name.
5949 return "";
Steve Anton75737c02017-11-06 10:37:17 -08005950}
5951
5952void PeerConnection::DestroyRtcpTransport_n(const std::string& transport_name) {
5953 RTC_DCHECK(network_thread()->IsCurrent());
5954 transport_controller_->DestroyDtlsTransport_n(
5955 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
5956}
5957
Steve Anton6fec8802017-12-04 10:37:29 -08005958void PeerConnection::DestroyTransceiverChannel(
5959 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
5960 transceiver) {
5961 RTC_DCHECK(transceiver);
Steve Anton75737c02017-11-06 10:37:17 -08005962
Steve Anton6fec8802017-12-04 10:37:29 -08005963 cricket::BaseChannel* channel = transceiver->internal()->channel();
5964 if (channel) {
5965 transceiver->internal()->SetChannel(nullptr);
5966 DestroyBaseChannel(channel);
Steve Anton75737c02017-11-06 10:37:17 -08005967 }
5968}
5969
5970void PeerConnection::DestroyDataChannel() {
Steve Anton6fec8802017-12-04 10:37:29 -08005971 if (rtp_data_channel_) {
5972 OnDataChannelDestroyed();
5973 DestroyBaseChannel(rtp_data_channel_);
5974 rtp_data_channel_ = nullptr;
5975 }
5976
5977 // Note: Cannot use rtc::Bind to create a functor to invoke because it will
5978 // grab a reference to this PeerConnection. If this is called from the
5979 // PeerConnection destructor, the RefCountedObject vtable will have already
5980 // been destroyed (since it is a subclass of PeerConnection) and using
5981 // rtc::Bind will cause "Pure virtual function called" error to appear.
5982
5983 if (sctp_transport_) {
5984 OnDataChannelDestroyed();
5985 network_thread()->Invoke<void>(RTC_FROM_HERE,
5986 [this] { DestroySctpTransport_n(); });
5987 }
5988}
5989
5990void PeerConnection::DestroyBaseChannel(cricket::BaseChannel* channel) {
5991 RTC_DCHECK(channel);
5992 RTC_DCHECK(channel->rtp_dtls_transport());
5993
5994 // Need to cache these before destroying the base channel so that we do not
5995 // access uninitialized memory.
5996 const std::string transport_name =
5997 channel->rtp_dtls_transport()->transport_name();
5998 const bool need_to_delete_rtcp = (channel->rtcp_dtls_transport() != nullptr);
5999
6000 switch (channel->media_type()) {
6001 case cricket::MEDIA_TYPE_AUDIO:
6002 channel_manager()->DestroyVoiceChannel(
6003 static_cast<cricket::VoiceChannel*>(channel));
6004 break;
6005 case cricket::MEDIA_TYPE_VIDEO:
6006 channel_manager()->DestroyVideoChannel(
6007 static_cast<cricket::VideoChannel*>(channel));
6008 break;
6009 case cricket::MEDIA_TYPE_DATA:
6010 channel_manager()->DestroyRtpDataChannel(
6011 static_cast<cricket::RtpDataChannel*>(channel));
6012 break;
6013 default:
6014 RTC_NOTREACHED() << "Unknown media type: " << channel->media_type();
6015 break;
6016 }
6017
6018 // |channel| can no longer be used.
6019
Steve Anton75737c02017-11-06 10:37:17 -08006020 transport_controller_->DestroyDtlsTransport(
6021 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
6022 if (need_to_delete_rtcp) {
6023 transport_controller_->DestroyDtlsTransport(
6024 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
6025 }
6026}
6027
Harald Alvestrand89061872018-01-02 14:08:34 +01006028void PeerConnection::ClearStatsCache() {
6029 if (stats_collector_) {
6030 stats_collector_->ClearCachedStatsReport();
6031 }
6032}
6033
henrike@webrtc.org28e20752013-07-10 00:45:36 +00006034} // namespace webrtc