blob: 4f5bd8e75f182d071980ab3a0650dd3c4e8fcc70 [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
564} // namespace
565
Henrik Boström31638672017-11-23 17:48:32 +0100566// Upon completion, posts a task to execute the callback of the
567// SetSessionDescriptionObserver asynchronously on the same thread. At this
568// point, the state of the peer connection might no longer reflect the effects
569// of the SetRemoteDescription operation, as the peer connection could have been
570// modified during the post.
571// TODO(hbos): Remove this class once we remove the version of
572// PeerConnectionInterface::SetRemoteDescription() that takes a
573// SetSessionDescriptionObserver as an argument.
574class PeerConnection::SetRemoteDescriptionObserverAdapter
575 : public rtc::RefCountedObject<SetRemoteDescriptionObserverInterface> {
576 public:
577 SetRemoteDescriptionObserverAdapter(
578 rtc::scoped_refptr<PeerConnection> pc,
579 rtc::scoped_refptr<SetSessionDescriptionObserver> wrapper)
580 : pc_(std::move(pc)), wrapper_(std::move(wrapper)) {}
581
582 // SetRemoteDescriptionObserverInterface implementation.
583 void OnSetRemoteDescriptionComplete(RTCError error) override {
584 if (error.ok())
585 pc_->PostSetSessionDescriptionSuccess(wrapper_);
586 else
587 pc_->PostSetSessionDescriptionFailure(wrapper_, error.message());
588 }
589
590 private:
591 rtc::scoped_refptr<PeerConnection> pc_;
592 rtc::scoped_refptr<SetSessionDescriptionObserver> wrapper_;
593};
594
deadbeef293e9262017-01-11 12:28:30 -0800595bool PeerConnectionInterface::RTCConfiguration::operator==(
596 const PeerConnectionInterface::RTCConfiguration& o) const {
597 // This static_assert prevents us from accidentally breaking operator==.
Steve Anton300bf8e2017-07-14 10:13:10 -0700598 // Note: Order matters! Fields must be ordered the same as RTCConfiguration.
deadbeef293e9262017-01-11 12:28:30 -0800599 struct stuff_being_tested_for_equality {
Magnus Jedvert3beb2072017-07-14 14:23:56 +0000600 IceServers servers;
Steve Anton300bf8e2017-07-14 10:13:10 -0700601 IceTransportsType type;
deadbeef293e9262017-01-11 12:28:30 -0800602 BundlePolicy bundle_policy;
603 RtcpMuxPolicy rtcp_mux_policy;
Steve Anton300bf8e2017-07-14 10:13:10 -0700604 std::vector<rtc::scoped_refptr<rtc::RTCCertificate>> certificates;
605 int ice_candidate_pool_size;
606 bool disable_ipv6;
607 bool disable_ipv6_on_wifi;
deadbeefd21eab32017-07-26 16:50:11 -0700608 int max_ipv6_networks;
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +0100609 bool disable_link_local_networks;
Steve Anton300bf8e2017-07-14 10:13:10 -0700610 bool enable_rtp_data_channel;
611 rtc::Optional<int> screencast_min_bitrate;
612 rtc::Optional<bool> combined_audio_video_bwe;
613 rtc::Optional<bool> enable_dtls_srtp;
deadbeef293e9262017-01-11 12:28:30 -0800614 TcpCandidatePolicy tcp_candidate_policy;
615 CandidateNetworkPolicy candidate_network_policy;
616 int audio_jitter_buffer_max_packets;
617 bool audio_jitter_buffer_fast_accelerate;
618 int ice_connection_receiving_timeout;
619 int ice_backup_candidate_pair_ping_interval;
620 ContinualGatheringPolicy continual_gathering_policy;
deadbeef293e9262017-01-11 12:28:30 -0800621 bool prioritize_most_likely_ice_candidate_pairs;
622 struct cricket::MediaConfig media_config;
deadbeef293e9262017-01-11 12:28:30 -0800623 bool prune_turn_ports;
624 bool presume_writable_when_fully_relayed;
625 bool enable_ice_renomination;
626 bool redetermine_role_on_ice_restart;
skvlad51072462017-02-02 11:50:14 -0800627 rtc::Optional<int> ice_check_min_interval;
Steve Anton300bf8e2017-07-14 10:13:10 -0700628 rtc::Optional<rtc::IntervalRange> ice_regather_interval_range;
Jonas Orelandbdcee282017-10-10 14:01:40 +0200629 webrtc::TurnCustomizer* turn_customizer;
Steve Anton79e79602017-11-20 10:25:56 -0800630 SdpSemantics sdp_semantics;
Qingsi Wang9a5c6f82018-02-01 10:38:40 -0800631 rtc::Optional<rtc::AdapterType> network_preference;
deadbeef293e9262017-01-11 12:28:30 -0800632 };
633 static_assert(sizeof(stuff_being_tested_for_equality) == sizeof(*this),
634 "Did you add something to RTCConfiguration and forget to "
635 "update operator==?");
636 return type == o.type && servers == o.servers &&
637 bundle_policy == o.bundle_policy &&
638 rtcp_mux_policy == o.rtcp_mux_policy &&
639 tcp_candidate_policy == o.tcp_candidate_policy &&
640 candidate_network_policy == o.candidate_network_policy &&
641 audio_jitter_buffer_max_packets == o.audio_jitter_buffer_max_packets &&
642 audio_jitter_buffer_fast_accelerate ==
643 o.audio_jitter_buffer_fast_accelerate &&
644 ice_connection_receiving_timeout ==
645 o.ice_connection_receiving_timeout &&
646 ice_backup_candidate_pair_ping_interval ==
647 o.ice_backup_candidate_pair_ping_interval &&
648 continual_gathering_policy == o.continual_gathering_policy &&
649 certificates == o.certificates &&
650 prioritize_most_likely_ice_candidate_pairs ==
651 o.prioritize_most_likely_ice_candidate_pairs &&
652 media_config == o.media_config && disable_ipv6 == o.disable_ipv6 &&
zhihuangb09b3f92017-03-07 14:40:51 -0800653 disable_ipv6_on_wifi == o.disable_ipv6_on_wifi &&
deadbeefd21eab32017-07-26 16:50:11 -0700654 max_ipv6_networks == o.max_ipv6_networks &&
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +0100655 disable_link_local_networks == o.disable_link_local_networks &&
deadbeef293e9262017-01-11 12:28:30 -0800656 enable_rtp_data_channel == o.enable_rtp_data_channel &&
deadbeef293e9262017-01-11 12:28:30 -0800657 screencast_min_bitrate == o.screencast_min_bitrate &&
658 combined_audio_video_bwe == o.combined_audio_video_bwe &&
659 enable_dtls_srtp == o.enable_dtls_srtp &&
660 ice_candidate_pool_size == o.ice_candidate_pool_size &&
661 prune_turn_ports == o.prune_turn_ports &&
662 presume_writable_when_fully_relayed ==
663 o.presume_writable_when_fully_relayed &&
664 enable_ice_renomination == o.enable_ice_renomination &&
skvlad51072462017-02-02 11:50:14 -0800665 redetermine_role_on_ice_restart == o.redetermine_role_on_ice_restart &&
Steve Anton300bf8e2017-07-14 10:13:10 -0700666 ice_check_min_interval == o.ice_check_min_interval &&
Jonas Orelandbdcee282017-10-10 14:01:40 +0200667 ice_regather_interval_range == o.ice_regather_interval_range &&
Steve Anton79e79602017-11-20 10:25:56 -0800668 turn_customizer == o.turn_customizer &&
Qingsi Wang9a5c6f82018-02-01 10:38:40 -0800669 sdp_semantics == o.sdp_semantics &&
670 network_preference == o.network_preference;
deadbeef293e9262017-01-11 12:28:30 -0800671}
672
673bool PeerConnectionInterface::RTCConfiguration::operator!=(
674 const PeerConnectionInterface::RTCConfiguration& o) const {
675 return !(*this == o);
deadbeef3edec7c2016-12-10 11:44:26 -0800676}
677
zhihuang8f65cdf2016-05-06 18:40:30 -0700678// Generate a RTCP CNAME when a PeerConnection is created.
679std::string GenerateRtcpCname() {
680 std::string cname;
681 if (!rtc::CreateRandomString(kRtcpCnameLength, &cname)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100682 RTC_LOG(LS_ERROR) << "Failed to generate CNAME.";
nisseeb4ca4e2017-01-12 02:24:27 -0800683 RTC_NOTREACHED();
zhihuang8f65cdf2016-05-06 18:40:30 -0700684 }
685 return cname;
686}
687
zhihuang1c378ed2017-08-17 14:10:50 -0700688bool ValidateOfferAnswerOptions(
689 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options) {
690 return IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_audio) &&
691 IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_video);
olka3c747662017-08-17 06:50:32 -0700692}
693
zhihuang1c378ed2017-08-17 14:10:50 -0700694// From |rtc_options|, fill parts of |session_options| shared by all generated
695// m= sections (in other words, nothing that involves a map/array).
696void ExtractSharedMediaSessionOptions(
697 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options,
698 cricket::MediaSessionOptions* session_options) {
699 session_options->vad_enabled = rtc_options.voice_activity_detection;
700 session_options->bundle_enabled = rtc_options.use_rtp_mux;
701}
zhihuanga77e6bb2017-08-14 18:17:48 -0700702
zhihuang1c378ed2017-08-17 14:10:50 -0700703bool ConvertConstraintsToOfferAnswerOptions(
704 const MediaConstraintsInterface* constraints,
705 PeerConnectionInterface::RTCOfferAnswerOptions* offer_answer_options) {
olka3c747662017-08-17 06:50:32 -0700706 if (!constraints) {
707 return true;
708 }
zhihuang1c378ed2017-08-17 14:10:50 -0700709
710 bool value = false;
711 size_t mandatory_constraints_satisfied = 0;
712
713 if (FindConstraint(constraints,
714 MediaConstraintsInterface::kOfferToReceiveAudio, &value,
715 &mandatory_constraints_satisfied)) {
716 offer_answer_options->offer_to_receive_audio =
717 value ? PeerConnectionInterface::RTCOfferAnswerOptions::
718 kOfferToReceiveMediaTrue
719 : 0;
720 }
721
722 if (FindConstraint(constraints,
723 MediaConstraintsInterface::kOfferToReceiveVideo, &value,
724 &mandatory_constraints_satisfied)) {
725 offer_answer_options->offer_to_receive_video =
726 value ? PeerConnectionInterface::RTCOfferAnswerOptions::
727 kOfferToReceiveMediaTrue
728 : 0;
729 }
730 if (FindConstraint(constraints,
731 MediaConstraintsInterface::kVoiceActivityDetection, &value,
732 &mandatory_constraints_satisfied)) {
733 offer_answer_options->voice_activity_detection = value;
734 }
735 if (FindConstraint(constraints, MediaConstraintsInterface::kUseRtpMux, &value,
736 &mandatory_constraints_satisfied)) {
737 offer_answer_options->use_rtp_mux = value;
738 }
739 if (FindConstraint(constraints, MediaConstraintsInterface::kIceRestart,
740 &value, &mandatory_constraints_satisfied)) {
741 offer_answer_options->ice_restart = value;
742 }
743
deadbeefab9b2d12015-10-14 11:33:11 -0700744 return mandatory_constraints_satisfied == constraints->GetMandatory().size();
745}
746
zhihuang38ede132017-06-15 12:52:32 -0700747PeerConnection::PeerConnection(PeerConnectionFactory* factory,
748 std::unique_ptr<RtcEventLog> event_log,
749 std::unique_ptr<Call> call)
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000750 : factory_(factory),
zhihuang38ede132017-06-15 12:52:32 -0700751 event_log_(std::move(event_log)),
zhihuang8f65cdf2016-05-06 18:40:30 -0700752 rtcp_cname_(GenerateRtcpCname()),
deadbeefab9b2d12015-10-14 11:33:11 -0700753 local_streams_(StreamCollection::Create()),
zhihuang38ede132017-06-15 12:52:32 -0700754 remote_streams_(StreamCollection::Create()),
755 call_(std::move(call)) {}
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000756
757PeerConnection::~PeerConnection() {
Peter Boström1a9d6152015-12-08 22:15:17 +0100758 TRACE_EVENT0("webrtc", "PeerConnection::~PeerConnection");
Steve Anton4171afb2017-11-20 10:20:22 -0800759 RTC_DCHECK_RUN_ON(signaling_thread());
760
Steve Anton8af21862017-12-15 11:20:13 -0800761 // Need to stop transceivers before destroying the stats collector because
762 // AudioRtpSender has a reference to the StatsCollector it will update when
763 // stopping.
764 for (auto transceiver : transceivers_) {
765 transceiver->Stop();
766 }
Steve Anton4171afb2017-11-20 10:20:22 -0800767
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700768 stats_.reset(nullptr);
hbosb78306a2016-12-19 05:06:57 -0800769 if (stats_collector_) {
770 stats_collector_->WaitForPendingRequest();
771 stats_collector_ = nullptr;
772 }
Steve Anton75737c02017-11-06 10:37:17 -0800773
Steve Anton8af21862017-12-15 11:20:13 -0800774 // Don't destroy BaseChannels until after stats has been cleaned up so that
775 // the last stats request can still read from the channels.
776 DestroyAllChannels();
777
Mirko Bonadei675513b2017-11-09 11:09:25 +0100778 RTC_LOG(LS_INFO) << "Session: " << session_id() << " is destroyed.";
Steve Anton75737c02017-11-06 10:37:17 -0800779
780 webrtc_session_desc_factory_.reset();
781 sctp_invoker_.reset();
782 sctp_factory_.reset();
783 transport_controller_.reset();
784
deadbeef91dd5672016-05-18 16:55:30 -0700785 // port_allocator_ lives on the network thread and should be destroyed there.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700786 network_thread()->Invoke<void>(RTC_FROM_HERE,
nisseeaabdf62017-05-05 02:23:02 -0700787 [this] { port_allocator_.reset(); });
eladalon248fd4f2017-09-06 05:18:15 -0700788 // call_ and event_log_ must be destroyed on the worker thread.
Steve Anton978b8762017-09-29 12:15:02 -0700789 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
eladalon248fd4f2017-09-06 05:18:15 -0700790 call_.reset();
Qingsi Wang93a84392018-01-30 17:13:09 -0800791 // The event log must outlive call (and any other object that uses it).
eladalon248fd4f2017-09-06 05:18:15 -0700792 event_log_.reset();
793 });
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000794}
795
Steve Anton8af21862017-12-15 11:20:13 -0800796void PeerConnection::DestroyAllChannels() {
Steve Anton3fe1b152017-12-12 10:20:08 -0800797 // Destroy video channels first since they may have a pointer to a voice
798 // channel.
799 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -0800800 if (transceiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton3fe1b152017-12-12 10:20:08 -0800801 DestroyTransceiverChannel(transceiver);
802 }
803 }
804 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -0800805 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton3fe1b152017-12-12 10:20:08 -0800806 DestroyTransceiverChannel(transceiver);
807 }
808 }
809 DestroyDataChannel();
810}
811
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000812bool PeerConnection::Initialize(
buildbot@webrtc.org41451d42014-05-03 05:39:45 +0000813 const PeerConnectionInterface::RTCConfiguration& configuration,
kwibergd1fe2812016-04-27 06:47:29 -0700814 std::unique_ptr<cricket::PortAllocator> allocator,
Henrik Boströmd03c23b2016-06-01 11:44:18 +0200815 std::unique_ptr<rtc::RTCCertificateGeneratorInterface> cert_generator,
deadbeef653b8e02015-11-11 12:55:10 -0800816 PeerConnectionObserver* observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100817 TRACE_EVENT0("webrtc", "PeerConnection::Initialize");
Steve Anton038834f2017-07-14 15:59:59 -0700818
819 RTCError config_error = ValidateConfiguration(configuration);
820 if (!config_error.ok()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100821 RTC_LOG(LS_ERROR) << "Invalid configuration: " << config_error.message();
Steve Anton038834f2017-07-14 15:59:59 -0700822 return false;
823 }
824
deadbeef293e9262017-01-11 12:28:30 -0800825 if (!allocator) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100826 RTC_LOG(LS_ERROR)
827 << "PeerConnection initialized without a PortAllocator? "
Jonas Olsson45cc8902018-02-13 10:37:07 +0100828 "This shouldn't happen if using PeerConnectionFactory.";
deadbeef293e9262017-01-11 12:28:30 -0800829 return false;
830 }
Jonas Orelandbdcee282017-10-10 14:01:40 +0200831
deadbeef653b8e02015-11-11 12:55:10 -0800832 if (!observer) {
deadbeef293e9262017-01-11 12:28:30 -0800833 // TODO(deadbeef): Why do we do this?
Mirko Bonadei675513b2017-11-09 11:09:25 +0100834 RTC_LOG(LS_ERROR) << "PeerConnection initialized without a "
Jonas Olsson45cc8902018-02-13 10:37:07 +0100835 "PeerConnectionObserver";
deadbeef653b8e02015-11-11 12:55:10 -0800836 return false;
837 }
pthatcher@webrtc.org877ac762015-02-04 22:03:09 +0000838 observer_ = observer;
kwiberg0eb15ed2015-12-17 03:04:15 -0800839 port_allocator_ = std::move(allocator);
deadbeef653b8e02015-11-11 12:55:10 -0800840
deadbeef91dd5672016-05-18 16:55:30 -0700841 // The port allocator lives on the network thread and should be initialized
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700842 // there.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700843 if (!network_thread()->Invoke<bool>(
844 RTC_FROM_HERE, rtc::Bind(&PeerConnection::InitializePortAllocator_n,
845 this, configuration))) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000846 return false;
847 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000848
Steve Anton75737c02017-11-06 10:37:17 -0800849 // RFC 3264: The numeric value of the session id and version in the
850 // o line MUST be representable with a "64 bit signed integer".
851 // Due to this constraint session id |session_id_| is max limited to
852 // LLONG_MAX.
853 session_id_ = rtc::ToString(rtc::CreateRandomId64() & LLONG_MAX);
854 transport_controller_.reset(factory_->CreateTransportController(
Qingsi Wang93a84392018-01-30 17:13:09 -0800855 port_allocator_.get(), configuration.redetermine_role_on_ice_restart,
856 event_log_.get()));
Steve Anton75737c02017-11-06 10:37:17 -0800857 transport_controller_->SetIceRole(cricket::ICEROLE_CONTROLLED);
858 transport_controller_->SignalConnectionState.connect(
859 this, &PeerConnection::OnTransportControllerConnectionState);
860 transport_controller_->SignalGatheringState.connect(
861 this, &PeerConnection::OnTransportControllerGatheringState);
862 transport_controller_->SignalCandidatesGathered.connect(
863 this, &PeerConnection::OnTransportControllerCandidatesGathered);
864 transport_controller_->SignalCandidatesRemoved.connect(
865 this, &PeerConnection::OnTransportControllerCandidatesRemoved);
866 transport_controller_->SignalDtlsHandshakeError.connect(
867 this, &PeerConnection::OnTransportControllerDtlsHandshakeError);
868
869 sctp_factory_ = factory_->CreateSctpTransportInternalFactory();
zhihuang29ff8442016-07-27 11:07:25 -0700870
deadbeefab9b2d12015-10-14 11:33:11 -0700871 stats_.reset(new StatsCollector(this));
hbos74e1a4f2016-09-15 23:33:01 -0700872 stats_collector_ = RTCStatsCollector::Create(this);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000873
Steve Antonba818672017-11-06 10:21:57 -0800874 configuration_ = configuration;
875
Steve Anton75737c02017-11-06 10:37:17 -0800876 const PeerConnectionFactoryInterface::Options& options = factory_->options();
877
878 transport_controller_->SetSslMaxProtocolVersion(options.ssl_max_version);
879
880 // Obtain a certificate from RTCConfiguration if any were provided (optional).
881 rtc::scoped_refptr<rtc::RTCCertificate> certificate;
882 if (!configuration.certificates.empty()) {
883 // TODO(hbos,torbjorng): Decide on certificate-selection strategy instead of
884 // just picking the first one. The decision should be made based on the DTLS
885 // handshake. The DTLS negotiations need to know about all certificates.
886 certificate = configuration.certificates[0];
887 }
888
Steve Antond25da372017-11-06 14:50:29 -0800889 transport_controller_->SetIceConfig(ParseIceConfig(configuration));
Steve Anton75737c02017-11-06 10:37:17 -0800890
891 if (options.disable_encryption) {
892 dtls_enabled_ = false;
893 } else {
894 // Enable DTLS by default if we have an identity store or a certificate.
895 dtls_enabled_ = (cert_generator || certificate);
896 // |configuration| can override the default |dtls_enabled_| value.
897 if (configuration.enable_dtls_srtp) {
898 dtls_enabled_ = *(configuration.enable_dtls_srtp);
899 }
900 }
901
902 // Enable creation of RTP data channels if the kEnableRtpDataChannels is set.
903 // It takes precendence over the disable_sctp_data_channels
904 // PeerConnectionFactoryInterface::Options.
905 if (configuration.enable_rtp_data_channel) {
906 data_channel_type_ = cricket::DCT_RTP;
907 } else {
908 // DTLS has to be enabled to use SCTP.
909 if (!options.disable_sctp_data_channels && dtls_enabled_) {
910 data_channel_type_ = cricket::DCT_SCTP;
911 }
912 }
913
914 video_options_.screencast_min_bitrate_kbps =
915 configuration.screencast_min_bitrate;
916 audio_options_.combined_audio_video_bwe =
917 configuration.combined_audio_video_bwe;
918
919 audio_options_.audio_jitter_buffer_max_packets =
Oskar Sundbom9b28a032017-11-16 10:53:30 +0100920 configuration.audio_jitter_buffer_max_packets;
Steve Anton75737c02017-11-06 10:37:17 -0800921
922 audio_options_.audio_jitter_buffer_fast_accelerate =
Oskar Sundbom9b28a032017-11-16 10:53:30 +0100923 configuration.audio_jitter_buffer_fast_accelerate;
Steve Anton75737c02017-11-06 10:37:17 -0800924
925 // Whether the certificate generator/certificate is null or not determines
926 // what PeerConnectionDescriptionFactory will do, so make sure that we give it
927 // the right instructions by clearing the variables if needed.
928 if (!dtls_enabled_) {
929 cert_generator.reset();
930 certificate = nullptr;
931 } else if (certificate) {
932 // Favor generated certificate over the certificate generator.
933 cert_generator.reset();
934 }
935
936 webrtc_session_desc_factory_.reset(new WebRtcSessionDescriptionFactory(
937 signaling_thread(), channel_manager(), this, session_id(),
938 std::move(cert_generator), certificate));
939 webrtc_session_desc_factory_->SignalCertificateReady.connect(
940 this, &PeerConnection::OnCertificateReady);
941
942 if (options.disable_encryption) {
943 webrtc_session_desc_factory_->SetSdesPolicy(cricket::SEC_DISABLED);
944 }
945
946 webrtc_session_desc_factory_->set_enable_encrypted_rtp_header_extensions(
947 options.crypto_options.enable_encrypted_rtp_header_extensions);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000948
Steve Anton4171afb2017-11-20 10:20:22 -0800949 // Add default audio/video transceivers for Plan B SDP.
950 if (!IsUnifiedPlan()) {
951 transceivers_.push_back(
952 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
953 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_AUDIO)));
954 transceivers_.push_back(
955 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
956 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_VIDEO)));
957 }
958
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000959 return true;
960}
961
Steve Anton038834f2017-07-14 15:59:59 -0700962RTCError PeerConnection::ValidateConfiguration(
963 const RTCConfiguration& config) const {
964 if (config.ice_regather_interval_range &&
965 config.continual_gathering_policy == GATHER_ONCE) {
966 return RTCError(RTCErrorType::INVALID_PARAMETER,
967 "ice_regather_interval_range specified but continual "
968 "gathering policy is GATHER_ONCE");
969 }
970 return RTCError::OK();
971}
972
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000973rtc::scoped_refptr<StreamCollectionInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000974PeerConnection::local_streams() {
deadbeefab9b2d12015-10-14 11:33:11 -0700975 return local_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000976}
977
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000978rtc::scoped_refptr<StreamCollectionInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000979PeerConnection::remote_streams() {
deadbeefab9b2d12015-10-14 11:33:11 -0700980 return remote_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000981}
982
perkj@webrtc.orgc2dd5ee2014-11-04 11:31:29 +0000983bool PeerConnection::AddStream(MediaStreamInterface* local_stream) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100984 TRACE_EVENT0("webrtc", "PeerConnection::AddStream");
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000985 if (IsClosed()) {
986 return false;
987 }
deadbeefab9b2d12015-10-14 11:33:11 -0700988 if (!CanAddLocalMediaStream(local_streams_, local_stream)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000989 return false;
990 }
deadbeefab9b2d12015-10-14 11:33:11 -0700991
992 local_streams_->AddStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -0800993 MediaStreamObserver* observer = new MediaStreamObserver(local_stream);
994 observer->SignalAudioTrackAdded.connect(this,
995 &PeerConnection::OnAudioTrackAdded);
996 observer->SignalAudioTrackRemoved.connect(
997 this, &PeerConnection::OnAudioTrackRemoved);
998 observer->SignalVideoTrackAdded.connect(this,
999 &PeerConnection::OnVideoTrackAdded);
1000 observer->SignalVideoTrackRemoved.connect(
1001 this, &PeerConnection::OnVideoTrackRemoved);
kwibergd1fe2812016-04-27 06:47:29 -07001002 stream_observers_.push_back(std::unique_ptr<MediaStreamObserver>(observer));
deadbeefab9b2d12015-10-14 11:33:11 -07001003
deadbeefab9b2d12015-10-14 11:33:11 -07001004 for (const auto& track : local_stream->GetAudioTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001005 AddAudioTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -07001006 }
1007 for (const auto& track : local_stream->GetVideoTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001008 AddVideoTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -07001009 }
1010
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001011 stats_->AddStream(local_stream);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001012 observer_->OnRenegotiationNeeded();
1013 return true;
1014}
1015
1016void PeerConnection::RemoveStream(MediaStreamInterface* local_stream) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001017 TRACE_EVENT0("webrtc", "PeerConnection::RemoveStream");
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001018 if (!IsClosed()) {
1019 for (const auto& track : local_stream->GetAudioTracks()) {
1020 RemoveAudioTrack(track.get(), local_stream);
1021 }
1022 for (const auto& track : local_stream->GetVideoTracks()) {
1023 RemoveVideoTrack(track.get(), local_stream);
1024 }
deadbeefab9b2d12015-10-14 11:33:11 -07001025 }
deadbeefab9b2d12015-10-14 11:33:11 -07001026 local_streams_->RemoveStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -08001027 stream_observers_.erase(
1028 std::remove_if(
1029 stream_observers_.begin(), stream_observers_.end(),
kwibergd1fe2812016-04-27 06:47:29 -07001030 [local_stream](const std::unique_ptr<MediaStreamObserver>& observer) {
deadbeefeb459812015-12-15 19:24:43 -08001031 return observer->stream()->label().compare(local_stream->label()) ==
1032 0;
1033 }),
1034 stream_observers_.end());
deadbeefab9b2d12015-10-14 11:33:11 -07001035
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001036 if (IsClosed()) {
1037 return;
1038 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001039 observer_->OnRenegotiationNeeded();
1040}
1041
deadbeefe1f9d832016-01-14 15:35:42 -08001042rtc::scoped_refptr<RtpSenderInterface> PeerConnection::AddTrack(
1043 MediaStreamTrackInterface* track,
1044 std::vector<MediaStreamInterface*> streams) {
1045 TRACE_EVENT0("webrtc", "PeerConnection::AddTrack");
Steve Antonf9381f02017-12-14 10:23:57 -08001046 std::vector<std::string> stream_labels;
1047 for (auto* stream : streams) {
1048 if (!stream) {
1049 RTC_LOG(LS_ERROR) << "Stream list has null element.";
1050 return nullptr;
1051 }
1052 stream_labels.push_back(stream->label());
1053 }
Steve Anton2d6c76a2018-01-05 17:10:52 -08001054 auto sender_or_error = AddTrack(track, stream_labels);
Steve Antonf9381f02017-12-14 10:23:57 -08001055 if (!sender_or_error.ok()) {
deadbeefe1f9d832016-01-14 15:35:42 -08001056 return nullptr;
1057 }
Steve Antonf9381f02017-12-14 10:23:57 -08001058 return sender_or_error.MoveValue();
1059}
1060
Steve Anton2d6c76a2018-01-05 17:10:52 -08001061RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::AddTrack(
Steve Antonf9381f02017-12-14 10:23:57 -08001062 rtc::scoped_refptr<MediaStreamTrackInterface> track,
1063 const std::vector<std::string>& stream_labels) {
Steve Anton2d6c76a2018-01-05 17:10:52 -08001064 TRACE_EVENT0("webrtc", "PeerConnection::AddTrack");
Steve Antonf9381f02017-12-14 10:23:57 -08001065 if (!track) {
1066 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "Track is null.");
1067 }
1068 if (!(track->kind() == MediaStreamTrackInterface::kAudioKind ||
1069 track->kind() == MediaStreamTrackInterface::kVideoKind)) {
1070 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1071 "Track has invalid kind: " + track->kind());
1072 }
1073 // TODO(bugs.webrtc.org/7932): Support adding a track to multiple streams.
1074 if (stream_labels.size() > 1u) {
1075 LOG_AND_RETURN_ERROR(
1076 RTCErrorType::UNSUPPORTED_OPERATION,
1077 "AddTrack with more than one stream is not currently supported.");
1078 }
1079 if (IsClosed()) {
1080 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
1081 "PeerConnection is closed.");
deadbeefe1f9d832016-01-14 15:35:42 -08001082 }
Steve Anton4171afb2017-11-20 10:20:22 -08001083 if (FindSenderForTrack(track)) {
Steve Antonf9381f02017-12-14 10:23:57 -08001084 LOG_AND_RETURN_ERROR(
1085 RTCErrorType::INVALID_PARAMETER,
1086 "Sender already exists for track " + track->id() + ".");
deadbeefe1f9d832016-01-14 15:35:42 -08001087 }
Steve Antonf9381f02017-12-14 10:23:57 -08001088 // TODO(bugs.webrtc.org/7933): MediaSession expects the sender to have exactly
1089 // one stream. AddTrackInternal will return an error if there is more than one
1090 // stream, but if the caller specifies none then we need to generate a random
1091 // stream label.
1092 std::vector<std::string> adjusted_stream_labels = stream_labels;
1093 if (stream_labels.empty()) {
1094 adjusted_stream_labels.push_back(rtc::CreateRandomUuid());
1095 }
1096 RTC_DCHECK_EQ(1, adjusted_stream_labels.size());
1097 auto sender_or_error =
1098 (IsUnifiedPlan() ? AddTrackUnifiedPlan(track, adjusted_stream_labels)
1099 : AddTrackPlanB(track, adjusted_stream_labels));
1100 if (sender_or_error.ok()) {
1101 observer_->OnRenegotiationNeeded();
Steve Anton43a723a2018-01-04 15:48:17 -08001102 stats_->AddTrack(track);
Steve Antonf9381f02017-12-14 10:23:57 -08001103 }
1104 return sender_or_error;
1105}
deadbeefe1f9d832016-01-14 15:35:42 -08001106
Steve Antonf9381f02017-12-14 10:23:57 -08001107RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>>
1108PeerConnection::AddTrackPlanB(
1109 rtc::scoped_refptr<MediaStreamTrackInterface> track,
1110 const std::vector<std::string>& stream_labels) {
Steve Anton02ee47c2018-01-10 16:26:06 -08001111 cricket::MediaType media_type =
1112 (track->kind() == MediaStreamTrackInterface::kAudioKind
1113 ? cricket::MEDIA_TYPE_AUDIO
1114 : cricket::MEDIA_TYPE_VIDEO);
1115 auto new_sender = CreateSender(media_type, track, stream_labels);
deadbeefe1f9d832016-01-14 15:35:42 -08001116 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
Guido Urdanetaee2388f2018-02-15 16:36:19 +00001117 static_cast<AudioRtpSender*>(new_sender->internal())
1118 ->SetMediaChannel(voice_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08001119 GetAudioTransceiver()->internal()->AddSender(new_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001120 const RtpSenderInfo* sender_info =
1121 FindSenderInfo(local_audio_sender_infos_,
1122 new_sender->internal()->stream_id(), track->id());
1123 if (sender_info) {
1124 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -08001125 }
Steve Antonf9381f02017-12-14 10:23:57 -08001126 } else {
1127 RTC_DCHECK_EQ(MediaStreamTrackInterface::kVideoKind, track->kind());
Guido Urdanetaee2388f2018-02-15 16:36:19 +00001128 static_cast<VideoRtpSender*>(new_sender->internal())
1129 ->SetMediaChannel(video_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08001130 GetVideoTransceiver()->internal()->AddSender(new_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001131 const RtpSenderInfo* sender_info =
1132 FindSenderInfo(local_video_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 }
deadbeefe1f9d832016-01-14 15:35:42 -08001137 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001138 return rtc::scoped_refptr<RtpSenderInterface>(new_sender);
Steve Antonf9381f02017-12-14 10:23:57 -08001139}
deadbeefe1f9d832016-01-14 15:35:42 -08001140
Steve Antonf9381f02017-12-14 10:23:57 -08001141RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>>
1142PeerConnection::AddTrackUnifiedPlan(
1143 rtc::scoped_refptr<MediaStreamTrackInterface> track,
1144 const std::vector<std::string>& stream_labels) {
1145 auto transceiver = FindFirstTransceiverForAddedTrack(track);
1146 if (transceiver) {
1147 if (transceiver->direction() == RtpTransceiverDirection::kRecvOnly) {
1148 transceiver->SetDirection(RtpTransceiverDirection::kSendRecv);
1149 } else if (transceiver->direction() == RtpTransceiverDirection::kInactive) {
1150 transceiver->SetDirection(RtpTransceiverDirection::kSendOnly);
1151 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001152 transceiver->sender()->SetTrack(track);
1153 transceiver->internal()->sender_internal()->set_stream_ids(stream_labels);
Steve Antonf9381f02017-12-14 10:23:57 -08001154 } else {
1155 cricket::MediaType media_type =
1156 (track->kind() == MediaStreamTrackInterface::kAudioKind
1157 ? cricket::MEDIA_TYPE_AUDIO
1158 : cricket::MEDIA_TYPE_VIDEO);
Steve Anton02ee47c2018-01-10 16:26:06 -08001159 auto sender = CreateSender(media_type, track, stream_labels);
1160 auto receiver = CreateReceiver(media_type, rtc::CreateRandomUuid());
1161 transceiver = CreateAndAddTransceiver(sender, receiver);
Steve Antonf9381f02017-12-14 10:23:57 -08001162 transceiver->internal()->set_created_by_addtrack(true);
1163 transceiver->SetDirection(RtpTransceiverDirection::kSendRecv);
1164 }
Steve Antonf9381f02017-12-14 10:23:57 -08001165 return transceiver->sender();
1166}
1167
1168rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1169PeerConnection::FindFirstTransceiverForAddedTrack(
1170 rtc::scoped_refptr<MediaStreamTrackInterface> track) {
1171 RTC_DCHECK(track);
1172 for (auto transceiver : transceivers_) {
1173 if (!transceiver->sender()->track() &&
Steve Anton69470252018-02-09 11:43:08 -08001174 cricket::MediaTypeToString(transceiver->media_type()) ==
Steve Antonf9381f02017-12-14 10:23:57 -08001175 track->kind() &&
1176 !transceiver->internal()->has_ever_been_used_to_send()) {
1177 return transceiver;
1178 }
1179 }
1180 return nullptr;
deadbeefe1f9d832016-01-14 15:35:42 -08001181}
1182
1183bool PeerConnection::RemoveTrack(RtpSenderInterface* sender) {
1184 TRACE_EVENT0("webrtc", "PeerConnection::RemoveTrack");
Steve Antonf9381f02017-12-14 10:23:57 -08001185 return RemoveTrackInternal(sender).ok();
1186}
1187
1188RTCError PeerConnection::RemoveTrackInternal(
1189 rtc::scoped_refptr<RtpSenderInterface> sender) {
1190 if (!sender) {
1191 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "Sender is null.");
1192 }
deadbeefe1f9d832016-01-14 15:35:42 -08001193 if (IsClosed()) {
Steve Antonf9381f02017-12-14 10:23:57 -08001194 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
1195 "PeerConnection is closed.");
deadbeefe1f9d832016-01-14 15:35:42 -08001196 }
Steve Antonf9381f02017-12-14 10:23:57 -08001197 if (IsUnifiedPlan()) {
1198 auto transceiver = FindTransceiverBySender(sender);
1199 if (!transceiver || !sender->track()) {
1200 return RTCError::OK();
1201 }
1202 sender->SetTrack(nullptr);
1203 if (transceiver->direction() == RtpTransceiverDirection::kSendRecv) {
1204 transceiver->internal()->SetDirection(RtpTransceiverDirection::kRecvOnly);
1205 } else if (transceiver->direction() == RtpTransceiverDirection::kSendOnly) {
1206 transceiver->internal()->SetDirection(RtpTransceiverDirection::kInactive);
1207 }
Steve Anton4171afb2017-11-20 10:20:22 -08001208 } else {
Steve Antonf9381f02017-12-14 10:23:57 -08001209 bool removed;
1210 if (sender->media_type() == cricket::MEDIA_TYPE_AUDIO) {
1211 removed = GetAudioTransceiver()->internal()->RemoveSender(sender);
1212 } else {
1213 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, sender->media_type());
1214 removed = GetVideoTransceiver()->internal()->RemoveSender(sender);
1215 }
1216 if (!removed) {
1217 LOG_AND_RETURN_ERROR(
1218 RTCErrorType::INVALID_PARAMETER,
1219 "Couldn't find sender " + sender->id() + " to remove.");
1220 }
Steve Anton4171afb2017-11-20 10:20:22 -08001221 }
deadbeefe1f9d832016-01-14 15:35:42 -08001222 observer_->OnRenegotiationNeeded();
Steve Antonf9381f02017-12-14 10:23:57 -08001223 return RTCError::OK();
1224}
1225
1226rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1227PeerConnection::FindTransceiverBySender(
1228 rtc::scoped_refptr<RtpSenderInterface> sender) {
1229 for (auto transceiver : transceivers_) {
1230 if (transceiver->sender() == sender) {
1231 return transceiver;
1232 }
1233 }
1234 return nullptr;
deadbeefe1f9d832016-01-14 15:35:42 -08001235}
1236
Steve Anton9158ef62017-11-27 13:01:52 -08001237RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1238PeerConnection::AddTransceiver(
1239 rtc::scoped_refptr<MediaStreamTrackInterface> track) {
1240 return AddTransceiver(track, RtpTransceiverInit());
1241}
1242
1243RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1244PeerConnection::AddTransceiver(
1245 rtc::scoped_refptr<MediaStreamTrackInterface> track,
1246 const RtpTransceiverInit& init) {
1247 if (!IsUnifiedPlan()) {
1248 LOG_AND_RETURN_ERROR(
1249 RTCErrorType::INTERNAL_ERROR,
1250 "AddTransceiver only supported when Unified Plan is enabled.");
1251 }
1252 if (!track) {
1253 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "track is null");
1254 }
1255 cricket::MediaType media_type;
1256 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
1257 media_type = cricket::MEDIA_TYPE_AUDIO;
1258 } else if (track->kind() == MediaStreamTrackInterface::kVideoKind) {
1259 media_type = cricket::MEDIA_TYPE_VIDEO;
1260 } else {
1261 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1262 "Track kind is not audio or video");
1263 }
1264 return AddTransceiver(media_type, track, init);
1265}
1266
1267RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1268PeerConnection::AddTransceiver(cricket::MediaType media_type) {
1269 return AddTransceiver(media_type, RtpTransceiverInit());
1270}
1271
1272RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1273PeerConnection::AddTransceiver(cricket::MediaType media_type,
1274 const RtpTransceiverInit& init) {
1275 if (!IsUnifiedPlan()) {
1276 LOG_AND_RETURN_ERROR(
1277 RTCErrorType::INTERNAL_ERROR,
1278 "AddTransceiver only supported when Unified Plan is enabled.");
1279 }
1280 if (!(media_type == cricket::MEDIA_TYPE_AUDIO ||
1281 media_type == cricket::MEDIA_TYPE_VIDEO)) {
1282 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1283 "media type is not audio or video");
1284 }
1285 return AddTransceiver(media_type, nullptr, init);
1286}
1287
1288RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1289PeerConnection::AddTransceiver(
1290 cricket::MediaType media_type,
1291 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Steve Anton22da89f2018-01-25 13:58:07 -08001292 const RtpTransceiverInit& init,
1293 bool fire_callback) {
Steve Anton9158ef62017-11-27 13:01:52 -08001294 RTC_DCHECK((media_type == cricket::MEDIA_TYPE_AUDIO ||
1295 media_type == cricket::MEDIA_TYPE_VIDEO));
1296 if (track) {
1297 RTC_DCHECK_EQ(media_type,
1298 (track->kind() == MediaStreamTrackInterface::kAudioKind
1299 ? cricket::MEDIA_TYPE_AUDIO
1300 : cricket::MEDIA_TYPE_VIDEO));
1301 }
1302
1303 // TODO(bugs.webrtc.org/7600): Verify init.
1304
Steve Anton02ee47c2018-01-10 16:26:06 -08001305 if (init.stream_labels.size() > 1u) {
1306 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
1307 "More than one stream is not yet supported.");
Steve Antonf9381f02017-12-14 10:23:57 -08001308 }
1309
Steve Anton02ee47c2018-01-10 16:26:06 -08001310 std::vector<std::string> stream_labels = {!init.stream_labels.empty()
1311 ? init.stream_labels[0]
1312 : rtc::CreateRandomUuid()};
1313
1314 auto sender = CreateSender(media_type, track, stream_labels);
1315 auto receiver = CreateReceiver(media_type, rtc::CreateRandomUuid());
1316 auto transceiver = CreateAndAddTransceiver(sender, receiver);
1317 transceiver->internal()->set_direction(init.direction);
1318
Steve Anton22da89f2018-01-25 13:58:07 -08001319 if (fire_callback) {
1320 observer_->OnRenegotiationNeeded();
1321 }
Steve Antonf9381f02017-12-14 10:23:57 -08001322
1323 return rtc::scoped_refptr<RtpTransceiverInterface>(transceiver);
1324}
1325
Steve Anton02ee47c2018-01-10 16:26:06 -08001326rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
1327PeerConnection::CreateSender(
1328 cricket::MediaType media_type,
1329 rtc::scoped_refptr<MediaStreamTrackInterface> track,
1330 const std::vector<std::string>& stream_labels) {
Steve Anton9158ef62017-11-27 13:01:52 -08001331 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> sender;
Steve Anton02ee47c2018-01-10 16:26:06 -08001332 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
1333 RTC_DCHECK(!track ||
1334 (track->kind() == MediaStreamTrackInterface::kAudioKind));
1335 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
1336 signaling_thread(),
Steve Anton47136dd2018-01-12 10:49:35 -08001337 new AudioRtpSender(worker_thread(),
1338 static_cast<AudioTrackInterface*>(track.get()),
Steve Anton02ee47c2018-01-10 16:26:06 -08001339 stream_labels, stats_.get()));
1340 } else {
1341 RTC_DCHECK_EQ(media_type, cricket::MEDIA_TYPE_VIDEO);
1342 RTC_DCHECK(!track ||
1343 (track->kind() == MediaStreamTrackInterface::kVideoKind));
1344 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
1345 signaling_thread(),
Steve Anton47136dd2018-01-12 10:49:35 -08001346 new VideoRtpSender(worker_thread(),
1347 static_cast<VideoTrackInterface*>(track.get()),
Steve Anton02ee47c2018-01-10 16:26:06 -08001348 stream_labels));
1349 }
1350 sender->internal()->set_stream_ids(stream_labels);
1351 return sender;
1352}
1353
1354rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1355PeerConnection::CreateReceiver(cricket::MediaType media_type,
1356 const std::string& receiver_id) {
Steve Anton9158ef62017-11-27 13:01:52 -08001357 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1358 receiver;
Steve Anton9158ef62017-11-27 13:01:52 -08001359 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton9158ef62017-11-27 13:01:52 -08001360 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
Steve Anton60776752018-01-10 11:51:34 -08001361 signaling_thread(),
Steve Antond3679212018-01-17 17:41:02 -08001362 new AudioRtpReceiver(worker_thread(), receiver_id, {}));
Steve Anton9158ef62017-11-27 13:01:52 -08001363 } else {
Steve Anton02ee47c2018-01-10 16:26:06 -08001364 RTC_DCHECK_EQ(media_type, cricket::MEDIA_TYPE_VIDEO);
Steve Anton9158ef62017-11-27 13:01:52 -08001365 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
1366 signaling_thread(),
Steve Antond3679212018-01-17 17:41:02 -08001367 new VideoRtpReceiver(worker_thread(), receiver_id, {}));
Steve Anton9158ef62017-11-27 13:01:52 -08001368 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001369 return receiver;
1370}
1371
1372rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1373PeerConnection::CreateAndAddTransceiver(
1374 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> sender,
1375 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1376 receiver) {
1377 auto transceiver = RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1378 signaling_thread(), new RtpTransceiver(sender, receiver));
Steve Anton9158ef62017-11-27 13:01:52 -08001379 transceivers_.push_back(transceiver);
Steve Antonf9381f02017-12-14 10:23:57 -08001380 return transceiver;
Steve Anton9158ef62017-11-27 13:01:52 -08001381}
1382
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001383rtc::scoped_refptr<DtmfSenderInterface> PeerConnection::CreateDtmfSender(
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001384 AudioTrackInterface* track) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001385 TRACE_EVENT0("webrtc", "PeerConnection::CreateDtmfSender");
zhihuang29ff8442016-07-27 11:07:25 -07001386 if (IsClosed()) {
1387 return nullptr;
1388 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001389 if (!track) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001390 RTC_LOG(LS_ERROR) << "CreateDtmfSender - track is NULL.";
deadbeef20cb0c12017-02-01 20:27:00 -08001391 return nullptr;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001392 }
Steve Anton4171afb2017-11-20 10:20:22 -08001393 auto track_sender = FindSenderForTrack(track);
1394 if (!track_sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001395 RTC_LOG(LS_ERROR) << "CreateDtmfSender called with a non-added track.";
deadbeef20cb0c12017-02-01 20:27:00 -08001396 return nullptr;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001397 }
1398
Steve Anton4171afb2017-11-20 10:20:22 -08001399 return track_sender->GetDtmfSender();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001400}
1401
deadbeeffac06552015-11-25 11:26:01 -08001402rtc::scoped_refptr<RtpSenderInterface> PeerConnection::CreateSender(
deadbeefbd7d8f72015-12-18 16:58:44 -08001403 const std::string& kind,
1404 const std::string& stream_id) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001405 TRACE_EVENT0("webrtc", "PeerConnection::CreateSender");
zhihuang29ff8442016-07-27 11:07:25 -07001406 if (IsClosed()) {
1407 return nullptr;
1408 }
Steve Anton4171afb2017-11-20 10:20:22 -08001409
Steve Anton02ee47c2018-01-10 16:26:06 -08001410 std::vector<std::string> stream_labels;
1411 if (!stream_id.empty()) {
1412 stream_labels.push_back(stream_id);
1413 }
1414
Steve Anton4171afb2017-11-20 10:20:22 -08001415 // TODO(steveanton): Move construction of the RtpSenders to RtpTransceiver.
deadbeefa601f5c2016-06-06 14:27:39 -07001416 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender;
deadbeeffac06552015-11-25 11:26:01 -08001417 if (kind == MediaStreamTrackInterface::kAudioKind) {
Steve Anton47136dd2018-01-12 10:49:35 -08001418 auto* audio_sender = new AudioRtpSender(worker_thread(), nullptr,
1419 stream_labels, stats_.get());
Guido Urdanetaee2388f2018-02-15 16:36:19 +00001420 audio_sender->SetMediaChannel(voice_media_channel());
deadbeefa601f5c2016-06-06 14:27:39 -07001421 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton02ee47c2018-01-10 16:26:06 -08001422 signaling_thread(), audio_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001423 GetAudioTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 11:26:01 -08001424 } else if (kind == MediaStreamTrackInterface::kVideoKind) {
Steve Anton47136dd2018-01-12 10:49:35 -08001425 auto* video_sender =
1426 new VideoRtpSender(worker_thread(), nullptr, stream_labels);
Guido Urdanetaee2388f2018-02-15 16:36:19 +00001427 video_sender->SetMediaChannel(video_media_channel());
deadbeefa601f5c2016-06-06 14:27:39 -07001428 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton02ee47c2018-01-10 16:26:06 -08001429 signaling_thread(), video_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001430 GetVideoTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 11:26:01 -08001431 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001432 RTC_LOG(LS_ERROR) << "CreateSender called with invalid kind: " << kind;
Steve Anton4171afb2017-11-20 10:20:22 -08001433 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08001434 }
Steve Anton4171afb2017-11-20 10:20:22 -08001435
deadbeefe1f9d832016-01-14 15:35:42 -08001436 return new_sender;
deadbeeffac06552015-11-25 11:26:01 -08001437}
1438
deadbeef70ab1a12015-09-28 16:53:55 -07001439std::vector<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::GetSenders()
1440 const {
deadbeefa601f5c2016-06-06 14:27:39 -07001441 std::vector<rtc::scoped_refptr<RtpSenderInterface>> ret;
Steve Anton4171afb2017-11-20 10:20:22 -08001442 for (auto sender : GetSendersInternal()) {
1443 ret.push_back(sender);
deadbeefa601f5c2016-06-06 14:27:39 -07001444 }
1445 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -07001446}
1447
Steve Anton4171afb2017-11-20 10:20:22 -08001448std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1449PeerConnection::GetSendersInternal() const {
1450 std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1451 all_senders;
1452 for (auto transceiver : transceivers_) {
1453 auto senders = transceiver->internal()->senders();
1454 all_senders.insert(all_senders.end(), senders.begin(), senders.end());
1455 }
1456 return all_senders;
1457}
1458
deadbeef70ab1a12015-09-28 16:53:55 -07001459std::vector<rtc::scoped_refptr<RtpReceiverInterface>>
1460PeerConnection::GetReceivers() const {
deadbeefa601f5c2016-06-06 14:27:39 -07001461 std::vector<rtc::scoped_refptr<RtpReceiverInterface>> ret;
Steve Anton4171afb2017-11-20 10:20:22 -08001462 for (const auto& receiver : GetReceiversInternal()) {
1463 ret.push_back(receiver);
deadbeefa601f5c2016-06-06 14:27:39 -07001464 }
1465 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -07001466}
1467
Steve Anton4171afb2017-11-20 10:20:22 -08001468std::vector<
1469 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1470PeerConnection::GetReceiversInternal() const {
1471 std::vector<
1472 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1473 all_receivers;
1474 for (auto transceiver : transceivers_) {
1475 auto receivers = transceiver->internal()->receivers();
1476 all_receivers.insert(all_receivers.end(), receivers.begin(),
1477 receivers.end());
1478 }
1479 return all_receivers;
1480}
1481
Steve Anton9158ef62017-11-27 13:01:52 -08001482std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
1483PeerConnection::GetTransceivers() const {
1484 RTC_DCHECK(IsUnifiedPlan());
1485 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> all_transceivers;
1486 for (auto transceiver : transceivers_) {
1487 all_transceivers.push_back(transceiver);
1488 }
1489 return all_transceivers;
1490}
1491
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001492bool PeerConnection::GetStats(StatsObserver* observer,
wu@webrtc.orgb9a088b2014-02-13 23:18:49 +00001493 MediaStreamTrackInterface* track,
1494 StatsOutputLevel level) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001495 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
deadbeef0a6c4ca2015-10-06 11:38:28 -07001496 RTC_DCHECK(signaling_thread()->IsCurrent());
nisse7ce109a2017-01-31 00:57:56 -08001497 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001498 RTC_LOG(LS_ERROR) << "GetStats - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001499 return false;
1500 }
1501
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001502 stats_->UpdateStats(level);
zhihuange9e94c32016-11-04 11:38:15 -07001503 // The StatsCollector is used to tell if a track is valid because it may
1504 // remember tracks that the PeerConnection previously removed.
1505 if (track && !stats_->IsValidTrack(track->id())) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001506 RTC_LOG(LS_WARNING) << "GetStats is called with an invalid track: "
1507 << track->id();
zhihuange9e94c32016-11-04 11:38:15 -07001508 return false;
1509 }
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001510 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_GETSTATS,
tommi@webrtc.org5b06b062014-08-15 08:38:30 +00001511 new GetStatsMsg(observer, track));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001512 return true;
1513}
1514
hbos74e1a4f2016-09-15 23:33:01 -07001515void PeerConnection::GetStats(RTCStatsCollectorCallback* callback) {
1516 RTC_DCHECK(stats_collector_);
1517 stats_collector_->GetStatsReport(callback);
1518}
1519
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001520PeerConnectionInterface::SignalingState PeerConnection::signaling_state() {
1521 return signaling_state_;
1522}
1523
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001524PeerConnectionInterface::IceConnectionState
1525PeerConnection::ice_connection_state() {
1526 return ice_connection_state_;
1527}
1528
1529PeerConnectionInterface::IceGatheringState
1530PeerConnection::ice_gathering_state() {
1531 return ice_gathering_state_;
1532}
1533
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001534rtc::scoped_refptr<DataChannelInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001535PeerConnection::CreateDataChannel(
1536 const std::string& label,
1537 const DataChannelInit* config) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001538 TRACE_EVENT0("webrtc", "PeerConnection::CreateDataChannel");
zhihuang9763d562016-08-05 11:14:50 -07001539
deadbeefab9b2d12015-10-14 11:33:11 -07001540 bool first_datachannel = !HasDataChannels();
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001541
kwibergd1fe2812016-04-27 06:47:29 -07001542 std::unique_ptr<InternalDataChannelInit> internal_config;
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00001543 if (config) {
1544 internal_config.reset(new InternalDataChannelInit(*config));
1545 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001546 rtc::scoped_refptr<DataChannelInterface> channel(
deadbeefab9b2d12015-10-14 11:33:11 -07001547 InternalCreateDataChannel(label, internal_config.get()));
1548 if (!channel.get()) {
1549 return nullptr;
1550 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001551
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001552 // Trigger the onRenegotiationNeeded event for every new RTP DataChannel, or
1553 // the first SCTP DataChannel.
Steve Anton75737c02017-11-06 10:37:17 -08001554 if (data_channel_type() == cricket::DCT_RTP || first_datachannel) {
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001555 observer_->OnRenegotiationNeeded();
1556 }
wu@webrtc.org91053e72013-08-10 07:18:04 +00001557
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001558 return DataChannelProxy::Create(signaling_thread(), channel.get());
1559}
1560
1561void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
1562 const MediaConstraintsInterface* constraints) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001563 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
Steve Anton8d3444d2017-10-20 15:30:51 -07001564
zhihuang1c378ed2017-08-17 14:10:50 -07001565 PeerConnectionInterface::RTCOfferAnswerOptions offer_answer_options;
1566 // Always create an offer even if |ConvertConstraintsToOfferAnswerOptions|
1567 // returns false for now. Because |ConvertConstraintsToOfferAnswerOptions|
1568 // compares the mandatory fields parsed with the mandatory fields added in the
1569 // |constraints| and some downstream applications might create offers with
1570 // mandatory fields which would not be parsed in the helper method. For
1571 // example, in Chromium/remoting, |kEnableDtlsSrtp| is added to the
1572 // |constraints| as a mandatory field but it is not parsed.
1573 ConvertConstraintsToOfferAnswerOptions(constraints, &offer_answer_options);
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001574
zhihuang1c378ed2017-08-17 14:10:50 -07001575 CreateOffer(observer, offer_answer_options);
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001576}
1577
1578void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
1579 const RTCOfferAnswerOptions& options) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001580 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
Steve Anton8d3444d2017-10-20 15:30:51 -07001581
nisse7ce109a2017-01-31 00:57:56 -08001582 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001583 RTC_LOG(LS_ERROR) << "CreateOffer - observer is NULL.";
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001584 return;
1585 }
deadbeefab9b2d12015-10-14 11:33:11 -07001586
Steve Anton8d3444d2017-10-20 15:30:51 -07001587 if (IsClosed()) {
1588 std::string error = "CreateOffer called when PeerConnection is closed.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001589 RTC_LOG(LS_ERROR) << error;
Steve Anton8d3444d2017-10-20 15:30:51 -07001590 PostCreateSessionDescriptionFailure(observer, error);
1591 return;
1592 }
1593
zhihuang1c378ed2017-08-17 14:10:50 -07001594 if (!ValidateOfferAnswerOptions(options)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001595 std::string error = "CreateOffer called with invalid options.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001596 RTC_LOG(LS_ERROR) << error;
deadbeefab9b2d12015-10-14 11:33:11 -07001597 PostCreateSessionDescriptionFailure(observer, error);
1598 return;
1599 }
1600
Steve Anton22da89f2018-01-25 13:58:07 -08001601 // Legacy handling for offer_to_receive_audio and offer_to_receive_video.
1602 // Specified in WebRTC section 4.4.3.2 "Legacy configuration extensions".
1603 if (IsUnifiedPlan()) {
1604 RTCError error = HandleLegacyOfferOptions(options);
1605 if (!error.ok()) {
1606 PostCreateSessionDescriptionFailure(observer, error.message());
1607 return;
1608 }
1609 }
1610
zhihuang1c378ed2017-08-17 14:10:50 -07001611 cricket::MediaSessionOptions session_options;
1612 GetOptionsForOffer(options, &session_options);
Steve Antond25da372017-11-06 14:50:29 -08001613 webrtc_session_desc_factory_->CreateOffer(observer, options, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001614}
1615
Steve Anton22da89f2018-01-25 13:58:07 -08001616RTCError PeerConnection::HandleLegacyOfferOptions(
1617 const RTCOfferAnswerOptions& options) {
1618 RTC_DCHECK(IsUnifiedPlan());
1619
1620 if (options.offer_to_receive_audio == 0) {
1621 RemoveRecvDirectionFromReceivingTransceiversOfType(
1622 cricket::MEDIA_TYPE_AUDIO);
1623 } else if (options.offer_to_receive_audio == 1) {
1624 AddUpToOneReceivingTransceiverOfType(cricket::MEDIA_TYPE_AUDIO);
1625 } else if (options.offer_to_receive_audio > 1) {
1626 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
1627 "offer_to_receive_audio > 1 is not supported.");
1628 }
1629
1630 if (options.offer_to_receive_video == 0) {
1631 RemoveRecvDirectionFromReceivingTransceiversOfType(
1632 cricket::MEDIA_TYPE_VIDEO);
1633 } else if (options.offer_to_receive_video == 1) {
1634 AddUpToOneReceivingTransceiverOfType(cricket::MEDIA_TYPE_VIDEO);
1635 } else if (options.offer_to_receive_video > 1) {
1636 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
1637 "offer_to_receive_video > 1 is not supported.");
1638 }
1639
1640 return RTCError::OK();
1641}
1642
1643void PeerConnection::RemoveRecvDirectionFromReceivingTransceiversOfType(
1644 cricket::MediaType media_type) {
1645 for (auto transceiver : GetReceivingTransceiversOfType(media_type)) {
1646 transceiver->internal()->set_direction(
1647 RtpTransceiverDirectionWithRecvSet(transceiver->direction(), false));
1648 }
1649}
1650
1651void PeerConnection::AddUpToOneReceivingTransceiverOfType(
1652 cricket::MediaType media_type) {
1653 if (GetReceivingTransceiversOfType(media_type).empty()) {
1654 RtpTransceiverInit init;
1655 init.direction = RtpTransceiverDirection::kRecvOnly;
1656 AddTransceiver(media_type, nullptr, init, /*fire_callback=*/false);
1657 }
1658}
1659
1660std::vector<rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
1661PeerConnection::GetReceivingTransceiversOfType(cricket::MediaType media_type) {
1662 std::vector<
1663 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
1664 receiving_transceivers;
1665 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08001666 if (!transceiver->stopped() && transceiver->media_type() == media_type &&
Steve Anton22da89f2018-01-25 13:58:07 -08001667 RtpTransceiverDirectionHasRecv(transceiver->direction())) {
1668 receiving_transceivers.push_back(transceiver);
1669 }
1670 }
1671 return receiving_transceivers;
1672}
1673
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001674void PeerConnection::CreateAnswer(
1675 CreateSessionDescriptionObserver* observer,
1676 const MediaConstraintsInterface* constraints) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001677 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
Steve Anton8d3444d2017-10-20 15:30:51 -07001678
nisse7ce109a2017-01-31 00:57:56 -08001679 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001680 RTC_LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001681 return;
1682 }
deadbeefab9b2d12015-10-14 11:33:11 -07001683
zhihuang1c378ed2017-08-17 14:10:50 -07001684 PeerConnectionInterface::RTCOfferAnswerOptions offer_answer_options;
1685 if (!ConvertConstraintsToOfferAnswerOptions(constraints,
1686 &offer_answer_options)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001687 std::string error = "CreateAnswer called with invalid constraints.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001688 RTC_LOG(LS_ERROR) << error;
deadbeefab9b2d12015-10-14 11:33:11 -07001689 PostCreateSessionDescriptionFailure(observer, error);
1690 return;
1691 }
1692
Steve Anton8d3444d2017-10-20 15:30:51 -07001693 CreateAnswer(observer, offer_answer_options);
htaa2a49d92016-03-04 02:51:39 -08001694}
1695
1696void PeerConnection::CreateAnswer(CreateSessionDescriptionObserver* observer,
1697 const RTCOfferAnswerOptions& options) {
1698 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
nisse7ce109a2017-01-31 00:57:56 -08001699 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001700 RTC_LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
htaa2a49d92016-03-04 02:51:39 -08001701 return;
1702 }
1703
Steve Antondffead82018-02-06 10:31:29 -08001704 if (!(signaling_state_ == kHaveRemoteOffer ||
1705 signaling_state_ == kHaveLocalPrAnswer)) {
1706 std::string error =
1707 "PeerConnection cannot create an answer in a state other than "
1708 "have-remote-offer or have-local-pranswer.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001709 RTC_LOG(LS_ERROR) << error;
Steve Anton8d3444d2017-10-20 15:30:51 -07001710 PostCreateSessionDescriptionFailure(observer, error);
1711 return;
1712 }
1713
Steve Antondffead82018-02-06 10:31:29 -08001714 // The remote description should be set if we're in the right state.
1715 RTC_DCHECK(remote_description());
Steve Anton8d3444d2017-10-20 15:30:51 -07001716
Steve Anton22da89f2018-01-25 13:58:07 -08001717 if (IsUnifiedPlan()) {
1718 if (options.offer_to_receive_audio != RTCOfferAnswerOptions::kUndefined) {
1719 RTC_LOG(LS_WARNING) << "CreateAnswer: offer_to_receive_audio is not "
1720 "supported with Unified Plan semantics. Use the "
1721 "RtpTransceiver API instead.";
1722 }
1723 if (options.offer_to_receive_video != RTCOfferAnswerOptions::kUndefined) {
1724 RTC_LOG(LS_WARNING) << "CreateAnswer: offer_to_receive_video is not "
1725 "supported with Unified Plan semantics. Use the "
1726 "RtpTransceiver API instead.";
1727 }
1728 }
1729
htaa2a49d92016-03-04 02:51:39 -08001730 cricket::MediaSessionOptions session_options;
zhihuang1c378ed2017-08-17 14:10:50 -07001731 GetOptionsForAnswer(options, &session_options);
htaa2a49d92016-03-04 02:51:39 -08001732
Steve Antond25da372017-11-06 14:50:29 -08001733 webrtc_session_desc_factory_->CreateAnswer(observer, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001734}
1735
1736void PeerConnection::SetLocalDescription(
1737 SetSessionDescriptionObserver* observer,
1738 SessionDescriptionInterface* desc) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001739 TRACE_EVENT0("webrtc", "PeerConnection::SetLocalDescription");
Steve Anton8a006912017-12-04 15:25:56 -08001740
nisse7ce109a2017-01-31 00:57:56 -08001741 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001742 RTC_LOG(LS_ERROR) << "SetLocalDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001743 return;
1744 }
Steve Anton8a006912017-12-04 15:25:56 -08001745
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001746 if (!desc) {
1747 PostSetSessionDescriptionFailure(observer, "SessionDescription is NULL.");
1748 return;
1749 }
Steve Anton8d3444d2017-10-20 15:30:51 -07001750
Steve Antona3a92c22017-12-07 10:27:41 -08001751 SdpType type = desc->GetType();
Steve Anton8d3444d2017-10-20 15:30:51 -07001752
Steve Anton8a006912017-12-04 15:25:56 -08001753 RTCError error = ApplyLocalDescription(rtc::WrapUnique(desc));
1754 // |desc| may be destroyed at this point.
1755
1756 if (!error.ok()) {
Steve Antona3a92c22017-12-07 10:27:41 -08001757 std::ostringstream oss;
1758 oss << "Failed to set local " << SdpTypeToString(type)
1759 << " sdp: " << error.message();
1760 std::string error_message = oss.str();
Steve Anton8a006912017-12-04 15:25:56 -08001761 RTC_LOG(LS_ERROR) << error_message << " (" << error.type() << ")";
1762 PostSetSessionDescriptionFailure(observer, std::move(error_message));
Steve Anton8d3444d2017-10-20 15:30:51 -07001763 return;
1764 }
Steve Anton8a006912017-12-04 15:25:56 -08001765 RTC_DCHECK(local_description());
1766
1767 PostSetSessionDescriptionSuccess(observer);
1768
1769 // According to JSEP, after setLocalDescription, changing the candidate pool
1770 // size is not allowed, and changing the set of ICE servers will not result
1771 // in new candidates being gathered.
1772 port_allocator_->FreezeCandidatePool();
1773
1774 // MaybeStartGathering needs to be called after posting
1775 // MSG_SET_SESSIONDESCRIPTION_SUCCESS, so that we don't signal any candidates
1776 // before signaling that SetLocalDescription completed.
1777 transport_controller_->MaybeStartGathering();
1778
Steve Antona3a92c22017-12-07 10:27:41 -08001779 if (local_description()->GetType() == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08001780 // TODO(deadbeef): We already had to hop to the network thread for
1781 // MaybeStartGathering...
1782 network_thread()->Invoke<void>(
1783 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
1784 port_allocator_.get()));
1785 }
1786}
1787
1788RTCError PeerConnection::ApplyLocalDescription(
1789 std::unique_ptr<SessionDescriptionInterface> desc) {
1790 RTC_DCHECK_RUN_ON(signaling_thread());
1791 RTC_DCHECK(desc);
1792
1793 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_LOCAL);
1794 if (!error.ok()) {
1795 return error;
1796 }
Steve Anton8d3444d2017-10-20 15:30:51 -07001797
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001798 // Update stats here so that we have the most recent stats for tracks and
1799 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001800 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 15:25:56 -08001801
1802 // Update the initial_offerer flag if this session is the initial_offerer.
Steve Anton3828c062017-12-06 10:34:51 -08001803 SdpType type = desc->GetType();
Steve Anton8a006912017-12-04 15:25:56 -08001804 if (!initial_offerer_.has_value()) {
Steve Anton3828c062017-12-06 10:34:51 -08001805 initial_offerer_.emplace(type == SdpType::kOffer);
Steve Anton8a006912017-12-04 15:25:56 -08001806 if (*initial_offerer_) {
1807 transport_controller_->SetIceRole(cricket::ICEROLE_CONTROLLING);
1808 } else {
1809 transport_controller_->SetIceRole(cricket::ICEROLE_CONTROLLED);
1810 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001811 }
Steve Anton8a006912017-12-04 15:25:56 -08001812
Steve Antondcc3c022017-12-22 16:02:54 -08001813 // Take a reference to the old local description since it's used below to
1814 // compare against the new local description. When setting the new local
1815 // description, grab ownership of the replaced session description in case it
1816 // is the same as |old_local_description|, to keep it alive for the duration
1817 // of the method.
1818 const SessionDescriptionInterface* old_local_description =
1819 local_description();
1820 std::unique_ptr<SessionDescriptionInterface> replaced_local_description;
Steve Anton3828c062017-12-06 10:34:51 -08001821 if (type == SdpType::kAnswer) {
Steve Antondcc3c022017-12-22 16:02:54 -08001822 replaced_local_description = pending_local_description_
1823 ? std::move(pending_local_description_)
1824 : std::move(current_local_description_);
Steve Anton8a006912017-12-04 15:25:56 -08001825 current_local_description_ = std::move(desc);
1826 pending_local_description_ = nullptr;
1827 current_remote_description_ = std::move(pending_remote_description_);
1828 } else {
Steve Antondcc3c022017-12-22 16:02:54 -08001829 replaced_local_description = std::move(pending_local_description_);
Steve Anton8a006912017-12-04 15:25:56 -08001830 pending_local_description_ = std::move(desc);
1831 }
1832 // The session description to apply now must be accessed by
1833 // |local_description()|.
Henrik Boströmfdb92012017-11-09 19:55:44 +01001834 RTC_DCHECK(local_description());
deadbeefab9b2d12015-10-14 11:33:11 -07001835
Steve Antondcc3c022017-12-22 16:02:54 -08001836 if (IsUnifiedPlan()) {
1837 RTCError error = UpdateTransceiversAndDataChannels(
Seth Hampsonae8a90a2018-02-13 15:33:48 -08001838 cricket::CS_LOCAL, *local_description(), old_local_description,
1839 remote_description());
Steve Anton8a006912017-12-04 15:25:56 -08001840 if (!error.ok()) {
1841 return error;
1842 }
Steve Antondcc3c022017-12-22 16:02:54 -08001843 for (auto transceiver : transceivers_) {
1844 const ContentInfo* content =
1845 FindMediaSectionForTransceiver(transceiver, local_description());
1846 if (!content) {
1847 continue;
1848 }
1849 const MediaContentDescription* media_desc = content->media_description();
1850 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
1851 transceiver->internal()->set_current_direction(media_desc->direction());
1852 }
1853 if (content->rejected && !transceiver->stopped()) {
1854 transceiver->Stop();
1855 }
1856 }
1857 } else {
1858 // Transport and Media channels will be created only when offer is set.
1859 if (type == SdpType::kOffer) {
1860 // TODO(bugs.webrtc.org/4676) - Handle CreateChannel failure, as new local
1861 // description is applied. Restore back to old description.
1862 RTCError error = CreateChannels(*local_description()->description());
1863 if (!error.ok()) {
1864 return error;
1865 }
1866 }
Steve Anton8a006912017-12-04 15:25:56 -08001867
Steve Antondcc3c022017-12-22 16:02:54 -08001868 // Remove unused channels if MediaContentDescription is rejected.
1869 RemoveUnusedChannels(local_description()->description());
1870 }
Steve Anton8a006912017-12-04 15:25:56 -08001871
Steve Anton3828c062017-12-06 10:34:51 -08001872 error = UpdateSessionState(type, cricket::CS_LOCAL);
Steve Anton8a006912017-12-04 15:25:56 -08001873 if (!error.ok()) {
1874 return error;
1875 }
Steve Antondcc3c022017-12-22 16:02:54 -08001876
Steve Anton8a006912017-12-04 15:25:56 -08001877 if (remote_description()) {
1878 // Now that we have a local description, we can push down remote candidates.
1879 UseCandidatesInSessionDescription(remote_description());
1880 }
1881
1882 pending_ice_restarts_.clear();
1883 if (session_error() != SessionError::kNone) {
1884 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
1885 }
1886
deadbeefab9b2d12015-10-14 11:33:11 -07001887 // If setting the description decided our SSL role, allocate any necessary
1888 // SCTP sids.
1889 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08001890 if (data_channel_type() == cricket::DCT_SCTP && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001891 AllocateSctpSids(role);
1892 }
1893
Steve Antond3679212018-01-17 17:41:02 -08001894 if (IsUnifiedPlan()) {
1895 for (auto transceiver : transceivers_) {
1896 const ContentInfo* content =
1897 FindMediaSectionForTransceiver(transceiver, local_description());
1898 if (!content) {
1899 continue;
1900 }
1901 if (content->rejected && !transceiver->stopped()) {
1902 transceiver->Stop();
1903 }
Steve Anton74255ff2018-01-24 18:32:57 -08001904 const auto& streams = content->media_description()->streams();
1905 if (!content->rejected && !streams.empty()) {
Steve Antond3679212018-01-17 17:41:02 -08001906 transceiver->internal()->sender_internal()->set_stream_ids(
Steve Anton74255ff2018-01-24 18:32:57 -08001907 {streams[0].sync_label});
Steve Antond3679212018-01-17 17:41:02 -08001908 transceiver->internal()->sender_internal()->SetSsrc(
Steve Anton74255ff2018-01-24 18:32:57 -08001909 streams[0].first_ssrc());
Steve Antond3679212018-01-17 17:41:02 -08001910 }
1911 }
1912 } else {
1913 // Plan B semantics.
1914
Steve Antondcc3c022017-12-22 16:02:54 -08001915 // Update state and SSRC of local MediaStreams and DataChannels based on the
1916 // local session description.
1917 const cricket::ContentInfo* audio_content =
1918 GetFirstAudioContent(local_description()->description());
1919 if (audio_content) {
1920 if (audio_content->rejected) {
1921 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
1922 } else {
1923 const cricket::AudioContentDescription* audio_desc =
1924 audio_content->media_description()->as_audio();
1925 UpdateLocalSenders(audio_desc->streams(), audio_desc->type());
1926 }
deadbeeffaac4972015-11-12 15:33:07 -08001927 }
deadbeefab9b2d12015-10-14 11:33:11 -07001928
Steve Antondcc3c022017-12-22 16:02:54 -08001929 const cricket::ContentInfo* video_content =
1930 GetFirstVideoContent(local_description()->description());
1931 if (video_content) {
1932 if (video_content->rejected) {
1933 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
1934 } else {
1935 const cricket::VideoContentDescription* video_desc =
1936 video_content->media_description()->as_video();
1937 UpdateLocalSenders(video_desc->streams(), video_desc->type());
1938 }
deadbeeffaac4972015-11-12 15:33:07 -08001939 }
deadbeefab9b2d12015-10-14 11:33:11 -07001940 }
1941
1942 const cricket::ContentInfo* data_content =
Henrik Boströmfdb92012017-11-09 19:55:44 +01001943 GetFirstDataContent(local_description()->description());
deadbeefab9b2d12015-10-14 11:33:11 -07001944 if (data_content) {
1945 const cricket::DataContentDescription* data_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08001946 data_content->media_description()->as_data();
deadbeefab9b2d12015-10-14 11:33:11 -07001947 if (rtc::starts_with(data_desc->protocol().data(),
1948 cricket::kMediaProtocolRtpPrefix)) {
1949 UpdateLocalRtpDataChannels(data_desc->streams());
1950 }
1951 }
1952
Steve Anton8a006912017-12-04 15:25:56 -08001953 return RTCError::OK();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001954}
1955
1956void PeerConnection::SetRemoteDescription(
Henrik Boströma4ecf552017-11-23 14:17:07 +00001957 SetSessionDescriptionObserver* observer,
1958 SessionDescriptionInterface* desc) {
Henrik Boström31638672017-11-23 17:48:32 +01001959 SetRemoteDescription(
1960 std::unique_ptr<SessionDescriptionInterface>(desc),
1961 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface>(
1962 new SetRemoteDescriptionObserverAdapter(this, observer)));
1963}
1964
1965void PeerConnection::SetRemoteDescription(
1966 std::unique_ptr<SessionDescriptionInterface> desc,
1967 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface> observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001968 TRACE_EVENT0("webrtc", "PeerConnection::SetRemoteDescription");
Steve Anton8a006912017-12-04 15:25:56 -08001969
nisse7ce109a2017-01-31 00:57:56 -08001970 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001971 RTC_LOG(LS_ERROR) << "SetRemoteDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001972 return;
1973 }
Steve Anton8a006912017-12-04 15:25:56 -08001974
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001975 if (!desc) {
Henrik Boström31638672017-11-23 17:48:32 +01001976 observer->OnSetRemoteDescriptionComplete(RTCError(
Steve Anton8a006912017-12-04 15:25:56 -08001977 RTCErrorType::INVALID_PARAMETER, "SessionDescription is NULL."));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001978 return;
1979 }
Steve Anton8d3444d2017-10-20 15:30:51 -07001980
Steve Antona3a92c22017-12-07 10:27:41 -08001981 const SdpType type = desc->GetType();
Steve Anton8a006912017-12-04 15:25:56 -08001982
1983 RTCError error = ApplyRemoteDescription(std::move(desc));
1984 // |desc| may be destroyed at this point.
1985
1986 if (!error.ok()) {
Steve Antona3a92c22017-12-07 10:27:41 -08001987 std::ostringstream oss;
1988 oss << "Failed to set remote " << SdpTypeToString(type)
1989 << " sdp: " << error.message();
1990 std::string error_message = oss.str();
Steve Anton8a006912017-12-04 15:25:56 -08001991 RTC_LOG(LS_ERROR) << error_message << " (" << error.type() << ")";
Henrik Boström31638672017-11-23 17:48:32 +01001992 observer->OnSetRemoteDescriptionComplete(
Steve Anton8a006912017-12-04 15:25:56 -08001993 RTCError(error.type(), std::move(error_message)));
Steve Anton8d3444d2017-10-20 15:30:51 -07001994 return;
1995 }
1996
Steve Antona3a92c22017-12-07 10:27:41 -08001997 if (remote_description()->GetType() == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08001998 // TODO(deadbeef): We already had to hop to the network thread for
1999 // MaybeStartGathering...
2000 network_thread()->Invoke<void>(
2001 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
2002 port_allocator_.get()));
Harald Alvestrand5dbb5862018-02-13 23:48:00 +01002003 // Make UMA notes about what was agreed to.
2004 if (uma_observer_) {
2005 switch (remote_description()->description()->msid_signaling()) {
2006 case 0:
2007 uma_observer_->IncrementEnumCounter(kEnumCounterSdpSemanticNegotiated,
2008 kSdpSemanticNegotiatedNone,
2009 kSdpSemanticNegotiatedMax);
2010 break;
2011 case cricket::kMsidSignalingMediaSection:
2012 uma_observer_->IncrementEnumCounter(kEnumCounterSdpSemanticNegotiated,
2013 kSdpSemanticNegotiatedUnifiedPlan,
2014 kSdpSemanticNegotiatedMax);
2015 break;
2016 case cricket::kMsidSignalingSsrcAttribute:
2017 uma_observer_->IncrementEnumCounter(kEnumCounterSdpSemanticNegotiated,
2018 kSdpSemanticNegotiatedPlanB,
2019 kSdpSemanticNegotiatedMax);
2020 break;
2021 case cricket::kMsidSignalingMediaSection |
2022 cricket::kMsidSignalingSsrcAttribute:
2023 uma_observer_->IncrementEnumCounter(kEnumCounterSdpSemanticNegotiated,
2024 kSdpSemanticNegotiatedMixed,
2025 kSdpSemanticNegotiatedMax);
2026 break;
2027 default:
2028 RTC_NOTREACHED();
2029 }
2030 }
Steve Anton8a006912017-12-04 15:25:56 -08002031 }
2032
2033 observer->OnSetRemoteDescriptionComplete(RTCError::OK());
2034}
2035
2036RTCError PeerConnection::ApplyRemoteDescription(
2037 std::unique_ptr<SessionDescriptionInterface> desc) {
2038 RTC_DCHECK_RUN_ON(signaling_thread());
2039 RTC_DCHECK(desc);
2040
2041 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_REMOTE);
2042 if (!error.ok()) {
2043 return error;
2044 }
2045
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002046 // Update stats here so that we have the most recent stats for tracks and
2047 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00002048 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 15:25:56 -08002049
Steve Antondcc3c022017-12-22 16:02:54 -08002050 // Take a reference to the old remote description since it's used below to
2051 // compare against the new remote description. When setting the new remote
2052 // description, grab ownership of the replaced session description in case it
2053 // is the same as |old_remote_description|, to keep it alive for the duration
2054 // of the method.
Steve Anton8a006912017-12-04 15:25:56 -08002055 const SessionDescriptionInterface* old_remote_description =
2056 remote_description();
Steve Anton8a006912017-12-04 15:25:56 -08002057 std::unique_ptr<SessionDescriptionInterface> replaced_remote_description;
Steve Anton3828c062017-12-06 10:34:51 -08002058 SdpType type = desc->GetType();
2059 if (type == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002060 replaced_remote_description = pending_remote_description_
2061 ? std::move(pending_remote_description_)
2062 : std::move(current_remote_description_);
2063 current_remote_description_ = std::move(desc);
2064 pending_remote_description_ = nullptr;
2065 current_local_description_ = std::move(pending_local_description_);
2066 } else {
2067 replaced_remote_description = std::move(pending_remote_description_);
2068 pending_remote_description_ = std::move(desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002069 }
Steve Anton8a006912017-12-04 15:25:56 -08002070 // The session description to apply now must be accessed by
2071 // |remote_description()|.
Henrik Boströmfdb92012017-11-09 19:55:44 +01002072 RTC_DCHECK(remote_description());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002073
Steve Anton8a006912017-12-04 15:25:56 -08002074 // Transport and Media channels will be created only when offer is set.
Steve Antondcc3c022017-12-22 16:02:54 -08002075 if (IsUnifiedPlan()) {
2076 RTCError error = UpdateTransceiversAndDataChannels(
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002077 cricket::CS_REMOTE, *remote_description(), local_description(),
2078 old_remote_description);
Steve Anton8a006912017-12-04 15:25:56 -08002079 if (!error.ok()) {
2080 return error;
2081 }
Steve Antondcc3c022017-12-22 16:02:54 -08002082 } else {
2083 if (type == SdpType::kOffer) {
2084 // TODO(bugs.webrtc.org/4676) - Handle CreateChannel failure, as new local
2085 // description is applied. Restore back to old description.
2086 RTCError error = CreateChannels(*remote_description()->description());
2087 if (!error.ok()) {
2088 return error;
2089 }
2090 }
Steve Anton8a006912017-12-04 15:25:56 -08002091
Steve Antondcc3c022017-12-22 16:02:54 -08002092 // Remove unused channels if MediaContentDescription is rejected.
2093 RemoveUnusedChannels(remote_description()->description());
2094 }
Steve Anton8a006912017-12-04 15:25:56 -08002095
2096 // NOTE: Candidates allocation will be initiated only when SetLocalDescription
2097 // is called.
Steve Anton3828c062017-12-06 10:34:51 -08002098 error = UpdateSessionState(type, cricket::CS_REMOTE);
Steve Anton8a006912017-12-04 15:25:56 -08002099 if (!error.ok()) {
2100 return error;
2101 }
2102
2103 if (local_description() &&
2104 !UseCandidatesInSessionDescription(remote_description())) {
2105 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidCandidates);
2106 }
2107
2108 if (old_remote_description) {
2109 for (const cricket::ContentInfo& content :
2110 old_remote_description->description()->contents()) {
2111 // Check if this new SessionDescription contains new ICE ufrag and
2112 // password that indicates the remote peer requests an ICE restart.
2113 // TODO(deadbeef): When we start storing both the current and pending
2114 // remote description, this should reset pending_ice_restarts and compare
2115 // against the current description.
2116 if (CheckForRemoteIceRestart(old_remote_description, remote_description(),
2117 content.name)) {
Steve Anton3828c062017-12-06 10:34:51 -08002118 if (type == SdpType::kOffer) {
Steve Anton8a006912017-12-04 15:25:56 -08002119 pending_ice_restarts_.insert(content.name);
2120 }
2121 } else {
2122 // We retain all received candidates only if ICE is not restarted.
2123 // When ICE is restarted, all previous candidates belong to an old
2124 // generation and should not be kept.
2125 // TODO(deadbeef): This goes against the W3C spec which says the remote
2126 // description should only contain candidates from the last set remote
2127 // description plus any candidates added since then. We should remove
2128 // this once we're sure it won't break anything.
2129 WebRtcSessionDescriptionFactory::CopyCandidatesFromSessionDescription(
2130 old_remote_description, content.name, mutable_remote_description());
2131 }
2132 }
2133 }
2134
2135 if (session_error() != SessionError::kNone) {
2136 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
2137 }
2138
2139 // Set the the ICE connection state to connecting since the connection may
2140 // become writable with peer reflexive candidates before any remote candidate
2141 // is signaled.
2142 // TODO(pthatcher): This is a short-term solution for crbug/446908. A real fix
2143 // is to have a new signal the indicates a change in checking state from the
2144 // transport and expose a new checking() member from transport that can be
2145 // read to determine the current checking state. The existing SignalConnecting
2146 // actually means "gathering candidates", so cannot be be used here.
Steve Antona3a92c22017-12-07 10:27:41 -08002147 if (remote_description()->GetType() != SdpType::kOffer &&
Steve Anton8a006912017-12-04 15:25:56 -08002148 ice_connection_state() == PeerConnectionInterface::kIceConnectionNew) {
2149 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
2150 }
2151
deadbeefab9b2d12015-10-14 11:33:11 -07002152 // If setting the description decided our SSL role, allocate any necessary
2153 // SCTP sids.
2154 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08002155 if (data_channel_type() == cricket::DCT_SCTP && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07002156 AllocateSctpSids(role);
2157 }
2158
Steve Antondcc3c022017-12-22 16:02:54 -08002159 if (IsUnifiedPlan()) {
Steve Antonef65ef12018-01-10 17:15:20 -08002160 std::vector<TrackEvent> track_events;
Steve Antonc49bcd92018-02-14 14:28:13 -08002161 std::vector<rtc::scoped_refptr<MediaStreamInterface>> added_streams;
Steve Antondcc3c022017-12-22 16:02:54 -08002162 for (auto transceiver : transceivers_) {
2163 const ContentInfo* content =
2164 FindMediaSectionForTransceiver(transceiver, remote_description());
2165 if (!content) {
2166 continue;
2167 }
2168 const MediaContentDescription* media_desc = content->media_description();
2169 RtpTransceiverDirection local_direction =
2170 RtpTransceiverDirectionReversed(media_desc->direction());
2171 // From the WebRTC specification, steps 2.2.8.5/6 of section 4.4.1.6 "Set
2172 // the RTCSessionDescription: If direction is sendrecv or recvonly, and
2173 // transceiver's current direction is neither sendrecv nor recvonly,
2174 // process the addition of a remote track for the media description.
2175 if (RtpTransceiverDirectionHasRecv(local_direction) &&
2176 (!transceiver->current_direction() ||
2177 !RtpTransceiverDirectionHasRecv(
Steve Anton74255ff2018-01-24 18:32:57 -08002178 *transceiver->current_direction())) &&
2179 !media_desc->streams().empty()) {
Steve Antonef65ef12018-01-10 17:15:20 -08002180 const std::string& sync_label = media_desc->streams()[0].sync_label;
2181 rtc::scoped_refptr<MediaStreamInterface> stream =
2182 remote_streams_->find(sync_label);
2183 if (!stream) {
2184 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
2185 MediaStream::Create(sync_label));
2186 remote_streams_->AddStream(stream);
Steve Antonc49bcd92018-02-14 14:28:13 -08002187 added_streams.push_back(stream);
Steve Antonef65ef12018-01-10 17:15:20 -08002188 }
2189 transceiver->internal()->receiver_internal()->SetStreams({stream});
2190 TrackEvent track_event;
2191 track_event.receiver = transceiver->receiver();
2192 track_event.streams = transceiver->receiver()->streams();
2193 track_events.push_back(std::move(track_event));
Steve Antondcc3c022017-12-22 16:02:54 -08002194 }
2195 // If direction is sendonly or inactive, and transceiver's current
2196 // direction is neither sendonly nor inactive, process the removal of a
2197 // remote track for the media description.
2198 if (!RtpTransceiverDirectionHasRecv(local_direction) &&
Steve Antonef65ef12018-01-10 17:15:20 -08002199 (transceiver->current_direction() &&
Steve Antondcc3c022017-12-22 16:02:54 -08002200 RtpTransceiverDirectionHasRecv(*transceiver->current_direction()))) {
Steve Antonef65ef12018-01-10 17:15:20 -08002201 transceiver->internal()->receiver_internal()->SetStreams({});
Steve Antondcc3c022017-12-22 16:02:54 -08002202 }
2203 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
2204 transceiver->internal()->set_current_direction(local_direction);
2205 }
2206 if (content->rejected && !transceiver->stopped()) {
2207 transceiver->Stop();
2208 }
Steve Anton74255ff2018-01-24 18:32:57 -08002209 if (!content->rejected && !media_desc->streams().empty()) {
Steve Antond3679212018-01-17 17:41:02 -08002210 transceiver->internal()->receiver_internal()->SetupMediaChannel(
Steve Anton5f94aa22018-02-01 10:58:30 -08002211 media_desc->streams()[0].first_ssrc());
Steve Antond3679212018-01-17 17:41:02 -08002212 }
Steve Antondcc3c022017-12-22 16:02:54 -08002213 }
Steve Antonc49bcd92018-02-14 14:28:13 -08002214 // Once all processing has finished, fire off callbacks.
Steve Antonef65ef12018-01-10 17:15:20 -08002215 for (auto event : track_events) {
2216 observer_->OnAddTrack(event.receiver, event.streams);
2217 }
Steve Antonc49bcd92018-02-14 14:28:13 -08002218 for (auto stream : added_streams) {
2219 observer_->OnAddStream(stream);
2220 }
Steve Antondcc3c022017-12-22 16:02:54 -08002221 }
2222
Henrik Boströmfdb92012017-11-09 19:55:44 +01002223 const cricket::ContentInfo* audio_content =
2224 GetFirstAudioContent(remote_description()->description());
2225 const cricket::ContentInfo* video_content =
2226 GetFirstVideoContent(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002227 const cricket::AudioContentDescription* audio_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002228 GetFirstAudioContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002229 const cricket::VideoContentDescription* video_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002230 GetFirstVideoContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002231 const cricket::DataContentDescription* data_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002232 GetFirstDataContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002233
2234 // Check if the descriptions include streams, just in case the peer supports
2235 // MSID, but doesn't indicate so with "a=msid-semantic".
Henrik Boströmfdb92012017-11-09 19:55:44 +01002236 if (remote_description()->description()->msid_supported() ||
deadbeefbda7e0b2015-12-08 17:13:40 -08002237 (audio_desc && !audio_desc->streams().empty()) ||
2238 (video_desc && !video_desc->streams().empty())) {
2239 remote_peer_supports_msid_ = true;
2240 }
deadbeefab9b2d12015-10-14 11:33:11 -07002241
2242 // We wait to signal new streams until we finish processing the description,
2243 // since only at that point will new streams have all their tracks.
2244 rtc::scoped_refptr<StreamCollection> new_streams(StreamCollection::Create());
2245
Steve Antondcc3c022017-12-22 16:02:54 -08002246 if (!IsUnifiedPlan()) {
2247 // TODO(steveanton): When removing RTP senders/receivers in response to a
2248 // rejected media section, there is some cleanup logic that expects the
2249 // voice/ video channel to still be set. But in this method the voice/video
2250 // channel would have been destroyed by the SetRemoteDescription caller
2251 // above so the cleanup that relies on them fails to run. The RemoveSenders
2252 // calls should be moved to right before the DestroyChannel calls to fix
2253 // this.
Steve Anton8d3444d2017-10-20 15:30:51 -07002254
Steve Antondcc3c022017-12-22 16:02:54 -08002255 // Find all audio rtp streams and create corresponding remote AudioTracks
2256 // and MediaStreams.
2257 if (audio_content) {
2258 if (audio_content->rejected) {
2259 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
2260 } else {
2261 bool default_audio_track_needed =
2262 !remote_peer_supports_msid_ &&
2263 RtpTransceiverDirectionHasSend(audio_desc->direction());
2264 UpdateRemoteSendersList(GetActiveStreams(audio_desc),
2265 default_audio_track_needed, audio_desc->type(),
2266 new_streams);
2267 }
deadbeeffaac4972015-11-12 15:33:07 -08002268 }
deadbeefab9b2d12015-10-14 11:33:11 -07002269
Steve Antondcc3c022017-12-22 16:02:54 -08002270 // Find all video rtp streams and create corresponding remote VideoTracks
2271 // and MediaStreams.
2272 if (video_content) {
2273 if (video_content->rejected) {
2274 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
2275 } else {
2276 bool default_video_track_needed =
2277 !remote_peer_supports_msid_ &&
2278 RtpTransceiverDirectionHasSend(video_desc->direction());
2279 UpdateRemoteSendersList(GetActiveStreams(video_desc),
2280 default_video_track_needed, video_desc->type(),
2281 new_streams);
2282 }
deadbeeffaac4972015-11-12 15:33:07 -08002283 }
deadbeefab9b2d12015-10-14 11:33:11 -07002284
Steve Antondcc3c022017-12-22 16:02:54 -08002285 // Update the DataChannels with the information from the remote peer.
2286 if (data_desc) {
2287 if (rtc::starts_with(data_desc->protocol().data(),
2288 cricket::kMediaProtocolRtpPrefix)) {
2289 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
2290 }
deadbeefab9b2d12015-10-14 11:33:11 -07002291 }
deadbeefab9b2d12015-10-14 11:33:11 -07002292
Steve Antondcc3c022017-12-22 16:02:54 -08002293 // Iterate new_streams and notify the observer about new MediaStreams.
2294 for (size_t i = 0; i < new_streams->count(); ++i) {
2295 MediaStreamInterface* new_stream = new_streams->at(i);
2296 stats_->AddStream(new_stream);
2297 observer_->OnAddStream(
2298 rtc::scoped_refptr<MediaStreamInterface>(new_stream));
2299 }
deadbeefab9b2d12015-10-14 11:33:11 -07002300
Steve Antondcc3c022017-12-22 16:02:54 -08002301 UpdateEndedRemoteMediaStreams();
2302 }
deadbeefab9b2d12015-10-14 11:33:11 -07002303
Steve Anton8a006912017-12-04 15:25:56 -08002304 return RTCError::OK();
deadbeeffc648b62015-10-13 16:42:33 -07002305}
2306
Steve Antondcc3c022017-12-22 16:02:54 -08002307RTCError PeerConnection::UpdateTransceiversAndDataChannels(
2308 cricket::ContentSource source,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002309 const SessionDescriptionInterface& new_session,
2310 const SessionDescriptionInterface* old_local_description,
2311 const SessionDescriptionInterface* old_remote_description) {
Steve Antondcc3c022017-12-22 16:02:54 -08002312 RTC_DCHECK(IsUnifiedPlan());
2313
Steve Anton7464fca2018-01-19 11:10:37 -08002314 const cricket::ContentGroup* bundle_group = nullptr;
2315 if (new_session.GetType() == SdpType::kOffer) {
2316 auto bundle_group_or_error =
2317 GetEarlyBundleGroup(*new_session.description());
2318 if (!bundle_group_or_error.ok()) {
2319 return bundle_group_or_error.MoveError();
2320 }
2321 bundle_group = bundle_group_or_error.MoveValue();
Steve Antondcc3c022017-12-22 16:02:54 -08002322 }
Steve Antondcc3c022017-12-22 16:02:54 -08002323
Steve Antondcc3c022017-12-22 16:02:54 -08002324 const ContentInfos& new_contents = new_session.description()->contents();
Steve Antondcc3c022017-12-22 16:02:54 -08002325 for (size_t i = 0; i < new_contents.size(); ++i) {
2326 const cricket::ContentInfo& new_content = new_contents[i];
Steve Antondcc3c022017-12-22 16:02:54 -08002327 cricket::MediaType media_type = new_content.media_description()->type();
2328 seen_mids_.insert(new_content.name);
2329 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
2330 media_type == cricket::MEDIA_TYPE_VIDEO) {
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002331 const cricket::ContentInfo* old_local_content = nullptr;
2332 if (old_local_description &&
2333 i < old_local_description->description()->contents().size()) {
2334 old_local_content =
2335 &old_local_description->description()->contents()[i];
2336 }
2337 const cricket::ContentInfo* old_remote_content = nullptr;
2338 if (old_remote_description &&
2339 i < old_remote_description->description()->contents().size()) {
2340 old_remote_content =
2341 &old_remote_description->description()->contents()[i];
2342 }
Steve Antondcc3c022017-12-22 16:02:54 -08002343 auto transceiver_or_error =
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002344 AssociateTransceiver(source, new_session.GetType(), i, new_content,
2345 old_local_content, old_remote_content);
Steve Antondcc3c022017-12-22 16:02:54 -08002346 if (!transceiver_or_error.ok()) {
2347 return transceiver_or_error.MoveError();
2348 }
2349 auto transceiver = transceiver_or_error.MoveValue();
Steve Antondcc3c022017-12-22 16:02:54 -08002350 RTCError error =
2351 UpdateTransceiverChannel(transceiver, new_content, bundle_group);
2352 if (!error.ok()) {
2353 return error;
2354 }
2355 } else if (media_type == cricket::MEDIA_TYPE_DATA) {
Steve Antonfa2260d2017-12-28 16:38:23 -08002356 if (GetDataMid() && new_content.name != *GetDataMid()) {
2357 // Ignore all but the first data section.
2358 continue;
2359 }
2360 RTCError error = UpdateDataChannel(source, new_content, bundle_group);
2361 if (!error.ok()) {
2362 return error;
2363 }
Steve Antondcc3c022017-12-22 16:02:54 -08002364 } else {
2365 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
2366 "Unknown section type.");
2367 }
2368 }
2369
2370 return RTCError::OK();
2371}
2372
2373RTCError PeerConnection::UpdateTransceiverChannel(
2374 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2375 transceiver,
2376 const cricket::ContentInfo& content,
2377 const cricket::ContentGroup* bundle_group) {
2378 RTC_DCHECK(IsUnifiedPlan());
2379 RTC_DCHECK(transceiver);
2380 cricket::BaseChannel* channel = transceiver->internal()->channel();
2381 if (content.rejected) {
2382 if (channel) {
2383 transceiver->internal()->SetChannel(nullptr);
2384 DestroyBaseChannel(channel);
2385 }
2386 } else {
2387 if (!channel) {
Steve Anton69470252018-02-09 11:43:08 -08002388 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Steve Antondcc3c022017-12-22 16:02:54 -08002389 channel = CreateVoiceChannel(
2390 content.name,
2391 GetTransportNameForMediaSection(content.name, bundle_group));
2392 } else {
Steve Anton69470252018-02-09 11:43:08 -08002393 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, transceiver->media_type());
Steve Antondcc3c022017-12-22 16:02:54 -08002394 channel = CreateVideoChannel(
2395 content.name,
2396 GetTransportNameForMediaSection(content.name, bundle_group));
2397 }
2398 if (!channel) {
2399 LOG_AND_RETURN_ERROR(
2400 RTCErrorType::INTERNAL_ERROR,
2401 "Failed to create channel for mid=" + content.name);
2402 }
2403 transceiver->internal()->SetChannel(channel);
2404 }
2405 }
2406 return RTCError::OK();
2407}
2408
Steve Antonfa2260d2017-12-28 16:38:23 -08002409RTCError PeerConnection::UpdateDataChannel(
2410 cricket::ContentSource source,
2411 const cricket::ContentInfo& content,
2412 const cricket::ContentGroup* bundle_group) {
2413 if (data_channel_type_ == cricket::DCT_NONE) {
Steve Antondbf9d032018-01-19 15:23:40 -08002414 // If data channels are disabled, ignore this media section. CreateAnswer
2415 // will take care of rejecting it.
2416 return RTCError::OK();
Steve Antonfa2260d2017-12-28 16:38:23 -08002417 }
2418 if (content.rejected) {
2419 DestroyDataChannel();
2420 } else {
2421 if (!rtp_data_channel_ && !sctp_transport_) {
2422 if (!CreateDataChannel(content.name, GetTransportNameForMediaSection(
2423 content.name, bundle_group))) {
2424 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
2425 "Failed to create data channel.");
2426 }
2427 }
2428 if (source == cricket::CS_REMOTE) {
2429 const MediaContentDescription* data_desc = content.media_description();
2430 if (data_desc && cricket::IsRtpProtocol(data_desc->protocol())) {
2431 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
2432 }
2433 }
2434 }
2435 return RTCError::OK();
2436}
2437
Steve Antondcc3c022017-12-22 16:02:54 -08002438RTCErrorOr<rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
2439PeerConnection::AssociateTransceiver(cricket::ContentSource source,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002440 SdpType type,
Steve Antondcc3c022017-12-22 16:02:54 -08002441 size_t mline_index,
2442 const ContentInfo& content,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002443 const ContentInfo* old_local_content,
2444 const ContentInfo* old_remote_content) {
Steve Antondcc3c022017-12-22 16:02:54 -08002445 RTC_DCHECK(IsUnifiedPlan());
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002446 // If this is an offer then the m= section might be recycled. If the m=
2447 // section is being recycled (defined as: rejected in the current local or
2448 // remote description and not rejected in new description), dissociate the
2449 // currently associated RtpTransceiver by setting its mid property to null,
2450 // and discard the mapping between the transceiver and its m= section index.
2451 if (IsMediaSectionBeingRecycled(type, content, old_local_content,
2452 old_remote_content)) {
2453 // We want to dissociate the transceiver that has the rejected mid.
2454 const std::string& old_mid =
2455 (old_local_content && old_local_content->rejected)
2456 ? old_local_content->name
2457 : old_remote_content->name;
2458 auto old_transceiver = GetAssociatedTransceiver(old_mid);
Steve Antondcc3c022017-12-22 16:02:54 -08002459 if (old_transceiver) {
2460 old_transceiver->internal()->set_mid(rtc::nullopt);
2461 old_transceiver->internal()->set_mline_index(rtc::nullopt);
2462 }
2463 }
2464 const MediaContentDescription* media_desc = content.media_description();
2465 auto transceiver = GetAssociatedTransceiver(content.name);
2466 if (source == cricket::CS_LOCAL) {
2467 // Find the RtpTransceiver that corresponds to this m= section, using the
2468 // mapping between transceivers and m= section indices established when
2469 // creating the offer.
2470 if (!transceiver) {
2471 transceiver = GetTransceiverByMLineIndex(mline_index);
2472 }
2473 if (!transceiver) {
2474 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2475 "Unknown transceiver");
2476 }
2477 } else {
2478 RTC_DCHECK_EQ(source, cricket::CS_REMOTE);
2479 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers
2480 // of the same type...
2481 if (!transceiver &&
2482 RtpTransceiverDirectionHasRecv(media_desc->direction())) {
2483 transceiver = FindAvailableTransceiverToReceive(media_desc->type());
2484 }
2485 // If no RtpTransceiver was found in the previous step, create one with a
2486 // recvonly direction.
2487 if (!transceiver) {
Steve Anton02ee47c2018-01-10 16:26:06 -08002488 auto sender =
2489 CreateSender(media_desc->type(), nullptr, {rtc::CreateRandomUuid()});
Steve Anton5f94aa22018-02-01 10:58:30 -08002490 std::string receiver_id;
2491 if (!media_desc->streams().empty()) {
2492 receiver_id = media_desc->streams()[0].id;
2493 } else {
2494 receiver_id = rtc::CreateRandomUuid();
2495 }
2496 auto receiver = CreateReceiver(media_desc->type(), receiver_id);
Steve Anton02ee47c2018-01-10 16:26:06 -08002497 transceiver = CreateAndAddTransceiver(sender, receiver);
Steve Antondcc3c022017-12-22 16:02:54 -08002498 transceiver->internal()->set_direction(
2499 RtpTransceiverDirection::kRecvOnly);
2500 }
2501 }
2502 RTC_DCHECK(transceiver);
Steve Anton69470252018-02-09 11:43:08 -08002503 if (transceiver->media_type() != media_desc->type()) {
Steve Antondcc3c022017-12-22 16:02:54 -08002504 LOG_AND_RETURN_ERROR(
2505 RTCErrorType::INVALID_PARAMETER,
2506 "Transceiver type does not match media description type.");
2507 }
2508 // Associate the found or created RtpTransceiver with the m= section by
2509 // setting the value of the RtpTransceiver's mid property to the MID of the m=
2510 // section, and establish a mapping between the transceiver and the index of
2511 // the m= section.
2512 transceiver->internal()->set_mid(content.name);
2513 transceiver->internal()->set_mline_index(mline_index);
2514 return std::move(transceiver);
2515}
2516
2517rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2518PeerConnection::GetAssociatedTransceiver(const std::string& mid) const {
2519 RTC_DCHECK(IsUnifiedPlan());
2520 for (auto transceiver : transceivers_) {
2521 if (transceiver->mid() == mid) {
2522 return transceiver;
2523 }
2524 }
2525 return nullptr;
2526}
2527
2528rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2529PeerConnection::GetTransceiverByMLineIndex(size_t mline_index) const {
2530 RTC_DCHECK(IsUnifiedPlan());
2531 for (auto transceiver : transceivers_) {
2532 if (transceiver->internal()->mline_index() == mline_index) {
2533 return transceiver;
2534 }
2535 }
2536 return nullptr;
2537}
2538
2539rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2540PeerConnection::FindAvailableTransceiverToReceive(
2541 cricket::MediaType media_type) const {
2542 RTC_DCHECK(IsUnifiedPlan());
2543 // From JSEP section 5.10 (Applying a Remote Description):
2544 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers of
2545 // the same type that were added to the PeerConnection by addTrack and are not
2546 // associated with any m= section and are not stopped, find the first such
2547 // RtpTransceiver.
2548 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08002549 if (transceiver->media_type() == media_type &&
Steve Antondcc3c022017-12-22 16:02:54 -08002550 transceiver->internal()->created_by_addtrack() && !transceiver->mid() &&
2551 !transceiver->stopped()) {
2552 return transceiver;
2553 }
2554 }
2555 return nullptr;
2556}
2557
Steve Antoned10bd92017-12-05 10:52:59 -08002558const cricket::ContentInfo* PeerConnection::FindMediaSectionForTransceiver(
2559 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2560 transceiver,
2561 const SessionDescriptionInterface* sdesc) const {
2562 RTC_DCHECK(transceiver);
2563 RTC_DCHECK(sdesc);
2564 if (IsUnifiedPlan()) {
2565 if (!transceiver->internal()->mid()) {
2566 // This transceiver is not associated with a media section yet.
2567 return nullptr;
2568 }
2569 return sdesc->description()->GetContentByName(
2570 *transceiver->internal()->mid());
2571 } else {
2572 // Plan B only allows at most one audio and one video section, so use the
2573 // first media section of that type.
2574 return cricket::GetFirstMediaContent(sdesc->description()->contents(),
Steve Anton69470252018-02-09 11:43:08 -08002575 transceiver->media_type());
Steve Antoned10bd92017-12-05 10:52:59 -08002576 }
2577}
2578
deadbeef46c73892016-11-16 19:42:04 -08002579PeerConnectionInterface::RTCConfiguration PeerConnection::GetConfiguration() {
2580 return configuration_;
2581}
2582
deadbeef293e9262017-01-11 12:28:30 -08002583bool PeerConnection::SetConfiguration(const RTCConfiguration& configuration,
2584 RTCError* error) {
Peter Boström1a9d6152015-12-08 22:15:17 +01002585 TRACE_EVENT0("webrtc", "PeerConnection::SetConfiguration");
deadbeef6de92f92016-12-12 18:49:32 -08002586
Steve Anton75737c02017-11-06 10:37:17 -08002587 if (local_description() && configuration.ice_candidate_pool_size !=
2588 configuration_.ice_candidate_pool_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002589 RTC_LOG(LS_ERROR) << "Can't change candidate pool size after calling "
2590 "SetLocalDescription.";
deadbeef293e9262017-01-11 12:28:30 -08002591 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00002592 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002593
deadbeef293e9262017-01-11 12:28:30 -08002594 // The simplest (and most future-compatible) way to tell if the config was
2595 // modified in an invalid way is to copy each property we do support
2596 // modifying, then use operator==. There are far more properties we don't
2597 // support modifying than those we do, and more could be added.
2598 RTCConfiguration modified_config = configuration_;
2599 modified_config.servers = configuration.servers;
2600 modified_config.type = configuration.type;
2601 modified_config.ice_candidate_pool_size =
2602 configuration.ice_candidate_pool_size;
2603 modified_config.prune_turn_ports = configuration.prune_turn_ports;
skvladd1f5fda2017-02-03 16:54:05 -08002604 modified_config.ice_check_min_interval = configuration.ice_check_min_interval;
Jonas Orelandbdcee282017-10-10 14:01:40 +02002605 modified_config.turn_customizer = configuration.turn_customizer;
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08002606 modified_config.network_preference = configuration.network_preference;
deadbeef293e9262017-01-11 12:28:30 -08002607 if (configuration != modified_config) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002608 RTC_LOG(LS_ERROR) << "Modifying the configuration in an unsupported way.";
deadbeef293e9262017-01-11 12:28:30 -08002609 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
2610 }
2611
Steve Anton038834f2017-07-14 15:59:59 -07002612 // Validate the modified configuration.
2613 RTCError validate_error = ValidateConfiguration(modified_config);
2614 if (!validate_error.ok()) {
2615 return SafeSetError(std::move(validate_error), error);
2616 }
2617
deadbeef293e9262017-01-11 12:28:30 -08002618 // Note that this isn't possible through chromium, since it's an unsigned
2619 // short in WebIDL.
2620 if (configuration.ice_candidate_pool_size < 0 ||
2621 configuration.ice_candidate_pool_size > UINT16_MAX) {
2622 return SafeSetError(RTCErrorType::INVALID_RANGE, error);
2623 }
2624
2625 // Parse ICE servers before hopping to network thread.
2626 cricket::ServerAddresses stun_servers;
2627 std::vector<cricket::RelayServerConfig> turn_servers;
2628 RTCErrorType parse_error =
2629 ParseIceServers(configuration.servers, &stun_servers, &turn_servers);
2630 if (parse_error != RTCErrorType::NONE) {
2631 return SafeSetError(parse_error, error);
2632 }
2633
2634 // In theory this shouldn't fail.
2635 if (!network_thread()->Invoke<bool>(
2636 RTC_FROM_HERE,
2637 rtc::Bind(&PeerConnection::ReconfigurePortAllocator_n, this,
2638 stun_servers, turn_servers, modified_config.type,
2639 modified_config.ice_candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02002640 modified_config.prune_turn_ports,
2641 modified_config.turn_customizer))) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002642 RTC_LOG(LS_ERROR) << "Failed to apply configuration to PortAllocator.";
deadbeef293e9262017-01-11 12:28:30 -08002643 return SafeSetError(RTCErrorType::INTERNAL_ERROR, error);
2644 }
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07002645
deadbeefd1a38b52016-12-10 13:15:33 -08002646 // As described in JSEP, calling setConfiguration with new ICE servers or
2647 // candidate policy must set a "needs-ice-restart" bit so that the next offer
2648 // triggers an ICE restart which will pick up the changes.
deadbeef293e9262017-01-11 12:28:30 -08002649 if (modified_config.servers != configuration_.servers ||
2650 modified_config.type != configuration_.type ||
2651 modified_config.prune_turn_ports != configuration_.prune_turn_ports) {
Steve Antond25da372017-11-06 14:50:29 -08002652 transport_controller_->SetNeedsIceRestartFlag();
deadbeefd1a38b52016-12-10 13:15:33 -08002653 }
skvladd1f5fda2017-02-03 16:54:05 -08002654
Qingsi Wang9c98f0c2018-02-15 15:10:59 -08002655 transport_controller_->SetIceConfig(ParseIceConfig(modified_config));
skvladd1f5fda2017-02-03 16:54:05 -08002656
deadbeef293e9262017-01-11 12:28:30 -08002657 configuration_ = modified_config;
2658 return SafeSetError(RTCErrorType::NONE, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00002659}
2660
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002661bool PeerConnection::AddIceCandidate(
2662 const IceCandidateInterface* ice_candidate) {
Peter Boström1a9d6152015-12-08 22:15:17 +01002663 TRACE_EVENT0("webrtc", "PeerConnection::AddIceCandidate");
zhihuang29ff8442016-07-27 11:07:25 -07002664 if (IsClosed()) {
2665 return false;
2666 }
Steve Antond25da372017-11-06 14:50:29 -08002667
2668 if (!remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002669 RTC_LOG(LS_ERROR) << "ProcessIceMessage: ICE candidates can't be added "
Jonas Olsson45cc8902018-02-13 10:37:07 +01002670 "without any remote session description.";
Steve Antond25da372017-11-06 14:50:29 -08002671 return false;
2672 }
2673
2674 if (!ice_candidate) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002675 RTC_LOG(LS_ERROR) << "ProcessIceMessage: Candidate is NULL.";
Steve Antond25da372017-11-06 14:50:29 -08002676 return false;
2677 }
2678
2679 bool valid = false;
2680 bool ready = ReadyToUseRemoteCandidate(ice_candidate, nullptr, &valid);
2681 if (!valid) {
2682 return false;
2683 }
2684
2685 // Add this candidate to the remote session description.
2686 if (!mutable_remote_description()->AddCandidate(ice_candidate)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002687 RTC_LOG(LS_ERROR) << "ProcessIceMessage: Candidate cannot be used.";
Steve Antond25da372017-11-06 14:50:29 -08002688 return false;
2689 }
2690
2691 if (ready) {
2692 return UseCandidate(ice_candidate);
2693 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002694 RTC_LOG(LS_INFO) << "ProcessIceMessage: Not ready to use candidate.";
Steve Antond25da372017-11-06 14:50:29 -08002695 return true;
2696 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002697}
2698
Honghai Zhang7fb69db2016-03-14 11:59:18 -07002699bool PeerConnection::RemoveIceCandidates(
2700 const std::vector<cricket::Candidate>& candidates) {
2701 TRACE_EVENT0("webrtc", "PeerConnection::RemoveIceCandidates");
Steve Antond25da372017-11-06 14:50:29 -08002702 if (!remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002703 RTC_LOG(LS_ERROR) << "RemoveRemoteIceCandidates: ICE candidates can't be "
Jonas Olsson45cc8902018-02-13 10:37:07 +01002704 "removed without any remote session description.";
Steve Antond25da372017-11-06 14:50:29 -08002705 return false;
2706 }
2707
2708 if (candidates.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002709 RTC_LOG(LS_ERROR) << "RemoveRemoteIceCandidates: candidates are empty.";
Steve Antond25da372017-11-06 14:50:29 -08002710 return false;
2711 }
2712
2713 size_t number_removed =
2714 mutable_remote_description()->RemoveCandidates(candidates);
2715 if (number_removed != candidates.size()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002716 RTC_LOG(LS_ERROR)
2717 << "RemoveRemoteIceCandidates: Failed to remove candidates. "
Jonas Olsson45cc8902018-02-13 10:37:07 +01002718 "Requested "
2719 << candidates.size() << " but only " << number_removed
Mirko Bonadei675513b2017-11-09 11:09:25 +01002720 << " are removed.";
Steve Antond25da372017-11-06 14:50:29 -08002721 }
2722
2723 // Remove the candidates from the transport controller.
2724 std::string error;
2725 bool res = transport_controller_->RemoveRemoteCandidates(candidates, &error);
2726 if (!res && !error.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002727 RTC_LOG(LS_ERROR) << "Error when removing remote candidates: " << error;
Steve Antond25da372017-11-06 14:50:29 -08002728 }
2729 return true;
Honghai Zhang7fb69db2016-03-14 11:59:18 -07002730}
2731
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00002732void PeerConnection::RegisterUMAObserver(UMAObserver* observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +01002733 TRACE_EVENT0("webrtc", "PeerConnection::RegisterUmaObserver");
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00002734 uma_observer_ = observer;
guoweis@webrtc.org7169afd2014-12-04 17:59:29 +00002735
Steve Anton75737c02017-11-06 10:37:17 -08002736 if (transport_controller()) {
2737 transport_controller()->SetMetricsObserver(uma_observer_);
guoweis@webrtc.org7169afd2014-12-04 17:59:29 +00002738 }
2739
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00002740 // Send information about IPv4/IPv6 status.
deadbeef293e9262017-01-11 12:28:30 -08002741 if (uma_observer_) {
Honghai Zhangd93f50c2016-10-05 11:47:22 -07002742 port_allocator_->SetMetricsObserver(uma_observer_);
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00002743 if (port_allocator_->flags() & cricket::PORTALLOCATOR_ENABLE_IPV6) {
Guo-wei Shiehdfbe6792015-09-03 17:12:07 -07002744 uma_observer_->IncrementEnumCounter(
2745 kEnumCounterAddressFamily, kPeerConnection_IPv6,
2746 kPeerConnectionAddressFamilyCounter_Max);
mallinath@webrtc.orgb445f262014-05-23 22:19:37 +00002747 } else {
Guo-wei Shiehdfbe6792015-09-03 17:12:07 -07002748 uma_observer_->IncrementEnumCounter(
2749 kEnumCounterAddressFamily, kPeerConnection_IPv4,
2750 kPeerConnectionAddressFamilyCounter_Max);
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00002751 }
Harald Alvestrand5dbb5862018-02-13 23:48:00 +01002752 // Send information about the requested SDP semantics.
2753 switch (configuration_.sdp_semantics) {
2754 case SdpSemantics::kDefault:
2755 uma_observer_->IncrementEnumCounter(kEnumCounterSdpSemanticRequested,
2756 kSdpSemanticRequestDefault,
2757 kSdpSemanticRequestMax);
2758
2759 break;
2760 case SdpSemantics::kPlanB:
2761 uma_observer_->IncrementEnumCounter(kEnumCounterSdpSemanticRequested,
2762 kSdpSemanticRequestPlanB,
2763 kSdpSemanticRequestMax);
2764 break;
2765 case SdpSemantics::kUnifiedPlan:
2766 uma_observer_->IncrementEnumCounter(kEnumCounterSdpSemanticRequested,
2767 kSdpSemanticRequestUnifiedPlan,
2768 kSdpSemanticRequestMax);
2769 break;
2770 default:
2771 RTC_NOTREACHED();
2772 }
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00002773 }
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00002774}
2775
zstein4b979802017-06-02 14:37:37 -07002776RTCError PeerConnection::SetBitrate(const BitrateParameters& bitrate) {
Steve Anton978b8762017-09-29 12:15:02 -07002777 if (!worker_thread()->IsCurrent()) {
2778 return worker_thread()->Invoke<RTCError>(
zstein4b979802017-06-02 14:37:37 -07002779 RTC_FROM_HERE, rtc::Bind(&PeerConnection::SetBitrate, this, bitrate));
2780 }
2781
2782 const bool has_min = static_cast<bool>(bitrate.min_bitrate_bps);
2783 const bool has_current = static_cast<bool>(bitrate.current_bitrate_bps);
2784 const bool has_max = static_cast<bool>(bitrate.max_bitrate_bps);
2785 if (has_min && *bitrate.min_bitrate_bps < 0) {
2786 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2787 "min_bitrate_bps <= 0");
2788 }
2789 if (has_current) {
2790 if (has_min && *bitrate.current_bitrate_bps < *bitrate.min_bitrate_bps) {
2791 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2792 "current_bitrate_bps < min_bitrate_bps");
2793 } else if (*bitrate.current_bitrate_bps < 0) {
2794 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2795 "curent_bitrate_bps < 0");
2796 }
2797 }
2798 if (has_max) {
2799 if (has_current &&
2800 *bitrate.max_bitrate_bps < *bitrate.current_bitrate_bps) {
2801 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2802 "max_bitrate_bps < current_bitrate_bps");
2803 } else if (has_min && *bitrate.max_bitrate_bps < *bitrate.min_bitrate_bps) {
2804 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2805 "max_bitrate_bps < min_bitrate_bps");
2806 } else if (*bitrate.max_bitrate_bps < 0) {
2807 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2808 "max_bitrate_bps < 0");
2809 }
2810 }
2811
2812 Call::Config::BitrateConfigMask mask;
2813 mask.min_bitrate_bps = bitrate.min_bitrate_bps;
2814 mask.start_bitrate_bps = bitrate.current_bitrate_bps;
2815 mask.max_bitrate_bps = bitrate.max_bitrate_bps;
2816
2817 RTC_DCHECK(call_.get());
2818 call_->SetBitrateConfigMask(mask);
2819
2820 return RTCError::OK();
2821}
2822
Alex Narest78609d52017-10-20 10:37:47 +02002823void PeerConnection::SetBitrateAllocationStrategy(
2824 std::unique_ptr<rtc::BitrateAllocationStrategy>
2825 bitrate_allocation_strategy) {
2826 rtc::Thread* worker_thread = factory_->worker_thread();
2827 if (!worker_thread->IsCurrent()) {
2828 rtc::BitrateAllocationStrategy* strategy_raw =
2829 bitrate_allocation_strategy.release();
2830 auto functor = [this, strategy_raw]() {
2831 call_->SetBitrateAllocationStrategy(
2832 rtc::WrapUnique<rtc::BitrateAllocationStrategy>(strategy_raw));
2833 };
2834 worker_thread->Invoke<void>(RTC_FROM_HERE, functor);
2835 return;
2836 }
2837 RTC_DCHECK(call_.get());
2838 call_->SetBitrateAllocationStrategy(std::move(bitrate_allocation_strategy));
2839}
2840
henrika5f6bf242017-11-01 11:06:56 +01002841void PeerConnection::SetAudioPlayout(bool playout) {
2842 if (!worker_thread()->IsCurrent()) {
2843 worker_thread()->Invoke<void>(
2844 RTC_FROM_HERE,
2845 rtc::Bind(&PeerConnection::SetAudioPlayout, this, playout));
2846 return;
2847 }
2848 auto audio_state =
2849 factory_->channel_manager()->media_engine()->GetAudioState();
2850 audio_state->SetPlayout(playout);
2851}
2852
2853void PeerConnection::SetAudioRecording(bool recording) {
2854 if (!worker_thread()->IsCurrent()) {
2855 worker_thread()->Invoke<void>(
2856 RTC_FROM_HERE,
2857 rtc::Bind(&PeerConnection::SetAudioRecording, this, recording));
2858 return;
2859 }
2860 auto audio_state =
2861 factory_->channel_manager()->media_engine()->GetAudioState();
2862 audio_state->SetRecording(recording);
2863}
2864
Steve Anton8c0f7a72017-10-03 10:03:10 -07002865std::unique_ptr<rtc::SSLCertificate>
2866PeerConnection::GetRemoteAudioSSLCertificate() {
Steve Anton75737c02017-11-06 10:37:17 -08002867 if (!voice_channel()) {
Steve Anton8c0f7a72017-10-03 10:03:10 -07002868 return nullptr;
2869 }
Steve Anton75737c02017-11-06 10:37:17 -08002870 return GetRemoteSSLCertificate(voice_channel()->transport_name());
Steve Anton8c0f7a72017-10-03 10:03:10 -07002871}
2872
Zhi Huang70b820f2018-01-27 14:16:15 -08002873std::unique_ptr<rtc::SSLCertChain>
2874PeerConnection::GetRemoteAudioSSLCertChain() {
2875 if (!voice_channel()) {
2876 return nullptr;
2877 }
2878
2879 return transport_controller_->GetRemoteSSLCertChain(
2880 voice_channel()->transport_name());
2881}
2882
ivoc14d5dbe2016-07-04 07:06:55 -07002883bool PeerConnection::StartRtcEventLog(rtc::PlatformFile file,
2884 int64_t max_size_bytes) {
Elad Alon99c3fe52017-10-13 16:29:40 +02002885 // TODO(eladalon): It would be better to not allow negative values into PC.
2886 const size_t max_size = (max_size_bytes < 0)
2887 ? RtcEventLog::kUnlimitedOutput
2888 : rtc::saturated_cast<size_t>(max_size_bytes);
2889 return StartRtcEventLog(
Bjorn Tereliusde939432017-11-20 17:38:14 +01002890 rtc::MakeUnique<RtcEventLogOutputFile>(file, max_size),
2891 webrtc::RtcEventLog::kImmediateOutput);
Elad Alon99c3fe52017-10-13 16:29:40 +02002892}
2893
Bjorn Tereliusde939432017-11-20 17:38:14 +01002894bool PeerConnection::StartRtcEventLog(std::unique_ptr<RtcEventLogOutput> output,
2895 int64_t output_period_ms) {
Karl Wibergd6b48192017-10-16 23:01:06 +02002896 // TODO(eladalon): In C++14, this can be done with a lambda.
2897 struct Functor {
Bjorn Tereliusde939432017-11-20 17:38:14 +01002898 bool operator()() {
2899 return pc->StartRtcEventLog_w(std::move(output), output_period_ms);
2900 }
Karl Wibergd6b48192017-10-16 23:01:06 +02002901 PeerConnection* const pc;
2902 std::unique_ptr<RtcEventLogOutput> output;
Bjorn Tereliusde939432017-11-20 17:38:14 +01002903 const int64_t output_period_ms;
Elad Alon99c3fe52017-10-13 16:29:40 +02002904 };
Bjorn Tereliusde939432017-11-20 17:38:14 +01002905 return worker_thread()->Invoke<bool>(
2906 RTC_FROM_HERE, Functor{this, std::move(output), output_period_ms});
ivoc14d5dbe2016-07-04 07:06:55 -07002907}
2908
2909void PeerConnection::StopRtcEventLog() {
Steve Anton978b8762017-09-29 12:15:02 -07002910 worker_thread()->Invoke<void>(
ivoc14d5dbe2016-07-04 07:06:55 -07002911 RTC_FROM_HERE, rtc::Bind(&PeerConnection::StopRtcEventLog_w, this));
2912}
2913
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002914const SessionDescriptionInterface* PeerConnection::local_description() const {
Steve Anton75737c02017-11-06 10:37:17 -08002915 return pending_local_description_ ? pending_local_description_.get()
2916 : current_local_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002917}
2918
2919const SessionDescriptionInterface* PeerConnection::remote_description() const {
Steve Anton75737c02017-11-06 10:37:17 -08002920 return pending_remote_description_ ? pending_remote_description_.get()
2921 : current_remote_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002922}
2923
deadbeeffe4a8a42016-12-20 17:56:17 -08002924const SessionDescriptionInterface* PeerConnection::current_local_description()
2925 const {
Steve Anton75737c02017-11-06 10:37:17 -08002926 return current_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08002927}
2928
2929const SessionDescriptionInterface* PeerConnection::current_remote_description()
2930 const {
Steve Anton75737c02017-11-06 10:37:17 -08002931 return current_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08002932}
2933
2934const SessionDescriptionInterface* PeerConnection::pending_local_description()
2935 const {
Steve Anton75737c02017-11-06 10:37:17 -08002936 return pending_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08002937}
2938
2939const SessionDescriptionInterface* PeerConnection::pending_remote_description()
2940 const {
Steve Anton75737c02017-11-06 10:37:17 -08002941 return pending_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08002942}
2943
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002944void PeerConnection::Close() {
Peter Boström1a9d6152015-12-08 22:15:17 +01002945 TRACE_EVENT0("webrtc", "PeerConnection::Close");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002946 // Update stats here so that we have the most recent stats for tracks and
2947 // streams before the channels are closed.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00002948 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002949
Steve Anton75737c02017-11-06 10:37:17 -08002950 ChangeSignalingState(PeerConnectionInterface::kClosed);
Steve Anton3fe1b152017-12-12 10:20:08 -08002951
Steve Anton8af21862017-12-15 11:20:13 -08002952 for (auto transceiver : transceivers_) {
2953 transceiver->Stop();
2954 }
2955 DestroyAllChannels();
Steve Anton75737c02017-11-06 10:37:17 -08002956
Qingsi Wang93a84392018-01-30 17:13:09 -08002957 // The event log is used in the transport controller, which must be outlived
2958 // by the former. CreateOffer by the peer connection is implemented
2959 // asynchronously and if the peer connection is closed without resetting the
2960 // WebRTC session description factory, the session description factory would
2961 // call the transport controller.
2962 webrtc_session_desc_factory_.reset();
2963 transport_controller_.reset();
2964
deadbeef42a42632017-03-10 15:18:00 -08002965 network_thread()->Invoke<void>(
2966 RTC_FROM_HERE,
2967 rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
2968 port_allocator_.get()));
nisseeaabdf62017-05-05 02:23:02 -07002969
Steve Anton978b8762017-09-29 12:15:02 -07002970 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
eladalon248fd4f2017-09-06 05:18:15 -07002971 call_.reset();
2972 // The event log must outlive call (and any other object that uses it).
2973 event_log_.reset();
2974 });
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002975}
2976
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002977void PeerConnection::OnMessage(rtc::Message* msg) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002978 switch (msg->message_id) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002979 case MSG_SET_SESSIONDESCRIPTION_SUCCESS: {
2980 SetSessionDescriptionMsg* param =
2981 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
2982 param->observer->OnSuccess();
2983 delete param;
2984 break;
2985 }
2986 case MSG_SET_SESSIONDESCRIPTION_FAILED: {
2987 SetSessionDescriptionMsg* param =
2988 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
2989 param->observer->OnFailure(param->error);
2990 delete param;
2991 break;
2992 }
deadbeefab9b2d12015-10-14 11:33:11 -07002993 case MSG_CREATE_SESSIONDESCRIPTION_FAILED: {
2994 CreateSessionDescriptionMsg* param =
2995 static_cast<CreateSessionDescriptionMsg*>(msg->pdata);
2996 param->observer->OnFailure(param->error);
2997 delete param;
2998 break;
2999 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003000 case MSG_GETSTATS: {
3001 GetStatsMsg* param = static_cast<GetStatsMsg*>(msg->pdata);
nissee8abe3e2017-01-18 05:00:34 -08003002 StatsReports reports;
3003 stats_->GetStats(param->track, &reports);
3004 param->observer->OnComplete(reports);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003005 delete param;
3006 break;
3007 }
deadbeefbd292462015-12-14 18:15:29 -08003008 case MSG_FREE_DATACHANNELS: {
3009 sctp_data_channels_to_free_.clear();
3010 break;
3011 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003012 default:
nisseeb4ca4e2017-01-12 02:24:27 -08003013 RTC_NOTREACHED() << "Not implemented";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003014 break;
3015 }
3016}
3017
Steve Anton4171afb2017-11-20 10:20:22 -08003018void PeerConnection::CreateAudioReceiver(
3019 MediaStreamInterface* stream,
3020 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01003021 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
3022 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Steve Antond3679212018-01-17 17:41:02 -08003023 auto* audio_receiver = new AudioRtpReceiver(
3024 worker_thread(), remote_sender_info.sender_id, streams);
Guido Urdanetaee2388f2018-02-15 16:36:19 +00003025 audio_receiver->SetMediaChannel(voice_media_channel());
Steve Antond3679212018-01-17 17:41:02 -08003026 audio_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
3027 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
3028 signaling_thread(), audio_receiver);
Steve Anton4171afb2017-11-20 10:20:22 -08003029 GetAudioTransceiver()->internal()->AddReceiver(receiver);
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01003030 observer_->OnAddTrack(receiver, std::move(streams));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003031}
3032
Steve Anton4171afb2017-11-20 10:20:22 -08003033void PeerConnection::CreateVideoReceiver(
3034 MediaStreamInterface* stream,
3035 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01003036 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
3037 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Steve Antond3679212018-01-17 17:41:02 -08003038 auto* video_receiver = new VideoRtpReceiver(
3039 worker_thread(), remote_sender_info.sender_id, streams);
Guido Urdanetaee2388f2018-02-15 16:36:19 +00003040 video_receiver->SetMediaChannel(video_media_channel());
Steve Antond3679212018-01-17 17:41:02 -08003041 video_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
3042 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
3043 signaling_thread(), video_receiver);
Steve Anton4171afb2017-11-20 10:20:22 -08003044 GetVideoTransceiver()->internal()->AddReceiver(receiver);
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01003045 observer_->OnAddTrack(receiver, std::move(streams));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003046}
3047
deadbeef70ab1a12015-09-28 16:53:55 -07003048// TODO(deadbeef): Keep RtpReceivers around even if track goes away in remote
3049// description.
Henrik Boström933d8b02017-10-10 10:05:16 -07003050rtc::scoped_refptr<RtpReceiverInterface> PeerConnection::RemoveAndStopReceiver(
Steve Anton4171afb2017-11-20 10:20:22 -08003051 const RtpSenderInfo& remote_sender_info) {
3052 auto receiver = FindReceiverById(remote_sender_info.sender_id);
3053 if (!receiver) {
3054 RTC_LOG(LS_WARNING) << "RtpReceiver for track with id "
3055 << remote_sender_info.sender_id << " doesn't exist.";
Henrik Boström933d8b02017-10-10 10:05:16 -07003056 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07003057 }
Steve Anton4171afb2017-11-20 10:20:22 -08003058 if (receiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
3059 GetAudioTransceiver()->internal()->RemoveReceiver(receiver);
3060 } else {
3061 GetVideoTransceiver()->internal()->RemoveReceiver(receiver);
3062 }
Henrik Boström933d8b02017-10-10 10:05:16 -07003063 return receiver;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003064}
3065
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003066void PeerConnection::AddAudioTrack(AudioTrackInterface* track,
3067 MediaStreamInterface* stream) {
3068 RTC_DCHECK(!IsClosed());
3069 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003070 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003071 // We already have a sender for this track, so just change the stream_id
3072 // so that it's correct in the next call to CreateOffer.
Steve Anton4171afb2017-11-20 10:20:22 -08003073 sender->internal()->set_stream_id(stream->label());
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003074 return;
3075 }
3076
3077 // Normal case; we've never seen this track before.
Steve Anton02ee47c2018-01-10 16:26:06 -08003078 auto new_sender =
3079 CreateSender(cricket::MEDIA_TYPE_AUDIO, track, {stream->label()});
Guido Urdanetaee2388f2018-02-15 16:36:19 +00003080 static_cast<AudioRtpSender*>(new_sender->internal())
3081 ->SetMediaChannel(voice_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08003082 GetAudioTransceiver()->internal()->AddSender(new_sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003083 // If the sender has already been configured in SDP, we call SetSsrc,
3084 // which will connect the sender to the underlying transport. This can
3085 // occur if a local session description that contains the ID of the sender
3086 // is set before AddStream is called. It can also occur if the local
3087 // session description is not changed and RemoveStream is called, and
3088 // later AddStream is called again with the same stream.
Steve Anton4171afb2017-11-20 10:20:22 -08003089 const RtpSenderInfo* sender_info =
3090 FindSenderInfo(local_audio_sender_infos_, stream->label(), track->id());
3091 if (sender_info) {
3092 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003093 }
3094}
3095
3096// TODO(deadbeef): Don't destroy RtpSenders here; they should be kept around
3097// indefinitely, when we have unified plan SDP.
3098void PeerConnection::RemoveAudioTrack(AudioTrackInterface* track,
3099 MediaStreamInterface* stream) {
3100 RTC_DCHECK(!IsClosed());
3101 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003102 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003103 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
3104 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003105 return;
3106 }
Steve Anton4171afb2017-11-20 10:20:22 -08003107 GetAudioTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003108}
3109
3110void PeerConnection::AddVideoTrack(VideoTrackInterface* track,
3111 MediaStreamInterface* stream) {
3112 RTC_DCHECK(!IsClosed());
3113 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003114 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003115 // We already have a sender for this track, so just change the stream_id
3116 // so that it's correct in the next call to CreateOffer.
Steve Anton4171afb2017-11-20 10:20:22 -08003117 sender->internal()->set_stream_id(stream->label());
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003118 return;
3119 }
3120
3121 // Normal case; we've never seen this track before.
Steve Anton02ee47c2018-01-10 16:26:06 -08003122 auto new_sender =
3123 CreateSender(cricket::MEDIA_TYPE_VIDEO, track, {stream->label()});
Guido Urdanetaee2388f2018-02-15 16:36:19 +00003124 static_cast<VideoRtpSender*>(new_sender->internal())
3125 ->SetMediaChannel(video_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08003126 GetVideoTransceiver()->internal()->AddSender(new_sender);
3127 const RtpSenderInfo* sender_info =
3128 FindSenderInfo(local_video_sender_infos_, stream->label(), track->id());
3129 if (sender_info) {
3130 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003131 }
3132}
3133
3134void PeerConnection::RemoveVideoTrack(VideoTrackInterface* track,
3135 MediaStreamInterface* stream) {
3136 RTC_DCHECK(!IsClosed());
3137 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003138 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003139 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
3140 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003141 return;
3142 }
Steve Anton4171afb2017-11-20 10:20:22 -08003143 GetVideoTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003144}
3145
Steve Antonba818672017-11-06 10:21:57 -08003146void PeerConnection::SetIceConnectionState(IceConnectionState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07003147 RTC_DCHECK(signaling_thread()->IsCurrent());
Steve Antonba818672017-11-06 10:21:57 -08003148 if (ice_connection_state_ == new_state) {
3149 return;
3150 }
3151
deadbeefcbecd352015-09-23 11:50:27 -07003152 // After transitioning to "closed", ignore any additional states from
Steve Antonba818672017-11-06 10:21:57 -08003153 // TransportController (such as "disconnected").
deadbeefab9b2d12015-10-14 11:33:11 -07003154 if (IsClosed()) {
deadbeefcbecd352015-09-23 11:50:27 -07003155 return;
3156 }
Steve Antonba818672017-11-06 10:21:57 -08003157
Mirko Bonadei675513b2017-11-09 11:09:25 +01003158 RTC_LOG(LS_INFO) << "Changing IceConnectionState " << ice_connection_state_
3159 << " => " << new_state;
Steve Antonba818672017-11-06 10:21:57 -08003160 RTC_DCHECK(ice_connection_state_ !=
3161 PeerConnectionInterface::kIceConnectionClosed);
3162
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003163 ice_connection_state_ = new_state;
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00003164 observer_->OnIceConnectionChange(ice_connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003165}
3166
3167void PeerConnection::OnIceGatheringChange(
3168 PeerConnectionInterface::IceGatheringState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07003169 RTC_DCHECK(signaling_thread()->IsCurrent());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003170 if (IsClosed()) {
3171 return;
3172 }
3173 ice_gathering_state_ = new_state;
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00003174 observer_->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003175}
3176
jbauch81bf7b02017-03-25 08:31:12 -07003177void PeerConnection::OnIceCandidate(
3178 std::unique_ptr<IceCandidateInterface> candidate) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07003179 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07003180 if (IsClosed()) {
3181 return;
3182 }
jbauch81bf7b02017-03-25 08:31:12 -07003183 observer_->OnIceCandidate(candidate.get());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003184}
3185
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003186void PeerConnection::OnIceCandidatesRemoved(
3187 const std::vector<cricket::Candidate>& candidates) {
3188 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07003189 if (IsClosed()) {
3190 return;
3191 }
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003192 observer_->OnIceCandidatesRemoved(candidates);
3193}
3194
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003195void PeerConnection::ChangeSignalingState(
3196 PeerConnectionInterface::SignalingState signaling_state) {
Steve Antonba818672017-11-06 10:21:57 -08003197 RTC_DCHECK(signaling_thread()->IsCurrent());
3198 if (signaling_state_ == signaling_state) {
3199 return;
3200 }
Mirko Bonadei675513b2017-11-09 11:09:25 +01003201 RTC_LOG(LS_INFO) << "Session: " << session_id() << " Old state: "
3202 << GetSignalingStateString(signaling_state_)
3203 << " New state: "
3204 << GetSignalingStateString(signaling_state);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003205 signaling_state_ = signaling_state;
3206 if (signaling_state == kClosed) {
3207 ice_connection_state_ = kIceConnectionClosed;
3208 observer_->OnIceConnectionChange(ice_connection_state_);
3209 if (ice_gathering_state_ != kIceGatheringComplete) {
3210 ice_gathering_state_ = kIceGatheringComplete;
3211 observer_->OnIceGatheringChange(ice_gathering_state_);
3212 }
3213 }
3214 observer_->OnSignalingChange(signaling_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003215}
3216
deadbeefeb459812015-12-15 19:24:43 -08003217void PeerConnection::OnAudioTrackAdded(AudioTrackInterface* track,
3218 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003219 if (IsClosed()) {
3220 return;
3221 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003222 AddAudioTrack(track, stream);
3223 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003224}
3225
deadbeefeb459812015-12-15 19:24:43 -08003226void PeerConnection::OnAudioTrackRemoved(AudioTrackInterface* track,
3227 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003228 if (IsClosed()) {
3229 return;
3230 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003231 RemoveAudioTrack(track, stream);
3232 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003233}
3234
3235void PeerConnection::OnVideoTrackAdded(VideoTrackInterface* track,
3236 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003237 if (IsClosed()) {
3238 return;
3239 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003240 AddVideoTrack(track, stream);
3241 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003242}
3243
3244void PeerConnection::OnVideoTrackRemoved(VideoTrackInterface* track,
3245 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003246 if (IsClosed()) {
3247 return;
3248 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003249 RemoveVideoTrack(track, stream);
3250 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003251}
3252
Henrik Boström31638672017-11-23 17:48:32 +01003253void PeerConnection::PostSetSessionDescriptionSuccess(
3254 SetSessionDescriptionObserver* observer) {
3255 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
3256 signaling_thread()->Post(RTC_FROM_HERE, this,
3257 MSG_SET_SESSIONDESCRIPTION_SUCCESS, msg);
3258}
3259
deadbeefab9b2d12015-10-14 11:33:11 -07003260void PeerConnection::PostSetSessionDescriptionFailure(
3261 SetSessionDescriptionObserver* observer,
3262 const std::string& error) {
3263 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
3264 msg->error = error;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07003265 signaling_thread()->Post(RTC_FROM_HERE, this,
3266 MSG_SET_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07003267}
3268
3269void PeerConnection::PostCreateSessionDescriptionFailure(
3270 CreateSessionDescriptionObserver* observer,
3271 const std::string& error) {
3272 CreateSessionDescriptionMsg* msg = new CreateSessionDescriptionMsg(observer);
3273 msg->error = error;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07003274 signaling_thread()->Post(RTC_FROM_HERE, this,
3275 MSG_CREATE_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07003276}
3277
zhihuang1c378ed2017-08-17 14:10:50 -07003278void PeerConnection::GetOptionsForOffer(
Steve Antondcc3c022017-12-22 16:02:54 -08003279 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
deadbeefab9b2d12015-10-14 11:33:11 -07003280 cricket::MediaSessionOptions* session_options) {
Steve Antondcc3c022017-12-22 16:02:54 -08003281 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
zhihuang1c378ed2017-08-17 14:10:50 -07003282
Steve Antondcc3c022017-12-22 16:02:54 -08003283 if (IsUnifiedPlan()) {
3284 GetOptionsForUnifiedPlanOffer(offer_answer_options, session_options);
3285 } else {
3286 GetOptionsForPlanBOffer(offer_answer_options, session_options);
3287 }
3288
Steve Antonfa2260d2017-12-28 16:38:23 -08003289 // Intentionally unset the data channel type for RTP data channel with the
3290 // second condition. Otherwise the RTP data channels would be successfully
3291 // negotiated by default and the unit tests in WebRtcDataBrowserTest will fail
3292 // when building with chromium. We want to leave RTP data channels broken, so
3293 // people won't try to use them.
3294 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
3295 session_options->data_channel_type = data_channel_type();
3296 }
3297
Steve Antondcc3c022017-12-22 16:02:54 -08003298 // Apply ICE restart flag and renomination flag.
3299 for (auto& options : session_options->media_description_options) {
3300 options.transport_options.ice_restart = offer_answer_options.ice_restart;
3301 options.transport_options.enable_ice_renomination =
3302 configuration_.enable_ice_renomination;
3303 }
3304
3305 session_options->rtcp_cname = rtcp_cname_;
3306 session_options->crypto_options = factory_->options().crypto_options;
Steve Antone831b8c2018-02-01 12:22:16 -08003307 session_options->is_unified_plan = IsUnifiedPlan();
Steve Antondcc3c022017-12-22 16:02:54 -08003308}
3309
3310void PeerConnection::GetOptionsForPlanBOffer(
3311 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
3312 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07003313 // Figure out transceiver directional preferences.
3314 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
3315 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
3316
3317 // By default, generate sendrecv/recvonly m= sections.
3318 bool recv_audio = true;
3319 bool recv_video = true;
3320
3321 // By default, only offer a new m= section if we have media to send with it.
3322 bool offer_new_audio_description = send_audio;
3323 bool offer_new_video_description = send_video;
3324 bool offer_new_data_description = HasDataChannels();
3325
3326 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-22 16:02:54 -08003327 if (offer_answer_options.offer_to_receive_audio !=
3328 RTCOfferAnswerOptions::kUndefined) {
3329 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003330 offer_new_audio_description =
Steve Antondcc3c022017-12-22 16:02:54 -08003331 offer_new_audio_description ||
3332 (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003333 }
Steve Antondcc3c022017-12-22 16:02:54 -08003334 if (offer_answer_options.offer_to_receive_video !=
3335 RTCOfferAnswerOptions::kUndefined) {
3336 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003337 offer_new_video_description =
Steve Antondcc3c022017-12-22 16:02:54 -08003338 offer_new_video_description ||
3339 (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003340 }
3341
3342 rtc::Optional<size_t> audio_index;
3343 rtc::Optional<size_t> video_index;
3344 rtc::Optional<size_t> data_index;
3345 // If a current description exists, generate m= sections in the same order,
3346 // using the first audio/video/data section that appears and rejecting
3347 // extraneous ones.
Steve Anton75737c02017-11-06 10:37:17 -08003348 if (local_description()) {
zhihuang1c378ed2017-08-17 14:10:50 -07003349 GenerateMediaDescriptionOptions(
Steve Anton75737c02017-11-06 10:37:17 -08003350 local_description(),
Steve Anton1d03a752017-11-27 14:30:09 -08003351 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
3352 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
3353 &audio_index, &video_index, &data_index, session_options);
deadbeefab9b2d12015-10-14 11:33:11 -07003354 }
3355
zhihuang1c378ed2017-08-17 14:10:50 -07003356 // Add audio/video/data m= sections to the end if needed.
3357 if (!audio_index && offer_new_audio_description) {
3358 session_options->media_description_options.push_back(
3359 cricket::MediaDescriptionOptions(
3360 cricket::MEDIA_TYPE_AUDIO, cricket::CN_AUDIO,
Steve Anton1d03a752017-11-27 14:30:09 -08003361 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
3362 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003363 audio_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07003364 }
zhihuang1c378ed2017-08-17 14:10:50 -07003365 if (!video_index && offer_new_video_description) {
3366 session_options->media_description_options.push_back(
3367 cricket::MediaDescriptionOptions(
3368 cricket::MEDIA_TYPE_VIDEO, cricket::CN_VIDEO,
Steve Anton1d03a752017-11-27 14:30:09 -08003369 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
3370 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003371 video_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07003372 }
zhihuang1c378ed2017-08-17 14:10:50 -07003373 if (!data_index && offer_new_data_description) {
3374 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08003375 GetMediaDescriptionOptionsForActiveData(cricket::CN_DATA));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003376 data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07003377 }
3378
3379 cricket::MediaDescriptionOptions* audio_media_description_options =
3380 !audio_index ? nullptr
3381 : &session_options->media_description_options[*audio_index];
3382 cricket::MediaDescriptionOptions* video_media_description_options =
3383 !video_index ? nullptr
3384 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 14:10:50 -07003385
Steve Anton4171afb2017-11-20 10:20:22 -08003386 AddRtpSenderOptions(GetSendersInternal(), audio_media_description_options,
zhihuang1c378ed2017-08-17 14:10:50 -07003387 video_media_description_options);
Steve Antondcc3c022017-12-22 16:02:54 -08003388}
3389
3390// Find a new MID that is not already in |used_mids|, then add it to |used_mids|
3391// and return a reference to it.
3392// Generated MIDs should be no more than 3 bytes long to take up less space in
3393// the RTP packet.
3394static const std::string& AllocateMid(std::set<std::string>* used_mids) {
3395 RTC_DCHECK(used_mids);
3396 // We're boring: just generate MIDs 0, 1, 2, ...
3397 size_t i = 0;
3398 std::set<std::string>::iterator it;
3399 bool inserted;
3400 do {
3401 std::string mid = rtc::ToString(i++);
3402 auto insert_result = used_mids->insert(mid);
3403 it = insert_result.first;
3404 inserted = insert_result.second;
3405 } while (!inserted);
3406 return *it;
3407}
3408
3409static cricket::MediaDescriptionOptions
3410GetMediaDescriptionOptionsForTransceiver(
3411 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3412 transceiver,
3413 const std::string& mid) {
3414 cricket::MediaDescriptionOptions media_description_options(
Steve Anton69470252018-02-09 11:43:08 -08003415 transceiver->media_type(), mid, transceiver->direction(),
Steve Antondcc3c022017-12-22 16:02:54 -08003416 transceiver->stopped());
Steve Anton5f94aa22018-02-01 10:58:30 -08003417 // This behavior is specified in JSEP. The gist is that:
3418 // 1. The MSID is included if the RtpTransceiver's direction is sendonly or
3419 // sendrecv.
3420 // 2. If the MSID is included, then it must be included in any subsequent
3421 // offer/answer exactly the same until the RtpTransceiver is stopped.
3422 if (!transceiver->stopped() &&
3423 (RtpTransceiverDirectionHasSend(transceiver->direction()) ||
3424 transceiver->internal()->has_ever_been_used_to_send())) {
3425 cricket::SenderOptions sender_options;
3426 sender_options.track_id = transceiver->sender()->id();
3427 sender_options.stream_ids = transceiver->sender()->stream_ids();
3428 // TODO(bugs.webrtc.org/7600): Set num_sim_layers to the number of encodings
3429 // set in the RTP parameters when the transceiver was added.
3430 sender_options.num_sim_layers = 1;
3431 media_description_options.sender_options.push_back(sender_options);
3432 }
Steve Antondcc3c022017-12-22 16:02:54 -08003433 return media_description_options;
3434}
3435
3436void PeerConnection::GetOptionsForUnifiedPlanOffer(
3437 const RTCOfferAnswerOptions& offer_answer_options,
3438 cricket::MediaSessionOptions* session_options) {
3439 // Rules for generating an offer are dictated by JSEP sections 5.2.1 (Initial
3440 // Offers) and 5.2.2 (Subsequent Offers).
3441 RTC_DCHECK_EQ(session_options->media_description_options.size(), 0);
3442 const ContentInfos& local_contents =
3443 (local_description() ? local_description()->description()->contents()
3444 : ContentInfos());
3445 const ContentInfos& remote_contents =
3446 (remote_description() ? remote_description()->description()->contents()
3447 : ContentInfos());
3448 // The mline indices that can be recycled. New transceivers should reuse these
3449 // slots first.
3450 std::queue<size_t> recycleable_mline_indices;
3451 // Track the MIDs used in previous offer/answer exchanges and the current
3452 // offer so that new, unique MIDs are generated.
3453 std::set<std::string> used_mids = seen_mids_;
3454 // First, go through each media section that exists in either the local or
3455 // remote description and generate a media section in this offer for the
3456 // associated transceiver. If a media section can be recycled, generate a
3457 // default, rejected media section here that can be later overwritten.
3458 for (size_t i = 0;
3459 i < std::max(local_contents.size(), remote_contents.size()); ++i) {
3460 // Either |local_content| or |remote_content| is non-null.
3461 const ContentInfo* local_content =
3462 (i < local_contents.size() ? &local_contents[i] : nullptr);
3463 const ContentInfo* remote_content =
3464 (i < remote_contents.size() ? &remote_contents[i] : nullptr);
3465 bool had_been_rejected = (local_content && local_content->rejected) ||
3466 (remote_content && remote_content->rejected);
3467 const std::string& mid =
3468 (local_content ? local_content->name : remote_content->name);
3469 cricket::MediaType media_type =
3470 (local_content ? local_content->media_description()->type()
3471 : remote_content->media_description()->type());
3472 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
3473 media_type == cricket::MEDIA_TYPE_VIDEO) {
3474 auto transceiver = GetAssociatedTransceiver(mid);
3475 RTC_CHECK(transceiver);
3476 // A media section is considered eligible for recycling if it is marked as
3477 // rejected in either the local or remote description.
Seth Hampsonae8a90a2018-02-13 15:33:48 -08003478 if (had_been_rejected && transceiver->stopped()) {
Steve Antondcc3c022017-12-22 16:02:54 -08003479 session_options->media_description_options.push_back(
Steve Anton69470252018-02-09 11:43:08 -08003480 cricket::MediaDescriptionOptions(transceiver->media_type(), mid,
3481 RtpTransceiverDirection::kInactive,
3482 /*stopped=*/true));
Steve Antondcc3c022017-12-22 16:02:54 -08003483 recycleable_mline_indices.push(i);
3484 } else {
3485 session_options->media_description_options.push_back(
3486 GetMediaDescriptionOptionsForTransceiver(transceiver, mid));
3487 // CreateOffer shouldn't really cause any state changes in
3488 // PeerConnection, but we need a way to match new transceivers to new
3489 // media sections in SetLocalDescription and JSEP specifies this is done
3490 // by recording the index of the media section generated for the
3491 // transceiver in the offer.
3492 transceiver->internal()->set_mline_index(i);
3493 }
3494 } else {
3495 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antonfa2260d2017-12-28 16:38:23 -08003496 RTC_CHECK(GetDataMid());
3497 if (had_been_rejected || mid != *GetDataMid()) {
3498 session_options->media_description_options.push_back(
3499 GetMediaDescriptionOptionsForRejectedData(mid));
3500 } else {
3501 session_options->media_description_options.push_back(
3502 GetMediaDescriptionOptionsForActiveData(mid));
3503 }
Steve Antondcc3c022017-12-22 16:02:54 -08003504 }
3505 }
3506 // Next, look for transceivers that are newly added (that is, are not stopped
3507 // and not associated). Reuse media sections marked as recyclable first,
3508 // otherwise append to the end of the offer. New media sections should be
3509 // added in the order they were added to the PeerConnection.
3510 for (auto transceiver : transceivers_) {
3511 if (transceiver->mid() || transceiver->stopped()) {
3512 continue;
3513 }
3514 size_t mline_index;
3515 if (!recycleable_mline_indices.empty()) {
3516 mline_index = recycleable_mline_indices.front();
3517 recycleable_mline_indices.pop();
3518 session_options->media_description_options[mline_index] =
3519 GetMediaDescriptionOptionsForTransceiver(transceiver,
3520 AllocateMid(&used_mids));
3521 } else {
3522 mline_index = session_options->media_description_options.size();
3523 session_options->media_description_options.push_back(
3524 GetMediaDescriptionOptionsForTransceiver(transceiver,
3525 AllocateMid(&used_mids)));
3526 }
3527 // See comment above for why CreateOffer changes the transceiver's state.
3528 transceiver->internal()->set_mline_index(mline_index);
3529 }
Steve Antonfa2260d2017-12-28 16:38:23 -08003530 // Lastly, add a m-section if we have local data channels and an m section
3531 // does not already exist.
3532 if (!GetDataMid() && HasDataChannels()) {
3533 session_options->media_description_options.push_back(
3534 GetMediaDescriptionOptionsForActiveData(AllocateMid(&used_mids)));
3535 }
Steve Antondcc3c022017-12-22 16:02:54 -08003536}
3537
3538void PeerConnection::GetOptionsForAnswer(
3539 const RTCOfferAnswerOptions& offer_answer_options,
3540 cricket::MediaSessionOptions* session_options) {
3541 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
3542
3543 if (IsUnifiedPlan()) {
3544 GetOptionsForUnifiedPlanAnswer(offer_answer_options, session_options);
3545 } else {
3546 GetOptionsForPlanBAnswer(offer_answer_options, session_options);
3547 }
3548
Steve Antonfa2260d2017-12-28 16:38:23 -08003549 // Intentionally unset the data channel type for RTP data channel. Otherwise
3550 // the RTP data channels would be successfully negotiated by default and the
3551 // unit tests in WebRtcDataBrowserTest will fail when building with chromium.
3552 // We want to leave RTP data channels broken, so people won't try to use them.
3553 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
3554 session_options->data_channel_type = data_channel_type();
3555 }
3556
Steve Antondcc3c022017-12-22 16:02:54 -08003557 // Apply ICE renomination flag.
3558 for (auto& options : session_options->media_description_options) {
3559 options.transport_options.enable_ice_renomination =
3560 configuration_.enable_ice_renomination;
3561 }
zhihuang8f65cdf2016-05-06 18:40:30 -07003562
3563 session_options->rtcp_cname = rtcp_cname_;
jbauchcb560652016-08-04 05:20:32 -07003564 session_options->crypto_options = factory_->options().crypto_options;
Steve Antone831b8c2018-02-01 12:22:16 -08003565 session_options->is_unified_plan = IsUnifiedPlan();
deadbeefab9b2d12015-10-14 11:33:11 -07003566}
3567
Steve Antondcc3c022017-12-22 16:02:54 -08003568void PeerConnection::GetOptionsForPlanBAnswer(
3569 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07003570 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07003571 // Figure out transceiver directional preferences.
3572 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
3573 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
3574
3575 // By default, generate sendrecv/recvonly m= sections. The direction is also
3576 // restricted by the direction in the offer.
3577 bool recv_audio = true;
3578 bool recv_video = true;
3579
3580 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-22 16:02:54 -08003581 if (offer_answer_options.offer_to_receive_audio !=
3582 RTCOfferAnswerOptions::kUndefined) {
3583 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
deadbeef0ed85b22016-02-23 17:24:52 -08003584 }
Steve Antondcc3c022017-12-22 16:02:54 -08003585 if (offer_answer_options.offer_to_receive_video !=
3586 RTCOfferAnswerOptions::kUndefined) {
3587 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003588 }
3589
3590 rtc::Optional<size_t> audio_index;
3591 rtc::Optional<size_t> video_index;
3592 rtc::Optional<size_t> data_index;
Steve Antondffead82018-02-06 10:31:29 -08003593
3594 // Generate m= sections that match those in the offer.
3595 // Note that mediasession.cc will handle intersection our preferred
3596 // direction with the offered direction.
3597 GenerateMediaDescriptionOptions(
3598 remote_description(),
3599 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
3600 RtpTransceiverDirectionFromSendRecv(send_video, recv_video), &audio_index,
3601 &video_index, &data_index, session_options);
zhihuang1c378ed2017-08-17 14:10:50 -07003602
3603 cricket::MediaDescriptionOptions* audio_media_description_options =
3604 !audio_index ? nullptr
3605 : &session_options->media_description_options[*audio_index];
3606 cricket::MediaDescriptionOptions* video_media_description_options =
3607 !video_index ? nullptr
3608 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 14:10:50 -07003609
Steve Anton4171afb2017-11-20 10:20:22 -08003610 AddRtpSenderOptions(GetSendersInternal(), audio_media_description_options,
zhihuang1c378ed2017-08-17 14:10:50 -07003611 video_media_description_options);
Steve Antondcc3c022017-12-22 16:02:54 -08003612}
zhihuangaf388472016-11-02 16:49:48 -07003613
Steve Antondcc3c022017-12-22 16:02:54 -08003614void PeerConnection::GetOptionsForUnifiedPlanAnswer(
3615 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
3616 cricket::MediaSessionOptions* session_options) {
3617 // Rules for generating an answer are dictated by JSEP sections 5.3.1 (Initial
3618 // Answers) and 5.3.2 (Subsequent Answers).
3619 RTC_DCHECK(remote_description());
3620 RTC_DCHECK(remote_description()->GetType() == SdpType::kOffer);
3621 for (const ContentInfo& content :
3622 remote_description()->description()->contents()) {
3623 cricket::MediaType media_type = content.media_description()->type();
3624 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
3625 media_type == cricket::MEDIA_TYPE_VIDEO) {
3626 auto transceiver = GetAssociatedTransceiver(content.name);
3627 RTC_CHECK(transceiver);
3628 session_options->media_description_options.push_back(
3629 GetMediaDescriptionOptionsForTransceiver(transceiver, content.name));
3630 } else {
3631 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antondbf9d032018-01-19 15:23:40 -08003632 // Reject all data sections if data channels are disabled.
3633 // Reject a data section if it has already been rejected.
3634 // Reject all data sections except for the first one.
3635 if (data_channel_type_ == cricket::DCT_NONE || content.rejected ||
3636 content.name != *GetDataMid()) {
Steve Antonfa2260d2017-12-28 16:38:23 -08003637 session_options->media_description_options.push_back(
3638 GetMediaDescriptionOptionsForRejectedData(content.name));
3639 } else {
3640 session_options->media_description_options.push_back(
3641 GetMediaDescriptionOptionsForActiveData(content.name));
3642 }
Steve Antondcc3c022017-12-22 16:02:54 -08003643 }
3644 }
htaa2a49d92016-03-04 02:51:39 -08003645}
3646
zhihuang1c378ed2017-08-17 14:10:50 -07003647void PeerConnection::GenerateMediaDescriptionOptions(
3648 const SessionDescriptionInterface* session_desc,
Steve Anton1d03a752017-11-27 14:30:09 -08003649 RtpTransceiverDirection audio_direction,
3650 RtpTransceiverDirection video_direction,
zhihuang1c378ed2017-08-17 14:10:50 -07003651 rtc::Optional<size_t>* audio_index,
3652 rtc::Optional<size_t>* video_index,
3653 rtc::Optional<size_t>* data_index,
htaa2a49d92016-03-04 02:51:39 -08003654 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07003655 for (const cricket::ContentInfo& content :
3656 session_desc->description()->contents()) {
3657 if (IsAudioContent(&content)) {
3658 // If we already have an audio m= section, reject this extra one.
3659 if (*audio_index) {
3660 session_options->media_description_options.push_back(
3661 cricket::MediaDescriptionOptions(
3662 cricket::MEDIA_TYPE_AUDIO, content.name,
Steve Anton1d03a752017-11-27 14:30:09 -08003663 RtpTransceiverDirection::kInactive, true));
zhihuang1c378ed2017-08-17 14:10:50 -07003664 } else {
3665 session_options->media_description_options.push_back(
3666 cricket::MediaDescriptionOptions(
3667 cricket::MEDIA_TYPE_AUDIO, content.name, audio_direction,
Steve Anton1d03a752017-11-27 14:30:09 -08003668 audio_direction == RtpTransceiverDirection::kInactive));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003669 *audio_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07003670 }
3671 } else if (IsVideoContent(&content)) {
3672 // If we already have an video m= section, reject this extra one.
3673 if (*video_index) {
3674 session_options->media_description_options.push_back(
3675 cricket::MediaDescriptionOptions(
3676 cricket::MEDIA_TYPE_VIDEO, content.name,
Steve Anton1d03a752017-11-27 14:30:09 -08003677 RtpTransceiverDirection::kInactive, true));
zhihuang1c378ed2017-08-17 14:10:50 -07003678 } else {
3679 session_options->media_description_options.push_back(
3680 cricket::MediaDescriptionOptions(
3681 cricket::MEDIA_TYPE_VIDEO, content.name, video_direction,
Steve Anton1d03a752017-11-27 14:30:09 -08003682 video_direction == RtpTransceiverDirection::kInactive));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003683 *video_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07003684 }
3685 } else {
3686 RTC_DCHECK(IsDataContent(&content));
3687 // If we already have an data m= section, reject this extra one.
3688 if (*data_index) {
3689 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08003690 GetMediaDescriptionOptionsForRejectedData(content.name));
zhihuang1c378ed2017-08-17 14:10:50 -07003691 } else {
3692 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08003693 GetMediaDescriptionOptionsForActiveData(content.name));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003694 *data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07003695 }
3696 }
htaa2a49d92016-03-04 02:51:39 -08003697 }
deadbeefab9b2d12015-10-14 11:33:11 -07003698}
3699
Steve Antonfa2260d2017-12-28 16:38:23 -08003700cricket::MediaDescriptionOptions
3701PeerConnection::GetMediaDescriptionOptionsForActiveData(
3702 const std::string& mid) const {
3703 // Direction for data sections is meaningless, but legacy endpoints might
3704 // expect sendrecv.
3705 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
3706 RtpTransceiverDirection::kSendRecv,
3707 /*stopped=*/false);
3708 AddRtpDataChannelOptions(rtp_data_channels_, &options);
3709 return options;
3710}
3711
3712cricket::MediaDescriptionOptions
3713PeerConnection::GetMediaDescriptionOptionsForRejectedData(
3714 const std::string& mid) const {
3715 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
3716 RtpTransceiverDirection::kInactive,
3717 /*stopped=*/true);
3718 AddRtpDataChannelOptions(rtp_data_channels_, &options);
3719 return options;
3720}
3721
3722rtc::Optional<std::string> PeerConnection::GetDataMid() const {
3723 switch (data_channel_type_) {
3724 case cricket::DCT_RTP:
3725 if (!rtp_data_channel_) {
3726 return rtc::nullopt;
3727 }
3728 return rtp_data_channel_->content_name();
3729 case cricket::DCT_SCTP:
3730 return sctp_content_name_;
3731 default:
3732 return rtc::nullopt;
3733 }
3734}
3735
Steve Anton4171afb2017-11-20 10:20:22 -08003736void PeerConnection::RemoveSenders(cricket::MediaType media_type) {
3737 UpdateLocalSenders(std::vector<cricket::StreamParams>(), media_type);
3738 UpdateRemoteSendersList(std::vector<cricket::StreamParams>(), false,
deadbeefbda7e0b2015-12-08 17:13:40 -08003739 media_type, nullptr);
deadbeeffaac4972015-11-12 15:33:07 -08003740}
3741
Steve Anton4171afb2017-11-20 10:20:22 -08003742void PeerConnection::UpdateRemoteSendersList(
deadbeefab9b2d12015-10-14 11:33:11 -07003743 const cricket::StreamParamsVec& streams,
Steve Anton4171afb2017-11-20 10:20:22 -08003744 bool default_sender_needed,
deadbeefab9b2d12015-10-14 11:33:11 -07003745 cricket::MediaType media_type,
3746 StreamCollection* new_streams) {
Steve Anton4171afb2017-11-20 10:20:22 -08003747 std::vector<RtpSenderInfo>* current_senders =
3748 GetRemoteSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07003749
Steve Anton4171afb2017-11-20 10:20:22 -08003750 // Find removed senders. I.e., senders where the sender id or ssrc don't match
deadbeeffac06552015-11-25 11:26:01 -08003751 // the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08003752 for (auto sender_it = current_senders->begin();
3753 sender_it != current_senders->end();
3754 /* incremented manually */) {
3755 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07003756 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08003757 cricket::GetStreamBySsrc(streams, info.first_ssrc);
3758 bool sender_exists = params && params->id == info.sender_id;
deadbeefbda7e0b2015-12-08 17:13:40 -08003759 // If this is a default track, and we still need it, don't remove it.
Steve Anton4171afb2017-11-20 10:20:22 -08003760 if ((info.stream_label == kDefaultStreamLabel && default_sender_needed) ||
3761 sender_exists) {
3762 ++sender_it;
deadbeefbda7e0b2015-12-08 17:13:40 -08003763 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08003764 OnRemoteSenderRemoved(info, media_type);
3765 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07003766 }
3767 }
3768
Steve Anton4171afb2017-11-20 10:20:22 -08003769 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07003770 for (const cricket::StreamParams& params : streams) {
3771 // The sync_label is the MediaStream label and the |stream.id| is the
Steve Anton4171afb2017-11-20 10:20:22 -08003772 // sender id.
deadbeefab9b2d12015-10-14 11:33:11 -07003773 const std::string& stream_label = params.sync_label;
Steve Anton4171afb2017-11-20 10:20:22 -08003774 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07003775 uint32_t ssrc = params.first_ssrc();
3776
3777 rtc::scoped_refptr<MediaStreamInterface> stream =
3778 remote_streams_->find(stream_label);
3779 if (!stream) {
3780 // This is a new MediaStream. Create a new remote MediaStream.
perkjd61bf802016-03-24 03:16:19 -07003781 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
3782 MediaStream::Create(stream_label));
deadbeefab9b2d12015-10-14 11:33:11 -07003783 remote_streams_->AddStream(stream);
3784 new_streams->AddStream(stream);
3785 }
3786
Steve Anton4171afb2017-11-20 10:20:22 -08003787 const RtpSenderInfo* sender_info =
3788 FindSenderInfo(*current_senders, stream_label, sender_id);
3789 if (!sender_info) {
3790 current_senders->push_back(RtpSenderInfo(stream_label, sender_id, ssrc));
3791 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07003792 }
3793 }
deadbeefbda7e0b2015-12-08 17:13:40 -08003794
Steve Anton4171afb2017-11-20 10:20:22 -08003795 // Add default sender if necessary.
3796 if (default_sender_needed) {
deadbeefbda7e0b2015-12-08 17:13:40 -08003797 rtc::scoped_refptr<MediaStreamInterface> default_stream =
3798 remote_streams_->find(kDefaultStreamLabel);
3799 if (!default_stream) {
3800 // Create the new default MediaStream.
perkjd61bf802016-03-24 03:16:19 -07003801 default_stream = MediaStreamProxy::Create(
3802 rtc::Thread::Current(), MediaStream::Create(kDefaultStreamLabel));
deadbeefbda7e0b2015-12-08 17:13:40 -08003803 remote_streams_->AddStream(default_stream);
3804 new_streams->AddStream(default_stream);
3805 }
Steve Anton4171afb2017-11-20 10:20:22 -08003806 std::string default_sender_id = (media_type == cricket::MEDIA_TYPE_AUDIO)
3807 ? kDefaultAudioSenderId
3808 : kDefaultVideoSenderId;
3809 const RtpSenderInfo* default_sender_info = FindSenderInfo(
3810 *current_senders, kDefaultStreamLabel, default_sender_id);
3811 if (!default_sender_info) {
3812 current_senders->push_back(
3813 RtpSenderInfo(kDefaultStreamLabel, default_sender_id, 0));
3814 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefbda7e0b2015-12-08 17:13:40 -08003815 }
3816 }
deadbeefab9b2d12015-10-14 11:33:11 -07003817}
3818
Steve Anton4171afb2017-11-20 10:20:22 -08003819void PeerConnection::OnRemoteSenderAdded(const RtpSenderInfo& sender_info,
3820 cricket::MediaType media_type) {
3821 MediaStreamInterface* stream =
3822 remote_streams_->find(sender_info.stream_label);
deadbeefab9b2d12015-10-14 11:33:11 -07003823
3824 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 10:20:22 -08003825 CreateAudioReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07003826 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 10:20:22 -08003827 CreateVideoReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07003828 } else {
nisseeb4ca4e2017-01-12 02:24:27 -08003829 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07003830 }
3831}
3832
Steve Anton4171afb2017-11-20 10:20:22 -08003833void PeerConnection::OnRemoteSenderRemoved(const RtpSenderInfo& sender_info,
3834 cricket::MediaType media_type) {
3835 MediaStreamInterface* stream =
3836 remote_streams_->find(sender_info.stream_label);
deadbeefab9b2d12015-10-14 11:33:11 -07003837
Henrik Boström933d8b02017-10-10 10:05:16 -07003838 rtc::scoped_refptr<RtpReceiverInterface> receiver;
deadbeefab9b2d12015-10-14 11:33:11 -07003839 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
perkjd61bf802016-03-24 03:16:19 -07003840 // When the MediaEngine audio channel is destroyed, the RemoteAudioSource
3841 // will be notified which will end the AudioRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08003842 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07003843 rtc::scoped_refptr<AudioTrackInterface> audio_track =
Steve Anton4171afb2017-11-20 10:20:22 -08003844 stream->FindAudioTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07003845 if (audio_track) {
deadbeefab9b2d12015-10-14 11:33:11 -07003846 stream->RemoveTrack(audio_track);
deadbeefab9b2d12015-10-14 11:33:11 -07003847 }
3848 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
perkjd61bf802016-03-24 03:16:19 -07003849 // Stopping or destroying a VideoRtpReceiver will end the
3850 // VideoRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08003851 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07003852 rtc::scoped_refptr<VideoTrackInterface> video_track =
Steve Anton4171afb2017-11-20 10:20:22 -08003853 stream->FindVideoTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07003854 if (video_track) {
perkjd61bf802016-03-24 03:16:19 -07003855 // There's no guarantee the track is still available, e.g. the track may
3856 // have been removed from the stream by an application.
deadbeefab9b2d12015-10-14 11:33:11 -07003857 stream->RemoveTrack(video_track);
deadbeefab9b2d12015-10-14 11:33:11 -07003858 }
3859 } else {
nisseede5da42017-01-12 05:15:36 -08003860 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07003861 }
Henrik Boström933d8b02017-10-10 10:05:16 -07003862 if (receiver) {
3863 observer_->OnRemoveTrack(receiver);
3864 }
deadbeefab9b2d12015-10-14 11:33:11 -07003865}
3866
3867void PeerConnection::UpdateEndedRemoteMediaStreams() {
3868 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams_to_remove;
3869 for (size_t i = 0; i < remote_streams_->count(); ++i) {
3870 MediaStreamInterface* stream = remote_streams_->at(i);
3871 if (stream->GetAudioTracks().empty() && stream->GetVideoTracks().empty()) {
3872 streams_to_remove.push_back(stream);
3873 }
3874 }
3875
Taylor Brandstetter98cde262016-05-31 13:02:21 -07003876 for (auto& stream : streams_to_remove) {
deadbeefab9b2d12015-10-14 11:33:11 -07003877 remote_streams_->RemoveStream(stream);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07003878 observer_->OnRemoveStream(std::move(stream));
deadbeefab9b2d12015-10-14 11:33:11 -07003879 }
3880}
3881
Steve Anton4171afb2017-11-20 10:20:22 -08003882void PeerConnection::UpdateLocalSenders(
deadbeefab9b2d12015-10-14 11:33:11 -07003883 const std::vector<cricket::StreamParams>& streams,
3884 cricket::MediaType media_type) {
Steve Anton4171afb2017-11-20 10:20:22 -08003885 std::vector<RtpSenderInfo>* current_senders = GetLocalSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07003886
3887 // Find removed tracks. I.e., tracks where the track id, stream label or ssrc
3888 // don't match the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08003889 for (auto sender_it = current_senders->begin();
3890 sender_it != current_senders->end();
3891 /* incremented manually */) {
3892 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07003893 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08003894 cricket::GetStreamBySsrc(streams, info.first_ssrc);
3895 if (!params || params->id != info.sender_id ||
deadbeefab9b2d12015-10-14 11:33:11 -07003896 params->sync_label != info.stream_label) {
Steve Anton4171afb2017-11-20 10:20:22 -08003897 OnLocalSenderRemoved(info, media_type);
3898 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07003899 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08003900 ++sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07003901 }
3902 }
3903
Steve Anton4171afb2017-11-20 10:20:22 -08003904 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07003905 for (const cricket::StreamParams& params : streams) {
3906 // The sync_label is the MediaStream label and the |stream.id| is the
Steve Anton4171afb2017-11-20 10:20:22 -08003907 // sender id.
deadbeefab9b2d12015-10-14 11:33:11 -07003908 const std::string& stream_label = params.sync_label;
Steve Anton4171afb2017-11-20 10:20:22 -08003909 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07003910 uint32_t ssrc = params.first_ssrc();
Steve Anton4171afb2017-11-20 10:20:22 -08003911 const RtpSenderInfo* sender_info =
3912 FindSenderInfo(*current_senders, stream_label, sender_id);
3913 if (!sender_info) {
3914 current_senders->push_back(RtpSenderInfo(stream_label, sender_id, ssrc));
3915 OnLocalSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07003916 }
3917 }
3918}
3919
Steve Anton4171afb2017-11-20 10:20:22 -08003920void PeerConnection::OnLocalSenderAdded(const RtpSenderInfo& sender_info,
3921 cricket::MediaType media_type) {
3922 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08003923 if (!sender) {
Steve Anton4171afb2017-11-20 10:20:22 -08003924 RTC_LOG(LS_WARNING) << "An unknown RtpSender with id "
3925 << sender_info.sender_id
Mirko Bonadei675513b2017-11-09 11:09:25 +01003926 << " has been configured in the local description.";
deadbeefab9b2d12015-10-14 11:33:11 -07003927 return;
3928 }
3929
deadbeeffac06552015-11-25 11:26:01 -08003930 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003931 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
Jonas Olsson45cc8902018-02-13 10:37:07 +01003932 " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08003933 return;
deadbeefab9b2d12015-10-14 11:33:11 -07003934 }
deadbeeffac06552015-11-25 11:26:01 -08003935
Steve Anton4171afb2017-11-20 10:20:22 -08003936 sender->internal()->set_stream_id(sender_info.stream_label);
3937 sender->internal()->SetSsrc(sender_info.first_ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07003938}
3939
Steve Anton4171afb2017-11-20 10:20:22 -08003940void PeerConnection::OnLocalSenderRemoved(const RtpSenderInfo& sender_info,
3941 cricket::MediaType media_type) {
3942 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08003943 if (!sender) {
3944 // This is the normal case. I.e., RemoveStream has been called and the
deadbeefab9b2d12015-10-14 11:33:11 -07003945 // SessionDescriptions has been renegotiated.
3946 return;
3947 }
deadbeeffac06552015-11-25 11:26:01 -08003948
3949 // A sender has been removed from the SessionDescription but it's still
3950 // associated with the PeerConnection. This only occurs if the SDP doesn't
3951 // match with the calls to CreateSender, AddStream and RemoveStream.
3952 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003953 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
Jonas Olsson45cc8902018-02-13 10:37:07 +01003954 " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08003955 return;
deadbeefab9b2d12015-10-14 11:33:11 -07003956 }
deadbeeffac06552015-11-25 11:26:01 -08003957
Steve Anton4171afb2017-11-20 10:20:22 -08003958 sender->internal()->SetSsrc(0);
deadbeefab9b2d12015-10-14 11:33:11 -07003959}
3960
3961void PeerConnection::UpdateLocalRtpDataChannels(
3962 const cricket::StreamParamsVec& streams) {
3963 std::vector<std::string> existing_channels;
3964
3965 // Find new and active data channels.
3966 for (const cricket::StreamParams& params : streams) {
3967 // |it->sync_label| is actually the data channel label. The reason is that
3968 // we use the same naming of data channels as we do for
3969 // MediaStreams and Tracks.
3970 // For MediaStreams, the sync_label is the MediaStream label and the
3971 // track label is the same as |streamid|.
3972 const std::string& channel_label = params.sync_label;
3973 auto data_channel_it = rtp_data_channels_.find(channel_label);
nisse7ce109a2017-01-31 00:57:56 -08003974 if (data_channel_it == rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003975 RTC_LOG(LS_ERROR) << "channel label not found";
deadbeefab9b2d12015-10-14 11:33:11 -07003976 continue;
3977 }
3978 // Set the SSRC the data channel should use for sending.
3979 data_channel_it->second->SetSendSsrc(params.first_ssrc());
3980 existing_channels.push_back(data_channel_it->first);
3981 }
3982
3983 UpdateClosingRtpDataChannels(existing_channels, true);
3984}
3985
3986void PeerConnection::UpdateRemoteRtpDataChannels(
3987 const cricket::StreamParamsVec& streams) {
3988 std::vector<std::string> existing_channels;
3989
3990 // Find new and active data channels.
3991 for (const cricket::StreamParams& params : streams) {
3992 // The data channel label is either the mslabel or the SSRC if the mslabel
3993 // does not exist. Ex a=ssrc:444330170 mslabel:test1.
3994 std::string label = params.sync_label.empty()
3995 ? rtc::ToString(params.first_ssrc())
3996 : params.sync_label;
3997 auto data_channel_it = rtp_data_channels_.find(label);
3998 if (data_channel_it == rtp_data_channels_.end()) {
3999 // This is a new data channel.
4000 CreateRemoteRtpDataChannel(label, params.first_ssrc());
4001 } else {
4002 data_channel_it->second->SetReceiveSsrc(params.first_ssrc());
4003 }
4004 existing_channels.push_back(label);
4005 }
4006
4007 UpdateClosingRtpDataChannels(existing_channels, false);
4008}
4009
4010void PeerConnection::UpdateClosingRtpDataChannels(
4011 const std::vector<std::string>& active_channels,
4012 bool is_local_update) {
4013 auto it = rtp_data_channels_.begin();
4014 while (it != rtp_data_channels_.end()) {
4015 DataChannel* data_channel = it->second;
4016 if (std::find(active_channels.begin(), active_channels.end(),
4017 data_channel->label()) != active_channels.end()) {
4018 ++it;
4019 continue;
4020 }
4021
4022 if (is_local_update) {
4023 data_channel->SetSendSsrc(0);
4024 } else {
4025 data_channel->RemotePeerRequestClose();
4026 }
4027
4028 if (data_channel->state() == DataChannel::kClosed) {
4029 rtp_data_channels_.erase(it);
4030 it = rtp_data_channels_.begin();
4031 } else {
4032 ++it;
4033 }
4034 }
4035}
4036
4037void PeerConnection::CreateRemoteRtpDataChannel(const std::string& label,
4038 uint32_t remote_ssrc) {
4039 rtc::scoped_refptr<DataChannel> channel(
4040 InternalCreateDataChannel(label, nullptr));
4041 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004042 RTC_LOG(LS_WARNING) << "Remote peer requested a DataChannel but"
Jonas Olsson45cc8902018-02-13 10:37:07 +01004043 "CreateDataChannel failed.";
deadbeefab9b2d12015-10-14 11:33:11 -07004044 return;
4045 }
4046 channel->SetReceiveSsrc(remote_ssrc);
deadbeefa601f5c2016-06-06 14:27:39 -07004047 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
4048 DataChannelProxy::Create(signaling_thread(), channel);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07004049 observer_->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07004050}
4051
4052rtc::scoped_refptr<DataChannel> PeerConnection::InternalCreateDataChannel(
4053 const std::string& label,
4054 const InternalDataChannelInit* config) {
4055 if (IsClosed()) {
4056 return nullptr;
4057 }
Steve Anton75737c02017-11-06 10:37:17 -08004058 if (data_channel_type() == cricket::DCT_NONE) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004059 RTC_LOG(LS_ERROR)
deadbeefab9b2d12015-10-14 11:33:11 -07004060 << "InternalCreateDataChannel: Data is not supported in this call.";
4061 return nullptr;
4062 }
4063 InternalDataChannelInit new_config =
4064 config ? (*config) : InternalDataChannelInit();
Steve Anton75737c02017-11-06 10:37:17 -08004065 if (data_channel_type() == cricket::DCT_SCTP) {
deadbeefab9b2d12015-10-14 11:33:11 -07004066 if (new_config.id < 0) {
4067 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08004068 if ((GetSctpSslRole(&role)) &&
deadbeefab9b2d12015-10-14 11:33:11 -07004069 !sid_allocator_.AllocateSid(role, &new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004070 RTC_LOG(LS_ERROR)
4071 << "No id can be allocated for the SCTP data channel.";
deadbeefab9b2d12015-10-14 11:33:11 -07004072 return nullptr;
4073 }
4074 } else if (!sid_allocator_.ReserveSid(new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004075 RTC_LOG(LS_ERROR) << "Failed to create a SCTP data channel "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004076 "because the id is already in use or out of range.";
deadbeefab9b2d12015-10-14 11:33:11 -07004077 return nullptr;
4078 }
4079 }
4080
Steve Anton75737c02017-11-06 10:37:17 -08004081 rtc::scoped_refptr<DataChannel> channel(
4082 DataChannel::Create(this, data_channel_type(), label, new_config));
deadbeefab9b2d12015-10-14 11:33:11 -07004083 if (!channel) {
4084 sid_allocator_.ReleaseSid(new_config.id);
4085 return nullptr;
4086 }
4087
4088 if (channel->data_channel_type() == cricket::DCT_RTP) {
4089 if (rtp_data_channels_.find(channel->label()) != rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004090 RTC_LOG(LS_ERROR) << "DataChannel with label " << channel->label()
4091 << " already exists.";
deadbeefab9b2d12015-10-14 11:33:11 -07004092 return nullptr;
4093 }
4094 rtp_data_channels_[channel->label()] = channel;
4095 } else {
4096 RTC_DCHECK(channel->data_channel_type() == cricket::DCT_SCTP);
4097 sctp_data_channels_.push_back(channel);
4098 channel->SignalClosed.connect(this,
4099 &PeerConnection::OnSctpDataChannelClosed);
4100 }
4101
Steve Anton2d8609c2018-01-23 16:38:46 -08004102 SignalDataChannelCreated_(channel.get());
deadbeefab9b2d12015-10-14 11:33:11 -07004103 return channel;
4104}
4105
4106bool PeerConnection::HasDataChannels() const {
4107 return !rtp_data_channels_.empty() || !sctp_data_channels_.empty();
4108}
4109
4110void PeerConnection::AllocateSctpSids(rtc::SSLRole role) {
4111 for (const auto& channel : sctp_data_channels_) {
4112 if (channel->id() < 0) {
4113 int sid;
4114 if (!sid_allocator_.AllocateSid(role, &sid)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004115 RTC_LOG(LS_ERROR) << "Failed to allocate SCTP sid.";
deadbeefab9b2d12015-10-14 11:33:11 -07004116 continue;
4117 }
4118 channel->SetSctpSid(sid);
4119 }
4120 }
4121}
4122
4123void PeerConnection::OnSctpDataChannelClosed(DataChannel* channel) {
deadbeefbd292462015-12-14 18:15:29 -08004124 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeefab9b2d12015-10-14 11:33:11 -07004125 for (auto it = sctp_data_channels_.begin(); it != sctp_data_channels_.end();
4126 ++it) {
4127 if (it->get() == channel) {
4128 if (channel->id() >= 0) {
4129 sid_allocator_.ReleaseSid(channel->id());
4130 }
deadbeefbd292462015-12-14 18:15:29 -08004131 // Since this method is triggered by a signal from the DataChannel,
4132 // we can't free it directly here; we need to free it asynchronously.
4133 sctp_data_channels_to_free_.push_back(*it);
deadbeefab9b2d12015-10-14 11:33:11 -07004134 sctp_data_channels_.erase(it);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07004135 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_FREE_DATACHANNELS,
4136 nullptr);
deadbeefab9b2d12015-10-14 11:33:11 -07004137 return;
4138 }
4139 }
4140}
4141
deadbeefab9b2d12015-10-14 11:33:11 -07004142void PeerConnection::OnDataChannelDestroyed() {
4143 // Use a temporary copy of the RTP/SCTP DataChannel list because the
4144 // DataChannel may callback to us and try to modify the list.
4145 std::map<std::string, rtc::scoped_refptr<DataChannel>> temp_rtp_dcs;
4146 temp_rtp_dcs.swap(rtp_data_channels_);
4147 for (const auto& kv : temp_rtp_dcs) {
4148 kv.second->OnTransportChannelDestroyed();
4149 }
4150
4151 std::vector<rtc::scoped_refptr<DataChannel>> temp_sctp_dcs;
4152 temp_sctp_dcs.swap(sctp_data_channels_);
4153 for (const auto& channel : temp_sctp_dcs) {
4154 channel->OnTransportChannelDestroyed();
4155 }
4156}
4157
4158void PeerConnection::OnDataChannelOpenMessage(
4159 const std::string& label,
4160 const InternalDataChannelInit& config) {
4161 rtc::scoped_refptr<DataChannel> channel(
4162 InternalCreateDataChannel(label, &config));
4163 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004164 RTC_LOG(LS_ERROR) << "Failed to create DataChannel from the OPEN message.";
deadbeefab9b2d12015-10-14 11:33:11 -07004165 return;
4166 }
4167
deadbeefa601f5c2016-06-06 14:27:39 -07004168 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
4169 DataChannelProxy::Create(signaling_thread(), channel);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07004170 observer_->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07004171}
4172
Steve Anton4171afb2017-11-20 10:20:22 -08004173rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
4174PeerConnection::GetAudioTransceiver() const {
4175 // This method only works with Plan B SDP, where there is a single
4176 // audio/video transceiver.
4177 RTC_DCHECK(!IsUnifiedPlan());
4178 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08004179 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004180 return transceiver;
4181 }
4182 }
4183 RTC_NOTREACHED();
4184 return nullptr;
4185}
4186
4187rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
4188PeerConnection::GetVideoTransceiver() const {
4189 // This method only works with Plan B SDP, where there is a single
4190 // audio/video transceiver.
4191 RTC_DCHECK(!IsUnifiedPlan());
4192 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08004193 if (transceiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004194 return transceiver;
4195 }
4196 }
4197 RTC_NOTREACHED();
4198 return nullptr;
4199}
4200
4201// TODO(bugs.webrtc.org/7600): Remove this when multiple transceivers with
4202// individual transceiver directions are supported.
zhihuang1c378ed2017-08-17 14:10:50 -07004203bool PeerConnection::HasRtpSender(cricket::MediaType type) const {
Steve Anton4171afb2017-11-20 10:20:22 -08004204 switch (type) {
4205 case cricket::MEDIA_TYPE_AUDIO:
4206 return !GetAudioTransceiver()->internal()->senders().empty();
4207 case cricket::MEDIA_TYPE_VIDEO:
4208 return !GetVideoTransceiver()->internal()->senders().empty();
4209 case cricket::MEDIA_TYPE_DATA:
4210 return false;
4211 }
4212 RTC_NOTREACHED();
4213 return false;
zhihuang1c378ed2017-08-17 14:10:50 -07004214}
4215
Steve Anton4171afb2017-11-20 10:20:22 -08004216rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
4217PeerConnection::FindSenderForTrack(MediaStreamTrackInterface* track) const {
4218 for (auto transceiver : transceivers_) {
4219 for (auto sender : transceiver->internal()->senders()) {
4220 if (sender->track() == track) {
4221 return sender;
4222 }
4223 }
4224 }
4225 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08004226}
4227
Steve Anton4171afb2017-11-20 10:20:22 -08004228rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
4229PeerConnection::FindSenderById(const std::string& sender_id) const {
4230 for (auto transceiver : transceivers_) {
4231 for (auto sender : transceiver->internal()->senders()) {
4232 if (sender->id() == sender_id) {
4233 return sender;
4234 }
4235 }
4236 }
4237 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07004238}
4239
Steve Anton4171afb2017-11-20 10:20:22 -08004240rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
4241PeerConnection::FindReceiverById(const std::string& receiver_id) const {
4242 for (auto transceiver : transceivers_) {
4243 for (auto receiver : transceiver->internal()->receivers()) {
4244 if (receiver->id() == receiver_id) {
4245 return receiver;
4246 }
4247 }
4248 }
4249 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07004250}
4251
Steve Anton4171afb2017-11-20 10:20:22 -08004252std::vector<PeerConnection::RtpSenderInfo>*
4253PeerConnection::GetRemoteSenderInfos(cricket::MediaType media_type) {
4254 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
4255 media_type == cricket::MEDIA_TYPE_VIDEO);
4256 return (media_type == cricket::MEDIA_TYPE_AUDIO)
4257 ? &remote_audio_sender_infos_
4258 : &remote_video_sender_infos_;
4259}
4260
4261std::vector<PeerConnection::RtpSenderInfo>* PeerConnection::GetLocalSenderInfos(
deadbeefab9b2d12015-10-14 11:33:11 -07004262 cricket::MediaType media_type) {
4263 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
4264 media_type == cricket::MEDIA_TYPE_VIDEO);
Steve Anton4171afb2017-11-20 10:20:22 -08004265 return (media_type == cricket::MEDIA_TYPE_AUDIO) ? &local_audio_sender_infos_
4266 : &local_video_sender_infos_;
deadbeefab9b2d12015-10-14 11:33:11 -07004267}
4268
Steve Anton4171afb2017-11-20 10:20:22 -08004269const PeerConnection::RtpSenderInfo* PeerConnection::FindSenderInfo(
4270 const std::vector<PeerConnection::RtpSenderInfo>& infos,
deadbeefab9b2d12015-10-14 11:33:11 -07004271 const std::string& stream_label,
Steve Anton4171afb2017-11-20 10:20:22 -08004272 const std::string sender_id) const {
4273 for (const RtpSenderInfo& sender_info : infos) {
4274 if (sender_info.stream_label == stream_label &&
4275 sender_info.sender_id == sender_id) {
4276 return &sender_info;
deadbeefab9b2d12015-10-14 11:33:11 -07004277 }
4278 }
4279 return nullptr;
4280}
4281
4282DataChannel* PeerConnection::FindDataChannelBySid(int sid) const {
4283 for (const auto& channel : sctp_data_channels_) {
4284 if (channel->id() == sid) {
4285 return channel;
4286 }
4287 }
4288 return nullptr;
4289}
4290
deadbeef91dd5672016-05-18 16:55:30 -07004291bool PeerConnection::InitializePortAllocator_n(
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004292 const RTCConfiguration& configuration) {
4293 cricket::ServerAddresses stun_servers;
4294 std::vector<cricket::RelayServerConfig> turn_servers;
deadbeef293e9262017-01-11 12:28:30 -08004295 if (ParseIceServers(configuration.servers, &stun_servers, &turn_servers) !=
4296 RTCErrorType::NONE) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004297 return false;
4298 }
4299
Taylor Brandstetterf8e65772016-06-27 17:20:15 -07004300 port_allocator_->Initialize();
4301
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004302 // To handle both internal and externally created port allocator, we will
4303 // enable BUNDLE here.
4304 int portallocator_flags = port_allocator_->flags();
4305 portallocator_flags |= cricket::PORTALLOCATOR_ENABLE_SHARED_SOCKET |
zhihuangb09b3f92017-03-07 14:40:51 -08004306 cricket::PORTALLOCATOR_ENABLE_IPV6 |
4307 cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI;
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004308 // If the disable-IPv6 flag was specified, we'll not override it
4309 // by experiment.
4310 if (configuration.disable_ipv6) {
4311 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
sprangc1b57a12017-02-28 08:50:47 -08004312 } else if (webrtc::field_trial::FindFullName("WebRTC-IPv6Default")
4313 .find("Disabled") == 0) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004314 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
4315 }
4316
zhihuangb09b3f92017-03-07 14:40:51 -08004317 if (configuration.disable_ipv6_on_wifi) {
4318 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI);
Mirko Bonadei675513b2017-11-09 11:09:25 +01004319 RTC_LOG(LS_INFO) << "IPv6 candidates on Wi-Fi are disabled.";
zhihuangb09b3f92017-03-07 14:40:51 -08004320 }
4321
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004322 if (configuration.tcp_candidate_policy == kTcpCandidatePolicyDisabled) {
4323 portallocator_flags |= cricket::PORTALLOCATOR_DISABLE_TCP;
Mirko Bonadei675513b2017-11-09 11:09:25 +01004324 RTC_LOG(LS_INFO) << "TCP candidates are disabled.";
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004325 }
4326
honghaiz60347052016-05-31 18:29:12 -07004327 if (configuration.candidate_network_policy ==
4328 kCandidateNetworkPolicyLowCost) {
4329 portallocator_flags |= cricket::PORTALLOCATOR_DISABLE_COSTLY_NETWORKS;
Mirko Bonadei675513b2017-11-09 11:09:25 +01004330 RTC_LOG(LS_INFO) << "Do not gather candidates on high-cost networks";
honghaiz60347052016-05-31 18:29:12 -07004331 }
4332
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +01004333 if (configuration.disable_link_local_networks) {
4334 portallocator_flags |= cricket::PORTALLOCATOR_DISABLE_LINK_LOCAL_NETWORKS;
4335 RTC_LOG(LS_INFO) << "Disable candidates on link-local network interfaces.";
4336 }
4337
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004338 port_allocator_->set_flags(portallocator_flags);
4339 // No step delay is used while allocating ports.
4340 port_allocator_->set_step_delay(cricket::kMinimumStepDelay);
4341 port_allocator_->set_candidate_filter(
4342 ConvertIceTransportTypeToCandidateFilter(configuration.type));
deadbeefd21eab32017-07-26 16:50:11 -07004343 port_allocator_->set_max_ipv6_networks(configuration.max_ipv6_networks);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004344
4345 // Call this last since it may create pooled allocator sessions using the
4346 // properties set above.
4347 port_allocator_->SetConfiguration(stun_servers, turn_servers,
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -07004348 configuration.ice_candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02004349 configuration.prune_turn_ports,
4350 configuration.turn_customizer);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004351 return true;
4352}
4353
deadbeef91dd5672016-05-18 16:55:30 -07004354bool PeerConnection::ReconfigurePortAllocator_n(
deadbeef293e9262017-01-11 12:28:30 -08004355 const cricket::ServerAddresses& stun_servers,
4356 const std::vector<cricket::RelayServerConfig>& turn_servers,
4357 IceTransportsType type,
4358 int candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02004359 bool prune_turn_ports,
4360 webrtc::TurnCustomizer* turn_customizer) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004361 port_allocator_->set_candidate_filter(
deadbeef293e9262017-01-11 12:28:30 -08004362 ConvertIceTransportTypeToCandidateFilter(type));
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004363 // Call this last since it may create pooled allocator sessions using the
4364 // candidate filter set above.
deadbeef6de92f92016-12-12 18:49:32 -08004365 return port_allocator_->SetConfiguration(
Jonas Orelandbdcee282017-10-10 14:01:40 +02004366 stun_servers, turn_servers, candidate_pool_size, prune_turn_ports,
4367 turn_customizer);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004368}
4369
Steve Antonba818672017-11-06 10:21:57 -08004370cricket::ChannelManager* PeerConnection::channel_manager() const {
4371 return factory_->channel_manager();
4372}
4373
4374MetricsObserverInterface* PeerConnection::metrics_observer() const {
4375 return uma_observer_;
4376}
4377
Elad Alon99c3fe52017-10-13 16:29:40 +02004378bool PeerConnection::StartRtcEventLog_w(
Bjorn Tereliusde939432017-11-20 17:38:14 +01004379 std::unique_ptr<RtcEventLogOutput> output,
4380 int64_t output_period_ms) {
zhihuang77985012017-02-07 15:45:16 -08004381 if (!event_log_) {
4382 return false;
4383 }
Bjorn Tereliusde939432017-11-20 17:38:14 +01004384 return event_log_->StartLogging(std::move(output), output_period_ms);
ivoc14d5dbe2016-07-04 07:06:55 -07004385}
4386
4387void PeerConnection::StopRtcEventLog_w() {
zhihuang77985012017-02-07 15:45:16 -08004388 if (event_log_) {
4389 event_log_->StopLogging();
4390 }
ivoc14d5dbe2016-07-04 07:06:55 -07004391}
nisseeaabdf62017-05-05 02:23:02 -07004392
Steve Anton75737c02017-11-06 10:37:17 -08004393cricket::BaseChannel* PeerConnection::GetChannel(
4394 const std::string& content_name) {
Steve Antondcc3c022017-12-22 16:02:54 -08004395 for (auto transceiver : transceivers_) {
4396 cricket::BaseChannel* channel = transceiver->internal()->channel();
4397 if (channel && channel->content_name() == content_name) {
4398 return channel;
4399 }
Steve Anton75737c02017-11-06 10:37:17 -08004400 }
4401 if (rtp_data_channel() &&
4402 rtp_data_channel()->content_name() == content_name) {
4403 return rtp_data_channel();
4404 }
4405 return nullptr;
4406}
4407
4408bool PeerConnection::GetSctpSslRole(rtc::SSLRole* role) {
4409 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004410 RTC_LOG(LS_INFO)
4411 << "Local and Remote descriptions must be applied to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004412 "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08004413 return false;
4414 }
4415 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004416 RTC_LOG(LS_INFO) << "Non-rejected SCTP m= section is needed to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004417 "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08004418 return false;
4419 }
4420
4421 return transport_controller_->GetSslRole(*sctp_transport_name_, role);
4422}
4423
4424bool PeerConnection::GetSslRole(const std::string& content_name,
4425 rtc::SSLRole* role) {
4426 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004427 RTC_LOG(LS_INFO)
4428 << "Local and Remote descriptions must be applied to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004429 "SSL Role of the session.";
Steve Anton75737c02017-11-06 10:37:17 -08004430 return false;
4431 }
4432
4433 return transport_controller_->GetSslRole(GetTransportName(content_name),
4434 role);
4435}
4436
Steve Antonf8470812017-12-04 10:46:21 -08004437void PeerConnection::SetSessionError(SessionError error,
4438 const std::string& error_desc) {
4439 RTC_DCHECK_RUN_ON(signaling_thread());
4440 if (error != session_error_) {
4441 session_error_ = error;
4442 session_error_desc_ = error_desc;
Steve Anton75737c02017-11-06 10:37:17 -08004443 }
4444}
4445
Steve Anton3828c062017-12-06 10:34:51 -08004446RTCError PeerConnection::UpdateSessionState(SdpType type,
Steve Anton8a006912017-12-04 15:25:56 -08004447 cricket::ContentSource source) {
4448 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08004449
4450 // If there's already a pending error then no state transition should happen.
4451 // But all call-sites should be verifying this before calling us!
Steve Antonf8470812017-12-04 10:46:21 -08004452 RTC_DCHECK(session_error() == SessionError::kNone);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004453
4454 // If this is an answer then we know whether to BUNDLE or not. If both the
4455 // local and remote side have agreed to BUNDLE, go ahead and enable it.
Steve Anton3828c062017-12-06 10:34:51 -08004456 if (type == SdpType::kAnswer) {
Steve Anton75737c02017-11-06 10:37:17 -08004457 const cricket::ContentGroup* local_bundle =
4458 local_description()->description()->GetGroupByName(
4459 cricket::GROUP_TYPE_BUNDLE);
4460 const cricket::ContentGroup* remote_bundle =
4461 remote_description()->description()->GetGroupByName(
4462 cricket::GROUP_TYPE_BUNDLE);
4463 if (local_bundle && remote_bundle) {
4464 // The answerer decides the transport to bundle on.
4465 const cricket::ContentGroup* answer_bundle =
4466 (source == cricket::CS_LOCAL ? local_bundle : remote_bundle);
4467 if (!EnableBundle(*answer_bundle)) {
Steve Anton8a006912017-12-04 15:25:56 -08004468 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
4469 kEnableBundleFailed);
Steve Anton75737c02017-11-06 10:37:17 -08004470 }
4471 }
Steve Anton75737c02017-11-06 10:37:17 -08004472 }
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004473
4474 // Only push down the transport description after potentially enabling BUNDLE;
4475 // we don't want to push down a description on a transport about to be
4476 // destroyed.
Steve Anton3828c062017-12-06 10:34:51 -08004477 RTCError error = PushdownTransportDescription(source, type);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004478 if (!error.ok()) {
4479 return error;
4480 }
4481
4482 // If this is answer-ish we're ready to let media flow.
Steve Anton3828c062017-12-06 10:34:51 -08004483 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Antoned10bd92017-12-05 10:52:59 -08004484 EnableSending();
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004485 }
4486
4487 // Update the signaling state according to the specified state machine (see
4488 // https://w3c.github.io/webrtc-pc/#rtcsignalingstate-enum).
Steve Anton3828c062017-12-06 10:34:51 -08004489 if (type == SdpType::kOffer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004490 ChangeSignalingState(source == cricket::CS_LOCAL
4491 ? PeerConnectionInterface::kHaveLocalOffer
4492 : PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton3828c062017-12-06 10:34:51 -08004493 } else if (type == SdpType::kPrAnswer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004494 ChangeSignalingState(source == cricket::CS_LOCAL
4495 ? PeerConnectionInterface::kHaveLocalPrAnswer
4496 : PeerConnectionInterface::kHaveRemotePrAnswer);
4497 } else {
Steve Anton3828c062017-12-06 10:34:51 -08004498 RTC_DCHECK(type == SdpType::kAnswer);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004499 ChangeSignalingState(PeerConnectionInterface::kStable);
4500 }
4501
4502 // Update internal objects according to the session description's media
4503 // descriptions.
Steve Anton3828c062017-12-06 10:34:51 -08004504 error = PushdownMediaDescription(type, source);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004505 if (!error.ok()) {
4506 SetSessionError(SessionError::kContent, error.message());
4507 }
4508 if (session_error() != SessionError::kNone) {
4509 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
4510 }
4511
Steve Anton8a006912017-12-04 15:25:56 -08004512 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08004513}
4514
Steve Anton8a006912017-12-04 15:25:56 -08004515RTCError PeerConnection::PushdownMediaDescription(
Steve Anton3828c062017-12-06 10:34:51 -08004516 SdpType type,
Steve Anton8a006912017-12-04 15:25:56 -08004517 cricket::ContentSource source) {
Steve Antoned10bd92017-12-05 10:52:59 -08004518 const SessionDescriptionInterface* sdesc =
4519 (source == cricket::CS_LOCAL ? local_description()
4520 : remote_description());
Steve Anton75737c02017-11-06 10:37:17 -08004521 RTC_DCHECK(sdesc);
Steve Antoned10bd92017-12-05 10:52:59 -08004522
4523 // Push down the new SDP media section for each audio/video transceiver.
4524 for (auto transceiver : transceivers_) {
Steve Anton75737c02017-11-06 10:37:17 -08004525 const ContentInfo* content_info =
Steve Antoned10bd92017-12-05 10:52:59 -08004526 FindMediaSectionForTransceiver(transceiver, sdesc);
4527 cricket::BaseChannel* channel = transceiver->internal()->channel();
4528 if (!channel || !content_info || content_info->rejected) {
Steve Anton75737c02017-11-06 10:37:17 -08004529 continue;
4530 }
4531 const MediaContentDescription* content_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08004532 content_info->media_description();
Steve Antoned10bd92017-12-05 10:52:59 -08004533 if (!content_desc) {
4534 continue;
4535 }
4536 std::string error;
4537 bool success =
4538 (source == cricket::CS_LOCAL)
Steve Anton3828c062017-12-06 10:34:51 -08004539 ? channel->SetLocalContent(content_desc, type, &error)
4540 : channel->SetRemoteContent(content_desc, type, &error);
Steve Antoned10bd92017-12-05 10:52:59 -08004541 if (!success) {
4542 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, std::move(error));
4543 }
4544 }
4545
4546 // If using the RtpDataChannel, push down the new SDP section for it too.
4547 if (rtp_data_channel_) {
4548 const ContentInfo* data_content =
4549 cricket::GetFirstDataContent(sdesc->description());
4550 if (data_content && !data_content->rejected) {
4551 const MediaContentDescription* data_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08004552 data_content->media_description();
Steve Antoned10bd92017-12-05 10:52:59 -08004553 if (data_desc) {
4554 std::string error;
4555 bool success =
4556 (source == cricket::CS_LOCAL)
Steve Anton3828c062017-12-06 10:34:51 -08004557 ? rtp_data_channel_->SetLocalContent(data_desc, type, &error)
4558 : rtp_data_channel_->SetRemoteContent(data_desc, type,
Steve Antoned10bd92017-12-05 10:52:59 -08004559 &error);
4560 if (!success) {
4561 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
4562 std::move(error));
4563 }
Steve Anton75737c02017-11-06 10:37:17 -08004564 }
4565 }
4566 }
Steve Antoned10bd92017-12-05 10:52:59 -08004567
Steve Anton75737c02017-11-06 10:37:17 -08004568 // Need complete offer/answer with an SCTP m= section before starting SCTP,
4569 // according to https://tools.ietf.org/html/draft-ietf-mmusic-sctp-sdp-19
4570 if (sctp_transport_ && local_description() && remote_description() &&
4571 cricket::GetFirstDataContent(local_description()->description()) &&
4572 cricket::GetFirstDataContent(remote_description()->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08004573 bool success = network_thread()->Invoke<bool>(
Steve Anton75737c02017-11-06 10:37:17 -08004574 RTC_FROM_HERE,
4575 rtc::Bind(&PeerConnection::PushdownSctpParameters_n, this, source));
Steve Anton8a006912017-12-04 15:25:56 -08004576 if (!success) {
4577 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
4578 "Failed to push down SCTP parameters.");
4579 }
Steve Anton75737c02017-11-06 10:37:17 -08004580 }
Steve Antoned10bd92017-12-05 10:52:59 -08004581
Steve Anton8a006912017-12-04 15:25:56 -08004582 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08004583}
4584
4585bool PeerConnection::PushdownSctpParameters_n(cricket::ContentSource source) {
4586 RTC_DCHECK(network_thread()->IsCurrent());
4587 RTC_DCHECK(local_description());
4588 RTC_DCHECK(remote_description());
4589 // Apply the SCTP port (which is hidden inside a DataCodec structure...)
4590 // When we support "max-message-size", that would also be pushed down here.
4591 return sctp_transport_->Start(
4592 GetSctpPort(local_description()->description()),
4593 GetSctpPort(remote_description()->description()));
4594}
4595
Steve Anton8a006912017-12-04 15:25:56 -08004596RTCError PeerConnection::PushdownTransportDescription(
4597 cricket::ContentSource source,
Steve Anton3828c062017-12-06 10:34:51 -08004598 SdpType type) {
Steve Anton8a006912017-12-04 15:25:56 -08004599 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08004600
Steve Anton8a006912017-12-04 15:25:56 -08004601 const SessionDescriptionInterface* sdesc =
4602 (source == cricket::CS_LOCAL ? local_description()
4603 : remote_description());
4604 RTC_DCHECK(sdesc);
4605 for (const cricket::TransportInfo& tinfo :
4606 sdesc->description()->transport_infos()) {
4607 std::string error;
4608 bool success;
4609 if (source == cricket::CS_LOCAL) {
4610 success = transport_controller_->SetLocalTransportDescription(
Steve Anton3828c062017-12-06 10:34:51 -08004611 tinfo.content_name, tinfo.description, type, &error);
Steve Anton8a006912017-12-04 15:25:56 -08004612 } else {
4613 success = transport_controller_->SetRemoteTransportDescription(
Steve Anton3828c062017-12-06 10:34:51 -08004614 tinfo.content_name, tinfo.description, type, &error);
Steve Anton8a006912017-12-04 15:25:56 -08004615 }
4616 if (!success) {
Steve Antondcc3c022017-12-22 16:02:54 -08004617 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
4618 "Failed to push down transport description for " +
4619 tinfo.content_name + ": " + error);
Steve Anton75737c02017-11-06 10:37:17 -08004620 }
4621 }
4622
Steve Anton8a006912017-12-04 15:25:56 -08004623 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08004624}
4625
4626bool PeerConnection::GetTransportDescription(
4627 const SessionDescription* description,
4628 const std::string& content_name,
4629 cricket::TransportDescription* tdesc) {
4630 if (!description || !tdesc) {
4631 return false;
4632 }
4633 const TransportInfo* transport_info =
4634 description->GetTransportInfoByName(content_name);
4635 if (!transport_info) {
4636 return false;
4637 }
4638 *tdesc = transport_info->description;
4639 return true;
4640}
4641
4642bool PeerConnection::EnableBundle(const cricket::ContentGroup& bundle) {
4643 const std::string* first_content_name = bundle.FirstContentName();
4644 if (!first_content_name) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004645 RTC_LOG(LS_WARNING) << "Tried to BUNDLE with no contents.";
Steve Anton75737c02017-11-06 10:37:17 -08004646 return false;
4647 }
4648 const std::string& transport_name = *first_content_name;
4649
4650 auto maybe_set_transport = [this, bundle,
4651 transport_name](cricket::BaseChannel* ch) {
4652 if (!ch || !bundle.HasContentName(ch->content_name())) {
Steve Antoned10bd92017-12-05 10:52:59 -08004653 return;
Steve Anton75737c02017-11-06 10:37:17 -08004654 }
4655
4656 std::string old_transport_name = ch->transport_name();
4657 if (old_transport_name == transport_name) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004658 RTC_LOG(LS_INFO) << "BUNDLE already enabled for " << ch->content_name()
4659 << " on " << transport_name << ".";
Steve Antoned10bd92017-12-05 10:52:59 -08004660 return;
Steve Anton75737c02017-11-06 10:37:17 -08004661 }
4662
4663 cricket::DtlsTransportInternal* rtp_dtls_transport =
4664 transport_controller_->CreateDtlsTransport(
4665 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4666 bool need_rtcp = (ch->rtcp_dtls_transport() != nullptr);
4667 cricket::DtlsTransportInternal* rtcp_dtls_transport = nullptr;
4668 if (need_rtcp) {
4669 rtcp_dtls_transport = transport_controller_->CreateDtlsTransport(
4670 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
4671 }
4672
4673 ch->SetTransports(rtp_dtls_transport, rtcp_dtls_transport);
Mirko Bonadei675513b2017-11-09 11:09:25 +01004674 RTC_LOG(LS_INFO) << "Enabled BUNDLE for " << ch->content_name() << " on "
4675 << transport_name << ".";
Steve Anton75737c02017-11-06 10:37:17 -08004676 transport_controller_->DestroyDtlsTransport(
4677 old_transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4678 // If the channel needs rtcp, it means that the channel used to have a
4679 // rtcp transport which needs to be deleted now.
4680 if (need_rtcp) {
4681 transport_controller_->DestroyDtlsTransport(
4682 old_transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
4683 }
Steve Anton75737c02017-11-06 10:37:17 -08004684 };
4685
Steve Antoned10bd92017-12-05 10:52:59 -08004686 for (auto transceiver : transceivers_) {
4687 maybe_set_transport(transceiver->internal()->channel());
Steve Anton75737c02017-11-06 10:37:17 -08004688 }
Steve Antoned10bd92017-12-05 10:52:59 -08004689 maybe_set_transport(rtp_data_channel_);
4690
Steve Anton75737c02017-11-06 10:37:17 -08004691 // For SCTP, transport creation/deletion happens here instead of in the
4692 // object itself.
4693 if (sctp_transport_) {
4694 RTC_DCHECK(sctp_transport_name_);
4695 RTC_DCHECK(sctp_content_name_);
4696 if (transport_name != *sctp_transport_name_ &&
4697 bundle.HasContentName(*sctp_content_name_)) {
4698 network_thread()->Invoke<void>(
4699 RTC_FROM_HERE, rtc::Bind(&PeerConnection::ChangeSctpTransport_n, this,
4700 transport_name));
4701 }
4702 }
4703
4704 return true;
4705}
4706
Steve Anton75737c02017-11-06 10:37:17 -08004707cricket::IceConfig PeerConnection::ParseIceConfig(
4708 const PeerConnectionInterface::RTCConfiguration& config) const {
4709 cricket::ContinualGatheringPolicy gathering_policy;
4710 // TODO(honghaiz): Add the third continual gathering policy in
4711 // PeerConnectionInterface and map it to GATHER_CONTINUALLY_AND_RECOVER.
4712 switch (config.continual_gathering_policy) {
4713 case PeerConnectionInterface::GATHER_ONCE:
4714 gathering_policy = cricket::GATHER_ONCE;
4715 break;
4716 case PeerConnectionInterface::GATHER_CONTINUALLY:
4717 gathering_policy = cricket::GATHER_CONTINUALLY;
4718 break;
4719 default:
4720 RTC_NOTREACHED();
4721 gathering_policy = cricket::GATHER_ONCE;
4722 }
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08004723
Steve Anton75737c02017-11-06 10:37:17 -08004724 cricket::IceConfig ice_config;
4725 ice_config.receiving_timeout = config.ice_connection_receiving_timeout;
4726 ice_config.prioritize_most_likely_candidate_pairs =
4727 config.prioritize_most_likely_ice_candidate_pairs;
4728 ice_config.backup_connection_ping_interval =
4729 config.ice_backup_candidate_pair_ping_interval;
4730 ice_config.continual_gathering_policy = gathering_policy;
4731 ice_config.presume_writable_when_fully_relayed =
4732 config.presume_writable_when_fully_relayed;
4733 ice_config.ice_check_min_interval = config.ice_check_min_interval;
4734 ice_config.regather_all_networks_interval_range =
4735 config.ice_regather_interval_range;
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08004736 ice_config.network_preference = config.network_preference;
Steve Anton75737c02017-11-06 10:37:17 -08004737 return ice_config;
4738}
4739
Steve Anton75737c02017-11-06 10:37:17 -08004740bool PeerConnection::GetLocalTrackIdBySsrc(uint32_t ssrc,
4741 std::string* track_id) {
4742 if (!local_description()) {
4743 return false;
4744 }
4745 return webrtc::GetTrackIdBySsrc(local_description()->description(), ssrc,
4746 track_id);
4747}
4748
4749bool PeerConnection::GetRemoteTrackIdBySsrc(uint32_t ssrc,
4750 std::string* track_id) {
4751 if (!remote_description()) {
4752 return false;
4753 }
4754 return webrtc::GetTrackIdBySsrc(remote_description()->description(), ssrc,
4755 track_id);
4756}
4757
4758bool PeerConnection::SendData(const cricket::SendDataParams& params,
4759 const rtc::CopyOnWriteBuffer& payload,
4760 cricket::SendDataResult* result) {
4761 if (!rtp_data_channel_ && !sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004762 RTC_LOG(LS_ERROR) << "SendData called when rtp_data_channel_ "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004763 "and sctp_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08004764 return false;
4765 }
4766 return rtp_data_channel_
4767 ? rtp_data_channel_->SendData(params, payload, result)
4768 : network_thread()->Invoke<bool>(
4769 RTC_FROM_HERE,
4770 Bind(&cricket::SctpTransportInternal::SendData,
4771 sctp_transport_.get(), params, payload, result));
4772}
4773
4774bool PeerConnection::ConnectDataChannel(DataChannel* webrtc_data_channel) {
4775 if (!rtp_data_channel_ && !sctp_transport_) {
4776 // Don't log an error here, because DataChannels are expected to call
4777 // ConnectDataChannel in this state. It's the only way to initially tell
4778 // whether or not the underlying transport is ready.
4779 return false;
4780 }
4781 if (rtp_data_channel_) {
4782 rtp_data_channel_->SignalReadyToSendData.connect(
4783 webrtc_data_channel, &DataChannel::OnChannelReady);
4784 rtp_data_channel_->SignalDataReceived.connect(webrtc_data_channel,
4785 &DataChannel::OnDataReceived);
4786 } else {
4787 SignalSctpReadyToSendData.connect(webrtc_data_channel,
4788 &DataChannel::OnChannelReady);
4789 SignalSctpDataReceived.connect(webrtc_data_channel,
4790 &DataChannel::OnDataReceived);
4791 SignalSctpStreamClosedRemotely.connect(
4792 webrtc_data_channel, &DataChannel::OnStreamClosedRemotely);
4793 }
4794 return true;
4795}
4796
4797void PeerConnection::DisconnectDataChannel(DataChannel* webrtc_data_channel) {
4798 if (!rtp_data_channel_ && !sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004799 RTC_LOG(LS_ERROR)
4800 << "DisconnectDataChannel called when rtp_data_channel_ and "
4801 "sctp_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08004802 return;
4803 }
4804 if (rtp_data_channel_) {
4805 rtp_data_channel_->SignalReadyToSendData.disconnect(webrtc_data_channel);
4806 rtp_data_channel_->SignalDataReceived.disconnect(webrtc_data_channel);
4807 } else {
4808 SignalSctpReadyToSendData.disconnect(webrtc_data_channel);
4809 SignalSctpDataReceived.disconnect(webrtc_data_channel);
4810 SignalSctpStreamClosedRemotely.disconnect(webrtc_data_channel);
4811 }
4812}
4813
4814void PeerConnection::AddSctpDataStream(int sid) {
4815 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004816 RTC_LOG(LS_ERROR)
4817 << "AddSctpDataStream called when sctp_transport_ is NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08004818 return;
4819 }
4820 network_thread()->Invoke<void>(
4821 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::OpenStream,
4822 sctp_transport_.get(), sid));
4823}
4824
4825void PeerConnection::RemoveSctpDataStream(int sid) {
4826 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004827 RTC_LOG(LS_ERROR) << "RemoveSctpDataStream called when sctp_transport_ is "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004828 "NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08004829 return;
4830 }
4831 network_thread()->Invoke<void>(
4832 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::ResetStream,
4833 sctp_transport_.get(), sid));
4834}
4835
4836bool PeerConnection::ReadyToSendData() const {
4837 return (rtp_data_channel_ && rtp_data_channel_->ready_to_send_data()) ||
4838 sctp_ready_to_send_data_;
4839}
4840
Steve Anton5dfde182018-02-06 10:34:40 -08004841std::map<std::string, std::string> PeerConnection::GetTransportNamesByMid()
4842 const {
4843 std::map<std::string, std::string> transport_names_by_mid;
4844 for (auto transceiver : transceivers_) {
4845 cricket::BaseChannel* channel = transceiver->internal()->channel();
4846 if (channel) {
4847 transport_names_by_mid[channel->content_name()] =
4848 channel->transport_name();
4849 }
Steve Anton75737c02017-11-06 10:37:17 -08004850 }
Steve Anton5dfde182018-02-06 10:34:40 -08004851 if (rtp_data_channel_) {
4852 transport_names_by_mid[rtp_data_channel_->content_name()] =
4853 rtp_data_channel_->transport_name();
Steve Anton75737c02017-11-06 10:37:17 -08004854 }
4855 if (sctp_transport_) {
Steve Anton5dfde182018-02-06 10:34:40 -08004856 transport_names_by_mid[*sctp_content_name_] = *sctp_transport_name_;
Steve Anton75737c02017-11-06 10:37:17 -08004857 }
Steve Anton5dfde182018-02-06 10:34:40 -08004858 return transport_names_by_mid;
Steve Anton75737c02017-11-06 10:37:17 -08004859}
4860
Steve Anton5dfde182018-02-06 10:34:40 -08004861std::map<std::string, cricket::TransportStats>
4862PeerConnection::GetTransportStatsByNames(
4863 const std::set<std::string>& transport_names) {
4864 if (!network_thread()->IsCurrent()) {
4865 return network_thread()
4866 ->Invoke<std::map<std::string, cricket::TransportStats>>(
4867 RTC_FROM_HERE,
4868 [&] { return GetTransportStatsByNames(transport_names); });
Steve Anton75737c02017-11-06 10:37:17 -08004869 }
Steve Anton5dfde182018-02-06 10:34:40 -08004870 std::map<std::string, cricket::TransportStats> transport_stats_by_name;
4871 for (const std::string& transport_name : transport_names) {
4872 cricket::TransportStats transport_stats;
4873 bool success =
4874 transport_controller_->GetStats(transport_name, &transport_stats);
4875 if (success) {
4876 transport_stats_by_name[transport_name] = std::move(transport_stats);
4877 } else {
4878 RTC_LOG(LS_ERROR) << "Failed to get transport stats for transport_name="
4879 << transport_name;
4880 }
4881 }
4882 return transport_stats_by_name;
Steve Anton75737c02017-11-06 10:37:17 -08004883}
4884
4885bool PeerConnection::GetLocalCertificate(
4886 const std::string& transport_name,
4887 rtc::scoped_refptr<rtc::RTCCertificate>* certificate) {
4888 return transport_controller_->GetLocalCertificate(transport_name,
4889 certificate);
4890}
4891
4892std::unique_ptr<rtc::SSLCertificate> PeerConnection::GetRemoteSSLCertificate(
4893 const std::string& transport_name) {
4894 return transport_controller_->GetRemoteSSLCertificate(transport_name);
4895}
4896
4897cricket::DataChannelType PeerConnection::data_channel_type() const {
4898 return data_channel_type_;
4899}
4900
4901bool PeerConnection::IceRestartPending(const std::string& content_name) const {
4902 return pending_ice_restarts_.find(content_name) !=
4903 pending_ice_restarts_.end();
4904}
4905
Steve Anton75737c02017-11-06 10:37:17 -08004906bool PeerConnection::NeedsIceRestart(const std::string& content_name) const {
4907 return transport_controller_->NeedsIceRestart(content_name);
4908}
4909
4910void PeerConnection::OnCertificateReady(
4911 const rtc::scoped_refptr<rtc::RTCCertificate>& certificate) {
4912 transport_controller_->SetLocalCertificate(certificate);
4913}
4914
4915void PeerConnection::OnDtlsSrtpSetupFailure(cricket::BaseChannel*, bool rtcp) {
Steve Antonf8470812017-12-04 10:46:21 -08004916 SetSessionError(SessionError::kTransport,
4917 rtcp ? kDtlsSrtpSetupFailureRtcp : kDtlsSrtpSetupFailureRtp);
Steve Anton75737c02017-11-06 10:37:17 -08004918}
4919
4920void PeerConnection::OnTransportControllerConnectionState(
4921 cricket::IceConnectionState state) {
4922 switch (state) {
4923 case cricket::kIceConnectionConnecting:
4924 // If the current state is Connected or Completed, then there were
4925 // writable channels but now there are not, so the next state must
4926 // be Disconnected.
4927 // kIceConnectionConnecting is currently used as the default,
4928 // un-connected state by the TransportController, so its only use is
4929 // detecting disconnections.
4930 if (ice_connection_state_ ==
4931 PeerConnectionInterface::kIceConnectionConnected ||
4932 ice_connection_state_ ==
4933 PeerConnectionInterface::kIceConnectionCompleted) {
4934 SetIceConnectionState(
4935 PeerConnectionInterface::kIceConnectionDisconnected);
4936 }
4937 break;
4938 case cricket::kIceConnectionFailed:
4939 SetIceConnectionState(PeerConnectionInterface::kIceConnectionFailed);
4940 break;
4941 case cricket::kIceConnectionConnected:
Mirko Bonadei675513b2017-11-09 11:09:25 +01004942 RTC_LOG(LS_INFO) << "Changing to ICE connected state because "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004943 "all transports are writable.";
Steve Anton75737c02017-11-06 10:37:17 -08004944 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
4945 break;
4946 case cricket::kIceConnectionCompleted:
Mirko Bonadei675513b2017-11-09 11:09:25 +01004947 RTC_LOG(LS_INFO) << "Changing to ICE completed state because "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004948 "all transports are complete.";
Steve Anton75737c02017-11-06 10:37:17 -08004949 if (ice_connection_state_ !=
4950 PeerConnectionInterface::kIceConnectionConnected) {
4951 // If jumping directly from "checking" to "connected",
4952 // signal "connected" first.
4953 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
4954 }
4955 SetIceConnectionState(PeerConnectionInterface::kIceConnectionCompleted);
4956 if (metrics_observer()) {
4957 ReportTransportStats();
4958 }
4959 break;
4960 default:
4961 RTC_NOTREACHED();
4962 }
4963}
4964
4965void PeerConnection::OnTransportControllerCandidatesGathered(
4966 const std::string& transport_name,
4967 const cricket::Candidates& candidates) {
4968 RTC_DCHECK(signaling_thread()->IsCurrent());
4969 int sdp_mline_index;
4970 if (!GetLocalCandidateMediaIndex(transport_name, &sdp_mline_index)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004971 RTC_LOG(LS_ERROR)
4972 << "OnTransportControllerCandidatesGathered: content name "
4973 << transport_name << " not found";
Steve Anton75737c02017-11-06 10:37:17 -08004974 return;
4975 }
4976
4977 for (cricket::Candidates::const_iterator citer = candidates.begin();
4978 citer != candidates.end(); ++citer) {
4979 // Use transport_name as the candidate media id.
4980 std::unique_ptr<JsepIceCandidate> candidate(
4981 new JsepIceCandidate(transport_name, sdp_mline_index, *citer));
4982 if (local_description()) {
4983 mutable_local_description()->AddCandidate(candidate.get());
4984 }
4985 OnIceCandidate(std::move(candidate));
4986 }
4987}
4988
4989void PeerConnection::OnTransportControllerCandidatesRemoved(
4990 const std::vector<cricket::Candidate>& candidates) {
4991 RTC_DCHECK(signaling_thread()->IsCurrent());
4992 // Sanity check.
4993 for (const cricket::Candidate& candidate : candidates) {
4994 if (candidate.transport_name().empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004995 RTC_LOG(LS_ERROR) << "OnTransportControllerCandidatesRemoved: "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004996 "empty content name in candidate "
Mirko Bonadei675513b2017-11-09 11:09:25 +01004997 << candidate.ToString();
Steve Anton75737c02017-11-06 10:37:17 -08004998 return;
4999 }
5000 }
5001
5002 if (local_description()) {
5003 mutable_local_description()->RemoveCandidates(candidates);
5004 }
5005 OnIceCandidatesRemoved(candidates);
5006}
5007
5008void PeerConnection::OnTransportControllerDtlsHandshakeError(
5009 rtc::SSLHandshakeError error) {
5010 if (metrics_observer()) {
5011 metrics_observer()->IncrementEnumCounter(
5012 webrtc::kEnumCounterDtlsHandshakeError, static_cast<int>(error),
5013 static_cast<int>(rtc::SSLHandshakeError::MAX_VALUE));
5014 }
5015}
5016
Steve Antoned10bd92017-12-05 10:52:59 -08005017void PeerConnection::EnableSending() {
5018 for (auto transceiver : transceivers_) {
5019 cricket::BaseChannel* channel = transceiver->internal()->channel();
5020 if (channel && !channel->enabled()) {
5021 channel->Enable(true);
5022 }
Steve Anton75737c02017-11-06 10:37:17 -08005023 }
5024
Steve Anton4171afb2017-11-20 10:20:22 -08005025 if (rtp_data_channel_ && !rtp_data_channel_->enabled()) {
Steve Anton75737c02017-11-06 10:37:17 -08005026 rtp_data_channel_->Enable(true);
Steve Anton4171afb2017-11-20 10:20:22 -08005027 }
Steve Anton75737c02017-11-06 10:37:17 -08005028}
5029
5030// Returns the media index for a local ice candidate given the content name.
5031bool PeerConnection::GetLocalCandidateMediaIndex(
5032 const std::string& content_name,
5033 int* sdp_mline_index) {
5034 if (!local_description() || !sdp_mline_index) {
5035 return false;
5036 }
5037
5038 bool content_found = false;
5039 const ContentInfos& contents = local_description()->description()->contents();
5040 for (size_t index = 0; index < contents.size(); ++index) {
5041 if (contents[index].name == content_name) {
5042 *sdp_mline_index = static_cast<int>(index);
5043 content_found = true;
5044 break;
5045 }
5046 }
5047 return content_found;
5048}
5049
5050bool PeerConnection::UseCandidatesInSessionDescription(
5051 const SessionDescriptionInterface* remote_desc) {
5052 if (!remote_desc) {
5053 return true;
5054 }
5055 bool ret = true;
5056
5057 for (size_t m = 0; m < remote_desc->number_of_mediasections(); ++m) {
5058 const IceCandidateCollection* candidates = remote_desc->candidates(m);
5059 for (size_t n = 0; n < candidates->count(); ++n) {
5060 const IceCandidateInterface* candidate = candidates->at(n);
5061 bool valid = false;
5062 if (!ReadyToUseRemoteCandidate(candidate, remote_desc, &valid)) {
5063 if (valid) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005064 RTC_LOG(LS_INFO)
5065 << "UseCandidatesInSessionDescription: Not ready to use "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005066 "candidate.";
Steve Anton75737c02017-11-06 10:37:17 -08005067 }
5068 continue;
5069 }
5070 ret = UseCandidate(candidate);
5071 if (!ret) {
5072 break;
5073 }
5074 }
5075 }
5076 return ret;
5077}
5078
5079bool PeerConnection::UseCandidate(const IceCandidateInterface* candidate) {
5080 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
5081 size_t remote_content_size =
5082 remote_description()->description()->contents().size();
5083 if (mediacontent_index >= remote_content_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005084 RTC_LOG(LS_ERROR) << "UseCandidate: Invalid candidate media index.";
Steve Anton75737c02017-11-06 10:37:17 -08005085 return false;
5086 }
5087
5088 cricket::ContentInfo content =
5089 remote_description()->description()->contents()[mediacontent_index];
5090 std::vector<cricket::Candidate> candidates;
5091 candidates.push_back(candidate->candidate());
5092 // Invoking BaseSession method to handle remote candidates.
5093 std::string error;
5094 if (transport_controller_->AddRemoteCandidates(content.name, candidates,
5095 &error)) {
5096 // Candidates successfully submitted for checking.
5097 if (ice_connection_state_ == PeerConnectionInterface::kIceConnectionNew ||
5098 ice_connection_state_ ==
5099 PeerConnectionInterface::kIceConnectionDisconnected) {
5100 // If state is New, then the session has just gotten its first remote ICE
5101 // candidates, so go to Checking.
5102 // If state is Disconnected, the session is re-using old candidates or
5103 // receiving additional ones, so go to Checking.
5104 // If state is Connected, stay Connected.
5105 // TODO(bemasc): If state is Connected, and the new candidates are for a
5106 // newly added transport, then the state actually _should_ move to
5107 // checking. Add a way to distinguish that case.
5108 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
5109 }
5110 // TODO(bemasc): If state is Completed, go back to Connected.
5111 } else {
5112 if (!error.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005113 RTC_LOG(LS_WARNING) << error;
Steve Anton75737c02017-11-06 10:37:17 -08005114 }
5115 }
5116 return true;
5117}
5118
5119void PeerConnection::RemoveUnusedChannels(const SessionDescription* desc) {
Steve Anton75737c02017-11-06 10:37:17 -08005120 // Destroy video channel first since it may have a pointer to the
5121 // voice channel.
5122 const cricket::ContentInfo* video_info = cricket::GetFirstVideoContent(desc);
Steve Anton6fec8802017-12-04 10:37:29 -08005123 if (!video_info || video_info->rejected) {
5124 DestroyTransceiverChannel(GetVideoTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08005125 }
5126
Steve Anton6fec8802017-12-04 10:37:29 -08005127 const cricket::ContentInfo* audio_info = cricket::GetFirstAudioContent(desc);
5128 if (!audio_info || audio_info->rejected) {
5129 DestroyTransceiverChannel(GetAudioTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08005130 }
5131
5132 const cricket::ContentInfo* data_info = cricket::GetFirstDataContent(desc);
5133 if (!data_info || data_info->rejected) {
Steve Anton6fec8802017-12-04 10:37:29 -08005134 DestroyDataChannel();
Steve Anton75737c02017-11-06 10:37:17 -08005135 }
5136}
5137
Steve Antoneda6ccd2017-12-04 10:21:55 -08005138std::string PeerConnection::GetTransportNameForMediaSection(
5139 const std::string& mid,
5140 const cricket::ContentGroup* bundle_group) const {
5141 if (!bundle_group) {
5142 return mid;
Steve Anton75737c02017-11-06 10:37:17 -08005143 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005144 const std::string* first_content_name = bundle_group->FirstContentName();
Steve Anton75737c02017-11-06 10:37:17 -08005145 if (!first_content_name) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005146 RTC_LOG(LS_WARNING) << "Tried to BUNDLE with no contents.";
Steve Antoneda6ccd2017-12-04 10:21:55 -08005147 return mid;
Steve Anton75737c02017-11-06 10:37:17 -08005148 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005149 if (!bundle_group->HasContentName(mid)) {
5150 RTC_LOG(LS_WARNING) << mid << " is not part of any bundle group";
5151 return mid;
Steve Anton75737c02017-11-06 10:37:17 -08005152 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005153 RTC_LOG(LS_INFO) << "Bundling " << mid << " on " << *first_content_name;
5154 return *first_content_name;
Steve Anton75737c02017-11-06 10:37:17 -08005155}
5156
Steve Antondcc3c022017-12-22 16:02:54 -08005157RTCErrorOr<const cricket::ContentGroup*> PeerConnection::GetEarlyBundleGroup(
5158 const SessionDescription& desc) const {
Steve Anton75737c02017-11-06 10:37:17 -08005159 const cricket::ContentGroup* bundle_group = nullptr;
5160 if (configuration_.bundle_policy ==
5161 PeerConnectionInterface::kBundlePolicyMaxBundle) {
Steve Antondcc3c022017-12-22 16:02:54 -08005162 bundle_group = desc.GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton75737c02017-11-06 10:37:17 -08005163 if (!bundle_group) {
Steve Anton8a006912017-12-04 15:25:56 -08005164 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5165 "max-bundle configured but session description "
5166 "has no BUNDLE group");
Steve Anton75737c02017-11-06 10:37:17 -08005167 }
5168 }
Steve Antondcc3c022017-12-22 16:02:54 -08005169 return std::move(bundle_group);
5170}
5171
5172RTCError PeerConnection::CreateChannels(const SessionDescription& desc) {
5173 auto bundle_group_or_error = GetEarlyBundleGroup(desc);
5174 if (!bundle_group_or_error.ok()) {
5175 return bundle_group_or_error.MoveError();
5176 }
5177 const cricket::ContentGroup* bundle_group = bundle_group_or_error.MoveValue();
Steve Anton75737c02017-11-06 10:37:17 -08005178
Steve Antoneda6ccd2017-12-04 10:21:55 -08005179 // Creating the media channels and transport proxies.
Steve Antondcc3c022017-12-22 16:02:54 -08005180 const cricket::ContentInfo* voice = cricket::GetFirstAudioContent(&desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08005181 if (voice && !voice->rejected &&
5182 !GetAudioTransceiver()->internal()->channel()) {
5183 cricket::VoiceChannel* voice_channel = CreateVoiceChannel(
5184 voice->name,
5185 GetTransportNameForMediaSection(voice->name, bundle_group));
5186 if (!voice_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08005187 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5188 "Failed to create voice channel.");
Steve Antoneda6ccd2017-12-04 10:21:55 -08005189 }
5190 GetAudioTransceiver()->internal()->SetChannel(voice_channel);
5191 }
5192
Steve Antondcc3c022017-12-22 16:02:54 -08005193 const cricket::ContentInfo* video = cricket::GetFirstVideoContent(&desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08005194 if (video && !video->rejected &&
5195 !GetVideoTransceiver()->internal()->channel()) {
5196 cricket::VideoChannel* video_channel = CreateVideoChannel(
5197 video->name,
5198 GetTransportNameForMediaSection(video->name, bundle_group));
5199 if (!video_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08005200 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5201 "Failed to create video channel.");
Steve Anton75737c02017-11-06 10:37:17 -08005202 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005203 GetVideoTransceiver()->internal()->SetChannel(video_channel);
Steve Anton75737c02017-11-06 10:37:17 -08005204 }
5205
Steve Antondcc3c022017-12-22 16:02:54 -08005206 const cricket::ContentInfo* data = cricket::GetFirstDataContent(&desc);
Steve Anton75737c02017-11-06 10:37:17 -08005207 if (data_channel_type_ != cricket::DCT_NONE && data && !data->rejected &&
5208 !rtp_data_channel_ && !sctp_transport_) {
Steve Antoneda6ccd2017-12-04 10:21:55 -08005209 if (!CreateDataChannel(data->name, GetTransportNameForMediaSection(
5210 data->name, bundle_group))) {
Steve Anton8a006912017-12-04 15:25:56 -08005211 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5212 "Failed to create data channel.");
Steve Anton75737c02017-11-06 10:37:17 -08005213 }
5214 }
5215
Steve Anton8a006912017-12-04 15:25:56 -08005216 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08005217}
5218
Steve Anton4171afb2017-11-20 10:20:22 -08005219// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08005220cricket::VoiceChannel* PeerConnection::CreateVoiceChannel(
5221 const std::string& mid,
5222 const std::string& transport_name) {
Steve Anton75737c02017-11-06 10:37:17 -08005223 cricket::DtlsTransportInternal* rtp_dtls_transport =
5224 transport_controller_->CreateDtlsTransport(
5225 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5226 cricket::DtlsTransportInternal* rtcp_dtls_transport = nullptr;
5227 if (configuration_.rtcp_mux_policy !=
5228 PeerConnectionInterface::kRtcpMuxPolicyRequire) {
5229 rtcp_dtls_transport = transport_controller_->CreateDtlsTransport(
5230 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
5231 }
5232
5233 cricket::VoiceChannel* voice_channel = channel_manager()->CreateVoiceChannel(
5234 call_.get(), configuration_.media_config, rtp_dtls_transport,
Steve Antoneda6ccd2017-12-04 10:21:55 -08005235 rtcp_dtls_transport, signaling_thread(), mid, SrtpRequired(),
5236 audio_options_);
Steve Anton75737c02017-11-06 10:37:17 -08005237 if (!voice_channel) {
5238 transport_controller_->DestroyDtlsTransport(
5239 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5240 if (rtcp_dtls_transport) {
5241 transport_controller_->DestroyDtlsTransport(
5242 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
5243 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005244 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08005245 }
Steve Anton75737c02017-11-06 10:37:17 -08005246 voice_channel->SignalRtcpMuxFullyActive.connect(
5247 this, &PeerConnection::DestroyRtcpTransport_n);
5248 voice_channel->SignalDtlsSrtpSetupFailure.connect(
5249 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08005250 voice_channel->SignalSentPacket.connect(this,
5251 &PeerConnection::OnSentPacket_w);
Steve Anton4171afb2017-11-20 10:20:22 -08005252
Steve Antoneda6ccd2017-12-04 10:21:55 -08005253 return voice_channel;
Steve Anton75737c02017-11-06 10:37:17 -08005254}
5255
Steve Anton4171afb2017-11-20 10:20:22 -08005256// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08005257cricket::VideoChannel* PeerConnection::CreateVideoChannel(
5258 const std::string& mid,
5259 const std::string& transport_name) {
Steve Anton75737c02017-11-06 10:37:17 -08005260 cricket::DtlsTransportInternal* rtp_dtls_transport =
5261 transport_controller_->CreateDtlsTransport(
5262 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5263 cricket::DtlsTransportInternal* rtcp_dtls_transport = nullptr;
5264 if (configuration_.rtcp_mux_policy !=
5265 PeerConnectionInterface::kRtcpMuxPolicyRequire) {
5266 rtcp_dtls_transport = transport_controller_->CreateDtlsTransport(
5267 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
5268 }
5269
5270 cricket::VideoChannel* video_channel = channel_manager()->CreateVideoChannel(
5271 call_.get(), configuration_.media_config, rtp_dtls_transport,
Steve Antoneda6ccd2017-12-04 10:21:55 -08005272 rtcp_dtls_transport, signaling_thread(), mid, SrtpRequired(),
5273 video_options_);
Steve Anton75737c02017-11-06 10:37:17 -08005274
5275 if (!video_channel) {
5276 transport_controller_->DestroyDtlsTransport(
5277 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5278 if (rtcp_dtls_transport) {
5279 transport_controller_->DestroyDtlsTransport(
5280 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
5281 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005282 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08005283 }
Steve Anton75737c02017-11-06 10:37:17 -08005284 video_channel->SignalRtcpMuxFullyActive.connect(
5285 this, &PeerConnection::DestroyRtcpTransport_n);
5286 video_channel->SignalDtlsSrtpSetupFailure.connect(
5287 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08005288 video_channel->SignalSentPacket.connect(this,
5289 &PeerConnection::OnSentPacket_w);
Steve Anton4171afb2017-11-20 10:20:22 -08005290
Steve Antoneda6ccd2017-12-04 10:21:55 -08005291 return video_channel;
Steve Anton75737c02017-11-06 10:37:17 -08005292}
5293
Steve Antoneda6ccd2017-12-04 10:21:55 -08005294bool PeerConnection::CreateDataChannel(const std::string& mid,
5295 const std::string& transport_name) {
Steve Anton75737c02017-11-06 10:37:17 -08005296 bool sctp = (data_channel_type_ == cricket::DCT_SCTP);
5297 if (sctp) {
5298 if (!sctp_factory_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005299 RTC_LOG(LS_ERROR)
Steve Anton75737c02017-11-06 10:37:17 -08005300 << "Trying to create SCTP transport, but didn't compile with "
5301 "SCTP support (HAVE_SCTP)";
5302 return false;
5303 }
5304 if (!network_thread()->Invoke<bool>(
5305 RTC_FROM_HERE, rtc::Bind(&PeerConnection::CreateSctpTransport_n,
Steve Antoneda6ccd2017-12-04 10:21:55 -08005306 this, mid, transport_name))) {
Steve Anton75737c02017-11-06 10:37:17 -08005307 return false;
5308 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005309 for (const auto& channel : sctp_data_channels_) {
5310 channel->OnTransportChannelCreated();
5311 }
Steve Anton75737c02017-11-06 10:37:17 -08005312 } else {
Steve Anton75737c02017-11-06 10:37:17 -08005313 cricket::DtlsTransportInternal* rtp_dtls_transport =
5314 transport_controller_->CreateDtlsTransport(
5315 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5316 cricket::DtlsTransportInternal* rtcp_dtls_transport = nullptr;
5317 if (configuration_.rtcp_mux_policy !=
5318 PeerConnectionInterface::kRtcpMuxPolicyRequire) {
5319 rtcp_dtls_transport = transport_controller_->CreateDtlsTransport(
5320 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
5321 }
5322
5323 rtp_data_channel_ = channel_manager()->CreateRtpDataChannel(
5324 configuration_.media_config, rtp_dtls_transport, rtcp_dtls_transport,
Steve Antoneda6ccd2017-12-04 10:21:55 -08005325 signaling_thread(), mid, SrtpRequired());
Steve Anton75737c02017-11-06 10:37:17 -08005326
5327 if (!rtp_data_channel_) {
5328 transport_controller_->DestroyDtlsTransport(
5329 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5330 if (rtcp_dtls_transport) {
5331 transport_controller_->DestroyDtlsTransport(
5332 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
5333 }
5334 return false;
5335 }
5336
5337 rtp_data_channel_->SignalRtcpMuxFullyActive.connect(
5338 this, &PeerConnection::DestroyRtcpTransport_n);
5339 rtp_data_channel_->SignalDtlsSrtpSetupFailure.connect(
5340 this, &PeerConnection::OnDtlsSrtpSetupFailure);
5341 rtp_data_channel_->SignalSentPacket.connect(
5342 this, &PeerConnection::OnSentPacket_w);
5343 }
5344
Steve Anton75737c02017-11-06 10:37:17 -08005345 return true;
5346}
5347
5348Call::Stats PeerConnection::GetCallStats() {
5349 if (!worker_thread()->IsCurrent()) {
5350 return worker_thread()->Invoke<Call::Stats>(
5351 RTC_FROM_HERE, rtc::Bind(&PeerConnection::GetCallStats, this));
5352 }
5353 if (call_) {
5354 return call_->GetStats();
5355 } else {
5356 return Call::Stats();
5357 }
5358}
5359
Steve Anton75737c02017-11-06 10:37:17 -08005360bool PeerConnection::CreateSctpTransport_n(const std::string& content_name,
5361 const std::string& transport_name) {
5362 RTC_DCHECK(network_thread()->IsCurrent());
5363 RTC_DCHECK(sctp_factory_);
5364 cricket::DtlsTransportInternal* tc =
5365 transport_controller_->CreateDtlsTransport_n(
5366 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5367 sctp_transport_ = sctp_factory_->CreateSctpTransport(tc);
5368 RTC_DCHECK(sctp_transport_);
5369 sctp_invoker_.reset(new rtc::AsyncInvoker());
5370 sctp_transport_->SignalReadyToSendData.connect(
5371 this, &PeerConnection::OnSctpTransportReadyToSendData_n);
5372 sctp_transport_->SignalDataReceived.connect(
5373 this, &PeerConnection::OnSctpTransportDataReceived_n);
5374 sctp_transport_->SignalStreamClosedRemotely.connect(
5375 this, &PeerConnection::OnSctpStreamClosedRemotely_n);
Oskar Sundbom9b28a032017-11-16 10:53:30 +01005376 sctp_transport_name_ = transport_name;
5377 sctp_content_name_ = content_name;
Steve Anton75737c02017-11-06 10:37:17 -08005378 return true;
5379}
5380
5381void PeerConnection::ChangeSctpTransport_n(const std::string& transport_name) {
5382 RTC_DCHECK(network_thread()->IsCurrent());
5383 RTC_DCHECK(sctp_transport_);
5384 RTC_DCHECK(sctp_transport_name_);
5385 std::string old_sctp_transport_name = *sctp_transport_name_;
Oskar Sundbom9b28a032017-11-16 10:53:30 +01005386 sctp_transport_name_ = transport_name;
Steve Anton75737c02017-11-06 10:37:17 -08005387 cricket::DtlsTransportInternal* tc =
5388 transport_controller_->CreateDtlsTransport_n(
5389 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5390 sctp_transport_->SetTransportChannel(tc);
5391 transport_controller_->DestroyDtlsTransport_n(
5392 old_sctp_transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5393}
5394
5395void PeerConnection::DestroySctpTransport_n() {
5396 RTC_DCHECK(network_thread()->IsCurrent());
5397 sctp_transport_.reset(nullptr);
Taylor Brandstetter389a97c2018-01-03 16:26:06 -08005398 transport_controller_->DestroyDtlsTransport_n(
5399 *sctp_transport_name_, cricket::ICE_CANDIDATE_COMPONENT_RTP);
Steve Anton75737c02017-11-06 10:37:17 -08005400 sctp_content_name_.reset();
5401 sctp_transport_name_.reset();
5402 sctp_invoker_.reset(nullptr);
5403 sctp_ready_to_send_data_ = false;
5404}
5405
5406void PeerConnection::OnSctpTransportReadyToSendData_n() {
5407 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5408 RTC_DCHECK(network_thread()->IsCurrent());
5409 // Note: Cannot use rtc::Bind here because it will grab a reference to
5410 // PeerConnection and potentially cause PeerConnection to live longer than
5411 // expected. It is safe not to grab a reference since the sctp_invoker_ will
5412 // be destroyed before PeerConnection is destroyed, and at that point all
5413 // pending tasks will be cleared.
5414 sctp_invoker_->AsyncInvoke<void>(RTC_FROM_HERE, signaling_thread(), [this] {
5415 OnSctpTransportReadyToSendData_s(true);
5416 });
5417}
5418
5419void PeerConnection::OnSctpTransportReadyToSendData_s(bool ready) {
5420 RTC_DCHECK(signaling_thread()->IsCurrent());
5421 sctp_ready_to_send_data_ = ready;
5422 SignalSctpReadyToSendData(ready);
5423}
5424
5425void PeerConnection::OnSctpTransportDataReceived_n(
5426 const cricket::ReceiveDataParams& params,
5427 const rtc::CopyOnWriteBuffer& payload) {
5428 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5429 RTC_DCHECK(network_thread()->IsCurrent());
5430 // Note: Cannot use rtc::Bind here because it will grab a reference to
5431 // PeerConnection and potentially cause PeerConnection to live longer than
5432 // expected. It is safe not to grab a reference since the sctp_invoker_ will
5433 // be destroyed before PeerConnection is destroyed, and at that point all
5434 // pending tasks will be cleared.
5435 sctp_invoker_->AsyncInvoke<void>(
5436 RTC_FROM_HERE, signaling_thread(), [this, params, payload] {
5437 OnSctpTransportDataReceived_s(params, payload);
5438 });
5439}
5440
5441void PeerConnection::OnSctpTransportDataReceived_s(
5442 const cricket::ReceiveDataParams& params,
5443 const rtc::CopyOnWriteBuffer& payload) {
5444 RTC_DCHECK(signaling_thread()->IsCurrent());
5445 if (params.type == cricket::DMT_CONTROL && IsOpenMessage(payload)) {
5446 // Received OPEN message; parse and signal that a new data channel should
5447 // be created.
5448 std::string label;
5449 InternalDataChannelInit config;
5450 config.id = params.ssrc;
5451 if (!ParseDataChannelOpenMessage(payload, &label, &config)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005452 RTC_LOG(LS_WARNING) << "Failed to parse the OPEN message for sid "
5453 << params.ssrc;
Steve Anton75737c02017-11-06 10:37:17 -08005454 return;
5455 }
5456 config.open_handshake_role = InternalDataChannelInit::kAcker;
5457 OnDataChannelOpenMessage(label, config);
5458 } else {
5459 // Otherwise just forward the signal.
5460 SignalSctpDataReceived(params, payload);
5461 }
5462}
5463
5464void PeerConnection::OnSctpStreamClosedRemotely_n(int sid) {
5465 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5466 RTC_DCHECK(network_thread()->IsCurrent());
5467 sctp_invoker_->AsyncInvoke<void>(
5468 RTC_FROM_HERE, signaling_thread(),
5469 rtc::Bind(&sigslot::signal1<int>::operator(),
5470 &SignalSctpStreamClosedRemotely, sid));
5471}
5472
5473// Returns false if bundle is enabled and rtcp_mux is disabled.
5474bool PeerConnection::ValidateBundleSettings(const SessionDescription* desc) {
5475 bool bundle_enabled = desc->HasGroup(cricket::GROUP_TYPE_BUNDLE);
5476 if (!bundle_enabled)
5477 return true;
5478
5479 const cricket::ContentGroup* bundle_group =
5480 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
5481 RTC_DCHECK(bundle_group != NULL);
5482
5483 const cricket::ContentInfos& contents = desc->contents();
5484 for (cricket::ContentInfos::const_iterator citer = contents.begin();
5485 citer != contents.end(); ++citer) {
5486 const cricket::ContentInfo* content = (&*citer);
5487 RTC_DCHECK(content != NULL);
5488 if (bundle_group->HasContentName(content->name) && !content->rejected &&
Steve Anton5adfafd2017-12-20 16:34:00 -08005489 content->type == MediaProtocolType::kRtp) {
Steve Anton75737c02017-11-06 10:37:17 -08005490 if (!HasRtcpMuxEnabled(content))
5491 return false;
5492 }
5493 }
5494 // RTCP-MUX is enabled in all the contents.
5495 return true;
5496}
5497
5498bool PeerConnection::HasRtcpMuxEnabled(const cricket::ContentInfo* content) {
Steve Antonb1c1de12017-12-21 15:14:30 -08005499 return content->media_description()->rtcp_mux();
Steve Anton75737c02017-11-06 10:37:17 -08005500}
5501
Steve Anton8a006912017-12-04 15:25:56 -08005502RTCError PeerConnection::ValidateSessionDescription(
Steve Anton75737c02017-11-06 10:37:17 -08005503 const SessionDescriptionInterface* sdesc,
Steve Anton8a006912017-12-04 15:25:56 -08005504 cricket::ContentSource source) {
Steve Antonf8470812017-12-04 10:46:21 -08005505 if (session_error() != SessionError::kNone) {
Steve Anton8a006912017-12-04 15:25:56 -08005506 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
Steve Anton75737c02017-11-06 10:37:17 -08005507 }
5508
5509 if (!sdesc || !sdesc->description()) {
Steve Anton8a006912017-12-04 15:25:56 -08005510 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidSdp);
Steve Anton75737c02017-11-06 10:37:17 -08005511 }
5512
Steve Anton3828c062017-12-06 10:34:51 -08005513 SdpType type = sdesc->GetType();
5514 if ((source == cricket::CS_LOCAL && !ExpectSetLocalDescription(type)) ||
5515 (source == cricket::CS_REMOTE && !ExpectSetRemoteDescription(type))) {
Steve Anton8a006912017-12-04 15:25:56 -08005516 LOG_AND_RETURN_ERROR(
5517 RTCErrorType::INVALID_PARAMETER,
5518 "Called in wrong state: " + GetSignalingStateString(signaling_state()));
Steve Anton75737c02017-11-06 10:37:17 -08005519 }
5520
5521 // Verify crypto settings.
5522 std::string crypto_error;
Steve Anton8a006912017-12-04 15:25:56 -08005523 if (webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED ||
5524 dtls_enabled_) {
Harald Alvestrand194939b2018-01-24 16:04:13 +01005525 RTCError crypto_error =
5526 VerifyCrypto(sdesc->description(), dtls_enabled_, uma_observer_);
Steve Anton8a006912017-12-04 15:25:56 -08005527 if (!crypto_error.ok()) {
5528 return crypto_error;
5529 }
Steve Anton75737c02017-11-06 10:37:17 -08005530 }
5531
5532 // Verify ice-ufrag and ice-pwd.
5533 if (!VerifyIceUfragPwdPresent(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08005534 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5535 kSdpWithoutIceUfragPwd);
Steve Anton75737c02017-11-06 10:37:17 -08005536 }
5537
5538 if (!ValidateBundleSettings(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08005539 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5540 kBundleWithoutRtcpMux);
Steve Anton75737c02017-11-06 10:37:17 -08005541 }
5542
5543 // TODO(skvlad): When the local rtcp-mux policy is Require, reject any
5544 // m-lines that do not rtcp-mux enabled.
5545
5546 // Verify m-lines in Answer when compared against Offer.
Steve Anton3828c062017-12-06 10:34:51 -08005547 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Seth Hampsonae8a90a2018-02-13 15:33:48 -08005548 // With an answer we want to compare the new answer session description with
5549 // the offer's session description from the current negotiation.
Steve Anton75737c02017-11-06 10:37:17 -08005550 const cricket::SessionDescription* offer_desc =
5551 (source == cricket::CS_LOCAL) ? remote_description()->description()
5552 : local_description()->description();
Seth Hampsonae8a90a2018-02-13 15:33:48 -08005553 if (!MediaSectionsHaveSameCount(*offer_desc, *sdesc->description()) ||
5554 !MediaSectionsInSameOrder(*offer_desc, nullptr, *sdesc->description(),
5555 type)) {
Steve Anton8a006912017-12-04 15:25:56 -08005556 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5557 kMlineMismatchInAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08005558 }
5559 } else {
Steve Anton75737c02017-11-06 10:37:17 -08005560 // The re-offers should respect the order of m= sections in current
5561 // description. See RFC3264 Section 8 paragraph 4 for more details.
Seth Hampsonae8a90a2018-02-13 15:33:48 -08005562 // With a re-offer, either the current local or current remote descriptions
5563 // could be the most up to date, so we would like to check against both of
5564 // them if they exist. It could be the case that one of them has a 0 port
5565 // for a media section, but the other does not. This is important to check
5566 // against in the case that we are recycling an m= section.
5567 const cricket::SessionDescription* current_desc = nullptr;
5568 const cricket::SessionDescription* secondary_current_desc = nullptr;
5569 if (local_description()) {
5570 current_desc = local_description()->description();
5571 if (remote_description()) {
5572 secondary_current_desc = remote_description()->description();
5573 }
5574 } else if (remote_description()) {
5575 current_desc = remote_description()->description();
5576 }
Steve Anton75737c02017-11-06 10:37:17 -08005577 if (current_desc &&
Seth Hampsonae8a90a2018-02-13 15:33:48 -08005578 !MediaSectionsInSameOrder(*current_desc, secondary_current_desc,
5579 *sdesc->description(), type)) {
Steve Anton8a006912017-12-04 15:25:56 -08005580 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5581 kMlineMismatchInSubsequentOffer);
Steve Anton75737c02017-11-06 10:37:17 -08005582 }
5583 }
5584
Steve Anton8a006912017-12-04 15:25:56 -08005585 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08005586}
5587
Steve Anton3828c062017-12-06 10:34:51 -08005588bool PeerConnection::ExpectSetLocalDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08005589 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08005590 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08005591 return (state == PeerConnectionInterface::kStable) ||
5592 (state == PeerConnectionInterface::kHaveLocalOffer);
Steve Anton20393062017-12-04 16:24:52 -08005593 } else {
Steve Anton3828c062017-12-06 10:34:51 -08005594 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08005595 return (state == PeerConnectionInterface::kHaveRemoteOffer) ||
5596 (state == PeerConnectionInterface::kHaveLocalPrAnswer);
5597 }
5598}
5599
Steve Anton3828c062017-12-06 10:34:51 -08005600bool PeerConnection::ExpectSetRemoteDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08005601 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08005602 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08005603 return (state == PeerConnectionInterface::kStable) ||
5604 (state == PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton20393062017-12-04 16:24:52 -08005605 } else {
Steve Anton3828c062017-12-06 10:34:51 -08005606 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08005607 return (state == PeerConnectionInterface::kHaveLocalOffer) ||
5608 (state == PeerConnectionInterface::kHaveRemotePrAnswer);
5609 }
5610}
5611
Steve Antonf8470812017-12-04 10:46:21 -08005612const char* PeerConnection::SessionErrorToString(SessionError error) const {
5613 switch (error) {
5614 case SessionError::kNone:
5615 return "ERROR_NONE";
5616 case SessionError::kContent:
5617 return "ERROR_CONTENT";
5618 case SessionError::kTransport:
5619 return "ERROR_TRANSPORT";
5620 }
5621 RTC_NOTREACHED();
5622 return "";
5623}
5624
Steve Anton75737c02017-11-06 10:37:17 -08005625std::string PeerConnection::GetSessionErrorMsg() {
5626 std::ostringstream desc;
Steve Antonf8470812017-12-04 10:46:21 -08005627 desc << kSessionError << SessionErrorToString(session_error()) << ". ";
5628 desc << kSessionErrorDesc << session_error_desc() << ".";
Steve Anton75737c02017-11-06 10:37:17 -08005629 return desc.str();
5630}
5631
5632// We need to check the local/remote description for the Transport instead of
5633// the session, because a new Transport added during renegotiation may have
5634// them unset while the session has them set from the previous negotiation.
5635// Not doing so may trigger the auto generation of transport description and
5636// mess up DTLS identity information, ICE credential, etc.
5637bool PeerConnection::ReadyToUseRemoteCandidate(
5638 const IceCandidateInterface* candidate,
5639 const SessionDescriptionInterface* remote_desc,
5640 bool* valid) {
5641 *valid = true;
5642
5643 const SessionDescriptionInterface* current_remote_desc =
5644 remote_desc ? remote_desc : remote_description();
5645
5646 if (!current_remote_desc) {
5647 return false;
5648 }
5649
5650 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
5651 size_t remote_content_size =
5652 current_remote_desc->description()->contents().size();
5653 if (mediacontent_index >= remote_content_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005654 RTC_LOG(LS_ERROR)
5655 << "ReadyToUseRemoteCandidate: Invalid candidate media index "
5656 << mediacontent_index;
Steve Anton75737c02017-11-06 10:37:17 -08005657
5658 *valid = false;
5659 return false;
5660 }
5661
5662 cricket::ContentInfo content =
5663 current_remote_desc->description()->contents()[mediacontent_index];
5664
5665 const std::string transport_name = GetTransportName(content.name);
5666 if (transport_name.empty()) {
5667 return false;
5668 }
5669 return transport_controller_->ReadyForRemoteCandidates(transport_name);
5670}
5671
5672bool PeerConnection::SrtpRequired() const {
5673 return dtls_enabled_ ||
5674 webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED;
5675}
5676
5677void PeerConnection::OnTransportControllerGatheringState(
5678 cricket::IceGatheringState state) {
5679 RTC_DCHECK(signaling_thread()->IsCurrent());
5680 if (state == cricket::kIceGatheringGathering) {
5681 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringGathering);
5682 } else if (state == cricket::kIceGatheringComplete) {
5683 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringComplete);
5684 }
5685}
5686
5687void PeerConnection::ReportTransportStats() {
Steve Antonc7b964c2018-02-01 14:39:45 -08005688 std::map<std::string, std::set<cricket::MediaType>>
5689 media_types_by_transport_name;
5690 for (auto transceiver : transceivers_) {
5691 if (transceiver->internal()->channel()) {
5692 const std::string& transport_name =
5693 transceiver->internal()->channel()->transport_name();
5694 media_types_by_transport_name[transport_name].insert(
Steve Anton69470252018-02-09 11:43:08 -08005695 transceiver->media_type());
Steve Antonc7b964c2018-02-01 14:39:45 -08005696 }
Steve Anton75737c02017-11-06 10:37:17 -08005697 }
5698 if (rtp_data_channel()) {
Steve Antonc7b964c2018-02-01 14:39:45 -08005699 media_types_by_transport_name[rtp_data_channel()->transport_name()].insert(
5700 cricket::MEDIA_TYPE_DATA);
Steve Anton75737c02017-11-06 10:37:17 -08005701 }
5702 if (sctp_transport_name_) {
Steve Antonc7b964c2018-02-01 14:39:45 -08005703 media_types_by_transport_name[*sctp_transport_name_].insert(
5704 cricket::MEDIA_TYPE_DATA);
Steve Anton75737c02017-11-06 10:37:17 -08005705 }
Steve Antonc7b964c2018-02-01 14:39:45 -08005706 for (const auto& entry : media_types_by_transport_name) {
5707 const std::string& transport_name = entry.first;
5708 const std::set<cricket::MediaType> media_types = entry.second;
Steve Anton75737c02017-11-06 10:37:17 -08005709 cricket::TransportStats stats;
Steve Antonc7b964c2018-02-01 14:39:45 -08005710 if (transport_controller_->GetStats(transport_name, &stats)) {
Steve Anton75737c02017-11-06 10:37:17 -08005711 ReportBestConnectionState(stats);
Steve Antonc7b964c2018-02-01 14:39:45 -08005712 ReportNegotiatedCiphers(stats, media_types);
Steve Anton75737c02017-11-06 10:37:17 -08005713 }
5714 }
5715}
5716// Walk through the ConnectionInfos to gather best connection usage
5717// for IPv4 and IPv6.
5718void PeerConnection::ReportBestConnectionState(
5719 const cricket::TransportStats& stats) {
5720 RTC_DCHECK(metrics_observer());
Steve Antonc7b964c2018-02-01 14:39:45 -08005721 for (const cricket::TransportChannelStats& channel_stats :
5722 stats.channel_stats) {
5723 for (const cricket::ConnectionInfo& connection_info :
5724 channel_stats.connection_infos) {
5725 if (!connection_info.best_connection) {
Steve Anton75737c02017-11-06 10:37:17 -08005726 continue;
5727 }
5728
5729 PeerConnectionEnumCounterType type = kPeerConnectionEnumCounterMax;
Steve Antonc7b964c2018-02-01 14:39:45 -08005730 const cricket::Candidate& local = connection_info.local_candidate;
5731 const cricket::Candidate& remote = connection_info.remote_candidate;
Steve Anton75737c02017-11-06 10:37:17 -08005732
5733 // Increment the counter for IceCandidatePairType.
5734 if (local.protocol() == cricket::TCP_PROTOCOL_NAME ||
5735 (local.type() == RELAY_PORT_TYPE &&
5736 local.relay_protocol() == cricket::TCP_PROTOCOL_NAME)) {
5737 type = kEnumCounterIceCandidatePairTypeTcp;
5738 } else if (local.protocol() == cricket::UDP_PROTOCOL_NAME) {
5739 type = kEnumCounterIceCandidatePairTypeUdp;
5740 } else {
5741 RTC_CHECK(0);
5742 }
5743 metrics_observer()->IncrementEnumCounter(
5744 type, GetIceCandidatePairCounter(local, remote),
5745 kIceCandidatePairMax);
5746
5747 // Increment the counter for IP type.
5748 if (local.address().family() == AF_INET) {
5749 metrics_observer()->IncrementEnumCounter(
5750 kEnumCounterAddressFamily, kBestConnections_IPv4,
5751 kPeerConnectionAddressFamilyCounter_Max);
5752
5753 } else if (local.address().family() == AF_INET6) {
5754 metrics_observer()->IncrementEnumCounter(
5755 kEnumCounterAddressFamily, kBestConnections_IPv6,
5756 kPeerConnectionAddressFamilyCounter_Max);
5757 } else {
5758 RTC_CHECK(0);
5759 }
5760
5761 return;
5762 }
5763 }
5764}
5765
5766void PeerConnection::ReportNegotiatedCiphers(
Steve Antonc7b964c2018-02-01 14:39:45 -08005767 const cricket::TransportStats& stats,
5768 const std::set<cricket::MediaType>& media_types) {
Steve Anton75737c02017-11-06 10:37:17 -08005769 RTC_DCHECK(metrics_observer());
5770 if (!dtls_enabled_ || stats.channel_stats.empty()) {
5771 return;
5772 }
5773
5774 int srtp_crypto_suite = stats.channel_stats[0].srtp_crypto_suite;
5775 int ssl_cipher_suite = stats.channel_stats[0].ssl_cipher_suite;
5776 if (srtp_crypto_suite == rtc::SRTP_INVALID_CRYPTO_SUITE &&
5777 ssl_cipher_suite == rtc::TLS_NULL_WITH_NULL_NULL) {
5778 return;
5779 }
5780
Steve Antonc7b964c2018-02-01 14:39:45 -08005781 for (cricket::MediaType media_type : media_types) {
5782 PeerConnectionEnumCounterType srtp_counter_type;
5783 PeerConnectionEnumCounterType ssl_counter_type;
5784 switch (media_type) {
5785 case cricket::MEDIA_TYPE_AUDIO:
5786 srtp_counter_type = kEnumCounterAudioSrtpCipher;
5787 ssl_counter_type = kEnumCounterAudioSslCipher;
5788 break;
5789 case cricket::MEDIA_TYPE_VIDEO:
5790 srtp_counter_type = kEnumCounterVideoSrtpCipher;
5791 ssl_counter_type = kEnumCounterVideoSslCipher;
5792 break;
5793 case cricket::MEDIA_TYPE_DATA:
5794 srtp_counter_type = kEnumCounterDataSrtpCipher;
5795 ssl_counter_type = kEnumCounterDataSslCipher;
5796 break;
5797 default:
5798 RTC_NOTREACHED();
5799 continue;
5800 }
5801 if (srtp_crypto_suite != rtc::SRTP_INVALID_CRYPTO_SUITE) {
5802 metrics_observer()->IncrementSparseEnumCounter(srtp_counter_type,
5803 srtp_crypto_suite);
5804 }
5805 if (ssl_cipher_suite != rtc::TLS_NULL_WITH_NULL_NULL) {
5806 metrics_observer()->IncrementSparseEnumCounter(ssl_counter_type,
5807 ssl_cipher_suite);
5808 }
Steve Anton75737c02017-11-06 10:37:17 -08005809 }
5810}
5811
5812void PeerConnection::OnSentPacket_w(const rtc::SentPacket& sent_packet) {
5813 RTC_DCHECK(worker_thread()->IsCurrent());
5814 RTC_DCHECK(call_);
5815 call_->OnSentPacket(sent_packet);
5816}
5817
5818const std::string PeerConnection::GetTransportName(
5819 const std::string& content_name) {
5820 cricket::BaseChannel* channel = GetChannel(content_name);
Steve Anton6fec8802017-12-04 10:37:29 -08005821 if (channel) {
5822 return channel->transport_name();
Steve Anton75737c02017-11-06 10:37:17 -08005823 }
Steve Anton6fec8802017-12-04 10:37:29 -08005824 if (sctp_transport_) {
5825 RTC_DCHECK(sctp_content_name_);
5826 RTC_DCHECK(sctp_transport_name_);
5827 if (content_name == *sctp_content_name_) {
5828 return *sctp_transport_name_;
5829 }
5830 }
5831 // Return an empty string if failed to retrieve the transport name.
5832 return "";
Steve Anton75737c02017-11-06 10:37:17 -08005833}
5834
5835void PeerConnection::DestroyRtcpTransport_n(const std::string& transport_name) {
5836 RTC_DCHECK(network_thread()->IsCurrent());
5837 transport_controller_->DestroyDtlsTransport_n(
5838 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
5839}
5840
Steve Anton6fec8802017-12-04 10:37:29 -08005841void PeerConnection::DestroyTransceiverChannel(
5842 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
5843 transceiver) {
5844 RTC_DCHECK(transceiver);
Steve Anton75737c02017-11-06 10:37:17 -08005845
Steve Anton6fec8802017-12-04 10:37:29 -08005846 cricket::BaseChannel* channel = transceiver->internal()->channel();
5847 if (channel) {
5848 transceiver->internal()->SetChannel(nullptr);
5849 DestroyBaseChannel(channel);
Steve Anton75737c02017-11-06 10:37:17 -08005850 }
5851}
5852
5853void PeerConnection::DestroyDataChannel() {
Steve Anton6fec8802017-12-04 10:37:29 -08005854 if (rtp_data_channel_) {
5855 OnDataChannelDestroyed();
5856 DestroyBaseChannel(rtp_data_channel_);
5857 rtp_data_channel_ = nullptr;
5858 }
5859
5860 // Note: Cannot use rtc::Bind to create a functor to invoke because it will
5861 // grab a reference to this PeerConnection. If this is called from the
5862 // PeerConnection destructor, the RefCountedObject vtable will have already
5863 // been destroyed (since it is a subclass of PeerConnection) and using
5864 // rtc::Bind will cause "Pure virtual function called" error to appear.
5865
5866 if (sctp_transport_) {
5867 OnDataChannelDestroyed();
5868 network_thread()->Invoke<void>(RTC_FROM_HERE,
5869 [this] { DestroySctpTransport_n(); });
5870 }
5871}
5872
5873void PeerConnection::DestroyBaseChannel(cricket::BaseChannel* channel) {
5874 RTC_DCHECK(channel);
5875 RTC_DCHECK(channel->rtp_dtls_transport());
5876
5877 // Need to cache these before destroying the base channel so that we do not
5878 // access uninitialized memory.
5879 const std::string transport_name =
5880 channel->rtp_dtls_transport()->transport_name();
5881 const bool need_to_delete_rtcp = (channel->rtcp_dtls_transport() != nullptr);
5882
5883 switch (channel->media_type()) {
5884 case cricket::MEDIA_TYPE_AUDIO:
5885 channel_manager()->DestroyVoiceChannel(
5886 static_cast<cricket::VoiceChannel*>(channel));
5887 break;
5888 case cricket::MEDIA_TYPE_VIDEO:
5889 channel_manager()->DestroyVideoChannel(
5890 static_cast<cricket::VideoChannel*>(channel));
5891 break;
5892 case cricket::MEDIA_TYPE_DATA:
5893 channel_manager()->DestroyRtpDataChannel(
5894 static_cast<cricket::RtpDataChannel*>(channel));
5895 break;
5896 default:
5897 RTC_NOTREACHED() << "Unknown media type: " << channel->media_type();
5898 break;
5899 }
5900
5901 // |channel| can no longer be used.
5902
Steve Anton75737c02017-11-06 10:37:17 -08005903 transport_controller_->DestroyDtlsTransport(
5904 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5905 if (need_to_delete_rtcp) {
5906 transport_controller_->DestroyDtlsTransport(
5907 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
5908 }
5909}
5910
Harald Alvestrand89061872018-01-02 14:08:34 +01005911void PeerConnection::ClearStatsCache() {
5912 if (stats_collector_) {
5913 stats_collector_->ClearCachedStatsReport();
5914 }
5915}
5916
henrike@webrtc.org28e20752013-07-10 00:45:36 +00005917} // namespace webrtc