blob: b032043206d0139634fc813bac250f811a891975 [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) {
1160 transceiver->SetDirection(RtpTransceiverDirection::kSendRecv);
1161 } else if (transceiver->direction() == RtpTransceiverDirection::kInactive) {
1162 transceiver->SetDirection(RtpTransceiverDirection::kSendOnly);
1163 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001164 transceiver->sender()->SetTrack(track);
1165 transceiver->internal()->sender_internal()->set_stream_ids(stream_labels);
Steve Antonf9381f02017-12-14 10:23:57 -08001166 } else {
1167 cricket::MediaType media_type =
1168 (track->kind() == MediaStreamTrackInterface::kAudioKind
1169 ? cricket::MEDIA_TYPE_AUDIO
1170 : cricket::MEDIA_TYPE_VIDEO);
Steve Anton02ee47c2018-01-10 16:26:06 -08001171 auto sender = CreateSender(media_type, track, stream_labels);
1172 auto receiver = CreateReceiver(media_type, rtc::CreateRandomUuid());
1173 transceiver = CreateAndAddTransceiver(sender, receiver);
Steve Antonf9381f02017-12-14 10:23:57 -08001174 transceiver->internal()->set_created_by_addtrack(true);
1175 transceiver->SetDirection(RtpTransceiverDirection::kSendRecv);
1176 }
Steve Antonf9381f02017-12-14 10:23:57 -08001177 return transceiver->sender();
1178}
1179
1180rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1181PeerConnection::FindFirstTransceiverForAddedTrack(
1182 rtc::scoped_refptr<MediaStreamTrackInterface> track) {
1183 RTC_DCHECK(track);
1184 for (auto transceiver : transceivers_) {
1185 if (!transceiver->sender()->track() &&
Steve Anton69470252018-02-09 11:43:08 -08001186 cricket::MediaTypeToString(transceiver->media_type()) ==
Steve Antonf9381f02017-12-14 10:23:57 -08001187 track->kind() &&
1188 !transceiver->internal()->has_ever_been_used_to_send()) {
1189 return transceiver;
1190 }
1191 }
1192 return nullptr;
deadbeefe1f9d832016-01-14 15:35:42 -08001193}
1194
1195bool PeerConnection::RemoveTrack(RtpSenderInterface* sender) {
1196 TRACE_EVENT0("webrtc", "PeerConnection::RemoveTrack");
Steve Antonf9381f02017-12-14 10:23:57 -08001197 return RemoveTrackInternal(sender).ok();
1198}
1199
1200RTCError PeerConnection::RemoveTrackInternal(
1201 rtc::scoped_refptr<RtpSenderInterface> sender) {
1202 if (!sender) {
1203 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "Sender is null.");
1204 }
deadbeefe1f9d832016-01-14 15:35:42 -08001205 if (IsClosed()) {
Steve Antonf9381f02017-12-14 10:23:57 -08001206 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
1207 "PeerConnection is closed.");
deadbeefe1f9d832016-01-14 15:35:42 -08001208 }
Steve Antonf9381f02017-12-14 10:23:57 -08001209 if (IsUnifiedPlan()) {
1210 auto transceiver = FindTransceiverBySender(sender);
1211 if (!transceiver || !sender->track()) {
1212 return RTCError::OK();
1213 }
1214 sender->SetTrack(nullptr);
1215 if (transceiver->direction() == RtpTransceiverDirection::kSendRecv) {
1216 transceiver->internal()->SetDirection(RtpTransceiverDirection::kRecvOnly);
1217 } else if (transceiver->direction() == RtpTransceiverDirection::kSendOnly) {
1218 transceiver->internal()->SetDirection(RtpTransceiverDirection::kInactive);
1219 }
Steve Anton4171afb2017-11-20 10:20:22 -08001220 } else {
Steve Antonf9381f02017-12-14 10:23:57 -08001221 bool removed;
1222 if (sender->media_type() == cricket::MEDIA_TYPE_AUDIO) {
1223 removed = GetAudioTransceiver()->internal()->RemoveSender(sender);
1224 } else {
1225 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, sender->media_type());
1226 removed = GetVideoTransceiver()->internal()->RemoveSender(sender);
1227 }
1228 if (!removed) {
1229 LOG_AND_RETURN_ERROR(
1230 RTCErrorType::INVALID_PARAMETER,
1231 "Couldn't find sender " + sender->id() + " to remove.");
1232 }
Steve Anton4171afb2017-11-20 10:20:22 -08001233 }
deadbeefe1f9d832016-01-14 15:35:42 -08001234 observer_->OnRenegotiationNeeded();
Steve Antonf9381f02017-12-14 10:23:57 -08001235 return RTCError::OK();
1236}
1237
1238rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1239PeerConnection::FindTransceiverBySender(
1240 rtc::scoped_refptr<RtpSenderInterface> sender) {
1241 for (auto transceiver : transceivers_) {
1242 if (transceiver->sender() == sender) {
1243 return transceiver;
1244 }
1245 }
1246 return nullptr;
deadbeefe1f9d832016-01-14 15:35:42 -08001247}
1248
Steve Anton9158ef62017-11-27 13:01:52 -08001249RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1250PeerConnection::AddTransceiver(
1251 rtc::scoped_refptr<MediaStreamTrackInterface> track) {
1252 return AddTransceiver(track, RtpTransceiverInit());
1253}
1254
1255RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1256PeerConnection::AddTransceiver(
1257 rtc::scoped_refptr<MediaStreamTrackInterface> track,
1258 const RtpTransceiverInit& init) {
1259 if (!IsUnifiedPlan()) {
1260 LOG_AND_RETURN_ERROR(
1261 RTCErrorType::INTERNAL_ERROR,
1262 "AddTransceiver only supported when Unified Plan is enabled.");
1263 }
1264 if (!track) {
1265 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "track is null");
1266 }
1267 cricket::MediaType media_type;
1268 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
1269 media_type = cricket::MEDIA_TYPE_AUDIO;
1270 } else if (track->kind() == MediaStreamTrackInterface::kVideoKind) {
1271 media_type = cricket::MEDIA_TYPE_VIDEO;
1272 } else {
1273 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1274 "Track kind is not audio or video");
1275 }
1276 return AddTransceiver(media_type, track, init);
1277}
1278
1279RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1280PeerConnection::AddTransceiver(cricket::MediaType media_type) {
1281 return AddTransceiver(media_type, RtpTransceiverInit());
1282}
1283
1284RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1285PeerConnection::AddTransceiver(cricket::MediaType media_type,
1286 const RtpTransceiverInit& init) {
1287 if (!IsUnifiedPlan()) {
1288 LOG_AND_RETURN_ERROR(
1289 RTCErrorType::INTERNAL_ERROR,
1290 "AddTransceiver only supported when Unified Plan is enabled.");
1291 }
1292 if (!(media_type == cricket::MEDIA_TYPE_AUDIO ||
1293 media_type == cricket::MEDIA_TYPE_VIDEO)) {
1294 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1295 "media type is not audio or video");
1296 }
1297 return AddTransceiver(media_type, nullptr, init);
1298}
1299
1300RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1301PeerConnection::AddTransceiver(
1302 cricket::MediaType media_type,
1303 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Steve Anton22da89f2018-01-25 13:58:07 -08001304 const RtpTransceiverInit& init,
1305 bool fire_callback) {
Steve Anton9158ef62017-11-27 13:01:52 -08001306 RTC_DCHECK((media_type == cricket::MEDIA_TYPE_AUDIO ||
1307 media_type == cricket::MEDIA_TYPE_VIDEO));
1308 if (track) {
1309 RTC_DCHECK_EQ(media_type,
1310 (track->kind() == MediaStreamTrackInterface::kAudioKind
1311 ? cricket::MEDIA_TYPE_AUDIO
1312 : cricket::MEDIA_TYPE_VIDEO));
1313 }
1314
1315 // TODO(bugs.webrtc.org/7600): Verify init.
1316
Steve Anton02ee47c2018-01-10 16:26:06 -08001317 if (init.stream_labels.size() > 1u) {
1318 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
1319 "More than one stream is not yet supported.");
Steve Antonf9381f02017-12-14 10:23:57 -08001320 }
1321
Steve Anton02ee47c2018-01-10 16:26:06 -08001322 std::vector<std::string> stream_labels = {!init.stream_labels.empty()
1323 ? init.stream_labels[0]
1324 : rtc::CreateRandomUuid()};
1325
1326 auto sender = CreateSender(media_type, track, stream_labels);
1327 auto receiver = CreateReceiver(media_type, rtc::CreateRandomUuid());
1328 auto transceiver = CreateAndAddTransceiver(sender, receiver);
1329 transceiver->internal()->set_direction(init.direction);
1330
Steve Anton22da89f2018-01-25 13:58:07 -08001331 if (fire_callback) {
1332 observer_->OnRenegotiationNeeded();
1333 }
Steve Antonf9381f02017-12-14 10:23:57 -08001334
1335 return rtc::scoped_refptr<RtpTransceiverInterface>(transceiver);
1336}
1337
Steve Anton02ee47c2018-01-10 16:26:06 -08001338rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
1339PeerConnection::CreateSender(
1340 cricket::MediaType media_type,
1341 rtc::scoped_refptr<MediaStreamTrackInterface> track,
1342 const std::vector<std::string>& stream_labels) {
Steve Anton9158ef62017-11-27 13:01:52 -08001343 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> sender;
Steve Anton02ee47c2018-01-10 16:26:06 -08001344 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
1345 RTC_DCHECK(!track ||
1346 (track->kind() == MediaStreamTrackInterface::kAudioKind));
1347 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
1348 signaling_thread(),
Steve Anton47136dd2018-01-12 10:49:35 -08001349 new AudioRtpSender(worker_thread(),
1350 static_cast<AudioTrackInterface*>(track.get()),
Steve Anton02ee47c2018-01-10 16:26:06 -08001351 stream_labels, stats_.get()));
1352 } else {
1353 RTC_DCHECK_EQ(media_type, cricket::MEDIA_TYPE_VIDEO);
1354 RTC_DCHECK(!track ||
1355 (track->kind() == MediaStreamTrackInterface::kVideoKind));
1356 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
1357 signaling_thread(),
Steve Anton47136dd2018-01-12 10:49:35 -08001358 new VideoRtpSender(worker_thread(),
1359 static_cast<VideoTrackInterface*>(track.get()),
Steve Anton02ee47c2018-01-10 16:26:06 -08001360 stream_labels));
1361 }
1362 sender->internal()->set_stream_ids(stream_labels);
1363 return sender;
1364}
1365
1366rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1367PeerConnection::CreateReceiver(cricket::MediaType media_type,
1368 const std::string& receiver_id) {
Steve Anton9158ef62017-11-27 13:01:52 -08001369 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1370 receiver;
Steve Anton9158ef62017-11-27 13:01:52 -08001371 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton9158ef62017-11-27 13:01:52 -08001372 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
Steve Anton60776752018-01-10 11:51:34 -08001373 signaling_thread(),
Steve Antond3679212018-01-17 17:41:02 -08001374 new AudioRtpReceiver(worker_thread(), receiver_id, {}));
Steve Anton9158ef62017-11-27 13:01:52 -08001375 } else {
Steve Anton02ee47c2018-01-10 16:26:06 -08001376 RTC_DCHECK_EQ(media_type, cricket::MEDIA_TYPE_VIDEO);
Steve Anton9158ef62017-11-27 13:01:52 -08001377 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
1378 signaling_thread(),
Steve Antond3679212018-01-17 17:41:02 -08001379 new VideoRtpReceiver(worker_thread(), receiver_id, {}));
Steve Anton9158ef62017-11-27 13:01:52 -08001380 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001381 return receiver;
1382}
1383
1384rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1385PeerConnection::CreateAndAddTransceiver(
1386 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> sender,
1387 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1388 receiver) {
1389 auto transceiver = RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1390 signaling_thread(), new RtpTransceiver(sender, receiver));
Steve Anton9158ef62017-11-27 13:01:52 -08001391 transceivers_.push_back(transceiver);
Steve Antonf9381f02017-12-14 10:23:57 -08001392 return transceiver;
Steve Anton9158ef62017-11-27 13:01:52 -08001393}
1394
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001395rtc::scoped_refptr<DtmfSenderInterface> PeerConnection::CreateDtmfSender(
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001396 AudioTrackInterface* track) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001397 TRACE_EVENT0("webrtc", "PeerConnection::CreateDtmfSender");
zhihuang29ff8442016-07-27 11:07:25 -07001398 if (IsClosed()) {
1399 return nullptr;
1400 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001401 if (!track) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001402 RTC_LOG(LS_ERROR) << "CreateDtmfSender - track is NULL.";
deadbeef20cb0c12017-02-01 20:27:00 -08001403 return nullptr;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001404 }
Steve Anton4171afb2017-11-20 10:20:22 -08001405 auto track_sender = FindSenderForTrack(track);
1406 if (!track_sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001407 RTC_LOG(LS_ERROR) << "CreateDtmfSender called with a non-added track.";
deadbeef20cb0c12017-02-01 20:27:00 -08001408 return nullptr;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001409 }
1410
Steve Anton4171afb2017-11-20 10:20:22 -08001411 return track_sender->GetDtmfSender();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001412}
1413
deadbeeffac06552015-11-25 11:26:01 -08001414rtc::scoped_refptr<RtpSenderInterface> PeerConnection::CreateSender(
deadbeefbd7d8f72015-12-18 16:58:44 -08001415 const std::string& kind,
1416 const std::string& stream_id) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001417 TRACE_EVENT0("webrtc", "PeerConnection::CreateSender");
zhihuang29ff8442016-07-27 11:07:25 -07001418 if (IsClosed()) {
1419 return nullptr;
1420 }
Steve Anton4171afb2017-11-20 10:20:22 -08001421
Steve Anton02ee47c2018-01-10 16:26:06 -08001422 std::vector<std::string> stream_labels;
1423 if (!stream_id.empty()) {
1424 stream_labels.push_back(stream_id);
1425 }
1426
Steve Anton4171afb2017-11-20 10:20:22 -08001427 // TODO(steveanton): Move construction of the RtpSenders to RtpTransceiver.
deadbeefa601f5c2016-06-06 14:27:39 -07001428 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender;
deadbeeffac06552015-11-25 11:26:01 -08001429 if (kind == MediaStreamTrackInterface::kAudioKind) {
Steve Anton47136dd2018-01-12 10:49:35 -08001430 auto* audio_sender = new AudioRtpSender(worker_thread(), nullptr,
1431 stream_labels, stats_.get());
Steve Anton57858b32018-02-15 15:19:50 -08001432 audio_sender->SetVoiceMediaChannel(voice_media_channel());
deadbeefa601f5c2016-06-06 14:27:39 -07001433 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton02ee47c2018-01-10 16:26:06 -08001434 signaling_thread(), audio_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001435 GetAudioTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 11:26:01 -08001436 } else if (kind == MediaStreamTrackInterface::kVideoKind) {
Steve Anton47136dd2018-01-12 10:49:35 -08001437 auto* video_sender =
1438 new VideoRtpSender(worker_thread(), nullptr, stream_labels);
Steve Anton57858b32018-02-15 15:19:50 -08001439 video_sender->SetVideoMediaChannel(video_media_channel());
deadbeefa601f5c2016-06-06 14:27:39 -07001440 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton02ee47c2018-01-10 16:26:06 -08001441 signaling_thread(), video_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001442 GetVideoTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 11:26:01 -08001443 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001444 RTC_LOG(LS_ERROR) << "CreateSender called with invalid kind: " << kind;
Steve Anton4171afb2017-11-20 10:20:22 -08001445 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08001446 }
Steve Anton4171afb2017-11-20 10:20:22 -08001447
deadbeefe1f9d832016-01-14 15:35:42 -08001448 return new_sender;
deadbeeffac06552015-11-25 11:26:01 -08001449}
1450
deadbeef70ab1a12015-09-28 16:53:55 -07001451std::vector<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::GetSenders()
1452 const {
deadbeefa601f5c2016-06-06 14:27:39 -07001453 std::vector<rtc::scoped_refptr<RtpSenderInterface>> ret;
Steve Anton4171afb2017-11-20 10:20:22 -08001454 for (auto sender : GetSendersInternal()) {
1455 ret.push_back(sender);
deadbeefa601f5c2016-06-06 14:27:39 -07001456 }
1457 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -07001458}
1459
Steve Anton4171afb2017-11-20 10:20:22 -08001460std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1461PeerConnection::GetSendersInternal() const {
1462 std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1463 all_senders;
1464 for (auto transceiver : transceivers_) {
1465 auto senders = transceiver->internal()->senders();
1466 all_senders.insert(all_senders.end(), senders.begin(), senders.end());
1467 }
1468 return all_senders;
1469}
1470
deadbeef70ab1a12015-09-28 16:53:55 -07001471std::vector<rtc::scoped_refptr<RtpReceiverInterface>>
1472PeerConnection::GetReceivers() const {
deadbeefa601f5c2016-06-06 14:27:39 -07001473 std::vector<rtc::scoped_refptr<RtpReceiverInterface>> ret;
Steve Anton4171afb2017-11-20 10:20:22 -08001474 for (const auto& receiver : GetReceiversInternal()) {
1475 ret.push_back(receiver);
deadbeefa601f5c2016-06-06 14:27:39 -07001476 }
1477 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -07001478}
1479
Steve Anton4171afb2017-11-20 10:20:22 -08001480std::vector<
1481 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1482PeerConnection::GetReceiversInternal() const {
1483 std::vector<
1484 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1485 all_receivers;
1486 for (auto transceiver : transceivers_) {
1487 auto receivers = transceiver->internal()->receivers();
1488 all_receivers.insert(all_receivers.end(), receivers.begin(),
1489 receivers.end());
1490 }
1491 return all_receivers;
1492}
1493
Steve Anton9158ef62017-11-27 13:01:52 -08001494std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
1495PeerConnection::GetTransceivers() const {
1496 RTC_DCHECK(IsUnifiedPlan());
1497 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> all_transceivers;
1498 for (auto transceiver : transceivers_) {
1499 all_transceivers.push_back(transceiver);
1500 }
1501 return all_transceivers;
1502}
1503
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001504bool PeerConnection::GetStats(StatsObserver* observer,
wu@webrtc.orgb9a088b2014-02-13 23:18:49 +00001505 MediaStreamTrackInterface* track,
1506 StatsOutputLevel level) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001507 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
deadbeef0a6c4ca2015-10-06 11:38:28 -07001508 RTC_DCHECK(signaling_thread()->IsCurrent());
nisse7ce109a2017-01-31 00:57:56 -08001509 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001510 RTC_LOG(LS_ERROR) << "GetStats - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001511 return false;
1512 }
1513
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001514 stats_->UpdateStats(level);
zhihuange9e94c32016-11-04 11:38:15 -07001515 // The StatsCollector is used to tell if a track is valid because it may
1516 // remember tracks that the PeerConnection previously removed.
1517 if (track && !stats_->IsValidTrack(track->id())) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001518 RTC_LOG(LS_WARNING) << "GetStats is called with an invalid track: "
1519 << track->id();
zhihuange9e94c32016-11-04 11:38:15 -07001520 return false;
1521 }
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001522 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_GETSTATS,
tommi@webrtc.org5b06b062014-08-15 08:38:30 +00001523 new GetStatsMsg(observer, track));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001524 return true;
1525}
1526
hbos74e1a4f2016-09-15 23:33:01 -07001527void PeerConnection::GetStats(RTCStatsCollectorCallback* callback) {
1528 RTC_DCHECK(stats_collector_);
1529 stats_collector_->GetStatsReport(callback);
1530}
1531
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001532PeerConnectionInterface::SignalingState PeerConnection::signaling_state() {
1533 return signaling_state_;
1534}
1535
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001536PeerConnectionInterface::IceConnectionState
1537PeerConnection::ice_connection_state() {
1538 return ice_connection_state_;
1539}
1540
1541PeerConnectionInterface::IceGatheringState
1542PeerConnection::ice_gathering_state() {
1543 return ice_gathering_state_;
1544}
1545
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001546rtc::scoped_refptr<DataChannelInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001547PeerConnection::CreateDataChannel(
1548 const std::string& label,
1549 const DataChannelInit* config) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001550 TRACE_EVENT0("webrtc", "PeerConnection::CreateDataChannel");
zhihuang9763d562016-08-05 11:14:50 -07001551
deadbeefab9b2d12015-10-14 11:33:11 -07001552 bool first_datachannel = !HasDataChannels();
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001553
kwibergd1fe2812016-04-27 06:47:29 -07001554 std::unique_ptr<InternalDataChannelInit> internal_config;
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00001555 if (config) {
1556 internal_config.reset(new InternalDataChannelInit(*config));
1557 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001558 rtc::scoped_refptr<DataChannelInterface> channel(
deadbeefab9b2d12015-10-14 11:33:11 -07001559 InternalCreateDataChannel(label, internal_config.get()));
1560 if (!channel.get()) {
1561 return nullptr;
1562 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001563
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001564 // Trigger the onRenegotiationNeeded event for every new RTP DataChannel, or
1565 // the first SCTP DataChannel.
Steve Anton75737c02017-11-06 10:37:17 -08001566 if (data_channel_type() == cricket::DCT_RTP || first_datachannel) {
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001567 observer_->OnRenegotiationNeeded();
1568 }
wu@webrtc.org91053e72013-08-10 07:18:04 +00001569
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001570 return DataChannelProxy::Create(signaling_thread(), channel.get());
1571}
1572
1573void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
1574 const MediaConstraintsInterface* constraints) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001575 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
Steve Anton8d3444d2017-10-20 15:30:51 -07001576
zhihuang1c378ed2017-08-17 14:10:50 -07001577 PeerConnectionInterface::RTCOfferAnswerOptions offer_answer_options;
1578 // Always create an offer even if |ConvertConstraintsToOfferAnswerOptions|
1579 // returns false for now. Because |ConvertConstraintsToOfferAnswerOptions|
1580 // compares the mandatory fields parsed with the mandatory fields added in the
1581 // |constraints| and some downstream applications might create offers with
1582 // mandatory fields which would not be parsed in the helper method. For
1583 // example, in Chromium/remoting, |kEnableDtlsSrtp| is added to the
1584 // |constraints| as a mandatory field but it is not parsed.
1585 ConvertConstraintsToOfferAnswerOptions(constraints, &offer_answer_options);
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001586
zhihuang1c378ed2017-08-17 14:10:50 -07001587 CreateOffer(observer, offer_answer_options);
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001588}
1589
1590void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
1591 const RTCOfferAnswerOptions& options) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001592 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
Steve Anton8d3444d2017-10-20 15:30:51 -07001593
nisse7ce109a2017-01-31 00:57:56 -08001594 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001595 RTC_LOG(LS_ERROR) << "CreateOffer - observer is NULL.";
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001596 return;
1597 }
deadbeefab9b2d12015-10-14 11:33:11 -07001598
Steve Anton8d3444d2017-10-20 15:30:51 -07001599 if (IsClosed()) {
1600 std::string error = "CreateOffer called when PeerConnection is closed.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001601 RTC_LOG(LS_ERROR) << error;
Steve Anton8d3444d2017-10-20 15:30:51 -07001602 PostCreateSessionDescriptionFailure(observer, error);
1603 return;
1604 }
1605
zhihuang1c378ed2017-08-17 14:10:50 -07001606 if (!ValidateOfferAnswerOptions(options)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001607 std::string error = "CreateOffer called with invalid options.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001608 RTC_LOG(LS_ERROR) << error;
deadbeefab9b2d12015-10-14 11:33:11 -07001609 PostCreateSessionDescriptionFailure(observer, error);
1610 return;
1611 }
1612
Steve Anton22da89f2018-01-25 13:58:07 -08001613 // Legacy handling for offer_to_receive_audio and offer_to_receive_video.
1614 // Specified in WebRTC section 4.4.3.2 "Legacy configuration extensions".
1615 if (IsUnifiedPlan()) {
1616 RTCError error = HandleLegacyOfferOptions(options);
1617 if (!error.ok()) {
1618 PostCreateSessionDescriptionFailure(observer, error.message());
1619 return;
1620 }
1621 }
1622
zhihuang1c378ed2017-08-17 14:10:50 -07001623 cricket::MediaSessionOptions session_options;
1624 GetOptionsForOffer(options, &session_options);
Steve Antond25da372017-11-06 14:50:29 -08001625 webrtc_session_desc_factory_->CreateOffer(observer, options, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001626}
1627
Steve Anton22da89f2018-01-25 13:58:07 -08001628RTCError PeerConnection::HandleLegacyOfferOptions(
1629 const RTCOfferAnswerOptions& options) {
1630 RTC_DCHECK(IsUnifiedPlan());
1631
1632 if (options.offer_to_receive_audio == 0) {
1633 RemoveRecvDirectionFromReceivingTransceiversOfType(
1634 cricket::MEDIA_TYPE_AUDIO);
1635 } else if (options.offer_to_receive_audio == 1) {
1636 AddUpToOneReceivingTransceiverOfType(cricket::MEDIA_TYPE_AUDIO);
1637 } else if (options.offer_to_receive_audio > 1) {
1638 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
1639 "offer_to_receive_audio > 1 is not supported.");
1640 }
1641
1642 if (options.offer_to_receive_video == 0) {
1643 RemoveRecvDirectionFromReceivingTransceiversOfType(
1644 cricket::MEDIA_TYPE_VIDEO);
1645 } else if (options.offer_to_receive_video == 1) {
1646 AddUpToOneReceivingTransceiverOfType(cricket::MEDIA_TYPE_VIDEO);
1647 } else if (options.offer_to_receive_video > 1) {
1648 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
1649 "offer_to_receive_video > 1 is not supported.");
1650 }
1651
1652 return RTCError::OK();
1653}
1654
1655void PeerConnection::RemoveRecvDirectionFromReceivingTransceiversOfType(
1656 cricket::MediaType media_type) {
1657 for (auto transceiver : GetReceivingTransceiversOfType(media_type)) {
1658 transceiver->internal()->set_direction(
1659 RtpTransceiverDirectionWithRecvSet(transceiver->direction(), false));
1660 }
1661}
1662
1663void PeerConnection::AddUpToOneReceivingTransceiverOfType(
1664 cricket::MediaType media_type) {
1665 if (GetReceivingTransceiversOfType(media_type).empty()) {
1666 RtpTransceiverInit init;
1667 init.direction = RtpTransceiverDirection::kRecvOnly;
1668 AddTransceiver(media_type, nullptr, init, /*fire_callback=*/false);
1669 }
1670}
1671
1672std::vector<rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
1673PeerConnection::GetReceivingTransceiversOfType(cricket::MediaType media_type) {
1674 std::vector<
1675 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
1676 receiving_transceivers;
1677 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08001678 if (!transceiver->stopped() && transceiver->media_type() == media_type &&
Steve Anton22da89f2018-01-25 13:58:07 -08001679 RtpTransceiverDirectionHasRecv(transceiver->direction())) {
1680 receiving_transceivers.push_back(transceiver);
1681 }
1682 }
1683 return receiving_transceivers;
1684}
1685
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001686void PeerConnection::CreateAnswer(
1687 CreateSessionDescriptionObserver* observer,
1688 const MediaConstraintsInterface* constraints) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001689 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
Steve Anton8d3444d2017-10-20 15:30:51 -07001690
nisse7ce109a2017-01-31 00:57:56 -08001691 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001692 RTC_LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001693 return;
1694 }
deadbeefab9b2d12015-10-14 11:33:11 -07001695
zhihuang1c378ed2017-08-17 14:10:50 -07001696 PeerConnectionInterface::RTCOfferAnswerOptions offer_answer_options;
1697 if (!ConvertConstraintsToOfferAnswerOptions(constraints,
1698 &offer_answer_options)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001699 std::string error = "CreateAnswer called with invalid constraints.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001700 RTC_LOG(LS_ERROR) << error;
deadbeefab9b2d12015-10-14 11:33:11 -07001701 PostCreateSessionDescriptionFailure(observer, error);
1702 return;
1703 }
1704
Steve Anton8d3444d2017-10-20 15:30:51 -07001705 CreateAnswer(observer, offer_answer_options);
htaa2a49d92016-03-04 02:51:39 -08001706}
1707
1708void PeerConnection::CreateAnswer(CreateSessionDescriptionObserver* observer,
1709 const RTCOfferAnswerOptions& options) {
1710 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
nisse7ce109a2017-01-31 00:57:56 -08001711 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001712 RTC_LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
htaa2a49d92016-03-04 02:51:39 -08001713 return;
1714 }
1715
Steve Antondffead82018-02-06 10:31:29 -08001716 if (!(signaling_state_ == kHaveRemoteOffer ||
1717 signaling_state_ == kHaveLocalPrAnswer)) {
1718 std::string error =
1719 "PeerConnection cannot create an answer in a state other than "
1720 "have-remote-offer or have-local-pranswer.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001721 RTC_LOG(LS_ERROR) << error;
Steve Anton8d3444d2017-10-20 15:30:51 -07001722 PostCreateSessionDescriptionFailure(observer, error);
1723 return;
1724 }
1725
Steve Antondffead82018-02-06 10:31:29 -08001726 // The remote description should be set if we're in the right state.
1727 RTC_DCHECK(remote_description());
Steve Anton8d3444d2017-10-20 15:30:51 -07001728
Steve Anton22da89f2018-01-25 13:58:07 -08001729 if (IsUnifiedPlan()) {
1730 if (options.offer_to_receive_audio != RTCOfferAnswerOptions::kUndefined) {
1731 RTC_LOG(LS_WARNING) << "CreateAnswer: offer_to_receive_audio is not "
1732 "supported with Unified Plan semantics. Use the "
1733 "RtpTransceiver API instead.";
1734 }
1735 if (options.offer_to_receive_video != RTCOfferAnswerOptions::kUndefined) {
1736 RTC_LOG(LS_WARNING) << "CreateAnswer: offer_to_receive_video is not "
1737 "supported with Unified Plan semantics. Use the "
1738 "RtpTransceiver API instead.";
1739 }
1740 }
1741
htaa2a49d92016-03-04 02:51:39 -08001742 cricket::MediaSessionOptions session_options;
zhihuang1c378ed2017-08-17 14:10:50 -07001743 GetOptionsForAnswer(options, &session_options);
htaa2a49d92016-03-04 02:51:39 -08001744
Steve Antond25da372017-11-06 14:50:29 -08001745 webrtc_session_desc_factory_->CreateAnswer(observer, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001746}
1747
1748void PeerConnection::SetLocalDescription(
1749 SetSessionDescriptionObserver* observer,
Steve Anton80dd7b52018-02-16 17:08:42 -08001750 SessionDescriptionInterface* desc_ptr) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001751 TRACE_EVENT0("webrtc", "PeerConnection::SetLocalDescription");
Steve Anton8a006912017-12-04 15:25:56 -08001752
Steve Anton80dd7b52018-02-16 17:08:42 -08001753 // The SetLocalDescription contract is that we take ownership of the session
1754 // description regardless of the outcome, so wrap it in a unique_ptr right
1755 // away. Ideally, SetLocalDescription's signature will be changed to take the
1756 // description as a unique_ptr argument to formalize this agreement.
1757 std::unique_ptr<SessionDescriptionInterface> desc(desc_ptr);
1758
nisse7ce109a2017-01-31 00:57:56 -08001759 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001760 RTC_LOG(LS_ERROR) << "SetLocalDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001761 return;
1762 }
Steve Anton8a006912017-12-04 15:25:56 -08001763
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001764 if (!desc) {
1765 PostSetSessionDescriptionFailure(observer, "SessionDescription is NULL.");
1766 return;
1767 }
Steve Anton8d3444d2017-10-20 15:30:51 -07001768
Steve Anton80dd7b52018-02-16 17:08:42 -08001769 // If a session error has occurred the PeerConnection is in a possibly
1770 // inconsistent state so fail right away.
1771 if (session_error() != SessionError::kNone) {
1772 std::string error_message = GetSessionErrorMsg();
1773 RTC_LOG(LS_ERROR) << "SetLocalDescription: " << error_message;
1774 PostSetSessionDescriptionFailure(observer, std::move(error_message));
1775 return;
1776 }
Steve Anton8d3444d2017-10-20 15:30:51 -07001777
Steve Anton80dd7b52018-02-16 17:08:42 -08001778 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_LOCAL);
1779 if (!error.ok()) {
1780 std::string error_message = GetSetDescriptionErrorMessage(
1781 cricket::CS_LOCAL, desc->GetType(), error);
1782 RTC_LOG(LS_ERROR) << error_message;
1783 PostSetSessionDescriptionFailure(observer, std::move(error_message));
1784 return;
1785 }
1786
1787 // Grab the description type before moving ownership to ApplyLocalDescription,
1788 // which may destroy it before returning.
1789 const SdpType type = desc->GetType();
1790
1791 error = ApplyLocalDescription(std::move(desc));
Steve Anton8a006912017-12-04 15:25:56 -08001792 // |desc| may be destroyed at this point.
1793
1794 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08001795 // If ApplyLocalDescription fails, the PeerConnection could be in an
1796 // inconsistent state, so act conservatively here and set the session error
1797 // so that future calls to SetLocalDescription/SetRemoteDescription fail.
1798 SetSessionError(SessionError::kContent, error.message());
1799 std::string error_message =
1800 GetSetDescriptionErrorMessage(cricket::CS_LOCAL, type, error);
1801 RTC_LOG(LS_ERROR) << error_message;
Steve Anton8a006912017-12-04 15:25:56 -08001802 PostSetSessionDescriptionFailure(observer, std::move(error_message));
Steve Anton8d3444d2017-10-20 15:30:51 -07001803 return;
1804 }
Steve Anton8a006912017-12-04 15:25:56 -08001805 RTC_DCHECK(local_description());
1806
1807 PostSetSessionDescriptionSuccess(observer);
1808
1809 // According to JSEP, after setLocalDescription, changing the candidate pool
1810 // size is not allowed, and changing the set of ICE servers will not result
1811 // in new candidates being gathered.
1812 port_allocator_->FreezeCandidatePool();
1813
1814 // MaybeStartGathering needs to be called after posting
1815 // MSG_SET_SESSIONDESCRIPTION_SUCCESS, so that we don't signal any candidates
1816 // before signaling that SetLocalDescription completed.
1817 transport_controller_->MaybeStartGathering();
1818
Steve Antona3a92c22017-12-07 10:27:41 -08001819 if (local_description()->GetType() == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08001820 // TODO(deadbeef): We already had to hop to the network thread for
1821 // MaybeStartGathering...
1822 network_thread()->Invoke<void>(
1823 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
1824 port_allocator_.get()));
1825 }
1826}
1827
1828RTCError PeerConnection::ApplyLocalDescription(
1829 std::unique_ptr<SessionDescriptionInterface> desc) {
1830 RTC_DCHECK_RUN_ON(signaling_thread());
1831 RTC_DCHECK(desc);
1832
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001833 // Update stats here so that we have the most recent stats for tracks and
1834 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001835 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 15:25:56 -08001836
1837 // Update the initial_offerer flag if this session is the initial_offerer.
Steve Anton3828c062017-12-06 10:34:51 -08001838 SdpType type = desc->GetType();
Steve Anton8a006912017-12-04 15:25:56 -08001839 if (!initial_offerer_.has_value()) {
Steve Anton3828c062017-12-06 10:34:51 -08001840 initial_offerer_.emplace(type == SdpType::kOffer);
Steve Anton8a006912017-12-04 15:25:56 -08001841 if (*initial_offerer_) {
1842 transport_controller_->SetIceRole(cricket::ICEROLE_CONTROLLING);
1843 } else {
1844 transport_controller_->SetIceRole(cricket::ICEROLE_CONTROLLED);
1845 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001846 }
Steve Anton8a006912017-12-04 15:25:56 -08001847
Steve Antondcc3c022017-12-22 16:02:54 -08001848 // Take a reference to the old local description since it's used below to
1849 // compare against the new local description. When setting the new local
1850 // description, grab ownership of the replaced session description in case it
1851 // is the same as |old_local_description|, to keep it alive for the duration
1852 // of the method.
1853 const SessionDescriptionInterface* old_local_description =
1854 local_description();
1855 std::unique_ptr<SessionDescriptionInterface> replaced_local_description;
Steve Anton3828c062017-12-06 10:34:51 -08001856 if (type == SdpType::kAnswer) {
Steve Antondcc3c022017-12-22 16:02:54 -08001857 replaced_local_description = pending_local_description_
1858 ? std::move(pending_local_description_)
1859 : std::move(current_local_description_);
Steve Anton8a006912017-12-04 15:25:56 -08001860 current_local_description_ = std::move(desc);
1861 pending_local_description_ = nullptr;
1862 current_remote_description_ = std::move(pending_remote_description_);
1863 } else {
Steve Antondcc3c022017-12-22 16:02:54 -08001864 replaced_local_description = std::move(pending_local_description_);
Steve Anton8a006912017-12-04 15:25:56 -08001865 pending_local_description_ = std::move(desc);
1866 }
1867 // The session description to apply now must be accessed by
1868 // |local_description()|.
Henrik Boströmfdb92012017-11-09 19:55:44 +01001869 RTC_DCHECK(local_description());
deadbeefab9b2d12015-10-14 11:33:11 -07001870
Steve Antondcc3c022017-12-22 16:02:54 -08001871 if (IsUnifiedPlan()) {
1872 RTCError error = UpdateTransceiversAndDataChannels(
Seth Hampsonae8a90a2018-02-13 15:33:48 -08001873 cricket::CS_LOCAL, *local_description(), old_local_description,
1874 remote_description());
Steve Anton8a006912017-12-04 15:25:56 -08001875 if (!error.ok()) {
1876 return error;
1877 }
Steve Antondcc3c022017-12-22 16:02:54 -08001878 for (auto transceiver : transceivers_) {
1879 const ContentInfo* content =
1880 FindMediaSectionForTransceiver(transceiver, local_description());
1881 if (!content) {
1882 continue;
1883 }
1884 const MediaContentDescription* media_desc = content->media_description();
1885 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
1886 transceiver->internal()->set_current_direction(media_desc->direction());
1887 }
1888 if (content->rejected && !transceiver->stopped()) {
1889 transceiver->Stop();
1890 }
1891 }
1892 } else {
1893 // Transport and Media channels will be created only when offer is set.
1894 if (type == SdpType::kOffer) {
1895 // TODO(bugs.webrtc.org/4676) - Handle CreateChannel failure, as new local
1896 // description is applied. Restore back to old description.
1897 RTCError error = CreateChannels(*local_description()->description());
1898 if (!error.ok()) {
1899 return error;
1900 }
1901 }
Steve Anton8a006912017-12-04 15:25:56 -08001902
Steve Antondcc3c022017-12-22 16:02:54 -08001903 // Remove unused channels if MediaContentDescription is rejected.
1904 RemoveUnusedChannels(local_description()->description());
1905 }
Steve Anton8a006912017-12-04 15:25:56 -08001906
Steve Anton80dd7b52018-02-16 17:08:42 -08001907 RTCError error = UpdateSessionState(type, cricket::CS_LOCAL);
Steve Anton8a006912017-12-04 15:25:56 -08001908 if (!error.ok()) {
1909 return error;
1910 }
Steve Antondcc3c022017-12-22 16:02:54 -08001911
Steve Anton8a006912017-12-04 15:25:56 -08001912 if (remote_description()) {
1913 // Now that we have a local description, we can push down remote candidates.
1914 UseCandidatesInSessionDescription(remote_description());
1915 }
1916
1917 pending_ice_restarts_.clear();
1918 if (session_error() != SessionError::kNone) {
1919 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
1920 }
1921
deadbeefab9b2d12015-10-14 11:33:11 -07001922 // If setting the description decided our SSL role, allocate any necessary
1923 // SCTP sids.
1924 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08001925 if (data_channel_type() == cricket::DCT_SCTP && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001926 AllocateSctpSids(role);
1927 }
1928
Steve Antond3679212018-01-17 17:41:02 -08001929 if (IsUnifiedPlan()) {
1930 for (auto transceiver : transceivers_) {
1931 const ContentInfo* content =
1932 FindMediaSectionForTransceiver(transceiver, local_description());
1933 if (!content) {
1934 continue;
1935 }
1936 if (content->rejected && !transceiver->stopped()) {
1937 transceiver->Stop();
1938 }
Steve Anton74255ff2018-01-24 18:32:57 -08001939 const auto& streams = content->media_description()->streams();
1940 if (!content->rejected && !streams.empty()) {
Steve Antond3679212018-01-17 17:41:02 -08001941 transceiver->internal()->sender_internal()->set_stream_ids(
Steve Anton74255ff2018-01-24 18:32:57 -08001942 {streams[0].sync_label});
Steve Antond3679212018-01-17 17:41:02 -08001943 transceiver->internal()->sender_internal()->SetSsrc(
Steve Anton74255ff2018-01-24 18:32:57 -08001944 streams[0].first_ssrc());
Steve Antond3679212018-01-17 17:41:02 -08001945 }
1946 }
1947 } else {
1948 // Plan B semantics.
1949
Steve Antondcc3c022017-12-22 16:02:54 -08001950 // Update state and SSRC of local MediaStreams and DataChannels based on the
1951 // local session description.
1952 const cricket::ContentInfo* audio_content =
1953 GetFirstAudioContent(local_description()->description());
1954 if (audio_content) {
1955 if (audio_content->rejected) {
1956 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
1957 } else {
1958 const cricket::AudioContentDescription* audio_desc =
1959 audio_content->media_description()->as_audio();
1960 UpdateLocalSenders(audio_desc->streams(), audio_desc->type());
1961 }
deadbeeffaac4972015-11-12 15:33:07 -08001962 }
deadbeefab9b2d12015-10-14 11:33:11 -07001963
Steve Antondcc3c022017-12-22 16:02:54 -08001964 const cricket::ContentInfo* video_content =
1965 GetFirstVideoContent(local_description()->description());
1966 if (video_content) {
1967 if (video_content->rejected) {
1968 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
1969 } else {
1970 const cricket::VideoContentDescription* video_desc =
1971 video_content->media_description()->as_video();
1972 UpdateLocalSenders(video_desc->streams(), video_desc->type());
1973 }
deadbeeffaac4972015-11-12 15:33:07 -08001974 }
deadbeefab9b2d12015-10-14 11:33:11 -07001975 }
1976
1977 const cricket::ContentInfo* data_content =
Henrik Boströmfdb92012017-11-09 19:55:44 +01001978 GetFirstDataContent(local_description()->description());
deadbeefab9b2d12015-10-14 11:33:11 -07001979 if (data_content) {
1980 const cricket::DataContentDescription* data_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08001981 data_content->media_description()->as_data();
deadbeefab9b2d12015-10-14 11:33:11 -07001982 if (rtc::starts_with(data_desc->protocol().data(),
1983 cricket::kMediaProtocolRtpPrefix)) {
1984 UpdateLocalRtpDataChannels(data_desc->streams());
1985 }
1986 }
1987
Steve Anton8a006912017-12-04 15:25:56 -08001988 return RTCError::OK();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001989}
1990
1991void PeerConnection::SetRemoteDescription(
Henrik Boströma4ecf552017-11-23 14:17:07 +00001992 SetSessionDescriptionObserver* observer,
1993 SessionDescriptionInterface* desc) {
Henrik Boström31638672017-11-23 17:48:32 +01001994 SetRemoteDescription(
1995 std::unique_ptr<SessionDescriptionInterface>(desc),
1996 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface>(
1997 new SetRemoteDescriptionObserverAdapter(this, observer)));
1998}
1999
2000void PeerConnection::SetRemoteDescription(
2001 std::unique_ptr<SessionDescriptionInterface> desc,
2002 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface> observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +01002003 TRACE_EVENT0("webrtc", "PeerConnection::SetRemoteDescription");
Steve Anton8a006912017-12-04 15:25:56 -08002004
nisse7ce109a2017-01-31 00:57:56 -08002005 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002006 RTC_LOG(LS_ERROR) << "SetRemoteDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002007 return;
2008 }
Steve Anton8a006912017-12-04 15:25:56 -08002009
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002010 if (!desc) {
Henrik Boström31638672017-11-23 17:48:32 +01002011 observer->OnSetRemoteDescriptionComplete(RTCError(
Steve Anton8a006912017-12-04 15:25:56 -08002012 RTCErrorType::INVALID_PARAMETER, "SessionDescription is NULL."));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002013 return;
2014 }
Steve Anton8d3444d2017-10-20 15:30:51 -07002015
Steve Anton80dd7b52018-02-16 17:08:42 -08002016 // If a session error has occurred the PeerConnection is in a possibly
2017 // inconsistent state so fail right away.
2018 if (session_error() != SessionError::kNone) {
2019 std::string error_message = GetSessionErrorMsg();
2020 RTC_LOG(LS_ERROR) << "SetRemoteDescription: " << error_message;
2021 observer->OnSetRemoteDescriptionComplete(
2022 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
2023 return;
2024 }
Steve Anton71439a62018-02-15 11:53:06 -08002025
Steve Anton80dd7b52018-02-16 17:08:42 -08002026 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_REMOTE);
Steve Anton71439a62018-02-15 11:53:06 -08002027 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08002028 std::string error_message = GetSetDescriptionErrorMessage(
2029 cricket::CS_REMOTE, desc->GetType(), error);
2030 RTC_LOG(LS_ERROR) << error_message;
Steve Anton71439a62018-02-15 11:53:06 -08002031 observer->OnSetRemoteDescriptionComplete(
2032 RTCError(error.type(), std::move(error_message)));
2033 return;
2034 }
Steve Anton71439a62018-02-15 11:53:06 -08002035
Steve Anton80dd7b52018-02-16 17:08:42 -08002036 // Grab the description type before moving ownership to
2037 // ApplyRemoteDescription, which may destroy it before returning.
2038 const SdpType type = desc->GetType();
2039
2040 error = ApplyRemoteDescription(std::move(desc));
2041 // |desc| may be destroyed at this point.
2042
2043 if (!error.ok()) {
2044 // If ApplyRemoteDescription fails, the PeerConnection could be in an
2045 // inconsistent state, so act conservatively here and set the session error
2046 // so that future calls to SetLocalDescription/SetRemoteDescription fail.
2047 SetSessionError(SessionError::kContent, error.message());
2048 std::string error_message =
2049 GetSetDescriptionErrorMessage(cricket::CS_REMOTE, type, error);
2050 RTC_LOG(LS_ERROR) << error_message;
2051 observer->OnSetRemoteDescriptionComplete(
2052 RTCError(error.type(), std::move(error_message)));
2053 return;
2054 }
2055 RTC_DCHECK(remote_description());
2056
2057 if (type == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002058 // TODO(deadbeef): We already had to hop to the network thread for
2059 // MaybeStartGathering...
2060 network_thread()->Invoke<void>(
2061 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
2062 port_allocator_.get()));
Harald Alvestrand5dbb5862018-02-13 23:48:00 +01002063 // Make UMA notes about what was agreed to.
2064 if (uma_observer_) {
2065 switch (remote_description()->description()->msid_signaling()) {
2066 case 0:
2067 uma_observer_->IncrementEnumCounter(kEnumCounterSdpSemanticNegotiated,
2068 kSdpSemanticNegotiatedNone,
2069 kSdpSemanticNegotiatedMax);
2070 break;
2071 case cricket::kMsidSignalingMediaSection:
2072 uma_observer_->IncrementEnumCounter(kEnumCounterSdpSemanticNegotiated,
2073 kSdpSemanticNegotiatedUnifiedPlan,
2074 kSdpSemanticNegotiatedMax);
2075 break;
2076 case cricket::kMsidSignalingSsrcAttribute:
2077 uma_observer_->IncrementEnumCounter(kEnumCounterSdpSemanticNegotiated,
2078 kSdpSemanticNegotiatedPlanB,
2079 kSdpSemanticNegotiatedMax);
2080 break;
2081 case cricket::kMsidSignalingMediaSection |
2082 cricket::kMsidSignalingSsrcAttribute:
2083 uma_observer_->IncrementEnumCounter(kEnumCounterSdpSemanticNegotiated,
2084 kSdpSemanticNegotiatedMixed,
2085 kSdpSemanticNegotiatedMax);
2086 break;
2087 default:
2088 RTC_NOTREACHED();
2089 }
2090 }
Steve Anton8a006912017-12-04 15:25:56 -08002091 }
2092
2093 observer->OnSetRemoteDescriptionComplete(RTCError::OK());
2094}
2095
2096RTCError PeerConnection::ApplyRemoteDescription(
2097 std::unique_ptr<SessionDescriptionInterface> desc) {
2098 RTC_DCHECK_RUN_ON(signaling_thread());
2099 RTC_DCHECK(desc);
2100
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002101 // Update stats here so that we have the most recent stats for tracks and
2102 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00002103 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 15:25:56 -08002104
Steve Antondcc3c022017-12-22 16:02:54 -08002105 // Take a reference to the old remote description since it's used below to
2106 // compare against the new remote description. When setting the new remote
2107 // description, grab ownership of the replaced session description in case it
2108 // is the same as |old_remote_description|, to keep it alive for the duration
2109 // of the method.
Steve Anton8a006912017-12-04 15:25:56 -08002110 const SessionDescriptionInterface* old_remote_description =
2111 remote_description();
Steve Anton8a006912017-12-04 15:25:56 -08002112 std::unique_ptr<SessionDescriptionInterface> replaced_remote_description;
Steve Anton3828c062017-12-06 10:34:51 -08002113 SdpType type = desc->GetType();
2114 if (type == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002115 replaced_remote_description = pending_remote_description_
2116 ? std::move(pending_remote_description_)
2117 : std::move(current_remote_description_);
2118 current_remote_description_ = std::move(desc);
2119 pending_remote_description_ = nullptr;
2120 current_local_description_ = std::move(pending_local_description_);
2121 } else {
2122 replaced_remote_description = std::move(pending_remote_description_);
2123 pending_remote_description_ = std::move(desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002124 }
Steve Anton8a006912017-12-04 15:25:56 -08002125 // The session description to apply now must be accessed by
2126 // |remote_description()|.
Henrik Boströmfdb92012017-11-09 19:55:44 +01002127 RTC_DCHECK(remote_description());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002128
Steve Anton8a006912017-12-04 15:25:56 -08002129 // Transport and Media channels will be created only when offer is set.
Steve Antondcc3c022017-12-22 16:02:54 -08002130 if (IsUnifiedPlan()) {
2131 RTCError error = UpdateTransceiversAndDataChannels(
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002132 cricket::CS_REMOTE, *remote_description(), local_description(),
2133 old_remote_description);
Steve Anton8a006912017-12-04 15:25:56 -08002134 if (!error.ok()) {
2135 return error;
2136 }
Steve Antondcc3c022017-12-22 16:02:54 -08002137 } else {
2138 if (type == SdpType::kOffer) {
2139 // TODO(bugs.webrtc.org/4676) - Handle CreateChannel failure, as new local
2140 // description is applied. Restore back to old description.
2141 RTCError error = CreateChannels(*remote_description()->description());
2142 if (!error.ok()) {
2143 return error;
2144 }
2145 }
Steve Anton8a006912017-12-04 15:25:56 -08002146
Steve Antondcc3c022017-12-22 16:02:54 -08002147 // Remove unused channels if MediaContentDescription is rejected.
2148 RemoveUnusedChannels(remote_description()->description());
2149 }
Steve Anton8a006912017-12-04 15:25:56 -08002150
2151 // NOTE: Candidates allocation will be initiated only when SetLocalDescription
2152 // is called.
Steve Anton80dd7b52018-02-16 17:08:42 -08002153 RTCError error = UpdateSessionState(type, cricket::CS_REMOTE);
Steve Anton8a006912017-12-04 15:25:56 -08002154 if (!error.ok()) {
2155 return error;
2156 }
2157
2158 if (local_description() &&
2159 !UseCandidatesInSessionDescription(remote_description())) {
2160 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidCandidates);
2161 }
2162
2163 if (old_remote_description) {
2164 for (const cricket::ContentInfo& content :
2165 old_remote_description->description()->contents()) {
2166 // Check if this new SessionDescription contains new ICE ufrag and
2167 // password that indicates the remote peer requests an ICE restart.
2168 // TODO(deadbeef): When we start storing both the current and pending
2169 // remote description, this should reset pending_ice_restarts and compare
2170 // against the current description.
2171 if (CheckForRemoteIceRestart(old_remote_description, remote_description(),
2172 content.name)) {
Steve Anton3828c062017-12-06 10:34:51 -08002173 if (type == SdpType::kOffer) {
Steve Anton8a006912017-12-04 15:25:56 -08002174 pending_ice_restarts_.insert(content.name);
2175 }
2176 } else {
2177 // We retain all received candidates only if ICE is not restarted.
2178 // When ICE is restarted, all previous candidates belong to an old
2179 // generation and should not be kept.
2180 // TODO(deadbeef): This goes against the W3C spec which says the remote
2181 // description should only contain candidates from the last set remote
2182 // description plus any candidates added since then. We should remove
2183 // this once we're sure it won't break anything.
2184 WebRtcSessionDescriptionFactory::CopyCandidatesFromSessionDescription(
2185 old_remote_description, content.name, mutable_remote_description());
2186 }
2187 }
2188 }
2189
2190 if (session_error() != SessionError::kNone) {
2191 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
2192 }
2193
2194 // Set the the ICE connection state to connecting since the connection may
2195 // become writable with peer reflexive candidates before any remote candidate
2196 // is signaled.
2197 // TODO(pthatcher): This is a short-term solution for crbug/446908. A real fix
2198 // is to have a new signal the indicates a change in checking state from the
2199 // transport and expose a new checking() member from transport that can be
2200 // read to determine the current checking state. The existing SignalConnecting
2201 // actually means "gathering candidates", so cannot be be used here.
Steve Antona3a92c22017-12-07 10:27:41 -08002202 if (remote_description()->GetType() != SdpType::kOffer &&
Steve Anton8a006912017-12-04 15:25:56 -08002203 ice_connection_state() == PeerConnectionInterface::kIceConnectionNew) {
2204 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
2205 }
2206
deadbeefab9b2d12015-10-14 11:33:11 -07002207 // If setting the description decided our SSL role, allocate any necessary
2208 // SCTP sids.
2209 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08002210 if (data_channel_type() == cricket::DCT_SCTP && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07002211 AllocateSctpSids(role);
2212 }
2213
Steve Antondcc3c022017-12-22 16:02:54 -08002214 if (IsUnifiedPlan()) {
Steve Anton8b815cd2018-02-16 16:14:42 -08002215 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
2216 receiving_transceivers;
Steve Antonc49bcd92018-02-14 14:28:13 -08002217 std::vector<rtc::scoped_refptr<MediaStreamInterface>> added_streams;
Steve Antondcc3c022017-12-22 16:02:54 -08002218 for (auto transceiver : transceivers_) {
2219 const ContentInfo* content =
2220 FindMediaSectionForTransceiver(transceiver, remote_description());
2221 if (!content) {
2222 continue;
2223 }
2224 const MediaContentDescription* media_desc = content->media_description();
2225 RtpTransceiverDirection local_direction =
2226 RtpTransceiverDirectionReversed(media_desc->direction());
2227 // From the WebRTC specification, steps 2.2.8.5/6 of section 4.4.1.6 "Set
2228 // the RTCSessionDescription: If direction is sendrecv or recvonly, and
2229 // transceiver's current direction is neither sendrecv nor recvonly,
2230 // process the addition of a remote track for the media description.
2231 if (RtpTransceiverDirectionHasRecv(local_direction) &&
2232 (!transceiver->current_direction() ||
2233 !RtpTransceiverDirectionHasRecv(
Steve Anton74255ff2018-01-24 18:32:57 -08002234 *transceiver->current_direction())) &&
2235 !media_desc->streams().empty()) {
Steve Antonef65ef12018-01-10 17:15:20 -08002236 const std::string& sync_label = media_desc->streams()[0].sync_label;
2237 rtc::scoped_refptr<MediaStreamInterface> stream =
2238 remote_streams_->find(sync_label);
2239 if (!stream) {
2240 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
2241 MediaStream::Create(sync_label));
2242 remote_streams_->AddStream(stream);
Steve Antonc49bcd92018-02-14 14:28:13 -08002243 added_streams.push_back(stream);
Steve Antonef65ef12018-01-10 17:15:20 -08002244 }
2245 transceiver->internal()->receiver_internal()->SetStreams({stream});
Steve Anton8b815cd2018-02-16 16:14:42 -08002246 receiving_transceivers.push_back(transceiver);
Steve Antondcc3c022017-12-22 16:02:54 -08002247 }
2248 // If direction is sendonly or inactive, and transceiver's current
2249 // direction is neither sendonly nor inactive, process the removal of a
2250 // remote track for the media description.
2251 if (!RtpTransceiverDirectionHasRecv(local_direction) &&
Steve Antonef65ef12018-01-10 17:15:20 -08002252 (transceiver->current_direction() &&
Steve Antondcc3c022017-12-22 16:02:54 -08002253 RtpTransceiverDirectionHasRecv(*transceiver->current_direction()))) {
Steve Antonef65ef12018-01-10 17:15:20 -08002254 transceiver->internal()->receiver_internal()->SetStreams({});
Steve Antondcc3c022017-12-22 16:02:54 -08002255 }
2256 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
2257 transceiver->internal()->set_current_direction(local_direction);
2258 }
2259 if (content->rejected && !transceiver->stopped()) {
2260 transceiver->Stop();
2261 }
Steve Anton74255ff2018-01-24 18:32:57 -08002262 if (!content->rejected && !media_desc->streams().empty()) {
Steve Antond3679212018-01-17 17:41:02 -08002263 transceiver->internal()->receiver_internal()->SetupMediaChannel(
Steve Anton5f94aa22018-02-01 10:58:30 -08002264 media_desc->streams()[0].first_ssrc());
Steve Antond3679212018-01-17 17:41:02 -08002265 }
Steve Antondcc3c022017-12-22 16:02:54 -08002266 }
Steve Antonc49bcd92018-02-14 14:28:13 -08002267 // Once all processing has finished, fire off callbacks.
Steve Anton8b815cd2018-02-16 16:14:42 -08002268 for (auto transceiver : receiving_transceivers) {
2269 observer_->OnTrack(transceiver);
2270 observer_->OnAddTrack(transceiver->receiver(),
2271 transceiver->receiver()->streams());
Steve Antonef65ef12018-01-10 17:15:20 -08002272 }
Steve Antonc49bcd92018-02-14 14:28:13 -08002273 for (auto stream : added_streams) {
2274 observer_->OnAddStream(stream);
2275 }
Steve Antondcc3c022017-12-22 16:02:54 -08002276 }
2277
Henrik Boströmfdb92012017-11-09 19:55:44 +01002278 const cricket::ContentInfo* audio_content =
2279 GetFirstAudioContent(remote_description()->description());
2280 const cricket::ContentInfo* video_content =
2281 GetFirstVideoContent(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002282 const cricket::AudioContentDescription* audio_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002283 GetFirstAudioContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002284 const cricket::VideoContentDescription* video_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002285 GetFirstVideoContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002286 const cricket::DataContentDescription* data_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002287 GetFirstDataContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002288
2289 // Check if the descriptions include streams, just in case the peer supports
2290 // MSID, but doesn't indicate so with "a=msid-semantic".
Henrik Boströmfdb92012017-11-09 19:55:44 +01002291 if (remote_description()->description()->msid_supported() ||
deadbeefbda7e0b2015-12-08 17:13:40 -08002292 (audio_desc && !audio_desc->streams().empty()) ||
2293 (video_desc && !video_desc->streams().empty())) {
2294 remote_peer_supports_msid_ = true;
2295 }
deadbeefab9b2d12015-10-14 11:33:11 -07002296
2297 // We wait to signal new streams until we finish processing the description,
2298 // since only at that point will new streams have all their tracks.
2299 rtc::scoped_refptr<StreamCollection> new_streams(StreamCollection::Create());
2300
Steve Antondcc3c022017-12-22 16:02:54 -08002301 if (!IsUnifiedPlan()) {
2302 // TODO(steveanton): When removing RTP senders/receivers in response to a
2303 // rejected media section, there is some cleanup logic that expects the
2304 // voice/ video channel to still be set. But in this method the voice/video
2305 // channel would have been destroyed by the SetRemoteDescription caller
2306 // above so the cleanup that relies on them fails to run. The RemoveSenders
2307 // calls should be moved to right before the DestroyChannel calls to fix
2308 // this.
Steve Anton8d3444d2017-10-20 15:30:51 -07002309
Steve Antondcc3c022017-12-22 16:02:54 -08002310 // Find all audio rtp streams and create corresponding remote AudioTracks
2311 // and MediaStreams.
2312 if (audio_content) {
2313 if (audio_content->rejected) {
2314 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
2315 } else {
2316 bool default_audio_track_needed =
2317 !remote_peer_supports_msid_ &&
2318 RtpTransceiverDirectionHasSend(audio_desc->direction());
2319 UpdateRemoteSendersList(GetActiveStreams(audio_desc),
2320 default_audio_track_needed, audio_desc->type(),
2321 new_streams);
2322 }
deadbeeffaac4972015-11-12 15:33:07 -08002323 }
deadbeefab9b2d12015-10-14 11:33:11 -07002324
Steve Antondcc3c022017-12-22 16:02:54 -08002325 // Find all video rtp streams and create corresponding remote VideoTracks
2326 // and MediaStreams.
2327 if (video_content) {
2328 if (video_content->rejected) {
2329 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
2330 } else {
2331 bool default_video_track_needed =
2332 !remote_peer_supports_msid_ &&
2333 RtpTransceiverDirectionHasSend(video_desc->direction());
2334 UpdateRemoteSendersList(GetActiveStreams(video_desc),
2335 default_video_track_needed, video_desc->type(),
2336 new_streams);
2337 }
deadbeeffaac4972015-11-12 15:33:07 -08002338 }
deadbeefab9b2d12015-10-14 11:33:11 -07002339
Steve Antondcc3c022017-12-22 16:02:54 -08002340 // Update the DataChannels with the information from the remote peer.
2341 if (data_desc) {
2342 if (rtc::starts_with(data_desc->protocol().data(),
2343 cricket::kMediaProtocolRtpPrefix)) {
2344 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
2345 }
deadbeefab9b2d12015-10-14 11:33:11 -07002346 }
deadbeefab9b2d12015-10-14 11:33:11 -07002347
Steve Antondcc3c022017-12-22 16:02:54 -08002348 // Iterate new_streams and notify the observer about new MediaStreams.
2349 for (size_t i = 0; i < new_streams->count(); ++i) {
2350 MediaStreamInterface* new_stream = new_streams->at(i);
2351 stats_->AddStream(new_stream);
2352 observer_->OnAddStream(
2353 rtc::scoped_refptr<MediaStreamInterface>(new_stream));
2354 }
deadbeefab9b2d12015-10-14 11:33:11 -07002355
Steve Antondcc3c022017-12-22 16:02:54 -08002356 UpdateEndedRemoteMediaStreams();
2357 }
deadbeefab9b2d12015-10-14 11:33:11 -07002358
Steve Anton8a006912017-12-04 15:25:56 -08002359 return RTCError::OK();
deadbeeffc648b62015-10-13 16:42:33 -07002360}
2361
Steve Antondcc3c022017-12-22 16:02:54 -08002362RTCError PeerConnection::UpdateTransceiversAndDataChannels(
2363 cricket::ContentSource source,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002364 const SessionDescriptionInterface& new_session,
2365 const SessionDescriptionInterface* old_local_description,
2366 const SessionDescriptionInterface* old_remote_description) {
Steve Antondcc3c022017-12-22 16:02:54 -08002367 RTC_DCHECK(IsUnifiedPlan());
2368
Steve Anton7464fca2018-01-19 11:10:37 -08002369 const cricket::ContentGroup* bundle_group = nullptr;
2370 if (new_session.GetType() == SdpType::kOffer) {
2371 auto bundle_group_or_error =
2372 GetEarlyBundleGroup(*new_session.description());
2373 if (!bundle_group_or_error.ok()) {
2374 return bundle_group_or_error.MoveError();
2375 }
2376 bundle_group = bundle_group_or_error.MoveValue();
Steve Antondcc3c022017-12-22 16:02:54 -08002377 }
Steve Antondcc3c022017-12-22 16:02:54 -08002378
Steve Antondcc3c022017-12-22 16:02:54 -08002379 const ContentInfos& new_contents = new_session.description()->contents();
Steve Antondcc3c022017-12-22 16:02:54 -08002380 for (size_t i = 0; i < new_contents.size(); ++i) {
2381 const cricket::ContentInfo& new_content = new_contents[i];
Steve Antondcc3c022017-12-22 16:02:54 -08002382 cricket::MediaType media_type = new_content.media_description()->type();
2383 seen_mids_.insert(new_content.name);
2384 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
2385 media_type == cricket::MEDIA_TYPE_VIDEO) {
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002386 const cricket::ContentInfo* old_local_content = nullptr;
2387 if (old_local_description &&
2388 i < old_local_description->description()->contents().size()) {
2389 old_local_content =
2390 &old_local_description->description()->contents()[i];
2391 }
2392 const cricket::ContentInfo* old_remote_content = nullptr;
2393 if (old_remote_description &&
2394 i < old_remote_description->description()->contents().size()) {
2395 old_remote_content =
2396 &old_remote_description->description()->contents()[i];
2397 }
Steve Antondcc3c022017-12-22 16:02:54 -08002398 auto transceiver_or_error =
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002399 AssociateTransceiver(source, new_session.GetType(), i, new_content,
2400 old_local_content, old_remote_content);
Steve Antondcc3c022017-12-22 16:02:54 -08002401 if (!transceiver_or_error.ok()) {
2402 return transceiver_or_error.MoveError();
2403 }
2404 auto transceiver = transceiver_or_error.MoveValue();
Steve Antondcc3c022017-12-22 16:02:54 -08002405 RTCError error =
2406 UpdateTransceiverChannel(transceiver, new_content, bundle_group);
2407 if (!error.ok()) {
2408 return error;
2409 }
2410 } else if (media_type == cricket::MEDIA_TYPE_DATA) {
Steve Antonfa2260d2017-12-28 16:38:23 -08002411 if (GetDataMid() && new_content.name != *GetDataMid()) {
2412 // Ignore all but the first data section.
2413 continue;
2414 }
2415 RTCError error = UpdateDataChannel(source, new_content, bundle_group);
2416 if (!error.ok()) {
2417 return error;
2418 }
Steve Antondcc3c022017-12-22 16:02:54 -08002419 } else {
2420 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
2421 "Unknown section type.");
2422 }
2423 }
2424
2425 return RTCError::OK();
2426}
2427
2428RTCError PeerConnection::UpdateTransceiverChannel(
2429 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2430 transceiver,
2431 const cricket::ContentInfo& content,
2432 const cricket::ContentGroup* bundle_group) {
2433 RTC_DCHECK(IsUnifiedPlan());
2434 RTC_DCHECK(transceiver);
2435 cricket::BaseChannel* channel = transceiver->internal()->channel();
2436 if (content.rejected) {
2437 if (channel) {
2438 transceiver->internal()->SetChannel(nullptr);
2439 DestroyBaseChannel(channel);
2440 }
2441 } else {
2442 if (!channel) {
Steve Anton69470252018-02-09 11:43:08 -08002443 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Steve Antondcc3c022017-12-22 16:02:54 -08002444 channel = CreateVoiceChannel(
2445 content.name,
2446 GetTransportNameForMediaSection(content.name, bundle_group));
2447 } else {
Steve Anton69470252018-02-09 11:43:08 -08002448 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, transceiver->media_type());
Steve Antondcc3c022017-12-22 16:02:54 -08002449 channel = CreateVideoChannel(
2450 content.name,
2451 GetTransportNameForMediaSection(content.name, bundle_group));
2452 }
2453 if (!channel) {
2454 LOG_AND_RETURN_ERROR(
2455 RTCErrorType::INTERNAL_ERROR,
2456 "Failed to create channel for mid=" + content.name);
2457 }
2458 transceiver->internal()->SetChannel(channel);
2459 }
2460 }
2461 return RTCError::OK();
2462}
2463
Steve Antonfa2260d2017-12-28 16:38:23 -08002464RTCError PeerConnection::UpdateDataChannel(
2465 cricket::ContentSource source,
2466 const cricket::ContentInfo& content,
2467 const cricket::ContentGroup* bundle_group) {
2468 if (data_channel_type_ == cricket::DCT_NONE) {
Steve Antondbf9d032018-01-19 15:23:40 -08002469 // If data channels are disabled, ignore this media section. CreateAnswer
2470 // will take care of rejecting it.
2471 return RTCError::OK();
Steve Antonfa2260d2017-12-28 16:38:23 -08002472 }
2473 if (content.rejected) {
2474 DestroyDataChannel();
2475 } else {
2476 if (!rtp_data_channel_ && !sctp_transport_) {
2477 if (!CreateDataChannel(content.name, GetTransportNameForMediaSection(
2478 content.name, bundle_group))) {
2479 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
2480 "Failed to create data channel.");
2481 }
2482 }
2483 if (source == cricket::CS_REMOTE) {
2484 const MediaContentDescription* data_desc = content.media_description();
2485 if (data_desc && cricket::IsRtpProtocol(data_desc->protocol())) {
2486 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
2487 }
2488 }
2489 }
2490 return RTCError::OK();
2491}
2492
Steve Antondcc3c022017-12-22 16:02:54 -08002493RTCErrorOr<rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
2494PeerConnection::AssociateTransceiver(cricket::ContentSource source,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002495 SdpType type,
Steve Antondcc3c022017-12-22 16:02:54 -08002496 size_t mline_index,
2497 const ContentInfo& content,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002498 const ContentInfo* old_local_content,
2499 const ContentInfo* old_remote_content) {
Steve Antondcc3c022017-12-22 16:02:54 -08002500 RTC_DCHECK(IsUnifiedPlan());
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002501 // If this is an offer then the m= section might be recycled. If the m=
2502 // section is being recycled (defined as: rejected in the current local or
2503 // remote description and not rejected in new description), dissociate the
2504 // currently associated RtpTransceiver by setting its mid property to null,
2505 // and discard the mapping between the transceiver and its m= section index.
2506 if (IsMediaSectionBeingRecycled(type, content, old_local_content,
2507 old_remote_content)) {
2508 // We want to dissociate the transceiver that has the rejected mid.
2509 const std::string& old_mid =
2510 (old_local_content && old_local_content->rejected)
2511 ? old_local_content->name
2512 : old_remote_content->name;
2513 auto old_transceiver = GetAssociatedTransceiver(old_mid);
Steve Antondcc3c022017-12-22 16:02:54 -08002514 if (old_transceiver) {
2515 old_transceiver->internal()->set_mid(rtc::nullopt);
2516 old_transceiver->internal()->set_mline_index(rtc::nullopt);
2517 }
2518 }
2519 const MediaContentDescription* media_desc = content.media_description();
2520 auto transceiver = GetAssociatedTransceiver(content.name);
2521 if (source == cricket::CS_LOCAL) {
2522 // Find the RtpTransceiver that corresponds to this m= section, using the
2523 // mapping between transceivers and m= section indices established when
2524 // creating the offer.
2525 if (!transceiver) {
2526 transceiver = GetTransceiverByMLineIndex(mline_index);
2527 }
2528 if (!transceiver) {
2529 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2530 "Unknown transceiver");
2531 }
2532 } else {
2533 RTC_DCHECK_EQ(source, cricket::CS_REMOTE);
2534 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers
2535 // of the same type...
2536 if (!transceiver &&
2537 RtpTransceiverDirectionHasRecv(media_desc->direction())) {
2538 transceiver = FindAvailableTransceiverToReceive(media_desc->type());
2539 }
2540 // If no RtpTransceiver was found in the previous step, create one with a
2541 // recvonly direction.
2542 if (!transceiver) {
Steve Anton02ee47c2018-01-10 16:26:06 -08002543 auto sender =
2544 CreateSender(media_desc->type(), nullptr, {rtc::CreateRandomUuid()});
Steve Anton5f94aa22018-02-01 10:58:30 -08002545 std::string receiver_id;
2546 if (!media_desc->streams().empty()) {
2547 receiver_id = media_desc->streams()[0].id;
2548 } else {
2549 receiver_id = rtc::CreateRandomUuid();
2550 }
2551 auto receiver = CreateReceiver(media_desc->type(), receiver_id);
Steve Anton02ee47c2018-01-10 16:26:06 -08002552 transceiver = CreateAndAddTransceiver(sender, receiver);
Steve Antondcc3c022017-12-22 16:02:54 -08002553 transceiver->internal()->set_direction(
2554 RtpTransceiverDirection::kRecvOnly);
2555 }
2556 }
2557 RTC_DCHECK(transceiver);
Steve Anton69470252018-02-09 11:43:08 -08002558 if (transceiver->media_type() != media_desc->type()) {
Steve Antondcc3c022017-12-22 16:02:54 -08002559 LOG_AND_RETURN_ERROR(
2560 RTCErrorType::INVALID_PARAMETER,
2561 "Transceiver type does not match media description type.");
2562 }
2563 // Associate the found or created RtpTransceiver with the m= section by
2564 // setting the value of the RtpTransceiver's mid property to the MID of the m=
2565 // section, and establish a mapping between the transceiver and the index of
2566 // the m= section.
2567 transceiver->internal()->set_mid(content.name);
2568 transceiver->internal()->set_mline_index(mline_index);
2569 return std::move(transceiver);
2570}
2571
2572rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2573PeerConnection::GetAssociatedTransceiver(const std::string& mid) const {
2574 RTC_DCHECK(IsUnifiedPlan());
2575 for (auto transceiver : transceivers_) {
2576 if (transceiver->mid() == mid) {
2577 return transceiver;
2578 }
2579 }
2580 return nullptr;
2581}
2582
2583rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2584PeerConnection::GetTransceiverByMLineIndex(size_t mline_index) const {
2585 RTC_DCHECK(IsUnifiedPlan());
2586 for (auto transceiver : transceivers_) {
2587 if (transceiver->internal()->mline_index() == mline_index) {
2588 return transceiver;
2589 }
2590 }
2591 return nullptr;
2592}
2593
2594rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2595PeerConnection::FindAvailableTransceiverToReceive(
2596 cricket::MediaType media_type) const {
2597 RTC_DCHECK(IsUnifiedPlan());
2598 // From JSEP section 5.10 (Applying a Remote Description):
2599 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers of
2600 // the same type that were added to the PeerConnection by addTrack and are not
2601 // associated with any m= section and are not stopped, find the first such
2602 // RtpTransceiver.
2603 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08002604 if (transceiver->media_type() == media_type &&
Steve Antondcc3c022017-12-22 16:02:54 -08002605 transceiver->internal()->created_by_addtrack() && !transceiver->mid() &&
2606 !transceiver->stopped()) {
2607 return transceiver;
2608 }
2609 }
2610 return nullptr;
2611}
2612
Steve Antoned10bd92017-12-05 10:52:59 -08002613const cricket::ContentInfo* PeerConnection::FindMediaSectionForTransceiver(
2614 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2615 transceiver,
2616 const SessionDescriptionInterface* sdesc) const {
2617 RTC_DCHECK(transceiver);
2618 RTC_DCHECK(sdesc);
2619 if (IsUnifiedPlan()) {
2620 if (!transceiver->internal()->mid()) {
2621 // This transceiver is not associated with a media section yet.
2622 return nullptr;
2623 }
2624 return sdesc->description()->GetContentByName(
2625 *transceiver->internal()->mid());
2626 } else {
2627 // Plan B only allows at most one audio and one video section, so use the
2628 // first media section of that type.
2629 return cricket::GetFirstMediaContent(sdesc->description()->contents(),
Steve Anton69470252018-02-09 11:43:08 -08002630 transceiver->media_type());
Steve Antoned10bd92017-12-05 10:52:59 -08002631 }
2632}
2633
deadbeef46c73892016-11-16 19:42:04 -08002634PeerConnectionInterface::RTCConfiguration PeerConnection::GetConfiguration() {
2635 return configuration_;
2636}
2637
deadbeef293e9262017-01-11 12:28:30 -08002638bool PeerConnection::SetConfiguration(const RTCConfiguration& configuration,
2639 RTCError* error) {
Peter Boström1a9d6152015-12-08 22:15:17 +01002640 TRACE_EVENT0("webrtc", "PeerConnection::SetConfiguration");
deadbeef6de92f92016-12-12 18:49:32 -08002641
Steve Anton75737c02017-11-06 10:37:17 -08002642 if (local_description() && configuration.ice_candidate_pool_size !=
2643 configuration_.ice_candidate_pool_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002644 RTC_LOG(LS_ERROR) << "Can't change candidate pool size after calling "
2645 "SetLocalDescription.";
deadbeef293e9262017-01-11 12:28:30 -08002646 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00002647 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002648
deadbeef293e9262017-01-11 12:28:30 -08002649 // The simplest (and most future-compatible) way to tell if the config was
2650 // modified in an invalid way is to copy each property we do support
2651 // modifying, then use operator==. There are far more properties we don't
2652 // support modifying than those we do, and more could be added.
2653 RTCConfiguration modified_config = configuration_;
2654 modified_config.servers = configuration.servers;
2655 modified_config.type = configuration.type;
2656 modified_config.ice_candidate_pool_size =
2657 configuration.ice_candidate_pool_size;
2658 modified_config.prune_turn_ports = configuration.prune_turn_ports;
skvladd1f5fda2017-02-03 16:54:05 -08002659 modified_config.ice_check_min_interval = configuration.ice_check_min_interval;
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08002660 modified_config.stun_candidate_keepalive_interval =
2661 configuration.stun_candidate_keepalive_interval;
Jonas Orelandbdcee282017-10-10 14:01:40 +02002662 modified_config.turn_customizer = configuration.turn_customizer;
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08002663 modified_config.network_preference = configuration.network_preference;
deadbeef293e9262017-01-11 12:28:30 -08002664 if (configuration != modified_config) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002665 RTC_LOG(LS_ERROR) << "Modifying the configuration in an unsupported way.";
deadbeef293e9262017-01-11 12:28:30 -08002666 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
2667 }
2668
Steve Anton038834f2017-07-14 15:59:59 -07002669 // Validate the modified configuration.
2670 RTCError validate_error = ValidateConfiguration(modified_config);
2671 if (!validate_error.ok()) {
2672 return SafeSetError(std::move(validate_error), error);
2673 }
2674
deadbeef293e9262017-01-11 12:28:30 -08002675 // Note that this isn't possible through chromium, since it's an unsigned
2676 // short in WebIDL.
2677 if (configuration.ice_candidate_pool_size < 0 ||
2678 configuration.ice_candidate_pool_size > UINT16_MAX) {
2679 return SafeSetError(RTCErrorType::INVALID_RANGE, error);
2680 }
2681
2682 // Parse ICE servers before hopping to network thread.
2683 cricket::ServerAddresses stun_servers;
2684 std::vector<cricket::RelayServerConfig> turn_servers;
2685 RTCErrorType parse_error =
2686 ParseIceServers(configuration.servers, &stun_servers, &turn_servers);
2687 if (parse_error != RTCErrorType::NONE) {
2688 return SafeSetError(parse_error, error);
2689 }
2690
2691 // In theory this shouldn't fail.
2692 if (!network_thread()->Invoke<bool>(
2693 RTC_FROM_HERE,
2694 rtc::Bind(&PeerConnection::ReconfigurePortAllocator_n, this,
2695 stun_servers, turn_servers, modified_config.type,
2696 modified_config.ice_candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02002697 modified_config.prune_turn_ports,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08002698 modified_config.turn_customizer,
2699 modified_config.stun_candidate_keepalive_interval))) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002700 RTC_LOG(LS_ERROR) << "Failed to apply configuration to PortAllocator.";
deadbeef293e9262017-01-11 12:28:30 -08002701 return SafeSetError(RTCErrorType::INTERNAL_ERROR, error);
2702 }
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07002703
deadbeefd1a38b52016-12-10 13:15:33 -08002704 // As described in JSEP, calling setConfiguration with new ICE servers or
2705 // candidate policy must set a "needs-ice-restart" bit so that the next offer
2706 // triggers an ICE restart which will pick up the changes.
deadbeef293e9262017-01-11 12:28:30 -08002707 if (modified_config.servers != configuration_.servers ||
2708 modified_config.type != configuration_.type ||
2709 modified_config.prune_turn_ports != configuration_.prune_turn_ports) {
Steve Antond25da372017-11-06 14:50:29 -08002710 transport_controller_->SetNeedsIceRestartFlag();
deadbeefd1a38b52016-12-10 13:15:33 -08002711 }
skvladd1f5fda2017-02-03 16:54:05 -08002712
Qingsi Wang9c98f0c2018-02-15 15:10:59 -08002713 transport_controller_->SetIceConfig(ParseIceConfig(modified_config));
skvladd1f5fda2017-02-03 16:54:05 -08002714
deadbeef293e9262017-01-11 12:28:30 -08002715 configuration_ = modified_config;
2716 return SafeSetError(RTCErrorType::NONE, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00002717}
2718
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002719bool PeerConnection::AddIceCandidate(
2720 const IceCandidateInterface* ice_candidate) {
Peter Boström1a9d6152015-12-08 22:15:17 +01002721 TRACE_EVENT0("webrtc", "PeerConnection::AddIceCandidate");
zhihuang29ff8442016-07-27 11:07:25 -07002722 if (IsClosed()) {
2723 return false;
2724 }
Steve Antond25da372017-11-06 14:50:29 -08002725
2726 if (!remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002727 RTC_LOG(LS_ERROR) << "ProcessIceMessage: ICE candidates can't be added "
Jonas Olsson45cc8902018-02-13 10:37:07 +01002728 "without any remote session description.";
Steve Antond25da372017-11-06 14:50:29 -08002729 return false;
2730 }
2731
2732 if (!ice_candidate) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002733 RTC_LOG(LS_ERROR) << "ProcessIceMessage: Candidate is NULL.";
Steve Antond25da372017-11-06 14:50:29 -08002734 return false;
2735 }
2736
2737 bool valid = false;
2738 bool ready = ReadyToUseRemoteCandidate(ice_candidate, nullptr, &valid);
2739 if (!valid) {
2740 return false;
2741 }
2742
2743 // Add this candidate to the remote session description.
2744 if (!mutable_remote_description()->AddCandidate(ice_candidate)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002745 RTC_LOG(LS_ERROR) << "ProcessIceMessage: Candidate cannot be used.";
Steve Antond25da372017-11-06 14:50:29 -08002746 return false;
2747 }
2748
2749 if (ready) {
2750 return UseCandidate(ice_candidate);
2751 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002752 RTC_LOG(LS_INFO) << "ProcessIceMessage: Not ready to use candidate.";
Steve Antond25da372017-11-06 14:50:29 -08002753 return true;
2754 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002755}
2756
Honghai Zhang7fb69db2016-03-14 11:59:18 -07002757bool PeerConnection::RemoveIceCandidates(
2758 const std::vector<cricket::Candidate>& candidates) {
2759 TRACE_EVENT0("webrtc", "PeerConnection::RemoveIceCandidates");
Steve Antond25da372017-11-06 14:50:29 -08002760 if (!remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002761 RTC_LOG(LS_ERROR) << "RemoveRemoteIceCandidates: ICE candidates can't be "
Jonas Olsson45cc8902018-02-13 10:37:07 +01002762 "removed without any remote session description.";
Steve Antond25da372017-11-06 14:50:29 -08002763 return false;
2764 }
2765
2766 if (candidates.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002767 RTC_LOG(LS_ERROR) << "RemoveRemoteIceCandidates: candidates are empty.";
Steve Antond25da372017-11-06 14:50:29 -08002768 return false;
2769 }
2770
2771 size_t number_removed =
2772 mutable_remote_description()->RemoveCandidates(candidates);
2773 if (number_removed != candidates.size()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002774 RTC_LOG(LS_ERROR)
2775 << "RemoveRemoteIceCandidates: Failed to remove candidates. "
Jonas Olsson45cc8902018-02-13 10:37:07 +01002776 "Requested "
2777 << candidates.size() << " but only " << number_removed
Mirko Bonadei675513b2017-11-09 11:09:25 +01002778 << " are removed.";
Steve Antond25da372017-11-06 14:50:29 -08002779 }
2780
2781 // Remove the candidates from the transport controller.
2782 std::string error;
2783 bool res = transport_controller_->RemoveRemoteCandidates(candidates, &error);
2784 if (!res && !error.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002785 RTC_LOG(LS_ERROR) << "Error when removing remote candidates: " << error;
Steve Antond25da372017-11-06 14:50:29 -08002786 }
2787 return true;
Honghai Zhang7fb69db2016-03-14 11:59:18 -07002788}
2789
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00002790void PeerConnection::RegisterUMAObserver(UMAObserver* observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +01002791 TRACE_EVENT0("webrtc", "PeerConnection::RegisterUmaObserver");
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00002792 uma_observer_ = observer;
guoweis@webrtc.org7169afd2014-12-04 17:59:29 +00002793
Steve Anton75737c02017-11-06 10:37:17 -08002794 if (transport_controller()) {
2795 transport_controller()->SetMetricsObserver(uma_observer_);
guoweis@webrtc.org7169afd2014-12-04 17:59:29 +00002796 }
2797
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00002798 // Send information about IPv4/IPv6 status.
deadbeef293e9262017-01-11 12:28:30 -08002799 if (uma_observer_) {
Honghai Zhangd93f50c2016-10-05 11:47:22 -07002800 port_allocator_->SetMetricsObserver(uma_observer_);
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00002801 if (port_allocator_->flags() & cricket::PORTALLOCATOR_ENABLE_IPV6) {
Guo-wei Shiehdfbe6792015-09-03 17:12:07 -07002802 uma_observer_->IncrementEnumCounter(
2803 kEnumCounterAddressFamily, kPeerConnection_IPv6,
2804 kPeerConnectionAddressFamilyCounter_Max);
mallinath@webrtc.orgb445f262014-05-23 22:19:37 +00002805 } else {
Guo-wei Shiehdfbe6792015-09-03 17:12:07 -07002806 uma_observer_->IncrementEnumCounter(
2807 kEnumCounterAddressFamily, kPeerConnection_IPv4,
2808 kPeerConnectionAddressFamilyCounter_Max);
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00002809 }
Harald Alvestrand5dbb5862018-02-13 23:48:00 +01002810 // Send information about the requested SDP semantics.
2811 switch (configuration_.sdp_semantics) {
2812 case SdpSemantics::kDefault:
2813 uma_observer_->IncrementEnumCounter(kEnumCounterSdpSemanticRequested,
2814 kSdpSemanticRequestDefault,
2815 kSdpSemanticRequestMax);
2816
2817 break;
2818 case SdpSemantics::kPlanB:
2819 uma_observer_->IncrementEnumCounter(kEnumCounterSdpSemanticRequested,
2820 kSdpSemanticRequestPlanB,
2821 kSdpSemanticRequestMax);
2822 break;
2823 case SdpSemantics::kUnifiedPlan:
2824 uma_observer_->IncrementEnumCounter(kEnumCounterSdpSemanticRequested,
2825 kSdpSemanticRequestUnifiedPlan,
2826 kSdpSemanticRequestMax);
2827 break;
2828 default:
2829 RTC_NOTREACHED();
2830 }
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00002831 }
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00002832}
2833
zstein4b979802017-06-02 14:37:37 -07002834RTCError PeerConnection::SetBitrate(const BitrateParameters& bitrate) {
Steve Anton978b8762017-09-29 12:15:02 -07002835 if (!worker_thread()->IsCurrent()) {
2836 return worker_thread()->Invoke<RTCError>(
zstein4b979802017-06-02 14:37:37 -07002837 RTC_FROM_HERE, rtc::Bind(&PeerConnection::SetBitrate, this, bitrate));
2838 }
2839
2840 const bool has_min = static_cast<bool>(bitrate.min_bitrate_bps);
2841 const bool has_current = static_cast<bool>(bitrate.current_bitrate_bps);
2842 const bool has_max = static_cast<bool>(bitrate.max_bitrate_bps);
2843 if (has_min && *bitrate.min_bitrate_bps < 0) {
2844 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2845 "min_bitrate_bps <= 0");
2846 }
2847 if (has_current) {
2848 if (has_min && *bitrate.current_bitrate_bps < *bitrate.min_bitrate_bps) {
2849 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2850 "current_bitrate_bps < min_bitrate_bps");
2851 } else if (*bitrate.current_bitrate_bps < 0) {
2852 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2853 "curent_bitrate_bps < 0");
2854 }
2855 }
2856 if (has_max) {
2857 if (has_current &&
2858 *bitrate.max_bitrate_bps < *bitrate.current_bitrate_bps) {
2859 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2860 "max_bitrate_bps < current_bitrate_bps");
2861 } else if (has_min && *bitrate.max_bitrate_bps < *bitrate.min_bitrate_bps) {
2862 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2863 "max_bitrate_bps < min_bitrate_bps");
2864 } else if (*bitrate.max_bitrate_bps < 0) {
2865 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2866 "max_bitrate_bps < 0");
2867 }
2868 }
2869
Lu Liue4bf6002018-02-20 19:16:26 +00002870 Call::Config::BitrateConfigMask mask;
zstein4b979802017-06-02 14:37:37 -07002871 mask.min_bitrate_bps = bitrate.min_bitrate_bps;
2872 mask.start_bitrate_bps = bitrate.current_bitrate_bps;
2873 mask.max_bitrate_bps = bitrate.max_bitrate_bps;
2874
2875 RTC_DCHECK(call_.get());
2876 call_->SetBitrateConfigMask(mask);
2877
2878 return RTCError::OK();
2879}
2880
Alex Narest78609d52017-10-20 10:37:47 +02002881void PeerConnection::SetBitrateAllocationStrategy(
2882 std::unique_ptr<rtc::BitrateAllocationStrategy>
2883 bitrate_allocation_strategy) {
2884 rtc::Thread* worker_thread = factory_->worker_thread();
2885 if (!worker_thread->IsCurrent()) {
2886 rtc::BitrateAllocationStrategy* strategy_raw =
2887 bitrate_allocation_strategy.release();
2888 auto functor = [this, strategy_raw]() {
2889 call_->SetBitrateAllocationStrategy(
2890 rtc::WrapUnique<rtc::BitrateAllocationStrategy>(strategy_raw));
2891 };
2892 worker_thread->Invoke<void>(RTC_FROM_HERE, functor);
2893 return;
2894 }
2895 RTC_DCHECK(call_.get());
2896 call_->SetBitrateAllocationStrategy(std::move(bitrate_allocation_strategy));
2897}
2898
henrika5f6bf242017-11-01 11:06:56 +01002899void PeerConnection::SetAudioPlayout(bool playout) {
2900 if (!worker_thread()->IsCurrent()) {
2901 worker_thread()->Invoke<void>(
2902 RTC_FROM_HERE,
2903 rtc::Bind(&PeerConnection::SetAudioPlayout, this, playout));
2904 return;
2905 }
2906 auto audio_state =
2907 factory_->channel_manager()->media_engine()->GetAudioState();
2908 audio_state->SetPlayout(playout);
2909}
2910
2911void PeerConnection::SetAudioRecording(bool recording) {
2912 if (!worker_thread()->IsCurrent()) {
2913 worker_thread()->Invoke<void>(
2914 RTC_FROM_HERE,
2915 rtc::Bind(&PeerConnection::SetAudioRecording, this, recording));
2916 return;
2917 }
2918 auto audio_state =
2919 factory_->channel_manager()->media_engine()->GetAudioState();
2920 audio_state->SetRecording(recording);
2921}
2922
Steve Anton8c0f7a72017-10-03 10:03:10 -07002923std::unique_ptr<rtc::SSLCertificate>
2924PeerConnection::GetRemoteAudioSSLCertificate() {
Steve Antonafb0bb72018-02-20 11:35:37 -08002925 auto audio_transceiver = GetFirstAudioTransceiver();
2926 if (!audio_transceiver || !audio_transceiver->internal()->channel()) {
Steve Anton8c0f7a72017-10-03 10:03:10 -07002927 return nullptr;
2928 }
Steve Antonafb0bb72018-02-20 11:35:37 -08002929 return GetRemoteSSLCertificate(
2930 audio_transceiver->internal()->channel()->transport_name());
Steve Anton8c0f7a72017-10-03 10:03:10 -07002931}
2932
Zhi Huang70b820f2018-01-27 14:16:15 -08002933std::unique_ptr<rtc::SSLCertChain>
2934PeerConnection::GetRemoteAudioSSLCertChain() {
Steve Antonafb0bb72018-02-20 11:35:37 -08002935 auto audio_transceiver = GetFirstAudioTransceiver();
2936 if (!audio_transceiver || !audio_transceiver->internal()->channel()) {
Zhi Huang70b820f2018-01-27 14:16:15 -08002937 return nullptr;
2938 }
Zhi Huang70b820f2018-01-27 14:16:15 -08002939 return transport_controller_->GetRemoteSSLCertChain(
Steve Antonafb0bb72018-02-20 11:35:37 -08002940 audio_transceiver->internal()->channel()->transport_name());
2941}
2942
2943rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2944PeerConnection::GetFirstAudioTransceiver() const {
2945 for (auto transceiver : transceivers_) {
2946 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
2947 return transceiver;
2948 }
2949 }
2950 return nullptr;
Zhi Huang70b820f2018-01-27 14:16:15 -08002951}
2952
ivoc14d5dbe2016-07-04 07:06:55 -07002953bool PeerConnection::StartRtcEventLog(rtc::PlatformFile file,
2954 int64_t max_size_bytes) {
Elad Alon99c3fe52017-10-13 16:29:40 +02002955 // TODO(eladalon): It would be better to not allow negative values into PC.
2956 const size_t max_size = (max_size_bytes < 0)
2957 ? RtcEventLog::kUnlimitedOutput
2958 : rtc::saturated_cast<size_t>(max_size_bytes);
2959 return StartRtcEventLog(
Bjorn Tereliusde939432017-11-20 17:38:14 +01002960 rtc::MakeUnique<RtcEventLogOutputFile>(file, max_size),
2961 webrtc::RtcEventLog::kImmediateOutput);
Elad Alon99c3fe52017-10-13 16:29:40 +02002962}
2963
Bjorn Tereliusde939432017-11-20 17:38:14 +01002964bool PeerConnection::StartRtcEventLog(std::unique_ptr<RtcEventLogOutput> output,
2965 int64_t output_period_ms) {
Karl Wibergd6b48192017-10-16 23:01:06 +02002966 // TODO(eladalon): In C++14, this can be done with a lambda.
2967 struct Functor {
Bjorn Tereliusde939432017-11-20 17:38:14 +01002968 bool operator()() {
2969 return pc->StartRtcEventLog_w(std::move(output), output_period_ms);
2970 }
Karl Wibergd6b48192017-10-16 23:01:06 +02002971 PeerConnection* const pc;
2972 std::unique_ptr<RtcEventLogOutput> output;
Bjorn Tereliusde939432017-11-20 17:38:14 +01002973 const int64_t output_period_ms;
Elad Alon99c3fe52017-10-13 16:29:40 +02002974 };
Bjorn Tereliusde939432017-11-20 17:38:14 +01002975 return worker_thread()->Invoke<bool>(
2976 RTC_FROM_HERE, Functor{this, std::move(output), output_period_ms});
ivoc14d5dbe2016-07-04 07:06:55 -07002977}
2978
2979void PeerConnection::StopRtcEventLog() {
Steve Anton978b8762017-09-29 12:15:02 -07002980 worker_thread()->Invoke<void>(
ivoc14d5dbe2016-07-04 07:06:55 -07002981 RTC_FROM_HERE, rtc::Bind(&PeerConnection::StopRtcEventLog_w, this));
2982}
2983
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002984const SessionDescriptionInterface* PeerConnection::local_description() const {
Steve Anton75737c02017-11-06 10:37:17 -08002985 return pending_local_description_ ? pending_local_description_.get()
2986 : current_local_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002987}
2988
2989const SessionDescriptionInterface* PeerConnection::remote_description() const {
Steve Anton75737c02017-11-06 10:37:17 -08002990 return pending_remote_description_ ? pending_remote_description_.get()
2991 : current_remote_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002992}
2993
deadbeeffe4a8a42016-12-20 17:56:17 -08002994const SessionDescriptionInterface* PeerConnection::current_local_description()
2995 const {
Steve Anton75737c02017-11-06 10:37:17 -08002996 return current_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08002997}
2998
2999const SessionDescriptionInterface* PeerConnection::current_remote_description()
3000 const {
Steve Anton75737c02017-11-06 10:37:17 -08003001 return current_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003002}
3003
3004const SessionDescriptionInterface* PeerConnection::pending_local_description()
3005 const {
Steve Anton75737c02017-11-06 10:37:17 -08003006 return pending_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003007}
3008
3009const SessionDescriptionInterface* PeerConnection::pending_remote_description()
3010 const {
Steve Anton75737c02017-11-06 10:37:17 -08003011 return pending_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003012}
3013
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003014void PeerConnection::Close() {
Peter Boström1a9d6152015-12-08 22:15:17 +01003015 TRACE_EVENT0("webrtc", "PeerConnection::Close");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003016 // Update stats here so that we have the most recent stats for tracks and
3017 // streams before the channels are closed.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00003018 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003019
Steve Anton75737c02017-11-06 10:37:17 -08003020 ChangeSignalingState(PeerConnectionInterface::kClosed);
Steve Anton3fe1b152017-12-12 10:20:08 -08003021
Steve Anton8af21862017-12-15 11:20:13 -08003022 for (auto transceiver : transceivers_) {
3023 transceiver->Stop();
3024 }
3025 DestroyAllChannels();
Steve Anton75737c02017-11-06 10:37:17 -08003026
Qingsi Wang93a84392018-01-30 17:13:09 -08003027 // The event log is used in the transport controller, which must be outlived
3028 // by the former. CreateOffer by the peer connection is implemented
3029 // asynchronously and if the peer connection is closed without resetting the
3030 // WebRTC session description factory, the session description factory would
3031 // call the transport controller.
3032 webrtc_session_desc_factory_.reset();
3033 transport_controller_.reset();
3034
deadbeef42a42632017-03-10 15:18:00 -08003035 network_thread()->Invoke<void>(
3036 RTC_FROM_HERE,
3037 rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
3038 port_allocator_.get()));
nisseeaabdf62017-05-05 02:23:02 -07003039
Steve Anton978b8762017-09-29 12:15:02 -07003040 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
eladalon248fd4f2017-09-06 05:18:15 -07003041 call_.reset();
3042 // The event log must outlive call (and any other object that uses it).
3043 event_log_.reset();
3044 });
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003045}
3046
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003047void PeerConnection::OnMessage(rtc::Message* msg) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003048 switch (msg->message_id) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003049 case MSG_SET_SESSIONDESCRIPTION_SUCCESS: {
3050 SetSessionDescriptionMsg* param =
3051 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
3052 param->observer->OnSuccess();
3053 delete param;
3054 break;
3055 }
3056 case MSG_SET_SESSIONDESCRIPTION_FAILED: {
3057 SetSessionDescriptionMsg* param =
3058 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
3059 param->observer->OnFailure(param->error);
3060 delete param;
3061 break;
3062 }
deadbeefab9b2d12015-10-14 11:33:11 -07003063 case MSG_CREATE_SESSIONDESCRIPTION_FAILED: {
3064 CreateSessionDescriptionMsg* param =
3065 static_cast<CreateSessionDescriptionMsg*>(msg->pdata);
3066 param->observer->OnFailure(param->error);
3067 delete param;
3068 break;
3069 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003070 case MSG_GETSTATS: {
3071 GetStatsMsg* param = static_cast<GetStatsMsg*>(msg->pdata);
nissee8abe3e2017-01-18 05:00:34 -08003072 StatsReports reports;
3073 stats_->GetStats(param->track, &reports);
3074 param->observer->OnComplete(reports);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003075 delete param;
3076 break;
3077 }
deadbeefbd292462015-12-14 18:15:29 -08003078 case MSG_FREE_DATACHANNELS: {
3079 sctp_data_channels_to_free_.clear();
3080 break;
3081 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003082 default:
nisseeb4ca4e2017-01-12 02:24:27 -08003083 RTC_NOTREACHED() << "Not implemented";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003084 break;
3085 }
3086}
3087
Steve Antonafb0bb72018-02-20 11:35:37 -08003088cricket::VoiceMediaChannel* PeerConnection::voice_media_channel() const {
3089 RTC_DCHECK(!IsUnifiedPlan());
3090 auto* voice_channel = static_cast<cricket::VoiceChannel*>(
3091 GetAudioTransceiver()->internal()->channel());
3092 if (voice_channel) {
3093 return voice_channel->media_channel();
3094 } else {
3095 return nullptr;
3096 }
3097}
3098
3099cricket::VideoMediaChannel* PeerConnection::video_media_channel() const {
3100 RTC_DCHECK(!IsUnifiedPlan());
3101 auto* video_channel = static_cast<cricket::VideoChannel*>(
3102 GetVideoTransceiver()->internal()->channel());
3103 if (video_channel) {
3104 return video_channel->media_channel();
3105 } else {
3106 return nullptr;
3107 }
3108}
3109
Steve Anton4171afb2017-11-20 10:20:22 -08003110void PeerConnection::CreateAudioReceiver(
3111 MediaStreamInterface* stream,
3112 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01003113 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
3114 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Steve Antond3679212018-01-17 17:41:02 -08003115 auto* audio_receiver = new AudioRtpReceiver(
3116 worker_thread(), remote_sender_info.sender_id, streams);
Steve Anton57858b32018-02-15 15:19:50 -08003117 audio_receiver->SetVoiceMediaChannel(voice_media_channel());
Steve Antond3679212018-01-17 17:41:02 -08003118 audio_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
3119 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
3120 signaling_thread(), audio_receiver);
Steve Anton4171afb2017-11-20 10:20:22 -08003121 GetAudioTransceiver()->internal()->AddReceiver(receiver);
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01003122 observer_->OnAddTrack(receiver, std::move(streams));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003123}
3124
Steve Anton4171afb2017-11-20 10:20:22 -08003125void PeerConnection::CreateVideoReceiver(
3126 MediaStreamInterface* stream,
3127 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01003128 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
3129 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Steve Antond3679212018-01-17 17:41:02 -08003130 auto* video_receiver = new VideoRtpReceiver(
3131 worker_thread(), remote_sender_info.sender_id, streams);
Steve Anton57858b32018-02-15 15:19:50 -08003132 video_receiver->SetVideoMediaChannel(video_media_channel());
Steve Antond3679212018-01-17 17:41:02 -08003133 video_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
3134 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
3135 signaling_thread(), video_receiver);
Steve Anton4171afb2017-11-20 10:20:22 -08003136 GetVideoTransceiver()->internal()->AddReceiver(receiver);
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01003137 observer_->OnAddTrack(receiver, std::move(streams));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003138}
3139
deadbeef70ab1a12015-09-28 16:53:55 -07003140// TODO(deadbeef): Keep RtpReceivers around even if track goes away in remote
3141// description.
Henrik Boström933d8b02017-10-10 10:05:16 -07003142rtc::scoped_refptr<RtpReceiverInterface> PeerConnection::RemoveAndStopReceiver(
Steve Anton4171afb2017-11-20 10:20:22 -08003143 const RtpSenderInfo& remote_sender_info) {
3144 auto receiver = FindReceiverById(remote_sender_info.sender_id);
3145 if (!receiver) {
3146 RTC_LOG(LS_WARNING) << "RtpReceiver for track with id "
3147 << remote_sender_info.sender_id << " doesn't exist.";
Henrik Boström933d8b02017-10-10 10:05:16 -07003148 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07003149 }
Steve Anton4171afb2017-11-20 10:20:22 -08003150 if (receiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
3151 GetAudioTransceiver()->internal()->RemoveReceiver(receiver);
3152 } else {
3153 GetVideoTransceiver()->internal()->RemoveReceiver(receiver);
3154 }
Henrik Boström933d8b02017-10-10 10:05:16 -07003155 return receiver;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003156}
3157
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003158void PeerConnection::AddAudioTrack(AudioTrackInterface* track,
3159 MediaStreamInterface* stream) {
3160 RTC_DCHECK(!IsClosed());
3161 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003162 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003163 // We already have a sender for this track, so just change the stream_id
3164 // so that it's correct in the next call to CreateOffer.
Steve Anton4171afb2017-11-20 10:20:22 -08003165 sender->internal()->set_stream_id(stream->label());
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003166 return;
3167 }
3168
3169 // Normal case; we've never seen this track before.
Steve Anton02ee47c2018-01-10 16:26:06 -08003170 auto new_sender =
3171 CreateSender(cricket::MEDIA_TYPE_AUDIO, track, {stream->label()});
Steve Anton57858b32018-02-15 15:19:50 -08003172 new_sender->internal()->SetVoiceMediaChannel(voice_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08003173 GetAudioTransceiver()->internal()->AddSender(new_sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003174 // If the sender has already been configured in SDP, we call SetSsrc,
3175 // which will connect the sender to the underlying transport. This can
3176 // occur if a local session description that contains the ID of the sender
3177 // is set before AddStream is called. It can also occur if the local
3178 // session description is not changed and RemoveStream is called, and
3179 // later AddStream is called again with the same stream.
Steve Anton4171afb2017-11-20 10:20:22 -08003180 const RtpSenderInfo* sender_info =
3181 FindSenderInfo(local_audio_sender_infos_, stream->label(), track->id());
3182 if (sender_info) {
3183 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003184 }
3185}
3186
3187// TODO(deadbeef): Don't destroy RtpSenders here; they should be kept around
3188// indefinitely, when we have unified plan SDP.
3189void PeerConnection::RemoveAudioTrack(AudioTrackInterface* track,
3190 MediaStreamInterface* stream) {
3191 RTC_DCHECK(!IsClosed());
3192 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003193 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003194 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
3195 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003196 return;
3197 }
Steve Anton4171afb2017-11-20 10:20:22 -08003198 GetAudioTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003199}
3200
3201void PeerConnection::AddVideoTrack(VideoTrackInterface* track,
3202 MediaStreamInterface* stream) {
3203 RTC_DCHECK(!IsClosed());
3204 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003205 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003206 // We already have a sender for this track, so just change the stream_id
3207 // so that it's correct in the next call to CreateOffer.
Steve Anton4171afb2017-11-20 10:20:22 -08003208 sender->internal()->set_stream_id(stream->label());
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003209 return;
3210 }
3211
3212 // Normal case; we've never seen this track before.
Steve Anton02ee47c2018-01-10 16:26:06 -08003213 auto new_sender =
3214 CreateSender(cricket::MEDIA_TYPE_VIDEO, track, {stream->label()});
Steve Anton57858b32018-02-15 15:19:50 -08003215 new_sender->internal()->SetVideoMediaChannel(video_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08003216 GetVideoTransceiver()->internal()->AddSender(new_sender);
3217 const RtpSenderInfo* sender_info =
3218 FindSenderInfo(local_video_sender_infos_, stream->label(), track->id());
3219 if (sender_info) {
3220 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003221 }
3222}
3223
3224void PeerConnection::RemoveVideoTrack(VideoTrackInterface* track,
3225 MediaStreamInterface* stream) {
3226 RTC_DCHECK(!IsClosed());
3227 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003228 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003229 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
3230 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003231 return;
3232 }
Steve Anton4171afb2017-11-20 10:20:22 -08003233 GetVideoTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003234}
3235
Steve Antonba818672017-11-06 10:21:57 -08003236void PeerConnection::SetIceConnectionState(IceConnectionState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07003237 RTC_DCHECK(signaling_thread()->IsCurrent());
Steve Antonba818672017-11-06 10:21:57 -08003238 if (ice_connection_state_ == new_state) {
3239 return;
3240 }
3241
deadbeefcbecd352015-09-23 11:50:27 -07003242 // After transitioning to "closed", ignore any additional states from
Steve Antonba818672017-11-06 10:21:57 -08003243 // TransportController (such as "disconnected").
deadbeefab9b2d12015-10-14 11:33:11 -07003244 if (IsClosed()) {
deadbeefcbecd352015-09-23 11:50:27 -07003245 return;
3246 }
Steve Antonba818672017-11-06 10:21:57 -08003247
Mirko Bonadei675513b2017-11-09 11:09:25 +01003248 RTC_LOG(LS_INFO) << "Changing IceConnectionState " << ice_connection_state_
3249 << " => " << new_state;
Steve Antonba818672017-11-06 10:21:57 -08003250 RTC_DCHECK(ice_connection_state_ !=
3251 PeerConnectionInterface::kIceConnectionClosed);
3252
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003253 ice_connection_state_ = new_state;
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00003254 observer_->OnIceConnectionChange(ice_connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003255}
3256
3257void PeerConnection::OnIceGatheringChange(
3258 PeerConnectionInterface::IceGatheringState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07003259 RTC_DCHECK(signaling_thread()->IsCurrent());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003260 if (IsClosed()) {
3261 return;
3262 }
3263 ice_gathering_state_ = new_state;
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00003264 observer_->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003265}
3266
jbauch81bf7b02017-03-25 08:31:12 -07003267void PeerConnection::OnIceCandidate(
3268 std::unique_ptr<IceCandidateInterface> candidate) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07003269 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07003270 if (IsClosed()) {
3271 return;
3272 }
jbauch81bf7b02017-03-25 08:31:12 -07003273 observer_->OnIceCandidate(candidate.get());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003274}
3275
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003276void PeerConnection::OnIceCandidatesRemoved(
3277 const std::vector<cricket::Candidate>& candidates) {
3278 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07003279 if (IsClosed()) {
3280 return;
3281 }
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003282 observer_->OnIceCandidatesRemoved(candidates);
3283}
3284
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003285void PeerConnection::ChangeSignalingState(
3286 PeerConnectionInterface::SignalingState signaling_state) {
Steve Antonba818672017-11-06 10:21:57 -08003287 RTC_DCHECK(signaling_thread()->IsCurrent());
3288 if (signaling_state_ == signaling_state) {
3289 return;
3290 }
Mirko Bonadei675513b2017-11-09 11:09:25 +01003291 RTC_LOG(LS_INFO) << "Session: " << session_id() << " Old state: "
3292 << GetSignalingStateString(signaling_state_)
3293 << " New state: "
3294 << GetSignalingStateString(signaling_state);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003295 signaling_state_ = signaling_state;
3296 if (signaling_state == kClosed) {
3297 ice_connection_state_ = kIceConnectionClosed;
3298 observer_->OnIceConnectionChange(ice_connection_state_);
3299 if (ice_gathering_state_ != kIceGatheringComplete) {
3300 ice_gathering_state_ = kIceGatheringComplete;
3301 observer_->OnIceGatheringChange(ice_gathering_state_);
3302 }
3303 }
3304 observer_->OnSignalingChange(signaling_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003305}
3306
deadbeefeb459812015-12-15 19:24:43 -08003307void PeerConnection::OnAudioTrackAdded(AudioTrackInterface* track,
3308 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003309 if (IsClosed()) {
3310 return;
3311 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003312 AddAudioTrack(track, stream);
3313 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003314}
3315
deadbeefeb459812015-12-15 19:24:43 -08003316void PeerConnection::OnAudioTrackRemoved(AudioTrackInterface* track,
3317 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003318 if (IsClosed()) {
3319 return;
3320 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003321 RemoveAudioTrack(track, stream);
3322 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003323}
3324
3325void PeerConnection::OnVideoTrackAdded(VideoTrackInterface* track,
3326 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003327 if (IsClosed()) {
3328 return;
3329 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003330 AddVideoTrack(track, stream);
3331 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003332}
3333
3334void PeerConnection::OnVideoTrackRemoved(VideoTrackInterface* track,
3335 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003336 if (IsClosed()) {
3337 return;
3338 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003339 RemoveVideoTrack(track, stream);
3340 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003341}
3342
Henrik Boström31638672017-11-23 17:48:32 +01003343void PeerConnection::PostSetSessionDescriptionSuccess(
3344 SetSessionDescriptionObserver* observer) {
3345 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
3346 signaling_thread()->Post(RTC_FROM_HERE, this,
3347 MSG_SET_SESSIONDESCRIPTION_SUCCESS, msg);
3348}
3349
deadbeefab9b2d12015-10-14 11:33:11 -07003350void PeerConnection::PostSetSessionDescriptionFailure(
3351 SetSessionDescriptionObserver* observer,
3352 const std::string& error) {
3353 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
3354 msg->error = error;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07003355 signaling_thread()->Post(RTC_FROM_HERE, this,
3356 MSG_SET_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07003357}
3358
3359void PeerConnection::PostCreateSessionDescriptionFailure(
3360 CreateSessionDescriptionObserver* observer,
3361 const std::string& error) {
3362 CreateSessionDescriptionMsg* msg = new CreateSessionDescriptionMsg(observer);
3363 msg->error = error;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07003364 signaling_thread()->Post(RTC_FROM_HERE, this,
3365 MSG_CREATE_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07003366}
3367
zhihuang1c378ed2017-08-17 14:10:50 -07003368void PeerConnection::GetOptionsForOffer(
Steve Antondcc3c022017-12-22 16:02:54 -08003369 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
deadbeefab9b2d12015-10-14 11:33:11 -07003370 cricket::MediaSessionOptions* session_options) {
Steve Antondcc3c022017-12-22 16:02:54 -08003371 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
zhihuang1c378ed2017-08-17 14:10:50 -07003372
Steve Antondcc3c022017-12-22 16:02:54 -08003373 if (IsUnifiedPlan()) {
3374 GetOptionsForUnifiedPlanOffer(offer_answer_options, session_options);
3375 } else {
3376 GetOptionsForPlanBOffer(offer_answer_options, session_options);
3377 }
3378
Steve Antonfa2260d2017-12-28 16:38:23 -08003379 // Intentionally unset the data channel type for RTP data channel with the
3380 // second condition. Otherwise the RTP data channels would be successfully
3381 // negotiated by default and the unit tests in WebRtcDataBrowserTest will fail
3382 // when building with chromium. We want to leave RTP data channels broken, so
3383 // people won't try to use them.
3384 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
3385 session_options->data_channel_type = data_channel_type();
3386 }
3387
Steve Antondcc3c022017-12-22 16:02:54 -08003388 // Apply ICE restart flag and renomination flag.
3389 for (auto& options : session_options->media_description_options) {
3390 options.transport_options.ice_restart = offer_answer_options.ice_restart;
3391 options.transport_options.enable_ice_renomination =
3392 configuration_.enable_ice_renomination;
3393 }
3394
3395 session_options->rtcp_cname = rtcp_cname_;
3396 session_options->crypto_options = factory_->options().crypto_options;
Steve Antone831b8c2018-02-01 12:22:16 -08003397 session_options->is_unified_plan = IsUnifiedPlan();
Steve Antondcc3c022017-12-22 16:02:54 -08003398}
3399
3400void PeerConnection::GetOptionsForPlanBOffer(
3401 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
3402 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07003403 // Figure out transceiver directional preferences.
3404 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
3405 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
3406
3407 // By default, generate sendrecv/recvonly m= sections.
3408 bool recv_audio = true;
3409 bool recv_video = true;
3410
3411 // By default, only offer a new m= section if we have media to send with it.
3412 bool offer_new_audio_description = send_audio;
3413 bool offer_new_video_description = send_video;
3414 bool offer_new_data_description = HasDataChannels();
3415
3416 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-22 16:02:54 -08003417 if (offer_answer_options.offer_to_receive_audio !=
3418 RTCOfferAnswerOptions::kUndefined) {
3419 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003420 offer_new_audio_description =
Steve Antondcc3c022017-12-22 16:02:54 -08003421 offer_new_audio_description ||
3422 (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003423 }
Steve Antondcc3c022017-12-22 16:02:54 -08003424 if (offer_answer_options.offer_to_receive_video !=
3425 RTCOfferAnswerOptions::kUndefined) {
3426 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003427 offer_new_video_description =
Steve Antondcc3c022017-12-22 16:02:54 -08003428 offer_new_video_description ||
3429 (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003430 }
3431
3432 rtc::Optional<size_t> audio_index;
3433 rtc::Optional<size_t> video_index;
3434 rtc::Optional<size_t> data_index;
3435 // If a current description exists, generate m= sections in the same order,
3436 // using the first audio/video/data section that appears and rejecting
3437 // extraneous ones.
Steve Anton75737c02017-11-06 10:37:17 -08003438 if (local_description()) {
zhihuang1c378ed2017-08-17 14:10:50 -07003439 GenerateMediaDescriptionOptions(
Steve Anton75737c02017-11-06 10:37:17 -08003440 local_description(),
Steve Anton1d03a752017-11-27 14:30:09 -08003441 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
3442 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
3443 &audio_index, &video_index, &data_index, session_options);
deadbeefab9b2d12015-10-14 11:33:11 -07003444 }
3445
zhihuang1c378ed2017-08-17 14:10:50 -07003446 // Add audio/video/data m= sections to the end if needed.
3447 if (!audio_index && offer_new_audio_description) {
3448 session_options->media_description_options.push_back(
3449 cricket::MediaDescriptionOptions(
3450 cricket::MEDIA_TYPE_AUDIO, cricket::CN_AUDIO,
Steve Anton1d03a752017-11-27 14:30:09 -08003451 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
3452 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003453 audio_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07003454 }
zhihuang1c378ed2017-08-17 14:10:50 -07003455 if (!video_index && offer_new_video_description) {
3456 session_options->media_description_options.push_back(
3457 cricket::MediaDescriptionOptions(
3458 cricket::MEDIA_TYPE_VIDEO, cricket::CN_VIDEO,
Steve Anton1d03a752017-11-27 14:30:09 -08003459 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
3460 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003461 video_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07003462 }
zhihuang1c378ed2017-08-17 14:10:50 -07003463 if (!data_index && offer_new_data_description) {
3464 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08003465 GetMediaDescriptionOptionsForActiveData(cricket::CN_DATA));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003466 data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07003467 }
3468
3469 cricket::MediaDescriptionOptions* audio_media_description_options =
3470 !audio_index ? nullptr
3471 : &session_options->media_description_options[*audio_index];
3472 cricket::MediaDescriptionOptions* video_media_description_options =
3473 !video_index ? nullptr
3474 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 14:10:50 -07003475
Steve Anton4171afb2017-11-20 10:20:22 -08003476 AddRtpSenderOptions(GetSendersInternal(), audio_media_description_options,
zhihuang1c378ed2017-08-17 14:10:50 -07003477 video_media_description_options);
Steve Antondcc3c022017-12-22 16:02:54 -08003478}
3479
3480// Find a new MID that is not already in |used_mids|, then add it to |used_mids|
3481// and return a reference to it.
3482// Generated MIDs should be no more than 3 bytes long to take up less space in
3483// the RTP packet.
3484static const std::string& AllocateMid(std::set<std::string>* used_mids) {
3485 RTC_DCHECK(used_mids);
3486 // We're boring: just generate MIDs 0, 1, 2, ...
3487 size_t i = 0;
3488 std::set<std::string>::iterator it;
3489 bool inserted;
3490 do {
3491 std::string mid = rtc::ToString(i++);
3492 auto insert_result = used_mids->insert(mid);
3493 it = insert_result.first;
3494 inserted = insert_result.second;
3495 } while (!inserted);
3496 return *it;
3497}
3498
3499static cricket::MediaDescriptionOptions
3500GetMediaDescriptionOptionsForTransceiver(
3501 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3502 transceiver,
3503 const std::string& mid) {
3504 cricket::MediaDescriptionOptions media_description_options(
Steve Anton69470252018-02-09 11:43:08 -08003505 transceiver->media_type(), mid, transceiver->direction(),
Steve Antondcc3c022017-12-22 16:02:54 -08003506 transceiver->stopped());
Steve Anton5f94aa22018-02-01 10:58:30 -08003507 // This behavior is specified in JSEP. The gist is that:
3508 // 1. The MSID is included if the RtpTransceiver's direction is sendonly or
3509 // sendrecv.
3510 // 2. If the MSID is included, then it must be included in any subsequent
3511 // offer/answer exactly the same until the RtpTransceiver is stopped.
3512 if (!transceiver->stopped() &&
3513 (RtpTransceiverDirectionHasSend(transceiver->direction()) ||
3514 transceiver->internal()->has_ever_been_used_to_send())) {
3515 cricket::SenderOptions sender_options;
3516 sender_options.track_id = transceiver->sender()->id();
3517 sender_options.stream_ids = transceiver->sender()->stream_ids();
3518 // TODO(bugs.webrtc.org/7600): Set num_sim_layers to the number of encodings
3519 // set in the RTP parameters when the transceiver was added.
3520 sender_options.num_sim_layers = 1;
3521 media_description_options.sender_options.push_back(sender_options);
3522 }
Steve Antondcc3c022017-12-22 16:02:54 -08003523 return media_description_options;
3524}
3525
3526void PeerConnection::GetOptionsForUnifiedPlanOffer(
3527 const RTCOfferAnswerOptions& offer_answer_options,
3528 cricket::MediaSessionOptions* session_options) {
3529 // Rules for generating an offer are dictated by JSEP sections 5.2.1 (Initial
3530 // Offers) and 5.2.2 (Subsequent Offers).
3531 RTC_DCHECK_EQ(session_options->media_description_options.size(), 0);
3532 const ContentInfos& local_contents =
3533 (local_description() ? local_description()->description()->contents()
3534 : ContentInfos());
3535 const ContentInfos& remote_contents =
3536 (remote_description() ? remote_description()->description()->contents()
3537 : ContentInfos());
3538 // The mline indices that can be recycled. New transceivers should reuse these
3539 // slots first.
3540 std::queue<size_t> recycleable_mline_indices;
3541 // Track the MIDs used in previous offer/answer exchanges and the current
3542 // offer so that new, unique MIDs are generated.
3543 std::set<std::string> used_mids = seen_mids_;
3544 // First, go through each media section that exists in either the local or
3545 // remote description and generate a media section in this offer for the
3546 // associated transceiver. If a media section can be recycled, generate a
3547 // default, rejected media section here that can be later overwritten.
3548 for (size_t i = 0;
3549 i < std::max(local_contents.size(), remote_contents.size()); ++i) {
3550 // Either |local_content| or |remote_content| is non-null.
3551 const ContentInfo* local_content =
3552 (i < local_contents.size() ? &local_contents[i] : nullptr);
3553 const ContentInfo* remote_content =
3554 (i < remote_contents.size() ? &remote_contents[i] : nullptr);
3555 bool had_been_rejected = (local_content && local_content->rejected) ||
3556 (remote_content && remote_content->rejected);
3557 const std::string& mid =
3558 (local_content ? local_content->name : remote_content->name);
3559 cricket::MediaType media_type =
3560 (local_content ? local_content->media_description()->type()
3561 : remote_content->media_description()->type());
3562 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
3563 media_type == cricket::MEDIA_TYPE_VIDEO) {
3564 auto transceiver = GetAssociatedTransceiver(mid);
3565 RTC_CHECK(transceiver);
3566 // A media section is considered eligible for recycling if it is marked as
3567 // rejected in either the local or remote description.
Seth Hampsonae8a90a2018-02-13 15:33:48 -08003568 if (had_been_rejected && transceiver->stopped()) {
Steve Antondcc3c022017-12-22 16:02:54 -08003569 session_options->media_description_options.push_back(
Steve Anton69470252018-02-09 11:43:08 -08003570 cricket::MediaDescriptionOptions(transceiver->media_type(), mid,
3571 RtpTransceiverDirection::kInactive,
3572 /*stopped=*/true));
Steve Antondcc3c022017-12-22 16:02:54 -08003573 recycleable_mline_indices.push(i);
3574 } else {
3575 session_options->media_description_options.push_back(
3576 GetMediaDescriptionOptionsForTransceiver(transceiver, mid));
3577 // CreateOffer shouldn't really cause any state changes in
3578 // PeerConnection, but we need a way to match new transceivers to new
3579 // media sections in SetLocalDescription and JSEP specifies this is done
3580 // by recording the index of the media section generated for the
3581 // transceiver in the offer.
3582 transceiver->internal()->set_mline_index(i);
3583 }
3584 } else {
3585 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antonfa2260d2017-12-28 16:38:23 -08003586 RTC_CHECK(GetDataMid());
3587 if (had_been_rejected || mid != *GetDataMid()) {
3588 session_options->media_description_options.push_back(
3589 GetMediaDescriptionOptionsForRejectedData(mid));
3590 } else {
3591 session_options->media_description_options.push_back(
3592 GetMediaDescriptionOptionsForActiveData(mid));
3593 }
Steve Antondcc3c022017-12-22 16:02:54 -08003594 }
3595 }
3596 // Next, look for transceivers that are newly added (that is, are not stopped
3597 // and not associated). Reuse media sections marked as recyclable first,
3598 // otherwise append to the end of the offer. New media sections should be
3599 // added in the order they were added to the PeerConnection.
3600 for (auto transceiver : transceivers_) {
3601 if (transceiver->mid() || transceiver->stopped()) {
3602 continue;
3603 }
3604 size_t mline_index;
3605 if (!recycleable_mline_indices.empty()) {
3606 mline_index = recycleable_mline_indices.front();
3607 recycleable_mline_indices.pop();
3608 session_options->media_description_options[mline_index] =
3609 GetMediaDescriptionOptionsForTransceiver(transceiver,
3610 AllocateMid(&used_mids));
3611 } else {
3612 mline_index = session_options->media_description_options.size();
3613 session_options->media_description_options.push_back(
3614 GetMediaDescriptionOptionsForTransceiver(transceiver,
3615 AllocateMid(&used_mids)));
3616 }
3617 // See comment above for why CreateOffer changes the transceiver's state.
3618 transceiver->internal()->set_mline_index(mline_index);
3619 }
Steve Antonfa2260d2017-12-28 16:38:23 -08003620 // Lastly, add a m-section if we have local data channels and an m section
3621 // does not already exist.
3622 if (!GetDataMid() && HasDataChannels()) {
3623 session_options->media_description_options.push_back(
3624 GetMediaDescriptionOptionsForActiveData(AllocateMid(&used_mids)));
3625 }
Steve Antondcc3c022017-12-22 16:02:54 -08003626}
3627
3628void PeerConnection::GetOptionsForAnswer(
3629 const RTCOfferAnswerOptions& offer_answer_options,
3630 cricket::MediaSessionOptions* session_options) {
3631 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
3632
3633 if (IsUnifiedPlan()) {
3634 GetOptionsForUnifiedPlanAnswer(offer_answer_options, session_options);
3635 } else {
3636 GetOptionsForPlanBAnswer(offer_answer_options, session_options);
3637 }
3638
Steve Antonfa2260d2017-12-28 16:38:23 -08003639 // Intentionally unset the data channel type for RTP data channel. Otherwise
3640 // the RTP data channels would be successfully negotiated by default and the
3641 // unit tests in WebRtcDataBrowserTest will fail when building with chromium.
3642 // We want to leave RTP data channels broken, so people won't try to use them.
3643 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
3644 session_options->data_channel_type = data_channel_type();
3645 }
3646
Steve Antondcc3c022017-12-22 16:02:54 -08003647 // Apply ICE renomination flag.
3648 for (auto& options : session_options->media_description_options) {
3649 options.transport_options.enable_ice_renomination =
3650 configuration_.enable_ice_renomination;
3651 }
zhihuang8f65cdf2016-05-06 18:40:30 -07003652
3653 session_options->rtcp_cname = rtcp_cname_;
jbauchcb560652016-08-04 05:20:32 -07003654 session_options->crypto_options = factory_->options().crypto_options;
Steve Antone831b8c2018-02-01 12:22:16 -08003655 session_options->is_unified_plan = IsUnifiedPlan();
deadbeefab9b2d12015-10-14 11:33:11 -07003656}
3657
Steve Antondcc3c022017-12-22 16:02:54 -08003658void PeerConnection::GetOptionsForPlanBAnswer(
3659 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07003660 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07003661 // Figure out transceiver directional preferences.
3662 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
3663 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
3664
3665 // By default, generate sendrecv/recvonly m= sections. The direction is also
3666 // restricted by the direction in the offer.
3667 bool recv_audio = true;
3668 bool recv_video = true;
3669
3670 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-22 16:02:54 -08003671 if (offer_answer_options.offer_to_receive_audio !=
3672 RTCOfferAnswerOptions::kUndefined) {
3673 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
deadbeef0ed85b22016-02-23 17:24:52 -08003674 }
Steve Antondcc3c022017-12-22 16:02:54 -08003675 if (offer_answer_options.offer_to_receive_video !=
3676 RTCOfferAnswerOptions::kUndefined) {
3677 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003678 }
3679
3680 rtc::Optional<size_t> audio_index;
3681 rtc::Optional<size_t> video_index;
3682 rtc::Optional<size_t> data_index;
Steve Antondffead82018-02-06 10:31:29 -08003683
3684 // Generate m= sections that match those in the offer.
3685 // Note that mediasession.cc will handle intersection our preferred
3686 // direction with the offered direction.
3687 GenerateMediaDescriptionOptions(
3688 remote_description(),
3689 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
3690 RtpTransceiverDirectionFromSendRecv(send_video, recv_video), &audio_index,
3691 &video_index, &data_index, session_options);
zhihuang1c378ed2017-08-17 14:10:50 -07003692
3693 cricket::MediaDescriptionOptions* audio_media_description_options =
3694 !audio_index ? nullptr
3695 : &session_options->media_description_options[*audio_index];
3696 cricket::MediaDescriptionOptions* video_media_description_options =
3697 !video_index ? nullptr
3698 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 14:10:50 -07003699
Steve Anton4171afb2017-11-20 10:20:22 -08003700 AddRtpSenderOptions(GetSendersInternal(), audio_media_description_options,
zhihuang1c378ed2017-08-17 14:10:50 -07003701 video_media_description_options);
Steve Antondcc3c022017-12-22 16:02:54 -08003702}
zhihuangaf388472016-11-02 16:49:48 -07003703
Steve Antondcc3c022017-12-22 16:02:54 -08003704void PeerConnection::GetOptionsForUnifiedPlanAnswer(
3705 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
3706 cricket::MediaSessionOptions* session_options) {
3707 // Rules for generating an answer are dictated by JSEP sections 5.3.1 (Initial
3708 // Answers) and 5.3.2 (Subsequent Answers).
3709 RTC_DCHECK(remote_description());
3710 RTC_DCHECK(remote_description()->GetType() == SdpType::kOffer);
3711 for (const ContentInfo& content :
3712 remote_description()->description()->contents()) {
3713 cricket::MediaType media_type = content.media_description()->type();
3714 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
3715 media_type == cricket::MEDIA_TYPE_VIDEO) {
3716 auto transceiver = GetAssociatedTransceiver(content.name);
3717 RTC_CHECK(transceiver);
3718 session_options->media_description_options.push_back(
3719 GetMediaDescriptionOptionsForTransceiver(transceiver, content.name));
3720 } else {
3721 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antondbf9d032018-01-19 15:23:40 -08003722 // Reject all data sections if data channels are disabled.
3723 // Reject a data section if it has already been rejected.
3724 // Reject all data sections except for the first one.
3725 if (data_channel_type_ == cricket::DCT_NONE || content.rejected ||
3726 content.name != *GetDataMid()) {
Steve Antonfa2260d2017-12-28 16:38:23 -08003727 session_options->media_description_options.push_back(
3728 GetMediaDescriptionOptionsForRejectedData(content.name));
3729 } else {
3730 session_options->media_description_options.push_back(
3731 GetMediaDescriptionOptionsForActiveData(content.name));
3732 }
Steve Antondcc3c022017-12-22 16:02:54 -08003733 }
3734 }
htaa2a49d92016-03-04 02:51:39 -08003735}
3736
zhihuang1c378ed2017-08-17 14:10:50 -07003737void PeerConnection::GenerateMediaDescriptionOptions(
3738 const SessionDescriptionInterface* session_desc,
Steve Anton1d03a752017-11-27 14:30:09 -08003739 RtpTransceiverDirection audio_direction,
3740 RtpTransceiverDirection video_direction,
zhihuang1c378ed2017-08-17 14:10:50 -07003741 rtc::Optional<size_t>* audio_index,
3742 rtc::Optional<size_t>* video_index,
3743 rtc::Optional<size_t>* data_index,
htaa2a49d92016-03-04 02:51:39 -08003744 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07003745 for (const cricket::ContentInfo& content :
3746 session_desc->description()->contents()) {
3747 if (IsAudioContent(&content)) {
3748 // If we already have an audio m= section, reject this extra one.
3749 if (*audio_index) {
3750 session_options->media_description_options.push_back(
3751 cricket::MediaDescriptionOptions(
3752 cricket::MEDIA_TYPE_AUDIO, content.name,
Steve Anton1d03a752017-11-27 14:30:09 -08003753 RtpTransceiverDirection::kInactive, true));
zhihuang1c378ed2017-08-17 14:10:50 -07003754 } else {
3755 session_options->media_description_options.push_back(
3756 cricket::MediaDescriptionOptions(
3757 cricket::MEDIA_TYPE_AUDIO, content.name, audio_direction,
Steve Anton1d03a752017-11-27 14:30:09 -08003758 audio_direction == RtpTransceiverDirection::kInactive));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003759 *audio_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07003760 }
3761 } else if (IsVideoContent(&content)) {
3762 // If we already have an video m= section, reject this extra one.
3763 if (*video_index) {
3764 session_options->media_description_options.push_back(
3765 cricket::MediaDescriptionOptions(
3766 cricket::MEDIA_TYPE_VIDEO, content.name,
Steve Anton1d03a752017-11-27 14:30:09 -08003767 RtpTransceiverDirection::kInactive, true));
zhihuang1c378ed2017-08-17 14:10:50 -07003768 } else {
3769 session_options->media_description_options.push_back(
3770 cricket::MediaDescriptionOptions(
3771 cricket::MEDIA_TYPE_VIDEO, content.name, video_direction,
Steve Anton1d03a752017-11-27 14:30:09 -08003772 video_direction == RtpTransceiverDirection::kInactive));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003773 *video_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07003774 }
3775 } else {
3776 RTC_DCHECK(IsDataContent(&content));
3777 // If we already have an data m= section, reject this extra one.
3778 if (*data_index) {
3779 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08003780 GetMediaDescriptionOptionsForRejectedData(content.name));
zhihuang1c378ed2017-08-17 14:10:50 -07003781 } else {
3782 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08003783 GetMediaDescriptionOptionsForActiveData(content.name));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003784 *data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07003785 }
3786 }
htaa2a49d92016-03-04 02:51:39 -08003787 }
deadbeefab9b2d12015-10-14 11:33:11 -07003788}
3789
Steve Antonfa2260d2017-12-28 16:38:23 -08003790cricket::MediaDescriptionOptions
3791PeerConnection::GetMediaDescriptionOptionsForActiveData(
3792 const std::string& mid) const {
3793 // Direction for data sections is meaningless, but legacy endpoints might
3794 // expect sendrecv.
3795 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
3796 RtpTransceiverDirection::kSendRecv,
3797 /*stopped=*/false);
3798 AddRtpDataChannelOptions(rtp_data_channels_, &options);
3799 return options;
3800}
3801
3802cricket::MediaDescriptionOptions
3803PeerConnection::GetMediaDescriptionOptionsForRejectedData(
3804 const std::string& mid) const {
3805 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
3806 RtpTransceiverDirection::kInactive,
3807 /*stopped=*/true);
3808 AddRtpDataChannelOptions(rtp_data_channels_, &options);
3809 return options;
3810}
3811
3812rtc::Optional<std::string> PeerConnection::GetDataMid() const {
3813 switch (data_channel_type_) {
3814 case cricket::DCT_RTP:
3815 if (!rtp_data_channel_) {
3816 return rtc::nullopt;
3817 }
3818 return rtp_data_channel_->content_name();
3819 case cricket::DCT_SCTP:
3820 return sctp_content_name_;
3821 default:
3822 return rtc::nullopt;
3823 }
3824}
3825
Steve Anton4171afb2017-11-20 10:20:22 -08003826void PeerConnection::RemoveSenders(cricket::MediaType media_type) {
3827 UpdateLocalSenders(std::vector<cricket::StreamParams>(), media_type);
3828 UpdateRemoteSendersList(std::vector<cricket::StreamParams>(), false,
deadbeefbda7e0b2015-12-08 17:13:40 -08003829 media_type, nullptr);
deadbeeffaac4972015-11-12 15:33:07 -08003830}
3831
Steve Anton4171afb2017-11-20 10:20:22 -08003832void PeerConnection::UpdateRemoteSendersList(
deadbeefab9b2d12015-10-14 11:33:11 -07003833 const cricket::StreamParamsVec& streams,
Steve Anton4171afb2017-11-20 10:20:22 -08003834 bool default_sender_needed,
deadbeefab9b2d12015-10-14 11:33:11 -07003835 cricket::MediaType media_type,
3836 StreamCollection* new_streams) {
Steve Anton4171afb2017-11-20 10:20:22 -08003837 std::vector<RtpSenderInfo>* current_senders =
3838 GetRemoteSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07003839
Steve Anton4171afb2017-11-20 10:20:22 -08003840 // Find removed senders. I.e., senders where the sender id or ssrc don't match
deadbeeffac06552015-11-25 11:26:01 -08003841 // the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08003842 for (auto sender_it = current_senders->begin();
3843 sender_it != current_senders->end();
3844 /* incremented manually */) {
3845 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07003846 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08003847 cricket::GetStreamBySsrc(streams, info.first_ssrc);
3848 bool sender_exists = params && params->id == info.sender_id;
deadbeefbda7e0b2015-12-08 17:13:40 -08003849 // If this is a default track, and we still need it, don't remove it.
Steve Anton4171afb2017-11-20 10:20:22 -08003850 if ((info.stream_label == kDefaultStreamLabel && default_sender_needed) ||
3851 sender_exists) {
3852 ++sender_it;
deadbeefbda7e0b2015-12-08 17:13:40 -08003853 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08003854 OnRemoteSenderRemoved(info, media_type);
3855 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07003856 }
3857 }
3858
Steve Anton4171afb2017-11-20 10:20:22 -08003859 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07003860 for (const cricket::StreamParams& params : streams) {
3861 // The sync_label is the MediaStream label and the |stream.id| is the
Steve Anton4171afb2017-11-20 10:20:22 -08003862 // sender id.
deadbeefab9b2d12015-10-14 11:33:11 -07003863 const std::string& stream_label = params.sync_label;
Steve Anton4171afb2017-11-20 10:20:22 -08003864 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07003865 uint32_t ssrc = params.first_ssrc();
3866
3867 rtc::scoped_refptr<MediaStreamInterface> stream =
3868 remote_streams_->find(stream_label);
3869 if (!stream) {
3870 // This is a new MediaStream. Create a new remote MediaStream.
perkjd61bf802016-03-24 03:16:19 -07003871 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
3872 MediaStream::Create(stream_label));
deadbeefab9b2d12015-10-14 11:33:11 -07003873 remote_streams_->AddStream(stream);
3874 new_streams->AddStream(stream);
3875 }
3876
Steve Anton4171afb2017-11-20 10:20:22 -08003877 const RtpSenderInfo* sender_info =
3878 FindSenderInfo(*current_senders, stream_label, sender_id);
3879 if (!sender_info) {
3880 current_senders->push_back(RtpSenderInfo(stream_label, sender_id, ssrc));
3881 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07003882 }
3883 }
deadbeefbda7e0b2015-12-08 17:13:40 -08003884
Steve Anton4171afb2017-11-20 10:20:22 -08003885 // Add default sender if necessary.
3886 if (default_sender_needed) {
deadbeefbda7e0b2015-12-08 17:13:40 -08003887 rtc::scoped_refptr<MediaStreamInterface> default_stream =
3888 remote_streams_->find(kDefaultStreamLabel);
3889 if (!default_stream) {
3890 // Create the new default MediaStream.
perkjd61bf802016-03-24 03:16:19 -07003891 default_stream = MediaStreamProxy::Create(
3892 rtc::Thread::Current(), MediaStream::Create(kDefaultStreamLabel));
deadbeefbda7e0b2015-12-08 17:13:40 -08003893 remote_streams_->AddStream(default_stream);
3894 new_streams->AddStream(default_stream);
3895 }
Steve Anton4171afb2017-11-20 10:20:22 -08003896 std::string default_sender_id = (media_type == cricket::MEDIA_TYPE_AUDIO)
3897 ? kDefaultAudioSenderId
3898 : kDefaultVideoSenderId;
3899 const RtpSenderInfo* default_sender_info = FindSenderInfo(
3900 *current_senders, kDefaultStreamLabel, default_sender_id);
3901 if (!default_sender_info) {
3902 current_senders->push_back(
3903 RtpSenderInfo(kDefaultStreamLabel, default_sender_id, 0));
3904 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefbda7e0b2015-12-08 17:13:40 -08003905 }
3906 }
deadbeefab9b2d12015-10-14 11:33:11 -07003907}
3908
Steve Anton4171afb2017-11-20 10:20:22 -08003909void PeerConnection::OnRemoteSenderAdded(const RtpSenderInfo& sender_info,
3910 cricket::MediaType media_type) {
3911 MediaStreamInterface* stream =
3912 remote_streams_->find(sender_info.stream_label);
deadbeefab9b2d12015-10-14 11:33:11 -07003913
3914 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 10:20:22 -08003915 CreateAudioReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07003916 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 10:20:22 -08003917 CreateVideoReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07003918 } else {
nisseeb4ca4e2017-01-12 02:24:27 -08003919 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07003920 }
3921}
3922
Steve Anton4171afb2017-11-20 10:20:22 -08003923void PeerConnection::OnRemoteSenderRemoved(const RtpSenderInfo& sender_info,
3924 cricket::MediaType media_type) {
3925 MediaStreamInterface* stream =
3926 remote_streams_->find(sender_info.stream_label);
deadbeefab9b2d12015-10-14 11:33:11 -07003927
Henrik Boström933d8b02017-10-10 10:05:16 -07003928 rtc::scoped_refptr<RtpReceiverInterface> receiver;
deadbeefab9b2d12015-10-14 11:33:11 -07003929 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
perkjd61bf802016-03-24 03:16:19 -07003930 // When the MediaEngine audio channel is destroyed, the RemoteAudioSource
3931 // will be notified which will end the AudioRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08003932 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07003933 rtc::scoped_refptr<AudioTrackInterface> audio_track =
Steve Anton4171afb2017-11-20 10:20:22 -08003934 stream->FindAudioTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07003935 if (audio_track) {
deadbeefab9b2d12015-10-14 11:33:11 -07003936 stream->RemoveTrack(audio_track);
deadbeefab9b2d12015-10-14 11:33:11 -07003937 }
3938 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
perkjd61bf802016-03-24 03:16:19 -07003939 // Stopping or destroying a VideoRtpReceiver will end the
3940 // VideoRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08003941 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07003942 rtc::scoped_refptr<VideoTrackInterface> video_track =
Steve Anton4171afb2017-11-20 10:20:22 -08003943 stream->FindVideoTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07003944 if (video_track) {
perkjd61bf802016-03-24 03:16:19 -07003945 // There's no guarantee the track is still available, e.g. the track may
3946 // have been removed from the stream by an application.
deadbeefab9b2d12015-10-14 11:33:11 -07003947 stream->RemoveTrack(video_track);
deadbeefab9b2d12015-10-14 11:33:11 -07003948 }
3949 } else {
nisseede5da42017-01-12 05:15:36 -08003950 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07003951 }
Henrik Boström933d8b02017-10-10 10:05:16 -07003952 if (receiver) {
3953 observer_->OnRemoveTrack(receiver);
3954 }
deadbeefab9b2d12015-10-14 11:33:11 -07003955}
3956
3957void PeerConnection::UpdateEndedRemoteMediaStreams() {
3958 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams_to_remove;
3959 for (size_t i = 0; i < remote_streams_->count(); ++i) {
3960 MediaStreamInterface* stream = remote_streams_->at(i);
3961 if (stream->GetAudioTracks().empty() && stream->GetVideoTracks().empty()) {
3962 streams_to_remove.push_back(stream);
3963 }
3964 }
3965
Taylor Brandstetter98cde262016-05-31 13:02:21 -07003966 for (auto& stream : streams_to_remove) {
deadbeefab9b2d12015-10-14 11:33:11 -07003967 remote_streams_->RemoveStream(stream);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07003968 observer_->OnRemoveStream(std::move(stream));
deadbeefab9b2d12015-10-14 11:33:11 -07003969 }
3970}
3971
Steve Anton4171afb2017-11-20 10:20:22 -08003972void PeerConnection::UpdateLocalSenders(
deadbeefab9b2d12015-10-14 11:33:11 -07003973 const std::vector<cricket::StreamParams>& streams,
3974 cricket::MediaType media_type) {
Steve Anton4171afb2017-11-20 10:20:22 -08003975 std::vector<RtpSenderInfo>* current_senders = GetLocalSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07003976
3977 // Find removed tracks. I.e., tracks where the track id, stream label or ssrc
3978 // don't match the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08003979 for (auto sender_it = current_senders->begin();
3980 sender_it != current_senders->end();
3981 /* incremented manually */) {
3982 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07003983 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08003984 cricket::GetStreamBySsrc(streams, info.first_ssrc);
3985 if (!params || params->id != info.sender_id ||
deadbeefab9b2d12015-10-14 11:33:11 -07003986 params->sync_label != info.stream_label) {
Steve Anton4171afb2017-11-20 10:20:22 -08003987 OnLocalSenderRemoved(info, media_type);
3988 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07003989 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08003990 ++sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07003991 }
3992 }
3993
Steve Anton4171afb2017-11-20 10:20:22 -08003994 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07003995 for (const cricket::StreamParams& params : streams) {
3996 // The sync_label is the MediaStream label and the |stream.id| is the
Steve Anton4171afb2017-11-20 10:20:22 -08003997 // sender id.
deadbeefab9b2d12015-10-14 11:33:11 -07003998 const std::string& stream_label = params.sync_label;
Steve Anton4171afb2017-11-20 10:20:22 -08003999 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07004000 uint32_t ssrc = params.first_ssrc();
Steve Anton4171afb2017-11-20 10:20:22 -08004001 const RtpSenderInfo* sender_info =
4002 FindSenderInfo(*current_senders, stream_label, sender_id);
4003 if (!sender_info) {
4004 current_senders->push_back(RtpSenderInfo(stream_label, sender_id, ssrc));
4005 OnLocalSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004006 }
4007 }
4008}
4009
Steve Anton4171afb2017-11-20 10:20:22 -08004010void PeerConnection::OnLocalSenderAdded(const RtpSenderInfo& sender_info,
4011 cricket::MediaType media_type) {
4012 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08004013 if (!sender) {
Steve Anton4171afb2017-11-20 10:20:22 -08004014 RTC_LOG(LS_WARNING) << "An unknown RtpSender with id "
4015 << sender_info.sender_id
Mirko Bonadei675513b2017-11-09 11:09:25 +01004016 << " has been configured in the local description.";
deadbeefab9b2d12015-10-14 11:33:11 -07004017 return;
4018 }
4019
deadbeeffac06552015-11-25 11:26:01 -08004020 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004021 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
Jonas Olsson45cc8902018-02-13 10:37:07 +01004022 " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08004023 return;
deadbeefab9b2d12015-10-14 11:33:11 -07004024 }
deadbeeffac06552015-11-25 11:26:01 -08004025
Steve Anton4171afb2017-11-20 10:20:22 -08004026 sender->internal()->set_stream_id(sender_info.stream_label);
4027 sender->internal()->SetSsrc(sender_info.first_ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07004028}
4029
Steve Anton4171afb2017-11-20 10:20:22 -08004030void PeerConnection::OnLocalSenderRemoved(const RtpSenderInfo& sender_info,
4031 cricket::MediaType media_type) {
4032 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08004033 if (!sender) {
4034 // This is the normal case. I.e., RemoveStream has been called and the
deadbeefab9b2d12015-10-14 11:33:11 -07004035 // SessionDescriptions has been renegotiated.
4036 return;
4037 }
deadbeeffac06552015-11-25 11:26:01 -08004038
4039 // A sender has been removed from the SessionDescription but it's still
4040 // associated with the PeerConnection. This only occurs if the SDP doesn't
4041 // match with the calls to CreateSender, AddStream and RemoveStream.
4042 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004043 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
Jonas Olsson45cc8902018-02-13 10:37:07 +01004044 " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08004045 return;
deadbeefab9b2d12015-10-14 11:33:11 -07004046 }
deadbeeffac06552015-11-25 11:26:01 -08004047
Steve Anton4171afb2017-11-20 10:20:22 -08004048 sender->internal()->SetSsrc(0);
deadbeefab9b2d12015-10-14 11:33:11 -07004049}
4050
4051void PeerConnection::UpdateLocalRtpDataChannels(
4052 const cricket::StreamParamsVec& streams) {
4053 std::vector<std::string> existing_channels;
4054
4055 // Find new and active data channels.
4056 for (const cricket::StreamParams& params : streams) {
4057 // |it->sync_label| is actually the data channel label. The reason is that
4058 // we use the same naming of data channels as we do for
4059 // MediaStreams and Tracks.
4060 // For MediaStreams, the sync_label is the MediaStream label and the
4061 // track label is the same as |streamid|.
4062 const std::string& channel_label = params.sync_label;
4063 auto data_channel_it = rtp_data_channels_.find(channel_label);
nisse7ce109a2017-01-31 00:57:56 -08004064 if (data_channel_it == rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004065 RTC_LOG(LS_ERROR) << "channel label not found";
deadbeefab9b2d12015-10-14 11:33:11 -07004066 continue;
4067 }
4068 // Set the SSRC the data channel should use for sending.
4069 data_channel_it->second->SetSendSsrc(params.first_ssrc());
4070 existing_channels.push_back(data_channel_it->first);
4071 }
4072
4073 UpdateClosingRtpDataChannels(existing_channels, true);
4074}
4075
4076void PeerConnection::UpdateRemoteRtpDataChannels(
4077 const cricket::StreamParamsVec& streams) {
4078 std::vector<std::string> existing_channels;
4079
4080 // Find new and active data channels.
4081 for (const cricket::StreamParams& params : streams) {
4082 // The data channel label is either the mslabel or the SSRC if the mslabel
4083 // does not exist. Ex a=ssrc:444330170 mslabel:test1.
4084 std::string label = params.sync_label.empty()
4085 ? rtc::ToString(params.first_ssrc())
4086 : params.sync_label;
4087 auto data_channel_it = rtp_data_channels_.find(label);
4088 if (data_channel_it == rtp_data_channels_.end()) {
4089 // This is a new data channel.
4090 CreateRemoteRtpDataChannel(label, params.first_ssrc());
4091 } else {
4092 data_channel_it->second->SetReceiveSsrc(params.first_ssrc());
4093 }
4094 existing_channels.push_back(label);
4095 }
4096
4097 UpdateClosingRtpDataChannels(existing_channels, false);
4098}
4099
4100void PeerConnection::UpdateClosingRtpDataChannels(
4101 const std::vector<std::string>& active_channels,
4102 bool is_local_update) {
4103 auto it = rtp_data_channels_.begin();
4104 while (it != rtp_data_channels_.end()) {
4105 DataChannel* data_channel = it->second;
4106 if (std::find(active_channels.begin(), active_channels.end(),
4107 data_channel->label()) != active_channels.end()) {
4108 ++it;
4109 continue;
4110 }
4111
4112 if (is_local_update) {
4113 data_channel->SetSendSsrc(0);
4114 } else {
4115 data_channel->RemotePeerRequestClose();
4116 }
4117
4118 if (data_channel->state() == DataChannel::kClosed) {
4119 rtp_data_channels_.erase(it);
4120 it = rtp_data_channels_.begin();
4121 } else {
4122 ++it;
4123 }
4124 }
4125}
4126
4127void PeerConnection::CreateRemoteRtpDataChannel(const std::string& label,
4128 uint32_t remote_ssrc) {
4129 rtc::scoped_refptr<DataChannel> channel(
4130 InternalCreateDataChannel(label, nullptr));
4131 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004132 RTC_LOG(LS_WARNING) << "Remote peer requested a DataChannel but"
Jonas Olsson45cc8902018-02-13 10:37:07 +01004133 "CreateDataChannel failed.";
deadbeefab9b2d12015-10-14 11:33:11 -07004134 return;
4135 }
4136 channel->SetReceiveSsrc(remote_ssrc);
deadbeefa601f5c2016-06-06 14:27:39 -07004137 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
4138 DataChannelProxy::Create(signaling_thread(), channel);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07004139 observer_->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07004140}
4141
4142rtc::scoped_refptr<DataChannel> PeerConnection::InternalCreateDataChannel(
4143 const std::string& label,
4144 const InternalDataChannelInit* config) {
4145 if (IsClosed()) {
4146 return nullptr;
4147 }
Steve Anton75737c02017-11-06 10:37:17 -08004148 if (data_channel_type() == cricket::DCT_NONE) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004149 RTC_LOG(LS_ERROR)
deadbeefab9b2d12015-10-14 11:33:11 -07004150 << "InternalCreateDataChannel: Data is not supported in this call.";
4151 return nullptr;
4152 }
4153 InternalDataChannelInit new_config =
4154 config ? (*config) : InternalDataChannelInit();
Steve Anton75737c02017-11-06 10:37:17 -08004155 if (data_channel_type() == cricket::DCT_SCTP) {
deadbeefab9b2d12015-10-14 11:33:11 -07004156 if (new_config.id < 0) {
4157 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08004158 if ((GetSctpSslRole(&role)) &&
deadbeefab9b2d12015-10-14 11:33:11 -07004159 !sid_allocator_.AllocateSid(role, &new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004160 RTC_LOG(LS_ERROR)
4161 << "No id can be allocated for the SCTP data channel.";
deadbeefab9b2d12015-10-14 11:33:11 -07004162 return nullptr;
4163 }
4164 } else if (!sid_allocator_.ReserveSid(new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004165 RTC_LOG(LS_ERROR) << "Failed to create a SCTP data channel "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004166 "because the id is already in use or out of range.";
deadbeefab9b2d12015-10-14 11:33:11 -07004167 return nullptr;
4168 }
4169 }
4170
Steve Anton75737c02017-11-06 10:37:17 -08004171 rtc::scoped_refptr<DataChannel> channel(
4172 DataChannel::Create(this, data_channel_type(), label, new_config));
deadbeefab9b2d12015-10-14 11:33:11 -07004173 if (!channel) {
4174 sid_allocator_.ReleaseSid(new_config.id);
4175 return nullptr;
4176 }
4177
4178 if (channel->data_channel_type() == cricket::DCT_RTP) {
4179 if (rtp_data_channels_.find(channel->label()) != rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004180 RTC_LOG(LS_ERROR) << "DataChannel with label " << channel->label()
4181 << " already exists.";
deadbeefab9b2d12015-10-14 11:33:11 -07004182 return nullptr;
4183 }
4184 rtp_data_channels_[channel->label()] = channel;
4185 } else {
4186 RTC_DCHECK(channel->data_channel_type() == cricket::DCT_SCTP);
4187 sctp_data_channels_.push_back(channel);
4188 channel->SignalClosed.connect(this,
4189 &PeerConnection::OnSctpDataChannelClosed);
4190 }
4191
Steve Anton2d8609c2018-01-23 16:38:46 -08004192 SignalDataChannelCreated_(channel.get());
deadbeefab9b2d12015-10-14 11:33:11 -07004193 return channel;
4194}
4195
4196bool PeerConnection::HasDataChannels() const {
4197 return !rtp_data_channels_.empty() || !sctp_data_channels_.empty();
4198}
4199
4200void PeerConnection::AllocateSctpSids(rtc::SSLRole role) {
4201 for (const auto& channel : sctp_data_channels_) {
4202 if (channel->id() < 0) {
4203 int sid;
4204 if (!sid_allocator_.AllocateSid(role, &sid)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004205 RTC_LOG(LS_ERROR) << "Failed to allocate SCTP sid.";
deadbeefab9b2d12015-10-14 11:33:11 -07004206 continue;
4207 }
4208 channel->SetSctpSid(sid);
4209 }
4210 }
4211}
4212
4213void PeerConnection::OnSctpDataChannelClosed(DataChannel* channel) {
deadbeefbd292462015-12-14 18:15:29 -08004214 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeefab9b2d12015-10-14 11:33:11 -07004215 for (auto it = sctp_data_channels_.begin(); it != sctp_data_channels_.end();
4216 ++it) {
4217 if (it->get() == channel) {
4218 if (channel->id() >= 0) {
4219 sid_allocator_.ReleaseSid(channel->id());
4220 }
deadbeefbd292462015-12-14 18:15:29 -08004221 // Since this method is triggered by a signal from the DataChannel,
4222 // we can't free it directly here; we need to free it asynchronously.
4223 sctp_data_channels_to_free_.push_back(*it);
deadbeefab9b2d12015-10-14 11:33:11 -07004224 sctp_data_channels_.erase(it);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07004225 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_FREE_DATACHANNELS,
4226 nullptr);
deadbeefab9b2d12015-10-14 11:33:11 -07004227 return;
4228 }
4229 }
4230}
4231
deadbeefab9b2d12015-10-14 11:33:11 -07004232void PeerConnection::OnDataChannelDestroyed() {
4233 // Use a temporary copy of the RTP/SCTP DataChannel list because the
4234 // DataChannel may callback to us and try to modify the list.
4235 std::map<std::string, rtc::scoped_refptr<DataChannel>> temp_rtp_dcs;
4236 temp_rtp_dcs.swap(rtp_data_channels_);
4237 for (const auto& kv : temp_rtp_dcs) {
4238 kv.second->OnTransportChannelDestroyed();
4239 }
4240
4241 std::vector<rtc::scoped_refptr<DataChannel>> temp_sctp_dcs;
4242 temp_sctp_dcs.swap(sctp_data_channels_);
4243 for (const auto& channel : temp_sctp_dcs) {
4244 channel->OnTransportChannelDestroyed();
4245 }
4246}
4247
4248void PeerConnection::OnDataChannelOpenMessage(
4249 const std::string& label,
4250 const InternalDataChannelInit& config) {
4251 rtc::scoped_refptr<DataChannel> channel(
4252 InternalCreateDataChannel(label, &config));
4253 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004254 RTC_LOG(LS_ERROR) << "Failed to create DataChannel from the OPEN message.";
deadbeefab9b2d12015-10-14 11:33:11 -07004255 return;
4256 }
4257
deadbeefa601f5c2016-06-06 14:27:39 -07004258 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
4259 DataChannelProxy::Create(signaling_thread(), channel);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07004260 observer_->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07004261}
4262
Steve Anton4171afb2017-11-20 10:20:22 -08004263rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
4264PeerConnection::GetAudioTransceiver() const {
4265 // This method only works with Plan B SDP, where there is a single
4266 // audio/video transceiver.
4267 RTC_DCHECK(!IsUnifiedPlan());
4268 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08004269 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004270 return transceiver;
4271 }
4272 }
4273 RTC_NOTREACHED();
4274 return nullptr;
4275}
4276
4277rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
4278PeerConnection::GetVideoTransceiver() const {
4279 // This method only works with Plan B SDP, where there is a single
4280 // audio/video transceiver.
4281 RTC_DCHECK(!IsUnifiedPlan());
4282 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08004283 if (transceiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004284 return transceiver;
4285 }
4286 }
4287 RTC_NOTREACHED();
4288 return nullptr;
4289}
4290
4291// TODO(bugs.webrtc.org/7600): Remove this when multiple transceivers with
4292// individual transceiver directions are supported.
zhihuang1c378ed2017-08-17 14:10:50 -07004293bool PeerConnection::HasRtpSender(cricket::MediaType type) const {
Steve Anton4171afb2017-11-20 10:20:22 -08004294 switch (type) {
4295 case cricket::MEDIA_TYPE_AUDIO:
4296 return !GetAudioTransceiver()->internal()->senders().empty();
4297 case cricket::MEDIA_TYPE_VIDEO:
4298 return !GetVideoTransceiver()->internal()->senders().empty();
4299 case cricket::MEDIA_TYPE_DATA:
4300 return false;
4301 }
4302 RTC_NOTREACHED();
4303 return false;
zhihuang1c378ed2017-08-17 14:10:50 -07004304}
4305
Steve Anton4171afb2017-11-20 10:20:22 -08004306rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
4307PeerConnection::FindSenderForTrack(MediaStreamTrackInterface* track) const {
4308 for (auto transceiver : transceivers_) {
4309 for (auto sender : transceiver->internal()->senders()) {
4310 if (sender->track() == track) {
4311 return sender;
4312 }
4313 }
4314 }
4315 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08004316}
4317
Steve Anton4171afb2017-11-20 10:20:22 -08004318rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
4319PeerConnection::FindSenderById(const std::string& sender_id) const {
4320 for (auto transceiver : transceivers_) {
4321 for (auto sender : transceiver->internal()->senders()) {
4322 if (sender->id() == sender_id) {
4323 return sender;
4324 }
4325 }
4326 }
4327 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07004328}
4329
Steve Anton4171afb2017-11-20 10:20:22 -08004330rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
4331PeerConnection::FindReceiverById(const std::string& receiver_id) const {
4332 for (auto transceiver : transceivers_) {
4333 for (auto receiver : transceiver->internal()->receivers()) {
4334 if (receiver->id() == receiver_id) {
4335 return receiver;
4336 }
4337 }
4338 }
4339 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07004340}
4341
Steve Anton4171afb2017-11-20 10:20:22 -08004342std::vector<PeerConnection::RtpSenderInfo>*
4343PeerConnection::GetRemoteSenderInfos(cricket::MediaType media_type) {
4344 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
4345 media_type == cricket::MEDIA_TYPE_VIDEO);
4346 return (media_type == cricket::MEDIA_TYPE_AUDIO)
4347 ? &remote_audio_sender_infos_
4348 : &remote_video_sender_infos_;
4349}
4350
4351std::vector<PeerConnection::RtpSenderInfo>* PeerConnection::GetLocalSenderInfos(
deadbeefab9b2d12015-10-14 11:33:11 -07004352 cricket::MediaType media_type) {
4353 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
4354 media_type == cricket::MEDIA_TYPE_VIDEO);
Steve Anton4171afb2017-11-20 10:20:22 -08004355 return (media_type == cricket::MEDIA_TYPE_AUDIO) ? &local_audio_sender_infos_
4356 : &local_video_sender_infos_;
deadbeefab9b2d12015-10-14 11:33:11 -07004357}
4358
Steve Anton4171afb2017-11-20 10:20:22 -08004359const PeerConnection::RtpSenderInfo* PeerConnection::FindSenderInfo(
4360 const std::vector<PeerConnection::RtpSenderInfo>& infos,
deadbeefab9b2d12015-10-14 11:33:11 -07004361 const std::string& stream_label,
Steve Anton4171afb2017-11-20 10:20:22 -08004362 const std::string sender_id) const {
4363 for (const RtpSenderInfo& sender_info : infos) {
4364 if (sender_info.stream_label == stream_label &&
4365 sender_info.sender_id == sender_id) {
4366 return &sender_info;
deadbeefab9b2d12015-10-14 11:33:11 -07004367 }
4368 }
4369 return nullptr;
4370}
4371
4372DataChannel* PeerConnection::FindDataChannelBySid(int sid) const {
4373 for (const auto& channel : sctp_data_channels_) {
4374 if (channel->id() == sid) {
4375 return channel;
4376 }
4377 }
4378 return nullptr;
4379}
4380
deadbeef91dd5672016-05-18 16:55:30 -07004381bool PeerConnection::InitializePortAllocator_n(
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004382 const RTCConfiguration& configuration) {
4383 cricket::ServerAddresses stun_servers;
4384 std::vector<cricket::RelayServerConfig> turn_servers;
deadbeef293e9262017-01-11 12:28:30 -08004385 if (ParseIceServers(configuration.servers, &stun_servers, &turn_servers) !=
4386 RTCErrorType::NONE) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004387 return false;
4388 }
4389
Taylor Brandstetterf8e65772016-06-27 17:20:15 -07004390 port_allocator_->Initialize();
4391
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004392 // To handle both internal and externally created port allocator, we will
4393 // enable BUNDLE here.
4394 int portallocator_flags = port_allocator_->flags();
4395 portallocator_flags |= cricket::PORTALLOCATOR_ENABLE_SHARED_SOCKET |
zhihuangb09b3f92017-03-07 14:40:51 -08004396 cricket::PORTALLOCATOR_ENABLE_IPV6 |
4397 cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI;
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004398 // If the disable-IPv6 flag was specified, we'll not override it
4399 // by experiment.
4400 if (configuration.disable_ipv6) {
4401 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
sprangc1b57a12017-02-28 08:50:47 -08004402 } else if (webrtc::field_trial::FindFullName("WebRTC-IPv6Default")
4403 .find("Disabled") == 0) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004404 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
4405 }
4406
zhihuangb09b3f92017-03-07 14:40:51 -08004407 if (configuration.disable_ipv6_on_wifi) {
4408 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI);
Mirko Bonadei675513b2017-11-09 11:09:25 +01004409 RTC_LOG(LS_INFO) << "IPv6 candidates on Wi-Fi are disabled.";
zhihuangb09b3f92017-03-07 14:40:51 -08004410 }
4411
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004412 if (configuration.tcp_candidate_policy == kTcpCandidatePolicyDisabled) {
4413 portallocator_flags |= cricket::PORTALLOCATOR_DISABLE_TCP;
Mirko Bonadei675513b2017-11-09 11:09:25 +01004414 RTC_LOG(LS_INFO) << "TCP candidates are disabled.";
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004415 }
4416
honghaiz60347052016-05-31 18:29:12 -07004417 if (configuration.candidate_network_policy ==
4418 kCandidateNetworkPolicyLowCost) {
4419 portallocator_flags |= cricket::PORTALLOCATOR_DISABLE_COSTLY_NETWORKS;
Mirko Bonadei675513b2017-11-09 11:09:25 +01004420 RTC_LOG(LS_INFO) << "Do not gather candidates on high-cost networks";
honghaiz60347052016-05-31 18:29:12 -07004421 }
4422
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +01004423 if (configuration.disable_link_local_networks) {
4424 portallocator_flags |= cricket::PORTALLOCATOR_DISABLE_LINK_LOCAL_NETWORKS;
4425 RTC_LOG(LS_INFO) << "Disable candidates on link-local network interfaces.";
4426 }
4427
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004428 port_allocator_->set_flags(portallocator_flags);
4429 // No step delay is used while allocating ports.
4430 port_allocator_->set_step_delay(cricket::kMinimumStepDelay);
4431 port_allocator_->set_candidate_filter(
4432 ConvertIceTransportTypeToCandidateFilter(configuration.type));
deadbeefd21eab32017-07-26 16:50:11 -07004433 port_allocator_->set_max_ipv6_networks(configuration.max_ipv6_networks);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004434
4435 // Call this last since it may create pooled allocator sessions using the
4436 // properties set above.
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08004437 port_allocator_->SetConfiguration(
4438 stun_servers, turn_servers, configuration.ice_candidate_pool_size,
4439 configuration.prune_turn_ports, configuration.turn_customizer,
4440 configuration.stun_candidate_keepalive_interval);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004441 return true;
4442}
4443
deadbeef91dd5672016-05-18 16:55:30 -07004444bool PeerConnection::ReconfigurePortAllocator_n(
deadbeef293e9262017-01-11 12:28:30 -08004445 const cricket::ServerAddresses& stun_servers,
4446 const std::vector<cricket::RelayServerConfig>& turn_servers,
4447 IceTransportsType type,
4448 int candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02004449 bool prune_turn_ports,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08004450 webrtc::TurnCustomizer* turn_customizer,
4451 rtc::Optional<int> stun_candidate_keepalive_interval) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004452 port_allocator_->set_candidate_filter(
deadbeef293e9262017-01-11 12:28:30 -08004453 ConvertIceTransportTypeToCandidateFilter(type));
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004454 // Call this last since it may create pooled allocator sessions using the
4455 // candidate filter set above.
deadbeef6de92f92016-12-12 18:49:32 -08004456 return port_allocator_->SetConfiguration(
Jonas Orelandbdcee282017-10-10 14:01:40 +02004457 stun_servers, turn_servers, candidate_pool_size, prune_turn_ports,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08004458 turn_customizer, stun_candidate_keepalive_interval);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004459}
4460
Steve Antonba818672017-11-06 10:21:57 -08004461cricket::ChannelManager* PeerConnection::channel_manager() const {
4462 return factory_->channel_manager();
4463}
4464
4465MetricsObserverInterface* PeerConnection::metrics_observer() const {
4466 return uma_observer_;
4467}
4468
Elad Alon99c3fe52017-10-13 16:29:40 +02004469bool PeerConnection::StartRtcEventLog_w(
Bjorn Tereliusde939432017-11-20 17:38:14 +01004470 std::unique_ptr<RtcEventLogOutput> output,
4471 int64_t output_period_ms) {
zhihuang77985012017-02-07 15:45:16 -08004472 if (!event_log_) {
4473 return false;
4474 }
Bjorn Tereliusde939432017-11-20 17:38:14 +01004475 return event_log_->StartLogging(std::move(output), output_period_ms);
ivoc14d5dbe2016-07-04 07:06:55 -07004476}
4477
4478void PeerConnection::StopRtcEventLog_w() {
zhihuang77985012017-02-07 15:45:16 -08004479 if (event_log_) {
4480 event_log_->StopLogging();
4481 }
ivoc14d5dbe2016-07-04 07:06:55 -07004482}
nisseeaabdf62017-05-05 02:23:02 -07004483
Steve Anton75737c02017-11-06 10:37:17 -08004484cricket::BaseChannel* PeerConnection::GetChannel(
4485 const std::string& content_name) {
Steve Antondcc3c022017-12-22 16:02:54 -08004486 for (auto transceiver : transceivers_) {
4487 cricket::BaseChannel* channel = transceiver->internal()->channel();
4488 if (channel && channel->content_name() == content_name) {
4489 return channel;
4490 }
Steve Anton75737c02017-11-06 10:37:17 -08004491 }
4492 if (rtp_data_channel() &&
4493 rtp_data_channel()->content_name() == content_name) {
4494 return rtp_data_channel();
4495 }
4496 return nullptr;
4497}
4498
4499bool PeerConnection::GetSctpSslRole(rtc::SSLRole* role) {
4500 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004501 RTC_LOG(LS_INFO)
4502 << "Local and Remote descriptions must be applied to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004503 "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08004504 return false;
4505 }
4506 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004507 RTC_LOG(LS_INFO) << "Non-rejected SCTP m= section is needed to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004508 "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08004509 return false;
4510 }
4511
4512 return transport_controller_->GetSslRole(*sctp_transport_name_, role);
4513}
4514
4515bool PeerConnection::GetSslRole(const std::string& content_name,
4516 rtc::SSLRole* role) {
4517 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004518 RTC_LOG(LS_INFO)
4519 << "Local and Remote descriptions must be applied to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004520 "SSL Role of the session.";
Steve Anton75737c02017-11-06 10:37:17 -08004521 return false;
4522 }
4523
4524 return transport_controller_->GetSslRole(GetTransportName(content_name),
4525 role);
4526}
4527
Steve Antonf8470812017-12-04 10:46:21 -08004528void PeerConnection::SetSessionError(SessionError error,
4529 const std::string& error_desc) {
4530 RTC_DCHECK_RUN_ON(signaling_thread());
4531 if (error != session_error_) {
4532 session_error_ = error;
4533 session_error_desc_ = error_desc;
Steve Anton75737c02017-11-06 10:37:17 -08004534 }
4535}
4536
Steve Anton3828c062017-12-06 10:34:51 -08004537RTCError PeerConnection::UpdateSessionState(SdpType type,
Steve Anton8a006912017-12-04 15:25:56 -08004538 cricket::ContentSource source) {
4539 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08004540
4541 // If there's already a pending error then no state transition should happen.
4542 // But all call-sites should be verifying this before calling us!
Steve Antonf8470812017-12-04 10:46:21 -08004543 RTC_DCHECK(session_error() == SessionError::kNone);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004544
4545 // If this is an answer then we know whether to BUNDLE or not. If both the
4546 // local and remote side have agreed to BUNDLE, go ahead and enable it.
Steve Anton3828c062017-12-06 10:34:51 -08004547 if (type == SdpType::kAnswer) {
Steve Anton75737c02017-11-06 10:37:17 -08004548 const cricket::ContentGroup* local_bundle =
4549 local_description()->description()->GetGroupByName(
4550 cricket::GROUP_TYPE_BUNDLE);
4551 const cricket::ContentGroup* remote_bundle =
4552 remote_description()->description()->GetGroupByName(
4553 cricket::GROUP_TYPE_BUNDLE);
4554 if (local_bundle && remote_bundle) {
4555 // The answerer decides the transport to bundle on.
4556 const cricket::ContentGroup* answer_bundle =
4557 (source == cricket::CS_LOCAL ? local_bundle : remote_bundle);
4558 if (!EnableBundle(*answer_bundle)) {
Steve Anton8a006912017-12-04 15:25:56 -08004559 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
4560 kEnableBundleFailed);
Steve Anton75737c02017-11-06 10:37:17 -08004561 }
4562 }
Steve Anton75737c02017-11-06 10:37:17 -08004563 }
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004564
4565 // Only push down the transport description after potentially enabling BUNDLE;
4566 // we don't want to push down a description on a transport about to be
4567 // destroyed.
Steve Anton3828c062017-12-06 10:34:51 -08004568 RTCError error = PushdownTransportDescription(source, type);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004569 if (!error.ok()) {
4570 return error;
4571 }
4572
4573 // If this is answer-ish we're ready to let media flow.
Steve Anton3828c062017-12-06 10:34:51 -08004574 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Antoned10bd92017-12-05 10:52:59 -08004575 EnableSending();
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004576 }
4577
4578 // Update the signaling state according to the specified state machine (see
4579 // https://w3c.github.io/webrtc-pc/#rtcsignalingstate-enum).
Steve Anton3828c062017-12-06 10:34:51 -08004580 if (type == SdpType::kOffer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004581 ChangeSignalingState(source == cricket::CS_LOCAL
4582 ? PeerConnectionInterface::kHaveLocalOffer
4583 : PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton3828c062017-12-06 10:34:51 -08004584 } else if (type == SdpType::kPrAnswer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004585 ChangeSignalingState(source == cricket::CS_LOCAL
4586 ? PeerConnectionInterface::kHaveLocalPrAnswer
4587 : PeerConnectionInterface::kHaveRemotePrAnswer);
4588 } else {
Steve Anton3828c062017-12-06 10:34:51 -08004589 RTC_DCHECK(type == SdpType::kAnswer);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004590 ChangeSignalingState(PeerConnectionInterface::kStable);
4591 }
4592
4593 // Update internal objects according to the session description's media
4594 // descriptions.
Steve Anton3828c062017-12-06 10:34:51 -08004595 error = PushdownMediaDescription(type, source);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004596 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08004597 return error;
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004598 }
4599
Steve Anton8a006912017-12-04 15:25:56 -08004600 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08004601}
4602
Steve Anton8a006912017-12-04 15:25:56 -08004603RTCError PeerConnection::PushdownMediaDescription(
Steve Anton3828c062017-12-06 10:34:51 -08004604 SdpType type,
Steve Anton8a006912017-12-04 15:25:56 -08004605 cricket::ContentSource source) {
Steve Antoned10bd92017-12-05 10:52:59 -08004606 const SessionDescriptionInterface* sdesc =
4607 (source == cricket::CS_LOCAL ? local_description()
4608 : remote_description());
Steve Anton75737c02017-11-06 10:37:17 -08004609 RTC_DCHECK(sdesc);
Steve Antoned10bd92017-12-05 10:52:59 -08004610
4611 // Push down the new SDP media section for each audio/video transceiver.
4612 for (auto transceiver : transceivers_) {
Steve Anton75737c02017-11-06 10:37:17 -08004613 const ContentInfo* content_info =
Steve Antoned10bd92017-12-05 10:52:59 -08004614 FindMediaSectionForTransceiver(transceiver, sdesc);
4615 cricket::BaseChannel* channel = transceiver->internal()->channel();
4616 if (!channel || !content_info || content_info->rejected) {
Steve Anton75737c02017-11-06 10:37:17 -08004617 continue;
4618 }
4619 const MediaContentDescription* content_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08004620 content_info->media_description();
Steve Antoned10bd92017-12-05 10:52:59 -08004621 if (!content_desc) {
4622 continue;
4623 }
4624 std::string error;
4625 bool success =
4626 (source == cricket::CS_LOCAL)
Steve Anton3828c062017-12-06 10:34:51 -08004627 ? channel->SetLocalContent(content_desc, type, &error)
4628 : channel->SetRemoteContent(content_desc, type, &error);
Steve Antoned10bd92017-12-05 10:52:59 -08004629 if (!success) {
4630 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, std::move(error));
4631 }
4632 }
4633
4634 // If using the RtpDataChannel, push down the new SDP section for it too.
4635 if (rtp_data_channel_) {
4636 const ContentInfo* data_content =
4637 cricket::GetFirstDataContent(sdesc->description());
4638 if (data_content && !data_content->rejected) {
4639 const MediaContentDescription* data_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08004640 data_content->media_description();
Steve Antoned10bd92017-12-05 10:52:59 -08004641 if (data_desc) {
4642 std::string error;
4643 bool success =
4644 (source == cricket::CS_LOCAL)
Steve Anton3828c062017-12-06 10:34:51 -08004645 ? rtp_data_channel_->SetLocalContent(data_desc, type, &error)
4646 : rtp_data_channel_->SetRemoteContent(data_desc, type,
Steve Antoned10bd92017-12-05 10:52:59 -08004647 &error);
4648 if (!success) {
4649 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
4650 std::move(error));
4651 }
Steve Anton75737c02017-11-06 10:37:17 -08004652 }
4653 }
4654 }
Steve Antoned10bd92017-12-05 10:52:59 -08004655
Steve Anton75737c02017-11-06 10:37:17 -08004656 // Need complete offer/answer with an SCTP m= section before starting SCTP,
4657 // according to https://tools.ietf.org/html/draft-ietf-mmusic-sctp-sdp-19
4658 if (sctp_transport_ && local_description() && remote_description() &&
4659 cricket::GetFirstDataContent(local_description()->description()) &&
4660 cricket::GetFirstDataContent(remote_description()->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08004661 bool success = network_thread()->Invoke<bool>(
Steve Anton75737c02017-11-06 10:37:17 -08004662 RTC_FROM_HERE,
4663 rtc::Bind(&PeerConnection::PushdownSctpParameters_n, this, source));
Steve Anton8a006912017-12-04 15:25:56 -08004664 if (!success) {
4665 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
4666 "Failed to push down SCTP parameters.");
4667 }
Steve Anton75737c02017-11-06 10:37:17 -08004668 }
Steve Antoned10bd92017-12-05 10:52:59 -08004669
Steve Anton8a006912017-12-04 15:25:56 -08004670 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08004671}
4672
4673bool PeerConnection::PushdownSctpParameters_n(cricket::ContentSource source) {
4674 RTC_DCHECK(network_thread()->IsCurrent());
4675 RTC_DCHECK(local_description());
4676 RTC_DCHECK(remote_description());
4677 // Apply the SCTP port (which is hidden inside a DataCodec structure...)
4678 // When we support "max-message-size", that would also be pushed down here.
4679 return sctp_transport_->Start(
4680 GetSctpPort(local_description()->description()),
4681 GetSctpPort(remote_description()->description()));
4682}
4683
Steve Anton8a006912017-12-04 15:25:56 -08004684RTCError PeerConnection::PushdownTransportDescription(
4685 cricket::ContentSource source,
Steve Anton3828c062017-12-06 10:34:51 -08004686 SdpType type) {
Steve Anton8a006912017-12-04 15:25:56 -08004687 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08004688
Steve Anton8a006912017-12-04 15:25:56 -08004689 const SessionDescriptionInterface* sdesc =
4690 (source == cricket::CS_LOCAL ? local_description()
4691 : remote_description());
4692 RTC_DCHECK(sdesc);
4693 for (const cricket::TransportInfo& tinfo :
4694 sdesc->description()->transport_infos()) {
4695 std::string error;
4696 bool success;
4697 if (source == cricket::CS_LOCAL) {
4698 success = transport_controller_->SetLocalTransportDescription(
Steve Anton3828c062017-12-06 10:34:51 -08004699 tinfo.content_name, tinfo.description, type, &error);
Steve Anton8a006912017-12-04 15:25:56 -08004700 } else {
4701 success = transport_controller_->SetRemoteTransportDescription(
Steve Anton3828c062017-12-06 10:34:51 -08004702 tinfo.content_name, tinfo.description, type, &error);
Steve Anton8a006912017-12-04 15:25:56 -08004703 }
4704 if (!success) {
Steve Antondcc3c022017-12-22 16:02:54 -08004705 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
4706 "Failed to push down transport description for " +
4707 tinfo.content_name + ": " + error);
Steve Anton75737c02017-11-06 10:37:17 -08004708 }
4709 }
4710
Steve Anton8a006912017-12-04 15:25:56 -08004711 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08004712}
4713
4714bool PeerConnection::GetTransportDescription(
4715 const SessionDescription* description,
4716 const std::string& content_name,
4717 cricket::TransportDescription* tdesc) {
4718 if (!description || !tdesc) {
4719 return false;
4720 }
4721 const TransportInfo* transport_info =
4722 description->GetTransportInfoByName(content_name);
4723 if (!transport_info) {
4724 return false;
4725 }
4726 *tdesc = transport_info->description;
4727 return true;
4728}
4729
4730bool PeerConnection::EnableBundle(const cricket::ContentGroup& bundle) {
4731 const std::string* first_content_name = bundle.FirstContentName();
4732 if (!first_content_name) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004733 RTC_LOG(LS_WARNING) << "Tried to BUNDLE with no contents.";
Steve Anton75737c02017-11-06 10:37:17 -08004734 return false;
4735 }
4736 const std::string& transport_name = *first_content_name;
4737
4738 auto maybe_set_transport = [this, bundle,
4739 transport_name](cricket::BaseChannel* ch) {
4740 if (!ch || !bundle.HasContentName(ch->content_name())) {
Steve Antoned10bd92017-12-05 10:52:59 -08004741 return;
Steve Anton75737c02017-11-06 10:37:17 -08004742 }
4743
4744 std::string old_transport_name = ch->transport_name();
4745 if (old_transport_name == transport_name) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004746 RTC_LOG(LS_INFO) << "BUNDLE already enabled for " << ch->content_name()
4747 << " on " << transport_name << ".";
Steve Antoned10bd92017-12-05 10:52:59 -08004748 return;
Steve Anton75737c02017-11-06 10:37:17 -08004749 }
4750
4751 cricket::DtlsTransportInternal* rtp_dtls_transport =
4752 transport_controller_->CreateDtlsTransport(
4753 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4754 bool need_rtcp = (ch->rtcp_dtls_transport() != nullptr);
4755 cricket::DtlsTransportInternal* rtcp_dtls_transport = nullptr;
4756 if (need_rtcp) {
4757 rtcp_dtls_transport = transport_controller_->CreateDtlsTransport(
4758 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
4759 }
4760
4761 ch->SetTransports(rtp_dtls_transport, rtcp_dtls_transport);
Mirko Bonadei675513b2017-11-09 11:09:25 +01004762 RTC_LOG(LS_INFO) << "Enabled BUNDLE for " << ch->content_name() << " on "
4763 << transport_name << ".";
Steve Anton75737c02017-11-06 10:37:17 -08004764 transport_controller_->DestroyDtlsTransport(
4765 old_transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4766 // If the channel needs rtcp, it means that the channel used to have a
4767 // rtcp transport which needs to be deleted now.
4768 if (need_rtcp) {
4769 transport_controller_->DestroyDtlsTransport(
4770 old_transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
4771 }
Steve Anton75737c02017-11-06 10:37:17 -08004772 };
4773
Steve Antoned10bd92017-12-05 10:52:59 -08004774 for (auto transceiver : transceivers_) {
4775 maybe_set_transport(transceiver->internal()->channel());
Steve Anton75737c02017-11-06 10:37:17 -08004776 }
Steve Antoned10bd92017-12-05 10:52:59 -08004777 maybe_set_transport(rtp_data_channel_);
4778
Steve Anton75737c02017-11-06 10:37:17 -08004779 // For SCTP, transport creation/deletion happens here instead of in the
4780 // object itself.
4781 if (sctp_transport_) {
4782 RTC_DCHECK(sctp_transport_name_);
4783 RTC_DCHECK(sctp_content_name_);
4784 if (transport_name != *sctp_transport_name_ &&
4785 bundle.HasContentName(*sctp_content_name_)) {
4786 network_thread()->Invoke<void>(
4787 RTC_FROM_HERE, rtc::Bind(&PeerConnection::ChangeSctpTransport_n, this,
4788 transport_name));
4789 }
4790 }
4791
4792 return true;
4793}
4794
Steve Anton75737c02017-11-06 10:37:17 -08004795cricket::IceConfig PeerConnection::ParseIceConfig(
4796 const PeerConnectionInterface::RTCConfiguration& config) const {
4797 cricket::ContinualGatheringPolicy gathering_policy;
4798 // TODO(honghaiz): Add the third continual gathering policy in
4799 // PeerConnectionInterface and map it to GATHER_CONTINUALLY_AND_RECOVER.
4800 switch (config.continual_gathering_policy) {
4801 case PeerConnectionInterface::GATHER_ONCE:
4802 gathering_policy = cricket::GATHER_ONCE;
4803 break;
4804 case PeerConnectionInterface::GATHER_CONTINUALLY:
4805 gathering_policy = cricket::GATHER_CONTINUALLY;
4806 break;
4807 default:
4808 RTC_NOTREACHED();
4809 gathering_policy = cricket::GATHER_ONCE;
4810 }
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08004811
Steve Anton75737c02017-11-06 10:37:17 -08004812 cricket::IceConfig ice_config;
4813 ice_config.receiving_timeout = config.ice_connection_receiving_timeout;
4814 ice_config.prioritize_most_likely_candidate_pairs =
4815 config.prioritize_most_likely_ice_candidate_pairs;
4816 ice_config.backup_connection_ping_interval =
4817 config.ice_backup_candidate_pair_ping_interval;
4818 ice_config.continual_gathering_policy = gathering_policy;
4819 ice_config.presume_writable_when_fully_relayed =
4820 config.presume_writable_when_fully_relayed;
4821 ice_config.ice_check_min_interval = config.ice_check_min_interval;
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08004822 ice_config.stun_keepalive_interval = config.stun_candidate_keepalive_interval;
Steve Anton75737c02017-11-06 10:37:17 -08004823 ice_config.regather_all_networks_interval_range =
4824 config.ice_regather_interval_range;
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08004825 ice_config.network_preference = config.network_preference;
Steve Anton75737c02017-11-06 10:37:17 -08004826 return ice_config;
4827}
4828
Steve Anton75737c02017-11-06 10:37:17 -08004829bool PeerConnection::GetLocalTrackIdBySsrc(uint32_t ssrc,
4830 std::string* track_id) {
4831 if (!local_description()) {
4832 return false;
4833 }
4834 return webrtc::GetTrackIdBySsrc(local_description()->description(), ssrc,
4835 track_id);
4836}
4837
4838bool PeerConnection::GetRemoteTrackIdBySsrc(uint32_t ssrc,
4839 std::string* track_id) {
4840 if (!remote_description()) {
4841 return false;
4842 }
4843 return webrtc::GetTrackIdBySsrc(remote_description()->description(), ssrc,
4844 track_id);
4845}
4846
4847bool PeerConnection::SendData(const cricket::SendDataParams& params,
4848 const rtc::CopyOnWriteBuffer& payload,
4849 cricket::SendDataResult* result) {
4850 if (!rtp_data_channel_ && !sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004851 RTC_LOG(LS_ERROR) << "SendData called when rtp_data_channel_ "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004852 "and sctp_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08004853 return false;
4854 }
4855 return rtp_data_channel_
4856 ? rtp_data_channel_->SendData(params, payload, result)
4857 : network_thread()->Invoke<bool>(
4858 RTC_FROM_HERE,
4859 Bind(&cricket::SctpTransportInternal::SendData,
4860 sctp_transport_.get(), params, payload, result));
4861}
4862
4863bool PeerConnection::ConnectDataChannel(DataChannel* webrtc_data_channel) {
4864 if (!rtp_data_channel_ && !sctp_transport_) {
4865 // Don't log an error here, because DataChannels are expected to call
4866 // ConnectDataChannel in this state. It's the only way to initially tell
4867 // whether or not the underlying transport is ready.
4868 return false;
4869 }
4870 if (rtp_data_channel_) {
4871 rtp_data_channel_->SignalReadyToSendData.connect(
4872 webrtc_data_channel, &DataChannel::OnChannelReady);
4873 rtp_data_channel_->SignalDataReceived.connect(webrtc_data_channel,
4874 &DataChannel::OnDataReceived);
4875 } else {
4876 SignalSctpReadyToSendData.connect(webrtc_data_channel,
4877 &DataChannel::OnChannelReady);
4878 SignalSctpDataReceived.connect(webrtc_data_channel,
4879 &DataChannel::OnDataReceived);
4880 SignalSctpStreamClosedRemotely.connect(
4881 webrtc_data_channel, &DataChannel::OnStreamClosedRemotely);
4882 }
4883 return true;
4884}
4885
4886void PeerConnection::DisconnectDataChannel(DataChannel* webrtc_data_channel) {
4887 if (!rtp_data_channel_ && !sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004888 RTC_LOG(LS_ERROR)
4889 << "DisconnectDataChannel called when rtp_data_channel_ and "
4890 "sctp_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08004891 return;
4892 }
4893 if (rtp_data_channel_) {
4894 rtp_data_channel_->SignalReadyToSendData.disconnect(webrtc_data_channel);
4895 rtp_data_channel_->SignalDataReceived.disconnect(webrtc_data_channel);
4896 } else {
4897 SignalSctpReadyToSendData.disconnect(webrtc_data_channel);
4898 SignalSctpDataReceived.disconnect(webrtc_data_channel);
4899 SignalSctpStreamClosedRemotely.disconnect(webrtc_data_channel);
4900 }
4901}
4902
4903void PeerConnection::AddSctpDataStream(int sid) {
4904 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004905 RTC_LOG(LS_ERROR)
4906 << "AddSctpDataStream called when sctp_transport_ is NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08004907 return;
4908 }
4909 network_thread()->Invoke<void>(
4910 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::OpenStream,
4911 sctp_transport_.get(), sid));
4912}
4913
4914void PeerConnection::RemoveSctpDataStream(int sid) {
4915 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004916 RTC_LOG(LS_ERROR) << "RemoveSctpDataStream called when sctp_transport_ is "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004917 "NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08004918 return;
4919 }
4920 network_thread()->Invoke<void>(
4921 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::ResetStream,
4922 sctp_transport_.get(), sid));
4923}
4924
4925bool PeerConnection::ReadyToSendData() const {
4926 return (rtp_data_channel_ && rtp_data_channel_->ready_to_send_data()) ||
4927 sctp_ready_to_send_data_;
4928}
4929
Steve Anton5dfde182018-02-06 10:34:40 -08004930std::map<std::string, std::string> PeerConnection::GetTransportNamesByMid()
4931 const {
4932 std::map<std::string, std::string> transport_names_by_mid;
4933 for (auto transceiver : transceivers_) {
4934 cricket::BaseChannel* channel = transceiver->internal()->channel();
4935 if (channel) {
4936 transport_names_by_mid[channel->content_name()] =
4937 channel->transport_name();
4938 }
Steve Anton75737c02017-11-06 10:37:17 -08004939 }
Steve Anton5dfde182018-02-06 10:34:40 -08004940 if (rtp_data_channel_) {
4941 transport_names_by_mid[rtp_data_channel_->content_name()] =
4942 rtp_data_channel_->transport_name();
Steve Anton75737c02017-11-06 10:37:17 -08004943 }
4944 if (sctp_transport_) {
Steve Anton5dfde182018-02-06 10:34:40 -08004945 transport_names_by_mid[*sctp_content_name_] = *sctp_transport_name_;
Steve Anton75737c02017-11-06 10:37:17 -08004946 }
Steve Anton5dfde182018-02-06 10:34:40 -08004947 return transport_names_by_mid;
Steve Anton75737c02017-11-06 10:37:17 -08004948}
4949
Steve Anton5dfde182018-02-06 10:34:40 -08004950std::map<std::string, cricket::TransportStats>
4951PeerConnection::GetTransportStatsByNames(
4952 const std::set<std::string>& transport_names) {
4953 if (!network_thread()->IsCurrent()) {
4954 return network_thread()
4955 ->Invoke<std::map<std::string, cricket::TransportStats>>(
4956 RTC_FROM_HERE,
4957 [&] { return GetTransportStatsByNames(transport_names); });
Steve Anton75737c02017-11-06 10:37:17 -08004958 }
Steve Anton5dfde182018-02-06 10:34:40 -08004959 std::map<std::string, cricket::TransportStats> transport_stats_by_name;
4960 for (const std::string& transport_name : transport_names) {
4961 cricket::TransportStats transport_stats;
4962 bool success =
4963 transport_controller_->GetStats(transport_name, &transport_stats);
4964 if (success) {
4965 transport_stats_by_name[transport_name] = std::move(transport_stats);
4966 } else {
4967 RTC_LOG(LS_ERROR) << "Failed to get transport stats for transport_name="
4968 << transport_name;
4969 }
4970 }
4971 return transport_stats_by_name;
Steve Anton75737c02017-11-06 10:37:17 -08004972}
4973
4974bool PeerConnection::GetLocalCertificate(
4975 const std::string& transport_name,
4976 rtc::scoped_refptr<rtc::RTCCertificate>* certificate) {
4977 return transport_controller_->GetLocalCertificate(transport_name,
4978 certificate);
4979}
4980
4981std::unique_ptr<rtc::SSLCertificate> PeerConnection::GetRemoteSSLCertificate(
4982 const std::string& transport_name) {
4983 return transport_controller_->GetRemoteSSLCertificate(transport_name);
4984}
4985
4986cricket::DataChannelType PeerConnection::data_channel_type() const {
4987 return data_channel_type_;
4988}
4989
4990bool PeerConnection::IceRestartPending(const std::string& content_name) const {
4991 return pending_ice_restarts_.find(content_name) !=
4992 pending_ice_restarts_.end();
4993}
4994
Steve Anton75737c02017-11-06 10:37:17 -08004995bool PeerConnection::NeedsIceRestart(const std::string& content_name) const {
4996 return transport_controller_->NeedsIceRestart(content_name);
4997}
4998
4999void PeerConnection::OnCertificateReady(
5000 const rtc::scoped_refptr<rtc::RTCCertificate>& certificate) {
5001 transport_controller_->SetLocalCertificate(certificate);
5002}
5003
5004void PeerConnection::OnDtlsSrtpSetupFailure(cricket::BaseChannel*, bool rtcp) {
Steve Antonf8470812017-12-04 10:46:21 -08005005 SetSessionError(SessionError::kTransport,
5006 rtcp ? kDtlsSrtpSetupFailureRtcp : kDtlsSrtpSetupFailureRtp);
Steve Anton75737c02017-11-06 10:37:17 -08005007}
5008
5009void PeerConnection::OnTransportControllerConnectionState(
5010 cricket::IceConnectionState state) {
5011 switch (state) {
5012 case cricket::kIceConnectionConnecting:
5013 // If the current state is Connected or Completed, then there were
5014 // writable channels but now there are not, so the next state must
5015 // be Disconnected.
5016 // kIceConnectionConnecting is currently used as the default,
5017 // un-connected state by the TransportController, so its only use is
5018 // detecting disconnections.
5019 if (ice_connection_state_ ==
5020 PeerConnectionInterface::kIceConnectionConnected ||
5021 ice_connection_state_ ==
5022 PeerConnectionInterface::kIceConnectionCompleted) {
5023 SetIceConnectionState(
5024 PeerConnectionInterface::kIceConnectionDisconnected);
5025 }
5026 break;
5027 case cricket::kIceConnectionFailed:
5028 SetIceConnectionState(PeerConnectionInterface::kIceConnectionFailed);
5029 break;
5030 case cricket::kIceConnectionConnected:
Mirko Bonadei675513b2017-11-09 11:09:25 +01005031 RTC_LOG(LS_INFO) << "Changing to ICE connected state because "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005032 "all transports are writable.";
Steve Anton75737c02017-11-06 10:37:17 -08005033 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
5034 break;
5035 case cricket::kIceConnectionCompleted:
Mirko Bonadei675513b2017-11-09 11:09:25 +01005036 RTC_LOG(LS_INFO) << "Changing to ICE completed state because "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005037 "all transports are complete.";
Steve Anton75737c02017-11-06 10:37:17 -08005038 if (ice_connection_state_ !=
5039 PeerConnectionInterface::kIceConnectionConnected) {
5040 // If jumping directly from "checking" to "connected",
5041 // signal "connected" first.
5042 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
5043 }
5044 SetIceConnectionState(PeerConnectionInterface::kIceConnectionCompleted);
5045 if (metrics_observer()) {
5046 ReportTransportStats();
5047 }
5048 break;
5049 default:
5050 RTC_NOTREACHED();
5051 }
5052}
5053
5054void PeerConnection::OnTransportControllerCandidatesGathered(
5055 const std::string& transport_name,
5056 const cricket::Candidates& candidates) {
5057 RTC_DCHECK(signaling_thread()->IsCurrent());
5058 int sdp_mline_index;
5059 if (!GetLocalCandidateMediaIndex(transport_name, &sdp_mline_index)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005060 RTC_LOG(LS_ERROR)
5061 << "OnTransportControllerCandidatesGathered: content name "
5062 << transport_name << " not found";
Steve Anton75737c02017-11-06 10:37:17 -08005063 return;
5064 }
5065
5066 for (cricket::Candidates::const_iterator citer = candidates.begin();
5067 citer != candidates.end(); ++citer) {
5068 // Use transport_name as the candidate media id.
5069 std::unique_ptr<JsepIceCandidate> candidate(
5070 new JsepIceCandidate(transport_name, sdp_mline_index, *citer));
5071 if (local_description()) {
5072 mutable_local_description()->AddCandidate(candidate.get());
5073 }
5074 OnIceCandidate(std::move(candidate));
5075 }
5076}
5077
5078void PeerConnection::OnTransportControllerCandidatesRemoved(
5079 const std::vector<cricket::Candidate>& candidates) {
5080 RTC_DCHECK(signaling_thread()->IsCurrent());
5081 // Sanity check.
5082 for (const cricket::Candidate& candidate : candidates) {
5083 if (candidate.transport_name().empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005084 RTC_LOG(LS_ERROR) << "OnTransportControllerCandidatesRemoved: "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005085 "empty content name in candidate "
Mirko Bonadei675513b2017-11-09 11:09:25 +01005086 << candidate.ToString();
Steve Anton75737c02017-11-06 10:37:17 -08005087 return;
5088 }
5089 }
5090
5091 if (local_description()) {
5092 mutable_local_description()->RemoveCandidates(candidates);
5093 }
5094 OnIceCandidatesRemoved(candidates);
5095}
5096
5097void PeerConnection::OnTransportControllerDtlsHandshakeError(
5098 rtc::SSLHandshakeError error) {
5099 if (metrics_observer()) {
5100 metrics_observer()->IncrementEnumCounter(
5101 webrtc::kEnumCounterDtlsHandshakeError, static_cast<int>(error),
5102 static_cast<int>(rtc::SSLHandshakeError::MAX_VALUE));
5103 }
5104}
5105
Steve Antoned10bd92017-12-05 10:52:59 -08005106void PeerConnection::EnableSending() {
5107 for (auto transceiver : transceivers_) {
5108 cricket::BaseChannel* channel = transceiver->internal()->channel();
5109 if (channel && !channel->enabled()) {
5110 channel->Enable(true);
5111 }
Steve Anton75737c02017-11-06 10:37:17 -08005112 }
5113
Steve Anton4171afb2017-11-20 10:20:22 -08005114 if (rtp_data_channel_ && !rtp_data_channel_->enabled()) {
Steve Anton75737c02017-11-06 10:37:17 -08005115 rtp_data_channel_->Enable(true);
Steve Anton4171afb2017-11-20 10:20:22 -08005116 }
Steve Anton75737c02017-11-06 10:37:17 -08005117}
5118
5119// Returns the media index for a local ice candidate given the content name.
5120bool PeerConnection::GetLocalCandidateMediaIndex(
5121 const std::string& content_name,
5122 int* sdp_mline_index) {
5123 if (!local_description() || !sdp_mline_index) {
5124 return false;
5125 }
5126
5127 bool content_found = false;
5128 const ContentInfos& contents = local_description()->description()->contents();
5129 for (size_t index = 0; index < contents.size(); ++index) {
5130 if (contents[index].name == content_name) {
5131 *sdp_mline_index = static_cast<int>(index);
5132 content_found = true;
5133 break;
5134 }
5135 }
5136 return content_found;
5137}
5138
5139bool PeerConnection::UseCandidatesInSessionDescription(
5140 const SessionDescriptionInterface* remote_desc) {
5141 if (!remote_desc) {
5142 return true;
5143 }
5144 bool ret = true;
5145
5146 for (size_t m = 0; m < remote_desc->number_of_mediasections(); ++m) {
5147 const IceCandidateCollection* candidates = remote_desc->candidates(m);
5148 for (size_t n = 0; n < candidates->count(); ++n) {
5149 const IceCandidateInterface* candidate = candidates->at(n);
5150 bool valid = false;
5151 if (!ReadyToUseRemoteCandidate(candidate, remote_desc, &valid)) {
5152 if (valid) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005153 RTC_LOG(LS_INFO)
5154 << "UseCandidatesInSessionDescription: Not ready to use "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005155 "candidate.";
Steve Anton75737c02017-11-06 10:37:17 -08005156 }
5157 continue;
5158 }
5159 ret = UseCandidate(candidate);
5160 if (!ret) {
5161 break;
5162 }
5163 }
5164 }
5165 return ret;
5166}
5167
5168bool PeerConnection::UseCandidate(const IceCandidateInterface* candidate) {
5169 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
5170 size_t remote_content_size =
5171 remote_description()->description()->contents().size();
5172 if (mediacontent_index >= remote_content_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005173 RTC_LOG(LS_ERROR) << "UseCandidate: Invalid candidate media index.";
Steve Anton75737c02017-11-06 10:37:17 -08005174 return false;
5175 }
5176
5177 cricket::ContentInfo content =
5178 remote_description()->description()->contents()[mediacontent_index];
5179 std::vector<cricket::Candidate> candidates;
5180 candidates.push_back(candidate->candidate());
5181 // Invoking BaseSession method to handle remote candidates.
5182 std::string error;
5183 if (transport_controller_->AddRemoteCandidates(content.name, candidates,
5184 &error)) {
5185 // Candidates successfully submitted for checking.
5186 if (ice_connection_state_ == PeerConnectionInterface::kIceConnectionNew ||
5187 ice_connection_state_ ==
5188 PeerConnectionInterface::kIceConnectionDisconnected) {
5189 // If state is New, then the session has just gotten its first remote ICE
5190 // candidates, so go to Checking.
5191 // If state is Disconnected, the session is re-using old candidates or
5192 // receiving additional ones, so go to Checking.
5193 // If state is Connected, stay Connected.
5194 // TODO(bemasc): If state is Connected, and the new candidates are for a
5195 // newly added transport, then the state actually _should_ move to
5196 // checking. Add a way to distinguish that case.
5197 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
5198 }
5199 // TODO(bemasc): If state is Completed, go back to Connected.
5200 } else {
5201 if (!error.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005202 RTC_LOG(LS_WARNING) << error;
Steve Anton75737c02017-11-06 10:37:17 -08005203 }
5204 }
5205 return true;
5206}
5207
5208void PeerConnection::RemoveUnusedChannels(const SessionDescription* desc) {
Steve Anton75737c02017-11-06 10:37:17 -08005209 // Destroy video channel first since it may have a pointer to the
5210 // voice channel.
5211 const cricket::ContentInfo* video_info = cricket::GetFirstVideoContent(desc);
Steve Anton6fec8802017-12-04 10:37:29 -08005212 if (!video_info || video_info->rejected) {
5213 DestroyTransceiverChannel(GetVideoTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08005214 }
5215
Steve Anton6fec8802017-12-04 10:37:29 -08005216 const cricket::ContentInfo* audio_info = cricket::GetFirstAudioContent(desc);
5217 if (!audio_info || audio_info->rejected) {
5218 DestroyTransceiverChannel(GetAudioTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08005219 }
5220
5221 const cricket::ContentInfo* data_info = cricket::GetFirstDataContent(desc);
5222 if (!data_info || data_info->rejected) {
Steve Anton6fec8802017-12-04 10:37:29 -08005223 DestroyDataChannel();
Steve Anton75737c02017-11-06 10:37:17 -08005224 }
5225}
5226
Steve Antoneda6ccd2017-12-04 10:21:55 -08005227std::string PeerConnection::GetTransportNameForMediaSection(
5228 const std::string& mid,
5229 const cricket::ContentGroup* bundle_group) const {
5230 if (!bundle_group) {
5231 return mid;
Steve Anton75737c02017-11-06 10:37:17 -08005232 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005233 const std::string* first_content_name = bundle_group->FirstContentName();
Steve Anton75737c02017-11-06 10:37:17 -08005234 if (!first_content_name) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005235 RTC_LOG(LS_WARNING) << "Tried to BUNDLE with no contents.";
Steve Antoneda6ccd2017-12-04 10:21:55 -08005236 return mid;
Steve Anton75737c02017-11-06 10:37:17 -08005237 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005238 if (!bundle_group->HasContentName(mid)) {
5239 RTC_LOG(LS_WARNING) << mid << " is not part of any bundle group";
5240 return mid;
Steve Anton75737c02017-11-06 10:37:17 -08005241 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005242 RTC_LOG(LS_INFO) << "Bundling " << mid << " on " << *first_content_name;
5243 return *first_content_name;
Steve Anton75737c02017-11-06 10:37:17 -08005244}
5245
Steve Antondcc3c022017-12-22 16:02:54 -08005246RTCErrorOr<const cricket::ContentGroup*> PeerConnection::GetEarlyBundleGroup(
5247 const SessionDescription& desc) const {
Steve Anton75737c02017-11-06 10:37:17 -08005248 const cricket::ContentGroup* bundle_group = nullptr;
5249 if (configuration_.bundle_policy ==
5250 PeerConnectionInterface::kBundlePolicyMaxBundle) {
Steve Antondcc3c022017-12-22 16:02:54 -08005251 bundle_group = desc.GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton75737c02017-11-06 10:37:17 -08005252 if (!bundle_group) {
Steve Anton8a006912017-12-04 15:25:56 -08005253 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5254 "max-bundle configured but session description "
5255 "has no BUNDLE group");
Steve Anton75737c02017-11-06 10:37:17 -08005256 }
5257 }
Steve Antondcc3c022017-12-22 16:02:54 -08005258 return std::move(bundle_group);
5259}
5260
5261RTCError PeerConnection::CreateChannels(const SessionDescription& desc) {
5262 auto bundle_group_or_error = GetEarlyBundleGroup(desc);
5263 if (!bundle_group_or_error.ok()) {
5264 return bundle_group_or_error.MoveError();
5265 }
5266 const cricket::ContentGroup* bundle_group = bundle_group_or_error.MoveValue();
Steve Anton75737c02017-11-06 10:37:17 -08005267
Steve Antoneda6ccd2017-12-04 10:21:55 -08005268 // Creating the media channels and transport proxies.
Steve Antondcc3c022017-12-22 16:02:54 -08005269 const cricket::ContentInfo* voice = cricket::GetFirstAudioContent(&desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08005270 if (voice && !voice->rejected &&
5271 !GetAudioTransceiver()->internal()->channel()) {
5272 cricket::VoiceChannel* voice_channel = CreateVoiceChannel(
5273 voice->name,
5274 GetTransportNameForMediaSection(voice->name, bundle_group));
5275 if (!voice_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08005276 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5277 "Failed to create voice channel.");
Steve Antoneda6ccd2017-12-04 10:21:55 -08005278 }
5279 GetAudioTransceiver()->internal()->SetChannel(voice_channel);
5280 }
5281
Steve Antondcc3c022017-12-22 16:02:54 -08005282 const cricket::ContentInfo* video = cricket::GetFirstVideoContent(&desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08005283 if (video && !video->rejected &&
5284 !GetVideoTransceiver()->internal()->channel()) {
5285 cricket::VideoChannel* video_channel = CreateVideoChannel(
5286 video->name,
5287 GetTransportNameForMediaSection(video->name, bundle_group));
5288 if (!video_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08005289 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5290 "Failed to create video channel.");
Steve Anton75737c02017-11-06 10:37:17 -08005291 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005292 GetVideoTransceiver()->internal()->SetChannel(video_channel);
Steve Anton75737c02017-11-06 10:37:17 -08005293 }
5294
Steve Antondcc3c022017-12-22 16:02:54 -08005295 const cricket::ContentInfo* data = cricket::GetFirstDataContent(&desc);
Steve Anton75737c02017-11-06 10:37:17 -08005296 if (data_channel_type_ != cricket::DCT_NONE && data && !data->rejected &&
5297 !rtp_data_channel_ && !sctp_transport_) {
Steve Antoneda6ccd2017-12-04 10:21:55 -08005298 if (!CreateDataChannel(data->name, GetTransportNameForMediaSection(
5299 data->name, bundle_group))) {
Steve Anton8a006912017-12-04 15:25:56 -08005300 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5301 "Failed to create data channel.");
Steve Anton75737c02017-11-06 10:37:17 -08005302 }
5303 }
5304
Steve Anton8a006912017-12-04 15:25:56 -08005305 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08005306}
5307
Steve Anton4171afb2017-11-20 10:20:22 -08005308// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08005309cricket::VoiceChannel* PeerConnection::CreateVoiceChannel(
5310 const std::string& mid,
5311 const std::string& transport_name) {
Steve Anton75737c02017-11-06 10:37:17 -08005312 cricket::DtlsTransportInternal* rtp_dtls_transport =
5313 transport_controller_->CreateDtlsTransport(
5314 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5315 cricket::DtlsTransportInternal* rtcp_dtls_transport = nullptr;
5316 if (configuration_.rtcp_mux_policy !=
5317 PeerConnectionInterface::kRtcpMuxPolicyRequire) {
5318 rtcp_dtls_transport = transport_controller_->CreateDtlsTransport(
5319 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
5320 }
5321
5322 cricket::VoiceChannel* voice_channel = channel_manager()->CreateVoiceChannel(
5323 call_.get(), configuration_.media_config, rtp_dtls_transport,
Steve Antoneda6ccd2017-12-04 10:21:55 -08005324 rtcp_dtls_transport, signaling_thread(), mid, SrtpRequired(),
5325 audio_options_);
Steve Anton75737c02017-11-06 10:37:17 -08005326 if (!voice_channel) {
5327 transport_controller_->DestroyDtlsTransport(
5328 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5329 if (rtcp_dtls_transport) {
5330 transport_controller_->DestroyDtlsTransport(
5331 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
5332 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005333 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08005334 }
Steve Anton75737c02017-11-06 10:37:17 -08005335 voice_channel->SignalRtcpMuxFullyActive.connect(
5336 this, &PeerConnection::DestroyRtcpTransport_n);
5337 voice_channel->SignalDtlsSrtpSetupFailure.connect(
5338 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08005339 voice_channel->SignalSentPacket.connect(this,
5340 &PeerConnection::OnSentPacket_w);
Steve Anton4171afb2017-11-20 10:20:22 -08005341
Steve Antoneda6ccd2017-12-04 10:21:55 -08005342 return voice_channel;
Steve Anton75737c02017-11-06 10:37:17 -08005343}
5344
Steve Anton4171afb2017-11-20 10:20:22 -08005345// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08005346cricket::VideoChannel* PeerConnection::CreateVideoChannel(
5347 const std::string& mid,
5348 const std::string& transport_name) {
Steve Anton75737c02017-11-06 10:37:17 -08005349 cricket::DtlsTransportInternal* rtp_dtls_transport =
5350 transport_controller_->CreateDtlsTransport(
5351 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5352 cricket::DtlsTransportInternal* rtcp_dtls_transport = nullptr;
5353 if (configuration_.rtcp_mux_policy !=
5354 PeerConnectionInterface::kRtcpMuxPolicyRequire) {
5355 rtcp_dtls_transport = transport_controller_->CreateDtlsTransport(
5356 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
5357 }
5358
5359 cricket::VideoChannel* video_channel = channel_manager()->CreateVideoChannel(
5360 call_.get(), configuration_.media_config, rtp_dtls_transport,
Steve Antoneda6ccd2017-12-04 10:21:55 -08005361 rtcp_dtls_transport, signaling_thread(), mid, SrtpRequired(),
5362 video_options_);
Steve Anton75737c02017-11-06 10:37:17 -08005363
5364 if (!video_channel) {
5365 transport_controller_->DestroyDtlsTransport(
5366 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5367 if (rtcp_dtls_transport) {
5368 transport_controller_->DestroyDtlsTransport(
5369 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
5370 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005371 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08005372 }
Steve Anton75737c02017-11-06 10:37:17 -08005373 video_channel->SignalRtcpMuxFullyActive.connect(
5374 this, &PeerConnection::DestroyRtcpTransport_n);
5375 video_channel->SignalDtlsSrtpSetupFailure.connect(
5376 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08005377 video_channel->SignalSentPacket.connect(this,
5378 &PeerConnection::OnSentPacket_w);
Steve Anton4171afb2017-11-20 10:20:22 -08005379
Steve Antoneda6ccd2017-12-04 10:21:55 -08005380 return video_channel;
Steve Anton75737c02017-11-06 10:37:17 -08005381}
5382
Steve Antoneda6ccd2017-12-04 10:21:55 -08005383bool PeerConnection::CreateDataChannel(const std::string& mid,
5384 const std::string& transport_name) {
Steve Anton75737c02017-11-06 10:37:17 -08005385 bool sctp = (data_channel_type_ == cricket::DCT_SCTP);
5386 if (sctp) {
5387 if (!sctp_factory_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005388 RTC_LOG(LS_ERROR)
Steve Anton75737c02017-11-06 10:37:17 -08005389 << "Trying to create SCTP transport, but didn't compile with "
5390 "SCTP support (HAVE_SCTP)";
5391 return false;
5392 }
5393 if (!network_thread()->Invoke<bool>(
5394 RTC_FROM_HERE, rtc::Bind(&PeerConnection::CreateSctpTransport_n,
Steve Antoneda6ccd2017-12-04 10:21:55 -08005395 this, mid, transport_name))) {
Steve Anton75737c02017-11-06 10:37:17 -08005396 return false;
5397 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005398 for (const auto& channel : sctp_data_channels_) {
5399 channel->OnTransportChannelCreated();
5400 }
Steve Anton75737c02017-11-06 10:37:17 -08005401 } else {
Steve Anton75737c02017-11-06 10:37:17 -08005402 cricket::DtlsTransportInternal* rtp_dtls_transport =
5403 transport_controller_->CreateDtlsTransport(
5404 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5405 cricket::DtlsTransportInternal* rtcp_dtls_transport = nullptr;
5406 if (configuration_.rtcp_mux_policy !=
5407 PeerConnectionInterface::kRtcpMuxPolicyRequire) {
5408 rtcp_dtls_transport = transport_controller_->CreateDtlsTransport(
5409 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
5410 }
5411
5412 rtp_data_channel_ = channel_manager()->CreateRtpDataChannel(
5413 configuration_.media_config, rtp_dtls_transport, rtcp_dtls_transport,
Steve Antoneda6ccd2017-12-04 10:21:55 -08005414 signaling_thread(), mid, SrtpRequired());
Steve Anton75737c02017-11-06 10:37:17 -08005415
5416 if (!rtp_data_channel_) {
5417 transport_controller_->DestroyDtlsTransport(
5418 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5419 if (rtcp_dtls_transport) {
5420 transport_controller_->DestroyDtlsTransport(
5421 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
5422 }
5423 return false;
5424 }
5425
5426 rtp_data_channel_->SignalRtcpMuxFullyActive.connect(
5427 this, &PeerConnection::DestroyRtcpTransport_n);
5428 rtp_data_channel_->SignalDtlsSrtpSetupFailure.connect(
5429 this, &PeerConnection::OnDtlsSrtpSetupFailure);
5430 rtp_data_channel_->SignalSentPacket.connect(
5431 this, &PeerConnection::OnSentPacket_w);
5432 }
5433
Steve Anton75737c02017-11-06 10:37:17 -08005434 return true;
5435}
5436
5437Call::Stats PeerConnection::GetCallStats() {
5438 if (!worker_thread()->IsCurrent()) {
5439 return worker_thread()->Invoke<Call::Stats>(
5440 RTC_FROM_HERE, rtc::Bind(&PeerConnection::GetCallStats, this));
5441 }
5442 if (call_) {
5443 return call_->GetStats();
5444 } else {
5445 return Call::Stats();
5446 }
5447}
5448
Steve Anton75737c02017-11-06 10:37:17 -08005449bool PeerConnection::CreateSctpTransport_n(const std::string& content_name,
5450 const std::string& transport_name) {
5451 RTC_DCHECK(network_thread()->IsCurrent());
5452 RTC_DCHECK(sctp_factory_);
5453 cricket::DtlsTransportInternal* tc =
5454 transport_controller_->CreateDtlsTransport_n(
5455 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5456 sctp_transport_ = sctp_factory_->CreateSctpTransport(tc);
5457 RTC_DCHECK(sctp_transport_);
5458 sctp_invoker_.reset(new rtc::AsyncInvoker());
5459 sctp_transport_->SignalReadyToSendData.connect(
5460 this, &PeerConnection::OnSctpTransportReadyToSendData_n);
5461 sctp_transport_->SignalDataReceived.connect(
5462 this, &PeerConnection::OnSctpTransportDataReceived_n);
5463 sctp_transport_->SignalStreamClosedRemotely.connect(
5464 this, &PeerConnection::OnSctpStreamClosedRemotely_n);
Oskar Sundbom9b28a032017-11-16 10:53:30 +01005465 sctp_transport_name_ = transport_name;
5466 sctp_content_name_ = content_name;
Steve Anton75737c02017-11-06 10:37:17 -08005467 return true;
5468}
5469
5470void PeerConnection::ChangeSctpTransport_n(const std::string& transport_name) {
5471 RTC_DCHECK(network_thread()->IsCurrent());
5472 RTC_DCHECK(sctp_transport_);
5473 RTC_DCHECK(sctp_transport_name_);
5474 std::string old_sctp_transport_name = *sctp_transport_name_;
Oskar Sundbom9b28a032017-11-16 10:53:30 +01005475 sctp_transport_name_ = transport_name;
Steve Anton75737c02017-11-06 10:37:17 -08005476 cricket::DtlsTransportInternal* tc =
5477 transport_controller_->CreateDtlsTransport_n(
5478 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5479 sctp_transport_->SetTransportChannel(tc);
5480 transport_controller_->DestroyDtlsTransport_n(
5481 old_sctp_transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5482}
5483
5484void PeerConnection::DestroySctpTransport_n() {
5485 RTC_DCHECK(network_thread()->IsCurrent());
5486 sctp_transport_.reset(nullptr);
Taylor Brandstetter389a97c2018-01-03 16:26:06 -08005487 transport_controller_->DestroyDtlsTransport_n(
5488 *sctp_transport_name_, cricket::ICE_CANDIDATE_COMPONENT_RTP);
Steve Anton75737c02017-11-06 10:37:17 -08005489 sctp_content_name_.reset();
5490 sctp_transport_name_.reset();
5491 sctp_invoker_.reset(nullptr);
5492 sctp_ready_to_send_data_ = false;
5493}
5494
5495void PeerConnection::OnSctpTransportReadyToSendData_n() {
5496 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5497 RTC_DCHECK(network_thread()->IsCurrent());
5498 // Note: Cannot use rtc::Bind here because it will grab a reference to
5499 // PeerConnection and potentially cause PeerConnection to live longer than
5500 // expected. It is safe not to grab a reference since the sctp_invoker_ will
5501 // be destroyed before PeerConnection is destroyed, and at that point all
5502 // pending tasks will be cleared.
5503 sctp_invoker_->AsyncInvoke<void>(RTC_FROM_HERE, signaling_thread(), [this] {
5504 OnSctpTransportReadyToSendData_s(true);
5505 });
5506}
5507
5508void PeerConnection::OnSctpTransportReadyToSendData_s(bool ready) {
5509 RTC_DCHECK(signaling_thread()->IsCurrent());
5510 sctp_ready_to_send_data_ = ready;
5511 SignalSctpReadyToSendData(ready);
5512}
5513
5514void PeerConnection::OnSctpTransportDataReceived_n(
5515 const cricket::ReceiveDataParams& params,
5516 const rtc::CopyOnWriteBuffer& payload) {
5517 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5518 RTC_DCHECK(network_thread()->IsCurrent());
5519 // Note: Cannot use rtc::Bind here because it will grab a reference to
5520 // PeerConnection and potentially cause PeerConnection to live longer than
5521 // expected. It is safe not to grab a reference since the sctp_invoker_ will
5522 // be destroyed before PeerConnection is destroyed, and at that point all
5523 // pending tasks will be cleared.
5524 sctp_invoker_->AsyncInvoke<void>(
5525 RTC_FROM_HERE, signaling_thread(), [this, params, payload] {
5526 OnSctpTransportDataReceived_s(params, payload);
5527 });
5528}
5529
5530void PeerConnection::OnSctpTransportDataReceived_s(
5531 const cricket::ReceiveDataParams& params,
5532 const rtc::CopyOnWriteBuffer& payload) {
5533 RTC_DCHECK(signaling_thread()->IsCurrent());
5534 if (params.type == cricket::DMT_CONTROL && IsOpenMessage(payload)) {
5535 // Received OPEN message; parse and signal that a new data channel should
5536 // be created.
5537 std::string label;
5538 InternalDataChannelInit config;
5539 config.id = params.ssrc;
5540 if (!ParseDataChannelOpenMessage(payload, &label, &config)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005541 RTC_LOG(LS_WARNING) << "Failed to parse the OPEN message for sid "
5542 << params.ssrc;
Steve Anton75737c02017-11-06 10:37:17 -08005543 return;
5544 }
5545 config.open_handshake_role = InternalDataChannelInit::kAcker;
5546 OnDataChannelOpenMessage(label, config);
5547 } else {
5548 // Otherwise just forward the signal.
5549 SignalSctpDataReceived(params, payload);
5550 }
5551}
5552
5553void PeerConnection::OnSctpStreamClosedRemotely_n(int sid) {
5554 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5555 RTC_DCHECK(network_thread()->IsCurrent());
5556 sctp_invoker_->AsyncInvoke<void>(
5557 RTC_FROM_HERE, signaling_thread(),
5558 rtc::Bind(&sigslot::signal1<int>::operator(),
5559 &SignalSctpStreamClosedRemotely, sid));
5560}
5561
5562// Returns false if bundle is enabled and rtcp_mux is disabled.
5563bool PeerConnection::ValidateBundleSettings(const SessionDescription* desc) {
5564 bool bundle_enabled = desc->HasGroup(cricket::GROUP_TYPE_BUNDLE);
5565 if (!bundle_enabled)
5566 return true;
5567
5568 const cricket::ContentGroup* bundle_group =
5569 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
5570 RTC_DCHECK(bundle_group != NULL);
5571
5572 const cricket::ContentInfos& contents = desc->contents();
5573 for (cricket::ContentInfos::const_iterator citer = contents.begin();
5574 citer != contents.end(); ++citer) {
5575 const cricket::ContentInfo* content = (&*citer);
5576 RTC_DCHECK(content != NULL);
5577 if (bundle_group->HasContentName(content->name) && !content->rejected &&
Steve Anton5adfafd2017-12-20 16:34:00 -08005578 content->type == MediaProtocolType::kRtp) {
Steve Anton75737c02017-11-06 10:37:17 -08005579 if (!HasRtcpMuxEnabled(content))
5580 return false;
5581 }
5582 }
5583 // RTCP-MUX is enabled in all the contents.
5584 return true;
5585}
5586
5587bool PeerConnection::HasRtcpMuxEnabled(const cricket::ContentInfo* content) {
Steve Antonb1c1de12017-12-21 15:14:30 -08005588 return content->media_description()->rtcp_mux();
Steve Anton75737c02017-11-06 10:37:17 -08005589}
5590
Steve Anton8a006912017-12-04 15:25:56 -08005591RTCError PeerConnection::ValidateSessionDescription(
Steve Anton75737c02017-11-06 10:37:17 -08005592 const SessionDescriptionInterface* sdesc,
Steve Anton8a006912017-12-04 15:25:56 -08005593 cricket::ContentSource source) {
Steve Antonf8470812017-12-04 10:46:21 -08005594 if (session_error() != SessionError::kNone) {
Steve Anton8a006912017-12-04 15:25:56 -08005595 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
Steve Anton75737c02017-11-06 10:37:17 -08005596 }
5597
5598 if (!sdesc || !sdesc->description()) {
Steve Anton8a006912017-12-04 15:25:56 -08005599 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidSdp);
Steve Anton75737c02017-11-06 10:37:17 -08005600 }
5601
Steve Anton3828c062017-12-06 10:34:51 -08005602 SdpType type = sdesc->GetType();
5603 if ((source == cricket::CS_LOCAL && !ExpectSetLocalDescription(type)) ||
5604 (source == cricket::CS_REMOTE && !ExpectSetRemoteDescription(type))) {
Steve Anton8a006912017-12-04 15:25:56 -08005605 LOG_AND_RETURN_ERROR(
5606 RTCErrorType::INVALID_PARAMETER,
5607 "Called in wrong state: " + GetSignalingStateString(signaling_state()));
Steve Anton75737c02017-11-06 10:37:17 -08005608 }
5609
5610 // Verify crypto settings.
5611 std::string crypto_error;
Steve Anton8a006912017-12-04 15:25:56 -08005612 if (webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED ||
5613 dtls_enabled_) {
Harald Alvestrand194939b2018-01-24 16:04:13 +01005614 RTCError crypto_error =
5615 VerifyCrypto(sdesc->description(), dtls_enabled_, uma_observer_);
Steve Anton8a006912017-12-04 15:25:56 -08005616 if (!crypto_error.ok()) {
5617 return crypto_error;
5618 }
Steve Anton75737c02017-11-06 10:37:17 -08005619 }
5620
5621 // Verify ice-ufrag and ice-pwd.
5622 if (!VerifyIceUfragPwdPresent(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08005623 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5624 kSdpWithoutIceUfragPwd);
Steve Anton75737c02017-11-06 10:37:17 -08005625 }
5626
5627 if (!ValidateBundleSettings(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08005628 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5629 kBundleWithoutRtcpMux);
Steve Anton75737c02017-11-06 10:37:17 -08005630 }
5631
5632 // TODO(skvlad): When the local rtcp-mux policy is Require, reject any
5633 // m-lines that do not rtcp-mux enabled.
5634
5635 // Verify m-lines in Answer when compared against Offer.
Steve Anton3828c062017-12-06 10:34:51 -08005636 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Seth Hampsonae8a90a2018-02-13 15:33:48 -08005637 // With an answer we want to compare the new answer session description with
5638 // the offer's session description from the current negotiation.
Steve Anton75737c02017-11-06 10:37:17 -08005639 const cricket::SessionDescription* offer_desc =
5640 (source == cricket::CS_LOCAL) ? remote_description()->description()
5641 : local_description()->description();
Seth Hampsonae8a90a2018-02-13 15:33:48 -08005642 if (!MediaSectionsHaveSameCount(*offer_desc, *sdesc->description()) ||
5643 !MediaSectionsInSameOrder(*offer_desc, nullptr, *sdesc->description(),
5644 type)) {
Steve Anton8a006912017-12-04 15:25:56 -08005645 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5646 kMlineMismatchInAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08005647 }
5648 } else {
Steve Anton75737c02017-11-06 10:37:17 -08005649 // The re-offers should respect the order of m= sections in current
5650 // description. See RFC3264 Section 8 paragraph 4 for more details.
Seth Hampsonae8a90a2018-02-13 15:33:48 -08005651 // With a re-offer, either the current local or current remote descriptions
5652 // could be the most up to date, so we would like to check against both of
5653 // them if they exist. It could be the case that one of them has a 0 port
5654 // for a media section, but the other does not. This is important to check
5655 // against in the case that we are recycling an m= section.
5656 const cricket::SessionDescription* current_desc = nullptr;
5657 const cricket::SessionDescription* secondary_current_desc = nullptr;
5658 if (local_description()) {
5659 current_desc = local_description()->description();
5660 if (remote_description()) {
5661 secondary_current_desc = remote_description()->description();
5662 }
5663 } else if (remote_description()) {
5664 current_desc = remote_description()->description();
5665 }
Steve Anton75737c02017-11-06 10:37:17 -08005666 if (current_desc &&
Seth Hampsonae8a90a2018-02-13 15:33:48 -08005667 !MediaSectionsInSameOrder(*current_desc, secondary_current_desc,
5668 *sdesc->description(), type)) {
Steve Anton8a006912017-12-04 15:25:56 -08005669 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5670 kMlineMismatchInSubsequentOffer);
Steve Anton75737c02017-11-06 10:37:17 -08005671 }
5672 }
5673
Steve Anton8a006912017-12-04 15:25:56 -08005674 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08005675}
5676
Steve Anton3828c062017-12-06 10:34:51 -08005677bool PeerConnection::ExpectSetLocalDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08005678 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08005679 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08005680 return (state == PeerConnectionInterface::kStable) ||
5681 (state == PeerConnectionInterface::kHaveLocalOffer);
Steve Anton20393062017-12-04 16:24:52 -08005682 } else {
Steve Anton3828c062017-12-06 10:34:51 -08005683 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08005684 return (state == PeerConnectionInterface::kHaveRemoteOffer) ||
5685 (state == PeerConnectionInterface::kHaveLocalPrAnswer);
5686 }
5687}
5688
Steve Anton3828c062017-12-06 10:34:51 -08005689bool PeerConnection::ExpectSetRemoteDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08005690 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08005691 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08005692 return (state == PeerConnectionInterface::kStable) ||
5693 (state == PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton20393062017-12-04 16:24:52 -08005694 } else {
Steve Anton3828c062017-12-06 10:34:51 -08005695 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08005696 return (state == PeerConnectionInterface::kHaveLocalOffer) ||
5697 (state == PeerConnectionInterface::kHaveRemotePrAnswer);
5698 }
5699}
5700
Steve Antonf8470812017-12-04 10:46:21 -08005701const char* PeerConnection::SessionErrorToString(SessionError error) const {
5702 switch (error) {
5703 case SessionError::kNone:
5704 return "ERROR_NONE";
5705 case SessionError::kContent:
5706 return "ERROR_CONTENT";
5707 case SessionError::kTransport:
5708 return "ERROR_TRANSPORT";
5709 }
5710 RTC_NOTREACHED();
5711 return "";
5712}
5713
Steve Anton75737c02017-11-06 10:37:17 -08005714std::string PeerConnection::GetSessionErrorMsg() {
5715 std::ostringstream desc;
Steve Antonf8470812017-12-04 10:46:21 -08005716 desc << kSessionError << SessionErrorToString(session_error()) << ". ";
5717 desc << kSessionErrorDesc << session_error_desc() << ".";
Steve Anton75737c02017-11-06 10:37:17 -08005718 return desc.str();
5719}
5720
5721// We need to check the local/remote description for the Transport instead of
5722// the session, because a new Transport added during renegotiation may have
5723// them unset while the session has them set from the previous negotiation.
5724// Not doing so may trigger the auto generation of transport description and
5725// mess up DTLS identity information, ICE credential, etc.
5726bool PeerConnection::ReadyToUseRemoteCandidate(
5727 const IceCandidateInterface* candidate,
5728 const SessionDescriptionInterface* remote_desc,
5729 bool* valid) {
5730 *valid = true;
5731
5732 const SessionDescriptionInterface* current_remote_desc =
5733 remote_desc ? remote_desc : remote_description();
5734
5735 if (!current_remote_desc) {
5736 return false;
5737 }
5738
5739 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
5740 size_t remote_content_size =
5741 current_remote_desc->description()->contents().size();
5742 if (mediacontent_index >= remote_content_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005743 RTC_LOG(LS_ERROR)
5744 << "ReadyToUseRemoteCandidate: Invalid candidate media index "
5745 << mediacontent_index;
Steve Anton75737c02017-11-06 10:37:17 -08005746
5747 *valid = false;
5748 return false;
5749 }
5750
5751 cricket::ContentInfo content =
5752 current_remote_desc->description()->contents()[mediacontent_index];
5753
5754 const std::string transport_name = GetTransportName(content.name);
5755 if (transport_name.empty()) {
5756 return false;
5757 }
5758 return transport_controller_->ReadyForRemoteCandidates(transport_name);
5759}
5760
5761bool PeerConnection::SrtpRequired() const {
5762 return dtls_enabled_ ||
5763 webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED;
5764}
5765
5766void PeerConnection::OnTransportControllerGatheringState(
5767 cricket::IceGatheringState state) {
5768 RTC_DCHECK(signaling_thread()->IsCurrent());
5769 if (state == cricket::kIceGatheringGathering) {
5770 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringGathering);
5771 } else if (state == cricket::kIceGatheringComplete) {
5772 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringComplete);
5773 }
5774}
5775
5776void PeerConnection::ReportTransportStats() {
Steve Antonc7b964c2018-02-01 14:39:45 -08005777 std::map<std::string, std::set<cricket::MediaType>>
5778 media_types_by_transport_name;
5779 for (auto transceiver : transceivers_) {
5780 if (transceiver->internal()->channel()) {
5781 const std::string& transport_name =
5782 transceiver->internal()->channel()->transport_name();
5783 media_types_by_transport_name[transport_name].insert(
Steve Anton69470252018-02-09 11:43:08 -08005784 transceiver->media_type());
Steve Antonc7b964c2018-02-01 14:39:45 -08005785 }
Steve Anton75737c02017-11-06 10:37:17 -08005786 }
5787 if (rtp_data_channel()) {
Steve Antonc7b964c2018-02-01 14:39:45 -08005788 media_types_by_transport_name[rtp_data_channel()->transport_name()].insert(
5789 cricket::MEDIA_TYPE_DATA);
Steve Anton75737c02017-11-06 10:37:17 -08005790 }
5791 if (sctp_transport_name_) {
Steve Antonc7b964c2018-02-01 14:39:45 -08005792 media_types_by_transport_name[*sctp_transport_name_].insert(
5793 cricket::MEDIA_TYPE_DATA);
Steve Anton75737c02017-11-06 10:37:17 -08005794 }
Steve Antonc7b964c2018-02-01 14:39:45 -08005795 for (const auto& entry : media_types_by_transport_name) {
5796 const std::string& transport_name = entry.first;
5797 const std::set<cricket::MediaType> media_types = entry.second;
Steve Anton75737c02017-11-06 10:37:17 -08005798 cricket::TransportStats stats;
Steve Antonc7b964c2018-02-01 14:39:45 -08005799 if (transport_controller_->GetStats(transport_name, &stats)) {
Steve Anton75737c02017-11-06 10:37:17 -08005800 ReportBestConnectionState(stats);
Steve Antonc7b964c2018-02-01 14:39:45 -08005801 ReportNegotiatedCiphers(stats, media_types);
Steve Anton75737c02017-11-06 10:37:17 -08005802 }
5803 }
5804}
5805// Walk through the ConnectionInfos to gather best connection usage
5806// for IPv4 and IPv6.
5807void PeerConnection::ReportBestConnectionState(
5808 const cricket::TransportStats& stats) {
5809 RTC_DCHECK(metrics_observer());
Steve Antonc7b964c2018-02-01 14:39:45 -08005810 for (const cricket::TransportChannelStats& channel_stats :
5811 stats.channel_stats) {
5812 for (const cricket::ConnectionInfo& connection_info :
5813 channel_stats.connection_infos) {
5814 if (!connection_info.best_connection) {
Steve Anton75737c02017-11-06 10:37:17 -08005815 continue;
5816 }
5817
5818 PeerConnectionEnumCounterType type = kPeerConnectionEnumCounterMax;
Steve Antonc7b964c2018-02-01 14:39:45 -08005819 const cricket::Candidate& local = connection_info.local_candidate;
5820 const cricket::Candidate& remote = connection_info.remote_candidate;
Steve Anton75737c02017-11-06 10:37:17 -08005821
5822 // Increment the counter for IceCandidatePairType.
5823 if (local.protocol() == cricket::TCP_PROTOCOL_NAME ||
5824 (local.type() == RELAY_PORT_TYPE &&
5825 local.relay_protocol() == cricket::TCP_PROTOCOL_NAME)) {
5826 type = kEnumCounterIceCandidatePairTypeTcp;
5827 } else if (local.protocol() == cricket::UDP_PROTOCOL_NAME) {
5828 type = kEnumCounterIceCandidatePairTypeUdp;
5829 } else {
5830 RTC_CHECK(0);
5831 }
5832 metrics_observer()->IncrementEnumCounter(
5833 type, GetIceCandidatePairCounter(local, remote),
5834 kIceCandidatePairMax);
5835
5836 // Increment the counter for IP type.
5837 if (local.address().family() == AF_INET) {
5838 metrics_observer()->IncrementEnumCounter(
5839 kEnumCounterAddressFamily, kBestConnections_IPv4,
5840 kPeerConnectionAddressFamilyCounter_Max);
5841
5842 } else if (local.address().family() == AF_INET6) {
5843 metrics_observer()->IncrementEnumCounter(
5844 kEnumCounterAddressFamily, kBestConnections_IPv6,
5845 kPeerConnectionAddressFamilyCounter_Max);
5846 } else {
5847 RTC_CHECK(0);
5848 }
5849
5850 return;
5851 }
5852 }
5853}
5854
5855void PeerConnection::ReportNegotiatedCiphers(
Steve Antonc7b964c2018-02-01 14:39:45 -08005856 const cricket::TransportStats& stats,
5857 const std::set<cricket::MediaType>& media_types) {
Steve Anton75737c02017-11-06 10:37:17 -08005858 RTC_DCHECK(metrics_observer());
5859 if (!dtls_enabled_ || stats.channel_stats.empty()) {
5860 return;
5861 }
5862
5863 int srtp_crypto_suite = stats.channel_stats[0].srtp_crypto_suite;
5864 int ssl_cipher_suite = stats.channel_stats[0].ssl_cipher_suite;
5865 if (srtp_crypto_suite == rtc::SRTP_INVALID_CRYPTO_SUITE &&
5866 ssl_cipher_suite == rtc::TLS_NULL_WITH_NULL_NULL) {
5867 return;
5868 }
5869
Steve Antonc7b964c2018-02-01 14:39:45 -08005870 for (cricket::MediaType media_type : media_types) {
5871 PeerConnectionEnumCounterType srtp_counter_type;
5872 PeerConnectionEnumCounterType ssl_counter_type;
5873 switch (media_type) {
5874 case cricket::MEDIA_TYPE_AUDIO:
5875 srtp_counter_type = kEnumCounterAudioSrtpCipher;
5876 ssl_counter_type = kEnumCounterAudioSslCipher;
5877 break;
5878 case cricket::MEDIA_TYPE_VIDEO:
5879 srtp_counter_type = kEnumCounterVideoSrtpCipher;
5880 ssl_counter_type = kEnumCounterVideoSslCipher;
5881 break;
5882 case cricket::MEDIA_TYPE_DATA:
5883 srtp_counter_type = kEnumCounterDataSrtpCipher;
5884 ssl_counter_type = kEnumCounterDataSslCipher;
5885 break;
5886 default:
5887 RTC_NOTREACHED();
5888 continue;
5889 }
5890 if (srtp_crypto_suite != rtc::SRTP_INVALID_CRYPTO_SUITE) {
5891 metrics_observer()->IncrementSparseEnumCounter(srtp_counter_type,
5892 srtp_crypto_suite);
5893 }
5894 if (ssl_cipher_suite != rtc::TLS_NULL_WITH_NULL_NULL) {
5895 metrics_observer()->IncrementSparseEnumCounter(ssl_counter_type,
5896 ssl_cipher_suite);
5897 }
Steve Anton75737c02017-11-06 10:37:17 -08005898 }
5899}
5900
5901void PeerConnection::OnSentPacket_w(const rtc::SentPacket& sent_packet) {
5902 RTC_DCHECK(worker_thread()->IsCurrent());
5903 RTC_DCHECK(call_);
5904 call_->OnSentPacket(sent_packet);
5905}
5906
5907const std::string PeerConnection::GetTransportName(
5908 const std::string& content_name) {
5909 cricket::BaseChannel* channel = GetChannel(content_name);
Steve Anton6fec8802017-12-04 10:37:29 -08005910 if (channel) {
5911 return channel->transport_name();
Steve Anton75737c02017-11-06 10:37:17 -08005912 }
Steve Anton6fec8802017-12-04 10:37:29 -08005913 if (sctp_transport_) {
5914 RTC_DCHECK(sctp_content_name_);
5915 RTC_DCHECK(sctp_transport_name_);
5916 if (content_name == *sctp_content_name_) {
5917 return *sctp_transport_name_;
5918 }
5919 }
5920 // Return an empty string if failed to retrieve the transport name.
5921 return "";
Steve Anton75737c02017-11-06 10:37:17 -08005922}
5923
5924void PeerConnection::DestroyRtcpTransport_n(const std::string& transport_name) {
5925 RTC_DCHECK(network_thread()->IsCurrent());
5926 transport_controller_->DestroyDtlsTransport_n(
5927 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
5928}
5929
Steve Anton6fec8802017-12-04 10:37:29 -08005930void PeerConnection::DestroyTransceiverChannel(
5931 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
5932 transceiver) {
5933 RTC_DCHECK(transceiver);
Steve Anton75737c02017-11-06 10:37:17 -08005934
Steve Anton6fec8802017-12-04 10:37:29 -08005935 cricket::BaseChannel* channel = transceiver->internal()->channel();
5936 if (channel) {
5937 transceiver->internal()->SetChannel(nullptr);
5938 DestroyBaseChannel(channel);
Steve Anton75737c02017-11-06 10:37:17 -08005939 }
5940}
5941
5942void PeerConnection::DestroyDataChannel() {
Steve Anton6fec8802017-12-04 10:37:29 -08005943 if (rtp_data_channel_) {
5944 OnDataChannelDestroyed();
5945 DestroyBaseChannel(rtp_data_channel_);
5946 rtp_data_channel_ = nullptr;
5947 }
5948
5949 // Note: Cannot use rtc::Bind to create a functor to invoke because it will
5950 // grab a reference to this PeerConnection. If this is called from the
5951 // PeerConnection destructor, the RefCountedObject vtable will have already
5952 // been destroyed (since it is a subclass of PeerConnection) and using
5953 // rtc::Bind will cause "Pure virtual function called" error to appear.
5954
5955 if (sctp_transport_) {
5956 OnDataChannelDestroyed();
5957 network_thread()->Invoke<void>(RTC_FROM_HERE,
5958 [this] { DestroySctpTransport_n(); });
5959 }
5960}
5961
5962void PeerConnection::DestroyBaseChannel(cricket::BaseChannel* channel) {
5963 RTC_DCHECK(channel);
5964 RTC_DCHECK(channel->rtp_dtls_transport());
5965
5966 // Need to cache these before destroying the base channel so that we do not
5967 // access uninitialized memory.
5968 const std::string transport_name =
5969 channel->rtp_dtls_transport()->transport_name();
5970 const bool need_to_delete_rtcp = (channel->rtcp_dtls_transport() != nullptr);
5971
5972 switch (channel->media_type()) {
5973 case cricket::MEDIA_TYPE_AUDIO:
5974 channel_manager()->DestroyVoiceChannel(
5975 static_cast<cricket::VoiceChannel*>(channel));
5976 break;
5977 case cricket::MEDIA_TYPE_VIDEO:
5978 channel_manager()->DestroyVideoChannel(
5979 static_cast<cricket::VideoChannel*>(channel));
5980 break;
5981 case cricket::MEDIA_TYPE_DATA:
5982 channel_manager()->DestroyRtpDataChannel(
5983 static_cast<cricket::RtpDataChannel*>(channel));
5984 break;
5985 default:
5986 RTC_NOTREACHED() << "Unknown media type: " << channel->media_type();
5987 break;
5988 }
5989
5990 // |channel| can no longer be used.
5991
Steve Anton75737c02017-11-06 10:37:17 -08005992 transport_controller_->DestroyDtlsTransport(
5993 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5994 if (need_to_delete_rtcp) {
5995 transport_controller_->DestroyDtlsTransport(
5996 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
5997 }
5998}
5999
Harald Alvestrand89061872018-01-02 14:08:34 +01006000void PeerConnection::ClearStatsCache() {
6001 if (stats_collector_) {
6002 stats_collector_->ClearCachedStatsReport();
6003 }
6004}
6005
henrike@webrtc.org28e20752013-07-10 00:45:36 +00006006} // namespace webrtc