blob: 245e89d216accca9f73964b4639b689b756b7118 [file] [log] [blame]
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001/*
kjellanderb24317b2016-02-10 07:54:43 -08002 * Copyright 2012 The WebRTC project authors. All Rights Reserved.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003 *
kjellanderb24317b2016-02-10 07:54:43 -08004 * Use of this source code is governed by a BSD-style license
5 * that can be found in the LICENSE file in the root of the source
6 * tree. An additional intellectual property rights grant can be found
7 * in the file PATENTS. All contributing project authors may
8 * be found in the AUTHORS file in the root of the source tree.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00009 */
10
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020011#include "pc/peerconnection.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000012
deadbeefeb459812015-12-15 19:24:43 -080013#include <algorithm>
Steve Antondcc3c022017-12-22 16:02:54 -080014#include <queue>
Steve Anton75737c02017-11-06 10:37:17 -080015#include <set>
kwiberg0eb15ed2015-12-17 03:04:15 -080016#include <utility>
17#include <vector>
henrike@webrtc.org28e20752013-07-10 00:45:36 +000018
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020019#include "api/jsepicecandidate.h"
20#include "api/jsepsessiondescription.h"
21#include "api/mediaconstraintsinterface.h"
22#include "api/mediastreamproxy.h"
23#include "api/mediastreamtrackproxy.h"
24#include "call/call.h"
Qingsi Wang93a84392018-01-30 17:13:09 -080025#include "logging/rtc_event_log/icelogger.h"
Elad Alon83ccca12017-10-04 13:18:26 +020026#include "logging/rtc_event_log/output/rtc_event_log_output_file.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020027#include "logging/rtc_event_log/rtc_event_log.h"
28#include "media/sctp/sctptransport.h"
29#include "pc/audiotrack.h"
Steve Anton75737c02017-11-06 10:37:17 -080030#include "pc/channel.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020031#include "pc/channelmanager.h"
32#include "pc/dtmfsender.h"
33#include "pc/mediastream.h"
34#include "pc/mediastreamobserver.h"
35#include "pc/remoteaudiosource.h"
Steve Anton1d03a752017-11-27 14:30:09 -080036#include "pc/rtpmediautils.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020037#include "pc/rtpreceiver.h"
38#include "pc/rtpsender.h"
Steve Anton75737c02017-11-06 10:37:17 -080039#include "pc/sctputils.h"
Steve Antona3a92c22017-12-07 10:27:41 -080040#include "pc/sdputils.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020041#include "pc/streamcollection.h"
42#include "pc/videocapturertracksource.h"
43#include "pc/videotrack.h"
44#include "rtc_base/bind.h"
45#include "rtc_base/checks.h"
46#include "rtc_base/logging.h"
Karl Wiberge40468b2017-11-22 10:42:26 +010047#include "rtc_base/numerics/safe_conversions.h"
Elad Alon83ccca12017-10-04 13:18:26 +020048#include "rtc_base/ptr_util.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020049#include "rtc_base/stringencode.h"
50#include "rtc_base/stringutils.h"
51#include "rtc_base/trace_event.h"
52#include "system_wrappers/include/clock.h"
53#include "system_wrappers/include/field_trial.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000054
Steve Anton75737c02017-11-06 10:37:17 -080055using cricket::ContentInfo;
56using cricket::ContentInfos;
57using cricket::MediaContentDescription;
58using cricket::SessionDescription;
Steve Anton5adfafd2017-12-20 16:34:00 -080059using cricket::MediaProtocolType;
Steve Anton75737c02017-11-06 10:37:17 -080060using cricket::TransportInfo;
61
62using cricket::LOCAL_PORT_TYPE;
63using cricket::STUN_PORT_TYPE;
64using cricket::RELAY_PORT_TYPE;
65using cricket::PRFLX_PORT_TYPE;
66
Steve Antonba818672017-11-06 10:21:57 -080067namespace webrtc {
68
Steve Anton75737c02017-11-06 10:37:17 -080069// Error messages
70const char kBundleWithoutRtcpMux[] =
71 "rtcp-mux must be enabled when BUNDLE "
72 "is enabled.";
Steve Anton75737c02017-11-06 10:37:17 -080073const char kInvalidCandidates[] = "Description contains invalid candidates.";
74const char kInvalidSdp[] = "Invalid session description.";
75const char kMlineMismatchInAnswer[] =
76 "The order of m-lines in answer doesn't match order in offer. Rejecting "
77 "answer.";
78const char kMlineMismatchInSubsequentOffer[] =
79 "The order of m-lines in subsequent offer doesn't match order from "
80 "previous offer/answer.";
Steve Anton75737c02017-11-06 10:37:17 -080081const char kSdpWithoutDtlsFingerprint[] =
82 "Called with SDP without DTLS fingerprint.";
83const char kSdpWithoutSdesCrypto[] = "Called with SDP without SDES crypto.";
84const char kSdpWithoutIceUfragPwd[] =
85 "Called with SDP without ice-ufrag and ice-pwd.";
86const char kSessionError[] = "Session error code: ";
87const char kSessionErrorDesc[] = "Session error description: ";
88const char kDtlsSrtpSetupFailureRtp[] =
89 "Couldn't set up DTLS-SRTP on RTP channel.";
90const char kDtlsSrtpSetupFailureRtcp[] =
91 "Couldn't set up DTLS-SRTP on RTCP channel.";
92const char kEnableBundleFailed[] = "Failed to enable BUNDLE.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +000093
Steve Anton75737c02017-11-06 10:37:17 -080094namespace {
henrike@webrtc.org28e20752013-07-10 00:45:36 +000095
deadbeefab9b2d12015-10-14 11:33:11 -070096static const char kDefaultStreamLabel[] = "default";
Steve Anton4171afb2017-11-20 10:20:22 -080097static const char kDefaultAudioSenderId[] = "defaulta0";
98static const char kDefaultVideoSenderId[] = "defaultv0";
deadbeefab9b2d12015-10-14 11:33:11 -070099
zhihuang8f65cdf2016-05-06 18:40:30 -0700100// The length of RTCP CNAMEs.
101static const int kRtcpCnameLength = 16;
102
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000103enum {
wu@webrtc.org91053e72013-08-10 07:18:04 +0000104 MSG_SET_SESSIONDESCRIPTION_SUCCESS = 0,
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000105 MSG_SET_SESSIONDESCRIPTION_FAILED,
deadbeefab9b2d12015-10-14 11:33:11 -0700106 MSG_CREATE_SESSIONDESCRIPTION_FAILED,
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000107 MSG_GETSTATS,
deadbeefbd292462015-12-14 18:15:29 -0800108 MSG_FREE_DATACHANNELS,
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000109};
110
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000111struct SetSessionDescriptionMsg : public rtc::MessageData {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000112 explicit SetSessionDescriptionMsg(
113 webrtc::SetSessionDescriptionObserver* observer)
114 : observer(observer) {
115 }
116
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000117 rtc::scoped_refptr<webrtc::SetSessionDescriptionObserver> observer;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000118 std::string error;
119};
120
deadbeefab9b2d12015-10-14 11:33:11 -0700121struct CreateSessionDescriptionMsg : public rtc::MessageData {
122 explicit CreateSessionDescriptionMsg(
123 webrtc::CreateSessionDescriptionObserver* observer)
124 : observer(observer) {}
125
126 rtc::scoped_refptr<webrtc::CreateSessionDescriptionObserver> observer;
127 std::string error;
128};
129
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000130struct GetStatsMsg : public rtc::MessageData {
tommi@webrtc.org5b06b062014-08-15 08:38:30 +0000131 GetStatsMsg(webrtc::StatsObserver* observer,
132 webrtc::MediaStreamTrackInterface* track)
133 : observer(observer), track(track) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000134 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000135 rtc::scoped_refptr<webrtc::StatsObserver> observer;
tommi@webrtc.org5b06b062014-08-15 08:38:30 +0000136 rtc::scoped_refptr<webrtc::MediaStreamTrackInterface> track;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000137};
138
deadbeefab9b2d12015-10-14 11:33:11 -0700139// Check if we can send |new_stream| on a PeerConnection.
140bool CanAddLocalMediaStream(webrtc::StreamCollectionInterface* current_streams,
141 webrtc::MediaStreamInterface* new_stream) {
142 if (!new_stream || !current_streams) {
143 return false;
144 }
145 if (current_streams->find(new_stream->label()) != nullptr) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100146 RTC_LOG(LS_ERROR) << "MediaStream with label " << new_stream->label()
147 << " is already added.";
deadbeefab9b2d12015-10-14 11:33:11 -0700148 return false;
149 }
150 return true;
151}
152
deadbeef5e97fb52015-10-15 12:49:08 -0700153// If the direction is "recvonly" or "inactive", treat the description
154// as containing no streams.
155// See: https://code.google.com/p/webrtc/issues/detail?id=5054
156std::vector<cricket::StreamParams> GetActiveStreams(
157 const cricket::MediaContentDescription* desc) {
Steve Anton4e70a722017-11-28 14:57:10 -0800158 return RtpTransceiverDirectionHasSend(desc->direction())
deadbeef5e97fb52015-10-15 12:49:08 -0700159 ? desc->streams()
160 : std::vector<cricket::StreamParams>();
161}
162
deadbeefab9b2d12015-10-14 11:33:11 -0700163bool IsValidOfferToReceiveMedia(int value) {
164 typedef PeerConnectionInterface::RTCOfferAnswerOptions Options;
165 return (value >= Options::kUndefined) &&
166 (value <= Options::kMaxOfferToReceiveMedia);
167}
168
zhihuang1c378ed2017-08-17 14:10:50 -0700169// Add options to |[audio/video]_media_description_options| from |senders|.
170void AddRtpSenderOptions(
deadbeefa601f5c2016-06-06 14:27:39 -0700171 const std::vector<rtc::scoped_refptr<
172 RtpSenderProxyWithInternal<RtpSenderInternal>>>& senders,
zhihuang1c378ed2017-08-17 14:10:50 -0700173 cricket::MediaDescriptionOptions* audio_media_description_options,
174 cricket::MediaDescriptionOptions* video_media_description_options) {
olka3c747662017-08-17 06:50:32 -0700175 for (const auto& sender : senders) {
zhihuang1c378ed2017-08-17 14:10:50 -0700176 if (sender->media_type() == cricket::MEDIA_TYPE_AUDIO) {
177 if (audio_media_description_options) {
178 audio_media_description_options->AddAudioSender(
Steve Anton8ffb9c32017-08-31 15:45:38 -0700179 sender->id(), sender->internal()->stream_ids());
zhihuang1c378ed2017-08-17 14:10:50 -0700180 }
181 } else {
182 RTC_DCHECK(sender->media_type() == cricket::MEDIA_TYPE_VIDEO);
183 if (video_media_description_options) {
184 video_media_description_options->AddVideoSender(
Steve Anton8ffb9c32017-08-31 15:45:38 -0700185 sender->id(), sender->internal()->stream_ids(), 1);
zhihuang1c378ed2017-08-17 14:10:50 -0700186 }
187 }
zhihuanga77e6bb2017-08-14 18:17:48 -0700188 }
zhihuang1c378ed2017-08-17 14:10:50 -0700189}
olka3c747662017-08-17 06:50:32 -0700190
zhihuang1c378ed2017-08-17 14:10:50 -0700191// Add options to |session_options| from |rtp_data_channels|.
192void AddRtpDataChannelOptions(
193 const std::map<std::string, rtc::scoped_refptr<DataChannel>>&
194 rtp_data_channels,
195 cricket::MediaDescriptionOptions* data_media_description_options) {
196 if (!data_media_description_options) {
197 return;
198 }
deadbeefab9b2d12015-10-14 11:33:11 -0700199 // Check for data channels.
200 for (const auto& kv : rtp_data_channels) {
201 const DataChannel* channel = kv.second;
202 if (channel->state() == DataChannel::kConnecting ||
203 channel->state() == DataChannel::kOpen) {
zhihuang1c378ed2017-08-17 14:10:50 -0700204 // Legacy RTP data channels are signaled with the track/stream ID set to
205 // the data channel's label.
206 data_media_description_options->AddRtpDataChannel(channel->label(),
207 channel->label());
deadbeefab9b2d12015-10-14 11:33:11 -0700208 }
209 }
210}
211
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700212uint32_t ConvertIceTransportTypeToCandidateFilter(
213 PeerConnectionInterface::IceTransportsType type) {
214 switch (type) {
215 case PeerConnectionInterface::kNone:
216 return cricket::CF_NONE;
217 case PeerConnectionInterface::kRelay:
218 return cricket::CF_RELAY;
219 case PeerConnectionInterface::kNoHost:
220 return (cricket::CF_ALL & ~cricket::CF_HOST);
221 case PeerConnectionInterface::kAll:
222 return cricket::CF_ALL;
223 default:
nissec80e7412017-01-11 05:56:46 -0800224 RTC_NOTREACHED();
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700225 }
226 return cricket::CF_NONE;
227}
228
deadbeef293e9262017-01-11 12:28:30 -0800229// Helper to set an error and return from a method.
230bool SafeSetError(webrtc::RTCErrorType type, webrtc::RTCError* error) {
231 if (error) {
232 error->set_type(type);
233 }
234 return type == webrtc::RTCErrorType::NONE;
235}
236
Steve Anton038834f2017-07-14 15:59:59 -0700237bool SafeSetError(webrtc::RTCError error, webrtc::RTCError* error_out) {
238 if (error_out) {
239 *error_out = std::move(error);
240 }
241 return error.ok();
242}
243
Steve Antonba818672017-11-06 10:21:57 -0800244std::string GetSignalingStateString(
245 PeerConnectionInterface::SignalingState state) {
246 switch (state) {
247 case PeerConnectionInterface::kStable:
248 return "kStable";
249 case PeerConnectionInterface::kHaveLocalOffer:
250 return "kHaveLocalOffer";
251 case PeerConnectionInterface::kHaveLocalPrAnswer:
252 return "kHavePrAnswer";
253 case PeerConnectionInterface::kHaveRemoteOffer:
254 return "kHaveRemoteOffer";
255 case PeerConnectionInterface::kHaveRemotePrAnswer:
256 return "kHaveRemotePrAnswer";
257 case PeerConnectionInterface::kClosed:
258 return "kClosed";
259 }
260 RTC_NOTREACHED();
261 return "";
262}
deadbeef0a6c4ca2015-10-06 11:38:28 -0700263
Steve Anton75737c02017-11-06 10:37:17 -0800264IceCandidatePairType GetIceCandidatePairCounter(
265 const cricket::Candidate& local,
266 const cricket::Candidate& remote) {
267 const auto& l = local.type();
268 const auto& r = remote.type();
269 const auto& host = LOCAL_PORT_TYPE;
270 const auto& srflx = STUN_PORT_TYPE;
271 const auto& relay = RELAY_PORT_TYPE;
272 const auto& prflx = PRFLX_PORT_TYPE;
273 if (l == host && r == host) {
274 bool local_private = IPIsPrivate(local.address().ipaddr());
275 bool remote_private = IPIsPrivate(remote.address().ipaddr());
276 if (local_private) {
277 if (remote_private) {
278 return kIceCandidatePairHostPrivateHostPrivate;
279 } else {
280 return kIceCandidatePairHostPrivateHostPublic;
281 }
282 } else {
283 if (remote_private) {
284 return kIceCandidatePairHostPublicHostPrivate;
285 } else {
286 return kIceCandidatePairHostPublicHostPublic;
287 }
288 }
289 }
290 if (l == host && r == srflx)
291 return kIceCandidatePairHostSrflx;
292 if (l == host && r == relay)
293 return kIceCandidatePairHostRelay;
294 if (l == host && r == prflx)
295 return kIceCandidatePairHostPrflx;
296 if (l == srflx && r == host)
297 return kIceCandidatePairSrflxHost;
298 if (l == srflx && r == srflx)
299 return kIceCandidatePairSrflxSrflx;
300 if (l == srflx && r == relay)
301 return kIceCandidatePairSrflxRelay;
302 if (l == srflx && r == prflx)
303 return kIceCandidatePairSrflxPrflx;
304 if (l == relay && r == host)
305 return kIceCandidatePairRelayHost;
306 if (l == relay && r == srflx)
307 return kIceCandidatePairRelaySrflx;
308 if (l == relay && r == relay)
309 return kIceCandidatePairRelayRelay;
310 if (l == relay && r == prflx)
311 return kIceCandidatePairRelayPrflx;
312 if (l == prflx && r == host)
313 return kIceCandidatePairPrflxHost;
314 if (l == prflx && r == srflx)
315 return kIceCandidatePairPrflxSrflx;
316 if (l == prflx && r == relay)
317 return kIceCandidatePairPrflxRelay;
318 return kIceCandidatePairMax;
319}
320
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800321// Logic to decide if an m= section can be recycled. This means that the new
322// m= section is not rejected, but the old local or remote m= section is
323// rejected. |old_content_one| and |old_content_two| refer to the m= section
324// of the old remote and old local descriptions in no particular order.
325// We need to check both the old local and remote because either
326// could be the most current from the latest negotation.
327bool IsMediaSectionBeingRecycled(SdpType type,
328 const ContentInfo& content,
329 const ContentInfo* old_content_one,
330 const ContentInfo* old_content_two) {
331 return type == SdpType::kOffer && !content.rejected &&
332 ((old_content_one && old_content_one->rejected) ||
333 (old_content_two && old_content_two->rejected));
334}
335
Steve Anton75737c02017-11-06 10:37:17 -0800336// Verify that the order of media sections in |new_desc| matches
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800337// |current_desc|. The number of m= sections in |new_desc| should be no
338// less than |current_desc|. In the case of checking an answer's
339// |new_desc|, the |current_desc| is the last offer that was set as the
340// local or remote. In the case of checking an offer's |new_desc| we
341// check against the local and remote descriptions stored from the last
342// negotiation, because either of these could be the most up to date for
343// possible rejected m sections. These are the |current_desc| and
344// |secondary_current_desc|.
345bool MediaSectionsInSameOrder(const SessionDescription& current_desc,
346 const SessionDescription* secondary_current_desc,
347 const SessionDescription& new_desc,
348 const SdpType type) {
349 if (current_desc.contents().size() > new_desc.contents().size()) {
Steve Anton75737c02017-11-06 10:37:17 -0800350 return false;
351 }
352
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800353 for (size_t i = 0; i < current_desc.contents().size(); ++i) {
354 const cricket::ContentInfo* secondary_content_info = nullptr;
355 if (secondary_current_desc &&
356 i < secondary_current_desc->contents().size()) {
357 secondary_content_info = &secondary_current_desc->contents()[i];
358 }
359 if (IsMediaSectionBeingRecycled(type, new_desc.contents()[i],
360 &current_desc.contents()[i],
361 secondary_content_info)) {
362 // For new offer descriptions, if the media section can be recycled, it's
363 // valid for the MID and media type to change.
Steve Antondcc3c022017-12-22 16:02:54 -0800364 continue;
365 }
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800366 if (new_desc.contents()[i].name != current_desc.contents()[i].name) {
Steve Anton75737c02017-11-06 10:37:17 -0800367 return false;
368 }
369 const MediaContentDescription* new_desc_mdesc =
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800370 new_desc.contents()[i].media_description();
371 const MediaContentDescription* current_desc_mdesc =
372 current_desc.contents()[i].media_description();
373 if (new_desc_mdesc->type() != current_desc_mdesc->type()) {
Steve Anton75737c02017-11-06 10:37:17 -0800374 return false;
375 }
376 }
377 return true;
378}
379
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800380bool MediaSectionsHaveSameCount(const SessionDescription& desc1,
381 const SessionDescription& desc2) {
382 return desc1.contents().size() == desc2.contents().size();
Steve Anton75737c02017-11-06 10:37:17 -0800383}
384
385// Checks that each non-rejected content has SDES crypto keys or a DTLS
386// fingerprint, unless it's in a BUNDLE group, in which case only the
387// BUNDLE-tag section (first media section/description in the BUNDLE group)
388// needs a ufrag and pwd. Mismatches, such as replying with a DTLS fingerprint
389// to SDES keys, will be caught in JsepTransport negotiation, and backstopped
390// by Channel's |srtp_required| check.
Harald Alvestrand194939b2018-01-24 16:04:13 +0100391RTCError VerifyCrypto(const SessionDescription* desc,
392 bool dtls_enabled,
393 rtc::scoped_refptr<webrtc::UMAObserver> uma_observer) {
Steve Anton75737c02017-11-06 10:37:17 -0800394 const cricket::ContentGroup* bundle =
395 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton8a006912017-12-04 15:25:56 -0800396 for (const cricket::ContentInfo& content_info : desc->contents()) {
397 if (content_info.rejected) {
Steve Anton75737c02017-11-06 10:37:17 -0800398 continue;
399 }
Steve Anton8a006912017-12-04 15:25:56 -0800400 const std::string& mid = content_info.name;
401 if (bundle && bundle->HasContentName(mid) &&
402 mid != *(bundle->FirstContentName())) {
Steve Anton75737c02017-11-06 10:37:17 -0800403 // This isn't the first media section in the BUNDLE group, so it's not
404 // required to have crypto attributes, since only the crypto attributes
405 // from the first section actually get used.
406 continue;
407 }
408
409 // If the content isn't rejected or bundled into another m= section, crypto
410 // must be present.
Steve Antonb1c1de12017-12-21 15:14:30 -0800411 const MediaContentDescription* media = content_info.media_description();
Steve Anton8a006912017-12-04 15:25:56 -0800412 const TransportInfo* tinfo = desc->GetTransportInfoByName(mid);
Steve Anton75737c02017-11-06 10:37:17 -0800413 if (!media || !tinfo) {
414 // Something is not right.
Steve Anton8a006912017-12-04 15:25:56 -0800415 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidSdp);
Steve Anton75737c02017-11-06 10:37:17 -0800416 }
417 if (dtls_enabled) {
418 if (!tinfo->description.identity_fingerprint) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100419 RTC_LOG(LS_WARNING)
420 << "Session description must have DTLS fingerprint if "
421 "DTLS enabled.";
Steve Anton8a006912017-12-04 15:25:56 -0800422 return RTCError(RTCErrorType::INVALID_PARAMETER,
423 kSdpWithoutDtlsFingerprint);
Steve Anton75737c02017-11-06 10:37:17 -0800424 }
Harald Alvestrand194939b2018-01-24 16:04:13 +0100425 if (uma_observer) {
426 uma_observer->IncrementEnumCounter(webrtc::kEnumCounterKeyProtocol,
427 webrtc::kEnumCounterKeyProtocolDtls,
428 webrtc::kEnumCounterKeyProtocolMax);
429 }
Steve Anton75737c02017-11-06 10:37:17 -0800430 } else {
431 if (media->cryptos().empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100432 RTC_LOG(LS_WARNING)
Steve Anton75737c02017-11-06 10:37:17 -0800433 << "Session description must have SDES when DTLS disabled.";
Steve Anton8a006912017-12-04 15:25:56 -0800434 return RTCError(RTCErrorType::INVALID_PARAMETER, kSdpWithoutSdesCrypto);
Steve Anton75737c02017-11-06 10:37:17 -0800435 }
Harald Alvestrand194939b2018-01-24 16:04:13 +0100436 if (uma_observer) {
437 uma_observer->IncrementEnumCounter(webrtc::kEnumCounterKeyProtocol,
438 webrtc::kEnumCounterKeyProtocolSdes,
439 webrtc::kEnumCounterKeyProtocolMax);
440 }
Steve Anton75737c02017-11-06 10:37:17 -0800441 }
442 }
Steve Anton8a006912017-12-04 15:25:56 -0800443 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -0800444}
445
446// Checks that each non-rejected content has ice-ufrag and ice-pwd set, unless
447// it's in a BUNDLE group, in which case only the BUNDLE-tag section (first
448// media section/description in the BUNDLE group) needs a ufrag and pwd.
449bool VerifyIceUfragPwdPresent(const SessionDescription* desc) {
450 const cricket::ContentGroup* bundle =
451 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton8a006912017-12-04 15:25:56 -0800452 for (const cricket::ContentInfo& content_info : desc->contents()) {
453 if (content_info.rejected) {
Steve Anton75737c02017-11-06 10:37:17 -0800454 continue;
455 }
Steve Anton8a006912017-12-04 15:25:56 -0800456 const std::string& mid = content_info.name;
457 if (bundle && bundle->HasContentName(mid) &&
458 mid != *(bundle->FirstContentName())) {
Steve Anton75737c02017-11-06 10:37:17 -0800459 // This isn't the first media section in the BUNDLE group, so it's not
460 // required to have ufrag/password, since only the ufrag/password from
461 // the first section actually get used.
462 continue;
463 }
464
465 // If the content isn't rejected or bundled into another m= section,
466 // ice-ufrag and ice-pwd must be present.
Steve Anton8a006912017-12-04 15:25:56 -0800467 const TransportInfo* tinfo = desc->GetTransportInfoByName(mid);
Steve Anton75737c02017-11-06 10:37:17 -0800468 if (!tinfo) {
469 // Something is not right.
Mirko Bonadei675513b2017-11-09 11:09:25 +0100470 RTC_LOG(LS_ERROR) << kInvalidSdp;
Steve Anton75737c02017-11-06 10:37:17 -0800471 return false;
472 }
473 if (tinfo->description.ice_ufrag.empty() ||
474 tinfo->description.ice_pwd.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100475 RTC_LOG(LS_ERROR) << "Session description must have ice ufrag and pwd.";
Steve Anton75737c02017-11-06 10:37:17 -0800476 return false;
477 }
478 }
479 return true;
480}
481
482bool GetTrackIdBySsrc(const SessionDescription* session_description,
483 uint32_t ssrc,
484 std::string* track_id) {
485 RTC_DCHECK(track_id != NULL);
486
Steve Antonb1c1de12017-12-21 15:14:30 -0800487 const cricket::AudioContentDescription* audio_desc =
488 cricket::GetFirstAudioContentDescription(session_description);
489 if (audio_desc) {
490 const auto* found = cricket::GetStreamBySsrc(audio_desc->streams(), ssrc);
Steve Anton75737c02017-11-06 10:37:17 -0800491 if (found) {
492 *track_id = found->id;
493 return true;
494 }
495 }
496
Steve Antonb1c1de12017-12-21 15:14:30 -0800497 const cricket::VideoContentDescription* video_desc =
498 cricket::GetFirstVideoContentDescription(session_description);
499 if (video_desc) {
500 const auto* found = cricket::GetStreamBySsrc(video_desc->streams(), ssrc);
Steve Anton75737c02017-11-06 10:37:17 -0800501 if (found) {
502 *track_id = found->id;
503 return true;
504 }
505 }
506 return false;
507}
508
509// Get the SCTP port out of a SessionDescription.
510// Return -1 if not found.
511int GetSctpPort(const SessionDescription* session_description) {
Steve Antonb1c1de12017-12-21 15:14:30 -0800512 const cricket::DataContentDescription* data_desc =
513 GetFirstDataContentDescription(session_description);
514 RTC_DCHECK(data_desc);
515 if (!data_desc) {
Steve Anton75737c02017-11-06 10:37:17 -0800516 return -1;
517 }
Steve Anton75737c02017-11-06 10:37:17 -0800518 std::string value;
519 cricket::DataCodec match_pattern(cricket::kGoogleSctpDataCodecPlType,
520 cricket::kGoogleSctpDataCodecName);
Steve Antonb1c1de12017-12-21 15:14:30 -0800521 for (const cricket::DataCodec& codec : data_desc->codecs()) {
Steve Anton75737c02017-11-06 10:37:17 -0800522 if (!codec.Matches(match_pattern)) {
523 continue;
524 }
525 if (codec.GetParam(cricket::kCodecParamPort, &value)) {
526 return rtc::FromString<int>(value);
527 }
528 }
529 return -1;
530}
531
Steve Anton75737c02017-11-06 10:37:17 -0800532// Returns true if |new_desc| requests an ICE restart (i.e., new ufrag/pwd).
533bool CheckForRemoteIceRestart(const SessionDescriptionInterface* old_desc,
534 const SessionDescriptionInterface* new_desc,
535 const std::string& content_name) {
536 if (!old_desc) {
537 return false;
538 }
539 const SessionDescription* new_sd = new_desc->description();
540 const SessionDescription* old_sd = old_desc->description();
541 const ContentInfo* cinfo = new_sd->GetContentByName(content_name);
542 if (!cinfo || cinfo->rejected) {
543 return false;
544 }
545 // If the content isn't rejected, check if ufrag and password has changed.
546 const cricket::TransportDescription* new_transport_desc =
547 new_sd->GetTransportDescriptionByName(content_name);
548 const cricket::TransportDescription* old_transport_desc =
549 old_sd->GetTransportDescriptionByName(content_name);
550 if (!new_transport_desc || !old_transport_desc) {
551 // No transport description exists. This is not an ICE restart.
552 return false;
553 }
554 if (cricket::IceCredentialsChanged(
555 old_transport_desc->ice_ufrag, old_transport_desc->ice_pwd,
556 new_transport_desc->ice_ufrag, new_transport_desc->ice_pwd)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100557 RTC_LOG(LS_INFO) << "Remote peer requests ICE restart for " << content_name
558 << ".";
Steve Anton75737c02017-11-06 10:37:17 -0800559 return true;
560 }
561 return false;
562}
563
Steve Anton80dd7b52018-02-16 17:08:42 -0800564// Generates a string error message for SetLocalDescription/SetRemoteDescription
565// from an RTCError.
566std::string GetSetDescriptionErrorMessage(cricket::ContentSource source,
567 SdpType type,
568 const RTCError& error) {
569 std::ostringstream oss;
570 oss << "Failed to set " << (source == cricket::CS_LOCAL ? "local" : "remote")
571 << " " << SdpTypeToString(type) << " sdp: " << error.message();
572 return oss.str();
573}
574
Steve Anton75737c02017-11-06 10:37:17 -0800575} // namespace
576
Henrik Boström31638672017-11-23 17:48:32 +0100577// Upon completion, posts a task to execute the callback of the
578// SetSessionDescriptionObserver asynchronously on the same thread. At this
579// point, the state of the peer connection might no longer reflect the effects
580// of the SetRemoteDescription operation, as the peer connection could have been
581// modified during the post.
582// TODO(hbos): Remove this class once we remove the version of
583// PeerConnectionInterface::SetRemoteDescription() that takes a
584// SetSessionDescriptionObserver as an argument.
585class PeerConnection::SetRemoteDescriptionObserverAdapter
586 : public rtc::RefCountedObject<SetRemoteDescriptionObserverInterface> {
587 public:
588 SetRemoteDescriptionObserverAdapter(
589 rtc::scoped_refptr<PeerConnection> pc,
590 rtc::scoped_refptr<SetSessionDescriptionObserver> wrapper)
591 : pc_(std::move(pc)), wrapper_(std::move(wrapper)) {}
592
593 // SetRemoteDescriptionObserverInterface implementation.
594 void OnSetRemoteDescriptionComplete(RTCError error) override {
595 if (error.ok())
596 pc_->PostSetSessionDescriptionSuccess(wrapper_);
597 else
598 pc_->PostSetSessionDescriptionFailure(wrapper_, error.message());
599 }
600
601 private:
602 rtc::scoped_refptr<PeerConnection> pc_;
603 rtc::scoped_refptr<SetSessionDescriptionObserver> wrapper_;
604};
605
deadbeef293e9262017-01-11 12:28:30 -0800606bool PeerConnectionInterface::RTCConfiguration::operator==(
607 const PeerConnectionInterface::RTCConfiguration& o) const {
608 // This static_assert prevents us from accidentally breaking operator==.
Steve Anton300bf8e2017-07-14 10:13:10 -0700609 // Note: Order matters! Fields must be ordered the same as RTCConfiguration.
deadbeef293e9262017-01-11 12:28:30 -0800610 struct stuff_being_tested_for_equality {
Magnus Jedvert3beb2072017-07-14 14:23:56 +0000611 IceServers servers;
Steve Anton300bf8e2017-07-14 10:13:10 -0700612 IceTransportsType type;
deadbeef293e9262017-01-11 12:28:30 -0800613 BundlePolicy bundle_policy;
614 RtcpMuxPolicy rtcp_mux_policy;
Steve Anton300bf8e2017-07-14 10:13:10 -0700615 std::vector<rtc::scoped_refptr<rtc::RTCCertificate>> certificates;
616 int ice_candidate_pool_size;
617 bool disable_ipv6;
618 bool disable_ipv6_on_wifi;
deadbeefd21eab32017-07-26 16:50:11 -0700619 int max_ipv6_networks;
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +0100620 bool disable_link_local_networks;
Steve Anton300bf8e2017-07-14 10:13:10 -0700621 bool enable_rtp_data_channel;
622 rtc::Optional<int> screencast_min_bitrate;
623 rtc::Optional<bool> combined_audio_video_bwe;
624 rtc::Optional<bool> enable_dtls_srtp;
deadbeef293e9262017-01-11 12:28:30 -0800625 TcpCandidatePolicy tcp_candidate_policy;
626 CandidateNetworkPolicy candidate_network_policy;
627 int audio_jitter_buffer_max_packets;
628 bool audio_jitter_buffer_fast_accelerate;
629 int ice_connection_receiving_timeout;
630 int ice_backup_candidate_pair_ping_interval;
631 ContinualGatheringPolicy continual_gathering_policy;
deadbeef293e9262017-01-11 12:28:30 -0800632 bool prioritize_most_likely_ice_candidate_pairs;
633 struct cricket::MediaConfig media_config;
deadbeef293e9262017-01-11 12:28:30 -0800634 bool prune_turn_ports;
635 bool presume_writable_when_fully_relayed;
636 bool enable_ice_renomination;
637 bool redetermine_role_on_ice_restart;
skvlad51072462017-02-02 11:50:14 -0800638 rtc::Optional<int> ice_check_min_interval;
Qingsi Wangdb53f8e2018-02-20 14:45:49 -0800639 rtc::Optional<int> stun_candidate_keepalive_interval;
Steve Anton300bf8e2017-07-14 10:13:10 -0700640 rtc::Optional<rtc::IntervalRange> ice_regather_interval_range;
Jonas Orelandbdcee282017-10-10 14:01:40 +0200641 webrtc::TurnCustomizer* turn_customizer;
Steve Anton79e79602017-11-20 10:25:56 -0800642 SdpSemantics sdp_semantics;
Qingsi Wang9a5c6f82018-02-01 10:38:40 -0800643 rtc::Optional<rtc::AdapterType> network_preference;
deadbeef293e9262017-01-11 12:28:30 -0800644 };
645 static_assert(sizeof(stuff_being_tested_for_equality) == sizeof(*this),
646 "Did you add something to RTCConfiguration and forget to "
647 "update operator==?");
648 return type == o.type && servers == o.servers &&
649 bundle_policy == o.bundle_policy &&
650 rtcp_mux_policy == o.rtcp_mux_policy &&
651 tcp_candidate_policy == o.tcp_candidate_policy &&
652 candidate_network_policy == o.candidate_network_policy &&
653 audio_jitter_buffer_max_packets == o.audio_jitter_buffer_max_packets &&
654 audio_jitter_buffer_fast_accelerate ==
655 o.audio_jitter_buffer_fast_accelerate &&
656 ice_connection_receiving_timeout ==
657 o.ice_connection_receiving_timeout &&
658 ice_backup_candidate_pair_ping_interval ==
659 o.ice_backup_candidate_pair_ping_interval &&
660 continual_gathering_policy == o.continual_gathering_policy &&
661 certificates == o.certificates &&
662 prioritize_most_likely_ice_candidate_pairs ==
663 o.prioritize_most_likely_ice_candidate_pairs &&
664 media_config == o.media_config && disable_ipv6 == o.disable_ipv6 &&
zhihuangb09b3f92017-03-07 14:40:51 -0800665 disable_ipv6_on_wifi == o.disable_ipv6_on_wifi &&
deadbeefd21eab32017-07-26 16:50:11 -0700666 max_ipv6_networks == o.max_ipv6_networks &&
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +0100667 disable_link_local_networks == o.disable_link_local_networks &&
deadbeef293e9262017-01-11 12:28:30 -0800668 enable_rtp_data_channel == o.enable_rtp_data_channel &&
deadbeef293e9262017-01-11 12:28:30 -0800669 screencast_min_bitrate == o.screencast_min_bitrate &&
670 combined_audio_video_bwe == o.combined_audio_video_bwe &&
671 enable_dtls_srtp == o.enable_dtls_srtp &&
672 ice_candidate_pool_size == o.ice_candidate_pool_size &&
673 prune_turn_ports == o.prune_turn_ports &&
674 presume_writable_when_fully_relayed ==
675 o.presume_writable_when_fully_relayed &&
676 enable_ice_renomination == o.enable_ice_renomination &&
skvlad51072462017-02-02 11:50:14 -0800677 redetermine_role_on_ice_restart == o.redetermine_role_on_ice_restart &&
Steve Anton300bf8e2017-07-14 10:13:10 -0700678 ice_check_min_interval == o.ice_check_min_interval &&
Qingsi Wangdb53f8e2018-02-20 14:45:49 -0800679 stun_candidate_keepalive_interval ==
680 o.stun_candidate_keepalive_interval &&
Jonas Orelandbdcee282017-10-10 14:01:40 +0200681 ice_regather_interval_range == o.ice_regather_interval_range &&
Steve Anton79e79602017-11-20 10:25:56 -0800682 turn_customizer == o.turn_customizer &&
Qingsi Wang9a5c6f82018-02-01 10:38:40 -0800683 sdp_semantics == o.sdp_semantics &&
684 network_preference == o.network_preference;
deadbeef293e9262017-01-11 12:28:30 -0800685}
686
687bool PeerConnectionInterface::RTCConfiguration::operator!=(
688 const PeerConnectionInterface::RTCConfiguration& o) const {
689 return !(*this == o);
deadbeef3edec7c2016-12-10 11:44:26 -0800690}
691
zhihuang8f65cdf2016-05-06 18:40:30 -0700692// Generate a RTCP CNAME when a PeerConnection is created.
693std::string GenerateRtcpCname() {
694 std::string cname;
695 if (!rtc::CreateRandomString(kRtcpCnameLength, &cname)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100696 RTC_LOG(LS_ERROR) << "Failed to generate CNAME.";
nisseeb4ca4e2017-01-12 02:24:27 -0800697 RTC_NOTREACHED();
zhihuang8f65cdf2016-05-06 18:40:30 -0700698 }
699 return cname;
700}
701
zhihuang1c378ed2017-08-17 14:10:50 -0700702bool ValidateOfferAnswerOptions(
703 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options) {
704 return IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_audio) &&
705 IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_video);
olka3c747662017-08-17 06:50:32 -0700706}
707
zhihuang1c378ed2017-08-17 14:10:50 -0700708// From |rtc_options|, fill parts of |session_options| shared by all generated
709// m= sections (in other words, nothing that involves a map/array).
710void ExtractSharedMediaSessionOptions(
711 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options,
712 cricket::MediaSessionOptions* session_options) {
713 session_options->vad_enabled = rtc_options.voice_activity_detection;
714 session_options->bundle_enabled = rtc_options.use_rtp_mux;
715}
zhihuanga77e6bb2017-08-14 18:17:48 -0700716
zhihuang1c378ed2017-08-17 14:10:50 -0700717bool ConvertConstraintsToOfferAnswerOptions(
718 const MediaConstraintsInterface* constraints,
719 PeerConnectionInterface::RTCOfferAnswerOptions* offer_answer_options) {
olka3c747662017-08-17 06:50:32 -0700720 if (!constraints) {
721 return true;
722 }
zhihuang1c378ed2017-08-17 14:10:50 -0700723
724 bool value = false;
725 size_t mandatory_constraints_satisfied = 0;
726
727 if (FindConstraint(constraints,
728 MediaConstraintsInterface::kOfferToReceiveAudio, &value,
729 &mandatory_constraints_satisfied)) {
730 offer_answer_options->offer_to_receive_audio =
731 value ? PeerConnectionInterface::RTCOfferAnswerOptions::
732 kOfferToReceiveMediaTrue
733 : 0;
734 }
735
736 if (FindConstraint(constraints,
737 MediaConstraintsInterface::kOfferToReceiveVideo, &value,
738 &mandatory_constraints_satisfied)) {
739 offer_answer_options->offer_to_receive_video =
740 value ? PeerConnectionInterface::RTCOfferAnswerOptions::
741 kOfferToReceiveMediaTrue
742 : 0;
743 }
744 if (FindConstraint(constraints,
745 MediaConstraintsInterface::kVoiceActivityDetection, &value,
746 &mandatory_constraints_satisfied)) {
747 offer_answer_options->voice_activity_detection = value;
748 }
749 if (FindConstraint(constraints, MediaConstraintsInterface::kUseRtpMux, &value,
750 &mandatory_constraints_satisfied)) {
751 offer_answer_options->use_rtp_mux = value;
752 }
753 if (FindConstraint(constraints, MediaConstraintsInterface::kIceRestart,
754 &value, &mandatory_constraints_satisfied)) {
755 offer_answer_options->ice_restart = value;
756 }
757
deadbeefab9b2d12015-10-14 11:33:11 -0700758 return mandatory_constraints_satisfied == constraints->GetMandatory().size();
759}
760
zhihuang38ede132017-06-15 12:52:32 -0700761PeerConnection::PeerConnection(PeerConnectionFactory* factory,
762 std::unique_ptr<RtcEventLog> event_log,
763 std::unique_ptr<Call> call)
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000764 : factory_(factory),
zhihuang38ede132017-06-15 12:52:32 -0700765 event_log_(std::move(event_log)),
zhihuang8f65cdf2016-05-06 18:40:30 -0700766 rtcp_cname_(GenerateRtcpCname()),
deadbeefab9b2d12015-10-14 11:33:11 -0700767 local_streams_(StreamCollection::Create()),
zhihuang38ede132017-06-15 12:52:32 -0700768 remote_streams_(StreamCollection::Create()),
769 call_(std::move(call)) {}
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000770
771PeerConnection::~PeerConnection() {
Peter Boström1a9d6152015-12-08 22:15:17 +0100772 TRACE_EVENT0("webrtc", "PeerConnection::~PeerConnection");
Steve Anton4171afb2017-11-20 10:20:22 -0800773 RTC_DCHECK_RUN_ON(signaling_thread());
774
Steve Anton8af21862017-12-15 11:20:13 -0800775 // Need to stop transceivers before destroying the stats collector because
776 // AudioRtpSender has a reference to the StatsCollector it will update when
777 // stopping.
778 for (auto transceiver : transceivers_) {
779 transceiver->Stop();
780 }
Steve Anton4171afb2017-11-20 10:20:22 -0800781
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700782 stats_.reset(nullptr);
hbosb78306a2016-12-19 05:06:57 -0800783 if (stats_collector_) {
784 stats_collector_->WaitForPendingRequest();
785 stats_collector_ = nullptr;
786 }
Steve Anton75737c02017-11-06 10:37:17 -0800787
Steve Anton8af21862017-12-15 11:20:13 -0800788 // Don't destroy BaseChannels until after stats has been cleaned up so that
789 // the last stats request can still read from the channels.
790 DestroyAllChannels();
791
Mirko Bonadei675513b2017-11-09 11:09:25 +0100792 RTC_LOG(LS_INFO) << "Session: " << session_id() << " is destroyed.";
Steve Anton75737c02017-11-06 10:37:17 -0800793
794 webrtc_session_desc_factory_.reset();
795 sctp_invoker_.reset();
796 sctp_factory_.reset();
797 transport_controller_.reset();
798
deadbeef91dd5672016-05-18 16:55:30 -0700799 // port_allocator_ lives on the network thread and should be destroyed there.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700800 network_thread()->Invoke<void>(RTC_FROM_HERE,
nisseeaabdf62017-05-05 02:23:02 -0700801 [this] { port_allocator_.reset(); });
eladalon248fd4f2017-09-06 05:18:15 -0700802 // call_ and event_log_ must be destroyed on the worker thread.
Steve Anton978b8762017-09-29 12:15:02 -0700803 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
eladalon248fd4f2017-09-06 05:18:15 -0700804 call_.reset();
Qingsi Wang93a84392018-01-30 17:13:09 -0800805 // The event log must outlive call (and any other object that uses it).
eladalon248fd4f2017-09-06 05:18:15 -0700806 event_log_.reset();
807 });
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000808}
809
Steve Anton8af21862017-12-15 11:20:13 -0800810void PeerConnection::DestroyAllChannels() {
Steve Anton3fe1b152017-12-12 10:20:08 -0800811 // Destroy video channels first since they may have a pointer to a voice
812 // channel.
813 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -0800814 if (transceiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton3fe1b152017-12-12 10:20:08 -0800815 DestroyTransceiverChannel(transceiver);
816 }
817 }
818 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -0800819 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton3fe1b152017-12-12 10:20:08 -0800820 DestroyTransceiverChannel(transceiver);
821 }
822 }
823 DestroyDataChannel();
824}
825
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000826bool PeerConnection::Initialize(
buildbot@webrtc.org41451d42014-05-03 05:39:45 +0000827 const PeerConnectionInterface::RTCConfiguration& configuration,
kwibergd1fe2812016-04-27 06:47:29 -0700828 std::unique_ptr<cricket::PortAllocator> allocator,
Henrik Boströmd03c23b2016-06-01 11:44:18 +0200829 std::unique_ptr<rtc::RTCCertificateGeneratorInterface> cert_generator,
deadbeef653b8e02015-11-11 12:55:10 -0800830 PeerConnectionObserver* observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100831 TRACE_EVENT0("webrtc", "PeerConnection::Initialize");
Steve Anton038834f2017-07-14 15:59:59 -0700832
833 RTCError config_error = ValidateConfiguration(configuration);
834 if (!config_error.ok()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100835 RTC_LOG(LS_ERROR) << "Invalid configuration: " << config_error.message();
Steve Anton038834f2017-07-14 15:59:59 -0700836 return false;
837 }
838
deadbeef293e9262017-01-11 12:28:30 -0800839 if (!allocator) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100840 RTC_LOG(LS_ERROR)
841 << "PeerConnection initialized without a PortAllocator? "
Jonas Olsson45cc8902018-02-13 10:37:07 +0100842 "This shouldn't happen if using PeerConnectionFactory.";
deadbeef293e9262017-01-11 12:28:30 -0800843 return false;
844 }
Jonas Orelandbdcee282017-10-10 14:01:40 +0200845
deadbeef653b8e02015-11-11 12:55:10 -0800846 if (!observer) {
deadbeef293e9262017-01-11 12:28:30 -0800847 // TODO(deadbeef): Why do we do this?
Mirko Bonadei675513b2017-11-09 11:09:25 +0100848 RTC_LOG(LS_ERROR) << "PeerConnection initialized without a "
Jonas Olsson45cc8902018-02-13 10:37:07 +0100849 "PeerConnectionObserver";
deadbeef653b8e02015-11-11 12:55:10 -0800850 return false;
851 }
pthatcher@webrtc.org877ac762015-02-04 22:03:09 +0000852 observer_ = observer;
kwiberg0eb15ed2015-12-17 03:04:15 -0800853 port_allocator_ = std::move(allocator);
deadbeef653b8e02015-11-11 12:55:10 -0800854
deadbeef91dd5672016-05-18 16:55:30 -0700855 // The port allocator lives on the network thread and should be initialized
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700856 // there.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700857 if (!network_thread()->Invoke<bool>(
858 RTC_FROM_HERE, rtc::Bind(&PeerConnection::InitializePortAllocator_n,
859 this, configuration))) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000860 return false;
861 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000862
Steve Anton75737c02017-11-06 10:37:17 -0800863 // RFC 3264: The numeric value of the session id and version in the
864 // o line MUST be representable with a "64 bit signed integer".
865 // Due to this constraint session id |session_id_| is max limited to
866 // LLONG_MAX.
867 session_id_ = rtc::ToString(rtc::CreateRandomId64() & LLONG_MAX);
868 transport_controller_.reset(factory_->CreateTransportController(
Qingsi Wang93a84392018-01-30 17:13:09 -0800869 port_allocator_.get(), configuration.redetermine_role_on_ice_restart,
870 event_log_.get()));
Steve Anton75737c02017-11-06 10:37:17 -0800871 transport_controller_->SetIceRole(cricket::ICEROLE_CONTROLLED);
872 transport_controller_->SignalConnectionState.connect(
873 this, &PeerConnection::OnTransportControllerConnectionState);
874 transport_controller_->SignalGatheringState.connect(
875 this, &PeerConnection::OnTransportControllerGatheringState);
876 transport_controller_->SignalCandidatesGathered.connect(
877 this, &PeerConnection::OnTransportControllerCandidatesGathered);
878 transport_controller_->SignalCandidatesRemoved.connect(
879 this, &PeerConnection::OnTransportControllerCandidatesRemoved);
880 transport_controller_->SignalDtlsHandshakeError.connect(
881 this, &PeerConnection::OnTransportControllerDtlsHandshakeError);
882
883 sctp_factory_ = factory_->CreateSctpTransportInternalFactory();
zhihuang29ff8442016-07-27 11:07:25 -0700884
deadbeefab9b2d12015-10-14 11:33:11 -0700885 stats_.reset(new StatsCollector(this));
hbos74e1a4f2016-09-15 23:33:01 -0700886 stats_collector_ = RTCStatsCollector::Create(this);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000887
Steve Antonba818672017-11-06 10:21:57 -0800888 configuration_ = configuration;
889
Steve Anton75737c02017-11-06 10:37:17 -0800890 const PeerConnectionFactoryInterface::Options& options = factory_->options();
891
892 transport_controller_->SetSslMaxProtocolVersion(options.ssl_max_version);
893
894 // Obtain a certificate from RTCConfiguration if any were provided (optional).
895 rtc::scoped_refptr<rtc::RTCCertificate> certificate;
896 if (!configuration.certificates.empty()) {
897 // TODO(hbos,torbjorng): Decide on certificate-selection strategy instead of
898 // just picking the first one. The decision should be made based on the DTLS
899 // handshake. The DTLS negotiations need to know about all certificates.
900 certificate = configuration.certificates[0];
901 }
902
Steve Antond25da372017-11-06 14:50:29 -0800903 transport_controller_->SetIceConfig(ParseIceConfig(configuration));
Steve Anton75737c02017-11-06 10:37:17 -0800904
905 if (options.disable_encryption) {
906 dtls_enabled_ = false;
907 } else {
908 // Enable DTLS by default if we have an identity store or a certificate.
909 dtls_enabled_ = (cert_generator || certificate);
910 // |configuration| can override the default |dtls_enabled_| value.
911 if (configuration.enable_dtls_srtp) {
912 dtls_enabled_ = *(configuration.enable_dtls_srtp);
913 }
914 }
915
916 // Enable creation of RTP data channels if the kEnableRtpDataChannels is set.
917 // It takes precendence over the disable_sctp_data_channels
918 // PeerConnectionFactoryInterface::Options.
919 if (configuration.enable_rtp_data_channel) {
920 data_channel_type_ = cricket::DCT_RTP;
921 } else {
922 // DTLS has to be enabled to use SCTP.
923 if (!options.disable_sctp_data_channels && dtls_enabled_) {
924 data_channel_type_ = cricket::DCT_SCTP;
925 }
926 }
927
928 video_options_.screencast_min_bitrate_kbps =
929 configuration.screencast_min_bitrate;
930 audio_options_.combined_audio_video_bwe =
931 configuration.combined_audio_video_bwe;
932
933 audio_options_.audio_jitter_buffer_max_packets =
Oskar Sundbom9b28a032017-11-16 10:53:30 +0100934 configuration.audio_jitter_buffer_max_packets;
Steve Anton75737c02017-11-06 10:37:17 -0800935
936 audio_options_.audio_jitter_buffer_fast_accelerate =
Oskar Sundbom9b28a032017-11-16 10:53:30 +0100937 configuration.audio_jitter_buffer_fast_accelerate;
Steve Anton75737c02017-11-06 10:37:17 -0800938
939 // Whether the certificate generator/certificate is null or not determines
940 // what PeerConnectionDescriptionFactory will do, so make sure that we give it
941 // the right instructions by clearing the variables if needed.
942 if (!dtls_enabled_) {
943 cert_generator.reset();
944 certificate = nullptr;
945 } else if (certificate) {
946 // Favor generated certificate over the certificate generator.
947 cert_generator.reset();
948 }
949
950 webrtc_session_desc_factory_.reset(new WebRtcSessionDescriptionFactory(
951 signaling_thread(), channel_manager(), this, session_id(),
952 std::move(cert_generator), certificate));
953 webrtc_session_desc_factory_->SignalCertificateReady.connect(
954 this, &PeerConnection::OnCertificateReady);
955
956 if (options.disable_encryption) {
957 webrtc_session_desc_factory_->SetSdesPolicy(cricket::SEC_DISABLED);
958 }
959
960 webrtc_session_desc_factory_->set_enable_encrypted_rtp_header_extensions(
961 options.crypto_options.enable_encrypted_rtp_header_extensions);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000962
Steve Anton4171afb2017-11-20 10:20:22 -0800963 // Add default audio/video transceivers for Plan B SDP.
964 if (!IsUnifiedPlan()) {
965 transceivers_.push_back(
966 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
967 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_AUDIO)));
968 transceivers_.push_back(
969 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
970 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_VIDEO)));
971 }
972
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000973 return true;
974}
975
Steve Anton038834f2017-07-14 15:59:59 -0700976RTCError PeerConnection::ValidateConfiguration(
977 const RTCConfiguration& config) const {
978 if (config.ice_regather_interval_range &&
979 config.continual_gathering_policy == GATHER_ONCE) {
980 return RTCError(RTCErrorType::INVALID_PARAMETER,
981 "ice_regather_interval_range specified but continual "
982 "gathering policy is GATHER_ONCE");
983 }
984 return RTCError::OK();
985}
986
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000987rtc::scoped_refptr<StreamCollectionInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000988PeerConnection::local_streams() {
Steve Antonfc853712018-03-01 13:48:58 -0800989 RTC_CHECK(!IsUnifiedPlan()) << "local_streams is not available with Unified "
990 "Plan SdpSemantics. Please use GetSenders "
991 "instead.";
deadbeefab9b2d12015-10-14 11:33:11 -0700992 return local_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000993}
994
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000995rtc::scoped_refptr<StreamCollectionInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000996PeerConnection::remote_streams() {
Steve Antonfc853712018-03-01 13:48:58 -0800997 RTC_CHECK(!IsUnifiedPlan()) << "remote_streams is not available with Unified "
998 "Plan SdpSemantics. Please use GetReceivers "
999 "instead.";
deadbeefab9b2d12015-10-14 11:33:11 -07001000 return remote_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001001}
1002
perkj@webrtc.orgc2dd5ee2014-11-04 11:31:29 +00001003bool PeerConnection::AddStream(MediaStreamInterface* local_stream) {
Steve Antonfc853712018-03-01 13:48:58 -08001004 RTC_CHECK(!IsUnifiedPlan()) << "AddStream is not available with Unified Plan "
1005 "SdpSemantics. Please use AddTrack instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001006 TRACE_EVENT0("webrtc", "PeerConnection::AddStream");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001007 if (IsClosed()) {
1008 return false;
1009 }
deadbeefab9b2d12015-10-14 11:33:11 -07001010 if (!CanAddLocalMediaStream(local_streams_, local_stream)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001011 return false;
1012 }
deadbeefab9b2d12015-10-14 11:33:11 -07001013
1014 local_streams_->AddStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -08001015 MediaStreamObserver* observer = new MediaStreamObserver(local_stream);
1016 observer->SignalAudioTrackAdded.connect(this,
1017 &PeerConnection::OnAudioTrackAdded);
1018 observer->SignalAudioTrackRemoved.connect(
1019 this, &PeerConnection::OnAudioTrackRemoved);
1020 observer->SignalVideoTrackAdded.connect(this,
1021 &PeerConnection::OnVideoTrackAdded);
1022 observer->SignalVideoTrackRemoved.connect(
1023 this, &PeerConnection::OnVideoTrackRemoved);
kwibergd1fe2812016-04-27 06:47:29 -07001024 stream_observers_.push_back(std::unique_ptr<MediaStreamObserver>(observer));
deadbeefab9b2d12015-10-14 11:33:11 -07001025
deadbeefab9b2d12015-10-14 11:33:11 -07001026 for (const auto& track : local_stream->GetAudioTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001027 AddAudioTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -07001028 }
1029 for (const auto& track : local_stream->GetVideoTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001030 AddVideoTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -07001031 }
1032
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001033 stats_->AddStream(local_stream);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001034 observer_->OnRenegotiationNeeded();
1035 return true;
1036}
1037
1038void PeerConnection::RemoveStream(MediaStreamInterface* local_stream) {
Steve Antonfc853712018-03-01 13:48:58 -08001039 RTC_CHECK(!IsUnifiedPlan()) << "RemoveStream is not available with Unified "
1040 "Plan SdpSemantics. Please use RemoveTrack "
1041 "instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001042 TRACE_EVENT0("webrtc", "PeerConnection::RemoveStream");
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001043 if (!IsClosed()) {
1044 for (const auto& track : local_stream->GetAudioTracks()) {
1045 RemoveAudioTrack(track.get(), local_stream);
1046 }
1047 for (const auto& track : local_stream->GetVideoTracks()) {
1048 RemoveVideoTrack(track.get(), local_stream);
1049 }
deadbeefab9b2d12015-10-14 11:33:11 -07001050 }
deadbeefab9b2d12015-10-14 11:33:11 -07001051 local_streams_->RemoveStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -08001052 stream_observers_.erase(
1053 std::remove_if(
1054 stream_observers_.begin(), stream_observers_.end(),
kwibergd1fe2812016-04-27 06:47:29 -07001055 [local_stream](const std::unique_ptr<MediaStreamObserver>& observer) {
deadbeefeb459812015-12-15 19:24:43 -08001056 return observer->stream()->label().compare(local_stream->label()) ==
1057 0;
1058 }),
1059 stream_observers_.end());
deadbeefab9b2d12015-10-14 11:33:11 -07001060
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001061 if (IsClosed()) {
1062 return;
1063 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001064 observer_->OnRenegotiationNeeded();
1065}
1066
deadbeefe1f9d832016-01-14 15:35:42 -08001067rtc::scoped_refptr<RtpSenderInterface> PeerConnection::AddTrack(
1068 MediaStreamTrackInterface* track,
1069 std::vector<MediaStreamInterface*> streams) {
1070 TRACE_EVENT0("webrtc", "PeerConnection::AddTrack");
Steve Antonf9381f02017-12-14 10:23:57 -08001071 std::vector<std::string> stream_labels;
1072 for (auto* stream : streams) {
1073 if (!stream) {
1074 RTC_LOG(LS_ERROR) << "Stream list has null element.";
1075 return nullptr;
1076 }
1077 stream_labels.push_back(stream->label());
1078 }
Steve Anton2d6c76a2018-01-05 17:10:52 -08001079 auto sender_or_error = AddTrack(track, stream_labels);
Steve Antonf9381f02017-12-14 10:23:57 -08001080 if (!sender_or_error.ok()) {
deadbeefe1f9d832016-01-14 15:35:42 -08001081 return nullptr;
1082 }
Steve Antonf9381f02017-12-14 10:23:57 -08001083 return sender_or_error.MoveValue();
1084}
1085
Steve Anton2d6c76a2018-01-05 17:10:52 -08001086RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::AddTrack(
Steve Antonf9381f02017-12-14 10:23:57 -08001087 rtc::scoped_refptr<MediaStreamTrackInterface> track,
1088 const std::vector<std::string>& stream_labels) {
Steve Anton2d6c76a2018-01-05 17:10:52 -08001089 TRACE_EVENT0("webrtc", "PeerConnection::AddTrack");
Steve Antonf9381f02017-12-14 10:23:57 -08001090 if (!track) {
1091 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "Track is null.");
1092 }
1093 if (!(track->kind() == MediaStreamTrackInterface::kAudioKind ||
1094 track->kind() == MediaStreamTrackInterface::kVideoKind)) {
1095 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1096 "Track has invalid kind: " + track->kind());
1097 }
1098 // TODO(bugs.webrtc.org/7932): Support adding a track to multiple streams.
1099 if (stream_labels.size() > 1u) {
1100 LOG_AND_RETURN_ERROR(
1101 RTCErrorType::UNSUPPORTED_OPERATION,
1102 "AddTrack with more than one stream is not currently supported.");
1103 }
1104 if (IsClosed()) {
1105 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
1106 "PeerConnection is closed.");
deadbeefe1f9d832016-01-14 15:35:42 -08001107 }
Steve Anton4171afb2017-11-20 10:20:22 -08001108 if (FindSenderForTrack(track)) {
Steve Antonf9381f02017-12-14 10:23:57 -08001109 LOG_AND_RETURN_ERROR(
1110 RTCErrorType::INVALID_PARAMETER,
1111 "Sender already exists for track " + track->id() + ".");
deadbeefe1f9d832016-01-14 15:35:42 -08001112 }
Steve Antonf9381f02017-12-14 10:23:57 -08001113 // TODO(bugs.webrtc.org/7933): MediaSession expects the sender to have exactly
1114 // one stream. AddTrackInternal will return an error if there is more than one
1115 // stream, but if the caller specifies none then we need to generate a random
1116 // stream label.
1117 std::vector<std::string> adjusted_stream_labels = stream_labels;
1118 if (stream_labels.empty()) {
1119 adjusted_stream_labels.push_back(rtc::CreateRandomUuid());
1120 }
1121 RTC_DCHECK_EQ(1, adjusted_stream_labels.size());
1122 auto sender_or_error =
1123 (IsUnifiedPlan() ? AddTrackUnifiedPlan(track, adjusted_stream_labels)
1124 : AddTrackPlanB(track, adjusted_stream_labels));
1125 if (sender_or_error.ok()) {
1126 observer_->OnRenegotiationNeeded();
Steve Anton43a723a2018-01-04 15:48:17 -08001127 stats_->AddTrack(track);
Steve Antonf9381f02017-12-14 10:23:57 -08001128 }
1129 return sender_or_error;
1130}
deadbeefe1f9d832016-01-14 15:35:42 -08001131
Steve Antonf9381f02017-12-14 10:23:57 -08001132RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>>
1133PeerConnection::AddTrackPlanB(
1134 rtc::scoped_refptr<MediaStreamTrackInterface> track,
1135 const std::vector<std::string>& stream_labels) {
Steve Anton02ee47c2018-01-10 16:26:06 -08001136 cricket::MediaType media_type =
1137 (track->kind() == MediaStreamTrackInterface::kAudioKind
1138 ? cricket::MEDIA_TYPE_AUDIO
1139 : cricket::MEDIA_TYPE_VIDEO);
1140 auto new_sender = CreateSender(media_type, track, stream_labels);
deadbeefe1f9d832016-01-14 15:35:42 -08001141 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
Steve Anton57858b32018-02-15 15:19:50 -08001142 new_sender->internal()->SetVoiceMediaChannel(voice_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08001143 GetAudioTransceiver()->internal()->AddSender(new_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001144 const RtpSenderInfo* sender_info =
1145 FindSenderInfo(local_audio_sender_infos_,
1146 new_sender->internal()->stream_id(), track->id());
1147 if (sender_info) {
1148 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -08001149 }
Steve Antonf9381f02017-12-14 10:23:57 -08001150 } else {
1151 RTC_DCHECK_EQ(MediaStreamTrackInterface::kVideoKind, track->kind());
Steve Anton57858b32018-02-15 15:19:50 -08001152 new_sender->internal()->SetVideoMediaChannel(video_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08001153 GetVideoTransceiver()->internal()->AddSender(new_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001154 const RtpSenderInfo* sender_info =
1155 FindSenderInfo(local_video_sender_infos_,
1156 new_sender->internal()->stream_id(), track->id());
1157 if (sender_info) {
1158 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -08001159 }
deadbeefe1f9d832016-01-14 15:35:42 -08001160 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001161 return rtc::scoped_refptr<RtpSenderInterface>(new_sender);
Steve Antonf9381f02017-12-14 10:23:57 -08001162}
deadbeefe1f9d832016-01-14 15:35:42 -08001163
Steve Antonf9381f02017-12-14 10:23:57 -08001164RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>>
1165PeerConnection::AddTrackUnifiedPlan(
1166 rtc::scoped_refptr<MediaStreamTrackInterface> track,
1167 const std::vector<std::string>& stream_labels) {
1168 auto transceiver = FindFirstTransceiverForAddedTrack(track);
1169 if (transceiver) {
1170 if (transceiver->direction() == RtpTransceiverDirection::kRecvOnly) {
Steve Anton52d86772018-02-20 15:48:12 -08001171 transceiver->internal()->set_direction(
1172 RtpTransceiverDirection::kSendRecv);
Steve Antonf9381f02017-12-14 10:23:57 -08001173 } else if (transceiver->direction() == RtpTransceiverDirection::kInactive) {
Steve Anton52d86772018-02-20 15:48:12 -08001174 transceiver->internal()->set_direction(
1175 RtpTransceiverDirection::kSendOnly);
Steve Antonf9381f02017-12-14 10:23:57 -08001176 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001177 transceiver->sender()->SetTrack(track);
1178 transceiver->internal()->sender_internal()->set_stream_ids(stream_labels);
Steve Antonf9381f02017-12-14 10:23:57 -08001179 } else {
1180 cricket::MediaType media_type =
1181 (track->kind() == MediaStreamTrackInterface::kAudioKind
1182 ? cricket::MEDIA_TYPE_AUDIO
1183 : cricket::MEDIA_TYPE_VIDEO);
Steve Anton02ee47c2018-01-10 16:26:06 -08001184 auto sender = CreateSender(media_type, track, stream_labels);
1185 auto receiver = CreateReceiver(media_type, rtc::CreateRandomUuid());
1186 transceiver = CreateAndAddTransceiver(sender, receiver);
Steve Antonf9381f02017-12-14 10:23:57 -08001187 transceiver->internal()->set_created_by_addtrack(true);
Steve Anton52d86772018-02-20 15:48:12 -08001188 transceiver->internal()->set_direction(RtpTransceiverDirection::kSendRecv);
Steve Antonf9381f02017-12-14 10:23:57 -08001189 }
Steve Antonf9381f02017-12-14 10:23:57 -08001190 return transceiver->sender();
1191}
1192
1193rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1194PeerConnection::FindFirstTransceiverForAddedTrack(
1195 rtc::scoped_refptr<MediaStreamTrackInterface> track) {
1196 RTC_DCHECK(track);
1197 for (auto transceiver : transceivers_) {
1198 if (!transceiver->sender()->track() &&
Steve Anton69470252018-02-09 11:43:08 -08001199 cricket::MediaTypeToString(transceiver->media_type()) ==
Steve Antonf9381f02017-12-14 10:23:57 -08001200 track->kind() &&
Seth Hampson2f0d7022018-02-20 11:54:42 -08001201 !transceiver->internal()->has_ever_been_used_to_send() &&
1202 !transceiver->stopped()) {
Steve Antonf9381f02017-12-14 10:23:57 -08001203 return transceiver;
1204 }
1205 }
1206 return nullptr;
deadbeefe1f9d832016-01-14 15:35:42 -08001207}
1208
1209bool PeerConnection::RemoveTrack(RtpSenderInterface* sender) {
1210 TRACE_EVENT0("webrtc", "PeerConnection::RemoveTrack");
Steve Antonf9381f02017-12-14 10:23:57 -08001211 return RemoveTrackInternal(sender).ok();
1212}
1213
1214RTCError PeerConnection::RemoveTrackInternal(
1215 rtc::scoped_refptr<RtpSenderInterface> sender) {
1216 if (!sender) {
1217 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "Sender is null.");
1218 }
deadbeefe1f9d832016-01-14 15:35:42 -08001219 if (IsClosed()) {
Steve Antonf9381f02017-12-14 10:23:57 -08001220 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
1221 "PeerConnection is closed.");
deadbeefe1f9d832016-01-14 15:35:42 -08001222 }
Steve Antonf9381f02017-12-14 10:23:57 -08001223 if (IsUnifiedPlan()) {
1224 auto transceiver = FindTransceiverBySender(sender);
1225 if (!transceiver || !sender->track()) {
1226 return RTCError::OK();
1227 }
1228 sender->SetTrack(nullptr);
1229 if (transceiver->direction() == RtpTransceiverDirection::kSendRecv) {
Steve Anton52d86772018-02-20 15:48:12 -08001230 transceiver->internal()->set_direction(
1231 RtpTransceiverDirection::kRecvOnly);
Steve Antonf9381f02017-12-14 10:23:57 -08001232 } else if (transceiver->direction() == RtpTransceiverDirection::kSendOnly) {
Steve Anton52d86772018-02-20 15:48:12 -08001233 transceiver->internal()->set_direction(
1234 RtpTransceiverDirection::kInactive);
Steve Antonf9381f02017-12-14 10:23:57 -08001235 }
Steve Anton4171afb2017-11-20 10:20:22 -08001236 } else {
Steve Antonf9381f02017-12-14 10:23:57 -08001237 bool removed;
1238 if (sender->media_type() == cricket::MEDIA_TYPE_AUDIO) {
1239 removed = GetAudioTransceiver()->internal()->RemoveSender(sender);
1240 } else {
1241 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, sender->media_type());
1242 removed = GetVideoTransceiver()->internal()->RemoveSender(sender);
1243 }
1244 if (!removed) {
1245 LOG_AND_RETURN_ERROR(
1246 RTCErrorType::INVALID_PARAMETER,
1247 "Couldn't find sender " + sender->id() + " to remove.");
1248 }
Steve Anton4171afb2017-11-20 10:20:22 -08001249 }
deadbeefe1f9d832016-01-14 15:35:42 -08001250 observer_->OnRenegotiationNeeded();
Steve Antonf9381f02017-12-14 10:23:57 -08001251 return RTCError::OK();
1252}
1253
1254rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1255PeerConnection::FindTransceiverBySender(
1256 rtc::scoped_refptr<RtpSenderInterface> sender) {
1257 for (auto transceiver : transceivers_) {
1258 if (transceiver->sender() == sender) {
1259 return transceiver;
1260 }
1261 }
1262 return nullptr;
deadbeefe1f9d832016-01-14 15:35:42 -08001263}
1264
Steve Anton9158ef62017-11-27 13:01:52 -08001265RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1266PeerConnection::AddTransceiver(
1267 rtc::scoped_refptr<MediaStreamTrackInterface> track) {
1268 return AddTransceiver(track, RtpTransceiverInit());
1269}
1270
1271RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1272PeerConnection::AddTransceiver(
1273 rtc::scoped_refptr<MediaStreamTrackInterface> track,
1274 const RtpTransceiverInit& init) {
Steve Antonfc853712018-03-01 13:48:58 -08001275 RTC_CHECK(IsUnifiedPlan())
1276 << "AddTransceiver is only available with Unified Plan SdpSemantics";
Steve Anton9158ef62017-11-27 13:01:52 -08001277 if (!track) {
1278 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "track is null");
1279 }
1280 cricket::MediaType media_type;
1281 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
1282 media_type = cricket::MEDIA_TYPE_AUDIO;
1283 } else if (track->kind() == MediaStreamTrackInterface::kVideoKind) {
1284 media_type = cricket::MEDIA_TYPE_VIDEO;
1285 } else {
1286 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1287 "Track kind is not audio or video");
1288 }
1289 return AddTransceiver(media_type, track, init);
1290}
1291
1292RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1293PeerConnection::AddTransceiver(cricket::MediaType media_type) {
1294 return AddTransceiver(media_type, RtpTransceiverInit());
1295}
1296
1297RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1298PeerConnection::AddTransceiver(cricket::MediaType media_type,
1299 const RtpTransceiverInit& init) {
Steve Antonfc853712018-03-01 13:48:58 -08001300 RTC_CHECK(IsUnifiedPlan())
1301 << "AddTransceiver is only available with Unified Plan SdpSemantics";
Steve Anton9158ef62017-11-27 13:01:52 -08001302 if (!(media_type == cricket::MEDIA_TYPE_AUDIO ||
1303 media_type == cricket::MEDIA_TYPE_VIDEO)) {
1304 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1305 "media type is not audio or video");
1306 }
1307 return AddTransceiver(media_type, nullptr, init);
1308}
1309
1310RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1311PeerConnection::AddTransceiver(
1312 cricket::MediaType media_type,
1313 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Steve Anton22da89f2018-01-25 13:58:07 -08001314 const RtpTransceiverInit& init,
1315 bool fire_callback) {
Steve Anton9158ef62017-11-27 13:01:52 -08001316 RTC_DCHECK((media_type == cricket::MEDIA_TYPE_AUDIO ||
1317 media_type == cricket::MEDIA_TYPE_VIDEO));
1318 if (track) {
1319 RTC_DCHECK_EQ(media_type,
1320 (track->kind() == MediaStreamTrackInterface::kAudioKind
1321 ? cricket::MEDIA_TYPE_AUDIO
1322 : cricket::MEDIA_TYPE_VIDEO));
1323 }
1324
1325 // TODO(bugs.webrtc.org/7600): Verify init.
1326
Steve Anton02ee47c2018-01-10 16:26:06 -08001327 if (init.stream_labels.size() > 1u) {
1328 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
1329 "More than one stream is not yet supported.");
Steve Antonf9381f02017-12-14 10:23:57 -08001330 }
1331
Steve Anton02ee47c2018-01-10 16:26:06 -08001332 std::vector<std::string> stream_labels = {!init.stream_labels.empty()
1333 ? init.stream_labels[0]
1334 : rtc::CreateRandomUuid()};
1335
1336 auto sender = CreateSender(media_type, track, stream_labels);
1337 auto receiver = CreateReceiver(media_type, rtc::CreateRandomUuid());
1338 auto transceiver = CreateAndAddTransceiver(sender, receiver);
1339 transceiver->internal()->set_direction(init.direction);
1340
Steve Anton22da89f2018-01-25 13:58:07 -08001341 if (fire_callback) {
1342 observer_->OnRenegotiationNeeded();
1343 }
Steve Antonf9381f02017-12-14 10:23:57 -08001344
1345 return rtc::scoped_refptr<RtpTransceiverInterface>(transceiver);
1346}
1347
Steve Anton02ee47c2018-01-10 16:26:06 -08001348rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
1349PeerConnection::CreateSender(
1350 cricket::MediaType media_type,
1351 rtc::scoped_refptr<MediaStreamTrackInterface> track,
1352 const std::vector<std::string>& stream_labels) {
Steve Anton9158ef62017-11-27 13:01:52 -08001353 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> sender;
Steve Anton02ee47c2018-01-10 16:26:06 -08001354 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
1355 RTC_DCHECK(!track ||
1356 (track->kind() == MediaStreamTrackInterface::kAudioKind));
1357 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
1358 signaling_thread(),
Steve Anton47136dd2018-01-12 10:49:35 -08001359 new AudioRtpSender(worker_thread(),
1360 static_cast<AudioTrackInterface*>(track.get()),
Steve Anton02ee47c2018-01-10 16:26:06 -08001361 stream_labels, stats_.get()));
1362 } else {
1363 RTC_DCHECK_EQ(media_type, cricket::MEDIA_TYPE_VIDEO);
1364 RTC_DCHECK(!track ||
1365 (track->kind() == MediaStreamTrackInterface::kVideoKind));
1366 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
1367 signaling_thread(),
Steve Anton47136dd2018-01-12 10:49:35 -08001368 new VideoRtpSender(worker_thread(),
1369 static_cast<VideoTrackInterface*>(track.get()),
Steve Anton02ee47c2018-01-10 16:26:06 -08001370 stream_labels));
1371 }
1372 sender->internal()->set_stream_ids(stream_labels);
1373 return sender;
1374}
1375
1376rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1377PeerConnection::CreateReceiver(cricket::MediaType media_type,
1378 const std::string& receiver_id) {
Steve Anton9158ef62017-11-27 13:01:52 -08001379 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1380 receiver;
Steve Anton9158ef62017-11-27 13:01:52 -08001381 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton9158ef62017-11-27 13:01:52 -08001382 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
Steve Anton60776752018-01-10 11:51:34 -08001383 signaling_thread(),
Steve Antond3679212018-01-17 17:41:02 -08001384 new AudioRtpReceiver(worker_thread(), receiver_id, {}));
Steve Anton9158ef62017-11-27 13:01:52 -08001385 } else {
Steve Anton02ee47c2018-01-10 16:26:06 -08001386 RTC_DCHECK_EQ(media_type, cricket::MEDIA_TYPE_VIDEO);
Steve Anton9158ef62017-11-27 13:01:52 -08001387 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
1388 signaling_thread(),
Steve Antond3679212018-01-17 17:41:02 -08001389 new VideoRtpReceiver(worker_thread(), receiver_id, {}));
Steve Anton9158ef62017-11-27 13:01:52 -08001390 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001391 return receiver;
1392}
1393
1394rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1395PeerConnection::CreateAndAddTransceiver(
1396 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> sender,
1397 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1398 receiver) {
1399 auto transceiver = RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1400 signaling_thread(), new RtpTransceiver(sender, receiver));
Steve Anton9158ef62017-11-27 13:01:52 -08001401 transceivers_.push_back(transceiver);
Steve Anton52d86772018-02-20 15:48:12 -08001402 transceiver->internal()->SignalNegotiationNeeded.connect(
1403 this, &PeerConnection::OnNegotiationNeeded);
Steve Antonf9381f02017-12-14 10:23:57 -08001404 return transceiver;
Steve Anton9158ef62017-11-27 13:01:52 -08001405}
1406
Steve Anton52d86772018-02-20 15:48:12 -08001407void PeerConnection::OnNegotiationNeeded() {
1408 RTC_DCHECK_RUN_ON(signaling_thread());
1409 RTC_DCHECK(!IsClosed());
1410 observer_->OnRenegotiationNeeded();
1411}
1412
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001413rtc::scoped_refptr<DtmfSenderInterface> PeerConnection::CreateDtmfSender(
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001414 AudioTrackInterface* track) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001415 TRACE_EVENT0("webrtc", "PeerConnection::CreateDtmfSender");
zhihuang29ff8442016-07-27 11:07:25 -07001416 if (IsClosed()) {
1417 return nullptr;
1418 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001419 if (!track) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001420 RTC_LOG(LS_ERROR) << "CreateDtmfSender - track is NULL.";
deadbeef20cb0c12017-02-01 20:27:00 -08001421 return nullptr;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001422 }
Steve Anton4171afb2017-11-20 10:20:22 -08001423 auto track_sender = FindSenderForTrack(track);
1424 if (!track_sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001425 RTC_LOG(LS_ERROR) << "CreateDtmfSender called with a non-added track.";
deadbeef20cb0c12017-02-01 20:27:00 -08001426 return nullptr;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001427 }
1428
Steve Anton4171afb2017-11-20 10:20:22 -08001429 return track_sender->GetDtmfSender();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001430}
1431
deadbeeffac06552015-11-25 11:26:01 -08001432rtc::scoped_refptr<RtpSenderInterface> PeerConnection::CreateSender(
deadbeefbd7d8f72015-12-18 16:58:44 -08001433 const std::string& kind,
1434 const std::string& stream_id) {
Steve Antonfc853712018-03-01 13:48:58 -08001435 RTC_CHECK(!IsUnifiedPlan()) << "CreateSender is not available with Unified "
1436 "Plan SdpSemantics. Please use AddTransceiver "
1437 "instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001438 TRACE_EVENT0("webrtc", "PeerConnection::CreateSender");
zhihuang29ff8442016-07-27 11:07:25 -07001439 if (IsClosed()) {
1440 return nullptr;
1441 }
Steve Anton4171afb2017-11-20 10:20:22 -08001442
Steve Anton02ee47c2018-01-10 16:26:06 -08001443 std::vector<std::string> stream_labels;
1444 if (!stream_id.empty()) {
1445 stream_labels.push_back(stream_id);
1446 }
1447
Steve Anton4171afb2017-11-20 10:20:22 -08001448 // TODO(steveanton): Move construction of the RtpSenders to RtpTransceiver.
deadbeefa601f5c2016-06-06 14:27:39 -07001449 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender;
deadbeeffac06552015-11-25 11:26:01 -08001450 if (kind == MediaStreamTrackInterface::kAudioKind) {
Steve Anton47136dd2018-01-12 10:49:35 -08001451 auto* audio_sender = new AudioRtpSender(worker_thread(), nullptr,
1452 stream_labels, stats_.get());
Steve Anton57858b32018-02-15 15:19:50 -08001453 audio_sender->SetVoiceMediaChannel(voice_media_channel());
deadbeefa601f5c2016-06-06 14:27:39 -07001454 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton02ee47c2018-01-10 16:26:06 -08001455 signaling_thread(), audio_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001456 GetAudioTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 11:26:01 -08001457 } else if (kind == MediaStreamTrackInterface::kVideoKind) {
Steve Anton47136dd2018-01-12 10:49:35 -08001458 auto* video_sender =
1459 new VideoRtpSender(worker_thread(), nullptr, stream_labels);
Steve Anton57858b32018-02-15 15:19:50 -08001460 video_sender->SetVideoMediaChannel(video_media_channel());
deadbeefa601f5c2016-06-06 14:27:39 -07001461 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton02ee47c2018-01-10 16:26:06 -08001462 signaling_thread(), video_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001463 GetVideoTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 11:26:01 -08001464 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001465 RTC_LOG(LS_ERROR) << "CreateSender called with invalid kind: " << kind;
Steve Anton4171afb2017-11-20 10:20:22 -08001466 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08001467 }
Steve Anton4171afb2017-11-20 10:20:22 -08001468
deadbeefe1f9d832016-01-14 15:35:42 -08001469 return new_sender;
deadbeeffac06552015-11-25 11:26:01 -08001470}
1471
deadbeef70ab1a12015-09-28 16:53:55 -07001472std::vector<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::GetSenders()
1473 const {
deadbeefa601f5c2016-06-06 14:27:39 -07001474 std::vector<rtc::scoped_refptr<RtpSenderInterface>> ret;
Steve Anton4171afb2017-11-20 10:20:22 -08001475 for (auto sender : GetSendersInternal()) {
1476 ret.push_back(sender);
deadbeefa601f5c2016-06-06 14:27:39 -07001477 }
1478 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -07001479}
1480
Steve Anton4171afb2017-11-20 10:20:22 -08001481std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1482PeerConnection::GetSendersInternal() const {
1483 std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1484 all_senders;
1485 for (auto transceiver : transceivers_) {
1486 auto senders = transceiver->internal()->senders();
1487 all_senders.insert(all_senders.end(), senders.begin(), senders.end());
1488 }
1489 return all_senders;
1490}
1491
deadbeef70ab1a12015-09-28 16:53:55 -07001492std::vector<rtc::scoped_refptr<RtpReceiverInterface>>
1493PeerConnection::GetReceivers() const {
deadbeefa601f5c2016-06-06 14:27:39 -07001494 std::vector<rtc::scoped_refptr<RtpReceiverInterface>> ret;
Steve Anton4171afb2017-11-20 10:20:22 -08001495 for (const auto& receiver : GetReceiversInternal()) {
1496 ret.push_back(receiver);
deadbeefa601f5c2016-06-06 14:27:39 -07001497 }
1498 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -07001499}
1500
Steve Anton4171afb2017-11-20 10:20:22 -08001501std::vector<
1502 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1503PeerConnection::GetReceiversInternal() const {
1504 std::vector<
1505 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1506 all_receivers;
1507 for (auto transceiver : transceivers_) {
1508 auto receivers = transceiver->internal()->receivers();
1509 all_receivers.insert(all_receivers.end(), receivers.begin(),
1510 receivers.end());
1511 }
1512 return all_receivers;
1513}
1514
Steve Anton9158ef62017-11-27 13:01:52 -08001515std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
1516PeerConnection::GetTransceivers() const {
Steve Antonfc853712018-03-01 13:48:58 -08001517 RTC_CHECK(IsUnifiedPlan())
1518 << "GetTransceivers is only supported with Unified Plan SdpSemantics.";
Steve Anton9158ef62017-11-27 13:01:52 -08001519 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> all_transceivers;
1520 for (auto transceiver : transceivers_) {
1521 all_transceivers.push_back(transceiver);
1522 }
1523 return all_transceivers;
1524}
1525
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001526bool PeerConnection::GetStats(StatsObserver* observer,
wu@webrtc.orgb9a088b2014-02-13 23:18:49 +00001527 MediaStreamTrackInterface* track,
1528 StatsOutputLevel level) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001529 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
deadbeef0a6c4ca2015-10-06 11:38:28 -07001530 RTC_DCHECK(signaling_thread()->IsCurrent());
nisse7ce109a2017-01-31 00:57:56 -08001531 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001532 RTC_LOG(LS_ERROR) << "GetStats - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001533 return false;
1534 }
1535
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001536 stats_->UpdateStats(level);
zhihuange9e94c32016-11-04 11:38:15 -07001537 // The StatsCollector is used to tell if a track is valid because it may
1538 // remember tracks that the PeerConnection previously removed.
1539 if (track && !stats_->IsValidTrack(track->id())) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001540 RTC_LOG(LS_WARNING) << "GetStats is called with an invalid track: "
1541 << track->id();
zhihuange9e94c32016-11-04 11:38:15 -07001542 return false;
1543 }
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001544 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_GETSTATS,
tommi@webrtc.org5b06b062014-08-15 08:38:30 +00001545 new GetStatsMsg(observer, track));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001546 return true;
1547}
1548
hbos74e1a4f2016-09-15 23:33:01 -07001549void PeerConnection::GetStats(RTCStatsCollectorCallback* callback) {
1550 RTC_DCHECK(stats_collector_);
1551 stats_collector_->GetStatsReport(callback);
1552}
1553
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001554PeerConnectionInterface::SignalingState PeerConnection::signaling_state() {
1555 return signaling_state_;
1556}
1557
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001558PeerConnectionInterface::IceConnectionState
1559PeerConnection::ice_connection_state() {
1560 return ice_connection_state_;
1561}
1562
1563PeerConnectionInterface::IceGatheringState
1564PeerConnection::ice_gathering_state() {
1565 return ice_gathering_state_;
1566}
1567
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001568rtc::scoped_refptr<DataChannelInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001569PeerConnection::CreateDataChannel(
1570 const std::string& label,
1571 const DataChannelInit* config) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001572 TRACE_EVENT0("webrtc", "PeerConnection::CreateDataChannel");
zhihuang9763d562016-08-05 11:14:50 -07001573
deadbeefab9b2d12015-10-14 11:33:11 -07001574 bool first_datachannel = !HasDataChannels();
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001575
kwibergd1fe2812016-04-27 06:47:29 -07001576 std::unique_ptr<InternalDataChannelInit> internal_config;
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00001577 if (config) {
1578 internal_config.reset(new InternalDataChannelInit(*config));
1579 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001580 rtc::scoped_refptr<DataChannelInterface> channel(
deadbeefab9b2d12015-10-14 11:33:11 -07001581 InternalCreateDataChannel(label, internal_config.get()));
1582 if (!channel.get()) {
1583 return nullptr;
1584 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001585
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001586 // Trigger the onRenegotiationNeeded event for every new RTP DataChannel, or
1587 // the first SCTP DataChannel.
Steve Anton75737c02017-11-06 10:37:17 -08001588 if (data_channel_type() == cricket::DCT_RTP || first_datachannel) {
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001589 observer_->OnRenegotiationNeeded();
1590 }
wu@webrtc.org91053e72013-08-10 07:18:04 +00001591
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001592 return DataChannelProxy::Create(signaling_thread(), channel.get());
1593}
1594
1595void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
1596 const MediaConstraintsInterface* constraints) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001597 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
Steve Anton8d3444d2017-10-20 15:30:51 -07001598
zhihuang1c378ed2017-08-17 14:10:50 -07001599 PeerConnectionInterface::RTCOfferAnswerOptions offer_answer_options;
1600 // Always create an offer even if |ConvertConstraintsToOfferAnswerOptions|
1601 // returns false for now. Because |ConvertConstraintsToOfferAnswerOptions|
1602 // compares the mandatory fields parsed with the mandatory fields added in the
1603 // |constraints| and some downstream applications might create offers with
1604 // mandatory fields which would not be parsed in the helper method. For
1605 // example, in Chromium/remoting, |kEnableDtlsSrtp| is added to the
1606 // |constraints| as a mandatory field but it is not parsed.
1607 ConvertConstraintsToOfferAnswerOptions(constraints, &offer_answer_options);
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001608
zhihuang1c378ed2017-08-17 14:10:50 -07001609 CreateOffer(observer, offer_answer_options);
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001610}
1611
1612void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
1613 const RTCOfferAnswerOptions& options) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001614 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
Steve Anton8d3444d2017-10-20 15:30:51 -07001615
nisse7ce109a2017-01-31 00:57:56 -08001616 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001617 RTC_LOG(LS_ERROR) << "CreateOffer - observer is NULL.";
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001618 return;
1619 }
deadbeefab9b2d12015-10-14 11:33:11 -07001620
Steve Anton8d3444d2017-10-20 15:30:51 -07001621 if (IsClosed()) {
1622 std::string error = "CreateOffer called when PeerConnection is closed.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001623 RTC_LOG(LS_ERROR) << error;
Steve Anton8d3444d2017-10-20 15:30:51 -07001624 PostCreateSessionDescriptionFailure(observer, error);
1625 return;
1626 }
1627
zhihuang1c378ed2017-08-17 14:10:50 -07001628 if (!ValidateOfferAnswerOptions(options)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001629 std::string error = "CreateOffer called with invalid options.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001630 RTC_LOG(LS_ERROR) << error;
deadbeefab9b2d12015-10-14 11:33:11 -07001631 PostCreateSessionDescriptionFailure(observer, error);
1632 return;
1633 }
1634
Steve Anton22da89f2018-01-25 13:58:07 -08001635 // Legacy handling for offer_to_receive_audio and offer_to_receive_video.
1636 // Specified in WebRTC section 4.4.3.2 "Legacy configuration extensions".
1637 if (IsUnifiedPlan()) {
1638 RTCError error = HandleLegacyOfferOptions(options);
1639 if (!error.ok()) {
1640 PostCreateSessionDescriptionFailure(observer, error.message());
1641 return;
1642 }
1643 }
1644
zhihuang1c378ed2017-08-17 14:10:50 -07001645 cricket::MediaSessionOptions session_options;
1646 GetOptionsForOffer(options, &session_options);
Steve Antond25da372017-11-06 14:50:29 -08001647 webrtc_session_desc_factory_->CreateOffer(observer, options, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001648}
1649
Steve Anton22da89f2018-01-25 13:58:07 -08001650RTCError PeerConnection::HandleLegacyOfferOptions(
1651 const RTCOfferAnswerOptions& options) {
1652 RTC_DCHECK(IsUnifiedPlan());
1653
1654 if (options.offer_to_receive_audio == 0) {
1655 RemoveRecvDirectionFromReceivingTransceiversOfType(
1656 cricket::MEDIA_TYPE_AUDIO);
1657 } else if (options.offer_to_receive_audio == 1) {
1658 AddUpToOneReceivingTransceiverOfType(cricket::MEDIA_TYPE_AUDIO);
1659 } else if (options.offer_to_receive_audio > 1) {
1660 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
1661 "offer_to_receive_audio > 1 is not supported.");
1662 }
1663
1664 if (options.offer_to_receive_video == 0) {
1665 RemoveRecvDirectionFromReceivingTransceiversOfType(
1666 cricket::MEDIA_TYPE_VIDEO);
1667 } else if (options.offer_to_receive_video == 1) {
1668 AddUpToOneReceivingTransceiverOfType(cricket::MEDIA_TYPE_VIDEO);
1669 } else if (options.offer_to_receive_video > 1) {
1670 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
1671 "offer_to_receive_video > 1 is not supported.");
1672 }
1673
1674 return RTCError::OK();
1675}
1676
1677void PeerConnection::RemoveRecvDirectionFromReceivingTransceiversOfType(
1678 cricket::MediaType media_type) {
1679 for (auto transceiver : GetReceivingTransceiversOfType(media_type)) {
1680 transceiver->internal()->set_direction(
1681 RtpTransceiverDirectionWithRecvSet(transceiver->direction(), false));
1682 }
1683}
1684
1685void PeerConnection::AddUpToOneReceivingTransceiverOfType(
1686 cricket::MediaType media_type) {
1687 if (GetReceivingTransceiversOfType(media_type).empty()) {
1688 RtpTransceiverInit init;
1689 init.direction = RtpTransceiverDirection::kRecvOnly;
1690 AddTransceiver(media_type, nullptr, init, /*fire_callback=*/false);
1691 }
1692}
1693
1694std::vector<rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
1695PeerConnection::GetReceivingTransceiversOfType(cricket::MediaType media_type) {
1696 std::vector<
1697 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
1698 receiving_transceivers;
1699 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08001700 if (!transceiver->stopped() && transceiver->media_type() == media_type &&
Steve Anton22da89f2018-01-25 13:58:07 -08001701 RtpTransceiverDirectionHasRecv(transceiver->direction())) {
1702 receiving_transceivers.push_back(transceiver);
1703 }
1704 }
1705 return receiving_transceivers;
1706}
1707
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001708void PeerConnection::CreateAnswer(
1709 CreateSessionDescriptionObserver* observer,
1710 const MediaConstraintsInterface* constraints) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001711 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
Steve Anton8d3444d2017-10-20 15:30:51 -07001712
nisse7ce109a2017-01-31 00:57:56 -08001713 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001714 RTC_LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001715 return;
1716 }
deadbeefab9b2d12015-10-14 11:33:11 -07001717
zhihuang1c378ed2017-08-17 14:10:50 -07001718 PeerConnectionInterface::RTCOfferAnswerOptions offer_answer_options;
1719 if (!ConvertConstraintsToOfferAnswerOptions(constraints,
1720 &offer_answer_options)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001721 std::string error = "CreateAnswer called with invalid constraints.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001722 RTC_LOG(LS_ERROR) << error;
deadbeefab9b2d12015-10-14 11:33:11 -07001723 PostCreateSessionDescriptionFailure(observer, error);
1724 return;
1725 }
1726
Steve Anton8d3444d2017-10-20 15:30:51 -07001727 CreateAnswer(observer, offer_answer_options);
htaa2a49d92016-03-04 02:51:39 -08001728}
1729
1730void PeerConnection::CreateAnswer(CreateSessionDescriptionObserver* observer,
1731 const RTCOfferAnswerOptions& options) {
1732 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
nisse7ce109a2017-01-31 00:57:56 -08001733 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001734 RTC_LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
htaa2a49d92016-03-04 02:51:39 -08001735 return;
1736 }
1737
Steve Antondffead82018-02-06 10:31:29 -08001738 if (!(signaling_state_ == kHaveRemoteOffer ||
1739 signaling_state_ == kHaveLocalPrAnswer)) {
1740 std::string error =
1741 "PeerConnection cannot create an answer in a state other than "
1742 "have-remote-offer or have-local-pranswer.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001743 RTC_LOG(LS_ERROR) << error;
Steve Anton8d3444d2017-10-20 15:30:51 -07001744 PostCreateSessionDescriptionFailure(observer, error);
1745 return;
1746 }
1747
Steve Antondffead82018-02-06 10:31:29 -08001748 // The remote description should be set if we're in the right state.
1749 RTC_DCHECK(remote_description());
Steve Anton8d3444d2017-10-20 15:30:51 -07001750
Steve Anton22da89f2018-01-25 13:58:07 -08001751 if (IsUnifiedPlan()) {
1752 if (options.offer_to_receive_audio != RTCOfferAnswerOptions::kUndefined) {
1753 RTC_LOG(LS_WARNING) << "CreateAnswer: offer_to_receive_audio is not "
1754 "supported with Unified Plan semantics. Use the "
1755 "RtpTransceiver API instead.";
1756 }
1757 if (options.offer_to_receive_video != RTCOfferAnswerOptions::kUndefined) {
1758 RTC_LOG(LS_WARNING) << "CreateAnswer: offer_to_receive_video is not "
1759 "supported with Unified Plan semantics. Use the "
1760 "RtpTransceiver API instead.";
1761 }
1762 }
1763
htaa2a49d92016-03-04 02:51:39 -08001764 cricket::MediaSessionOptions session_options;
zhihuang1c378ed2017-08-17 14:10:50 -07001765 GetOptionsForAnswer(options, &session_options);
htaa2a49d92016-03-04 02:51:39 -08001766
Steve Antond25da372017-11-06 14:50:29 -08001767 webrtc_session_desc_factory_->CreateAnswer(observer, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001768}
1769
1770void PeerConnection::SetLocalDescription(
1771 SetSessionDescriptionObserver* observer,
Steve Anton80dd7b52018-02-16 17:08:42 -08001772 SessionDescriptionInterface* desc_ptr) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001773 TRACE_EVENT0("webrtc", "PeerConnection::SetLocalDescription");
Steve Anton8a006912017-12-04 15:25:56 -08001774
Steve Anton80dd7b52018-02-16 17:08:42 -08001775 // The SetLocalDescription contract is that we take ownership of the session
1776 // description regardless of the outcome, so wrap it in a unique_ptr right
1777 // away. Ideally, SetLocalDescription's signature will be changed to take the
1778 // description as a unique_ptr argument to formalize this agreement.
1779 std::unique_ptr<SessionDescriptionInterface> desc(desc_ptr);
1780
nisse7ce109a2017-01-31 00:57:56 -08001781 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001782 RTC_LOG(LS_ERROR) << "SetLocalDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001783 return;
1784 }
Steve Anton8a006912017-12-04 15:25:56 -08001785
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001786 if (!desc) {
1787 PostSetSessionDescriptionFailure(observer, "SessionDescription is NULL.");
1788 return;
1789 }
Steve Anton8d3444d2017-10-20 15:30:51 -07001790
Steve Anton80dd7b52018-02-16 17:08:42 -08001791 // If a session error has occurred the PeerConnection is in a possibly
1792 // inconsistent state so fail right away.
1793 if (session_error() != SessionError::kNone) {
1794 std::string error_message = GetSessionErrorMsg();
1795 RTC_LOG(LS_ERROR) << "SetLocalDescription: " << error_message;
1796 PostSetSessionDescriptionFailure(observer, std::move(error_message));
1797 return;
1798 }
Steve Anton8d3444d2017-10-20 15:30:51 -07001799
Steve Anton80dd7b52018-02-16 17:08:42 -08001800 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_LOCAL);
1801 if (!error.ok()) {
1802 std::string error_message = GetSetDescriptionErrorMessage(
1803 cricket::CS_LOCAL, desc->GetType(), error);
1804 RTC_LOG(LS_ERROR) << error_message;
1805 PostSetSessionDescriptionFailure(observer, std::move(error_message));
1806 return;
1807 }
1808
1809 // Grab the description type before moving ownership to ApplyLocalDescription,
1810 // which may destroy it before returning.
1811 const SdpType type = desc->GetType();
1812
1813 error = ApplyLocalDescription(std::move(desc));
Steve Anton8a006912017-12-04 15:25:56 -08001814 // |desc| may be destroyed at this point.
1815
1816 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08001817 // If ApplyLocalDescription fails, the PeerConnection could be in an
1818 // inconsistent state, so act conservatively here and set the session error
1819 // so that future calls to SetLocalDescription/SetRemoteDescription fail.
1820 SetSessionError(SessionError::kContent, error.message());
1821 std::string error_message =
1822 GetSetDescriptionErrorMessage(cricket::CS_LOCAL, type, error);
1823 RTC_LOG(LS_ERROR) << error_message;
Steve Anton8a006912017-12-04 15:25:56 -08001824 PostSetSessionDescriptionFailure(observer, std::move(error_message));
Steve Anton8d3444d2017-10-20 15:30:51 -07001825 return;
1826 }
Steve Anton8a006912017-12-04 15:25:56 -08001827 RTC_DCHECK(local_description());
1828
1829 PostSetSessionDescriptionSuccess(observer);
1830
1831 // According to JSEP, after setLocalDescription, changing the candidate pool
1832 // size is not allowed, and changing the set of ICE servers will not result
1833 // in new candidates being gathered.
1834 port_allocator_->FreezeCandidatePool();
1835
1836 // MaybeStartGathering needs to be called after posting
1837 // MSG_SET_SESSIONDESCRIPTION_SUCCESS, so that we don't signal any candidates
1838 // before signaling that SetLocalDescription completed.
1839 transport_controller_->MaybeStartGathering();
1840
Steve Antona3a92c22017-12-07 10:27:41 -08001841 if (local_description()->GetType() == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08001842 // TODO(deadbeef): We already had to hop to the network thread for
1843 // MaybeStartGathering...
1844 network_thread()->Invoke<void>(
1845 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
1846 port_allocator_.get()));
Steve Anton0ffaaa22018-02-23 10:31:30 -08001847 // Make UMA notes about what was agreed to.
1848 ReportNegotiatedSdpSemantics(*local_description());
Steve Anton8a006912017-12-04 15:25:56 -08001849 }
1850}
1851
1852RTCError PeerConnection::ApplyLocalDescription(
1853 std::unique_ptr<SessionDescriptionInterface> desc) {
1854 RTC_DCHECK_RUN_ON(signaling_thread());
1855 RTC_DCHECK(desc);
1856
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001857 // Update stats here so that we have the most recent stats for tracks and
1858 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001859 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 15:25:56 -08001860
1861 // Update the initial_offerer flag if this session is the initial_offerer.
Steve Anton3828c062017-12-06 10:34:51 -08001862 SdpType type = desc->GetType();
Steve Anton8a006912017-12-04 15:25:56 -08001863 if (!initial_offerer_.has_value()) {
Steve Anton3828c062017-12-06 10:34:51 -08001864 initial_offerer_.emplace(type == SdpType::kOffer);
Steve Anton8a006912017-12-04 15:25:56 -08001865 if (*initial_offerer_) {
1866 transport_controller_->SetIceRole(cricket::ICEROLE_CONTROLLING);
1867 } else {
1868 transport_controller_->SetIceRole(cricket::ICEROLE_CONTROLLED);
1869 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001870 }
Steve Anton8a006912017-12-04 15:25:56 -08001871
Steve Antondcc3c022017-12-22 16:02:54 -08001872 // Take a reference to the old local description since it's used below to
1873 // compare against the new local description. When setting the new local
1874 // description, grab ownership of the replaced session description in case it
1875 // is the same as |old_local_description|, to keep it alive for the duration
1876 // of the method.
1877 const SessionDescriptionInterface* old_local_description =
1878 local_description();
1879 std::unique_ptr<SessionDescriptionInterface> replaced_local_description;
Steve Anton3828c062017-12-06 10:34:51 -08001880 if (type == SdpType::kAnswer) {
Steve Antondcc3c022017-12-22 16:02:54 -08001881 replaced_local_description = pending_local_description_
1882 ? std::move(pending_local_description_)
1883 : std::move(current_local_description_);
Steve Anton8a006912017-12-04 15:25:56 -08001884 current_local_description_ = std::move(desc);
1885 pending_local_description_ = nullptr;
1886 current_remote_description_ = std::move(pending_remote_description_);
1887 } else {
Steve Antondcc3c022017-12-22 16:02:54 -08001888 replaced_local_description = std::move(pending_local_description_);
Steve Anton8a006912017-12-04 15:25:56 -08001889 pending_local_description_ = std::move(desc);
1890 }
1891 // The session description to apply now must be accessed by
1892 // |local_description()|.
Henrik Boströmfdb92012017-11-09 19:55:44 +01001893 RTC_DCHECK(local_description());
deadbeefab9b2d12015-10-14 11:33:11 -07001894
Steve Antondcc3c022017-12-22 16:02:54 -08001895 if (IsUnifiedPlan()) {
1896 RTCError error = UpdateTransceiversAndDataChannels(
Seth Hampsonae8a90a2018-02-13 15:33:48 -08001897 cricket::CS_LOCAL, *local_description(), old_local_description,
1898 remote_description());
Steve Anton8a006912017-12-04 15:25:56 -08001899 if (!error.ok()) {
1900 return error;
1901 }
Steve Antondcc3c022017-12-22 16:02:54 -08001902 for (auto transceiver : transceivers_) {
1903 const ContentInfo* content =
1904 FindMediaSectionForTransceiver(transceiver, local_description());
1905 if (!content) {
1906 continue;
1907 }
1908 const MediaContentDescription* media_desc = content->media_description();
1909 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
1910 transceiver->internal()->set_current_direction(media_desc->direction());
1911 }
1912 if (content->rejected && !transceiver->stopped()) {
1913 transceiver->Stop();
1914 }
1915 }
1916 } else {
1917 // Transport and Media channels will be created only when offer is set.
1918 if (type == SdpType::kOffer) {
1919 // TODO(bugs.webrtc.org/4676) - Handle CreateChannel failure, as new local
1920 // description is applied. Restore back to old description.
1921 RTCError error = CreateChannels(*local_description()->description());
1922 if (!error.ok()) {
1923 return error;
1924 }
1925 }
Steve Anton8a006912017-12-04 15:25:56 -08001926
Steve Antondcc3c022017-12-22 16:02:54 -08001927 // Remove unused channels if MediaContentDescription is rejected.
1928 RemoveUnusedChannels(local_description()->description());
1929 }
Steve Anton8a006912017-12-04 15:25:56 -08001930
Steve Anton80dd7b52018-02-16 17:08:42 -08001931 RTCError error = UpdateSessionState(type, cricket::CS_LOCAL);
Steve Anton8a006912017-12-04 15:25:56 -08001932 if (!error.ok()) {
1933 return error;
1934 }
Steve Antondcc3c022017-12-22 16:02:54 -08001935
Steve Anton8a006912017-12-04 15:25:56 -08001936 if (remote_description()) {
1937 // Now that we have a local description, we can push down remote candidates.
1938 UseCandidatesInSessionDescription(remote_description());
1939 }
1940
1941 pending_ice_restarts_.clear();
1942 if (session_error() != SessionError::kNone) {
1943 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
1944 }
1945
deadbeefab9b2d12015-10-14 11:33:11 -07001946 // If setting the description decided our SSL role, allocate any necessary
1947 // SCTP sids.
1948 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08001949 if (data_channel_type() == cricket::DCT_SCTP && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001950 AllocateSctpSids(role);
1951 }
1952
Steve Antond3679212018-01-17 17:41:02 -08001953 if (IsUnifiedPlan()) {
1954 for (auto transceiver : transceivers_) {
1955 const ContentInfo* content =
1956 FindMediaSectionForTransceiver(transceiver, local_description());
1957 if (!content) {
1958 continue;
1959 }
1960 if (content->rejected && !transceiver->stopped()) {
1961 transceiver->Stop();
1962 }
Steve Anton74255ff2018-01-24 18:32:57 -08001963 const auto& streams = content->media_description()->streams();
1964 if (!content->rejected && !streams.empty()) {
Steve Antond3679212018-01-17 17:41:02 -08001965 transceiver->internal()->sender_internal()->set_stream_ids(
Steve Anton5a26a3a2018-02-28 11:38:47 -08001966 streams[0].stream_labels());
Steve Antond3679212018-01-17 17:41:02 -08001967 transceiver->internal()->sender_internal()->SetSsrc(
Steve Anton74255ff2018-01-24 18:32:57 -08001968 streams[0].first_ssrc());
Steve Antond3679212018-01-17 17:41:02 -08001969 }
1970 }
1971 } else {
1972 // Plan B semantics.
1973
Steve Antondcc3c022017-12-22 16:02:54 -08001974 // Update state and SSRC of local MediaStreams and DataChannels based on the
1975 // local session description.
1976 const cricket::ContentInfo* audio_content =
1977 GetFirstAudioContent(local_description()->description());
1978 if (audio_content) {
1979 if (audio_content->rejected) {
1980 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
1981 } else {
1982 const cricket::AudioContentDescription* audio_desc =
1983 audio_content->media_description()->as_audio();
1984 UpdateLocalSenders(audio_desc->streams(), audio_desc->type());
1985 }
deadbeeffaac4972015-11-12 15:33:07 -08001986 }
deadbeefab9b2d12015-10-14 11:33:11 -07001987
Steve Antondcc3c022017-12-22 16:02:54 -08001988 const cricket::ContentInfo* video_content =
1989 GetFirstVideoContent(local_description()->description());
1990 if (video_content) {
1991 if (video_content->rejected) {
1992 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
1993 } else {
1994 const cricket::VideoContentDescription* video_desc =
1995 video_content->media_description()->as_video();
1996 UpdateLocalSenders(video_desc->streams(), video_desc->type());
1997 }
deadbeeffaac4972015-11-12 15:33:07 -08001998 }
deadbeefab9b2d12015-10-14 11:33:11 -07001999 }
2000
2001 const cricket::ContentInfo* data_content =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002002 GetFirstDataContent(local_description()->description());
deadbeefab9b2d12015-10-14 11:33:11 -07002003 if (data_content) {
2004 const cricket::DataContentDescription* data_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08002005 data_content->media_description()->as_data();
deadbeefab9b2d12015-10-14 11:33:11 -07002006 if (rtc::starts_with(data_desc->protocol().data(),
2007 cricket::kMediaProtocolRtpPrefix)) {
2008 UpdateLocalRtpDataChannels(data_desc->streams());
2009 }
2010 }
2011
Steve Anton8a006912017-12-04 15:25:56 -08002012 return RTCError::OK();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002013}
2014
2015void PeerConnection::SetRemoteDescription(
Henrik Boströma4ecf552017-11-23 14:17:07 +00002016 SetSessionDescriptionObserver* observer,
2017 SessionDescriptionInterface* desc) {
Henrik Boström31638672017-11-23 17:48:32 +01002018 SetRemoteDescription(
2019 std::unique_ptr<SessionDescriptionInterface>(desc),
2020 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface>(
2021 new SetRemoteDescriptionObserverAdapter(this, observer)));
2022}
2023
2024void PeerConnection::SetRemoteDescription(
2025 std::unique_ptr<SessionDescriptionInterface> desc,
2026 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface> observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +01002027 TRACE_EVENT0("webrtc", "PeerConnection::SetRemoteDescription");
Steve Anton8a006912017-12-04 15:25:56 -08002028
nisse7ce109a2017-01-31 00:57:56 -08002029 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002030 RTC_LOG(LS_ERROR) << "SetRemoteDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002031 return;
2032 }
Steve Anton8a006912017-12-04 15:25:56 -08002033
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002034 if (!desc) {
Henrik Boström31638672017-11-23 17:48:32 +01002035 observer->OnSetRemoteDescriptionComplete(RTCError(
Steve Anton8a006912017-12-04 15:25:56 -08002036 RTCErrorType::INVALID_PARAMETER, "SessionDescription is NULL."));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002037 return;
2038 }
Steve Anton8d3444d2017-10-20 15:30:51 -07002039
Steve Anton80dd7b52018-02-16 17:08:42 -08002040 // If a session error has occurred the PeerConnection is in a possibly
2041 // inconsistent state so fail right away.
2042 if (session_error() != SessionError::kNone) {
2043 std::string error_message = GetSessionErrorMsg();
2044 RTC_LOG(LS_ERROR) << "SetRemoteDescription: " << error_message;
2045 observer->OnSetRemoteDescriptionComplete(
2046 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
2047 return;
2048 }
Steve Anton71439a62018-02-15 11:53:06 -08002049
Steve Anton80dd7b52018-02-16 17:08:42 -08002050 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_REMOTE);
Steve Anton71439a62018-02-15 11:53:06 -08002051 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08002052 std::string error_message = GetSetDescriptionErrorMessage(
2053 cricket::CS_REMOTE, desc->GetType(), error);
2054 RTC_LOG(LS_ERROR) << error_message;
Steve Anton71439a62018-02-15 11:53:06 -08002055 observer->OnSetRemoteDescriptionComplete(
2056 RTCError(error.type(), std::move(error_message)));
2057 return;
2058 }
Steve Anton71439a62018-02-15 11:53:06 -08002059
Steve Anton80dd7b52018-02-16 17:08:42 -08002060 // Grab the description type before moving ownership to
2061 // ApplyRemoteDescription, which may destroy it before returning.
2062 const SdpType type = desc->GetType();
2063
2064 error = ApplyRemoteDescription(std::move(desc));
2065 // |desc| may be destroyed at this point.
2066
2067 if (!error.ok()) {
2068 // If ApplyRemoteDescription fails, the PeerConnection could be in an
2069 // inconsistent state, so act conservatively here and set the session error
2070 // so that future calls to SetLocalDescription/SetRemoteDescription fail.
2071 SetSessionError(SessionError::kContent, error.message());
2072 std::string error_message =
2073 GetSetDescriptionErrorMessage(cricket::CS_REMOTE, type, error);
2074 RTC_LOG(LS_ERROR) << error_message;
2075 observer->OnSetRemoteDescriptionComplete(
2076 RTCError(error.type(), std::move(error_message)));
2077 return;
2078 }
2079 RTC_DCHECK(remote_description());
2080
2081 if (type == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002082 // TODO(deadbeef): We already had to hop to the network thread for
2083 // MaybeStartGathering...
2084 network_thread()->Invoke<void>(
2085 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
2086 port_allocator_.get()));
Harald Alvestrand5dbb5862018-02-13 23:48:00 +01002087 // Make UMA notes about what was agreed to.
Steve Anton0ffaaa22018-02-23 10:31:30 -08002088 ReportNegotiatedSdpSemantics(*remote_description());
Steve Anton8a006912017-12-04 15:25:56 -08002089 }
2090
2091 observer->OnSetRemoteDescriptionComplete(RTCError::OK());
2092}
2093
2094RTCError PeerConnection::ApplyRemoteDescription(
2095 std::unique_ptr<SessionDescriptionInterface> desc) {
2096 RTC_DCHECK_RUN_ON(signaling_thread());
2097 RTC_DCHECK(desc);
2098
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002099 // Update stats here so that we have the most recent stats for tracks and
2100 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00002101 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 15:25:56 -08002102
Steve Antondcc3c022017-12-22 16:02:54 -08002103 // Take a reference to the old remote description since it's used below to
2104 // compare against the new remote description. When setting the new remote
2105 // description, grab ownership of the replaced session description in case it
2106 // is the same as |old_remote_description|, to keep it alive for the duration
2107 // of the method.
Steve Anton8a006912017-12-04 15:25:56 -08002108 const SessionDescriptionInterface* old_remote_description =
2109 remote_description();
Steve Anton8a006912017-12-04 15:25:56 -08002110 std::unique_ptr<SessionDescriptionInterface> replaced_remote_description;
Steve Anton3828c062017-12-06 10:34:51 -08002111 SdpType type = desc->GetType();
2112 if (type == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002113 replaced_remote_description = pending_remote_description_
2114 ? std::move(pending_remote_description_)
2115 : std::move(current_remote_description_);
2116 current_remote_description_ = std::move(desc);
2117 pending_remote_description_ = nullptr;
2118 current_local_description_ = std::move(pending_local_description_);
2119 } else {
2120 replaced_remote_description = std::move(pending_remote_description_);
2121 pending_remote_description_ = std::move(desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002122 }
Steve Anton8a006912017-12-04 15:25:56 -08002123 // The session description to apply now must be accessed by
2124 // |remote_description()|.
Henrik Boströmfdb92012017-11-09 19:55:44 +01002125 RTC_DCHECK(remote_description());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002126
Steve Anton8a006912017-12-04 15:25:56 -08002127 // Transport and Media channels will be created only when offer is set.
Steve Antondcc3c022017-12-22 16:02:54 -08002128 if (IsUnifiedPlan()) {
2129 RTCError error = UpdateTransceiversAndDataChannels(
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002130 cricket::CS_REMOTE, *remote_description(), local_description(),
2131 old_remote_description);
Steve Anton8a006912017-12-04 15:25:56 -08002132 if (!error.ok()) {
2133 return error;
2134 }
Steve Antondcc3c022017-12-22 16:02:54 -08002135 } else {
2136 if (type == SdpType::kOffer) {
2137 // TODO(bugs.webrtc.org/4676) - Handle CreateChannel failure, as new local
2138 // description is applied. Restore back to old description.
2139 RTCError error = CreateChannels(*remote_description()->description());
2140 if (!error.ok()) {
2141 return error;
2142 }
2143 }
Steve Anton8a006912017-12-04 15:25:56 -08002144
Steve Antondcc3c022017-12-22 16:02:54 -08002145 // Remove unused channels if MediaContentDescription is rejected.
2146 RemoveUnusedChannels(remote_description()->description());
2147 }
Steve Anton8a006912017-12-04 15:25:56 -08002148
2149 // NOTE: Candidates allocation will be initiated only when SetLocalDescription
2150 // is called.
Steve Anton80dd7b52018-02-16 17:08:42 -08002151 RTCError error = UpdateSessionState(type, cricket::CS_REMOTE);
Steve Anton8a006912017-12-04 15:25:56 -08002152 if (!error.ok()) {
2153 return error;
2154 }
2155
2156 if (local_description() &&
2157 !UseCandidatesInSessionDescription(remote_description())) {
2158 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidCandidates);
2159 }
2160
2161 if (old_remote_description) {
2162 for (const cricket::ContentInfo& content :
2163 old_remote_description->description()->contents()) {
2164 // Check if this new SessionDescription contains new ICE ufrag and
2165 // password that indicates the remote peer requests an ICE restart.
2166 // TODO(deadbeef): When we start storing both the current and pending
2167 // remote description, this should reset pending_ice_restarts and compare
2168 // against the current description.
2169 if (CheckForRemoteIceRestart(old_remote_description, remote_description(),
2170 content.name)) {
Steve Anton3828c062017-12-06 10:34:51 -08002171 if (type == SdpType::kOffer) {
Steve Anton8a006912017-12-04 15:25:56 -08002172 pending_ice_restarts_.insert(content.name);
2173 }
2174 } else {
2175 // We retain all received candidates only if ICE is not restarted.
2176 // When ICE is restarted, all previous candidates belong to an old
2177 // generation and should not be kept.
2178 // TODO(deadbeef): This goes against the W3C spec which says the remote
2179 // description should only contain candidates from the last set remote
2180 // description plus any candidates added since then. We should remove
2181 // this once we're sure it won't break anything.
2182 WebRtcSessionDescriptionFactory::CopyCandidatesFromSessionDescription(
2183 old_remote_description, content.name, mutable_remote_description());
2184 }
2185 }
2186 }
2187
2188 if (session_error() != SessionError::kNone) {
2189 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
2190 }
2191
2192 // Set the the ICE connection state to connecting since the connection may
2193 // become writable with peer reflexive candidates before any remote candidate
2194 // is signaled.
2195 // TODO(pthatcher): This is a short-term solution for crbug/446908. A real fix
2196 // is to have a new signal the indicates a change in checking state from the
2197 // transport and expose a new checking() member from transport that can be
2198 // read to determine the current checking state. The existing SignalConnecting
2199 // actually means "gathering candidates", so cannot be be used here.
Steve Antona3a92c22017-12-07 10:27:41 -08002200 if (remote_description()->GetType() != SdpType::kOffer &&
Steve Anton8a006912017-12-04 15:25:56 -08002201 ice_connection_state() == PeerConnectionInterface::kIceConnectionNew) {
2202 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
2203 }
2204
deadbeefab9b2d12015-10-14 11:33:11 -07002205 // If setting the description decided our SSL role, allocate any necessary
2206 // SCTP sids.
2207 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08002208 if (data_channel_type() == cricket::DCT_SCTP && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07002209 AllocateSctpSids(role);
2210 }
2211
Steve Antondcc3c022017-12-22 16:02:54 -08002212 if (IsUnifiedPlan()) {
Steve Anton8b815cd2018-02-16 16:14:42 -08002213 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
2214 receiving_transceivers;
Steve Antonc49bcd92018-02-14 14:28:13 -08002215 std::vector<rtc::scoped_refptr<MediaStreamInterface>> added_streams;
Steve Antondcc3c022017-12-22 16:02:54 -08002216 for (auto transceiver : transceivers_) {
2217 const ContentInfo* content =
2218 FindMediaSectionForTransceiver(transceiver, remote_description());
2219 if (!content) {
2220 continue;
2221 }
2222 const MediaContentDescription* media_desc = content->media_description();
2223 RtpTransceiverDirection local_direction =
2224 RtpTransceiverDirectionReversed(media_desc->direction());
2225 // From the WebRTC specification, steps 2.2.8.5/6 of section 4.4.1.6 "Set
2226 // the RTCSessionDescription: If direction is sendrecv or recvonly, and
2227 // transceiver's current direction is neither sendrecv nor recvonly,
2228 // process the addition of a remote track for the media description.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002229 //
2230 // Create a sync label in the case of an unsignalled msid.
2231 std::string sync_label = rtc::CreateRandomUuid();
2232 if (!media_desc->streams().empty()) {
Steve Anton5a26a3a2018-02-28 11:38:47 -08002233 const cricket::StreamParams& stream_params = media_desc->streams()[0];
2234 if (!stream_params.stream_labels().empty()) {
2235 sync_label = stream_params.stream_labels()[0];
2236 }
Seth Hampson2f0d7022018-02-20 11:54:42 -08002237 }
Steve Antondcc3c022017-12-22 16:02:54 -08002238 if (RtpTransceiverDirectionHasRecv(local_direction) &&
2239 (!transceiver->current_direction() ||
2240 !RtpTransceiverDirectionHasRecv(
Seth Hampson2f0d7022018-02-20 11:54:42 -08002241 *transceiver->current_direction()))) {
Steve Antonef65ef12018-01-10 17:15:20 -08002242 rtc::scoped_refptr<MediaStreamInterface> stream =
2243 remote_streams_->find(sync_label);
2244 if (!stream) {
2245 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
2246 MediaStream::Create(sync_label));
2247 remote_streams_->AddStream(stream);
Steve Antonc49bcd92018-02-14 14:28:13 -08002248 added_streams.push_back(stream);
Steve Antonef65ef12018-01-10 17:15:20 -08002249 }
2250 transceiver->internal()->receiver_internal()->SetStreams({stream});
Steve Anton8b815cd2018-02-16 16:14:42 -08002251 receiving_transceivers.push_back(transceiver);
Steve Antondcc3c022017-12-22 16:02:54 -08002252 }
2253 // If direction is sendonly or inactive, and transceiver's current
2254 // direction is neither sendonly nor inactive, process the removal of a
2255 // remote track for the media description.
2256 if (!RtpTransceiverDirectionHasRecv(local_direction) &&
Steve Antonef65ef12018-01-10 17:15:20 -08002257 (transceiver->current_direction() &&
Steve Antondcc3c022017-12-22 16:02:54 -08002258 RtpTransceiverDirectionHasRecv(*transceiver->current_direction()))) {
Steve Antonef65ef12018-01-10 17:15:20 -08002259 transceiver->internal()->receiver_internal()->SetStreams({});
Steve Antondcc3c022017-12-22 16:02:54 -08002260 }
2261 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
2262 transceiver->internal()->set_current_direction(local_direction);
2263 }
2264 if (content->rejected && !transceiver->stopped()) {
2265 transceiver->Stop();
2266 }
Seth Hampson2f0d7022018-02-20 11:54:42 -08002267 if (!content->rejected &&
2268 RtpTransceiverDirectionHasRecv(local_direction)) {
2269 // Set ssrc to 0 in the case of an unsignalled ssrc.
2270 uint32_t ssrc = 0;
2271 if (!media_desc->streams().empty()) {
2272 ssrc = media_desc->streams()[0].first_ssrc();
2273 }
2274 transceiver->internal()->receiver_internal()->SetupMediaChannel(ssrc);
Steve Antond3679212018-01-17 17:41:02 -08002275 }
Steve Antondcc3c022017-12-22 16:02:54 -08002276 }
Steve Antonc49bcd92018-02-14 14:28:13 -08002277 // Once all processing has finished, fire off callbacks.
Steve Anton8b815cd2018-02-16 16:14:42 -08002278 for (auto transceiver : receiving_transceivers) {
Steve Anton6e221372018-02-20 12:59:16 -08002279 stats_->AddTrack(transceiver->receiver()->track());
Steve Anton8b815cd2018-02-16 16:14:42 -08002280 observer_->OnTrack(transceiver);
2281 observer_->OnAddTrack(transceiver->receiver(),
2282 transceiver->receiver()->streams());
Steve Antonef65ef12018-01-10 17:15:20 -08002283 }
Steve Antonc49bcd92018-02-14 14:28:13 -08002284 for (auto stream : added_streams) {
2285 observer_->OnAddStream(stream);
2286 }
Steve Antondcc3c022017-12-22 16:02:54 -08002287 }
2288
Henrik Boströmfdb92012017-11-09 19:55:44 +01002289 const cricket::ContentInfo* audio_content =
2290 GetFirstAudioContent(remote_description()->description());
2291 const cricket::ContentInfo* video_content =
2292 GetFirstVideoContent(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002293 const cricket::AudioContentDescription* audio_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002294 GetFirstAudioContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002295 const cricket::VideoContentDescription* video_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002296 GetFirstVideoContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002297 const cricket::DataContentDescription* data_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002298 GetFirstDataContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002299
2300 // Check if the descriptions include streams, just in case the peer supports
2301 // MSID, but doesn't indicate so with "a=msid-semantic".
Henrik Boströmfdb92012017-11-09 19:55:44 +01002302 if (remote_description()->description()->msid_supported() ||
deadbeefbda7e0b2015-12-08 17:13:40 -08002303 (audio_desc && !audio_desc->streams().empty()) ||
2304 (video_desc && !video_desc->streams().empty())) {
2305 remote_peer_supports_msid_ = true;
2306 }
deadbeefab9b2d12015-10-14 11:33:11 -07002307
2308 // We wait to signal new streams until we finish processing the description,
2309 // since only at that point will new streams have all their tracks.
2310 rtc::scoped_refptr<StreamCollection> new_streams(StreamCollection::Create());
2311
Steve Antondcc3c022017-12-22 16:02:54 -08002312 if (!IsUnifiedPlan()) {
2313 // TODO(steveanton): When removing RTP senders/receivers in response to a
2314 // rejected media section, there is some cleanup logic that expects the
2315 // voice/ video channel to still be set. But in this method the voice/video
2316 // channel would have been destroyed by the SetRemoteDescription caller
2317 // above so the cleanup that relies on them fails to run. The RemoveSenders
2318 // calls should be moved to right before the DestroyChannel calls to fix
2319 // this.
Steve Anton8d3444d2017-10-20 15:30:51 -07002320
Steve Antondcc3c022017-12-22 16:02:54 -08002321 // Find all audio rtp streams and create corresponding remote AudioTracks
2322 // and MediaStreams.
2323 if (audio_content) {
2324 if (audio_content->rejected) {
2325 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
2326 } else {
2327 bool default_audio_track_needed =
2328 !remote_peer_supports_msid_ &&
2329 RtpTransceiverDirectionHasSend(audio_desc->direction());
2330 UpdateRemoteSendersList(GetActiveStreams(audio_desc),
2331 default_audio_track_needed, audio_desc->type(),
2332 new_streams);
2333 }
deadbeeffaac4972015-11-12 15:33:07 -08002334 }
deadbeefab9b2d12015-10-14 11:33:11 -07002335
Steve Antondcc3c022017-12-22 16:02:54 -08002336 // Find all video rtp streams and create corresponding remote VideoTracks
2337 // and MediaStreams.
2338 if (video_content) {
2339 if (video_content->rejected) {
2340 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
2341 } else {
2342 bool default_video_track_needed =
2343 !remote_peer_supports_msid_ &&
2344 RtpTransceiverDirectionHasSend(video_desc->direction());
2345 UpdateRemoteSendersList(GetActiveStreams(video_desc),
2346 default_video_track_needed, video_desc->type(),
2347 new_streams);
2348 }
deadbeeffaac4972015-11-12 15:33:07 -08002349 }
deadbeefab9b2d12015-10-14 11:33:11 -07002350
Steve Antondcc3c022017-12-22 16:02:54 -08002351 // Update the DataChannels with the information from the remote peer.
2352 if (data_desc) {
2353 if (rtc::starts_with(data_desc->protocol().data(),
2354 cricket::kMediaProtocolRtpPrefix)) {
2355 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
2356 }
deadbeefab9b2d12015-10-14 11:33:11 -07002357 }
deadbeefab9b2d12015-10-14 11:33:11 -07002358
Steve Antondcc3c022017-12-22 16:02:54 -08002359 // Iterate new_streams and notify the observer about new MediaStreams.
2360 for (size_t i = 0; i < new_streams->count(); ++i) {
2361 MediaStreamInterface* new_stream = new_streams->at(i);
2362 stats_->AddStream(new_stream);
2363 observer_->OnAddStream(
2364 rtc::scoped_refptr<MediaStreamInterface>(new_stream));
2365 }
deadbeefab9b2d12015-10-14 11:33:11 -07002366
Steve Antondcc3c022017-12-22 16:02:54 -08002367 UpdateEndedRemoteMediaStreams();
2368 }
deadbeefab9b2d12015-10-14 11:33:11 -07002369
Steve Anton8a006912017-12-04 15:25:56 -08002370 return RTCError::OK();
deadbeeffc648b62015-10-13 16:42:33 -07002371}
2372
Steve Antondcc3c022017-12-22 16:02:54 -08002373RTCError PeerConnection::UpdateTransceiversAndDataChannels(
2374 cricket::ContentSource source,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002375 const SessionDescriptionInterface& new_session,
2376 const SessionDescriptionInterface* old_local_description,
2377 const SessionDescriptionInterface* old_remote_description) {
Steve Antondcc3c022017-12-22 16:02:54 -08002378 RTC_DCHECK(IsUnifiedPlan());
2379
Steve Anton7464fca2018-01-19 11:10:37 -08002380 const cricket::ContentGroup* bundle_group = nullptr;
2381 if (new_session.GetType() == SdpType::kOffer) {
2382 auto bundle_group_or_error =
2383 GetEarlyBundleGroup(*new_session.description());
2384 if (!bundle_group_or_error.ok()) {
2385 return bundle_group_or_error.MoveError();
2386 }
2387 bundle_group = bundle_group_or_error.MoveValue();
Steve Antondcc3c022017-12-22 16:02:54 -08002388 }
Steve Antondcc3c022017-12-22 16:02:54 -08002389
Steve Antondcc3c022017-12-22 16:02:54 -08002390 const ContentInfos& new_contents = new_session.description()->contents();
Steve Antondcc3c022017-12-22 16:02:54 -08002391 for (size_t i = 0; i < new_contents.size(); ++i) {
2392 const cricket::ContentInfo& new_content = new_contents[i];
Steve Antondcc3c022017-12-22 16:02:54 -08002393 cricket::MediaType media_type = new_content.media_description()->type();
2394 seen_mids_.insert(new_content.name);
2395 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
2396 media_type == cricket::MEDIA_TYPE_VIDEO) {
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002397 const cricket::ContentInfo* old_local_content = nullptr;
2398 if (old_local_description &&
2399 i < old_local_description->description()->contents().size()) {
2400 old_local_content =
2401 &old_local_description->description()->contents()[i];
2402 }
2403 const cricket::ContentInfo* old_remote_content = nullptr;
2404 if (old_remote_description &&
2405 i < old_remote_description->description()->contents().size()) {
2406 old_remote_content =
2407 &old_remote_description->description()->contents()[i];
2408 }
Steve Antondcc3c022017-12-22 16:02:54 -08002409 auto transceiver_or_error =
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002410 AssociateTransceiver(source, new_session.GetType(), i, new_content,
2411 old_local_content, old_remote_content);
Steve Antondcc3c022017-12-22 16:02:54 -08002412 if (!transceiver_or_error.ok()) {
2413 return transceiver_or_error.MoveError();
2414 }
2415 auto transceiver = transceiver_or_error.MoveValue();
Steve Antondcc3c022017-12-22 16:02:54 -08002416 RTCError error =
2417 UpdateTransceiverChannel(transceiver, new_content, bundle_group);
2418 if (!error.ok()) {
2419 return error;
2420 }
2421 } else if (media_type == cricket::MEDIA_TYPE_DATA) {
Steve Antonfa2260d2017-12-28 16:38:23 -08002422 if (GetDataMid() && new_content.name != *GetDataMid()) {
2423 // Ignore all but the first data section.
2424 continue;
2425 }
2426 RTCError error = UpdateDataChannel(source, new_content, bundle_group);
2427 if (!error.ok()) {
2428 return error;
2429 }
Steve Antondcc3c022017-12-22 16:02:54 -08002430 } else {
2431 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
2432 "Unknown section type.");
2433 }
2434 }
2435
2436 return RTCError::OK();
2437}
2438
2439RTCError PeerConnection::UpdateTransceiverChannel(
2440 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2441 transceiver,
2442 const cricket::ContentInfo& content,
2443 const cricket::ContentGroup* bundle_group) {
2444 RTC_DCHECK(IsUnifiedPlan());
2445 RTC_DCHECK(transceiver);
2446 cricket::BaseChannel* channel = transceiver->internal()->channel();
2447 if (content.rejected) {
2448 if (channel) {
2449 transceiver->internal()->SetChannel(nullptr);
2450 DestroyBaseChannel(channel);
2451 }
2452 } else {
2453 if (!channel) {
Steve Anton69470252018-02-09 11:43:08 -08002454 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Steve Antondcc3c022017-12-22 16:02:54 -08002455 channel = CreateVoiceChannel(
2456 content.name,
2457 GetTransportNameForMediaSection(content.name, bundle_group));
2458 } else {
Steve Anton69470252018-02-09 11:43:08 -08002459 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, transceiver->media_type());
Steve Antondcc3c022017-12-22 16:02:54 -08002460 channel = CreateVideoChannel(
2461 content.name,
2462 GetTransportNameForMediaSection(content.name, bundle_group));
2463 }
2464 if (!channel) {
2465 LOG_AND_RETURN_ERROR(
2466 RTCErrorType::INTERNAL_ERROR,
2467 "Failed to create channel for mid=" + content.name);
2468 }
2469 transceiver->internal()->SetChannel(channel);
2470 }
2471 }
2472 return RTCError::OK();
2473}
2474
Steve Antonfa2260d2017-12-28 16:38:23 -08002475RTCError PeerConnection::UpdateDataChannel(
2476 cricket::ContentSource source,
2477 const cricket::ContentInfo& content,
2478 const cricket::ContentGroup* bundle_group) {
2479 if (data_channel_type_ == cricket::DCT_NONE) {
Steve Antondbf9d032018-01-19 15:23:40 -08002480 // If data channels are disabled, ignore this media section. CreateAnswer
2481 // will take care of rejecting it.
2482 return RTCError::OK();
Steve Antonfa2260d2017-12-28 16:38:23 -08002483 }
2484 if (content.rejected) {
2485 DestroyDataChannel();
2486 } else {
2487 if (!rtp_data_channel_ && !sctp_transport_) {
2488 if (!CreateDataChannel(content.name, GetTransportNameForMediaSection(
2489 content.name, bundle_group))) {
2490 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
2491 "Failed to create data channel.");
2492 }
2493 }
2494 if (source == cricket::CS_REMOTE) {
2495 const MediaContentDescription* data_desc = content.media_description();
2496 if (data_desc && cricket::IsRtpProtocol(data_desc->protocol())) {
2497 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
2498 }
2499 }
2500 }
2501 return RTCError::OK();
2502}
2503
Steve Antondcc3c022017-12-22 16:02:54 -08002504RTCErrorOr<rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
2505PeerConnection::AssociateTransceiver(cricket::ContentSource source,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002506 SdpType type,
Steve Antondcc3c022017-12-22 16:02:54 -08002507 size_t mline_index,
2508 const ContentInfo& content,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002509 const ContentInfo* old_local_content,
2510 const ContentInfo* old_remote_content) {
Steve Antondcc3c022017-12-22 16:02:54 -08002511 RTC_DCHECK(IsUnifiedPlan());
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002512 // If this is an offer then the m= section might be recycled. If the m=
2513 // section is being recycled (defined as: rejected in the current local or
2514 // remote description and not rejected in new description), dissociate the
2515 // currently associated RtpTransceiver by setting its mid property to null,
2516 // and discard the mapping between the transceiver and its m= section index.
2517 if (IsMediaSectionBeingRecycled(type, content, old_local_content,
2518 old_remote_content)) {
2519 // We want to dissociate the transceiver that has the rejected mid.
2520 const std::string& old_mid =
2521 (old_local_content && old_local_content->rejected)
2522 ? old_local_content->name
2523 : old_remote_content->name;
2524 auto old_transceiver = GetAssociatedTransceiver(old_mid);
Steve Antondcc3c022017-12-22 16:02:54 -08002525 if (old_transceiver) {
2526 old_transceiver->internal()->set_mid(rtc::nullopt);
2527 old_transceiver->internal()->set_mline_index(rtc::nullopt);
2528 }
2529 }
2530 const MediaContentDescription* media_desc = content.media_description();
2531 auto transceiver = GetAssociatedTransceiver(content.name);
2532 if (source == cricket::CS_LOCAL) {
2533 // Find the RtpTransceiver that corresponds to this m= section, using the
2534 // mapping between transceivers and m= section indices established when
2535 // creating the offer.
2536 if (!transceiver) {
2537 transceiver = GetTransceiverByMLineIndex(mline_index);
2538 }
2539 if (!transceiver) {
2540 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2541 "Unknown transceiver");
2542 }
2543 } else {
2544 RTC_DCHECK_EQ(source, cricket::CS_REMOTE);
2545 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers
2546 // of the same type...
2547 if (!transceiver &&
2548 RtpTransceiverDirectionHasRecv(media_desc->direction())) {
2549 transceiver = FindAvailableTransceiverToReceive(media_desc->type());
2550 }
2551 // If no RtpTransceiver was found in the previous step, create one with a
2552 // recvonly direction.
2553 if (!transceiver) {
Steve Anton02ee47c2018-01-10 16:26:06 -08002554 auto sender =
2555 CreateSender(media_desc->type(), nullptr, {rtc::CreateRandomUuid()});
Steve Anton5f94aa22018-02-01 10:58:30 -08002556 std::string receiver_id;
2557 if (!media_desc->streams().empty()) {
2558 receiver_id = media_desc->streams()[0].id;
2559 } else {
2560 receiver_id = rtc::CreateRandomUuid();
2561 }
2562 auto receiver = CreateReceiver(media_desc->type(), receiver_id);
Steve Anton02ee47c2018-01-10 16:26:06 -08002563 transceiver = CreateAndAddTransceiver(sender, receiver);
Steve Antondcc3c022017-12-22 16:02:54 -08002564 transceiver->internal()->set_direction(
2565 RtpTransceiverDirection::kRecvOnly);
2566 }
2567 }
2568 RTC_DCHECK(transceiver);
Steve Anton69470252018-02-09 11:43:08 -08002569 if (transceiver->media_type() != media_desc->type()) {
Steve Antondcc3c022017-12-22 16:02:54 -08002570 LOG_AND_RETURN_ERROR(
2571 RTCErrorType::INVALID_PARAMETER,
2572 "Transceiver type does not match media description type.");
2573 }
2574 // Associate the found or created RtpTransceiver with the m= section by
2575 // setting the value of the RtpTransceiver's mid property to the MID of the m=
2576 // section, and establish a mapping between the transceiver and the index of
2577 // the m= section.
2578 transceiver->internal()->set_mid(content.name);
2579 transceiver->internal()->set_mline_index(mline_index);
2580 return std::move(transceiver);
2581}
2582
2583rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2584PeerConnection::GetAssociatedTransceiver(const std::string& mid) const {
2585 RTC_DCHECK(IsUnifiedPlan());
2586 for (auto transceiver : transceivers_) {
2587 if (transceiver->mid() == mid) {
2588 return transceiver;
2589 }
2590 }
2591 return nullptr;
2592}
2593
2594rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2595PeerConnection::GetTransceiverByMLineIndex(size_t mline_index) const {
2596 RTC_DCHECK(IsUnifiedPlan());
2597 for (auto transceiver : transceivers_) {
2598 if (transceiver->internal()->mline_index() == mline_index) {
2599 return transceiver;
2600 }
2601 }
2602 return nullptr;
2603}
2604
2605rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2606PeerConnection::FindAvailableTransceiverToReceive(
2607 cricket::MediaType media_type) const {
2608 RTC_DCHECK(IsUnifiedPlan());
2609 // From JSEP section 5.10 (Applying a Remote Description):
2610 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers of
2611 // the same type that were added to the PeerConnection by addTrack and are not
2612 // associated with any m= section and are not stopped, find the first such
2613 // RtpTransceiver.
2614 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08002615 if (transceiver->media_type() == media_type &&
Steve Antondcc3c022017-12-22 16:02:54 -08002616 transceiver->internal()->created_by_addtrack() && !transceiver->mid() &&
2617 !transceiver->stopped()) {
2618 return transceiver;
2619 }
2620 }
2621 return nullptr;
2622}
2623
Steve Antoned10bd92017-12-05 10:52:59 -08002624const cricket::ContentInfo* PeerConnection::FindMediaSectionForTransceiver(
2625 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2626 transceiver,
2627 const SessionDescriptionInterface* sdesc) const {
2628 RTC_DCHECK(transceiver);
2629 RTC_DCHECK(sdesc);
2630 if (IsUnifiedPlan()) {
2631 if (!transceiver->internal()->mid()) {
2632 // This transceiver is not associated with a media section yet.
2633 return nullptr;
2634 }
2635 return sdesc->description()->GetContentByName(
2636 *transceiver->internal()->mid());
2637 } else {
2638 // Plan B only allows at most one audio and one video section, so use the
2639 // first media section of that type.
2640 return cricket::GetFirstMediaContent(sdesc->description()->contents(),
Steve Anton69470252018-02-09 11:43:08 -08002641 transceiver->media_type());
Steve Antoned10bd92017-12-05 10:52:59 -08002642 }
2643}
2644
deadbeef46c73892016-11-16 19:42:04 -08002645PeerConnectionInterface::RTCConfiguration PeerConnection::GetConfiguration() {
2646 return configuration_;
2647}
2648
deadbeef293e9262017-01-11 12:28:30 -08002649bool PeerConnection::SetConfiguration(const RTCConfiguration& configuration,
2650 RTCError* error) {
Peter Boström1a9d6152015-12-08 22:15:17 +01002651 TRACE_EVENT0("webrtc", "PeerConnection::SetConfiguration");
deadbeef6de92f92016-12-12 18:49:32 -08002652
Steve Anton75737c02017-11-06 10:37:17 -08002653 if (local_description() && configuration.ice_candidate_pool_size !=
2654 configuration_.ice_candidate_pool_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002655 RTC_LOG(LS_ERROR) << "Can't change candidate pool size after calling "
2656 "SetLocalDescription.";
deadbeef293e9262017-01-11 12:28:30 -08002657 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00002658 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002659
deadbeef293e9262017-01-11 12:28:30 -08002660 // The simplest (and most future-compatible) way to tell if the config was
2661 // modified in an invalid way is to copy each property we do support
2662 // modifying, then use operator==. There are far more properties we don't
2663 // support modifying than those we do, and more could be added.
2664 RTCConfiguration modified_config = configuration_;
2665 modified_config.servers = configuration.servers;
2666 modified_config.type = configuration.type;
2667 modified_config.ice_candidate_pool_size =
2668 configuration.ice_candidate_pool_size;
2669 modified_config.prune_turn_ports = configuration.prune_turn_ports;
skvladd1f5fda2017-02-03 16:54:05 -08002670 modified_config.ice_check_min_interval = configuration.ice_check_min_interval;
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08002671 modified_config.stun_candidate_keepalive_interval =
2672 configuration.stun_candidate_keepalive_interval;
Jonas Orelandbdcee282017-10-10 14:01:40 +02002673 modified_config.turn_customizer = configuration.turn_customizer;
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08002674 modified_config.network_preference = configuration.network_preference;
deadbeef293e9262017-01-11 12:28:30 -08002675 if (configuration != modified_config) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002676 RTC_LOG(LS_ERROR) << "Modifying the configuration in an unsupported way.";
deadbeef293e9262017-01-11 12:28:30 -08002677 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
2678 }
2679
Steve Anton038834f2017-07-14 15:59:59 -07002680 // Validate the modified configuration.
2681 RTCError validate_error = ValidateConfiguration(modified_config);
2682 if (!validate_error.ok()) {
2683 return SafeSetError(std::move(validate_error), error);
2684 }
2685
deadbeef293e9262017-01-11 12:28:30 -08002686 // Note that this isn't possible through chromium, since it's an unsigned
2687 // short in WebIDL.
2688 if (configuration.ice_candidate_pool_size < 0 ||
2689 configuration.ice_candidate_pool_size > UINT16_MAX) {
2690 return SafeSetError(RTCErrorType::INVALID_RANGE, error);
2691 }
2692
2693 // Parse ICE servers before hopping to network thread.
2694 cricket::ServerAddresses stun_servers;
2695 std::vector<cricket::RelayServerConfig> turn_servers;
2696 RTCErrorType parse_error =
2697 ParseIceServers(configuration.servers, &stun_servers, &turn_servers);
2698 if (parse_error != RTCErrorType::NONE) {
2699 return SafeSetError(parse_error, error);
2700 }
2701
2702 // In theory this shouldn't fail.
2703 if (!network_thread()->Invoke<bool>(
2704 RTC_FROM_HERE,
2705 rtc::Bind(&PeerConnection::ReconfigurePortAllocator_n, this,
2706 stun_servers, turn_servers, modified_config.type,
2707 modified_config.ice_candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02002708 modified_config.prune_turn_ports,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08002709 modified_config.turn_customizer,
2710 modified_config.stun_candidate_keepalive_interval))) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002711 RTC_LOG(LS_ERROR) << "Failed to apply configuration to PortAllocator.";
deadbeef293e9262017-01-11 12:28:30 -08002712 return SafeSetError(RTCErrorType::INTERNAL_ERROR, error);
2713 }
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07002714
deadbeefd1a38b52016-12-10 13:15:33 -08002715 // As described in JSEP, calling setConfiguration with new ICE servers or
2716 // candidate policy must set a "needs-ice-restart" bit so that the next offer
2717 // triggers an ICE restart which will pick up the changes.
deadbeef293e9262017-01-11 12:28:30 -08002718 if (modified_config.servers != configuration_.servers ||
2719 modified_config.type != configuration_.type ||
2720 modified_config.prune_turn_ports != configuration_.prune_turn_ports) {
Steve Antond25da372017-11-06 14:50:29 -08002721 transport_controller_->SetNeedsIceRestartFlag();
deadbeefd1a38b52016-12-10 13:15:33 -08002722 }
skvladd1f5fda2017-02-03 16:54:05 -08002723
Qingsi Wang9c98f0c2018-02-15 15:10:59 -08002724 transport_controller_->SetIceConfig(ParseIceConfig(modified_config));
skvladd1f5fda2017-02-03 16:54:05 -08002725
deadbeef293e9262017-01-11 12:28:30 -08002726 configuration_ = modified_config;
2727 return SafeSetError(RTCErrorType::NONE, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00002728}
2729
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002730bool PeerConnection::AddIceCandidate(
2731 const IceCandidateInterface* ice_candidate) {
Peter Boström1a9d6152015-12-08 22:15:17 +01002732 TRACE_EVENT0("webrtc", "PeerConnection::AddIceCandidate");
zhihuang29ff8442016-07-27 11:07:25 -07002733 if (IsClosed()) {
2734 return false;
2735 }
Steve Antond25da372017-11-06 14:50:29 -08002736
2737 if (!remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002738 RTC_LOG(LS_ERROR) << "ProcessIceMessage: ICE candidates can't be added "
Jonas Olsson45cc8902018-02-13 10:37:07 +01002739 "without any remote session description.";
Steve Antond25da372017-11-06 14:50:29 -08002740 return false;
2741 }
2742
2743 if (!ice_candidate) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002744 RTC_LOG(LS_ERROR) << "ProcessIceMessage: Candidate is NULL.";
Steve Antond25da372017-11-06 14:50:29 -08002745 return false;
2746 }
2747
2748 bool valid = false;
2749 bool ready = ReadyToUseRemoteCandidate(ice_candidate, nullptr, &valid);
2750 if (!valid) {
2751 return false;
2752 }
2753
2754 // Add this candidate to the remote session description.
2755 if (!mutable_remote_description()->AddCandidate(ice_candidate)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002756 RTC_LOG(LS_ERROR) << "ProcessIceMessage: Candidate cannot be used.";
Steve Antond25da372017-11-06 14:50:29 -08002757 return false;
2758 }
2759
2760 if (ready) {
2761 return UseCandidate(ice_candidate);
2762 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002763 RTC_LOG(LS_INFO) << "ProcessIceMessage: Not ready to use candidate.";
Steve Antond25da372017-11-06 14:50:29 -08002764 return true;
2765 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002766}
2767
Honghai Zhang7fb69db2016-03-14 11:59:18 -07002768bool PeerConnection::RemoveIceCandidates(
2769 const std::vector<cricket::Candidate>& candidates) {
2770 TRACE_EVENT0("webrtc", "PeerConnection::RemoveIceCandidates");
Steve Antond25da372017-11-06 14:50:29 -08002771 if (!remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002772 RTC_LOG(LS_ERROR) << "RemoveRemoteIceCandidates: ICE candidates can't be "
Jonas Olsson45cc8902018-02-13 10:37:07 +01002773 "removed without any remote session description.";
Steve Antond25da372017-11-06 14:50:29 -08002774 return false;
2775 }
2776
2777 if (candidates.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002778 RTC_LOG(LS_ERROR) << "RemoveRemoteIceCandidates: candidates are empty.";
Steve Antond25da372017-11-06 14:50:29 -08002779 return false;
2780 }
2781
2782 size_t number_removed =
2783 mutable_remote_description()->RemoveCandidates(candidates);
2784 if (number_removed != candidates.size()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002785 RTC_LOG(LS_ERROR)
2786 << "RemoveRemoteIceCandidates: Failed to remove candidates. "
Jonas Olsson45cc8902018-02-13 10:37:07 +01002787 "Requested "
2788 << candidates.size() << " but only " << number_removed
Mirko Bonadei675513b2017-11-09 11:09:25 +01002789 << " are removed.";
Steve Antond25da372017-11-06 14:50:29 -08002790 }
2791
2792 // Remove the candidates from the transport controller.
2793 std::string error;
2794 bool res = transport_controller_->RemoveRemoteCandidates(candidates, &error);
2795 if (!res && !error.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002796 RTC_LOG(LS_ERROR) << "Error when removing remote candidates: " << error;
Steve Antond25da372017-11-06 14:50:29 -08002797 }
2798 return true;
Honghai Zhang7fb69db2016-03-14 11:59:18 -07002799}
2800
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00002801void PeerConnection::RegisterUMAObserver(UMAObserver* observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +01002802 TRACE_EVENT0("webrtc", "PeerConnection::RegisterUmaObserver");
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00002803 uma_observer_ = observer;
guoweis@webrtc.org7169afd2014-12-04 17:59:29 +00002804
Steve Anton75737c02017-11-06 10:37:17 -08002805 if (transport_controller()) {
2806 transport_controller()->SetMetricsObserver(uma_observer_);
guoweis@webrtc.org7169afd2014-12-04 17:59:29 +00002807 }
2808
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00002809 // Send information about IPv4/IPv6 status.
deadbeef293e9262017-01-11 12:28:30 -08002810 if (uma_observer_) {
Honghai Zhangd93f50c2016-10-05 11:47:22 -07002811 port_allocator_->SetMetricsObserver(uma_observer_);
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00002812 if (port_allocator_->flags() & cricket::PORTALLOCATOR_ENABLE_IPV6) {
Guo-wei Shiehdfbe6792015-09-03 17:12:07 -07002813 uma_observer_->IncrementEnumCounter(
2814 kEnumCounterAddressFamily, kPeerConnection_IPv6,
2815 kPeerConnectionAddressFamilyCounter_Max);
mallinath@webrtc.orgb445f262014-05-23 22:19:37 +00002816 } else {
Guo-wei Shiehdfbe6792015-09-03 17:12:07 -07002817 uma_observer_->IncrementEnumCounter(
2818 kEnumCounterAddressFamily, kPeerConnection_IPv4,
2819 kPeerConnectionAddressFamilyCounter_Max);
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00002820 }
Harald Alvestrand5dbb5862018-02-13 23:48:00 +01002821 // Send information about the requested SDP semantics.
2822 switch (configuration_.sdp_semantics) {
2823 case SdpSemantics::kDefault:
2824 uma_observer_->IncrementEnumCounter(kEnumCounterSdpSemanticRequested,
2825 kSdpSemanticRequestDefault,
2826 kSdpSemanticRequestMax);
2827
2828 break;
2829 case SdpSemantics::kPlanB:
2830 uma_observer_->IncrementEnumCounter(kEnumCounterSdpSemanticRequested,
2831 kSdpSemanticRequestPlanB,
2832 kSdpSemanticRequestMax);
2833 break;
2834 case SdpSemantics::kUnifiedPlan:
2835 uma_observer_->IncrementEnumCounter(kEnumCounterSdpSemanticRequested,
2836 kSdpSemanticRequestUnifiedPlan,
2837 kSdpSemanticRequestMax);
2838 break;
2839 default:
2840 RTC_NOTREACHED();
2841 }
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00002842 }
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00002843}
2844
zstein4b979802017-06-02 14:37:37 -07002845RTCError PeerConnection::SetBitrate(const BitrateParameters& bitrate) {
Steve Anton978b8762017-09-29 12:15:02 -07002846 if (!worker_thread()->IsCurrent()) {
2847 return worker_thread()->Invoke<RTCError>(
zstein4b979802017-06-02 14:37:37 -07002848 RTC_FROM_HERE, rtc::Bind(&PeerConnection::SetBitrate, this, bitrate));
2849 }
2850
2851 const bool has_min = static_cast<bool>(bitrate.min_bitrate_bps);
2852 const bool has_current = static_cast<bool>(bitrate.current_bitrate_bps);
2853 const bool has_max = static_cast<bool>(bitrate.max_bitrate_bps);
2854 if (has_min && *bitrate.min_bitrate_bps < 0) {
2855 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2856 "min_bitrate_bps <= 0");
2857 }
2858 if (has_current) {
2859 if (has_min && *bitrate.current_bitrate_bps < *bitrate.min_bitrate_bps) {
2860 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2861 "current_bitrate_bps < min_bitrate_bps");
2862 } else if (*bitrate.current_bitrate_bps < 0) {
2863 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2864 "curent_bitrate_bps < 0");
2865 }
2866 }
2867 if (has_max) {
2868 if (has_current &&
2869 *bitrate.max_bitrate_bps < *bitrate.current_bitrate_bps) {
2870 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2871 "max_bitrate_bps < current_bitrate_bps");
2872 } else if (has_min && *bitrate.max_bitrate_bps < *bitrate.min_bitrate_bps) {
2873 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2874 "max_bitrate_bps < min_bitrate_bps");
2875 } else if (*bitrate.max_bitrate_bps < 0) {
2876 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2877 "max_bitrate_bps < 0");
2878 }
2879 }
2880
Sebastian Janssonfc8d26b2018-02-21 09:52:06 +01002881 BitrateConstraintsMask mask;
zstein4b979802017-06-02 14:37:37 -07002882 mask.min_bitrate_bps = bitrate.min_bitrate_bps;
2883 mask.start_bitrate_bps = bitrate.current_bitrate_bps;
2884 mask.max_bitrate_bps = bitrate.max_bitrate_bps;
2885
2886 RTC_DCHECK(call_.get());
Sebastian Jansson8f83b422018-02-21 13:07:13 +01002887 call_->GetTransportControllerSend()->SetClientBitratePreferences(mask);
zstein4b979802017-06-02 14:37:37 -07002888
2889 return RTCError::OK();
2890}
2891
Alex Narest78609d52017-10-20 10:37:47 +02002892void PeerConnection::SetBitrateAllocationStrategy(
2893 std::unique_ptr<rtc::BitrateAllocationStrategy>
2894 bitrate_allocation_strategy) {
2895 rtc::Thread* worker_thread = factory_->worker_thread();
2896 if (!worker_thread->IsCurrent()) {
2897 rtc::BitrateAllocationStrategy* strategy_raw =
2898 bitrate_allocation_strategy.release();
2899 auto functor = [this, strategy_raw]() {
2900 call_->SetBitrateAllocationStrategy(
2901 rtc::WrapUnique<rtc::BitrateAllocationStrategy>(strategy_raw));
2902 };
2903 worker_thread->Invoke<void>(RTC_FROM_HERE, functor);
2904 return;
2905 }
2906 RTC_DCHECK(call_.get());
2907 call_->SetBitrateAllocationStrategy(std::move(bitrate_allocation_strategy));
2908}
2909
henrika5f6bf242017-11-01 11:06:56 +01002910void PeerConnection::SetAudioPlayout(bool playout) {
2911 if (!worker_thread()->IsCurrent()) {
2912 worker_thread()->Invoke<void>(
2913 RTC_FROM_HERE,
2914 rtc::Bind(&PeerConnection::SetAudioPlayout, this, playout));
2915 return;
2916 }
2917 auto audio_state =
2918 factory_->channel_manager()->media_engine()->GetAudioState();
2919 audio_state->SetPlayout(playout);
2920}
2921
2922void PeerConnection::SetAudioRecording(bool recording) {
2923 if (!worker_thread()->IsCurrent()) {
2924 worker_thread()->Invoke<void>(
2925 RTC_FROM_HERE,
2926 rtc::Bind(&PeerConnection::SetAudioRecording, this, recording));
2927 return;
2928 }
2929 auto audio_state =
2930 factory_->channel_manager()->media_engine()->GetAudioState();
2931 audio_state->SetRecording(recording);
2932}
2933
Steve Anton8c0f7a72017-10-03 10:03:10 -07002934std::unique_ptr<rtc::SSLCertificate>
2935PeerConnection::GetRemoteAudioSSLCertificate() {
Taylor Brandstetterc3928662018-02-23 13:04:51 -08002936 std::unique_ptr<rtc::SSLCertChain> chain = GetRemoteAudioSSLCertChain();
2937 if (!chain || !chain->GetSize()) {
Steve Anton8c0f7a72017-10-03 10:03:10 -07002938 return nullptr;
2939 }
Taylor Brandstetterc3928662018-02-23 13:04:51 -08002940 return chain->Get(0).GetUniqueReference();
Steve Anton8c0f7a72017-10-03 10:03:10 -07002941}
2942
Zhi Huang70b820f2018-01-27 14:16:15 -08002943std::unique_ptr<rtc::SSLCertChain>
2944PeerConnection::GetRemoteAudioSSLCertChain() {
Steve Antonafb0bb72018-02-20 11:35:37 -08002945 auto audio_transceiver = GetFirstAudioTransceiver();
2946 if (!audio_transceiver || !audio_transceiver->internal()->channel()) {
Zhi Huang70b820f2018-01-27 14:16:15 -08002947 return nullptr;
2948 }
Zhi Huang70b820f2018-01-27 14:16:15 -08002949 return transport_controller_->GetRemoteSSLCertChain(
Steve Antonafb0bb72018-02-20 11:35:37 -08002950 audio_transceiver->internal()->channel()->transport_name());
2951}
2952
2953rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2954PeerConnection::GetFirstAudioTransceiver() const {
2955 for (auto transceiver : transceivers_) {
2956 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
2957 return transceiver;
2958 }
2959 }
2960 return nullptr;
Zhi Huang70b820f2018-01-27 14:16:15 -08002961}
2962
ivoc14d5dbe2016-07-04 07:06:55 -07002963bool PeerConnection::StartRtcEventLog(rtc::PlatformFile file,
2964 int64_t max_size_bytes) {
Elad Alon99c3fe52017-10-13 16:29:40 +02002965 // TODO(eladalon): It would be better to not allow negative values into PC.
2966 const size_t max_size = (max_size_bytes < 0)
2967 ? RtcEventLog::kUnlimitedOutput
2968 : rtc::saturated_cast<size_t>(max_size_bytes);
2969 return StartRtcEventLog(
Bjorn Tereliusde939432017-11-20 17:38:14 +01002970 rtc::MakeUnique<RtcEventLogOutputFile>(file, max_size),
2971 webrtc::RtcEventLog::kImmediateOutput);
Elad Alon99c3fe52017-10-13 16:29:40 +02002972}
2973
Bjorn Tereliusde939432017-11-20 17:38:14 +01002974bool PeerConnection::StartRtcEventLog(std::unique_ptr<RtcEventLogOutput> output,
2975 int64_t output_period_ms) {
Karl Wibergd6b48192017-10-16 23:01:06 +02002976 // TODO(eladalon): In C++14, this can be done with a lambda.
2977 struct Functor {
Bjorn Tereliusde939432017-11-20 17:38:14 +01002978 bool operator()() {
2979 return pc->StartRtcEventLog_w(std::move(output), output_period_ms);
2980 }
Karl Wibergd6b48192017-10-16 23:01:06 +02002981 PeerConnection* const pc;
2982 std::unique_ptr<RtcEventLogOutput> output;
Bjorn Tereliusde939432017-11-20 17:38:14 +01002983 const int64_t output_period_ms;
Elad Alon99c3fe52017-10-13 16:29:40 +02002984 };
Bjorn Tereliusde939432017-11-20 17:38:14 +01002985 return worker_thread()->Invoke<bool>(
2986 RTC_FROM_HERE, Functor{this, std::move(output), output_period_ms});
ivoc14d5dbe2016-07-04 07:06:55 -07002987}
2988
2989void PeerConnection::StopRtcEventLog() {
Steve Anton978b8762017-09-29 12:15:02 -07002990 worker_thread()->Invoke<void>(
ivoc14d5dbe2016-07-04 07:06:55 -07002991 RTC_FROM_HERE, rtc::Bind(&PeerConnection::StopRtcEventLog_w, this));
2992}
2993
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002994const SessionDescriptionInterface* PeerConnection::local_description() const {
Steve Anton75737c02017-11-06 10:37:17 -08002995 return pending_local_description_ ? pending_local_description_.get()
2996 : current_local_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002997}
2998
2999const SessionDescriptionInterface* PeerConnection::remote_description() const {
Steve Anton75737c02017-11-06 10:37:17 -08003000 return pending_remote_description_ ? pending_remote_description_.get()
3001 : current_remote_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003002}
3003
deadbeeffe4a8a42016-12-20 17:56:17 -08003004const SessionDescriptionInterface* PeerConnection::current_local_description()
3005 const {
Steve Anton75737c02017-11-06 10:37:17 -08003006 return current_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003007}
3008
3009const SessionDescriptionInterface* PeerConnection::current_remote_description()
3010 const {
Steve Anton75737c02017-11-06 10:37:17 -08003011 return current_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003012}
3013
3014const SessionDescriptionInterface* PeerConnection::pending_local_description()
3015 const {
Steve Anton75737c02017-11-06 10:37:17 -08003016 return pending_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003017}
3018
3019const SessionDescriptionInterface* PeerConnection::pending_remote_description()
3020 const {
Steve Anton75737c02017-11-06 10:37:17 -08003021 return pending_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003022}
3023
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003024void PeerConnection::Close() {
Peter Boström1a9d6152015-12-08 22:15:17 +01003025 TRACE_EVENT0("webrtc", "PeerConnection::Close");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003026 // Update stats here so that we have the most recent stats for tracks and
3027 // streams before the channels are closed.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00003028 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003029
Steve Anton75737c02017-11-06 10:37:17 -08003030 ChangeSignalingState(PeerConnectionInterface::kClosed);
Steve Anton3fe1b152017-12-12 10:20:08 -08003031
Steve Anton8af21862017-12-15 11:20:13 -08003032 for (auto transceiver : transceivers_) {
3033 transceiver->Stop();
3034 }
3035 DestroyAllChannels();
Steve Anton75737c02017-11-06 10:37:17 -08003036
Qingsi Wang93a84392018-01-30 17:13:09 -08003037 // The event log is used in the transport controller, which must be outlived
3038 // by the former. CreateOffer by the peer connection is implemented
3039 // asynchronously and if the peer connection is closed without resetting the
3040 // WebRTC session description factory, the session description factory would
3041 // call the transport controller.
3042 webrtc_session_desc_factory_.reset();
3043 transport_controller_.reset();
3044
deadbeef42a42632017-03-10 15:18:00 -08003045 network_thread()->Invoke<void>(
3046 RTC_FROM_HERE,
3047 rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
3048 port_allocator_.get()));
nisseeaabdf62017-05-05 02:23:02 -07003049
Steve Anton978b8762017-09-29 12:15:02 -07003050 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
eladalon248fd4f2017-09-06 05:18:15 -07003051 call_.reset();
3052 // The event log must outlive call (and any other object that uses it).
3053 event_log_.reset();
3054 });
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003055}
3056
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003057void PeerConnection::OnMessage(rtc::Message* msg) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003058 switch (msg->message_id) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003059 case MSG_SET_SESSIONDESCRIPTION_SUCCESS: {
3060 SetSessionDescriptionMsg* param =
3061 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
3062 param->observer->OnSuccess();
3063 delete param;
3064 break;
3065 }
3066 case MSG_SET_SESSIONDESCRIPTION_FAILED: {
3067 SetSessionDescriptionMsg* param =
3068 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
3069 param->observer->OnFailure(param->error);
3070 delete param;
3071 break;
3072 }
deadbeefab9b2d12015-10-14 11:33:11 -07003073 case MSG_CREATE_SESSIONDESCRIPTION_FAILED: {
3074 CreateSessionDescriptionMsg* param =
3075 static_cast<CreateSessionDescriptionMsg*>(msg->pdata);
3076 param->observer->OnFailure(param->error);
3077 delete param;
3078 break;
3079 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003080 case MSG_GETSTATS: {
3081 GetStatsMsg* param = static_cast<GetStatsMsg*>(msg->pdata);
nissee8abe3e2017-01-18 05:00:34 -08003082 StatsReports reports;
3083 stats_->GetStats(param->track, &reports);
3084 param->observer->OnComplete(reports);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003085 delete param;
3086 break;
3087 }
deadbeefbd292462015-12-14 18:15:29 -08003088 case MSG_FREE_DATACHANNELS: {
3089 sctp_data_channels_to_free_.clear();
3090 break;
3091 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003092 default:
nisseeb4ca4e2017-01-12 02:24:27 -08003093 RTC_NOTREACHED() << "Not implemented";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003094 break;
3095 }
3096}
3097
Steve Antonafb0bb72018-02-20 11:35:37 -08003098cricket::VoiceMediaChannel* PeerConnection::voice_media_channel() const {
3099 RTC_DCHECK(!IsUnifiedPlan());
3100 auto* voice_channel = static_cast<cricket::VoiceChannel*>(
3101 GetAudioTransceiver()->internal()->channel());
3102 if (voice_channel) {
3103 return voice_channel->media_channel();
3104 } else {
3105 return nullptr;
3106 }
3107}
3108
3109cricket::VideoMediaChannel* PeerConnection::video_media_channel() const {
3110 RTC_DCHECK(!IsUnifiedPlan());
3111 auto* video_channel = static_cast<cricket::VideoChannel*>(
3112 GetVideoTransceiver()->internal()->channel());
3113 if (video_channel) {
3114 return video_channel->media_channel();
3115 } else {
3116 return nullptr;
3117 }
3118}
3119
Steve Anton4171afb2017-11-20 10:20:22 -08003120void PeerConnection::CreateAudioReceiver(
3121 MediaStreamInterface* stream,
3122 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01003123 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
3124 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Steve Antond3679212018-01-17 17:41:02 -08003125 auto* audio_receiver = new AudioRtpReceiver(
3126 worker_thread(), remote_sender_info.sender_id, streams);
Steve Anton57858b32018-02-15 15:19:50 -08003127 audio_receiver->SetVoiceMediaChannel(voice_media_channel());
Steve Antond3679212018-01-17 17:41:02 -08003128 audio_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
3129 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
3130 signaling_thread(), audio_receiver);
Steve Anton4171afb2017-11-20 10:20:22 -08003131 GetAudioTransceiver()->internal()->AddReceiver(receiver);
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01003132 observer_->OnAddTrack(receiver, std::move(streams));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003133}
3134
Steve Anton4171afb2017-11-20 10:20:22 -08003135void PeerConnection::CreateVideoReceiver(
3136 MediaStreamInterface* stream,
3137 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01003138 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
3139 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Steve Antond3679212018-01-17 17:41:02 -08003140 auto* video_receiver = new VideoRtpReceiver(
3141 worker_thread(), remote_sender_info.sender_id, streams);
Steve Anton57858b32018-02-15 15:19:50 -08003142 video_receiver->SetVideoMediaChannel(video_media_channel());
Steve Antond3679212018-01-17 17:41:02 -08003143 video_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
3144 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
3145 signaling_thread(), video_receiver);
Steve Anton4171afb2017-11-20 10:20:22 -08003146 GetVideoTransceiver()->internal()->AddReceiver(receiver);
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01003147 observer_->OnAddTrack(receiver, std::move(streams));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003148}
3149
deadbeef70ab1a12015-09-28 16:53:55 -07003150// TODO(deadbeef): Keep RtpReceivers around even if track goes away in remote
3151// description.
Henrik Boström933d8b02017-10-10 10:05:16 -07003152rtc::scoped_refptr<RtpReceiverInterface> PeerConnection::RemoveAndStopReceiver(
Steve Anton4171afb2017-11-20 10:20:22 -08003153 const RtpSenderInfo& remote_sender_info) {
3154 auto receiver = FindReceiverById(remote_sender_info.sender_id);
3155 if (!receiver) {
3156 RTC_LOG(LS_WARNING) << "RtpReceiver for track with id "
3157 << remote_sender_info.sender_id << " doesn't exist.";
Henrik Boström933d8b02017-10-10 10:05:16 -07003158 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07003159 }
Steve Anton4171afb2017-11-20 10:20:22 -08003160 if (receiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
3161 GetAudioTransceiver()->internal()->RemoveReceiver(receiver);
3162 } else {
3163 GetVideoTransceiver()->internal()->RemoveReceiver(receiver);
3164 }
Henrik Boström933d8b02017-10-10 10:05:16 -07003165 return receiver;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003166}
3167
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003168void PeerConnection::AddAudioTrack(AudioTrackInterface* track,
3169 MediaStreamInterface* stream) {
3170 RTC_DCHECK(!IsClosed());
3171 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003172 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003173 // We already have a sender for this track, so just change the stream_id
3174 // so that it's correct in the next call to CreateOffer.
Steve Anton4171afb2017-11-20 10:20:22 -08003175 sender->internal()->set_stream_id(stream->label());
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003176 return;
3177 }
3178
3179 // Normal case; we've never seen this track before.
Steve Anton02ee47c2018-01-10 16:26:06 -08003180 auto new_sender =
3181 CreateSender(cricket::MEDIA_TYPE_AUDIO, track, {stream->label()});
Steve Anton57858b32018-02-15 15:19:50 -08003182 new_sender->internal()->SetVoiceMediaChannel(voice_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08003183 GetAudioTransceiver()->internal()->AddSender(new_sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003184 // If the sender has already been configured in SDP, we call SetSsrc,
3185 // which will connect the sender to the underlying transport. This can
3186 // occur if a local session description that contains the ID of the sender
3187 // is set before AddStream is called. It can also occur if the local
3188 // session description is not changed and RemoveStream is called, and
3189 // later AddStream is called again with the same stream.
Steve Anton4171afb2017-11-20 10:20:22 -08003190 const RtpSenderInfo* sender_info =
3191 FindSenderInfo(local_audio_sender_infos_, stream->label(), track->id());
3192 if (sender_info) {
3193 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003194 }
3195}
3196
3197// TODO(deadbeef): Don't destroy RtpSenders here; they should be kept around
3198// indefinitely, when we have unified plan SDP.
3199void PeerConnection::RemoveAudioTrack(AudioTrackInterface* track,
3200 MediaStreamInterface* stream) {
3201 RTC_DCHECK(!IsClosed());
3202 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003203 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003204 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
3205 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003206 return;
3207 }
Steve Anton4171afb2017-11-20 10:20:22 -08003208 GetAudioTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003209}
3210
3211void PeerConnection::AddVideoTrack(VideoTrackInterface* track,
3212 MediaStreamInterface* stream) {
3213 RTC_DCHECK(!IsClosed());
3214 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003215 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003216 // We already have a sender for this track, so just change the stream_id
3217 // so that it's correct in the next call to CreateOffer.
Steve Anton4171afb2017-11-20 10:20:22 -08003218 sender->internal()->set_stream_id(stream->label());
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003219 return;
3220 }
3221
3222 // Normal case; we've never seen this track before.
Steve Anton02ee47c2018-01-10 16:26:06 -08003223 auto new_sender =
3224 CreateSender(cricket::MEDIA_TYPE_VIDEO, track, {stream->label()});
Steve Anton57858b32018-02-15 15:19:50 -08003225 new_sender->internal()->SetVideoMediaChannel(video_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08003226 GetVideoTransceiver()->internal()->AddSender(new_sender);
3227 const RtpSenderInfo* sender_info =
3228 FindSenderInfo(local_video_sender_infos_, stream->label(), track->id());
3229 if (sender_info) {
3230 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003231 }
3232}
3233
3234void PeerConnection::RemoveVideoTrack(VideoTrackInterface* track,
3235 MediaStreamInterface* stream) {
3236 RTC_DCHECK(!IsClosed());
3237 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003238 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003239 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
3240 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003241 return;
3242 }
Steve Anton4171afb2017-11-20 10:20:22 -08003243 GetVideoTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003244}
3245
Steve Antonba818672017-11-06 10:21:57 -08003246void PeerConnection::SetIceConnectionState(IceConnectionState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07003247 RTC_DCHECK(signaling_thread()->IsCurrent());
Steve Antonba818672017-11-06 10:21:57 -08003248 if (ice_connection_state_ == new_state) {
3249 return;
3250 }
3251
deadbeefcbecd352015-09-23 11:50:27 -07003252 // After transitioning to "closed", ignore any additional states from
Steve Antonba818672017-11-06 10:21:57 -08003253 // TransportController (such as "disconnected").
deadbeefab9b2d12015-10-14 11:33:11 -07003254 if (IsClosed()) {
deadbeefcbecd352015-09-23 11:50:27 -07003255 return;
3256 }
Steve Antonba818672017-11-06 10:21:57 -08003257
Mirko Bonadei675513b2017-11-09 11:09:25 +01003258 RTC_LOG(LS_INFO) << "Changing IceConnectionState " << ice_connection_state_
3259 << " => " << new_state;
Steve Antonba818672017-11-06 10:21:57 -08003260 RTC_DCHECK(ice_connection_state_ !=
3261 PeerConnectionInterface::kIceConnectionClosed);
3262
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003263 ice_connection_state_ = new_state;
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00003264 observer_->OnIceConnectionChange(ice_connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003265}
3266
3267void PeerConnection::OnIceGatheringChange(
3268 PeerConnectionInterface::IceGatheringState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07003269 RTC_DCHECK(signaling_thread()->IsCurrent());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003270 if (IsClosed()) {
3271 return;
3272 }
3273 ice_gathering_state_ = new_state;
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00003274 observer_->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003275}
3276
jbauch81bf7b02017-03-25 08:31:12 -07003277void PeerConnection::OnIceCandidate(
3278 std::unique_ptr<IceCandidateInterface> candidate) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07003279 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07003280 if (IsClosed()) {
3281 return;
3282 }
jbauch81bf7b02017-03-25 08:31:12 -07003283 observer_->OnIceCandidate(candidate.get());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003284}
3285
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003286void PeerConnection::OnIceCandidatesRemoved(
3287 const std::vector<cricket::Candidate>& candidates) {
3288 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07003289 if (IsClosed()) {
3290 return;
3291 }
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003292 observer_->OnIceCandidatesRemoved(candidates);
3293}
3294
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003295void PeerConnection::ChangeSignalingState(
3296 PeerConnectionInterface::SignalingState signaling_state) {
Steve Antonba818672017-11-06 10:21:57 -08003297 RTC_DCHECK(signaling_thread()->IsCurrent());
3298 if (signaling_state_ == signaling_state) {
3299 return;
3300 }
Mirko Bonadei675513b2017-11-09 11:09:25 +01003301 RTC_LOG(LS_INFO) << "Session: " << session_id() << " Old state: "
3302 << GetSignalingStateString(signaling_state_)
3303 << " New state: "
3304 << GetSignalingStateString(signaling_state);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003305 signaling_state_ = signaling_state;
3306 if (signaling_state == kClosed) {
3307 ice_connection_state_ = kIceConnectionClosed;
3308 observer_->OnIceConnectionChange(ice_connection_state_);
3309 if (ice_gathering_state_ != kIceGatheringComplete) {
3310 ice_gathering_state_ = kIceGatheringComplete;
3311 observer_->OnIceGatheringChange(ice_gathering_state_);
3312 }
3313 }
3314 observer_->OnSignalingChange(signaling_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003315}
3316
deadbeefeb459812015-12-15 19:24:43 -08003317void PeerConnection::OnAudioTrackAdded(AudioTrackInterface* track,
3318 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003319 if (IsClosed()) {
3320 return;
3321 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003322 AddAudioTrack(track, stream);
3323 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003324}
3325
deadbeefeb459812015-12-15 19:24:43 -08003326void PeerConnection::OnAudioTrackRemoved(AudioTrackInterface* track,
3327 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003328 if (IsClosed()) {
3329 return;
3330 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003331 RemoveAudioTrack(track, stream);
3332 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003333}
3334
3335void PeerConnection::OnVideoTrackAdded(VideoTrackInterface* track,
3336 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003337 if (IsClosed()) {
3338 return;
3339 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003340 AddVideoTrack(track, stream);
3341 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003342}
3343
3344void PeerConnection::OnVideoTrackRemoved(VideoTrackInterface* track,
3345 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003346 if (IsClosed()) {
3347 return;
3348 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003349 RemoveVideoTrack(track, stream);
3350 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003351}
3352
Henrik Boström31638672017-11-23 17:48:32 +01003353void PeerConnection::PostSetSessionDescriptionSuccess(
3354 SetSessionDescriptionObserver* observer) {
3355 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
3356 signaling_thread()->Post(RTC_FROM_HERE, this,
3357 MSG_SET_SESSIONDESCRIPTION_SUCCESS, msg);
3358}
3359
deadbeefab9b2d12015-10-14 11:33:11 -07003360void PeerConnection::PostSetSessionDescriptionFailure(
3361 SetSessionDescriptionObserver* observer,
3362 const std::string& error) {
3363 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
3364 msg->error = error;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07003365 signaling_thread()->Post(RTC_FROM_HERE, this,
3366 MSG_SET_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07003367}
3368
3369void PeerConnection::PostCreateSessionDescriptionFailure(
3370 CreateSessionDescriptionObserver* observer,
3371 const std::string& error) {
3372 CreateSessionDescriptionMsg* msg = new CreateSessionDescriptionMsg(observer);
3373 msg->error = error;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07003374 signaling_thread()->Post(RTC_FROM_HERE, this,
3375 MSG_CREATE_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07003376}
3377
zhihuang1c378ed2017-08-17 14:10:50 -07003378void PeerConnection::GetOptionsForOffer(
Steve Antondcc3c022017-12-22 16:02:54 -08003379 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
deadbeefab9b2d12015-10-14 11:33:11 -07003380 cricket::MediaSessionOptions* session_options) {
Steve Antondcc3c022017-12-22 16:02:54 -08003381 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
zhihuang1c378ed2017-08-17 14:10:50 -07003382
Steve Antondcc3c022017-12-22 16:02:54 -08003383 if (IsUnifiedPlan()) {
3384 GetOptionsForUnifiedPlanOffer(offer_answer_options, session_options);
3385 } else {
3386 GetOptionsForPlanBOffer(offer_answer_options, session_options);
3387 }
3388
Steve Antonfa2260d2017-12-28 16:38:23 -08003389 // Intentionally unset the data channel type for RTP data channel with the
3390 // second condition. Otherwise the RTP data channels would be successfully
3391 // negotiated by default and the unit tests in WebRtcDataBrowserTest will fail
3392 // when building with chromium. We want to leave RTP data channels broken, so
3393 // people won't try to use them.
3394 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
3395 session_options->data_channel_type = data_channel_type();
3396 }
3397
Steve Antondcc3c022017-12-22 16:02:54 -08003398 // Apply ICE restart flag and renomination flag.
3399 for (auto& options : session_options->media_description_options) {
3400 options.transport_options.ice_restart = offer_answer_options.ice_restart;
3401 options.transport_options.enable_ice_renomination =
3402 configuration_.enable_ice_renomination;
3403 }
3404
3405 session_options->rtcp_cname = rtcp_cname_;
3406 session_options->crypto_options = factory_->options().crypto_options;
Steve Antone831b8c2018-02-01 12:22:16 -08003407 session_options->is_unified_plan = IsUnifiedPlan();
Steve Antondcc3c022017-12-22 16:02:54 -08003408}
3409
3410void PeerConnection::GetOptionsForPlanBOffer(
3411 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
3412 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07003413 // Figure out transceiver directional preferences.
3414 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
3415 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
3416
3417 // By default, generate sendrecv/recvonly m= sections.
3418 bool recv_audio = true;
3419 bool recv_video = true;
3420
3421 // By default, only offer a new m= section if we have media to send with it.
3422 bool offer_new_audio_description = send_audio;
3423 bool offer_new_video_description = send_video;
3424 bool offer_new_data_description = HasDataChannels();
3425
3426 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-22 16:02:54 -08003427 if (offer_answer_options.offer_to_receive_audio !=
3428 RTCOfferAnswerOptions::kUndefined) {
3429 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003430 offer_new_audio_description =
Steve Antondcc3c022017-12-22 16:02:54 -08003431 offer_new_audio_description ||
3432 (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003433 }
Steve Antondcc3c022017-12-22 16:02:54 -08003434 if (offer_answer_options.offer_to_receive_video !=
3435 RTCOfferAnswerOptions::kUndefined) {
3436 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003437 offer_new_video_description =
Steve Antondcc3c022017-12-22 16:02:54 -08003438 offer_new_video_description ||
3439 (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003440 }
3441
3442 rtc::Optional<size_t> audio_index;
3443 rtc::Optional<size_t> video_index;
3444 rtc::Optional<size_t> data_index;
3445 // If a current description exists, generate m= sections in the same order,
3446 // using the first audio/video/data section that appears and rejecting
3447 // extraneous ones.
Steve Anton75737c02017-11-06 10:37:17 -08003448 if (local_description()) {
zhihuang1c378ed2017-08-17 14:10:50 -07003449 GenerateMediaDescriptionOptions(
Steve Anton75737c02017-11-06 10:37:17 -08003450 local_description(),
Steve Anton1d03a752017-11-27 14:30:09 -08003451 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
3452 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
3453 &audio_index, &video_index, &data_index, session_options);
deadbeefab9b2d12015-10-14 11:33:11 -07003454 }
3455
zhihuang1c378ed2017-08-17 14:10:50 -07003456 // Add audio/video/data m= sections to the end if needed.
3457 if (!audio_index && offer_new_audio_description) {
3458 session_options->media_description_options.push_back(
3459 cricket::MediaDescriptionOptions(
3460 cricket::MEDIA_TYPE_AUDIO, cricket::CN_AUDIO,
Steve Anton1d03a752017-11-27 14:30:09 -08003461 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
3462 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003463 audio_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07003464 }
zhihuang1c378ed2017-08-17 14:10:50 -07003465 if (!video_index && offer_new_video_description) {
3466 session_options->media_description_options.push_back(
3467 cricket::MediaDescriptionOptions(
3468 cricket::MEDIA_TYPE_VIDEO, cricket::CN_VIDEO,
Steve Anton1d03a752017-11-27 14:30:09 -08003469 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
3470 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003471 video_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07003472 }
zhihuang1c378ed2017-08-17 14:10:50 -07003473 if (!data_index && offer_new_data_description) {
3474 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08003475 GetMediaDescriptionOptionsForActiveData(cricket::CN_DATA));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003476 data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07003477 }
3478
3479 cricket::MediaDescriptionOptions* audio_media_description_options =
3480 !audio_index ? nullptr
3481 : &session_options->media_description_options[*audio_index];
3482 cricket::MediaDescriptionOptions* video_media_description_options =
3483 !video_index ? nullptr
3484 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 14:10:50 -07003485
Steve Anton4171afb2017-11-20 10:20:22 -08003486 AddRtpSenderOptions(GetSendersInternal(), audio_media_description_options,
zhihuang1c378ed2017-08-17 14:10:50 -07003487 video_media_description_options);
Steve Antondcc3c022017-12-22 16:02:54 -08003488}
3489
3490// Find a new MID that is not already in |used_mids|, then add it to |used_mids|
3491// and return a reference to it.
3492// Generated MIDs should be no more than 3 bytes long to take up less space in
3493// the RTP packet.
3494static const std::string& AllocateMid(std::set<std::string>* used_mids) {
3495 RTC_DCHECK(used_mids);
3496 // We're boring: just generate MIDs 0, 1, 2, ...
3497 size_t i = 0;
3498 std::set<std::string>::iterator it;
3499 bool inserted;
3500 do {
3501 std::string mid = rtc::ToString(i++);
3502 auto insert_result = used_mids->insert(mid);
3503 it = insert_result.first;
3504 inserted = insert_result.second;
3505 } while (!inserted);
3506 return *it;
3507}
3508
3509static cricket::MediaDescriptionOptions
3510GetMediaDescriptionOptionsForTransceiver(
3511 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3512 transceiver,
3513 const std::string& mid) {
3514 cricket::MediaDescriptionOptions media_description_options(
Steve Anton69470252018-02-09 11:43:08 -08003515 transceiver->media_type(), mid, transceiver->direction(),
Steve Antondcc3c022017-12-22 16:02:54 -08003516 transceiver->stopped());
Steve Anton5f94aa22018-02-01 10:58:30 -08003517 // This behavior is specified in JSEP. The gist is that:
3518 // 1. The MSID is included if the RtpTransceiver's direction is sendonly or
3519 // sendrecv.
3520 // 2. If the MSID is included, then it must be included in any subsequent
3521 // offer/answer exactly the same until the RtpTransceiver is stopped.
3522 if (!transceiver->stopped() &&
3523 (RtpTransceiverDirectionHasSend(transceiver->direction()) ||
3524 transceiver->internal()->has_ever_been_used_to_send())) {
3525 cricket::SenderOptions sender_options;
3526 sender_options.track_id = transceiver->sender()->id();
3527 sender_options.stream_ids = transceiver->sender()->stream_ids();
3528 // TODO(bugs.webrtc.org/7600): Set num_sim_layers to the number of encodings
3529 // set in the RTP parameters when the transceiver was added.
3530 sender_options.num_sim_layers = 1;
3531 media_description_options.sender_options.push_back(sender_options);
3532 }
Steve Antondcc3c022017-12-22 16:02:54 -08003533 return media_description_options;
3534}
3535
3536void PeerConnection::GetOptionsForUnifiedPlanOffer(
3537 const RTCOfferAnswerOptions& offer_answer_options,
3538 cricket::MediaSessionOptions* session_options) {
3539 // Rules for generating an offer are dictated by JSEP sections 5.2.1 (Initial
3540 // Offers) and 5.2.2 (Subsequent Offers).
3541 RTC_DCHECK_EQ(session_options->media_description_options.size(), 0);
3542 const ContentInfos& local_contents =
3543 (local_description() ? local_description()->description()->contents()
3544 : ContentInfos());
3545 const ContentInfos& remote_contents =
3546 (remote_description() ? remote_description()->description()->contents()
3547 : ContentInfos());
3548 // The mline indices that can be recycled. New transceivers should reuse these
3549 // slots first.
3550 std::queue<size_t> recycleable_mline_indices;
3551 // Track the MIDs used in previous offer/answer exchanges and the current
3552 // offer so that new, unique MIDs are generated.
3553 std::set<std::string> used_mids = seen_mids_;
3554 // First, go through each media section that exists in either the local or
3555 // remote description and generate a media section in this offer for the
3556 // associated transceiver. If a media section can be recycled, generate a
3557 // default, rejected media section here that can be later overwritten.
3558 for (size_t i = 0;
3559 i < std::max(local_contents.size(), remote_contents.size()); ++i) {
3560 // Either |local_content| or |remote_content| is non-null.
3561 const ContentInfo* local_content =
3562 (i < local_contents.size() ? &local_contents[i] : nullptr);
3563 const ContentInfo* remote_content =
3564 (i < remote_contents.size() ? &remote_contents[i] : nullptr);
3565 bool had_been_rejected = (local_content && local_content->rejected) ||
3566 (remote_content && remote_content->rejected);
3567 const std::string& mid =
3568 (local_content ? local_content->name : remote_content->name);
3569 cricket::MediaType media_type =
3570 (local_content ? local_content->media_description()->type()
3571 : remote_content->media_description()->type());
3572 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
3573 media_type == cricket::MEDIA_TYPE_VIDEO) {
3574 auto transceiver = GetAssociatedTransceiver(mid);
3575 RTC_CHECK(transceiver);
3576 // A media section is considered eligible for recycling if it is marked as
3577 // rejected in either the local or remote description.
Seth Hampsonae8a90a2018-02-13 15:33:48 -08003578 if (had_been_rejected && transceiver->stopped()) {
Steve Antondcc3c022017-12-22 16:02:54 -08003579 session_options->media_description_options.push_back(
Steve Anton69470252018-02-09 11:43:08 -08003580 cricket::MediaDescriptionOptions(transceiver->media_type(), mid,
3581 RtpTransceiverDirection::kInactive,
3582 /*stopped=*/true));
Steve Antondcc3c022017-12-22 16:02:54 -08003583 recycleable_mline_indices.push(i);
3584 } else {
3585 session_options->media_description_options.push_back(
3586 GetMediaDescriptionOptionsForTransceiver(transceiver, mid));
3587 // CreateOffer shouldn't really cause any state changes in
3588 // PeerConnection, but we need a way to match new transceivers to new
3589 // media sections in SetLocalDescription and JSEP specifies this is done
3590 // by recording the index of the media section generated for the
3591 // transceiver in the offer.
3592 transceiver->internal()->set_mline_index(i);
3593 }
3594 } else {
3595 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antonfa2260d2017-12-28 16:38:23 -08003596 RTC_CHECK(GetDataMid());
3597 if (had_been_rejected || mid != *GetDataMid()) {
3598 session_options->media_description_options.push_back(
3599 GetMediaDescriptionOptionsForRejectedData(mid));
3600 } else {
3601 session_options->media_description_options.push_back(
3602 GetMediaDescriptionOptionsForActiveData(mid));
3603 }
Steve Antondcc3c022017-12-22 16:02:54 -08003604 }
3605 }
3606 // Next, look for transceivers that are newly added (that is, are not stopped
3607 // and not associated). Reuse media sections marked as recyclable first,
3608 // otherwise append to the end of the offer. New media sections should be
3609 // added in the order they were added to the PeerConnection.
3610 for (auto transceiver : transceivers_) {
3611 if (transceiver->mid() || transceiver->stopped()) {
3612 continue;
3613 }
3614 size_t mline_index;
3615 if (!recycleable_mline_indices.empty()) {
3616 mline_index = recycleable_mline_indices.front();
3617 recycleable_mline_indices.pop();
3618 session_options->media_description_options[mline_index] =
3619 GetMediaDescriptionOptionsForTransceiver(transceiver,
3620 AllocateMid(&used_mids));
3621 } else {
3622 mline_index = session_options->media_description_options.size();
3623 session_options->media_description_options.push_back(
3624 GetMediaDescriptionOptionsForTransceiver(transceiver,
3625 AllocateMid(&used_mids)));
3626 }
3627 // See comment above for why CreateOffer changes the transceiver's state.
3628 transceiver->internal()->set_mline_index(mline_index);
3629 }
Steve Antonfa2260d2017-12-28 16:38:23 -08003630 // Lastly, add a m-section if we have local data channels and an m section
3631 // does not already exist.
3632 if (!GetDataMid() && HasDataChannels()) {
3633 session_options->media_description_options.push_back(
3634 GetMediaDescriptionOptionsForActiveData(AllocateMid(&used_mids)));
3635 }
Steve Antondcc3c022017-12-22 16:02:54 -08003636}
3637
3638void PeerConnection::GetOptionsForAnswer(
3639 const RTCOfferAnswerOptions& offer_answer_options,
3640 cricket::MediaSessionOptions* session_options) {
3641 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
3642
3643 if (IsUnifiedPlan()) {
3644 GetOptionsForUnifiedPlanAnswer(offer_answer_options, session_options);
3645 } else {
3646 GetOptionsForPlanBAnswer(offer_answer_options, session_options);
3647 }
3648
Steve Antonfa2260d2017-12-28 16:38:23 -08003649 // Intentionally unset the data channel type for RTP data channel. Otherwise
3650 // the RTP data channels would be successfully negotiated by default and the
3651 // unit tests in WebRtcDataBrowserTest will fail when building with chromium.
3652 // We want to leave RTP data channels broken, so people won't try to use them.
3653 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
3654 session_options->data_channel_type = data_channel_type();
3655 }
3656
Steve Antondcc3c022017-12-22 16:02:54 -08003657 // Apply ICE renomination flag.
3658 for (auto& options : session_options->media_description_options) {
3659 options.transport_options.enable_ice_renomination =
3660 configuration_.enable_ice_renomination;
3661 }
zhihuang8f65cdf2016-05-06 18:40:30 -07003662
3663 session_options->rtcp_cname = rtcp_cname_;
jbauchcb560652016-08-04 05:20:32 -07003664 session_options->crypto_options = factory_->options().crypto_options;
Steve Antone831b8c2018-02-01 12:22:16 -08003665 session_options->is_unified_plan = IsUnifiedPlan();
deadbeefab9b2d12015-10-14 11:33:11 -07003666}
3667
Steve Antondcc3c022017-12-22 16:02:54 -08003668void PeerConnection::GetOptionsForPlanBAnswer(
3669 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07003670 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07003671 // Figure out transceiver directional preferences.
3672 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
3673 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
3674
3675 // By default, generate sendrecv/recvonly m= sections. The direction is also
3676 // restricted by the direction in the offer.
3677 bool recv_audio = true;
3678 bool recv_video = true;
3679
3680 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-22 16:02:54 -08003681 if (offer_answer_options.offer_to_receive_audio !=
3682 RTCOfferAnswerOptions::kUndefined) {
3683 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
deadbeef0ed85b22016-02-23 17:24:52 -08003684 }
Steve Antondcc3c022017-12-22 16:02:54 -08003685 if (offer_answer_options.offer_to_receive_video !=
3686 RTCOfferAnswerOptions::kUndefined) {
3687 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003688 }
3689
3690 rtc::Optional<size_t> audio_index;
3691 rtc::Optional<size_t> video_index;
3692 rtc::Optional<size_t> data_index;
Steve Antondffead82018-02-06 10:31:29 -08003693
3694 // Generate m= sections that match those in the offer.
3695 // Note that mediasession.cc will handle intersection our preferred
3696 // direction with the offered direction.
3697 GenerateMediaDescriptionOptions(
3698 remote_description(),
3699 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
3700 RtpTransceiverDirectionFromSendRecv(send_video, recv_video), &audio_index,
3701 &video_index, &data_index, session_options);
zhihuang1c378ed2017-08-17 14:10:50 -07003702
3703 cricket::MediaDescriptionOptions* audio_media_description_options =
3704 !audio_index ? nullptr
3705 : &session_options->media_description_options[*audio_index];
3706 cricket::MediaDescriptionOptions* video_media_description_options =
3707 !video_index ? nullptr
3708 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 14:10:50 -07003709
Steve Anton4171afb2017-11-20 10:20:22 -08003710 AddRtpSenderOptions(GetSendersInternal(), audio_media_description_options,
zhihuang1c378ed2017-08-17 14:10:50 -07003711 video_media_description_options);
Steve Antondcc3c022017-12-22 16:02:54 -08003712}
zhihuangaf388472016-11-02 16:49:48 -07003713
Steve Antondcc3c022017-12-22 16:02:54 -08003714void PeerConnection::GetOptionsForUnifiedPlanAnswer(
3715 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
3716 cricket::MediaSessionOptions* session_options) {
3717 // Rules for generating an answer are dictated by JSEP sections 5.3.1 (Initial
3718 // Answers) and 5.3.2 (Subsequent Answers).
3719 RTC_DCHECK(remote_description());
3720 RTC_DCHECK(remote_description()->GetType() == SdpType::kOffer);
3721 for (const ContentInfo& content :
3722 remote_description()->description()->contents()) {
3723 cricket::MediaType media_type = content.media_description()->type();
3724 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
3725 media_type == cricket::MEDIA_TYPE_VIDEO) {
3726 auto transceiver = GetAssociatedTransceiver(content.name);
3727 RTC_CHECK(transceiver);
3728 session_options->media_description_options.push_back(
3729 GetMediaDescriptionOptionsForTransceiver(transceiver, content.name));
3730 } else {
3731 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antondbf9d032018-01-19 15:23:40 -08003732 // Reject all data sections if data channels are disabled.
3733 // Reject a data section if it has already been rejected.
3734 // Reject all data sections except for the first one.
3735 if (data_channel_type_ == cricket::DCT_NONE || content.rejected ||
3736 content.name != *GetDataMid()) {
Steve Antonfa2260d2017-12-28 16:38:23 -08003737 session_options->media_description_options.push_back(
3738 GetMediaDescriptionOptionsForRejectedData(content.name));
3739 } else {
3740 session_options->media_description_options.push_back(
3741 GetMediaDescriptionOptionsForActiveData(content.name));
3742 }
Steve Antondcc3c022017-12-22 16:02:54 -08003743 }
3744 }
htaa2a49d92016-03-04 02:51:39 -08003745}
3746
zhihuang1c378ed2017-08-17 14:10:50 -07003747void PeerConnection::GenerateMediaDescriptionOptions(
3748 const SessionDescriptionInterface* session_desc,
Steve Anton1d03a752017-11-27 14:30:09 -08003749 RtpTransceiverDirection audio_direction,
3750 RtpTransceiverDirection video_direction,
zhihuang1c378ed2017-08-17 14:10:50 -07003751 rtc::Optional<size_t>* audio_index,
3752 rtc::Optional<size_t>* video_index,
3753 rtc::Optional<size_t>* data_index,
htaa2a49d92016-03-04 02:51:39 -08003754 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07003755 for (const cricket::ContentInfo& content :
3756 session_desc->description()->contents()) {
3757 if (IsAudioContent(&content)) {
3758 // If we already have an audio m= section, reject this extra one.
3759 if (*audio_index) {
3760 session_options->media_description_options.push_back(
3761 cricket::MediaDescriptionOptions(
3762 cricket::MEDIA_TYPE_AUDIO, content.name,
Steve Anton1d03a752017-11-27 14:30:09 -08003763 RtpTransceiverDirection::kInactive, true));
zhihuang1c378ed2017-08-17 14:10:50 -07003764 } else {
3765 session_options->media_description_options.push_back(
3766 cricket::MediaDescriptionOptions(
3767 cricket::MEDIA_TYPE_AUDIO, content.name, audio_direction,
Steve Anton1d03a752017-11-27 14:30:09 -08003768 audio_direction == RtpTransceiverDirection::kInactive));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003769 *audio_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07003770 }
3771 } else if (IsVideoContent(&content)) {
3772 // If we already have an video m= section, reject this extra one.
3773 if (*video_index) {
3774 session_options->media_description_options.push_back(
3775 cricket::MediaDescriptionOptions(
3776 cricket::MEDIA_TYPE_VIDEO, content.name,
Steve Anton1d03a752017-11-27 14:30:09 -08003777 RtpTransceiverDirection::kInactive, true));
zhihuang1c378ed2017-08-17 14:10:50 -07003778 } else {
3779 session_options->media_description_options.push_back(
3780 cricket::MediaDescriptionOptions(
3781 cricket::MEDIA_TYPE_VIDEO, content.name, video_direction,
Steve Anton1d03a752017-11-27 14:30:09 -08003782 video_direction == RtpTransceiverDirection::kInactive));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003783 *video_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07003784 }
3785 } else {
3786 RTC_DCHECK(IsDataContent(&content));
3787 // If we already have an data m= section, reject this extra one.
3788 if (*data_index) {
3789 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08003790 GetMediaDescriptionOptionsForRejectedData(content.name));
zhihuang1c378ed2017-08-17 14:10:50 -07003791 } else {
3792 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08003793 GetMediaDescriptionOptionsForActiveData(content.name));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003794 *data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07003795 }
3796 }
htaa2a49d92016-03-04 02:51:39 -08003797 }
deadbeefab9b2d12015-10-14 11:33:11 -07003798}
3799
Steve Antonfa2260d2017-12-28 16:38:23 -08003800cricket::MediaDescriptionOptions
3801PeerConnection::GetMediaDescriptionOptionsForActiveData(
3802 const std::string& mid) const {
3803 // Direction for data sections is meaningless, but legacy endpoints might
3804 // expect sendrecv.
3805 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
3806 RtpTransceiverDirection::kSendRecv,
3807 /*stopped=*/false);
3808 AddRtpDataChannelOptions(rtp_data_channels_, &options);
3809 return options;
3810}
3811
3812cricket::MediaDescriptionOptions
3813PeerConnection::GetMediaDescriptionOptionsForRejectedData(
3814 const std::string& mid) const {
3815 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
3816 RtpTransceiverDirection::kInactive,
3817 /*stopped=*/true);
3818 AddRtpDataChannelOptions(rtp_data_channels_, &options);
3819 return options;
3820}
3821
3822rtc::Optional<std::string> PeerConnection::GetDataMid() const {
3823 switch (data_channel_type_) {
3824 case cricket::DCT_RTP:
3825 if (!rtp_data_channel_) {
3826 return rtc::nullopt;
3827 }
3828 return rtp_data_channel_->content_name();
3829 case cricket::DCT_SCTP:
3830 return sctp_content_name_;
3831 default:
3832 return rtc::nullopt;
3833 }
3834}
3835
Steve Anton4171afb2017-11-20 10:20:22 -08003836void PeerConnection::RemoveSenders(cricket::MediaType media_type) {
3837 UpdateLocalSenders(std::vector<cricket::StreamParams>(), media_type);
3838 UpdateRemoteSendersList(std::vector<cricket::StreamParams>(), false,
deadbeefbda7e0b2015-12-08 17:13:40 -08003839 media_type, nullptr);
deadbeeffaac4972015-11-12 15:33:07 -08003840}
3841
Steve Anton4171afb2017-11-20 10:20:22 -08003842void PeerConnection::UpdateRemoteSendersList(
deadbeefab9b2d12015-10-14 11:33:11 -07003843 const cricket::StreamParamsVec& streams,
Steve Anton4171afb2017-11-20 10:20:22 -08003844 bool default_sender_needed,
deadbeefab9b2d12015-10-14 11:33:11 -07003845 cricket::MediaType media_type,
3846 StreamCollection* new_streams) {
Steve Anton4171afb2017-11-20 10:20:22 -08003847 std::vector<RtpSenderInfo>* current_senders =
3848 GetRemoteSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07003849
Steve Anton4171afb2017-11-20 10:20:22 -08003850 // Find removed senders. I.e., senders where the sender id or ssrc don't match
deadbeeffac06552015-11-25 11:26:01 -08003851 // the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08003852 for (auto sender_it = current_senders->begin();
3853 sender_it != current_senders->end();
3854 /* incremented manually */) {
3855 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07003856 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08003857 cricket::GetStreamBySsrc(streams, info.first_ssrc);
3858 bool sender_exists = params && params->id == info.sender_id;
deadbeefbda7e0b2015-12-08 17:13:40 -08003859 // If this is a default track, and we still need it, don't remove it.
Steve Anton4171afb2017-11-20 10:20:22 -08003860 if ((info.stream_label == kDefaultStreamLabel && default_sender_needed) ||
3861 sender_exists) {
3862 ++sender_it;
deadbeefbda7e0b2015-12-08 17:13:40 -08003863 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08003864 OnRemoteSenderRemoved(info, media_type);
3865 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07003866 }
3867 }
3868
Steve Anton4171afb2017-11-20 10:20:22 -08003869 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07003870 for (const cricket::StreamParams& params : streams) {
3871 // The sync_label is the MediaStream label and the |stream.id| is the
Steve Anton4171afb2017-11-20 10:20:22 -08003872 // sender id.
Steve Anton5a26a3a2018-02-28 11:38:47 -08003873 // TODO(bugs.webrtc.org/7932): Add support for multiple stream labels.
3874 const std::string& stream_label =
3875 (!params.stream_labels().empty() ? params.stream_labels()[0] : "");
Steve Anton4171afb2017-11-20 10:20:22 -08003876 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07003877 uint32_t ssrc = params.first_ssrc();
3878
3879 rtc::scoped_refptr<MediaStreamInterface> stream =
3880 remote_streams_->find(stream_label);
3881 if (!stream) {
3882 // This is a new MediaStream. Create a new remote MediaStream.
perkjd61bf802016-03-24 03:16:19 -07003883 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
3884 MediaStream::Create(stream_label));
deadbeefab9b2d12015-10-14 11:33:11 -07003885 remote_streams_->AddStream(stream);
3886 new_streams->AddStream(stream);
3887 }
3888
Steve Anton4171afb2017-11-20 10:20:22 -08003889 const RtpSenderInfo* sender_info =
3890 FindSenderInfo(*current_senders, stream_label, sender_id);
3891 if (!sender_info) {
3892 current_senders->push_back(RtpSenderInfo(stream_label, sender_id, ssrc));
3893 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07003894 }
3895 }
deadbeefbda7e0b2015-12-08 17:13:40 -08003896
Steve Anton4171afb2017-11-20 10:20:22 -08003897 // Add default sender if necessary.
3898 if (default_sender_needed) {
deadbeefbda7e0b2015-12-08 17:13:40 -08003899 rtc::scoped_refptr<MediaStreamInterface> default_stream =
3900 remote_streams_->find(kDefaultStreamLabel);
3901 if (!default_stream) {
3902 // Create the new default MediaStream.
perkjd61bf802016-03-24 03:16:19 -07003903 default_stream = MediaStreamProxy::Create(
3904 rtc::Thread::Current(), MediaStream::Create(kDefaultStreamLabel));
deadbeefbda7e0b2015-12-08 17:13:40 -08003905 remote_streams_->AddStream(default_stream);
3906 new_streams->AddStream(default_stream);
3907 }
Steve Anton4171afb2017-11-20 10:20:22 -08003908 std::string default_sender_id = (media_type == cricket::MEDIA_TYPE_AUDIO)
3909 ? kDefaultAudioSenderId
3910 : kDefaultVideoSenderId;
3911 const RtpSenderInfo* default_sender_info = FindSenderInfo(
3912 *current_senders, kDefaultStreamLabel, default_sender_id);
3913 if (!default_sender_info) {
3914 current_senders->push_back(
3915 RtpSenderInfo(kDefaultStreamLabel, default_sender_id, 0));
3916 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefbda7e0b2015-12-08 17:13:40 -08003917 }
3918 }
deadbeefab9b2d12015-10-14 11:33:11 -07003919}
3920
Steve Anton4171afb2017-11-20 10:20:22 -08003921void PeerConnection::OnRemoteSenderAdded(const RtpSenderInfo& sender_info,
3922 cricket::MediaType media_type) {
3923 MediaStreamInterface* stream =
3924 remote_streams_->find(sender_info.stream_label);
deadbeefab9b2d12015-10-14 11:33:11 -07003925
3926 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 10:20:22 -08003927 CreateAudioReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07003928 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 10:20:22 -08003929 CreateVideoReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07003930 } else {
nisseeb4ca4e2017-01-12 02:24:27 -08003931 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07003932 }
3933}
3934
Steve Anton4171afb2017-11-20 10:20:22 -08003935void PeerConnection::OnRemoteSenderRemoved(const RtpSenderInfo& sender_info,
3936 cricket::MediaType media_type) {
3937 MediaStreamInterface* stream =
3938 remote_streams_->find(sender_info.stream_label);
deadbeefab9b2d12015-10-14 11:33:11 -07003939
Henrik Boström933d8b02017-10-10 10:05:16 -07003940 rtc::scoped_refptr<RtpReceiverInterface> receiver;
deadbeefab9b2d12015-10-14 11:33:11 -07003941 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
perkjd61bf802016-03-24 03:16:19 -07003942 // When the MediaEngine audio channel is destroyed, the RemoteAudioSource
3943 // will be notified which will end the AudioRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08003944 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07003945 rtc::scoped_refptr<AudioTrackInterface> audio_track =
Steve Anton4171afb2017-11-20 10:20:22 -08003946 stream->FindAudioTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07003947 if (audio_track) {
deadbeefab9b2d12015-10-14 11:33:11 -07003948 stream->RemoveTrack(audio_track);
deadbeefab9b2d12015-10-14 11:33:11 -07003949 }
3950 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
perkjd61bf802016-03-24 03:16:19 -07003951 // Stopping or destroying a VideoRtpReceiver will end the
3952 // VideoRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08003953 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07003954 rtc::scoped_refptr<VideoTrackInterface> video_track =
Steve Anton4171afb2017-11-20 10:20:22 -08003955 stream->FindVideoTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07003956 if (video_track) {
perkjd61bf802016-03-24 03:16:19 -07003957 // There's no guarantee the track is still available, e.g. the track may
3958 // have been removed from the stream by an application.
deadbeefab9b2d12015-10-14 11:33:11 -07003959 stream->RemoveTrack(video_track);
deadbeefab9b2d12015-10-14 11:33:11 -07003960 }
3961 } else {
nisseede5da42017-01-12 05:15:36 -08003962 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07003963 }
Henrik Boström933d8b02017-10-10 10:05:16 -07003964 if (receiver) {
3965 observer_->OnRemoveTrack(receiver);
3966 }
deadbeefab9b2d12015-10-14 11:33:11 -07003967}
3968
3969void PeerConnection::UpdateEndedRemoteMediaStreams() {
3970 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams_to_remove;
3971 for (size_t i = 0; i < remote_streams_->count(); ++i) {
3972 MediaStreamInterface* stream = remote_streams_->at(i);
3973 if (stream->GetAudioTracks().empty() && stream->GetVideoTracks().empty()) {
3974 streams_to_remove.push_back(stream);
3975 }
3976 }
3977
Taylor Brandstetter98cde262016-05-31 13:02:21 -07003978 for (auto& stream : streams_to_remove) {
deadbeefab9b2d12015-10-14 11:33:11 -07003979 remote_streams_->RemoveStream(stream);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07003980 observer_->OnRemoveStream(std::move(stream));
deadbeefab9b2d12015-10-14 11:33:11 -07003981 }
3982}
3983
Steve Anton4171afb2017-11-20 10:20:22 -08003984void PeerConnection::UpdateLocalSenders(
deadbeefab9b2d12015-10-14 11:33:11 -07003985 const std::vector<cricket::StreamParams>& streams,
3986 cricket::MediaType media_type) {
Steve Anton4171afb2017-11-20 10:20:22 -08003987 std::vector<RtpSenderInfo>* current_senders = GetLocalSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07003988
3989 // Find removed tracks. I.e., tracks where the track id, stream label or ssrc
3990 // don't match the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08003991 for (auto sender_it = current_senders->begin();
3992 sender_it != current_senders->end();
3993 /* incremented manually */) {
3994 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07003995 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08003996 cricket::GetStreamBySsrc(streams, info.first_ssrc);
3997 if (!params || params->id != info.sender_id ||
Steve Anton5a26a3a2018-02-28 11:38:47 -08003998 params->first_stream_label() != info.stream_label) {
Steve Anton4171afb2017-11-20 10:20:22 -08003999 OnLocalSenderRemoved(info, media_type);
4000 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07004001 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08004002 ++sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07004003 }
4004 }
4005
Steve Anton4171afb2017-11-20 10:20:22 -08004006 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07004007 for (const cricket::StreamParams& params : streams) {
4008 // The sync_label is the MediaStream label and the |stream.id| is the
Steve Anton4171afb2017-11-20 10:20:22 -08004009 // sender id.
Steve Anton5a26a3a2018-02-28 11:38:47 -08004010 const std::string& stream_label = params.first_stream_label();
Steve Anton4171afb2017-11-20 10:20:22 -08004011 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07004012 uint32_t ssrc = params.first_ssrc();
Steve Anton4171afb2017-11-20 10:20:22 -08004013 const RtpSenderInfo* sender_info =
4014 FindSenderInfo(*current_senders, stream_label, sender_id);
4015 if (!sender_info) {
4016 current_senders->push_back(RtpSenderInfo(stream_label, sender_id, ssrc));
4017 OnLocalSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004018 }
4019 }
4020}
4021
Steve Anton4171afb2017-11-20 10:20:22 -08004022void PeerConnection::OnLocalSenderAdded(const RtpSenderInfo& sender_info,
4023 cricket::MediaType media_type) {
4024 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08004025 if (!sender) {
Steve Anton4171afb2017-11-20 10:20:22 -08004026 RTC_LOG(LS_WARNING) << "An unknown RtpSender with id "
4027 << sender_info.sender_id
Mirko Bonadei675513b2017-11-09 11:09:25 +01004028 << " has been configured in the local description.";
deadbeefab9b2d12015-10-14 11:33:11 -07004029 return;
4030 }
4031
deadbeeffac06552015-11-25 11:26:01 -08004032 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004033 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
Jonas Olsson45cc8902018-02-13 10:37:07 +01004034 " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08004035 return;
deadbeefab9b2d12015-10-14 11:33:11 -07004036 }
deadbeeffac06552015-11-25 11:26:01 -08004037
Steve Anton4171afb2017-11-20 10:20:22 -08004038 sender->internal()->set_stream_id(sender_info.stream_label);
4039 sender->internal()->SetSsrc(sender_info.first_ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07004040}
4041
Steve Anton4171afb2017-11-20 10:20:22 -08004042void PeerConnection::OnLocalSenderRemoved(const RtpSenderInfo& sender_info,
4043 cricket::MediaType media_type) {
4044 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08004045 if (!sender) {
4046 // This is the normal case. I.e., RemoveStream has been called and the
deadbeefab9b2d12015-10-14 11:33:11 -07004047 // SessionDescriptions has been renegotiated.
4048 return;
4049 }
deadbeeffac06552015-11-25 11:26:01 -08004050
4051 // A sender has been removed from the SessionDescription but it's still
4052 // associated with the PeerConnection. This only occurs if the SDP doesn't
4053 // match with the calls to CreateSender, AddStream and RemoveStream.
4054 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004055 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
Jonas Olsson45cc8902018-02-13 10:37:07 +01004056 " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08004057 return;
deadbeefab9b2d12015-10-14 11:33:11 -07004058 }
deadbeeffac06552015-11-25 11:26:01 -08004059
Steve Anton4171afb2017-11-20 10:20:22 -08004060 sender->internal()->SetSsrc(0);
deadbeefab9b2d12015-10-14 11:33:11 -07004061}
4062
4063void PeerConnection::UpdateLocalRtpDataChannels(
4064 const cricket::StreamParamsVec& streams) {
4065 std::vector<std::string> existing_channels;
4066
4067 // Find new and active data channels.
4068 for (const cricket::StreamParams& params : streams) {
4069 // |it->sync_label| is actually the data channel label. The reason is that
4070 // we use the same naming of data channels as we do for
4071 // MediaStreams and Tracks.
4072 // For MediaStreams, the sync_label is the MediaStream label and the
4073 // track label is the same as |streamid|.
Steve Anton5a26a3a2018-02-28 11:38:47 -08004074 const std::string& channel_label = params.first_stream_label();
deadbeefab9b2d12015-10-14 11:33:11 -07004075 auto data_channel_it = rtp_data_channels_.find(channel_label);
nisse7ce109a2017-01-31 00:57:56 -08004076 if (data_channel_it == rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004077 RTC_LOG(LS_ERROR) << "channel label not found";
deadbeefab9b2d12015-10-14 11:33:11 -07004078 continue;
4079 }
4080 // Set the SSRC the data channel should use for sending.
4081 data_channel_it->second->SetSendSsrc(params.first_ssrc());
4082 existing_channels.push_back(data_channel_it->first);
4083 }
4084
4085 UpdateClosingRtpDataChannels(existing_channels, true);
4086}
4087
4088void PeerConnection::UpdateRemoteRtpDataChannels(
4089 const cricket::StreamParamsVec& streams) {
4090 std::vector<std::string> existing_channels;
4091
4092 // Find new and active data channels.
4093 for (const cricket::StreamParams& params : streams) {
4094 // The data channel label is either the mslabel or the SSRC if the mslabel
4095 // does not exist. Ex a=ssrc:444330170 mslabel:test1.
Steve Anton5a26a3a2018-02-28 11:38:47 -08004096 std::string label = params.first_stream_label().empty()
deadbeefab9b2d12015-10-14 11:33:11 -07004097 ? rtc::ToString(params.first_ssrc())
Steve Anton5a26a3a2018-02-28 11:38:47 -08004098 : params.first_stream_label();
deadbeefab9b2d12015-10-14 11:33:11 -07004099 auto data_channel_it = rtp_data_channels_.find(label);
4100 if (data_channel_it == rtp_data_channels_.end()) {
4101 // This is a new data channel.
4102 CreateRemoteRtpDataChannel(label, params.first_ssrc());
4103 } else {
4104 data_channel_it->second->SetReceiveSsrc(params.first_ssrc());
4105 }
4106 existing_channels.push_back(label);
4107 }
4108
4109 UpdateClosingRtpDataChannels(existing_channels, false);
4110}
4111
4112void PeerConnection::UpdateClosingRtpDataChannels(
4113 const std::vector<std::string>& active_channels,
4114 bool is_local_update) {
4115 auto it = rtp_data_channels_.begin();
4116 while (it != rtp_data_channels_.end()) {
4117 DataChannel* data_channel = it->second;
4118 if (std::find(active_channels.begin(), active_channels.end(),
4119 data_channel->label()) != active_channels.end()) {
4120 ++it;
4121 continue;
4122 }
4123
4124 if (is_local_update) {
4125 data_channel->SetSendSsrc(0);
4126 } else {
4127 data_channel->RemotePeerRequestClose();
4128 }
4129
4130 if (data_channel->state() == DataChannel::kClosed) {
4131 rtp_data_channels_.erase(it);
4132 it = rtp_data_channels_.begin();
4133 } else {
4134 ++it;
4135 }
4136 }
4137}
4138
4139void PeerConnection::CreateRemoteRtpDataChannel(const std::string& label,
4140 uint32_t remote_ssrc) {
4141 rtc::scoped_refptr<DataChannel> channel(
4142 InternalCreateDataChannel(label, nullptr));
4143 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004144 RTC_LOG(LS_WARNING) << "Remote peer requested a DataChannel but"
Jonas Olsson45cc8902018-02-13 10:37:07 +01004145 "CreateDataChannel failed.";
deadbeefab9b2d12015-10-14 11:33:11 -07004146 return;
4147 }
4148 channel->SetReceiveSsrc(remote_ssrc);
deadbeefa601f5c2016-06-06 14:27:39 -07004149 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
4150 DataChannelProxy::Create(signaling_thread(), channel);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07004151 observer_->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07004152}
4153
4154rtc::scoped_refptr<DataChannel> PeerConnection::InternalCreateDataChannel(
4155 const std::string& label,
4156 const InternalDataChannelInit* config) {
4157 if (IsClosed()) {
4158 return nullptr;
4159 }
Steve Anton75737c02017-11-06 10:37:17 -08004160 if (data_channel_type() == cricket::DCT_NONE) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004161 RTC_LOG(LS_ERROR)
deadbeefab9b2d12015-10-14 11:33:11 -07004162 << "InternalCreateDataChannel: Data is not supported in this call.";
4163 return nullptr;
4164 }
4165 InternalDataChannelInit new_config =
4166 config ? (*config) : InternalDataChannelInit();
Steve Anton75737c02017-11-06 10:37:17 -08004167 if (data_channel_type() == cricket::DCT_SCTP) {
deadbeefab9b2d12015-10-14 11:33:11 -07004168 if (new_config.id < 0) {
4169 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08004170 if ((GetSctpSslRole(&role)) &&
deadbeefab9b2d12015-10-14 11:33:11 -07004171 !sid_allocator_.AllocateSid(role, &new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004172 RTC_LOG(LS_ERROR)
4173 << "No id can be allocated for the SCTP data channel.";
deadbeefab9b2d12015-10-14 11:33:11 -07004174 return nullptr;
4175 }
4176 } else if (!sid_allocator_.ReserveSid(new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004177 RTC_LOG(LS_ERROR) << "Failed to create a SCTP data channel "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004178 "because the id is already in use or out of range.";
deadbeefab9b2d12015-10-14 11:33:11 -07004179 return nullptr;
4180 }
4181 }
4182
Steve Anton75737c02017-11-06 10:37:17 -08004183 rtc::scoped_refptr<DataChannel> channel(
4184 DataChannel::Create(this, data_channel_type(), label, new_config));
deadbeefab9b2d12015-10-14 11:33:11 -07004185 if (!channel) {
4186 sid_allocator_.ReleaseSid(new_config.id);
4187 return nullptr;
4188 }
4189
4190 if (channel->data_channel_type() == cricket::DCT_RTP) {
4191 if (rtp_data_channels_.find(channel->label()) != rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004192 RTC_LOG(LS_ERROR) << "DataChannel with label " << channel->label()
4193 << " already exists.";
deadbeefab9b2d12015-10-14 11:33:11 -07004194 return nullptr;
4195 }
4196 rtp_data_channels_[channel->label()] = channel;
4197 } else {
4198 RTC_DCHECK(channel->data_channel_type() == cricket::DCT_SCTP);
4199 sctp_data_channels_.push_back(channel);
4200 channel->SignalClosed.connect(this,
4201 &PeerConnection::OnSctpDataChannelClosed);
4202 }
4203
Steve Anton2d8609c2018-01-23 16:38:46 -08004204 SignalDataChannelCreated_(channel.get());
deadbeefab9b2d12015-10-14 11:33:11 -07004205 return channel;
4206}
4207
4208bool PeerConnection::HasDataChannels() const {
4209 return !rtp_data_channels_.empty() || !sctp_data_channels_.empty();
4210}
4211
4212void PeerConnection::AllocateSctpSids(rtc::SSLRole role) {
4213 for (const auto& channel : sctp_data_channels_) {
4214 if (channel->id() < 0) {
4215 int sid;
4216 if (!sid_allocator_.AllocateSid(role, &sid)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004217 RTC_LOG(LS_ERROR) << "Failed to allocate SCTP sid.";
deadbeefab9b2d12015-10-14 11:33:11 -07004218 continue;
4219 }
4220 channel->SetSctpSid(sid);
4221 }
4222 }
4223}
4224
4225void PeerConnection::OnSctpDataChannelClosed(DataChannel* channel) {
deadbeefbd292462015-12-14 18:15:29 -08004226 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeefab9b2d12015-10-14 11:33:11 -07004227 for (auto it = sctp_data_channels_.begin(); it != sctp_data_channels_.end();
4228 ++it) {
4229 if (it->get() == channel) {
4230 if (channel->id() >= 0) {
4231 sid_allocator_.ReleaseSid(channel->id());
4232 }
deadbeefbd292462015-12-14 18:15:29 -08004233 // Since this method is triggered by a signal from the DataChannel,
4234 // we can't free it directly here; we need to free it asynchronously.
4235 sctp_data_channels_to_free_.push_back(*it);
deadbeefab9b2d12015-10-14 11:33:11 -07004236 sctp_data_channels_.erase(it);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07004237 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_FREE_DATACHANNELS,
4238 nullptr);
deadbeefab9b2d12015-10-14 11:33:11 -07004239 return;
4240 }
4241 }
4242}
4243
deadbeefab9b2d12015-10-14 11:33:11 -07004244void PeerConnection::OnDataChannelDestroyed() {
4245 // Use a temporary copy of the RTP/SCTP DataChannel list because the
4246 // DataChannel may callback to us and try to modify the list.
4247 std::map<std::string, rtc::scoped_refptr<DataChannel>> temp_rtp_dcs;
4248 temp_rtp_dcs.swap(rtp_data_channels_);
4249 for (const auto& kv : temp_rtp_dcs) {
4250 kv.second->OnTransportChannelDestroyed();
4251 }
4252
4253 std::vector<rtc::scoped_refptr<DataChannel>> temp_sctp_dcs;
4254 temp_sctp_dcs.swap(sctp_data_channels_);
4255 for (const auto& channel : temp_sctp_dcs) {
4256 channel->OnTransportChannelDestroyed();
4257 }
4258}
4259
4260void PeerConnection::OnDataChannelOpenMessage(
4261 const std::string& label,
4262 const InternalDataChannelInit& config) {
4263 rtc::scoped_refptr<DataChannel> channel(
4264 InternalCreateDataChannel(label, &config));
4265 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004266 RTC_LOG(LS_ERROR) << "Failed to create DataChannel from the OPEN message.";
deadbeefab9b2d12015-10-14 11:33:11 -07004267 return;
4268 }
4269
deadbeefa601f5c2016-06-06 14:27:39 -07004270 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
4271 DataChannelProxy::Create(signaling_thread(), channel);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07004272 observer_->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07004273}
4274
Steve Anton4171afb2017-11-20 10:20:22 -08004275rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
4276PeerConnection::GetAudioTransceiver() const {
4277 // This method only works with Plan B SDP, where there is a single
4278 // audio/video transceiver.
4279 RTC_DCHECK(!IsUnifiedPlan());
4280 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08004281 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004282 return transceiver;
4283 }
4284 }
4285 RTC_NOTREACHED();
4286 return nullptr;
4287}
4288
4289rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
4290PeerConnection::GetVideoTransceiver() const {
4291 // This method only works with Plan B SDP, where there is a single
4292 // audio/video transceiver.
4293 RTC_DCHECK(!IsUnifiedPlan());
4294 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08004295 if (transceiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004296 return transceiver;
4297 }
4298 }
4299 RTC_NOTREACHED();
4300 return nullptr;
4301}
4302
4303// TODO(bugs.webrtc.org/7600): Remove this when multiple transceivers with
4304// individual transceiver directions are supported.
zhihuang1c378ed2017-08-17 14:10:50 -07004305bool PeerConnection::HasRtpSender(cricket::MediaType type) const {
Steve Anton4171afb2017-11-20 10:20:22 -08004306 switch (type) {
4307 case cricket::MEDIA_TYPE_AUDIO:
4308 return !GetAudioTransceiver()->internal()->senders().empty();
4309 case cricket::MEDIA_TYPE_VIDEO:
4310 return !GetVideoTransceiver()->internal()->senders().empty();
4311 case cricket::MEDIA_TYPE_DATA:
4312 return false;
4313 }
4314 RTC_NOTREACHED();
4315 return false;
zhihuang1c378ed2017-08-17 14:10:50 -07004316}
4317
Steve Anton4171afb2017-11-20 10:20:22 -08004318rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
4319PeerConnection::FindSenderForTrack(MediaStreamTrackInterface* track) const {
4320 for (auto transceiver : transceivers_) {
4321 for (auto sender : transceiver->internal()->senders()) {
4322 if (sender->track() == track) {
4323 return sender;
4324 }
4325 }
4326 }
4327 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08004328}
4329
Steve Anton4171afb2017-11-20 10:20:22 -08004330rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
4331PeerConnection::FindSenderById(const std::string& sender_id) const {
4332 for (auto transceiver : transceivers_) {
4333 for (auto sender : transceiver->internal()->senders()) {
4334 if (sender->id() == sender_id) {
4335 return sender;
4336 }
4337 }
4338 }
4339 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07004340}
4341
Steve Anton4171afb2017-11-20 10:20:22 -08004342rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
4343PeerConnection::FindReceiverById(const std::string& receiver_id) const {
4344 for (auto transceiver : transceivers_) {
4345 for (auto receiver : transceiver->internal()->receivers()) {
4346 if (receiver->id() == receiver_id) {
4347 return receiver;
4348 }
4349 }
4350 }
4351 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07004352}
4353
Steve Anton4171afb2017-11-20 10:20:22 -08004354std::vector<PeerConnection::RtpSenderInfo>*
4355PeerConnection::GetRemoteSenderInfos(cricket::MediaType media_type) {
4356 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
4357 media_type == cricket::MEDIA_TYPE_VIDEO);
4358 return (media_type == cricket::MEDIA_TYPE_AUDIO)
4359 ? &remote_audio_sender_infos_
4360 : &remote_video_sender_infos_;
4361}
4362
4363std::vector<PeerConnection::RtpSenderInfo>* PeerConnection::GetLocalSenderInfos(
deadbeefab9b2d12015-10-14 11:33:11 -07004364 cricket::MediaType media_type) {
4365 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
4366 media_type == cricket::MEDIA_TYPE_VIDEO);
Steve Anton4171afb2017-11-20 10:20:22 -08004367 return (media_type == cricket::MEDIA_TYPE_AUDIO) ? &local_audio_sender_infos_
4368 : &local_video_sender_infos_;
deadbeefab9b2d12015-10-14 11:33:11 -07004369}
4370
Steve Anton4171afb2017-11-20 10:20:22 -08004371const PeerConnection::RtpSenderInfo* PeerConnection::FindSenderInfo(
4372 const std::vector<PeerConnection::RtpSenderInfo>& infos,
deadbeefab9b2d12015-10-14 11:33:11 -07004373 const std::string& stream_label,
Steve Anton4171afb2017-11-20 10:20:22 -08004374 const std::string sender_id) const {
4375 for (const RtpSenderInfo& sender_info : infos) {
4376 if (sender_info.stream_label == stream_label &&
4377 sender_info.sender_id == sender_id) {
4378 return &sender_info;
deadbeefab9b2d12015-10-14 11:33:11 -07004379 }
4380 }
4381 return nullptr;
4382}
4383
4384DataChannel* PeerConnection::FindDataChannelBySid(int sid) const {
4385 for (const auto& channel : sctp_data_channels_) {
4386 if (channel->id() == sid) {
4387 return channel;
4388 }
4389 }
4390 return nullptr;
4391}
4392
deadbeef91dd5672016-05-18 16:55:30 -07004393bool PeerConnection::InitializePortAllocator_n(
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004394 const RTCConfiguration& configuration) {
4395 cricket::ServerAddresses stun_servers;
4396 std::vector<cricket::RelayServerConfig> turn_servers;
deadbeef293e9262017-01-11 12:28:30 -08004397 if (ParseIceServers(configuration.servers, &stun_servers, &turn_servers) !=
4398 RTCErrorType::NONE) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004399 return false;
4400 }
4401
Taylor Brandstetterf8e65772016-06-27 17:20:15 -07004402 port_allocator_->Initialize();
4403
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004404 // To handle both internal and externally created port allocator, we will
4405 // enable BUNDLE here.
4406 int portallocator_flags = port_allocator_->flags();
4407 portallocator_flags |= cricket::PORTALLOCATOR_ENABLE_SHARED_SOCKET |
zhihuangb09b3f92017-03-07 14:40:51 -08004408 cricket::PORTALLOCATOR_ENABLE_IPV6 |
4409 cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI;
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004410 // If the disable-IPv6 flag was specified, we'll not override it
4411 // by experiment.
4412 if (configuration.disable_ipv6) {
4413 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
sprangc1b57a12017-02-28 08:50:47 -08004414 } else if (webrtc::field_trial::FindFullName("WebRTC-IPv6Default")
4415 .find("Disabled") == 0) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004416 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
4417 }
4418
zhihuangb09b3f92017-03-07 14:40:51 -08004419 if (configuration.disable_ipv6_on_wifi) {
4420 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI);
Mirko Bonadei675513b2017-11-09 11:09:25 +01004421 RTC_LOG(LS_INFO) << "IPv6 candidates on Wi-Fi are disabled.";
zhihuangb09b3f92017-03-07 14:40:51 -08004422 }
4423
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004424 if (configuration.tcp_candidate_policy == kTcpCandidatePolicyDisabled) {
4425 portallocator_flags |= cricket::PORTALLOCATOR_DISABLE_TCP;
Mirko Bonadei675513b2017-11-09 11:09:25 +01004426 RTC_LOG(LS_INFO) << "TCP candidates are disabled.";
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004427 }
4428
honghaiz60347052016-05-31 18:29:12 -07004429 if (configuration.candidate_network_policy ==
4430 kCandidateNetworkPolicyLowCost) {
4431 portallocator_flags |= cricket::PORTALLOCATOR_DISABLE_COSTLY_NETWORKS;
Mirko Bonadei675513b2017-11-09 11:09:25 +01004432 RTC_LOG(LS_INFO) << "Do not gather candidates on high-cost networks";
honghaiz60347052016-05-31 18:29:12 -07004433 }
4434
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +01004435 if (configuration.disable_link_local_networks) {
4436 portallocator_flags |= cricket::PORTALLOCATOR_DISABLE_LINK_LOCAL_NETWORKS;
4437 RTC_LOG(LS_INFO) << "Disable candidates on link-local network interfaces.";
4438 }
4439
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004440 port_allocator_->set_flags(portallocator_flags);
4441 // No step delay is used while allocating ports.
4442 port_allocator_->set_step_delay(cricket::kMinimumStepDelay);
4443 port_allocator_->set_candidate_filter(
4444 ConvertIceTransportTypeToCandidateFilter(configuration.type));
deadbeefd21eab32017-07-26 16:50:11 -07004445 port_allocator_->set_max_ipv6_networks(configuration.max_ipv6_networks);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004446
4447 // Call this last since it may create pooled allocator sessions using the
4448 // properties set above.
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08004449 port_allocator_->SetConfiguration(
4450 stun_servers, turn_servers, configuration.ice_candidate_pool_size,
4451 configuration.prune_turn_ports, configuration.turn_customizer,
4452 configuration.stun_candidate_keepalive_interval);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004453 return true;
4454}
4455
deadbeef91dd5672016-05-18 16:55:30 -07004456bool PeerConnection::ReconfigurePortAllocator_n(
deadbeef293e9262017-01-11 12:28:30 -08004457 const cricket::ServerAddresses& stun_servers,
4458 const std::vector<cricket::RelayServerConfig>& turn_servers,
4459 IceTransportsType type,
4460 int candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02004461 bool prune_turn_ports,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08004462 webrtc::TurnCustomizer* turn_customizer,
4463 rtc::Optional<int> stun_candidate_keepalive_interval) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004464 port_allocator_->set_candidate_filter(
deadbeef293e9262017-01-11 12:28:30 -08004465 ConvertIceTransportTypeToCandidateFilter(type));
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004466 // Call this last since it may create pooled allocator sessions using the
4467 // candidate filter set above.
deadbeef6de92f92016-12-12 18:49:32 -08004468 return port_allocator_->SetConfiguration(
Jonas Orelandbdcee282017-10-10 14:01:40 +02004469 stun_servers, turn_servers, candidate_pool_size, prune_turn_ports,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08004470 turn_customizer, stun_candidate_keepalive_interval);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004471}
4472
Steve Antonba818672017-11-06 10:21:57 -08004473cricket::ChannelManager* PeerConnection::channel_manager() const {
4474 return factory_->channel_manager();
4475}
4476
4477MetricsObserverInterface* PeerConnection::metrics_observer() const {
4478 return uma_observer_;
4479}
4480
Elad Alon99c3fe52017-10-13 16:29:40 +02004481bool PeerConnection::StartRtcEventLog_w(
Bjorn Tereliusde939432017-11-20 17:38:14 +01004482 std::unique_ptr<RtcEventLogOutput> output,
4483 int64_t output_period_ms) {
zhihuang77985012017-02-07 15:45:16 -08004484 if (!event_log_) {
4485 return false;
4486 }
Bjorn Tereliusde939432017-11-20 17:38:14 +01004487 return event_log_->StartLogging(std::move(output), output_period_ms);
ivoc14d5dbe2016-07-04 07:06:55 -07004488}
4489
4490void PeerConnection::StopRtcEventLog_w() {
zhihuang77985012017-02-07 15:45:16 -08004491 if (event_log_) {
4492 event_log_->StopLogging();
4493 }
ivoc14d5dbe2016-07-04 07:06:55 -07004494}
nisseeaabdf62017-05-05 02:23:02 -07004495
Steve Anton75737c02017-11-06 10:37:17 -08004496cricket::BaseChannel* PeerConnection::GetChannel(
4497 const std::string& content_name) {
Steve Antondcc3c022017-12-22 16:02:54 -08004498 for (auto transceiver : transceivers_) {
4499 cricket::BaseChannel* channel = transceiver->internal()->channel();
4500 if (channel && channel->content_name() == content_name) {
4501 return channel;
4502 }
Steve Anton75737c02017-11-06 10:37:17 -08004503 }
4504 if (rtp_data_channel() &&
4505 rtp_data_channel()->content_name() == content_name) {
4506 return rtp_data_channel();
4507 }
4508 return nullptr;
4509}
4510
4511bool PeerConnection::GetSctpSslRole(rtc::SSLRole* role) {
4512 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004513 RTC_LOG(LS_INFO)
4514 << "Local and Remote descriptions must be applied to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004515 "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08004516 return false;
4517 }
4518 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004519 RTC_LOG(LS_INFO) << "Non-rejected SCTP m= section is needed to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004520 "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08004521 return false;
4522 }
4523
4524 return transport_controller_->GetSslRole(*sctp_transport_name_, role);
4525}
4526
4527bool PeerConnection::GetSslRole(const std::string& content_name,
4528 rtc::SSLRole* role) {
4529 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004530 RTC_LOG(LS_INFO)
4531 << "Local and Remote descriptions must be applied to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004532 "SSL Role of the session.";
Steve Anton75737c02017-11-06 10:37:17 -08004533 return false;
4534 }
4535
4536 return transport_controller_->GetSslRole(GetTransportName(content_name),
4537 role);
4538}
4539
Steve Antonf8470812017-12-04 10:46:21 -08004540void PeerConnection::SetSessionError(SessionError error,
4541 const std::string& error_desc) {
4542 RTC_DCHECK_RUN_ON(signaling_thread());
4543 if (error != session_error_) {
4544 session_error_ = error;
4545 session_error_desc_ = error_desc;
Steve Anton75737c02017-11-06 10:37:17 -08004546 }
4547}
4548
Steve Anton3828c062017-12-06 10:34:51 -08004549RTCError PeerConnection::UpdateSessionState(SdpType type,
Steve Anton8a006912017-12-04 15:25:56 -08004550 cricket::ContentSource source) {
4551 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08004552
4553 // If there's already a pending error then no state transition should happen.
4554 // But all call-sites should be verifying this before calling us!
Steve Antonf8470812017-12-04 10:46:21 -08004555 RTC_DCHECK(session_error() == SessionError::kNone);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004556
4557 // If this is an answer then we know whether to BUNDLE or not. If both the
4558 // local and remote side have agreed to BUNDLE, go ahead and enable it.
Steve Anton3828c062017-12-06 10:34:51 -08004559 if (type == SdpType::kAnswer) {
Steve Anton75737c02017-11-06 10:37:17 -08004560 const cricket::ContentGroup* local_bundle =
4561 local_description()->description()->GetGroupByName(
4562 cricket::GROUP_TYPE_BUNDLE);
4563 const cricket::ContentGroup* remote_bundle =
4564 remote_description()->description()->GetGroupByName(
4565 cricket::GROUP_TYPE_BUNDLE);
4566 if (local_bundle && remote_bundle) {
4567 // The answerer decides the transport to bundle on.
4568 const cricket::ContentGroup* answer_bundle =
4569 (source == cricket::CS_LOCAL ? local_bundle : remote_bundle);
4570 if (!EnableBundle(*answer_bundle)) {
Steve Anton8a006912017-12-04 15:25:56 -08004571 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
4572 kEnableBundleFailed);
Steve Anton75737c02017-11-06 10:37:17 -08004573 }
4574 }
Steve Anton75737c02017-11-06 10:37:17 -08004575 }
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004576
4577 // Only push down the transport description after potentially enabling BUNDLE;
4578 // we don't want to push down a description on a transport about to be
4579 // destroyed.
Steve Anton3828c062017-12-06 10:34:51 -08004580 RTCError error = PushdownTransportDescription(source, type);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004581 if (!error.ok()) {
4582 return error;
4583 }
4584
4585 // If this is answer-ish we're ready to let media flow.
Steve Anton3828c062017-12-06 10:34:51 -08004586 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Antoned10bd92017-12-05 10:52:59 -08004587 EnableSending();
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004588 }
4589
4590 // Update the signaling state according to the specified state machine (see
4591 // https://w3c.github.io/webrtc-pc/#rtcsignalingstate-enum).
Steve Anton3828c062017-12-06 10:34:51 -08004592 if (type == SdpType::kOffer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004593 ChangeSignalingState(source == cricket::CS_LOCAL
4594 ? PeerConnectionInterface::kHaveLocalOffer
4595 : PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton3828c062017-12-06 10:34:51 -08004596 } else if (type == SdpType::kPrAnswer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004597 ChangeSignalingState(source == cricket::CS_LOCAL
4598 ? PeerConnectionInterface::kHaveLocalPrAnswer
4599 : PeerConnectionInterface::kHaveRemotePrAnswer);
4600 } else {
Steve Anton3828c062017-12-06 10:34:51 -08004601 RTC_DCHECK(type == SdpType::kAnswer);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004602 ChangeSignalingState(PeerConnectionInterface::kStable);
4603 }
4604
4605 // Update internal objects according to the session description's media
4606 // descriptions.
Steve Anton3828c062017-12-06 10:34:51 -08004607 error = PushdownMediaDescription(type, source);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004608 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08004609 return error;
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004610 }
4611
Steve Anton8a006912017-12-04 15:25:56 -08004612 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08004613}
4614
Steve Anton8a006912017-12-04 15:25:56 -08004615RTCError PeerConnection::PushdownMediaDescription(
Steve Anton3828c062017-12-06 10:34:51 -08004616 SdpType type,
Steve Anton8a006912017-12-04 15:25:56 -08004617 cricket::ContentSource source) {
Steve Antoned10bd92017-12-05 10:52:59 -08004618 const SessionDescriptionInterface* sdesc =
4619 (source == cricket::CS_LOCAL ? local_description()
4620 : remote_description());
Steve Anton75737c02017-11-06 10:37:17 -08004621 RTC_DCHECK(sdesc);
Steve Antoned10bd92017-12-05 10:52:59 -08004622
4623 // Push down the new SDP media section for each audio/video transceiver.
4624 for (auto transceiver : transceivers_) {
Steve Anton75737c02017-11-06 10:37:17 -08004625 const ContentInfo* content_info =
Steve Antoned10bd92017-12-05 10:52:59 -08004626 FindMediaSectionForTransceiver(transceiver, sdesc);
4627 cricket::BaseChannel* channel = transceiver->internal()->channel();
4628 if (!channel || !content_info || content_info->rejected) {
Steve Anton75737c02017-11-06 10:37:17 -08004629 continue;
4630 }
4631 const MediaContentDescription* content_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08004632 content_info->media_description();
Steve Antoned10bd92017-12-05 10:52:59 -08004633 if (!content_desc) {
4634 continue;
4635 }
4636 std::string error;
4637 bool success =
4638 (source == cricket::CS_LOCAL)
Steve Anton3828c062017-12-06 10:34:51 -08004639 ? channel->SetLocalContent(content_desc, type, &error)
4640 : channel->SetRemoteContent(content_desc, type, &error);
Steve Antoned10bd92017-12-05 10:52:59 -08004641 if (!success) {
4642 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, std::move(error));
4643 }
4644 }
4645
4646 // If using the RtpDataChannel, push down the new SDP section for it too.
4647 if (rtp_data_channel_) {
4648 const ContentInfo* data_content =
4649 cricket::GetFirstDataContent(sdesc->description());
4650 if (data_content && !data_content->rejected) {
4651 const MediaContentDescription* data_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08004652 data_content->media_description();
Steve Antoned10bd92017-12-05 10:52:59 -08004653 if (data_desc) {
4654 std::string error;
4655 bool success =
4656 (source == cricket::CS_LOCAL)
Steve Anton3828c062017-12-06 10:34:51 -08004657 ? rtp_data_channel_->SetLocalContent(data_desc, type, &error)
4658 : rtp_data_channel_->SetRemoteContent(data_desc, type,
Steve Antoned10bd92017-12-05 10:52:59 -08004659 &error);
4660 if (!success) {
4661 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
4662 std::move(error));
4663 }
Steve Anton75737c02017-11-06 10:37:17 -08004664 }
4665 }
4666 }
Steve Antoned10bd92017-12-05 10:52:59 -08004667
Steve Anton75737c02017-11-06 10:37:17 -08004668 // Need complete offer/answer with an SCTP m= section before starting SCTP,
4669 // according to https://tools.ietf.org/html/draft-ietf-mmusic-sctp-sdp-19
4670 if (sctp_transport_ && local_description() && remote_description() &&
4671 cricket::GetFirstDataContent(local_description()->description()) &&
4672 cricket::GetFirstDataContent(remote_description()->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08004673 bool success = network_thread()->Invoke<bool>(
Steve Anton75737c02017-11-06 10:37:17 -08004674 RTC_FROM_HERE,
4675 rtc::Bind(&PeerConnection::PushdownSctpParameters_n, this, source));
Steve Anton8a006912017-12-04 15:25:56 -08004676 if (!success) {
4677 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
4678 "Failed to push down SCTP parameters.");
4679 }
Steve Anton75737c02017-11-06 10:37:17 -08004680 }
Steve Antoned10bd92017-12-05 10:52:59 -08004681
Steve Anton8a006912017-12-04 15:25:56 -08004682 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08004683}
4684
4685bool PeerConnection::PushdownSctpParameters_n(cricket::ContentSource source) {
4686 RTC_DCHECK(network_thread()->IsCurrent());
4687 RTC_DCHECK(local_description());
4688 RTC_DCHECK(remote_description());
4689 // Apply the SCTP port (which is hidden inside a DataCodec structure...)
4690 // When we support "max-message-size", that would also be pushed down here.
4691 return sctp_transport_->Start(
4692 GetSctpPort(local_description()->description()),
4693 GetSctpPort(remote_description()->description()));
4694}
4695
Steve Anton8a006912017-12-04 15:25:56 -08004696RTCError PeerConnection::PushdownTransportDescription(
4697 cricket::ContentSource source,
Steve Anton3828c062017-12-06 10:34:51 -08004698 SdpType type) {
Steve Anton8a006912017-12-04 15:25:56 -08004699 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08004700
Steve Anton8a006912017-12-04 15:25:56 -08004701 const SessionDescriptionInterface* sdesc =
4702 (source == cricket::CS_LOCAL ? local_description()
4703 : remote_description());
4704 RTC_DCHECK(sdesc);
4705 for (const cricket::TransportInfo& tinfo :
4706 sdesc->description()->transport_infos()) {
4707 std::string error;
4708 bool success;
4709 if (source == cricket::CS_LOCAL) {
4710 success = transport_controller_->SetLocalTransportDescription(
Steve Anton3828c062017-12-06 10:34:51 -08004711 tinfo.content_name, tinfo.description, type, &error);
Steve Anton8a006912017-12-04 15:25:56 -08004712 } else {
4713 success = transport_controller_->SetRemoteTransportDescription(
Steve Anton3828c062017-12-06 10:34:51 -08004714 tinfo.content_name, tinfo.description, type, &error);
Steve Anton8a006912017-12-04 15:25:56 -08004715 }
4716 if (!success) {
Steve Antondcc3c022017-12-22 16:02:54 -08004717 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
4718 "Failed to push down transport description for " +
4719 tinfo.content_name + ": " + error);
Steve Anton75737c02017-11-06 10:37:17 -08004720 }
4721 }
4722
Steve Anton8a006912017-12-04 15:25:56 -08004723 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08004724}
4725
4726bool PeerConnection::GetTransportDescription(
4727 const SessionDescription* description,
4728 const std::string& content_name,
4729 cricket::TransportDescription* tdesc) {
4730 if (!description || !tdesc) {
4731 return false;
4732 }
4733 const TransportInfo* transport_info =
4734 description->GetTransportInfoByName(content_name);
4735 if (!transport_info) {
4736 return false;
4737 }
4738 *tdesc = transport_info->description;
4739 return true;
4740}
4741
4742bool PeerConnection::EnableBundle(const cricket::ContentGroup& bundle) {
4743 const std::string* first_content_name = bundle.FirstContentName();
4744 if (!first_content_name) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004745 RTC_LOG(LS_WARNING) << "Tried to BUNDLE with no contents.";
Steve Anton75737c02017-11-06 10:37:17 -08004746 return false;
4747 }
4748 const std::string& transport_name = *first_content_name;
4749
4750 auto maybe_set_transport = [this, bundle,
4751 transport_name](cricket::BaseChannel* ch) {
4752 if (!ch || !bundle.HasContentName(ch->content_name())) {
Steve Antoned10bd92017-12-05 10:52:59 -08004753 return;
Steve Anton75737c02017-11-06 10:37:17 -08004754 }
4755
4756 std::string old_transport_name = ch->transport_name();
4757 if (old_transport_name == transport_name) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004758 RTC_LOG(LS_INFO) << "BUNDLE already enabled for " << ch->content_name()
4759 << " on " << transport_name << ".";
Steve Antoned10bd92017-12-05 10:52:59 -08004760 return;
Steve Anton75737c02017-11-06 10:37:17 -08004761 }
4762
4763 cricket::DtlsTransportInternal* rtp_dtls_transport =
4764 transport_controller_->CreateDtlsTransport(
4765 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4766 bool need_rtcp = (ch->rtcp_dtls_transport() != nullptr);
4767 cricket::DtlsTransportInternal* rtcp_dtls_transport = nullptr;
4768 if (need_rtcp) {
4769 rtcp_dtls_transport = transport_controller_->CreateDtlsTransport(
4770 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
4771 }
4772
4773 ch->SetTransports(rtp_dtls_transport, rtcp_dtls_transport);
Mirko Bonadei675513b2017-11-09 11:09:25 +01004774 RTC_LOG(LS_INFO) << "Enabled BUNDLE for " << ch->content_name() << " on "
4775 << transport_name << ".";
Steve Anton75737c02017-11-06 10:37:17 -08004776 transport_controller_->DestroyDtlsTransport(
4777 old_transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4778 // If the channel needs rtcp, it means that the channel used to have a
4779 // rtcp transport which needs to be deleted now.
4780 if (need_rtcp) {
4781 transport_controller_->DestroyDtlsTransport(
4782 old_transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
4783 }
Steve Anton75737c02017-11-06 10:37:17 -08004784 };
4785
Steve Antoned10bd92017-12-05 10:52:59 -08004786 for (auto transceiver : transceivers_) {
4787 maybe_set_transport(transceiver->internal()->channel());
Steve Anton75737c02017-11-06 10:37:17 -08004788 }
Steve Antoned10bd92017-12-05 10:52:59 -08004789 maybe_set_transport(rtp_data_channel_);
4790
Steve Anton75737c02017-11-06 10:37:17 -08004791 // For SCTP, transport creation/deletion happens here instead of in the
4792 // object itself.
4793 if (sctp_transport_) {
4794 RTC_DCHECK(sctp_transport_name_);
4795 RTC_DCHECK(sctp_content_name_);
4796 if (transport_name != *sctp_transport_name_ &&
4797 bundle.HasContentName(*sctp_content_name_)) {
4798 network_thread()->Invoke<void>(
4799 RTC_FROM_HERE, rtc::Bind(&PeerConnection::ChangeSctpTransport_n, this,
4800 transport_name));
4801 }
4802 }
4803
4804 return true;
4805}
4806
Steve Anton75737c02017-11-06 10:37:17 -08004807cricket::IceConfig PeerConnection::ParseIceConfig(
4808 const PeerConnectionInterface::RTCConfiguration& config) const {
4809 cricket::ContinualGatheringPolicy gathering_policy;
4810 // TODO(honghaiz): Add the third continual gathering policy in
4811 // PeerConnectionInterface and map it to GATHER_CONTINUALLY_AND_RECOVER.
4812 switch (config.continual_gathering_policy) {
4813 case PeerConnectionInterface::GATHER_ONCE:
4814 gathering_policy = cricket::GATHER_ONCE;
4815 break;
4816 case PeerConnectionInterface::GATHER_CONTINUALLY:
4817 gathering_policy = cricket::GATHER_CONTINUALLY;
4818 break;
4819 default:
4820 RTC_NOTREACHED();
4821 gathering_policy = cricket::GATHER_ONCE;
4822 }
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08004823
Steve Anton75737c02017-11-06 10:37:17 -08004824 cricket::IceConfig ice_config;
4825 ice_config.receiving_timeout = config.ice_connection_receiving_timeout;
4826 ice_config.prioritize_most_likely_candidate_pairs =
4827 config.prioritize_most_likely_ice_candidate_pairs;
4828 ice_config.backup_connection_ping_interval =
4829 config.ice_backup_candidate_pair_ping_interval;
4830 ice_config.continual_gathering_policy = gathering_policy;
4831 ice_config.presume_writable_when_fully_relayed =
4832 config.presume_writable_when_fully_relayed;
4833 ice_config.ice_check_min_interval = config.ice_check_min_interval;
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08004834 ice_config.stun_keepalive_interval = config.stun_candidate_keepalive_interval;
Steve Anton75737c02017-11-06 10:37:17 -08004835 ice_config.regather_all_networks_interval_range =
4836 config.ice_regather_interval_range;
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08004837 ice_config.network_preference = config.network_preference;
Steve Anton75737c02017-11-06 10:37:17 -08004838 return ice_config;
4839}
4840
Steve Anton75737c02017-11-06 10:37:17 -08004841bool PeerConnection::GetLocalTrackIdBySsrc(uint32_t ssrc,
4842 std::string* track_id) {
4843 if (!local_description()) {
4844 return false;
4845 }
4846 return webrtc::GetTrackIdBySsrc(local_description()->description(), ssrc,
4847 track_id);
4848}
4849
4850bool PeerConnection::GetRemoteTrackIdBySsrc(uint32_t ssrc,
4851 std::string* track_id) {
4852 if (!remote_description()) {
4853 return false;
4854 }
4855 return webrtc::GetTrackIdBySsrc(remote_description()->description(), ssrc,
4856 track_id);
4857}
4858
4859bool PeerConnection::SendData(const cricket::SendDataParams& params,
4860 const rtc::CopyOnWriteBuffer& payload,
4861 cricket::SendDataResult* result) {
4862 if (!rtp_data_channel_ && !sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004863 RTC_LOG(LS_ERROR) << "SendData called when rtp_data_channel_ "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004864 "and sctp_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08004865 return false;
4866 }
4867 return rtp_data_channel_
4868 ? rtp_data_channel_->SendData(params, payload, result)
4869 : network_thread()->Invoke<bool>(
4870 RTC_FROM_HERE,
4871 Bind(&cricket::SctpTransportInternal::SendData,
4872 sctp_transport_.get(), params, payload, result));
4873}
4874
4875bool PeerConnection::ConnectDataChannel(DataChannel* webrtc_data_channel) {
4876 if (!rtp_data_channel_ && !sctp_transport_) {
4877 // Don't log an error here, because DataChannels are expected to call
4878 // ConnectDataChannel in this state. It's the only way to initially tell
4879 // whether or not the underlying transport is ready.
4880 return false;
4881 }
4882 if (rtp_data_channel_) {
4883 rtp_data_channel_->SignalReadyToSendData.connect(
4884 webrtc_data_channel, &DataChannel::OnChannelReady);
4885 rtp_data_channel_->SignalDataReceived.connect(webrtc_data_channel,
4886 &DataChannel::OnDataReceived);
4887 } else {
4888 SignalSctpReadyToSendData.connect(webrtc_data_channel,
4889 &DataChannel::OnChannelReady);
4890 SignalSctpDataReceived.connect(webrtc_data_channel,
4891 &DataChannel::OnDataReceived);
4892 SignalSctpStreamClosedRemotely.connect(
4893 webrtc_data_channel, &DataChannel::OnStreamClosedRemotely);
4894 }
4895 return true;
4896}
4897
4898void PeerConnection::DisconnectDataChannel(DataChannel* webrtc_data_channel) {
4899 if (!rtp_data_channel_ && !sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004900 RTC_LOG(LS_ERROR)
4901 << "DisconnectDataChannel called when rtp_data_channel_ and "
4902 "sctp_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08004903 return;
4904 }
4905 if (rtp_data_channel_) {
4906 rtp_data_channel_->SignalReadyToSendData.disconnect(webrtc_data_channel);
4907 rtp_data_channel_->SignalDataReceived.disconnect(webrtc_data_channel);
4908 } else {
4909 SignalSctpReadyToSendData.disconnect(webrtc_data_channel);
4910 SignalSctpDataReceived.disconnect(webrtc_data_channel);
4911 SignalSctpStreamClosedRemotely.disconnect(webrtc_data_channel);
4912 }
4913}
4914
4915void PeerConnection::AddSctpDataStream(int sid) {
4916 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004917 RTC_LOG(LS_ERROR)
4918 << "AddSctpDataStream called when sctp_transport_ is NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08004919 return;
4920 }
4921 network_thread()->Invoke<void>(
4922 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::OpenStream,
4923 sctp_transport_.get(), sid));
4924}
4925
4926void PeerConnection::RemoveSctpDataStream(int sid) {
4927 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004928 RTC_LOG(LS_ERROR) << "RemoveSctpDataStream called when sctp_transport_ is "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004929 "NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08004930 return;
4931 }
4932 network_thread()->Invoke<void>(
4933 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::ResetStream,
4934 sctp_transport_.get(), sid));
4935}
4936
4937bool PeerConnection::ReadyToSendData() const {
4938 return (rtp_data_channel_ && rtp_data_channel_->ready_to_send_data()) ||
4939 sctp_ready_to_send_data_;
4940}
4941
Qingsi Wang72a43a12018-02-20 16:03:18 -08004942cricket::CandidateStatsList PeerConnection::GetPooledCandidateStats() const {
4943 cricket::CandidateStatsList candidate_states_list;
4944 port_allocator_->GetCandidateStatsFromPooledSessions(&candidate_states_list);
4945 return candidate_states_list;
4946}
4947
Steve Anton5dfde182018-02-06 10:34:40 -08004948std::map<std::string, std::string> PeerConnection::GetTransportNamesByMid()
4949 const {
4950 std::map<std::string, std::string> transport_names_by_mid;
4951 for (auto transceiver : transceivers_) {
4952 cricket::BaseChannel* channel = transceiver->internal()->channel();
4953 if (channel) {
4954 transport_names_by_mid[channel->content_name()] =
4955 channel->transport_name();
4956 }
Steve Anton75737c02017-11-06 10:37:17 -08004957 }
Steve Anton5dfde182018-02-06 10:34:40 -08004958 if (rtp_data_channel_) {
4959 transport_names_by_mid[rtp_data_channel_->content_name()] =
4960 rtp_data_channel_->transport_name();
Steve Anton75737c02017-11-06 10:37:17 -08004961 }
4962 if (sctp_transport_) {
Steve Anton5dfde182018-02-06 10:34:40 -08004963 transport_names_by_mid[*sctp_content_name_] = *sctp_transport_name_;
Steve Anton75737c02017-11-06 10:37:17 -08004964 }
Steve Anton5dfde182018-02-06 10:34:40 -08004965 return transport_names_by_mid;
Steve Anton75737c02017-11-06 10:37:17 -08004966}
4967
Steve Anton5dfde182018-02-06 10:34:40 -08004968std::map<std::string, cricket::TransportStats>
4969PeerConnection::GetTransportStatsByNames(
4970 const std::set<std::string>& transport_names) {
4971 if (!network_thread()->IsCurrent()) {
4972 return network_thread()
4973 ->Invoke<std::map<std::string, cricket::TransportStats>>(
4974 RTC_FROM_HERE,
4975 [&] { return GetTransportStatsByNames(transport_names); });
Steve Anton75737c02017-11-06 10:37:17 -08004976 }
Steve Anton5dfde182018-02-06 10:34:40 -08004977 std::map<std::string, cricket::TransportStats> transport_stats_by_name;
4978 for (const std::string& transport_name : transport_names) {
4979 cricket::TransportStats transport_stats;
4980 bool success =
4981 transport_controller_->GetStats(transport_name, &transport_stats);
4982 if (success) {
4983 transport_stats_by_name[transport_name] = std::move(transport_stats);
4984 } else {
4985 RTC_LOG(LS_ERROR) << "Failed to get transport stats for transport_name="
4986 << transport_name;
4987 }
4988 }
4989 return transport_stats_by_name;
Steve Anton75737c02017-11-06 10:37:17 -08004990}
4991
4992bool PeerConnection::GetLocalCertificate(
4993 const std::string& transport_name,
4994 rtc::scoped_refptr<rtc::RTCCertificate>* certificate) {
4995 return transport_controller_->GetLocalCertificate(transport_name,
4996 certificate);
4997}
4998
Taylor Brandstetterc3928662018-02-23 13:04:51 -08004999std::unique_ptr<rtc::SSLCertChain> PeerConnection::GetRemoteSSLCertChain(
Steve Anton75737c02017-11-06 10:37:17 -08005000 const std::string& transport_name) {
Taylor Brandstetterc3928662018-02-23 13:04:51 -08005001 return transport_controller_->GetRemoteSSLCertChain(transport_name);
Steve Anton75737c02017-11-06 10:37:17 -08005002}
5003
5004cricket::DataChannelType PeerConnection::data_channel_type() const {
5005 return data_channel_type_;
5006}
5007
5008bool PeerConnection::IceRestartPending(const std::string& content_name) const {
5009 return pending_ice_restarts_.find(content_name) !=
5010 pending_ice_restarts_.end();
5011}
5012
Steve Anton75737c02017-11-06 10:37:17 -08005013bool PeerConnection::NeedsIceRestart(const std::string& content_name) const {
5014 return transport_controller_->NeedsIceRestart(content_name);
5015}
5016
5017void PeerConnection::OnCertificateReady(
5018 const rtc::scoped_refptr<rtc::RTCCertificate>& certificate) {
5019 transport_controller_->SetLocalCertificate(certificate);
5020}
5021
5022void PeerConnection::OnDtlsSrtpSetupFailure(cricket::BaseChannel*, bool rtcp) {
Steve Antonf8470812017-12-04 10:46:21 -08005023 SetSessionError(SessionError::kTransport,
5024 rtcp ? kDtlsSrtpSetupFailureRtcp : kDtlsSrtpSetupFailureRtp);
Steve Anton75737c02017-11-06 10:37:17 -08005025}
5026
5027void PeerConnection::OnTransportControllerConnectionState(
5028 cricket::IceConnectionState state) {
5029 switch (state) {
5030 case cricket::kIceConnectionConnecting:
5031 // If the current state is Connected or Completed, then there were
5032 // writable channels but now there are not, so the next state must
5033 // be Disconnected.
5034 // kIceConnectionConnecting is currently used as the default,
5035 // un-connected state by the TransportController, so its only use is
5036 // detecting disconnections.
5037 if (ice_connection_state_ ==
5038 PeerConnectionInterface::kIceConnectionConnected ||
5039 ice_connection_state_ ==
5040 PeerConnectionInterface::kIceConnectionCompleted) {
5041 SetIceConnectionState(
5042 PeerConnectionInterface::kIceConnectionDisconnected);
5043 }
5044 break;
5045 case cricket::kIceConnectionFailed:
5046 SetIceConnectionState(PeerConnectionInterface::kIceConnectionFailed);
5047 break;
5048 case cricket::kIceConnectionConnected:
Mirko Bonadei675513b2017-11-09 11:09:25 +01005049 RTC_LOG(LS_INFO) << "Changing to ICE connected state because "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005050 "all transports are writable.";
Steve Anton75737c02017-11-06 10:37:17 -08005051 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
5052 break;
5053 case cricket::kIceConnectionCompleted:
Mirko Bonadei675513b2017-11-09 11:09:25 +01005054 RTC_LOG(LS_INFO) << "Changing to ICE completed state because "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005055 "all transports are complete.";
Steve Anton75737c02017-11-06 10:37:17 -08005056 if (ice_connection_state_ !=
5057 PeerConnectionInterface::kIceConnectionConnected) {
5058 // If jumping directly from "checking" to "connected",
5059 // signal "connected" first.
5060 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
5061 }
5062 SetIceConnectionState(PeerConnectionInterface::kIceConnectionCompleted);
5063 if (metrics_observer()) {
5064 ReportTransportStats();
5065 }
5066 break;
5067 default:
5068 RTC_NOTREACHED();
5069 }
5070}
5071
5072void PeerConnection::OnTransportControllerCandidatesGathered(
5073 const std::string& transport_name,
5074 const cricket::Candidates& candidates) {
5075 RTC_DCHECK(signaling_thread()->IsCurrent());
5076 int sdp_mline_index;
5077 if (!GetLocalCandidateMediaIndex(transport_name, &sdp_mline_index)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005078 RTC_LOG(LS_ERROR)
5079 << "OnTransportControllerCandidatesGathered: content name "
5080 << transport_name << " not found";
Steve Anton75737c02017-11-06 10:37:17 -08005081 return;
5082 }
5083
5084 for (cricket::Candidates::const_iterator citer = candidates.begin();
5085 citer != candidates.end(); ++citer) {
5086 // Use transport_name as the candidate media id.
5087 std::unique_ptr<JsepIceCandidate> candidate(
5088 new JsepIceCandidate(transport_name, sdp_mline_index, *citer));
5089 if (local_description()) {
5090 mutable_local_description()->AddCandidate(candidate.get());
5091 }
5092 OnIceCandidate(std::move(candidate));
5093 }
5094}
5095
5096void PeerConnection::OnTransportControllerCandidatesRemoved(
5097 const std::vector<cricket::Candidate>& candidates) {
5098 RTC_DCHECK(signaling_thread()->IsCurrent());
5099 // Sanity check.
5100 for (const cricket::Candidate& candidate : candidates) {
5101 if (candidate.transport_name().empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005102 RTC_LOG(LS_ERROR) << "OnTransportControllerCandidatesRemoved: "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005103 "empty content name in candidate "
Mirko Bonadei675513b2017-11-09 11:09:25 +01005104 << candidate.ToString();
Steve Anton75737c02017-11-06 10:37:17 -08005105 return;
5106 }
5107 }
5108
5109 if (local_description()) {
5110 mutable_local_description()->RemoveCandidates(candidates);
5111 }
5112 OnIceCandidatesRemoved(candidates);
5113}
5114
5115void PeerConnection::OnTransportControllerDtlsHandshakeError(
5116 rtc::SSLHandshakeError error) {
5117 if (metrics_observer()) {
5118 metrics_observer()->IncrementEnumCounter(
5119 webrtc::kEnumCounterDtlsHandshakeError, static_cast<int>(error),
5120 static_cast<int>(rtc::SSLHandshakeError::MAX_VALUE));
5121 }
5122}
5123
Steve Antoned10bd92017-12-05 10:52:59 -08005124void PeerConnection::EnableSending() {
5125 for (auto transceiver : transceivers_) {
5126 cricket::BaseChannel* channel = transceiver->internal()->channel();
5127 if (channel && !channel->enabled()) {
5128 channel->Enable(true);
5129 }
Steve Anton75737c02017-11-06 10:37:17 -08005130 }
5131
Steve Anton4171afb2017-11-20 10:20:22 -08005132 if (rtp_data_channel_ && !rtp_data_channel_->enabled()) {
Steve Anton75737c02017-11-06 10:37:17 -08005133 rtp_data_channel_->Enable(true);
Steve Anton4171afb2017-11-20 10:20:22 -08005134 }
Steve Anton75737c02017-11-06 10:37:17 -08005135}
5136
5137// Returns the media index for a local ice candidate given the content name.
5138bool PeerConnection::GetLocalCandidateMediaIndex(
5139 const std::string& content_name,
5140 int* sdp_mline_index) {
5141 if (!local_description() || !sdp_mline_index) {
5142 return false;
5143 }
5144
5145 bool content_found = false;
5146 const ContentInfos& contents = local_description()->description()->contents();
5147 for (size_t index = 0; index < contents.size(); ++index) {
5148 if (contents[index].name == content_name) {
5149 *sdp_mline_index = static_cast<int>(index);
5150 content_found = true;
5151 break;
5152 }
5153 }
5154 return content_found;
5155}
5156
5157bool PeerConnection::UseCandidatesInSessionDescription(
5158 const SessionDescriptionInterface* remote_desc) {
5159 if (!remote_desc) {
5160 return true;
5161 }
5162 bool ret = true;
5163
5164 for (size_t m = 0; m < remote_desc->number_of_mediasections(); ++m) {
5165 const IceCandidateCollection* candidates = remote_desc->candidates(m);
5166 for (size_t n = 0; n < candidates->count(); ++n) {
5167 const IceCandidateInterface* candidate = candidates->at(n);
5168 bool valid = false;
5169 if (!ReadyToUseRemoteCandidate(candidate, remote_desc, &valid)) {
5170 if (valid) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005171 RTC_LOG(LS_INFO)
5172 << "UseCandidatesInSessionDescription: Not ready to use "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005173 "candidate.";
Steve Anton75737c02017-11-06 10:37:17 -08005174 }
5175 continue;
5176 }
5177 ret = UseCandidate(candidate);
5178 if (!ret) {
5179 break;
5180 }
5181 }
5182 }
5183 return ret;
5184}
5185
5186bool PeerConnection::UseCandidate(const IceCandidateInterface* candidate) {
5187 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
5188 size_t remote_content_size =
5189 remote_description()->description()->contents().size();
5190 if (mediacontent_index >= remote_content_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005191 RTC_LOG(LS_ERROR) << "UseCandidate: Invalid candidate media index.";
Steve Anton75737c02017-11-06 10:37:17 -08005192 return false;
5193 }
5194
5195 cricket::ContentInfo content =
5196 remote_description()->description()->contents()[mediacontent_index];
5197 std::vector<cricket::Candidate> candidates;
5198 candidates.push_back(candidate->candidate());
5199 // Invoking BaseSession method to handle remote candidates.
5200 std::string error;
5201 if (transport_controller_->AddRemoteCandidates(content.name, candidates,
5202 &error)) {
5203 // Candidates successfully submitted for checking.
5204 if (ice_connection_state_ == PeerConnectionInterface::kIceConnectionNew ||
5205 ice_connection_state_ ==
5206 PeerConnectionInterface::kIceConnectionDisconnected) {
5207 // If state is New, then the session has just gotten its first remote ICE
5208 // candidates, so go to Checking.
5209 // If state is Disconnected, the session is re-using old candidates or
5210 // receiving additional ones, so go to Checking.
5211 // If state is Connected, stay Connected.
5212 // TODO(bemasc): If state is Connected, and the new candidates are for a
5213 // newly added transport, then the state actually _should_ move to
5214 // checking. Add a way to distinguish that case.
5215 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
5216 }
5217 // TODO(bemasc): If state is Completed, go back to Connected.
5218 } else {
5219 if (!error.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005220 RTC_LOG(LS_WARNING) << error;
Steve Anton75737c02017-11-06 10:37:17 -08005221 }
5222 }
5223 return true;
5224}
5225
5226void PeerConnection::RemoveUnusedChannels(const SessionDescription* desc) {
Steve Anton75737c02017-11-06 10:37:17 -08005227 // Destroy video channel first since it may have a pointer to the
5228 // voice channel.
5229 const cricket::ContentInfo* video_info = cricket::GetFirstVideoContent(desc);
Steve Anton6fec8802017-12-04 10:37:29 -08005230 if (!video_info || video_info->rejected) {
5231 DestroyTransceiverChannel(GetVideoTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08005232 }
5233
Steve Anton6fec8802017-12-04 10:37:29 -08005234 const cricket::ContentInfo* audio_info = cricket::GetFirstAudioContent(desc);
5235 if (!audio_info || audio_info->rejected) {
5236 DestroyTransceiverChannel(GetAudioTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08005237 }
5238
5239 const cricket::ContentInfo* data_info = cricket::GetFirstDataContent(desc);
5240 if (!data_info || data_info->rejected) {
Steve Anton6fec8802017-12-04 10:37:29 -08005241 DestroyDataChannel();
Steve Anton75737c02017-11-06 10:37:17 -08005242 }
5243}
5244
Steve Antoneda6ccd2017-12-04 10:21:55 -08005245std::string PeerConnection::GetTransportNameForMediaSection(
5246 const std::string& mid,
5247 const cricket::ContentGroup* bundle_group) const {
5248 if (!bundle_group) {
5249 return mid;
Steve Anton75737c02017-11-06 10:37:17 -08005250 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005251 const std::string* first_content_name = bundle_group->FirstContentName();
Steve Anton75737c02017-11-06 10:37:17 -08005252 if (!first_content_name) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005253 RTC_LOG(LS_WARNING) << "Tried to BUNDLE with no contents.";
Steve Antoneda6ccd2017-12-04 10:21:55 -08005254 return mid;
Steve Anton75737c02017-11-06 10:37:17 -08005255 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005256 if (!bundle_group->HasContentName(mid)) {
5257 RTC_LOG(LS_WARNING) << mid << " is not part of any bundle group";
5258 return mid;
Steve Anton75737c02017-11-06 10:37:17 -08005259 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005260 RTC_LOG(LS_INFO) << "Bundling " << mid << " on " << *first_content_name;
5261 return *first_content_name;
Steve Anton75737c02017-11-06 10:37:17 -08005262}
5263
Steve Antondcc3c022017-12-22 16:02:54 -08005264RTCErrorOr<const cricket::ContentGroup*> PeerConnection::GetEarlyBundleGroup(
5265 const SessionDescription& desc) const {
Steve Anton75737c02017-11-06 10:37:17 -08005266 const cricket::ContentGroup* bundle_group = nullptr;
5267 if (configuration_.bundle_policy ==
5268 PeerConnectionInterface::kBundlePolicyMaxBundle) {
Steve Antondcc3c022017-12-22 16:02:54 -08005269 bundle_group = desc.GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton75737c02017-11-06 10:37:17 -08005270 if (!bundle_group) {
Steve Anton8a006912017-12-04 15:25:56 -08005271 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5272 "max-bundle configured but session description "
5273 "has no BUNDLE group");
Steve Anton75737c02017-11-06 10:37:17 -08005274 }
5275 }
Steve Antondcc3c022017-12-22 16:02:54 -08005276 return std::move(bundle_group);
5277}
5278
5279RTCError PeerConnection::CreateChannels(const SessionDescription& desc) {
5280 auto bundle_group_or_error = GetEarlyBundleGroup(desc);
5281 if (!bundle_group_or_error.ok()) {
5282 return bundle_group_or_error.MoveError();
5283 }
5284 const cricket::ContentGroup* bundle_group = bundle_group_or_error.MoveValue();
Steve Anton75737c02017-11-06 10:37:17 -08005285
Steve Antoneda6ccd2017-12-04 10:21:55 -08005286 // Creating the media channels and transport proxies.
Steve Antondcc3c022017-12-22 16:02:54 -08005287 const cricket::ContentInfo* voice = cricket::GetFirstAudioContent(&desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08005288 if (voice && !voice->rejected &&
5289 !GetAudioTransceiver()->internal()->channel()) {
5290 cricket::VoiceChannel* voice_channel = CreateVoiceChannel(
5291 voice->name,
5292 GetTransportNameForMediaSection(voice->name, bundle_group));
5293 if (!voice_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08005294 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5295 "Failed to create voice channel.");
Steve Antoneda6ccd2017-12-04 10:21:55 -08005296 }
5297 GetAudioTransceiver()->internal()->SetChannel(voice_channel);
5298 }
5299
Steve Antondcc3c022017-12-22 16:02:54 -08005300 const cricket::ContentInfo* video = cricket::GetFirstVideoContent(&desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08005301 if (video && !video->rejected &&
5302 !GetVideoTransceiver()->internal()->channel()) {
5303 cricket::VideoChannel* video_channel = CreateVideoChannel(
5304 video->name,
5305 GetTransportNameForMediaSection(video->name, bundle_group));
5306 if (!video_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08005307 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5308 "Failed to create video channel.");
Steve Anton75737c02017-11-06 10:37:17 -08005309 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005310 GetVideoTransceiver()->internal()->SetChannel(video_channel);
Steve Anton75737c02017-11-06 10:37:17 -08005311 }
5312
Steve Antondcc3c022017-12-22 16:02:54 -08005313 const cricket::ContentInfo* data = cricket::GetFirstDataContent(&desc);
Steve Anton75737c02017-11-06 10:37:17 -08005314 if (data_channel_type_ != cricket::DCT_NONE && data && !data->rejected &&
5315 !rtp_data_channel_ && !sctp_transport_) {
Steve Antoneda6ccd2017-12-04 10:21:55 -08005316 if (!CreateDataChannel(data->name, GetTransportNameForMediaSection(
5317 data->name, bundle_group))) {
Steve Anton8a006912017-12-04 15:25:56 -08005318 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5319 "Failed to create data channel.");
Steve Anton75737c02017-11-06 10:37:17 -08005320 }
5321 }
5322
Steve Anton8a006912017-12-04 15:25:56 -08005323 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08005324}
5325
Steve Anton4171afb2017-11-20 10:20:22 -08005326// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08005327cricket::VoiceChannel* PeerConnection::CreateVoiceChannel(
5328 const std::string& mid,
5329 const std::string& transport_name) {
Steve Anton75737c02017-11-06 10:37:17 -08005330 cricket::DtlsTransportInternal* rtp_dtls_transport =
5331 transport_controller_->CreateDtlsTransport(
5332 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5333 cricket::DtlsTransportInternal* rtcp_dtls_transport = nullptr;
5334 if (configuration_.rtcp_mux_policy !=
5335 PeerConnectionInterface::kRtcpMuxPolicyRequire) {
5336 rtcp_dtls_transport = transport_controller_->CreateDtlsTransport(
5337 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
5338 }
5339
5340 cricket::VoiceChannel* voice_channel = channel_manager()->CreateVoiceChannel(
5341 call_.get(), configuration_.media_config, rtp_dtls_transport,
Steve Antoneda6ccd2017-12-04 10:21:55 -08005342 rtcp_dtls_transport, signaling_thread(), mid, SrtpRequired(),
5343 audio_options_);
Steve Anton75737c02017-11-06 10:37:17 -08005344 if (!voice_channel) {
5345 transport_controller_->DestroyDtlsTransport(
5346 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5347 if (rtcp_dtls_transport) {
5348 transport_controller_->DestroyDtlsTransport(
5349 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
5350 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005351 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08005352 }
Steve Anton75737c02017-11-06 10:37:17 -08005353 voice_channel->SignalRtcpMuxFullyActive.connect(
5354 this, &PeerConnection::DestroyRtcpTransport_n);
5355 voice_channel->SignalDtlsSrtpSetupFailure.connect(
5356 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08005357 voice_channel->SignalSentPacket.connect(this,
5358 &PeerConnection::OnSentPacket_w);
Steve Anton4171afb2017-11-20 10:20:22 -08005359
Steve Antoneda6ccd2017-12-04 10:21:55 -08005360 return voice_channel;
Steve Anton75737c02017-11-06 10:37:17 -08005361}
5362
Steve Anton4171afb2017-11-20 10:20:22 -08005363// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08005364cricket::VideoChannel* PeerConnection::CreateVideoChannel(
5365 const std::string& mid,
5366 const std::string& transport_name) {
Steve Anton75737c02017-11-06 10:37:17 -08005367 cricket::DtlsTransportInternal* rtp_dtls_transport =
5368 transport_controller_->CreateDtlsTransport(
5369 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5370 cricket::DtlsTransportInternal* rtcp_dtls_transport = nullptr;
5371 if (configuration_.rtcp_mux_policy !=
5372 PeerConnectionInterface::kRtcpMuxPolicyRequire) {
5373 rtcp_dtls_transport = transport_controller_->CreateDtlsTransport(
5374 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
5375 }
5376
5377 cricket::VideoChannel* video_channel = channel_manager()->CreateVideoChannel(
5378 call_.get(), configuration_.media_config, rtp_dtls_transport,
Steve Antoneda6ccd2017-12-04 10:21:55 -08005379 rtcp_dtls_transport, signaling_thread(), mid, SrtpRequired(),
5380 video_options_);
Steve Anton75737c02017-11-06 10:37:17 -08005381
5382 if (!video_channel) {
5383 transport_controller_->DestroyDtlsTransport(
5384 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5385 if (rtcp_dtls_transport) {
5386 transport_controller_->DestroyDtlsTransport(
5387 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
5388 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005389 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08005390 }
Steve Anton75737c02017-11-06 10:37:17 -08005391 video_channel->SignalRtcpMuxFullyActive.connect(
5392 this, &PeerConnection::DestroyRtcpTransport_n);
5393 video_channel->SignalDtlsSrtpSetupFailure.connect(
5394 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08005395 video_channel->SignalSentPacket.connect(this,
5396 &PeerConnection::OnSentPacket_w);
Steve Anton4171afb2017-11-20 10:20:22 -08005397
Steve Antoneda6ccd2017-12-04 10:21:55 -08005398 return video_channel;
Steve Anton75737c02017-11-06 10:37:17 -08005399}
5400
Steve Antoneda6ccd2017-12-04 10:21:55 -08005401bool PeerConnection::CreateDataChannel(const std::string& mid,
5402 const std::string& transport_name) {
Steve Anton75737c02017-11-06 10:37:17 -08005403 bool sctp = (data_channel_type_ == cricket::DCT_SCTP);
5404 if (sctp) {
5405 if (!sctp_factory_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005406 RTC_LOG(LS_ERROR)
Steve Anton75737c02017-11-06 10:37:17 -08005407 << "Trying to create SCTP transport, but didn't compile with "
5408 "SCTP support (HAVE_SCTP)";
5409 return false;
5410 }
5411 if (!network_thread()->Invoke<bool>(
5412 RTC_FROM_HERE, rtc::Bind(&PeerConnection::CreateSctpTransport_n,
Steve Antoneda6ccd2017-12-04 10:21:55 -08005413 this, mid, transport_name))) {
Steve Anton75737c02017-11-06 10:37:17 -08005414 return false;
5415 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005416 for (const auto& channel : sctp_data_channels_) {
5417 channel->OnTransportChannelCreated();
5418 }
Steve Anton75737c02017-11-06 10:37:17 -08005419 } else {
Steve Anton75737c02017-11-06 10:37:17 -08005420 cricket::DtlsTransportInternal* rtp_dtls_transport =
5421 transport_controller_->CreateDtlsTransport(
5422 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5423 cricket::DtlsTransportInternal* rtcp_dtls_transport = nullptr;
5424 if (configuration_.rtcp_mux_policy !=
5425 PeerConnectionInterface::kRtcpMuxPolicyRequire) {
5426 rtcp_dtls_transport = transport_controller_->CreateDtlsTransport(
5427 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
5428 }
5429
5430 rtp_data_channel_ = channel_manager()->CreateRtpDataChannel(
5431 configuration_.media_config, rtp_dtls_transport, rtcp_dtls_transport,
Steve Antoneda6ccd2017-12-04 10:21:55 -08005432 signaling_thread(), mid, SrtpRequired());
Steve Anton75737c02017-11-06 10:37:17 -08005433
5434 if (!rtp_data_channel_) {
5435 transport_controller_->DestroyDtlsTransport(
5436 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5437 if (rtcp_dtls_transport) {
5438 transport_controller_->DestroyDtlsTransport(
5439 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
5440 }
5441 return false;
5442 }
5443
5444 rtp_data_channel_->SignalRtcpMuxFullyActive.connect(
5445 this, &PeerConnection::DestroyRtcpTransport_n);
5446 rtp_data_channel_->SignalDtlsSrtpSetupFailure.connect(
5447 this, &PeerConnection::OnDtlsSrtpSetupFailure);
5448 rtp_data_channel_->SignalSentPacket.connect(
5449 this, &PeerConnection::OnSentPacket_w);
5450 }
5451
Steve Anton75737c02017-11-06 10:37:17 -08005452 return true;
5453}
5454
5455Call::Stats PeerConnection::GetCallStats() {
5456 if (!worker_thread()->IsCurrent()) {
5457 return worker_thread()->Invoke<Call::Stats>(
5458 RTC_FROM_HERE, rtc::Bind(&PeerConnection::GetCallStats, this));
5459 }
5460 if (call_) {
5461 return call_->GetStats();
5462 } else {
5463 return Call::Stats();
5464 }
5465}
5466
Steve Anton75737c02017-11-06 10:37:17 -08005467bool PeerConnection::CreateSctpTransport_n(const std::string& content_name,
5468 const std::string& transport_name) {
5469 RTC_DCHECK(network_thread()->IsCurrent());
5470 RTC_DCHECK(sctp_factory_);
5471 cricket::DtlsTransportInternal* tc =
5472 transport_controller_->CreateDtlsTransport_n(
5473 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5474 sctp_transport_ = sctp_factory_->CreateSctpTransport(tc);
5475 RTC_DCHECK(sctp_transport_);
5476 sctp_invoker_.reset(new rtc::AsyncInvoker());
5477 sctp_transport_->SignalReadyToSendData.connect(
5478 this, &PeerConnection::OnSctpTransportReadyToSendData_n);
5479 sctp_transport_->SignalDataReceived.connect(
5480 this, &PeerConnection::OnSctpTransportDataReceived_n);
5481 sctp_transport_->SignalStreamClosedRemotely.connect(
5482 this, &PeerConnection::OnSctpStreamClosedRemotely_n);
Oskar Sundbom9b28a032017-11-16 10:53:30 +01005483 sctp_transport_name_ = transport_name;
5484 sctp_content_name_ = content_name;
Steve Anton75737c02017-11-06 10:37:17 -08005485 return true;
5486}
5487
5488void PeerConnection::ChangeSctpTransport_n(const std::string& transport_name) {
5489 RTC_DCHECK(network_thread()->IsCurrent());
5490 RTC_DCHECK(sctp_transport_);
5491 RTC_DCHECK(sctp_transport_name_);
5492 std::string old_sctp_transport_name = *sctp_transport_name_;
Oskar Sundbom9b28a032017-11-16 10:53:30 +01005493 sctp_transport_name_ = transport_name;
Steve Anton75737c02017-11-06 10:37:17 -08005494 cricket::DtlsTransportInternal* tc =
5495 transport_controller_->CreateDtlsTransport_n(
5496 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5497 sctp_transport_->SetTransportChannel(tc);
5498 transport_controller_->DestroyDtlsTransport_n(
5499 old_sctp_transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5500}
5501
5502void PeerConnection::DestroySctpTransport_n() {
5503 RTC_DCHECK(network_thread()->IsCurrent());
5504 sctp_transport_.reset(nullptr);
Taylor Brandstetter389a97c2018-01-03 16:26:06 -08005505 transport_controller_->DestroyDtlsTransport_n(
5506 *sctp_transport_name_, cricket::ICE_CANDIDATE_COMPONENT_RTP);
Steve Anton75737c02017-11-06 10:37:17 -08005507 sctp_content_name_.reset();
5508 sctp_transport_name_.reset();
5509 sctp_invoker_.reset(nullptr);
5510 sctp_ready_to_send_data_ = false;
5511}
5512
5513void PeerConnection::OnSctpTransportReadyToSendData_n() {
5514 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5515 RTC_DCHECK(network_thread()->IsCurrent());
5516 // Note: Cannot use rtc::Bind here because it will grab a reference to
5517 // PeerConnection and potentially cause PeerConnection to live longer than
5518 // expected. It is safe not to grab a reference since the sctp_invoker_ will
5519 // be destroyed before PeerConnection is destroyed, and at that point all
5520 // pending tasks will be cleared.
5521 sctp_invoker_->AsyncInvoke<void>(RTC_FROM_HERE, signaling_thread(), [this] {
5522 OnSctpTransportReadyToSendData_s(true);
5523 });
5524}
5525
5526void PeerConnection::OnSctpTransportReadyToSendData_s(bool ready) {
5527 RTC_DCHECK(signaling_thread()->IsCurrent());
5528 sctp_ready_to_send_data_ = ready;
5529 SignalSctpReadyToSendData(ready);
5530}
5531
5532void PeerConnection::OnSctpTransportDataReceived_n(
5533 const cricket::ReceiveDataParams& params,
5534 const rtc::CopyOnWriteBuffer& payload) {
5535 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5536 RTC_DCHECK(network_thread()->IsCurrent());
5537 // Note: Cannot use rtc::Bind here because it will grab a reference to
5538 // PeerConnection and potentially cause PeerConnection to live longer than
5539 // expected. It is safe not to grab a reference since the sctp_invoker_ will
5540 // be destroyed before PeerConnection is destroyed, and at that point all
5541 // pending tasks will be cleared.
5542 sctp_invoker_->AsyncInvoke<void>(
5543 RTC_FROM_HERE, signaling_thread(), [this, params, payload] {
5544 OnSctpTransportDataReceived_s(params, payload);
5545 });
5546}
5547
5548void PeerConnection::OnSctpTransportDataReceived_s(
5549 const cricket::ReceiveDataParams& params,
5550 const rtc::CopyOnWriteBuffer& payload) {
5551 RTC_DCHECK(signaling_thread()->IsCurrent());
5552 if (params.type == cricket::DMT_CONTROL && IsOpenMessage(payload)) {
5553 // Received OPEN message; parse and signal that a new data channel should
5554 // be created.
5555 std::string label;
5556 InternalDataChannelInit config;
5557 config.id = params.ssrc;
5558 if (!ParseDataChannelOpenMessage(payload, &label, &config)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005559 RTC_LOG(LS_WARNING) << "Failed to parse the OPEN message for sid "
5560 << params.ssrc;
Steve Anton75737c02017-11-06 10:37:17 -08005561 return;
5562 }
5563 config.open_handshake_role = InternalDataChannelInit::kAcker;
5564 OnDataChannelOpenMessage(label, config);
5565 } else {
5566 // Otherwise just forward the signal.
5567 SignalSctpDataReceived(params, payload);
5568 }
5569}
5570
5571void PeerConnection::OnSctpStreamClosedRemotely_n(int sid) {
5572 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5573 RTC_DCHECK(network_thread()->IsCurrent());
5574 sctp_invoker_->AsyncInvoke<void>(
5575 RTC_FROM_HERE, signaling_thread(),
5576 rtc::Bind(&sigslot::signal1<int>::operator(),
5577 &SignalSctpStreamClosedRemotely, sid));
5578}
5579
5580// Returns false if bundle is enabled and rtcp_mux is disabled.
5581bool PeerConnection::ValidateBundleSettings(const SessionDescription* desc) {
5582 bool bundle_enabled = desc->HasGroup(cricket::GROUP_TYPE_BUNDLE);
5583 if (!bundle_enabled)
5584 return true;
5585
5586 const cricket::ContentGroup* bundle_group =
5587 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
5588 RTC_DCHECK(bundle_group != NULL);
5589
5590 const cricket::ContentInfos& contents = desc->contents();
5591 for (cricket::ContentInfos::const_iterator citer = contents.begin();
5592 citer != contents.end(); ++citer) {
5593 const cricket::ContentInfo* content = (&*citer);
5594 RTC_DCHECK(content != NULL);
5595 if (bundle_group->HasContentName(content->name) && !content->rejected &&
Steve Anton5adfafd2017-12-20 16:34:00 -08005596 content->type == MediaProtocolType::kRtp) {
Steve Anton75737c02017-11-06 10:37:17 -08005597 if (!HasRtcpMuxEnabled(content))
5598 return false;
5599 }
5600 }
5601 // RTCP-MUX is enabled in all the contents.
5602 return true;
5603}
5604
5605bool PeerConnection::HasRtcpMuxEnabled(const cricket::ContentInfo* content) {
Steve Antonb1c1de12017-12-21 15:14:30 -08005606 return content->media_description()->rtcp_mux();
Steve Anton75737c02017-11-06 10:37:17 -08005607}
5608
Steve Anton8a006912017-12-04 15:25:56 -08005609RTCError PeerConnection::ValidateSessionDescription(
Steve Anton75737c02017-11-06 10:37:17 -08005610 const SessionDescriptionInterface* sdesc,
Steve Anton8a006912017-12-04 15:25:56 -08005611 cricket::ContentSource source) {
Steve Antonf8470812017-12-04 10:46:21 -08005612 if (session_error() != SessionError::kNone) {
Steve Anton8a006912017-12-04 15:25:56 -08005613 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
Steve Anton75737c02017-11-06 10:37:17 -08005614 }
5615
5616 if (!sdesc || !sdesc->description()) {
Steve Anton8a006912017-12-04 15:25:56 -08005617 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidSdp);
Steve Anton75737c02017-11-06 10:37:17 -08005618 }
5619
Steve Anton3828c062017-12-06 10:34:51 -08005620 SdpType type = sdesc->GetType();
5621 if ((source == cricket::CS_LOCAL && !ExpectSetLocalDescription(type)) ||
5622 (source == cricket::CS_REMOTE && !ExpectSetRemoteDescription(type))) {
Steve Anton8a006912017-12-04 15:25:56 -08005623 LOG_AND_RETURN_ERROR(
5624 RTCErrorType::INVALID_PARAMETER,
5625 "Called in wrong state: " + GetSignalingStateString(signaling_state()));
Steve Anton75737c02017-11-06 10:37:17 -08005626 }
5627
5628 // Verify crypto settings.
5629 std::string crypto_error;
Steve Anton8a006912017-12-04 15:25:56 -08005630 if (webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED ||
5631 dtls_enabled_) {
Harald Alvestrand194939b2018-01-24 16:04:13 +01005632 RTCError crypto_error =
5633 VerifyCrypto(sdesc->description(), dtls_enabled_, uma_observer_);
Steve Anton8a006912017-12-04 15:25:56 -08005634 if (!crypto_error.ok()) {
5635 return crypto_error;
5636 }
Steve Anton75737c02017-11-06 10:37:17 -08005637 }
5638
5639 // Verify ice-ufrag and ice-pwd.
5640 if (!VerifyIceUfragPwdPresent(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08005641 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5642 kSdpWithoutIceUfragPwd);
Steve Anton75737c02017-11-06 10:37:17 -08005643 }
5644
5645 if (!ValidateBundleSettings(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08005646 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5647 kBundleWithoutRtcpMux);
Steve Anton75737c02017-11-06 10:37:17 -08005648 }
5649
5650 // TODO(skvlad): When the local rtcp-mux policy is Require, reject any
5651 // m-lines that do not rtcp-mux enabled.
5652
5653 // Verify m-lines in Answer when compared against Offer.
Steve Anton3828c062017-12-06 10:34:51 -08005654 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Seth Hampsonae8a90a2018-02-13 15:33:48 -08005655 // With an answer we want to compare the new answer session description with
5656 // the offer's session description from the current negotiation.
Steve Anton75737c02017-11-06 10:37:17 -08005657 const cricket::SessionDescription* offer_desc =
5658 (source == cricket::CS_LOCAL) ? remote_description()->description()
5659 : local_description()->description();
Seth Hampsonae8a90a2018-02-13 15:33:48 -08005660 if (!MediaSectionsHaveSameCount(*offer_desc, *sdesc->description()) ||
5661 !MediaSectionsInSameOrder(*offer_desc, nullptr, *sdesc->description(),
5662 type)) {
Steve Anton8a006912017-12-04 15:25:56 -08005663 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5664 kMlineMismatchInAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08005665 }
5666 } else {
Steve Anton75737c02017-11-06 10:37:17 -08005667 // The re-offers should respect the order of m= sections in current
5668 // description. See RFC3264 Section 8 paragraph 4 for more details.
Seth Hampsonae8a90a2018-02-13 15:33:48 -08005669 // With a re-offer, either the current local or current remote descriptions
5670 // could be the most up to date, so we would like to check against both of
5671 // them if they exist. It could be the case that one of them has a 0 port
5672 // for a media section, but the other does not. This is important to check
5673 // against in the case that we are recycling an m= section.
5674 const cricket::SessionDescription* current_desc = nullptr;
5675 const cricket::SessionDescription* secondary_current_desc = nullptr;
5676 if (local_description()) {
5677 current_desc = local_description()->description();
5678 if (remote_description()) {
5679 secondary_current_desc = remote_description()->description();
5680 }
5681 } else if (remote_description()) {
5682 current_desc = remote_description()->description();
5683 }
Steve Anton75737c02017-11-06 10:37:17 -08005684 if (current_desc &&
Seth Hampsonae8a90a2018-02-13 15:33:48 -08005685 !MediaSectionsInSameOrder(*current_desc, secondary_current_desc,
5686 *sdesc->description(), type)) {
Steve Anton8a006912017-12-04 15:25:56 -08005687 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5688 kMlineMismatchInSubsequentOffer);
Steve Anton75737c02017-11-06 10:37:17 -08005689 }
5690 }
5691
Steve Anton8a006912017-12-04 15:25:56 -08005692 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08005693}
5694
Steve Anton3828c062017-12-06 10:34:51 -08005695bool PeerConnection::ExpectSetLocalDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08005696 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08005697 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08005698 return (state == PeerConnectionInterface::kStable) ||
5699 (state == PeerConnectionInterface::kHaveLocalOffer);
Steve Anton20393062017-12-04 16:24:52 -08005700 } else {
Steve Anton3828c062017-12-06 10:34:51 -08005701 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08005702 return (state == PeerConnectionInterface::kHaveRemoteOffer) ||
5703 (state == PeerConnectionInterface::kHaveLocalPrAnswer);
5704 }
5705}
5706
Steve Anton3828c062017-12-06 10:34:51 -08005707bool PeerConnection::ExpectSetRemoteDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08005708 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08005709 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08005710 return (state == PeerConnectionInterface::kStable) ||
5711 (state == PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton20393062017-12-04 16:24:52 -08005712 } else {
Steve Anton3828c062017-12-06 10:34:51 -08005713 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08005714 return (state == PeerConnectionInterface::kHaveLocalOffer) ||
5715 (state == PeerConnectionInterface::kHaveRemotePrAnswer);
5716 }
5717}
5718
Steve Antonf8470812017-12-04 10:46:21 -08005719const char* PeerConnection::SessionErrorToString(SessionError error) const {
5720 switch (error) {
5721 case SessionError::kNone:
5722 return "ERROR_NONE";
5723 case SessionError::kContent:
5724 return "ERROR_CONTENT";
5725 case SessionError::kTransport:
5726 return "ERROR_TRANSPORT";
5727 }
5728 RTC_NOTREACHED();
5729 return "";
5730}
5731
Steve Anton75737c02017-11-06 10:37:17 -08005732std::string PeerConnection::GetSessionErrorMsg() {
5733 std::ostringstream desc;
Steve Antonf8470812017-12-04 10:46:21 -08005734 desc << kSessionError << SessionErrorToString(session_error()) << ". ";
5735 desc << kSessionErrorDesc << session_error_desc() << ".";
Steve Anton75737c02017-11-06 10:37:17 -08005736 return desc.str();
5737}
5738
Steve Anton0ffaaa22018-02-23 10:31:30 -08005739void PeerConnection::ReportNegotiatedSdpSemantics(
5740 const SessionDescriptionInterface& answer) {
5741 if (!uma_observer_) {
5742 return;
5743 }
5744 switch (answer.description()->msid_signaling()) {
5745 case 0:
5746 uma_observer_->IncrementEnumCounter(kEnumCounterSdpSemanticNegotiated,
5747 kSdpSemanticNegotiatedNone,
5748 kSdpSemanticNegotiatedMax);
5749 break;
5750 case cricket::kMsidSignalingMediaSection:
5751 uma_observer_->IncrementEnumCounter(kEnumCounterSdpSemanticNegotiated,
5752 kSdpSemanticNegotiatedUnifiedPlan,
5753 kSdpSemanticNegotiatedMax);
5754 break;
5755 case cricket::kMsidSignalingSsrcAttribute:
5756 uma_observer_->IncrementEnumCounter(kEnumCounterSdpSemanticNegotiated,
5757 kSdpSemanticNegotiatedPlanB,
5758 kSdpSemanticNegotiatedMax);
5759 break;
5760 case cricket::kMsidSignalingMediaSection |
5761 cricket::kMsidSignalingSsrcAttribute:
5762 uma_observer_->IncrementEnumCounter(kEnumCounterSdpSemanticNegotiated,
5763 kSdpSemanticNegotiatedMixed,
5764 kSdpSemanticNegotiatedMax);
5765 break;
5766 default:
5767 RTC_NOTREACHED();
5768 }
5769}
5770
Steve Anton75737c02017-11-06 10:37:17 -08005771// We need to check the local/remote description for the Transport instead of
5772// the session, because a new Transport added during renegotiation may have
5773// them unset while the session has them set from the previous negotiation.
5774// Not doing so may trigger the auto generation of transport description and
5775// mess up DTLS identity information, ICE credential, etc.
5776bool PeerConnection::ReadyToUseRemoteCandidate(
5777 const IceCandidateInterface* candidate,
5778 const SessionDescriptionInterface* remote_desc,
5779 bool* valid) {
5780 *valid = true;
5781
5782 const SessionDescriptionInterface* current_remote_desc =
5783 remote_desc ? remote_desc : remote_description();
5784
5785 if (!current_remote_desc) {
5786 return false;
5787 }
5788
5789 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
5790 size_t remote_content_size =
5791 current_remote_desc->description()->contents().size();
5792 if (mediacontent_index >= remote_content_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005793 RTC_LOG(LS_ERROR)
5794 << "ReadyToUseRemoteCandidate: Invalid candidate media index "
5795 << mediacontent_index;
Steve Anton75737c02017-11-06 10:37:17 -08005796
5797 *valid = false;
5798 return false;
5799 }
5800
5801 cricket::ContentInfo content =
5802 current_remote_desc->description()->contents()[mediacontent_index];
5803
5804 const std::string transport_name = GetTransportName(content.name);
5805 if (transport_name.empty()) {
5806 return false;
5807 }
5808 return transport_controller_->ReadyForRemoteCandidates(transport_name);
5809}
5810
5811bool PeerConnection::SrtpRequired() const {
5812 return dtls_enabled_ ||
5813 webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED;
5814}
5815
5816void PeerConnection::OnTransportControllerGatheringState(
5817 cricket::IceGatheringState state) {
5818 RTC_DCHECK(signaling_thread()->IsCurrent());
5819 if (state == cricket::kIceGatheringGathering) {
5820 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringGathering);
5821 } else if (state == cricket::kIceGatheringComplete) {
5822 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringComplete);
5823 }
5824}
5825
5826void PeerConnection::ReportTransportStats() {
Steve Antonc7b964c2018-02-01 14:39:45 -08005827 std::map<std::string, std::set<cricket::MediaType>>
5828 media_types_by_transport_name;
5829 for (auto transceiver : transceivers_) {
5830 if (transceiver->internal()->channel()) {
5831 const std::string& transport_name =
5832 transceiver->internal()->channel()->transport_name();
5833 media_types_by_transport_name[transport_name].insert(
Steve Anton69470252018-02-09 11:43:08 -08005834 transceiver->media_type());
Steve Antonc7b964c2018-02-01 14:39:45 -08005835 }
Steve Anton75737c02017-11-06 10:37:17 -08005836 }
5837 if (rtp_data_channel()) {
Steve Antonc7b964c2018-02-01 14:39:45 -08005838 media_types_by_transport_name[rtp_data_channel()->transport_name()].insert(
5839 cricket::MEDIA_TYPE_DATA);
Steve Anton75737c02017-11-06 10:37:17 -08005840 }
5841 if (sctp_transport_name_) {
Steve Antonc7b964c2018-02-01 14:39:45 -08005842 media_types_by_transport_name[*sctp_transport_name_].insert(
5843 cricket::MEDIA_TYPE_DATA);
Steve Anton75737c02017-11-06 10:37:17 -08005844 }
Steve Antonc7b964c2018-02-01 14:39:45 -08005845 for (const auto& entry : media_types_by_transport_name) {
5846 const std::string& transport_name = entry.first;
5847 const std::set<cricket::MediaType> media_types = entry.second;
Steve Anton75737c02017-11-06 10:37:17 -08005848 cricket::TransportStats stats;
Steve Antonc7b964c2018-02-01 14:39:45 -08005849 if (transport_controller_->GetStats(transport_name, &stats)) {
Steve Anton75737c02017-11-06 10:37:17 -08005850 ReportBestConnectionState(stats);
Steve Antonc7b964c2018-02-01 14:39:45 -08005851 ReportNegotiatedCiphers(stats, media_types);
Steve Anton75737c02017-11-06 10:37:17 -08005852 }
5853 }
5854}
5855// Walk through the ConnectionInfos to gather best connection usage
5856// for IPv4 and IPv6.
5857void PeerConnection::ReportBestConnectionState(
5858 const cricket::TransportStats& stats) {
5859 RTC_DCHECK(metrics_observer());
Steve Antonc7b964c2018-02-01 14:39:45 -08005860 for (const cricket::TransportChannelStats& channel_stats :
5861 stats.channel_stats) {
5862 for (const cricket::ConnectionInfo& connection_info :
5863 channel_stats.connection_infos) {
5864 if (!connection_info.best_connection) {
Steve Anton75737c02017-11-06 10:37:17 -08005865 continue;
5866 }
5867
5868 PeerConnectionEnumCounterType type = kPeerConnectionEnumCounterMax;
Steve Antonc7b964c2018-02-01 14:39:45 -08005869 const cricket::Candidate& local = connection_info.local_candidate;
5870 const cricket::Candidate& remote = connection_info.remote_candidate;
Steve Anton75737c02017-11-06 10:37:17 -08005871
5872 // Increment the counter for IceCandidatePairType.
5873 if (local.protocol() == cricket::TCP_PROTOCOL_NAME ||
5874 (local.type() == RELAY_PORT_TYPE &&
5875 local.relay_protocol() == cricket::TCP_PROTOCOL_NAME)) {
5876 type = kEnumCounterIceCandidatePairTypeTcp;
5877 } else if (local.protocol() == cricket::UDP_PROTOCOL_NAME) {
5878 type = kEnumCounterIceCandidatePairTypeUdp;
5879 } else {
5880 RTC_CHECK(0);
5881 }
5882 metrics_observer()->IncrementEnumCounter(
5883 type, GetIceCandidatePairCounter(local, remote),
5884 kIceCandidatePairMax);
5885
5886 // Increment the counter for IP type.
5887 if (local.address().family() == AF_INET) {
5888 metrics_observer()->IncrementEnumCounter(
5889 kEnumCounterAddressFamily, kBestConnections_IPv4,
5890 kPeerConnectionAddressFamilyCounter_Max);
5891
5892 } else if (local.address().family() == AF_INET6) {
5893 metrics_observer()->IncrementEnumCounter(
5894 kEnumCounterAddressFamily, kBestConnections_IPv6,
5895 kPeerConnectionAddressFamilyCounter_Max);
5896 } else {
5897 RTC_CHECK(0);
5898 }
5899
5900 return;
5901 }
5902 }
5903}
5904
5905void PeerConnection::ReportNegotiatedCiphers(
Steve Antonc7b964c2018-02-01 14:39:45 -08005906 const cricket::TransportStats& stats,
5907 const std::set<cricket::MediaType>& media_types) {
Steve Anton75737c02017-11-06 10:37:17 -08005908 RTC_DCHECK(metrics_observer());
5909 if (!dtls_enabled_ || stats.channel_stats.empty()) {
5910 return;
5911 }
5912
5913 int srtp_crypto_suite = stats.channel_stats[0].srtp_crypto_suite;
5914 int ssl_cipher_suite = stats.channel_stats[0].ssl_cipher_suite;
5915 if (srtp_crypto_suite == rtc::SRTP_INVALID_CRYPTO_SUITE &&
5916 ssl_cipher_suite == rtc::TLS_NULL_WITH_NULL_NULL) {
5917 return;
5918 }
5919
Steve Antonc7b964c2018-02-01 14:39:45 -08005920 for (cricket::MediaType media_type : media_types) {
5921 PeerConnectionEnumCounterType srtp_counter_type;
5922 PeerConnectionEnumCounterType ssl_counter_type;
5923 switch (media_type) {
5924 case cricket::MEDIA_TYPE_AUDIO:
5925 srtp_counter_type = kEnumCounterAudioSrtpCipher;
5926 ssl_counter_type = kEnumCounterAudioSslCipher;
5927 break;
5928 case cricket::MEDIA_TYPE_VIDEO:
5929 srtp_counter_type = kEnumCounterVideoSrtpCipher;
5930 ssl_counter_type = kEnumCounterVideoSslCipher;
5931 break;
5932 case cricket::MEDIA_TYPE_DATA:
5933 srtp_counter_type = kEnumCounterDataSrtpCipher;
5934 ssl_counter_type = kEnumCounterDataSslCipher;
5935 break;
5936 default:
5937 RTC_NOTREACHED();
5938 continue;
5939 }
5940 if (srtp_crypto_suite != rtc::SRTP_INVALID_CRYPTO_SUITE) {
5941 metrics_observer()->IncrementSparseEnumCounter(srtp_counter_type,
5942 srtp_crypto_suite);
5943 }
5944 if (ssl_cipher_suite != rtc::TLS_NULL_WITH_NULL_NULL) {
5945 metrics_observer()->IncrementSparseEnumCounter(ssl_counter_type,
5946 ssl_cipher_suite);
5947 }
Steve Anton75737c02017-11-06 10:37:17 -08005948 }
5949}
5950
5951void PeerConnection::OnSentPacket_w(const rtc::SentPacket& sent_packet) {
5952 RTC_DCHECK(worker_thread()->IsCurrent());
5953 RTC_DCHECK(call_);
5954 call_->OnSentPacket(sent_packet);
5955}
5956
5957const std::string PeerConnection::GetTransportName(
5958 const std::string& content_name) {
5959 cricket::BaseChannel* channel = GetChannel(content_name);
Steve Anton6fec8802017-12-04 10:37:29 -08005960 if (channel) {
5961 return channel->transport_name();
Steve Anton75737c02017-11-06 10:37:17 -08005962 }
Steve Anton6fec8802017-12-04 10:37:29 -08005963 if (sctp_transport_) {
5964 RTC_DCHECK(sctp_content_name_);
5965 RTC_DCHECK(sctp_transport_name_);
5966 if (content_name == *sctp_content_name_) {
5967 return *sctp_transport_name_;
5968 }
5969 }
5970 // Return an empty string if failed to retrieve the transport name.
5971 return "";
Steve Anton75737c02017-11-06 10:37:17 -08005972}
5973
5974void PeerConnection::DestroyRtcpTransport_n(const std::string& transport_name) {
5975 RTC_DCHECK(network_thread()->IsCurrent());
5976 transport_controller_->DestroyDtlsTransport_n(
5977 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
5978}
5979
Steve Anton6fec8802017-12-04 10:37:29 -08005980void PeerConnection::DestroyTransceiverChannel(
5981 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
5982 transceiver) {
5983 RTC_DCHECK(transceiver);
Steve Anton75737c02017-11-06 10:37:17 -08005984
Steve Anton6fec8802017-12-04 10:37:29 -08005985 cricket::BaseChannel* channel = transceiver->internal()->channel();
5986 if (channel) {
5987 transceiver->internal()->SetChannel(nullptr);
5988 DestroyBaseChannel(channel);
Steve Anton75737c02017-11-06 10:37:17 -08005989 }
5990}
5991
5992void PeerConnection::DestroyDataChannel() {
Steve Anton6fec8802017-12-04 10:37:29 -08005993 if (rtp_data_channel_) {
5994 OnDataChannelDestroyed();
5995 DestroyBaseChannel(rtp_data_channel_);
5996 rtp_data_channel_ = nullptr;
5997 }
5998
5999 // Note: Cannot use rtc::Bind to create a functor to invoke because it will
6000 // grab a reference to this PeerConnection. If this is called from the
6001 // PeerConnection destructor, the RefCountedObject vtable will have already
6002 // been destroyed (since it is a subclass of PeerConnection) and using
6003 // rtc::Bind will cause "Pure virtual function called" error to appear.
6004
6005 if (sctp_transport_) {
6006 OnDataChannelDestroyed();
6007 network_thread()->Invoke<void>(RTC_FROM_HERE,
6008 [this] { DestroySctpTransport_n(); });
6009 }
6010}
6011
6012void PeerConnection::DestroyBaseChannel(cricket::BaseChannel* channel) {
6013 RTC_DCHECK(channel);
6014 RTC_DCHECK(channel->rtp_dtls_transport());
6015
6016 // Need to cache these before destroying the base channel so that we do not
6017 // access uninitialized memory.
6018 const std::string transport_name =
6019 channel->rtp_dtls_transport()->transport_name();
6020 const bool need_to_delete_rtcp = (channel->rtcp_dtls_transport() != nullptr);
6021
6022 switch (channel->media_type()) {
6023 case cricket::MEDIA_TYPE_AUDIO:
6024 channel_manager()->DestroyVoiceChannel(
6025 static_cast<cricket::VoiceChannel*>(channel));
6026 break;
6027 case cricket::MEDIA_TYPE_VIDEO:
6028 channel_manager()->DestroyVideoChannel(
6029 static_cast<cricket::VideoChannel*>(channel));
6030 break;
6031 case cricket::MEDIA_TYPE_DATA:
6032 channel_manager()->DestroyRtpDataChannel(
6033 static_cast<cricket::RtpDataChannel*>(channel));
6034 break;
6035 default:
6036 RTC_NOTREACHED() << "Unknown media type: " << channel->media_type();
6037 break;
6038 }
6039
6040 // |channel| can no longer be used.
6041
Steve Anton75737c02017-11-06 10:37:17 -08006042 transport_controller_->DestroyDtlsTransport(
6043 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
6044 if (need_to_delete_rtcp) {
6045 transport_controller_->DestroyDtlsTransport(
6046 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
6047 }
6048}
6049
Harald Alvestrand89061872018-01-02 14:08:34 +01006050void PeerConnection::ClearStatsCache() {
6051 if (stats_collector_) {
6052 stats_collector_->ClearCachedStatsReport();
6053 }
6054}
6055
henrike@webrtc.org28e20752013-07-10 00:45:36 +00006056} // namespace webrtc