blob: 15ec9509a0a36aca732ff3e56f25f9397470ca0f [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 Anton71439a62018-02-15 11:53:06 -0800564// Generates a string error message for SetLocalDescription/SetRemoteDescription
565// from an RTCError.
566std::string GetSetDescriptionErrorMessage(cricket::ContentSource source,
567 SdpType type,
568 const RTCError& error) {
569 std::ostringstream oss;
570 oss << "Failed to set " << (source == cricket::CS_LOCAL ? "local" : "remote")
571 << " " << SdpTypeToString(type) << " sdp: " << error.message();
572 return oss.str();
573}
574
Steve Anton75737c02017-11-06 10:37:17 -0800575} // namespace
576
Henrik Boström31638672017-11-23 17:48:32 +0100577// Upon completion, posts a task to execute the callback of the
578// SetSessionDescriptionObserver asynchronously on the same thread. At this
579// point, the state of the peer connection might no longer reflect the effects
580// of the SetRemoteDescription operation, as the peer connection could have been
581// modified during the post.
582// TODO(hbos): Remove this class once we remove the version of
583// PeerConnectionInterface::SetRemoteDescription() that takes a
584// SetSessionDescriptionObserver as an argument.
585class PeerConnection::SetRemoteDescriptionObserverAdapter
586 : public rtc::RefCountedObject<SetRemoteDescriptionObserverInterface> {
587 public:
588 SetRemoteDescriptionObserverAdapter(
589 rtc::scoped_refptr<PeerConnection> pc,
590 rtc::scoped_refptr<SetSessionDescriptionObserver> wrapper)
591 : pc_(std::move(pc)), wrapper_(std::move(wrapper)) {}
592
593 // SetRemoteDescriptionObserverInterface implementation.
594 void OnSetRemoteDescriptionComplete(RTCError error) override {
595 if (error.ok())
596 pc_->PostSetSessionDescriptionSuccess(wrapper_);
597 else
598 pc_->PostSetSessionDescriptionFailure(wrapper_, error.message());
599 }
600
601 private:
602 rtc::scoped_refptr<PeerConnection> pc_;
603 rtc::scoped_refptr<SetSessionDescriptionObserver> wrapper_;
604};
605
deadbeef293e9262017-01-11 12:28:30 -0800606bool PeerConnectionInterface::RTCConfiguration::operator==(
607 const PeerConnectionInterface::RTCConfiguration& o) const {
608 // This static_assert prevents us from accidentally breaking operator==.
Steve Anton300bf8e2017-07-14 10:13:10 -0700609 // Note: Order matters! Fields must be ordered the same as RTCConfiguration.
deadbeef293e9262017-01-11 12:28:30 -0800610 struct stuff_being_tested_for_equality {
Magnus Jedvert3beb2072017-07-14 14:23:56 +0000611 IceServers servers;
Steve Anton300bf8e2017-07-14 10:13:10 -0700612 IceTransportsType type;
deadbeef293e9262017-01-11 12:28:30 -0800613 BundlePolicy bundle_policy;
614 RtcpMuxPolicy rtcp_mux_policy;
Steve Anton300bf8e2017-07-14 10:13:10 -0700615 std::vector<rtc::scoped_refptr<rtc::RTCCertificate>> certificates;
616 int ice_candidate_pool_size;
617 bool disable_ipv6;
618 bool disable_ipv6_on_wifi;
deadbeefd21eab32017-07-26 16:50:11 -0700619 int max_ipv6_networks;
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +0100620 bool disable_link_local_networks;
Steve Anton300bf8e2017-07-14 10:13:10 -0700621 bool enable_rtp_data_channel;
622 rtc::Optional<int> screencast_min_bitrate;
623 rtc::Optional<bool> combined_audio_video_bwe;
624 rtc::Optional<bool> enable_dtls_srtp;
deadbeef293e9262017-01-11 12:28:30 -0800625 TcpCandidatePolicy tcp_candidate_policy;
626 CandidateNetworkPolicy candidate_network_policy;
627 int audio_jitter_buffer_max_packets;
628 bool audio_jitter_buffer_fast_accelerate;
629 int ice_connection_receiving_timeout;
630 int ice_backup_candidate_pair_ping_interval;
631 ContinualGatheringPolicy continual_gathering_policy;
deadbeef293e9262017-01-11 12:28:30 -0800632 bool prioritize_most_likely_ice_candidate_pairs;
633 struct cricket::MediaConfig media_config;
deadbeef293e9262017-01-11 12:28:30 -0800634 bool prune_turn_ports;
635 bool presume_writable_when_fully_relayed;
636 bool enable_ice_renomination;
637 bool redetermine_role_on_ice_restart;
skvlad51072462017-02-02 11:50:14 -0800638 rtc::Optional<int> ice_check_min_interval;
Steve Anton300bf8e2017-07-14 10:13:10 -0700639 rtc::Optional<rtc::IntervalRange> ice_regather_interval_range;
Jonas Orelandbdcee282017-10-10 14:01:40 +0200640 webrtc::TurnCustomizer* turn_customizer;
Steve Anton79e79602017-11-20 10:25:56 -0800641 SdpSemantics sdp_semantics;
Qingsi Wang9a5c6f82018-02-01 10:38:40 -0800642 rtc::Optional<rtc::AdapterType> network_preference;
deadbeef293e9262017-01-11 12:28:30 -0800643 };
644 static_assert(sizeof(stuff_being_tested_for_equality) == sizeof(*this),
645 "Did you add something to RTCConfiguration and forget to "
646 "update operator==?");
647 return type == o.type && servers == o.servers &&
648 bundle_policy == o.bundle_policy &&
649 rtcp_mux_policy == o.rtcp_mux_policy &&
650 tcp_candidate_policy == o.tcp_candidate_policy &&
651 candidate_network_policy == o.candidate_network_policy &&
652 audio_jitter_buffer_max_packets == o.audio_jitter_buffer_max_packets &&
653 audio_jitter_buffer_fast_accelerate ==
654 o.audio_jitter_buffer_fast_accelerate &&
655 ice_connection_receiving_timeout ==
656 o.ice_connection_receiving_timeout &&
657 ice_backup_candidate_pair_ping_interval ==
658 o.ice_backup_candidate_pair_ping_interval &&
659 continual_gathering_policy == o.continual_gathering_policy &&
660 certificates == o.certificates &&
661 prioritize_most_likely_ice_candidate_pairs ==
662 o.prioritize_most_likely_ice_candidate_pairs &&
663 media_config == o.media_config && disable_ipv6 == o.disable_ipv6 &&
zhihuangb09b3f92017-03-07 14:40:51 -0800664 disable_ipv6_on_wifi == o.disable_ipv6_on_wifi &&
deadbeefd21eab32017-07-26 16:50:11 -0700665 max_ipv6_networks == o.max_ipv6_networks &&
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +0100666 disable_link_local_networks == o.disable_link_local_networks &&
deadbeef293e9262017-01-11 12:28:30 -0800667 enable_rtp_data_channel == o.enable_rtp_data_channel &&
deadbeef293e9262017-01-11 12:28:30 -0800668 screencast_min_bitrate == o.screencast_min_bitrate &&
669 combined_audio_video_bwe == o.combined_audio_video_bwe &&
670 enable_dtls_srtp == o.enable_dtls_srtp &&
671 ice_candidate_pool_size == o.ice_candidate_pool_size &&
672 prune_turn_ports == o.prune_turn_ports &&
673 presume_writable_when_fully_relayed ==
674 o.presume_writable_when_fully_relayed &&
675 enable_ice_renomination == o.enable_ice_renomination &&
skvlad51072462017-02-02 11:50:14 -0800676 redetermine_role_on_ice_restart == o.redetermine_role_on_ice_restart &&
Steve Anton300bf8e2017-07-14 10:13:10 -0700677 ice_check_min_interval == o.ice_check_min_interval &&
Jonas Orelandbdcee282017-10-10 14:01:40 +0200678 ice_regather_interval_range == o.ice_regather_interval_range &&
Steve Anton79e79602017-11-20 10:25:56 -0800679 turn_customizer == o.turn_customizer &&
Qingsi Wang9a5c6f82018-02-01 10:38:40 -0800680 sdp_semantics == o.sdp_semantics &&
681 network_preference == o.network_preference;
deadbeef293e9262017-01-11 12:28:30 -0800682}
683
684bool PeerConnectionInterface::RTCConfiguration::operator!=(
685 const PeerConnectionInterface::RTCConfiguration& o) const {
686 return !(*this == o);
deadbeef3edec7c2016-12-10 11:44:26 -0800687}
688
zhihuang8f65cdf2016-05-06 18:40:30 -0700689// Generate a RTCP CNAME when a PeerConnection is created.
690std::string GenerateRtcpCname() {
691 std::string cname;
692 if (!rtc::CreateRandomString(kRtcpCnameLength, &cname)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100693 RTC_LOG(LS_ERROR) << "Failed to generate CNAME.";
nisseeb4ca4e2017-01-12 02:24:27 -0800694 RTC_NOTREACHED();
zhihuang8f65cdf2016-05-06 18:40:30 -0700695 }
696 return cname;
697}
698
zhihuang1c378ed2017-08-17 14:10:50 -0700699bool ValidateOfferAnswerOptions(
700 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options) {
701 return IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_audio) &&
702 IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_video);
olka3c747662017-08-17 06:50:32 -0700703}
704
zhihuang1c378ed2017-08-17 14:10:50 -0700705// From |rtc_options|, fill parts of |session_options| shared by all generated
706// m= sections (in other words, nothing that involves a map/array).
707void ExtractSharedMediaSessionOptions(
708 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options,
709 cricket::MediaSessionOptions* session_options) {
710 session_options->vad_enabled = rtc_options.voice_activity_detection;
711 session_options->bundle_enabled = rtc_options.use_rtp_mux;
712}
zhihuanga77e6bb2017-08-14 18:17:48 -0700713
zhihuang1c378ed2017-08-17 14:10:50 -0700714bool ConvertConstraintsToOfferAnswerOptions(
715 const MediaConstraintsInterface* constraints,
716 PeerConnectionInterface::RTCOfferAnswerOptions* offer_answer_options) {
olka3c747662017-08-17 06:50:32 -0700717 if (!constraints) {
718 return true;
719 }
zhihuang1c378ed2017-08-17 14:10:50 -0700720
721 bool value = false;
722 size_t mandatory_constraints_satisfied = 0;
723
724 if (FindConstraint(constraints,
725 MediaConstraintsInterface::kOfferToReceiveAudio, &value,
726 &mandatory_constraints_satisfied)) {
727 offer_answer_options->offer_to_receive_audio =
728 value ? PeerConnectionInterface::RTCOfferAnswerOptions::
729 kOfferToReceiveMediaTrue
730 : 0;
731 }
732
733 if (FindConstraint(constraints,
734 MediaConstraintsInterface::kOfferToReceiveVideo, &value,
735 &mandatory_constraints_satisfied)) {
736 offer_answer_options->offer_to_receive_video =
737 value ? PeerConnectionInterface::RTCOfferAnswerOptions::
738 kOfferToReceiveMediaTrue
739 : 0;
740 }
741 if (FindConstraint(constraints,
742 MediaConstraintsInterface::kVoiceActivityDetection, &value,
743 &mandatory_constraints_satisfied)) {
744 offer_answer_options->voice_activity_detection = value;
745 }
746 if (FindConstraint(constraints, MediaConstraintsInterface::kUseRtpMux, &value,
747 &mandatory_constraints_satisfied)) {
748 offer_answer_options->use_rtp_mux = value;
749 }
750 if (FindConstraint(constraints, MediaConstraintsInterface::kIceRestart,
751 &value, &mandatory_constraints_satisfied)) {
752 offer_answer_options->ice_restart = value;
753 }
754
deadbeefab9b2d12015-10-14 11:33:11 -0700755 return mandatory_constraints_satisfied == constraints->GetMandatory().size();
756}
757
zhihuang38ede132017-06-15 12:52:32 -0700758PeerConnection::PeerConnection(PeerConnectionFactory* factory,
759 std::unique_ptr<RtcEventLog> event_log,
760 std::unique_ptr<Call> call)
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000761 : factory_(factory),
zhihuang38ede132017-06-15 12:52:32 -0700762 event_log_(std::move(event_log)),
zhihuang8f65cdf2016-05-06 18:40:30 -0700763 rtcp_cname_(GenerateRtcpCname()),
deadbeefab9b2d12015-10-14 11:33:11 -0700764 local_streams_(StreamCollection::Create()),
zhihuang38ede132017-06-15 12:52:32 -0700765 remote_streams_(StreamCollection::Create()),
766 call_(std::move(call)) {}
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000767
768PeerConnection::~PeerConnection() {
Peter Boström1a9d6152015-12-08 22:15:17 +0100769 TRACE_EVENT0("webrtc", "PeerConnection::~PeerConnection");
Steve Anton4171afb2017-11-20 10:20:22 -0800770 RTC_DCHECK_RUN_ON(signaling_thread());
771
Steve Anton8af21862017-12-15 11:20:13 -0800772 // Need to stop transceivers before destroying the stats collector because
773 // AudioRtpSender has a reference to the StatsCollector it will update when
774 // stopping.
775 for (auto transceiver : transceivers_) {
776 transceiver->Stop();
777 }
Steve Anton4171afb2017-11-20 10:20:22 -0800778
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700779 stats_.reset(nullptr);
hbosb78306a2016-12-19 05:06:57 -0800780 if (stats_collector_) {
781 stats_collector_->WaitForPendingRequest();
782 stats_collector_ = nullptr;
783 }
Steve Anton75737c02017-11-06 10:37:17 -0800784
Steve Anton8af21862017-12-15 11:20:13 -0800785 // Don't destroy BaseChannels until after stats has been cleaned up so that
786 // the last stats request can still read from the channels.
787 DestroyAllChannels();
788
Mirko Bonadei675513b2017-11-09 11:09:25 +0100789 RTC_LOG(LS_INFO) << "Session: " << session_id() << " is destroyed.";
Steve Anton75737c02017-11-06 10:37:17 -0800790
791 webrtc_session_desc_factory_.reset();
792 sctp_invoker_.reset();
793 sctp_factory_.reset();
794 transport_controller_.reset();
795
deadbeef91dd5672016-05-18 16:55:30 -0700796 // port_allocator_ lives on the network thread and should be destroyed there.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700797 network_thread()->Invoke<void>(RTC_FROM_HERE,
nisseeaabdf62017-05-05 02:23:02 -0700798 [this] { port_allocator_.reset(); });
eladalon248fd4f2017-09-06 05:18:15 -0700799 // call_ and event_log_ must be destroyed on the worker thread.
Steve Anton978b8762017-09-29 12:15:02 -0700800 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
eladalon248fd4f2017-09-06 05:18:15 -0700801 call_.reset();
Qingsi Wang93a84392018-01-30 17:13:09 -0800802 // The event log must outlive call (and any other object that uses it).
eladalon248fd4f2017-09-06 05:18:15 -0700803 event_log_.reset();
804 });
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000805}
806
Steve Anton8af21862017-12-15 11:20:13 -0800807void PeerConnection::DestroyAllChannels() {
Steve Anton3fe1b152017-12-12 10:20:08 -0800808 // Destroy video channels first since they may have a pointer to a voice
809 // channel.
810 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -0800811 if (transceiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton3fe1b152017-12-12 10:20:08 -0800812 DestroyTransceiverChannel(transceiver);
813 }
814 }
815 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -0800816 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton3fe1b152017-12-12 10:20:08 -0800817 DestroyTransceiverChannel(transceiver);
818 }
819 }
820 DestroyDataChannel();
821}
822
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000823bool PeerConnection::Initialize(
buildbot@webrtc.org41451d42014-05-03 05:39:45 +0000824 const PeerConnectionInterface::RTCConfiguration& configuration,
kwibergd1fe2812016-04-27 06:47:29 -0700825 std::unique_ptr<cricket::PortAllocator> allocator,
Henrik Boströmd03c23b2016-06-01 11:44:18 +0200826 std::unique_ptr<rtc::RTCCertificateGeneratorInterface> cert_generator,
deadbeef653b8e02015-11-11 12:55:10 -0800827 PeerConnectionObserver* observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100828 TRACE_EVENT0("webrtc", "PeerConnection::Initialize");
Steve Anton038834f2017-07-14 15:59:59 -0700829
830 RTCError config_error = ValidateConfiguration(configuration);
831 if (!config_error.ok()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100832 RTC_LOG(LS_ERROR) << "Invalid configuration: " << config_error.message();
Steve Anton038834f2017-07-14 15:59:59 -0700833 return false;
834 }
835
deadbeef293e9262017-01-11 12:28:30 -0800836 if (!allocator) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100837 RTC_LOG(LS_ERROR)
838 << "PeerConnection initialized without a PortAllocator? "
Jonas Olsson45cc8902018-02-13 10:37:07 +0100839 "This shouldn't happen if using PeerConnectionFactory.";
deadbeef293e9262017-01-11 12:28:30 -0800840 return false;
841 }
Jonas Orelandbdcee282017-10-10 14:01:40 +0200842
deadbeef653b8e02015-11-11 12:55:10 -0800843 if (!observer) {
deadbeef293e9262017-01-11 12:28:30 -0800844 // TODO(deadbeef): Why do we do this?
Mirko Bonadei675513b2017-11-09 11:09:25 +0100845 RTC_LOG(LS_ERROR) << "PeerConnection initialized without a "
Jonas Olsson45cc8902018-02-13 10:37:07 +0100846 "PeerConnectionObserver";
deadbeef653b8e02015-11-11 12:55:10 -0800847 return false;
848 }
pthatcher@webrtc.org877ac762015-02-04 22:03:09 +0000849 observer_ = observer;
kwiberg0eb15ed2015-12-17 03:04:15 -0800850 port_allocator_ = std::move(allocator);
deadbeef653b8e02015-11-11 12:55:10 -0800851
deadbeef91dd5672016-05-18 16:55:30 -0700852 // The port allocator lives on the network thread and should be initialized
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700853 // there.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700854 if (!network_thread()->Invoke<bool>(
855 RTC_FROM_HERE, rtc::Bind(&PeerConnection::InitializePortAllocator_n,
856 this, configuration))) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000857 return false;
858 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000859
Steve Anton75737c02017-11-06 10:37:17 -0800860 // RFC 3264: The numeric value of the session id and version in the
861 // o line MUST be representable with a "64 bit signed integer".
862 // Due to this constraint session id |session_id_| is max limited to
863 // LLONG_MAX.
864 session_id_ = rtc::ToString(rtc::CreateRandomId64() & LLONG_MAX);
865 transport_controller_.reset(factory_->CreateTransportController(
Qingsi Wang93a84392018-01-30 17:13:09 -0800866 port_allocator_.get(), configuration.redetermine_role_on_ice_restart,
867 event_log_.get()));
Steve Anton75737c02017-11-06 10:37:17 -0800868 transport_controller_->SetIceRole(cricket::ICEROLE_CONTROLLED);
869 transport_controller_->SignalConnectionState.connect(
870 this, &PeerConnection::OnTransportControllerConnectionState);
871 transport_controller_->SignalGatheringState.connect(
872 this, &PeerConnection::OnTransportControllerGatheringState);
873 transport_controller_->SignalCandidatesGathered.connect(
874 this, &PeerConnection::OnTransportControllerCandidatesGathered);
875 transport_controller_->SignalCandidatesRemoved.connect(
876 this, &PeerConnection::OnTransportControllerCandidatesRemoved);
877 transport_controller_->SignalDtlsHandshakeError.connect(
878 this, &PeerConnection::OnTransportControllerDtlsHandshakeError);
879
880 sctp_factory_ = factory_->CreateSctpTransportInternalFactory();
zhihuang29ff8442016-07-27 11:07:25 -0700881
deadbeefab9b2d12015-10-14 11:33:11 -0700882 stats_.reset(new StatsCollector(this));
hbos74e1a4f2016-09-15 23:33:01 -0700883 stats_collector_ = RTCStatsCollector::Create(this);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000884
Steve Antonba818672017-11-06 10:21:57 -0800885 configuration_ = configuration;
886
Steve Anton75737c02017-11-06 10:37:17 -0800887 const PeerConnectionFactoryInterface::Options& options = factory_->options();
888
889 transport_controller_->SetSslMaxProtocolVersion(options.ssl_max_version);
890
891 // Obtain a certificate from RTCConfiguration if any were provided (optional).
892 rtc::scoped_refptr<rtc::RTCCertificate> certificate;
893 if (!configuration.certificates.empty()) {
894 // TODO(hbos,torbjorng): Decide on certificate-selection strategy instead of
895 // just picking the first one. The decision should be made based on the DTLS
896 // handshake. The DTLS negotiations need to know about all certificates.
897 certificate = configuration.certificates[0];
898 }
899
Steve Antond25da372017-11-06 14:50:29 -0800900 transport_controller_->SetIceConfig(ParseIceConfig(configuration));
Steve Anton75737c02017-11-06 10:37:17 -0800901
902 if (options.disable_encryption) {
903 dtls_enabled_ = false;
904 } else {
905 // Enable DTLS by default if we have an identity store or a certificate.
906 dtls_enabled_ = (cert_generator || certificate);
907 // |configuration| can override the default |dtls_enabled_| value.
908 if (configuration.enable_dtls_srtp) {
909 dtls_enabled_ = *(configuration.enable_dtls_srtp);
910 }
911 }
912
913 // Enable creation of RTP data channels if the kEnableRtpDataChannels is set.
914 // It takes precendence over the disable_sctp_data_channels
915 // PeerConnectionFactoryInterface::Options.
916 if (configuration.enable_rtp_data_channel) {
917 data_channel_type_ = cricket::DCT_RTP;
918 } else {
919 // DTLS has to be enabled to use SCTP.
920 if (!options.disable_sctp_data_channels && dtls_enabled_) {
921 data_channel_type_ = cricket::DCT_SCTP;
922 }
923 }
924
925 video_options_.screencast_min_bitrate_kbps =
926 configuration.screencast_min_bitrate;
927 audio_options_.combined_audio_video_bwe =
928 configuration.combined_audio_video_bwe;
929
930 audio_options_.audio_jitter_buffer_max_packets =
Oskar Sundbom9b28a032017-11-16 10:53:30 +0100931 configuration.audio_jitter_buffer_max_packets;
Steve Anton75737c02017-11-06 10:37:17 -0800932
933 audio_options_.audio_jitter_buffer_fast_accelerate =
Oskar Sundbom9b28a032017-11-16 10:53:30 +0100934 configuration.audio_jitter_buffer_fast_accelerate;
Steve Anton75737c02017-11-06 10:37:17 -0800935
936 // Whether the certificate generator/certificate is null or not determines
937 // what PeerConnectionDescriptionFactory will do, so make sure that we give it
938 // the right instructions by clearing the variables if needed.
939 if (!dtls_enabled_) {
940 cert_generator.reset();
941 certificate = nullptr;
942 } else if (certificate) {
943 // Favor generated certificate over the certificate generator.
944 cert_generator.reset();
945 }
946
947 webrtc_session_desc_factory_.reset(new WebRtcSessionDescriptionFactory(
948 signaling_thread(), channel_manager(), this, session_id(),
949 std::move(cert_generator), certificate));
950 webrtc_session_desc_factory_->SignalCertificateReady.connect(
951 this, &PeerConnection::OnCertificateReady);
952
953 if (options.disable_encryption) {
954 webrtc_session_desc_factory_->SetSdesPolicy(cricket::SEC_DISABLED);
955 }
956
957 webrtc_session_desc_factory_->set_enable_encrypted_rtp_header_extensions(
958 options.crypto_options.enable_encrypted_rtp_header_extensions);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000959
Steve Anton4171afb2017-11-20 10:20:22 -0800960 // Add default audio/video transceivers for Plan B SDP.
961 if (!IsUnifiedPlan()) {
962 transceivers_.push_back(
963 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
964 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_AUDIO)));
965 transceivers_.push_back(
966 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
967 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_VIDEO)));
968 }
969
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000970 return true;
971}
972
Steve Anton038834f2017-07-14 15:59:59 -0700973RTCError PeerConnection::ValidateConfiguration(
974 const RTCConfiguration& config) const {
975 if (config.ice_regather_interval_range &&
976 config.continual_gathering_policy == GATHER_ONCE) {
977 return RTCError(RTCErrorType::INVALID_PARAMETER,
978 "ice_regather_interval_range specified but continual "
979 "gathering policy is GATHER_ONCE");
980 }
981 return RTCError::OK();
982}
983
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000984rtc::scoped_refptr<StreamCollectionInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000985PeerConnection::local_streams() {
deadbeefab9b2d12015-10-14 11:33:11 -0700986 return local_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000987}
988
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000989rtc::scoped_refptr<StreamCollectionInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000990PeerConnection::remote_streams() {
deadbeefab9b2d12015-10-14 11:33:11 -0700991 return remote_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000992}
993
perkj@webrtc.orgc2dd5ee2014-11-04 11:31:29 +0000994bool PeerConnection::AddStream(MediaStreamInterface* local_stream) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100995 TRACE_EVENT0("webrtc", "PeerConnection::AddStream");
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000996 if (IsClosed()) {
997 return false;
998 }
deadbeefab9b2d12015-10-14 11:33:11 -0700999 if (!CanAddLocalMediaStream(local_streams_, local_stream)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001000 return false;
1001 }
deadbeefab9b2d12015-10-14 11:33:11 -07001002
1003 local_streams_->AddStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -08001004 MediaStreamObserver* observer = new MediaStreamObserver(local_stream);
1005 observer->SignalAudioTrackAdded.connect(this,
1006 &PeerConnection::OnAudioTrackAdded);
1007 observer->SignalAudioTrackRemoved.connect(
1008 this, &PeerConnection::OnAudioTrackRemoved);
1009 observer->SignalVideoTrackAdded.connect(this,
1010 &PeerConnection::OnVideoTrackAdded);
1011 observer->SignalVideoTrackRemoved.connect(
1012 this, &PeerConnection::OnVideoTrackRemoved);
kwibergd1fe2812016-04-27 06:47:29 -07001013 stream_observers_.push_back(std::unique_ptr<MediaStreamObserver>(observer));
deadbeefab9b2d12015-10-14 11:33:11 -07001014
deadbeefab9b2d12015-10-14 11:33:11 -07001015 for (const auto& track : local_stream->GetAudioTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001016 AddAudioTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -07001017 }
1018 for (const auto& track : local_stream->GetVideoTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001019 AddVideoTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -07001020 }
1021
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001022 stats_->AddStream(local_stream);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001023 observer_->OnRenegotiationNeeded();
1024 return true;
1025}
1026
1027void PeerConnection::RemoveStream(MediaStreamInterface* local_stream) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001028 TRACE_EVENT0("webrtc", "PeerConnection::RemoveStream");
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001029 if (!IsClosed()) {
1030 for (const auto& track : local_stream->GetAudioTracks()) {
1031 RemoveAudioTrack(track.get(), local_stream);
1032 }
1033 for (const auto& track : local_stream->GetVideoTracks()) {
1034 RemoveVideoTrack(track.get(), local_stream);
1035 }
deadbeefab9b2d12015-10-14 11:33:11 -07001036 }
deadbeefab9b2d12015-10-14 11:33:11 -07001037 local_streams_->RemoveStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -08001038 stream_observers_.erase(
1039 std::remove_if(
1040 stream_observers_.begin(), stream_observers_.end(),
kwibergd1fe2812016-04-27 06:47:29 -07001041 [local_stream](const std::unique_ptr<MediaStreamObserver>& observer) {
deadbeefeb459812015-12-15 19:24:43 -08001042 return observer->stream()->label().compare(local_stream->label()) ==
1043 0;
1044 }),
1045 stream_observers_.end());
deadbeefab9b2d12015-10-14 11:33:11 -07001046
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001047 if (IsClosed()) {
1048 return;
1049 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001050 observer_->OnRenegotiationNeeded();
1051}
1052
deadbeefe1f9d832016-01-14 15:35:42 -08001053rtc::scoped_refptr<RtpSenderInterface> PeerConnection::AddTrack(
1054 MediaStreamTrackInterface* track,
1055 std::vector<MediaStreamInterface*> streams) {
1056 TRACE_EVENT0("webrtc", "PeerConnection::AddTrack");
Steve Antonf9381f02017-12-14 10:23:57 -08001057 std::vector<std::string> stream_labels;
1058 for (auto* stream : streams) {
1059 if (!stream) {
1060 RTC_LOG(LS_ERROR) << "Stream list has null element.";
1061 return nullptr;
1062 }
1063 stream_labels.push_back(stream->label());
1064 }
Steve Anton2d6c76a2018-01-05 17:10:52 -08001065 auto sender_or_error = AddTrack(track, stream_labels);
Steve Antonf9381f02017-12-14 10:23:57 -08001066 if (!sender_or_error.ok()) {
deadbeefe1f9d832016-01-14 15:35:42 -08001067 return nullptr;
1068 }
Steve Antonf9381f02017-12-14 10:23:57 -08001069 return sender_or_error.MoveValue();
1070}
1071
Steve Anton2d6c76a2018-01-05 17:10:52 -08001072RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::AddTrack(
Steve Antonf9381f02017-12-14 10:23:57 -08001073 rtc::scoped_refptr<MediaStreamTrackInterface> track,
1074 const std::vector<std::string>& stream_labels) {
Steve Anton2d6c76a2018-01-05 17:10:52 -08001075 TRACE_EVENT0("webrtc", "PeerConnection::AddTrack");
Steve Antonf9381f02017-12-14 10:23:57 -08001076 if (!track) {
1077 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "Track is null.");
1078 }
1079 if (!(track->kind() == MediaStreamTrackInterface::kAudioKind ||
1080 track->kind() == MediaStreamTrackInterface::kVideoKind)) {
1081 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1082 "Track has invalid kind: " + track->kind());
1083 }
1084 // TODO(bugs.webrtc.org/7932): Support adding a track to multiple streams.
1085 if (stream_labels.size() > 1u) {
1086 LOG_AND_RETURN_ERROR(
1087 RTCErrorType::UNSUPPORTED_OPERATION,
1088 "AddTrack with more than one stream is not currently supported.");
1089 }
1090 if (IsClosed()) {
1091 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
1092 "PeerConnection is closed.");
deadbeefe1f9d832016-01-14 15:35:42 -08001093 }
Steve Anton4171afb2017-11-20 10:20:22 -08001094 if (FindSenderForTrack(track)) {
Steve Antonf9381f02017-12-14 10:23:57 -08001095 LOG_AND_RETURN_ERROR(
1096 RTCErrorType::INVALID_PARAMETER,
1097 "Sender already exists for track " + track->id() + ".");
deadbeefe1f9d832016-01-14 15:35:42 -08001098 }
Steve Antonf9381f02017-12-14 10:23:57 -08001099 // TODO(bugs.webrtc.org/7933): MediaSession expects the sender to have exactly
1100 // one stream. AddTrackInternal will return an error if there is more than one
1101 // stream, but if the caller specifies none then we need to generate a random
1102 // stream label.
1103 std::vector<std::string> adjusted_stream_labels = stream_labels;
1104 if (stream_labels.empty()) {
1105 adjusted_stream_labels.push_back(rtc::CreateRandomUuid());
1106 }
1107 RTC_DCHECK_EQ(1, adjusted_stream_labels.size());
1108 auto sender_or_error =
1109 (IsUnifiedPlan() ? AddTrackUnifiedPlan(track, adjusted_stream_labels)
1110 : AddTrackPlanB(track, adjusted_stream_labels));
1111 if (sender_or_error.ok()) {
1112 observer_->OnRenegotiationNeeded();
Steve Anton43a723a2018-01-04 15:48:17 -08001113 stats_->AddTrack(track);
Steve Antonf9381f02017-12-14 10:23:57 -08001114 }
1115 return sender_or_error;
1116}
deadbeefe1f9d832016-01-14 15:35:42 -08001117
Steve Antonf9381f02017-12-14 10:23:57 -08001118RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>>
1119PeerConnection::AddTrackPlanB(
1120 rtc::scoped_refptr<MediaStreamTrackInterface> track,
1121 const std::vector<std::string>& stream_labels) {
Steve Anton02ee47c2018-01-10 16:26:06 -08001122 cricket::MediaType media_type =
1123 (track->kind() == MediaStreamTrackInterface::kAudioKind
1124 ? cricket::MEDIA_TYPE_AUDIO
1125 : cricket::MEDIA_TYPE_VIDEO);
1126 auto new_sender = CreateSender(media_type, track, stream_labels);
deadbeefe1f9d832016-01-14 15:35:42 -08001127 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
Guido Urdanetaee2388f2018-02-15 16:36:19 +00001128 static_cast<AudioRtpSender*>(new_sender->internal())
1129 ->SetMediaChannel(voice_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08001130 GetAudioTransceiver()->internal()->AddSender(new_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001131 const RtpSenderInfo* sender_info =
1132 FindSenderInfo(local_audio_sender_infos_,
1133 new_sender->internal()->stream_id(), track->id());
1134 if (sender_info) {
1135 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -08001136 }
Steve Antonf9381f02017-12-14 10:23:57 -08001137 } else {
1138 RTC_DCHECK_EQ(MediaStreamTrackInterface::kVideoKind, track->kind());
Guido Urdanetaee2388f2018-02-15 16:36:19 +00001139 static_cast<VideoRtpSender*>(new_sender->internal())
1140 ->SetMediaChannel(video_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08001141 GetVideoTransceiver()->internal()->AddSender(new_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001142 const RtpSenderInfo* sender_info =
1143 FindSenderInfo(local_video_sender_infos_,
1144 new_sender->internal()->stream_id(), track->id());
1145 if (sender_info) {
1146 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -08001147 }
deadbeefe1f9d832016-01-14 15:35:42 -08001148 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001149 return rtc::scoped_refptr<RtpSenderInterface>(new_sender);
Steve Antonf9381f02017-12-14 10:23:57 -08001150}
deadbeefe1f9d832016-01-14 15:35:42 -08001151
Steve Antonf9381f02017-12-14 10:23:57 -08001152RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>>
1153PeerConnection::AddTrackUnifiedPlan(
1154 rtc::scoped_refptr<MediaStreamTrackInterface> track,
1155 const std::vector<std::string>& stream_labels) {
1156 auto transceiver = FindFirstTransceiverForAddedTrack(track);
1157 if (transceiver) {
1158 if (transceiver->direction() == RtpTransceiverDirection::kRecvOnly) {
1159 transceiver->SetDirection(RtpTransceiverDirection::kSendRecv);
1160 } else if (transceiver->direction() == RtpTransceiverDirection::kInactive) {
1161 transceiver->SetDirection(RtpTransceiverDirection::kSendOnly);
1162 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001163 transceiver->sender()->SetTrack(track);
1164 transceiver->internal()->sender_internal()->set_stream_ids(stream_labels);
Steve Antonf9381f02017-12-14 10:23:57 -08001165 } else {
1166 cricket::MediaType media_type =
1167 (track->kind() == MediaStreamTrackInterface::kAudioKind
1168 ? cricket::MEDIA_TYPE_AUDIO
1169 : cricket::MEDIA_TYPE_VIDEO);
Steve Anton02ee47c2018-01-10 16:26:06 -08001170 auto sender = CreateSender(media_type, track, stream_labels);
1171 auto receiver = CreateReceiver(media_type, rtc::CreateRandomUuid());
1172 transceiver = CreateAndAddTransceiver(sender, receiver);
Steve Antonf9381f02017-12-14 10:23:57 -08001173 transceiver->internal()->set_created_by_addtrack(true);
1174 transceiver->SetDirection(RtpTransceiverDirection::kSendRecv);
1175 }
Steve Antonf9381f02017-12-14 10:23:57 -08001176 return transceiver->sender();
1177}
1178
1179rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1180PeerConnection::FindFirstTransceiverForAddedTrack(
1181 rtc::scoped_refptr<MediaStreamTrackInterface> track) {
1182 RTC_DCHECK(track);
1183 for (auto transceiver : transceivers_) {
1184 if (!transceiver->sender()->track() &&
Steve Anton69470252018-02-09 11:43:08 -08001185 cricket::MediaTypeToString(transceiver->media_type()) ==
Steve Antonf9381f02017-12-14 10:23:57 -08001186 track->kind() &&
1187 !transceiver->internal()->has_ever_been_used_to_send()) {
1188 return transceiver;
1189 }
1190 }
1191 return nullptr;
deadbeefe1f9d832016-01-14 15:35:42 -08001192}
1193
1194bool PeerConnection::RemoveTrack(RtpSenderInterface* sender) {
1195 TRACE_EVENT0("webrtc", "PeerConnection::RemoveTrack");
Steve Antonf9381f02017-12-14 10:23:57 -08001196 return RemoveTrackInternal(sender).ok();
1197}
1198
1199RTCError PeerConnection::RemoveTrackInternal(
1200 rtc::scoped_refptr<RtpSenderInterface> sender) {
1201 if (!sender) {
1202 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "Sender is null.");
1203 }
deadbeefe1f9d832016-01-14 15:35:42 -08001204 if (IsClosed()) {
Steve Antonf9381f02017-12-14 10:23:57 -08001205 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
1206 "PeerConnection is closed.");
deadbeefe1f9d832016-01-14 15:35:42 -08001207 }
Steve Antonf9381f02017-12-14 10:23:57 -08001208 if (IsUnifiedPlan()) {
1209 auto transceiver = FindTransceiverBySender(sender);
1210 if (!transceiver || !sender->track()) {
1211 return RTCError::OK();
1212 }
1213 sender->SetTrack(nullptr);
1214 if (transceiver->direction() == RtpTransceiverDirection::kSendRecv) {
1215 transceiver->internal()->SetDirection(RtpTransceiverDirection::kRecvOnly);
1216 } else if (transceiver->direction() == RtpTransceiverDirection::kSendOnly) {
1217 transceiver->internal()->SetDirection(RtpTransceiverDirection::kInactive);
1218 }
Steve Anton4171afb2017-11-20 10:20:22 -08001219 } else {
Steve Antonf9381f02017-12-14 10:23:57 -08001220 bool removed;
1221 if (sender->media_type() == cricket::MEDIA_TYPE_AUDIO) {
1222 removed = GetAudioTransceiver()->internal()->RemoveSender(sender);
1223 } else {
1224 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, sender->media_type());
1225 removed = GetVideoTransceiver()->internal()->RemoveSender(sender);
1226 }
1227 if (!removed) {
1228 LOG_AND_RETURN_ERROR(
1229 RTCErrorType::INVALID_PARAMETER,
1230 "Couldn't find sender " + sender->id() + " to remove.");
1231 }
Steve Anton4171afb2017-11-20 10:20:22 -08001232 }
deadbeefe1f9d832016-01-14 15:35:42 -08001233 observer_->OnRenegotiationNeeded();
Steve Antonf9381f02017-12-14 10:23:57 -08001234 return RTCError::OK();
1235}
1236
1237rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1238PeerConnection::FindTransceiverBySender(
1239 rtc::scoped_refptr<RtpSenderInterface> sender) {
1240 for (auto transceiver : transceivers_) {
1241 if (transceiver->sender() == sender) {
1242 return transceiver;
1243 }
1244 }
1245 return nullptr;
deadbeefe1f9d832016-01-14 15:35:42 -08001246}
1247
Steve Anton9158ef62017-11-27 13:01:52 -08001248RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1249PeerConnection::AddTransceiver(
1250 rtc::scoped_refptr<MediaStreamTrackInterface> track) {
1251 return AddTransceiver(track, RtpTransceiverInit());
1252}
1253
1254RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1255PeerConnection::AddTransceiver(
1256 rtc::scoped_refptr<MediaStreamTrackInterface> track,
1257 const RtpTransceiverInit& init) {
1258 if (!IsUnifiedPlan()) {
1259 LOG_AND_RETURN_ERROR(
1260 RTCErrorType::INTERNAL_ERROR,
1261 "AddTransceiver only supported when Unified Plan is enabled.");
1262 }
1263 if (!track) {
1264 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "track is null");
1265 }
1266 cricket::MediaType media_type;
1267 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
1268 media_type = cricket::MEDIA_TYPE_AUDIO;
1269 } else if (track->kind() == MediaStreamTrackInterface::kVideoKind) {
1270 media_type = cricket::MEDIA_TYPE_VIDEO;
1271 } else {
1272 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1273 "Track kind is not audio or video");
1274 }
1275 return AddTransceiver(media_type, track, init);
1276}
1277
1278RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1279PeerConnection::AddTransceiver(cricket::MediaType media_type) {
1280 return AddTransceiver(media_type, RtpTransceiverInit());
1281}
1282
1283RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1284PeerConnection::AddTransceiver(cricket::MediaType media_type,
1285 const RtpTransceiverInit& init) {
1286 if (!IsUnifiedPlan()) {
1287 LOG_AND_RETURN_ERROR(
1288 RTCErrorType::INTERNAL_ERROR,
1289 "AddTransceiver only supported when Unified Plan is enabled.");
1290 }
1291 if (!(media_type == cricket::MEDIA_TYPE_AUDIO ||
1292 media_type == cricket::MEDIA_TYPE_VIDEO)) {
1293 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1294 "media type is not audio or video");
1295 }
1296 return AddTransceiver(media_type, nullptr, init);
1297}
1298
1299RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1300PeerConnection::AddTransceiver(
1301 cricket::MediaType media_type,
1302 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Steve Anton22da89f2018-01-25 13:58:07 -08001303 const RtpTransceiverInit& init,
1304 bool fire_callback) {
Steve Anton9158ef62017-11-27 13:01:52 -08001305 RTC_DCHECK((media_type == cricket::MEDIA_TYPE_AUDIO ||
1306 media_type == cricket::MEDIA_TYPE_VIDEO));
1307 if (track) {
1308 RTC_DCHECK_EQ(media_type,
1309 (track->kind() == MediaStreamTrackInterface::kAudioKind
1310 ? cricket::MEDIA_TYPE_AUDIO
1311 : cricket::MEDIA_TYPE_VIDEO));
1312 }
1313
1314 // TODO(bugs.webrtc.org/7600): Verify init.
1315
Steve Anton02ee47c2018-01-10 16:26:06 -08001316 if (init.stream_labels.size() > 1u) {
1317 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
1318 "More than one stream is not yet supported.");
Steve Antonf9381f02017-12-14 10:23:57 -08001319 }
1320
Steve Anton02ee47c2018-01-10 16:26:06 -08001321 std::vector<std::string> stream_labels = {!init.stream_labels.empty()
1322 ? init.stream_labels[0]
1323 : rtc::CreateRandomUuid()};
1324
1325 auto sender = CreateSender(media_type, track, stream_labels);
1326 auto receiver = CreateReceiver(media_type, rtc::CreateRandomUuid());
1327 auto transceiver = CreateAndAddTransceiver(sender, receiver);
1328 transceiver->internal()->set_direction(init.direction);
1329
Steve Anton22da89f2018-01-25 13:58:07 -08001330 if (fire_callback) {
1331 observer_->OnRenegotiationNeeded();
1332 }
Steve Antonf9381f02017-12-14 10:23:57 -08001333
1334 return rtc::scoped_refptr<RtpTransceiverInterface>(transceiver);
1335}
1336
Steve Anton02ee47c2018-01-10 16:26:06 -08001337rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
1338PeerConnection::CreateSender(
1339 cricket::MediaType media_type,
1340 rtc::scoped_refptr<MediaStreamTrackInterface> track,
1341 const std::vector<std::string>& stream_labels) {
Steve Anton9158ef62017-11-27 13:01:52 -08001342 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> sender;
Steve Anton02ee47c2018-01-10 16:26:06 -08001343 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
1344 RTC_DCHECK(!track ||
1345 (track->kind() == MediaStreamTrackInterface::kAudioKind));
1346 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
1347 signaling_thread(),
Steve Anton47136dd2018-01-12 10:49:35 -08001348 new AudioRtpSender(worker_thread(),
1349 static_cast<AudioTrackInterface*>(track.get()),
Steve Anton02ee47c2018-01-10 16:26:06 -08001350 stream_labels, stats_.get()));
1351 } else {
1352 RTC_DCHECK_EQ(media_type, cricket::MEDIA_TYPE_VIDEO);
1353 RTC_DCHECK(!track ||
1354 (track->kind() == MediaStreamTrackInterface::kVideoKind));
1355 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
1356 signaling_thread(),
Steve Anton47136dd2018-01-12 10:49:35 -08001357 new VideoRtpSender(worker_thread(),
1358 static_cast<VideoTrackInterface*>(track.get()),
Steve Anton02ee47c2018-01-10 16:26:06 -08001359 stream_labels));
1360 }
1361 sender->internal()->set_stream_ids(stream_labels);
1362 return sender;
1363}
1364
1365rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1366PeerConnection::CreateReceiver(cricket::MediaType media_type,
1367 const std::string& receiver_id) {
Steve Anton9158ef62017-11-27 13:01:52 -08001368 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1369 receiver;
Steve Anton9158ef62017-11-27 13:01:52 -08001370 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton9158ef62017-11-27 13:01:52 -08001371 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
Steve Anton60776752018-01-10 11:51:34 -08001372 signaling_thread(),
Steve Antond3679212018-01-17 17:41:02 -08001373 new AudioRtpReceiver(worker_thread(), receiver_id, {}));
Steve Anton9158ef62017-11-27 13:01:52 -08001374 } else {
Steve Anton02ee47c2018-01-10 16:26:06 -08001375 RTC_DCHECK_EQ(media_type, cricket::MEDIA_TYPE_VIDEO);
Steve Anton9158ef62017-11-27 13:01:52 -08001376 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
1377 signaling_thread(),
Steve Antond3679212018-01-17 17:41:02 -08001378 new VideoRtpReceiver(worker_thread(), receiver_id, {}));
Steve Anton9158ef62017-11-27 13:01:52 -08001379 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001380 return receiver;
1381}
1382
1383rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1384PeerConnection::CreateAndAddTransceiver(
1385 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> sender,
1386 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1387 receiver) {
1388 auto transceiver = RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1389 signaling_thread(), new RtpTransceiver(sender, receiver));
Steve Anton9158ef62017-11-27 13:01:52 -08001390 transceivers_.push_back(transceiver);
Steve Antonf9381f02017-12-14 10:23:57 -08001391 return transceiver;
Steve Anton9158ef62017-11-27 13:01:52 -08001392}
1393
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001394rtc::scoped_refptr<DtmfSenderInterface> PeerConnection::CreateDtmfSender(
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001395 AudioTrackInterface* track) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001396 TRACE_EVENT0("webrtc", "PeerConnection::CreateDtmfSender");
zhihuang29ff8442016-07-27 11:07:25 -07001397 if (IsClosed()) {
1398 return nullptr;
1399 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001400 if (!track) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001401 RTC_LOG(LS_ERROR) << "CreateDtmfSender - track is NULL.";
deadbeef20cb0c12017-02-01 20:27:00 -08001402 return nullptr;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001403 }
Steve Anton4171afb2017-11-20 10:20:22 -08001404 auto track_sender = FindSenderForTrack(track);
1405 if (!track_sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001406 RTC_LOG(LS_ERROR) << "CreateDtmfSender called with a non-added track.";
deadbeef20cb0c12017-02-01 20:27:00 -08001407 return nullptr;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001408 }
1409
Steve Anton4171afb2017-11-20 10:20:22 -08001410 return track_sender->GetDtmfSender();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001411}
1412
deadbeeffac06552015-11-25 11:26:01 -08001413rtc::scoped_refptr<RtpSenderInterface> PeerConnection::CreateSender(
deadbeefbd7d8f72015-12-18 16:58:44 -08001414 const std::string& kind,
1415 const std::string& stream_id) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001416 TRACE_EVENT0("webrtc", "PeerConnection::CreateSender");
zhihuang29ff8442016-07-27 11:07:25 -07001417 if (IsClosed()) {
1418 return nullptr;
1419 }
Steve Anton4171afb2017-11-20 10:20:22 -08001420
Steve Anton02ee47c2018-01-10 16:26:06 -08001421 std::vector<std::string> stream_labels;
1422 if (!stream_id.empty()) {
1423 stream_labels.push_back(stream_id);
1424 }
1425
Steve Anton4171afb2017-11-20 10:20:22 -08001426 // TODO(steveanton): Move construction of the RtpSenders to RtpTransceiver.
deadbeefa601f5c2016-06-06 14:27:39 -07001427 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender;
deadbeeffac06552015-11-25 11:26:01 -08001428 if (kind == MediaStreamTrackInterface::kAudioKind) {
Steve Anton47136dd2018-01-12 10:49:35 -08001429 auto* audio_sender = new AudioRtpSender(worker_thread(), nullptr,
1430 stream_labels, stats_.get());
Guido Urdanetaee2388f2018-02-15 16:36:19 +00001431 audio_sender->SetMediaChannel(voice_media_channel());
deadbeefa601f5c2016-06-06 14:27:39 -07001432 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton02ee47c2018-01-10 16:26:06 -08001433 signaling_thread(), audio_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001434 GetAudioTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 11:26:01 -08001435 } else if (kind == MediaStreamTrackInterface::kVideoKind) {
Steve Anton47136dd2018-01-12 10:49:35 -08001436 auto* video_sender =
1437 new VideoRtpSender(worker_thread(), nullptr, stream_labels);
Guido Urdanetaee2388f2018-02-15 16:36:19 +00001438 video_sender->SetMediaChannel(video_media_channel());
deadbeefa601f5c2016-06-06 14:27:39 -07001439 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton02ee47c2018-01-10 16:26:06 -08001440 signaling_thread(), video_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001441 GetVideoTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 11:26:01 -08001442 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001443 RTC_LOG(LS_ERROR) << "CreateSender called with invalid kind: " << kind;
Steve Anton4171afb2017-11-20 10:20:22 -08001444 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08001445 }
Steve Anton4171afb2017-11-20 10:20:22 -08001446
deadbeefe1f9d832016-01-14 15:35:42 -08001447 return new_sender;
deadbeeffac06552015-11-25 11:26:01 -08001448}
1449
deadbeef70ab1a12015-09-28 16:53:55 -07001450std::vector<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::GetSenders()
1451 const {
deadbeefa601f5c2016-06-06 14:27:39 -07001452 std::vector<rtc::scoped_refptr<RtpSenderInterface>> ret;
Steve Anton4171afb2017-11-20 10:20:22 -08001453 for (auto sender : GetSendersInternal()) {
1454 ret.push_back(sender);
deadbeefa601f5c2016-06-06 14:27:39 -07001455 }
1456 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -07001457}
1458
Steve Anton4171afb2017-11-20 10:20:22 -08001459std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1460PeerConnection::GetSendersInternal() const {
1461 std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1462 all_senders;
1463 for (auto transceiver : transceivers_) {
1464 auto senders = transceiver->internal()->senders();
1465 all_senders.insert(all_senders.end(), senders.begin(), senders.end());
1466 }
1467 return all_senders;
1468}
1469
deadbeef70ab1a12015-09-28 16:53:55 -07001470std::vector<rtc::scoped_refptr<RtpReceiverInterface>>
1471PeerConnection::GetReceivers() const {
deadbeefa601f5c2016-06-06 14:27:39 -07001472 std::vector<rtc::scoped_refptr<RtpReceiverInterface>> ret;
Steve Anton4171afb2017-11-20 10:20:22 -08001473 for (const auto& receiver : GetReceiversInternal()) {
1474 ret.push_back(receiver);
deadbeefa601f5c2016-06-06 14:27:39 -07001475 }
1476 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -07001477}
1478
Steve Anton4171afb2017-11-20 10:20:22 -08001479std::vector<
1480 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1481PeerConnection::GetReceiversInternal() const {
1482 std::vector<
1483 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1484 all_receivers;
1485 for (auto transceiver : transceivers_) {
1486 auto receivers = transceiver->internal()->receivers();
1487 all_receivers.insert(all_receivers.end(), receivers.begin(),
1488 receivers.end());
1489 }
1490 return all_receivers;
1491}
1492
Steve Anton9158ef62017-11-27 13:01:52 -08001493std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
1494PeerConnection::GetTransceivers() const {
1495 RTC_DCHECK(IsUnifiedPlan());
1496 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> all_transceivers;
1497 for (auto transceiver : transceivers_) {
1498 all_transceivers.push_back(transceiver);
1499 }
1500 return all_transceivers;
1501}
1502
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001503bool PeerConnection::GetStats(StatsObserver* observer,
wu@webrtc.orgb9a088b2014-02-13 23:18:49 +00001504 MediaStreamTrackInterface* track,
1505 StatsOutputLevel level) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001506 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
deadbeef0a6c4ca2015-10-06 11:38:28 -07001507 RTC_DCHECK(signaling_thread()->IsCurrent());
nisse7ce109a2017-01-31 00:57:56 -08001508 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001509 RTC_LOG(LS_ERROR) << "GetStats - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001510 return false;
1511 }
1512
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001513 stats_->UpdateStats(level);
zhihuange9e94c32016-11-04 11:38:15 -07001514 // The StatsCollector is used to tell if a track is valid because it may
1515 // remember tracks that the PeerConnection previously removed.
1516 if (track && !stats_->IsValidTrack(track->id())) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001517 RTC_LOG(LS_WARNING) << "GetStats is called with an invalid track: "
1518 << track->id();
zhihuange9e94c32016-11-04 11:38:15 -07001519 return false;
1520 }
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001521 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_GETSTATS,
tommi@webrtc.org5b06b062014-08-15 08:38:30 +00001522 new GetStatsMsg(observer, track));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001523 return true;
1524}
1525
hbos74e1a4f2016-09-15 23:33:01 -07001526void PeerConnection::GetStats(RTCStatsCollectorCallback* callback) {
1527 RTC_DCHECK(stats_collector_);
1528 stats_collector_->GetStatsReport(callback);
1529}
1530
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001531PeerConnectionInterface::SignalingState PeerConnection::signaling_state() {
1532 return signaling_state_;
1533}
1534
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001535PeerConnectionInterface::IceConnectionState
1536PeerConnection::ice_connection_state() {
1537 return ice_connection_state_;
1538}
1539
1540PeerConnectionInterface::IceGatheringState
1541PeerConnection::ice_gathering_state() {
1542 return ice_gathering_state_;
1543}
1544
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001545rtc::scoped_refptr<DataChannelInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001546PeerConnection::CreateDataChannel(
1547 const std::string& label,
1548 const DataChannelInit* config) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001549 TRACE_EVENT0("webrtc", "PeerConnection::CreateDataChannel");
zhihuang9763d562016-08-05 11:14:50 -07001550
deadbeefab9b2d12015-10-14 11:33:11 -07001551 bool first_datachannel = !HasDataChannels();
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001552
kwibergd1fe2812016-04-27 06:47:29 -07001553 std::unique_ptr<InternalDataChannelInit> internal_config;
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00001554 if (config) {
1555 internal_config.reset(new InternalDataChannelInit(*config));
1556 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001557 rtc::scoped_refptr<DataChannelInterface> channel(
deadbeefab9b2d12015-10-14 11:33:11 -07001558 InternalCreateDataChannel(label, internal_config.get()));
1559 if (!channel.get()) {
1560 return nullptr;
1561 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001562
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001563 // Trigger the onRenegotiationNeeded event for every new RTP DataChannel, or
1564 // the first SCTP DataChannel.
Steve Anton75737c02017-11-06 10:37:17 -08001565 if (data_channel_type() == cricket::DCT_RTP || first_datachannel) {
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001566 observer_->OnRenegotiationNeeded();
1567 }
wu@webrtc.org91053e72013-08-10 07:18:04 +00001568
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001569 return DataChannelProxy::Create(signaling_thread(), channel.get());
1570}
1571
1572void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
1573 const MediaConstraintsInterface* constraints) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001574 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
Steve Anton8d3444d2017-10-20 15:30:51 -07001575
zhihuang1c378ed2017-08-17 14:10:50 -07001576 PeerConnectionInterface::RTCOfferAnswerOptions offer_answer_options;
1577 // Always create an offer even if |ConvertConstraintsToOfferAnswerOptions|
1578 // returns false for now. Because |ConvertConstraintsToOfferAnswerOptions|
1579 // compares the mandatory fields parsed with the mandatory fields added in the
1580 // |constraints| and some downstream applications might create offers with
1581 // mandatory fields which would not be parsed in the helper method. For
1582 // example, in Chromium/remoting, |kEnableDtlsSrtp| is added to the
1583 // |constraints| as a mandatory field but it is not parsed.
1584 ConvertConstraintsToOfferAnswerOptions(constraints, &offer_answer_options);
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001585
zhihuang1c378ed2017-08-17 14:10:50 -07001586 CreateOffer(observer, offer_answer_options);
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001587}
1588
1589void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
1590 const RTCOfferAnswerOptions& options) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001591 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
Steve Anton8d3444d2017-10-20 15:30:51 -07001592
nisse7ce109a2017-01-31 00:57:56 -08001593 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001594 RTC_LOG(LS_ERROR) << "CreateOffer - observer is NULL.";
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001595 return;
1596 }
deadbeefab9b2d12015-10-14 11:33:11 -07001597
Steve Anton8d3444d2017-10-20 15:30:51 -07001598 if (IsClosed()) {
1599 std::string error = "CreateOffer called when PeerConnection is closed.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001600 RTC_LOG(LS_ERROR) << error;
Steve Anton8d3444d2017-10-20 15:30:51 -07001601 PostCreateSessionDescriptionFailure(observer, error);
1602 return;
1603 }
1604
zhihuang1c378ed2017-08-17 14:10:50 -07001605 if (!ValidateOfferAnswerOptions(options)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001606 std::string error = "CreateOffer called with invalid options.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001607 RTC_LOG(LS_ERROR) << error;
deadbeefab9b2d12015-10-14 11:33:11 -07001608 PostCreateSessionDescriptionFailure(observer, error);
1609 return;
1610 }
1611
Steve Anton22da89f2018-01-25 13:58:07 -08001612 // Legacy handling for offer_to_receive_audio and offer_to_receive_video.
1613 // Specified in WebRTC section 4.4.3.2 "Legacy configuration extensions".
1614 if (IsUnifiedPlan()) {
1615 RTCError error = HandleLegacyOfferOptions(options);
1616 if (!error.ok()) {
1617 PostCreateSessionDescriptionFailure(observer, error.message());
1618 return;
1619 }
1620 }
1621
zhihuang1c378ed2017-08-17 14:10:50 -07001622 cricket::MediaSessionOptions session_options;
1623 GetOptionsForOffer(options, &session_options);
Steve Antond25da372017-11-06 14:50:29 -08001624 webrtc_session_desc_factory_->CreateOffer(observer, options, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001625}
1626
Steve Anton22da89f2018-01-25 13:58:07 -08001627RTCError PeerConnection::HandleLegacyOfferOptions(
1628 const RTCOfferAnswerOptions& options) {
1629 RTC_DCHECK(IsUnifiedPlan());
1630
1631 if (options.offer_to_receive_audio == 0) {
1632 RemoveRecvDirectionFromReceivingTransceiversOfType(
1633 cricket::MEDIA_TYPE_AUDIO);
1634 } else if (options.offer_to_receive_audio == 1) {
1635 AddUpToOneReceivingTransceiverOfType(cricket::MEDIA_TYPE_AUDIO);
1636 } else if (options.offer_to_receive_audio > 1) {
1637 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
1638 "offer_to_receive_audio > 1 is not supported.");
1639 }
1640
1641 if (options.offer_to_receive_video == 0) {
1642 RemoveRecvDirectionFromReceivingTransceiversOfType(
1643 cricket::MEDIA_TYPE_VIDEO);
1644 } else if (options.offer_to_receive_video == 1) {
1645 AddUpToOneReceivingTransceiverOfType(cricket::MEDIA_TYPE_VIDEO);
1646 } else if (options.offer_to_receive_video > 1) {
1647 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
1648 "offer_to_receive_video > 1 is not supported.");
1649 }
1650
1651 return RTCError::OK();
1652}
1653
1654void PeerConnection::RemoveRecvDirectionFromReceivingTransceiversOfType(
1655 cricket::MediaType media_type) {
1656 for (auto transceiver : GetReceivingTransceiversOfType(media_type)) {
1657 transceiver->internal()->set_direction(
1658 RtpTransceiverDirectionWithRecvSet(transceiver->direction(), false));
1659 }
1660}
1661
1662void PeerConnection::AddUpToOneReceivingTransceiverOfType(
1663 cricket::MediaType media_type) {
1664 if (GetReceivingTransceiversOfType(media_type).empty()) {
1665 RtpTransceiverInit init;
1666 init.direction = RtpTransceiverDirection::kRecvOnly;
1667 AddTransceiver(media_type, nullptr, init, /*fire_callback=*/false);
1668 }
1669}
1670
1671std::vector<rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
1672PeerConnection::GetReceivingTransceiversOfType(cricket::MediaType media_type) {
1673 std::vector<
1674 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
1675 receiving_transceivers;
1676 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08001677 if (!transceiver->stopped() && transceiver->media_type() == media_type &&
Steve Anton22da89f2018-01-25 13:58:07 -08001678 RtpTransceiverDirectionHasRecv(transceiver->direction())) {
1679 receiving_transceivers.push_back(transceiver);
1680 }
1681 }
1682 return receiving_transceivers;
1683}
1684
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001685void PeerConnection::CreateAnswer(
1686 CreateSessionDescriptionObserver* observer,
1687 const MediaConstraintsInterface* constraints) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001688 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
Steve Anton8d3444d2017-10-20 15:30:51 -07001689
nisse7ce109a2017-01-31 00:57:56 -08001690 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001691 RTC_LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001692 return;
1693 }
deadbeefab9b2d12015-10-14 11:33:11 -07001694
zhihuang1c378ed2017-08-17 14:10:50 -07001695 PeerConnectionInterface::RTCOfferAnswerOptions offer_answer_options;
1696 if (!ConvertConstraintsToOfferAnswerOptions(constraints,
1697 &offer_answer_options)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001698 std::string error = "CreateAnswer called with invalid constraints.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001699 RTC_LOG(LS_ERROR) << error;
deadbeefab9b2d12015-10-14 11:33:11 -07001700 PostCreateSessionDescriptionFailure(observer, error);
1701 return;
1702 }
1703
Steve Anton8d3444d2017-10-20 15:30:51 -07001704 CreateAnswer(observer, offer_answer_options);
htaa2a49d92016-03-04 02:51:39 -08001705}
1706
1707void PeerConnection::CreateAnswer(CreateSessionDescriptionObserver* observer,
1708 const RTCOfferAnswerOptions& options) {
1709 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
nisse7ce109a2017-01-31 00:57:56 -08001710 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001711 RTC_LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
htaa2a49d92016-03-04 02:51:39 -08001712 return;
1713 }
1714
Steve Antondffead82018-02-06 10:31:29 -08001715 if (!(signaling_state_ == kHaveRemoteOffer ||
1716 signaling_state_ == kHaveLocalPrAnswer)) {
1717 std::string error =
1718 "PeerConnection cannot create an answer in a state other than "
1719 "have-remote-offer or have-local-pranswer.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001720 RTC_LOG(LS_ERROR) << error;
Steve Anton8d3444d2017-10-20 15:30:51 -07001721 PostCreateSessionDescriptionFailure(observer, error);
1722 return;
1723 }
1724
Steve Antondffead82018-02-06 10:31:29 -08001725 // The remote description should be set if we're in the right state.
1726 RTC_DCHECK(remote_description());
Steve Anton8d3444d2017-10-20 15:30:51 -07001727
Steve Anton22da89f2018-01-25 13:58:07 -08001728 if (IsUnifiedPlan()) {
1729 if (options.offer_to_receive_audio != RTCOfferAnswerOptions::kUndefined) {
1730 RTC_LOG(LS_WARNING) << "CreateAnswer: offer_to_receive_audio is not "
1731 "supported with Unified Plan semantics. Use the "
1732 "RtpTransceiver API instead.";
1733 }
1734 if (options.offer_to_receive_video != RTCOfferAnswerOptions::kUndefined) {
1735 RTC_LOG(LS_WARNING) << "CreateAnswer: offer_to_receive_video is not "
1736 "supported with Unified Plan semantics. Use the "
1737 "RtpTransceiver API instead.";
1738 }
1739 }
1740
htaa2a49d92016-03-04 02:51:39 -08001741 cricket::MediaSessionOptions session_options;
zhihuang1c378ed2017-08-17 14:10:50 -07001742 GetOptionsForAnswer(options, &session_options);
htaa2a49d92016-03-04 02:51:39 -08001743
Steve Antond25da372017-11-06 14:50:29 -08001744 webrtc_session_desc_factory_->CreateAnswer(observer, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001745}
1746
1747void PeerConnection::SetLocalDescription(
1748 SetSessionDescriptionObserver* observer,
Steve Anton71439a62018-02-15 11:53:06 -08001749 SessionDescriptionInterface* desc_ptr) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001750 TRACE_EVENT0("webrtc", "PeerConnection::SetLocalDescription");
Steve Anton8a006912017-12-04 15:25:56 -08001751
Steve Anton71439a62018-02-15 11:53:06 -08001752 // The SetLocalDescription contract is that we take ownership of the session
1753 // description regardless of the outcome, so wrap it in a unique_ptr right
1754 // away. Ideally, SetLocalDescription's signature will be changed to take the
1755 // description as a unique_ptr argument to formalize this agreement.
1756 std::unique_ptr<SessionDescriptionInterface> desc(desc_ptr);
1757
nisse7ce109a2017-01-31 00:57:56 -08001758 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001759 RTC_LOG(LS_ERROR) << "SetLocalDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001760 return;
1761 }
Steve Anton8a006912017-12-04 15:25:56 -08001762
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001763 if (!desc) {
1764 PostSetSessionDescriptionFailure(observer, "SessionDescription is NULL.");
1765 return;
1766 }
Steve Anton8d3444d2017-10-20 15:30:51 -07001767
Steve Anton71439a62018-02-15 11:53:06 -08001768 // If a session error has occurred the PeerConnection is in a possibly
1769 // inconsistent state so fail right away.
1770 if (session_error() != SessionError::kNone) {
1771 std::string error_message = GetSessionErrorMsg();
1772 RTC_LOG(LS_ERROR) << "SetLocalDescription: " << error_message;
1773 PostSetSessionDescriptionFailure(observer, std::move(error_message));
1774 return;
1775 }
Steve Anton8d3444d2017-10-20 15:30:51 -07001776
Steve Anton71439a62018-02-15 11:53:06 -08001777 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_LOCAL);
1778 if (!error.ok()) {
1779 std::string error_message = GetSetDescriptionErrorMessage(
1780 cricket::CS_LOCAL, desc->GetType(), error);
1781 RTC_LOG(LS_ERROR) << error_message;
1782 PostSetSessionDescriptionFailure(observer, std::move(error_message));
1783 return;
1784 }
1785
1786 // Grab the description type before moving ownership to ApplyLocalDescription,
1787 // which may destroy it before returning.
1788 const SdpType type = desc->GetType();
1789
1790 error = ApplyLocalDescription(std::move(desc));
Steve Anton8a006912017-12-04 15:25:56 -08001791 // |desc| may be destroyed at this point.
1792
1793 if (!error.ok()) {
Steve Anton71439a62018-02-15 11:53:06 -08001794 // If ApplyLocalDescription fails, the PeerConnection could be in an
1795 // inconsistent state, so act conservatively here and set the session error
1796 // so that future calls to SetLocalDescription/SetRemoteDescription fail.
1797 SetSessionError(SessionError::kContent, error.message());
1798 std::string error_message =
1799 GetSetDescriptionErrorMessage(cricket::CS_LOCAL, type, error);
1800 RTC_LOG(LS_ERROR) << error_message;
Steve Anton8a006912017-12-04 15:25:56 -08001801 PostSetSessionDescriptionFailure(observer, std::move(error_message));
Steve Anton8d3444d2017-10-20 15:30:51 -07001802 return;
1803 }
Steve Anton8a006912017-12-04 15:25:56 -08001804 RTC_DCHECK(local_description());
1805
1806 PostSetSessionDescriptionSuccess(observer);
1807
1808 // According to JSEP, after setLocalDescription, changing the candidate pool
1809 // size is not allowed, and changing the set of ICE servers will not result
1810 // in new candidates being gathered.
1811 port_allocator_->FreezeCandidatePool();
1812
1813 // MaybeStartGathering needs to be called after posting
1814 // MSG_SET_SESSIONDESCRIPTION_SUCCESS, so that we don't signal any candidates
1815 // before signaling that SetLocalDescription completed.
1816 transport_controller_->MaybeStartGathering();
1817
Steve Antona3a92c22017-12-07 10:27:41 -08001818 if (local_description()->GetType() == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08001819 // TODO(deadbeef): We already had to hop to the network thread for
1820 // MaybeStartGathering...
1821 network_thread()->Invoke<void>(
1822 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
1823 port_allocator_.get()));
1824 }
1825}
1826
1827RTCError PeerConnection::ApplyLocalDescription(
1828 std::unique_ptr<SessionDescriptionInterface> desc) {
1829 RTC_DCHECK_RUN_ON(signaling_thread());
1830 RTC_DCHECK(desc);
1831
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001832 // Update stats here so that we have the most recent stats for tracks and
1833 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001834 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 15:25:56 -08001835
1836 // Update the initial_offerer flag if this session is the initial_offerer.
Steve Anton3828c062017-12-06 10:34:51 -08001837 SdpType type = desc->GetType();
Steve Anton8a006912017-12-04 15:25:56 -08001838 if (!initial_offerer_.has_value()) {
Steve Anton3828c062017-12-06 10:34:51 -08001839 initial_offerer_.emplace(type == SdpType::kOffer);
Steve Anton8a006912017-12-04 15:25:56 -08001840 if (*initial_offerer_) {
1841 transport_controller_->SetIceRole(cricket::ICEROLE_CONTROLLING);
1842 } else {
1843 transport_controller_->SetIceRole(cricket::ICEROLE_CONTROLLED);
1844 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001845 }
Steve Anton8a006912017-12-04 15:25:56 -08001846
Steve Antondcc3c022017-12-22 16:02:54 -08001847 // Take a reference to the old local description since it's used below to
1848 // compare against the new local description. When setting the new local
1849 // description, grab ownership of the replaced session description in case it
1850 // is the same as |old_local_description|, to keep it alive for the duration
1851 // of the method.
1852 const SessionDescriptionInterface* old_local_description =
1853 local_description();
1854 std::unique_ptr<SessionDescriptionInterface> replaced_local_description;
Steve Anton3828c062017-12-06 10:34:51 -08001855 if (type == SdpType::kAnswer) {
Steve Antondcc3c022017-12-22 16:02:54 -08001856 replaced_local_description = pending_local_description_
1857 ? std::move(pending_local_description_)
1858 : std::move(current_local_description_);
Steve Anton8a006912017-12-04 15:25:56 -08001859 current_local_description_ = std::move(desc);
1860 pending_local_description_ = nullptr;
1861 current_remote_description_ = std::move(pending_remote_description_);
1862 } else {
Steve Antondcc3c022017-12-22 16:02:54 -08001863 replaced_local_description = std::move(pending_local_description_);
Steve Anton8a006912017-12-04 15:25:56 -08001864 pending_local_description_ = std::move(desc);
1865 }
1866 // The session description to apply now must be accessed by
1867 // |local_description()|.
Henrik Boströmfdb92012017-11-09 19:55:44 +01001868 RTC_DCHECK(local_description());
deadbeefab9b2d12015-10-14 11:33:11 -07001869
Steve Antondcc3c022017-12-22 16:02:54 -08001870 if (IsUnifiedPlan()) {
1871 RTCError error = UpdateTransceiversAndDataChannels(
Seth Hampsonae8a90a2018-02-13 15:33:48 -08001872 cricket::CS_LOCAL, *local_description(), old_local_description,
1873 remote_description());
Steve Anton8a006912017-12-04 15:25:56 -08001874 if (!error.ok()) {
1875 return error;
1876 }
Steve Antondcc3c022017-12-22 16:02:54 -08001877 for (auto transceiver : transceivers_) {
1878 const ContentInfo* content =
1879 FindMediaSectionForTransceiver(transceiver, local_description());
1880 if (!content) {
1881 continue;
1882 }
1883 const MediaContentDescription* media_desc = content->media_description();
1884 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
1885 transceiver->internal()->set_current_direction(media_desc->direction());
1886 }
1887 if (content->rejected && !transceiver->stopped()) {
1888 transceiver->Stop();
1889 }
1890 }
1891 } else {
1892 // Transport and Media channels will be created only when offer is set.
1893 if (type == SdpType::kOffer) {
1894 // TODO(bugs.webrtc.org/4676) - Handle CreateChannel failure, as new local
1895 // description is applied. Restore back to old description.
1896 RTCError error = CreateChannels(*local_description()->description());
1897 if (!error.ok()) {
1898 return error;
1899 }
1900 }
Steve Anton8a006912017-12-04 15:25:56 -08001901
Steve Antondcc3c022017-12-22 16:02:54 -08001902 // Remove unused channels if MediaContentDescription is rejected.
1903 RemoveUnusedChannels(local_description()->description());
1904 }
Steve Anton8a006912017-12-04 15:25:56 -08001905
Steve Anton71439a62018-02-15 11:53:06 -08001906 RTCError error = UpdateSessionState(type, cricket::CS_LOCAL);
Steve Anton8a006912017-12-04 15:25:56 -08001907 if (!error.ok()) {
1908 return error;
1909 }
Steve Antondcc3c022017-12-22 16:02:54 -08001910
Steve Anton8a006912017-12-04 15:25:56 -08001911 if (remote_description()) {
1912 // Now that we have a local description, we can push down remote candidates.
1913 UseCandidatesInSessionDescription(remote_description());
1914 }
1915
1916 pending_ice_restarts_.clear();
1917 if (session_error() != SessionError::kNone) {
1918 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
1919 }
1920
deadbeefab9b2d12015-10-14 11:33:11 -07001921 // If setting the description decided our SSL role, allocate any necessary
1922 // SCTP sids.
1923 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08001924 if (data_channel_type() == cricket::DCT_SCTP && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001925 AllocateSctpSids(role);
1926 }
1927
Steve Antond3679212018-01-17 17:41:02 -08001928 if (IsUnifiedPlan()) {
1929 for (auto transceiver : transceivers_) {
1930 const ContentInfo* content =
1931 FindMediaSectionForTransceiver(transceiver, local_description());
1932 if (!content) {
1933 continue;
1934 }
1935 if (content->rejected && !transceiver->stopped()) {
1936 transceiver->Stop();
1937 }
Steve Anton74255ff2018-01-24 18:32:57 -08001938 const auto& streams = content->media_description()->streams();
1939 if (!content->rejected && !streams.empty()) {
Steve Antond3679212018-01-17 17:41:02 -08001940 transceiver->internal()->sender_internal()->set_stream_ids(
Steve Anton74255ff2018-01-24 18:32:57 -08001941 {streams[0].sync_label});
Steve Antond3679212018-01-17 17:41:02 -08001942 transceiver->internal()->sender_internal()->SetSsrc(
Steve Anton74255ff2018-01-24 18:32:57 -08001943 streams[0].first_ssrc());
Steve Antond3679212018-01-17 17:41:02 -08001944 }
1945 }
1946 } else {
1947 // Plan B semantics.
1948
Steve Antondcc3c022017-12-22 16:02:54 -08001949 // Update state and SSRC of local MediaStreams and DataChannels based on the
1950 // local session description.
1951 const cricket::ContentInfo* audio_content =
1952 GetFirstAudioContent(local_description()->description());
1953 if (audio_content) {
1954 if (audio_content->rejected) {
1955 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
1956 } else {
1957 const cricket::AudioContentDescription* audio_desc =
1958 audio_content->media_description()->as_audio();
1959 UpdateLocalSenders(audio_desc->streams(), audio_desc->type());
1960 }
deadbeeffaac4972015-11-12 15:33:07 -08001961 }
deadbeefab9b2d12015-10-14 11:33:11 -07001962
Steve Antondcc3c022017-12-22 16:02:54 -08001963 const cricket::ContentInfo* video_content =
1964 GetFirstVideoContent(local_description()->description());
1965 if (video_content) {
1966 if (video_content->rejected) {
1967 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
1968 } else {
1969 const cricket::VideoContentDescription* video_desc =
1970 video_content->media_description()->as_video();
1971 UpdateLocalSenders(video_desc->streams(), video_desc->type());
1972 }
deadbeeffaac4972015-11-12 15:33:07 -08001973 }
deadbeefab9b2d12015-10-14 11:33:11 -07001974 }
1975
1976 const cricket::ContentInfo* data_content =
Henrik Boströmfdb92012017-11-09 19:55:44 +01001977 GetFirstDataContent(local_description()->description());
deadbeefab9b2d12015-10-14 11:33:11 -07001978 if (data_content) {
1979 const cricket::DataContentDescription* data_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08001980 data_content->media_description()->as_data();
deadbeefab9b2d12015-10-14 11:33:11 -07001981 if (rtc::starts_with(data_desc->protocol().data(),
1982 cricket::kMediaProtocolRtpPrefix)) {
1983 UpdateLocalRtpDataChannels(data_desc->streams());
1984 }
1985 }
1986
Steve Anton8a006912017-12-04 15:25:56 -08001987 return RTCError::OK();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001988}
1989
1990void PeerConnection::SetRemoteDescription(
Henrik Boströma4ecf552017-11-23 14:17:07 +00001991 SetSessionDescriptionObserver* observer,
1992 SessionDescriptionInterface* desc) {
Henrik Boström31638672017-11-23 17:48:32 +01001993 SetRemoteDescription(
1994 std::unique_ptr<SessionDescriptionInterface>(desc),
1995 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface>(
1996 new SetRemoteDescriptionObserverAdapter(this, observer)));
1997}
1998
1999void PeerConnection::SetRemoteDescription(
2000 std::unique_ptr<SessionDescriptionInterface> desc,
2001 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface> observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +01002002 TRACE_EVENT0("webrtc", "PeerConnection::SetRemoteDescription");
Steve Anton8a006912017-12-04 15:25:56 -08002003
nisse7ce109a2017-01-31 00:57:56 -08002004 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002005 RTC_LOG(LS_ERROR) << "SetRemoteDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002006 return;
2007 }
Steve Anton8a006912017-12-04 15:25:56 -08002008
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002009 if (!desc) {
Henrik Boström31638672017-11-23 17:48:32 +01002010 observer->OnSetRemoteDescriptionComplete(RTCError(
Steve Anton8a006912017-12-04 15:25:56 -08002011 RTCErrorType::INVALID_PARAMETER, "SessionDescription is NULL."));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002012 return;
2013 }
Steve Anton8d3444d2017-10-20 15:30:51 -07002014
Steve Anton71439a62018-02-15 11:53:06 -08002015 // If a session error has occurred the PeerConnection is in a possibly
2016 // inconsistent state so fail right away.
2017 if (session_error() != SessionError::kNone) {
2018 std::string error_message = GetSessionErrorMsg();
2019 RTC_LOG(LS_ERROR) << "SetRemoteDescription: " << error_message;
2020 observer->OnSetRemoteDescriptionComplete(
2021 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
2022 return;
2023 }
Steve Anton8a006912017-12-04 15:25:56 -08002024
Steve Anton71439a62018-02-15 11:53:06 -08002025 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_REMOTE);
Steve Anton8a006912017-12-04 15:25:56 -08002026 if (!error.ok()) {
Steve Anton71439a62018-02-15 11:53:06 -08002027 std::string error_message = GetSetDescriptionErrorMessage(
2028 cricket::CS_REMOTE, desc->GetType(), error);
2029 RTC_LOG(LS_ERROR) << error_message;
Henrik Boström31638672017-11-23 17:48:32 +01002030 observer->OnSetRemoteDescriptionComplete(
Steve Anton8a006912017-12-04 15:25:56 -08002031 RTCError(error.type(), std::move(error_message)));
Steve Anton8d3444d2017-10-20 15:30:51 -07002032 return;
2033 }
2034
Steve Anton71439a62018-02-15 11:53:06 -08002035 // Grab the description type before moving ownership to
2036 // ApplyRemoteDescription, which may destroy it before returning.
2037 const SdpType type = desc->GetType();
2038
2039 error = ApplyRemoteDescription(std::move(desc));
2040 // |desc| may be destroyed at this point.
2041
2042 if (!error.ok()) {
2043 // If ApplyRemoteDescription fails, the PeerConnection could be in an
2044 // inconsistent state, so act conservatively here and set the session error
2045 // so that future calls to SetLocalDescription/SetRemoteDescription fail.
2046 SetSessionError(SessionError::kContent, error.message());
2047 std::string error_message =
2048 GetSetDescriptionErrorMessage(cricket::CS_REMOTE, type, error);
2049 RTC_LOG(LS_ERROR) << error_message;
2050 observer->OnSetRemoteDescriptionComplete(
2051 RTCError(error.type(), std::move(error_message)));
2052 return;
2053 }
2054 RTC_DCHECK(remote_description());
2055
2056 if (type == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002057 // TODO(deadbeef): We already had to hop to the network thread for
2058 // MaybeStartGathering...
2059 network_thread()->Invoke<void>(
2060 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
2061 port_allocator_.get()));
Harald Alvestrand5dbb5862018-02-13 23:48:00 +01002062 // Make UMA notes about what was agreed to.
2063 if (uma_observer_) {
2064 switch (remote_description()->description()->msid_signaling()) {
2065 case 0:
2066 uma_observer_->IncrementEnumCounter(kEnumCounterSdpSemanticNegotiated,
2067 kSdpSemanticNegotiatedNone,
2068 kSdpSemanticNegotiatedMax);
2069 break;
2070 case cricket::kMsidSignalingMediaSection:
2071 uma_observer_->IncrementEnumCounter(kEnumCounterSdpSemanticNegotiated,
2072 kSdpSemanticNegotiatedUnifiedPlan,
2073 kSdpSemanticNegotiatedMax);
2074 break;
2075 case cricket::kMsidSignalingSsrcAttribute:
2076 uma_observer_->IncrementEnumCounter(kEnumCounterSdpSemanticNegotiated,
2077 kSdpSemanticNegotiatedPlanB,
2078 kSdpSemanticNegotiatedMax);
2079 break;
2080 case cricket::kMsidSignalingMediaSection |
2081 cricket::kMsidSignalingSsrcAttribute:
2082 uma_observer_->IncrementEnumCounter(kEnumCounterSdpSemanticNegotiated,
2083 kSdpSemanticNegotiatedMixed,
2084 kSdpSemanticNegotiatedMax);
2085 break;
2086 default:
2087 RTC_NOTREACHED();
2088 }
2089 }
Steve Anton8a006912017-12-04 15:25:56 -08002090 }
2091
2092 observer->OnSetRemoteDescriptionComplete(RTCError::OK());
2093}
2094
2095RTCError PeerConnection::ApplyRemoteDescription(
2096 std::unique_ptr<SessionDescriptionInterface> desc) {
2097 RTC_DCHECK_RUN_ON(signaling_thread());
2098 RTC_DCHECK(desc);
2099
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002100 // Update stats here so that we have the most recent stats for tracks and
2101 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00002102 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 15:25:56 -08002103
Steve Antondcc3c022017-12-22 16:02:54 -08002104 // Take a reference to the old remote description since it's used below to
2105 // compare against the new remote description. When setting the new remote
2106 // description, grab ownership of the replaced session description in case it
2107 // is the same as |old_remote_description|, to keep it alive for the duration
2108 // of the method.
Steve Anton8a006912017-12-04 15:25:56 -08002109 const SessionDescriptionInterface* old_remote_description =
2110 remote_description();
Steve Anton8a006912017-12-04 15:25:56 -08002111 std::unique_ptr<SessionDescriptionInterface> replaced_remote_description;
Steve Anton3828c062017-12-06 10:34:51 -08002112 SdpType type = desc->GetType();
2113 if (type == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002114 replaced_remote_description = pending_remote_description_
2115 ? std::move(pending_remote_description_)
2116 : std::move(current_remote_description_);
2117 current_remote_description_ = std::move(desc);
2118 pending_remote_description_ = nullptr;
2119 current_local_description_ = std::move(pending_local_description_);
2120 } else {
2121 replaced_remote_description = std::move(pending_remote_description_);
2122 pending_remote_description_ = std::move(desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002123 }
Steve Anton8a006912017-12-04 15:25:56 -08002124 // The session description to apply now must be accessed by
2125 // |remote_description()|.
Henrik Boströmfdb92012017-11-09 19:55:44 +01002126 RTC_DCHECK(remote_description());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002127
Steve Anton8a006912017-12-04 15:25:56 -08002128 // Transport and Media channels will be created only when offer is set.
Steve Antondcc3c022017-12-22 16:02:54 -08002129 if (IsUnifiedPlan()) {
2130 RTCError error = UpdateTransceiversAndDataChannels(
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002131 cricket::CS_REMOTE, *remote_description(), local_description(),
2132 old_remote_description);
Steve Anton8a006912017-12-04 15:25:56 -08002133 if (!error.ok()) {
2134 return error;
2135 }
Steve Antondcc3c022017-12-22 16:02:54 -08002136 } else {
2137 if (type == SdpType::kOffer) {
2138 // TODO(bugs.webrtc.org/4676) - Handle CreateChannel failure, as new local
2139 // description is applied. Restore back to old description.
2140 RTCError error = CreateChannels(*remote_description()->description());
2141 if (!error.ok()) {
2142 return error;
2143 }
2144 }
Steve Anton8a006912017-12-04 15:25:56 -08002145
Steve Antondcc3c022017-12-22 16:02:54 -08002146 // Remove unused channels if MediaContentDescription is rejected.
2147 RemoveUnusedChannels(remote_description()->description());
2148 }
Steve Anton8a006912017-12-04 15:25:56 -08002149
2150 // NOTE: Candidates allocation will be initiated only when SetLocalDescription
2151 // is called.
Steve Anton71439a62018-02-15 11:53:06 -08002152 RTCError error = UpdateSessionState(type, cricket::CS_REMOTE);
Steve Anton8a006912017-12-04 15:25:56 -08002153 if (!error.ok()) {
2154 return error;
2155 }
2156
2157 if (local_description() &&
2158 !UseCandidatesInSessionDescription(remote_description())) {
2159 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidCandidates);
2160 }
2161
2162 if (old_remote_description) {
2163 for (const cricket::ContentInfo& content :
2164 old_remote_description->description()->contents()) {
2165 // Check if this new SessionDescription contains new ICE ufrag and
2166 // password that indicates the remote peer requests an ICE restart.
2167 // TODO(deadbeef): When we start storing both the current and pending
2168 // remote description, this should reset pending_ice_restarts and compare
2169 // against the current description.
2170 if (CheckForRemoteIceRestart(old_remote_description, remote_description(),
2171 content.name)) {
Steve Anton3828c062017-12-06 10:34:51 -08002172 if (type == SdpType::kOffer) {
Steve Anton8a006912017-12-04 15:25:56 -08002173 pending_ice_restarts_.insert(content.name);
2174 }
2175 } else {
2176 // We retain all received candidates only if ICE is not restarted.
2177 // When ICE is restarted, all previous candidates belong to an old
2178 // generation and should not be kept.
2179 // TODO(deadbeef): This goes against the W3C spec which says the remote
2180 // description should only contain candidates from the last set remote
2181 // description plus any candidates added since then. We should remove
2182 // this once we're sure it won't break anything.
2183 WebRtcSessionDescriptionFactory::CopyCandidatesFromSessionDescription(
2184 old_remote_description, content.name, mutable_remote_description());
2185 }
2186 }
2187 }
2188
2189 if (session_error() != SessionError::kNone) {
2190 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
2191 }
2192
2193 // Set the the ICE connection state to connecting since the connection may
2194 // become writable with peer reflexive candidates before any remote candidate
2195 // is signaled.
2196 // TODO(pthatcher): This is a short-term solution for crbug/446908. A real fix
2197 // is to have a new signal the indicates a change in checking state from the
2198 // transport and expose a new checking() member from transport that can be
2199 // read to determine the current checking state. The existing SignalConnecting
2200 // actually means "gathering candidates", so cannot be be used here.
Steve Antona3a92c22017-12-07 10:27:41 -08002201 if (remote_description()->GetType() != SdpType::kOffer &&
Steve Anton8a006912017-12-04 15:25:56 -08002202 ice_connection_state() == PeerConnectionInterface::kIceConnectionNew) {
2203 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
2204 }
2205
deadbeefab9b2d12015-10-14 11:33:11 -07002206 // If setting the description decided our SSL role, allocate any necessary
2207 // SCTP sids.
2208 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08002209 if (data_channel_type() == cricket::DCT_SCTP && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07002210 AllocateSctpSids(role);
2211 }
2212
Steve Antondcc3c022017-12-22 16:02:54 -08002213 if (IsUnifiedPlan()) {
Steve Antonef65ef12018-01-10 17:15:20 -08002214 std::vector<TrackEvent> track_events;
Steve Antonc49bcd92018-02-14 14:28:13 -08002215 std::vector<rtc::scoped_refptr<MediaStreamInterface>> added_streams;
Steve Antondcc3c022017-12-22 16:02:54 -08002216 for (auto transceiver : transceivers_) {
2217 const ContentInfo* content =
2218 FindMediaSectionForTransceiver(transceiver, remote_description());
2219 if (!content) {
2220 continue;
2221 }
2222 const MediaContentDescription* media_desc = content->media_description();
2223 RtpTransceiverDirection local_direction =
2224 RtpTransceiverDirectionReversed(media_desc->direction());
2225 // From the WebRTC specification, steps 2.2.8.5/6 of section 4.4.1.6 "Set
2226 // the RTCSessionDescription: If direction is sendrecv or recvonly, and
2227 // transceiver's current direction is neither sendrecv nor recvonly,
2228 // process the addition of a remote track for the media description.
2229 if (RtpTransceiverDirectionHasRecv(local_direction) &&
2230 (!transceiver->current_direction() ||
2231 !RtpTransceiverDirectionHasRecv(
Steve Anton74255ff2018-01-24 18:32:57 -08002232 *transceiver->current_direction())) &&
2233 !media_desc->streams().empty()) {
Steve Antonef65ef12018-01-10 17:15:20 -08002234 const std::string& sync_label = media_desc->streams()[0].sync_label;
2235 rtc::scoped_refptr<MediaStreamInterface> stream =
2236 remote_streams_->find(sync_label);
2237 if (!stream) {
2238 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
2239 MediaStream::Create(sync_label));
2240 remote_streams_->AddStream(stream);
Steve Antonc49bcd92018-02-14 14:28:13 -08002241 added_streams.push_back(stream);
Steve Antonef65ef12018-01-10 17:15:20 -08002242 }
2243 transceiver->internal()->receiver_internal()->SetStreams({stream});
2244 TrackEvent track_event;
2245 track_event.receiver = transceiver->receiver();
2246 track_event.streams = transceiver->receiver()->streams();
2247 track_events.push_back(std::move(track_event));
Steve Antondcc3c022017-12-22 16:02:54 -08002248 }
2249 // If direction is sendonly or inactive, and transceiver's current
2250 // direction is neither sendonly nor inactive, process the removal of a
2251 // remote track for the media description.
2252 if (!RtpTransceiverDirectionHasRecv(local_direction) &&
Steve Antonef65ef12018-01-10 17:15:20 -08002253 (transceiver->current_direction() &&
Steve Antondcc3c022017-12-22 16:02:54 -08002254 RtpTransceiverDirectionHasRecv(*transceiver->current_direction()))) {
Steve Antonef65ef12018-01-10 17:15:20 -08002255 transceiver->internal()->receiver_internal()->SetStreams({});
Steve Antondcc3c022017-12-22 16:02:54 -08002256 }
2257 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
2258 transceiver->internal()->set_current_direction(local_direction);
2259 }
2260 if (content->rejected && !transceiver->stopped()) {
2261 transceiver->Stop();
2262 }
Steve Anton74255ff2018-01-24 18:32:57 -08002263 if (!content->rejected && !media_desc->streams().empty()) {
Steve Antond3679212018-01-17 17:41:02 -08002264 transceiver->internal()->receiver_internal()->SetupMediaChannel(
Steve Anton5f94aa22018-02-01 10:58:30 -08002265 media_desc->streams()[0].first_ssrc());
Steve Antond3679212018-01-17 17:41:02 -08002266 }
Steve Antondcc3c022017-12-22 16:02:54 -08002267 }
Steve Antonc49bcd92018-02-14 14:28:13 -08002268 // Once all processing has finished, fire off callbacks.
Steve Antonef65ef12018-01-10 17:15:20 -08002269 for (auto event : track_events) {
2270 observer_->OnAddTrack(event.receiver, event.streams);
2271 }
Steve Antonc49bcd92018-02-14 14:28:13 -08002272 for (auto stream : added_streams) {
2273 observer_->OnAddStream(stream);
2274 }
Steve Antondcc3c022017-12-22 16:02:54 -08002275 }
2276
Henrik Boströmfdb92012017-11-09 19:55:44 +01002277 const cricket::ContentInfo* audio_content =
2278 GetFirstAudioContent(remote_description()->description());
2279 const cricket::ContentInfo* video_content =
2280 GetFirstVideoContent(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002281 const cricket::AudioContentDescription* audio_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002282 GetFirstAudioContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002283 const cricket::VideoContentDescription* video_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002284 GetFirstVideoContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002285 const cricket::DataContentDescription* data_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002286 GetFirstDataContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002287
2288 // Check if the descriptions include streams, just in case the peer supports
2289 // MSID, but doesn't indicate so with "a=msid-semantic".
Henrik Boströmfdb92012017-11-09 19:55:44 +01002290 if (remote_description()->description()->msid_supported() ||
deadbeefbda7e0b2015-12-08 17:13:40 -08002291 (audio_desc && !audio_desc->streams().empty()) ||
2292 (video_desc && !video_desc->streams().empty())) {
2293 remote_peer_supports_msid_ = true;
2294 }
deadbeefab9b2d12015-10-14 11:33:11 -07002295
2296 // We wait to signal new streams until we finish processing the description,
2297 // since only at that point will new streams have all their tracks.
2298 rtc::scoped_refptr<StreamCollection> new_streams(StreamCollection::Create());
2299
Steve Antondcc3c022017-12-22 16:02:54 -08002300 if (!IsUnifiedPlan()) {
2301 // TODO(steveanton): When removing RTP senders/receivers in response to a
2302 // rejected media section, there is some cleanup logic that expects the
2303 // voice/ video channel to still be set. But in this method the voice/video
2304 // channel would have been destroyed by the SetRemoteDescription caller
2305 // above so the cleanup that relies on them fails to run. The RemoveSenders
2306 // calls should be moved to right before the DestroyChannel calls to fix
2307 // this.
Steve Anton8d3444d2017-10-20 15:30:51 -07002308
Steve Antondcc3c022017-12-22 16:02:54 -08002309 // Find all audio rtp streams and create corresponding remote AudioTracks
2310 // and MediaStreams.
2311 if (audio_content) {
2312 if (audio_content->rejected) {
2313 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
2314 } else {
2315 bool default_audio_track_needed =
2316 !remote_peer_supports_msid_ &&
2317 RtpTransceiverDirectionHasSend(audio_desc->direction());
2318 UpdateRemoteSendersList(GetActiveStreams(audio_desc),
2319 default_audio_track_needed, audio_desc->type(),
2320 new_streams);
2321 }
deadbeeffaac4972015-11-12 15:33:07 -08002322 }
deadbeefab9b2d12015-10-14 11:33:11 -07002323
Steve Antondcc3c022017-12-22 16:02:54 -08002324 // Find all video rtp streams and create corresponding remote VideoTracks
2325 // and MediaStreams.
2326 if (video_content) {
2327 if (video_content->rejected) {
2328 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
2329 } else {
2330 bool default_video_track_needed =
2331 !remote_peer_supports_msid_ &&
2332 RtpTransceiverDirectionHasSend(video_desc->direction());
2333 UpdateRemoteSendersList(GetActiveStreams(video_desc),
2334 default_video_track_needed, video_desc->type(),
2335 new_streams);
2336 }
deadbeeffaac4972015-11-12 15:33:07 -08002337 }
deadbeefab9b2d12015-10-14 11:33:11 -07002338
Steve Antondcc3c022017-12-22 16:02:54 -08002339 // Update the DataChannels with the information from the remote peer.
2340 if (data_desc) {
2341 if (rtc::starts_with(data_desc->protocol().data(),
2342 cricket::kMediaProtocolRtpPrefix)) {
2343 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
2344 }
deadbeefab9b2d12015-10-14 11:33:11 -07002345 }
deadbeefab9b2d12015-10-14 11:33:11 -07002346
Steve Antondcc3c022017-12-22 16:02:54 -08002347 // Iterate new_streams and notify the observer about new MediaStreams.
2348 for (size_t i = 0; i < new_streams->count(); ++i) {
2349 MediaStreamInterface* new_stream = new_streams->at(i);
2350 stats_->AddStream(new_stream);
2351 observer_->OnAddStream(
2352 rtc::scoped_refptr<MediaStreamInterface>(new_stream));
2353 }
deadbeefab9b2d12015-10-14 11:33:11 -07002354
Steve Antondcc3c022017-12-22 16:02:54 -08002355 UpdateEndedRemoteMediaStreams();
2356 }
deadbeefab9b2d12015-10-14 11:33:11 -07002357
Steve Anton8a006912017-12-04 15:25:56 -08002358 return RTCError::OK();
deadbeeffc648b62015-10-13 16:42:33 -07002359}
2360
Steve Antondcc3c022017-12-22 16:02:54 -08002361RTCError PeerConnection::UpdateTransceiversAndDataChannels(
2362 cricket::ContentSource source,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002363 const SessionDescriptionInterface& new_session,
2364 const SessionDescriptionInterface* old_local_description,
2365 const SessionDescriptionInterface* old_remote_description) {
Steve Antondcc3c022017-12-22 16:02:54 -08002366 RTC_DCHECK(IsUnifiedPlan());
2367
Steve Anton7464fca2018-01-19 11:10:37 -08002368 const cricket::ContentGroup* bundle_group = nullptr;
2369 if (new_session.GetType() == SdpType::kOffer) {
2370 auto bundle_group_or_error =
2371 GetEarlyBundleGroup(*new_session.description());
2372 if (!bundle_group_or_error.ok()) {
2373 return bundle_group_or_error.MoveError();
2374 }
2375 bundle_group = bundle_group_or_error.MoveValue();
Steve Antondcc3c022017-12-22 16:02:54 -08002376 }
Steve Antondcc3c022017-12-22 16:02:54 -08002377
Steve Antondcc3c022017-12-22 16:02:54 -08002378 const ContentInfos& new_contents = new_session.description()->contents();
Steve Antondcc3c022017-12-22 16:02:54 -08002379 for (size_t i = 0; i < new_contents.size(); ++i) {
2380 const cricket::ContentInfo& new_content = new_contents[i];
Steve Antondcc3c022017-12-22 16:02:54 -08002381 cricket::MediaType media_type = new_content.media_description()->type();
2382 seen_mids_.insert(new_content.name);
2383 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
2384 media_type == cricket::MEDIA_TYPE_VIDEO) {
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002385 const cricket::ContentInfo* old_local_content = nullptr;
2386 if (old_local_description &&
2387 i < old_local_description->description()->contents().size()) {
2388 old_local_content =
2389 &old_local_description->description()->contents()[i];
2390 }
2391 const cricket::ContentInfo* old_remote_content = nullptr;
2392 if (old_remote_description &&
2393 i < old_remote_description->description()->contents().size()) {
2394 old_remote_content =
2395 &old_remote_description->description()->contents()[i];
2396 }
Steve Antondcc3c022017-12-22 16:02:54 -08002397 auto transceiver_or_error =
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002398 AssociateTransceiver(source, new_session.GetType(), i, new_content,
2399 old_local_content, old_remote_content);
Steve Antondcc3c022017-12-22 16:02:54 -08002400 if (!transceiver_or_error.ok()) {
2401 return transceiver_or_error.MoveError();
2402 }
2403 auto transceiver = transceiver_or_error.MoveValue();
Steve Antondcc3c022017-12-22 16:02:54 -08002404 RTCError error =
2405 UpdateTransceiverChannel(transceiver, new_content, bundle_group);
2406 if (!error.ok()) {
2407 return error;
2408 }
2409 } else if (media_type == cricket::MEDIA_TYPE_DATA) {
Steve Antonfa2260d2017-12-28 16:38:23 -08002410 if (GetDataMid() && new_content.name != *GetDataMid()) {
2411 // Ignore all but the first data section.
2412 continue;
2413 }
2414 RTCError error = UpdateDataChannel(source, new_content, bundle_group);
2415 if (!error.ok()) {
2416 return error;
2417 }
Steve Antondcc3c022017-12-22 16:02:54 -08002418 } else {
2419 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
2420 "Unknown section type.");
2421 }
2422 }
2423
2424 return RTCError::OK();
2425}
2426
2427RTCError PeerConnection::UpdateTransceiverChannel(
2428 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2429 transceiver,
2430 const cricket::ContentInfo& content,
2431 const cricket::ContentGroup* bundle_group) {
2432 RTC_DCHECK(IsUnifiedPlan());
2433 RTC_DCHECK(transceiver);
2434 cricket::BaseChannel* channel = transceiver->internal()->channel();
2435 if (content.rejected) {
2436 if (channel) {
2437 transceiver->internal()->SetChannel(nullptr);
2438 DestroyBaseChannel(channel);
2439 }
2440 } else {
2441 if (!channel) {
Steve Anton69470252018-02-09 11:43:08 -08002442 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Steve Antondcc3c022017-12-22 16:02:54 -08002443 channel = CreateVoiceChannel(
2444 content.name,
2445 GetTransportNameForMediaSection(content.name, bundle_group));
2446 } else {
Steve Anton69470252018-02-09 11:43:08 -08002447 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, transceiver->media_type());
Steve Antondcc3c022017-12-22 16:02:54 -08002448 channel = CreateVideoChannel(
2449 content.name,
2450 GetTransportNameForMediaSection(content.name, bundle_group));
2451 }
2452 if (!channel) {
2453 LOG_AND_RETURN_ERROR(
2454 RTCErrorType::INTERNAL_ERROR,
2455 "Failed to create channel for mid=" + content.name);
2456 }
2457 transceiver->internal()->SetChannel(channel);
2458 }
2459 }
2460 return RTCError::OK();
2461}
2462
Steve Antonfa2260d2017-12-28 16:38:23 -08002463RTCError PeerConnection::UpdateDataChannel(
2464 cricket::ContentSource source,
2465 const cricket::ContentInfo& content,
2466 const cricket::ContentGroup* bundle_group) {
2467 if (data_channel_type_ == cricket::DCT_NONE) {
Steve Antondbf9d032018-01-19 15:23:40 -08002468 // If data channels are disabled, ignore this media section. CreateAnswer
2469 // will take care of rejecting it.
2470 return RTCError::OK();
Steve Antonfa2260d2017-12-28 16:38:23 -08002471 }
2472 if (content.rejected) {
2473 DestroyDataChannel();
2474 } else {
2475 if (!rtp_data_channel_ && !sctp_transport_) {
2476 if (!CreateDataChannel(content.name, GetTransportNameForMediaSection(
2477 content.name, bundle_group))) {
2478 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
2479 "Failed to create data channel.");
2480 }
2481 }
2482 if (source == cricket::CS_REMOTE) {
2483 const MediaContentDescription* data_desc = content.media_description();
2484 if (data_desc && cricket::IsRtpProtocol(data_desc->protocol())) {
2485 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
2486 }
2487 }
2488 }
2489 return RTCError::OK();
2490}
2491
Steve Antondcc3c022017-12-22 16:02:54 -08002492RTCErrorOr<rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
2493PeerConnection::AssociateTransceiver(cricket::ContentSource source,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002494 SdpType type,
Steve Antondcc3c022017-12-22 16:02:54 -08002495 size_t mline_index,
2496 const ContentInfo& content,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002497 const ContentInfo* old_local_content,
2498 const ContentInfo* old_remote_content) {
Steve Antondcc3c022017-12-22 16:02:54 -08002499 RTC_DCHECK(IsUnifiedPlan());
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002500 // If this is an offer then the m= section might be recycled. If the m=
2501 // section is being recycled (defined as: rejected in the current local or
2502 // remote description and not rejected in new description), dissociate the
2503 // currently associated RtpTransceiver by setting its mid property to null,
2504 // and discard the mapping between the transceiver and its m= section index.
2505 if (IsMediaSectionBeingRecycled(type, content, old_local_content,
2506 old_remote_content)) {
2507 // We want to dissociate the transceiver that has the rejected mid.
2508 const std::string& old_mid =
2509 (old_local_content && old_local_content->rejected)
2510 ? old_local_content->name
2511 : old_remote_content->name;
2512 auto old_transceiver = GetAssociatedTransceiver(old_mid);
Steve Antondcc3c022017-12-22 16:02:54 -08002513 if (old_transceiver) {
2514 old_transceiver->internal()->set_mid(rtc::nullopt);
2515 old_transceiver->internal()->set_mline_index(rtc::nullopt);
2516 }
2517 }
2518 const MediaContentDescription* media_desc = content.media_description();
2519 auto transceiver = GetAssociatedTransceiver(content.name);
2520 if (source == cricket::CS_LOCAL) {
2521 // Find the RtpTransceiver that corresponds to this m= section, using the
2522 // mapping between transceivers and m= section indices established when
2523 // creating the offer.
2524 if (!transceiver) {
2525 transceiver = GetTransceiverByMLineIndex(mline_index);
2526 }
2527 if (!transceiver) {
2528 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2529 "Unknown transceiver");
2530 }
2531 } else {
2532 RTC_DCHECK_EQ(source, cricket::CS_REMOTE);
2533 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers
2534 // of the same type...
2535 if (!transceiver &&
2536 RtpTransceiverDirectionHasRecv(media_desc->direction())) {
2537 transceiver = FindAvailableTransceiverToReceive(media_desc->type());
2538 }
2539 // If no RtpTransceiver was found in the previous step, create one with a
2540 // recvonly direction.
2541 if (!transceiver) {
Steve Anton02ee47c2018-01-10 16:26:06 -08002542 auto sender =
2543 CreateSender(media_desc->type(), nullptr, {rtc::CreateRandomUuid()});
Steve Anton5f94aa22018-02-01 10:58:30 -08002544 std::string receiver_id;
2545 if (!media_desc->streams().empty()) {
2546 receiver_id = media_desc->streams()[0].id;
2547 } else {
2548 receiver_id = rtc::CreateRandomUuid();
2549 }
2550 auto receiver = CreateReceiver(media_desc->type(), receiver_id);
Steve Anton02ee47c2018-01-10 16:26:06 -08002551 transceiver = CreateAndAddTransceiver(sender, receiver);
Steve Antondcc3c022017-12-22 16:02:54 -08002552 transceiver->internal()->set_direction(
2553 RtpTransceiverDirection::kRecvOnly);
2554 }
2555 }
2556 RTC_DCHECK(transceiver);
Steve Anton69470252018-02-09 11:43:08 -08002557 if (transceiver->media_type() != media_desc->type()) {
Steve Antondcc3c022017-12-22 16:02:54 -08002558 LOG_AND_RETURN_ERROR(
2559 RTCErrorType::INVALID_PARAMETER,
2560 "Transceiver type does not match media description type.");
2561 }
2562 // Associate the found or created RtpTransceiver with the m= section by
2563 // setting the value of the RtpTransceiver's mid property to the MID of the m=
2564 // section, and establish a mapping between the transceiver and the index of
2565 // the m= section.
2566 transceiver->internal()->set_mid(content.name);
2567 transceiver->internal()->set_mline_index(mline_index);
2568 return std::move(transceiver);
2569}
2570
2571rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2572PeerConnection::GetAssociatedTransceiver(const std::string& mid) const {
2573 RTC_DCHECK(IsUnifiedPlan());
2574 for (auto transceiver : transceivers_) {
2575 if (transceiver->mid() == mid) {
2576 return transceiver;
2577 }
2578 }
2579 return nullptr;
2580}
2581
2582rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2583PeerConnection::GetTransceiverByMLineIndex(size_t mline_index) const {
2584 RTC_DCHECK(IsUnifiedPlan());
2585 for (auto transceiver : transceivers_) {
2586 if (transceiver->internal()->mline_index() == mline_index) {
2587 return transceiver;
2588 }
2589 }
2590 return nullptr;
2591}
2592
2593rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2594PeerConnection::FindAvailableTransceiverToReceive(
2595 cricket::MediaType media_type) const {
2596 RTC_DCHECK(IsUnifiedPlan());
2597 // From JSEP section 5.10 (Applying a Remote Description):
2598 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers of
2599 // the same type that were added to the PeerConnection by addTrack and are not
2600 // associated with any m= section and are not stopped, find the first such
2601 // RtpTransceiver.
2602 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08002603 if (transceiver->media_type() == media_type &&
Steve Antondcc3c022017-12-22 16:02:54 -08002604 transceiver->internal()->created_by_addtrack() && !transceiver->mid() &&
2605 !transceiver->stopped()) {
2606 return transceiver;
2607 }
2608 }
2609 return nullptr;
2610}
2611
Steve Antoned10bd92017-12-05 10:52:59 -08002612const cricket::ContentInfo* PeerConnection::FindMediaSectionForTransceiver(
2613 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2614 transceiver,
2615 const SessionDescriptionInterface* sdesc) const {
2616 RTC_DCHECK(transceiver);
2617 RTC_DCHECK(sdesc);
2618 if (IsUnifiedPlan()) {
2619 if (!transceiver->internal()->mid()) {
2620 // This transceiver is not associated with a media section yet.
2621 return nullptr;
2622 }
2623 return sdesc->description()->GetContentByName(
2624 *transceiver->internal()->mid());
2625 } else {
2626 // Plan B only allows at most one audio and one video section, so use the
2627 // first media section of that type.
2628 return cricket::GetFirstMediaContent(sdesc->description()->contents(),
Steve Anton69470252018-02-09 11:43:08 -08002629 transceiver->media_type());
Steve Antoned10bd92017-12-05 10:52:59 -08002630 }
2631}
2632
deadbeef46c73892016-11-16 19:42:04 -08002633PeerConnectionInterface::RTCConfiguration PeerConnection::GetConfiguration() {
2634 return configuration_;
2635}
2636
deadbeef293e9262017-01-11 12:28:30 -08002637bool PeerConnection::SetConfiguration(const RTCConfiguration& configuration,
2638 RTCError* error) {
Peter Boström1a9d6152015-12-08 22:15:17 +01002639 TRACE_EVENT0("webrtc", "PeerConnection::SetConfiguration");
deadbeef6de92f92016-12-12 18:49:32 -08002640
Steve Anton75737c02017-11-06 10:37:17 -08002641 if (local_description() && configuration.ice_candidate_pool_size !=
2642 configuration_.ice_candidate_pool_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002643 RTC_LOG(LS_ERROR) << "Can't change candidate pool size after calling "
2644 "SetLocalDescription.";
deadbeef293e9262017-01-11 12:28:30 -08002645 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00002646 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002647
deadbeef293e9262017-01-11 12:28:30 -08002648 // The simplest (and most future-compatible) way to tell if the config was
2649 // modified in an invalid way is to copy each property we do support
2650 // modifying, then use operator==. There are far more properties we don't
2651 // support modifying than those we do, and more could be added.
2652 RTCConfiguration modified_config = configuration_;
2653 modified_config.servers = configuration.servers;
2654 modified_config.type = configuration.type;
2655 modified_config.ice_candidate_pool_size =
2656 configuration.ice_candidate_pool_size;
2657 modified_config.prune_turn_ports = configuration.prune_turn_ports;
skvladd1f5fda2017-02-03 16:54:05 -08002658 modified_config.ice_check_min_interval = configuration.ice_check_min_interval;
Jonas Orelandbdcee282017-10-10 14:01:40 +02002659 modified_config.turn_customizer = configuration.turn_customizer;
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08002660 modified_config.network_preference = configuration.network_preference;
deadbeef293e9262017-01-11 12:28:30 -08002661 if (configuration != modified_config) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002662 RTC_LOG(LS_ERROR) << "Modifying the configuration in an unsupported way.";
deadbeef293e9262017-01-11 12:28:30 -08002663 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
2664 }
2665
Steve Anton038834f2017-07-14 15:59:59 -07002666 // Validate the modified configuration.
2667 RTCError validate_error = ValidateConfiguration(modified_config);
2668 if (!validate_error.ok()) {
2669 return SafeSetError(std::move(validate_error), error);
2670 }
2671
deadbeef293e9262017-01-11 12:28:30 -08002672 // Note that this isn't possible through chromium, since it's an unsigned
2673 // short in WebIDL.
2674 if (configuration.ice_candidate_pool_size < 0 ||
2675 configuration.ice_candidate_pool_size > UINT16_MAX) {
2676 return SafeSetError(RTCErrorType::INVALID_RANGE, error);
2677 }
2678
2679 // Parse ICE servers before hopping to network thread.
2680 cricket::ServerAddresses stun_servers;
2681 std::vector<cricket::RelayServerConfig> turn_servers;
2682 RTCErrorType parse_error =
2683 ParseIceServers(configuration.servers, &stun_servers, &turn_servers);
2684 if (parse_error != RTCErrorType::NONE) {
2685 return SafeSetError(parse_error, error);
2686 }
2687
2688 // In theory this shouldn't fail.
2689 if (!network_thread()->Invoke<bool>(
2690 RTC_FROM_HERE,
2691 rtc::Bind(&PeerConnection::ReconfigurePortAllocator_n, this,
2692 stun_servers, turn_servers, modified_config.type,
2693 modified_config.ice_candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02002694 modified_config.prune_turn_ports,
2695 modified_config.turn_customizer))) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002696 RTC_LOG(LS_ERROR) << "Failed to apply configuration to PortAllocator.";
deadbeef293e9262017-01-11 12:28:30 -08002697 return SafeSetError(RTCErrorType::INTERNAL_ERROR, error);
2698 }
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07002699
deadbeefd1a38b52016-12-10 13:15:33 -08002700 // As described in JSEP, calling setConfiguration with new ICE servers or
2701 // candidate policy must set a "needs-ice-restart" bit so that the next offer
2702 // triggers an ICE restart which will pick up the changes.
deadbeef293e9262017-01-11 12:28:30 -08002703 if (modified_config.servers != configuration_.servers ||
2704 modified_config.type != configuration_.type ||
2705 modified_config.prune_turn_ports != configuration_.prune_turn_ports) {
Steve Antond25da372017-11-06 14:50:29 -08002706 transport_controller_->SetNeedsIceRestartFlag();
deadbeefd1a38b52016-12-10 13:15:33 -08002707 }
skvladd1f5fda2017-02-03 16:54:05 -08002708
Qingsi Wang9c98f0c2018-02-15 15:10:59 -08002709 transport_controller_->SetIceConfig(ParseIceConfig(modified_config));
skvladd1f5fda2017-02-03 16:54:05 -08002710
deadbeef293e9262017-01-11 12:28:30 -08002711 configuration_ = modified_config;
2712 return SafeSetError(RTCErrorType::NONE, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00002713}
2714
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002715bool PeerConnection::AddIceCandidate(
2716 const IceCandidateInterface* ice_candidate) {
Peter Boström1a9d6152015-12-08 22:15:17 +01002717 TRACE_EVENT0("webrtc", "PeerConnection::AddIceCandidate");
zhihuang29ff8442016-07-27 11:07:25 -07002718 if (IsClosed()) {
2719 return false;
2720 }
Steve Antond25da372017-11-06 14:50:29 -08002721
2722 if (!remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002723 RTC_LOG(LS_ERROR) << "ProcessIceMessage: ICE candidates can't be added "
Jonas Olsson45cc8902018-02-13 10:37:07 +01002724 "without any remote session description.";
Steve Antond25da372017-11-06 14:50:29 -08002725 return false;
2726 }
2727
2728 if (!ice_candidate) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002729 RTC_LOG(LS_ERROR) << "ProcessIceMessage: Candidate is NULL.";
Steve Antond25da372017-11-06 14:50:29 -08002730 return false;
2731 }
2732
2733 bool valid = false;
2734 bool ready = ReadyToUseRemoteCandidate(ice_candidate, nullptr, &valid);
2735 if (!valid) {
2736 return false;
2737 }
2738
2739 // Add this candidate to the remote session description.
2740 if (!mutable_remote_description()->AddCandidate(ice_candidate)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002741 RTC_LOG(LS_ERROR) << "ProcessIceMessage: Candidate cannot be used.";
Steve Antond25da372017-11-06 14:50:29 -08002742 return false;
2743 }
2744
2745 if (ready) {
2746 return UseCandidate(ice_candidate);
2747 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002748 RTC_LOG(LS_INFO) << "ProcessIceMessage: Not ready to use candidate.";
Steve Antond25da372017-11-06 14:50:29 -08002749 return true;
2750 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002751}
2752
Honghai Zhang7fb69db2016-03-14 11:59:18 -07002753bool PeerConnection::RemoveIceCandidates(
2754 const std::vector<cricket::Candidate>& candidates) {
2755 TRACE_EVENT0("webrtc", "PeerConnection::RemoveIceCandidates");
Steve Antond25da372017-11-06 14:50:29 -08002756 if (!remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002757 RTC_LOG(LS_ERROR) << "RemoveRemoteIceCandidates: ICE candidates can't be "
Jonas Olsson45cc8902018-02-13 10:37:07 +01002758 "removed without any remote session description.";
Steve Antond25da372017-11-06 14:50:29 -08002759 return false;
2760 }
2761
2762 if (candidates.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002763 RTC_LOG(LS_ERROR) << "RemoveRemoteIceCandidates: candidates are empty.";
Steve Antond25da372017-11-06 14:50:29 -08002764 return false;
2765 }
2766
2767 size_t number_removed =
2768 mutable_remote_description()->RemoveCandidates(candidates);
2769 if (number_removed != candidates.size()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002770 RTC_LOG(LS_ERROR)
2771 << "RemoveRemoteIceCandidates: Failed to remove candidates. "
Jonas Olsson45cc8902018-02-13 10:37:07 +01002772 "Requested "
2773 << candidates.size() << " but only " << number_removed
Mirko Bonadei675513b2017-11-09 11:09:25 +01002774 << " are removed.";
Steve Antond25da372017-11-06 14:50:29 -08002775 }
2776
2777 // Remove the candidates from the transport controller.
2778 std::string error;
2779 bool res = transport_controller_->RemoveRemoteCandidates(candidates, &error);
2780 if (!res && !error.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002781 RTC_LOG(LS_ERROR) << "Error when removing remote candidates: " << error;
Steve Antond25da372017-11-06 14:50:29 -08002782 }
2783 return true;
Honghai Zhang7fb69db2016-03-14 11:59:18 -07002784}
2785
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00002786void PeerConnection::RegisterUMAObserver(UMAObserver* observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +01002787 TRACE_EVENT0("webrtc", "PeerConnection::RegisterUmaObserver");
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00002788 uma_observer_ = observer;
guoweis@webrtc.org7169afd2014-12-04 17:59:29 +00002789
Steve Anton75737c02017-11-06 10:37:17 -08002790 if (transport_controller()) {
2791 transport_controller()->SetMetricsObserver(uma_observer_);
guoweis@webrtc.org7169afd2014-12-04 17:59:29 +00002792 }
2793
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00002794 // Send information about IPv4/IPv6 status.
deadbeef293e9262017-01-11 12:28:30 -08002795 if (uma_observer_) {
Honghai Zhangd93f50c2016-10-05 11:47:22 -07002796 port_allocator_->SetMetricsObserver(uma_observer_);
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00002797 if (port_allocator_->flags() & cricket::PORTALLOCATOR_ENABLE_IPV6) {
Guo-wei Shiehdfbe6792015-09-03 17:12:07 -07002798 uma_observer_->IncrementEnumCounter(
2799 kEnumCounterAddressFamily, kPeerConnection_IPv6,
2800 kPeerConnectionAddressFamilyCounter_Max);
mallinath@webrtc.orgb445f262014-05-23 22:19:37 +00002801 } else {
Guo-wei Shiehdfbe6792015-09-03 17:12:07 -07002802 uma_observer_->IncrementEnumCounter(
2803 kEnumCounterAddressFamily, kPeerConnection_IPv4,
2804 kPeerConnectionAddressFamilyCounter_Max);
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00002805 }
Harald Alvestrand5dbb5862018-02-13 23:48:00 +01002806 // Send information about the requested SDP semantics.
2807 switch (configuration_.sdp_semantics) {
2808 case SdpSemantics::kDefault:
2809 uma_observer_->IncrementEnumCounter(kEnumCounterSdpSemanticRequested,
2810 kSdpSemanticRequestDefault,
2811 kSdpSemanticRequestMax);
2812
2813 break;
2814 case SdpSemantics::kPlanB:
2815 uma_observer_->IncrementEnumCounter(kEnumCounterSdpSemanticRequested,
2816 kSdpSemanticRequestPlanB,
2817 kSdpSemanticRequestMax);
2818 break;
2819 case SdpSemantics::kUnifiedPlan:
2820 uma_observer_->IncrementEnumCounter(kEnumCounterSdpSemanticRequested,
2821 kSdpSemanticRequestUnifiedPlan,
2822 kSdpSemanticRequestMax);
2823 break;
2824 default:
2825 RTC_NOTREACHED();
2826 }
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00002827 }
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00002828}
2829
zstein4b979802017-06-02 14:37:37 -07002830RTCError PeerConnection::SetBitrate(const BitrateParameters& bitrate) {
Steve Anton978b8762017-09-29 12:15:02 -07002831 if (!worker_thread()->IsCurrent()) {
2832 return worker_thread()->Invoke<RTCError>(
zstein4b979802017-06-02 14:37:37 -07002833 RTC_FROM_HERE, rtc::Bind(&PeerConnection::SetBitrate, this, bitrate));
2834 }
2835
2836 const bool has_min = static_cast<bool>(bitrate.min_bitrate_bps);
2837 const bool has_current = static_cast<bool>(bitrate.current_bitrate_bps);
2838 const bool has_max = static_cast<bool>(bitrate.max_bitrate_bps);
2839 if (has_min && *bitrate.min_bitrate_bps < 0) {
2840 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2841 "min_bitrate_bps <= 0");
2842 }
2843 if (has_current) {
2844 if (has_min && *bitrate.current_bitrate_bps < *bitrate.min_bitrate_bps) {
2845 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2846 "current_bitrate_bps < min_bitrate_bps");
2847 } else if (*bitrate.current_bitrate_bps < 0) {
2848 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2849 "curent_bitrate_bps < 0");
2850 }
2851 }
2852 if (has_max) {
2853 if (has_current &&
2854 *bitrate.max_bitrate_bps < *bitrate.current_bitrate_bps) {
2855 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2856 "max_bitrate_bps < current_bitrate_bps");
2857 } else if (has_min && *bitrate.max_bitrate_bps < *bitrate.min_bitrate_bps) {
2858 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2859 "max_bitrate_bps < min_bitrate_bps");
2860 } else if (*bitrate.max_bitrate_bps < 0) {
2861 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2862 "max_bitrate_bps < 0");
2863 }
2864 }
2865
2866 Call::Config::BitrateConfigMask mask;
2867 mask.min_bitrate_bps = bitrate.min_bitrate_bps;
2868 mask.start_bitrate_bps = bitrate.current_bitrate_bps;
2869 mask.max_bitrate_bps = bitrate.max_bitrate_bps;
2870
2871 RTC_DCHECK(call_.get());
2872 call_->SetBitrateConfigMask(mask);
2873
2874 return RTCError::OK();
2875}
2876
Alex Narest78609d52017-10-20 10:37:47 +02002877void PeerConnection::SetBitrateAllocationStrategy(
2878 std::unique_ptr<rtc::BitrateAllocationStrategy>
2879 bitrate_allocation_strategy) {
2880 rtc::Thread* worker_thread = factory_->worker_thread();
2881 if (!worker_thread->IsCurrent()) {
2882 rtc::BitrateAllocationStrategy* strategy_raw =
2883 bitrate_allocation_strategy.release();
2884 auto functor = [this, strategy_raw]() {
2885 call_->SetBitrateAllocationStrategy(
2886 rtc::WrapUnique<rtc::BitrateAllocationStrategy>(strategy_raw));
2887 };
2888 worker_thread->Invoke<void>(RTC_FROM_HERE, functor);
2889 return;
2890 }
2891 RTC_DCHECK(call_.get());
2892 call_->SetBitrateAllocationStrategy(std::move(bitrate_allocation_strategy));
2893}
2894
henrika5f6bf242017-11-01 11:06:56 +01002895void PeerConnection::SetAudioPlayout(bool playout) {
2896 if (!worker_thread()->IsCurrent()) {
2897 worker_thread()->Invoke<void>(
2898 RTC_FROM_HERE,
2899 rtc::Bind(&PeerConnection::SetAudioPlayout, this, playout));
2900 return;
2901 }
2902 auto audio_state =
2903 factory_->channel_manager()->media_engine()->GetAudioState();
2904 audio_state->SetPlayout(playout);
2905}
2906
2907void PeerConnection::SetAudioRecording(bool recording) {
2908 if (!worker_thread()->IsCurrent()) {
2909 worker_thread()->Invoke<void>(
2910 RTC_FROM_HERE,
2911 rtc::Bind(&PeerConnection::SetAudioRecording, this, recording));
2912 return;
2913 }
2914 auto audio_state =
2915 factory_->channel_manager()->media_engine()->GetAudioState();
2916 audio_state->SetRecording(recording);
2917}
2918
Steve Anton8c0f7a72017-10-03 10:03:10 -07002919std::unique_ptr<rtc::SSLCertificate>
2920PeerConnection::GetRemoteAudioSSLCertificate() {
Steve Anton75737c02017-11-06 10:37:17 -08002921 if (!voice_channel()) {
Steve Anton8c0f7a72017-10-03 10:03:10 -07002922 return nullptr;
2923 }
Steve Anton75737c02017-11-06 10:37:17 -08002924 return GetRemoteSSLCertificate(voice_channel()->transport_name());
Steve Anton8c0f7a72017-10-03 10:03:10 -07002925}
2926
Zhi Huang70b820f2018-01-27 14:16:15 -08002927std::unique_ptr<rtc::SSLCertChain>
2928PeerConnection::GetRemoteAudioSSLCertChain() {
2929 if (!voice_channel()) {
2930 return nullptr;
2931 }
2932
2933 return transport_controller_->GetRemoteSSLCertChain(
2934 voice_channel()->transport_name());
2935}
2936
ivoc14d5dbe2016-07-04 07:06:55 -07002937bool PeerConnection::StartRtcEventLog(rtc::PlatformFile file,
2938 int64_t max_size_bytes) {
Elad Alon99c3fe52017-10-13 16:29:40 +02002939 // TODO(eladalon): It would be better to not allow negative values into PC.
2940 const size_t max_size = (max_size_bytes < 0)
2941 ? RtcEventLog::kUnlimitedOutput
2942 : rtc::saturated_cast<size_t>(max_size_bytes);
2943 return StartRtcEventLog(
Bjorn Tereliusde939432017-11-20 17:38:14 +01002944 rtc::MakeUnique<RtcEventLogOutputFile>(file, max_size),
2945 webrtc::RtcEventLog::kImmediateOutput);
Elad Alon99c3fe52017-10-13 16:29:40 +02002946}
2947
Bjorn Tereliusde939432017-11-20 17:38:14 +01002948bool PeerConnection::StartRtcEventLog(std::unique_ptr<RtcEventLogOutput> output,
2949 int64_t output_period_ms) {
Karl Wibergd6b48192017-10-16 23:01:06 +02002950 // TODO(eladalon): In C++14, this can be done with a lambda.
2951 struct Functor {
Bjorn Tereliusde939432017-11-20 17:38:14 +01002952 bool operator()() {
2953 return pc->StartRtcEventLog_w(std::move(output), output_period_ms);
2954 }
Karl Wibergd6b48192017-10-16 23:01:06 +02002955 PeerConnection* const pc;
2956 std::unique_ptr<RtcEventLogOutput> output;
Bjorn Tereliusde939432017-11-20 17:38:14 +01002957 const int64_t output_period_ms;
Elad Alon99c3fe52017-10-13 16:29:40 +02002958 };
Bjorn Tereliusde939432017-11-20 17:38:14 +01002959 return worker_thread()->Invoke<bool>(
2960 RTC_FROM_HERE, Functor{this, std::move(output), output_period_ms});
ivoc14d5dbe2016-07-04 07:06:55 -07002961}
2962
2963void PeerConnection::StopRtcEventLog() {
Steve Anton978b8762017-09-29 12:15:02 -07002964 worker_thread()->Invoke<void>(
ivoc14d5dbe2016-07-04 07:06:55 -07002965 RTC_FROM_HERE, rtc::Bind(&PeerConnection::StopRtcEventLog_w, this));
2966}
2967
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002968const SessionDescriptionInterface* PeerConnection::local_description() const {
Steve Anton75737c02017-11-06 10:37:17 -08002969 return pending_local_description_ ? pending_local_description_.get()
2970 : current_local_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002971}
2972
2973const SessionDescriptionInterface* PeerConnection::remote_description() const {
Steve Anton75737c02017-11-06 10:37:17 -08002974 return pending_remote_description_ ? pending_remote_description_.get()
2975 : current_remote_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002976}
2977
deadbeeffe4a8a42016-12-20 17:56:17 -08002978const SessionDescriptionInterface* PeerConnection::current_local_description()
2979 const {
Steve Anton75737c02017-11-06 10:37:17 -08002980 return current_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08002981}
2982
2983const SessionDescriptionInterface* PeerConnection::current_remote_description()
2984 const {
Steve Anton75737c02017-11-06 10:37:17 -08002985 return current_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08002986}
2987
2988const SessionDescriptionInterface* PeerConnection::pending_local_description()
2989 const {
Steve Anton75737c02017-11-06 10:37:17 -08002990 return pending_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08002991}
2992
2993const SessionDescriptionInterface* PeerConnection::pending_remote_description()
2994 const {
Steve Anton75737c02017-11-06 10:37:17 -08002995 return pending_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08002996}
2997
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002998void PeerConnection::Close() {
Peter Boström1a9d6152015-12-08 22:15:17 +01002999 TRACE_EVENT0("webrtc", "PeerConnection::Close");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003000 // Update stats here so that we have the most recent stats for tracks and
3001 // streams before the channels are closed.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00003002 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003003
Steve Anton75737c02017-11-06 10:37:17 -08003004 ChangeSignalingState(PeerConnectionInterface::kClosed);
Steve Anton3fe1b152017-12-12 10:20:08 -08003005
Steve Anton8af21862017-12-15 11:20:13 -08003006 for (auto transceiver : transceivers_) {
3007 transceiver->Stop();
3008 }
3009 DestroyAllChannels();
Steve Anton75737c02017-11-06 10:37:17 -08003010
Qingsi Wang93a84392018-01-30 17:13:09 -08003011 // The event log is used in the transport controller, which must be outlived
3012 // by the former. CreateOffer by the peer connection is implemented
3013 // asynchronously and if the peer connection is closed without resetting the
3014 // WebRTC session description factory, the session description factory would
3015 // call the transport controller.
3016 webrtc_session_desc_factory_.reset();
3017 transport_controller_.reset();
3018
deadbeef42a42632017-03-10 15:18:00 -08003019 network_thread()->Invoke<void>(
3020 RTC_FROM_HERE,
3021 rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
3022 port_allocator_.get()));
nisseeaabdf62017-05-05 02:23:02 -07003023
Steve Anton978b8762017-09-29 12:15:02 -07003024 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
eladalon248fd4f2017-09-06 05:18:15 -07003025 call_.reset();
3026 // The event log must outlive call (and any other object that uses it).
3027 event_log_.reset();
3028 });
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003029}
3030
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003031void PeerConnection::OnMessage(rtc::Message* msg) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003032 switch (msg->message_id) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003033 case MSG_SET_SESSIONDESCRIPTION_SUCCESS: {
3034 SetSessionDescriptionMsg* param =
3035 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
3036 param->observer->OnSuccess();
3037 delete param;
3038 break;
3039 }
3040 case MSG_SET_SESSIONDESCRIPTION_FAILED: {
3041 SetSessionDescriptionMsg* param =
3042 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
3043 param->observer->OnFailure(param->error);
3044 delete param;
3045 break;
3046 }
deadbeefab9b2d12015-10-14 11:33:11 -07003047 case MSG_CREATE_SESSIONDESCRIPTION_FAILED: {
3048 CreateSessionDescriptionMsg* param =
3049 static_cast<CreateSessionDescriptionMsg*>(msg->pdata);
3050 param->observer->OnFailure(param->error);
3051 delete param;
3052 break;
3053 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003054 case MSG_GETSTATS: {
3055 GetStatsMsg* param = static_cast<GetStatsMsg*>(msg->pdata);
nissee8abe3e2017-01-18 05:00:34 -08003056 StatsReports reports;
3057 stats_->GetStats(param->track, &reports);
3058 param->observer->OnComplete(reports);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003059 delete param;
3060 break;
3061 }
deadbeefbd292462015-12-14 18:15:29 -08003062 case MSG_FREE_DATACHANNELS: {
3063 sctp_data_channels_to_free_.clear();
3064 break;
3065 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003066 default:
nisseeb4ca4e2017-01-12 02:24:27 -08003067 RTC_NOTREACHED() << "Not implemented";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003068 break;
3069 }
3070}
3071
Steve Anton4171afb2017-11-20 10:20:22 -08003072void PeerConnection::CreateAudioReceiver(
3073 MediaStreamInterface* stream,
3074 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01003075 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
3076 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Steve Antond3679212018-01-17 17:41:02 -08003077 auto* audio_receiver = new AudioRtpReceiver(
3078 worker_thread(), remote_sender_info.sender_id, streams);
Guido Urdanetaee2388f2018-02-15 16:36:19 +00003079 audio_receiver->SetMediaChannel(voice_media_channel());
Steve Antond3679212018-01-17 17:41:02 -08003080 audio_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
3081 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
3082 signaling_thread(), audio_receiver);
Steve Anton4171afb2017-11-20 10:20:22 -08003083 GetAudioTransceiver()->internal()->AddReceiver(receiver);
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01003084 observer_->OnAddTrack(receiver, std::move(streams));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003085}
3086
Steve Anton4171afb2017-11-20 10:20:22 -08003087void PeerConnection::CreateVideoReceiver(
3088 MediaStreamInterface* stream,
3089 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01003090 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
3091 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Steve Antond3679212018-01-17 17:41:02 -08003092 auto* video_receiver = new VideoRtpReceiver(
3093 worker_thread(), remote_sender_info.sender_id, streams);
Guido Urdanetaee2388f2018-02-15 16:36:19 +00003094 video_receiver->SetMediaChannel(video_media_channel());
Steve Antond3679212018-01-17 17:41:02 -08003095 video_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
3096 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
3097 signaling_thread(), video_receiver);
Steve Anton4171afb2017-11-20 10:20:22 -08003098 GetVideoTransceiver()->internal()->AddReceiver(receiver);
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01003099 observer_->OnAddTrack(receiver, std::move(streams));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003100}
3101
deadbeef70ab1a12015-09-28 16:53:55 -07003102// TODO(deadbeef): Keep RtpReceivers around even if track goes away in remote
3103// description.
Henrik Boström933d8b02017-10-10 10:05:16 -07003104rtc::scoped_refptr<RtpReceiverInterface> PeerConnection::RemoveAndStopReceiver(
Steve Anton4171afb2017-11-20 10:20:22 -08003105 const RtpSenderInfo& remote_sender_info) {
3106 auto receiver = FindReceiverById(remote_sender_info.sender_id);
3107 if (!receiver) {
3108 RTC_LOG(LS_WARNING) << "RtpReceiver for track with id "
3109 << remote_sender_info.sender_id << " doesn't exist.";
Henrik Boström933d8b02017-10-10 10:05:16 -07003110 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07003111 }
Steve Anton4171afb2017-11-20 10:20:22 -08003112 if (receiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
3113 GetAudioTransceiver()->internal()->RemoveReceiver(receiver);
3114 } else {
3115 GetVideoTransceiver()->internal()->RemoveReceiver(receiver);
3116 }
Henrik Boström933d8b02017-10-10 10:05:16 -07003117 return receiver;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003118}
3119
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003120void PeerConnection::AddAudioTrack(AudioTrackInterface* track,
3121 MediaStreamInterface* stream) {
3122 RTC_DCHECK(!IsClosed());
3123 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003124 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003125 // We already have a sender for this track, so just change the stream_id
3126 // so that it's correct in the next call to CreateOffer.
Steve Anton4171afb2017-11-20 10:20:22 -08003127 sender->internal()->set_stream_id(stream->label());
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003128 return;
3129 }
3130
3131 // Normal case; we've never seen this track before.
Steve Anton02ee47c2018-01-10 16:26:06 -08003132 auto new_sender =
3133 CreateSender(cricket::MEDIA_TYPE_AUDIO, track, {stream->label()});
Guido Urdanetaee2388f2018-02-15 16:36:19 +00003134 static_cast<AudioRtpSender*>(new_sender->internal())
3135 ->SetMediaChannel(voice_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08003136 GetAudioTransceiver()->internal()->AddSender(new_sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003137 // If the sender has already been configured in SDP, we call SetSsrc,
3138 // which will connect the sender to the underlying transport. This can
3139 // occur if a local session description that contains the ID of the sender
3140 // is set before AddStream is called. It can also occur if the local
3141 // session description is not changed and RemoveStream is called, and
3142 // later AddStream is called again with the same stream.
Steve Anton4171afb2017-11-20 10:20:22 -08003143 const RtpSenderInfo* sender_info =
3144 FindSenderInfo(local_audio_sender_infos_, stream->label(), track->id());
3145 if (sender_info) {
3146 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003147 }
3148}
3149
3150// TODO(deadbeef): Don't destroy RtpSenders here; they should be kept around
3151// indefinitely, when we have unified plan SDP.
3152void PeerConnection::RemoveAudioTrack(AudioTrackInterface* track,
3153 MediaStreamInterface* stream) {
3154 RTC_DCHECK(!IsClosed());
3155 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003156 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003157 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
3158 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003159 return;
3160 }
Steve Anton4171afb2017-11-20 10:20:22 -08003161 GetAudioTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003162}
3163
3164void PeerConnection::AddVideoTrack(VideoTrackInterface* track,
3165 MediaStreamInterface* stream) {
3166 RTC_DCHECK(!IsClosed());
3167 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003168 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003169 // We already have a sender for this track, so just change the stream_id
3170 // so that it's correct in the next call to CreateOffer.
Steve Anton4171afb2017-11-20 10:20:22 -08003171 sender->internal()->set_stream_id(stream->label());
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003172 return;
3173 }
3174
3175 // Normal case; we've never seen this track before.
Steve Anton02ee47c2018-01-10 16:26:06 -08003176 auto new_sender =
3177 CreateSender(cricket::MEDIA_TYPE_VIDEO, track, {stream->label()});
Guido Urdanetaee2388f2018-02-15 16:36:19 +00003178 static_cast<VideoRtpSender*>(new_sender->internal())
3179 ->SetMediaChannel(video_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08003180 GetVideoTransceiver()->internal()->AddSender(new_sender);
3181 const RtpSenderInfo* sender_info =
3182 FindSenderInfo(local_video_sender_infos_, stream->label(), track->id());
3183 if (sender_info) {
3184 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003185 }
3186}
3187
3188void PeerConnection::RemoveVideoTrack(VideoTrackInterface* track,
3189 MediaStreamInterface* stream) {
3190 RTC_DCHECK(!IsClosed());
3191 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003192 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003193 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
3194 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003195 return;
3196 }
Steve Anton4171afb2017-11-20 10:20:22 -08003197 GetVideoTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003198}
3199
Steve Antonba818672017-11-06 10:21:57 -08003200void PeerConnection::SetIceConnectionState(IceConnectionState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07003201 RTC_DCHECK(signaling_thread()->IsCurrent());
Steve Antonba818672017-11-06 10:21:57 -08003202 if (ice_connection_state_ == new_state) {
3203 return;
3204 }
3205
deadbeefcbecd352015-09-23 11:50:27 -07003206 // After transitioning to "closed", ignore any additional states from
Steve Antonba818672017-11-06 10:21:57 -08003207 // TransportController (such as "disconnected").
deadbeefab9b2d12015-10-14 11:33:11 -07003208 if (IsClosed()) {
deadbeefcbecd352015-09-23 11:50:27 -07003209 return;
3210 }
Steve Antonba818672017-11-06 10:21:57 -08003211
Mirko Bonadei675513b2017-11-09 11:09:25 +01003212 RTC_LOG(LS_INFO) << "Changing IceConnectionState " << ice_connection_state_
3213 << " => " << new_state;
Steve Antonba818672017-11-06 10:21:57 -08003214 RTC_DCHECK(ice_connection_state_ !=
3215 PeerConnectionInterface::kIceConnectionClosed);
3216
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003217 ice_connection_state_ = new_state;
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00003218 observer_->OnIceConnectionChange(ice_connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003219}
3220
3221void PeerConnection::OnIceGatheringChange(
3222 PeerConnectionInterface::IceGatheringState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07003223 RTC_DCHECK(signaling_thread()->IsCurrent());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003224 if (IsClosed()) {
3225 return;
3226 }
3227 ice_gathering_state_ = new_state;
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00003228 observer_->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003229}
3230
jbauch81bf7b02017-03-25 08:31:12 -07003231void PeerConnection::OnIceCandidate(
3232 std::unique_ptr<IceCandidateInterface> candidate) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07003233 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07003234 if (IsClosed()) {
3235 return;
3236 }
jbauch81bf7b02017-03-25 08:31:12 -07003237 observer_->OnIceCandidate(candidate.get());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003238}
3239
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003240void PeerConnection::OnIceCandidatesRemoved(
3241 const std::vector<cricket::Candidate>& candidates) {
3242 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07003243 if (IsClosed()) {
3244 return;
3245 }
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003246 observer_->OnIceCandidatesRemoved(candidates);
3247}
3248
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003249void PeerConnection::ChangeSignalingState(
3250 PeerConnectionInterface::SignalingState signaling_state) {
Steve Antonba818672017-11-06 10:21:57 -08003251 RTC_DCHECK(signaling_thread()->IsCurrent());
3252 if (signaling_state_ == signaling_state) {
3253 return;
3254 }
Mirko Bonadei675513b2017-11-09 11:09:25 +01003255 RTC_LOG(LS_INFO) << "Session: " << session_id() << " Old state: "
3256 << GetSignalingStateString(signaling_state_)
3257 << " New state: "
3258 << GetSignalingStateString(signaling_state);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003259 signaling_state_ = signaling_state;
3260 if (signaling_state == kClosed) {
3261 ice_connection_state_ = kIceConnectionClosed;
3262 observer_->OnIceConnectionChange(ice_connection_state_);
3263 if (ice_gathering_state_ != kIceGatheringComplete) {
3264 ice_gathering_state_ = kIceGatheringComplete;
3265 observer_->OnIceGatheringChange(ice_gathering_state_);
3266 }
3267 }
3268 observer_->OnSignalingChange(signaling_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003269}
3270
deadbeefeb459812015-12-15 19:24:43 -08003271void PeerConnection::OnAudioTrackAdded(AudioTrackInterface* track,
3272 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003273 if (IsClosed()) {
3274 return;
3275 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003276 AddAudioTrack(track, stream);
3277 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003278}
3279
deadbeefeb459812015-12-15 19:24:43 -08003280void PeerConnection::OnAudioTrackRemoved(AudioTrackInterface* track,
3281 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003282 if (IsClosed()) {
3283 return;
3284 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003285 RemoveAudioTrack(track, stream);
3286 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003287}
3288
3289void PeerConnection::OnVideoTrackAdded(VideoTrackInterface* track,
3290 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003291 if (IsClosed()) {
3292 return;
3293 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003294 AddVideoTrack(track, stream);
3295 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003296}
3297
3298void PeerConnection::OnVideoTrackRemoved(VideoTrackInterface* track,
3299 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003300 if (IsClosed()) {
3301 return;
3302 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003303 RemoveVideoTrack(track, stream);
3304 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003305}
3306
Henrik Boström31638672017-11-23 17:48:32 +01003307void PeerConnection::PostSetSessionDescriptionSuccess(
3308 SetSessionDescriptionObserver* observer) {
3309 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
3310 signaling_thread()->Post(RTC_FROM_HERE, this,
3311 MSG_SET_SESSIONDESCRIPTION_SUCCESS, msg);
3312}
3313
deadbeefab9b2d12015-10-14 11:33:11 -07003314void PeerConnection::PostSetSessionDescriptionFailure(
3315 SetSessionDescriptionObserver* observer,
3316 const std::string& error) {
3317 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
3318 msg->error = error;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07003319 signaling_thread()->Post(RTC_FROM_HERE, this,
3320 MSG_SET_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07003321}
3322
3323void PeerConnection::PostCreateSessionDescriptionFailure(
3324 CreateSessionDescriptionObserver* observer,
3325 const std::string& error) {
3326 CreateSessionDescriptionMsg* msg = new CreateSessionDescriptionMsg(observer);
3327 msg->error = error;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07003328 signaling_thread()->Post(RTC_FROM_HERE, this,
3329 MSG_CREATE_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07003330}
3331
zhihuang1c378ed2017-08-17 14:10:50 -07003332void PeerConnection::GetOptionsForOffer(
Steve Antondcc3c022017-12-22 16:02:54 -08003333 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
deadbeefab9b2d12015-10-14 11:33:11 -07003334 cricket::MediaSessionOptions* session_options) {
Steve Antondcc3c022017-12-22 16:02:54 -08003335 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
zhihuang1c378ed2017-08-17 14:10:50 -07003336
Steve Antondcc3c022017-12-22 16:02:54 -08003337 if (IsUnifiedPlan()) {
3338 GetOptionsForUnifiedPlanOffer(offer_answer_options, session_options);
3339 } else {
3340 GetOptionsForPlanBOffer(offer_answer_options, session_options);
3341 }
3342
Steve Antonfa2260d2017-12-28 16:38:23 -08003343 // Intentionally unset the data channel type for RTP data channel with the
3344 // second condition. Otherwise the RTP data channels would be successfully
3345 // negotiated by default and the unit tests in WebRtcDataBrowserTest will fail
3346 // when building with chromium. We want to leave RTP data channels broken, so
3347 // people won't try to use them.
3348 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
3349 session_options->data_channel_type = data_channel_type();
3350 }
3351
Steve Antondcc3c022017-12-22 16:02:54 -08003352 // Apply ICE restart flag and renomination flag.
3353 for (auto& options : session_options->media_description_options) {
3354 options.transport_options.ice_restart = offer_answer_options.ice_restart;
3355 options.transport_options.enable_ice_renomination =
3356 configuration_.enable_ice_renomination;
3357 }
3358
3359 session_options->rtcp_cname = rtcp_cname_;
3360 session_options->crypto_options = factory_->options().crypto_options;
Steve Antone831b8c2018-02-01 12:22:16 -08003361 session_options->is_unified_plan = IsUnifiedPlan();
Steve Antondcc3c022017-12-22 16:02:54 -08003362}
3363
3364void PeerConnection::GetOptionsForPlanBOffer(
3365 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
3366 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07003367 // Figure out transceiver directional preferences.
3368 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
3369 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
3370
3371 // By default, generate sendrecv/recvonly m= sections.
3372 bool recv_audio = true;
3373 bool recv_video = true;
3374
3375 // By default, only offer a new m= section if we have media to send with it.
3376 bool offer_new_audio_description = send_audio;
3377 bool offer_new_video_description = send_video;
3378 bool offer_new_data_description = HasDataChannels();
3379
3380 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-22 16:02:54 -08003381 if (offer_answer_options.offer_to_receive_audio !=
3382 RTCOfferAnswerOptions::kUndefined) {
3383 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003384 offer_new_audio_description =
Steve Antondcc3c022017-12-22 16:02:54 -08003385 offer_new_audio_description ||
3386 (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003387 }
Steve Antondcc3c022017-12-22 16:02:54 -08003388 if (offer_answer_options.offer_to_receive_video !=
3389 RTCOfferAnswerOptions::kUndefined) {
3390 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003391 offer_new_video_description =
Steve Antondcc3c022017-12-22 16:02:54 -08003392 offer_new_video_description ||
3393 (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003394 }
3395
3396 rtc::Optional<size_t> audio_index;
3397 rtc::Optional<size_t> video_index;
3398 rtc::Optional<size_t> data_index;
3399 // If a current description exists, generate m= sections in the same order,
3400 // using the first audio/video/data section that appears and rejecting
3401 // extraneous ones.
Steve Anton75737c02017-11-06 10:37:17 -08003402 if (local_description()) {
zhihuang1c378ed2017-08-17 14:10:50 -07003403 GenerateMediaDescriptionOptions(
Steve Anton75737c02017-11-06 10:37:17 -08003404 local_description(),
Steve Anton1d03a752017-11-27 14:30:09 -08003405 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
3406 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
3407 &audio_index, &video_index, &data_index, session_options);
deadbeefab9b2d12015-10-14 11:33:11 -07003408 }
3409
zhihuang1c378ed2017-08-17 14:10:50 -07003410 // Add audio/video/data m= sections to the end if needed.
3411 if (!audio_index && offer_new_audio_description) {
3412 session_options->media_description_options.push_back(
3413 cricket::MediaDescriptionOptions(
3414 cricket::MEDIA_TYPE_AUDIO, cricket::CN_AUDIO,
Steve Anton1d03a752017-11-27 14:30:09 -08003415 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
3416 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003417 audio_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07003418 }
zhihuang1c378ed2017-08-17 14:10:50 -07003419 if (!video_index && offer_new_video_description) {
3420 session_options->media_description_options.push_back(
3421 cricket::MediaDescriptionOptions(
3422 cricket::MEDIA_TYPE_VIDEO, cricket::CN_VIDEO,
Steve Anton1d03a752017-11-27 14:30:09 -08003423 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
3424 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003425 video_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07003426 }
zhihuang1c378ed2017-08-17 14:10:50 -07003427 if (!data_index && offer_new_data_description) {
3428 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08003429 GetMediaDescriptionOptionsForActiveData(cricket::CN_DATA));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003430 data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07003431 }
3432
3433 cricket::MediaDescriptionOptions* audio_media_description_options =
3434 !audio_index ? nullptr
3435 : &session_options->media_description_options[*audio_index];
3436 cricket::MediaDescriptionOptions* video_media_description_options =
3437 !video_index ? nullptr
3438 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 14:10:50 -07003439
Steve Anton4171afb2017-11-20 10:20:22 -08003440 AddRtpSenderOptions(GetSendersInternal(), audio_media_description_options,
zhihuang1c378ed2017-08-17 14:10:50 -07003441 video_media_description_options);
Steve Antondcc3c022017-12-22 16:02:54 -08003442}
3443
3444// Find a new MID that is not already in |used_mids|, then add it to |used_mids|
3445// and return a reference to it.
3446// Generated MIDs should be no more than 3 bytes long to take up less space in
3447// the RTP packet.
3448static const std::string& AllocateMid(std::set<std::string>* used_mids) {
3449 RTC_DCHECK(used_mids);
3450 // We're boring: just generate MIDs 0, 1, 2, ...
3451 size_t i = 0;
3452 std::set<std::string>::iterator it;
3453 bool inserted;
3454 do {
3455 std::string mid = rtc::ToString(i++);
3456 auto insert_result = used_mids->insert(mid);
3457 it = insert_result.first;
3458 inserted = insert_result.second;
3459 } while (!inserted);
3460 return *it;
3461}
3462
3463static cricket::MediaDescriptionOptions
3464GetMediaDescriptionOptionsForTransceiver(
3465 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3466 transceiver,
3467 const std::string& mid) {
3468 cricket::MediaDescriptionOptions media_description_options(
Steve Anton69470252018-02-09 11:43:08 -08003469 transceiver->media_type(), mid, transceiver->direction(),
Steve Antondcc3c022017-12-22 16:02:54 -08003470 transceiver->stopped());
Steve Anton5f94aa22018-02-01 10:58:30 -08003471 // This behavior is specified in JSEP. The gist is that:
3472 // 1. The MSID is included if the RtpTransceiver's direction is sendonly or
3473 // sendrecv.
3474 // 2. If the MSID is included, then it must be included in any subsequent
3475 // offer/answer exactly the same until the RtpTransceiver is stopped.
3476 if (!transceiver->stopped() &&
3477 (RtpTransceiverDirectionHasSend(transceiver->direction()) ||
3478 transceiver->internal()->has_ever_been_used_to_send())) {
3479 cricket::SenderOptions sender_options;
3480 sender_options.track_id = transceiver->sender()->id();
3481 sender_options.stream_ids = transceiver->sender()->stream_ids();
3482 // TODO(bugs.webrtc.org/7600): Set num_sim_layers to the number of encodings
3483 // set in the RTP parameters when the transceiver was added.
3484 sender_options.num_sim_layers = 1;
3485 media_description_options.sender_options.push_back(sender_options);
3486 }
Steve Antondcc3c022017-12-22 16:02:54 -08003487 return media_description_options;
3488}
3489
3490void PeerConnection::GetOptionsForUnifiedPlanOffer(
3491 const RTCOfferAnswerOptions& offer_answer_options,
3492 cricket::MediaSessionOptions* session_options) {
3493 // Rules for generating an offer are dictated by JSEP sections 5.2.1 (Initial
3494 // Offers) and 5.2.2 (Subsequent Offers).
3495 RTC_DCHECK_EQ(session_options->media_description_options.size(), 0);
3496 const ContentInfos& local_contents =
3497 (local_description() ? local_description()->description()->contents()
3498 : ContentInfos());
3499 const ContentInfos& remote_contents =
3500 (remote_description() ? remote_description()->description()->contents()
3501 : ContentInfos());
3502 // The mline indices that can be recycled. New transceivers should reuse these
3503 // slots first.
3504 std::queue<size_t> recycleable_mline_indices;
3505 // Track the MIDs used in previous offer/answer exchanges and the current
3506 // offer so that new, unique MIDs are generated.
3507 std::set<std::string> used_mids = seen_mids_;
3508 // First, go through each media section that exists in either the local or
3509 // remote description and generate a media section in this offer for the
3510 // associated transceiver. If a media section can be recycled, generate a
3511 // default, rejected media section here that can be later overwritten.
3512 for (size_t i = 0;
3513 i < std::max(local_contents.size(), remote_contents.size()); ++i) {
3514 // Either |local_content| or |remote_content| is non-null.
3515 const ContentInfo* local_content =
3516 (i < local_contents.size() ? &local_contents[i] : nullptr);
3517 const ContentInfo* remote_content =
3518 (i < remote_contents.size() ? &remote_contents[i] : nullptr);
3519 bool had_been_rejected = (local_content && local_content->rejected) ||
3520 (remote_content && remote_content->rejected);
3521 const std::string& mid =
3522 (local_content ? local_content->name : remote_content->name);
3523 cricket::MediaType media_type =
3524 (local_content ? local_content->media_description()->type()
3525 : remote_content->media_description()->type());
3526 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
3527 media_type == cricket::MEDIA_TYPE_VIDEO) {
3528 auto transceiver = GetAssociatedTransceiver(mid);
3529 RTC_CHECK(transceiver);
3530 // A media section is considered eligible for recycling if it is marked as
3531 // rejected in either the local or remote description.
Seth Hampsonae8a90a2018-02-13 15:33:48 -08003532 if (had_been_rejected && transceiver->stopped()) {
Steve Antondcc3c022017-12-22 16:02:54 -08003533 session_options->media_description_options.push_back(
Steve Anton69470252018-02-09 11:43:08 -08003534 cricket::MediaDescriptionOptions(transceiver->media_type(), mid,
3535 RtpTransceiverDirection::kInactive,
3536 /*stopped=*/true));
Steve Antondcc3c022017-12-22 16:02:54 -08003537 recycleable_mline_indices.push(i);
3538 } else {
3539 session_options->media_description_options.push_back(
3540 GetMediaDescriptionOptionsForTransceiver(transceiver, mid));
3541 // CreateOffer shouldn't really cause any state changes in
3542 // PeerConnection, but we need a way to match new transceivers to new
3543 // media sections in SetLocalDescription and JSEP specifies this is done
3544 // by recording the index of the media section generated for the
3545 // transceiver in the offer.
3546 transceiver->internal()->set_mline_index(i);
3547 }
3548 } else {
3549 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antonfa2260d2017-12-28 16:38:23 -08003550 RTC_CHECK(GetDataMid());
3551 if (had_been_rejected || mid != *GetDataMid()) {
3552 session_options->media_description_options.push_back(
3553 GetMediaDescriptionOptionsForRejectedData(mid));
3554 } else {
3555 session_options->media_description_options.push_back(
3556 GetMediaDescriptionOptionsForActiveData(mid));
3557 }
Steve Antondcc3c022017-12-22 16:02:54 -08003558 }
3559 }
3560 // Next, look for transceivers that are newly added (that is, are not stopped
3561 // and not associated). Reuse media sections marked as recyclable first,
3562 // otherwise append to the end of the offer. New media sections should be
3563 // added in the order they were added to the PeerConnection.
3564 for (auto transceiver : transceivers_) {
3565 if (transceiver->mid() || transceiver->stopped()) {
3566 continue;
3567 }
3568 size_t mline_index;
3569 if (!recycleable_mline_indices.empty()) {
3570 mline_index = recycleable_mline_indices.front();
3571 recycleable_mline_indices.pop();
3572 session_options->media_description_options[mline_index] =
3573 GetMediaDescriptionOptionsForTransceiver(transceiver,
3574 AllocateMid(&used_mids));
3575 } else {
3576 mline_index = session_options->media_description_options.size();
3577 session_options->media_description_options.push_back(
3578 GetMediaDescriptionOptionsForTransceiver(transceiver,
3579 AllocateMid(&used_mids)));
3580 }
3581 // See comment above for why CreateOffer changes the transceiver's state.
3582 transceiver->internal()->set_mline_index(mline_index);
3583 }
Steve Antonfa2260d2017-12-28 16:38:23 -08003584 // Lastly, add a m-section if we have local data channels and an m section
3585 // does not already exist.
3586 if (!GetDataMid() && HasDataChannels()) {
3587 session_options->media_description_options.push_back(
3588 GetMediaDescriptionOptionsForActiveData(AllocateMid(&used_mids)));
3589 }
Steve Antondcc3c022017-12-22 16:02:54 -08003590}
3591
3592void PeerConnection::GetOptionsForAnswer(
3593 const RTCOfferAnswerOptions& offer_answer_options,
3594 cricket::MediaSessionOptions* session_options) {
3595 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
3596
3597 if (IsUnifiedPlan()) {
3598 GetOptionsForUnifiedPlanAnswer(offer_answer_options, session_options);
3599 } else {
3600 GetOptionsForPlanBAnswer(offer_answer_options, session_options);
3601 }
3602
Steve Antonfa2260d2017-12-28 16:38:23 -08003603 // Intentionally unset the data channel type for RTP data channel. Otherwise
3604 // the RTP data channels would be successfully negotiated by default and the
3605 // unit tests in WebRtcDataBrowserTest will fail when building with chromium.
3606 // We want to leave RTP data channels broken, so people won't try to use them.
3607 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
3608 session_options->data_channel_type = data_channel_type();
3609 }
3610
Steve Antondcc3c022017-12-22 16:02:54 -08003611 // Apply ICE renomination flag.
3612 for (auto& options : session_options->media_description_options) {
3613 options.transport_options.enable_ice_renomination =
3614 configuration_.enable_ice_renomination;
3615 }
zhihuang8f65cdf2016-05-06 18:40:30 -07003616
3617 session_options->rtcp_cname = rtcp_cname_;
jbauchcb560652016-08-04 05:20:32 -07003618 session_options->crypto_options = factory_->options().crypto_options;
Steve Antone831b8c2018-02-01 12:22:16 -08003619 session_options->is_unified_plan = IsUnifiedPlan();
deadbeefab9b2d12015-10-14 11:33:11 -07003620}
3621
Steve Antondcc3c022017-12-22 16:02:54 -08003622void PeerConnection::GetOptionsForPlanBAnswer(
3623 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07003624 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07003625 // Figure out transceiver directional preferences.
3626 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
3627 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
3628
3629 // By default, generate sendrecv/recvonly m= sections. The direction is also
3630 // restricted by the direction in the offer.
3631 bool recv_audio = true;
3632 bool recv_video = true;
3633
3634 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-22 16:02:54 -08003635 if (offer_answer_options.offer_to_receive_audio !=
3636 RTCOfferAnswerOptions::kUndefined) {
3637 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
deadbeef0ed85b22016-02-23 17:24:52 -08003638 }
Steve Antondcc3c022017-12-22 16:02:54 -08003639 if (offer_answer_options.offer_to_receive_video !=
3640 RTCOfferAnswerOptions::kUndefined) {
3641 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003642 }
3643
3644 rtc::Optional<size_t> audio_index;
3645 rtc::Optional<size_t> video_index;
3646 rtc::Optional<size_t> data_index;
Steve Antondffead82018-02-06 10:31:29 -08003647
3648 // Generate m= sections that match those in the offer.
3649 // Note that mediasession.cc will handle intersection our preferred
3650 // direction with the offered direction.
3651 GenerateMediaDescriptionOptions(
3652 remote_description(),
3653 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
3654 RtpTransceiverDirectionFromSendRecv(send_video, recv_video), &audio_index,
3655 &video_index, &data_index, session_options);
zhihuang1c378ed2017-08-17 14:10:50 -07003656
3657 cricket::MediaDescriptionOptions* audio_media_description_options =
3658 !audio_index ? nullptr
3659 : &session_options->media_description_options[*audio_index];
3660 cricket::MediaDescriptionOptions* video_media_description_options =
3661 !video_index ? nullptr
3662 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 14:10:50 -07003663
Steve Anton4171afb2017-11-20 10:20:22 -08003664 AddRtpSenderOptions(GetSendersInternal(), audio_media_description_options,
zhihuang1c378ed2017-08-17 14:10:50 -07003665 video_media_description_options);
Steve Antondcc3c022017-12-22 16:02:54 -08003666}
zhihuangaf388472016-11-02 16:49:48 -07003667
Steve Antondcc3c022017-12-22 16:02:54 -08003668void PeerConnection::GetOptionsForUnifiedPlanAnswer(
3669 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
3670 cricket::MediaSessionOptions* session_options) {
3671 // Rules for generating an answer are dictated by JSEP sections 5.3.1 (Initial
3672 // Answers) and 5.3.2 (Subsequent Answers).
3673 RTC_DCHECK(remote_description());
3674 RTC_DCHECK(remote_description()->GetType() == SdpType::kOffer);
3675 for (const ContentInfo& content :
3676 remote_description()->description()->contents()) {
3677 cricket::MediaType media_type = content.media_description()->type();
3678 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
3679 media_type == cricket::MEDIA_TYPE_VIDEO) {
3680 auto transceiver = GetAssociatedTransceiver(content.name);
3681 RTC_CHECK(transceiver);
3682 session_options->media_description_options.push_back(
3683 GetMediaDescriptionOptionsForTransceiver(transceiver, content.name));
3684 } else {
3685 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antondbf9d032018-01-19 15:23:40 -08003686 // Reject all data sections if data channels are disabled.
3687 // Reject a data section if it has already been rejected.
3688 // Reject all data sections except for the first one.
3689 if (data_channel_type_ == cricket::DCT_NONE || content.rejected ||
3690 content.name != *GetDataMid()) {
Steve Antonfa2260d2017-12-28 16:38:23 -08003691 session_options->media_description_options.push_back(
3692 GetMediaDescriptionOptionsForRejectedData(content.name));
3693 } else {
3694 session_options->media_description_options.push_back(
3695 GetMediaDescriptionOptionsForActiveData(content.name));
3696 }
Steve Antondcc3c022017-12-22 16:02:54 -08003697 }
3698 }
htaa2a49d92016-03-04 02:51:39 -08003699}
3700
zhihuang1c378ed2017-08-17 14:10:50 -07003701void PeerConnection::GenerateMediaDescriptionOptions(
3702 const SessionDescriptionInterface* session_desc,
Steve Anton1d03a752017-11-27 14:30:09 -08003703 RtpTransceiverDirection audio_direction,
3704 RtpTransceiverDirection video_direction,
zhihuang1c378ed2017-08-17 14:10:50 -07003705 rtc::Optional<size_t>* audio_index,
3706 rtc::Optional<size_t>* video_index,
3707 rtc::Optional<size_t>* data_index,
htaa2a49d92016-03-04 02:51:39 -08003708 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07003709 for (const cricket::ContentInfo& content :
3710 session_desc->description()->contents()) {
3711 if (IsAudioContent(&content)) {
3712 // If we already have an audio m= section, reject this extra one.
3713 if (*audio_index) {
3714 session_options->media_description_options.push_back(
3715 cricket::MediaDescriptionOptions(
3716 cricket::MEDIA_TYPE_AUDIO, content.name,
Steve Anton1d03a752017-11-27 14:30:09 -08003717 RtpTransceiverDirection::kInactive, true));
zhihuang1c378ed2017-08-17 14:10:50 -07003718 } else {
3719 session_options->media_description_options.push_back(
3720 cricket::MediaDescriptionOptions(
3721 cricket::MEDIA_TYPE_AUDIO, content.name, audio_direction,
Steve Anton1d03a752017-11-27 14:30:09 -08003722 audio_direction == RtpTransceiverDirection::kInactive));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003723 *audio_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07003724 }
3725 } else if (IsVideoContent(&content)) {
3726 // If we already have an video m= section, reject this extra one.
3727 if (*video_index) {
3728 session_options->media_description_options.push_back(
3729 cricket::MediaDescriptionOptions(
3730 cricket::MEDIA_TYPE_VIDEO, content.name,
Steve Anton1d03a752017-11-27 14:30:09 -08003731 RtpTransceiverDirection::kInactive, true));
zhihuang1c378ed2017-08-17 14:10:50 -07003732 } else {
3733 session_options->media_description_options.push_back(
3734 cricket::MediaDescriptionOptions(
3735 cricket::MEDIA_TYPE_VIDEO, content.name, video_direction,
Steve Anton1d03a752017-11-27 14:30:09 -08003736 video_direction == RtpTransceiverDirection::kInactive));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003737 *video_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07003738 }
3739 } else {
3740 RTC_DCHECK(IsDataContent(&content));
3741 // If we already have an data m= section, reject this extra one.
3742 if (*data_index) {
3743 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08003744 GetMediaDescriptionOptionsForRejectedData(content.name));
zhihuang1c378ed2017-08-17 14:10:50 -07003745 } else {
3746 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08003747 GetMediaDescriptionOptionsForActiveData(content.name));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003748 *data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07003749 }
3750 }
htaa2a49d92016-03-04 02:51:39 -08003751 }
deadbeefab9b2d12015-10-14 11:33:11 -07003752}
3753
Steve Antonfa2260d2017-12-28 16:38:23 -08003754cricket::MediaDescriptionOptions
3755PeerConnection::GetMediaDescriptionOptionsForActiveData(
3756 const std::string& mid) const {
3757 // Direction for data sections is meaningless, but legacy endpoints might
3758 // expect sendrecv.
3759 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
3760 RtpTransceiverDirection::kSendRecv,
3761 /*stopped=*/false);
3762 AddRtpDataChannelOptions(rtp_data_channels_, &options);
3763 return options;
3764}
3765
3766cricket::MediaDescriptionOptions
3767PeerConnection::GetMediaDescriptionOptionsForRejectedData(
3768 const std::string& mid) const {
3769 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
3770 RtpTransceiverDirection::kInactive,
3771 /*stopped=*/true);
3772 AddRtpDataChannelOptions(rtp_data_channels_, &options);
3773 return options;
3774}
3775
3776rtc::Optional<std::string> PeerConnection::GetDataMid() const {
3777 switch (data_channel_type_) {
3778 case cricket::DCT_RTP:
3779 if (!rtp_data_channel_) {
3780 return rtc::nullopt;
3781 }
3782 return rtp_data_channel_->content_name();
3783 case cricket::DCT_SCTP:
3784 return sctp_content_name_;
3785 default:
3786 return rtc::nullopt;
3787 }
3788}
3789
Steve Anton4171afb2017-11-20 10:20:22 -08003790void PeerConnection::RemoveSenders(cricket::MediaType media_type) {
3791 UpdateLocalSenders(std::vector<cricket::StreamParams>(), media_type);
3792 UpdateRemoteSendersList(std::vector<cricket::StreamParams>(), false,
deadbeefbda7e0b2015-12-08 17:13:40 -08003793 media_type, nullptr);
deadbeeffaac4972015-11-12 15:33:07 -08003794}
3795
Steve Anton4171afb2017-11-20 10:20:22 -08003796void PeerConnection::UpdateRemoteSendersList(
deadbeefab9b2d12015-10-14 11:33:11 -07003797 const cricket::StreamParamsVec& streams,
Steve Anton4171afb2017-11-20 10:20:22 -08003798 bool default_sender_needed,
deadbeefab9b2d12015-10-14 11:33:11 -07003799 cricket::MediaType media_type,
3800 StreamCollection* new_streams) {
Steve Anton4171afb2017-11-20 10:20:22 -08003801 std::vector<RtpSenderInfo>* current_senders =
3802 GetRemoteSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07003803
Steve Anton4171afb2017-11-20 10:20:22 -08003804 // Find removed senders. I.e., senders where the sender id or ssrc don't match
deadbeeffac06552015-11-25 11:26:01 -08003805 // the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08003806 for (auto sender_it = current_senders->begin();
3807 sender_it != current_senders->end();
3808 /* incremented manually */) {
3809 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07003810 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08003811 cricket::GetStreamBySsrc(streams, info.first_ssrc);
3812 bool sender_exists = params && params->id == info.sender_id;
deadbeefbda7e0b2015-12-08 17:13:40 -08003813 // If this is a default track, and we still need it, don't remove it.
Steve Anton4171afb2017-11-20 10:20:22 -08003814 if ((info.stream_label == kDefaultStreamLabel && default_sender_needed) ||
3815 sender_exists) {
3816 ++sender_it;
deadbeefbda7e0b2015-12-08 17:13:40 -08003817 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08003818 OnRemoteSenderRemoved(info, media_type);
3819 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07003820 }
3821 }
3822
Steve Anton4171afb2017-11-20 10:20:22 -08003823 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07003824 for (const cricket::StreamParams& params : streams) {
3825 // The sync_label is the MediaStream label and the |stream.id| is the
Steve Anton4171afb2017-11-20 10:20:22 -08003826 // sender id.
deadbeefab9b2d12015-10-14 11:33:11 -07003827 const std::string& stream_label = params.sync_label;
Steve Anton4171afb2017-11-20 10:20:22 -08003828 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07003829 uint32_t ssrc = params.first_ssrc();
3830
3831 rtc::scoped_refptr<MediaStreamInterface> stream =
3832 remote_streams_->find(stream_label);
3833 if (!stream) {
3834 // This is a new MediaStream. Create a new remote MediaStream.
perkjd61bf802016-03-24 03:16:19 -07003835 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
3836 MediaStream::Create(stream_label));
deadbeefab9b2d12015-10-14 11:33:11 -07003837 remote_streams_->AddStream(stream);
3838 new_streams->AddStream(stream);
3839 }
3840
Steve Anton4171afb2017-11-20 10:20:22 -08003841 const RtpSenderInfo* sender_info =
3842 FindSenderInfo(*current_senders, stream_label, sender_id);
3843 if (!sender_info) {
3844 current_senders->push_back(RtpSenderInfo(stream_label, sender_id, ssrc));
3845 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07003846 }
3847 }
deadbeefbda7e0b2015-12-08 17:13:40 -08003848
Steve Anton4171afb2017-11-20 10:20:22 -08003849 // Add default sender if necessary.
3850 if (default_sender_needed) {
deadbeefbda7e0b2015-12-08 17:13:40 -08003851 rtc::scoped_refptr<MediaStreamInterface> default_stream =
3852 remote_streams_->find(kDefaultStreamLabel);
3853 if (!default_stream) {
3854 // Create the new default MediaStream.
perkjd61bf802016-03-24 03:16:19 -07003855 default_stream = MediaStreamProxy::Create(
3856 rtc::Thread::Current(), MediaStream::Create(kDefaultStreamLabel));
deadbeefbda7e0b2015-12-08 17:13:40 -08003857 remote_streams_->AddStream(default_stream);
3858 new_streams->AddStream(default_stream);
3859 }
Steve Anton4171afb2017-11-20 10:20:22 -08003860 std::string default_sender_id = (media_type == cricket::MEDIA_TYPE_AUDIO)
3861 ? kDefaultAudioSenderId
3862 : kDefaultVideoSenderId;
3863 const RtpSenderInfo* default_sender_info = FindSenderInfo(
3864 *current_senders, kDefaultStreamLabel, default_sender_id);
3865 if (!default_sender_info) {
3866 current_senders->push_back(
3867 RtpSenderInfo(kDefaultStreamLabel, default_sender_id, 0));
3868 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefbda7e0b2015-12-08 17:13:40 -08003869 }
3870 }
deadbeefab9b2d12015-10-14 11:33:11 -07003871}
3872
Steve Anton4171afb2017-11-20 10:20:22 -08003873void PeerConnection::OnRemoteSenderAdded(const RtpSenderInfo& sender_info,
3874 cricket::MediaType media_type) {
3875 MediaStreamInterface* stream =
3876 remote_streams_->find(sender_info.stream_label);
deadbeefab9b2d12015-10-14 11:33:11 -07003877
3878 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 10:20:22 -08003879 CreateAudioReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07003880 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 10:20:22 -08003881 CreateVideoReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07003882 } else {
nisseeb4ca4e2017-01-12 02:24:27 -08003883 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07003884 }
3885}
3886
Steve Anton4171afb2017-11-20 10:20:22 -08003887void PeerConnection::OnRemoteSenderRemoved(const RtpSenderInfo& sender_info,
3888 cricket::MediaType media_type) {
3889 MediaStreamInterface* stream =
3890 remote_streams_->find(sender_info.stream_label);
deadbeefab9b2d12015-10-14 11:33:11 -07003891
Henrik Boström933d8b02017-10-10 10:05:16 -07003892 rtc::scoped_refptr<RtpReceiverInterface> receiver;
deadbeefab9b2d12015-10-14 11:33:11 -07003893 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
perkjd61bf802016-03-24 03:16:19 -07003894 // When the MediaEngine audio channel is destroyed, the RemoteAudioSource
3895 // will be notified which will end the AudioRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08003896 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07003897 rtc::scoped_refptr<AudioTrackInterface> audio_track =
Steve Anton4171afb2017-11-20 10:20:22 -08003898 stream->FindAudioTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07003899 if (audio_track) {
deadbeefab9b2d12015-10-14 11:33:11 -07003900 stream->RemoveTrack(audio_track);
deadbeefab9b2d12015-10-14 11:33:11 -07003901 }
3902 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
perkjd61bf802016-03-24 03:16:19 -07003903 // Stopping or destroying a VideoRtpReceiver will end the
3904 // VideoRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08003905 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07003906 rtc::scoped_refptr<VideoTrackInterface> video_track =
Steve Anton4171afb2017-11-20 10:20:22 -08003907 stream->FindVideoTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07003908 if (video_track) {
perkjd61bf802016-03-24 03:16:19 -07003909 // There's no guarantee the track is still available, e.g. the track may
3910 // have been removed from the stream by an application.
deadbeefab9b2d12015-10-14 11:33:11 -07003911 stream->RemoveTrack(video_track);
deadbeefab9b2d12015-10-14 11:33:11 -07003912 }
3913 } else {
nisseede5da42017-01-12 05:15:36 -08003914 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07003915 }
Henrik Boström933d8b02017-10-10 10:05:16 -07003916 if (receiver) {
3917 observer_->OnRemoveTrack(receiver);
3918 }
deadbeefab9b2d12015-10-14 11:33:11 -07003919}
3920
3921void PeerConnection::UpdateEndedRemoteMediaStreams() {
3922 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams_to_remove;
3923 for (size_t i = 0; i < remote_streams_->count(); ++i) {
3924 MediaStreamInterface* stream = remote_streams_->at(i);
3925 if (stream->GetAudioTracks().empty() && stream->GetVideoTracks().empty()) {
3926 streams_to_remove.push_back(stream);
3927 }
3928 }
3929
Taylor Brandstetter98cde262016-05-31 13:02:21 -07003930 for (auto& stream : streams_to_remove) {
deadbeefab9b2d12015-10-14 11:33:11 -07003931 remote_streams_->RemoveStream(stream);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07003932 observer_->OnRemoveStream(std::move(stream));
deadbeefab9b2d12015-10-14 11:33:11 -07003933 }
3934}
3935
Steve Anton4171afb2017-11-20 10:20:22 -08003936void PeerConnection::UpdateLocalSenders(
deadbeefab9b2d12015-10-14 11:33:11 -07003937 const std::vector<cricket::StreamParams>& streams,
3938 cricket::MediaType media_type) {
Steve Anton4171afb2017-11-20 10:20:22 -08003939 std::vector<RtpSenderInfo>* current_senders = GetLocalSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07003940
3941 // Find removed tracks. I.e., tracks where the track id, stream label or ssrc
3942 // don't match the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08003943 for (auto sender_it = current_senders->begin();
3944 sender_it != current_senders->end();
3945 /* incremented manually */) {
3946 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07003947 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08003948 cricket::GetStreamBySsrc(streams, info.first_ssrc);
3949 if (!params || params->id != info.sender_id ||
deadbeefab9b2d12015-10-14 11:33:11 -07003950 params->sync_label != info.stream_label) {
Steve Anton4171afb2017-11-20 10:20:22 -08003951 OnLocalSenderRemoved(info, media_type);
3952 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07003953 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08003954 ++sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07003955 }
3956 }
3957
Steve Anton4171afb2017-11-20 10:20:22 -08003958 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07003959 for (const cricket::StreamParams& params : streams) {
3960 // The sync_label is the MediaStream label and the |stream.id| is the
Steve Anton4171afb2017-11-20 10:20:22 -08003961 // sender id.
deadbeefab9b2d12015-10-14 11:33:11 -07003962 const std::string& stream_label = params.sync_label;
Steve Anton4171afb2017-11-20 10:20:22 -08003963 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07003964 uint32_t ssrc = params.first_ssrc();
Steve Anton4171afb2017-11-20 10:20:22 -08003965 const RtpSenderInfo* sender_info =
3966 FindSenderInfo(*current_senders, stream_label, sender_id);
3967 if (!sender_info) {
3968 current_senders->push_back(RtpSenderInfo(stream_label, sender_id, ssrc));
3969 OnLocalSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07003970 }
3971 }
3972}
3973
Steve Anton4171afb2017-11-20 10:20:22 -08003974void PeerConnection::OnLocalSenderAdded(const RtpSenderInfo& sender_info,
3975 cricket::MediaType media_type) {
3976 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08003977 if (!sender) {
Steve Anton4171afb2017-11-20 10:20:22 -08003978 RTC_LOG(LS_WARNING) << "An unknown RtpSender with id "
3979 << sender_info.sender_id
Mirko Bonadei675513b2017-11-09 11:09:25 +01003980 << " has been configured in the local description.";
deadbeefab9b2d12015-10-14 11:33:11 -07003981 return;
3982 }
3983
deadbeeffac06552015-11-25 11:26:01 -08003984 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003985 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
Jonas Olsson45cc8902018-02-13 10:37:07 +01003986 " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08003987 return;
deadbeefab9b2d12015-10-14 11:33:11 -07003988 }
deadbeeffac06552015-11-25 11:26:01 -08003989
Steve Anton4171afb2017-11-20 10:20:22 -08003990 sender->internal()->set_stream_id(sender_info.stream_label);
3991 sender->internal()->SetSsrc(sender_info.first_ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07003992}
3993
Steve Anton4171afb2017-11-20 10:20:22 -08003994void PeerConnection::OnLocalSenderRemoved(const RtpSenderInfo& sender_info,
3995 cricket::MediaType media_type) {
3996 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08003997 if (!sender) {
3998 // This is the normal case. I.e., RemoveStream has been called and the
deadbeefab9b2d12015-10-14 11:33:11 -07003999 // SessionDescriptions has been renegotiated.
4000 return;
4001 }
deadbeeffac06552015-11-25 11:26:01 -08004002
4003 // A sender has been removed from the SessionDescription but it's still
4004 // associated with the PeerConnection. This only occurs if the SDP doesn't
4005 // match with the calls to CreateSender, AddStream and RemoveStream.
4006 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004007 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
Jonas Olsson45cc8902018-02-13 10:37:07 +01004008 " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08004009 return;
deadbeefab9b2d12015-10-14 11:33:11 -07004010 }
deadbeeffac06552015-11-25 11:26:01 -08004011
Steve Anton4171afb2017-11-20 10:20:22 -08004012 sender->internal()->SetSsrc(0);
deadbeefab9b2d12015-10-14 11:33:11 -07004013}
4014
4015void PeerConnection::UpdateLocalRtpDataChannels(
4016 const cricket::StreamParamsVec& streams) {
4017 std::vector<std::string> existing_channels;
4018
4019 // Find new and active data channels.
4020 for (const cricket::StreamParams& params : streams) {
4021 // |it->sync_label| is actually the data channel label. The reason is that
4022 // we use the same naming of data channels as we do for
4023 // MediaStreams and Tracks.
4024 // For MediaStreams, the sync_label is the MediaStream label and the
4025 // track label is the same as |streamid|.
4026 const std::string& channel_label = params.sync_label;
4027 auto data_channel_it = rtp_data_channels_.find(channel_label);
nisse7ce109a2017-01-31 00:57:56 -08004028 if (data_channel_it == rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004029 RTC_LOG(LS_ERROR) << "channel label not found";
deadbeefab9b2d12015-10-14 11:33:11 -07004030 continue;
4031 }
4032 // Set the SSRC the data channel should use for sending.
4033 data_channel_it->second->SetSendSsrc(params.first_ssrc());
4034 existing_channels.push_back(data_channel_it->first);
4035 }
4036
4037 UpdateClosingRtpDataChannels(existing_channels, true);
4038}
4039
4040void PeerConnection::UpdateRemoteRtpDataChannels(
4041 const cricket::StreamParamsVec& streams) {
4042 std::vector<std::string> existing_channels;
4043
4044 // Find new and active data channels.
4045 for (const cricket::StreamParams& params : streams) {
4046 // The data channel label is either the mslabel or the SSRC if the mslabel
4047 // does not exist. Ex a=ssrc:444330170 mslabel:test1.
4048 std::string label = params.sync_label.empty()
4049 ? rtc::ToString(params.first_ssrc())
4050 : params.sync_label;
4051 auto data_channel_it = rtp_data_channels_.find(label);
4052 if (data_channel_it == rtp_data_channels_.end()) {
4053 // This is a new data channel.
4054 CreateRemoteRtpDataChannel(label, params.first_ssrc());
4055 } else {
4056 data_channel_it->second->SetReceiveSsrc(params.first_ssrc());
4057 }
4058 existing_channels.push_back(label);
4059 }
4060
4061 UpdateClosingRtpDataChannels(existing_channels, false);
4062}
4063
4064void PeerConnection::UpdateClosingRtpDataChannels(
4065 const std::vector<std::string>& active_channels,
4066 bool is_local_update) {
4067 auto it = rtp_data_channels_.begin();
4068 while (it != rtp_data_channels_.end()) {
4069 DataChannel* data_channel = it->second;
4070 if (std::find(active_channels.begin(), active_channels.end(),
4071 data_channel->label()) != active_channels.end()) {
4072 ++it;
4073 continue;
4074 }
4075
4076 if (is_local_update) {
4077 data_channel->SetSendSsrc(0);
4078 } else {
4079 data_channel->RemotePeerRequestClose();
4080 }
4081
4082 if (data_channel->state() == DataChannel::kClosed) {
4083 rtp_data_channels_.erase(it);
4084 it = rtp_data_channels_.begin();
4085 } else {
4086 ++it;
4087 }
4088 }
4089}
4090
4091void PeerConnection::CreateRemoteRtpDataChannel(const std::string& label,
4092 uint32_t remote_ssrc) {
4093 rtc::scoped_refptr<DataChannel> channel(
4094 InternalCreateDataChannel(label, nullptr));
4095 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004096 RTC_LOG(LS_WARNING) << "Remote peer requested a DataChannel but"
Jonas Olsson45cc8902018-02-13 10:37:07 +01004097 "CreateDataChannel failed.";
deadbeefab9b2d12015-10-14 11:33:11 -07004098 return;
4099 }
4100 channel->SetReceiveSsrc(remote_ssrc);
deadbeefa601f5c2016-06-06 14:27:39 -07004101 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
4102 DataChannelProxy::Create(signaling_thread(), channel);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07004103 observer_->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07004104}
4105
4106rtc::scoped_refptr<DataChannel> PeerConnection::InternalCreateDataChannel(
4107 const std::string& label,
4108 const InternalDataChannelInit* config) {
4109 if (IsClosed()) {
4110 return nullptr;
4111 }
Steve Anton75737c02017-11-06 10:37:17 -08004112 if (data_channel_type() == cricket::DCT_NONE) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004113 RTC_LOG(LS_ERROR)
deadbeefab9b2d12015-10-14 11:33:11 -07004114 << "InternalCreateDataChannel: Data is not supported in this call.";
4115 return nullptr;
4116 }
4117 InternalDataChannelInit new_config =
4118 config ? (*config) : InternalDataChannelInit();
Steve Anton75737c02017-11-06 10:37:17 -08004119 if (data_channel_type() == cricket::DCT_SCTP) {
deadbeefab9b2d12015-10-14 11:33:11 -07004120 if (new_config.id < 0) {
4121 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08004122 if ((GetSctpSslRole(&role)) &&
deadbeefab9b2d12015-10-14 11:33:11 -07004123 !sid_allocator_.AllocateSid(role, &new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004124 RTC_LOG(LS_ERROR)
4125 << "No id can be allocated for the SCTP data channel.";
deadbeefab9b2d12015-10-14 11:33:11 -07004126 return nullptr;
4127 }
4128 } else if (!sid_allocator_.ReserveSid(new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004129 RTC_LOG(LS_ERROR) << "Failed to create a SCTP data channel "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004130 "because the id is already in use or out of range.";
deadbeefab9b2d12015-10-14 11:33:11 -07004131 return nullptr;
4132 }
4133 }
4134
Steve Anton75737c02017-11-06 10:37:17 -08004135 rtc::scoped_refptr<DataChannel> channel(
4136 DataChannel::Create(this, data_channel_type(), label, new_config));
deadbeefab9b2d12015-10-14 11:33:11 -07004137 if (!channel) {
4138 sid_allocator_.ReleaseSid(new_config.id);
4139 return nullptr;
4140 }
4141
4142 if (channel->data_channel_type() == cricket::DCT_RTP) {
4143 if (rtp_data_channels_.find(channel->label()) != rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004144 RTC_LOG(LS_ERROR) << "DataChannel with label " << channel->label()
4145 << " already exists.";
deadbeefab9b2d12015-10-14 11:33:11 -07004146 return nullptr;
4147 }
4148 rtp_data_channels_[channel->label()] = channel;
4149 } else {
4150 RTC_DCHECK(channel->data_channel_type() == cricket::DCT_SCTP);
4151 sctp_data_channels_.push_back(channel);
4152 channel->SignalClosed.connect(this,
4153 &PeerConnection::OnSctpDataChannelClosed);
4154 }
4155
Steve Anton2d8609c2018-01-23 16:38:46 -08004156 SignalDataChannelCreated_(channel.get());
deadbeefab9b2d12015-10-14 11:33:11 -07004157 return channel;
4158}
4159
4160bool PeerConnection::HasDataChannels() const {
4161 return !rtp_data_channels_.empty() || !sctp_data_channels_.empty();
4162}
4163
4164void PeerConnection::AllocateSctpSids(rtc::SSLRole role) {
4165 for (const auto& channel : sctp_data_channels_) {
4166 if (channel->id() < 0) {
4167 int sid;
4168 if (!sid_allocator_.AllocateSid(role, &sid)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004169 RTC_LOG(LS_ERROR) << "Failed to allocate SCTP sid.";
deadbeefab9b2d12015-10-14 11:33:11 -07004170 continue;
4171 }
4172 channel->SetSctpSid(sid);
4173 }
4174 }
4175}
4176
4177void PeerConnection::OnSctpDataChannelClosed(DataChannel* channel) {
deadbeefbd292462015-12-14 18:15:29 -08004178 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeefab9b2d12015-10-14 11:33:11 -07004179 for (auto it = sctp_data_channels_.begin(); it != sctp_data_channels_.end();
4180 ++it) {
4181 if (it->get() == channel) {
4182 if (channel->id() >= 0) {
4183 sid_allocator_.ReleaseSid(channel->id());
4184 }
deadbeefbd292462015-12-14 18:15:29 -08004185 // Since this method is triggered by a signal from the DataChannel,
4186 // we can't free it directly here; we need to free it asynchronously.
4187 sctp_data_channels_to_free_.push_back(*it);
deadbeefab9b2d12015-10-14 11:33:11 -07004188 sctp_data_channels_.erase(it);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07004189 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_FREE_DATACHANNELS,
4190 nullptr);
deadbeefab9b2d12015-10-14 11:33:11 -07004191 return;
4192 }
4193 }
4194}
4195
deadbeefab9b2d12015-10-14 11:33:11 -07004196void PeerConnection::OnDataChannelDestroyed() {
4197 // Use a temporary copy of the RTP/SCTP DataChannel list because the
4198 // DataChannel may callback to us and try to modify the list.
4199 std::map<std::string, rtc::scoped_refptr<DataChannel>> temp_rtp_dcs;
4200 temp_rtp_dcs.swap(rtp_data_channels_);
4201 for (const auto& kv : temp_rtp_dcs) {
4202 kv.second->OnTransportChannelDestroyed();
4203 }
4204
4205 std::vector<rtc::scoped_refptr<DataChannel>> temp_sctp_dcs;
4206 temp_sctp_dcs.swap(sctp_data_channels_);
4207 for (const auto& channel : temp_sctp_dcs) {
4208 channel->OnTransportChannelDestroyed();
4209 }
4210}
4211
4212void PeerConnection::OnDataChannelOpenMessage(
4213 const std::string& label,
4214 const InternalDataChannelInit& config) {
4215 rtc::scoped_refptr<DataChannel> channel(
4216 InternalCreateDataChannel(label, &config));
4217 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004218 RTC_LOG(LS_ERROR) << "Failed to create DataChannel from the OPEN message.";
deadbeefab9b2d12015-10-14 11:33:11 -07004219 return;
4220 }
4221
deadbeefa601f5c2016-06-06 14:27:39 -07004222 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
4223 DataChannelProxy::Create(signaling_thread(), channel);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07004224 observer_->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07004225}
4226
Steve Anton4171afb2017-11-20 10:20:22 -08004227rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
4228PeerConnection::GetAudioTransceiver() const {
4229 // This method only works with Plan B SDP, where there is a single
4230 // audio/video transceiver.
4231 RTC_DCHECK(!IsUnifiedPlan());
4232 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08004233 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004234 return transceiver;
4235 }
4236 }
4237 RTC_NOTREACHED();
4238 return nullptr;
4239}
4240
4241rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
4242PeerConnection::GetVideoTransceiver() const {
4243 // This method only works with Plan B SDP, where there is a single
4244 // audio/video transceiver.
4245 RTC_DCHECK(!IsUnifiedPlan());
4246 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08004247 if (transceiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004248 return transceiver;
4249 }
4250 }
4251 RTC_NOTREACHED();
4252 return nullptr;
4253}
4254
4255// TODO(bugs.webrtc.org/7600): Remove this when multiple transceivers with
4256// individual transceiver directions are supported.
zhihuang1c378ed2017-08-17 14:10:50 -07004257bool PeerConnection::HasRtpSender(cricket::MediaType type) const {
Steve Anton4171afb2017-11-20 10:20:22 -08004258 switch (type) {
4259 case cricket::MEDIA_TYPE_AUDIO:
4260 return !GetAudioTransceiver()->internal()->senders().empty();
4261 case cricket::MEDIA_TYPE_VIDEO:
4262 return !GetVideoTransceiver()->internal()->senders().empty();
4263 case cricket::MEDIA_TYPE_DATA:
4264 return false;
4265 }
4266 RTC_NOTREACHED();
4267 return false;
zhihuang1c378ed2017-08-17 14:10:50 -07004268}
4269
Steve Anton4171afb2017-11-20 10:20:22 -08004270rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
4271PeerConnection::FindSenderForTrack(MediaStreamTrackInterface* track) const {
4272 for (auto transceiver : transceivers_) {
4273 for (auto sender : transceiver->internal()->senders()) {
4274 if (sender->track() == track) {
4275 return sender;
4276 }
4277 }
4278 }
4279 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08004280}
4281
Steve Anton4171afb2017-11-20 10:20:22 -08004282rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
4283PeerConnection::FindSenderById(const std::string& sender_id) const {
4284 for (auto transceiver : transceivers_) {
4285 for (auto sender : transceiver->internal()->senders()) {
4286 if (sender->id() == sender_id) {
4287 return sender;
4288 }
4289 }
4290 }
4291 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07004292}
4293
Steve Anton4171afb2017-11-20 10:20:22 -08004294rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
4295PeerConnection::FindReceiverById(const std::string& receiver_id) const {
4296 for (auto transceiver : transceivers_) {
4297 for (auto receiver : transceiver->internal()->receivers()) {
4298 if (receiver->id() == receiver_id) {
4299 return receiver;
4300 }
4301 }
4302 }
4303 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07004304}
4305
Steve Anton4171afb2017-11-20 10:20:22 -08004306std::vector<PeerConnection::RtpSenderInfo>*
4307PeerConnection::GetRemoteSenderInfos(cricket::MediaType media_type) {
4308 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
4309 media_type == cricket::MEDIA_TYPE_VIDEO);
4310 return (media_type == cricket::MEDIA_TYPE_AUDIO)
4311 ? &remote_audio_sender_infos_
4312 : &remote_video_sender_infos_;
4313}
4314
4315std::vector<PeerConnection::RtpSenderInfo>* PeerConnection::GetLocalSenderInfos(
deadbeefab9b2d12015-10-14 11:33:11 -07004316 cricket::MediaType media_type) {
4317 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
4318 media_type == cricket::MEDIA_TYPE_VIDEO);
Steve Anton4171afb2017-11-20 10:20:22 -08004319 return (media_type == cricket::MEDIA_TYPE_AUDIO) ? &local_audio_sender_infos_
4320 : &local_video_sender_infos_;
deadbeefab9b2d12015-10-14 11:33:11 -07004321}
4322
Steve Anton4171afb2017-11-20 10:20:22 -08004323const PeerConnection::RtpSenderInfo* PeerConnection::FindSenderInfo(
4324 const std::vector<PeerConnection::RtpSenderInfo>& infos,
deadbeefab9b2d12015-10-14 11:33:11 -07004325 const std::string& stream_label,
Steve Anton4171afb2017-11-20 10:20:22 -08004326 const std::string sender_id) const {
4327 for (const RtpSenderInfo& sender_info : infos) {
4328 if (sender_info.stream_label == stream_label &&
4329 sender_info.sender_id == sender_id) {
4330 return &sender_info;
deadbeefab9b2d12015-10-14 11:33:11 -07004331 }
4332 }
4333 return nullptr;
4334}
4335
4336DataChannel* PeerConnection::FindDataChannelBySid(int sid) const {
4337 for (const auto& channel : sctp_data_channels_) {
4338 if (channel->id() == sid) {
4339 return channel;
4340 }
4341 }
4342 return nullptr;
4343}
4344
deadbeef91dd5672016-05-18 16:55:30 -07004345bool PeerConnection::InitializePortAllocator_n(
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004346 const RTCConfiguration& configuration) {
4347 cricket::ServerAddresses stun_servers;
4348 std::vector<cricket::RelayServerConfig> turn_servers;
deadbeef293e9262017-01-11 12:28:30 -08004349 if (ParseIceServers(configuration.servers, &stun_servers, &turn_servers) !=
4350 RTCErrorType::NONE) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004351 return false;
4352 }
4353
Taylor Brandstetterf8e65772016-06-27 17:20:15 -07004354 port_allocator_->Initialize();
4355
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004356 // To handle both internal and externally created port allocator, we will
4357 // enable BUNDLE here.
4358 int portallocator_flags = port_allocator_->flags();
4359 portallocator_flags |= cricket::PORTALLOCATOR_ENABLE_SHARED_SOCKET |
zhihuangb09b3f92017-03-07 14:40:51 -08004360 cricket::PORTALLOCATOR_ENABLE_IPV6 |
4361 cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI;
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004362 // If the disable-IPv6 flag was specified, we'll not override it
4363 // by experiment.
4364 if (configuration.disable_ipv6) {
4365 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
sprangc1b57a12017-02-28 08:50:47 -08004366 } else if (webrtc::field_trial::FindFullName("WebRTC-IPv6Default")
4367 .find("Disabled") == 0) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004368 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
4369 }
4370
zhihuangb09b3f92017-03-07 14:40:51 -08004371 if (configuration.disable_ipv6_on_wifi) {
4372 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI);
Mirko Bonadei675513b2017-11-09 11:09:25 +01004373 RTC_LOG(LS_INFO) << "IPv6 candidates on Wi-Fi are disabled.";
zhihuangb09b3f92017-03-07 14:40:51 -08004374 }
4375
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004376 if (configuration.tcp_candidate_policy == kTcpCandidatePolicyDisabled) {
4377 portallocator_flags |= cricket::PORTALLOCATOR_DISABLE_TCP;
Mirko Bonadei675513b2017-11-09 11:09:25 +01004378 RTC_LOG(LS_INFO) << "TCP candidates are disabled.";
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004379 }
4380
honghaiz60347052016-05-31 18:29:12 -07004381 if (configuration.candidate_network_policy ==
4382 kCandidateNetworkPolicyLowCost) {
4383 portallocator_flags |= cricket::PORTALLOCATOR_DISABLE_COSTLY_NETWORKS;
Mirko Bonadei675513b2017-11-09 11:09:25 +01004384 RTC_LOG(LS_INFO) << "Do not gather candidates on high-cost networks";
honghaiz60347052016-05-31 18:29:12 -07004385 }
4386
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +01004387 if (configuration.disable_link_local_networks) {
4388 portallocator_flags |= cricket::PORTALLOCATOR_DISABLE_LINK_LOCAL_NETWORKS;
4389 RTC_LOG(LS_INFO) << "Disable candidates on link-local network interfaces.";
4390 }
4391
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004392 port_allocator_->set_flags(portallocator_flags);
4393 // No step delay is used while allocating ports.
4394 port_allocator_->set_step_delay(cricket::kMinimumStepDelay);
4395 port_allocator_->set_candidate_filter(
4396 ConvertIceTransportTypeToCandidateFilter(configuration.type));
deadbeefd21eab32017-07-26 16:50:11 -07004397 port_allocator_->set_max_ipv6_networks(configuration.max_ipv6_networks);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004398
4399 // Call this last since it may create pooled allocator sessions using the
4400 // properties set above.
4401 port_allocator_->SetConfiguration(stun_servers, turn_servers,
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -07004402 configuration.ice_candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02004403 configuration.prune_turn_ports,
4404 configuration.turn_customizer);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004405 return true;
4406}
4407
deadbeef91dd5672016-05-18 16:55:30 -07004408bool PeerConnection::ReconfigurePortAllocator_n(
deadbeef293e9262017-01-11 12:28:30 -08004409 const cricket::ServerAddresses& stun_servers,
4410 const std::vector<cricket::RelayServerConfig>& turn_servers,
4411 IceTransportsType type,
4412 int candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02004413 bool prune_turn_ports,
4414 webrtc::TurnCustomizer* turn_customizer) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004415 port_allocator_->set_candidate_filter(
deadbeef293e9262017-01-11 12:28:30 -08004416 ConvertIceTransportTypeToCandidateFilter(type));
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004417 // Call this last since it may create pooled allocator sessions using the
4418 // candidate filter set above.
deadbeef6de92f92016-12-12 18:49:32 -08004419 return port_allocator_->SetConfiguration(
Jonas Orelandbdcee282017-10-10 14:01:40 +02004420 stun_servers, turn_servers, candidate_pool_size, prune_turn_ports,
4421 turn_customizer);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004422}
4423
Steve Antonba818672017-11-06 10:21:57 -08004424cricket::ChannelManager* PeerConnection::channel_manager() const {
4425 return factory_->channel_manager();
4426}
4427
4428MetricsObserverInterface* PeerConnection::metrics_observer() const {
4429 return uma_observer_;
4430}
4431
Elad Alon99c3fe52017-10-13 16:29:40 +02004432bool PeerConnection::StartRtcEventLog_w(
Bjorn Tereliusde939432017-11-20 17:38:14 +01004433 std::unique_ptr<RtcEventLogOutput> output,
4434 int64_t output_period_ms) {
zhihuang77985012017-02-07 15:45:16 -08004435 if (!event_log_) {
4436 return false;
4437 }
Bjorn Tereliusde939432017-11-20 17:38:14 +01004438 return event_log_->StartLogging(std::move(output), output_period_ms);
ivoc14d5dbe2016-07-04 07:06:55 -07004439}
4440
4441void PeerConnection::StopRtcEventLog_w() {
zhihuang77985012017-02-07 15:45:16 -08004442 if (event_log_) {
4443 event_log_->StopLogging();
4444 }
ivoc14d5dbe2016-07-04 07:06:55 -07004445}
nisseeaabdf62017-05-05 02:23:02 -07004446
Steve Anton75737c02017-11-06 10:37:17 -08004447cricket::BaseChannel* PeerConnection::GetChannel(
4448 const std::string& content_name) {
Steve Antondcc3c022017-12-22 16:02:54 -08004449 for (auto transceiver : transceivers_) {
4450 cricket::BaseChannel* channel = transceiver->internal()->channel();
4451 if (channel && channel->content_name() == content_name) {
4452 return channel;
4453 }
Steve Anton75737c02017-11-06 10:37:17 -08004454 }
4455 if (rtp_data_channel() &&
4456 rtp_data_channel()->content_name() == content_name) {
4457 return rtp_data_channel();
4458 }
4459 return nullptr;
4460}
4461
4462bool PeerConnection::GetSctpSslRole(rtc::SSLRole* role) {
4463 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004464 RTC_LOG(LS_INFO)
4465 << "Local and Remote descriptions must be applied to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004466 "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08004467 return false;
4468 }
4469 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004470 RTC_LOG(LS_INFO) << "Non-rejected SCTP m= section is needed to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004471 "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08004472 return false;
4473 }
4474
4475 return transport_controller_->GetSslRole(*sctp_transport_name_, role);
4476}
4477
4478bool PeerConnection::GetSslRole(const std::string& content_name,
4479 rtc::SSLRole* role) {
4480 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004481 RTC_LOG(LS_INFO)
4482 << "Local and Remote descriptions must be applied to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004483 "SSL Role of the session.";
Steve Anton75737c02017-11-06 10:37:17 -08004484 return false;
4485 }
4486
4487 return transport_controller_->GetSslRole(GetTransportName(content_name),
4488 role);
4489}
4490
Steve Antonf8470812017-12-04 10:46:21 -08004491void PeerConnection::SetSessionError(SessionError error,
4492 const std::string& error_desc) {
4493 RTC_DCHECK_RUN_ON(signaling_thread());
4494 if (error != session_error_) {
4495 session_error_ = error;
4496 session_error_desc_ = error_desc;
Steve Anton75737c02017-11-06 10:37:17 -08004497 }
4498}
4499
Steve Anton3828c062017-12-06 10:34:51 -08004500RTCError PeerConnection::UpdateSessionState(SdpType type,
Steve Anton8a006912017-12-04 15:25:56 -08004501 cricket::ContentSource source) {
4502 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08004503
4504 // If there's already a pending error then no state transition should happen.
4505 // But all call-sites should be verifying this before calling us!
Steve Antonf8470812017-12-04 10:46:21 -08004506 RTC_DCHECK(session_error() == SessionError::kNone);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004507
4508 // If this is an answer then we know whether to BUNDLE or not. If both the
4509 // local and remote side have agreed to BUNDLE, go ahead and enable it.
Steve Anton3828c062017-12-06 10:34:51 -08004510 if (type == SdpType::kAnswer) {
Steve Anton75737c02017-11-06 10:37:17 -08004511 const cricket::ContentGroup* local_bundle =
4512 local_description()->description()->GetGroupByName(
4513 cricket::GROUP_TYPE_BUNDLE);
4514 const cricket::ContentGroup* remote_bundle =
4515 remote_description()->description()->GetGroupByName(
4516 cricket::GROUP_TYPE_BUNDLE);
4517 if (local_bundle && remote_bundle) {
4518 // The answerer decides the transport to bundle on.
4519 const cricket::ContentGroup* answer_bundle =
4520 (source == cricket::CS_LOCAL ? local_bundle : remote_bundle);
4521 if (!EnableBundle(*answer_bundle)) {
Steve Anton8a006912017-12-04 15:25:56 -08004522 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
4523 kEnableBundleFailed);
Steve Anton75737c02017-11-06 10:37:17 -08004524 }
4525 }
Steve Anton75737c02017-11-06 10:37:17 -08004526 }
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004527
4528 // Only push down the transport description after potentially enabling BUNDLE;
4529 // we don't want to push down a description on a transport about to be
4530 // destroyed.
Steve Anton3828c062017-12-06 10:34:51 -08004531 RTCError error = PushdownTransportDescription(source, type);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004532 if (!error.ok()) {
4533 return error;
4534 }
4535
4536 // If this is answer-ish we're ready to let media flow.
Steve Anton3828c062017-12-06 10:34:51 -08004537 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Antoned10bd92017-12-05 10:52:59 -08004538 EnableSending();
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004539 }
4540
4541 // Update the signaling state according to the specified state machine (see
4542 // https://w3c.github.io/webrtc-pc/#rtcsignalingstate-enum).
Steve Anton3828c062017-12-06 10:34:51 -08004543 if (type == SdpType::kOffer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004544 ChangeSignalingState(source == cricket::CS_LOCAL
4545 ? PeerConnectionInterface::kHaveLocalOffer
4546 : PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton3828c062017-12-06 10:34:51 -08004547 } else if (type == SdpType::kPrAnswer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004548 ChangeSignalingState(source == cricket::CS_LOCAL
4549 ? PeerConnectionInterface::kHaveLocalPrAnswer
4550 : PeerConnectionInterface::kHaveRemotePrAnswer);
4551 } else {
Steve Anton3828c062017-12-06 10:34:51 -08004552 RTC_DCHECK(type == SdpType::kAnswer);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004553 ChangeSignalingState(PeerConnectionInterface::kStable);
4554 }
4555
4556 // Update internal objects according to the session description's media
4557 // descriptions.
Steve Anton3828c062017-12-06 10:34:51 -08004558 error = PushdownMediaDescription(type, source);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004559 if (!error.ok()) {
Steve Anton71439a62018-02-15 11:53:06 -08004560 return error;
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004561 }
4562
Steve Anton8a006912017-12-04 15:25:56 -08004563 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08004564}
4565
Steve Anton8a006912017-12-04 15:25:56 -08004566RTCError PeerConnection::PushdownMediaDescription(
Steve Anton3828c062017-12-06 10:34:51 -08004567 SdpType type,
Steve Anton8a006912017-12-04 15:25:56 -08004568 cricket::ContentSource source) {
Steve Antoned10bd92017-12-05 10:52:59 -08004569 const SessionDescriptionInterface* sdesc =
4570 (source == cricket::CS_LOCAL ? local_description()
4571 : remote_description());
Steve Anton75737c02017-11-06 10:37:17 -08004572 RTC_DCHECK(sdesc);
Steve Antoned10bd92017-12-05 10:52:59 -08004573
4574 // Push down the new SDP media section for each audio/video transceiver.
4575 for (auto transceiver : transceivers_) {
Steve Anton75737c02017-11-06 10:37:17 -08004576 const ContentInfo* content_info =
Steve Antoned10bd92017-12-05 10:52:59 -08004577 FindMediaSectionForTransceiver(transceiver, sdesc);
4578 cricket::BaseChannel* channel = transceiver->internal()->channel();
4579 if (!channel || !content_info || content_info->rejected) {
Steve Anton75737c02017-11-06 10:37:17 -08004580 continue;
4581 }
4582 const MediaContentDescription* content_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08004583 content_info->media_description();
Steve Antoned10bd92017-12-05 10:52:59 -08004584 if (!content_desc) {
4585 continue;
4586 }
4587 std::string error;
4588 bool success =
4589 (source == cricket::CS_LOCAL)
Steve Anton3828c062017-12-06 10:34:51 -08004590 ? channel->SetLocalContent(content_desc, type, &error)
4591 : channel->SetRemoteContent(content_desc, type, &error);
Steve Antoned10bd92017-12-05 10:52:59 -08004592 if (!success) {
4593 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, std::move(error));
4594 }
4595 }
4596
4597 // If using the RtpDataChannel, push down the new SDP section for it too.
4598 if (rtp_data_channel_) {
4599 const ContentInfo* data_content =
4600 cricket::GetFirstDataContent(sdesc->description());
4601 if (data_content && !data_content->rejected) {
4602 const MediaContentDescription* data_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08004603 data_content->media_description();
Steve Antoned10bd92017-12-05 10:52:59 -08004604 if (data_desc) {
4605 std::string error;
4606 bool success =
4607 (source == cricket::CS_LOCAL)
Steve Anton3828c062017-12-06 10:34:51 -08004608 ? rtp_data_channel_->SetLocalContent(data_desc, type, &error)
4609 : rtp_data_channel_->SetRemoteContent(data_desc, type,
Steve Antoned10bd92017-12-05 10:52:59 -08004610 &error);
4611 if (!success) {
4612 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
4613 std::move(error));
4614 }
Steve Anton75737c02017-11-06 10:37:17 -08004615 }
4616 }
4617 }
Steve Antoned10bd92017-12-05 10:52:59 -08004618
Steve Anton75737c02017-11-06 10:37:17 -08004619 // Need complete offer/answer with an SCTP m= section before starting SCTP,
4620 // according to https://tools.ietf.org/html/draft-ietf-mmusic-sctp-sdp-19
4621 if (sctp_transport_ && local_description() && remote_description() &&
4622 cricket::GetFirstDataContent(local_description()->description()) &&
4623 cricket::GetFirstDataContent(remote_description()->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08004624 bool success = network_thread()->Invoke<bool>(
Steve Anton75737c02017-11-06 10:37:17 -08004625 RTC_FROM_HERE,
4626 rtc::Bind(&PeerConnection::PushdownSctpParameters_n, this, source));
Steve Anton8a006912017-12-04 15:25:56 -08004627 if (!success) {
4628 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
4629 "Failed to push down SCTP parameters.");
4630 }
Steve Anton75737c02017-11-06 10:37:17 -08004631 }
Steve Antoned10bd92017-12-05 10:52:59 -08004632
Steve Anton8a006912017-12-04 15:25:56 -08004633 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08004634}
4635
4636bool PeerConnection::PushdownSctpParameters_n(cricket::ContentSource source) {
4637 RTC_DCHECK(network_thread()->IsCurrent());
4638 RTC_DCHECK(local_description());
4639 RTC_DCHECK(remote_description());
4640 // Apply the SCTP port (which is hidden inside a DataCodec structure...)
4641 // When we support "max-message-size", that would also be pushed down here.
4642 return sctp_transport_->Start(
4643 GetSctpPort(local_description()->description()),
4644 GetSctpPort(remote_description()->description()));
4645}
4646
Steve Anton8a006912017-12-04 15:25:56 -08004647RTCError PeerConnection::PushdownTransportDescription(
4648 cricket::ContentSource source,
Steve Anton3828c062017-12-06 10:34:51 -08004649 SdpType type) {
Steve Anton8a006912017-12-04 15:25:56 -08004650 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08004651
Steve Anton8a006912017-12-04 15:25:56 -08004652 const SessionDescriptionInterface* sdesc =
4653 (source == cricket::CS_LOCAL ? local_description()
4654 : remote_description());
4655 RTC_DCHECK(sdesc);
4656 for (const cricket::TransportInfo& tinfo :
4657 sdesc->description()->transport_infos()) {
4658 std::string error;
4659 bool success;
4660 if (source == cricket::CS_LOCAL) {
4661 success = transport_controller_->SetLocalTransportDescription(
Steve Anton3828c062017-12-06 10:34:51 -08004662 tinfo.content_name, tinfo.description, type, &error);
Steve Anton8a006912017-12-04 15:25:56 -08004663 } else {
4664 success = transport_controller_->SetRemoteTransportDescription(
Steve Anton3828c062017-12-06 10:34:51 -08004665 tinfo.content_name, tinfo.description, type, &error);
Steve Anton8a006912017-12-04 15:25:56 -08004666 }
4667 if (!success) {
Steve Antondcc3c022017-12-22 16:02:54 -08004668 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
4669 "Failed to push down transport description for " +
4670 tinfo.content_name + ": " + error);
Steve Anton75737c02017-11-06 10:37:17 -08004671 }
4672 }
4673
Steve Anton8a006912017-12-04 15:25:56 -08004674 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08004675}
4676
4677bool PeerConnection::GetTransportDescription(
4678 const SessionDescription* description,
4679 const std::string& content_name,
4680 cricket::TransportDescription* tdesc) {
4681 if (!description || !tdesc) {
4682 return false;
4683 }
4684 const TransportInfo* transport_info =
4685 description->GetTransportInfoByName(content_name);
4686 if (!transport_info) {
4687 return false;
4688 }
4689 *tdesc = transport_info->description;
4690 return true;
4691}
4692
4693bool PeerConnection::EnableBundle(const cricket::ContentGroup& bundle) {
4694 const std::string* first_content_name = bundle.FirstContentName();
4695 if (!first_content_name) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004696 RTC_LOG(LS_WARNING) << "Tried to BUNDLE with no contents.";
Steve Anton75737c02017-11-06 10:37:17 -08004697 return false;
4698 }
4699 const std::string& transport_name = *first_content_name;
4700
4701 auto maybe_set_transport = [this, bundle,
4702 transport_name](cricket::BaseChannel* ch) {
4703 if (!ch || !bundle.HasContentName(ch->content_name())) {
Steve Antoned10bd92017-12-05 10:52:59 -08004704 return;
Steve Anton75737c02017-11-06 10:37:17 -08004705 }
4706
4707 std::string old_transport_name = ch->transport_name();
4708 if (old_transport_name == transport_name) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004709 RTC_LOG(LS_INFO) << "BUNDLE already enabled for " << ch->content_name()
4710 << " on " << transport_name << ".";
Steve Antoned10bd92017-12-05 10:52:59 -08004711 return;
Steve Anton75737c02017-11-06 10:37:17 -08004712 }
4713
4714 cricket::DtlsTransportInternal* rtp_dtls_transport =
4715 transport_controller_->CreateDtlsTransport(
4716 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4717 bool need_rtcp = (ch->rtcp_dtls_transport() != nullptr);
4718 cricket::DtlsTransportInternal* rtcp_dtls_transport = nullptr;
4719 if (need_rtcp) {
4720 rtcp_dtls_transport = transport_controller_->CreateDtlsTransport(
4721 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
4722 }
4723
4724 ch->SetTransports(rtp_dtls_transport, rtcp_dtls_transport);
Mirko Bonadei675513b2017-11-09 11:09:25 +01004725 RTC_LOG(LS_INFO) << "Enabled BUNDLE for " << ch->content_name() << " on "
4726 << transport_name << ".";
Steve Anton75737c02017-11-06 10:37:17 -08004727 transport_controller_->DestroyDtlsTransport(
4728 old_transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4729 // If the channel needs rtcp, it means that the channel used to have a
4730 // rtcp transport which needs to be deleted now.
4731 if (need_rtcp) {
4732 transport_controller_->DestroyDtlsTransport(
4733 old_transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
4734 }
Steve Anton75737c02017-11-06 10:37:17 -08004735 };
4736
Steve Antoned10bd92017-12-05 10:52:59 -08004737 for (auto transceiver : transceivers_) {
4738 maybe_set_transport(transceiver->internal()->channel());
Steve Anton75737c02017-11-06 10:37:17 -08004739 }
Steve Antoned10bd92017-12-05 10:52:59 -08004740 maybe_set_transport(rtp_data_channel_);
4741
Steve Anton75737c02017-11-06 10:37:17 -08004742 // For SCTP, transport creation/deletion happens here instead of in the
4743 // object itself.
4744 if (sctp_transport_) {
4745 RTC_DCHECK(sctp_transport_name_);
4746 RTC_DCHECK(sctp_content_name_);
4747 if (transport_name != *sctp_transport_name_ &&
4748 bundle.HasContentName(*sctp_content_name_)) {
4749 network_thread()->Invoke<void>(
4750 RTC_FROM_HERE, rtc::Bind(&PeerConnection::ChangeSctpTransport_n, this,
4751 transport_name));
4752 }
4753 }
4754
4755 return true;
4756}
4757
Steve Anton75737c02017-11-06 10:37:17 -08004758cricket::IceConfig PeerConnection::ParseIceConfig(
4759 const PeerConnectionInterface::RTCConfiguration& config) const {
4760 cricket::ContinualGatheringPolicy gathering_policy;
4761 // TODO(honghaiz): Add the third continual gathering policy in
4762 // PeerConnectionInterface and map it to GATHER_CONTINUALLY_AND_RECOVER.
4763 switch (config.continual_gathering_policy) {
4764 case PeerConnectionInterface::GATHER_ONCE:
4765 gathering_policy = cricket::GATHER_ONCE;
4766 break;
4767 case PeerConnectionInterface::GATHER_CONTINUALLY:
4768 gathering_policy = cricket::GATHER_CONTINUALLY;
4769 break;
4770 default:
4771 RTC_NOTREACHED();
4772 gathering_policy = cricket::GATHER_ONCE;
4773 }
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08004774
Steve Anton75737c02017-11-06 10:37:17 -08004775 cricket::IceConfig ice_config;
4776 ice_config.receiving_timeout = config.ice_connection_receiving_timeout;
4777 ice_config.prioritize_most_likely_candidate_pairs =
4778 config.prioritize_most_likely_ice_candidate_pairs;
4779 ice_config.backup_connection_ping_interval =
4780 config.ice_backup_candidate_pair_ping_interval;
4781 ice_config.continual_gathering_policy = gathering_policy;
4782 ice_config.presume_writable_when_fully_relayed =
4783 config.presume_writable_when_fully_relayed;
4784 ice_config.ice_check_min_interval = config.ice_check_min_interval;
4785 ice_config.regather_all_networks_interval_range =
4786 config.ice_regather_interval_range;
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08004787 ice_config.network_preference = config.network_preference;
Steve Anton75737c02017-11-06 10:37:17 -08004788 return ice_config;
4789}
4790
Steve Anton75737c02017-11-06 10:37:17 -08004791bool PeerConnection::GetLocalTrackIdBySsrc(uint32_t ssrc,
4792 std::string* track_id) {
4793 if (!local_description()) {
4794 return false;
4795 }
4796 return webrtc::GetTrackIdBySsrc(local_description()->description(), ssrc,
4797 track_id);
4798}
4799
4800bool PeerConnection::GetRemoteTrackIdBySsrc(uint32_t ssrc,
4801 std::string* track_id) {
4802 if (!remote_description()) {
4803 return false;
4804 }
4805 return webrtc::GetTrackIdBySsrc(remote_description()->description(), ssrc,
4806 track_id);
4807}
4808
4809bool PeerConnection::SendData(const cricket::SendDataParams& params,
4810 const rtc::CopyOnWriteBuffer& payload,
4811 cricket::SendDataResult* result) {
4812 if (!rtp_data_channel_ && !sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004813 RTC_LOG(LS_ERROR) << "SendData called when rtp_data_channel_ "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004814 "and sctp_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08004815 return false;
4816 }
4817 return rtp_data_channel_
4818 ? rtp_data_channel_->SendData(params, payload, result)
4819 : network_thread()->Invoke<bool>(
4820 RTC_FROM_HERE,
4821 Bind(&cricket::SctpTransportInternal::SendData,
4822 sctp_transport_.get(), params, payload, result));
4823}
4824
4825bool PeerConnection::ConnectDataChannel(DataChannel* webrtc_data_channel) {
4826 if (!rtp_data_channel_ && !sctp_transport_) {
4827 // Don't log an error here, because DataChannels are expected to call
4828 // ConnectDataChannel in this state. It's the only way to initially tell
4829 // whether or not the underlying transport is ready.
4830 return false;
4831 }
4832 if (rtp_data_channel_) {
4833 rtp_data_channel_->SignalReadyToSendData.connect(
4834 webrtc_data_channel, &DataChannel::OnChannelReady);
4835 rtp_data_channel_->SignalDataReceived.connect(webrtc_data_channel,
4836 &DataChannel::OnDataReceived);
4837 } else {
4838 SignalSctpReadyToSendData.connect(webrtc_data_channel,
4839 &DataChannel::OnChannelReady);
4840 SignalSctpDataReceived.connect(webrtc_data_channel,
4841 &DataChannel::OnDataReceived);
4842 SignalSctpStreamClosedRemotely.connect(
4843 webrtc_data_channel, &DataChannel::OnStreamClosedRemotely);
4844 }
4845 return true;
4846}
4847
4848void PeerConnection::DisconnectDataChannel(DataChannel* webrtc_data_channel) {
4849 if (!rtp_data_channel_ && !sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004850 RTC_LOG(LS_ERROR)
4851 << "DisconnectDataChannel called when rtp_data_channel_ and "
4852 "sctp_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08004853 return;
4854 }
4855 if (rtp_data_channel_) {
4856 rtp_data_channel_->SignalReadyToSendData.disconnect(webrtc_data_channel);
4857 rtp_data_channel_->SignalDataReceived.disconnect(webrtc_data_channel);
4858 } else {
4859 SignalSctpReadyToSendData.disconnect(webrtc_data_channel);
4860 SignalSctpDataReceived.disconnect(webrtc_data_channel);
4861 SignalSctpStreamClosedRemotely.disconnect(webrtc_data_channel);
4862 }
4863}
4864
4865void PeerConnection::AddSctpDataStream(int sid) {
4866 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004867 RTC_LOG(LS_ERROR)
4868 << "AddSctpDataStream called when sctp_transport_ is NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08004869 return;
4870 }
4871 network_thread()->Invoke<void>(
4872 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::OpenStream,
4873 sctp_transport_.get(), sid));
4874}
4875
4876void PeerConnection::RemoveSctpDataStream(int sid) {
4877 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004878 RTC_LOG(LS_ERROR) << "RemoveSctpDataStream called when sctp_transport_ is "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004879 "NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08004880 return;
4881 }
4882 network_thread()->Invoke<void>(
4883 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::ResetStream,
4884 sctp_transport_.get(), sid));
4885}
4886
4887bool PeerConnection::ReadyToSendData() const {
4888 return (rtp_data_channel_ && rtp_data_channel_->ready_to_send_data()) ||
4889 sctp_ready_to_send_data_;
4890}
4891
Steve Anton5dfde182018-02-06 10:34:40 -08004892std::map<std::string, std::string> PeerConnection::GetTransportNamesByMid()
4893 const {
4894 std::map<std::string, std::string> transport_names_by_mid;
4895 for (auto transceiver : transceivers_) {
4896 cricket::BaseChannel* channel = transceiver->internal()->channel();
4897 if (channel) {
4898 transport_names_by_mid[channel->content_name()] =
4899 channel->transport_name();
4900 }
Steve Anton75737c02017-11-06 10:37:17 -08004901 }
Steve Anton5dfde182018-02-06 10:34:40 -08004902 if (rtp_data_channel_) {
4903 transport_names_by_mid[rtp_data_channel_->content_name()] =
4904 rtp_data_channel_->transport_name();
Steve Anton75737c02017-11-06 10:37:17 -08004905 }
4906 if (sctp_transport_) {
Steve Anton5dfde182018-02-06 10:34:40 -08004907 transport_names_by_mid[*sctp_content_name_] = *sctp_transport_name_;
Steve Anton75737c02017-11-06 10:37:17 -08004908 }
Steve Anton5dfde182018-02-06 10:34:40 -08004909 return transport_names_by_mid;
Steve Anton75737c02017-11-06 10:37:17 -08004910}
4911
Steve Anton5dfde182018-02-06 10:34:40 -08004912std::map<std::string, cricket::TransportStats>
4913PeerConnection::GetTransportStatsByNames(
4914 const std::set<std::string>& transport_names) {
4915 if (!network_thread()->IsCurrent()) {
4916 return network_thread()
4917 ->Invoke<std::map<std::string, cricket::TransportStats>>(
4918 RTC_FROM_HERE,
4919 [&] { return GetTransportStatsByNames(transport_names); });
Steve Anton75737c02017-11-06 10:37:17 -08004920 }
Steve Anton5dfde182018-02-06 10:34:40 -08004921 std::map<std::string, cricket::TransportStats> transport_stats_by_name;
4922 for (const std::string& transport_name : transport_names) {
4923 cricket::TransportStats transport_stats;
4924 bool success =
4925 transport_controller_->GetStats(transport_name, &transport_stats);
4926 if (success) {
4927 transport_stats_by_name[transport_name] = std::move(transport_stats);
4928 } else {
4929 RTC_LOG(LS_ERROR) << "Failed to get transport stats for transport_name="
4930 << transport_name;
4931 }
4932 }
4933 return transport_stats_by_name;
Steve Anton75737c02017-11-06 10:37:17 -08004934}
4935
4936bool PeerConnection::GetLocalCertificate(
4937 const std::string& transport_name,
4938 rtc::scoped_refptr<rtc::RTCCertificate>* certificate) {
4939 return transport_controller_->GetLocalCertificate(transport_name,
4940 certificate);
4941}
4942
4943std::unique_ptr<rtc::SSLCertificate> PeerConnection::GetRemoteSSLCertificate(
4944 const std::string& transport_name) {
4945 return transport_controller_->GetRemoteSSLCertificate(transport_name);
4946}
4947
4948cricket::DataChannelType PeerConnection::data_channel_type() const {
4949 return data_channel_type_;
4950}
4951
4952bool PeerConnection::IceRestartPending(const std::string& content_name) const {
4953 return pending_ice_restarts_.find(content_name) !=
4954 pending_ice_restarts_.end();
4955}
4956
Steve Anton75737c02017-11-06 10:37:17 -08004957bool PeerConnection::NeedsIceRestart(const std::string& content_name) const {
4958 return transport_controller_->NeedsIceRestart(content_name);
4959}
4960
4961void PeerConnection::OnCertificateReady(
4962 const rtc::scoped_refptr<rtc::RTCCertificate>& certificate) {
4963 transport_controller_->SetLocalCertificate(certificate);
4964}
4965
4966void PeerConnection::OnDtlsSrtpSetupFailure(cricket::BaseChannel*, bool rtcp) {
Steve Antonf8470812017-12-04 10:46:21 -08004967 SetSessionError(SessionError::kTransport,
4968 rtcp ? kDtlsSrtpSetupFailureRtcp : kDtlsSrtpSetupFailureRtp);
Steve Anton75737c02017-11-06 10:37:17 -08004969}
4970
4971void PeerConnection::OnTransportControllerConnectionState(
4972 cricket::IceConnectionState state) {
4973 switch (state) {
4974 case cricket::kIceConnectionConnecting:
4975 // If the current state is Connected or Completed, then there were
4976 // writable channels but now there are not, so the next state must
4977 // be Disconnected.
4978 // kIceConnectionConnecting is currently used as the default,
4979 // un-connected state by the TransportController, so its only use is
4980 // detecting disconnections.
4981 if (ice_connection_state_ ==
4982 PeerConnectionInterface::kIceConnectionConnected ||
4983 ice_connection_state_ ==
4984 PeerConnectionInterface::kIceConnectionCompleted) {
4985 SetIceConnectionState(
4986 PeerConnectionInterface::kIceConnectionDisconnected);
4987 }
4988 break;
4989 case cricket::kIceConnectionFailed:
4990 SetIceConnectionState(PeerConnectionInterface::kIceConnectionFailed);
4991 break;
4992 case cricket::kIceConnectionConnected:
Mirko Bonadei675513b2017-11-09 11:09:25 +01004993 RTC_LOG(LS_INFO) << "Changing to ICE connected state because "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004994 "all transports are writable.";
Steve Anton75737c02017-11-06 10:37:17 -08004995 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
4996 break;
4997 case cricket::kIceConnectionCompleted:
Mirko Bonadei675513b2017-11-09 11:09:25 +01004998 RTC_LOG(LS_INFO) << "Changing to ICE completed state because "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004999 "all transports are complete.";
Steve Anton75737c02017-11-06 10:37:17 -08005000 if (ice_connection_state_ !=
5001 PeerConnectionInterface::kIceConnectionConnected) {
5002 // If jumping directly from "checking" to "connected",
5003 // signal "connected" first.
5004 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
5005 }
5006 SetIceConnectionState(PeerConnectionInterface::kIceConnectionCompleted);
5007 if (metrics_observer()) {
5008 ReportTransportStats();
5009 }
5010 break;
5011 default:
5012 RTC_NOTREACHED();
5013 }
5014}
5015
5016void PeerConnection::OnTransportControllerCandidatesGathered(
5017 const std::string& transport_name,
5018 const cricket::Candidates& candidates) {
5019 RTC_DCHECK(signaling_thread()->IsCurrent());
5020 int sdp_mline_index;
5021 if (!GetLocalCandidateMediaIndex(transport_name, &sdp_mline_index)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005022 RTC_LOG(LS_ERROR)
5023 << "OnTransportControllerCandidatesGathered: content name "
5024 << transport_name << " not found";
Steve Anton75737c02017-11-06 10:37:17 -08005025 return;
5026 }
5027
5028 for (cricket::Candidates::const_iterator citer = candidates.begin();
5029 citer != candidates.end(); ++citer) {
5030 // Use transport_name as the candidate media id.
5031 std::unique_ptr<JsepIceCandidate> candidate(
5032 new JsepIceCandidate(transport_name, sdp_mline_index, *citer));
5033 if (local_description()) {
5034 mutable_local_description()->AddCandidate(candidate.get());
5035 }
5036 OnIceCandidate(std::move(candidate));
5037 }
5038}
5039
5040void PeerConnection::OnTransportControllerCandidatesRemoved(
5041 const std::vector<cricket::Candidate>& candidates) {
5042 RTC_DCHECK(signaling_thread()->IsCurrent());
5043 // Sanity check.
5044 for (const cricket::Candidate& candidate : candidates) {
5045 if (candidate.transport_name().empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005046 RTC_LOG(LS_ERROR) << "OnTransportControllerCandidatesRemoved: "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005047 "empty content name in candidate "
Mirko Bonadei675513b2017-11-09 11:09:25 +01005048 << candidate.ToString();
Steve Anton75737c02017-11-06 10:37:17 -08005049 return;
5050 }
5051 }
5052
5053 if (local_description()) {
5054 mutable_local_description()->RemoveCandidates(candidates);
5055 }
5056 OnIceCandidatesRemoved(candidates);
5057}
5058
5059void PeerConnection::OnTransportControllerDtlsHandshakeError(
5060 rtc::SSLHandshakeError error) {
5061 if (metrics_observer()) {
5062 metrics_observer()->IncrementEnumCounter(
5063 webrtc::kEnumCounterDtlsHandshakeError, static_cast<int>(error),
5064 static_cast<int>(rtc::SSLHandshakeError::MAX_VALUE));
5065 }
5066}
5067
Steve Antoned10bd92017-12-05 10:52:59 -08005068void PeerConnection::EnableSending() {
5069 for (auto transceiver : transceivers_) {
5070 cricket::BaseChannel* channel = transceiver->internal()->channel();
5071 if (channel && !channel->enabled()) {
5072 channel->Enable(true);
5073 }
Steve Anton75737c02017-11-06 10:37:17 -08005074 }
5075
Steve Anton4171afb2017-11-20 10:20:22 -08005076 if (rtp_data_channel_ && !rtp_data_channel_->enabled()) {
Steve Anton75737c02017-11-06 10:37:17 -08005077 rtp_data_channel_->Enable(true);
Steve Anton4171afb2017-11-20 10:20:22 -08005078 }
Steve Anton75737c02017-11-06 10:37:17 -08005079}
5080
5081// Returns the media index for a local ice candidate given the content name.
5082bool PeerConnection::GetLocalCandidateMediaIndex(
5083 const std::string& content_name,
5084 int* sdp_mline_index) {
5085 if (!local_description() || !sdp_mline_index) {
5086 return false;
5087 }
5088
5089 bool content_found = false;
5090 const ContentInfos& contents = local_description()->description()->contents();
5091 for (size_t index = 0; index < contents.size(); ++index) {
5092 if (contents[index].name == content_name) {
5093 *sdp_mline_index = static_cast<int>(index);
5094 content_found = true;
5095 break;
5096 }
5097 }
5098 return content_found;
5099}
5100
5101bool PeerConnection::UseCandidatesInSessionDescription(
5102 const SessionDescriptionInterface* remote_desc) {
5103 if (!remote_desc) {
5104 return true;
5105 }
5106 bool ret = true;
5107
5108 for (size_t m = 0; m < remote_desc->number_of_mediasections(); ++m) {
5109 const IceCandidateCollection* candidates = remote_desc->candidates(m);
5110 for (size_t n = 0; n < candidates->count(); ++n) {
5111 const IceCandidateInterface* candidate = candidates->at(n);
5112 bool valid = false;
5113 if (!ReadyToUseRemoteCandidate(candidate, remote_desc, &valid)) {
5114 if (valid) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005115 RTC_LOG(LS_INFO)
5116 << "UseCandidatesInSessionDescription: Not ready to use "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005117 "candidate.";
Steve Anton75737c02017-11-06 10:37:17 -08005118 }
5119 continue;
5120 }
5121 ret = UseCandidate(candidate);
5122 if (!ret) {
5123 break;
5124 }
5125 }
5126 }
5127 return ret;
5128}
5129
5130bool PeerConnection::UseCandidate(const IceCandidateInterface* candidate) {
5131 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
5132 size_t remote_content_size =
5133 remote_description()->description()->contents().size();
5134 if (mediacontent_index >= remote_content_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005135 RTC_LOG(LS_ERROR) << "UseCandidate: Invalid candidate media index.";
Steve Anton75737c02017-11-06 10:37:17 -08005136 return false;
5137 }
5138
5139 cricket::ContentInfo content =
5140 remote_description()->description()->contents()[mediacontent_index];
5141 std::vector<cricket::Candidate> candidates;
5142 candidates.push_back(candidate->candidate());
5143 // Invoking BaseSession method to handle remote candidates.
5144 std::string error;
5145 if (transport_controller_->AddRemoteCandidates(content.name, candidates,
5146 &error)) {
5147 // Candidates successfully submitted for checking.
5148 if (ice_connection_state_ == PeerConnectionInterface::kIceConnectionNew ||
5149 ice_connection_state_ ==
5150 PeerConnectionInterface::kIceConnectionDisconnected) {
5151 // If state is New, then the session has just gotten its first remote ICE
5152 // candidates, so go to Checking.
5153 // If state is Disconnected, the session is re-using old candidates or
5154 // receiving additional ones, so go to Checking.
5155 // If state is Connected, stay Connected.
5156 // TODO(bemasc): If state is Connected, and the new candidates are for a
5157 // newly added transport, then the state actually _should_ move to
5158 // checking. Add a way to distinguish that case.
5159 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
5160 }
5161 // TODO(bemasc): If state is Completed, go back to Connected.
5162 } else {
5163 if (!error.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005164 RTC_LOG(LS_WARNING) << error;
Steve Anton75737c02017-11-06 10:37:17 -08005165 }
5166 }
5167 return true;
5168}
5169
5170void PeerConnection::RemoveUnusedChannels(const SessionDescription* desc) {
Steve Anton75737c02017-11-06 10:37:17 -08005171 // Destroy video channel first since it may have a pointer to the
5172 // voice channel.
5173 const cricket::ContentInfo* video_info = cricket::GetFirstVideoContent(desc);
Steve Anton6fec8802017-12-04 10:37:29 -08005174 if (!video_info || video_info->rejected) {
5175 DestroyTransceiverChannel(GetVideoTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08005176 }
5177
Steve Anton6fec8802017-12-04 10:37:29 -08005178 const cricket::ContentInfo* audio_info = cricket::GetFirstAudioContent(desc);
5179 if (!audio_info || audio_info->rejected) {
5180 DestroyTransceiverChannel(GetAudioTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08005181 }
5182
5183 const cricket::ContentInfo* data_info = cricket::GetFirstDataContent(desc);
5184 if (!data_info || data_info->rejected) {
Steve Anton6fec8802017-12-04 10:37:29 -08005185 DestroyDataChannel();
Steve Anton75737c02017-11-06 10:37:17 -08005186 }
5187}
5188
Steve Antoneda6ccd2017-12-04 10:21:55 -08005189std::string PeerConnection::GetTransportNameForMediaSection(
5190 const std::string& mid,
5191 const cricket::ContentGroup* bundle_group) const {
5192 if (!bundle_group) {
5193 return mid;
Steve Anton75737c02017-11-06 10:37:17 -08005194 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005195 const std::string* first_content_name = bundle_group->FirstContentName();
Steve Anton75737c02017-11-06 10:37:17 -08005196 if (!first_content_name) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005197 RTC_LOG(LS_WARNING) << "Tried to BUNDLE with no contents.";
Steve Antoneda6ccd2017-12-04 10:21:55 -08005198 return mid;
Steve Anton75737c02017-11-06 10:37:17 -08005199 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005200 if (!bundle_group->HasContentName(mid)) {
5201 RTC_LOG(LS_WARNING) << mid << " is not part of any bundle group";
5202 return mid;
Steve Anton75737c02017-11-06 10:37:17 -08005203 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005204 RTC_LOG(LS_INFO) << "Bundling " << mid << " on " << *first_content_name;
5205 return *first_content_name;
Steve Anton75737c02017-11-06 10:37:17 -08005206}
5207
Steve Antondcc3c022017-12-22 16:02:54 -08005208RTCErrorOr<const cricket::ContentGroup*> PeerConnection::GetEarlyBundleGroup(
5209 const SessionDescription& desc) const {
Steve Anton75737c02017-11-06 10:37:17 -08005210 const cricket::ContentGroup* bundle_group = nullptr;
5211 if (configuration_.bundle_policy ==
5212 PeerConnectionInterface::kBundlePolicyMaxBundle) {
Steve Antondcc3c022017-12-22 16:02:54 -08005213 bundle_group = desc.GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton75737c02017-11-06 10:37:17 -08005214 if (!bundle_group) {
Steve Anton8a006912017-12-04 15:25:56 -08005215 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5216 "max-bundle configured but session description "
5217 "has no BUNDLE group");
Steve Anton75737c02017-11-06 10:37:17 -08005218 }
5219 }
Steve Antondcc3c022017-12-22 16:02:54 -08005220 return std::move(bundle_group);
5221}
5222
5223RTCError PeerConnection::CreateChannels(const SessionDescription& desc) {
5224 auto bundle_group_or_error = GetEarlyBundleGroup(desc);
5225 if (!bundle_group_or_error.ok()) {
5226 return bundle_group_or_error.MoveError();
5227 }
5228 const cricket::ContentGroup* bundle_group = bundle_group_or_error.MoveValue();
Steve Anton75737c02017-11-06 10:37:17 -08005229
Steve Antoneda6ccd2017-12-04 10:21:55 -08005230 // Creating the media channels and transport proxies.
Steve Antondcc3c022017-12-22 16:02:54 -08005231 const cricket::ContentInfo* voice = cricket::GetFirstAudioContent(&desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08005232 if (voice && !voice->rejected &&
5233 !GetAudioTransceiver()->internal()->channel()) {
5234 cricket::VoiceChannel* voice_channel = CreateVoiceChannel(
5235 voice->name,
5236 GetTransportNameForMediaSection(voice->name, bundle_group));
5237 if (!voice_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08005238 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5239 "Failed to create voice channel.");
Steve Antoneda6ccd2017-12-04 10:21:55 -08005240 }
5241 GetAudioTransceiver()->internal()->SetChannel(voice_channel);
5242 }
5243
Steve Antondcc3c022017-12-22 16:02:54 -08005244 const cricket::ContentInfo* video = cricket::GetFirstVideoContent(&desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08005245 if (video && !video->rejected &&
5246 !GetVideoTransceiver()->internal()->channel()) {
5247 cricket::VideoChannel* video_channel = CreateVideoChannel(
5248 video->name,
5249 GetTransportNameForMediaSection(video->name, bundle_group));
5250 if (!video_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08005251 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5252 "Failed to create video channel.");
Steve Anton75737c02017-11-06 10:37:17 -08005253 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005254 GetVideoTransceiver()->internal()->SetChannel(video_channel);
Steve Anton75737c02017-11-06 10:37:17 -08005255 }
5256
Steve Antondcc3c022017-12-22 16:02:54 -08005257 const cricket::ContentInfo* data = cricket::GetFirstDataContent(&desc);
Steve Anton75737c02017-11-06 10:37:17 -08005258 if (data_channel_type_ != cricket::DCT_NONE && data && !data->rejected &&
5259 !rtp_data_channel_ && !sctp_transport_) {
Steve Antoneda6ccd2017-12-04 10:21:55 -08005260 if (!CreateDataChannel(data->name, GetTransportNameForMediaSection(
5261 data->name, bundle_group))) {
Steve Anton8a006912017-12-04 15:25:56 -08005262 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5263 "Failed to create data channel.");
Steve Anton75737c02017-11-06 10:37:17 -08005264 }
5265 }
5266
Steve Anton8a006912017-12-04 15:25:56 -08005267 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08005268}
5269
Steve Anton4171afb2017-11-20 10:20:22 -08005270// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08005271cricket::VoiceChannel* PeerConnection::CreateVoiceChannel(
5272 const std::string& mid,
5273 const std::string& transport_name) {
Steve Anton75737c02017-11-06 10:37:17 -08005274 cricket::DtlsTransportInternal* rtp_dtls_transport =
5275 transport_controller_->CreateDtlsTransport(
5276 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5277 cricket::DtlsTransportInternal* rtcp_dtls_transport = nullptr;
5278 if (configuration_.rtcp_mux_policy !=
5279 PeerConnectionInterface::kRtcpMuxPolicyRequire) {
5280 rtcp_dtls_transport = transport_controller_->CreateDtlsTransport(
5281 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
5282 }
5283
5284 cricket::VoiceChannel* voice_channel = channel_manager()->CreateVoiceChannel(
5285 call_.get(), configuration_.media_config, rtp_dtls_transport,
Steve Antoneda6ccd2017-12-04 10:21:55 -08005286 rtcp_dtls_transport, signaling_thread(), mid, SrtpRequired(),
5287 audio_options_);
Steve Anton75737c02017-11-06 10:37:17 -08005288 if (!voice_channel) {
5289 transport_controller_->DestroyDtlsTransport(
5290 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5291 if (rtcp_dtls_transport) {
5292 transport_controller_->DestroyDtlsTransport(
5293 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
5294 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005295 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08005296 }
Steve Anton75737c02017-11-06 10:37:17 -08005297 voice_channel->SignalRtcpMuxFullyActive.connect(
5298 this, &PeerConnection::DestroyRtcpTransport_n);
5299 voice_channel->SignalDtlsSrtpSetupFailure.connect(
5300 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08005301 voice_channel->SignalSentPacket.connect(this,
5302 &PeerConnection::OnSentPacket_w);
Steve Anton4171afb2017-11-20 10:20:22 -08005303
Steve Antoneda6ccd2017-12-04 10:21:55 -08005304 return voice_channel;
Steve Anton75737c02017-11-06 10:37:17 -08005305}
5306
Steve Anton4171afb2017-11-20 10:20:22 -08005307// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08005308cricket::VideoChannel* PeerConnection::CreateVideoChannel(
5309 const std::string& mid,
5310 const std::string& transport_name) {
Steve Anton75737c02017-11-06 10:37:17 -08005311 cricket::DtlsTransportInternal* rtp_dtls_transport =
5312 transport_controller_->CreateDtlsTransport(
5313 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5314 cricket::DtlsTransportInternal* rtcp_dtls_transport = nullptr;
5315 if (configuration_.rtcp_mux_policy !=
5316 PeerConnectionInterface::kRtcpMuxPolicyRequire) {
5317 rtcp_dtls_transport = transport_controller_->CreateDtlsTransport(
5318 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
5319 }
5320
5321 cricket::VideoChannel* video_channel = channel_manager()->CreateVideoChannel(
5322 call_.get(), configuration_.media_config, rtp_dtls_transport,
Steve Antoneda6ccd2017-12-04 10:21:55 -08005323 rtcp_dtls_transport, signaling_thread(), mid, SrtpRequired(),
5324 video_options_);
Steve Anton75737c02017-11-06 10:37:17 -08005325
5326 if (!video_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 video_channel->SignalRtcpMuxFullyActive.connect(
5336 this, &PeerConnection::DestroyRtcpTransport_n);
5337 video_channel->SignalDtlsSrtpSetupFailure.connect(
5338 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08005339 video_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 video_channel;
Steve Anton75737c02017-11-06 10:37:17 -08005343}
5344
Steve Antoneda6ccd2017-12-04 10:21:55 -08005345bool PeerConnection::CreateDataChannel(const std::string& mid,
5346 const std::string& transport_name) {
Steve Anton75737c02017-11-06 10:37:17 -08005347 bool sctp = (data_channel_type_ == cricket::DCT_SCTP);
5348 if (sctp) {
5349 if (!sctp_factory_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005350 RTC_LOG(LS_ERROR)
Steve Anton75737c02017-11-06 10:37:17 -08005351 << "Trying to create SCTP transport, but didn't compile with "
5352 "SCTP support (HAVE_SCTP)";
5353 return false;
5354 }
5355 if (!network_thread()->Invoke<bool>(
5356 RTC_FROM_HERE, rtc::Bind(&PeerConnection::CreateSctpTransport_n,
Steve Antoneda6ccd2017-12-04 10:21:55 -08005357 this, mid, transport_name))) {
Steve Anton75737c02017-11-06 10:37:17 -08005358 return false;
5359 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005360 for (const auto& channel : sctp_data_channels_) {
5361 channel->OnTransportChannelCreated();
5362 }
Steve Anton75737c02017-11-06 10:37:17 -08005363 } else {
Steve Anton75737c02017-11-06 10:37:17 -08005364 cricket::DtlsTransportInternal* rtp_dtls_transport =
5365 transport_controller_->CreateDtlsTransport(
5366 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5367 cricket::DtlsTransportInternal* rtcp_dtls_transport = nullptr;
5368 if (configuration_.rtcp_mux_policy !=
5369 PeerConnectionInterface::kRtcpMuxPolicyRequire) {
5370 rtcp_dtls_transport = transport_controller_->CreateDtlsTransport(
5371 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
5372 }
5373
5374 rtp_data_channel_ = channel_manager()->CreateRtpDataChannel(
5375 configuration_.media_config, rtp_dtls_transport, rtcp_dtls_transport,
Steve Antoneda6ccd2017-12-04 10:21:55 -08005376 signaling_thread(), mid, SrtpRequired());
Steve Anton75737c02017-11-06 10:37:17 -08005377
5378 if (!rtp_data_channel_) {
5379 transport_controller_->DestroyDtlsTransport(
5380 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5381 if (rtcp_dtls_transport) {
5382 transport_controller_->DestroyDtlsTransport(
5383 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
5384 }
5385 return false;
5386 }
5387
5388 rtp_data_channel_->SignalRtcpMuxFullyActive.connect(
5389 this, &PeerConnection::DestroyRtcpTransport_n);
5390 rtp_data_channel_->SignalDtlsSrtpSetupFailure.connect(
5391 this, &PeerConnection::OnDtlsSrtpSetupFailure);
5392 rtp_data_channel_->SignalSentPacket.connect(
5393 this, &PeerConnection::OnSentPacket_w);
5394 }
5395
Steve Anton75737c02017-11-06 10:37:17 -08005396 return true;
5397}
5398
5399Call::Stats PeerConnection::GetCallStats() {
5400 if (!worker_thread()->IsCurrent()) {
5401 return worker_thread()->Invoke<Call::Stats>(
5402 RTC_FROM_HERE, rtc::Bind(&PeerConnection::GetCallStats, this));
5403 }
5404 if (call_) {
5405 return call_->GetStats();
5406 } else {
5407 return Call::Stats();
5408 }
5409}
5410
Steve Anton75737c02017-11-06 10:37:17 -08005411bool PeerConnection::CreateSctpTransport_n(const std::string& content_name,
5412 const std::string& transport_name) {
5413 RTC_DCHECK(network_thread()->IsCurrent());
5414 RTC_DCHECK(sctp_factory_);
5415 cricket::DtlsTransportInternal* tc =
5416 transport_controller_->CreateDtlsTransport_n(
5417 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5418 sctp_transport_ = sctp_factory_->CreateSctpTransport(tc);
5419 RTC_DCHECK(sctp_transport_);
5420 sctp_invoker_.reset(new rtc::AsyncInvoker());
5421 sctp_transport_->SignalReadyToSendData.connect(
5422 this, &PeerConnection::OnSctpTransportReadyToSendData_n);
5423 sctp_transport_->SignalDataReceived.connect(
5424 this, &PeerConnection::OnSctpTransportDataReceived_n);
5425 sctp_transport_->SignalStreamClosedRemotely.connect(
5426 this, &PeerConnection::OnSctpStreamClosedRemotely_n);
Oskar Sundbom9b28a032017-11-16 10:53:30 +01005427 sctp_transport_name_ = transport_name;
5428 sctp_content_name_ = content_name;
Steve Anton75737c02017-11-06 10:37:17 -08005429 return true;
5430}
5431
5432void PeerConnection::ChangeSctpTransport_n(const std::string& transport_name) {
5433 RTC_DCHECK(network_thread()->IsCurrent());
5434 RTC_DCHECK(sctp_transport_);
5435 RTC_DCHECK(sctp_transport_name_);
5436 std::string old_sctp_transport_name = *sctp_transport_name_;
Oskar Sundbom9b28a032017-11-16 10:53:30 +01005437 sctp_transport_name_ = transport_name;
Steve Anton75737c02017-11-06 10:37:17 -08005438 cricket::DtlsTransportInternal* tc =
5439 transport_controller_->CreateDtlsTransport_n(
5440 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5441 sctp_transport_->SetTransportChannel(tc);
5442 transport_controller_->DestroyDtlsTransport_n(
5443 old_sctp_transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5444}
5445
5446void PeerConnection::DestroySctpTransport_n() {
5447 RTC_DCHECK(network_thread()->IsCurrent());
5448 sctp_transport_.reset(nullptr);
Taylor Brandstetter389a97c2018-01-03 16:26:06 -08005449 transport_controller_->DestroyDtlsTransport_n(
5450 *sctp_transport_name_, cricket::ICE_CANDIDATE_COMPONENT_RTP);
Steve Anton75737c02017-11-06 10:37:17 -08005451 sctp_content_name_.reset();
5452 sctp_transport_name_.reset();
5453 sctp_invoker_.reset(nullptr);
5454 sctp_ready_to_send_data_ = false;
5455}
5456
5457void PeerConnection::OnSctpTransportReadyToSendData_n() {
5458 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5459 RTC_DCHECK(network_thread()->IsCurrent());
5460 // Note: Cannot use rtc::Bind here because it will grab a reference to
5461 // PeerConnection and potentially cause PeerConnection to live longer than
5462 // expected. It is safe not to grab a reference since the sctp_invoker_ will
5463 // be destroyed before PeerConnection is destroyed, and at that point all
5464 // pending tasks will be cleared.
5465 sctp_invoker_->AsyncInvoke<void>(RTC_FROM_HERE, signaling_thread(), [this] {
5466 OnSctpTransportReadyToSendData_s(true);
5467 });
5468}
5469
5470void PeerConnection::OnSctpTransportReadyToSendData_s(bool ready) {
5471 RTC_DCHECK(signaling_thread()->IsCurrent());
5472 sctp_ready_to_send_data_ = ready;
5473 SignalSctpReadyToSendData(ready);
5474}
5475
5476void PeerConnection::OnSctpTransportDataReceived_n(
5477 const cricket::ReceiveDataParams& params,
5478 const rtc::CopyOnWriteBuffer& payload) {
5479 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5480 RTC_DCHECK(network_thread()->IsCurrent());
5481 // Note: Cannot use rtc::Bind here because it will grab a reference to
5482 // PeerConnection and potentially cause PeerConnection to live longer than
5483 // expected. It is safe not to grab a reference since the sctp_invoker_ will
5484 // be destroyed before PeerConnection is destroyed, and at that point all
5485 // pending tasks will be cleared.
5486 sctp_invoker_->AsyncInvoke<void>(
5487 RTC_FROM_HERE, signaling_thread(), [this, params, payload] {
5488 OnSctpTransportDataReceived_s(params, payload);
5489 });
5490}
5491
5492void PeerConnection::OnSctpTransportDataReceived_s(
5493 const cricket::ReceiveDataParams& params,
5494 const rtc::CopyOnWriteBuffer& payload) {
5495 RTC_DCHECK(signaling_thread()->IsCurrent());
5496 if (params.type == cricket::DMT_CONTROL && IsOpenMessage(payload)) {
5497 // Received OPEN message; parse and signal that a new data channel should
5498 // be created.
5499 std::string label;
5500 InternalDataChannelInit config;
5501 config.id = params.ssrc;
5502 if (!ParseDataChannelOpenMessage(payload, &label, &config)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005503 RTC_LOG(LS_WARNING) << "Failed to parse the OPEN message for sid "
5504 << params.ssrc;
Steve Anton75737c02017-11-06 10:37:17 -08005505 return;
5506 }
5507 config.open_handshake_role = InternalDataChannelInit::kAcker;
5508 OnDataChannelOpenMessage(label, config);
5509 } else {
5510 // Otherwise just forward the signal.
5511 SignalSctpDataReceived(params, payload);
5512 }
5513}
5514
5515void PeerConnection::OnSctpStreamClosedRemotely_n(int sid) {
5516 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5517 RTC_DCHECK(network_thread()->IsCurrent());
5518 sctp_invoker_->AsyncInvoke<void>(
5519 RTC_FROM_HERE, signaling_thread(),
5520 rtc::Bind(&sigslot::signal1<int>::operator(),
5521 &SignalSctpStreamClosedRemotely, sid));
5522}
5523
5524// Returns false if bundle is enabled and rtcp_mux is disabled.
5525bool PeerConnection::ValidateBundleSettings(const SessionDescription* desc) {
5526 bool bundle_enabled = desc->HasGroup(cricket::GROUP_TYPE_BUNDLE);
5527 if (!bundle_enabled)
5528 return true;
5529
5530 const cricket::ContentGroup* bundle_group =
5531 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
5532 RTC_DCHECK(bundle_group != NULL);
5533
5534 const cricket::ContentInfos& contents = desc->contents();
5535 for (cricket::ContentInfos::const_iterator citer = contents.begin();
5536 citer != contents.end(); ++citer) {
5537 const cricket::ContentInfo* content = (&*citer);
5538 RTC_DCHECK(content != NULL);
5539 if (bundle_group->HasContentName(content->name) && !content->rejected &&
Steve Anton5adfafd2017-12-20 16:34:00 -08005540 content->type == MediaProtocolType::kRtp) {
Steve Anton75737c02017-11-06 10:37:17 -08005541 if (!HasRtcpMuxEnabled(content))
5542 return false;
5543 }
5544 }
5545 // RTCP-MUX is enabled in all the contents.
5546 return true;
5547}
5548
5549bool PeerConnection::HasRtcpMuxEnabled(const cricket::ContentInfo* content) {
Steve Antonb1c1de12017-12-21 15:14:30 -08005550 return content->media_description()->rtcp_mux();
Steve Anton75737c02017-11-06 10:37:17 -08005551}
5552
Steve Anton8a006912017-12-04 15:25:56 -08005553RTCError PeerConnection::ValidateSessionDescription(
Steve Anton75737c02017-11-06 10:37:17 -08005554 const SessionDescriptionInterface* sdesc,
Steve Anton8a006912017-12-04 15:25:56 -08005555 cricket::ContentSource source) {
Steve Antonf8470812017-12-04 10:46:21 -08005556 if (session_error() != SessionError::kNone) {
Steve Anton8a006912017-12-04 15:25:56 -08005557 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
Steve Anton75737c02017-11-06 10:37:17 -08005558 }
5559
5560 if (!sdesc || !sdesc->description()) {
Steve Anton8a006912017-12-04 15:25:56 -08005561 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidSdp);
Steve Anton75737c02017-11-06 10:37:17 -08005562 }
5563
Steve Anton3828c062017-12-06 10:34:51 -08005564 SdpType type = sdesc->GetType();
5565 if ((source == cricket::CS_LOCAL && !ExpectSetLocalDescription(type)) ||
5566 (source == cricket::CS_REMOTE && !ExpectSetRemoteDescription(type))) {
Steve Anton8a006912017-12-04 15:25:56 -08005567 LOG_AND_RETURN_ERROR(
5568 RTCErrorType::INVALID_PARAMETER,
5569 "Called in wrong state: " + GetSignalingStateString(signaling_state()));
Steve Anton75737c02017-11-06 10:37:17 -08005570 }
5571
5572 // Verify crypto settings.
5573 std::string crypto_error;
Steve Anton8a006912017-12-04 15:25:56 -08005574 if (webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED ||
5575 dtls_enabled_) {
Harald Alvestrand194939b2018-01-24 16:04:13 +01005576 RTCError crypto_error =
5577 VerifyCrypto(sdesc->description(), dtls_enabled_, uma_observer_);
Steve Anton8a006912017-12-04 15:25:56 -08005578 if (!crypto_error.ok()) {
5579 return crypto_error;
5580 }
Steve Anton75737c02017-11-06 10:37:17 -08005581 }
5582
5583 // Verify ice-ufrag and ice-pwd.
5584 if (!VerifyIceUfragPwdPresent(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08005585 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5586 kSdpWithoutIceUfragPwd);
Steve Anton75737c02017-11-06 10:37:17 -08005587 }
5588
5589 if (!ValidateBundleSettings(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08005590 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5591 kBundleWithoutRtcpMux);
Steve Anton75737c02017-11-06 10:37:17 -08005592 }
5593
5594 // TODO(skvlad): When the local rtcp-mux policy is Require, reject any
5595 // m-lines that do not rtcp-mux enabled.
5596
5597 // Verify m-lines in Answer when compared against Offer.
Steve Anton3828c062017-12-06 10:34:51 -08005598 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Seth Hampsonae8a90a2018-02-13 15:33:48 -08005599 // With an answer we want to compare the new answer session description with
5600 // the offer's session description from the current negotiation.
Steve Anton75737c02017-11-06 10:37:17 -08005601 const cricket::SessionDescription* offer_desc =
5602 (source == cricket::CS_LOCAL) ? remote_description()->description()
5603 : local_description()->description();
Seth Hampsonae8a90a2018-02-13 15:33:48 -08005604 if (!MediaSectionsHaveSameCount(*offer_desc, *sdesc->description()) ||
5605 !MediaSectionsInSameOrder(*offer_desc, nullptr, *sdesc->description(),
5606 type)) {
Steve Anton8a006912017-12-04 15:25:56 -08005607 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5608 kMlineMismatchInAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08005609 }
5610 } else {
Steve Anton75737c02017-11-06 10:37:17 -08005611 // The re-offers should respect the order of m= sections in current
5612 // description. See RFC3264 Section 8 paragraph 4 for more details.
Seth Hampsonae8a90a2018-02-13 15:33:48 -08005613 // With a re-offer, either the current local or current remote descriptions
5614 // could be the most up to date, so we would like to check against both of
5615 // them if they exist. It could be the case that one of them has a 0 port
5616 // for a media section, but the other does not. This is important to check
5617 // against in the case that we are recycling an m= section.
5618 const cricket::SessionDescription* current_desc = nullptr;
5619 const cricket::SessionDescription* secondary_current_desc = nullptr;
5620 if (local_description()) {
5621 current_desc = local_description()->description();
5622 if (remote_description()) {
5623 secondary_current_desc = remote_description()->description();
5624 }
5625 } else if (remote_description()) {
5626 current_desc = remote_description()->description();
5627 }
Steve Anton75737c02017-11-06 10:37:17 -08005628 if (current_desc &&
Seth Hampsonae8a90a2018-02-13 15:33:48 -08005629 !MediaSectionsInSameOrder(*current_desc, secondary_current_desc,
5630 *sdesc->description(), type)) {
Steve Anton8a006912017-12-04 15:25:56 -08005631 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5632 kMlineMismatchInSubsequentOffer);
Steve Anton75737c02017-11-06 10:37:17 -08005633 }
5634 }
5635
Steve Anton8a006912017-12-04 15:25:56 -08005636 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08005637}
5638
Steve Anton3828c062017-12-06 10:34:51 -08005639bool PeerConnection::ExpectSetLocalDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08005640 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08005641 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08005642 return (state == PeerConnectionInterface::kStable) ||
5643 (state == PeerConnectionInterface::kHaveLocalOffer);
Steve Anton20393062017-12-04 16:24:52 -08005644 } else {
Steve Anton3828c062017-12-06 10:34:51 -08005645 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08005646 return (state == PeerConnectionInterface::kHaveRemoteOffer) ||
5647 (state == PeerConnectionInterface::kHaveLocalPrAnswer);
5648 }
5649}
5650
Steve Anton3828c062017-12-06 10:34:51 -08005651bool PeerConnection::ExpectSetRemoteDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08005652 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08005653 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08005654 return (state == PeerConnectionInterface::kStable) ||
5655 (state == PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton20393062017-12-04 16:24:52 -08005656 } else {
Steve Anton3828c062017-12-06 10:34:51 -08005657 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08005658 return (state == PeerConnectionInterface::kHaveLocalOffer) ||
5659 (state == PeerConnectionInterface::kHaveRemotePrAnswer);
5660 }
5661}
5662
Steve Antonf8470812017-12-04 10:46:21 -08005663const char* PeerConnection::SessionErrorToString(SessionError error) const {
5664 switch (error) {
5665 case SessionError::kNone:
5666 return "ERROR_NONE";
5667 case SessionError::kContent:
5668 return "ERROR_CONTENT";
5669 case SessionError::kTransport:
5670 return "ERROR_TRANSPORT";
5671 }
5672 RTC_NOTREACHED();
5673 return "";
5674}
5675
Steve Anton75737c02017-11-06 10:37:17 -08005676std::string PeerConnection::GetSessionErrorMsg() {
5677 std::ostringstream desc;
Steve Antonf8470812017-12-04 10:46:21 -08005678 desc << kSessionError << SessionErrorToString(session_error()) << ". ";
5679 desc << kSessionErrorDesc << session_error_desc() << ".";
Steve Anton75737c02017-11-06 10:37:17 -08005680 return desc.str();
5681}
5682
5683// We need to check the local/remote description for the Transport instead of
5684// the session, because a new Transport added during renegotiation may have
5685// them unset while the session has them set from the previous negotiation.
5686// Not doing so may trigger the auto generation of transport description and
5687// mess up DTLS identity information, ICE credential, etc.
5688bool PeerConnection::ReadyToUseRemoteCandidate(
5689 const IceCandidateInterface* candidate,
5690 const SessionDescriptionInterface* remote_desc,
5691 bool* valid) {
5692 *valid = true;
5693
5694 const SessionDescriptionInterface* current_remote_desc =
5695 remote_desc ? remote_desc : remote_description();
5696
5697 if (!current_remote_desc) {
5698 return false;
5699 }
5700
5701 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
5702 size_t remote_content_size =
5703 current_remote_desc->description()->contents().size();
5704 if (mediacontent_index >= remote_content_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005705 RTC_LOG(LS_ERROR)
5706 << "ReadyToUseRemoteCandidate: Invalid candidate media index "
5707 << mediacontent_index;
Steve Anton75737c02017-11-06 10:37:17 -08005708
5709 *valid = false;
5710 return false;
5711 }
5712
5713 cricket::ContentInfo content =
5714 current_remote_desc->description()->contents()[mediacontent_index];
5715
5716 const std::string transport_name = GetTransportName(content.name);
5717 if (transport_name.empty()) {
5718 return false;
5719 }
5720 return transport_controller_->ReadyForRemoteCandidates(transport_name);
5721}
5722
5723bool PeerConnection::SrtpRequired() const {
5724 return dtls_enabled_ ||
5725 webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED;
5726}
5727
5728void PeerConnection::OnTransportControllerGatheringState(
5729 cricket::IceGatheringState state) {
5730 RTC_DCHECK(signaling_thread()->IsCurrent());
5731 if (state == cricket::kIceGatheringGathering) {
5732 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringGathering);
5733 } else if (state == cricket::kIceGatheringComplete) {
5734 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringComplete);
5735 }
5736}
5737
5738void PeerConnection::ReportTransportStats() {
Steve Antonc7b964c2018-02-01 14:39:45 -08005739 std::map<std::string, std::set<cricket::MediaType>>
5740 media_types_by_transport_name;
5741 for (auto transceiver : transceivers_) {
5742 if (transceiver->internal()->channel()) {
5743 const std::string& transport_name =
5744 transceiver->internal()->channel()->transport_name();
5745 media_types_by_transport_name[transport_name].insert(
Steve Anton69470252018-02-09 11:43:08 -08005746 transceiver->media_type());
Steve Antonc7b964c2018-02-01 14:39:45 -08005747 }
Steve Anton75737c02017-11-06 10:37:17 -08005748 }
5749 if (rtp_data_channel()) {
Steve Antonc7b964c2018-02-01 14:39:45 -08005750 media_types_by_transport_name[rtp_data_channel()->transport_name()].insert(
5751 cricket::MEDIA_TYPE_DATA);
Steve Anton75737c02017-11-06 10:37:17 -08005752 }
5753 if (sctp_transport_name_) {
Steve Antonc7b964c2018-02-01 14:39:45 -08005754 media_types_by_transport_name[*sctp_transport_name_].insert(
5755 cricket::MEDIA_TYPE_DATA);
Steve Anton75737c02017-11-06 10:37:17 -08005756 }
Steve Antonc7b964c2018-02-01 14:39:45 -08005757 for (const auto& entry : media_types_by_transport_name) {
5758 const std::string& transport_name = entry.first;
5759 const std::set<cricket::MediaType> media_types = entry.second;
Steve Anton75737c02017-11-06 10:37:17 -08005760 cricket::TransportStats stats;
Steve Antonc7b964c2018-02-01 14:39:45 -08005761 if (transport_controller_->GetStats(transport_name, &stats)) {
Steve Anton75737c02017-11-06 10:37:17 -08005762 ReportBestConnectionState(stats);
Steve Antonc7b964c2018-02-01 14:39:45 -08005763 ReportNegotiatedCiphers(stats, media_types);
Steve Anton75737c02017-11-06 10:37:17 -08005764 }
5765 }
5766}
5767// Walk through the ConnectionInfos to gather best connection usage
5768// for IPv4 and IPv6.
5769void PeerConnection::ReportBestConnectionState(
5770 const cricket::TransportStats& stats) {
5771 RTC_DCHECK(metrics_observer());
Steve Antonc7b964c2018-02-01 14:39:45 -08005772 for (const cricket::TransportChannelStats& channel_stats :
5773 stats.channel_stats) {
5774 for (const cricket::ConnectionInfo& connection_info :
5775 channel_stats.connection_infos) {
5776 if (!connection_info.best_connection) {
Steve Anton75737c02017-11-06 10:37:17 -08005777 continue;
5778 }
5779
5780 PeerConnectionEnumCounterType type = kPeerConnectionEnumCounterMax;
Steve Antonc7b964c2018-02-01 14:39:45 -08005781 const cricket::Candidate& local = connection_info.local_candidate;
5782 const cricket::Candidate& remote = connection_info.remote_candidate;
Steve Anton75737c02017-11-06 10:37:17 -08005783
5784 // Increment the counter for IceCandidatePairType.
5785 if (local.protocol() == cricket::TCP_PROTOCOL_NAME ||
5786 (local.type() == RELAY_PORT_TYPE &&
5787 local.relay_protocol() == cricket::TCP_PROTOCOL_NAME)) {
5788 type = kEnumCounterIceCandidatePairTypeTcp;
5789 } else if (local.protocol() == cricket::UDP_PROTOCOL_NAME) {
5790 type = kEnumCounterIceCandidatePairTypeUdp;
5791 } else {
5792 RTC_CHECK(0);
5793 }
5794 metrics_observer()->IncrementEnumCounter(
5795 type, GetIceCandidatePairCounter(local, remote),
5796 kIceCandidatePairMax);
5797
5798 // Increment the counter for IP type.
5799 if (local.address().family() == AF_INET) {
5800 metrics_observer()->IncrementEnumCounter(
5801 kEnumCounterAddressFamily, kBestConnections_IPv4,
5802 kPeerConnectionAddressFamilyCounter_Max);
5803
5804 } else if (local.address().family() == AF_INET6) {
5805 metrics_observer()->IncrementEnumCounter(
5806 kEnumCounterAddressFamily, kBestConnections_IPv6,
5807 kPeerConnectionAddressFamilyCounter_Max);
5808 } else {
5809 RTC_CHECK(0);
5810 }
5811
5812 return;
5813 }
5814 }
5815}
5816
5817void PeerConnection::ReportNegotiatedCiphers(
Steve Antonc7b964c2018-02-01 14:39:45 -08005818 const cricket::TransportStats& stats,
5819 const std::set<cricket::MediaType>& media_types) {
Steve Anton75737c02017-11-06 10:37:17 -08005820 RTC_DCHECK(metrics_observer());
5821 if (!dtls_enabled_ || stats.channel_stats.empty()) {
5822 return;
5823 }
5824
5825 int srtp_crypto_suite = stats.channel_stats[0].srtp_crypto_suite;
5826 int ssl_cipher_suite = stats.channel_stats[0].ssl_cipher_suite;
5827 if (srtp_crypto_suite == rtc::SRTP_INVALID_CRYPTO_SUITE &&
5828 ssl_cipher_suite == rtc::TLS_NULL_WITH_NULL_NULL) {
5829 return;
5830 }
5831
Steve Antonc7b964c2018-02-01 14:39:45 -08005832 for (cricket::MediaType media_type : media_types) {
5833 PeerConnectionEnumCounterType srtp_counter_type;
5834 PeerConnectionEnumCounterType ssl_counter_type;
5835 switch (media_type) {
5836 case cricket::MEDIA_TYPE_AUDIO:
5837 srtp_counter_type = kEnumCounterAudioSrtpCipher;
5838 ssl_counter_type = kEnumCounterAudioSslCipher;
5839 break;
5840 case cricket::MEDIA_TYPE_VIDEO:
5841 srtp_counter_type = kEnumCounterVideoSrtpCipher;
5842 ssl_counter_type = kEnumCounterVideoSslCipher;
5843 break;
5844 case cricket::MEDIA_TYPE_DATA:
5845 srtp_counter_type = kEnumCounterDataSrtpCipher;
5846 ssl_counter_type = kEnumCounterDataSslCipher;
5847 break;
5848 default:
5849 RTC_NOTREACHED();
5850 continue;
5851 }
5852 if (srtp_crypto_suite != rtc::SRTP_INVALID_CRYPTO_SUITE) {
5853 metrics_observer()->IncrementSparseEnumCounter(srtp_counter_type,
5854 srtp_crypto_suite);
5855 }
5856 if (ssl_cipher_suite != rtc::TLS_NULL_WITH_NULL_NULL) {
5857 metrics_observer()->IncrementSparseEnumCounter(ssl_counter_type,
5858 ssl_cipher_suite);
5859 }
Steve Anton75737c02017-11-06 10:37:17 -08005860 }
5861}
5862
5863void PeerConnection::OnSentPacket_w(const rtc::SentPacket& sent_packet) {
5864 RTC_DCHECK(worker_thread()->IsCurrent());
5865 RTC_DCHECK(call_);
5866 call_->OnSentPacket(sent_packet);
5867}
5868
5869const std::string PeerConnection::GetTransportName(
5870 const std::string& content_name) {
5871 cricket::BaseChannel* channel = GetChannel(content_name);
Steve Anton6fec8802017-12-04 10:37:29 -08005872 if (channel) {
5873 return channel->transport_name();
Steve Anton75737c02017-11-06 10:37:17 -08005874 }
Steve Anton6fec8802017-12-04 10:37:29 -08005875 if (sctp_transport_) {
5876 RTC_DCHECK(sctp_content_name_);
5877 RTC_DCHECK(sctp_transport_name_);
5878 if (content_name == *sctp_content_name_) {
5879 return *sctp_transport_name_;
5880 }
5881 }
5882 // Return an empty string if failed to retrieve the transport name.
5883 return "";
Steve Anton75737c02017-11-06 10:37:17 -08005884}
5885
5886void PeerConnection::DestroyRtcpTransport_n(const std::string& transport_name) {
5887 RTC_DCHECK(network_thread()->IsCurrent());
5888 transport_controller_->DestroyDtlsTransport_n(
5889 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
5890}
5891
Steve Anton6fec8802017-12-04 10:37:29 -08005892void PeerConnection::DestroyTransceiverChannel(
5893 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
5894 transceiver) {
5895 RTC_DCHECK(transceiver);
Steve Anton75737c02017-11-06 10:37:17 -08005896
Steve Anton6fec8802017-12-04 10:37:29 -08005897 cricket::BaseChannel* channel = transceiver->internal()->channel();
5898 if (channel) {
5899 transceiver->internal()->SetChannel(nullptr);
5900 DestroyBaseChannel(channel);
Steve Anton75737c02017-11-06 10:37:17 -08005901 }
5902}
5903
5904void PeerConnection::DestroyDataChannel() {
Steve Anton6fec8802017-12-04 10:37:29 -08005905 if (rtp_data_channel_) {
5906 OnDataChannelDestroyed();
5907 DestroyBaseChannel(rtp_data_channel_);
5908 rtp_data_channel_ = nullptr;
5909 }
5910
5911 // Note: Cannot use rtc::Bind to create a functor to invoke because it will
5912 // grab a reference to this PeerConnection. If this is called from the
5913 // PeerConnection destructor, the RefCountedObject vtable will have already
5914 // been destroyed (since it is a subclass of PeerConnection) and using
5915 // rtc::Bind will cause "Pure virtual function called" error to appear.
5916
5917 if (sctp_transport_) {
5918 OnDataChannelDestroyed();
5919 network_thread()->Invoke<void>(RTC_FROM_HERE,
5920 [this] { DestroySctpTransport_n(); });
5921 }
5922}
5923
5924void PeerConnection::DestroyBaseChannel(cricket::BaseChannel* channel) {
5925 RTC_DCHECK(channel);
5926 RTC_DCHECK(channel->rtp_dtls_transport());
5927
5928 // Need to cache these before destroying the base channel so that we do not
5929 // access uninitialized memory.
5930 const std::string transport_name =
5931 channel->rtp_dtls_transport()->transport_name();
5932 const bool need_to_delete_rtcp = (channel->rtcp_dtls_transport() != nullptr);
5933
5934 switch (channel->media_type()) {
5935 case cricket::MEDIA_TYPE_AUDIO:
5936 channel_manager()->DestroyVoiceChannel(
5937 static_cast<cricket::VoiceChannel*>(channel));
5938 break;
5939 case cricket::MEDIA_TYPE_VIDEO:
5940 channel_manager()->DestroyVideoChannel(
5941 static_cast<cricket::VideoChannel*>(channel));
5942 break;
5943 case cricket::MEDIA_TYPE_DATA:
5944 channel_manager()->DestroyRtpDataChannel(
5945 static_cast<cricket::RtpDataChannel*>(channel));
5946 break;
5947 default:
5948 RTC_NOTREACHED() << "Unknown media type: " << channel->media_type();
5949 break;
5950 }
5951
5952 // |channel| can no longer be used.
5953
Steve Anton75737c02017-11-06 10:37:17 -08005954 transport_controller_->DestroyDtlsTransport(
5955 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5956 if (need_to_delete_rtcp) {
5957 transport_controller_->DestroyDtlsTransport(
5958 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
5959 }
5960}
5961
Harald Alvestrand89061872018-01-02 14:08:34 +01005962void PeerConnection::ClearStatsCache() {
5963 if (stats_collector_) {
5964 stats_collector_->ClearCachedStatsReport();
5965 }
5966}
5967
henrike@webrtc.org28e20752013-07-10 00:45:36 +00005968} // namespace webrtc