blob: 428530fac00e984a935de278de5c459daafdef59 [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()));
Steve Anton0ffaaa22018-02-23 10:31:30 -08001838 // Make UMA notes about what was agreed to.
1839 ReportNegotiatedSdpSemantics(*local_description());
Steve Anton8a006912017-12-04 15:25:56 -08001840 }
1841}
1842
1843RTCError PeerConnection::ApplyLocalDescription(
1844 std::unique_ptr<SessionDescriptionInterface> desc) {
1845 RTC_DCHECK_RUN_ON(signaling_thread());
1846 RTC_DCHECK(desc);
1847
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001848 // Update stats here so that we have the most recent stats for tracks and
1849 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001850 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 15:25:56 -08001851
1852 // Update the initial_offerer flag if this session is the initial_offerer.
Steve Anton3828c062017-12-06 10:34:51 -08001853 SdpType type = desc->GetType();
Steve Anton8a006912017-12-04 15:25:56 -08001854 if (!initial_offerer_.has_value()) {
Steve Anton3828c062017-12-06 10:34:51 -08001855 initial_offerer_.emplace(type == SdpType::kOffer);
Steve Anton8a006912017-12-04 15:25:56 -08001856 if (*initial_offerer_) {
1857 transport_controller_->SetIceRole(cricket::ICEROLE_CONTROLLING);
1858 } else {
1859 transport_controller_->SetIceRole(cricket::ICEROLE_CONTROLLED);
1860 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001861 }
Steve Anton8a006912017-12-04 15:25:56 -08001862
Steve Antondcc3c022017-12-22 16:02:54 -08001863 // Take a reference to the old local description since it's used below to
1864 // compare against the new local description. When setting the new local
1865 // description, grab ownership of the replaced session description in case it
1866 // is the same as |old_local_description|, to keep it alive for the duration
1867 // of the method.
1868 const SessionDescriptionInterface* old_local_description =
1869 local_description();
1870 std::unique_ptr<SessionDescriptionInterface> replaced_local_description;
Steve Anton3828c062017-12-06 10:34:51 -08001871 if (type == SdpType::kAnswer) {
Steve Antondcc3c022017-12-22 16:02:54 -08001872 replaced_local_description = pending_local_description_
1873 ? std::move(pending_local_description_)
1874 : std::move(current_local_description_);
Steve Anton8a006912017-12-04 15:25:56 -08001875 current_local_description_ = std::move(desc);
1876 pending_local_description_ = nullptr;
1877 current_remote_description_ = std::move(pending_remote_description_);
1878 } else {
Steve Antondcc3c022017-12-22 16:02:54 -08001879 replaced_local_description = std::move(pending_local_description_);
Steve Anton8a006912017-12-04 15:25:56 -08001880 pending_local_description_ = std::move(desc);
1881 }
1882 // The session description to apply now must be accessed by
1883 // |local_description()|.
Henrik Boströmfdb92012017-11-09 19:55:44 +01001884 RTC_DCHECK(local_description());
deadbeefab9b2d12015-10-14 11:33:11 -07001885
Steve Antondcc3c022017-12-22 16:02:54 -08001886 if (IsUnifiedPlan()) {
1887 RTCError error = UpdateTransceiversAndDataChannels(
Seth Hampsonae8a90a2018-02-13 15:33:48 -08001888 cricket::CS_LOCAL, *local_description(), old_local_description,
1889 remote_description());
Steve Anton8a006912017-12-04 15:25:56 -08001890 if (!error.ok()) {
1891 return error;
1892 }
Steve Antondcc3c022017-12-22 16:02:54 -08001893 for (auto transceiver : transceivers_) {
1894 const ContentInfo* content =
1895 FindMediaSectionForTransceiver(transceiver, local_description());
1896 if (!content) {
1897 continue;
1898 }
1899 const MediaContentDescription* media_desc = content->media_description();
1900 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
1901 transceiver->internal()->set_current_direction(media_desc->direction());
1902 }
1903 if (content->rejected && !transceiver->stopped()) {
1904 transceiver->Stop();
1905 }
1906 }
1907 } else {
1908 // Transport and Media channels will be created only when offer is set.
1909 if (type == SdpType::kOffer) {
1910 // TODO(bugs.webrtc.org/4676) - Handle CreateChannel failure, as new local
1911 // description is applied. Restore back to old description.
1912 RTCError error = CreateChannels(*local_description()->description());
1913 if (!error.ok()) {
1914 return error;
1915 }
1916 }
Steve Anton8a006912017-12-04 15:25:56 -08001917
Steve Antondcc3c022017-12-22 16:02:54 -08001918 // Remove unused channels if MediaContentDescription is rejected.
1919 RemoveUnusedChannels(local_description()->description());
1920 }
Steve Anton8a006912017-12-04 15:25:56 -08001921
Steve Anton80dd7b52018-02-16 17:08:42 -08001922 RTCError error = UpdateSessionState(type, cricket::CS_LOCAL);
Steve Anton8a006912017-12-04 15:25:56 -08001923 if (!error.ok()) {
1924 return error;
1925 }
Steve Antondcc3c022017-12-22 16:02:54 -08001926
Steve Anton8a006912017-12-04 15:25:56 -08001927 if (remote_description()) {
1928 // Now that we have a local description, we can push down remote candidates.
1929 UseCandidatesInSessionDescription(remote_description());
1930 }
1931
1932 pending_ice_restarts_.clear();
1933 if (session_error() != SessionError::kNone) {
1934 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
1935 }
1936
deadbeefab9b2d12015-10-14 11:33:11 -07001937 // If setting the description decided our SSL role, allocate any necessary
1938 // SCTP sids.
1939 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08001940 if (data_channel_type() == cricket::DCT_SCTP && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001941 AllocateSctpSids(role);
1942 }
1943
Steve Antond3679212018-01-17 17:41:02 -08001944 if (IsUnifiedPlan()) {
1945 for (auto transceiver : transceivers_) {
1946 const ContentInfo* content =
1947 FindMediaSectionForTransceiver(transceiver, local_description());
1948 if (!content) {
1949 continue;
1950 }
1951 if (content->rejected && !transceiver->stopped()) {
1952 transceiver->Stop();
1953 }
Steve Anton74255ff2018-01-24 18:32:57 -08001954 const auto& streams = content->media_description()->streams();
1955 if (!content->rejected && !streams.empty()) {
Steve Antond3679212018-01-17 17:41:02 -08001956 transceiver->internal()->sender_internal()->set_stream_ids(
Steve Anton74255ff2018-01-24 18:32:57 -08001957 {streams[0].sync_label});
Steve Antond3679212018-01-17 17:41:02 -08001958 transceiver->internal()->sender_internal()->SetSsrc(
Steve Anton74255ff2018-01-24 18:32:57 -08001959 streams[0].first_ssrc());
Steve Antond3679212018-01-17 17:41:02 -08001960 }
1961 }
1962 } else {
1963 // Plan B semantics.
1964
Steve Antondcc3c022017-12-22 16:02:54 -08001965 // Update state and SSRC of local MediaStreams and DataChannels based on the
1966 // local session description.
1967 const cricket::ContentInfo* audio_content =
1968 GetFirstAudioContent(local_description()->description());
1969 if (audio_content) {
1970 if (audio_content->rejected) {
1971 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
1972 } else {
1973 const cricket::AudioContentDescription* audio_desc =
1974 audio_content->media_description()->as_audio();
1975 UpdateLocalSenders(audio_desc->streams(), audio_desc->type());
1976 }
deadbeeffaac4972015-11-12 15:33:07 -08001977 }
deadbeefab9b2d12015-10-14 11:33:11 -07001978
Steve Antondcc3c022017-12-22 16:02:54 -08001979 const cricket::ContentInfo* video_content =
1980 GetFirstVideoContent(local_description()->description());
1981 if (video_content) {
1982 if (video_content->rejected) {
1983 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
1984 } else {
1985 const cricket::VideoContentDescription* video_desc =
1986 video_content->media_description()->as_video();
1987 UpdateLocalSenders(video_desc->streams(), video_desc->type());
1988 }
deadbeeffaac4972015-11-12 15:33:07 -08001989 }
deadbeefab9b2d12015-10-14 11:33:11 -07001990 }
1991
1992 const cricket::ContentInfo* data_content =
Henrik Boströmfdb92012017-11-09 19:55:44 +01001993 GetFirstDataContent(local_description()->description());
deadbeefab9b2d12015-10-14 11:33:11 -07001994 if (data_content) {
1995 const cricket::DataContentDescription* data_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08001996 data_content->media_description()->as_data();
deadbeefab9b2d12015-10-14 11:33:11 -07001997 if (rtc::starts_with(data_desc->protocol().data(),
1998 cricket::kMediaProtocolRtpPrefix)) {
1999 UpdateLocalRtpDataChannels(data_desc->streams());
2000 }
2001 }
2002
Steve Anton8a006912017-12-04 15:25:56 -08002003 return RTCError::OK();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002004}
2005
2006void PeerConnection::SetRemoteDescription(
Henrik Boströma4ecf552017-11-23 14:17:07 +00002007 SetSessionDescriptionObserver* observer,
2008 SessionDescriptionInterface* desc) {
Henrik Boström31638672017-11-23 17:48:32 +01002009 SetRemoteDescription(
2010 std::unique_ptr<SessionDescriptionInterface>(desc),
2011 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface>(
2012 new SetRemoteDescriptionObserverAdapter(this, observer)));
2013}
2014
2015void PeerConnection::SetRemoteDescription(
2016 std::unique_ptr<SessionDescriptionInterface> desc,
2017 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface> observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +01002018 TRACE_EVENT0("webrtc", "PeerConnection::SetRemoteDescription");
Steve Anton8a006912017-12-04 15:25:56 -08002019
nisse7ce109a2017-01-31 00:57:56 -08002020 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002021 RTC_LOG(LS_ERROR) << "SetRemoteDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002022 return;
2023 }
Steve Anton8a006912017-12-04 15:25:56 -08002024
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002025 if (!desc) {
Henrik Boström31638672017-11-23 17:48:32 +01002026 observer->OnSetRemoteDescriptionComplete(RTCError(
Steve Anton8a006912017-12-04 15:25:56 -08002027 RTCErrorType::INVALID_PARAMETER, "SessionDescription is NULL."));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002028 return;
2029 }
Steve Anton8d3444d2017-10-20 15:30:51 -07002030
Steve Anton80dd7b52018-02-16 17:08:42 -08002031 // If a session error has occurred the PeerConnection is in a possibly
2032 // inconsistent state so fail right away.
2033 if (session_error() != SessionError::kNone) {
2034 std::string error_message = GetSessionErrorMsg();
2035 RTC_LOG(LS_ERROR) << "SetRemoteDescription: " << error_message;
2036 observer->OnSetRemoteDescriptionComplete(
2037 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
2038 return;
2039 }
Steve Anton71439a62018-02-15 11:53:06 -08002040
Steve Anton80dd7b52018-02-16 17:08:42 -08002041 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_REMOTE);
Steve Anton71439a62018-02-15 11:53:06 -08002042 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08002043 std::string error_message = GetSetDescriptionErrorMessage(
2044 cricket::CS_REMOTE, desc->GetType(), error);
2045 RTC_LOG(LS_ERROR) << error_message;
Steve Anton71439a62018-02-15 11:53:06 -08002046 observer->OnSetRemoteDescriptionComplete(
2047 RTCError(error.type(), std::move(error_message)));
2048 return;
2049 }
Steve Anton71439a62018-02-15 11:53:06 -08002050
Steve Anton80dd7b52018-02-16 17:08:42 -08002051 // Grab the description type before moving ownership to
2052 // ApplyRemoteDescription, which may destroy it before returning.
2053 const SdpType type = desc->GetType();
2054
2055 error = ApplyRemoteDescription(std::move(desc));
2056 // |desc| may be destroyed at this point.
2057
2058 if (!error.ok()) {
2059 // If ApplyRemoteDescription fails, the PeerConnection could be in an
2060 // inconsistent state, so act conservatively here and set the session error
2061 // so that future calls to SetLocalDescription/SetRemoteDescription fail.
2062 SetSessionError(SessionError::kContent, error.message());
2063 std::string error_message =
2064 GetSetDescriptionErrorMessage(cricket::CS_REMOTE, type, error);
2065 RTC_LOG(LS_ERROR) << error_message;
2066 observer->OnSetRemoteDescriptionComplete(
2067 RTCError(error.type(), std::move(error_message)));
2068 return;
2069 }
2070 RTC_DCHECK(remote_description());
2071
2072 if (type == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002073 // TODO(deadbeef): We already had to hop to the network thread for
2074 // MaybeStartGathering...
2075 network_thread()->Invoke<void>(
2076 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
2077 port_allocator_.get()));
Harald Alvestrand5dbb5862018-02-13 23:48:00 +01002078 // Make UMA notes about what was agreed to.
Steve Anton0ffaaa22018-02-23 10:31:30 -08002079 ReportNegotiatedSdpSemantics(*remote_description());
Steve Anton8a006912017-12-04 15:25:56 -08002080 }
2081
2082 observer->OnSetRemoteDescriptionComplete(RTCError::OK());
2083}
2084
2085RTCError PeerConnection::ApplyRemoteDescription(
2086 std::unique_ptr<SessionDescriptionInterface> desc) {
2087 RTC_DCHECK_RUN_ON(signaling_thread());
2088 RTC_DCHECK(desc);
2089
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002090 // Update stats here so that we have the most recent stats for tracks and
2091 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00002092 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 15:25:56 -08002093
Steve Antondcc3c022017-12-22 16:02:54 -08002094 // Take a reference to the old remote description since it's used below to
2095 // compare against the new remote description. When setting the new remote
2096 // description, grab ownership of the replaced session description in case it
2097 // is the same as |old_remote_description|, to keep it alive for the duration
2098 // of the method.
Steve Anton8a006912017-12-04 15:25:56 -08002099 const SessionDescriptionInterface* old_remote_description =
2100 remote_description();
Steve Anton8a006912017-12-04 15:25:56 -08002101 std::unique_ptr<SessionDescriptionInterface> replaced_remote_description;
Steve Anton3828c062017-12-06 10:34:51 -08002102 SdpType type = desc->GetType();
2103 if (type == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002104 replaced_remote_description = pending_remote_description_
2105 ? std::move(pending_remote_description_)
2106 : std::move(current_remote_description_);
2107 current_remote_description_ = std::move(desc);
2108 pending_remote_description_ = nullptr;
2109 current_local_description_ = std::move(pending_local_description_);
2110 } else {
2111 replaced_remote_description = std::move(pending_remote_description_);
2112 pending_remote_description_ = std::move(desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002113 }
Steve Anton8a006912017-12-04 15:25:56 -08002114 // The session description to apply now must be accessed by
2115 // |remote_description()|.
Henrik Boströmfdb92012017-11-09 19:55:44 +01002116 RTC_DCHECK(remote_description());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002117
Steve Anton8a006912017-12-04 15:25:56 -08002118 // Transport and Media channels will be created only when offer is set.
Steve Antondcc3c022017-12-22 16:02:54 -08002119 if (IsUnifiedPlan()) {
2120 RTCError error = UpdateTransceiversAndDataChannels(
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002121 cricket::CS_REMOTE, *remote_description(), local_description(),
2122 old_remote_description);
Steve Anton8a006912017-12-04 15:25:56 -08002123 if (!error.ok()) {
2124 return error;
2125 }
Steve Antondcc3c022017-12-22 16:02:54 -08002126 } else {
2127 if (type == SdpType::kOffer) {
2128 // TODO(bugs.webrtc.org/4676) - Handle CreateChannel failure, as new local
2129 // description is applied. Restore back to old description.
2130 RTCError error = CreateChannels(*remote_description()->description());
2131 if (!error.ok()) {
2132 return error;
2133 }
2134 }
Steve Anton8a006912017-12-04 15:25:56 -08002135
Steve Antondcc3c022017-12-22 16:02:54 -08002136 // Remove unused channels if MediaContentDescription is rejected.
2137 RemoveUnusedChannels(remote_description()->description());
2138 }
Steve Anton8a006912017-12-04 15:25:56 -08002139
2140 // NOTE: Candidates allocation will be initiated only when SetLocalDescription
2141 // is called.
Steve Anton80dd7b52018-02-16 17:08:42 -08002142 RTCError error = UpdateSessionState(type, cricket::CS_REMOTE);
Steve Anton8a006912017-12-04 15:25:56 -08002143 if (!error.ok()) {
2144 return error;
2145 }
2146
2147 if (local_description() &&
2148 !UseCandidatesInSessionDescription(remote_description())) {
2149 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidCandidates);
2150 }
2151
2152 if (old_remote_description) {
2153 for (const cricket::ContentInfo& content :
2154 old_remote_description->description()->contents()) {
2155 // Check if this new SessionDescription contains new ICE ufrag and
2156 // password that indicates the remote peer requests an ICE restart.
2157 // TODO(deadbeef): When we start storing both the current and pending
2158 // remote description, this should reset pending_ice_restarts and compare
2159 // against the current description.
2160 if (CheckForRemoteIceRestart(old_remote_description, remote_description(),
2161 content.name)) {
Steve Anton3828c062017-12-06 10:34:51 -08002162 if (type == SdpType::kOffer) {
Steve Anton8a006912017-12-04 15:25:56 -08002163 pending_ice_restarts_.insert(content.name);
2164 }
2165 } else {
2166 // We retain all received candidates only if ICE is not restarted.
2167 // When ICE is restarted, all previous candidates belong to an old
2168 // generation and should not be kept.
2169 // TODO(deadbeef): This goes against the W3C spec which says the remote
2170 // description should only contain candidates from the last set remote
2171 // description plus any candidates added since then. We should remove
2172 // this once we're sure it won't break anything.
2173 WebRtcSessionDescriptionFactory::CopyCandidatesFromSessionDescription(
2174 old_remote_description, content.name, mutable_remote_description());
2175 }
2176 }
2177 }
2178
2179 if (session_error() != SessionError::kNone) {
2180 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
2181 }
2182
2183 // Set the the ICE connection state to connecting since the connection may
2184 // become writable with peer reflexive candidates before any remote candidate
2185 // is signaled.
2186 // TODO(pthatcher): This is a short-term solution for crbug/446908. A real fix
2187 // is to have a new signal the indicates a change in checking state from the
2188 // transport and expose a new checking() member from transport that can be
2189 // read to determine the current checking state. The existing SignalConnecting
2190 // actually means "gathering candidates", so cannot be be used here.
Steve Antona3a92c22017-12-07 10:27:41 -08002191 if (remote_description()->GetType() != SdpType::kOffer &&
Steve Anton8a006912017-12-04 15:25:56 -08002192 ice_connection_state() == PeerConnectionInterface::kIceConnectionNew) {
2193 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
2194 }
2195
deadbeefab9b2d12015-10-14 11:33:11 -07002196 // If setting the description decided our SSL role, allocate any necessary
2197 // SCTP sids.
2198 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08002199 if (data_channel_type() == cricket::DCT_SCTP && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07002200 AllocateSctpSids(role);
2201 }
2202
Steve Antondcc3c022017-12-22 16:02:54 -08002203 if (IsUnifiedPlan()) {
Steve Anton8b815cd2018-02-16 16:14:42 -08002204 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
2205 receiving_transceivers;
Steve Antonc49bcd92018-02-14 14:28:13 -08002206 std::vector<rtc::scoped_refptr<MediaStreamInterface>> added_streams;
Steve Antondcc3c022017-12-22 16:02:54 -08002207 for (auto transceiver : transceivers_) {
2208 const ContentInfo* content =
2209 FindMediaSectionForTransceiver(transceiver, remote_description());
2210 if (!content) {
2211 continue;
2212 }
2213 const MediaContentDescription* media_desc = content->media_description();
2214 RtpTransceiverDirection local_direction =
2215 RtpTransceiverDirectionReversed(media_desc->direction());
2216 // From the WebRTC specification, steps 2.2.8.5/6 of section 4.4.1.6 "Set
2217 // the RTCSessionDescription: If direction is sendrecv or recvonly, and
2218 // transceiver's current direction is neither sendrecv nor recvonly,
2219 // process the addition of a remote track for the media description.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002220 //
2221 // Create a sync label in the case of an unsignalled msid.
2222 std::string sync_label = rtc::CreateRandomUuid();
2223 if (!media_desc->streams().empty()) {
2224 sync_label = media_desc->streams()[0].sync_label;
2225 }
Steve Antondcc3c022017-12-22 16:02:54 -08002226 if (RtpTransceiverDirectionHasRecv(local_direction) &&
2227 (!transceiver->current_direction() ||
2228 !RtpTransceiverDirectionHasRecv(
Seth Hampson2f0d7022018-02-20 11:54:42 -08002229 *transceiver->current_direction()))) {
Steve Antonef65ef12018-01-10 17:15:20 -08002230 rtc::scoped_refptr<MediaStreamInterface> stream =
2231 remote_streams_->find(sync_label);
2232 if (!stream) {
2233 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
2234 MediaStream::Create(sync_label));
2235 remote_streams_->AddStream(stream);
Steve Antonc49bcd92018-02-14 14:28:13 -08002236 added_streams.push_back(stream);
Steve Antonef65ef12018-01-10 17:15:20 -08002237 }
2238 transceiver->internal()->receiver_internal()->SetStreams({stream});
Steve Anton8b815cd2018-02-16 16:14:42 -08002239 receiving_transceivers.push_back(transceiver);
Steve Antondcc3c022017-12-22 16:02:54 -08002240 }
2241 // If direction is sendonly or inactive, and transceiver's current
2242 // direction is neither sendonly nor inactive, process the removal of a
2243 // remote track for the media description.
2244 if (!RtpTransceiverDirectionHasRecv(local_direction) &&
Steve Antonef65ef12018-01-10 17:15:20 -08002245 (transceiver->current_direction() &&
Steve Antondcc3c022017-12-22 16:02:54 -08002246 RtpTransceiverDirectionHasRecv(*transceiver->current_direction()))) {
Steve Antonef65ef12018-01-10 17:15:20 -08002247 transceiver->internal()->receiver_internal()->SetStreams({});
Steve Antondcc3c022017-12-22 16:02:54 -08002248 }
2249 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
2250 transceiver->internal()->set_current_direction(local_direction);
2251 }
2252 if (content->rejected && !transceiver->stopped()) {
2253 transceiver->Stop();
2254 }
Seth Hampson2f0d7022018-02-20 11:54:42 -08002255 if (!content->rejected &&
2256 RtpTransceiverDirectionHasRecv(local_direction)) {
2257 // Set ssrc to 0 in the case of an unsignalled ssrc.
2258 uint32_t ssrc = 0;
2259 if (!media_desc->streams().empty()) {
2260 ssrc = media_desc->streams()[0].first_ssrc();
2261 }
2262 transceiver->internal()->receiver_internal()->SetupMediaChannel(ssrc);
Steve Antond3679212018-01-17 17:41:02 -08002263 }
Steve Antondcc3c022017-12-22 16:02:54 -08002264 }
Steve Antonc49bcd92018-02-14 14:28:13 -08002265 // Once all processing has finished, fire off callbacks.
Steve Anton8b815cd2018-02-16 16:14:42 -08002266 for (auto transceiver : receiving_transceivers) {
Steve Anton6e221372018-02-20 12:59:16 -08002267 stats_->AddTrack(transceiver->receiver()->track());
Steve Anton8b815cd2018-02-16 16:14:42 -08002268 observer_->OnTrack(transceiver);
2269 observer_->OnAddTrack(transceiver->receiver(),
2270 transceiver->receiver()->streams());
Steve Antonef65ef12018-01-10 17:15:20 -08002271 }
Steve Antonc49bcd92018-02-14 14:28:13 -08002272 for (auto stream : added_streams) {
2273 observer_->OnAddStream(stream);
2274 }
Steve Antondcc3c022017-12-22 16:02:54 -08002275 }
2276
Henrik Boströmfdb92012017-11-09 19:55:44 +01002277 const cricket::ContentInfo* audio_content =
2278 GetFirstAudioContent(remote_description()->description());
2279 const cricket::ContentInfo* video_content =
2280 GetFirstVideoContent(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002281 const cricket::AudioContentDescription* audio_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002282 GetFirstAudioContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002283 const cricket::VideoContentDescription* video_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002284 GetFirstVideoContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002285 const cricket::DataContentDescription* data_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002286 GetFirstDataContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002287
2288 // Check if the descriptions include streams, just in case the peer supports
2289 // MSID, but doesn't indicate so with "a=msid-semantic".
Henrik Boströmfdb92012017-11-09 19:55:44 +01002290 if (remote_description()->description()->msid_supported() ||
deadbeefbda7e0b2015-12-08 17:13:40 -08002291 (audio_desc && !audio_desc->streams().empty()) ||
2292 (video_desc && !video_desc->streams().empty())) {
2293 remote_peer_supports_msid_ = true;
2294 }
deadbeefab9b2d12015-10-14 11:33:11 -07002295
2296 // We wait to signal new streams until we finish processing the description,
2297 // since only at that point will new streams have all their tracks.
2298 rtc::scoped_refptr<StreamCollection> new_streams(StreamCollection::Create());
2299
Steve Antondcc3c022017-12-22 16:02:54 -08002300 if (!IsUnifiedPlan()) {
2301 // TODO(steveanton): When removing RTP senders/receivers in response to a
2302 // rejected media section, there is some cleanup logic that expects the
2303 // voice/ video channel to still be set. But in this method the voice/video
2304 // channel would have been destroyed by the SetRemoteDescription caller
2305 // above so the cleanup that relies on them fails to run. The RemoveSenders
2306 // calls should be moved to right before the DestroyChannel calls to fix
2307 // this.
Steve Anton8d3444d2017-10-20 15:30:51 -07002308
Steve Antondcc3c022017-12-22 16:02:54 -08002309 // Find all audio rtp streams and create corresponding remote AudioTracks
2310 // and MediaStreams.
2311 if (audio_content) {
2312 if (audio_content->rejected) {
2313 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
2314 } else {
2315 bool default_audio_track_needed =
2316 !remote_peer_supports_msid_ &&
2317 RtpTransceiverDirectionHasSend(audio_desc->direction());
2318 UpdateRemoteSendersList(GetActiveStreams(audio_desc),
2319 default_audio_track_needed, audio_desc->type(),
2320 new_streams);
2321 }
deadbeeffaac4972015-11-12 15:33:07 -08002322 }
deadbeefab9b2d12015-10-14 11:33:11 -07002323
Steve Antondcc3c022017-12-22 16:02:54 -08002324 // Find all video rtp streams and create corresponding remote VideoTracks
2325 // and MediaStreams.
2326 if (video_content) {
2327 if (video_content->rejected) {
2328 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
2329 } else {
2330 bool default_video_track_needed =
2331 !remote_peer_supports_msid_ &&
2332 RtpTransceiverDirectionHasSend(video_desc->direction());
2333 UpdateRemoteSendersList(GetActiveStreams(video_desc),
2334 default_video_track_needed, video_desc->type(),
2335 new_streams);
2336 }
deadbeeffaac4972015-11-12 15:33:07 -08002337 }
deadbeefab9b2d12015-10-14 11:33:11 -07002338
Steve Antondcc3c022017-12-22 16:02:54 -08002339 // Update the DataChannels with the information from the remote peer.
2340 if (data_desc) {
2341 if (rtc::starts_with(data_desc->protocol().data(),
2342 cricket::kMediaProtocolRtpPrefix)) {
2343 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
2344 }
deadbeefab9b2d12015-10-14 11:33:11 -07002345 }
deadbeefab9b2d12015-10-14 11:33:11 -07002346
Steve Antondcc3c022017-12-22 16:02:54 -08002347 // Iterate new_streams and notify the observer about new MediaStreams.
2348 for (size_t i = 0; i < new_streams->count(); ++i) {
2349 MediaStreamInterface* new_stream = new_streams->at(i);
2350 stats_->AddStream(new_stream);
2351 observer_->OnAddStream(
2352 rtc::scoped_refptr<MediaStreamInterface>(new_stream));
2353 }
deadbeefab9b2d12015-10-14 11:33:11 -07002354
Steve Antondcc3c022017-12-22 16:02:54 -08002355 UpdateEndedRemoteMediaStreams();
2356 }
deadbeefab9b2d12015-10-14 11:33:11 -07002357
Steve Anton8a006912017-12-04 15:25:56 -08002358 return RTCError::OK();
deadbeeffc648b62015-10-13 16:42:33 -07002359}
2360
Steve Antondcc3c022017-12-22 16:02:54 -08002361RTCError PeerConnection::UpdateTransceiversAndDataChannels(
2362 cricket::ContentSource source,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002363 const SessionDescriptionInterface& new_session,
2364 const SessionDescriptionInterface* old_local_description,
2365 const SessionDescriptionInterface* old_remote_description) {
Steve Antondcc3c022017-12-22 16:02:54 -08002366 RTC_DCHECK(IsUnifiedPlan());
2367
Steve Anton7464fca2018-01-19 11:10:37 -08002368 const cricket::ContentGroup* bundle_group = nullptr;
2369 if (new_session.GetType() == SdpType::kOffer) {
2370 auto bundle_group_or_error =
2371 GetEarlyBundleGroup(*new_session.description());
2372 if (!bundle_group_or_error.ok()) {
2373 return bundle_group_or_error.MoveError();
2374 }
2375 bundle_group = bundle_group_or_error.MoveValue();
Steve Antondcc3c022017-12-22 16:02:54 -08002376 }
Steve Antondcc3c022017-12-22 16:02:54 -08002377
Steve Antondcc3c022017-12-22 16:02:54 -08002378 const ContentInfos& new_contents = new_session.description()->contents();
Steve Antondcc3c022017-12-22 16:02:54 -08002379 for (size_t i = 0; i < new_contents.size(); ++i) {
2380 const cricket::ContentInfo& new_content = new_contents[i];
Steve Antondcc3c022017-12-22 16:02:54 -08002381 cricket::MediaType media_type = new_content.media_description()->type();
2382 seen_mids_.insert(new_content.name);
2383 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
2384 media_type == cricket::MEDIA_TYPE_VIDEO) {
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002385 const cricket::ContentInfo* old_local_content = nullptr;
2386 if (old_local_description &&
2387 i < old_local_description->description()->contents().size()) {
2388 old_local_content =
2389 &old_local_description->description()->contents()[i];
2390 }
2391 const cricket::ContentInfo* old_remote_content = nullptr;
2392 if (old_remote_description &&
2393 i < old_remote_description->description()->contents().size()) {
2394 old_remote_content =
2395 &old_remote_description->description()->contents()[i];
2396 }
Steve Antondcc3c022017-12-22 16:02:54 -08002397 auto transceiver_or_error =
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002398 AssociateTransceiver(source, new_session.GetType(), i, new_content,
2399 old_local_content, old_remote_content);
Steve Antondcc3c022017-12-22 16:02:54 -08002400 if (!transceiver_or_error.ok()) {
2401 return transceiver_or_error.MoveError();
2402 }
2403 auto transceiver = transceiver_or_error.MoveValue();
Steve Antondcc3c022017-12-22 16:02:54 -08002404 RTCError error =
2405 UpdateTransceiverChannel(transceiver, new_content, bundle_group);
2406 if (!error.ok()) {
2407 return error;
2408 }
2409 } else if (media_type == cricket::MEDIA_TYPE_DATA) {
Steve Antonfa2260d2017-12-28 16:38:23 -08002410 if (GetDataMid() && new_content.name != *GetDataMid()) {
2411 // Ignore all but the first data section.
2412 continue;
2413 }
2414 RTCError error = UpdateDataChannel(source, new_content, bundle_group);
2415 if (!error.ok()) {
2416 return error;
2417 }
Steve Antondcc3c022017-12-22 16:02:54 -08002418 } else {
2419 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
2420 "Unknown section type.");
2421 }
2422 }
2423
2424 return RTCError::OK();
2425}
2426
2427RTCError PeerConnection::UpdateTransceiverChannel(
2428 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2429 transceiver,
2430 const cricket::ContentInfo& content,
2431 const cricket::ContentGroup* bundle_group) {
2432 RTC_DCHECK(IsUnifiedPlan());
2433 RTC_DCHECK(transceiver);
2434 cricket::BaseChannel* channel = transceiver->internal()->channel();
2435 if (content.rejected) {
2436 if (channel) {
2437 transceiver->internal()->SetChannel(nullptr);
2438 DestroyBaseChannel(channel);
2439 }
2440 } else {
2441 if (!channel) {
Steve Anton69470252018-02-09 11:43:08 -08002442 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Steve Antondcc3c022017-12-22 16:02:54 -08002443 channel = CreateVoiceChannel(
2444 content.name,
2445 GetTransportNameForMediaSection(content.name, bundle_group));
2446 } else {
Steve Anton69470252018-02-09 11:43:08 -08002447 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, transceiver->media_type());
Steve Antondcc3c022017-12-22 16:02:54 -08002448 channel = CreateVideoChannel(
2449 content.name,
2450 GetTransportNameForMediaSection(content.name, bundle_group));
2451 }
2452 if (!channel) {
2453 LOG_AND_RETURN_ERROR(
2454 RTCErrorType::INTERNAL_ERROR,
2455 "Failed to create channel for mid=" + content.name);
2456 }
2457 transceiver->internal()->SetChannel(channel);
2458 }
2459 }
2460 return RTCError::OK();
2461}
2462
Steve Antonfa2260d2017-12-28 16:38:23 -08002463RTCError PeerConnection::UpdateDataChannel(
2464 cricket::ContentSource source,
2465 const cricket::ContentInfo& content,
2466 const cricket::ContentGroup* bundle_group) {
2467 if (data_channel_type_ == cricket::DCT_NONE) {
Steve Antondbf9d032018-01-19 15:23:40 -08002468 // If data channels are disabled, ignore this media section. CreateAnswer
2469 // will take care of rejecting it.
2470 return RTCError::OK();
Steve Antonfa2260d2017-12-28 16:38:23 -08002471 }
2472 if (content.rejected) {
2473 DestroyDataChannel();
2474 } else {
2475 if (!rtp_data_channel_ && !sctp_transport_) {
2476 if (!CreateDataChannel(content.name, GetTransportNameForMediaSection(
2477 content.name, bundle_group))) {
2478 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
2479 "Failed to create data channel.");
2480 }
2481 }
2482 if (source == cricket::CS_REMOTE) {
2483 const MediaContentDescription* data_desc = content.media_description();
2484 if (data_desc && cricket::IsRtpProtocol(data_desc->protocol())) {
2485 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
2486 }
2487 }
2488 }
2489 return RTCError::OK();
2490}
2491
Steve Antondcc3c022017-12-22 16:02:54 -08002492RTCErrorOr<rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
2493PeerConnection::AssociateTransceiver(cricket::ContentSource source,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002494 SdpType type,
Steve Antondcc3c022017-12-22 16:02:54 -08002495 size_t mline_index,
2496 const ContentInfo& content,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002497 const ContentInfo* old_local_content,
2498 const ContentInfo* old_remote_content) {
Steve Antondcc3c022017-12-22 16:02:54 -08002499 RTC_DCHECK(IsUnifiedPlan());
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002500 // If this is an offer then the m= section might be recycled. If the m=
2501 // section is being recycled (defined as: rejected in the current local or
2502 // remote description and not rejected in new description), dissociate the
2503 // currently associated RtpTransceiver by setting its mid property to null,
2504 // and discard the mapping between the transceiver and its m= section index.
2505 if (IsMediaSectionBeingRecycled(type, content, old_local_content,
2506 old_remote_content)) {
2507 // We want to dissociate the transceiver that has the rejected mid.
2508 const std::string& old_mid =
2509 (old_local_content && old_local_content->rejected)
2510 ? old_local_content->name
2511 : old_remote_content->name;
2512 auto old_transceiver = GetAssociatedTransceiver(old_mid);
Steve Antondcc3c022017-12-22 16:02:54 -08002513 if (old_transceiver) {
2514 old_transceiver->internal()->set_mid(rtc::nullopt);
2515 old_transceiver->internal()->set_mline_index(rtc::nullopt);
2516 }
2517 }
2518 const MediaContentDescription* media_desc = content.media_description();
2519 auto transceiver = GetAssociatedTransceiver(content.name);
2520 if (source == cricket::CS_LOCAL) {
2521 // Find the RtpTransceiver that corresponds to this m= section, using the
2522 // mapping between transceivers and m= section indices established when
2523 // creating the offer.
2524 if (!transceiver) {
2525 transceiver = GetTransceiverByMLineIndex(mline_index);
2526 }
2527 if (!transceiver) {
2528 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2529 "Unknown transceiver");
2530 }
2531 } else {
2532 RTC_DCHECK_EQ(source, cricket::CS_REMOTE);
2533 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers
2534 // of the same type...
2535 if (!transceiver &&
2536 RtpTransceiverDirectionHasRecv(media_desc->direction())) {
2537 transceiver = FindAvailableTransceiverToReceive(media_desc->type());
2538 }
2539 // If no RtpTransceiver was found in the previous step, create one with a
2540 // recvonly direction.
2541 if (!transceiver) {
Steve Anton02ee47c2018-01-10 16:26:06 -08002542 auto sender =
2543 CreateSender(media_desc->type(), nullptr, {rtc::CreateRandomUuid()});
Steve Anton5f94aa22018-02-01 10:58:30 -08002544 std::string receiver_id;
2545 if (!media_desc->streams().empty()) {
2546 receiver_id = media_desc->streams()[0].id;
2547 } else {
2548 receiver_id = rtc::CreateRandomUuid();
2549 }
2550 auto receiver = CreateReceiver(media_desc->type(), receiver_id);
Steve Anton02ee47c2018-01-10 16:26:06 -08002551 transceiver = CreateAndAddTransceiver(sender, receiver);
Steve Antondcc3c022017-12-22 16:02:54 -08002552 transceiver->internal()->set_direction(
2553 RtpTransceiverDirection::kRecvOnly);
2554 }
2555 }
2556 RTC_DCHECK(transceiver);
Steve Anton69470252018-02-09 11:43:08 -08002557 if (transceiver->media_type() != media_desc->type()) {
Steve Antondcc3c022017-12-22 16:02:54 -08002558 LOG_AND_RETURN_ERROR(
2559 RTCErrorType::INVALID_PARAMETER,
2560 "Transceiver type does not match media description type.");
2561 }
2562 // Associate the found or created RtpTransceiver with the m= section by
2563 // setting the value of the RtpTransceiver's mid property to the MID of the m=
2564 // section, and establish a mapping between the transceiver and the index of
2565 // the m= section.
2566 transceiver->internal()->set_mid(content.name);
2567 transceiver->internal()->set_mline_index(mline_index);
2568 return std::move(transceiver);
2569}
2570
2571rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2572PeerConnection::GetAssociatedTransceiver(const std::string& mid) const {
2573 RTC_DCHECK(IsUnifiedPlan());
2574 for (auto transceiver : transceivers_) {
2575 if (transceiver->mid() == mid) {
2576 return transceiver;
2577 }
2578 }
2579 return nullptr;
2580}
2581
2582rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2583PeerConnection::GetTransceiverByMLineIndex(size_t mline_index) const {
2584 RTC_DCHECK(IsUnifiedPlan());
2585 for (auto transceiver : transceivers_) {
2586 if (transceiver->internal()->mline_index() == mline_index) {
2587 return transceiver;
2588 }
2589 }
2590 return nullptr;
2591}
2592
2593rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2594PeerConnection::FindAvailableTransceiverToReceive(
2595 cricket::MediaType media_type) const {
2596 RTC_DCHECK(IsUnifiedPlan());
2597 // From JSEP section 5.10 (Applying a Remote Description):
2598 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers of
2599 // the same type that were added to the PeerConnection by addTrack and are not
2600 // associated with any m= section and are not stopped, find the first such
2601 // RtpTransceiver.
2602 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08002603 if (transceiver->media_type() == media_type &&
Steve Antondcc3c022017-12-22 16:02:54 -08002604 transceiver->internal()->created_by_addtrack() && !transceiver->mid() &&
2605 !transceiver->stopped()) {
2606 return transceiver;
2607 }
2608 }
2609 return nullptr;
2610}
2611
Steve Antoned10bd92017-12-05 10:52:59 -08002612const cricket::ContentInfo* PeerConnection::FindMediaSectionForTransceiver(
2613 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2614 transceiver,
2615 const SessionDescriptionInterface* sdesc) const {
2616 RTC_DCHECK(transceiver);
2617 RTC_DCHECK(sdesc);
2618 if (IsUnifiedPlan()) {
2619 if (!transceiver->internal()->mid()) {
2620 // This transceiver is not associated with a media section yet.
2621 return nullptr;
2622 }
2623 return sdesc->description()->GetContentByName(
2624 *transceiver->internal()->mid());
2625 } else {
2626 // Plan B only allows at most one audio and one video section, so use the
2627 // first media section of that type.
2628 return cricket::GetFirstMediaContent(sdesc->description()->contents(),
Steve Anton69470252018-02-09 11:43:08 -08002629 transceiver->media_type());
Steve Antoned10bd92017-12-05 10:52:59 -08002630 }
2631}
2632
deadbeef46c73892016-11-16 19:42:04 -08002633PeerConnectionInterface::RTCConfiguration PeerConnection::GetConfiguration() {
2634 return configuration_;
2635}
2636
deadbeef293e9262017-01-11 12:28:30 -08002637bool PeerConnection::SetConfiguration(const RTCConfiguration& configuration,
2638 RTCError* error) {
Peter Boström1a9d6152015-12-08 22:15:17 +01002639 TRACE_EVENT0("webrtc", "PeerConnection::SetConfiguration");
deadbeef6de92f92016-12-12 18:49:32 -08002640
Steve Anton75737c02017-11-06 10:37:17 -08002641 if (local_description() && configuration.ice_candidate_pool_size !=
2642 configuration_.ice_candidate_pool_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002643 RTC_LOG(LS_ERROR) << "Can't change candidate pool size after calling "
2644 "SetLocalDescription.";
deadbeef293e9262017-01-11 12:28:30 -08002645 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00002646 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002647
deadbeef293e9262017-01-11 12:28:30 -08002648 // The simplest (and most future-compatible) way to tell if the config was
2649 // modified in an invalid way is to copy each property we do support
2650 // modifying, then use operator==. There are far more properties we don't
2651 // support modifying than those we do, and more could be added.
2652 RTCConfiguration modified_config = configuration_;
2653 modified_config.servers = configuration.servers;
2654 modified_config.type = configuration.type;
2655 modified_config.ice_candidate_pool_size =
2656 configuration.ice_candidate_pool_size;
2657 modified_config.prune_turn_ports = configuration.prune_turn_ports;
skvladd1f5fda2017-02-03 16:54:05 -08002658 modified_config.ice_check_min_interval = configuration.ice_check_min_interval;
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08002659 modified_config.stun_candidate_keepalive_interval =
2660 configuration.stun_candidate_keepalive_interval;
Jonas Orelandbdcee282017-10-10 14:01:40 +02002661 modified_config.turn_customizer = configuration.turn_customizer;
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08002662 modified_config.network_preference = configuration.network_preference;
deadbeef293e9262017-01-11 12:28:30 -08002663 if (configuration != modified_config) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002664 RTC_LOG(LS_ERROR) << "Modifying the configuration in an unsupported way.";
deadbeef293e9262017-01-11 12:28:30 -08002665 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
2666 }
2667
Steve Anton038834f2017-07-14 15:59:59 -07002668 // Validate the modified configuration.
2669 RTCError validate_error = ValidateConfiguration(modified_config);
2670 if (!validate_error.ok()) {
2671 return SafeSetError(std::move(validate_error), error);
2672 }
2673
deadbeef293e9262017-01-11 12:28:30 -08002674 // Note that this isn't possible through chromium, since it's an unsigned
2675 // short in WebIDL.
2676 if (configuration.ice_candidate_pool_size < 0 ||
2677 configuration.ice_candidate_pool_size > UINT16_MAX) {
2678 return SafeSetError(RTCErrorType::INVALID_RANGE, error);
2679 }
2680
2681 // Parse ICE servers before hopping to network thread.
2682 cricket::ServerAddresses stun_servers;
2683 std::vector<cricket::RelayServerConfig> turn_servers;
2684 RTCErrorType parse_error =
2685 ParseIceServers(configuration.servers, &stun_servers, &turn_servers);
2686 if (parse_error != RTCErrorType::NONE) {
2687 return SafeSetError(parse_error, error);
2688 }
2689
2690 // In theory this shouldn't fail.
2691 if (!network_thread()->Invoke<bool>(
2692 RTC_FROM_HERE,
2693 rtc::Bind(&PeerConnection::ReconfigurePortAllocator_n, this,
2694 stun_servers, turn_servers, modified_config.type,
2695 modified_config.ice_candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02002696 modified_config.prune_turn_ports,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08002697 modified_config.turn_customizer,
2698 modified_config.stun_candidate_keepalive_interval))) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002699 RTC_LOG(LS_ERROR) << "Failed to apply configuration to PortAllocator.";
deadbeef293e9262017-01-11 12:28:30 -08002700 return SafeSetError(RTCErrorType::INTERNAL_ERROR, error);
2701 }
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07002702
deadbeefd1a38b52016-12-10 13:15:33 -08002703 // As described in JSEP, calling setConfiguration with new ICE servers or
2704 // candidate policy must set a "needs-ice-restart" bit so that the next offer
2705 // triggers an ICE restart which will pick up the changes.
deadbeef293e9262017-01-11 12:28:30 -08002706 if (modified_config.servers != configuration_.servers ||
2707 modified_config.type != configuration_.type ||
2708 modified_config.prune_turn_ports != configuration_.prune_turn_ports) {
Steve Antond25da372017-11-06 14:50:29 -08002709 transport_controller_->SetNeedsIceRestartFlag();
deadbeefd1a38b52016-12-10 13:15:33 -08002710 }
skvladd1f5fda2017-02-03 16:54:05 -08002711
Qingsi Wang9c98f0c2018-02-15 15:10:59 -08002712 transport_controller_->SetIceConfig(ParseIceConfig(modified_config));
skvladd1f5fda2017-02-03 16:54:05 -08002713
deadbeef293e9262017-01-11 12:28:30 -08002714 configuration_ = modified_config;
2715 return SafeSetError(RTCErrorType::NONE, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00002716}
2717
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002718bool PeerConnection::AddIceCandidate(
2719 const IceCandidateInterface* ice_candidate) {
Peter Boström1a9d6152015-12-08 22:15:17 +01002720 TRACE_EVENT0("webrtc", "PeerConnection::AddIceCandidate");
zhihuang29ff8442016-07-27 11:07:25 -07002721 if (IsClosed()) {
2722 return false;
2723 }
Steve Antond25da372017-11-06 14:50:29 -08002724
2725 if (!remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002726 RTC_LOG(LS_ERROR) << "ProcessIceMessage: ICE candidates can't be added "
Jonas Olsson45cc8902018-02-13 10:37:07 +01002727 "without any remote session description.";
Steve Antond25da372017-11-06 14:50:29 -08002728 return false;
2729 }
2730
2731 if (!ice_candidate) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002732 RTC_LOG(LS_ERROR) << "ProcessIceMessage: Candidate is NULL.";
Steve Antond25da372017-11-06 14:50:29 -08002733 return false;
2734 }
2735
2736 bool valid = false;
2737 bool ready = ReadyToUseRemoteCandidate(ice_candidate, nullptr, &valid);
2738 if (!valid) {
2739 return false;
2740 }
2741
2742 // Add this candidate to the remote session description.
2743 if (!mutable_remote_description()->AddCandidate(ice_candidate)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002744 RTC_LOG(LS_ERROR) << "ProcessIceMessage: Candidate cannot be used.";
Steve Antond25da372017-11-06 14:50:29 -08002745 return false;
2746 }
2747
2748 if (ready) {
2749 return UseCandidate(ice_candidate);
2750 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002751 RTC_LOG(LS_INFO) << "ProcessIceMessage: Not ready to use candidate.";
Steve Antond25da372017-11-06 14:50:29 -08002752 return true;
2753 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002754}
2755
Honghai Zhang7fb69db2016-03-14 11:59:18 -07002756bool PeerConnection::RemoveIceCandidates(
2757 const std::vector<cricket::Candidate>& candidates) {
2758 TRACE_EVENT0("webrtc", "PeerConnection::RemoveIceCandidates");
Steve Antond25da372017-11-06 14:50:29 -08002759 if (!remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002760 RTC_LOG(LS_ERROR) << "RemoveRemoteIceCandidates: ICE candidates can't be "
Jonas Olsson45cc8902018-02-13 10:37:07 +01002761 "removed without any remote session description.";
Steve Antond25da372017-11-06 14:50:29 -08002762 return false;
2763 }
2764
2765 if (candidates.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002766 RTC_LOG(LS_ERROR) << "RemoveRemoteIceCandidates: candidates are empty.";
Steve Antond25da372017-11-06 14:50:29 -08002767 return false;
2768 }
2769
2770 size_t number_removed =
2771 mutable_remote_description()->RemoveCandidates(candidates);
2772 if (number_removed != candidates.size()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002773 RTC_LOG(LS_ERROR)
2774 << "RemoveRemoteIceCandidates: Failed to remove candidates. "
Jonas Olsson45cc8902018-02-13 10:37:07 +01002775 "Requested "
2776 << candidates.size() << " but only " << number_removed
Mirko Bonadei675513b2017-11-09 11:09:25 +01002777 << " are removed.";
Steve Antond25da372017-11-06 14:50:29 -08002778 }
2779
2780 // Remove the candidates from the transport controller.
2781 std::string error;
2782 bool res = transport_controller_->RemoveRemoteCandidates(candidates, &error);
2783 if (!res && !error.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002784 RTC_LOG(LS_ERROR) << "Error when removing remote candidates: " << error;
Steve Antond25da372017-11-06 14:50:29 -08002785 }
2786 return true;
Honghai Zhang7fb69db2016-03-14 11:59:18 -07002787}
2788
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00002789void PeerConnection::RegisterUMAObserver(UMAObserver* observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +01002790 TRACE_EVENT0("webrtc", "PeerConnection::RegisterUmaObserver");
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00002791 uma_observer_ = observer;
guoweis@webrtc.org7169afd2014-12-04 17:59:29 +00002792
Steve Anton75737c02017-11-06 10:37:17 -08002793 if (transport_controller()) {
2794 transport_controller()->SetMetricsObserver(uma_observer_);
guoweis@webrtc.org7169afd2014-12-04 17:59:29 +00002795 }
2796
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00002797 // Send information about IPv4/IPv6 status.
deadbeef293e9262017-01-11 12:28:30 -08002798 if (uma_observer_) {
Honghai Zhangd93f50c2016-10-05 11:47:22 -07002799 port_allocator_->SetMetricsObserver(uma_observer_);
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00002800 if (port_allocator_->flags() & cricket::PORTALLOCATOR_ENABLE_IPV6) {
Guo-wei Shiehdfbe6792015-09-03 17:12:07 -07002801 uma_observer_->IncrementEnumCounter(
2802 kEnumCounterAddressFamily, kPeerConnection_IPv6,
2803 kPeerConnectionAddressFamilyCounter_Max);
mallinath@webrtc.orgb445f262014-05-23 22:19:37 +00002804 } else {
Guo-wei Shiehdfbe6792015-09-03 17:12:07 -07002805 uma_observer_->IncrementEnumCounter(
2806 kEnumCounterAddressFamily, kPeerConnection_IPv4,
2807 kPeerConnectionAddressFamilyCounter_Max);
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00002808 }
Harald Alvestrand5dbb5862018-02-13 23:48:00 +01002809 // Send information about the requested SDP semantics.
2810 switch (configuration_.sdp_semantics) {
2811 case SdpSemantics::kDefault:
2812 uma_observer_->IncrementEnumCounter(kEnumCounterSdpSemanticRequested,
2813 kSdpSemanticRequestDefault,
2814 kSdpSemanticRequestMax);
2815
2816 break;
2817 case SdpSemantics::kPlanB:
2818 uma_observer_->IncrementEnumCounter(kEnumCounterSdpSemanticRequested,
2819 kSdpSemanticRequestPlanB,
2820 kSdpSemanticRequestMax);
2821 break;
2822 case SdpSemantics::kUnifiedPlan:
2823 uma_observer_->IncrementEnumCounter(kEnumCounterSdpSemanticRequested,
2824 kSdpSemanticRequestUnifiedPlan,
2825 kSdpSemanticRequestMax);
2826 break;
2827 default:
2828 RTC_NOTREACHED();
2829 }
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00002830 }
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00002831}
2832
zstein4b979802017-06-02 14:37:37 -07002833RTCError PeerConnection::SetBitrate(const BitrateParameters& bitrate) {
Steve Anton978b8762017-09-29 12:15:02 -07002834 if (!worker_thread()->IsCurrent()) {
2835 return worker_thread()->Invoke<RTCError>(
zstein4b979802017-06-02 14:37:37 -07002836 RTC_FROM_HERE, rtc::Bind(&PeerConnection::SetBitrate, this, bitrate));
2837 }
2838
2839 const bool has_min = static_cast<bool>(bitrate.min_bitrate_bps);
2840 const bool has_current = static_cast<bool>(bitrate.current_bitrate_bps);
2841 const bool has_max = static_cast<bool>(bitrate.max_bitrate_bps);
2842 if (has_min && *bitrate.min_bitrate_bps < 0) {
2843 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2844 "min_bitrate_bps <= 0");
2845 }
2846 if (has_current) {
2847 if (has_min && *bitrate.current_bitrate_bps < *bitrate.min_bitrate_bps) {
2848 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2849 "current_bitrate_bps < min_bitrate_bps");
2850 } else if (*bitrate.current_bitrate_bps < 0) {
2851 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2852 "curent_bitrate_bps < 0");
2853 }
2854 }
2855 if (has_max) {
2856 if (has_current &&
2857 *bitrate.max_bitrate_bps < *bitrate.current_bitrate_bps) {
2858 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2859 "max_bitrate_bps < current_bitrate_bps");
2860 } else if (has_min && *bitrate.max_bitrate_bps < *bitrate.min_bitrate_bps) {
2861 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2862 "max_bitrate_bps < min_bitrate_bps");
2863 } else if (*bitrate.max_bitrate_bps < 0) {
2864 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2865 "max_bitrate_bps < 0");
2866 }
2867 }
2868
Sebastian Janssonfc8d26b2018-02-21 09:52:06 +01002869 BitrateConstraintsMask mask;
zstein4b979802017-06-02 14:37:37 -07002870 mask.min_bitrate_bps = bitrate.min_bitrate_bps;
2871 mask.start_bitrate_bps = bitrate.current_bitrate_bps;
2872 mask.max_bitrate_bps = bitrate.max_bitrate_bps;
2873
2874 RTC_DCHECK(call_.get());
Sebastian Jansson8f83b422018-02-21 13:07:13 +01002875 call_->GetTransportControllerSend()->SetClientBitratePreferences(mask);
zstein4b979802017-06-02 14:37:37 -07002876
2877 return RTCError::OK();
2878}
2879
Alex Narest78609d52017-10-20 10:37:47 +02002880void PeerConnection::SetBitrateAllocationStrategy(
2881 std::unique_ptr<rtc::BitrateAllocationStrategy>
2882 bitrate_allocation_strategy) {
2883 rtc::Thread* worker_thread = factory_->worker_thread();
2884 if (!worker_thread->IsCurrent()) {
2885 rtc::BitrateAllocationStrategy* strategy_raw =
2886 bitrate_allocation_strategy.release();
2887 auto functor = [this, strategy_raw]() {
2888 call_->SetBitrateAllocationStrategy(
2889 rtc::WrapUnique<rtc::BitrateAllocationStrategy>(strategy_raw));
2890 };
2891 worker_thread->Invoke<void>(RTC_FROM_HERE, functor);
2892 return;
2893 }
2894 RTC_DCHECK(call_.get());
2895 call_->SetBitrateAllocationStrategy(std::move(bitrate_allocation_strategy));
2896}
2897
henrika5f6bf242017-11-01 11:06:56 +01002898void PeerConnection::SetAudioPlayout(bool playout) {
2899 if (!worker_thread()->IsCurrent()) {
2900 worker_thread()->Invoke<void>(
2901 RTC_FROM_HERE,
2902 rtc::Bind(&PeerConnection::SetAudioPlayout, this, playout));
2903 return;
2904 }
2905 auto audio_state =
2906 factory_->channel_manager()->media_engine()->GetAudioState();
2907 audio_state->SetPlayout(playout);
2908}
2909
2910void PeerConnection::SetAudioRecording(bool recording) {
2911 if (!worker_thread()->IsCurrent()) {
2912 worker_thread()->Invoke<void>(
2913 RTC_FROM_HERE,
2914 rtc::Bind(&PeerConnection::SetAudioRecording, this, recording));
2915 return;
2916 }
2917 auto audio_state =
2918 factory_->channel_manager()->media_engine()->GetAudioState();
2919 audio_state->SetRecording(recording);
2920}
2921
Steve Anton8c0f7a72017-10-03 10:03:10 -07002922std::unique_ptr<rtc::SSLCertificate>
2923PeerConnection::GetRemoteAudioSSLCertificate() {
Taylor Brandstetterc3928662018-02-23 13:04:51 -08002924 std::unique_ptr<rtc::SSLCertChain> chain = GetRemoteAudioSSLCertChain();
2925 if (!chain || !chain->GetSize()) {
Steve Anton8c0f7a72017-10-03 10:03:10 -07002926 return nullptr;
2927 }
Taylor Brandstetterc3928662018-02-23 13:04:51 -08002928 return chain->Get(0).GetUniqueReference();
Steve Anton8c0f7a72017-10-03 10:03:10 -07002929}
2930
Zhi Huang70b820f2018-01-27 14:16:15 -08002931std::unique_ptr<rtc::SSLCertChain>
2932PeerConnection::GetRemoteAudioSSLCertChain() {
Steve Antonafb0bb72018-02-20 11:35:37 -08002933 auto audio_transceiver = GetFirstAudioTransceiver();
2934 if (!audio_transceiver || !audio_transceiver->internal()->channel()) {
Zhi Huang70b820f2018-01-27 14:16:15 -08002935 return nullptr;
2936 }
Zhi Huang70b820f2018-01-27 14:16:15 -08002937 return transport_controller_->GetRemoteSSLCertChain(
Steve Antonafb0bb72018-02-20 11:35:37 -08002938 audio_transceiver->internal()->channel()->transport_name());
2939}
2940
2941rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2942PeerConnection::GetFirstAudioTransceiver() const {
2943 for (auto transceiver : transceivers_) {
2944 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
2945 return transceiver;
2946 }
2947 }
2948 return nullptr;
Zhi Huang70b820f2018-01-27 14:16:15 -08002949}
2950
ivoc14d5dbe2016-07-04 07:06:55 -07002951bool PeerConnection::StartRtcEventLog(rtc::PlatformFile file,
2952 int64_t max_size_bytes) {
Elad Alon99c3fe52017-10-13 16:29:40 +02002953 // TODO(eladalon): It would be better to not allow negative values into PC.
2954 const size_t max_size = (max_size_bytes < 0)
2955 ? RtcEventLog::kUnlimitedOutput
2956 : rtc::saturated_cast<size_t>(max_size_bytes);
2957 return StartRtcEventLog(
Bjorn Tereliusde939432017-11-20 17:38:14 +01002958 rtc::MakeUnique<RtcEventLogOutputFile>(file, max_size),
2959 webrtc::RtcEventLog::kImmediateOutput);
Elad Alon99c3fe52017-10-13 16:29:40 +02002960}
2961
Bjorn Tereliusde939432017-11-20 17:38:14 +01002962bool PeerConnection::StartRtcEventLog(std::unique_ptr<RtcEventLogOutput> output,
2963 int64_t output_period_ms) {
Karl Wibergd6b48192017-10-16 23:01:06 +02002964 // TODO(eladalon): In C++14, this can be done with a lambda.
2965 struct Functor {
Bjorn Tereliusde939432017-11-20 17:38:14 +01002966 bool operator()() {
2967 return pc->StartRtcEventLog_w(std::move(output), output_period_ms);
2968 }
Karl Wibergd6b48192017-10-16 23:01:06 +02002969 PeerConnection* const pc;
2970 std::unique_ptr<RtcEventLogOutput> output;
Bjorn Tereliusde939432017-11-20 17:38:14 +01002971 const int64_t output_period_ms;
Elad Alon99c3fe52017-10-13 16:29:40 +02002972 };
Bjorn Tereliusde939432017-11-20 17:38:14 +01002973 return worker_thread()->Invoke<bool>(
2974 RTC_FROM_HERE, Functor{this, std::move(output), output_period_ms});
ivoc14d5dbe2016-07-04 07:06:55 -07002975}
2976
2977void PeerConnection::StopRtcEventLog() {
Steve Anton978b8762017-09-29 12:15:02 -07002978 worker_thread()->Invoke<void>(
ivoc14d5dbe2016-07-04 07:06:55 -07002979 RTC_FROM_HERE, rtc::Bind(&PeerConnection::StopRtcEventLog_w, this));
2980}
2981
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002982const SessionDescriptionInterface* PeerConnection::local_description() const {
Steve Anton75737c02017-11-06 10:37:17 -08002983 return pending_local_description_ ? pending_local_description_.get()
2984 : current_local_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002985}
2986
2987const SessionDescriptionInterface* PeerConnection::remote_description() const {
Steve Anton75737c02017-11-06 10:37:17 -08002988 return pending_remote_description_ ? pending_remote_description_.get()
2989 : current_remote_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002990}
2991
deadbeeffe4a8a42016-12-20 17:56:17 -08002992const SessionDescriptionInterface* PeerConnection::current_local_description()
2993 const {
Steve Anton75737c02017-11-06 10:37:17 -08002994 return current_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08002995}
2996
2997const SessionDescriptionInterface* PeerConnection::current_remote_description()
2998 const {
Steve Anton75737c02017-11-06 10:37:17 -08002999 return current_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003000}
3001
3002const SessionDescriptionInterface* PeerConnection::pending_local_description()
3003 const {
Steve Anton75737c02017-11-06 10:37:17 -08003004 return pending_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003005}
3006
3007const SessionDescriptionInterface* PeerConnection::pending_remote_description()
3008 const {
Steve Anton75737c02017-11-06 10:37:17 -08003009 return pending_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003010}
3011
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003012void PeerConnection::Close() {
Peter Boström1a9d6152015-12-08 22:15:17 +01003013 TRACE_EVENT0("webrtc", "PeerConnection::Close");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003014 // Update stats here so that we have the most recent stats for tracks and
3015 // streams before the channels are closed.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00003016 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003017
Steve Anton75737c02017-11-06 10:37:17 -08003018 ChangeSignalingState(PeerConnectionInterface::kClosed);
Steve Anton3fe1b152017-12-12 10:20:08 -08003019
Steve Anton8af21862017-12-15 11:20:13 -08003020 for (auto transceiver : transceivers_) {
3021 transceiver->Stop();
3022 }
3023 DestroyAllChannels();
Steve Anton75737c02017-11-06 10:37:17 -08003024
Qingsi Wang93a84392018-01-30 17:13:09 -08003025 // The event log is used in the transport controller, which must be outlived
3026 // by the former. CreateOffer by the peer connection is implemented
3027 // asynchronously and if the peer connection is closed without resetting the
3028 // WebRTC session description factory, the session description factory would
3029 // call the transport controller.
3030 webrtc_session_desc_factory_.reset();
3031 transport_controller_.reset();
3032
deadbeef42a42632017-03-10 15:18:00 -08003033 network_thread()->Invoke<void>(
3034 RTC_FROM_HERE,
3035 rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
3036 port_allocator_.get()));
nisseeaabdf62017-05-05 02:23:02 -07003037
Steve Anton978b8762017-09-29 12:15:02 -07003038 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
eladalon248fd4f2017-09-06 05:18:15 -07003039 call_.reset();
3040 // The event log must outlive call (and any other object that uses it).
3041 event_log_.reset();
3042 });
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003043}
3044
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003045void PeerConnection::OnMessage(rtc::Message* msg) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003046 switch (msg->message_id) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003047 case MSG_SET_SESSIONDESCRIPTION_SUCCESS: {
3048 SetSessionDescriptionMsg* param =
3049 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
3050 param->observer->OnSuccess();
3051 delete param;
3052 break;
3053 }
3054 case MSG_SET_SESSIONDESCRIPTION_FAILED: {
3055 SetSessionDescriptionMsg* param =
3056 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
3057 param->observer->OnFailure(param->error);
3058 delete param;
3059 break;
3060 }
deadbeefab9b2d12015-10-14 11:33:11 -07003061 case MSG_CREATE_SESSIONDESCRIPTION_FAILED: {
3062 CreateSessionDescriptionMsg* param =
3063 static_cast<CreateSessionDescriptionMsg*>(msg->pdata);
3064 param->observer->OnFailure(param->error);
3065 delete param;
3066 break;
3067 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003068 case MSG_GETSTATS: {
3069 GetStatsMsg* param = static_cast<GetStatsMsg*>(msg->pdata);
nissee8abe3e2017-01-18 05:00:34 -08003070 StatsReports reports;
3071 stats_->GetStats(param->track, &reports);
3072 param->observer->OnComplete(reports);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003073 delete param;
3074 break;
3075 }
deadbeefbd292462015-12-14 18:15:29 -08003076 case MSG_FREE_DATACHANNELS: {
3077 sctp_data_channels_to_free_.clear();
3078 break;
3079 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003080 default:
nisseeb4ca4e2017-01-12 02:24:27 -08003081 RTC_NOTREACHED() << "Not implemented";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003082 break;
3083 }
3084}
3085
Steve Antonafb0bb72018-02-20 11:35:37 -08003086cricket::VoiceMediaChannel* PeerConnection::voice_media_channel() const {
3087 RTC_DCHECK(!IsUnifiedPlan());
3088 auto* voice_channel = static_cast<cricket::VoiceChannel*>(
3089 GetAudioTransceiver()->internal()->channel());
3090 if (voice_channel) {
3091 return voice_channel->media_channel();
3092 } else {
3093 return nullptr;
3094 }
3095}
3096
3097cricket::VideoMediaChannel* PeerConnection::video_media_channel() const {
3098 RTC_DCHECK(!IsUnifiedPlan());
3099 auto* video_channel = static_cast<cricket::VideoChannel*>(
3100 GetVideoTransceiver()->internal()->channel());
3101 if (video_channel) {
3102 return video_channel->media_channel();
3103 } else {
3104 return nullptr;
3105 }
3106}
3107
Steve Anton4171afb2017-11-20 10:20:22 -08003108void PeerConnection::CreateAudioReceiver(
3109 MediaStreamInterface* stream,
3110 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01003111 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
3112 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Steve Antond3679212018-01-17 17:41:02 -08003113 auto* audio_receiver = new AudioRtpReceiver(
3114 worker_thread(), remote_sender_info.sender_id, streams);
Steve Anton57858b32018-02-15 15:19:50 -08003115 audio_receiver->SetVoiceMediaChannel(voice_media_channel());
Steve Antond3679212018-01-17 17:41:02 -08003116 audio_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
3117 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
3118 signaling_thread(), audio_receiver);
Steve Anton4171afb2017-11-20 10:20:22 -08003119 GetAudioTransceiver()->internal()->AddReceiver(receiver);
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01003120 observer_->OnAddTrack(receiver, std::move(streams));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003121}
3122
Steve Anton4171afb2017-11-20 10:20:22 -08003123void PeerConnection::CreateVideoReceiver(
3124 MediaStreamInterface* stream,
3125 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01003126 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
3127 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Steve Antond3679212018-01-17 17:41:02 -08003128 auto* video_receiver = new VideoRtpReceiver(
3129 worker_thread(), remote_sender_info.sender_id, streams);
Steve Anton57858b32018-02-15 15:19:50 -08003130 video_receiver->SetVideoMediaChannel(video_media_channel());
Steve Antond3679212018-01-17 17:41:02 -08003131 video_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
3132 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
3133 signaling_thread(), video_receiver);
Steve Anton4171afb2017-11-20 10:20:22 -08003134 GetVideoTransceiver()->internal()->AddReceiver(receiver);
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01003135 observer_->OnAddTrack(receiver, std::move(streams));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003136}
3137
deadbeef70ab1a12015-09-28 16:53:55 -07003138// TODO(deadbeef): Keep RtpReceivers around even if track goes away in remote
3139// description.
Henrik Boström933d8b02017-10-10 10:05:16 -07003140rtc::scoped_refptr<RtpReceiverInterface> PeerConnection::RemoveAndStopReceiver(
Steve Anton4171afb2017-11-20 10:20:22 -08003141 const RtpSenderInfo& remote_sender_info) {
3142 auto receiver = FindReceiverById(remote_sender_info.sender_id);
3143 if (!receiver) {
3144 RTC_LOG(LS_WARNING) << "RtpReceiver for track with id "
3145 << remote_sender_info.sender_id << " doesn't exist.";
Henrik Boström933d8b02017-10-10 10:05:16 -07003146 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07003147 }
Steve Anton4171afb2017-11-20 10:20:22 -08003148 if (receiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
3149 GetAudioTransceiver()->internal()->RemoveReceiver(receiver);
3150 } else {
3151 GetVideoTransceiver()->internal()->RemoveReceiver(receiver);
3152 }
Henrik Boström933d8b02017-10-10 10:05:16 -07003153 return receiver;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003154}
3155
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003156void PeerConnection::AddAudioTrack(AudioTrackInterface* track,
3157 MediaStreamInterface* stream) {
3158 RTC_DCHECK(!IsClosed());
3159 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003160 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003161 // We already have a sender for this track, so just change the stream_id
3162 // so that it's correct in the next call to CreateOffer.
Steve Anton4171afb2017-11-20 10:20:22 -08003163 sender->internal()->set_stream_id(stream->label());
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003164 return;
3165 }
3166
3167 // Normal case; we've never seen this track before.
Steve Anton02ee47c2018-01-10 16:26:06 -08003168 auto new_sender =
3169 CreateSender(cricket::MEDIA_TYPE_AUDIO, track, {stream->label()});
Steve Anton57858b32018-02-15 15:19:50 -08003170 new_sender->internal()->SetVoiceMediaChannel(voice_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08003171 GetAudioTransceiver()->internal()->AddSender(new_sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003172 // If the sender has already been configured in SDP, we call SetSsrc,
3173 // which will connect the sender to the underlying transport. This can
3174 // occur if a local session description that contains the ID of the sender
3175 // is set before AddStream is called. It can also occur if the local
3176 // session description is not changed and RemoveStream is called, and
3177 // later AddStream is called again with the same stream.
Steve Anton4171afb2017-11-20 10:20:22 -08003178 const RtpSenderInfo* sender_info =
3179 FindSenderInfo(local_audio_sender_infos_, stream->label(), track->id());
3180 if (sender_info) {
3181 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003182 }
3183}
3184
3185// TODO(deadbeef): Don't destroy RtpSenders here; they should be kept around
3186// indefinitely, when we have unified plan SDP.
3187void PeerConnection::RemoveAudioTrack(AudioTrackInterface* track,
3188 MediaStreamInterface* stream) {
3189 RTC_DCHECK(!IsClosed());
3190 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003191 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003192 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
3193 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003194 return;
3195 }
Steve Anton4171afb2017-11-20 10:20:22 -08003196 GetAudioTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003197}
3198
3199void PeerConnection::AddVideoTrack(VideoTrackInterface* track,
3200 MediaStreamInterface* stream) {
3201 RTC_DCHECK(!IsClosed());
3202 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003203 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003204 // We already have a sender for this track, so just change the stream_id
3205 // so that it's correct in the next call to CreateOffer.
Steve Anton4171afb2017-11-20 10:20:22 -08003206 sender->internal()->set_stream_id(stream->label());
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003207 return;
3208 }
3209
3210 // Normal case; we've never seen this track before.
Steve Anton02ee47c2018-01-10 16:26:06 -08003211 auto new_sender =
3212 CreateSender(cricket::MEDIA_TYPE_VIDEO, track, {stream->label()});
Steve Anton57858b32018-02-15 15:19:50 -08003213 new_sender->internal()->SetVideoMediaChannel(video_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08003214 GetVideoTransceiver()->internal()->AddSender(new_sender);
3215 const RtpSenderInfo* sender_info =
3216 FindSenderInfo(local_video_sender_infos_, stream->label(), track->id());
3217 if (sender_info) {
3218 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003219 }
3220}
3221
3222void PeerConnection::RemoveVideoTrack(VideoTrackInterface* track,
3223 MediaStreamInterface* stream) {
3224 RTC_DCHECK(!IsClosed());
3225 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003226 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003227 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
3228 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003229 return;
3230 }
Steve Anton4171afb2017-11-20 10:20:22 -08003231 GetVideoTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003232}
3233
Steve Antonba818672017-11-06 10:21:57 -08003234void PeerConnection::SetIceConnectionState(IceConnectionState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07003235 RTC_DCHECK(signaling_thread()->IsCurrent());
Steve Antonba818672017-11-06 10:21:57 -08003236 if (ice_connection_state_ == new_state) {
3237 return;
3238 }
3239
deadbeefcbecd352015-09-23 11:50:27 -07003240 // After transitioning to "closed", ignore any additional states from
Steve Antonba818672017-11-06 10:21:57 -08003241 // TransportController (such as "disconnected").
deadbeefab9b2d12015-10-14 11:33:11 -07003242 if (IsClosed()) {
deadbeefcbecd352015-09-23 11:50:27 -07003243 return;
3244 }
Steve Antonba818672017-11-06 10:21:57 -08003245
Mirko Bonadei675513b2017-11-09 11:09:25 +01003246 RTC_LOG(LS_INFO) << "Changing IceConnectionState " << ice_connection_state_
3247 << " => " << new_state;
Steve Antonba818672017-11-06 10:21:57 -08003248 RTC_DCHECK(ice_connection_state_ !=
3249 PeerConnectionInterface::kIceConnectionClosed);
3250
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003251 ice_connection_state_ = new_state;
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00003252 observer_->OnIceConnectionChange(ice_connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003253}
3254
3255void PeerConnection::OnIceGatheringChange(
3256 PeerConnectionInterface::IceGatheringState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07003257 RTC_DCHECK(signaling_thread()->IsCurrent());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003258 if (IsClosed()) {
3259 return;
3260 }
3261 ice_gathering_state_ = new_state;
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00003262 observer_->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003263}
3264
jbauch81bf7b02017-03-25 08:31:12 -07003265void PeerConnection::OnIceCandidate(
3266 std::unique_ptr<IceCandidateInterface> candidate) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07003267 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07003268 if (IsClosed()) {
3269 return;
3270 }
jbauch81bf7b02017-03-25 08:31:12 -07003271 observer_->OnIceCandidate(candidate.get());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003272}
3273
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003274void PeerConnection::OnIceCandidatesRemoved(
3275 const std::vector<cricket::Candidate>& candidates) {
3276 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07003277 if (IsClosed()) {
3278 return;
3279 }
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003280 observer_->OnIceCandidatesRemoved(candidates);
3281}
3282
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003283void PeerConnection::ChangeSignalingState(
3284 PeerConnectionInterface::SignalingState signaling_state) {
Steve Antonba818672017-11-06 10:21:57 -08003285 RTC_DCHECK(signaling_thread()->IsCurrent());
3286 if (signaling_state_ == signaling_state) {
3287 return;
3288 }
Mirko Bonadei675513b2017-11-09 11:09:25 +01003289 RTC_LOG(LS_INFO) << "Session: " << session_id() << " Old state: "
3290 << GetSignalingStateString(signaling_state_)
3291 << " New state: "
3292 << GetSignalingStateString(signaling_state);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003293 signaling_state_ = signaling_state;
3294 if (signaling_state == kClosed) {
3295 ice_connection_state_ = kIceConnectionClosed;
3296 observer_->OnIceConnectionChange(ice_connection_state_);
3297 if (ice_gathering_state_ != kIceGatheringComplete) {
3298 ice_gathering_state_ = kIceGatheringComplete;
3299 observer_->OnIceGatheringChange(ice_gathering_state_);
3300 }
3301 }
3302 observer_->OnSignalingChange(signaling_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003303}
3304
deadbeefeb459812015-12-15 19:24:43 -08003305void PeerConnection::OnAudioTrackAdded(AudioTrackInterface* track,
3306 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003307 if (IsClosed()) {
3308 return;
3309 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003310 AddAudioTrack(track, stream);
3311 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003312}
3313
deadbeefeb459812015-12-15 19:24:43 -08003314void PeerConnection::OnAudioTrackRemoved(AudioTrackInterface* track,
3315 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003316 if (IsClosed()) {
3317 return;
3318 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003319 RemoveAudioTrack(track, stream);
3320 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003321}
3322
3323void PeerConnection::OnVideoTrackAdded(VideoTrackInterface* track,
3324 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003325 if (IsClosed()) {
3326 return;
3327 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003328 AddVideoTrack(track, stream);
3329 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003330}
3331
3332void PeerConnection::OnVideoTrackRemoved(VideoTrackInterface* track,
3333 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003334 if (IsClosed()) {
3335 return;
3336 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003337 RemoveVideoTrack(track, stream);
3338 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003339}
3340
Henrik Boström31638672017-11-23 17:48:32 +01003341void PeerConnection::PostSetSessionDescriptionSuccess(
3342 SetSessionDescriptionObserver* observer) {
3343 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
3344 signaling_thread()->Post(RTC_FROM_HERE, this,
3345 MSG_SET_SESSIONDESCRIPTION_SUCCESS, msg);
3346}
3347
deadbeefab9b2d12015-10-14 11:33:11 -07003348void PeerConnection::PostSetSessionDescriptionFailure(
3349 SetSessionDescriptionObserver* observer,
3350 const std::string& error) {
3351 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
3352 msg->error = error;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07003353 signaling_thread()->Post(RTC_FROM_HERE, this,
3354 MSG_SET_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07003355}
3356
3357void PeerConnection::PostCreateSessionDescriptionFailure(
3358 CreateSessionDescriptionObserver* observer,
3359 const std::string& error) {
3360 CreateSessionDescriptionMsg* msg = new CreateSessionDescriptionMsg(observer);
3361 msg->error = error;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07003362 signaling_thread()->Post(RTC_FROM_HERE, this,
3363 MSG_CREATE_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07003364}
3365
zhihuang1c378ed2017-08-17 14:10:50 -07003366void PeerConnection::GetOptionsForOffer(
Steve Antondcc3c022017-12-22 16:02:54 -08003367 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
deadbeefab9b2d12015-10-14 11:33:11 -07003368 cricket::MediaSessionOptions* session_options) {
Steve Antondcc3c022017-12-22 16:02:54 -08003369 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
zhihuang1c378ed2017-08-17 14:10:50 -07003370
Steve Antondcc3c022017-12-22 16:02:54 -08003371 if (IsUnifiedPlan()) {
3372 GetOptionsForUnifiedPlanOffer(offer_answer_options, session_options);
3373 } else {
3374 GetOptionsForPlanBOffer(offer_answer_options, session_options);
3375 }
3376
Steve Antonfa2260d2017-12-28 16:38:23 -08003377 // Intentionally unset the data channel type for RTP data channel with the
3378 // second condition. Otherwise the RTP data channels would be successfully
3379 // negotiated by default and the unit tests in WebRtcDataBrowserTest will fail
3380 // when building with chromium. We want to leave RTP data channels broken, so
3381 // people won't try to use them.
3382 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
3383 session_options->data_channel_type = data_channel_type();
3384 }
3385
Steve Antondcc3c022017-12-22 16:02:54 -08003386 // Apply ICE restart flag and renomination flag.
3387 for (auto& options : session_options->media_description_options) {
3388 options.transport_options.ice_restart = offer_answer_options.ice_restart;
3389 options.transport_options.enable_ice_renomination =
3390 configuration_.enable_ice_renomination;
3391 }
3392
3393 session_options->rtcp_cname = rtcp_cname_;
3394 session_options->crypto_options = factory_->options().crypto_options;
Steve Antone831b8c2018-02-01 12:22:16 -08003395 session_options->is_unified_plan = IsUnifiedPlan();
Steve Antondcc3c022017-12-22 16:02:54 -08003396}
3397
3398void PeerConnection::GetOptionsForPlanBOffer(
3399 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
3400 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07003401 // Figure out transceiver directional preferences.
3402 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
3403 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
3404
3405 // By default, generate sendrecv/recvonly m= sections.
3406 bool recv_audio = true;
3407 bool recv_video = true;
3408
3409 // By default, only offer a new m= section if we have media to send with it.
3410 bool offer_new_audio_description = send_audio;
3411 bool offer_new_video_description = send_video;
3412 bool offer_new_data_description = HasDataChannels();
3413
3414 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-22 16:02:54 -08003415 if (offer_answer_options.offer_to_receive_audio !=
3416 RTCOfferAnswerOptions::kUndefined) {
3417 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003418 offer_new_audio_description =
Steve Antondcc3c022017-12-22 16:02:54 -08003419 offer_new_audio_description ||
3420 (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003421 }
Steve Antondcc3c022017-12-22 16:02:54 -08003422 if (offer_answer_options.offer_to_receive_video !=
3423 RTCOfferAnswerOptions::kUndefined) {
3424 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003425 offer_new_video_description =
Steve Antondcc3c022017-12-22 16:02:54 -08003426 offer_new_video_description ||
3427 (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003428 }
3429
3430 rtc::Optional<size_t> audio_index;
3431 rtc::Optional<size_t> video_index;
3432 rtc::Optional<size_t> data_index;
3433 // If a current description exists, generate m= sections in the same order,
3434 // using the first audio/video/data section that appears and rejecting
3435 // extraneous ones.
Steve Anton75737c02017-11-06 10:37:17 -08003436 if (local_description()) {
zhihuang1c378ed2017-08-17 14:10:50 -07003437 GenerateMediaDescriptionOptions(
Steve Anton75737c02017-11-06 10:37:17 -08003438 local_description(),
Steve Anton1d03a752017-11-27 14:30:09 -08003439 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
3440 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
3441 &audio_index, &video_index, &data_index, session_options);
deadbeefab9b2d12015-10-14 11:33:11 -07003442 }
3443
zhihuang1c378ed2017-08-17 14:10:50 -07003444 // Add audio/video/data m= sections to the end if needed.
3445 if (!audio_index && offer_new_audio_description) {
3446 session_options->media_description_options.push_back(
3447 cricket::MediaDescriptionOptions(
3448 cricket::MEDIA_TYPE_AUDIO, cricket::CN_AUDIO,
Steve Anton1d03a752017-11-27 14:30:09 -08003449 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
3450 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003451 audio_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07003452 }
zhihuang1c378ed2017-08-17 14:10:50 -07003453 if (!video_index && offer_new_video_description) {
3454 session_options->media_description_options.push_back(
3455 cricket::MediaDescriptionOptions(
3456 cricket::MEDIA_TYPE_VIDEO, cricket::CN_VIDEO,
Steve Anton1d03a752017-11-27 14:30:09 -08003457 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
3458 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003459 video_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07003460 }
zhihuang1c378ed2017-08-17 14:10:50 -07003461 if (!data_index && offer_new_data_description) {
3462 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08003463 GetMediaDescriptionOptionsForActiveData(cricket::CN_DATA));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003464 data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07003465 }
3466
3467 cricket::MediaDescriptionOptions* audio_media_description_options =
3468 !audio_index ? nullptr
3469 : &session_options->media_description_options[*audio_index];
3470 cricket::MediaDescriptionOptions* video_media_description_options =
3471 !video_index ? nullptr
3472 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 14:10:50 -07003473
Steve Anton4171afb2017-11-20 10:20:22 -08003474 AddRtpSenderOptions(GetSendersInternal(), audio_media_description_options,
zhihuang1c378ed2017-08-17 14:10:50 -07003475 video_media_description_options);
Steve Antondcc3c022017-12-22 16:02:54 -08003476}
3477
3478// Find a new MID that is not already in |used_mids|, then add it to |used_mids|
3479// and return a reference to it.
3480// Generated MIDs should be no more than 3 bytes long to take up less space in
3481// the RTP packet.
3482static const std::string& AllocateMid(std::set<std::string>* used_mids) {
3483 RTC_DCHECK(used_mids);
3484 // We're boring: just generate MIDs 0, 1, 2, ...
3485 size_t i = 0;
3486 std::set<std::string>::iterator it;
3487 bool inserted;
3488 do {
3489 std::string mid = rtc::ToString(i++);
3490 auto insert_result = used_mids->insert(mid);
3491 it = insert_result.first;
3492 inserted = insert_result.second;
3493 } while (!inserted);
3494 return *it;
3495}
3496
3497static cricket::MediaDescriptionOptions
3498GetMediaDescriptionOptionsForTransceiver(
3499 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3500 transceiver,
3501 const std::string& mid) {
3502 cricket::MediaDescriptionOptions media_description_options(
Steve Anton69470252018-02-09 11:43:08 -08003503 transceiver->media_type(), mid, transceiver->direction(),
Steve Antondcc3c022017-12-22 16:02:54 -08003504 transceiver->stopped());
Steve Anton5f94aa22018-02-01 10:58:30 -08003505 // This behavior is specified in JSEP. The gist is that:
3506 // 1. The MSID is included if the RtpTransceiver's direction is sendonly or
3507 // sendrecv.
3508 // 2. If the MSID is included, then it must be included in any subsequent
3509 // offer/answer exactly the same until the RtpTransceiver is stopped.
3510 if (!transceiver->stopped() &&
3511 (RtpTransceiverDirectionHasSend(transceiver->direction()) ||
3512 transceiver->internal()->has_ever_been_used_to_send())) {
3513 cricket::SenderOptions sender_options;
3514 sender_options.track_id = transceiver->sender()->id();
3515 sender_options.stream_ids = transceiver->sender()->stream_ids();
3516 // TODO(bugs.webrtc.org/7600): Set num_sim_layers to the number of encodings
3517 // set in the RTP parameters when the transceiver was added.
3518 sender_options.num_sim_layers = 1;
3519 media_description_options.sender_options.push_back(sender_options);
3520 }
Steve Antondcc3c022017-12-22 16:02:54 -08003521 return media_description_options;
3522}
3523
3524void PeerConnection::GetOptionsForUnifiedPlanOffer(
3525 const RTCOfferAnswerOptions& offer_answer_options,
3526 cricket::MediaSessionOptions* session_options) {
3527 // Rules for generating an offer are dictated by JSEP sections 5.2.1 (Initial
3528 // Offers) and 5.2.2 (Subsequent Offers).
3529 RTC_DCHECK_EQ(session_options->media_description_options.size(), 0);
3530 const ContentInfos& local_contents =
3531 (local_description() ? local_description()->description()->contents()
3532 : ContentInfos());
3533 const ContentInfos& remote_contents =
3534 (remote_description() ? remote_description()->description()->contents()
3535 : ContentInfos());
3536 // The mline indices that can be recycled. New transceivers should reuse these
3537 // slots first.
3538 std::queue<size_t> recycleable_mline_indices;
3539 // Track the MIDs used in previous offer/answer exchanges and the current
3540 // offer so that new, unique MIDs are generated.
3541 std::set<std::string> used_mids = seen_mids_;
3542 // First, go through each media section that exists in either the local or
3543 // remote description and generate a media section in this offer for the
3544 // associated transceiver. If a media section can be recycled, generate a
3545 // default, rejected media section here that can be later overwritten.
3546 for (size_t i = 0;
3547 i < std::max(local_contents.size(), remote_contents.size()); ++i) {
3548 // Either |local_content| or |remote_content| is non-null.
3549 const ContentInfo* local_content =
3550 (i < local_contents.size() ? &local_contents[i] : nullptr);
3551 const ContentInfo* remote_content =
3552 (i < remote_contents.size() ? &remote_contents[i] : nullptr);
3553 bool had_been_rejected = (local_content && local_content->rejected) ||
3554 (remote_content && remote_content->rejected);
3555 const std::string& mid =
3556 (local_content ? local_content->name : remote_content->name);
3557 cricket::MediaType media_type =
3558 (local_content ? local_content->media_description()->type()
3559 : remote_content->media_description()->type());
3560 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
3561 media_type == cricket::MEDIA_TYPE_VIDEO) {
3562 auto transceiver = GetAssociatedTransceiver(mid);
3563 RTC_CHECK(transceiver);
3564 // A media section is considered eligible for recycling if it is marked as
3565 // rejected in either the local or remote description.
Seth Hampsonae8a90a2018-02-13 15:33:48 -08003566 if (had_been_rejected && transceiver->stopped()) {
Steve Antondcc3c022017-12-22 16:02:54 -08003567 session_options->media_description_options.push_back(
Steve Anton69470252018-02-09 11:43:08 -08003568 cricket::MediaDescriptionOptions(transceiver->media_type(), mid,
3569 RtpTransceiverDirection::kInactive,
3570 /*stopped=*/true));
Steve Antondcc3c022017-12-22 16:02:54 -08003571 recycleable_mline_indices.push(i);
3572 } else {
3573 session_options->media_description_options.push_back(
3574 GetMediaDescriptionOptionsForTransceiver(transceiver, mid));
3575 // CreateOffer shouldn't really cause any state changes in
3576 // PeerConnection, but we need a way to match new transceivers to new
3577 // media sections in SetLocalDescription and JSEP specifies this is done
3578 // by recording the index of the media section generated for the
3579 // transceiver in the offer.
3580 transceiver->internal()->set_mline_index(i);
3581 }
3582 } else {
3583 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antonfa2260d2017-12-28 16:38:23 -08003584 RTC_CHECK(GetDataMid());
3585 if (had_been_rejected || mid != *GetDataMid()) {
3586 session_options->media_description_options.push_back(
3587 GetMediaDescriptionOptionsForRejectedData(mid));
3588 } else {
3589 session_options->media_description_options.push_back(
3590 GetMediaDescriptionOptionsForActiveData(mid));
3591 }
Steve Antondcc3c022017-12-22 16:02:54 -08003592 }
3593 }
3594 // Next, look for transceivers that are newly added (that is, are not stopped
3595 // and not associated). Reuse media sections marked as recyclable first,
3596 // otherwise append to the end of the offer. New media sections should be
3597 // added in the order they were added to the PeerConnection.
3598 for (auto transceiver : transceivers_) {
3599 if (transceiver->mid() || transceiver->stopped()) {
3600 continue;
3601 }
3602 size_t mline_index;
3603 if (!recycleable_mline_indices.empty()) {
3604 mline_index = recycleable_mline_indices.front();
3605 recycleable_mline_indices.pop();
3606 session_options->media_description_options[mline_index] =
3607 GetMediaDescriptionOptionsForTransceiver(transceiver,
3608 AllocateMid(&used_mids));
3609 } else {
3610 mline_index = session_options->media_description_options.size();
3611 session_options->media_description_options.push_back(
3612 GetMediaDescriptionOptionsForTransceiver(transceiver,
3613 AllocateMid(&used_mids)));
3614 }
3615 // See comment above for why CreateOffer changes the transceiver's state.
3616 transceiver->internal()->set_mline_index(mline_index);
3617 }
Steve Antonfa2260d2017-12-28 16:38:23 -08003618 // Lastly, add a m-section if we have local data channels and an m section
3619 // does not already exist.
3620 if (!GetDataMid() && HasDataChannels()) {
3621 session_options->media_description_options.push_back(
3622 GetMediaDescriptionOptionsForActiveData(AllocateMid(&used_mids)));
3623 }
Steve Antondcc3c022017-12-22 16:02:54 -08003624}
3625
3626void PeerConnection::GetOptionsForAnswer(
3627 const RTCOfferAnswerOptions& offer_answer_options,
3628 cricket::MediaSessionOptions* session_options) {
3629 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
3630
3631 if (IsUnifiedPlan()) {
3632 GetOptionsForUnifiedPlanAnswer(offer_answer_options, session_options);
3633 } else {
3634 GetOptionsForPlanBAnswer(offer_answer_options, session_options);
3635 }
3636
Steve Antonfa2260d2017-12-28 16:38:23 -08003637 // Intentionally unset the data channel type for RTP data channel. Otherwise
3638 // the RTP data channels would be successfully negotiated by default and the
3639 // unit tests in WebRtcDataBrowserTest will fail when building with chromium.
3640 // We want to leave RTP data channels broken, so people won't try to use them.
3641 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
3642 session_options->data_channel_type = data_channel_type();
3643 }
3644
Steve Antondcc3c022017-12-22 16:02:54 -08003645 // Apply ICE renomination flag.
3646 for (auto& options : session_options->media_description_options) {
3647 options.transport_options.enable_ice_renomination =
3648 configuration_.enable_ice_renomination;
3649 }
zhihuang8f65cdf2016-05-06 18:40:30 -07003650
3651 session_options->rtcp_cname = rtcp_cname_;
jbauchcb560652016-08-04 05:20:32 -07003652 session_options->crypto_options = factory_->options().crypto_options;
Steve Antone831b8c2018-02-01 12:22:16 -08003653 session_options->is_unified_plan = IsUnifiedPlan();
deadbeefab9b2d12015-10-14 11:33:11 -07003654}
3655
Steve Antondcc3c022017-12-22 16:02:54 -08003656void PeerConnection::GetOptionsForPlanBAnswer(
3657 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07003658 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07003659 // Figure out transceiver directional preferences.
3660 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
3661 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
3662
3663 // By default, generate sendrecv/recvonly m= sections. The direction is also
3664 // restricted by the direction in the offer.
3665 bool recv_audio = true;
3666 bool recv_video = true;
3667
3668 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-22 16:02:54 -08003669 if (offer_answer_options.offer_to_receive_audio !=
3670 RTCOfferAnswerOptions::kUndefined) {
3671 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
deadbeef0ed85b22016-02-23 17:24:52 -08003672 }
Steve Antondcc3c022017-12-22 16:02:54 -08003673 if (offer_answer_options.offer_to_receive_video !=
3674 RTCOfferAnswerOptions::kUndefined) {
3675 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003676 }
3677
3678 rtc::Optional<size_t> audio_index;
3679 rtc::Optional<size_t> video_index;
3680 rtc::Optional<size_t> data_index;
Steve Antondffead82018-02-06 10:31:29 -08003681
3682 // Generate m= sections that match those in the offer.
3683 // Note that mediasession.cc will handle intersection our preferred
3684 // direction with the offered direction.
3685 GenerateMediaDescriptionOptions(
3686 remote_description(),
3687 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
3688 RtpTransceiverDirectionFromSendRecv(send_video, recv_video), &audio_index,
3689 &video_index, &data_index, session_options);
zhihuang1c378ed2017-08-17 14:10:50 -07003690
3691 cricket::MediaDescriptionOptions* audio_media_description_options =
3692 !audio_index ? nullptr
3693 : &session_options->media_description_options[*audio_index];
3694 cricket::MediaDescriptionOptions* video_media_description_options =
3695 !video_index ? nullptr
3696 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 14:10:50 -07003697
Steve Anton4171afb2017-11-20 10:20:22 -08003698 AddRtpSenderOptions(GetSendersInternal(), audio_media_description_options,
zhihuang1c378ed2017-08-17 14:10:50 -07003699 video_media_description_options);
Steve Antondcc3c022017-12-22 16:02:54 -08003700}
zhihuangaf388472016-11-02 16:49:48 -07003701
Steve Antondcc3c022017-12-22 16:02:54 -08003702void PeerConnection::GetOptionsForUnifiedPlanAnswer(
3703 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
3704 cricket::MediaSessionOptions* session_options) {
3705 // Rules for generating an answer are dictated by JSEP sections 5.3.1 (Initial
3706 // Answers) and 5.3.2 (Subsequent Answers).
3707 RTC_DCHECK(remote_description());
3708 RTC_DCHECK(remote_description()->GetType() == SdpType::kOffer);
3709 for (const ContentInfo& content :
3710 remote_description()->description()->contents()) {
3711 cricket::MediaType media_type = content.media_description()->type();
3712 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
3713 media_type == cricket::MEDIA_TYPE_VIDEO) {
3714 auto transceiver = GetAssociatedTransceiver(content.name);
3715 RTC_CHECK(transceiver);
3716 session_options->media_description_options.push_back(
3717 GetMediaDescriptionOptionsForTransceiver(transceiver, content.name));
3718 } else {
3719 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antondbf9d032018-01-19 15:23:40 -08003720 // Reject all data sections if data channels are disabled.
3721 // Reject a data section if it has already been rejected.
3722 // Reject all data sections except for the first one.
3723 if (data_channel_type_ == cricket::DCT_NONE || content.rejected ||
3724 content.name != *GetDataMid()) {
Steve Antonfa2260d2017-12-28 16:38:23 -08003725 session_options->media_description_options.push_back(
3726 GetMediaDescriptionOptionsForRejectedData(content.name));
3727 } else {
3728 session_options->media_description_options.push_back(
3729 GetMediaDescriptionOptionsForActiveData(content.name));
3730 }
Steve Antondcc3c022017-12-22 16:02:54 -08003731 }
3732 }
htaa2a49d92016-03-04 02:51:39 -08003733}
3734
zhihuang1c378ed2017-08-17 14:10:50 -07003735void PeerConnection::GenerateMediaDescriptionOptions(
3736 const SessionDescriptionInterface* session_desc,
Steve Anton1d03a752017-11-27 14:30:09 -08003737 RtpTransceiverDirection audio_direction,
3738 RtpTransceiverDirection video_direction,
zhihuang1c378ed2017-08-17 14:10:50 -07003739 rtc::Optional<size_t>* audio_index,
3740 rtc::Optional<size_t>* video_index,
3741 rtc::Optional<size_t>* data_index,
htaa2a49d92016-03-04 02:51:39 -08003742 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07003743 for (const cricket::ContentInfo& content :
3744 session_desc->description()->contents()) {
3745 if (IsAudioContent(&content)) {
3746 // If we already have an audio m= section, reject this extra one.
3747 if (*audio_index) {
3748 session_options->media_description_options.push_back(
3749 cricket::MediaDescriptionOptions(
3750 cricket::MEDIA_TYPE_AUDIO, content.name,
Steve Anton1d03a752017-11-27 14:30:09 -08003751 RtpTransceiverDirection::kInactive, true));
zhihuang1c378ed2017-08-17 14:10:50 -07003752 } else {
3753 session_options->media_description_options.push_back(
3754 cricket::MediaDescriptionOptions(
3755 cricket::MEDIA_TYPE_AUDIO, content.name, audio_direction,
Steve Anton1d03a752017-11-27 14:30:09 -08003756 audio_direction == RtpTransceiverDirection::kInactive));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003757 *audio_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07003758 }
3759 } else if (IsVideoContent(&content)) {
3760 // If we already have an video m= section, reject this extra one.
3761 if (*video_index) {
3762 session_options->media_description_options.push_back(
3763 cricket::MediaDescriptionOptions(
3764 cricket::MEDIA_TYPE_VIDEO, content.name,
Steve Anton1d03a752017-11-27 14:30:09 -08003765 RtpTransceiverDirection::kInactive, true));
zhihuang1c378ed2017-08-17 14:10:50 -07003766 } else {
3767 session_options->media_description_options.push_back(
3768 cricket::MediaDescriptionOptions(
3769 cricket::MEDIA_TYPE_VIDEO, content.name, video_direction,
Steve Anton1d03a752017-11-27 14:30:09 -08003770 video_direction == RtpTransceiverDirection::kInactive));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003771 *video_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07003772 }
3773 } else {
3774 RTC_DCHECK(IsDataContent(&content));
3775 // If we already have an data m= section, reject this extra one.
3776 if (*data_index) {
3777 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08003778 GetMediaDescriptionOptionsForRejectedData(content.name));
zhihuang1c378ed2017-08-17 14:10:50 -07003779 } else {
3780 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08003781 GetMediaDescriptionOptionsForActiveData(content.name));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003782 *data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07003783 }
3784 }
htaa2a49d92016-03-04 02:51:39 -08003785 }
deadbeefab9b2d12015-10-14 11:33:11 -07003786}
3787
Steve Antonfa2260d2017-12-28 16:38:23 -08003788cricket::MediaDescriptionOptions
3789PeerConnection::GetMediaDescriptionOptionsForActiveData(
3790 const std::string& mid) const {
3791 // Direction for data sections is meaningless, but legacy endpoints might
3792 // expect sendrecv.
3793 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
3794 RtpTransceiverDirection::kSendRecv,
3795 /*stopped=*/false);
3796 AddRtpDataChannelOptions(rtp_data_channels_, &options);
3797 return options;
3798}
3799
3800cricket::MediaDescriptionOptions
3801PeerConnection::GetMediaDescriptionOptionsForRejectedData(
3802 const std::string& mid) const {
3803 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
3804 RtpTransceiverDirection::kInactive,
3805 /*stopped=*/true);
3806 AddRtpDataChannelOptions(rtp_data_channels_, &options);
3807 return options;
3808}
3809
3810rtc::Optional<std::string> PeerConnection::GetDataMid() const {
3811 switch (data_channel_type_) {
3812 case cricket::DCT_RTP:
3813 if (!rtp_data_channel_) {
3814 return rtc::nullopt;
3815 }
3816 return rtp_data_channel_->content_name();
3817 case cricket::DCT_SCTP:
3818 return sctp_content_name_;
3819 default:
3820 return rtc::nullopt;
3821 }
3822}
3823
Steve Anton4171afb2017-11-20 10:20:22 -08003824void PeerConnection::RemoveSenders(cricket::MediaType media_type) {
3825 UpdateLocalSenders(std::vector<cricket::StreamParams>(), media_type);
3826 UpdateRemoteSendersList(std::vector<cricket::StreamParams>(), false,
deadbeefbda7e0b2015-12-08 17:13:40 -08003827 media_type, nullptr);
deadbeeffaac4972015-11-12 15:33:07 -08003828}
3829
Steve Anton4171afb2017-11-20 10:20:22 -08003830void PeerConnection::UpdateRemoteSendersList(
deadbeefab9b2d12015-10-14 11:33:11 -07003831 const cricket::StreamParamsVec& streams,
Steve Anton4171afb2017-11-20 10:20:22 -08003832 bool default_sender_needed,
deadbeefab9b2d12015-10-14 11:33:11 -07003833 cricket::MediaType media_type,
3834 StreamCollection* new_streams) {
Steve Anton4171afb2017-11-20 10:20:22 -08003835 std::vector<RtpSenderInfo>* current_senders =
3836 GetRemoteSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07003837
Steve Anton4171afb2017-11-20 10:20:22 -08003838 // Find removed senders. I.e., senders where the sender id or ssrc don't match
deadbeeffac06552015-11-25 11:26:01 -08003839 // the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08003840 for (auto sender_it = current_senders->begin();
3841 sender_it != current_senders->end();
3842 /* incremented manually */) {
3843 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07003844 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08003845 cricket::GetStreamBySsrc(streams, info.first_ssrc);
3846 bool sender_exists = params && params->id == info.sender_id;
deadbeefbda7e0b2015-12-08 17:13:40 -08003847 // If this is a default track, and we still need it, don't remove it.
Steve Anton4171afb2017-11-20 10:20:22 -08003848 if ((info.stream_label == kDefaultStreamLabel && default_sender_needed) ||
3849 sender_exists) {
3850 ++sender_it;
deadbeefbda7e0b2015-12-08 17:13:40 -08003851 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08003852 OnRemoteSenderRemoved(info, media_type);
3853 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07003854 }
3855 }
3856
Steve Anton4171afb2017-11-20 10:20:22 -08003857 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07003858 for (const cricket::StreamParams& params : streams) {
3859 // The sync_label is the MediaStream label and the |stream.id| is the
Steve Anton4171afb2017-11-20 10:20:22 -08003860 // sender id.
deadbeefab9b2d12015-10-14 11:33:11 -07003861 const std::string& stream_label = params.sync_label;
Steve Anton4171afb2017-11-20 10:20:22 -08003862 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07003863 uint32_t ssrc = params.first_ssrc();
3864
3865 rtc::scoped_refptr<MediaStreamInterface> stream =
3866 remote_streams_->find(stream_label);
3867 if (!stream) {
3868 // This is a new MediaStream. Create a new remote MediaStream.
perkjd61bf802016-03-24 03:16:19 -07003869 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
3870 MediaStream::Create(stream_label));
deadbeefab9b2d12015-10-14 11:33:11 -07003871 remote_streams_->AddStream(stream);
3872 new_streams->AddStream(stream);
3873 }
3874
Steve Anton4171afb2017-11-20 10:20:22 -08003875 const RtpSenderInfo* sender_info =
3876 FindSenderInfo(*current_senders, stream_label, sender_id);
3877 if (!sender_info) {
3878 current_senders->push_back(RtpSenderInfo(stream_label, sender_id, ssrc));
3879 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07003880 }
3881 }
deadbeefbda7e0b2015-12-08 17:13:40 -08003882
Steve Anton4171afb2017-11-20 10:20:22 -08003883 // Add default sender if necessary.
3884 if (default_sender_needed) {
deadbeefbda7e0b2015-12-08 17:13:40 -08003885 rtc::scoped_refptr<MediaStreamInterface> default_stream =
3886 remote_streams_->find(kDefaultStreamLabel);
3887 if (!default_stream) {
3888 // Create the new default MediaStream.
perkjd61bf802016-03-24 03:16:19 -07003889 default_stream = MediaStreamProxy::Create(
3890 rtc::Thread::Current(), MediaStream::Create(kDefaultStreamLabel));
deadbeefbda7e0b2015-12-08 17:13:40 -08003891 remote_streams_->AddStream(default_stream);
3892 new_streams->AddStream(default_stream);
3893 }
Steve Anton4171afb2017-11-20 10:20:22 -08003894 std::string default_sender_id = (media_type == cricket::MEDIA_TYPE_AUDIO)
3895 ? kDefaultAudioSenderId
3896 : kDefaultVideoSenderId;
3897 const RtpSenderInfo* default_sender_info = FindSenderInfo(
3898 *current_senders, kDefaultStreamLabel, default_sender_id);
3899 if (!default_sender_info) {
3900 current_senders->push_back(
3901 RtpSenderInfo(kDefaultStreamLabel, default_sender_id, 0));
3902 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefbda7e0b2015-12-08 17:13:40 -08003903 }
3904 }
deadbeefab9b2d12015-10-14 11:33:11 -07003905}
3906
Steve Anton4171afb2017-11-20 10:20:22 -08003907void PeerConnection::OnRemoteSenderAdded(const RtpSenderInfo& sender_info,
3908 cricket::MediaType media_type) {
3909 MediaStreamInterface* stream =
3910 remote_streams_->find(sender_info.stream_label);
deadbeefab9b2d12015-10-14 11:33:11 -07003911
3912 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 10:20:22 -08003913 CreateAudioReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07003914 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 10:20:22 -08003915 CreateVideoReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07003916 } else {
nisseeb4ca4e2017-01-12 02:24:27 -08003917 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07003918 }
3919}
3920
Steve Anton4171afb2017-11-20 10:20:22 -08003921void PeerConnection::OnRemoteSenderRemoved(const RtpSenderInfo& sender_info,
3922 cricket::MediaType media_type) {
3923 MediaStreamInterface* stream =
3924 remote_streams_->find(sender_info.stream_label);
deadbeefab9b2d12015-10-14 11:33:11 -07003925
Henrik Boström933d8b02017-10-10 10:05:16 -07003926 rtc::scoped_refptr<RtpReceiverInterface> receiver;
deadbeefab9b2d12015-10-14 11:33:11 -07003927 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
perkjd61bf802016-03-24 03:16:19 -07003928 // When the MediaEngine audio channel is destroyed, the RemoteAudioSource
3929 // will be notified which will end the AudioRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08003930 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07003931 rtc::scoped_refptr<AudioTrackInterface> audio_track =
Steve Anton4171afb2017-11-20 10:20:22 -08003932 stream->FindAudioTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07003933 if (audio_track) {
deadbeefab9b2d12015-10-14 11:33:11 -07003934 stream->RemoveTrack(audio_track);
deadbeefab9b2d12015-10-14 11:33:11 -07003935 }
3936 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
perkjd61bf802016-03-24 03:16:19 -07003937 // Stopping or destroying a VideoRtpReceiver will end the
3938 // VideoRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08003939 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07003940 rtc::scoped_refptr<VideoTrackInterface> video_track =
Steve Anton4171afb2017-11-20 10:20:22 -08003941 stream->FindVideoTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07003942 if (video_track) {
perkjd61bf802016-03-24 03:16:19 -07003943 // There's no guarantee the track is still available, e.g. the track may
3944 // have been removed from the stream by an application.
deadbeefab9b2d12015-10-14 11:33:11 -07003945 stream->RemoveTrack(video_track);
deadbeefab9b2d12015-10-14 11:33:11 -07003946 }
3947 } else {
nisseede5da42017-01-12 05:15:36 -08003948 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07003949 }
Henrik Boström933d8b02017-10-10 10:05:16 -07003950 if (receiver) {
3951 observer_->OnRemoveTrack(receiver);
3952 }
deadbeefab9b2d12015-10-14 11:33:11 -07003953}
3954
3955void PeerConnection::UpdateEndedRemoteMediaStreams() {
3956 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams_to_remove;
3957 for (size_t i = 0; i < remote_streams_->count(); ++i) {
3958 MediaStreamInterface* stream = remote_streams_->at(i);
3959 if (stream->GetAudioTracks().empty() && stream->GetVideoTracks().empty()) {
3960 streams_to_remove.push_back(stream);
3961 }
3962 }
3963
Taylor Brandstetter98cde262016-05-31 13:02:21 -07003964 for (auto& stream : streams_to_remove) {
deadbeefab9b2d12015-10-14 11:33:11 -07003965 remote_streams_->RemoveStream(stream);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07003966 observer_->OnRemoveStream(std::move(stream));
deadbeefab9b2d12015-10-14 11:33:11 -07003967 }
3968}
3969
Steve Anton4171afb2017-11-20 10:20:22 -08003970void PeerConnection::UpdateLocalSenders(
deadbeefab9b2d12015-10-14 11:33:11 -07003971 const std::vector<cricket::StreamParams>& streams,
3972 cricket::MediaType media_type) {
Steve Anton4171afb2017-11-20 10:20:22 -08003973 std::vector<RtpSenderInfo>* current_senders = GetLocalSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07003974
3975 // Find removed tracks. I.e., tracks where the track id, stream label or ssrc
3976 // don't match the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08003977 for (auto sender_it = current_senders->begin();
3978 sender_it != current_senders->end();
3979 /* incremented manually */) {
3980 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07003981 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08003982 cricket::GetStreamBySsrc(streams, info.first_ssrc);
3983 if (!params || params->id != info.sender_id ||
deadbeefab9b2d12015-10-14 11:33:11 -07003984 params->sync_label != info.stream_label) {
Steve Anton4171afb2017-11-20 10:20:22 -08003985 OnLocalSenderRemoved(info, media_type);
3986 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07003987 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08003988 ++sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07003989 }
3990 }
3991
Steve Anton4171afb2017-11-20 10:20:22 -08003992 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07003993 for (const cricket::StreamParams& params : streams) {
3994 // The sync_label is the MediaStream label and the |stream.id| is the
Steve Anton4171afb2017-11-20 10:20:22 -08003995 // sender id.
deadbeefab9b2d12015-10-14 11:33:11 -07003996 const std::string& stream_label = params.sync_label;
Steve Anton4171afb2017-11-20 10:20:22 -08003997 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07003998 uint32_t ssrc = params.first_ssrc();
Steve Anton4171afb2017-11-20 10:20:22 -08003999 const RtpSenderInfo* sender_info =
4000 FindSenderInfo(*current_senders, stream_label, sender_id);
4001 if (!sender_info) {
4002 current_senders->push_back(RtpSenderInfo(stream_label, sender_id, ssrc));
4003 OnLocalSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004004 }
4005 }
4006}
4007
Steve Anton4171afb2017-11-20 10:20:22 -08004008void PeerConnection::OnLocalSenderAdded(const RtpSenderInfo& sender_info,
4009 cricket::MediaType media_type) {
4010 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08004011 if (!sender) {
Steve Anton4171afb2017-11-20 10:20:22 -08004012 RTC_LOG(LS_WARNING) << "An unknown RtpSender with id "
4013 << sender_info.sender_id
Mirko Bonadei675513b2017-11-09 11:09:25 +01004014 << " has been configured in the local description.";
deadbeefab9b2d12015-10-14 11:33:11 -07004015 return;
4016 }
4017
deadbeeffac06552015-11-25 11:26:01 -08004018 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004019 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
Jonas Olsson45cc8902018-02-13 10:37:07 +01004020 " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08004021 return;
deadbeefab9b2d12015-10-14 11:33:11 -07004022 }
deadbeeffac06552015-11-25 11:26:01 -08004023
Steve Anton4171afb2017-11-20 10:20:22 -08004024 sender->internal()->set_stream_id(sender_info.stream_label);
4025 sender->internal()->SetSsrc(sender_info.first_ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07004026}
4027
Steve Anton4171afb2017-11-20 10:20:22 -08004028void PeerConnection::OnLocalSenderRemoved(const RtpSenderInfo& sender_info,
4029 cricket::MediaType media_type) {
4030 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08004031 if (!sender) {
4032 // This is the normal case. I.e., RemoveStream has been called and the
deadbeefab9b2d12015-10-14 11:33:11 -07004033 // SessionDescriptions has been renegotiated.
4034 return;
4035 }
deadbeeffac06552015-11-25 11:26:01 -08004036
4037 // A sender has been removed from the SessionDescription but it's still
4038 // associated with the PeerConnection. This only occurs if the SDP doesn't
4039 // match with the calls to CreateSender, AddStream and RemoveStream.
4040 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004041 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
Jonas Olsson45cc8902018-02-13 10:37:07 +01004042 " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08004043 return;
deadbeefab9b2d12015-10-14 11:33:11 -07004044 }
deadbeeffac06552015-11-25 11:26:01 -08004045
Steve Anton4171afb2017-11-20 10:20:22 -08004046 sender->internal()->SetSsrc(0);
deadbeefab9b2d12015-10-14 11:33:11 -07004047}
4048
4049void PeerConnection::UpdateLocalRtpDataChannels(
4050 const cricket::StreamParamsVec& streams) {
4051 std::vector<std::string> existing_channels;
4052
4053 // Find new and active data channels.
4054 for (const cricket::StreamParams& params : streams) {
4055 // |it->sync_label| is actually the data channel label. The reason is that
4056 // we use the same naming of data channels as we do for
4057 // MediaStreams and Tracks.
4058 // For MediaStreams, the sync_label is the MediaStream label and the
4059 // track label is the same as |streamid|.
4060 const std::string& channel_label = params.sync_label;
4061 auto data_channel_it = rtp_data_channels_.find(channel_label);
nisse7ce109a2017-01-31 00:57:56 -08004062 if (data_channel_it == rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004063 RTC_LOG(LS_ERROR) << "channel label not found";
deadbeefab9b2d12015-10-14 11:33:11 -07004064 continue;
4065 }
4066 // Set the SSRC the data channel should use for sending.
4067 data_channel_it->second->SetSendSsrc(params.first_ssrc());
4068 existing_channels.push_back(data_channel_it->first);
4069 }
4070
4071 UpdateClosingRtpDataChannels(existing_channels, true);
4072}
4073
4074void PeerConnection::UpdateRemoteRtpDataChannels(
4075 const cricket::StreamParamsVec& streams) {
4076 std::vector<std::string> existing_channels;
4077
4078 // Find new and active data channels.
4079 for (const cricket::StreamParams& params : streams) {
4080 // The data channel label is either the mslabel or the SSRC if the mslabel
4081 // does not exist. Ex a=ssrc:444330170 mslabel:test1.
4082 std::string label = params.sync_label.empty()
4083 ? rtc::ToString(params.first_ssrc())
4084 : params.sync_label;
4085 auto data_channel_it = rtp_data_channels_.find(label);
4086 if (data_channel_it == rtp_data_channels_.end()) {
4087 // This is a new data channel.
4088 CreateRemoteRtpDataChannel(label, params.first_ssrc());
4089 } else {
4090 data_channel_it->second->SetReceiveSsrc(params.first_ssrc());
4091 }
4092 existing_channels.push_back(label);
4093 }
4094
4095 UpdateClosingRtpDataChannels(existing_channels, false);
4096}
4097
4098void PeerConnection::UpdateClosingRtpDataChannels(
4099 const std::vector<std::string>& active_channels,
4100 bool is_local_update) {
4101 auto it = rtp_data_channels_.begin();
4102 while (it != rtp_data_channels_.end()) {
4103 DataChannel* data_channel = it->second;
4104 if (std::find(active_channels.begin(), active_channels.end(),
4105 data_channel->label()) != active_channels.end()) {
4106 ++it;
4107 continue;
4108 }
4109
4110 if (is_local_update) {
4111 data_channel->SetSendSsrc(0);
4112 } else {
4113 data_channel->RemotePeerRequestClose();
4114 }
4115
4116 if (data_channel->state() == DataChannel::kClosed) {
4117 rtp_data_channels_.erase(it);
4118 it = rtp_data_channels_.begin();
4119 } else {
4120 ++it;
4121 }
4122 }
4123}
4124
4125void PeerConnection::CreateRemoteRtpDataChannel(const std::string& label,
4126 uint32_t remote_ssrc) {
4127 rtc::scoped_refptr<DataChannel> channel(
4128 InternalCreateDataChannel(label, nullptr));
4129 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004130 RTC_LOG(LS_WARNING) << "Remote peer requested a DataChannel but"
Jonas Olsson45cc8902018-02-13 10:37:07 +01004131 "CreateDataChannel failed.";
deadbeefab9b2d12015-10-14 11:33:11 -07004132 return;
4133 }
4134 channel->SetReceiveSsrc(remote_ssrc);
deadbeefa601f5c2016-06-06 14:27:39 -07004135 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
4136 DataChannelProxy::Create(signaling_thread(), channel);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07004137 observer_->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07004138}
4139
4140rtc::scoped_refptr<DataChannel> PeerConnection::InternalCreateDataChannel(
4141 const std::string& label,
4142 const InternalDataChannelInit* config) {
4143 if (IsClosed()) {
4144 return nullptr;
4145 }
Steve Anton75737c02017-11-06 10:37:17 -08004146 if (data_channel_type() == cricket::DCT_NONE) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004147 RTC_LOG(LS_ERROR)
deadbeefab9b2d12015-10-14 11:33:11 -07004148 << "InternalCreateDataChannel: Data is not supported in this call.";
4149 return nullptr;
4150 }
4151 InternalDataChannelInit new_config =
4152 config ? (*config) : InternalDataChannelInit();
Steve Anton75737c02017-11-06 10:37:17 -08004153 if (data_channel_type() == cricket::DCT_SCTP) {
deadbeefab9b2d12015-10-14 11:33:11 -07004154 if (new_config.id < 0) {
4155 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08004156 if ((GetSctpSslRole(&role)) &&
deadbeefab9b2d12015-10-14 11:33:11 -07004157 !sid_allocator_.AllocateSid(role, &new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004158 RTC_LOG(LS_ERROR)
4159 << "No id can be allocated for the SCTP data channel.";
deadbeefab9b2d12015-10-14 11:33:11 -07004160 return nullptr;
4161 }
4162 } else if (!sid_allocator_.ReserveSid(new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004163 RTC_LOG(LS_ERROR) << "Failed to create a SCTP data channel "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004164 "because the id is already in use or out of range.";
deadbeefab9b2d12015-10-14 11:33:11 -07004165 return nullptr;
4166 }
4167 }
4168
Steve Anton75737c02017-11-06 10:37:17 -08004169 rtc::scoped_refptr<DataChannel> channel(
4170 DataChannel::Create(this, data_channel_type(), label, new_config));
deadbeefab9b2d12015-10-14 11:33:11 -07004171 if (!channel) {
4172 sid_allocator_.ReleaseSid(new_config.id);
4173 return nullptr;
4174 }
4175
4176 if (channel->data_channel_type() == cricket::DCT_RTP) {
4177 if (rtp_data_channels_.find(channel->label()) != rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004178 RTC_LOG(LS_ERROR) << "DataChannel with label " << channel->label()
4179 << " already exists.";
deadbeefab9b2d12015-10-14 11:33:11 -07004180 return nullptr;
4181 }
4182 rtp_data_channels_[channel->label()] = channel;
4183 } else {
4184 RTC_DCHECK(channel->data_channel_type() == cricket::DCT_SCTP);
4185 sctp_data_channels_.push_back(channel);
4186 channel->SignalClosed.connect(this,
4187 &PeerConnection::OnSctpDataChannelClosed);
4188 }
4189
Steve Anton2d8609c2018-01-23 16:38:46 -08004190 SignalDataChannelCreated_(channel.get());
deadbeefab9b2d12015-10-14 11:33:11 -07004191 return channel;
4192}
4193
4194bool PeerConnection::HasDataChannels() const {
4195 return !rtp_data_channels_.empty() || !sctp_data_channels_.empty();
4196}
4197
4198void PeerConnection::AllocateSctpSids(rtc::SSLRole role) {
4199 for (const auto& channel : sctp_data_channels_) {
4200 if (channel->id() < 0) {
4201 int sid;
4202 if (!sid_allocator_.AllocateSid(role, &sid)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004203 RTC_LOG(LS_ERROR) << "Failed to allocate SCTP sid.";
deadbeefab9b2d12015-10-14 11:33:11 -07004204 continue;
4205 }
4206 channel->SetSctpSid(sid);
4207 }
4208 }
4209}
4210
4211void PeerConnection::OnSctpDataChannelClosed(DataChannel* channel) {
deadbeefbd292462015-12-14 18:15:29 -08004212 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeefab9b2d12015-10-14 11:33:11 -07004213 for (auto it = sctp_data_channels_.begin(); it != sctp_data_channels_.end();
4214 ++it) {
4215 if (it->get() == channel) {
4216 if (channel->id() >= 0) {
4217 sid_allocator_.ReleaseSid(channel->id());
4218 }
deadbeefbd292462015-12-14 18:15:29 -08004219 // Since this method is triggered by a signal from the DataChannel,
4220 // we can't free it directly here; we need to free it asynchronously.
4221 sctp_data_channels_to_free_.push_back(*it);
deadbeefab9b2d12015-10-14 11:33:11 -07004222 sctp_data_channels_.erase(it);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07004223 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_FREE_DATACHANNELS,
4224 nullptr);
deadbeefab9b2d12015-10-14 11:33:11 -07004225 return;
4226 }
4227 }
4228}
4229
deadbeefab9b2d12015-10-14 11:33:11 -07004230void PeerConnection::OnDataChannelDestroyed() {
4231 // Use a temporary copy of the RTP/SCTP DataChannel list because the
4232 // DataChannel may callback to us and try to modify the list.
4233 std::map<std::string, rtc::scoped_refptr<DataChannel>> temp_rtp_dcs;
4234 temp_rtp_dcs.swap(rtp_data_channels_);
4235 for (const auto& kv : temp_rtp_dcs) {
4236 kv.second->OnTransportChannelDestroyed();
4237 }
4238
4239 std::vector<rtc::scoped_refptr<DataChannel>> temp_sctp_dcs;
4240 temp_sctp_dcs.swap(sctp_data_channels_);
4241 for (const auto& channel : temp_sctp_dcs) {
4242 channel->OnTransportChannelDestroyed();
4243 }
4244}
4245
4246void PeerConnection::OnDataChannelOpenMessage(
4247 const std::string& label,
4248 const InternalDataChannelInit& config) {
4249 rtc::scoped_refptr<DataChannel> channel(
4250 InternalCreateDataChannel(label, &config));
4251 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004252 RTC_LOG(LS_ERROR) << "Failed to create DataChannel from the OPEN message.";
deadbeefab9b2d12015-10-14 11:33:11 -07004253 return;
4254 }
4255
deadbeefa601f5c2016-06-06 14:27:39 -07004256 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
4257 DataChannelProxy::Create(signaling_thread(), channel);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07004258 observer_->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07004259}
4260
Steve Anton4171afb2017-11-20 10:20:22 -08004261rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
4262PeerConnection::GetAudioTransceiver() const {
4263 // This method only works with Plan B SDP, where there is a single
4264 // audio/video transceiver.
4265 RTC_DCHECK(!IsUnifiedPlan());
4266 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08004267 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004268 return transceiver;
4269 }
4270 }
4271 RTC_NOTREACHED();
4272 return nullptr;
4273}
4274
4275rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
4276PeerConnection::GetVideoTransceiver() const {
4277 // This method only works with Plan B SDP, where there is a single
4278 // audio/video transceiver.
4279 RTC_DCHECK(!IsUnifiedPlan());
4280 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08004281 if (transceiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004282 return transceiver;
4283 }
4284 }
4285 RTC_NOTREACHED();
4286 return nullptr;
4287}
4288
4289// TODO(bugs.webrtc.org/7600): Remove this when multiple transceivers with
4290// individual transceiver directions are supported.
zhihuang1c378ed2017-08-17 14:10:50 -07004291bool PeerConnection::HasRtpSender(cricket::MediaType type) const {
Steve Anton4171afb2017-11-20 10:20:22 -08004292 switch (type) {
4293 case cricket::MEDIA_TYPE_AUDIO:
4294 return !GetAudioTransceiver()->internal()->senders().empty();
4295 case cricket::MEDIA_TYPE_VIDEO:
4296 return !GetVideoTransceiver()->internal()->senders().empty();
4297 case cricket::MEDIA_TYPE_DATA:
4298 return false;
4299 }
4300 RTC_NOTREACHED();
4301 return false;
zhihuang1c378ed2017-08-17 14:10:50 -07004302}
4303
Steve Anton4171afb2017-11-20 10:20:22 -08004304rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
4305PeerConnection::FindSenderForTrack(MediaStreamTrackInterface* track) const {
4306 for (auto transceiver : transceivers_) {
4307 for (auto sender : transceiver->internal()->senders()) {
4308 if (sender->track() == track) {
4309 return sender;
4310 }
4311 }
4312 }
4313 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08004314}
4315
Steve Anton4171afb2017-11-20 10:20:22 -08004316rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
4317PeerConnection::FindSenderById(const std::string& sender_id) const {
4318 for (auto transceiver : transceivers_) {
4319 for (auto sender : transceiver->internal()->senders()) {
4320 if (sender->id() == sender_id) {
4321 return sender;
4322 }
4323 }
4324 }
4325 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07004326}
4327
Steve Anton4171afb2017-11-20 10:20:22 -08004328rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
4329PeerConnection::FindReceiverById(const std::string& receiver_id) const {
4330 for (auto transceiver : transceivers_) {
4331 for (auto receiver : transceiver->internal()->receivers()) {
4332 if (receiver->id() == receiver_id) {
4333 return receiver;
4334 }
4335 }
4336 }
4337 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07004338}
4339
Steve Anton4171afb2017-11-20 10:20:22 -08004340std::vector<PeerConnection::RtpSenderInfo>*
4341PeerConnection::GetRemoteSenderInfos(cricket::MediaType media_type) {
4342 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
4343 media_type == cricket::MEDIA_TYPE_VIDEO);
4344 return (media_type == cricket::MEDIA_TYPE_AUDIO)
4345 ? &remote_audio_sender_infos_
4346 : &remote_video_sender_infos_;
4347}
4348
4349std::vector<PeerConnection::RtpSenderInfo>* PeerConnection::GetLocalSenderInfos(
deadbeefab9b2d12015-10-14 11:33:11 -07004350 cricket::MediaType media_type) {
4351 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
4352 media_type == cricket::MEDIA_TYPE_VIDEO);
Steve Anton4171afb2017-11-20 10:20:22 -08004353 return (media_type == cricket::MEDIA_TYPE_AUDIO) ? &local_audio_sender_infos_
4354 : &local_video_sender_infos_;
deadbeefab9b2d12015-10-14 11:33:11 -07004355}
4356
Steve Anton4171afb2017-11-20 10:20:22 -08004357const PeerConnection::RtpSenderInfo* PeerConnection::FindSenderInfo(
4358 const std::vector<PeerConnection::RtpSenderInfo>& infos,
deadbeefab9b2d12015-10-14 11:33:11 -07004359 const std::string& stream_label,
Steve Anton4171afb2017-11-20 10:20:22 -08004360 const std::string sender_id) const {
4361 for (const RtpSenderInfo& sender_info : infos) {
4362 if (sender_info.stream_label == stream_label &&
4363 sender_info.sender_id == sender_id) {
4364 return &sender_info;
deadbeefab9b2d12015-10-14 11:33:11 -07004365 }
4366 }
4367 return nullptr;
4368}
4369
4370DataChannel* PeerConnection::FindDataChannelBySid(int sid) const {
4371 for (const auto& channel : sctp_data_channels_) {
4372 if (channel->id() == sid) {
4373 return channel;
4374 }
4375 }
4376 return nullptr;
4377}
4378
deadbeef91dd5672016-05-18 16:55:30 -07004379bool PeerConnection::InitializePortAllocator_n(
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004380 const RTCConfiguration& configuration) {
4381 cricket::ServerAddresses stun_servers;
4382 std::vector<cricket::RelayServerConfig> turn_servers;
deadbeef293e9262017-01-11 12:28:30 -08004383 if (ParseIceServers(configuration.servers, &stun_servers, &turn_servers) !=
4384 RTCErrorType::NONE) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004385 return false;
4386 }
4387
Taylor Brandstetterf8e65772016-06-27 17:20:15 -07004388 port_allocator_->Initialize();
4389
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004390 // To handle both internal and externally created port allocator, we will
4391 // enable BUNDLE here.
4392 int portallocator_flags = port_allocator_->flags();
4393 portallocator_flags |= cricket::PORTALLOCATOR_ENABLE_SHARED_SOCKET |
zhihuangb09b3f92017-03-07 14:40:51 -08004394 cricket::PORTALLOCATOR_ENABLE_IPV6 |
4395 cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI;
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004396 // If the disable-IPv6 flag was specified, we'll not override it
4397 // by experiment.
4398 if (configuration.disable_ipv6) {
4399 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
sprangc1b57a12017-02-28 08:50:47 -08004400 } else if (webrtc::field_trial::FindFullName("WebRTC-IPv6Default")
4401 .find("Disabled") == 0) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004402 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
4403 }
4404
zhihuangb09b3f92017-03-07 14:40:51 -08004405 if (configuration.disable_ipv6_on_wifi) {
4406 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI);
Mirko Bonadei675513b2017-11-09 11:09:25 +01004407 RTC_LOG(LS_INFO) << "IPv6 candidates on Wi-Fi are disabled.";
zhihuangb09b3f92017-03-07 14:40:51 -08004408 }
4409
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004410 if (configuration.tcp_candidate_policy == kTcpCandidatePolicyDisabled) {
4411 portallocator_flags |= cricket::PORTALLOCATOR_DISABLE_TCP;
Mirko Bonadei675513b2017-11-09 11:09:25 +01004412 RTC_LOG(LS_INFO) << "TCP candidates are disabled.";
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004413 }
4414
honghaiz60347052016-05-31 18:29:12 -07004415 if (configuration.candidate_network_policy ==
4416 kCandidateNetworkPolicyLowCost) {
4417 portallocator_flags |= cricket::PORTALLOCATOR_DISABLE_COSTLY_NETWORKS;
Mirko Bonadei675513b2017-11-09 11:09:25 +01004418 RTC_LOG(LS_INFO) << "Do not gather candidates on high-cost networks";
honghaiz60347052016-05-31 18:29:12 -07004419 }
4420
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +01004421 if (configuration.disable_link_local_networks) {
4422 portallocator_flags |= cricket::PORTALLOCATOR_DISABLE_LINK_LOCAL_NETWORKS;
4423 RTC_LOG(LS_INFO) << "Disable candidates on link-local network interfaces.";
4424 }
4425
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004426 port_allocator_->set_flags(portallocator_flags);
4427 // No step delay is used while allocating ports.
4428 port_allocator_->set_step_delay(cricket::kMinimumStepDelay);
4429 port_allocator_->set_candidate_filter(
4430 ConvertIceTransportTypeToCandidateFilter(configuration.type));
deadbeefd21eab32017-07-26 16:50:11 -07004431 port_allocator_->set_max_ipv6_networks(configuration.max_ipv6_networks);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004432
4433 // Call this last since it may create pooled allocator sessions using the
4434 // properties set above.
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08004435 port_allocator_->SetConfiguration(
4436 stun_servers, turn_servers, configuration.ice_candidate_pool_size,
4437 configuration.prune_turn_ports, configuration.turn_customizer,
4438 configuration.stun_candidate_keepalive_interval);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004439 return true;
4440}
4441
deadbeef91dd5672016-05-18 16:55:30 -07004442bool PeerConnection::ReconfigurePortAllocator_n(
deadbeef293e9262017-01-11 12:28:30 -08004443 const cricket::ServerAddresses& stun_servers,
4444 const std::vector<cricket::RelayServerConfig>& turn_servers,
4445 IceTransportsType type,
4446 int candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02004447 bool prune_turn_ports,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08004448 webrtc::TurnCustomizer* turn_customizer,
4449 rtc::Optional<int> stun_candidate_keepalive_interval) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004450 port_allocator_->set_candidate_filter(
deadbeef293e9262017-01-11 12:28:30 -08004451 ConvertIceTransportTypeToCandidateFilter(type));
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004452 // Call this last since it may create pooled allocator sessions using the
4453 // candidate filter set above.
deadbeef6de92f92016-12-12 18:49:32 -08004454 return port_allocator_->SetConfiguration(
Jonas Orelandbdcee282017-10-10 14:01:40 +02004455 stun_servers, turn_servers, candidate_pool_size, prune_turn_ports,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08004456 turn_customizer, stun_candidate_keepalive_interval);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004457}
4458
Steve Antonba818672017-11-06 10:21:57 -08004459cricket::ChannelManager* PeerConnection::channel_manager() const {
4460 return factory_->channel_manager();
4461}
4462
4463MetricsObserverInterface* PeerConnection::metrics_observer() const {
4464 return uma_observer_;
4465}
4466
Elad Alon99c3fe52017-10-13 16:29:40 +02004467bool PeerConnection::StartRtcEventLog_w(
Bjorn Tereliusde939432017-11-20 17:38:14 +01004468 std::unique_ptr<RtcEventLogOutput> output,
4469 int64_t output_period_ms) {
zhihuang77985012017-02-07 15:45:16 -08004470 if (!event_log_) {
4471 return false;
4472 }
Bjorn Tereliusde939432017-11-20 17:38:14 +01004473 return event_log_->StartLogging(std::move(output), output_period_ms);
ivoc14d5dbe2016-07-04 07:06:55 -07004474}
4475
4476void PeerConnection::StopRtcEventLog_w() {
zhihuang77985012017-02-07 15:45:16 -08004477 if (event_log_) {
4478 event_log_->StopLogging();
4479 }
ivoc14d5dbe2016-07-04 07:06:55 -07004480}
nisseeaabdf62017-05-05 02:23:02 -07004481
Steve Anton75737c02017-11-06 10:37:17 -08004482cricket::BaseChannel* PeerConnection::GetChannel(
4483 const std::string& content_name) {
Steve Antondcc3c022017-12-22 16:02:54 -08004484 for (auto transceiver : transceivers_) {
4485 cricket::BaseChannel* channel = transceiver->internal()->channel();
4486 if (channel && channel->content_name() == content_name) {
4487 return channel;
4488 }
Steve Anton75737c02017-11-06 10:37:17 -08004489 }
4490 if (rtp_data_channel() &&
4491 rtp_data_channel()->content_name() == content_name) {
4492 return rtp_data_channel();
4493 }
4494 return nullptr;
4495}
4496
4497bool PeerConnection::GetSctpSslRole(rtc::SSLRole* role) {
4498 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004499 RTC_LOG(LS_INFO)
4500 << "Local and Remote descriptions must be applied to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004501 "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08004502 return false;
4503 }
4504 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004505 RTC_LOG(LS_INFO) << "Non-rejected SCTP m= section is needed to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004506 "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08004507 return false;
4508 }
4509
4510 return transport_controller_->GetSslRole(*sctp_transport_name_, role);
4511}
4512
4513bool PeerConnection::GetSslRole(const std::string& content_name,
4514 rtc::SSLRole* role) {
4515 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004516 RTC_LOG(LS_INFO)
4517 << "Local and Remote descriptions must be applied to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004518 "SSL Role of the session.";
Steve Anton75737c02017-11-06 10:37:17 -08004519 return false;
4520 }
4521
4522 return transport_controller_->GetSslRole(GetTransportName(content_name),
4523 role);
4524}
4525
Steve Antonf8470812017-12-04 10:46:21 -08004526void PeerConnection::SetSessionError(SessionError error,
4527 const std::string& error_desc) {
4528 RTC_DCHECK_RUN_ON(signaling_thread());
4529 if (error != session_error_) {
4530 session_error_ = error;
4531 session_error_desc_ = error_desc;
Steve Anton75737c02017-11-06 10:37:17 -08004532 }
4533}
4534
Steve Anton3828c062017-12-06 10:34:51 -08004535RTCError PeerConnection::UpdateSessionState(SdpType type,
Steve Anton8a006912017-12-04 15:25:56 -08004536 cricket::ContentSource source) {
4537 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08004538
4539 // If there's already a pending error then no state transition should happen.
4540 // But all call-sites should be verifying this before calling us!
Steve Antonf8470812017-12-04 10:46:21 -08004541 RTC_DCHECK(session_error() == SessionError::kNone);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004542
4543 // If this is an answer then we know whether to BUNDLE or not. If both the
4544 // local and remote side have agreed to BUNDLE, go ahead and enable it.
Steve Anton3828c062017-12-06 10:34:51 -08004545 if (type == SdpType::kAnswer) {
Steve Anton75737c02017-11-06 10:37:17 -08004546 const cricket::ContentGroup* local_bundle =
4547 local_description()->description()->GetGroupByName(
4548 cricket::GROUP_TYPE_BUNDLE);
4549 const cricket::ContentGroup* remote_bundle =
4550 remote_description()->description()->GetGroupByName(
4551 cricket::GROUP_TYPE_BUNDLE);
4552 if (local_bundle && remote_bundle) {
4553 // The answerer decides the transport to bundle on.
4554 const cricket::ContentGroup* answer_bundle =
4555 (source == cricket::CS_LOCAL ? local_bundle : remote_bundle);
4556 if (!EnableBundle(*answer_bundle)) {
Steve Anton8a006912017-12-04 15:25:56 -08004557 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
4558 kEnableBundleFailed);
Steve Anton75737c02017-11-06 10:37:17 -08004559 }
4560 }
Steve Anton75737c02017-11-06 10:37:17 -08004561 }
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004562
4563 // Only push down the transport description after potentially enabling BUNDLE;
4564 // we don't want to push down a description on a transport about to be
4565 // destroyed.
Steve Anton3828c062017-12-06 10:34:51 -08004566 RTCError error = PushdownTransportDescription(source, type);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004567 if (!error.ok()) {
4568 return error;
4569 }
4570
4571 // If this is answer-ish we're ready to let media flow.
Steve Anton3828c062017-12-06 10:34:51 -08004572 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Antoned10bd92017-12-05 10:52:59 -08004573 EnableSending();
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004574 }
4575
4576 // Update the signaling state according to the specified state machine (see
4577 // https://w3c.github.io/webrtc-pc/#rtcsignalingstate-enum).
Steve Anton3828c062017-12-06 10:34:51 -08004578 if (type == SdpType::kOffer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004579 ChangeSignalingState(source == cricket::CS_LOCAL
4580 ? PeerConnectionInterface::kHaveLocalOffer
4581 : PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton3828c062017-12-06 10:34:51 -08004582 } else if (type == SdpType::kPrAnswer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004583 ChangeSignalingState(source == cricket::CS_LOCAL
4584 ? PeerConnectionInterface::kHaveLocalPrAnswer
4585 : PeerConnectionInterface::kHaveRemotePrAnswer);
4586 } else {
Steve Anton3828c062017-12-06 10:34:51 -08004587 RTC_DCHECK(type == SdpType::kAnswer);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004588 ChangeSignalingState(PeerConnectionInterface::kStable);
4589 }
4590
4591 // Update internal objects according to the session description's media
4592 // descriptions.
Steve Anton3828c062017-12-06 10:34:51 -08004593 error = PushdownMediaDescription(type, source);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004594 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08004595 return error;
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004596 }
4597
Steve Anton8a006912017-12-04 15:25:56 -08004598 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08004599}
4600
Steve Anton8a006912017-12-04 15:25:56 -08004601RTCError PeerConnection::PushdownMediaDescription(
Steve Anton3828c062017-12-06 10:34:51 -08004602 SdpType type,
Steve Anton8a006912017-12-04 15:25:56 -08004603 cricket::ContentSource source) {
Steve Antoned10bd92017-12-05 10:52:59 -08004604 const SessionDescriptionInterface* sdesc =
4605 (source == cricket::CS_LOCAL ? local_description()
4606 : remote_description());
Steve Anton75737c02017-11-06 10:37:17 -08004607 RTC_DCHECK(sdesc);
Steve Antoned10bd92017-12-05 10:52:59 -08004608
4609 // Push down the new SDP media section for each audio/video transceiver.
4610 for (auto transceiver : transceivers_) {
Steve Anton75737c02017-11-06 10:37:17 -08004611 const ContentInfo* content_info =
Steve Antoned10bd92017-12-05 10:52:59 -08004612 FindMediaSectionForTransceiver(transceiver, sdesc);
4613 cricket::BaseChannel* channel = transceiver->internal()->channel();
4614 if (!channel || !content_info || content_info->rejected) {
Steve Anton75737c02017-11-06 10:37:17 -08004615 continue;
4616 }
4617 const MediaContentDescription* content_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08004618 content_info->media_description();
Steve Antoned10bd92017-12-05 10:52:59 -08004619 if (!content_desc) {
4620 continue;
4621 }
4622 std::string error;
4623 bool success =
4624 (source == cricket::CS_LOCAL)
Steve Anton3828c062017-12-06 10:34:51 -08004625 ? channel->SetLocalContent(content_desc, type, &error)
4626 : channel->SetRemoteContent(content_desc, type, &error);
Steve Antoned10bd92017-12-05 10:52:59 -08004627 if (!success) {
4628 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, std::move(error));
4629 }
4630 }
4631
4632 // If using the RtpDataChannel, push down the new SDP section for it too.
4633 if (rtp_data_channel_) {
4634 const ContentInfo* data_content =
4635 cricket::GetFirstDataContent(sdesc->description());
4636 if (data_content && !data_content->rejected) {
4637 const MediaContentDescription* data_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08004638 data_content->media_description();
Steve Antoned10bd92017-12-05 10:52:59 -08004639 if (data_desc) {
4640 std::string error;
4641 bool success =
4642 (source == cricket::CS_LOCAL)
Steve Anton3828c062017-12-06 10:34:51 -08004643 ? rtp_data_channel_->SetLocalContent(data_desc, type, &error)
4644 : rtp_data_channel_->SetRemoteContent(data_desc, type,
Steve Antoned10bd92017-12-05 10:52:59 -08004645 &error);
4646 if (!success) {
4647 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
4648 std::move(error));
4649 }
Steve Anton75737c02017-11-06 10:37:17 -08004650 }
4651 }
4652 }
Steve Antoned10bd92017-12-05 10:52:59 -08004653
Steve Anton75737c02017-11-06 10:37:17 -08004654 // Need complete offer/answer with an SCTP m= section before starting SCTP,
4655 // according to https://tools.ietf.org/html/draft-ietf-mmusic-sctp-sdp-19
4656 if (sctp_transport_ && local_description() && remote_description() &&
4657 cricket::GetFirstDataContent(local_description()->description()) &&
4658 cricket::GetFirstDataContent(remote_description()->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08004659 bool success = network_thread()->Invoke<bool>(
Steve Anton75737c02017-11-06 10:37:17 -08004660 RTC_FROM_HERE,
4661 rtc::Bind(&PeerConnection::PushdownSctpParameters_n, this, source));
Steve Anton8a006912017-12-04 15:25:56 -08004662 if (!success) {
4663 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
4664 "Failed to push down SCTP parameters.");
4665 }
Steve Anton75737c02017-11-06 10:37:17 -08004666 }
Steve Antoned10bd92017-12-05 10:52:59 -08004667
Steve Anton8a006912017-12-04 15:25:56 -08004668 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08004669}
4670
4671bool PeerConnection::PushdownSctpParameters_n(cricket::ContentSource source) {
4672 RTC_DCHECK(network_thread()->IsCurrent());
4673 RTC_DCHECK(local_description());
4674 RTC_DCHECK(remote_description());
4675 // Apply the SCTP port (which is hidden inside a DataCodec structure...)
4676 // When we support "max-message-size", that would also be pushed down here.
4677 return sctp_transport_->Start(
4678 GetSctpPort(local_description()->description()),
4679 GetSctpPort(remote_description()->description()));
4680}
4681
Steve Anton8a006912017-12-04 15:25:56 -08004682RTCError PeerConnection::PushdownTransportDescription(
4683 cricket::ContentSource source,
Steve Anton3828c062017-12-06 10:34:51 -08004684 SdpType type) {
Steve Anton8a006912017-12-04 15:25:56 -08004685 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08004686
Steve Anton8a006912017-12-04 15:25:56 -08004687 const SessionDescriptionInterface* sdesc =
4688 (source == cricket::CS_LOCAL ? local_description()
4689 : remote_description());
4690 RTC_DCHECK(sdesc);
4691 for (const cricket::TransportInfo& tinfo :
4692 sdesc->description()->transport_infos()) {
4693 std::string error;
4694 bool success;
4695 if (source == cricket::CS_LOCAL) {
4696 success = transport_controller_->SetLocalTransportDescription(
Steve Anton3828c062017-12-06 10:34:51 -08004697 tinfo.content_name, tinfo.description, type, &error);
Steve Anton8a006912017-12-04 15:25:56 -08004698 } else {
4699 success = transport_controller_->SetRemoteTransportDescription(
Steve Anton3828c062017-12-06 10:34:51 -08004700 tinfo.content_name, tinfo.description, type, &error);
Steve Anton8a006912017-12-04 15:25:56 -08004701 }
4702 if (!success) {
Steve Antondcc3c022017-12-22 16:02:54 -08004703 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
4704 "Failed to push down transport description for " +
4705 tinfo.content_name + ": " + error);
Steve Anton75737c02017-11-06 10:37:17 -08004706 }
4707 }
4708
Steve Anton8a006912017-12-04 15:25:56 -08004709 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08004710}
4711
4712bool PeerConnection::GetTransportDescription(
4713 const SessionDescription* description,
4714 const std::string& content_name,
4715 cricket::TransportDescription* tdesc) {
4716 if (!description || !tdesc) {
4717 return false;
4718 }
4719 const TransportInfo* transport_info =
4720 description->GetTransportInfoByName(content_name);
4721 if (!transport_info) {
4722 return false;
4723 }
4724 *tdesc = transport_info->description;
4725 return true;
4726}
4727
4728bool PeerConnection::EnableBundle(const cricket::ContentGroup& bundle) {
4729 const std::string* first_content_name = bundle.FirstContentName();
4730 if (!first_content_name) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004731 RTC_LOG(LS_WARNING) << "Tried to BUNDLE with no contents.";
Steve Anton75737c02017-11-06 10:37:17 -08004732 return false;
4733 }
4734 const std::string& transport_name = *first_content_name;
4735
4736 auto maybe_set_transport = [this, bundle,
4737 transport_name](cricket::BaseChannel* ch) {
4738 if (!ch || !bundle.HasContentName(ch->content_name())) {
Steve Antoned10bd92017-12-05 10:52:59 -08004739 return;
Steve Anton75737c02017-11-06 10:37:17 -08004740 }
4741
4742 std::string old_transport_name = ch->transport_name();
4743 if (old_transport_name == transport_name) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004744 RTC_LOG(LS_INFO) << "BUNDLE already enabled for " << ch->content_name()
4745 << " on " << transport_name << ".";
Steve Antoned10bd92017-12-05 10:52:59 -08004746 return;
Steve Anton75737c02017-11-06 10:37:17 -08004747 }
4748
4749 cricket::DtlsTransportInternal* rtp_dtls_transport =
4750 transport_controller_->CreateDtlsTransport(
4751 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4752 bool need_rtcp = (ch->rtcp_dtls_transport() != nullptr);
4753 cricket::DtlsTransportInternal* rtcp_dtls_transport = nullptr;
4754 if (need_rtcp) {
4755 rtcp_dtls_transport = transport_controller_->CreateDtlsTransport(
4756 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
4757 }
4758
4759 ch->SetTransports(rtp_dtls_transport, rtcp_dtls_transport);
Mirko Bonadei675513b2017-11-09 11:09:25 +01004760 RTC_LOG(LS_INFO) << "Enabled BUNDLE for " << ch->content_name() << " on "
4761 << transport_name << ".";
Steve Anton75737c02017-11-06 10:37:17 -08004762 transport_controller_->DestroyDtlsTransport(
4763 old_transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4764 // If the channel needs rtcp, it means that the channel used to have a
4765 // rtcp transport which needs to be deleted now.
4766 if (need_rtcp) {
4767 transport_controller_->DestroyDtlsTransport(
4768 old_transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
4769 }
Steve Anton75737c02017-11-06 10:37:17 -08004770 };
4771
Steve Antoned10bd92017-12-05 10:52:59 -08004772 for (auto transceiver : transceivers_) {
4773 maybe_set_transport(transceiver->internal()->channel());
Steve Anton75737c02017-11-06 10:37:17 -08004774 }
Steve Antoned10bd92017-12-05 10:52:59 -08004775 maybe_set_transport(rtp_data_channel_);
4776
Steve Anton75737c02017-11-06 10:37:17 -08004777 // For SCTP, transport creation/deletion happens here instead of in the
4778 // object itself.
4779 if (sctp_transport_) {
4780 RTC_DCHECK(sctp_transport_name_);
4781 RTC_DCHECK(sctp_content_name_);
4782 if (transport_name != *sctp_transport_name_ &&
4783 bundle.HasContentName(*sctp_content_name_)) {
4784 network_thread()->Invoke<void>(
4785 RTC_FROM_HERE, rtc::Bind(&PeerConnection::ChangeSctpTransport_n, this,
4786 transport_name));
4787 }
4788 }
4789
4790 return true;
4791}
4792
Steve Anton75737c02017-11-06 10:37:17 -08004793cricket::IceConfig PeerConnection::ParseIceConfig(
4794 const PeerConnectionInterface::RTCConfiguration& config) const {
4795 cricket::ContinualGatheringPolicy gathering_policy;
4796 // TODO(honghaiz): Add the third continual gathering policy in
4797 // PeerConnectionInterface and map it to GATHER_CONTINUALLY_AND_RECOVER.
4798 switch (config.continual_gathering_policy) {
4799 case PeerConnectionInterface::GATHER_ONCE:
4800 gathering_policy = cricket::GATHER_ONCE;
4801 break;
4802 case PeerConnectionInterface::GATHER_CONTINUALLY:
4803 gathering_policy = cricket::GATHER_CONTINUALLY;
4804 break;
4805 default:
4806 RTC_NOTREACHED();
4807 gathering_policy = cricket::GATHER_ONCE;
4808 }
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08004809
Steve Anton75737c02017-11-06 10:37:17 -08004810 cricket::IceConfig ice_config;
4811 ice_config.receiving_timeout = config.ice_connection_receiving_timeout;
4812 ice_config.prioritize_most_likely_candidate_pairs =
4813 config.prioritize_most_likely_ice_candidate_pairs;
4814 ice_config.backup_connection_ping_interval =
4815 config.ice_backup_candidate_pair_ping_interval;
4816 ice_config.continual_gathering_policy = gathering_policy;
4817 ice_config.presume_writable_when_fully_relayed =
4818 config.presume_writable_when_fully_relayed;
4819 ice_config.ice_check_min_interval = config.ice_check_min_interval;
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08004820 ice_config.stun_keepalive_interval = config.stun_candidate_keepalive_interval;
Steve Anton75737c02017-11-06 10:37:17 -08004821 ice_config.regather_all_networks_interval_range =
4822 config.ice_regather_interval_range;
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08004823 ice_config.network_preference = config.network_preference;
Steve Anton75737c02017-11-06 10:37:17 -08004824 return ice_config;
4825}
4826
Steve Anton75737c02017-11-06 10:37:17 -08004827bool PeerConnection::GetLocalTrackIdBySsrc(uint32_t ssrc,
4828 std::string* track_id) {
4829 if (!local_description()) {
4830 return false;
4831 }
4832 return webrtc::GetTrackIdBySsrc(local_description()->description(), ssrc,
4833 track_id);
4834}
4835
4836bool PeerConnection::GetRemoteTrackIdBySsrc(uint32_t ssrc,
4837 std::string* track_id) {
4838 if (!remote_description()) {
4839 return false;
4840 }
4841 return webrtc::GetTrackIdBySsrc(remote_description()->description(), ssrc,
4842 track_id);
4843}
4844
4845bool PeerConnection::SendData(const cricket::SendDataParams& params,
4846 const rtc::CopyOnWriteBuffer& payload,
4847 cricket::SendDataResult* result) {
4848 if (!rtp_data_channel_ && !sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004849 RTC_LOG(LS_ERROR) << "SendData called when rtp_data_channel_ "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004850 "and sctp_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08004851 return false;
4852 }
4853 return rtp_data_channel_
4854 ? rtp_data_channel_->SendData(params, payload, result)
4855 : network_thread()->Invoke<bool>(
4856 RTC_FROM_HERE,
4857 Bind(&cricket::SctpTransportInternal::SendData,
4858 sctp_transport_.get(), params, payload, result));
4859}
4860
4861bool PeerConnection::ConnectDataChannel(DataChannel* webrtc_data_channel) {
4862 if (!rtp_data_channel_ && !sctp_transport_) {
4863 // Don't log an error here, because DataChannels are expected to call
4864 // ConnectDataChannel in this state. It's the only way to initially tell
4865 // whether or not the underlying transport is ready.
4866 return false;
4867 }
4868 if (rtp_data_channel_) {
4869 rtp_data_channel_->SignalReadyToSendData.connect(
4870 webrtc_data_channel, &DataChannel::OnChannelReady);
4871 rtp_data_channel_->SignalDataReceived.connect(webrtc_data_channel,
4872 &DataChannel::OnDataReceived);
4873 } else {
4874 SignalSctpReadyToSendData.connect(webrtc_data_channel,
4875 &DataChannel::OnChannelReady);
4876 SignalSctpDataReceived.connect(webrtc_data_channel,
4877 &DataChannel::OnDataReceived);
4878 SignalSctpStreamClosedRemotely.connect(
4879 webrtc_data_channel, &DataChannel::OnStreamClosedRemotely);
4880 }
4881 return true;
4882}
4883
4884void PeerConnection::DisconnectDataChannel(DataChannel* webrtc_data_channel) {
4885 if (!rtp_data_channel_ && !sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004886 RTC_LOG(LS_ERROR)
4887 << "DisconnectDataChannel called when rtp_data_channel_ and "
4888 "sctp_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08004889 return;
4890 }
4891 if (rtp_data_channel_) {
4892 rtp_data_channel_->SignalReadyToSendData.disconnect(webrtc_data_channel);
4893 rtp_data_channel_->SignalDataReceived.disconnect(webrtc_data_channel);
4894 } else {
4895 SignalSctpReadyToSendData.disconnect(webrtc_data_channel);
4896 SignalSctpDataReceived.disconnect(webrtc_data_channel);
4897 SignalSctpStreamClosedRemotely.disconnect(webrtc_data_channel);
4898 }
4899}
4900
4901void PeerConnection::AddSctpDataStream(int sid) {
4902 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004903 RTC_LOG(LS_ERROR)
4904 << "AddSctpDataStream called when sctp_transport_ is NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08004905 return;
4906 }
4907 network_thread()->Invoke<void>(
4908 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::OpenStream,
4909 sctp_transport_.get(), sid));
4910}
4911
4912void PeerConnection::RemoveSctpDataStream(int sid) {
4913 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004914 RTC_LOG(LS_ERROR) << "RemoveSctpDataStream called when sctp_transport_ is "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004915 "NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08004916 return;
4917 }
4918 network_thread()->Invoke<void>(
4919 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::ResetStream,
4920 sctp_transport_.get(), sid));
4921}
4922
4923bool PeerConnection::ReadyToSendData() const {
4924 return (rtp_data_channel_ && rtp_data_channel_->ready_to_send_data()) ||
4925 sctp_ready_to_send_data_;
4926}
4927
Qingsi Wang72a43a12018-02-20 16:03:18 -08004928cricket::CandidateStatsList PeerConnection::GetPooledCandidateStats() const {
4929 cricket::CandidateStatsList candidate_states_list;
4930 port_allocator_->GetCandidateStatsFromPooledSessions(&candidate_states_list);
4931 return candidate_states_list;
4932}
4933
Steve Anton5dfde182018-02-06 10:34:40 -08004934std::map<std::string, std::string> PeerConnection::GetTransportNamesByMid()
4935 const {
4936 std::map<std::string, std::string> transport_names_by_mid;
4937 for (auto transceiver : transceivers_) {
4938 cricket::BaseChannel* channel = transceiver->internal()->channel();
4939 if (channel) {
4940 transport_names_by_mid[channel->content_name()] =
4941 channel->transport_name();
4942 }
Steve Anton75737c02017-11-06 10:37:17 -08004943 }
Steve Anton5dfde182018-02-06 10:34:40 -08004944 if (rtp_data_channel_) {
4945 transport_names_by_mid[rtp_data_channel_->content_name()] =
4946 rtp_data_channel_->transport_name();
Steve Anton75737c02017-11-06 10:37:17 -08004947 }
4948 if (sctp_transport_) {
Steve Anton5dfde182018-02-06 10:34:40 -08004949 transport_names_by_mid[*sctp_content_name_] = *sctp_transport_name_;
Steve Anton75737c02017-11-06 10:37:17 -08004950 }
Steve Anton5dfde182018-02-06 10:34:40 -08004951 return transport_names_by_mid;
Steve Anton75737c02017-11-06 10:37:17 -08004952}
4953
Steve Anton5dfde182018-02-06 10:34:40 -08004954std::map<std::string, cricket::TransportStats>
4955PeerConnection::GetTransportStatsByNames(
4956 const std::set<std::string>& transport_names) {
4957 if (!network_thread()->IsCurrent()) {
4958 return network_thread()
4959 ->Invoke<std::map<std::string, cricket::TransportStats>>(
4960 RTC_FROM_HERE,
4961 [&] { return GetTransportStatsByNames(transport_names); });
Steve Anton75737c02017-11-06 10:37:17 -08004962 }
Steve Anton5dfde182018-02-06 10:34:40 -08004963 std::map<std::string, cricket::TransportStats> transport_stats_by_name;
4964 for (const std::string& transport_name : transport_names) {
4965 cricket::TransportStats transport_stats;
4966 bool success =
4967 transport_controller_->GetStats(transport_name, &transport_stats);
4968 if (success) {
4969 transport_stats_by_name[transport_name] = std::move(transport_stats);
4970 } else {
4971 RTC_LOG(LS_ERROR) << "Failed to get transport stats for transport_name="
4972 << transport_name;
4973 }
4974 }
4975 return transport_stats_by_name;
Steve Anton75737c02017-11-06 10:37:17 -08004976}
4977
4978bool PeerConnection::GetLocalCertificate(
4979 const std::string& transport_name,
4980 rtc::scoped_refptr<rtc::RTCCertificate>* certificate) {
4981 return transport_controller_->GetLocalCertificate(transport_name,
4982 certificate);
4983}
4984
Taylor Brandstetterc3928662018-02-23 13:04:51 -08004985std::unique_ptr<rtc::SSLCertChain> PeerConnection::GetRemoteSSLCertChain(
Steve Anton75737c02017-11-06 10:37:17 -08004986 const std::string& transport_name) {
Taylor Brandstetterc3928662018-02-23 13:04:51 -08004987 return transport_controller_->GetRemoteSSLCertChain(transport_name);
Steve Anton75737c02017-11-06 10:37:17 -08004988}
4989
4990cricket::DataChannelType PeerConnection::data_channel_type() const {
4991 return data_channel_type_;
4992}
4993
4994bool PeerConnection::IceRestartPending(const std::string& content_name) const {
4995 return pending_ice_restarts_.find(content_name) !=
4996 pending_ice_restarts_.end();
4997}
4998
Steve Anton75737c02017-11-06 10:37:17 -08004999bool PeerConnection::NeedsIceRestart(const std::string& content_name) const {
5000 return transport_controller_->NeedsIceRestart(content_name);
5001}
5002
5003void PeerConnection::OnCertificateReady(
5004 const rtc::scoped_refptr<rtc::RTCCertificate>& certificate) {
5005 transport_controller_->SetLocalCertificate(certificate);
5006}
5007
5008void PeerConnection::OnDtlsSrtpSetupFailure(cricket::BaseChannel*, bool rtcp) {
Steve Antonf8470812017-12-04 10:46:21 -08005009 SetSessionError(SessionError::kTransport,
5010 rtcp ? kDtlsSrtpSetupFailureRtcp : kDtlsSrtpSetupFailureRtp);
Steve Anton75737c02017-11-06 10:37:17 -08005011}
5012
5013void PeerConnection::OnTransportControllerConnectionState(
5014 cricket::IceConnectionState state) {
5015 switch (state) {
5016 case cricket::kIceConnectionConnecting:
5017 // If the current state is Connected or Completed, then there were
5018 // writable channels but now there are not, so the next state must
5019 // be Disconnected.
5020 // kIceConnectionConnecting is currently used as the default,
5021 // un-connected state by the TransportController, so its only use is
5022 // detecting disconnections.
5023 if (ice_connection_state_ ==
5024 PeerConnectionInterface::kIceConnectionConnected ||
5025 ice_connection_state_ ==
5026 PeerConnectionInterface::kIceConnectionCompleted) {
5027 SetIceConnectionState(
5028 PeerConnectionInterface::kIceConnectionDisconnected);
5029 }
5030 break;
5031 case cricket::kIceConnectionFailed:
5032 SetIceConnectionState(PeerConnectionInterface::kIceConnectionFailed);
5033 break;
5034 case cricket::kIceConnectionConnected:
Mirko Bonadei675513b2017-11-09 11:09:25 +01005035 RTC_LOG(LS_INFO) << "Changing to ICE connected state because "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005036 "all transports are writable.";
Steve Anton75737c02017-11-06 10:37:17 -08005037 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
5038 break;
5039 case cricket::kIceConnectionCompleted:
Mirko Bonadei675513b2017-11-09 11:09:25 +01005040 RTC_LOG(LS_INFO) << "Changing to ICE completed state because "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005041 "all transports are complete.";
Steve Anton75737c02017-11-06 10:37:17 -08005042 if (ice_connection_state_ !=
5043 PeerConnectionInterface::kIceConnectionConnected) {
5044 // If jumping directly from "checking" to "connected",
5045 // signal "connected" first.
5046 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
5047 }
5048 SetIceConnectionState(PeerConnectionInterface::kIceConnectionCompleted);
5049 if (metrics_observer()) {
5050 ReportTransportStats();
5051 }
5052 break;
5053 default:
5054 RTC_NOTREACHED();
5055 }
5056}
5057
5058void PeerConnection::OnTransportControllerCandidatesGathered(
5059 const std::string& transport_name,
5060 const cricket::Candidates& candidates) {
5061 RTC_DCHECK(signaling_thread()->IsCurrent());
5062 int sdp_mline_index;
5063 if (!GetLocalCandidateMediaIndex(transport_name, &sdp_mline_index)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005064 RTC_LOG(LS_ERROR)
5065 << "OnTransportControllerCandidatesGathered: content name "
5066 << transport_name << " not found";
Steve Anton75737c02017-11-06 10:37:17 -08005067 return;
5068 }
5069
5070 for (cricket::Candidates::const_iterator citer = candidates.begin();
5071 citer != candidates.end(); ++citer) {
5072 // Use transport_name as the candidate media id.
5073 std::unique_ptr<JsepIceCandidate> candidate(
5074 new JsepIceCandidate(transport_name, sdp_mline_index, *citer));
5075 if (local_description()) {
5076 mutable_local_description()->AddCandidate(candidate.get());
5077 }
5078 OnIceCandidate(std::move(candidate));
5079 }
5080}
5081
5082void PeerConnection::OnTransportControllerCandidatesRemoved(
5083 const std::vector<cricket::Candidate>& candidates) {
5084 RTC_DCHECK(signaling_thread()->IsCurrent());
5085 // Sanity check.
5086 for (const cricket::Candidate& candidate : candidates) {
5087 if (candidate.transport_name().empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005088 RTC_LOG(LS_ERROR) << "OnTransportControllerCandidatesRemoved: "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005089 "empty content name in candidate "
Mirko Bonadei675513b2017-11-09 11:09:25 +01005090 << candidate.ToString();
Steve Anton75737c02017-11-06 10:37:17 -08005091 return;
5092 }
5093 }
5094
5095 if (local_description()) {
5096 mutable_local_description()->RemoveCandidates(candidates);
5097 }
5098 OnIceCandidatesRemoved(candidates);
5099}
5100
5101void PeerConnection::OnTransportControllerDtlsHandshakeError(
5102 rtc::SSLHandshakeError error) {
5103 if (metrics_observer()) {
5104 metrics_observer()->IncrementEnumCounter(
5105 webrtc::kEnumCounterDtlsHandshakeError, static_cast<int>(error),
5106 static_cast<int>(rtc::SSLHandshakeError::MAX_VALUE));
5107 }
5108}
5109
Steve Antoned10bd92017-12-05 10:52:59 -08005110void PeerConnection::EnableSending() {
5111 for (auto transceiver : transceivers_) {
5112 cricket::BaseChannel* channel = transceiver->internal()->channel();
5113 if (channel && !channel->enabled()) {
5114 channel->Enable(true);
5115 }
Steve Anton75737c02017-11-06 10:37:17 -08005116 }
5117
Steve Anton4171afb2017-11-20 10:20:22 -08005118 if (rtp_data_channel_ && !rtp_data_channel_->enabled()) {
Steve Anton75737c02017-11-06 10:37:17 -08005119 rtp_data_channel_->Enable(true);
Steve Anton4171afb2017-11-20 10:20:22 -08005120 }
Steve Anton75737c02017-11-06 10:37:17 -08005121}
5122
5123// Returns the media index for a local ice candidate given the content name.
5124bool PeerConnection::GetLocalCandidateMediaIndex(
5125 const std::string& content_name,
5126 int* sdp_mline_index) {
5127 if (!local_description() || !sdp_mline_index) {
5128 return false;
5129 }
5130
5131 bool content_found = false;
5132 const ContentInfos& contents = local_description()->description()->contents();
5133 for (size_t index = 0; index < contents.size(); ++index) {
5134 if (contents[index].name == content_name) {
5135 *sdp_mline_index = static_cast<int>(index);
5136 content_found = true;
5137 break;
5138 }
5139 }
5140 return content_found;
5141}
5142
5143bool PeerConnection::UseCandidatesInSessionDescription(
5144 const SessionDescriptionInterface* remote_desc) {
5145 if (!remote_desc) {
5146 return true;
5147 }
5148 bool ret = true;
5149
5150 for (size_t m = 0; m < remote_desc->number_of_mediasections(); ++m) {
5151 const IceCandidateCollection* candidates = remote_desc->candidates(m);
5152 for (size_t n = 0; n < candidates->count(); ++n) {
5153 const IceCandidateInterface* candidate = candidates->at(n);
5154 bool valid = false;
5155 if (!ReadyToUseRemoteCandidate(candidate, remote_desc, &valid)) {
5156 if (valid) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005157 RTC_LOG(LS_INFO)
5158 << "UseCandidatesInSessionDescription: Not ready to use "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005159 "candidate.";
Steve Anton75737c02017-11-06 10:37:17 -08005160 }
5161 continue;
5162 }
5163 ret = UseCandidate(candidate);
5164 if (!ret) {
5165 break;
5166 }
5167 }
5168 }
5169 return ret;
5170}
5171
5172bool PeerConnection::UseCandidate(const IceCandidateInterface* candidate) {
5173 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
5174 size_t remote_content_size =
5175 remote_description()->description()->contents().size();
5176 if (mediacontent_index >= remote_content_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005177 RTC_LOG(LS_ERROR) << "UseCandidate: Invalid candidate media index.";
Steve Anton75737c02017-11-06 10:37:17 -08005178 return false;
5179 }
5180
5181 cricket::ContentInfo content =
5182 remote_description()->description()->contents()[mediacontent_index];
5183 std::vector<cricket::Candidate> candidates;
5184 candidates.push_back(candidate->candidate());
5185 // Invoking BaseSession method to handle remote candidates.
5186 std::string error;
5187 if (transport_controller_->AddRemoteCandidates(content.name, candidates,
5188 &error)) {
5189 // Candidates successfully submitted for checking.
5190 if (ice_connection_state_ == PeerConnectionInterface::kIceConnectionNew ||
5191 ice_connection_state_ ==
5192 PeerConnectionInterface::kIceConnectionDisconnected) {
5193 // If state is New, then the session has just gotten its first remote ICE
5194 // candidates, so go to Checking.
5195 // If state is Disconnected, the session is re-using old candidates or
5196 // receiving additional ones, so go to Checking.
5197 // If state is Connected, stay Connected.
5198 // TODO(bemasc): If state is Connected, and the new candidates are for a
5199 // newly added transport, then the state actually _should_ move to
5200 // checking. Add a way to distinguish that case.
5201 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
5202 }
5203 // TODO(bemasc): If state is Completed, go back to Connected.
5204 } else {
5205 if (!error.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005206 RTC_LOG(LS_WARNING) << error;
Steve Anton75737c02017-11-06 10:37:17 -08005207 }
5208 }
5209 return true;
5210}
5211
5212void PeerConnection::RemoveUnusedChannels(const SessionDescription* desc) {
Steve Anton75737c02017-11-06 10:37:17 -08005213 // Destroy video channel first since it may have a pointer to the
5214 // voice channel.
5215 const cricket::ContentInfo* video_info = cricket::GetFirstVideoContent(desc);
Steve Anton6fec8802017-12-04 10:37:29 -08005216 if (!video_info || video_info->rejected) {
5217 DestroyTransceiverChannel(GetVideoTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08005218 }
5219
Steve Anton6fec8802017-12-04 10:37:29 -08005220 const cricket::ContentInfo* audio_info = cricket::GetFirstAudioContent(desc);
5221 if (!audio_info || audio_info->rejected) {
5222 DestroyTransceiverChannel(GetAudioTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08005223 }
5224
5225 const cricket::ContentInfo* data_info = cricket::GetFirstDataContent(desc);
5226 if (!data_info || data_info->rejected) {
Steve Anton6fec8802017-12-04 10:37:29 -08005227 DestroyDataChannel();
Steve Anton75737c02017-11-06 10:37:17 -08005228 }
5229}
5230
Steve Antoneda6ccd2017-12-04 10:21:55 -08005231std::string PeerConnection::GetTransportNameForMediaSection(
5232 const std::string& mid,
5233 const cricket::ContentGroup* bundle_group) const {
5234 if (!bundle_group) {
5235 return mid;
Steve Anton75737c02017-11-06 10:37:17 -08005236 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005237 const std::string* first_content_name = bundle_group->FirstContentName();
Steve Anton75737c02017-11-06 10:37:17 -08005238 if (!first_content_name) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005239 RTC_LOG(LS_WARNING) << "Tried to BUNDLE with no contents.";
Steve Antoneda6ccd2017-12-04 10:21:55 -08005240 return mid;
Steve Anton75737c02017-11-06 10:37:17 -08005241 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005242 if (!bundle_group->HasContentName(mid)) {
5243 RTC_LOG(LS_WARNING) << mid << " is not part of any bundle group";
5244 return mid;
Steve Anton75737c02017-11-06 10:37:17 -08005245 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005246 RTC_LOG(LS_INFO) << "Bundling " << mid << " on " << *first_content_name;
5247 return *first_content_name;
Steve Anton75737c02017-11-06 10:37:17 -08005248}
5249
Steve Antondcc3c022017-12-22 16:02:54 -08005250RTCErrorOr<const cricket::ContentGroup*> PeerConnection::GetEarlyBundleGroup(
5251 const SessionDescription& desc) const {
Steve Anton75737c02017-11-06 10:37:17 -08005252 const cricket::ContentGroup* bundle_group = nullptr;
5253 if (configuration_.bundle_policy ==
5254 PeerConnectionInterface::kBundlePolicyMaxBundle) {
Steve Antondcc3c022017-12-22 16:02:54 -08005255 bundle_group = desc.GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton75737c02017-11-06 10:37:17 -08005256 if (!bundle_group) {
Steve Anton8a006912017-12-04 15:25:56 -08005257 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5258 "max-bundle configured but session description "
5259 "has no BUNDLE group");
Steve Anton75737c02017-11-06 10:37:17 -08005260 }
5261 }
Steve Antondcc3c022017-12-22 16:02:54 -08005262 return std::move(bundle_group);
5263}
5264
5265RTCError PeerConnection::CreateChannels(const SessionDescription& desc) {
5266 auto bundle_group_or_error = GetEarlyBundleGroup(desc);
5267 if (!bundle_group_or_error.ok()) {
5268 return bundle_group_or_error.MoveError();
5269 }
5270 const cricket::ContentGroup* bundle_group = bundle_group_or_error.MoveValue();
Steve Anton75737c02017-11-06 10:37:17 -08005271
Steve Antoneda6ccd2017-12-04 10:21:55 -08005272 // Creating the media channels and transport proxies.
Steve Antondcc3c022017-12-22 16:02:54 -08005273 const cricket::ContentInfo* voice = cricket::GetFirstAudioContent(&desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08005274 if (voice && !voice->rejected &&
5275 !GetAudioTransceiver()->internal()->channel()) {
5276 cricket::VoiceChannel* voice_channel = CreateVoiceChannel(
5277 voice->name,
5278 GetTransportNameForMediaSection(voice->name, bundle_group));
5279 if (!voice_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08005280 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5281 "Failed to create voice channel.");
Steve Antoneda6ccd2017-12-04 10:21:55 -08005282 }
5283 GetAudioTransceiver()->internal()->SetChannel(voice_channel);
5284 }
5285
Steve Antondcc3c022017-12-22 16:02:54 -08005286 const cricket::ContentInfo* video = cricket::GetFirstVideoContent(&desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08005287 if (video && !video->rejected &&
5288 !GetVideoTransceiver()->internal()->channel()) {
5289 cricket::VideoChannel* video_channel = CreateVideoChannel(
5290 video->name,
5291 GetTransportNameForMediaSection(video->name, bundle_group));
5292 if (!video_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08005293 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5294 "Failed to create video channel.");
Steve Anton75737c02017-11-06 10:37:17 -08005295 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005296 GetVideoTransceiver()->internal()->SetChannel(video_channel);
Steve Anton75737c02017-11-06 10:37:17 -08005297 }
5298
Steve Antondcc3c022017-12-22 16:02:54 -08005299 const cricket::ContentInfo* data = cricket::GetFirstDataContent(&desc);
Steve Anton75737c02017-11-06 10:37:17 -08005300 if (data_channel_type_ != cricket::DCT_NONE && data && !data->rejected &&
5301 !rtp_data_channel_ && !sctp_transport_) {
Steve Antoneda6ccd2017-12-04 10:21:55 -08005302 if (!CreateDataChannel(data->name, GetTransportNameForMediaSection(
5303 data->name, bundle_group))) {
Steve Anton8a006912017-12-04 15:25:56 -08005304 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5305 "Failed to create data channel.");
Steve Anton75737c02017-11-06 10:37:17 -08005306 }
5307 }
5308
Steve Anton8a006912017-12-04 15:25:56 -08005309 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08005310}
5311
Steve Anton4171afb2017-11-20 10:20:22 -08005312// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08005313cricket::VoiceChannel* PeerConnection::CreateVoiceChannel(
5314 const std::string& mid,
5315 const std::string& transport_name) {
Steve Anton75737c02017-11-06 10:37:17 -08005316 cricket::DtlsTransportInternal* rtp_dtls_transport =
5317 transport_controller_->CreateDtlsTransport(
5318 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5319 cricket::DtlsTransportInternal* rtcp_dtls_transport = nullptr;
5320 if (configuration_.rtcp_mux_policy !=
5321 PeerConnectionInterface::kRtcpMuxPolicyRequire) {
5322 rtcp_dtls_transport = transport_controller_->CreateDtlsTransport(
5323 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
5324 }
5325
5326 cricket::VoiceChannel* voice_channel = channel_manager()->CreateVoiceChannel(
5327 call_.get(), configuration_.media_config, rtp_dtls_transport,
Steve Antoneda6ccd2017-12-04 10:21:55 -08005328 rtcp_dtls_transport, signaling_thread(), mid, SrtpRequired(),
5329 audio_options_);
Steve Anton75737c02017-11-06 10:37:17 -08005330 if (!voice_channel) {
5331 transport_controller_->DestroyDtlsTransport(
5332 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5333 if (rtcp_dtls_transport) {
5334 transport_controller_->DestroyDtlsTransport(
5335 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
5336 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005337 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08005338 }
Steve Anton75737c02017-11-06 10:37:17 -08005339 voice_channel->SignalRtcpMuxFullyActive.connect(
5340 this, &PeerConnection::DestroyRtcpTransport_n);
5341 voice_channel->SignalDtlsSrtpSetupFailure.connect(
5342 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08005343 voice_channel->SignalSentPacket.connect(this,
5344 &PeerConnection::OnSentPacket_w);
Steve Anton4171afb2017-11-20 10:20:22 -08005345
Steve Antoneda6ccd2017-12-04 10:21:55 -08005346 return voice_channel;
Steve Anton75737c02017-11-06 10:37:17 -08005347}
5348
Steve Anton4171afb2017-11-20 10:20:22 -08005349// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08005350cricket::VideoChannel* PeerConnection::CreateVideoChannel(
5351 const std::string& mid,
5352 const std::string& transport_name) {
Steve Anton75737c02017-11-06 10:37:17 -08005353 cricket::DtlsTransportInternal* rtp_dtls_transport =
5354 transport_controller_->CreateDtlsTransport(
5355 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5356 cricket::DtlsTransportInternal* rtcp_dtls_transport = nullptr;
5357 if (configuration_.rtcp_mux_policy !=
5358 PeerConnectionInterface::kRtcpMuxPolicyRequire) {
5359 rtcp_dtls_transport = transport_controller_->CreateDtlsTransport(
5360 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
5361 }
5362
5363 cricket::VideoChannel* video_channel = channel_manager()->CreateVideoChannel(
5364 call_.get(), configuration_.media_config, rtp_dtls_transport,
Steve Antoneda6ccd2017-12-04 10:21:55 -08005365 rtcp_dtls_transport, signaling_thread(), mid, SrtpRequired(),
5366 video_options_);
Steve Anton75737c02017-11-06 10:37:17 -08005367
5368 if (!video_channel) {
5369 transport_controller_->DestroyDtlsTransport(
5370 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5371 if (rtcp_dtls_transport) {
5372 transport_controller_->DestroyDtlsTransport(
5373 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
5374 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005375 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08005376 }
Steve Anton75737c02017-11-06 10:37:17 -08005377 video_channel->SignalRtcpMuxFullyActive.connect(
5378 this, &PeerConnection::DestroyRtcpTransport_n);
5379 video_channel->SignalDtlsSrtpSetupFailure.connect(
5380 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08005381 video_channel->SignalSentPacket.connect(this,
5382 &PeerConnection::OnSentPacket_w);
Steve Anton4171afb2017-11-20 10:20:22 -08005383
Steve Antoneda6ccd2017-12-04 10:21:55 -08005384 return video_channel;
Steve Anton75737c02017-11-06 10:37:17 -08005385}
5386
Steve Antoneda6ccd2017-12-04 10:21:55 -08005387bool PeerConnection::CreateDataChannel(const std::string& mid,
5388 const std::string& transport_name) {
Steve Anton75737c02017-11-06 10:37:17 -08005389 bool sctp = (data_channel_type_ == cricket::DCT_SCTP);
5390 if (sctp) {
5391 if (!sctp_factory_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005392 RTC_LOG(LS_ERROR)
Steve Anton75737c02017-11-06 10:37:17 -08005393 << "Trying to create SCTP transport, but didn't compile with "
5394 "SCTP support (HAVE_SCTP)";
5395 return false;
5396 }
5397 if (!network_thread()->Invoke<bool>(
5398 RTC_FROM_HERE, rtc::Bind(&PeerConnection::CreateSctpTransport_n,
Steve Antoneda6ccd2017-12-04 10:21:55 -08005399 this, mid, transport_name))) {
Steve Anton75737c02017-11-06 10:37:17 -08005400 return false;
5401 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005402 for (const auto& channel : sctp_data_channels_) {
5403 channel->OnTransportChannelCreated();
5404 }
Steve Anton75737c02017-11-06 10:37:17 -08005405 } else {
Steve Anton75737c02017-11-06 10:37:17 -08005406 cricket::DtlsTransportInternal* rtp_dtls_transport =
5407 transport_controller_->CreateDtlsTransport(
5408 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5409 cricket::DtlsTransportInternal* rtcp_dtls_transport = nullptr;
5410 if (configuration_.rtcp_mux_policy !=
5411 PeerConnectionInterface::kRtcpMuxPolicyRequire) {
5412 rtcp_dtls_transport = transport_controller_->CreateDtlsTransport(
5413 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
5414 }
5415
5416 rtp_data_channel_ = channel_manager()->CreateRtpDataChannel(
5417 configuration_.media_config, rtp_dtls_transport, rtcp_dtls_transport,
Steve Antoneda6ccd2017-12-04 10:21:55 -08005418 signaling_thread(), mid, SrtpRequired());
Steve Anton75737c02017-11-06 10:37:17 -08005419
5420 if (!rtp_data_channel_) {
5421 transport_controller_->DestroyDtlsTransport(
5422 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5423 if (rtcp_dtls_transport) {
5424 transport_controller_->DestroyDtlsTransport(
5425 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
5426 }
5427 return false;
5428 }
5429
5430 rtp_data_channel_->SignalRtcpMuxFullyActive.connect(
5431 this, &PeerConnection::DestroyRtcpTransport_n);
5432 rtp_data_channel_->SignalDtlsSrtpSetupFailure.connect(
5433 this, &PeerConnection::OnDtlsSrtpSetupFailure);
5434 rtp_data_channel_->SignalSentPacket.connect(
5435 this, &PeerConnection::OnSentPacket_w);
5436 }
5437
Steve Anton75737c02017-11-06 10:37:17 -08005438 return true;
5439}
5440
5441Call::Stats PeerConnection::GetCallStats() {
5442 if (!worker_thread()->IsCurrent()) {
5443 return worker_thread()->Invoke<Call::Stats>(
5444 RTC_FROM_HERE, rtc::Bind(&PeerConnection::GetCallStats, this));
5445 }
5446 if (call_) {
5447 return call_->GetStats();
5448 } else {
5449 return Call::Stats();
5450 }
5451}
5452
Steve Anton75737c02017-11-06 10:37:17 -08005453bool PeerConnection::CreateSctpTransport_n(const std::string& content_name,
5454 const std::string& transport_name) {
5455 RTC_DCHECK(network_thread()->IsCurrent());
5456 RTC_DCHECK(sctp_factory_);
5457 cricket::DtlsTransportInternal* tc =
5458 transport_controller_->CreateDtlsTransport_n(
5459 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5460 sctp_transport_ = sctp_factory_->CreateSctpTransport(tc);
5461 RTC_DCHECK(sctp_transport_);
5462 sctp_invoker_.reset(new rtc::AsyncInvoker());
5463 sctp_transport_->SignalReadyToSendData.connect(
5464 this, &PeerConnection::OnSctpTransportReadyToSendData_n);
5465 sctp_transport_->SignalDataReceived.connect(
5466 this, &PeerConnection::OnSctpTransportDataReceived_n);
5467 sctp_transport_->SignalStreamClosedRemotely.connect(
5468 this, &PeerConnection::OnSctpStreamClosedRemotely_n);
Oskar Sundbom9b28a032017-11-16 10:53:30 +01005469 sctp_transport_name_ = transport_name;
5470 sctp_content_name_ = content_name;
Steve Anton75737c02017-11-06 10:37:17 -08005471 return true;
5472}
5473
5474void PeerConnection::ChangeSctpTransport_n(const std::string& transport_name) {
5475 RTC_DCHECK(network_thread()->IsCurrent());
5476 RTC_DCHECK(sctp_transport_);
5477 RTC_DCHECK(sctp_transport_name_);
5478 std::string old_sctp_transport_name = *sctp_transport_name_;
Oskar Sundbom9b28a032017-11-16 10:53:30 +01005479 sctp_transport_name_ = transport_name;
Steve Anton75737c02017-11-06 10:37:17 -08005480 cricket::DtlsTransportInternal* tc =
5481 transport_controller_->CreateDtlsTransport_n(
5482 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5483 sctp_transport_->SetTransportChannel(tc);
5484 transport_controller_->DestroyDtlsTransport_n(
5485 old_sctp_transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5486}
5487
5488void PeerConnection::DestroySctpTransport_n() {
5489 RTC_DCHECK(network_thread()->IsCurrent());
5490 sctp_transport_.reset(nullptr);
Taylor Brandstetter389a97c2018-01-03 16:26:06 -08005491 transport_controller_->DestroyDtlsTransport_n(
5492 *sctp_transport_name_, cricket::ICE_CANDIDATE_COMPONENT_RTP);
Steve Anton75737c02017-11-06 10:37:17 -08005493 sctp_content_name_.reset();
5494 sctp_transport_name_.reset();
5495 sctp_invoker_.reset(nullptr);
5496 sctp_ready_to_send_data_ = false;
5497}
5498
5499void PeerConnection::OnSctpTransportReadyToSendData_n() {
5500 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5501 RTC_DCHECK(network_thread()->IsCurrent());
5502 // Note: Cannot use rtc::Bind here because it will grab a reference to
5503 // PeerConnection and potentially cause PeerConnection to live longer than
5504 // expected. It is safe not to grab a reference since the sctp_invoker_ will
5505 // be destroyed before PeerConnection is destroyed, and at that point all
5506 // pending tasks will be cleared.
5507 sctp_invoker_->AsyncInvoke<void>(RTC_FROM_HERE, signaling_thread(), [this] {
5508 OnSctpTransportReadyToSendData_s(true);
5509 });
5510}
5511
5512void PeerConnection::OnSctpTransportReadyToSendData_s(bool ready) {
5513 RTC_DCHECK(signaling_thread()->IsCurrent());
5514 sctp_ready_to_send_data_ = ready;
5515 SignalSctpReadyToSendData(ready);
5516}
5517
5518void PeerConnection::OnSctpTransportDataReceived_n(
5519 const cricket::ReceiveDataParams& params,
5520 const rtc::CopyOnWriteBuffer& payload) {
5521 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5522 RTC_DCHECK(network_thread()->IsCurrent());
5523 // Note: Cannot use rtc::Bind here because it will grab a reference to
5524 // PeerConnection and potentially cause PeerConnection to live longer than
5525 // expected. It is safe not to grab a reference since the sctp_invoker_ will
5526 // be destroyed before PeerConnection is destroyed, and at that point all
5527 // pending tasks will be cleared.
5528 sctp_invoker_->AsyncInvoke<void>(
5529 RTC_FROM_HERE, signaling_thread(), [this, params, payload] {
5530 OnSctpTransportDataReceived_s(params, payload);
5531 });
5532}
5533
5534void PeerConnection::OnSctpTransportDataReceived_s(
5535 const cricket::ReceiveDataParams& params,
5536 const rtc::CopyOnWriteBuffer& payload) {
5537 RTC_DCHECK(signaling_thread()->IsCurrent());
5538 if (params.type == cricket::DMT_CONTROL && IsOpenMessage(payload)) {
5539 // Received OPEN message; parse and signal that a new data channel should
5540 // be created.
5541 std::string label;
5542 InternalDataChannelInit config;
5543 config.id = params.ssrc;
5544 if (!ParseDataChannelOpenMessage(payload, &label, &config)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005545 RTC_LOG(LS_WARNING) << "Failed to parse the OPEN message for sid "
5546 << params.ssrc;
Steve Anton75737c02017-11-06 10:37:17 -08005547 return;
5548 }
5549 config.open_handshake_role = InternalDataChannelInit::kAcker;
5550 OnDataChannelOpenMessage(label, config);
5551 } else {
5552 // Otherwise just forward the signal.
5553 SignalSctpDataReceived(params, payload);
5554 }
5555}
5556
5557void PeerConnection::OnSctpStreamClosedRemotely_n(int sid) {
5558 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5559 RTC_DCHECK(network_thread()->IsCurrent());
5560 sctp_invoker_->AsyncInvoke<void>(
5561 RTC_FROM_HERE, signaling_thread(),
5562 rtc::Bind(&sigslot::signal1<int>::operator(),
5563 &SignalSctpStreamClosedRemotely, sid));
5564}
5565
5566// Returns false if bundle is enabled and rtcp_mux is disabled.
5567bool PeerConnection::ValidateBundleSettings(const SessionDescription* desc) {
5568 bool bundle_enabled = desc->HasGroup(cricket::GROUP_TYPE_BUNDLE);
5569 if (!bundle_enabled)
5570 return true;
5571
5572 const cricket::ContentGroup* bundle_group =
5573 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
5574 RTC_DCHECK(bundle_group != NULL);
5575
5576 const cricket::ContentInfos& contents = desc->contents();
5577 for (cricket::ContentInfos::const_iterator citer = contents.begin();
5578 citer != contents.end(); ++citer) {
5579 const cricket::ContentInfo* content = (&*citer);
5580 RTC_DCHECK(content != NULL);
5581 if (bundle_group->HasContentName(content->name) && !content->rejected &&
Steve Anton5adfafd2017-12-20 16:34:00 -08005582 content->type == MediaProtocolType::kRtp) {
Steve Anton75737c02017-11-06 10:37:17 -08005583 if (!HasRtcpMuxEnabled(content))
5584 return false;
5585 }
5586 }
5587 // RTCP-MUX is enabled in all the contents.
5588 return true;
5589}
5590
5591bool PeerConnection::HasRtcpMuxEnabled(const cricket::ContentInfo* content) {
Steve Antonb1c1de12017-12-21 15:14:30 -08005592 return content->media_description()->rtcp_mux();
Steve Anton75737c02017-11-06 10:37:17 -08005593}
5594
Steve Anton8a006912017-12-04 15:25:56 -08005595RTCError PeerConnection::ValidateSessionDescription(
Steve Anton75737c02017-11-06 10:37:17 -08005596 const SessionDescriptionInterface* sdesc,
Steve Anton8a006912017-12-04 15:25:56 -08005597 cricket::ContentSource source) {
Steve Antonf8470812017-12-04 10:46:21 -08005598 if (session_error() != SessionError::kNone) {
Steve Anton8a006912017-12-04 15:25:56 -08005599 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
Steve Anton75737c02017-11-06 10:37:17 -08005600 }
5601
5602 if (!sdesc || !sdesc->description()) {
Steve Anton8a006912017-12-04 15:25:56 -08005603 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidSdp);
Steve Anton75737c02017-11-06 10:37:17 -08005604 }
5605
Steve Anton3828c062017-12-06 10:34:51 -08005606 SdpType type = sdesc->GetType();
5607 if ((source == cricket::CS_LOCAL && !ExpectSetLocalDescription(type)) ||
5608 (source == cricket::CS_REMOTE && !ExpectSetRemoteDescription(type))) {
Steve Anton8a006912017-12-04 15:25:56 -08005609 LOG_AND_RETURN_ERROR(
5610 RTCErrorType::INVALID_PARAMETER,
5611 "Called in wrong state: " + GetSignalingStateString(signaling_state()));
Steve Anton75737c02017-11-06 10:37:17 -08005612 }
5613
5614 // Verify crypto settings.
5615 std::string crypto_error;
Steve Anton8a006912017-12-04 15:25:56 -08005616 if (webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED ||
5617 dtls_enabled_) {
Harald Alvestrand194939b2018-01-24 16:04:13 +01005618 RTCError crypto_error =
5619 VerifyCrypto(sdesc->description(), dtls_enabled_, uma_observer_);
Steve Anton8a006912017-12-04 15:25:56 -08005620 if (!crypto_error.ok()) {
5621 return crypto_error;
5622 }
Steve Anton75737c02017-11-06 10:37:17 -08005623 }
5624
5625 // Verify ice-ufrag and ice-pwd.
5626 if (!VerifyIceUfragPwdPresent(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08005627 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5628 kSdpWithoutIceUfragPwd);
Steve Anton75737c02017-11-06 10:37:17 -08005629 }
5630
5631 if (!ValidateBundleSettings(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08005632 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5633 kBundleWithoutRtcpMux);
Steve Anton75737c02017-11-06 10:37:17 -08005634 }
5635
5636 // TODO(skvlad): When the local rtcp-mux policy is Require, reject any
5637 // m-lines that do not rtcp-mux enabled.
5638
5639 // Verify m-lines in Answer when compared against Offer.
Steve Anton3828c062017-12-06 10:34:51 -08005640 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Seth Hampsonae8a90a2018-02-13 15:33:48 -08005641 // With an answer we want to compare the new answer session description with
5642 // the offer's session description from the current negotiation.
Steve Anton75737c02017-11-06 10:37:17 -08005643 const cricket::SessionDescription* offer_desc =
5644 (source == cricket::CS_LOCAL) ? remote_description()->description()
5645 : local_description()->description();
Seth Hampsonae8a90a2018-02-13 15:33:48 -08005646 if (!MediaSectionsHaveSameCount(*offer_desc, *sdesc->description()) ||
5647 !MediaSectionsInSameOrder(*offer_desc, nullptr, *sdesc->description(),
5648 type)) {
Steve Anton8a006912017-12-04 15:25:56 -08005649 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5650 kMlineMismatchInAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08005651 }
5652 } else {
Steve Anton75737c02017-11-06 10:37:17 -08005653 // The re-offers should respect the order of m= sections in current
5654 // description. See RFC3264 Section 8 paragraph 4 for more details.
Seth Hampsonae8a90a2018-02-13 15:33:48 -08005655 // With a re-offer, either the current local or current remote descriptions
5656 // could be the most up to date, so we would like to check against both of
5657 // them if they exist. It could be the case that one of them has a 0 port
5658 // for a media section, but the other does not. This is important to check
5659 // against in the case that we are recycling an m= section.
5660 const cricket::SessionDescription* current_desc = nullptr;
5661 const cricket::SessionDescription* secondary_current_desc = nullptr;
5662 if (local_description()) {
5663 current_desc = local_description()->description();
5664 if (remote_description()) {
5665 secondary_current_desc = remote_description()->description();
5666 }
5667 } else if (remote_description()) {
5668 current_desc = remote_description()->description();
5669 }
Steve Anton75737c02017-11-06 10:37:17 -08005670 if (current_desc &&
Seth Hampsonae8a90a2018-02-13 15:33:48 -08005671 !MediaSectionsInSameOrder(*current_desc, secondary_current_desc,
5672 *sdesc->description(), type)) {
Steve Anton8a006912017-12-04 15:25:56 -08005673 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5674 kMlineMismatchInSubsequentOffer);
Steve Anton75737c02017-11-06 10:37:17 -08005675 }
5676 }
5677
Steve Anton8a006912017-12-04 15:25:56 -08005678 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08005679}
5680
Steve Anton3828c062017-12-06 10:34:51 -08005681bool PeerConnection::ExpectSetLocalDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08005682 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08005683 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08005684 return (state == PeerConnectionInterface::kStable) ||
5685 (state == PeerConnectionInterface::kHaveLocalOffer);
Steve Anton20393062017-12-04 16:24:52 -08005686 } else {
Steve Anton3828c062017-12-06 10:34:51 -08005687 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08005688 return (state == PeerConnectionInterface::kHaveRemoteOffer) ||
5689 (state == PeerConnectionInterface::kHaveLocalPrAnswer);
5690 }
5691}
5692
Steve Anton3828c062017-12-06 10:34:51 -08005693bool PeerConnection::ExpectSetRemoteDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08005694 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08005695 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08005696 return (state == PeerConnectionInterface::kStable) ||
5697 (state == PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton20393062017-12-04 16:24:52 -08005698 } else {
Steve Anton3828c062017-12-06 10:34:51 -08005699 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08005700 return (state == PeerConnectionInterface::kHaveLocalOffer) ||
5701 (state == PeerConnectionInterface::kHaveRemotePrAnswer);
5702 }
5703}
5704
Steve Antonf8470812017-12-04 10:46:21 -08005705const char* PeerConnection::SessionErrorToString(SessionError error) const {
5706 switch (error) {
5707 case SessionError::kNone:
5708 return "ERROR_NONE";
5709 case SessionError::kContent:
5710 return "ERROR_CONTENT";
5711 case SessionError::kTransport:
5712 return "ERROR_TRANSPORT";
5713 }
5714 RTC_NOTREACHED();
5715 return "";
5716}
5717
Steve Anton75737c02017-11-06 10:37:17 -08005718std::string PeerConnection::GetSessionErrorMsg() {
5719 std::ostringstream desc;
Steve Antonf8470812017-12-04 10:46:21 -08005720 desc << kSessionError << SessionErrorToString(session_error()) << ". ";
5721 desc << kSessionErrorDesc << session_error_desc() << ".";
Steve Anton75737c02017-11-06 10:37:17 -08005722 return desc.str();
5723}
5724
Steve Anton0ffaaa22018-02-23 10:31:30 -08005725void PeerConnection::ReportNegotiatedSdpSemantics(
5726 const SessionDescriptionInterface& answer) {
5727 if (!uma_observer_) {
5728 return;
5729 }
5730 switch (answer.description()->msid_signaling()) {
5731 case 0:
5732 uma_observer_->IncrementEnumCounter(kEnumCounterSdpSemanticNegotiated,
5733 kSdpSemanticNegotiatedNone,
5734 kSdpSemanticNegotiatedMax);
5735 break;
5736 case cricket::kMsidSignalingMediaSection:
5737 uma_observer_->IncrementEnumCounter(kEnumCounterSdpSemanticNegotiated,
5738 kSdpSemanticNegotiatedUnifiedPlan,
5739 kSdpSemanticNegotiatedMax);
5740 break;
5741 case cricket::kMsidSignalingSsrcAttribute:
5742 uma_observer_->IncrementEnumCounter(kEnumCounterSdpSemanticNegotiated,
5743 kSdpSemanticNegotiatedPlanB,
5744 kSdpSemanticNegotiatedMax);
5745 break;
5746 case cricket::kMsidSignalingMediaSection |
5747 cricket::kMsidSignalingSsrcAttribute:
5748 uma_observer_->IncrementEnumCounter(kEnumCounterSdpSemanticNegotiated,
5749 kSdpSemanticNegotiatedMixed,
5750 kSdpSemanticNegotiatedMax);
5751 break;
5752 default:
5753 RTC_NOTREACHED();
5754 }
5755}
5756
Steve Anton75737c02017-11-06 10:37:17 -08005757// We need to check the local/remote description for the Transport instead of
5758// the session, because a new Transport added during renegotiation may have
5759// them unset while the session has them set from the previous negotiation.
5760// Not doing so may trigger the auto generation of transport description and
5761// mess up DTLS identity information, ICE credential, etc.
5762bool PeerConnection::ReadyToUseRemoteCandidate(
5763 const IceCandidateInterface* candidate,
5764 const SessionDescriptionInterface* remote_desc,
5765 bool* valid) {
5766 *valid = true;
5767
5768 const SessionDescriptionInterface* current_remote_desc =
5769 remote_desc ? remote_desc : remote_description();
5770
5771 if (!current_remote_desc) {
5772 return false;
5773 }
5774
5775 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
5776 size_t remote_content_size =
5777 current_remote_desc->description()->contents().size();
5778 if (mediacontent_index >= remote_content_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005779 RTC_LOG(LS_ERROR)
5780 << "ReadyToUseRemoteCandidate: Invalid candidate media index "
5781 << mediacontent_index;
Steve Anton75737c02017-11-06 10:37:17 -08005782
5783 *valid = false;
5784 return false;
5785 }
5786
5787 cricket::ContentInfo content =
5788 current_remote_desc->description()->contents()[mediacontent_index];
5789
5790 const std::string transport_name = GetTransportName(content.name);
5791 if (transport_name.empty()) {
5792 return false;
5793 }
5794 return transport_controller_->ReadyForRemoteCandidates(transport_name);
5795}
5796
5797bool PeerConnection::SrtpRequired() const {
5798 return dtls_enabled_ ||
5799 webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED;
5800}
5801
5802void PeerConnection::OnTransportControllerGatheringState(
5803 cricket::IceGatheringState state) {
5804 RTC_DCHECK(signaling_thread()->IsCurrent());
5805 if (state == cricket::kIceGatheringGathering) {
5806 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringGathering);
5807 } else if (state == cricket::kIceGatheringComplete) {
5808 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringComplete);
5809 }
5810}
5811
5812void PeerConnection::ReportTransportStats() {
Steve Antonc7b964c2018-02-01 14:39:45 -08005813 std::map<std::string, std::set<cricket::MediaType>>
5814 media_types_by_transport_name;
5815 for (auto transceiver : transceivers_) {
5816 if (transceiver->internal()->channel()) {
5817 const std::string& transport_name =
5818 transceiver->internal()->channel()->transport_name();
5819 media_types_by_transport_name[transport_name].insert(
Steve Anton69470252018-02-09 11:43:08 -08005820 transceiver->media_type());
Steve Antonc7b964c2018-02-01 14:39:45 -08005821 }
Steve Anton75737c02017-11-06 10:37:17 -08005822 }
5823 if (rtp_data_channel()) {
Steve Antonc7b964c2018-02-01 14:39:45 -08005824 media_types_by_transport_name[rtp_data_channel()->transport_name()].insert(
5825 cricket::MEDIA_TYPE_DATA);
Steve Anton75737c02017-11-06 10:37:17 -08005826 }
5827 if (sctp_transport_name_) {
Steve Antonc7b964c2018-02-01 14:39:45 -08005828 media_types_by_transport_name[*sctp_transport_name_].insert(
5829 cricket::MEDIA_TYPE_DATA);
Steve Anton75737c02017-11-06 10:37:17 -08005830 }
Steve Antonc7b964c2018-02-01 14:39:45 -08005831 for (const auto& entry : media_types_by_transport_name) {
5832 const std::string& transport_name = entry.first;
5833 const std::set<cricket::MediaType> media_types = entry.second;
Steve Anton75737c02017-11-06 10:37:17 -08005834 cricket::TransportStats stats;
Steve Antonc7b964c2018-02-01 14:39:45 -08005835 if (transport_controller_->GetStats(transport_name, &stats)) {
Steve Anton75737c02017-11-06 10:37:17 -08005836 ReportBestConnectionState(stats);
Steve Antonc7b964c2018-02-01 14:39:45 -08005837 ReportNegotiatedCiphers(stats, media_types);
Steve Anton75737c02017-11-06 10:37:17 -08005838 }
5839 }
5840}
5841// Walk through the ConnectionInfos to gather best connection usage
5842// for IPv4 and IPv6.
5843void PeerConnection::ReportBestConnectionState(
5844 const cricket::TransportStats& stats) {
5845 RTC_DCHECK(metrics_observer());
Steve Antonc7b964c2018-02-01 14:39:45 -08005846 for (const cricket::TransportChannelStats& channel_stats :
5847 stats.channel_stats) {
5848 for (const cricket::ConnectionInfo& connection_info :
5849 channel_stats.connection_infos) {
5850 if (!connection_info.best_connection) {
Steve Anton75737c02017-11-06 10:37:17 -08005851 continue;
5852 }
5853
5854 PeerConnectionEnumCounterType type = kPeerConnectionEnumCounterMax;
Steve Antonc7b964c2018-02-01 14:39:45 -08005855 const cricket::Candidate& local = connection_info.local_candidate;
5856 const cricket::Candidate& remote = connection_info.remote_candidate;
Steve Anton75737c02017-11-06 10:37:17 -08005857
5858 // Increment the counter for IceCandidatePairType.
5859 if (local.protocol() == cricket::TCP_PROTOCOL_NAME ||
5860 (local.type() == RELAY_PORT_TYPE &&
5861 local.relay_protocol() == cricket::TCP_PROTOCOL_NAME)) {
5862 type = kEnumCounterIceCandidatePairTypeTcp;
5863 } else if (local.protocol() == cricket::UDP_PROTOCOL_NAME) {
5864 type = kEnumCounterIceCandidatePairTypeUdp;
5865 } else {
5866 RTC_CHECK(0);
5867 }
5868 metrics_observer()->IncrementEnumCounter(
5869 type, GetIceCandidatePairCounter(local, remote),
5870 kIceCandidatePairMax);
5871
5872 // Increment the counter for IP type.
5873 if (local.address().family() == AF_INET) {
5874 metrics_observer()->IncrementEnumCounter(
5875 kEnumCounterAddressFamily, kBestConnections_IPv4,
5876 kPeerConnectionAddressFamilyCounter_Max);
5877
5878 } else if (local.address().family() == AF_INET6) {
5879 metrics_observer()->IncrementEnumCounter(
5880 kEnumCounterAddressFamily, kBestConnections_IPv6,
5881 kPeerConnectionAddressFamilyCounter_Max);
5882 } else {
5883 RTC_CHECK(0);
5884 }
5885
5886 return;
5887 }
5888 }
5889}
5890
5891void PeerConnection::ReportNegotiatedCiphers(
Steve Antonc7b964c2018-02-01 14:39:45 -08005892 const cricket::TransportStats& stats,
5893 const std::set<cricket::MediaType>& media_types) {
Steve Anton75737c02017-11-06 10:37:17 -08005894 RTC_DCHECK(metrics_observer());
5895 if (!dtls_enabled_ || stats.channel_stats.empty()) {
5896 return;
5897 }
5898
5899 int srtp_crypto_suite = stats.channel_stats[0].srtp_crypto_suite;
5900 int ssl_cipher_suite = stats.channel_stats[0].ssl_cipher_suite;
5901 if (srtp_crypto_suite == rtc::SRTP_INVALID_CRYPTO_SUITE &&
5902 ssl_cipher_suite == rtc::TLS_NULL_WITH_NULL_NULL) {
5903 return;
5904 }
5905
Steve Antonc7b964c2018-02-01 14:39:45 -08005906 for (cricket::MediaType media_type : media_types) {
5907 PeerConnectionEnumCounterType srtp_counter_type;
5908 PeerConnectionEnumCounterType ssl_counter_type;
5909 switch (media_type) {
5910 case cricket::MEDIA_TYPE_AUDIO:
5911 srtp_counter_type = kEnumCounterAudioSrtpCipher;
5912 ssl_counter_type = kEnumCounterAudioSslCipher;
5913 break;
5914 case cricket::MEDIA_TYPE_VIDEO:
5915 srtp_counter_type = kEnumCounterVideoSrtpCipher;
5916 ssl_counter_type = kEnumCounterVideoSslCipher;
5917 break;
5918 case cricket::MEDIA_TYPE_DATA:
5919 srtp_counter_type = kEnumCounterDataSrtpCipher;
5920 ssl_counter_type = kEnumCounterDataSslCipher;
5921 break;
5922 default:
5923 RTC_NOTREACHED();
5924 continue;
5925 }
5926 if (srtp_crypto_suite != rtc::SRTP_INVALID_CRYPTO_SUITE) {
5927 metrics_observer()->IncrementSparseEnumCounter(srtp_counter_type,
5928 srtp_crypto_suite);
5929 }
5930 if (ssl_cipher_suite != rtc::TLS_NULL_WITH_NULL_NULL) {
5931 metrics_observer()->IncrementSparseEnumCounter(ssl_counter_type,
5932 ssl_cipher_suite);
5933 }
Steve Anton75737c02017-11-06 10:37:17 -08005934 }
5935}
5936
5937void PeerConnection::OnSentPacket_w(const rtc::SentPacket& sent_packet) {
5938 RTC_DCHECK(worker_thread()->IsCurrent());
5939 RTC_DCHECK(call_);
5940 call_->OnSentPacket(sent_packet);
5941}
5942
5943const std::string PeerConnection::GetTransportName(
5944 const std::string& content_name) {
5945 cricket::BaseChannel* channel = GetChannel(content_name);
Steve Anton6fec8802017-12-04 10:37:29 -08005946 if (channel) {
5947 return channel->transport_name();
Steve Anton75737c02017-11-06 10:37:17 -08005948 }
Steve Anton6fec8802017-12-04 10:37:29 -08005949 if (sctp_transport_) {
5950 RTC_DCHECK(sctp_content_name_);
5951 RTC_DCHECK(sctp_transport_name_);
5952 if (content_name == *sctp_content_name_) {
5953 return *sctp_transport_name_;
5954 }
5955 }
5956 // Return an empty string if failed to retrieve the transport name.
5957 return "";
Steve Anton75737c02017-11-06 10:37:17 -08005958}
5959
5960void PeerConnection::DestroyRtcpTransport_n(const std::string& transport_name) {
5961 RTC_DCHECK(network_thread()->IsCurrent());
5962 transport_controller_->DestroyDtlsTransport_n(
5963 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
5964}
5965
Steve Anton6fec8802017-12-04 10:37:29 -08005966void PeerConnection::DestroyTransceiverChannel(
5967 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
5968 transceiver) {
5969 RTC_DCHECK(transceiver);
Steve Anton75737c02017-11-06 10:37:17 -08005970
Steve Anton6fec8802017-12-04 10:37:29 -08005971 cricket::BaseChannel* channel = transceiver->internal()->channel();
5972 if (channel) {
5973 transceiver->internal()->SetChannel(nullptr);
5974 DestroyBaseChannel(channel);
Steve Anton75737c02017-11-06 10:37:17 -08005975 }
5976}
5977
5978void PeerConnection::DestroyDataChannel() {
Steve Anton6fec8802017-12-04 10:37:29 -08005979 if (rtp_data_channel_) {
5980 OnDataChannelDestroyed();
5981 DestroyBaseChannel(rtp_data_channel_);
5982 rtp_data_channel_ = nullptr;
5983 }
5984
5985 // Note: Cannot use rtc::Bind to create a functor to invoke because it will
5986 // grab a reference to this PeerConnection. If this is called from the
5987 // PeerConnection destructor, the RefCountedObject vtable will have already
5988 // been destroyed (since it is a subclass of PeerConnection) and using
5989 // rtc::Bind will cause "Pure virtual function called" error to appear.
5990
5991 if (sctp_transport_) {
5992 OnDataChannelDestroyed();
5993 network_thread()->Invoke<void>(RTC_FROM_HERE,
5994 [this] { DestroySctpTransport_n(); });
5995 }
5996}
5997
5998void PeerConnection::DestroyBaseChannel(cricket::BaseChannel* channel) {
5999 RTC_DCHECK(channel);
6000 RTC_DCHECK(channel->rtp_dtls_transport());
6001
6002 // Need to cache these before destroying the base channel so that we do not
6003 // access uninitialized memory.
6004 const std::string transport_name =
6005 channel->rtp_dtls_transport()->transport_name();
6006 const bool need_to_delete_rtcp = (channel->rtcp_dtls_transport() != nullptr);
6007
6008 switch (channel->media_type()) {
6009 case cricket::MEDIA_TYPE_AUDIO:
6010 channel_manager()->DestroyVoiceChannel(
6011 static_cast<cricket::VoiceChannel*>(channel));
6012 break;
6013 case cricket::MEDIA_TYPE_VIDEO:
6014 channel_manager()->DestroyVideoChannel(
6015 static_cast<cricket::VideoChannel*>(channel));
6016 break;
6017 case cricket::MEDIA_TYPE_DATA:
6018 channel_manager()->DestroyRtpDataChannel(
6019 static_cast<cricket::RtpDataChannel*>(channel));
6020 break;
6021 default:
6022 RTC_NOTREACHED() << "Unknown media type: " << channel->media_type();
6023 break;
6024 }
6025
6026 // |channel| can no longer be used.
6027
Steve Anton75737c02017-11-06 10:37:17 -08006028 transport_controller_->DestroyDtlsTransport(
6029 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
6030 if (need_to_delete_rtcp) {
6031 transport_controller_->DestroyDtlsTransport(
6032 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
6033 }
6034}
6035
Harald Alvestrand89061872018-01-02 14:08:34 +01006036void PeerConnection::ClearStatsCache() {
6037 if (stats_collector_) {
6038 stats_collector_->ClearCachedStatsReport();
6039 }
6040}
6041
henrike@webrtc.org28e20752013-07-10 00:45:36 +00006042} // namespace webrtc