blob: 0e0e9a62108e4441f30f29176369d6d93a7242f2 [file] [log] [blame]
henrike@webrtc.org28e20752013-07-10 00:45:361/*
kjellanderb24317b2016-02-10 15:54:432 * Copyright 2012 The WebRTC project authors. All Rights Reserved.
henrike@webrtc.org28e20752013-07-10 00:45:363 *
kjellanderb24317b2016-02-10 15:54:434 * 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:369 */
10
Mirko Bonadei92ea95e2017-09-15 04:47:3111#include "pc/peerconnection.h"
henrike@webrtc.org28e20752013-07-10 00:45:3612
deadbeefeb459812015-12-16 03:24:4313#include <algorithm>
Harald Alvestrand8ebba742018-05-31 12:00:3414#include <limits>
Steve Antondcc3c022017-12-23 00:02:5415#include <queue>
Steve Anton75737c02017-11-06 18:37:1716#include <set>
kwiberg0eb15ed2015-12-17 11:04:1517#include <utility>
18#include <vector>
henrike@webrtc.org28e20752013-07-10 00:45:3619
Mirko Bonadei92ea95e2017-09-15 04:47:3120#include "api/jsepicecandidate.h"
21#include "api/jsepsessiondescription.h"
22#include "api/mediaconstraintsinterface.h"
23#include "api/mediastreamproxy.h"
24#include "api/mediastreamtrackproxy.h"
25#include "call/call.h"
Qingsi Wang93a84392018-01-31 01:13:0926#include "logging/rtc_event_log/icelogger.h"
Elad Alon83ccca12017-10-04 11:18:2627#include "logging/rtc_event_log/output/rtc_event_log_output_file.h"
Mirko Bonadei92ea95e2017-09-15 04:47:3128#include "logging/rtc_event_log/rtc_event_log.h"
29#include "media/sctp/sctptransport.h"
30#include "pc/audiotrack.h"
Steve Anton75737c02017-11-06 18:37:1731#include "pc/channel.h"
Mirko Bonadei92ea95e2017-09-15 04:47:3132#include "pc/channelmanager.h"
33#include "pc/dtmfsender.h"
34#include "pc/mediastream.h"
35#include "pc/mediastreamobserver.h"
36#include "pc/remoteaudiosource.h"
Steve Anton1d03a752017-11-27 22:30:0937#include "pc/rtpmediautils.h"
Mirko Bonadei92ea95e2017-09-15 04:47:3138#include "pc/rtpreceiver.h"
39#include "pc/rtpsender.h"
Steve Anton75737c02017-11-06 18:37:1740#include "pc/sctputils.h"
Steve Antona3a92c22017-12-07 18:27:4141#include "pc/sdputils.h"
Mirko Bonadei92ea95e2017-09-15 04:47:3142#include "pc/streamcollection.h"
43#include "pc/videocapturertracksource.h"
44#include "pc/videotrack.h"
45#include "rtc_base/bind.h"
46#include "rtc_base/checks.h"
47#include "rtc_base/logging.h"
Karl Wiberge40468b2017-11-22 09:42:2648#include "rtc_base/numerics/safe_conversions.h"
Elad Alon83ccca12017-10-04 11:18:2649#include "rtc_base/ptr_util.h"
Mirko Bonadei92ea95e2017-09-15 04:47:3150#include "rtc_base/stringencode.h"
51#include "rtc_base/stringutils.h"
52#include "rtc_base/trace_event.h"
53#include "system_wrappers/include/clock.h"
54#include "system_wrappers/include/field_trial.h"
henrike@webrtc.org28e20752013-07-10 00:45:3655
Steve Anton75737c02017-11-06 18:37:1756using cricket::ContentInfo;
57using cricket::ContentInfos;
58using cricket::MediaContentDescription;
59using cricket::SessionDescription;
Steve Anton5adfafd2017-12-21 00:34:0060using cricket::MediaProtocolType;
Steve Anton75737c02017-11-06 18:37:1761using cricket::TransportInfo;
62
63using cricket::LOCAL_PORT_TYPE;
64using cricket::STUN_PORT_TYPE;
65using cricket::RELAY_PORT_TYPE;
66using cricket::PRFLX_PORT_TYPE;
67
Steve Antonba818672017-11-06 18:21:5768namespace webrtc {
69
Steve Anton75737c02017-11-06 18:37:1770// Error messages
71const char kBundleWithoutRtcpMux[] =
72 "rtcp-mux must be enabled when BUNDLE "
73 "is enabled.";
Steve Anton75737c02017-11-06 18:37:1774const char kInvalidCandidates[] = "Description contains invalid candidates.";
75const char kInvalidSdp[] = "Invalid session description.";
76const char kMlineMismatchInAnswer[] =
77 "The order of m-lines in answer doesn't match order in offer. Rejecting "
78 "answer.";
79const char kMlineMismatchInSubsequentOffer[] =
80 "The order of m-lines in subsequent offer doesn't match order from "
81 "previous offer/answer.";
Steve Anton75737c02017-11-06 18:37:1782const char kSdpWithoutDtlsFingerprint[] =
83 "Called with SDP without DTLS fingerprint.";
84const char kSdpWithoutSdesCrypto[] = "Called with SDP without SDES crypto.";
85const char kSdpWithoutIceUfragPwd[] =
86 "Called with SDP without ice-ufrag and ice-pwd.";
87const char kSessionError[] = "Session error code: ";
88const char kSessionErrorDesc[] = "Session error description: ";
89const char kDtlsSrtpSetupFailureRtp[] =
90 "Couldn't set up DTLS-SRTP on RTP channel.";
91const char kDtlsSrtpSetupFailureRtcp[] =
92 "Couldn't set up DTLS-SRTP on RTCP channel.";
henrike@webrtc.org28e20752013-07-10 00:45:3693
Steve Anton75737c02017-11-06 18:37:1794namespace {
henrike@webrtc.org28e20752013-07-10 00:45:3695
Seth Hampson845e8782018-03-02 19:34:1096static const char kDefaultStreamId[] = "default";
Steve Anton4171afb2017-11-20 18:20:2297static const char kDefaultAudioSenderId[] = "defaulta0";
98static const char kDefaultVideoSenderId[] = "defaultv0";
deadbeefab9b2d12015-10-14 18:33:1199
zhihuang8f65cdf2016-05-07 01:40:30100// The length of RTCP CNAMEs.
101static const int kRtcpCnameLength = 16;
102
henrike@webrtc.org28e20752013-07-10 00:45:36103enum {
wu@webrtc.org91053e72013-08-10 07:18:04104 MSG_SET_SESSIONDESCRIPTION_SUCCESS = 0,
henrike@webrtc.org28e20752013-07-10 00:45:36105 MSG_SET_SESSIONDESCRIPTION_FAILED,
deadbeefab9b2d12015-10-14 18:33:11106 MSG_CREATE_SESSIONDESCRIPTION_FAILED,
henrike@webrtc.org28e20752013-07-10 00:45:36107 MSG_GETSTATS,
deadbeefbd292462015-12-15 02:15:29108 MSG_FREE_DATACHANNELS,
henrike@webrtc.org28e20752013-07-10 00:45:36109};
110
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52111struct SetSessionDescriptionMsg : public rtc::MessageData {
henrike@webrtc.org28e20752013-07-10 00:45:36112 explicit SetSessionDescriptionMsg(
113 webrtc::SetSessionDescriptionObserver* observer)
114 : observer(observer) {
115 }
116
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52117 rtc::scoped_refptr<webrtc::SetSessionDescriptionObserver> observer;
Harald Alvestrand5081c0c2018-03-09 14:18:03118 RTCError error;
henrike@webrtc.org28e20752013-07-10 00:45:36119};
120
deadbeefab9b2d12015-10-14 18:33:11121struct CreateSessionDescriptionMsg : public rtc::MessageData {
122 explicit CreateSessionDescriptionMsg(
123 webrtc::CreateSessionDescriptionObserver* observer)
124 : observer(observer) {}
125
126 rtc::scoped_refptr<webrtc::CreateSessionDescriptionObserver> observer;
Harald Alvestrand5081c0c2018-03-09 14:18:03127 RTCError error;
deadbeefab9b2d12015-10-14 18:33:11128};
129
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52130struct GetStatsMsg : public rtc::MessageData {
tommi@webrtc.org5b06b062014-08-15 08:38:30131 GetStatsMsg(webrtc::StatsObserver* observer,
132 webrtc::MediaStreamTrackInterface* track)
133 : observer(observer), track(track) {
henrike@webrtc.org28e20752013-07-10 00:45:36134 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52135 rtc::scoped_refptr<webrtc::StatsObserver> observer;
tommi@webrtc.org5b06b062014-08-15 08:38:30136 rtc::scoped_refptr<webrtc::MediaStreamTrackInterface> track;
henrike@webrtc.org28e20752013-07-10 00:45:36137};
138
deadbeefab9b2d12015-10-14 18:33:11139// 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 }
Seth Hampson13b8bad2018-03-13 23:05:28145 if (current_streams->find(new_stream->id()) != nullptr) {
146 RTC_LOG(LS_ERROR) << "MediaStream with ID " << new_stream->id()
Mirko Bonadei675513b2017-11-09 10:09:25147 << " is already added.";
deadbeefab9b2d12015-10-14 18:33:11148 return false;
149 }
150 return true;
151}
152
deadbeef5e97fb52015-10-15 19:49:08153// 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 22:57:10158 return RtpTransceiverDirectionHasSend(desc->direction())
deadbeef5e97fb52015-10-15 19:49:08159 ? desc->streams()
160 : std::vector<cricket::StreamParams>();
161}
162
deadbeefab9b2d12015-10-14 18:33:11163bool IsValidOfferToReceiveMedia(int value) {
164 typedef PeerConnectionInterface::RTCOfferAnswerOptions Options;
165 return (value >= Options::kUndefined) &&
166 (value <= Options::kMaxOfferToReceiveMedia);
167}
168
zhihuang1c378ed2017-08-17 21:10:50169// Add options to |[audio/video]_media_description_options| from |senders|.
170void AddRtpSenderOptions(
deadbeefa601f5c2016-06-06 21:27:39171 const std::vector<rtc::scoped_refptr<
172 RtpSenderProxyWithInternal<RtpSenderInternal>>>& senders,
zhihuang1c378ed2017-08-17 21:10:50173 cricket::MediaDescriptionOptions* audio_media_description_options,
174 cricket::MediaDescriptionOptions* video_media_description_options) {
olka3c747662017-08-17 13:50:32175 for (const auto& sender : senders) {
zhihuang1c378ed2017-08-17 21:10:50176 if (sender->media_type() == cricket::MEDIA_TYPE_AUDIO) {
177 if (audio_media_description_options) {
178 audio_media_description_options->AddAudioSender(
Steve Anton8ffb9c32017-08-31 22:45:38179 sender->id(), sender->internal()->stream_ids());
zhihuang1c378ed2017-08-17 21:10:50180 }
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 22:45:38185 sender->id(), sender->internal()->stream_ids(), 1);
zhihuang1c378ed2017-08-17 21:10:50186 }
187 }
zhihuanga77e6bb2017-08-15 01:17:48188 }
zhihuang1c378ed2017-08-17 21:10:50189}
olka3c747662017-08-17 13:50:32190
zhihuang1c378ed2017-08-17 21:10:50191// 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 18:33:11199 // 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 21:10:50204 // 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 18:33:11208 }
209 }
210}
211
Taylor Brandstettera1c30352016-05-13 15:15:11212uint32_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 13:56:46224 RTC_NOTREACHED();
Taylor Brandstettera1c30352016-05-13 15:15:11225 }
226 return cricket::CF_NONE;
227}
228
deadbeef293e9262017-01-11 20:28:30229// 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 22:59:59237bool 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 18:21:57244std::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 18:38:28263
Steve Anton75737c02017-11-06 18:37:17264IceCandidatePairType 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 23:33:48321// 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 18:37:17336// Verify that the order of media sections in |new_desc| matches
Seth Hampsonae8a90a2018-02-13 23:33:48337// |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 18:37:17350 return false;
351 }
352
Seth Hampsonae8a90a2018-02-13 23:33:48353 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-23 00:02:54364 continue;
365 }
Seth Hampsonae8a90a2018-02-13 23:33:48366 if (new_desc.contents()[i].name != current_desc.contents()[i].name) {
Steve Anton75737c02017-11-06 18:37:17367 return false;
368 }
369 const MediaContentDescription* new_desc_mdesc =
Seth Hampsonae8a90a2018-02-13 23:33:48370 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 18:37:17374 return false;
375 }
376 }
377 return true;
378}
379
Seth Hampsonae8a90a2018-02-13 23:33:48380bool MediaSectionsHaveSameCount(const SessionDescription& desc1,
381 const SessionDescription& desc2) {
382 return desc1.contents().size() == desc2.contents().size();
Steve Anton75737c02017-11-06 18:37:17383}
384
Harald Alvestrandf9d0f1d2018-03-02 13:15:26385void NoteKeyProtocolAndMedia(
386 KeyExchangeProtocolType protocol_type,
387 cricket::MediaType media_type,
388 rtc::scoped_refptr<webrtc::UMAObserver> uma_observer) {
389 if (!uma_observer)
390 return;
391 uma_observer->IncrementEnumCounter(webrtc::kEnumCounterKeyProtocol,
392 protocol_type,
393 webrtc::kEnumCounterKeyProtocolMax);
394 static const std::map<std::pair<KeyExchangeProtocolType, cricket::MediaType>,
395 KeyExchangeProtocolMedia>
396 proto_media_counter_map = {
397 {{kEnumCounterKeyProtocolDtls, cricket::MEDIA_TYPE_AUDIO},
398 kEnumCounterKeyProtocolMediaTypeDtlsAudio},
399 {{kEnumCounterKeyProtocolDtls, cricket::MEDIA_TYPE_VIDEO},
400 kEnumCounterKeyProtocolMediaTypeDtlsVideo},
401 {{kEnumCounterKeyProtocolDtls, cricket::MEDIA_TYPE_DATA},
402 kEnumCounterKeyProtocolMediaTypeDtlsData},
403 {{kEnumCounterKeyProtocolSdes, cricket::MEDIA_TYPE_AUDIO},
404 kEnumCounterKeyProtocolMediaTypeSdesAudio},
405 {{kEnumCounterKeyProtocolSdes, cricket::MEDIA_TYPE_VIDEO},
406 kEnumCounterKeyProtocolMediaTypeSdesVideo},
407 {{kEnumCounterKeyProtocolSdes, cricket::MEDIA_TYPE_DATA},
408 kEnumCounterKeyProtocolMediaTypeSdesData}};
409
410 auto it = proto_media_counter_map.find({protocol_type, media_type});
411 if (it != proto_media_counter_map.end()) {
412 uma_observer->IncrementEnumCounter(webrtc::kEnumCounterKeyProtocolMediaType,
413 it->second,
414 kEnumCounterKeyProtocolMediaTypeMax);
415 }
416}
417
Steve Anton75737c02017-11-06 18:37:17418// Checks that each non-rejected content has SDES crypto keys or a DTLS
419// fingerprint, unless it's in a BUNDLE group, in which case only the
420// BUNDLE-tag section (first media section/description in the BUNDLE group)
421// needs a ufrag and pwd. Mismatches, such as replying with a DTLS fingerprint
422// to SDES keys, will be caught in JsepTransport negotiation, and backstopped
423// by Channel's |srtp_required| check.
Harald Alvestrand194939b2018-01-24 15:04:13424RTCError VerifyCrypto(const SessionDescription* desc,
425 bool dtls_enabled,
426 rtc::scoped_refptr<webrtc::UMAObserver> uma_observer) {
Steve Anton75737c02017-11-06 18:37:17427 const cricket::ContentGroup* bundle =
428 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton8a006912017-12-04 23:25:56429 for (const cricket::ContentInfo& content_info : desc->contents()) {
430 if (content_info.rejected) {
Steve Anton75737c02017-11-06 18:37:17431 continue;
432 }
Harald Alvestrand2e180612018-03-07 09:56:14433 // Note what media is used with each crypto protocol, for all sections.
434 NoteKeyProtocolAndMedia(dtls_enabled ? webrtc::kEnumCounterKeyProtocolDtls
435 : webrtc::kEnumCounterKeyProtocolSdes,
436 content_info.media_description()->type(),
437 uma_observer);
Steve Anton8a006912017-12-04 23:25:56438 const std::string& mid = content_info.name;
439 if (bundle && bundle->HasContentName(mid) &&
440 mid != *(bundle->FirstContentName())) {
Steve Anton75737c02017-11-06 18:37:17441 // This isn't the first media section in the BUNDLE group, so it's not
442 // required to have crypto attributes, since only the crypto attributes
443 // from the first section actually get used.
444 continue;
445 }
446
447 // If the content isn't rejected or bundled into another m= section, crypto
448 // must be present.
Steve Antonb1c1de12017-12-21 23:14:30449 const MediaContentDescription* media = content_info.media_description();
Steve Anton8a006912017-12-04 23:25:56450 const TransportInfo* tinfo = desc->GetTransportInfoByName(mid);
Steve Anton75737c02017-11-06 18:37:17451 if (!media || !tinfo) {
452 // Something is not right.
Steve Anton8a006912017-12-04 23:25:56453 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidSdp);
Steve Anton75737c02017-11-06 18:37:17454 }
455 if (dtls_enabled) {
456 if (!tinfo->description.identity_fingerprint) {
Mirko Bonadei675513b2017-11-09 10:09:25457 RTC_LOG(LS_WARNING)
458 << "Session description must have DTLS fingerprint if "
459 "DTLS enabled.";
Steve Anton8a006912017-12-04 23:25:56460 return RTCError(RTCErrorType::INVALID_PARAMETER,
461 kSdpWithoutDtlsFingerprint);
Steve Anton75737c02017-11-06 18:37:17462 }
463 } else {
464 if (media->cryptos().empty()) {
Mirko Bonadei675513b2017-11-09 10:09:25465 RTC_LOG(LS_WARNING)
Steve Anton75737c02017-11-06 18:37:17466 << "Session description must have SDES when DTLS disabled.";
Steve Anton8a006912017-12-04 23:25:56467 return RTCError(RTCErrorType::INVALID_PARAMETER, kSdpWithoutSdesCrypto);
Steve Anton75737c02017-11-06 18:37:17468 }
469 }
470 }
Steve Anton8a006912017-12-04 23:25:56471 return RTCError::OK();
Steve Anton75737c02017-11-06 18:37:17472}
473
474// Checks that each non-rejected content has ice-ufrag and ice-pwd set, unless
475// it's in a BUNDLE group, in which case only the BUNDLE-tag section (first
476// media section/description in the BUNDLE group) needs a ufrag and pwd.
477bool VerifyIceUfragPwdPresent(const SessionDescription* desc) {
478 const cricket::ContentGroup* bundle =
479 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton8a006912017-12-04 23:25:56480 for (const cricket::ContentInfo& content_info : desc->contents()) {
481 if (content_info.rejected) {
Steve Anton75737c02017-11-06 18:37:17482 continue;
483 }
Steve Anton8a006912017-12-04 23:25:56484 const std::string& mid = content_info.name;
485 if (bundle && bundle->HasContentName(mid) &&
486 mid != *(bundle->FirstContentName())) {
Steve Anton75737c02017-11-06 18:37:17487 // This isn't the first media section in the BUNDLE group, so it's not
488 // required to have ufrag/password, since only the ufrag/password from
489 // the first section actually get used.
490 continue;
491 }
492
493 // If the content isn't rejected or bundled into another m= section,
494 // ice-ufrag and ice-pwd must be present.
Steve Anton8a006912017-12-04 23:25:56495 const TransportInfo* tinfo = desc->GetTransportInfoByName(mid);
Steve Anton75737c02017-11-06 18:37:17496 if (!tinfo) {
497 // Something is not right.
Mirko Bonadei675513b2017-11-09 10:09:25498 RTC_LOG(LS_ERROR) << kInvalidSdp;
Steve Anton75737c02017-11-06 18:37:17499 return false;
500 }
501 if (tinfo->description.ice_ufrag.empty() ||
502 tinfo->description.ice_pwd.empty()) {
Mirko Bonadei675513b2017-11-09 10:09:25503 RTC_LOG(LS_ERROR) << "Session description must have ice ufrag and pwd.";
Steve Anton75737c02017-11-06 18:37:17504 return false;
505 }
506 }
507 return true;
508}
509
510bool GetTrackIdBySsrc(const SessionDescription* session_description,
511 uint32_t ssrc,
512 std::string* track_id) {
513 RTC_DCHECK(track_id != NULL);
514
Steve Antonb1c1de12017-12-21 23:14:30515 const cricket::AudioContentDescription* audio_desc =
516 cricket::GetFirstAudioContentDescription(session_description);
517 if (audio_desc) {
518 const auto* found = cricket::GetStreamBySsrc(audio_desc->streams(), ssrc);
Steve Anton75737c02017-11-06 18:37:17519 if (found) {
520 *track_id = found->id;
521 return true;
522 }
523 }
524
Steve Antonb1c1de12017-12-21 23:14:30525 const cricket::VideoContentDescription* video_desc =
526 cricket::GetFirstVideoContentDescription(session_description);
527 if (video_desc) {
528 const auto* found = cricket::GetStreamBySsrc(video_desc->streams(), ssrc);
Steve Anton75737c02017-11-06 18:37:17529 if (found) {
530 *track_id = found->id;
531 return true;
532 }
533 }
534 return false;
535}
536
537// Get the SCTP port out of a SessionDescription.
538// Return -1 if not found.
539int GetSctpPort(const SessionDescription* session_description) {
Steve Antonb1c1de12017-12-21 23:14:30540 const cricket::DataContentDescription* data_desc =
541 GetFirstDataContentDescription(session_description);
542 RTC_DCHECK(data_desc);
543 if (!data_desc) {
Steve Anton75737c02017-11-06 18:37:17544 return -1;
545 }
Steve Anton75737c02017-11-06 18:37:17546 std::string value;
547 cricket::DataCodec match_pattern(cricket::kGoogleSctpDataCodecPlType,
548 cricket::kGoogleSctpDataCodecName);
Steve Antonb1c1de12017-12-21 23:14:30549 for (const cricket::DataCodec& codec : data_desc->codecs()) {
Steve Anton75737c02017-11-06 18:37:17550 if (!codec.Matches(match_pattern)) {
551 continue;
552 }
553 if (codec.GetParam(cricket::kCodecParamPort, &value)) {
554 return rtc::FromString<int>(value);
555 }
556 }
557 return -1;
558}
559
Steve Anton75737c02017-11-06 18:37:17560// Returns true if |new_desc| requests an ICE restart (i.e., new ufrag/pwd).
561bool CheckForRemoteIceRestart(const SessionDescriptionInterface* old_desc,
562 const SessionDescriptionInterface* new_desc,
563 const std::string& content_name) {
564 if (!old_desc) {
565 return false;
566 }
567 const SessionDescription* new_sd = new_desc->description();
568 const SessionDescription* old_sd = old_desc->description();
569 const ContentInfo* cinfo = new_sd->GetContentByName(content_name);
570 if (!cinfo || cinfo->rejected) {
571 return false;
572 }
573 // If the content isn't rejected, check if ufrag and password has changed.
574 const cricket::TransportDescription* new_transport_desc =
575 new_sd->GetTransportDescriptionByName(content_name);
576 const cricket::TransportDescription* old_transport_desc =
577 old_sd->GetTransportDescriptionByName(content_name);
578 if (!new_transport_desc || !old_transport_desc) {
579 // No transport description exists. This is not an ICE restart.
580 return false;
581 }
582 if (cricket::IceCredentialsChanged(
583 old_transport_desc->ice_ufrag, old_transport_desc->ice_pwd,
584 new_transport_desc->ice_ufrag, new_transport_desc->ice_pwd)) {
Mirko Bonadei675513b2017-11-09 10:09:25585 RTC_LOG(LS_INFO) << "Remote peer requests ICE restart for " << content_name
586 << ".";
Steve Anton75737c02017-11-06 18:37:17587 return true;
588 }
589 return false;
590}
591
Steve Anton80dd7b52018-02-17 01:08:42592// Generates a string error message for SetLocalDescription/SetRemoteDescription
593// from an RTCError.
594std::string GetSetDescriptionErrorMessage(cricket::ContentSource source,
595 SdpType type,
596 const RTCError& error) {
597 std::ostringstream oss;
598 oss << "Failed to set " << (source == cricket::CS_LOCAL ? "local" : "remote")
599 << " " << SdpTypeToString(type) << " sdp: " << error.message();
600 return oss.str();
601}
602
Seth Hampson5b4f0752018-04-02 23:31:36603std::string GetStreamIdsString(rtc::ArrayView<const std::string> stream_ids) {
604 std::string output = "streams=[";
605 const char* separator = "";
606 for (const auto& stream_id : stream_ids) {
607 output.append(separator).append(stream_id);
608 separator = ", ";
609 }
610 output.append("]");
611 return output;
612}
613
Qingsi Wang866e08d2018-03-23 00:54:23614rtc::Optional<int> RTCConfigurationToIceConfigOptionalInt(
615 int rtc_configuration_parameter) {
616 if (rtc_configuration_parameter ==
617 webrtc::PeerConnectionInterface::RTCConfiguration::kUndefined) {
618 return rtc::nullopt;
619 }
620 return rtc_configuration_parameter;
621}
622
Steve Anton75737c02017-11-06 18:37:17623} // namespace
624
Henrik Boström31638672017-11-23 16:48:32625// Upon completion, posts a task to execute the callback of the
626// SetSessionDescriptionObserver asynchronously on the same thread. At this
627// point, the state of the peer connection might no longer reflect the effects
628// of the SetRemoteDescription operation, as the peer connection could have been
629// modified during the post.
630// TODO(hbos): Remove this class once we remove the version of
631// PeerConnectionInterface::SetRemoteDescription() that takes a
632// SetSessionDescriptionObserver as an argument.
633class PeerConnection::SetRemoteDescriptionObserverAdapter
634 : public rtc::RefCountedObject<SetRemoteDescriptionObserverInterface> {
635 public:
636 SetRemoteDescriptionObserverAdapter(
637 rtc::scoped_refptr<PeerConnection> pc,
638 rtc::scoped_refptr<SetSessionDescriptionObserver> wrapper)
639 : pc_(std::move(pc)), wrapper_(std::move(wrapper)) {}
640
641 // SetRemoteDescriptionObserverInterface implementation.
642 void OnSetRemoteDescriptionComplete(RTCError error) override {
643 if (error.ok())
644 pc_->PostSetSessionDescriptionSuccess(wrapper_);
645 else
Harald Alvestrand5081c0c2018-03-09 14:18:03646 pc_->PostSetSessionDescriptionFailure(wrapper_, std::move(error));
Henrik Boström31638672017-11-23 16:48:32647 }
648
649 private:
650 rtc::scoped_refptr<PeerConnection> pc_;
651 rtc::scoped_refptr<SetSessionDescriptionObserver> wrapper_;
652};
653
deadbeef293e9262017-01-11 20:28:30654bool PeerConnectionInterface::RTCConfiguration::operator==(
655 const PeerConnectionInterface::RTCConfiguration& o) const {
656 // This static_assert prevents us from accidentally breaking operator==.
Steve Anton300bf8e2017-07-14 17:13:10657 // Note: Order matters! Fields must be ordered the same as RTCConfiguration.
deadbeef293e9262017-01-11 20:28:30658 struct stuff_being_tested_for_equality {
Magnus Jedvert3beb2072017-07-14 14:23:56659 IceServers servers;
Steve Anton300bf8e2017-07-14 17:13:10660 IceTransportsType type;
deadbeef293e9262017-01-11 20:28:30661 BundlePolicy bundle_policy;
662 RtcpMuxPolicy rtcp_mux_policy;
Steve Anton300bf8e2017-07-14 17:13:10663 std::vector<rtc::scoped_refptr<rtc::RTCCertificate>> certificates;
664 int ice_candidate_pool_size;
665 bool disable_ipv6;
666 bool disable_ipv6_on_wifi;
deadbeefd21eab3e2017-07-26 23:50:11667 int max_ipv6_networks;
Daniel Lazarenko2870b0a2018-01-25 09:30:22668 bool disable_link_local_networks;
Steve Anton300bf8e2017-07-14 17:13:10669 bool enable_rtp_data_channel;
670 rtc::Optional<int> screencast_min_bitrate;
671 rtc::Optional<bool> combined_audio_video_bwe;
672 rtc::Optional<bool> enable_dtls_srtp;
deadbeef293e9262017-01-11 20:28:30673 TcpCandidatePolicy tcp_candidate_policy;
674 CandidateNetworkPolicy candidate_network_policy;
675 int audio_jitter_buffer_max_packets;
676 bool audio_jitter_buffer_fast_accelerate;
677 int ice_connection_receiving_timeout;
678 int ice_backup_candidate_pair_ping_interval;
679 ContinualGatheringPolicy continual_gathering_policy;
deadbeef293e9262017-01-11 20:28:30680 bool prioritize_most_likely_ice_candidate_pairs;
681 struct cricket::MediaConfig media_config;
deadbeef293e9262017-01-11 20:28:30682 bool prune_turn_ports;
683 bool presume_writable_when_fully_relayed;
684 bool enable_ice_renomination;
685 bool redetermine_role_on_ice_restart;
Qingsi Wange6826d22018-03-08 22:55:14686 rtc::Optional<int> ice_check_interval_strong_connectivity;
687 rtc::Optional<int> ice_check_interval_weak_connectivity;
skvlad51072462017-02-02 19:50:14688 rtc::Optional<int> ice_check_min_interval;
Qingsi Wang22e623a2018-03-13 17:53:57689 rtc::Optional<int> ice_unwritable_timeout;
690 rtc::Optional<int> ice_unwritable_min_checks;
Qingsi Wangdb53f8e2018-02-20 22:45:49691 rtc::Optional<int> stun_candidate_keepalive_interval;
Steve Anton300bf8e2017-07-14 17:13:10692 rtc::Optional<rtc::IntervalRange> ice_regather_interval_range;
Jonas Orelandbdcee282017-10-10 12:01:40693 webrtc::TurnCustomizer* turn_customizer;
Steve Anton79e79602017-11-20 18:25:56694 SdpSemantics sdp_semantics;
Qingsi Wang9a5c6f82018-02-01 18:38:40695 rtc::Optional<rtc::AdapterType> network_preference;
Zhi Huangb57e1692018-06-12 18:41:11696 bool active_reset_srtp_params;
deadbeef293e9262017-01-11 20:28:30697 };
698 static_assert(sizeof(stuff_being_tested_for_equality) == sizeof(*this),
699 "Did you add something to RTCConfiguration and forget to "
700 "update operator==?");
701 return type == o.type && servers == o.servers &&
702 bundle_policy == o.bundle_policy &&
703 rtcp_mux_policy == o.rtcp_mux_policy &&
704 tcp_candidate_policy == o.tcp_candidate_policy &&
705 candidate_network_policy == o.candidate_network_policy &&
706 audio_jitter_buffer_max_packets == o.audio_jitter_buffer_max_packets &&
707 audio_jitter_buffer_fast_accelerate ==
708 o.audio_jitter_buffer_fast_accelerate &&
709 ice_connection_receiving_timeout ==
710 o.ice_connection_receiving_timeout &&
711 ice_backup_candidate_pair_ping_interval ==
712 o.ice_backup_candidate_pair_ping_interval &&
713 continual_gathering_policy == o.continual_gathering_policy &&
714 certificates == o.certificates &&
715 prioritize_most_likely_ice_candidate_pairs ==
716 o.prioritize_most_likely_ice_candidate_pairs &&
717 media_config == o.media_config && disable_ipv6 == o.disable_ipv6 &&
zhihuangb09b3f92017-03-07 22:40:51718 disable_ipv6_on_wifi == o.disable_ipv6_on_wifi &&
deadbeefd21eab3e2017-07-26 23:50:11719 max_ipv6_networks == o.max_ipv6_networks &&
Daniel Lazarenko2870b0a2018-01-25 09:30:22720 disable_link_local_networks == o.disable_link_local_networks &&
deadbeef293e9262017-01-11 20:28:30721 enable_rtp_data_channel == o.enable_rtp_data_channel &&
deadbeef293e9262017-01-11 20:28:30722 screencast_min_bitrate == o.screencast_min_bitrate &&
723 combined_audio_video_bwe == o.combined_audio_video_bwe &&
724 enable_dtls_srtp == o.enable_dtls_srtp &&
725 ice_candidate_pool_size == o.ice_candidate_pool_size &&
726 prune_turn_ports == o.prune_turn_ports &&
727 presume_writable_when_fully_relayed ==
728 o.presume_writable_when_fully_relayed &&
729 enable_ice_renomination == o.enable_ice_renomination &&
skvlad51072462017-02-02 19:50:14730 redetermine_role_on_ice_restart == o.redetermine_role_on_ice_restart &&
Qingsi Wange6826d22018-03-08 22:55:14731 ice_check_interval_strong_connectivity ==
732 o.ice_check_interval_strong_connectivity &&
733 ice_check_interval_weak_connectivity ==
734 o.ice_check_interval_weak_connectivity &&
Steve Anton300bf8e2017-07-14 17:13:10735 ice_check_min_interval == o.ice_check_min_interval &&
Qingsi Wang22e623a2018-03-13 17:53:57736 ice_unwritable_timeout == o.ice_unwritable_timeout &&
737 ice_unwritable_min_checks == o.ice_unwritable_min_checks &&
Qingsi Wangdb53f8e2018-02-20 22:45:49738 stun_candidate_keepalive_interval ==
739 o.stun_candidate_keepalive_interval &&
Jonas Orelandbdcee282017-10-10 12:01:40740 ice_regather_interval_range == o.ice_regather_interval_range &&
Steve Anton79e79602017-11-20 18:25:56741 turn_customizer == o.turn_customizer &&
Qingsi Wang9a5c6f82018-02-01 18:38:40742 sdp_semantics == o.sdp_semantics &&
Zhi Huangb57e1692018-06-12 18:41:11743 network_preference == o.network_preference &&
744 active_reset_srtp_params == o.active_reset_srtp_params;
deadbeef293e9262017-01-11 20:28:30745}
746
747bool PeerConnectionInterface::RTCConfiguration::operator!=(
748 const PeerConnectionInterface::RTCConfiguration& o) const {
749 return !(*this == o);
deadbeef3edec7c2016-12-10 19:44:26750}
751
zhihuang8f65cdf2016-05-07 01:40:30752// Generate a RTCP CNAME when a PeerConnection is created.
753std::string GenerateRtcpCname() {
754 std::string cname;
755 if (!rtc::CreateRandomString(kRtcpCnameLength, &cname)) {
Mirko Bonadei675513b2017-11-09 10:09:25756 RTC_LOG(LS_ERROR) << "Failed to generate CNAME.";
nisseeb4ca4e2017-01-12 10:24:27757 RTC_NOTREACHED();
zhihuang8f65cdf2016-05-07 01:40:30758 }
759 return cname;
760}
761
zhihuang1c378ed2017-08-17 21:10:50762bool ValidateOfferAnswerOptions(
763 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options) {
764 return IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_audio) &&
765 IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_video);
olka3c747662017-08-17 13:50:32766}
767
zhihuang1c378ed2017-08-17 21:10:50768// From |rtc_options|, fill parts of |session_options| shared by all generated
769// m= sections (in other words, nothing that involves a map/array).
770void ExtractSharedMediaSessionOptions(
771 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options,
772 cricket::MediaSessionOptions* session_options) {
773 session_options->vad_enabled = rtc_options.voice_activity_detection;
774 session_options->bundle_enabled = rtc_options.use_rtp_mux;
775}
zhihuanga77e6bb2017-08-15 01:17:48776
zhihuang1c378ed2017-08-17 21:10:50777bool ConvertConstraintsToOfferAnswerOptions(
778 const MediaConstraintsInterface* constraints,
779 PeerConnectionInterface::RTCOfferAnswerOptions* offer_answer_options) {
olka3c747662017-08-17 13:50:32780 if (!constraints) {
781 return true;
782 }
zhihuang1c378ed2017-08-17 21:10:50783
784 bool value = false;
785 size_t mandatory_constraints_satisfied = 0;
786
787 if (FindConstraint(constraints,
788 MediaConstraintsInterface::kOfferToReceiveAudio, &value,
789 &mandatory_constraints_satisfied)) {
790 offer_answer_options->offer_to_receive_audio =
791 value ? PeerConnectionInterface::RTCOfferAnswerOptions::
792 kOfferToReceiveMediaTrue
793 : 0;
794 }
795
796 if (FindConstraint(constraints,
797 MediaConstraintsInterface::kOfferToReceiveVideo, &value,
798 &mandatory_constraints_satisfied)) {
799 offer_answer_options->offer_to_receive_video =
800 value ? PeerConnectionInterface::RTCOfferAnswerOptions::
801 kOfferToReceiveMediaTrue
802 : 0;
803 }
804 if (FindConstraint(constraints,
805 MediaConstraintsInterface::kVoiceActivityDetection, &value,
806 &mandatory_constraints_satisfied)) {
807 offer_answer_options->voice_activity_detection = value;
808 }
809 if (FindConstraint(constraints, MediaConstraintsInterface::kUseRtpMux, &value,
810 &mandatory_constraints_satisfied)) {
811 offer_answer_options->use_rtp_mux = value;
812 }
813 if (FindConstraint(constraints, MediaConstraintsInterface::kIceRestart,
814 &value, &mandatory_constraints_satisfied)) {
815 offer_answer_options->ice_restart = value;
816 }
817
deadbeefab9b2d12015-10-14 18:33:11818 return mandatory_constraints_satisfied == constraints->GetMandatory().size();
819}
820
zhihuang38ede132017-06-15 19:52:32821PeerConnection::PeerConnection(PeerConnectionFactory* factory,
822 std::unique_ptr<RtcEventLog> event_log,
823 std::unique_ptr<Call> call)
henrike@webrtc.org28e20752013-07-10 00:45:36824 : factory_(factory),
zhihuang38ede132017-06-15 19:52:32825 event_log_(std::move(event_log)),
zhihuang8f65cdf2016-05-07 01:40:30826 rtcp_cname_(GenerateRtcpCname()),
deadbeefab9b2d12015-10-14 18:33:11827 local_streams_(StreamCollection::Create()),
zhihuang38ede132017-06-15 19:52:32828 remote_streams_(StreamCollection::Create()),
829 call_(std::move(call)) {}
henrike@webrtc.org28e20752013-07-10 00:45:36830
831PeerConnection::~PeerConnection() {
Peter Boström1a9d6152015-12-08 21:15:17832 TRACE_EVENT0("webrtc", "PeerConnection::~PeerConnection");
Steve Anton4171afb2017-11-20 18:20:22833 RTC_DCHECK_RUN_ON(signaling_thread());
834
Steve Anton8af21862017-12-15 19:20:13835 // Need to stop transceivers before destroying the stats collector because
836 // AudioRtpSender has a reference to the StatsCollector it will update when
837 // stopping.
838 for (auto transceiver : transceivers_) {
839 transceiver->Stop();
840 }
Steve Anton4171afb2017-11-20 18:20:22841
Taylor Brandstettera1c30352016-05-13 15:15:11842 stats_.reset(nullptr);
hbosb78306a2016-12-19 13:06:57843 if (stats_collector_) {
844 stats_collector_->WaitForPendingRequest();
845 stats_collector_ = nullptr;
846 }
Steve Anton75737c02017-11-06 18:37:17847
Steve Anton8af21862017-12-15 19:20:13848 // Don't destroy BaseChannels until after stats has been cleaned up so that
849 // the last stats request can still read from the channels.
850 DestroyAllChannels();
851
Mirko Bonadei675513b2017-11-09 10:09:25852 RTC_LOG(LS_INFO) << "Session: " << session_id() << " is destroyed.";
Steve Anton75737c02017-11-06 18:37:17853
854 webrtc_session_desc_factory_.reset();
855 sctp_invoker_.reset();
856 sctp_factory_.reset();
857 transport_controller_.reset();
858
deadbeef91dd5672016-05-18 23:55:30859 // port_allocator_ lives on the network thread and should be destroyed there.
Taylor Brandstetter5d97a9a2016-06-10 21:17:27860 network_thread()->Invoke<void>(RTC_FROM_HERE,
nisseeaabdf62017-05-05 09:23:02861 [this] { port_allocator_.reset(); });
eladalon248fd4f2017-09-06 12:18:15862 // call_ and event_log_ must be destroyed on the worker thread.
Steve Anton978b8762017-09-29 19:15:02863 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
eladalon248fd4f2017-09-06 12:18:15864 call_.reset();
Qingsi Wang93a84392018-01-31 01:13:09865 // The event log must outlive call (and any other object that uses it).
eladalon248fd4f2017-09-06 12:18:15866 event_log_.reset();
867 });
henrike@webrtc.org28e20752013-07-10 00:45:36868}
869
Steve Anton8af21862017-12-15 19:20:13870void PeerConnection::DestroyAllChannels() {
Steve Anton3fe1b152017-12-12 18:20:08871 // Destroy video channels first since they may have a pointer to a voice
872 // channel.
873 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 19:43:08874 if (transceiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton3fe1b152017-12-12 18:20:08875 DestroyTransceiverChannel(transceiver);
876 }
877 }
878 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 19:43:08879 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton3fe1b152017-12-12 18:20:08880 DestroyTransceiverChannel(transceiver);
881 }
882 }
883 DestroyDataChannel();
884}
885
henrike@webrtc.org28e20752013-07-10 00:45:36886bool PeerConnection::Initialize(
buildbot@webrtc.org41451d42014-05-03 05:39:45887 const PeerConnectionInterface::RTCConfiguration& configuration,
Benjamin Wrightcab588882018-05-02 22:12:47888 PeerConnectionDependencies dependencies) {
Peter Boström1a9d6152015-12-08 21:15:17889 TRACE_EVENT0("webrtc", "PeerConnection::Initialize");
Steve Anton038834f2017-07-14 22:59:59890
891 RTCError config_error = ValidateConfiguration(configuration);
892 if (!config_error.ok()) {
Mirko Bonadei675513b2017-11-09 10:09:25893 RTC_LOG(LS_ERROR) << "Invalid configuration: " << config_error.message();
Steve Anton038834f2017-07-14 22:59:59894 return false;
895 }
896
Benjamin Wrightcab588882018-05-02 22:12:47897 if (!dependencies.allocator) {
Mirko Bonadei675513b2017-11-09 10:09:25898 RTC_LOG(LS_ERROR)
899 << "PeerConnection initialized without a PortAllocator? "
Jonas Olsson45cc8902018-02-13 09:37:07900 "This shouldn't happen if using PeerConnectionFactory.";
deadbeef293e9262017-01-11 20:28:30901 return false;
902 }
Jonas Orelandbdcee282017-10-10 12:01:40903
Benjamin Wrightcab588882018-05-02 22:12:47904 if (!dependencies.observer) {
deadbeef293e9262017-01-11 20:28:30905 // TODO(deadbeef): Why do we do this?
Mirko Bonadei675513b2017-11-09 10:09:25906 RTC_LOG(LS_ERROR) << "PeerConnection initialized without a "
Jonas Olsson45cc8902018-02-13 09:37:07907 "PeerConnectionObserver";
deadbeef653b8e02015-11-11 20:55:10908 return false;
909 }
Benjamin Wrightd6f86e82018-05-08 20:12:25910
Benjamin Wrightcab588882018-05-02 22:12:47911 observer_ = dependencies.observer;
912 port_allocator_ = std::move(dependencies.allocator);
Benjamin Wrightd6f86e82018-05-08 20:12:25913 tls_cert_verifier_ = std::move(dependencies.tls_cert_verifier);
deadbeef653b8e02015-11-11 20:55:10914
deadbeef91dd5672016-05-18 23:55:30915 // The port allocator lives on the network thread and should be initialized
Taylor Brandstettera1c30352016-05-13 15:15:11916 // there.
Taylor Brandstetter5d97a9a2016-06-10 21:17:27917 if (!network_thread()->Invoke<bool>(
918 RTC_FROM_HERE, rtc::Bind(&PeerConnection::InitializePortAllocator_n,
919 this, configuration))) {
henrike@webrtc.org28e20752013-07-10 00:45:36920 return false;
921 }
henrike@webrtc.org28e20752013-07-10 00:45:36922
Zhi Huange830e682018-03-30 17:48:35923 const PeerConnectionFactoryInterface::Options& options = factory_->options();
924
Steve Anton75737c02017-11-06 18:37:17925 // RFC 3264: The numeric value of the session id and version in the
926 // o line MUST be representable with a "64 bit signed integer".
927 // Due to this constraint session id |session_id_| is max limited to
928 // LLONG_MAX.
929 session_id_ = rtc::ToString(rtc::CreateRandomId64() & LLONG_MAX);
Zhi Huange830e682018-03-30 17:48:35930 JsepTransportController::Config config;
931 config.redetermine_role_on_ice_restart =
932 configuration.redetermine_role_on_ice_restart;
933 config.ssl_max_version = factory_->options().ssl_max_version;
934 config.disable_encryption = options.disable_encryption;
935 config.bundle_policy = configuration.bundle_policy;
936 config.rtcp_mux_policy = configuration.rtcp_mux_policy;
937 config.crypto_options = options.crypto_options;
Zhi Huang365381f2018-04-13 23:44:34938 config.transport_observer = this;
Qingsi Wang7685e862018-06-12 03:15:46939 config.event_log = event_log_.get();
Zhi Huange830e682018-03-30 17:48:35940#if defined(ENABLE_EXTERNAL_AUTH)
941 config.enable_external_auth = true;
942#endif
Zhi Huangb57e1692018-06-12 18:41:11943 config.active_reset_srtp_params = configuration.active_reset_srtp_params;
Zhi Huange830e682018-03-30 17:48:35944 transport_controller_.reset(new JsepTransportController(
945 signaling_thread(), network_thread(), port_allocator_.get(), config));
946 transport_controller_->SignalIceConnectionState.connect(
Steve Anton75737c02017-11-06 18:37:17947 this, &PeerConnection::OnTransportControllerConnectionState);
Zhi Huange830e682018-03-30 17:48:35948 transport_controller_->SignalIceGatheringState.connect(
Steve Anton75737c02017-11-06 18:37:17949 this, &PeerConnection::OnTransportControllerGatheringState);
Zhi Huange830e682018-03-30 17:48:35950 transport_controller_->SignalIceCandidatesGathered.connect(
Steve Anton75737c02017-11-06 18:37:17951 this, &PeerConnection::OnTransportControllerCandidatesGathered);
Zhi Huange830e682018-03-30 17:48:35952 transport_controller_->SignalIceCandidatesRemoved.connect(
Steve Anton75737c02017-11-06 18:37:17953 this, &PeerConnection::OnTransportControllerCandidatesRemoved);
954 transport_controller_->SignalDtlsHandshakeError.connect(
955 this, &PeerConnection::OnTransportControllerDtlsHandshakeError);
956
957 sctp_factory_ = factory_->CreateSctpTransportInternalFactory();
zhihuang29ff8442016-07-27 18:07:25958
deadbeefab9b2d12015-10-14 18:33:11959 stats_.reset(new StatsCollector(this));
hbos74e1a4f2016-09-16 06:33:01960 stats_collector_ = RTCStatsCollector::Create(this);
henrike@webrtc.org28e20752013-07-10 00:45:36961
Steve Antonba818672017-11-06 18:21:57962 configuration_ = configuration;
963
Steve Anton75737c02017-11-06 18:37:17964 // Obtain a certificate from RTCConfiguration if any were provided (optional).
965 rtc::scoped_refptr<rtc::RTCCertificate> certificate;
966 if (!configuration.certificates.empty()) {
967 // TODO(hbos,torbjorng): Decide on certificate-selection strategy instead of
968 // just picking the first one. The decision should be made based on the DTLS
969 // handshake. The DTLS negotiations need to know about all certificates.
970 certificate = configuration.certificates[0];
971 }
972
Steve Antond25da372017-11-06 22:50:29973 transport_controller_->SetIceConfig(ParseIceConfig(configuration));
Steve Anton75737c02017-11-06 18:37:17974
975 if (options.disable_encryption) {
976 dtls_enabled_ = false;
977 } else {
978 // Enable DTLS by default if we have an identity store or a certificate.
Benjamin Wrightcab588882018-05-02 22:12:47979 dtls_enabled_ = (dependencies.cert_generator || certificate);
Steve Anton75737c02017-11-06 18:37:17980 // |configuration| can override the default |dtls_enabled_| value.
981 if (configuration.enable_dtls_srtp) {
982 dtls_enabled_ = *(configuration.enable_dtls_srtp);
983 }
984 }
985
986 // Enable creation of RTP data channels if the kEnableRtpDataChannels is set.
987 // It takes precendence over the disable_sctp_data_channels
988 // PeerConnectionFactoryInterface::Options.
989 if (configuration.enable_rtp_data_channel) {
990 data_channel_type_ = cricket::DCT_RTP;
991 } else {
992 // DTLS has to be enabled to use SCTP.
993 if (!options.disable_sctp_data_channels && dtls_enabled_) {
994 data_channel_type_ = cricket::DCT_SCTP;
995 }
996 }
997
998 video_options_.screencast_min_bitrate_kbps =
999 configuration.screencast_min_bitrate;
1000 audio_options_.combined_audio_video_bwe =
1001 configuration.combined_audio_video_bwe;
1002
1003 audio_options_.audio_jitter_buffer_max_packets =
Oskar Sundbom9b28a032017-11-16 09:53:301004 configuration.audio_jitter_buffer_max_packets;
Steve Anton75737c02017-11-06 18:37:171005
1006 audio_options_.audio_jitter_buffer_fast_accelerate =
Oskar Sundbom9b28a032017-11-16 09:53:301007 configuration.audio_jitter_buffer_fast_accelerate;
Steve Anton75737c02017-11-06 18:37:171008
1009 // Whether the certificate generator/certificate is null or not determines
1010 // what PeerConnectionDescriptionFactory will do, so make sure that we give it
1011 // the right instructions by clearing the variables if needed.
1012 if (!dtls_enabled_) {
Benjamin Wrightcab588882018-05-02 22:12:471013 dependencies.cert_generator.reset();
Steve Anton75737c02017-11-06 18:37:171014 certificate = nullptr;
1015 } else if (certificate) {
1016 // Favor generated certificate over the certificate generator.
Benjamin Wrightcab588882018-05-02 22:12:471017 dependencies.cert_generator.reset();
Steve Anton75737c02017-11-06 18:37:171018 }
1019
1020 webrtc_session_desc_factory_.reset(new WebRtcSessionDescriptionFactory(
1021 signaling_thread(), channel_manager(), this, session_id(),
Benjamin Wrightcab588882018-05-02 22:12:471022 std::move(dependencies.cert_generator), certificate));
Steve Anton75737c02017-11-06 18:37:171023 webrtc_session_desc_factory_->SignalCertificateReady.connect(
1024 this, &PeerConnection::OnCertificateReady);
1025
1026 if (options.disable_encryption) {
1027 webrtc_session_desc_factory_->SetSdesPolicy(cricket::SEC_DISABLED);
1028 }
1029
1030 webrtc_session_desc_factory_->set_enable_encrypted_rtp_header_extensions(
1031 options.crypto_options.enable_encrypted_rtp_header_extensions);
henrike@webrtc.org28e20752013-07-10 00:45:361032
Steve Anton4171afb2017-11-20 18:20:221033 // Add default audio/video transceivers for Plan B SDP.
1034 if (!IsUnifiedPlan()) {
1035 transceivers_.push_back(
1036 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1037 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_AUDIO)));
1038 transceivers_.push_back(
1039 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1040 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_VIDEO)));
1041 }
henrike@webrtc.org28e20752013-07-10 00:45:361042 return true;
1043}
1044
Steve Anton038834f2017-07-14 22:59:591045RTCError PeerConnection::ValidateConfiguration(
1046 const RTCConfiguration& config) const {
1047 if (config.ice_regather_interval_range &&
1048 config.continual_gathering_policy == GATHER_ONCE) {
1049 return RTCError(RTCErrorType::INVALID_PARAMETER,
1050 "ice_regather_interval_range specified but continual "
1051 "gathering policy is GATHER_ONCE");
1052 }
Qingsi Wangdea68892018-03-27 17:55:211053 auto result =
1054 cricket::P2PTransportChannel::ValidateIceConfig(ParseIceConfig(config));
1055 return result;
Steve Anton038834f2017-07-14 22:59:591056}
1057
buildbot@webrtc.orgd4e598d2014-07-29 17:36:521058rtc::scoped_refptr<StreamCollectionInterface>
henrike@webrtc.org28e20752013-07-10 00:45:361059PeerConnection::local_streams() {
Steve Antonfc853712018-03-01 21:48:581060 RTC_CHECK(!IsUnifiedPlan()) << "local_streams is not available with Unified "
1061 "Plan SdpSemantics. Please use GetSenders "
1062 "instead.";
deadbeefab9b2d12015-10-14 18:33:111063 return local_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:361064}
1065
buildbot@webrtc.orgd4e598d2014-07-29 17:36:521066rtc::scoped_refptr<StreamCollectionInterface>
henrike@webrtc.org28e20752013-07-10 00:45:361067PeerConnection::remote_streams() {
Steve Antonfc853712018-03-01 21:48:581068 RTC_CHECK(!IsUnifiedPlan()) << "remote_streams is not available with Unified "
1069 "Plan SdpSemantics. Please use GetReceivers "
1070 "instead.";
deadbeefab9b2d12015-10-14 18:33:111071 return remote_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:361072}
1073
perkj@webrtc.orgc2dd5ee2014-11-04 11:31:291074bool PeerConnection::AddStream(MediaStreamInterface* local_stream) {
Steve Antonfc853712018-03-01 21:48:581075 RTC_CHECK(!IsUnifiedPlan()) << "AddStream is not available with Unified Plan "
1076 "SdpSemantics. Please use AddTrack instead.";
Peter Boström1a9d6152015-12-08 21:15:171077 TRACE_EVENT0("webrtc", "PeerConnection::AddStream");
henrike@webrtc.org28e20752013-07-10 00:45:361078 if (IsClosed()) {
1079 return false;
1080 }
deadbeefab9b2d12015-10-14 18:33:111081 if (!CanAddLocalMediaStream(local_streams_, local_stream)) {
henrike@webrtc.org28e20752013-07-10 00:45:361082 return false;
1083 }
deadbeefab9b2d12015-10-14 18:33:111084
1085 local_streams_->AddStream(local_stream);
deadbeefeb459812015-12-16 03:24:431086 MediaStreamObserver* observer = new MediaStreamObserver(local_stream);
1087 observer->SignalAudioTrackAdded.connect(this,
1088 &PeerConnection::OnAudioTrackAdded);
1089 observer->SignalAudioTrackRemoved.connect(
1090 this, &PeerConnection::OnAudioTrackRemoved);
1091 observer->SignalVideoTrackAdded.connect(this,
1092 &PeerConnection::OnVideoTrackAdded);
1093 observer->SignalVideoTrackRemoved.connect(
1094 this, &PeerConnection::OnVideoTrackRemoved);
kwibergd1fe2812016-04-27 13:47:291095 stream_observers_.push_back(std::unique_ptr<MediaStreamObserver>(observer));
deadbeefab9b2d12015-10-14 18:33:111096
deadbeefab9b2d12015-10-14 18:33:111097 for (const auto& track : local_stream->GetAudioTracks()) {
korniltsev.anatolyec390b52017-07-25 00:00:251098 AddAudioTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 18:33:111099 }
1100 for (const auto& track : local_stream->GetVideoTracks()) {
korniltsev.anatolyec390b52017-07-25 00:00:251101 AddVideoTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 18:33:111102 }
1103
tommi@webrtc.org03505bc2014-07-14 20:15:261104 stats_->AddStream(local_stream);
henrike@webrtc.org28e20752013-07-10 00:45:361105 observer_->OnRenegotiationNeeded();
1106 return true;
1107}
1108
1109void PeerConnection::RemoveStream(MediaStreamInterface* local_stream) {
Steve Antonfc853712018-03-01 21:48:581110 RTC_CHECK(!IsUnifiedPlan()) << "RemoveStream is not available with Unified "
1111 "Plan SdpSemantics. Please use RemoveTrack "
1112 "instead.";
Peter Boström1a9d6152015-12-08 21:15:171113 TRACE_EVENT0("webrtc", "PeerConnection::RemoveStream");
korniltsev.anatolyec390b52017-07-25 00:00:251114 if (!IsClosed()) {
1115 for (const auto& track : local_stream->GetAudioTracks()) {
1116 RemoveAudioTrack(track.get(), local_stream);
1117 }
1118 for (const auto& track : local_stream->GetVideoTracks()) {
1119 RemoveVideoTrack(track.get(), local_stream);
1120 }
deadbeefab9b2d12015-10-14 18:33:111121 }
deadbeefab9b2d12015-10-14 18:33:111122 local_streams_->RemoveStream(local_stream);
deadbeefeb459812015-12-16 03:24:431123 stream_observers_.erase(
1124 std::remove_if(
1125 stream_observers_.begin(), stream_observers_.end(),
kwibergd1fe2812016-04-27 13:47:291126 [local_stream](const std::unique_ptr<MediaStreamObserver>& observer) {
Seth Hampson13b8bad2018-03-13 23:05:281127 return observer->stream()->id().compare(local_stream->id()) == 0;
deadbeefeb459812015-12-16 03:24:431128 }),
1129 stream_observers_.end());
deadbeefab9b2d12015-10-14 18:33:111130
henrike@webrtc.org28e20752013-07-10 00:45:361131 if (IsClosed()) {
1132 return;
1133 }
henrike@webrtc.org28e20752013-07-10 00:45:361134 observer_->OnRenegotiationNeeded();
1135}
1136
deadbeefe1f9d832016-01-14 23:35:421137rtc::scoped_refptr<RtpSenderInterface> PeerConnection::AddTrack(
1138 MediaStreamTrackInterface* track,
1139 std::vector<MediaStreamInterface*> streams) {
1140 TRACE_EVENT0("webrtc", "PeerConnection::AddTrack");
Seth Hampson845e8782018-03-02 19:34:101141 std::vector<std::string> stream_ids;
Steve Antonf9381f02017-12-14 18:23:571142 for (auto* stream : streams) {
1143 if (!stream) {
1144 RTC_LOG(LS_ERROR) << "Stream list has null element.";
1145 return nullptr;
1146 }
Seth Hampson13b8bad2018-03-13 23:05:281147 stream_ids.push_back(stream->id());
Steve Antonf9381f02017-12-14 18:23:571148 }
Seth Hampson845e8782018-03-02 19:34:101149 auto sender_or_error = AddTrack(track, stream_ids);
Steve Antonf9381f02017-12-14 18:23:571150 if (!sender_or_error.ok()) {
deadbeefe1f9d832016-01-14 23:35:421151 return nullptr;
1152 }
Steve Antonf9381f02017-12-14 18:23:571153 return sender_or_error.MoveValue();
1154}
1155
Steve Anton2d6c76a2018-01-06 01:10:521156RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::AddTrack(
Steve Antonf9381f02017-12-14 18:23:571157 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 19:34:101158 const std::vector<std::string>& stream_ids) {
Steve Anton2d6c76a2018-01-06 01:10:521159 TRACE_EVENT0("webrtc", "PeerConnection::AddTrack");
Steve Antonf9381f02017-12-14 18:23:571160 if (!track) {
1161 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "Track is null.");
1162 }
1163 if (!(track->kind() == MediaStreamTrackInterface::kAudioKind ||
1164 track->kind() == MediaStreamTrackInterface::kVideoKind)) {
1165 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1166 "Track has invalid kind: " + track->kind());
1167 }
Steve Antonf9381f02017-12-14 18:23:571168 if (IsClosed()) {
1169 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
1170 "PeerConnection is closed.");
deadbeefe1f9d832016-01-14 23:35:421171 }
Steve Anton4171afb2017-11-20 18:20:221172 if (FindSenderForTrack(track)) {
Steve Antonf9381f02017-12-14 18:23:571173 LOG_AND_RETURN_ERROR(
1174 RTCErrorType::INVALID_PARAMETER,
1175 "Sender already exists for track " + track->id() + ".");
deadbeefe1f9d832016-01-14 23:35:421176 }
Steve Antonf9381f02017-12-14 18:23:571177 auto sender_or_error =
Seth Hampson5b4f0752018-04-02 23:31:361178 (IsUnifiedPlan() ? AddTrackUnifiedPlan(track, stream_ids)
1179 : AddTrackPlanB(track, stream_ids));
Steve Antonf9381f02017-12-14 18:23:571180 if (sender_or_error.ok()) {
1181 observer_->OnRenegotiationNeeded();
Steve Anton43a723a2018-01-04 23:48:171182 stats_->AddTrack(track);
Steve Antonf9381f02017-12-14 18:23:571183 }
1184 return sender_or_error;
1185}
deadbeefe1f9d832016-01-14 23:35:421186
Steve Antonf9381f02017-12-14 18:23:571187RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>>
1188PeerConnection::AddTrackPlanB(
1189 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 19:34:101190 const std::vector<std::string>& stream_ids) {
Seth Hampson5b4f0752018-04-02 23:31:361191 if (stream_ids.size() > 1u) {
1192 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_OPERATION,
1193 "AddTrack with more than one stream is not "
1194 "supported with Plan B semantics.");
1195 }
1196 std::vector<std::string> adjusted_stream_ids = stream_ids;
1197 if (adjusted_stream_ids.empty()) {
1198 adjusted_stream_ids.push_back(rtc::CreateRandomUuid());
1199 }
Steve Anton02ee47c2018-01-11 00:26:061200 cricket::MediaType media_type =
1201 (track->kind() == MediaStreamTrackInterface::kAudioKind
1202 ? cricket::MEDIA_TYPE_AUDIO
1203 : cricket::MEDIA_TYPE_VIDEO);
Seth Hampson5b4f0752018-04-02 23:31:361204 auto new_sender = CreateSender(media_type, track, adjusted_stream_ids);
deadbeefe1f9d832016-01-14 23:35:421205 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
Steve Anton57858b32018-02-15 23:19:501206 new_sender->internal()->SetVoiceMediaChannel(voice_media_channel());
Steve Anton4171afb2017-11-20 18:20:221207 GetAudioTransceiver()->internal()->AddSender(new_sender);
Steve Anton4171afb2017-11-20 18:20:221208 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609eaa2018-03-27 21:57:181209 FindSenderInfo(local_audio_sender_infos_,
Seth Hampson5b4f0752018-04-02 23:31:361210 new_sender->internal()->stream_ids()[0], track->id());
Steve Anton4171afb2017-11-20 18:20:221211 if (sender_info) {
1212 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 23:35:421213 }
Steve Antonf9381f02017-12-14 18:23:571214 } else {
1215 RTC_DCHECK_EQ(MediaStreamTrackInterface::kVideoKind, track->kind());
Steve Anton57858b32018-02-15 23:19:501216 new_sender->internal()->SetVideoMediaChannel(video_media_channel());
Steve Anton4171afb2017-11-20 18:20:221217 GetVideoTransceiver()->internal()->AddSender(new_sender);
Steve Anton4171afb2017-11-20 18:20:221218 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609eaa2018-03-27 21:57:181219 FindSenderInfo(local_video_sender_infos_,
Seth Hampson5b4f0752018-04-02 23:31:361220 new_sender->internal()->stream_ids()[0], track->id());
Steve Anton4171afb2017-11-20 18:20:221221 if (sender_info) {
1222 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 23:35:421223 }
deadbeefe1f9d832016-01-14 23:35:421224 }
Steve Anton02ee47c2018-01-11 00:26:061225 return rtc::scoped_refptr<RtpSenderInterface>(new_sender);
Steve Antonf9381f02017-12-14 18:23:571226}
deadbeefe1f9d832016-01-14 23:35:421227
Steve Antonf9381f02017-12-14 18:23:571228RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>>
1229PeerConnection::AddTrackUnifiedPlan(
1230 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 19:34:101231 const std::vector<std::string>& stream_ids) {
Steve Antonf9381f02017-12-14 18:23:571232 auto transceiver = FindFirstTransceiverForAddedTrack(track);
1233 if (transceiver) {
Steve Anton3d954a62018-04-02 18:27:231234 RTC_LOG(LS_INFO) << "Reusing an existing "
1235 << cricket::MediaTypeToString(transceiver->media_type())
1236 << " transceiver for AddTrack.";
Steve Antonf9381f02017-12-14 18:23:571237 if (transceiver->direction() == RtpTransceiverDirection::kRecvOnly) {
Steve Anton52d86772018-02-20 23:48:121238 transceiver->internal()->set_direction(
1239 RtpTransceiverDirection::kSendRecv);
Steve Antonf9381f02017-12-14 18:23:571240 } else if (transceiver->direction() == RtpTransceiverDirection::kInactive) {
Steve Anton52d86772018-02-20 23:48:121241 transceiver->internal()->set_direction(
1242 RtpTransceiverDirection::kSendOnly);
Steve Antonf9381f02017-12-14 18:23:571243 }
Steve Anton02ee47c2018-01-11 00:26:061244 transceiver->sender()->SetTrack(track);
Seth Hampson845e8782018-03-02 19:34:101245 transceiver->internal()->sender_internal()->set_stream_ids(stream_ids);
Steve Antonf9381f02017-12-14 18:23:571246 } else {
1247 cricket::MediaType media_type =
1248 (track->kind() == MediaStreamTrackInterface::kAudioKind
1249 ? cricket::MEDIA_TYPE_AUDIO
1250 : cricket::MEDIA_TYPE_VIDEO);
Steve Anton3d954a62018-04-02 18:27:231251 RTC_LOG(LS_INFO) << "Adding " << cricket::MediaTypeToString(media_type)
1252 << " transceiver in response to a call to AddTrack.";
Seth Hampson845e8782018-03-02 19:34:101253 auto sender = CreateSender(media_type, track, stream_ids);
Steve Anton02ee47c2018-01-11 00:26:061254 auto receiver = CreateReceiver(media_type, rtc::CreateRandomUuid());
1255 transceiver = CreateAndAddTransceiver(sender, receiver);
Steve Antonf9381f02017-12-14 18:23:571256 transceiver->internal()->set_created_by_addtrack(true);
Steve Anton52d86772018-02-20 23:48:121257 transceiver->internal()->set_direction(RtpTransceiverDirection::kSendRecv);
Steve Antonf9381f02017-12-14 18:23:571258 }
Steve Antonf9381f02017-12-14 18:23:571259 return transceiver->sender();
1260}
1261
1262rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1263PeerConnection::FindFirstTransceiverForAddedTrack(
1264 rtc::scoped_refptr<MediaStreamTrackInterface> track) {
1265 RTC_DCHECK(track);
1266 for (auto transceiver : transceivers_) {
1267 if (!transceiver->sender()->track() &&
Steve Anton69470252018-02-09 19:43:081268 cricket::MediaTypeToString(transceiver->media_type()) ==
Steve Antonf9381f02017-12-14 18:23:571269 track->kind() &&
Seth Hampson2f0d7022018-02-20 19:54:421270 !transceiver->internal()->has_ever_been_used_to_send() &&
1271 !transceiver->stopped()) {
Steve Antonf9381f02017-12-14 18:23:571272 return transceiver;
1273 }
1274 }
1275 return nullptr;
deadbeefe1f9d832016-01-14 23:35:421276}
1277
1278bool PeerConnection::RemoveTrack(RtpSenderInterface* sender) {
1279 TRACE_EVENT0("webrtc", "PeerConnection::RemoveTrack");
Steve Antonf9381f02017-12-14 18:23:571280 return RemoveTrackInternal(sender).ok();
1281}
1282
1283RTCError PeerConnection::RemoveTrackInternal(
1284 rtc::scoped_refptr<RtpSenderInterface> sender) {
1285 if (!sender) {
1286 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "Sender is null.");
1287 }
deadbeefe1f9d832016-01-14 23:35:421288 if (IsClosed()) {
Steve Antonf9381f02017-12-14 18:23:571289 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
1290 "PeerConnection is closed.");
deadbeefe1f9d832016-01-14 23:35:421291 }
Steve Antonf9381f02017-12-14 18:23:571292 if (IsUnifiedPlan()) {
1293 auto transceiver = FindTransceiverBySender(sender);
1294 if (!transceiver || !sender->track()) {
1295 return RTCError::OK();
1296 }
1297 sender->SetTrack(nullptr);
1298 if (transceiver->direction() == RtpTransceiverDirection::kSendRecv) {
Steve Anton52d86772018-02-20 23:48:121299 transceiver->internal()->set_direction(
1300 RtpTransceiverDirection::kRecvOnly);
Steve Antonf9381f02017-12-14 18:23:571301 } else if (transceiver->direction() == RtpTransceiverDirection::kSendOnly) {
Steve Anton52d86772018-02-20 23:48:121302 transceiver->internal()->set_direction(
1303 RtpTransceiverDirection::kInactive);
Steve Antonf9381f02017-12-14 18:23:571304 }
Steve Anton4171afb2017-11-20 18:20:221305 } else {
Steve Antonf9381f02017-12-14 18:23:571306 bool removed;
1307 if (sender->media_type() == cricket::MEDIA_TYPE_AUDIO) {
1308 removed = GetAudioTransceiver()->internal()->RemoveSender(sender);
1309 } else {
1310 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, sender->media_type());
1311 removed = GetVideoTransceiver()->internal()->RemoveSender(sender);
1312 }
1313 if (!removed) {
1314 LOG_AND_RETURN_ERROR(
1315 RTCErrorType::INVALID_PARAMETER,
1316 "Couldn't find sender " + sender->id() + " to remove.");
1317 }
Steve Anton4171afb2017-11-20 18:20:221318 }
deadbeefe1f9d832016-01-14 23:35:421319 observer_->OnRenegotiationNeeded();
Steve Antonf9381f02017-12-14 18:23:571320 return RTCError::OK();
1321}
1322
1323rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1324PeerConnection::FindTransceiverBySender(
1325 rtc::scoped_refptr<RtpSenderInterface> sender) {
1326 for (auto transceiver : transceivers_) {
1327 if (transceiver->sender() == sender) {
1328 return transceiver;
1329 }
1330 }
1331 return nullptr;
deadbeefe1f9d832016-01-14 23:35:421332}
1333
Steve Anton9158ef62017-11-27 21:01:521334RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1335PeerConnection::AddTransceiver(
1336 rtc::scoped_refptr<MediaStreamTrackInterface> track) {
1337 return AddTransceiver(track, RtpTransceiverInit());
1338}
1339
1340RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1341PeerConnection::AddTransceiver(
1342 rtc::scoped_refptr<MediaStreamTrackInterface> track,
1343 const RtpTransceiverInit& init) {
Steve Antonfc853712018-03-01 21:48:581344 RTC_CHECK(IsUnifiedPlan())
1345 << "AddTransceiver is only available with Unified Plan SdpSemantics";
Steve Anton9158ef62017-11-27 21:01:521346 if (!track) {
1347 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "track is null");
1348 }
1349 cricket::MediaType media_type;
1350 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
1351 media_type = cricket::MEDIA_TYPE_AUDIO;
1352 } else if (track->kind() == MediaStreamTrackInterface::kVideoKind) {
1353 media_type = cricket::MEDIA_TYPE_VIDEO;
1354 } else {
1355 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1356 "Track kind is not audio or video");
1357 }
1358 return AddTransceiver(media_type, track, init);
1359}
1360
1361RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1362PeerConnection::AddTransceiver(cricket::MediaType media_type) {
1363 return AddTransceiver(media_type, RtpTransceiverInit());
1364}
1365
1366RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1367PeerConnection::AddTransceiver(cricket::MediaType media_type,
1368 const RtpTransceiverInit& init) {
Steve Antonfc853712018-03-01 21:48:581369 RTC_CHECK(IsUnifiedPlan())
1370 << "AddTransceiver is only available with Unified Plan SdpSemantics";
Steve Anton9158ef62017-11-27 21:01:521371 if (!(media_type == cricket::MEDIA_TYPE_AUDIO ||
1372 media_type == cricket::MEDIA_TYPE_VIDEO)) {
1373 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1374 "media type is not audio or video");
1375 }
1376 return AddTransceiver(media_type, nullptr, init);
1377}
1378
1379RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1380PeerConnection::AddTransceiver(
1381 cricket::MediaType media_type,
1382 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Steve Anton22da89f2018-01-25 21:58:071383 const RtpTransceiverInit& init,
1384 bool fire_callback) {
Steve Anton9158ef62017-11-27 21:01:521385 RTC_DCHECK((media_type == cricket::MEDIA_TYPE_AUDIO ||
1386 media_type == cricket::MEDIA_TYPE_VIDEO));
1387 if (track) {
1388 RTC_DCHECK_EQ(media_type,
1389 (track->kind() == MediaStreamTrackInterface::kAudioKind
1390 ? cricket::MEDIA_TYPE_AUDIO
1391 : cricket::MEDIA_TYPE_VIDEO));
1392 }
1393
1394 // TODO(bugs.webrtc.org/7600): Verify init.
1395
Steve Anton3d954a62018-04-02 18:27:231396 RTC_LOG(LS_INFO) << "Adding " << cricket::MediaTypeToString(media_type)
1397 << " transceiver in response to a call to AddTransceiver.";
Seth Hampson5b4f0752018-04-02 23:31:361398 auto sender = CreateSender(media_type, track, init.stream_ids);
Steve Anton02ee47c2018-01-11 00:26:061399 auto receiver = CreateReceiver(media_type, rtc::CreateRandomUuid());
1400 auto transceiver = CreateAndAddTransceiver(sender, receiver);
1401 transceiver->internal()->set_direction(init.direction);
1402
Steve Anton22da89f2018-01-25 21:58:071403 if (fire_callback) {
1404 observer_->OnRenegotiationNeeded();
1405 }
Steve Antonf9381f02017-12-14 18:23:571406
1407 return rtc::scoped_refptr<RtpTransceiverInterface>(transceiver);
1408}
1409
Steve Anton02ee47c2018-01-11 00:26:061410rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
1411PeerConnection::CreateSender(
1412 cricket::MediaType media_type,
1413 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 19:34:101414 const std::vector<std::string>& stream_ids) {
Steve Anton9158ef62017-11-27 21:01:521415 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> sender;
Steve Anton02ee47c2018-01-11 00:26:061416 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
1417 RTC_DCHECK(!track ||
1418 (track->kind() == MediaStreamTrackInterface::kAudioKind));
1419 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
1420 signaling_thread(),
Steve Anton47136dd2018-01-12 18:49:351421 new AudioRtpSender(worker_thread(),
1422 static_cast<AudioTrackInterface*>(track.get()),
Seth Hampson845e8782018-03-02 19:34:101423 stream_ids, stats_.get()));
Harald Alvestrand8ebba742018-05-31 12:00:341424 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
Steve Anton02ee47c2018-01-11 00:26:061425 } else {
1426 RTC_DCHECK_EQ(media_type, cricket::MEDIA_TYPE_VIDEO);
1427 RTC_DCHECK(!track ||
1428 (track->kind() == MediaStreamTrackInterface::kVideoKind));
1429 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
1430 signaling_thread(),
Steve Anton47136dd2018-01-12 18:49:351431 new VideoRtpSender(worker_thread(),
1432 static_cast<VideoTrackInterface*>(track.get()),
Seth Hampson845e8782018-03-02 19:34:101433 stream_ids));
Harald Alvestrand8ebba742018-05-31 12:00:341434 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
Steve Anton02ee47c2018-01-11 00:26:061435 }
Steve Anton02ee47c2018-01-11 00:26:061436 return sender;
1437}
1438
1439rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1440PeerConnection::CreateReceiver(cricket::MediaType media_type,
1441 const std::string& receiver_id) {
Steve Anton9158ef62017-11-27 21:01:521442 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1443 receiver;
Steve Anton9158ef62017-11-27 21:01:521444 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton9158ef62017-11-27 21:01:521445 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
Steve Anton60776752018-01-10 19:51:341446 signaling_thread(),
Steve Antond3679212018-01-18 01:41:021447 new AudioRtpReceiver(worker_thread(), receiver_id, {}));
Harald Alvestrand8ebba742018-05-31 12:00:341448 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
Steve Anton9158ef62017-11-27 21:01:521449 } else {
Steve Anton02ee47c2018-01-11 00:26:061450 RTC_DCHECK_EQ(media_type, cricket::MEDIA_TYPE_VIDEO);
Steve Anton9158ef62017-11-27 21:01:521451 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
1452 signaling_thread(),
Steve Antond3679212018-01-18 01:41:021453 new VideoRtpReceiver(worker_thread(), receiver_id, {}));
Harald Alvestrand8ebba742018-05-31 12:00:341454 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
Steve Anton9158ef62017-11-27 21:01:521455 }
Steve Anton02ee47c2018-01-11 00:26:061456 return receiver;
1457}
1458
1459rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1460PeerConnection::CreateAndAddTransceiver(
1461 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> sender,
1462 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1463 receiver) {
1464 auto transceiver = RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1465 signaling_thread(), new RtpTransceiver(sender, receiver));
Steve Anton9158ef62017-11-27 21:01:521466 transceivers_.push_back(transceiver);
Steve Anton52d86772018-02-20 23:48:121467 transceiver->internal()->SignalNegotiationNeeded.connect(
1468 this, &PeerConnection::OnNegotiationNeeded);
Steve Antonf9381f02017-12-14 18:23:571469 return transceiver;
Steve Anton9158ef62017-11-27 21:01:521470}
1471
Steve Anton52d86772018-02-20 23:48:121472void PeerConnection::OnNegotiationNeeded() {
1473 RTC_DCHECK_RUN_ON(signaling_thread());
1474 RTC_DCHECK(!IsClosed());
1475 observer_->OnRenegotiationNeeded();
1476}
1477
buildbot@webrtc.orgd4e598d2014-07-29 17:36:521478rtc::scoped_refptr<DtmfSenderInterface> PeerConnection::CreateDtmfSender(
henrike@webrtc.org28e20752013-07-10 00:45:361479 AudioTrackInterface* track) {
Peter Boström1a9d6152015-12-08 21:15:171480 TRACE_EVENT0("webrtc", "PeerConnection::CreateDtmfSender");
zhihuang29ff8442016-07-27 18:07:251481 if (IsClosed()) {
1482 return nullptr;
1483 }
henrike@webrtc.org28e20752013-07-10 00:45:361484 if (!track) {
Mirko Bonadei675513b2017-11-09 10:09:251485 RTC_LOG(LS_ERROR) << "CreateDtmfSender - track is NULL.";
deadbeef20cb0c12017-02-02 04:27:001486 return nullptr;
henrike@webrtc.org28e20752013-07-10 00:45:361487 }
Steve Anton4171afb2017-11-20 18:20:221488 auto track_sender = FindSenderForTrack(track);
1489 if (!track_sender) {
Mirko Bonadei675513b2017-11-09 10:09:251490 RTC_LOG(LS_ERROR) << "CreateDtmfSender called with a non-added track.";
deadbeef20cb0c12017-02-02 04:27:001491 return nullptr;
henrike@webrtc.org28e20752013-07-10 00:45:361492 }
1493
Steve Anton4171afb2017-11-20 18:20:221494 return track_sender->GetDtmfSender();
henrike@webrtc.org28e20752013-07-10 00:45:361495}
1496
deadbeeffac06552015-11-25 19:26:011497rtc::scoped_refptr<RtpSenderInterface> PeerConnection::CreateSender(
deadbeefbd7d8f72015-12-19 00:58:441498 const std::string& kind,
1499 const std::string& stream_id) {
Steve Antonfc853712018-03-01 21:48:581500 RTC_CHECK(!IsUnifiedPlan()) << "CreateSender is not available with Unified "
1501 "Plan SdpSemantics. Please use AddTransceiver "
1502 "instead.";
Peter Boström1a9d6152015-12-08 21:15:171503 TRACE_EVENT0("webrtc", "PeerConnection::CreateSender");
zhihuang29ff8442016-07-27 18:07:251504 if (IsClosed()) {
1505 return nullptr;
1506 }
Steve Anton4171afb2017-11-20 18:20:221507
Seth Hampson5b4f0752018-04-02 23:31:361508 // Internally we need to have one stream with Plan B semantics, so we
1509 // generate a random stream ID if not specified.
Seth Hampson845e8782018-03-02 19:34:101510 std::vector<std::string> stream_ids;
Seth Hampson5b4f0752018-04-02 23:31:361511 if (stream_id.empty()) {
1512 stream_ids.push_back(rtc::CreateRandomUuid());
1513 RTC_LOG(LS_INFO)
1514 << "No stream_id specified for sender. Generated stream ID: "
1515 << stream_ids[0];
1516 } else {
Seth Hampson845e8782018-03-02 19:34:101517 stream_ids.push_back(stream_id);
Steve Anton02ee47c2018-01-11 00:26:061518 }
1519
Steve Anton4171afb2017-11-20 18:20:221520 // TODO(steveanton): Move construction of the RtpSenders to RtpTransceiver.
deadbeefa601f5c2016-06-06 21:27:391521 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender;
deadbeeffac06552015-11-25 19:26:011522 if (kind == MediaStreamTrackInterface::kAudioKind) {
Seth Hampson845e8782018-03-02 19:34:101523 auto* audio_sender =
1524 new AudioRtpSender(worker_thread(), nullptr, stream_ids, stats_.get());
Steve Anton57858b32018-02-15 23:19:501525 audio_sender->SetVoiceMediaChannel(voice_media_channel());
deadbeefa601f5c2016-06-06 21:27:391526 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton02ee47c2018-01-11 00:26:061527 signaling_thread(), audio_sender);
Steve Anton4171afb2017-11-20 18:20:221528 GetAudioTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 19:26:011529 } else if (kind == MediaStreamTrackInterface::kVideoKind) {
Steve Anton47136dd2018-01-12 18:49:351530 auto* video_sender =
Seth Hampson845e8782018-03-02 19:34:101531 new VideoRtpSender(worker_thread(), nullptr, stream_ids);
Steve Anton57858b32018-02-15 23:19:501532 video_sender->SetVideoMediaChannel(video_media_channel());
deadbeefa601f5c2016-06-06 21:27:391533 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton02ee47c2018-01-11 00:26:061534 signaling_thread(), video_sender);
Steve Anton4171afb2017-11-20 18:20:221535 GetVideoTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 19:26:011536 } else {
Mirko Bonadei675513b2017-11-09 10:09:251537 RTC_LOG(LS_ERROR) << "CreateSender called with invalid kind: " << kind;
Steve Anton4171afb2017-11-20 18:20:221538 return nullptr;
deadbeeffac06552015-11-25 19:26:011539 }
Steve Anton4171afb2017-11-20 18:20:221540
deadbeefe1f9d832016-01-14 23:35:421541 return new_sender;
deadbeeffac06552015-11-25 19:26:011542}
1543
deadbeef70ab1a12015-09-28 23:53:551544std::vector<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::GetSenders()
1545 const {
deadbeefa601f5c2016-06-06 21:27:391546 std::vector<rtc::scoped_refptr<RtpSenderInterface>> ret;
Steve Anton4171afb2017-11-20 18:20:221547 for (auto sender : GetSendersInternal()) {
1548 ret.push_back(sender);
deadbeefa601f5c2016-06-06 21:27:391549 }
1550 return ret;
deadbeef70ab1a12015-09-28 23:53:551551}
1552
Steve Anton4171afb2017-11-20 18:20:221553std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1554PeerConnection::GetSendersInternal() const {
1555 std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1556 all_senders;
1557 for (auto transceiver : transceivers_) {
1558 auto senders = transceiver->internal()->senders();
1559 all_senders.insert(all_senders.end(), senders.begin(), senders.end());
1560 }
1561 return all_senders;
1562}
1563
deadbeef70ab1a12015-09-28 23:53:551564std::vector<rtc::scoped_refptr<RtpReceiverInterface>>
1565PeerConnection::GetReceivers() const {
deadbeefa601f5c2016-06-06 21:27:391566 std::vector<rtc::scoped_refptr<RtpReceiverInterface>> ret;
Steve Anton4171afb2017-11-20 18:20:221567 for (const auto& receiver : GetReceiversInternal()) {
1568 ret.push_back(receiver);
deadbeefa601f5c2016-06-06 21:27:391569 }
1570 return ret;
deadbeef70ab1a12015-09-28 23:53:551571}
1572
Steve Anton4171afb2017-11-20 18:20:221573std::vector<
1574 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1575PeerConnection::GetReceiversInternal() const {
1576 std::vector<
1577 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1578 all_receivers;
1579 for (auto transceiver : transceivers_) {
1580 auto receivers = transceiver->internal()->receivers();
1581 all_receivers.insert(all_receivers.end(), receivers.begin(),
1582 receivers.end());
1583 }
1584 return all_receivers;
1585}
1586
Steve Anton9158ef62017-11-27 21:01:521587std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
1588PeerConnection::GetTransceivers() const {
Steve Antonfc853712018-03-01 21:48:581589 RTC_CHECK(IsUnifiedPlan())
1590 << "GetTransceivers is only supported with Unified Plan SdpSemantics.";
Steve Anton9158ef62017-11-27 21:01:521591 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> all_transceivers;
1592 for (auto transceiver : transceivers_) {
1593 all_transceivers.push_back(transceiver);
1594 }
1595 return all_transceivers;
1596}
1597
henrike@webrtc.org28e20752013-07-10 00:45:361598bool PeerConnection::GetStats(StatsObserver* observer,
wu@webrtc.orgb9a088b2014-02-13 23:18:491599 MediaStreamTrackInterface* track,
1600 StatsOutputLevel level) {
Peter Boström1a9d6152015-12-08 21:15:171601 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
deadbeef0a6c4ca2015-10-06 18:38:281602 RTC_DCHECK(signaling_thread()->IsCurrent());
nisse7ce109a2017-01-31 08:57:561603 if (!observer) {
Mirko Bonadei675513b2017-11-09 10:09:251604 RTC_LOG(LS_ERROR) << "GetStats - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:361605 return false;
1606 }
1607
tommi@webrtc.org03505bc2014-07-14 20:15:261608 stats_->UpdateStats(level);
zhihuange9e94c32016-11-04 18:38:151609 // The StatsCollector is used to tell if a track is valid because it may
1610 // remember tracks that the PeerConnection previously removed.
1611 if (track && !stats_->IsValidTrack(track->id())) {
Mirko Bonadei675513b2017-11-09 10:09:251612 RTC_LOG(LS_WARNING) << "GetStats is called with an invalid track: "
1613 << track->id();
zhihuange9e94c32016-11-04 18:38:151614 return false;
1615 }
Taylor Brandstetter5d97a9a2016-06-10 21:17:271616 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_GETSTATS,
tommi@webrtc.org5b06b062014-08-15 08:38:301617 new GetStatsMsg(observer, track));
henrike@webrtc.org28e20752013-07-10 00:45:361618 return true;
1619}
1620
hbos74e1a4f2016-09-16 06:33:011621void PeerConnection::GetStats(RTCStatsCollectorCallback* callback) {
Henrik Boström1df1bf82018-03-20 12:24:201622 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
hbos74e1a4f2016-09-16 06:33:011623 RTC_DCHECK(stats_collector_);
Henrik Boström1df1bf82018-03-20 12:24:201624 RTC_DCHECK(callback);
hbos74e1a4f2016-09-16 06:33:011625 stats_collector_->GetStatsReport(callback);
1626}
1627
Henrik Boström1df1bf82018-03-20 12:24:201628void PeerConnection::GetStats(
1629 rtc::scoped_refptr<RtpSenderInterface> selector,
1630 rtc::scoped_refptr<RTCStatsCollectorCallback> callback) {
1631 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
1632 RTC_DCHECK(callback);
1633 RTC_DCHECK(stats_collector_);
1634 rtc::scoped_refptr<RtpSenderInternal> internal_sender;
1635 if (selector) {
1636 for (const auto& proxy_transceiver : transceivers_) {
1637 for (const auto& proxy_sender :
1638 proxy_transceiver->internal()->senders()) {
1639 if (proxy_sender == selector) {
1640 internal_sender = proxy_sender->internal();
1641 break;
1642 }
1643 }
1644 if (internal_sender)
1645 break;
1646 }
1647 }
1648 // If there is no |internal_sender| then |selector| is either null or does not
1649 // belong to the PeerConnection (in Plan B, senders can be removed from the
1650 // PeerConnection). This means that "all the stats objects representing the
1651 // selector" is an empty set. Invoking GetStatsReport() with a null selector
1652 // produces an empty stats report.
1653 stats_collector_->GetStatsReport(internal_sender, callback);
1654}
1655
1656void PeerConnection::GetStats(
1657 rtc::scoped_refptr<RtpReceiverInterface> selector,
1658 rtc::scoped_refptr<RTCStatsCollectorCallback> callback) {
1659 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
1660 RTC_DCHECK(callback);
1661 RTC_DCHECK(stats_collector_);
1662 rtc::scoped_refptr<RtpReceiverInternal> internal_receiver;
1663 if (selector) {
1664 for (const auto& proxy_transceiver : transceivers_) {
1665 for (const auto& proxy_receiver :
1666 proxy_transceiver->internal()->receivers()) {
1667 if (proxy_receiver == selector) {
1668 internal_receiver = proxy_receiver->internal();
1669 break;
1670 }
1671 }
1672 if (internal_receiver)
1673 break;
1674 }
1675 }
1676 // If there is no |internal_receiver| then |selector| is either null or does
1677 // not belong to the PeerConnection (in Plan B, receivers can be removed from
1678 // the PeerConnection). This means that "all the stats objects representing
1679 // the selector" is an empty set. Invoking GetStatsReport() with a null
1680 // selector produces an empty stats report.
1681 stats_collector_->GetStatsReport(internal_receiver, callback);
1682}
1683
henrike@webrtc.org28e20752013-07-10 00:45:361684PeerConnectionInterface::SignalingState PeerConnection::signaling_state() {
1685 return signaling_state_;
1686}
1687
henrike@webrtc.org28e20752013-07-10 00:45:361688PeerConnectionInterface::IceConnectionState
1689PeerConnection::ice_connection_state() {
1690 return ice_connection_state_;
1691}
1692
1693PeerConnectionInterface::IceGatheringState
1694PeerConnection::ice_gathering_state() {
1695 return ice_gathering_state_;
1696}
1697
buildbot@webrtc.orgd4e598d2014-07-29 17:36:521698rtc::scoped_refptr<DataChannelInterface>
henrike@webrtc.org28e20752013-07-10 00:45:361699PeerConnection::CreateDataChannel(
1700 const std::string& label,
1701 const DataChannelInit* config) {
Peter Boström1a9d6152015-12-08 21:15:171702 TRACE_EVENT0("webrtc", "PeerConnection::CreateDataChannel");
zhihuang9763d562016-08-05 18:14:501703
deadbeefab9b2d12015-10-14 18:33:111704 bool first_datachannel = !HasDataChannels();
jiayl@webrtc.org001fd2d2014-05-29 15:31:111705
kwibergd1fe2812016-04-27 13:47:291706 std::unique_ptr<InternalDataChannelInit> internal_config;
henrika@webrtc.orgaebb1ad2014-01-14 10:00:581707 if (config) {
1708 internal_config.reset(new InternalDataChannelInit(*config));
1709 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:521710 rtc::scoped_refptr<DataChannelInterface> channel(
deadbeefab9b2d12015-10-14 18:33:111711 InternalCreateDataChannel(label, internal_config.get()));
1712 if (!channel.get()) {
1713 return nullptr;
1714 }
henrike@webrtc.org28e20752013-07-10 00:45:361715
jiayl@webrtc.org001fd2d2014-05-29 15:31:111716 // Trigger the onRenegotiationNeeded event for every new RTP DataChannel, or
1717 // the first SCTP DataChannel.
Steve Anton75737c02017-11-06 18:37:171718 if (data_channel_type() == cricket::DCT_RTP || first_datachannel) {
jiayl@webrtc.org001fd2d2014-05-29 15:31:111719 observer_->OnRenegotiationNeeded();
1720 }
Harald Alvestrand8ebba742018-05-31 12:00:341721 NoteUsageEvent(UsageEvent::DATA_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:361722 return DataChannelProxy::Create(signaling_thread(), channel.get());
1723}
1724
1725void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
1726 const MediaConstraintsInterface* constraints) {
Peter Boström1a9d6152015-12-08 21:15:171727 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
Steve Anton8d3444d2017-10-20 22:30:511728
zhihuang1c378ed2017-08-17 21:10:501729 PeerConnectionInterface::RTCOfferAnswerOptions offer_answer_options;
1730 // Always create an offer even if |ConvertConstraintsToOfferAnswerOptions|
1731 // returns false for now. Because |ConvertConstraintsToOfferAnswerOptions|
1732 // compares the mandatory fields parsed with the mandatory fields added in the
1733 // |constraints| and some downstream applications might create offers with
1734 // mandatory fields which would not be parsed in the helper method. For
1735 // example, in Chromium/remoting, |kEnableDtlsSrtp| is added to the
1736 // |constraints| as a mandatory field but it is not parsed.
1737 ConvertConstraintsToOfferAnswerOptions(constraints, &offer_answer_options);
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:161738
zhihuang1c378ed2017-08-17 21:10:501739 CreateOffer(observer, offer_answer_options);
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:161740}
1741
1742void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
1743 const RTCOfferAnswerOptions& options) {
Peter Boström1a9d6152015-12-08 21:15:171744 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
Steve Anton8d3444d2017-10-20 22:30:511745
nisse7ce109a2017-01-31 08:57:561746 if (!observer) {
Mirko Bonadei675513b2017-11-09 10:09:251747 RTC_LOG(LS_ERROR) << "CreateOffer - observer is NULL.";
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:161748 return;
1749 }
deadbeefab9b2d12015-10-14 18:33:111750
Steve Anton8d3444d2017-10-20 22:30:511751 if (IsClosed()) {
1752 std::string error = "CreateOffer called when PeerConnection is closed.";
Mirko Bonadei675513b2017-11-09 10:09:251753 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 14:18:031754 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 13:02:101755 observer, RTCError(RTCErrorType::INVALID_STATE, std::move(error)));
Steve Anton8d3444d2017-10-20 22:30:511756 return;
1757 }
1758
zhihuang1c378ed2017-08-17 21:10:501759 if (!ValidateOfferAnswerOptions(options)) {
deadbeefab9b2d12015-10-14 18:33:111760 std::string error = "CreateOffer called with invalid options.";
Mirko Bonadei675513b2017-11-09 10:09:251761 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 14:18:031762 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 13:02:101763 observer, RTCError(RTCErrorType::INVALID_PARAMETER, std::move(error)));
deadbeefab9b2d12015-10-14 18:33:111764 return;
1765 }
1766
Steve Anton22da89f2018-01-25 21:58:071767 // Legacy handling for offer_to_receive_audio and offer_to_receive_video.
1768 // Specified in WebRTC section 4.4.3.2 "Legacy configuration extensions".
1769 if (IsUnifiedPlan()) {
1770 RTCError error = HandleLegacyOfferOptions(options);
1771 if (!error.ok()) {
Harald Alvestrand5081c0c2018-03-09 14:18:031772 PostCreateSessionDescriptionFailure(observer, std::move(error));
Steve Anton22da89f2018-01-25 21:58:071773 return;
1774 }
1775 }
1776
zhihuang1c378ed2017-08-17 21:10:501777 cricket::MediaSessionOptions session_options;
1778 GetOptionsForOffer(options, &session_options);
Steve Antond25da372017-11-06 22:50:291779 webrtc_session_desc_factory_->CreateOffer(observer, options, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:361780}
1781
Steve Anton22da89f2018-01-25 21:58:071782RTCError PeerConnection::HandleLegacyOfferOptions(
1783 const RTCOfferAnswerOptions& options) {
1784 RTC_DCHECK(IsUnifiedPlan());
1785
1786 if (options.offer_to_receive_audio == 0) {
1787 RemoveRecvDirectionFromReceivingTransceiversOfType(
1788 cricket::MEDIA_TYPE_AUDIO);
1789 } else if (options.offer_to_receive_audio == 1) {
1790 AddUpToOneReceivingTransceiverOfType(cricket::MEDIA_TYPE_AUDIO);
1791 } else if (options.offer_to_receive_audio > 1) {
1792 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
1793 "offer_to_receive_audio > 1 is not supported.");
1794 }
1795
1796 if (options.offer_to_receive_video == 0) {
1797 RemoveRecvDirectionFromReceivingTransceiversOfType(
1798 cricket::MEDIA_TYPE_VIDEO);
1799 } else if (options.offer_to_receive_video == 1) {
1800 AddUpToOneReceivingTransceiverOfType(cricket::MEDIA_TYPE_VIDEO);
1801 } else if (options.offer_to_receive_video > 1) {
1802 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
1803 "offer_to_receive_video > 1 is not supported.");
1804 }
1805
1806 return RTCError::OK();
1807}
1808
1809void PeerConnection::RemoveRecvDirectionFromReceivingTransceiversOfType(
1810 cricket::MediaType media_type) {
1811 for (auto transceiver : GetReceivingTransceiversOfType(media_type)) {
Steve Anton3d954a62018-04-02 18:27:231812 RtpTransceiverDirection new_direction =
1813 RtpTransceiverDirectionWithRecvSet(transceiver->direction(), false);
1814 if (new_direction != transceiver->direction()) {
1815 RTC_LOG(LS_INFO) << "Changing " << cricket::MediaTypeToString(media_type)
1816 << " transceiver (MID="
1817 << transceiver->mid().value_or("<not set>") << ") from "
1818 << RtpTransceiverDirectionToString(
1819 transceiver->direction())
1820 << " to "
1821 << RtpTransceiverDirectionToString(new_direction)
1822 << " since CreateOffer specified offer_to_receive=0";
1823 transceiver->internal()->set_direction(new_direction);
1824 }
Steve Anton22da89f2018-01-25 21:58:071825 }
1826}
1827
1828void PeerConnection::AddUpToOneReceivingTransceiverOfType(
1829 cricket::MediaType media_type) {
1830 if (GetReceivingTransceiversOfType(media_type).empty()) {
Steve Anton3d954a62018-04-02 18:27:231831 RTC_LOG(LS_INFO)
1832 << "Adding one recvonly " << cricket::MediaTypeToString(media_type)
1833 << " transceiver since CreateOffer specified offer_to_receive=1";
Steve Anton22da89f2018-01-25 21:58:071834 RtpTransceiverInit init;
1835 init.direction = RtpTransceiverDirection::kRecvOnly;
1836 AddTransceiver(media_type, nullptr, init, /*fire_callback=*/false);
1837 }
1838}
1839
1840std::vector<rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
1841PeerConnection::GetReceivingTransceiversOfType(cricket::MediaType media_type) {
1842 std::vector<
1843 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
1844 receiving_transceivers;
1845 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 19:43:081846 if (!transceiver->stopped() && transceiver->media_type() == media_type &&
Steve Anton22da89f2018-01-25 21:58:071847 RtpTransceiverDirectionHasRecv(transceiver->direction())) {
1848 receiving_transceivers.push_back(transceiver);
1849 }
1850 }
1851 return receiving_transceivers;
1852}
1853
henrike@webrtc.org28e20752013-07-10 00:45:361854void PeerConnection::CreateAnswer(
1855 CreateSessionDescriptionObserver* observer,
1856 const MediaConstraintsInterface* constraints) {
Peter Boström1a9d6152015-12-08 21:15:171857 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
Steve Anton8d3444d2017-10-20 22:30:511858
nisse7ce109a2017-01-31 08:57:561859 if (!observer) {
Mirko Bonadei675513b2017-11-09 10:09:251860 RTC_LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:361861 return;
1862 }
deadbeefab9b2d12015-10-14 18:33:111863
zhihuang1c378ed2017-08-17 21:10:501864 PeerConnectionInterface::RTCOfferAnswerOptions offer_answer_options;
1865 if (!ConvertConstraintsToOfferAnswerOptions(constraints,
1866 &offer_answer_options)) {
deadbeefab9b2d12015-10-14 18:33:111867 std::string error = "CreateAnswer called with invalid constraints.";
Mirko Bonadei675513b2017-11-09 10:09:251868 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 14:18:031869 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 13:02:101870 observer, RTCError(RTCErrorType::INVALID_PARAMETER, std::move(error)));
deadbeefab9b2d12015-10-14 18:33:111871 return;
1872 }
1873
Steve Anton8d3444d2017-10-20 22:30:511874 CreateAnswer(observer, offer_answer_options);
htaa2a49d92016-03-04 10:51:391875}
1876
1877void PeerConnection::CreateAnswer(CreateSessionDescriptionObserver* observer,
1878 const RTCOfferAnswerOptions& options) {
1879 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
nisse7ce109a2017-01-31 08:57:561880 if (!observer) {
Mirko Bonadei675513b2017-11-09 10:09:251881 RTC_LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
htaa2a49d92016-03-04 10:51:391882 return;
1883 }
1884
Steve Antondffead82018-02-06 18:31:291885 if (!(signaling_state_ == kHaveRemoteOffer ||
1886 signaling_state_ == kHaveLocalPrAnswer)) {
1887 std::string error =
1888 "PeerConnection cannot create an answer in a state other than "
1889 "have-remote-offer or have-local-pranswer.";
Mirko Bonadei675513b2017-11-09 10:09:251890 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 14:18:031891 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 13:02:101892 observer, RTCError(RTCErrorType::INVALID_STATE, std::move(error)));
Steve Anton8d3444d2017-10-20 22:30:511893 return;
1894 }
1895
Steve Antondffead82018-02-06 18:31:291896 // The remote description should be set if we're in the right state.
1897 RTC_DCHECK(remote_description());
Steve Anton8d3444d2017-10-20 22:30:511898
Steve Anton22da89f2018-01-25 21:58:071899 if (IsUnifiedPlan()) {
1900 if (options.offer_to_receive_audio != RTCOfferAnswerOptions::kUndefined) {
1901 RTC_LOG(LS_WARNING) << "CreateAnswer: offer_to_receive_audio is not "
1902 "supported with Unified Plan semantics. Use the "
1903 "RtpTransceiver API instead.";
1904 }
1905 if (options.offer_to_receive_video != RTCOfferAnswerOptions::kUndefined) {
1906 RTC_LOG(LS_WARNING) << "CreateAnswer: offer_to_receive_video is not "
1907 "supported with Unified Plan semantics. Use the "
1908 "RtpTransceiver API instead.";
1909 }
1910 }
1911
htaa2a49d92016-03-04 10:51:391912 cricket::MediaSessionOptions session_options;
zhihuang1c378ed2017-08-17 21:10:501913 GetOptionsForAnswer(options, &session_options);
htaa2a49d92016-03-04 10:51:391914
Steve Antond25da372017-11-06 22:50:291915 webrtc_session_desc_factory_->CreateAnswer(observer, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:361916}
1917
1918void PeerConnection::SetLocalDescription(
1919 SetSessionDescriptionObserver* observer,
Steve Anton80dd7b52018-02-17 01:08:421920 SessionDescriptionInterface* desc_ptr) {
Peter Boström1a9d6152015-12-08 21:15:171921 TRACE_EVENT0("webrtc", "PeerConnection::SetLocalDescription");
Steve Anton8a006912017-12-04 23:25:561922
Steve Anton80dd7b52018-02-17 01:08:421923 // The SetLocalDescription contract is that we take ownership of the session
1924 // description regardless of the outcome, so wrap it in a unique_ptr right
1925 // away. Ideally, SetLocalDescription's signature will be changed to take the
1926 // description as a unique_ptr argument to formalize this agreement.
1927 std::unique_ptr<SessionDescriptionInterface> desc(desc_ptr);
1928
nisse7ce109a2017-01-31 08:57:561929 if (!observer) {
Mirko Bonadei675513b2017-11-09 10:09:251930 RTC_LOG(LS_ERROR) << "SetLocalDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:361931 return;
1932 }
Steve Anton8a006912017-12-04 23:25:561933
henrike@webrtc.org28e20752013-07-10 00:45:361934 if (!desc) {
Harald Alvestrand5081c0c2018-03-09 14:18:031935 PostSetSessionDescriptionFailure(
1936 observer,
1937 RTCError(RTCErrorType::INTERNAL_ERROR, "SessionDescription is NULL."));
henrike@webrtc.org28e20752013-07-10 00:45:361938 return;
1939 }
Steve Anton8d3444d2017-10-20 22:30:511940
Steve Anton80dd7b52018-02-17 01:08:421941 // If a session error has occurred the PeerConnection is in a possibly
1942 // inconsistent state so fail right away.
1943 if (session_error() != SessionError::kNone) {
1944 std::string error_message = GetSessionErrorMsg();
1945 RTC_LOG(LS_ERROR) << "SetLocalDescription: " << error_message;
Harald Alvestrand5081c0c2018-03-09 14:18:031946 PostSetSessionDescriptionFailure(
1947 observer,
1948 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton80dd7b52018-02-17 01:08:421949 return;
1950 }
Steve Anton8d3444d2017-10-20 22:30:511951
Steve Anton80dd7b52018-02-17 01:08:421952 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_LOCAL);
1953 if (!error.ok()) {
1954 std::string error_message = GetSetDescriptionErrorMessage(
1955 cricket::CS_LOCAL, desc->GetType(), error);
1956 RTC_LOG(LS_ERROR) << error_message;
Harald Alvestrand5081c0c2018-03-09 14:18:031957 PostSetSessionDescriptionFailure(
1958 observer,
1959 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton80dd7b52018-02-17 01:08:421960 return;
1961 }
1962
1963 // Grab the description type before moving ownership to ApplyLocalDescription,
1964 // which may destroy it before returning.
1965 const SdpType type = desc->GetType();
1966
1967 error = ApplyLocalDescription(std::move(desc));
Steve Anton8a006912017-12-04 23:25:561968 // |desc| may be destroyed at this point.
1969
1970 if (!error.ok()) {
Steve Anton80dd7b52018-02-17 01:08:421971 // If ApplyLocalDescription fails, the PeerConnection could be in an
1972 // inconsistent state, so act conservatively here and set the session error
1973 // so that future calls to SetLocalDescription/SetRemoteDescription fail.
1974 SetSessionError(SessionError::kContent, error.message());
1975 std::string error_message =
1976 GetSetDescriptionErrorMessage(cricket::CS_LOCAL, type, error);
1977 RTC_LOG(LS_ERROR) << error_message;
Harald Alvestrand5081c0c2018-03-09 14:18:031978 PostSetSessionDescriptionFailure(
1979 observer,
1980 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton8d3444d2017-10-20 22:30:511981 return;
1982 }
Steve Anton8a006912017-12-04 23:25:561983 RTC_DCHECK(local_description());
1984
1985 PostSetSessionDescriptionSuccess(observer);
1986
Steve Anton8a006912017-12-04 23:25:561987 // MaybeStartGathering needs to be called after posting
1988 // MSG_SET_SESSIONDESCRIPTION_SUCCESS, so that we don't signal any candidates
1989 // before signaling that SetLocalDescription completed.
1990 transport_controller_->MaybeStartGathering();
1991
Steve Antona3a92c22017-12-07 18:27:411992 if (local_description()->GetType() == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 23:25:561993 // TODO(deadbeef): We already had to hop to the network thread for
1994 // MaybeStartGathering...
1995 network_thread()->Invoke<void>(
1996 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
1997 port_allocator_.get()));
Steve Anton0ffaaa22018-02-23 18:31:301998 // Make UMA notes about what was agreed to.
1999 ReportNegotiatedSdpSemantics(*local_description());
Steve Anton8a006912017-12-04 23:25:562000 }
Harald Alvestrand8ebba742018-05-31 12:00:342001 NoteUsageEvent(UsageEvent::SET_LOCAL_DESCRIPTION_CALLED);
Steve Anton8a006912017-12-04 23:25:562002}
2003
2004RTCError PeerConnection::ApplyLocalDescription(
2005 std::unique_ptr<SessionDescriptionInterface> desc) {
2006 RTC_DCHECK_RUN_ON(signaling_thread());
2007 RTC_DCHECK(desc);
2008
henrike@webrtc.org28e20752013-07-10 00:45:362009 // Update stats here so that we have the most recent stats for tracks and
2010 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:262011 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 23:25:562012
Steve Antondcc3c022017-12-23 00:02:542013 // Take a reference to the old local description since it's used below to
2014 // compare against the new local description. When setting the new local
2015 // description, grab ownership of the replaced session description in case it
2016 // is the same as |old_local_description|, to keep it alive for the duration
2017 // of the method.
2018 const SessionDescriptionInterface* old_local_description =
2019 local_description();
2020 std::unique_ptr<SessionDescriptionInterface> replaced_local_description;
Zhi Huange830e682018-03-30 17:48:352021 SdpType type = desc->GetType();
Steve Anton3828c062017-12-06 18:34:512022 if (type == SdpType::kAnswer) {
Steve Antondcc3c022017-12-23 00:02:542023 replaced_local_description = pending_local_description_
2024 ? std::move(pending_local_description_)
2025 : std::move(current_local_description_);
Steve Anton8a006912017-12-04 23:25:562026 current_local_description_ = std::move(desc);
2027 pending_local_description_ = nullptr;
2028 current_remote_description_ = std::move(pending_remote_description_);
2029 } else {
Steve Antondcc3c022017-12-23 00:02:542030 replaced_local_description = std::move(pending_local_description_);
Steve Anton8a006912017-12-04 23:25:562031 pending_local_description_ = std::move(desc);
2032 }
2033 // The session description to apply now must be accessed by
2034 // |local_description()|.
Henrik Boströmfdb92012017-11-09 18:55:442035 RTC_DCHECK(local_description());
deadbeefab9b2d12015-10-14 18:33:112036
Zhi Huange830e682018-03-30 17:48:352037 RTCError error = PushdownTransportDescription(cricket::CS_LOCAL, type);
2038 if (!error.ok()) {
2039 return error;
2040 }
2041
Steve Antondcc3c022017-12-23 00:02:542042 if (IsUnifiedPlan()) {
2043 RTCError error = UpdateTransceiversAndDataChannels(
Seth Hampsonae8a90a2018-02-13 23:33:482044 cricket::CS_LOCAL, *local_description(), old_local_description,
2045 remote_description());
Steve Anton8a006912017-12-04 23:25:562046 if (!error.ok()) {
2047 return error;
2048 }
Steve Antondcc3c022017-12-23 00:02:542049 for (auto transceiver : transceivers_) {
2050 const ContentInfo* content =
2051 FindMediaSectionForTransceiver(transceiver, local_description());
2052 if (!content) {
2053 continue;
2054 }
2055 const MediaContentDescription* media_desc = content->media_description();
2056 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
2057 transceiver->internal()->set_current_direction(media_desc->direction());
2058 }
2059 if (content->rejected && !transceiver->stopped()) {
Steve Anton3d954a62018-04-02 18:27:232060 RTC_LOG(LS_INFO) << "Stopping transceiver for MID=" << content->name
2061 << " since the media section was rejected.";
Steve Antondcc3c022017-12-23 00:02:542062 transceiver->Stop();
2063 }
2064 }
2065 } else {
Zhi Huange830e682018-03-30 17:48:352066 // Media channels will be created only when offer is set. These may use new
2067 // transports just created by PushdownTransportDescription.
Steve Antondcc3c022017-12-23 00:02:542068 if (type == SdpType::kOffer) {
2069 // TODO(bugs.webrtc.org/4676) - Handle CreateChannel failure, as new local
2070 // description is applied. Restore back to old description.
2071 RTCError error = CreateChannels(*local_description()->description());
2072 if (!error.ok()) {
2073 return error;
2074 }
2075 }
Steve Antondcc3c022017-12-23 00:02:542076 // Remove unused channels if MediaContentDescription is rejected.
2077 RemoveUnusedChannels(local_description()->description());
2078 }
Steve Anton8a006912017-12-04 23:25:562079
Zhi Huange830e682018-03-30 17:48:352080 error = UpdateSessionState(type, cricket::CS_LOCAL,
2081 local_description()->description());
Steve Anton8a006912017-12-04 23:25:562082 if (!error.ok()) {
2083 return error;
2084 }
Steve Antondcc3c022017-12-23 00:02:542085
Steve Anton8a006912017-12-04 23:25:562086 if (remote_description()) {
2087 // Now that we have a local description, we can push down remote candidates.
2088 UseCandidatesInSessionDescription(remote_description());
2089 }
2090
2091 pending_ice_restarts_.clear();
2092 if (session_error() != SessionError::kNone) {
2093 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
2094 }
2095
deadbeefab9b2d12015-10-14 18:33:112096 // If setting the description decided our SSL role, allocate any necessary
2097 // SCTP sids.
2098 rtc::SSLRole role;
Steve Anton75737c02017-11-06 18:37:172099 if (data_channel_type() == cricket::DCT_SCTP && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 18:33:112100 AllocateSctpSids(role);
2101 }
2102
Steve Antond3679212018-01-18 01:41:022103 if (IsUnifiedPlan()) {
2104 for (auto transceiver : transceivers_) {
2105 const ContentInfo* content =
2106 FindMediaSectionForTransceiver(transceiver, local_description());
2107 if (!content) {
2108 continue;
2109 }
Steve Anton74255ff2018-01-25 02:32:572110 const auto& streams = content->media_description()->streams();
2111 if (!content->rejected && !streams.empty()) {
Steve Antond3679212018-01-18 01:41:022112 transceiver->internal()->sender_internal()->set_stream_ids(
Seth Hampson845e8782018-03-02 19:34:102113 streams[0].stream_ids());
Steve Antond3679212018-01-18 01:41:022114 transceiver->internal()->sender_internal()->SetSsrc(
Steve Anton74255ff2018-01-25 02:32:572115 streams[0].first_ssrc());
Steve Anton60b6c1d2018-06-13 18:32:272116 } else {
2117 // 0 is a special value meaning "this sender has no associated send
2118 // stream". Need to call this so the sender won't attempt to configure
2119 // a no longer existing stream and run into DCHECKs in the lower
2120 // layers.
2121 transceiver->internal()->sender_internal()->SetSsrc(0);
Steve Antond3679212018-01-18 01:41:022122 }
2123 }
2124 } else {
2125 // Plan B semantics.
2126
Steve Antondcc3c022017-12-23 00:02:542127 // Update state and SSRC of local MediaStreams and DataChannels based on the
2128 // local session description.
2129 const cricket::ContentInfo* audio_content =
2130 GetFirstAudioContent(local_description()->description());
2131 if (audio_content) {
2132 if (audio_content->rejected) {
2133 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
2134 } else {
2135 const cricket::AudioContentDescription* audio_desc =
2136 audio_content->media_description()->as_audio();
2137 UpdateLocalSenders(audio_desc->streams(), audio_desc->type());
2138 }
deadbeeffaac4972015-11-12 23:33:072139 }
deadbeefab9b2d12015-10-14 18:33:112140
Steve Antondcc3c022017-12-23 00:02:542141 const cricket::ContentInfo* video_content =
2142 GetFirstVideoContent(local_description()->description());
2143 if (video_content) {
2144 if (video_content->rejected) {
2145 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
2146 } else {
2147 const cricket::VideoContentDescription* video_desc =
2148 video_content->media_description()->as_video();
2149 UpdateLocalSenders(video_desc->streams(), video_desc->type());
2150 }
deadbeeffaac4972015-11-12 23:33:072151 }
deadbeefab9b2d12015-10-14 18:33:112152 }
2153
2154 const cricket::ContentInfo* data_content =
Henrik Boströmfdb92012017-11-09 18:55:442155 GetFirstDataContent(local_description()->description());
deadbeefab9b2d12015-10-14 18:33:112156 if (data_content) {
2157 const cricket::DataContentDescription* data_desc =
Steve Antonb1c1de12017-12-21 23:14:302158 data_content->media_description()->as_data();
deadbeefab9b2d12015-10-14 18:33:112159 if (rtc::starts_with(data_desc->protocol().data(),
2160 cricket::kMediaProtocolRtpPrefix)) {
2161 UpdateLocalRtpDataChannels(data_desc->streams());
2162 }
2163 }
2164
Steve Anton8a006912017-12-04 23:25:562165 return RTCError::OK();
henrike@webrtc.org28e20752013-07-10 00:45:362166}
2167
2168void PeerConnection::SetRemoteDescription(
Henrik Boströma4ecf552017-11-23 14:17:072169 SetSessionDescriptionObserver* observer,
2170 SessionDescriptionInterface* desc) {
Henrik Boström31638672017-11-23 16:48:322171 SetRemoteDescription(
2172 std::unique_ptr<SessionDescriptionInterface>(desc),
2173 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface>(
2174 new SetRemoteDescriptionObserverAdapter(this, observer)));
2175}
2176
2177void PeerConnection::SetRemoteDescription(
2178 std::unique_ptr<SessionDescriptionInterface> desc,
2179 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface> observer) {
Peter Boström1a9d6152015-12-08 21:15:172180 TRACE_EVENT0("webrtc", "PeerConnection::SetRemoteDescription");
Steve Anton8a006912017-12-04 23:25:562181
nisse7ce109a2017-01-31 08:57:562182 if (!observer) {
Mirko Bonadei675513b2017-11-09 10:09:252183 RTC_LOG(LS_ERROR) << "SetRemoteDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:362184 return;
2185 }
Steve Anton8a006912017-12-04 23:25:562186
henrike@webrtc.org28e20752013-07-10 00:45:362187 if (!desc) {
Henrik Boström31638672017-11-23 16:48:322188 observer->OnSetRemoteDescriptionComplete(RTCError(
Steve Anton8a006912017-12-04 23:25:562189 RTCErrorType::INVALID_PARAMETER, "SessionDescription is NULL."));
henrike@webrtc.org28e20752013-07-10 00:45:362190 return;
2191 }
Steve Anton8d3444d2017-10-20 22:30:512192
Steve Anton80dd7b52018-02-17 01:08:422193 // If a session error has occurred the PeerConnection is in a possibly
2194 // inconsistent state so fail right away.
2195 if (session_error() != SessionError::kNone) {
2196 std::string error_message = GetSessionErrorMsg();
2197 RTC_LOG(LS_ERROR) << "SetRemoteDescription: " << error_message;
2198 observer->OnSetRemoteDescriptionComplete(
2199 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
2200 return;
2201 }
Steve Anton71439a62018-02-15 19:53:062202
Steve Antonba42e992018-04-09 21:10:012203 if (desc->GetType() == SdpType::kOffer) {
2204 // Report to UMA the format of the received offer.
2205 ReportSdpFormatReceived(*desc);
2206 }
2207
Steve Anton80dd7b52018-02-17 01:08:422208 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_REMOTE);
Steve Anton71439a62018-02-15 19:53:062209 if (!error.ok()) {
Steve Anton80dd7b52018-02-17 01:08:422210 std::string error_message = GetSetDescriptionErrorMessage(
2211 cricket::CS_REMOTE, desc->GetType(), error);
2212 RTC_LOG(LS_ERROR) << error_message;
Steve Anton71439a62018-02-15 19:53:062213 observer->OnSetRemoteDescriptionComplete(
2214 RTCError(error.type(), std::move(error_message)));
2215 return;
2216 }
Steve Anton71439a62018-02-15 19:53:062217
Steve Anton80dd7b52018-02-17 01:08:422218 // Grab the description type before moving ownership to
2219 // ApplyRemoteDescription, which may destroy it before returning.
2220 const SdpType type = desc->GetType();
2221
2222 error = ApplyRemoteDescription(std::move(desc));
2223 // |desc| may be destroyed at this point.
2224
2225 if (!error.ok()) {
2226 // If ApplyRemoteDescription fails, the PeerConnection could be in an
2227 // inconsistent state, so act conservatively here and set the session error
2228 // so that future calls to SetLocalDescription/SetRemoteDescription fail.
2229 SetSessionError(SessionError::kContent, error.message());
2230 std::string error_message =
2231 GetSetDescriptionErrorMessage(cricket::CS_REMOTE, type, error);
2232 RTC_LOG(LS_ERROR) << error_message;
2233 observer->OnSetRemoteDescriptionComplete(
2234 RTCError(error.type(), std::move(error_message)));
2235 return;
2236 }
2237 RTC_DCHECK(remote_description());
2238
2239 if (type == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 23:25:562240 // TODO(deadbeef): We already had to hop to the network thread for
2241 // MaybeStartGathering...
2242 network_thread()->Invoke<void>(
2243 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
2244 port_allocator_.get()));
Harald Alvestrand5dbb5862018-02-13 22:48:002245 // Make UMA notes about what was agreed to.
Steve Anton0ffaaa22018-02-23 18:31:302246 ReportNegotiatedSdpSemantics(*remote_description());
Steve Anton8a006912017-12-04 23:25:562247 }
2248
2249 observer->OnSetRemoteDescriptionComplete(RTCError::OK());
Harald Alvestrand8ebba742018-05-31 12:00:342250 NoteUsageEvent(UsageEvent::SET_REMOTE_DESCRIPTION_CALLED);
Steve Anton8a006912017-12-04 23:25:562251}
2252
2253RTCError PeerConnection::ApplyRemoteDescription(
2254 std::unique_ptr<SessionDescriptionInterface> desc) {
2255 RTC_DCHECK_RUN_ON(signaling_thread());
2256 RTC_DCHECK(desc);
2257
henrike@webrtc.org28e20752013-07-10 00:45:362258 // Update stats here so that we have the most recent stats for tracks and
2259 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:262260 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 23:25:562261
Steve Antondcc3c022017-12-23 00:02:542262 // Take a reference to the old remote description since it's used below to
2263 // compare against the new remote description. When setting the new remote
2264 // description, grab ownership of the replaced session description in case it
2265 // is the same as |old_remote_description|, to keep it alive for the duration
2266 // of the method.
Steve Anton8a006912017-12-04 23:25:562267 const SessionDescriptionInterface* old_remote_description =
2268 remote_description();
Steve Anton8a006912017-12-04 23:25:562269 std::unique_ptr<SessionDescriptionInterface> replaced_remote_description;
Steve Anton3828c062017-12-06 18:34:512270 SdpType type = desc->GetType();
2271 if (type == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 23:25:562272 replaced_remote_description = pending_remote_description_
2273 ? std::move(pending_remote_description_)
2274 : std::move(current_remote_description_);
2275 current_remote_description_ = std::move(desc);
2276 pending_remote_description_ = nullptr;
2277 current_local_description_ = std::move(pending_local_description_);
2278 } else {
2279 replaced_remote_description = std::move(pending_remote_description_);
2280 pending_remote_description_ = std::move(desc);
henrike@webrtc.org28e20752013-07-10 00:45:362281 }
Steve Anton8a006912017-12-04 23:25:562282 // The session description to apply now must be accessed by
2283 // |remote_description()|.
Henrik Boströmfdb92012017-11-09 18:55:442284 RTC_DCHECK(remote_description());
henrike@webrtc.org28e20752013-07-10 00:45:362285
Zhi Huange830e682018-03-30 17:48:352286 RTCError error = PushdownTransportDescription(cricket::CS_REMOTE, type);
2287 if (!error.ok()) {
2288 return error;
2289 }
Steve Anton8a006912017-12-04 23:25:562290 // Transport and Media channels will be created only when offer is set.
Steve Antondcc3c022017-12-23 00:02:542291 if (IsUnifiedPlan()) {
2292 RTCError error = UpdateTransceiversAndDataChannels(
Seth Hampsonae8a90a2018-02-13 23:33:482293 cricket::CS_REMOTE, *remote_description(), local_description(),
2294 old_remote_description);
Steve Anton8a006912017-12-04 23:25:562295 if (!error.ok()) {
2296 return error;
2297 }
Steve Antondcc3c022017-12-23 00:02:542298 } else {
Zhi Huange830e682018-03-30 17:48:352299 // Media channels will be created only when offer is set. These may use new
2300 // transports just created by PushdownTransportDescription.
Steve Antondcc3c022017-12-23 00:02:542301 if (type == SdpType::kOffer) {
Zhi Huange830e682018-03-30 17:48:352302 // TODO(mallinath) - Handle CreateChannel failure, as new local
Steve Antondcc3c022017-12-23 00:02:542303 // description is applied. Restore back to old description.
2304 RTCError error = CreateChannels(*remote_description()->description());
2305 if (!error.ok()) {
2306 return error;
2307 }
2308 }
Steve Antondcc3c022017-12-23 00:02:542309 // Remove unused channels if MediaContentDescription is rejected.
2310 RemoveUnusedChannels(remote_description()->description());
2311 }
Steve Anton8a006912017-12-04 23:25:562312
Zhi Huange830e682018-03-30 17:48:352313 // NOTE: Candidates allocation will be initiated only when
2314 // SetLocalDescription is called.
2315 error = UpdateSessionState(type, cricket::CS_REMOTE,
2316 remote_description()->description());
Steve Anton8a006912017-12-04 23:25:562317 if (!error.ok()) {
2318 return error;
2319 }
2320
2321 if (local_description() &&
2322 !UseCandidatesInSessionDescription(remote_description())) {
2323 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidCandidates);
2324 }
2325
2326 if (old_remote_description) {
2327 for (const cricket::ContentInfo& content :
2328 old_remote_description->description()->contents()) {
2329 // Check if this new SessionDescription contains new ICE ufrag and
2330 // password that indicates the remote peer requests an ICE restart.
2331 // TODO(deadbeef): When we start storing both the current and pending
2332 // remote description, this should reset pending_ice_restarts and compare
2333 // against the current description.
2334 if (CheckForRemoteIceRestart(old_remote_description, remote_description(),
2335 content.name)) {
Steve Anton3828c062017-12-06 18:34:512336 if (type == SdpType::kOffer) {
Steve Anton8a006912017-12-04 23:25:562337 pending_ice_restarts_.insert(content.name);
2338 }
2339 } else {
2340 // We retain all received candidates only if ICE is not restarted.
2341 // When ICE is restarted, all previous candidates belong to an old
2342 // generation and should not be kept.
2343 // TODO(deadbeef): This goes against the W3C spec which says the remote
2344 // description should only contain candidates from the last set remote
2345 // description plus any candidates added since then. We should remove
2346 // this once we're sure it won't break anything.
2347 WebRtcSessionDescriptionFactory::CopyCandidatesFromSessionDescription(
2348 old_remote_description, content.name, mutable_remote_description());
2349 }
2350 }
2351 }
2352
2353 if (session_error() != SessionError::kNone) {
2354 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
2355 }
2356
2357 // Set the the ICE connection state to connecting since the connection may
2358 // become writable with peer reflexive candidates before any remote candidate
2359 // is signaled.
2360 // TODO(pthatcher): This is a short-term solution for crbug/446908. A real fix
2361 // is to have a new signal the indicates a change in checking state from the
2362 // transport and expose a new checking() member from transport that can be
2363 // read to determine the current checking state. The existing SignalConnecting
2364 // actually means "gathering candidates", so cannot be be used here.
Steve Antona3a92c22017-12-07 18:27:412365 if (remote_description()->GetType() != SdpType::kOffer &&
Steve Antonf764cf42018-05-01 21:32:172366 remote_description()->number_of_mediasections() > 0u &&
Steve Anton8a006912017-12-04 23:25:562367 ice_connection_state() == PeerConnectionInterface::kIceConnectionNew) {
2368 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
2369 }
2370
deadbeefab9b2d12015-10-14 18:33:112371 // If setting the description decided our SSL role, allocate any necessary
2372 // SCTP sids.
2373 rtc::SSLRole role;
Steve Anton75737c02017-11-06 18:37:172374 if (data_channel_type() == cricket::DCT_SCTP && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 18:33:112375 AllocateSctpSids(role);
2376 }
2377
Steve Antondcc3c022017-12-23 00:02:542378 if (IsUnifiedPlan()) {
Steve Anton8b815cd2018-02-17 00:14:422379 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
Steve Anton3172c032018-05-03 22:30:182380 now_receiving_transceivers;
2381 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
2382 no_longer_receiving_transceivers;
Steve Antonc49bcd92018-02-14 22:28:132383 std::vector<rtc::scoped_refptr<MediaStreamInterface>> added_streams;
Steve Anton3172c032018-05-03 22:30:182384 std::vector<rtc::scoped_refptr<MediaStreamInterface>> removed_streams;
Steve Antondcc3c022017-12-23 00:02:542385 for (auto transceiver : transceivers_) {
2386 const ContentInfo* content =
2387 FindMediaSectionForTransceiver(transceiver, remote_description());
2388 if (!content) {
2389 continue;
2390 }
2391 const MediaContentDescription* media_desc = content->media_description();
2392 RtpTransceiverDirection local_direction =
2393 RtpTransceiverDirectionReversed(media_desc->direction());
2394 // From the WebRTC specification, steps 2.2.8.5/6 of section 4.4.1.6 "Set
2395 // the RTCSessionDescription: If direction is sendrecv or recvonly, and
2396 // transceiver's current direction is neither sendrecv nor recvonly,
2397 // process the addition of a remote track for the media description.
Seth Hampson5b4f0752018-04-02 23:31:362398 std::vector<std::string> stream_ids;
Seth Hampson2f0d7022018-02-20 19:54:422399 if (!media_desc->streams().empty()) {
Seth Hampson5897a6e2018-04-03 18:16:332400 // The remote description has signaled the stream IDs.
2401 stream_ids = media_desc->streams()[0].stream_ids();
Seth Hampson2f0d7022018-02-20 19:54:422402 }
Steve Antondcc3c022017-12-23 00:02:542403 if (RtpTransceiverDirectionHasRecv(local_direction) &&
2404 (!transceiver->current_direction() ||
2405 !RtpTransceiverDirectionHasRecv(
Seth Hampson2f0d7022018-02-20 19:54:422406 *transceiver->current_direction()))) {
Steve Anton3d954a62018-04-02 18:27:232407 RTC_LOG(LS_INFO) << "Processing the addition of a new track for MID="
Seth Hampson5b4f0752018-04-02 23:31:362408 << content->name << " (added to "
2409 << GetStreamIdsString(stream_ids) << ").";
2410
2411 std::vector<rtc::scoped_refptr<MediaStreamInterface>> media_streams;
2412 for (const std::string& stream_id : stream_ids) {
2413 rtc::scoped_refptr<MediaStreamInterface> stream =
2414 remote_streams_->find(stream_id);
2415 if (!stream) {
2416 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
2417 MediaStream::Create(stream_id));
2418 remote_streams_->AddStream(stream);
2419 added_streams.push_back(stream);
2420 }
2421 media_streams.push_back(stream);
Steve Antonef65ef12018-01-11 01:15:202422 }
Steve Anton3172c032018-05-03 22:30:182423 // This will add the remote track to the streams.
Seth Hampson5b4f0752018-04-02 23:31:362424 transceiver->internal()->receiver_internal()->SetStreams(media_streams);
Steve Anton3172c032018-05-03 22:30:182425 now_receiving_transceivers.push_back(transceiver);
Steve Antondcc3c022017-12-23 00:02:542426 }
2427 // If direction is sendonly or inactive, and transceiver's current
2428 // direction is neither sendonly nor inactive, process the removal of a
2429 // remote track for the media description.
2430 if (!RtpTransceiverDirectionHasRecv(local_direction) &&
Steve Antonef65ef12018-01-11 01:15:202431 (transceiver->current_direction() &&
Steve Antondcc3c022017-12-23 00:02:542432 RtpTransceiverDirectionHasRecv(*transceiver->current_direction()))) {
Steve Anton3d954a62018-04-02 18:27:232433 RTC_LOG(LS_INFO) << "Processing the removal of a track for MID="
2434 << content->name;
Steve Anton3172c032018-05-03 22:30:182435 std::vector<rtc::scoped_refptr<MediaStreamInterface>> media_streams =
2436 transceiver->internal()->receiver_internal()->streams();
2437 // This will remove the remote track from the streams.
Steve Antonef65ef12018-01-11 01:15:202438 transceiver->internal()->receiver_internal()->SetStreams({});
Steve Anton3172c032018-05-03 22:30:182439 no_longer_receiving_transceivers.push_back(transceiver);
2440 // Remove any streams that no longer have tracks.
2441 for (auto stream : media_streams) {
2442 if (stream->GetAudioTracks().empty() &&
2443 stream->GetVideoTracks().empty()) {
2444 remote_streams_->RemoveStream(stream);
2445 removed_streams.push_back(stream);
2446 }
2447 }
Steve Antondcc3c022017-12-23 00:02:542448 }
2449 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
2450 transceiver->internal()->set_current_direction(local_direction);
2451 }
2452 if (content->rejected && !transceiver->stopped()) {
Steve Anton3d954a62018-04-02 18:27:232453 RTC_LOG(LS_INFO) << "Stopping transceiver for MID=" << content->name
2454 << " since the media section was rejected.";
Steve Antondcc3c022017-12-23 00:02:542455 transceiver->Stop();
2456 }
Seth Hampson2f0d7022018-02-20 19:54:422457 if (!content->rejected &&
2458 RtpTransceiverDirectionHasRecv(local_direction)) {
2459 // Set ssrc to 0 in the case of an unsignalled ssrc.
2460 uint32_t ssrc = 0;
Seth Hampson5897a6e2018-04-03 18:16:332461 if (!media_desc->streams().empty() &&
2462 media_desc->streams()[0].has_ssrcs()) {
Seth Hampson2f0d7022018-02-20 19:54:422463 ssrc = media_desc->streams()[0].first_ssrc();
2464 }
2465 transceiver->internal()->receiver_internal()->SetupMediaChannel(ssrc);
Steve Antond3679212018-01-18 01:41:022466 }
Steve Antondcc3c022017-12-23 00:02:542467 }
Steve Antonc49bcd92018-02-14 22:28:132468 // Once all processing has finished, fire off callbacks.
Steve Anton3172c032018-05-03 22:30:182469 for (auto transceiver : now_receiving_transceivers) {
Steve Anton6e221372018-02-20 20:59:162470 stats_->AddTrack(transceiver->receiver()->track());
Steve Anton8b815cd2018-02-17 00:14:422471 observer_->OnTrack(transceiver);
2472 observer_->OnAddTrack(transceiver->receiver(),
2473 transceiver->receiver()->streams());
Steve Antonef65ef12018-01-11 01:15:202474 }
Steve Antonc49bcd92018-02-14 22:28:132475 for (auto stream : added_streams) {
2476 observer_->OnAddStream(stream);
2477 }
Steve Anton3172c032018-05-03 22:30:182478 for (auto transceiver : no_longer_receiving_transceivers) {
2479 observer_->OnRemoveTrack(transceiver->receiver());
2480 }
2481 for (auto stream : removed_streams) {
2482 observer_->OnRemoveStream(stream);
2483 }
Steve Antondcc3c022017-12-23 00:02:542484 }
2485
Henrik Boströmfdb92012017-11-09 18:55:442486 const cricket::ContentInfo* audio_content =
2487 GetFirstAudioContent(remote_description()->description());
2488 const cricket::ContentInfo* video_content =
2489 GetFirstVideoContent(remote_description()->description());
deadbeefbda7e0b2015-12-09 01:13:402490 const cricket::AudioContentDescription* audio_desc =
Henrik Boströmfdb92012017-11-09 18:55:442491 GetFirstAudioContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-09 01:13:402492 const cricket::VideoContentDescription* video_desc =
Henrik Boströmfdb92012017-11-09 18:55:442493 GetFirstVideoContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-09 01:13:402494 const cricket::DataContentDescription* data_desc =
Henrik Boströmfdb92012017-11-09 18:55:442495 GetFirstDataContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-09 01:13:402496
2497 // Check if the descriptions include streams, just in case the peer supports
2498 // MSID, but doesn't indicate so with "a=msid-semantic".
Henrik Boströmfdb92012017-11-09 18:55:442499 if (remote_description()->description()->msid_supported() ||
deadbeefbda7e0b2015-12-09 01:13:402500 (audio_desc && !audio_desc->streams().empty()) ||
2501 (video_desc && !video_desc->streams().empty())) {
2502 remote_peer_supports_msid_ = true;
2503 }
deadbeefab9b2d12015-10-14 18:33:112504
2505 // We wait to signal new streams until we finish processing the description,
2506 // since only at that point will new streams have all their tracks.
2507 rtc::scoped_refptr<StreamCollection> new_streams(StreamCollection::Create());
2508
Steve Antondcc3c022017-12-23 00:02:542509 if (!IsUnifiedPlan()) {
2510 // TODO(steveanton): When removing RTP senders/receivers in response to a
2511 // rejected media section, there is some cleanup logic that expects the
2512 // voice/ video channel to still be set. But in this method the voice/video
2513 // channel would have been destroyed by the SetRemoteDescription caller
2514 // above so the cleanup that relies on them fails to run. The RemoveSenders
2515 // calls should be moved to right before the DestroyChannel calls to fix
2516 // this.
Steve Anton8d3444d2017-10-20 22:30:512517
Steve Antondcc3c022017-12-23 00:02:542518 // Find all audio rtp streams and create corresponding remote AudioTracks
2519 // and MediaStreams.
2520 if (audio_content) {
2521 if (audio_content->rejected) {
2522 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
2523 } else {
2524 bool default_audio_track_needed =
2525 !remote_peer_supports_msid_ &&
2526 RtpTransceiverDirectionHasSend(audio_desc->direction());
2527 UpdateRemoteSendersList(GetActiveStreams(audio_desc),
2528 default_audio_track_needed, audio_desc->type(),
2529 new_streams);
2530 }
deadbeeffaac4972015-11-12 23:33:072531 }
deadbeefab9b2d12015-10-14 18:33:112532
Steve Antondcc3c022017-12-23 00:02:542533 // Find all video rtp streams and create corresponding remote VideoTracks
2534 // and MediaStreams.
2535 if (video_content) {
2536 if (video_content->rejected) {
2537 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
2538 } else {
2539 bool default_video_track_needed =
2540 !remote_peer_supports_msid_ &&
2541 RtpTransceiverDirectionHasSend(video_desc->direction());
2542 UpdateRemoteSendersList(GetActiveStreams(video_desc),
2543 default_video_track_needed, video_desc->type(),
2544 new_streams);
2545 }
deadbeeffaac4972015-11-12 23:33:072546 }
deadbeefab9b2d12015-10-14 18:33:112547
Steve Antondcc3c022017-12-23 00:02:542548 // Update the DataChannels with the information from the remote peer.
2549 if (data_desc) {
2550 if (rtc::starts_with(data_desc->protocol().data(),
2551 cricket::kMediaProtocolRtpPrefix)) {
2552 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
2553 }
deadbeefab9b2d12015-10-14 18:33:112554 }
deadbeefab9b2d12015-10-14 18:33:112555
Steve Antondcc3c022017-12-23 00:02:542556 // Iterate new_streams and notify the observer about new MediaStreams.
2557 for (size_t i = 0; i < new_streams->count(); ++i) {
2558 MediaStreamInterface* new_stream = new_streams->at(i);
2559 stats_->AddStream(new_stream);
2560 observer_->OnAddStream(
2561 rtc::scoped_refptr<MediaStreamInterface>(new_stream));
2562 }
deadbeefab9b2d12015-10-14 18:33:112563
Steve Antondcc3c022017-12-23 00:02:542564 UpdateEndedRemoteMediaStreams();
2565 }
deadbeefab9b2d12015-10-14 18:33:112566
Steve Anton8a006912017-12-04 23:25:562567 return RTCError::OK();
deadbeeffc648b62015-10-13 23:42:332568}
2569
Steve Antondcc3c022017-12-23 00:02:542570RTCError PeerConnection::UpdateTransceiversAndDataChannels(
2571 cricket::ContentSource source,
Seth Hampsonae8a90a2018-02-13 23:33:482572 const SessionDescriptionInterface& new_session,
2573 const SessionDescriptionInterface* old_local_description,
2574 const SessionDescriptionInterface* old_remote_description) {
Steve Antondcc3c022017-12-23 00:02:542575 RTC_DCHECK(IsUnifiedPlan());
2576
Steve Anton7464fca2018-01-19 19:10:372577 const cricket::ContentGroup* bundle_group = nullptr;
2578 if (new_session.GetType() == SdpType::kOffer) {
2579 auto bundle_group_or_error =
2580 GetEarlyBundleGroup(*new_session.description());
2581 if (!bundle_group_or_error.ok()) {
2582 return bundle_group_or_error.MoveError();
2583 }
2584 bundle_group = bundle_group_or_error.MoveValue();
Steve Antondcc3c022017-12-23 00:02:542585 }
Steve Antondcc3c022017-12-23 00:02:542586
Steve Antondcc3c022017-12-23 00:02:542587 const ContentInfos& new_contents = new_session.description()->contents();
Steve Antondcc3c022017-12-23 00:02:542588 for (size_t i = 0; i < new_contents.size(); ++i) {
2589 const cricket::ContentInfo& new_content = new_contents[i];
Steve Antondcc3c022017-12-23 00:02:542590 cricket::MediaType media_type = new_content.media_description()->type();
2591 seen_mids_.insert(new_content.name);
2592 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
2593 media_type == cricket::MEDIA_TYPE_VIDEO) {
Seth Hampsonae8a90a2018-02-13 23:33:482594 const cricket::ContentInfo* old_local_content = nullptr;
2595 if (old_local_description &&
2596 i < old_local_description->description()->contents().size()) {
2597 old_local_content =
2598 &old_local_description->description()->contents()[i];
2599 }
2600 const cricket::ContentInfo* old_remote_content = nullptr;
2601 if (old_remote_description &&
2602 i < old_remote_description->description()->contents().size()) {
2603 old_remote_content =
2604 &old_remote_description->description()->contents()[i];
2605 }
Steve Antondcc3c022017-12-23 00:02:542606 auto transceiver_or_error =
Seth Hampsonae8a90a2018-02-13 23:33:482607 AssociateTransceiver(source, new_session.GetType(), i, new_content,
2608 old_local_content, old_remote_content);
Steve Antondcc3c022017-12-23 00:02:542609 if (!transceiver_or_error.ok()) {
2610 return transceiver_or_error.MoveError();
2611 }
2612 auto transceiver = transceiver_or_error.MoveValue();
Steve Antondcc3c022017-12-23 00:02:542613 RTCError error =
2614 UpdateTransceiverChannel(transceiver, new_content, bundle_group);
2615 if (!error.ok()) {
2616 return error;
2617 }
2618 } else if (media_type == cricket::MEDIA_TYPE_DATA) {
Steve Antonfa2260d2017-12-29 00:38:232619 if (GetDataMid() && new_content.name != *GetDataMid()) {
2620 // Ignore all but the first data section.
Steve Anton3d954a62018-04-02 18:27:232621 RTC_LOG(LS_INFO) << "Ignoring data media section with MID="
2622 << new_content.name;
Steve Antonfa2260d2017-12-29 00:38:232623 continue;
2624 }
2625 RTCError error = UpdateDataChannel(source, new_content, bundle_group);
2626 if (!error.ok()) {
2627 return error;
2628 }
Steve Antondcc3c022017-12-23 00:02:542629 } else {
2630 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
2631 "Unknown section type.");
2632 }
2633 }
2634
2635 return RTCError::OK();
2636}
2637
2638RTCError PeerConnection::UpdateTransceiverChannel(
2639 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2640 transceiver,
2641 const cricket::ContentInfo& content,
2642 const cricket::ContentGroup* bundle_group) {
2643 RTC_DCHECK(IsUnifiedPlan());
2644 RTC_DCHECK(transceiver);
2645 cricket::BaseChannel* channel = transceiver->internal()->channel();
2646 if (content.rejected) {
2647 if (channel) {
2648 transceiver->internal()->SetChannel(nullptr);
2649 DestroyBaseChannel(channel);
2650 }
2651 } else {
2652 if (!channel) {
Steve Anton69470252018-02-09 19:43:082653 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Zhi Huange830e682018-03-30 17:48:352654 channel = CreateVoiceChannel(content.name);
Steve Antondcc3c022017-12-23 00:02:542655 } else {
Steve Anton69470252018-02-09 19:43:082656 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, transceiver->media_type());
Zhi Huange830e682018-03-30 17:48:352657 channel = CreateVideoChannel(content.name);
Steve Antondcc3c022017-12-23 00:02:542658 }
2659 if (!channel) {
2660 LOG_AND_RETURN_ERROR(
2661 RTCErrorType::INTERNAL_ERROR,
2662 "Failed to create channel for mid=" + content.name);
2663 }
2664 transceiver->internal()->SetChannel(channel);
2665 }
2666 }
2667 return RTCError::OK();
2668}
2669
Steve Antonfa2260d2017-12-29 00:38:232670RTCError PeerConnection::UpdateDataChannel(
2671 cricket::ContentSource source,
2672 const cricket::ContentInfo& content,
2673 const cricket::ContentGroup* bundle_group) {
2674 if (data_channel_type_ == cricket::DCT_NONE) {
Steve Antondbf9d032018-01-19 23:23:402675 // If data channels are disabled, ignore this media section. CreateAnswer
2676 // will take care of rejecting it.
2677 return RTCError::OK();
Steve Antonfa2260d2017-12-29 00:38:232678 }
2679 if (content.rejected) {
2680 DestroyDataChannel();
2681 } else {
2682 if (!rtp_data_channel_ && !sctp_transport_) {
Zhi Huange830e682018-03-30 17:48:352683 if (!CreateDataChannel(content.name)) {
Steve Antonfa2260d2017-12-29 00:38:232684 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
2685 "Failed to create data channel.");
2686 }
2687 }
2688 if (source == cricket::CS_REMOTE) {
2689 const MediaContentDescription* data_desc = content.media_description();
2690 if (data_desc && cricket::IsRtpProtocol(data_desc->protocol())) {
2691 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
2692 }
2693 }
2694 }
2695 return RTCError::OK();
2696}
2697
Steve Antondcc3c022017-12-23 00:02:542698RTCErrorOr<rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
2699PeerConnection::AssociateTransceiver(cricket::ContentSource source,
Seth Hampsonae8a90a2018-02-13 23:33:482700 SdpType type,
Steve Antondcc3c022017-12-23 00:02:542701 size_t mline_index,
2702 const ContentInfo& content,
Seth Hampsonae8a90a2018-02-13 23:33:482703 const ContentInfo* old_local_content,
2704 const ContentInfo* old_remote_content) {
Steve Antondcc3c022017-12-23 00:02:542705 RTC_DCHECK(IsUnifiedPlan());
Seth Hampsonae8a90a2018-02-13 23:33:482706 // If this is an offer then the m= section might be recycled. If the m=
2707 // section is being recycled (defined as: rejected in the current local or
2708 // remote description and not rejected in new description), dissociate the
2709 // currently associated RtpTransceiver by setting its mid property to null,
2710 // and discard the mapping between the transceiver and its m= section index.
2711 if (IsMediaSectionBeingRecycled(type, content, old_local_content,
2712 old_remote_content)) {
2713 // We want to dissociate the transceiver that has the rejected mid.
2714 const std::string& old_mid =
2715 (old_local_content && old_local_content->rejected)
2716 ? old_local_content->name
2717 : old_remote_content->name;
2718 auto old_transceiver = GetAssociatedTransceiver(old_mid);
Steve Antondcc3c022017-12-23 00:02:542719 if (old_transceiver) {
Steve Anton3d954a62018-04-02 18:27:232720 RTC_LOG(LS_INFO) << "Dissociating transceiver for MID=" << old_mid
2721 << " since the media section is being recycled.";
Steve Antondcc3c022017-12-23 00:02:542722 old_transceiver->internal()->set_mid(rtc::nullopt);
2723 old_transceiver->internal()->set_mline_index(rtc::nullopt);
2724 }
2725 }
2726 const MediaContentDescription* media_desc = content.media_description();
2727 auto transceiver = GetAssociatedTransceiver(content.name);
2728 if (source == cricket::CS_LOCAL) {
2729 // Find the RtpTransceiver that corresponds to this m= section, using the
2730 // mapping between transceivers and m= section indices established when
2731 // creating the offer.
2732 if (!transceiver) {
2733 transceiver = GetTransceiverByMLineIndex(mline_index);
2734 }
2735 if (!transceiver) {
2736 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2737 "Unknown transceiver");
2738 }
2739 } else {
2740 RTC_DCHECK_EQ(source, cricket::CS_REMOTE);
2741 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers
2742 // of the same type...
2743 if (!transceiver &&
2744 RtpTransceiverDirectionHasRecv(media_desc->direction())) {
2745 transceiver = FindAvailableTransceiverToReceive(media_desc->type());
2746 }
2747 // If no RtpTransceiver was found in the previous step, create one with a
2748 // recvonly direction.
2749 if (!transceiver) {
Steve Anton3d954a62018-04-02 18:27:232750 RTC_LOG(LS_INFO) << "Adding "
2751 << cricket::MediaTypeToString(media_desc->type())
2752 << " transceiver for MID=" << content.name
2753 << " at i=" << mline_index
2754 << " in response to the remote description.";
Steve Anton02ee47c2018-01-11 00:26:062755 auto sender =
2756 CreateSender(media_desc->type(), nullptr, {rtc::CreateRandomUuid()});
Steve Anton5f94aa22018-02-01 18:58:302757 std::string receiver_id;
2758 if (!media_desc->streams().empty()) {
2759 receiver_id = media_desc->streams()[0].id;
2760 } else {
2761 receiver_id = rtc::CreateRandomUuid();
2762 }
2763 auto receiver = CreateReceiver(media_desc->type(), receiver_id);
Steve Anton02ee47c2018-01-11 00:26:062764 transceiver = CreateAndAddTransceiver(sender, receiver);
Steve Antondcc3c022017-12-23 00:02:542765 transceiver->internal()->set_direction(
2766 RtpTransceiverDirection::kRecvOnly);
2767 }
2768 }
2769 RTC_DCHECK(transceiver);
Steve Anton69470252018-02-09 19:43:082770 if (transceiver->media_type() != media_desc->type()) {
Steve Antondcc3c022017-12-23 00:02:542771 LOG_AND_RETURN_ERROR(
2772 RTCErrorType::INVALID_PARAMETER,
2773 "Transceiver type does not match media description type.");
2774 }
2775 // Associate the found or created RtpTransceiver with the m= section by
2776 // setting the value of the RtpTransceiver's mid property to the MID of the m=
2777 // section, and establish a mapping between the transceiver and the index of
2778 // the m= section.
2779 transceiver->internal()->set_mid(content.name);
2780 transceiver->internal()->set_mline_index(mline_index);
2781 return std::move(transceiver);
2782}
2783
2784rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2785PeerConnection::GetAssociatedTransceiver(const std::string& mid) const {
2786 RTC_DCHECK(IsUnifiedPlan());
2787 for (auto transceiver : transceivers_) {
2788 if (transceiver->mid() == mid) {
2789 return transceiver;
2790 }
2791 }
2792 return nullptr;
2793}
2794
2795rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2796PeerConnection::GetTransceiverByMLineIndex(size_t mline_index) const {
2797 RTC_DCHECK(IsUnifiedPlan());
2798 for (auto transceiver : transceivers_) {
2799 if (transceiver->internal()->mline_index() == mline_index) {
2800 return transceiver;
2801 }
2802 }
2803 return nullptr;
2804}
2805
2806rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2807PeerConnection::FindAvailableTransceiverToReceive(
2808 cricket::MediaType media_type) const {
2809 RTC_DCHECK(IsUnifiedPlan());
2810 // From JSEP section 5.10 (Applying a Remote Description):
2811 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers of
2812 // the same type that were added to the PeerConnection by addTrack and are not
2813 // associated with any m= section and are not stopped, find the first such
2814 // RtpTransceiver.
2815 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 19:43:082816 if (transceiver->media_type() == media_type &&
Steve Antondcc3c022017-12-23 00:02:542817 transceiver->internal()->created_by_addtrack() && !transceiver->mid() &&
2818 !transceiver->stopped()) {
2819 return transceiver;
2820 }
2821 }
2822 return nullptr;
2823}
2824
Steve Antoned10bd92017-12-05 18:52:592825const cricket::ContentInfo* PeerConnection::FindMediaSectionForTransceiver(
2826 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2827 transceiver,
2828 const SessionDescriptionInterface* sdesc) const {
2829 RTC_DCHECK(transceiver);
2830 RTC_DCHECK(sdesc);
2831 if (IsUnifiedPlan()) {
2832 if (!transceiver->internal()->mid()) {
2833 // This transceiver is not associated with a media section yet.
2834 return nullptr;
2835 }
2836 return sdesc->description()->GetContentByName(
2837 *transceiver->internal()->mid());
2838 } else {
2839 // Plan B only allows at most one audio and one video section, so use the
2840 // first media section of that type.
2841 return cricket::GetFirstMediaContent(sdesc->description()->contents(),
Steve Anton69470252018-02-09 19:43:082842 transceiver->media_type());
Steve Antoned10bd92017-12-05 18:52:592843 }
2844}
2845
deadbeef46c73892016-11-17 03:42:042846PeerConnectionInterface::RTCConfiguration PeerConnection::GetConfiguration() {
2847 return configuration_;
2848}
2849
deadbeef293e9262017-01-11 20:28:302850bool PeerConnection::SetConfiguration(const RTCConfiguration& configuration,
2851 RTCError* error) {
Peter Boström1a9d6152015-12-08 21:15:172852 TRACE_EVENT0("webrtc", "PeerConnection::SetConfiguration");
Steve Antonc79268f2018-04-24 16:54:102853 if (IsClosed()) {
2854 RTC_LOG(LS_ERROR) << "SetConfiguration: PeerConnection is closed.";
2855 return SafeSetError(RTCErrorType::INVALID_STATE, error);
2856 }
2857
Qingsi Wanga2d60672018-04-11 23:57:452858 // According to JSEP, after setLocalDescription, changing the candidate pool
2859 // size is not allowed, and changing the set of ICE servers will not result
2860 // in new candidates being gathered.
Steve Anton75737c02017-11-06 18:37:172861 if (local_description() && configuration.ice_candidate_pool_size !=
2862 configuration_.ice_candidate_pool_size) {
Mirko Bonadei675513b2017-11-09 10:09:252863 RTC_LOG(LS_ERROR) << "Can't change candidate pool size after calling "
2864 "SetLocalDescription.";
deadbeef293e9262017-01-11 20:28:302865 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
buildbot@webrtc.org41451d42014-05-03 05:39:452866 }
Taylor Brandstettera1c30352016-05-13 15:15:112867
deadbeef293e9262017-01-11 20:28:302868 // The simplest (and most future-compatible) way to tell if the config was
2869 // modified in an invalid way is to copy each property we do support
2870 // modifying, then use operator==. There are far more properties we don't
2871 // support modifying than those we do, and more could be added.
2872 RTCConfiguration modified_config = configuration_;
2873 modified_config.servers = configuration.servers;
2874 modified_config.type = configuration.type;
2875 modified_config.ice_candidate_pool_size =
2876 configuration.ice_candidate_pool_size;
2877 modified_config.prune_turn_ports = configuration.prune_turn_ports;
skvladd1f5fda2017-02-04 00:54:052878 modified_config.ice_check_min_interval = configuration.ice_check_min_interval;
Qingsi Wange6826d22018-03-08 22:55:142879 modified_config.ice_check_interval_strong_connectivity =
2880 configuration.ice_check_interval_strong_connectivity;
2881 modified_config.ice_check_interval_weak_connectivity =
2882 configuration.ice_check_interval_weak_connectivity;
Qingsi Wang22e623a2018-03-13 17:53:572883 modified_config.ice_unwritable_timeout = configuration.ice_unwritable_timeout;
2884 modified_config.ice_unwritable_min_checks =
2885 configuration.ice_unwritable_min_checks;
Qingsi Wangdb53f8e2018-02-20 22:45:492886 modified_config.stun_candidate_keepalive_interval =
2887 configuration.stun_candidate_keepalive_interval;
Jonas Orelandbdcee282017-10-10 12:01:402888 modified_config.turn_customizer = configuration.turn_customizer;
Qingsi Wang9a5c6f82018-02-01 18:38:402889 modified_config.network_preference = configuration.network_preference;
Zhi Huangb57e1692018-06-12 18:41:112890 modified_config.active_reset_srtp_params =
2891 configuration.active_reset_srtp_params;
deadbeef293e9262017-01-11 20:28:302892 if (configuration != modified_config) {
Mirko Bonadei675513b2017-11-09 10:09:252893 RTC_LOG(LS_ERROR) << "Modifying the configuration in an unsupported way.";
deadbeef293e9262017-01-11 20:28:302894 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
2895 }
2896
Steve Anton038834f2017-07-14 22:59:592897 // Validate the modified configuration.
2898 RTCError validate_error = ValidateConfiguration(modified_config);
2899 if (!validate_error.ok()) {
2900 return SafeSetError(std::move(validate_error), error);
2901 }
2902
deadbeef293e9262017-01-11 20:28:302903 // Note that this isn't possible through chromium, since it's an unsigned
2904 // short in WebIDL.
2905 if (configuration.ice_candidate_pool_size < 0 ||
Wez939eb802018-05-03 10:34:172906 configuration.ice_candidate_pool_size > static_cast<int>(UINT16_MAX)) {
deadbeef293e9262017-01-11 20:28:302907 return SafeSetError(RTCErrorType::INVALID_RANGE, error);
2908 }
2909
2910 // Parse ICE servers before hopping to network thread.
2911 cricket::ServerAddresses stun_servers;
2912 std::vector<cricket::RelayServerConfig> turn_servers;
2913 RTCErrorType parse_error =
2914 ParseIceServers(configuration.servers, &stun_servers, &turn_servers);
2915 if (parse_error != RTCErrorType::NONE) {
2916 return SafeSetError(parse_error, error);
2917 }
Harald Alvestrand8ebba742018-05-31 12:00:342918 // Note if STUN or TURN servers were supplied.
2919 if (!stun_servers.empty()) {
2920 NoteUsageEvent(UsageEvent::STUN_SERVER_ADDED);
2921 }
2922 if (!turn_servers.empty()) {
2923 NoteUsageEvent(UsageEvent::TURN_SERVER_ADDED);
2924 }
deadbeef293e9262017-01-11 20:28:302925
2926 // In theory this shouldn't fail.
2927 if (!network_thread()->Invoke<bool>(
2928 RTC_FROM_HERE,
2929 rtc::Bind(&PeerConnection::ReconfigurePortAllocator_n, this,
2930 stun_servers, turn_servers, modified_config.type,
2931 modified_config.ice_candidate_pool_size,
Jonas Orelandbdcee282017-10-10 12:01:402932 modified_config.prune_turn_ports,
Qingsi Wangdb53f8e2018-02-20 22:45:492933 modified_config.turn_customizer,
2934 modified_config.stun_candidate_keepalive_interval))) {
Mirko Bonadei675513b2017-11-09 10:09:252935 RTC_LOG(LS_ERROR) << "Failed to apply configuration to PortAllocator.";
deadbeef293e9262017-01-11 20:28:302936 return SafeSetError(RTCErrorType::INTERNAL_ERROR, error);
2937 }
Honghai Zhang4cedf2b2016-08-31 15:18:112938
deadbeefd1a38b52016-12-10 21:15:332939 // As described in JSEP, calling setConfiguration with new ICE servers or
2940 // candidate policy must set a "needs-ice-restart" bit so that the next offer
2941 // triggers an ICE restart which will pick up the changes.
deadbeef293e9262017-01-11 20:28:302942 if (modified_config.servers != configuration_.servers ||
2943 modified_config.type != configuration_.type ||
2944 modified_config.prune_turn_ports != configuration_.prune_turn_ports) {
Steve Antond25da372017-11-06 22:50:292945 transport_controller_->SetNeedsIceRestartFlag();
deadbeefd1a38b52016-12-10 21:15:332946 }
skvladd1f5fda2017-02-04 00:54:052947
Qingsi Wang9c98f0c2018-02-15 23:10:592948 transport_controller_->SetIceConfig(ParseIceConfig(modified_config));
skvladd1f5fda2017-02-04 00:54:052949
Zhi Huangb57e1692018-06-12 18:41:112950 if (configuration_.active_reset_srtp_params !=
2951 modified_config.active_reset_srtp_params) {
2952 transport_controller_->SetActiveResetSrtpParams(
2953 modified_config.active_reset_srtp_params);
2954 }
2955
deadbeef293e9262017-01-11 20:28:302956 configuration_ = modified_config;
2957 return SafeSetError(RTCErrorType::NONE, error);
buildbot@webrtc.org41451d42014-05-03 05:39:452958}
2959
henrike@webrtc.org28e20752013-07-10 00:45:362960bool PeerConnection::AddIceCandidate(
2961 const IceCandidateInterface* ice_candidate) {
Peter Boström1a9d6152015-12-08 21:15:172962 TRACE_EVENT0("webrtc", "PeerConnection::AddIceCandidate");
zhihuang29ff8442016-07-27 18:07:252963 if (IsClosed()) {
Steve Antonc79268f2018-04-24 16:54:102964 RTC_LOG(LS_ERROR) << "AddIceCandidate: PeerConnection is closed.";
zhihuang29ff8442016-07-27 18:07:252965 return false;
2966 }
Steve Antond25da372017-11-06 22:50:292967
2968 if (!remote_description()) {
Steve Antonc79268f2018-04-24 16:54:102969 RTC_LOG(LS_ERROR) << "AddIceCandidate: ICE candidates can't be added "
Jonas Olsson45cc8902018-02-13 09:37:072970 "without any remote session description.";
Steve Antond25da372017-11-06 22:50:292971 return false;
2972 }
2973
2974 if (!ice_candidate) {
Steve Antonc79268f2018-04-24 16:54:102975 RTC_LOG(LS_ERROR) << "AddIceCandidate: Candidate is null.";
Steve Antond25da372017-11-06 22:50:292976 return false;
2977 }
2978
2979 bool valid = false;
2980 bool ready = ReadyToUseRemoteCandidate(ice_candidate, nullptr, &valid);
2981 if (!valid) {
2982 return false;
2983 }
2984
2985 // Add this candidate to the remote session description.
2986 if (!mutable_remote_description()->AddCandidate(ice_candidate)) {
Steve Antonc79268f2018-04-24 16:54:102987 RTC_LOG(LS_ERROR) << "AddIceCandidate: Candidate cannot be used.";
Steve Antond25da372017-11-06 22:50:292988 return false;
2989 }
Harald Alvestrand8ebba742018-05-31 12:00:342990 NoteUsageEvent(UsageEvent::REMOTE_CANDIDATE_ADDED);
Steve Antond25da372017-11-06 22:50:292991
2992 if (ready) {
2993 return UseCandidate(ice_candidate);
2994 } else {
Steve Antonc79268f2018-04-24 16:54:102995 RTC_LOG(LS_INFO) << "AddIceCandidate: Not ready to use candidate.";
Steve Antond25da372017-11-06 22:50:292996 return true;
2997 }
henrike@webrtc.org28e20752013-07-10 00:45:362998}
2999
Honghai Zhang7fb69db2016-03-14 18:59:183000bool PeerConnection::RemoveIceCandidates(
3001 const std::vector<cricket::Candidate>& candidates) {
3002 TRACE_EVENT0("webrtc", "PeerConnection::RemoveIceCandidates");
Steve Antonc79268f2018-04-24 16:54:103003 if (IsClosed()) {
3004 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: PeerConnection is closed.";
3005 return false;
3006 }
3007
Steve Antond25da372017-11-06 22:50:293008 if (!remote_description()) {
Steve Antonc79268f2018-04-24 16:54:103009 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: ICE candidates can't be removed "
3010 "without any remote session description.";
Steve Antond25da372017-11-06 22:50:293011 return false;
3012 }
3013
3014 if (candidates.empty()) {
Steve Antonc79268f2018-04-24 16:54:103015 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: candidates are empty.";
Steve Antond25da372017-11-06 22:50:293016 return false;
3017 }
3018
3019 size_t number_removed =
3020 mutable_remote_description()->RemoveCandidates(candidates);
3021 if (number_removed != candidates.size()) {
Mirko Bonadei675513b2017-11-09 10:09:253022 RTC_LOG(LS_ERROR)
Steve Antonc79268f2018-04-24 16:54:103023 << "RemoveIceCandidates: Failed to remove candidates. Requested "
Jonas Olsson45cc8902018-02-13 09:37:073024 << candidates.size() << " but only " << number_removed
Mirko Bonadei675513b2017-11-09 10:09:253025 << " are removed.";
Steve Antond25da372017-11-06 22:50:293026 }
3027
3028 // Remove the candidates from the transport controller.
Zhi Huange830e682018-03-30 17:48:353029 RTCError error = transport_controller_->RemoveRemoteCandidates(candidates);
3030 if (!error.ok()) {
Steve Antonc79268f2018-04-24 16:54:103031 RTC_LOG(LS_ERROR)
3032 << "RemoveIceCandidates: Error when removing remote candidates: "
3033 << error.message();
Steve Antond25da372017-11-06 22:50:293034 }
3035 return true;
Honghai Zhang7fb69db2016-03-14 18:59:183036}
3037
buildbot@webrtc.org1567b8c2014-05-08 19:54:163038void PeerConnection::RegisterUMAObserver(UMAObserver* observer) {
Peter Boström1a9d6152015-12-08 21:15:173039 TRACE_EVENT0("webrtc", "PeerConnection::RegisterUmaObserver");
Qingsi Wanga2d60672018-04-11 23:57:453040 network_thread()->Invoke<void>(
3041 RTC_FROM_HERE,
3042 rtc::Bind(&PeerConnection::SetMetricObserver_n, this, observer));
3043 // Send information about IPv4/IPv6 status.
3044 if (uma_observer_) {
3045 if (port_allocator_flags_ & cricket::PORTALLOCATOR_ENABLE_IPV6) {
3046 uma_observer_->IncrementEnumCounter(
3047 kEnumCounterAddressFamily, kPeerConnection_IPv6,
3048 kPeerConnectionAddressFamilyCounter_Max);
3049 } else {
3050 uma_observer_->IncrementEnumCounter(
3051 kEnumCounterAddressFamily, kPeerConnection_IPv4,
3052 kPeerConnectionAddressFamilyCounter_Max);
3053 }
3054 }
3055}
Patrik Höglund3dc41062018-04-11 11:13:573056
Qingsi Wanga2d60672018-04-11 23:57:453057void PeerConnection::SetMetricObserver_n(UMAObserver* observer) {
3058 RTC_DCHECK(network_thread()->IsCurrent());
3059 uma_observer_ = observer;
Steve Antonc79268f2018-04-24 16:54:103060 if (transport_controller_) {
3061 transport_controller_->SetMetricsObserver(uma_observer_);
Patrik Höglund3dc41062018-04-11 11:13:573062 }
3063
3064 for (auto transceiver : transceivers_) {
3065 auto* channel = transceiver->internal()->channel();
3066 if (channel) {
3067 channel->SetMetricsObserver(uma_observer_);
3068 }
3069 }
3070
deadbeef293e9262017-01-11 20:28:303071 if (uma_observer_) {
Patrik Höglund3dc41062018-04-11 11:13:573072 port_allocator_->SetMetricsObserver(uma_observer_);
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:183073 }
buildbot@webrtc.org1567b8c2014-05-08 19:54:163074}
3075
Niels Möller0c4f7be2018-05-07 12:01:373076RTCError PeerConnection::SetBitrate(const BitrateSettings& bitrate) {
Steve Anton978b8762017-09-29 19:15:023077 if (!worker_thread()->IsCurrent()) {
3078 return worker_thread()->Invoke<RTCError>(
Niels Möller0c4f7be2018-05-07 12:01:373079 RTC_FROM_HERE, [&](){ return SetBitrate(bitrate); });
zstein4b979802017-06-02 21:37:373080 }
3081
Niels Möller0c4f7be2018-05-07 12:01:373082 const bool has_min = bitrate.min_bitrate_bps.has_value();
3083 const bool has_start = bitrate.start_bitrate_bps.has_value();
3084 const bool has_max = bitrate.max_bitrate_bps.has_value();
zstein4b979802017-06-02 21:37:373085 if (has_min && *bitrate.min_bitrate_bps < 0) {
3086 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3087 "min_bitrate_bps <= 0");
3088 }
Niels Möller0c4f7be2018-05-07 12:01:373089 if (has_start) {
3090 if (has_min && *bitrate.start_bitrate_bps < *bitrate.min_bitrate_bps) {
zstein4b979802017-06-02 21:37:373091 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
Niels Möller0c4f7be2018-05-07 12:01:373092 "start_bitrate_bps < min_bitrate_bps");
3093 } else if (*bitrate.start_bitrate_bps < 0) {
zstein4b979802017-06-02 21:37:373094 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3095 "curent_bitrate_bps < 0");
3096 }
3097 }
3098 if (has_max) {
Niels Möller0c4f7be2018-05-07 12:01:373099 if (has_start &&
3100 *bitrate.max_bitrate_bps < *bitrate.start_bitrate_bps) {
zstein4b979802017-06-02 21:37:373101 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
Niels Möller0c4f7be2018-05-07 12:01:373102 "max_bitrate_bps < start_bitrate_bps");
zstein4b979802017-06-02 21:37:373103 } else if (has_min && *bitrate.max_bitrate_bps < *bitrate.min_bitrate_bps) {
3104 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3105 "max_bitrate_bps < min_bitrate_bps");
3106 } else if (*bitrate.max_bitrate_bps < 0) {
3107 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3108 "max_bitrate_bps < 0");
3109 }
3110 }
3111
zstein4b979802017-06-02 21:37:373112 RTC_DCHECK(call_.get());
Niels Möller0c4f7be2018-05-07 12:01:373113 call_->GetTransportControllerSend()->SetClientBitratePreferences(bitrate);
zstein4b979802017-06-02 21:37:373114
3115 return RTCError::OK();
3116}
3117
Alex Narest78609d52017-10-20 08:37:473118void PeerConnection::SetBitrateAllocationStrategy(
3119 std::unique_ptr<rtc::BitrateAllocationStrategy>
3120 bitrate_allocation_strategy) {
3121 rtc::Thread* worker_thread = factory_->worker_thread();
3122 if (!worker_thread->IsCurrent()) {
3123 rtc::BitrateAllocationStrategy* strategy_raw =
3124 bitrate_allocation_strategy.release();
3125 auto functor = [this, strategy_raw]() {
3126 call_->SetBitrateAllocationStrategy(
3127 rtc::WrapUnique<rtc::BitrateAllocationStrategy>(strategy_raw));
3128 };
3129 worker_thread->Invoke<void>(RTC_FROM_HERE, functor);
3130 return;
3131 }
3132 RTC_DCHECK(call_.get());
3133 call_->SetBitrateAllocationStrategy(std::move(bitrate_allocation_strategy));
3134}
3135
henrika5f6bf242017-11-01 10:06:563136void PeerConnection::SetAudioPlayout(bool playout) {
3137 if (!worker_thread()->IsCurrent()) {
3138 worker_thread()->Invoke<void>(
3139 RTC_FROM_HERE,
3140 rtc::Bind(&PeerConnection::SetAudioPlayout, this, playout));
3141 return;
3142 }
3143 auto audio_state =
3144 factory_->channel_manager()->media_engine()->GetAudioState();
3145 audio_state->SetPlayout(playout);
3146}
3147
3148void PeerConnection::SetAudioRecording(bool recording) {
3149 if (!worker_thread()->IsCurrent()) {
3150 worker_thread()->Invoke<void>(
3151 RTC_FROM_HERE,
3152 rtc::Bind(&PeerConnection::SetAudioRecording, this, recording));
3153 return;
3154 }
3155 auto audio_state =
3156 factory_->channel_manager()->media_engine()->GetAudioState();
3157 audio_state->SetRecording(recording);
3158}
3159
Steve Anton8c0f7a72017-10-03 17:03:103160std::unique_ptr<rtc::SSLCertificate>
3161PeerConnection::GetRemoteAudioSSLCertificate() {
Taylor Brandstetterc3928662018-02-23 21:04:513162 std::unique_ptr<rtc::SSLCertChain> chain = GetRemoteAudioSSLCertChain();
3163 if (!chain || !chain->GetSize()) {
Steve Anton8c0f7a72017-10-03 17:03:103164 return nullptr;
3165 }
Taylor Brandstetterc3928662018-02-23 21:04:513166 return chain->Get(0).GetUniqueReference();
Steve Anton8c0f7a72017-10-03 17:03:103167}
3168
Zhi Huang70b820f2018-01-27 22:16:153169std::unique_ptr<rtc::SSLCertChain>
3170PeerConnection::GetRemoteAudioSSLCertChain() {
Steve Antonafb0bb72018-02-20 19:35:373171 auto audio_transceiver = GetFirstAudioTransceiver();
3172 if (!audio_transceiver || !audio_transceiver->internal()->channel()) {
Zhi Huang70b820f2018-01-27 22:16:153173 return nullptr;
3174 }
Zhi Huang70b820f2018-01-27 22:16:153175 return transport_controller_->GetRemoteSSLCertChain(
Steve Antonafb0bb72018-02-20 19:35:373176 audio_transceiver->internal()->channel()->transport_name());
3177}
3178
3179rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3180PeerConnection::GetFirstAudioTransceiver() const {
3181 for (auto transceiver : transceivers_) {
3182 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
3183 return transceiver;
3184 }
3185 }
3186 return nullptr;
Zhi Huang70b820f2018-01-27 22:16:153187}
3188
ivoc14d5dbe2016-07-04 14:06:553189bool PeerConnection::StartRtcEventLog(rtc::PlatformFile file,
3190 int64_t max_size_bytes) {
Elad Alon99c3fe52017-10-13 14:29:403191 // TODO(eladalon): It would be better to not allow negative values into PC.
3192 const size_t max_size = (max_size_bytes < 0)
3193 ? RtcEventLog::kUnlimitedOutput
3194 : rtc::saturated_cast<size_t>(max_size_bytes);
3195 return StartRtcEventLog(
Bjorn Tereliusde939432017-11-20 16:38:143196 rtc::MakeUnique<RtcEventLogOutputFile>(file, max_size),
3197 webrtc::RtcEventLog::kImmediateOutput);
Elad Alon99c3fe52017-10-13 14:29:403198}
3199
Bjorn Tereliusde939432017-11-20 16:38:143200bool PeerConnection::StartRtcEventLog(std::unique_ptr<RtcEventLogOutput> output,
3201 int64_t output_period_ms) {
Karl Wibergd6b48192017-10-16 21:01:063202 // TODO(eladalon): In C++14, this can be done with a lambda.
3203 struct Functor {
Bjorn Tereliusde939432017-11-20 16:38:143204 bool operator()() {
3205 return pc->StartRtcEventLog_w(std::move(output), output_period_ms);
3206 }
Karl Wibergd6b48192017-10-16 21:01:063207 PeerConnection* const pc;
3208 std::unique_ptr<RtcEventLogOutput> output;
Bjorn Tereliusde939432017-11-20 16:38:143209 const int64_t output_period_ms;
Elad Alon99c3fe52017-10-13 14:29:403210 };
Bjorn Tereliusde939432017-11-20 16:38:143211 return worker_thread()->Invoke<bool>(
3212 RTC_FROM_HERE, Functor{this, std::move(output), output_period_ms});
ivoc14d5dbe2016-07-04 14:06:553213}
3214
3215void PeerConnection::StopRtcEventLog() {
Steve Anton978b8762017-09-29 19:15:023216 worker_thread()->Invoke<void>(
ivoc14d5dbe2016-07-04 14:06:553217 RTC_FROM_HERE, rtc::Bind(&PeerConnection::StopRtcEventLog_w, this));
3218}
3219
henrike@webrtc.org28e20752013-07-10 00:45:363220const SessionDescriptionInterface* PeerConnection::local_description() const {
Steve Anton75737c02017-11-06 18:37:173221 return pending_local_description_ ? pending_local_description_.get()
3222 : current_local_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:363223}
3224
3225const SessionDescriptionInterface* PeerConnection::remote_description() const {
Steve Anton75737c02017-11-06 18:37:173226 return pending_remote_description_ ? pending_remote_description_.get()
3227 : current_remote_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:363228}
3229
deadbeeffe4a8a42016-12-21 01:56:173230const SessionDescriptionInterface* PeerConnection::current_local_description()
3231 const {
Steve Anton75737c02017-11-06 18:37:173232 return current_local_description_.get();
deadbeeffe4a8a42016-12-21 01:56:173233}
3234
3235const SessionDescriptionInterface* PeerConnection::current_remote_description()
3236 const {
Steve Anton75737c02017-11-06 18:37:173237 return current_remote_description_.get();
deadbeeffe4a8a42016-12-21 01:56:173238}
3239
3240const SessionDescriptionInterface* PeerConnection::pending_local_description()
3241 const {
Steve Anton75737c02017-11-06 18:37:173242 return pending_local_description_.get();
deadbeeffe4a8a42016-12-21 01:56:173243}
3244
3245const SessionDescriptionInterface* PeerConnection::pending_remote_description()
3246 const {
Steve Anton75737c02017-11-06 18:37:173247 return pending_remote_description_.get();
deadbeeffe4a8a42016-12-21 01:56:173248}
3249
henrike@webrtc.org28e20752013-07-10 00:45:363250void PeerConnection::Close() {
Peter Boström1a9d6152015-12-08 21:15:173251 TRACE_EVENT0("webrtc", "PeerConnection::Close");
henrike@webrtc.org28e20752013-07-10 00:45:363252 // Update stats here so that we have the most recent stats for tracks and
3253 // streams before the channels are closed.
tommi@webrtc.org03505bc2014-07-14 20:15:263254 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:363255
Steve Anton75737c02017-11-06 18:37:173256 ChangeSignalingState(PeerConnectionInterface::kClosed);
Harald Alvestrand8ebba742018-05-31 12:00:343257 NoteUsageEvent(UsageEvent::CLOSE_CALLED);
Steve Anton3fe1b152017-12-12 18:20:083258
Steve Anton8af21862017-12-15 19:20:133259 for (auto transceiver : transceivers_) {
3260 transceiver->Stop();
3261 }
Steve Anton25cfeb92018-04-26 18:44:003262
3263 // Ensure that all asynchronous stats requests are completed before destroying
3264 // the transport controller below.
3265 if (stats_collector_) {
3266 stats_collector_->WaitForPendingRequest();
3267 }
3268
3269 // Don't destroy BaseChannels until after stats has been cleaned up so that
3270 // the last stats request can still read from the channels.
Steve Anton8af21862017-12-15 19:20:133271 DestroyAllChannels();
Steve Anton75737c02017-11-06 18:37:173272
Qingsi Wang93a84392018-01-31 01:13:093273 // The event log is used in the transport controller, which must be outlived
3274 // by the former. CreateOffer by the peer connection is implemented
3275 // asynchronously and if the peer connection is closed without resetting the
3276 // WebRTC session description factory, the session description factory would
3277 // call the transport controller.
3278 webrtc_session_desc_factory_.reset();
3279 transport_controller_.reset();
3280
deadbeef42a42632017-03-10 23:18:003281 network_thread()->Invoke<void>(
3282 RTC_FROM_HERE,
3283 rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
3284 port_allocator_.get()));
nisseeaabdf62017-05-05 09:23:023285
Steve Anton978b8762017-09-29 19:15:023286 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
eladalon248fd4f2017-09-06 12:18:153287 call_.reset();
3288 // The event log must outlive call (and any other object that uses it).
3289 event_log_.reset();
3290 });
Harald Alvestrand8ebba742018-05-31 12:00:343291 ReportUsagePattern();
henrike@webrtc.org28e20752013-07-10 00:45:363292}
3293
buildbot@webrtc.orgd4e598d2014-07-29 17:36:523294void PeerConnection::OnMessage(rtc::Message* msg) {
henrike@webrtc.org28e20752013-07-10 00:45:363295 switch (msg->message_id) {
henrike@webrtc.org28e20752013-07-10 00:45:363296 case MSG_SET_SESSIONDESCRIPTION_SUCCESS: {
3297 SetSessionDescriptionMsg* param =
3298 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
3299 param->observer->OnSuccess();
3300 delete param;
3301 break;
3302 }
3303 case MSG_SET_SESSIONDESCRIPTION_FAILED: {
3304 SetSessionDescriptionMsg* param =
3305 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
Harald Alvestrand5081c0c2018-03-09 14:18:033306 param->observer->OnFailure(std::move(param->error));
henrike@webrtc.org28e20752013-07-10 00:45:363307 delete param;
3308 break;
3309 }
deadbeefab9b2d12015-10-14 18:33:113310 case MSG_CREATE_SESSIONDESCRIPTION_FAILED: {
3311 CreateSessionDescriptionMsg* param =
3312 static_cast<CreateSessionDescriptionMsg*>(msg->pdata);
Harald Alvestrand5081c0c2018-03-09 14:18:033313 param->observer->OnFailure(std::move(param->error));
deadbeefab9b2d12015-10-14 18:33:113314 delete param;
3315 break;
3316 }
henrike@webrtc.org28e20752013-07-10 00:45:363317 case MSG_GETSTATS: {
3318 GetStatsMsg* param = static_cast<GetStatsMsg*>(msg->pdata);
nissee8abe3e2017-01-18 13:00:343319 StatsReports reports;
3320 stats_->GetStats(param->track, &reports);
3321 param->observer->OnComplete(reports);
henrike@webrtc.org28e20752013-07-10 00:45:363322 delete param;
3323 break;
3324 }
deadbeefbd292462015-12-15 02:15:293325 case MSG_FREE_DATACHANNELS: {
3326 sctp_data_channels_to_free_.clear();
3327 break;
3328 }
henrike@webrtc.org28e20752013-07-10 00:45:363329 default:
nisseeb4ca4e2017-01-12 10:24:273330 RTC_NOTREACHED() << "Not implemented";
henrike@webrtc.org28e20752013-07-10 00:45:363331 break;
3332 }
3333}
3334
Steve Antonafb0bb72018-02-20 19:35:373335cricket::VoiceMediaChannel* PeerConnection::voice_media_channel() const {
3336 RTC_DCHECK(!IsUnifiedPlan());
3337 auto* voice_channel = static_cast<cricket::VoiceChannel*>(
3338 GetAudioTransceiver()->internal()->channel());
3339 if (voice_channel) {
3340 return voice_channel->media_channel();
3341 } else {
3342 return nullptr;
3343 }
3344}
3345
3346cricket::VideoMediaChannel* PeerConnection::video_media_channel() const {
3347 RTC_DCHECK(!IsUnifiedPlan());
3348 auto* video_channel = static_cast<cricket::VideoChannel*>(
3349 GetVideoTransceiver()->internal()->channel());
3350 if (video_channel) {
3351 return video_channel->media_channel();
3352 } else {
3353 return nullptr;
3354 }
3355}
3356
Steve Anton4171afb2017-11-20 18:20:223357void PeerConnection::CreateAudioReceiver(
3358 MediaStreamInterface* stream,
3359 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 12:41:513360 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
3361 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Steve Antond3679212018-01-18 01:41:023362 auto* audio_receiver = new AudioRtpReceiver(
3363 worker_thread(), remote_sender_info.sender_id, streams);
Steve Anton57858b32018-02-15 23:19:503364 audio_receiver->SetVoiceMediaChannel(voice_media_channel());
Steve Antond3679212018-01-18 01:41:023365 audio_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
3366 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
3367 signaling_thread(), audio_receiver);
Steve Anton4171afb2017-11-20 18:20:223368 GetAudioTransceiver()->internal()->AddReceiver(receiver);
Henrik Boström9e6fd2b2017-11-21 12:41:513369 observer_->OnAddTrack(receiver, std::move(streams));
Harald Alvestrand8ebba742018-05-31 12:00:343370 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:363371}
3372
Steve Anton4171afb2017-11-20 18:20:223373void PeerConnection::CreateVideoReceiver(
3374 MediaStreamInterface* stream,
3375 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 12:41:513376 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
3377 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Steve Antond3679212018-01-18 01:41:023378 auto* video_receiver = new VideoRtpReceiver(
3379 worker_thread(), remote_sender_info.sender_id, streams);
Steve Anton57858b32018-02-15 23:19:503380 video_receiver->SetVideoMediaChannel(video_media_channel());
Steve Antond3679212018-01-18 01:41:023381 video_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
3382 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
3383 signaling_thread(), video_receiver);
Steve Anton4171afb2017-11-20 18:20:223384 GetVideoTransceiver()->internal()->AddReceiver(receiver);
Henrik Boström9e6fd2b2017-11-21 12:41:513385 observer_->OnAddTrack(receiver, std::move(streams));
Harald Alvestrand8ebba742018-05-31 12:00:343386 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:363387}
3388
deadbeef70ab1a12015-09-28 23:53:553389// TODO(deadbeef): Keep RtpReceivers around even if track goes away in remote
3390// description.
Henrik Boström933d8b02017-10-10 17:05:163391rtc::scoped_refptr<RtpReceiverInterface> PeerConnection::RemoveAndStopReceiver(
Steve Anton4171afb2017-11-20 18:20:223392 const RtpSenderInfo& remote_sender_info) {
3393 auto receiver = FindReceiverById(remote_sender_info.sender_id);
3394 if (!receiver) {
3395 RTC_LOG(LS_WARNING) << "RtpReceiver for track with id "
3396 << remote_sender_info.sender_id << " doesn't exist.";
Henrik Boström933d8b02017-10-10 17:05:163397 return nullptr;
deadbeef70ab1a12015-09-28 23:53:553398 }
Steve Anton4171afb2017-11-20 18:20:223399 if (receiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
3400 GetAudioTransceiver()->internal()->RemoveReceiver(receiver);
3401 } else {
3402 GetVideoTransceiver()->internal()->RemoveReceiver(receiver);
3403 }
Henrik Boström933d8b02017-10-10 17:05:163404 return receiver;
henrike@webrtc.org28e20752013-07-10 00:45:363405}
3406
korniltsev.anatolyec390b52017-07-25 00:00:253407void PeerConnection::AddAudioTrack(AudioTrackInterface* track,
3408 MediaStreamInterface* stream) {
3409 RTC_DCHECK(!IsClosed());
3410 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 18:20:223411 if (sender) {
korniltsev.anatolyec390b52017-07-25 00:00:253412 // We already have a sender for this track, so just change the stream_id
3413 // so that it's correct in the next call to CreateOffer.
Seth Hampson5b4f0752018-04-02 23:31:363414 sender->internal()->set_stream_ids({stream->id()});
korniltsev.anatolyec390b52017-07-25 00:00:253415 return;
3416 }
3417
3418 // Normal case; we've never seen this track before.
Steve Anton02ee47c2018-01-11 00:26:063419 auto new_sender =
Seth Hampson13b8bad2018-03-13 23:05:283420 CreateSender(cricket::MEDIA_TYPE_AUDIO, track, {stream->id()});
Steve Anton57858b32018-02-15 23:19:503421 new_sender->internal()->SetVoiceMediaChannel(voice_media_channel());
Steve Anton4171afb2017-11-20 18:20:223422 GetAudioTransceiver()->internal()->AddSender(new_sender);
korniltsev.anatolyec390b52017-07-25 00:00:253423 // If the sender has already been configured in SDP, we call SetSsrc,
3424 // which will connect the sender to the underlying transport. This can
3425 // occur if a local session description that contains the ID of the sender
3426 // is set before AddStream is called. It can also occur if the local
3427 // session description is not changed and RemoveStream is called, and
3428 // later AddStream is called again with the same stream.
Steve Anton4171afb2017-11-20 18:20:223429 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609eaa2018-03-27 21:57:183430 FindSenderInfo(local_audio_sender_infos_, stream->id(), track->id());
Steve Anton4171afb2017-11-20 18:20:223431 if (sender_info) {
3432 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-25 00:00:253433 }
3434}
3435
3436// TODO(deadbeef): Don't destroy RtpSenders here; they should be kept around
3437// indefinitely, when we have unified plan SDP.
3438void PeerConnection::RemoveAudioTrack(AudioTrackInterface* track,
3439 MediaStreamInterface* stream) {
3440 RTC_DCHECK(!IsClosed());
3441 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 18:20:223442 if (!sender) {
Mirko Bonadei675513b2017-11-09 10:09:253443 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
3444 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-25 00:00:253445 return;
3446 }
Steve Anton4171afb2017-11-20 18:20:223447 GetAudioTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-25 00:00:253448}
3449
3450void PeerConnection::AddVideoTrack(VideoTrackInterface* track,
3451 MediaStreamInterface* stream) {
3452 RTC_DCHECK(!IsClosed());
3453 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 18:20:223454 if (sender) {
korniltsev.anatolyec390b52017-07-25 00:00:253455 // We already have a sender for this track, so just change the stream_id
3456 // so that it's correct in the next call to CreateOffer.
Seth Hampson5b4f0752018-04-02 23:31:363457 sender->internal()->set_stream_ids({stream->id()});
korniltsev.anatolyec390b52017-07-25 00:00:253458 return;
3459 }
3460
3461 // Normal case; we've never seen this track before.
Steve Anton02ee47c2018-01-11 00:26:063462 auto new_sender =
Seth Hampson13b8bad2018-03-13 23:05:283463 CreateSender(cricket::MEDIA_TYPE_VIDEO, track, {stream->id()});
Steve Anton57858b32018-02-15 23:19:503464 new_sender->internal()->SetVideoMediaChannel(video_media_channel());
Steve Anton4171afb2017-11-20 18:20:223465 GetVideoTransceiver()->internal()->AddSender(new_sender);
3466 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609eaa2018-03-27 21:57:183467 FindSenderInfo(local_video_sender_infos_, stream->id(), track->id());
Steve Anton4171afb2017-11-20 18:20:223468 if (sender_info) {
3469 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-25 00:00:253470 }
3471}
3472
3473void PeerConnection::RemoveVideoTrack(VideoTrackInterface* track,
3474 MediaStreamInterface* stream) {
3475 RTC_DCHECK(!IsClosed());
3476 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 18:20:223477 if (!sender) {
Mirko Bonadei675513b2017-11-09 10:09:253478 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
3479 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-25 00:00:253480 return;
3481 }
Steve Anton4171afb2017-11-20 18:20:223482 GetVideoTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-25 00:00:253483}
3484
Steve Antonba818672017-11-06 18:21:573485void PeerConnection::SetIceConnectionState(IceConnectionState new_state) {
deadbeef0a6c4ca2015-10-06 18:38:283486 RTC_DCHECK(signaling_thread()->IsCurrent());
Steve Antonba818672017-11-06 18:21:573487 if (ice_connection_state_ == new_state) {
3488 return;
3489 }
3490
deadbeefcbecd352015-09-23 18:50:273491 // After transitioning to "closed", ignore any additional states from
Steve Antonba818672017-11-06 18:21:573492 // TransportController (such as "disconnected").
deadbeefab9b2d12015-10-14 18:33:113493 if (IsClosed()) {
deadbeefcbecd352015-09-23 18:50:273494 return;
3495 }
Steve Antonba818672017-11-06 18:21:573496
Mirko Bonadei675513b2017-11-09 10:09:253497 RTC_LOG(LS_INFO) << "Changing IceConnectionState " << ice_connection_state_
3498 << " => " << new_state;
Steve Antonba818672017-11-06 18:21:573499 RTC_DCHECK(ice_connection_state_ !=
3500 PeerConnectionInterface::kIceConnectionClosed);
3501
henrike@webrtc.org28e20752013-07-10 00:45:363502 ice_connection_state_ = new_state;
mallinath@webrtc.orgd3dc4242014-03-01 00:05:523503 observer_->OnIceConnectionChange(ice_connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:363504}
3505
3506void PeerConnection::OnIceGatheringChange(
3507 PeerConnectionInterface::IceGatheringState new_state) {
deadbeef0a6c4ca2015-10-06 18:38:283508 RTC_DCHECK(signaling_thread()->IsCurrent());
henrike@webrtc.org28e20752013-07-10 00:45:363509 if (IsClosed()) {
3510 return;
3511 }
3512 ice_gathering_state_ = new_state;
mallinath@webrtc.orgd3dc4242014-03-01 00:05:523513 observer_->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:363514}
3515
jbauch81bf7b02017-03-25 15:31:123516void PeerConnection::OnIceCandidate(
3517 std::unique_ptr<IceCandidateInterface> candidate) {
deadbeef0a6c4ca2015-10-06 18:38:283518 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 18:07:253519 if (IsClosed()) {
3520 return;
3521 }
Harald Alvestrand8ebba742018-05-31 12:00:343522 NoteUsageEvent(UsageEvent::CANDIDATE_COLLECTED);
jbauch81bf7b02017-03-25 15:31:123523 observer_->OnIceCandidate(candidate.get());
henrike@webrtc.org28e20752013-07-10 00:45:363524}
3525
Honghai Zhang7fb69db2016-03-14 18:59:183526void PeerConnection::OnIceCandidatesRemoved(
3527 const std::vector<cricket::Candidate>& candidates) {
3528 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 18:07:253529 if (IsClosed()) {
3530 return;
3531 }
Honghai Zhang7fb69db2016-03-14 18:59:183532 observer_->OnIceCandidatesRemoved(candidates);
3533}
3534
henrike@webrtc.org28e20752013-07-10 00:45:363535void PeerConnection::ChangeSignalingState(
3536 PeerConnectionInterface::SignalingState signaling_state) {
Steve Antonba818672017-11-06 18:21:573537 RTC_DCHECK(signaling_thread()->IsCurrent());
3538 if (signaling_state_ == signaling_state) {
3539 return;
3540 }
Mirko Bonadei675513b2017-11-09 10:09:253541 RTC_LOG(LS_INFO) << "Session: " << session_id() << " Old state: "
3542 << GetSignalingStateString(signaling_state_)
3543 << " New state: "
3544 << GetSignalingStateString(signaling_state);
henrike@webrtc.org28e20752013-07-10 00:45:363545 signaling_state_ = signaling_state;
3546 if (signaling_state == kClosed) {
3547 ice_connection_state_ = kIceConnectionClosed;
3548 observer_->OnIceConnectionChange(ice_connection_state_);
3549 if (ice_gathering_state_ != kIceGatheringComplete) {
3550 ice_gathering_state_ = kIceGatheringComplete;
3551 observer_->OnIceGatheringChange(ice_gathering_state_);
3552 }
3553 }
3554 observer_->OnSignalingChange(signaling_state_);
henrike@webrtc.org28e20752013-07-10 00:45:363555}
3556
deadbeefeb459812015-12-16 03:24:433557void PeerConnection::OnAudioTrackAdded(AudioTrackInterface* track,
3558 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 18:07:253559 if (IsClosed()) {
3560 return;
3561 }
korniltsev.anatolyec390b52017-07-25 00:00:253562 AddAudioTrack(track, stream);
3563 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-16 03:24:433564}
3565
deadbeefeb459812015-12-16 03:24:433566void PeerConnection::OnAudioTrackRemoved(AudioTrackInterface* track,
3567 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 18:07:253568 if (IsClosed()) {
3569 return;
3570 }
korniltsev.anatolyec390b52017-07-25 00:00:253571 RemoveAudioTrack(track, stream);
3572 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-16 03:24:433573}
3574
3575void PeerConnection::OnVideoTrackAdded(VideoTrackInterface* track,
3576 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 18:07:253577 if (IsClosed()) {
3578 return;
3579 }
korniltsev.anatolyec390b52017-07-25 00:00:253580 AddVideoTrack(track, stream);
3581 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-16 03:24:433582}
3583
3584void PeerConnection::OnVideoTrackRemoved(VideoTrackInterface* track,
3585 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 18:07:253586 if (IsClosed()) {
3587 return;
3588 }
korniltsev.anatolyec390b52017-07-25 00:00:253589 RemoveVideoTrack(track, stream);
3590 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-16 03:24:433591}
3592
Henrik Boström31638672017-11-23 16:48:323593void PeerConnection::PostSetSessionDescriptionSuccess(
3594 SetSessionDescriptionObserver* observer) {
3595 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
3596 signaling_thread()->Post(RTC_FROM_HERE, this,
3597 MSG_SET_SESSIONDESCRIPTION_SUCCESS, msg);
3598}
3599
deadbeefab9b2d12015-10-14 18:33:113600void PeerConnection::PostSetSessionDescriptionFailure(
3601 SetSessionDescriptionObserver* observer,
Harald Alvestrand5081c0c2018-03-09 14:18:033602 RTCError&& error) {
3603 RTC_DCHECK(!error.ok());
deadbeefab9b2d12015-10-14 18:33:113604 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
Harald Alvestrand5081c0c2018-03-09 14:18:033605 msg->error = std::move(error);
Taylor Brandstetter5d97a9a2016-06-10 21:17:273606 signaling_thread()->Post(RTC_FROM_HERE, this,
3607 MSG_SET_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 18:33:113608}
3609
3610void PeerConnection::PostCreateSessionDescriptionFailure(
3611 CreateSessionDescriptionObserver* observer,
Harald Alvestrand5081c0c2018-03-09 14:18:033612 RTCError error) {
3613 RTC_DCHECK(!error.ok());
deadbeefab9b2d12015-10-14 18:33:113614 CreateSessionDescriptionMsg* msg = new CreateSessionDescriptionMsg(observer);
Harald Alvestrand5081c0c2018-03-09 14:18:033615 msg->error = std::move(error);
Taylor Brandstetter5d97a9a2016-06-10 21:17:273616 signaling_thread()->Post(RTC_FROM_HERE, this,
3617 MSG_CREATE_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 18:33:113618}
3619
zhihuang1c378ed2017-08-17 21:10:503620void PeerConnection::GetOptionsForOffer(
Steve Antondcc3c022017-12-23 00:02:543621 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
deadbeefab9b2d12015-10-14 18:33:113622 cricket::MediaSessionOptions* session_options) {
Steve Antondcc3c022017-12-23 00:02:543623 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
zhihuang1c378ed2017-08-17 21:10:503624
Steve Antondcc3c022017-12-23 00:02:543625 if (IsUnifiedPlan()) {
3626 GetOptionsForUnifiedPlanOffer(offer_answer_options, session_options);
3627 } else {
3628 GetOptionsForPlanBOffer(offer_answer_options, session_options);
3629 }
3630
Steve Antonfa2260d2017-12-29 00:38:233631 // Intentionally unset the data channel type for RTP data channel with the
3632 // second condition. Otherwise the RTP data channels would be successfully
3633 // negotiated by default and the unit tests in WebRtcDataBrowserTest will fail
3634 // when building with chromium. We want to leave RTP data channels broken, so
3635 // people won't try to use them.
3636 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
3637 session_options->data_channel_type = data_channel_type();
3638 }
3639
Steve Antondcc3c022017-12-23 00:02:543640 // Apply ICE restart flag and renomination flag.
3641 for (auto& options : session_options->media_description_options) {
3642 options.transport_options.ice_restart = offer_answer_options.ice_restart;
3643 options.transport_options.enable_ice_renomination =
3644 configuration_.enable_ice_renomination;
3645 }
3646
3647 session_options->rtcp_cname = rtcp_cname_;
3648 session_options->crypto_options = factory_->options().crypto_options;
Steve Antone831b8c2018-02-01 20:22:163649 session_options->is_unified_plan = IsUnifiedPlan();
Steve Antondcc3c022017-12-23 00:02:543650}
3651
3652void PeerConnection::GetOptionsForPlanBOffer(
3653 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
3654 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 21:10:503655 // Figure out transceiver directional preferences.
3656 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
3657 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
3658
3659 // By default, generate sendrecv/recvonly m= sections.
3660 bool recv_audio = true;
3661 bool recv_video = true;
3662
3663 // By default, only offer a new m= section if we have media to send with it.
3664 bool offer_new_audio_description = send_audio;
3665 bool offer_new_video_description = send_video;
3666 bool offer_new_data_description = HasDataChannels();
3667
3668 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-23 00:02:543669 if (offer_answer_options.offer_to_receive_audio !=
3670 RTCOfferAnswerOptions::kUndefined) {
3671 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 21:10:503672 offer_new_audio_description =
Steve Antondcc3c022017-12-23 00:02:543673 offer_new_audio_description ||
3674 (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 21:10:503675 }
Steve Antondcc3c022017-12-23 00:02:543676 if (offer_answer_options.offer_to_receive_video !=
3677 RTCOfferAnswerOptions::kUndefined) {
3678 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 21:10:503679 offer_new_video_description =
Steve Antondcc3c022017-12-23 00:02:543680 offer_new_video_description ||
3681 (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 21:10:503682 }
3683
3684 rtc::Optional<size_t> audio_index;
3685 rtc::Optional<size_t> video_index;
3686 rtc::Optional<size_t> data_index;
3687 // If a current description exists, generate m= sections in the same order,
3688 // using the first audio/video/data section that appears and rejecting
3689 // extraneous ones.
Steve Anton75737c02017-11-06 18:37:173690 if (local_description()) {
zhihuang1c378ed2017-08-17 21:10:503691 GenerateMediaDescriptionOptions(
Steve Anton75737c02017-11-06 18:37:173692 local_description(),
Steve Anton1d03a752017-11-27 22:30:093693 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
3694 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
3695 &audio_index, &video_index, &data_index, session_options);
deadbeefab9b2d12015-10-14 18:33:113696 }
3697
zhihuang1c378ed2017-08-17 21:10:503698 // Add audio/video/data m= sections to the end if needed.
3699 if (!audio_index && offer_new_audio_description) {
3700 session_options->media_description_options.push_back(
3701 cricket::MediaDescriptionOptions(
3702 cricket::MEDIA_TYPE_AUDIO, cricket::CN_AUDIO,
Steve Anton1d03a752017-11-27 22:30:093703 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
3704 false));
Oskar Sundbom9b28a032017-11-16 09:53:303705 audio_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 20:14:453706 }
zhihuang1c378ed2017-08-17 21:10:503707 if (!video_index && offer_new_video_description) {
3708 session_options->media_description_options.push_back(
3709 cricket::MediaDescriptionOptions(
3710 cricket::MEDIA_TYPE_VIDEO, cricket::CN_VIDEO,
Steve Anton1d03a752017-11-27 22:30:093711 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
3712 false));
Oskar Sundbom9b28a032017-11-16 09:53:303713 video_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 20:14:453714 }
zhihuang1c378ed2017-08-17 21:10:503715 if (!data_index && offer_new_data_description) {
3716 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-29 00:38:233717 GetMediaDescriptionOptionsForActiveData(cricket::CN_DATA));
Oskar Sundbom9b28a032017-11-16 09:53:303718 data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 21:10:503719 }
3720
3721 cricket::MediaDescriptionOptions* audio_media_description_options =
3722 !audio_index ? nullptr
3723 : &session_options->media_description_options[*audio_index];
3724 cricket::MediaDescriptionOptions* video_media_description_options =
3725 !video_index ? nullptr
3726 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 21:10:503727
Steve Anton4171afb2017-11-20 18:20:223728 AddRtpSenderOptions(GetSendersInternal(), audio_media_description_options,
zhihuang1c378ed2017-08-17 21:10:503729 video_media_description_options);
Steve Antondcc3c022017-12-23 00:02:543730}
3731
3732// Find a new MID that is not already in |used_mids|, then add it to |used_mids|
3733// and return a reference to it.
3734// Generated MIDs should be no more than 3 bytes long to take up less space in
3735// the RTP packet.
3736static const std::string& AllocateMid(std::set<std::string>* used_mids) {
3737 RTC_DCHECK(used_mids);
3738 // We're boring: just generate MIDs 0, 1, 2, ...
3739 size_t i = 0;
3740 std::set<std::string>::iterator it;
3741 bool inserted;
3742 do {
3743 std::string mid = rtc::ToString(i++);
3744 auto insert_result = used_mids->insert(mid);
3745 it = insert_result.first;
3746 inserted = insert_result.second;
3747 } while (!inserted);
3748 return *it;
3749}
3750
3751static cricket::MediaDescriptionOptions
3752GetMediaDescriptionOptionsForTransceiver(
3753 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3754 transceiver,
3755 const std::string& mid) {
3756 cricket::MediaDescriptionOptions media_description_options(
Steve Anton69470252018-02-09 19:43:083757 transceiver->media_type(), mid, transceiver->direction(),
Steve Antondcc3c022017-12-23 00:02:543758 transceiver->stopped());
Steve Anton5f94aa22018-02-01 18:58:303759 // This behavior is specified in JSEP. The gist is that:
3760 // 1. The MSID is included if the RtpTransceiver's direction is sendonly or
3761 // sendrecv.
3762 // 2. If the MSID is included, then it must be included in any subsequent
3763 // offer/answer exactly the same until the RtpTransceiver is stopped.
3764 if (!transceiver->stopped() &&
3765 (RtpTransceiverDirectionHasSend(transceiver->direction()) ||
3766 transceiver->internal()->has_ever_been_used_to_send())) {
3767 cricket::SenderOptions sender_options;
3768 sender_options.track_id = transceiver->sender()->id();
3769 sender_options.stream_ids = transceiver->sender()->stream_ids();
3770 // TODO(bugs.webrtc.org/7600): Set num_sim_layers to the number of encodings
3771 // set in the RTP parameters when the transceiver was added.
3772 sender_options.num_sim_layers = 1;
3773 media_description_options.sender_options.push_back(sender_options);
3774 }
Steve Antondcc3c022017-12-23 00:02:543775 return media_description_options;
3776}
3777
3778void PeerConnection::GetOptionsForUnifiedPlanOffer(
3779 const RTCOfferAnswerOptions& offer_answer_options,
3780 cricket::MediaSessionOptions* session_options) {
3781 // Rules for generating an offer are dictated by JSEP sections 5.2.1 (Initial
3782 // Offers) and 5.2.2 (Subsequent Offers).
3783 RTC_DCHECK_EQ(session_options->media_description_options.size(), 0);
3784 const ContentInfos& local_contents =
3785 (local_description() ? local_description()->description()->contents()
3786 : ContentInfos());
3787 const ContentInfos& remote_contents =
3788 (remote_description() ? remote_description()->description()->contents()
3789 : ContentInfos());
3790 // The mline indices that can be recycled. New transceivers should reuse these
3791 // slots first.
3792 std::queue<size_t> recycleable_mline_indices;
3793 // Track the MIDs used in previous offer/answer exchanges and the current
3794 // offer so that new, unique MIDs are generated.
3795 std::set<std::string> used_mids = seen_mids_;
3796 // First, go through each media section that exists in either the local or
3797 // remote description and generate a media section in this offer for the
3798 // associated transceiver. If a media section can be recycled, generate a
3799 // default, rejected media section here that can be later overwritten.
3800 for (size_t i = 0;
3801 i < std::max(local_contents.size(), remote_contents.size()); ++i) {
3802 // Either |local_content| or |remote_content| is non-null.
3803 const ContentInfo* local_content =
3804 (i < local_contents.size() ? &local_contents[i] : nullptr);
3805 const ContentInfo* remote_content =
3806 (i < remote_contents.size() ? &remote_contents[i] : nullptr);
3807 bool had_been_rejected = (local_content && local_content->rejected) ||
3808 (remote_content && remote_content->rejected);
3809 const std::string& mid =
3810 (local_content ? local_content->name : remote_content->name);
3811 cricket::MediaType media_type =
3812 (local_content ? local_content->media_description()->type()
3813 : remote_content->media_description()->type());
3814 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
3815 media_type == cricket::MEDIA_TYPE_VIDEO) {
3816 auto transceiver = GetAssociatedTransceiver(mid);
3817 RTC_CHECK(transceiver);
3818 // A media section is considered eligible for recycling if it is marked as
3819 // rejected in either the local or remote description.
Seth Hampsonae8a90a2018-02-13 23:33:483820 if (had_been_rejected && transceiver->stopped()) {
Steve Antondcc3c022017-12-23 00:02:543821 session_options->media_description_options.push_back(
Steve Anton69470252018-02-09 19:43:083822 cricket::MediaDescriptionOptions(transceiver->media_type(), mid,
3823 RtpTransceiverDirection::kInactive,
3824 /*stopped=*/true));
Steve Antondcc3c022017-12-23 00:02:543825 recycleable_mline_indices.push(i);
3826 } else {
3827 session_options->media_description_options.push_back(
3828 GetMediaDescriptionOptionsForTransceiver(transceiver, mid));
3829 // CreateOffer shouldn't really cause any state changes in
3830 // PeerConnection, but we need a way to match new transceivers to new
3831 // media sections in SetLocalDescription and JSEP specifies this is done
3832 // by recording the index of the media section generated for the
3833 // transceiver in the offer.
3834 transceiver->internal()->set_mline_index(i);
3835 }
3836 } else {
3837 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antonfa2260d2017-12-29 00:38:233838 RTC_CHECK(GetDataMid());
3839 if (had_been_rejected || mid != *GetDataMid()) {
3840 session_options->media_description_options.push_back(
3841 GetMediaDescriptionOptionsForRejectedData(mid));
3842 } else {
3843 session_options->media_description_options.push_back(
3844 GetMediaDescriptionOptionsForActiveData(mid));
3845 }
Steve Antondcc3c022017-12-23 00:02:543846 }
3847 }
3848 // Next, look for transceivers that are newly added (that is, are not stopped
3849 // and not associated). Reuse media sections marked as recyclable first,
3850 // otherwise append to the end of the offer. New media sections should be
3851 // added in the order they were added to the PeerConnection.
3852 for (auto transceiver : transceivers_) {
3853 if (transceiver->mid() || transceiver->stopped()) {
3854 continue;
3855 }
3856 size_t mline_index;
3857 if (!recycleable_mline_indices.empty()) {
3858 mline_index = recycleable_mline_indices.front();
3859 recycleable_mline_indices.pop();
3860 session_options->media_description_options[mline_index] =
3861 GetMediaDescriptionOptionsForTransceiver(transceiver,
3862 AllocateMid(&used_mids));
3863 } else {
3864 mline_index = session_options->media_description_options.size();
3865 session_options->media_description_options.push_back(
3866 GetMediaDescriptionOptionsForTransceiver(transceiver,
3867 AllocateMid(&used_mids)));
3868 }
3869 // See comment above for why CreateOffer changes the transceiver's state.
3870 transceiver->internal()->set_mline_index(mline_index);
3871 }
Steve Antonfa2260d2017-12-29 00:38:233872 // Lastly, add a m-section if we have local data channels and an m section
3873 // does not already exist.
3874 if (!GetDataMid() && HasDataChannels()) {
3875 session_options->media_description_options.push_back(
3876 GetMediaDescriptionOptionsForActiveData(AllocateMid(&used_mids)));
3877 }
Steve Antondcc3c022017-12-23 00:02:543878}
3879
3880void PeerConnection::GetOptionsForAnswer(
3881 const RTCOfferAnswerOptions& offer_answer_options,
3882 cricket::MediaSessionOptions* session_options) {
3883 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
3884
3885 if (IsUnifiedPlan()) {
3886 GetOptionsForUnifiedPlanAnswer(offer_answer_options, session_options);
3887 } else {
3888 GetOptionsForPlanBAnswer(offer_answer_options, session_options);
3889 }
3890
Steve Antonfa2260d2017-12-29 00:38:233891 // Intentionally unset the data channel type for RTP data channel. Otherwise
3892 // the RTP data channels would be successfully negotiated by default and the
3893 // unit tests in WebRtcDataBrowserTest will fail when building with chromium.
3894 // We want to leave RTP data channels broken, so people won't try to use them.
3895 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
3896 session_options->data_channel_type = data_channel_type();
3897 }
3898
Steve Antondcc3c022017-12-23 00:02:543899 // Apply ICE renomination flag.
3900 for (auto& options : session_options->media_description_options) {
3901 options.transport_options.enable_ice_renomination =
3902 configuration_.enable_ice_renomination;
3903 }
zhihuang8f65cdf2016-05-07 01:40:303904
3905 session_options->rtcp_cname = rtcp_cname_;
jbauchcb560652016-08-04 12:20:323906 session_options->crypto_options = factory_->options().crypto_options;
Steve Antone831b8c2018-02-01 20:22:163907 session_options->is_unified_plan = IsUnifiedPlan();
deadbeefab9b2d12015-10-14 18:33:113908}
3909
Steve Antondcc3c022017-12-23 00:02:543910void PeerConnection::GetOptionsForPlanBAnswer(
3911 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
Honghai Zhang4cedf2b2016-08-31 15:18:113912 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 21:10:503913 // Figure out transceiver directional preferences.
3914 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
3915 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
3916
3917 // By default, generate sendrecv/recvonly m= sections. The direction is also
3918 // restricted by the direction in the offer.
3919 bool recv_audio = true;
3920 bool recv_video = true;
3921
3922 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-23 00:02:543923 if (offer_answer_options.offer_to_receive_audio !=
3924 RTCOfferAnswerOptions::kUndefined) {
3925 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
deadbeef0ed85b22016-02-24 01:24:523926 }
Steve Antondcc3c022017-12-23 00:02:543927 if (offer_answer_options.offer_to_receive_video !=
3928 RTCOfferAnswerOptions::kUndefined) {
3929 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 21:10:503930 }
3931
3932 rtc::Optional<size_t> audio_index;
3933 rtc::Optional<size_t> video_index;
3934 rtc::Optional<size_t> data_index;
Steve Antondffead82018-02-06 18:31:293935
3936 // Generate m= sections that match those in the offer.
3937 // Note that mediasession.cc will handle intersection our preferred
3938 // direction with the offered direction.
3939 GenerateMediaDescriptionOptions(
3940 remote_description(),
3941 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
3942 RtpTransceiverDirectionFromSendRecv(send_video, recv_video), &audio_index,
3943 &video_index, &data_index, session_options);
zhihuang1c378ed2017-08-17 21:10:503944
3945 cricket::MediaDescriptionOptions* audio_media_description_options =
3946 !audio_index ? nullptr
3947 : &session_options->media_description_options[*audio_index];
3948 cricket::MediaDescriptionOptions* video_media_description_options =
3949 !video_index ? nullptr
3950 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 21:10:503951
Steve Anton4171afb2017-11-20 18:20:223952 AddRtpSenderOptions(GetSendersInternal(), audio_media_description_options,
zhihuang1c378ed2017-08-17 21:10:503953 video_media_description_options);
Steve Antondcc3c022017-12-23 00:02:543954}
zhihuangaf388472016-11-02 23:49:483955
Steve Antondcc3c022017-12-23 00:02:543956void PeerConnection::GetOptionsForUnifiedPlanAnswer(
3957 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
3958 cricket::MediaSessionOptions* session_options) {
3959 // Rules for generating an answer are dictated by JSEP sections 5.3.1 (Initial
3960 // Answers) and 5.3.2 (Subsequent Answers).
3961 RTC_DCHECK(remote_description());
3962 RTC_DCHECK(remote_description()->GetType() == SdpType::kOffer);
3963 for (const ContentInfo& content :
3964 remote_description()->description()->contents()) {
3965 cricket::MediaType media_type = content.media_description()->type();
3966 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
3967 media_type == cricket::MEDIA_TYPE_VIDEO) {
3968 auto transceiver = GetAssociatedTransceiver(content.name);
3969 RTC_CHECK(transceiver);
3970 session_options->media_description_options.push_back(
3971 GetMediaDescriptionOptionsForTransceiver(transceiver, content.name));
3972 } else {
3973 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antondbf9d032018-01-19 23:23:403974 // Reject all data sections if data channels are disabled.
3975 // Reject a data section if it has already been rejected.
3976 // Reject all data sections except for the first one.
3977 if (data_channel_type_ == cricket::DCT_NONE || content.rejected ||
3978 content.name != *GetDataMid()) {
Steve Antonfa2260d2017-12-29 00:38:233979 session_options->media_description_options.push_back(
3980 GetMediaDescriptionOptionsForRejectedData(content.name));
3981 } else {
3982 session_options->media_description_options.push_back(
3983 GetMediaDescriptionOptionsForActiveData(content.name));
3984 }
Steve Antondcc3c022017-12-23 00:02:543985 }
3986 }
htaa2a49d92016-03-04 10:51:393987}
3988
zhihuang1c378ed2017-08-17 21:10:503989void PeerConnection::GenerateMediaDescriptionOptions(
3990 const SessionDescriptionInterface* session_desc,
Steve Anton1d03a752017-11-27 22:30:093991 RtpTransceiverDirection audio_direction,
3992 RtpTransceiverDirection video_direction,
zhihuang1c378ed2017-08-17 21:10:503993 rtc::Optional<size_t>* audio_index,
3994 rtc::Optional<size_t>* video_index,
3995 rtc::Optional<size_t>* data_index,
htaa2a49d92016-03-04 10:51:393996 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 21:10:503997 for (const cricket::ContentInfo& content :
3998 session_desc->description()->contents()) {
3999 if (IsAudioContent(&content)) {
4000 // If we already have an audio m= section, reject this extra one.
4001 if (*audio_index) {
4002 session_options->media_description_options.push_back(
4003 cricket::MediaDescriptionOptions(
4004 cricket::MEDIA_TYPE_AUDIO, content.name,
Steve Anton1d03a752017-11-27 22:30:094005 RtpTransceiverDirection::kInactive, true));
zhihuang1c378ed2017-08-17 21:10:504006 } else {
4007 session_options->media_description_options.push_back(
4008 cricket::MediaDescriptionOptions(
4009 cricket::MEDIA_TYPE_AUDIO, content.name, audio_direction,
Steve Anton1d03a752017-11-27 22:30:094010 audio_direction == RtpTransceiverDirection::kInactive));
Oskar Sundbom9b28a032017-11-16 09:53:304011 *audio_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 21:10:504012 }
4013 } else if (IsVideoContent(&content)) {
4014 // If we already have an video m= section, reject this extra one.
4015 if (*video_index) {
4016 session_options->media_description_options.push_back(
4017 cricket::MediaDescriptionOptions(
4018 cricket::MEDIA_TYPE_VIDEO, content.name,
Steve Anton1d03a752017-11-27 22:30:094019 RtpTransceiverDirection::kInactive, true));
zhihuang1c378ed2017-08-17 21:10:504020 } else {
4021 session_options->media_description_options.push_back(
4022 cricket::MediaDescriptionOptions(
4023 cricket::MEDIA_TYPE_VIDEO, content.name, video_direction,
Steve Anton1d03a752017-11-27 22:30:094024 video_direction == RtpTransceiverDirection::kInactive));
Oskar Sundbom9b28a032017-11-16 09:53:304025 *video_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 21:10:504026 }
4027 } else {
4028 RTC_DCHECK(IsDataContent(&content));
4029 // If we already have an data m= section, reject this extra one.
4030 if (*data_index) {
4031 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-29 00:38:234032 GetMediaDescriptionOptionsForRejectedData(content.name));
zhihuang1c378ed2017-08-17 21:10:504033 } else {
4034 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-29 00:38:234035 GetMediaDescriptionOptionsForActiveData(content.name));
Oskar Sundbom9b28a032017-11-16 09:53:304036 *data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 21:10:504037 }
4038 }
htaa2a49d92016-03-04 10:51:394039 }
deadbeefab9b2d12015-10-14 18:33:114040}
4041
Steve Antonfa2260d2017-12-29 00:38:234042cricket::MediaDescriptionOptions
4043PeerConnection::GetMediaDescriptionOptionsForActiveData(
4044 const std::string& mid) const {
4045 // Direction for data sections is meaningless, but legacy endpoints might
4046 // expect sendrecv.
4047 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
4048 RtpTransceiverDirection::kSendRecv,
4049 /*stopped=*/false);
4050 AddRtpDataChannelOptions(rtp_data_channels_, &options);
4051 return options;
4052}
4053
4054cricket::MediaDescriptionOptions
4055PeerConnection::GetMediaDescriptionOptionsForRejectedData(
4056 const std::string& mid) const {
4057 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
4058 RtpTransceiverDirection::kInactive,
4059 /*stopped=*/true);
4060 AddRtpDataChannelOptions(rtp_data_channels_, &options);
4061 return options;
4062}
4063
4064rtc::Optional<std::string> PeerConnection::GetDataMid() const {
4065 switch (data_channel_type_) {
4066 case cricket::DCT_RTP:
4067 if (!rtp_data_channel_) {
4068 return rtc::nullopt;
4069 }
4070 return rtp_data_channel_->content_name();
4071 case cricket::DCT_SCTP:
Zhi Huange830e682018-03-30 17:48:354072 return sctp_mid_;
Steve Antonfa2260d2017-12-29 00:38:234073 default:
4074 return rtc::nullopt;
4075 }
4076}
4077
Steve Anton4171afb2017-11-20 18:20:224078void PeerConnection::RemoveSenders(cricket::MediaType media_type) {
4079 UpdateLocalSenders(std::vector<cricket::StreamParams>(), media_type);
4080 UpdateRemoteSendersList(std::vector<cricket::StreamParams>(), false,
deadbeefbda7e0b2015-12-09 01:13:404081 media_type, nullptr);
deadbeeffaac4972015-11-12 23:33:074082}
4083
Steve Anton4171afb2017-11-20 18:20:224084void PeerConnection::UpdateRemoteSendersList(
deadbeefab9b2d12015-10-14 18:33:114085 const cricket::StreamParamsVec& streams,
Steve Anton4171afb2017-11-20 18:20:224086 bool default_sender_needed,
deadbeefab9b2d12015-10-14 18:33:114087 cricket::MediaType media_type,
4088 StreamCollection* new_streams) {
Seth Hampson5b4f0752018-04-02 23:31:364089 RTC_DCHECK(!IsUnifiedPlan());
4090
Steve Anton4171afb2017-11-20 18:20:224091 std::vector<RtpSenderInfo>* current_senders =
4092 GetRemoteSenderInfos(media_type);
deadbeefab9b2d12015-10-14 18:33:114093
Steve Anton4171afb2017-11-20 18:20:224094 // Find removed senders. I.e., senders where the sender id or ssrc don't match
deadbeeffac06552015-11-25 19:26:014095 // the new StreamParam.
Steve Anton4171afb2017-11-20 18:20:224096 for (auto sender_it = current_senders->begin();
4097 sender_it != current_senders->end();
4098 /* incremented manually */) {
4099 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 18:33:114100 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 18:20:224101 cricket::GetStreamBySsrc(streams, info.first_ssrc);
Seth Hampson83d676b2018-04-06 01:12:094102 std::string params_stream_id;
4103 if (params) {
4104 params_stream_id =
4105 (!params->first_stream_id().empty() ? params->first_stream_id()
4106 : kDefaultStreamId);
4107 }
Seth Hampson5b4f0752018-04-02 23:31:364108 bool sender_exists = params && params->id == info.sender_id &&
Seth Hampson83d676b2018-04-06 01:12:094109 params_stream_id == info.stream_id;
deadbeefbda7e0b2015-12-09 01:13:404110 // If this is a default track, and we still need it, don't remove it.
Seth Hampson845e8782018-03-02 19:34:104111 if ((info.stream_id == kDefaultStreamId && default_sender_needed) ||
Steve Anton4171afb2017-11-20 18:20:224112 sender_exists) {
4113 ++sender_it;
deadbeefbda7e0b2015-12-09 01:13:404114 } else {
Steve Anton4171afb2017-11-20 18:20:224115 OnRemoteSenderRemoved(info, media_type);
4116 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 18:33:114117 }
4118 }
4119
Steve Anton4171afb2017-11-20 18:20:224120 // Find new and active senders.
deadbeefab9b2d12015-10-14 18:33:114121 for (const cricket::StreamParams& params : streams) {
Seth Hampson5897a6e2018-04-03 18:16:334122 if (!params.has_ssrcs()) {
4123 // The remote endpoint has streams, but didn't signal ssrcs. For an active
4124 // sender, this means it is coming from a Unified Plan endpoint,so we just
4125 // create a default.
4126 default_sender_needed = true;
4127 break;
4128 }
4129
Seth Hampson845e8782018-03-02 19:34:104130 // |params.id| is the sender id and the stream id uses the first of
Seth Hampson5b4f0752018-04-02 23:31:364131 // |params.stream_ids|. The remote description could come from a Unified
Seth Hampson5897a6e2018-04-03 18:16:334132 // Plan endpoint, with multiple or no stream_ids() signaled. Since this is
4133 // not supported in Plan B, we just take the first here and create the
4134 // default stream ID if none is specified.
Seth Hampson845e8782018-03-02 19:34:104135 const std::string& stream_id =
Seth Hampson83d676b2018-04-06 01:12:094136 (!params.first_stream_id().empty() ? params.first_stream_id()
4137 : kDefaultStreamId);
Steve Anton4171afb2017-11-20 18:20:224138 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 18:33:114139 uint32_t ssrc = params.first_ssrc();
4140
4141 rtc::scoped_refptr<MediaStreamInterface> stream =
Seth Hampson845e8782018-03-02 19:34:104142 remote_streams_->find(stream_id);
deadbeefab9b2d12015-10-14 18:33:114143 if (!stream) {
4144 // This is a new MediaStream. Create a new remote MediaStream.
perkjd61bf802016-03-24 10:16:194145 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
Seth Hampson845e8782018-03-02 19:34:104146 MediaStream::Create(stream_id));
deadbeefab9b2d12015-10-14 18:33:114147 remote_streams_->AddStream(stream);
4148 new_streams->AddStream(stream);
4149 }
4150
Steve Anton4171afb2017-11-20 18:20:224151 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609eaa2018-03-27 21:57:184152 FindSenderInfo(*current_senders, stream_id, sender_id);
Steve Anton4171afb2017-11-20 18:20:224153 if (!sender_info) {
Seth Hampson845e8782018-03-02 19:34:104154 current_senders->push_back(RtpSenderInfo(stream_id, sender_id, ssrc));
Steve Anton4171afb2017-11-20 18:20:224155 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 18:33:114156 }
4157 }
deadbeefbda7e0b2015-12-09 01:13:404158
Steve Anton4171afb2017-11-20 18:20:224159 // Add default sender if necessary.
4160 if (default_sender_needed) {
deadbeefbda7e0b2015-12-09 01:13:404161 rtc::scoped_refptr<MediaStreamInterface> default_stream =
Seth Hampson845e8782018-03-02 19:34:104162 remote_streams_->find(kDefaultStreamId);
deadbeefbda7e0b2015-12-09 01:13:404163 if (!default_stream) {
4164 // Create the new default MediaStream.
perkjd61bf802016-03-24 10:16:194165 default_stream = MediaStreamProxy::Create(
Seth Hampson845e8782018-03-02 19:34:104166 rtc::Thread::Current(), MediaStream::Create(kDefaultStreamId));
deadbeefbda7e0b2015-12-09 01:13:404167 remote_streams_->AddStream(default_stream);
4168 new_streams->AddStream(default_stream);
4169 }
Steve Anton4171afb2017-11-20 18:20:224170 std::string default_sender_id = (media_type == cricket::MEDIA_TYPE_AUDIO)
4171 ? kDefaultAudioSenderId
4172 : kDefaultVideoSenderId;
Seth Hampson845e8782018-03-02 19:34:104173 const RtpSenderInfo* default_sender_info =
Emircan Uysalerbc609eaa2018-03-27 21:57:184174 FindSenderInfo(*current_senders, kDefaultStreamId, default_sender_id);
Steve Anton4171afb2017-11-20 18:20:224175 if (!default_sender_info) {
4176 current_senders->push_back(
Seth Hampson845e8782018-03-02 19:34:104177 RtpSenderInfo(kDefaultStreamId, default_sender_id, 0));
Steve Anton4171afb2017-11-20 18:20:224178 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefbda7e0b2015-12-09 01:13:404179 }
4180 }
deadbeefab9b2d12015-10-14 18:33:114181}
4182
Steve Anton4171afb2017-11-20 18:20:224183void PeerConnection::OnRemoteSenderAdded(const RtpSenderInfo& sender_info,
4184 cricket::MediaType media_type) {
Steve Anton3d954a62018-04-02 18:27:234185 RTC_LOG(LS_INFO) << "Creating " << cricket::MediaTypeToString(media_type)
4186 << " receiver for track_id=" << sender_info.sender_id
4187 << " and stream_id=" << sender_info.stream_id;
deadbeefab9b2d12015-10-14 18:33:114188
Steve Anton3d954a62018-04-02 18:27:234189 MediaStreamInterface* stream = remote_streams_->find(sender_info.stream_id);
deadbeefab9b2d12015-10-14 18:33:114190 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 18:20:224191 CreateAudioReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 18:33:114192 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 18:20:224193 CreateVideoReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 18:33:114194 } else {
nisseeb4ca4e2017-01-12 10:24:274195 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 18:33:114196 }
4197}
4198
Steve Anton4171afb2017-11-20 18:20:224199void PeerConnection::OnRemoteSenderRemoved(const RtpSenderInfo& sender_info,
4200 cricket::MediaType media_type) {
Seth Hampson83d676b2018-04-06 01:12:094201 RTC_LOG(LS_INFO) << "Removing " << cricket::MediaTypeToString(media_type)
4202 << " receiver for track_id=" << sender_info.sender_id
4203 << " and stream_id=" << sender_info.stream_id;
4204
Seth Hampson845e8782018-03-02 19:34:104205 MediaStreamInterface* stream = remote_streams_->find(sender_info.stream_id);
deadbeefab9b2d12015-10-14 18:33:114206
Henrik Boström933d8b02017-10-10 17:05:164207 rtc::scoped_refptr<RtpReceiverInterface> receiver;
deadbeefab9b2d12015-10-14 18:33:114208 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
perkjd61bf802016-03-24 10:16:194209 // When the MediaEngine audio channel is destroyed, the RemoteAudioSource
4210 // will be notified which will end the AudioRtpReceiver::track().
Steve Anton4171afb2017-11-20 18:20:224211 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 18:33:114212 rtc::scoped_refptr<AudioTrackInterface> audio_track =
Steve Anton4171afb2017-11-20 18:20:224213 stream->FindAudioTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 18:33:114214 if (audio_track) {
deadbeefab9b2d12015-10-14 18:33:114215 stream->RemoveTrack(audio_track);
deadbeefab9b2d12015-10-14 18:33:114216 }
4217 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
perkjd61bf802016-03-24 10:16:194218 // Stopping or destroying a VideoRtpReceiver will end the
4219 // VideoRtpReceiver::track().
Steve Anton4171afb2017-11-20 18:20:224220 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 18:33:114221 rtc::scoped_refptr<VideoTrackInterface> video_track =
Steve Anton4171afb2017-11-20 18:20:224222 stream->FindVideoTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 18:33:114223 if (video_track) {
perkjd61bf802016-03-24 10:16:194224 // There's no guarantee the track is still available, e.g. the track may
4225 // have been removed from the stream by an application.
deadbeefab9b2d12015-10-14 18:33:114226 stream->RemoveTrack(video_track);
deadbeefab9b2d12015-10-14 18:33:114227 }
4228 } else {
nisseede5da42017-01-12 13:15:364229 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 18:33:114230 }
Henrik Boström933d8b02017-10-10 17:05:164231 if (receiver) {
4232 observer_->OnRemoveTrack(receiver);
4233 }
deadbeefab9b2d12015-10-14 18:33:114234}
4235
4236void PeerConnection::UpdateEndedRemoteMediaStreams() {
4237 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams_to_remove;
4238 for (size_t i = 0; i < remote_streams_->count(); ++i) {
4239 MediaStreamInterface* stream = remote_streams_->at(i);
4240 if (stream->GetAudioTracks().empty() && stream->GetVideoTracks().empty()) {
4241 streams_to_remove.push_back(stream);
4242 }
4243 }
4244
Taylor Brandstetter98cde262016-05-31 20:02:214245 for (auto& stream : streams_to_remove) {
deadbeefab9b2d12015-10-14 18:33:114246 remote_streams_->RemoveStream(stream);
Taylor Brandstetter98cde262016-05-31 20:02:214247 observer_->OnRemoveStream(std::move(stream));
deadbeefab9b2d12015-10-14 18:33:114248 }
4249}
4250
Steve Anton4171afb2017-11-20 18:20:224251void PeerConnection::UpdateLocalSenders(
deadbeefab9b2d12015-10-14 18:33:114252 const std::vector<cricket::StreamParams>& streams,
4253 cricket::MediaType media_type) {
Steve Anton4171afb2017-11-20 18:20:224254 std::vector<RtpSenderInfo>* current_senders = GetLocalSenderInfos(media_type);
deadbeefab9b2d12015-10-14 18:33:114255
Seth Hampson845e8782018-03-02 19:34:104256 // Find removed tracks. I.e., tracks where the track id, stream id or ssrc
deadbeefab9b2d12015-10-14 18:33:114257 // don't match the new StreamParam.
Steve Anton4171afb2017-11-20 18:20:224258 for (auto sender_it = current_senders->begin();
4259 sender_it != current_senders->end();
4260 /* incremented manually */) {
4261 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 18:33:114262 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 18:20:224263 cricket::GetStreamBySsrc(streams, info.first_ssrc);
4264 if (!params || params->id != info.sender_id ||
Seth Hampson845e8782018-03-02 19:34:104265 params->first_stream_id() != info.stream_id) {
Steve Anton4171afb2017-11-20 18:20:224266 OnLocalSenderRemoved(info, media_type);
4267 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 18:33:114268 } else {
Steve Anton4171afb2017-11-20 18:20:224269 ++sender_it;
deadbeefab9b2d12015-10-14 18:33:114270 }
4271 }
4272
Steve Anton4171afb2017-11-20 18:20:224273 // Find new and active senders.
deadbeefab9b2d12015-10-14 18:33:114274 for (const cricket::StreamParams& params : streams) {
4275 // The sync_label is the MediaStream label and the |stream.id| is the
Steve Anton4171afb2017-11-20 18:20:224276 // sender id.
Seth Hampson845e8782018-03-02 19:34:104277 const std::string& stream_id = params.first_stream_id();
Steve Anton4171afb2017-11-20 18:20:224278 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 18:33:114279 uint32_t ssrc = params.first_ssrc();
Steve Anton4171afb2017-11-20 18:20:224280 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609eaa2018-03-27 21:57:184281 FindSenderInfo(*current_senders, stream_id, sender_id);
Steve Anton4171afb2017-11-20 18:20:224282 if (!sender_info) {
Seth Hampson845e8782018-03-02 19:34:104283 current_senders->push_back(RtpSenderInfo(stream_id, sender_id, ssrc));
Steve Anton4171afb2017-11-20 18:20:224284 OnLocalSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 18:33:114285 }
4286 }
4287}
4288
Steve Anton4171afb2017-11-20 18:20:224289void PeerConnection::OnLocalSenderAdded(const RtpSenderInfo& sender_info,
4290 cricket::MediaType media_type) {
Seth Hampson5b4f0752018-04-02 23:31:364291 RTC_DCHECK(!IsUnifiedPlan());
Steve Anton4171afb2017-11-20 18:20:224292 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 19:26:014293 if (!sender) {
Steve Anton4171afb2017-11-20 18:20:224294 RTC_LOG(LS_WARNING) << "An unknown RtpSender with id "
4295 << sender_info.sender_id
Mirko Bonadei675513b2017-11-09 10:09:254296 << " has been configured in the local description.";
deadbeefab9b2d12015-10-14 18:33:114297 return;
4298 }
4299
deadbeeffac06552015-11-25 19:26:014300 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 10:09:254301 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
Jonas Olsson45cc8902018-02-13 09:37:074302 " description with an unexpected media type.";
deadbeeffac06552015-11-25 19:26:014303 return;
deadbeefab9b2d12015-10-14 18:33:114304 }
deadbeeffac06552015-11-25 19:26:014305
Seth Hampson5b4f0752018-04-02 23:31:364306 sender->internal()->set_stream_ids({sender_info.stream_id});
Steve Anton4171afb2017-11-20 18:20:224307 sender->internal()->SetSsrc(sender_info.first_ssrc);
deadbeefab9b2d12015-10-14 18:33:114308}
4309
Steve Anton4171afb2017-11-20 18:20:224310void PeerConnection::OnLocalSenderRemoved(const RtpSenderInfo& sender_info,
4311 cricket::MediaType media_type) {
4312 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 19:26:014313 if (!sender) {
4314 // This is the normal case. I.e., RemoveStream has been called and the
deadbeefab9b2d12015-10-14 18:33:114315 // SessionDescriptions has been renegotiated.
4316 return;
4317 }
deadbeeffac06552015-11-25 19:26:014318
4319 // A sender has been removed from the SessionDescription but it's still
4320 // associated with the PeerConnection. This only occurs if the SDP doesn't
4321 // match with the calls to CreateSender, AddStream and RemoveStream.
4322 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 10:09:254323 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
Jonas Olsson45cc8902018-02-13 09:37:074324 " description with an unexpected media type.";
deadbeeffac06552015-11-25 19:26:014325 return;
deadbeefab9b2d12015-10-14 18:33:114326 }
deadbeeffac06552015-11-25 19:26:014327
Steve Anton4171afb2017-11-20 18:20:224328 sender->internal()->SetSsrc(0);
deadbeefab9b2d12015-10-14 18:33:114329}
4330
4331void PeerConnection::UpdateLocalRtpDataChannels(
4332 const cricket::StreamParamsVec& streams) {
4333 std::vector<std::string> existing_channels;
4334
4335 // Find new and active data channels.
4336 for (const cricket::StreamParams& params : streams) {
4337 // |it->sync_label| is actually the data channel label. The reason is that
4338 // we use the same naming of data channels as we do for
4339 // MediaStreams and Tracks.
4340 // For MediaStreams, the sync_label is the MediaStream label and the
4341 // track label is the same as |streamid|.
Seth Hampson845e8782018-03-02 19:34:104342 const std::string& channel_label = params.first_stream_id();
deadbeefab9b2d12015-10-14 18:33:114343 auto data_channel_it = rtp_data_channels_.find(channel_label);
nisse7ce109a2017-01-31 08:57:564344 if (data_channel_it == rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 10:09:254345 RTC_LOG(LS_ERROR) << "channel label not found";
deadbeefab9b2d12015-10-14 18:33:114346 continue;
4347 }
4348 // Set the SSRC the data channel should use for sending.
4349 data_channel_it->second->SetSendSsrc(params.first_ssrc());
4350 existing_channels.push_back(data_channel_it->first);
4351 }
4352
4353 UpdateClosingRtpDataChannels(existing_channels, true);
4354}
4355
4356void PeerConnection::UpdateRemoteRtpDataChannels(
4357 const cricket::StreamParamsVec& streams) {
4358 std::vector<std::string> existing_channels;
4359
4360 // Find new and active data channels.
4361 for (const cricket::StreamParams& params : streams) {
4362 // The data channel label is either the mslabel or the SSRC if the mslabel
4363 // does not exist. Ex a=ssrc:444330170 mslabel:test1.
Seth Hampson845e8782018-03-02 19:34:104364 std::string label = params.first_stream_id().empty()
deadbeefab9b2d12015-10-14 18:33:114365 ? rtc::ToString(params.first_ssrc())
Seth Hampson845e8782018-03-02 19:34:104366 : params.first_stream_id();
deadbeefab9b2d12015-10-14 18:33:114367 auto data_channel_it = rtp_data_channels_.find(label);
4368 if (data_channel_it == rtp_data_channels_.end()) {
4369 // This is a new data channel.
4370 CreateRemoteRtpDataChannel(label, params.first_ssrc());
4371 } else {
4372 data_channel_it->second->SetReceiveSsrc(params.first_ssrc());
4373 }
4374 existing_channels.push_back(label);
4375 }
4376
4377 UpdateClosingRtpDataChannels(existing_channels, false);
4378}
4379
4380void PeerConnection::UpdateClosingRtpDataChannels(
4381 const std::vector<std::string>& active_channels,
4382 bool is_local_update) {
4383 auto it = rtp_data_channels_.begin();
4384 while (it != rtp_data_channels_.end()) {
4385 DataChannel* data_channel = it->second;
4386 if (std::find(active_channels.begin(), active_channels.end(),
4387 data_channel->label()) != active_channels.end()) {
4388 ++it;
4389 continue;
4390 }
4391
4392 if (is_local_update) {
4393 data_channel->SetSendSsrc(0);
4394 } else {
4395 data_channel->RemotePeerRequestClose();
4396 }
4397
4398 if (data_channel->state() == DataChannel::kClosed) {
4399 rtp_data_channels_.erase(it);
4400 it = rtp_data_channels_.begin();
4401 } else {
4402 ++it;
4403 }
4404 }
4405}
4406
4407void PeerConnection::CreateRemoteRtpDataChannel(const std::string& label,
4408 uint32_t remote_ssrc) {
4409 rtc::scoped_refptr<DataChannel> channel(
4410 InternalCreateDataChannel(label, nullptr));
4411 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 10:09:254412 RTC_LOG(LS_WARNING) << "Remote peer requested a DataChannel but"
Jonas Olsson45cc8902018-02-13 09:37:074413 "CreateDataChannel failed.";
deadbeefab9b2d12015-10-14 18:33:114414 return;
4415 }
4416 channel->SetReceiveSsrc(remote_ssrc);
deadbeefa601f5c2016-06-06 21:27:394417 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
4418 DataChannelProxy::Create(signaling_thread(), channel);
Taylor Brandstetter98cde262016-05-31 20:02:214419 observer_->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 18:33:114420}
4421
4422rtc::scoped_refptr<DataChannel> PeerConnection::InternalCreateDataChannel(
4423 const std::string& label,
4424 const InternalDataChannelInit* config) {
4425 if (IsClosed()) {
4426 return nullptr;
4427 }
Steve Anton75737c02017-11-06 18:37:174428 if (data_channel_type() == cricket::DCT_NONE) {
Mirko Bonadei675513b2017-11-09 10:09:254429 RTC_LOG(LS_ERROR)
deadbeefab9b2d12015-10-14 18:33:114430 << "InternalCreateDataChannel: Data is not supported in this call.";
4431 return nullptr;
4432 }
4433 InternalDataChannelInit new_config =
4434 config ? (*config) : InternalDataChannelInit();
Steve Anton75737c02017-11-06 18:37:174435 if (data_channel_type() == cricket::DCT_SCTP) {
deadbeefab9b2d12015-10-14 18:33:114436 if (new_config.id < 0) {
4437 rtc::SSLRole role;
Steve Anton75737c02017-11-06 18:37:174438 if ((GetSctpSslRole(&role)) &&
deadbeefab9b2d12015-10-14 18:33:114439 !sid_allocator_.AllocateSid(role, &new_config.id)) {
Mirko Bonadei675513b2017-11-09 10:09:254440 RTC_LOG(LS_ERROR)
4441 << "No id can be allocated for the SCTP data channel.";
deadbeefab9b2d12015-10-14 18:33:114442 return nullptr;
4443 }
4444 } else if (!sid_allocator_.ReserveSid(new_config.id)) {
Mirko Bonadei675513b2017-11-09 10:09:254445 RTC_LOG(LS_ERROR) << "Failed to create a SCTP data channel "
Jonas Olsson45cc8902018-02-13 09:37:074446 "because the id is already in use or out of range.";
deadbeefab9b2d12015-10-14 18:33:114447 return nullptr;
4448 }
4449 }
4450
Steve Anton75737c02017-11-06 18:37:174451 rtc::scoped_refptr<DataChannel> channel(
4452 DataChannel::Create(this, data_channel_type(), label, new_config));
deadbeefab9b2d12015-10-14 18:33:114453 if (!channel) {
4454 sid_allocator_.ReleaseSid(new_config.id);
4455 return nullptr;
4456 }
4457
4458 if (channel->data_channel_type() == cricket::DCT_RTP) {
4459 if (rtp_data_channels_.find(channel->label()) != rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 10:09:254460 RTC_LOG(LS_ERROR) << "DataChannel with label " << channel->label()
4461 << " already exists.";
deadbeefab9b2d12015-10-14 18:33:114462 return nullptr;
4463 }
4464 rtp_data_channels_[channel->label()] = channel;
4465 } else {
4466 RTC_DCHECK(channel->data_channel_type() == cricket::DCT_SCTP);
4467 sctp_data_channels_.push_back(channel);
4468 channel->SignalClosed.connect(this,
4469 &PeerConnection::OnSctpDataChannelClosed);
4470 }
4471
Steve Anton2d8609c2018-01-24 00:38:464472 SignalDataChannelCreated_(channel.get());
deadbeefab9b2d12015-10-14 18:33:114473 return channel;
4474}
4475
4476bool PeerConnection::HasDataChannels() const {
4477 return !rtp_data_channels_.empty() || !sctp_data_channels_.empty();
4478}
4479
4480void PeerConnection::AllocateSctpSids(rtc::SSLRole role) {
4481 for (const auto& channel : sctp_data_channels_) {
4482 if (channel->id() < 0) {
4483 int sid;
4484 if (!sid_allocator_.AllocateSid(role, &sid)) {
Mirko Bonadei675513b2017-11-09 10:09:254485 RTC_LOG(LS_ERROR) << "Failed to allocate SCTP sid.";
deadbeefab9b2d12015-10-14 18:33:114486 continue;
4487 }
4488 channel->SetSctpSid(sid);
4489 }
4490 }
4491}
4492
4493void PeerConnection::OnSctpDataChannelClosed(DataChannel* channel) {
deadbeefbd292462015-12-15 02:15:294494 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeefab9b2d12015-10-14 18:33:114495 for (auto it = sctp_data_channels_.begin(); it != sctp_data_channels_.end();
4496 ++it) {
4497 if (it->get() == channel) {
4498 if (channel->id() >= 0) {
Taylor Brandstettercdd05f02018-05-31 20:23:324499 // After the closing procedure is done, it's safe to use this ID for
4500 // another data channel.
deadbeefab9b2d12015-10-14 18:33:114501 sid_allocator_.ReleaseSid(channel->id());
4502 }
deadbeefbd292462015-12-15 02:15:294503 // Since this method is triggered by a signal from the DataChannel,
4504 // we can't free it directly here; we need to free it asynchronously.
4505 sctp_data_channels_to_free_.push_back(*it);
deadbeefab9b2d12015-10-14 18:33:114506 sctp_data_channels_.erase(it);
Taylor Brandstetter5d97a9a2016-06-10 21:17:274507 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_FREE_DATACHANNELS,
4508 nullptr);
deadbeefab9b2d12015-10-14 18:33:114509 return;
4510 }
4511 }
4512}
4513
deadbeefab9b2d12015-10-14 18:33:114514void PeerConnection::OnDataChannelDestroyed() {
4515 // Use a temporary copy of the RTP/SCTP DataChannel list because the
4516 // DataChannel may callback to us and try to modify the list.
4517 std::map<std::string, rtc::scoped_refptr<DataChannel>> temp_rtp_dcs;
4518 temp_rtp_dcs.swap(rtp_data_channels_);
4519 for (const auto& kv : temp_rtp_dcs) {
4520 kv.second->OnTransportChannelDestroyed();
4521 }
4522
4523 std::vector<rtc::scoped_refptr<DataChannel>> temp_sctp_dcs;
4524 temp_sctp_dcs.swap(sctp_data_channels_);
4525 for (const auto& channel : temp_sctp_dcs) {
4526 channel->OnTransportChannelDestroyed();
4527 }
4528}
4529
4530void PeerConnection::OnDataChannelOpenMessage(
4531 const std::string& label,
4532 const InternalDataChannelInit& config) {
4533 rtc::scoped_refptr<DataChannel> channel(
4534 InternalCreateDataChannel(label, &config));
4535 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 10:09:254536 RTC_LOG(LS_ERROR) << "Failed to create DataChannel from the OPEN message.";
deadbeefab9b2d12015-10-14 18:33:114537 return;
4538 }
4539
deadbeefa601f5c2016-06-06 21:27:394540 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
4541 DataChannelProxy::Create(signaling_thread(), channel);
Taylor Brandstetter98cde262016-05-31 20:02:214542 observer_->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 18:33:114543}
4544
Steve Anton4171afb2017-11-20 18:20:224545rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
4546PeerConnection::GetAudioTransceiver() const {
4547 // This method only works with Plan B SDP, where there is a single
4548 // audio/video transceiver.
4549 RTC_DCHECK(!IsUnifiedPlan());
4550 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 19:43:084551 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 18:20:224552 return transceiver;
4553 }
4554 }
4555 RTC_NOTREACHED();
4556 return nullptr;
4557}
4558
4559rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
4560PeerConnection::GetVideoTransceiver() const {
4561 // This method only works with Plan B SDP, where there is a single
4562 // audio/video transceiver.
4563 RTC_DCHECK(!IsUnifiedPlan());
4564 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 19:43:084565 if (transceiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 18:20:224566 return transceiver;
4567 }
4568 }
4569 RTC_NOTREACHED();
4570 return nullptr;
4571}
4572
4573// TODO(bugs.webrtc.org/7600): Remove this when multiple transceivers with
4574// individual transceiver directions are supported.
zhihuang1c378ed2017-08-17 21:10:504575bool PeerConnection::HasRtpSender(cricket::MediaType type) const {
Steve Anton4171afb2017-11-20 18:20:224576 switch (type) {
4577 case cricket::MEDIA_TYPE_AUDIO:
4578 return !GetAudioTransceiver()->internal()->senders().empty();
4579 case cricket::MEDIA_TYPE_VIDEO:
4580 return !GetVideoTransceiver()->internal()->senders().empty();
4581 case cricket::MEDIA_TYPE_DATA:
4582 return false;
4583 }
4584 RTC_NOTREACHED();
4585 return false;
zhihuang1c378ed2017-08-17 21:10:504586}
4587
Steve Anton4171afb2017-11-20 18:20:224588rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
4589PeerConnection::FindSenderForTrack(MediaStreamTrackInterface* track) const {
4590 for (auto transceiver : transceivers_) {
4591 for (auto sender : transceiver->internal()->senders()) {
4592 if (sender->track() == track) {
4593 return sender;
4594 }
4595 }
4596 }
4597 return nullptr;
deadbeeffac06552015-11-25 19:26:014598}
4599
Steve Anton4171afb2017-11-20 18:20:224600rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
4601PeerConnection::FindSenderById(const std::string& sender_id) const {
4602 for (auto transceiver : transceivers_) {
4603 for (auto sender : transceiver->internal()->senders()) {
4604 if (sender->id() == sender_id) {
4605 return sender;
4606 }
4607 }
4608 }
4609 return nullptr;
deadbeef70ab1a12015-09-28 23:53:554610}
4611
Steve Anton4171afb2017-11-20 18:20:224612rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
4613PeerConnection::FindReceiverById(const std::string& receiver_id) const {
4614 for (auto transceiver : transceivers_) {
4615 for (auto receiver : transceiver->internal()->receivers()) {
4616 if (receiver->id() == receiver_id) {
4617 return receiver;
4618 }
4619 }
4620 }
4621 return nullptr;
deadbeef70ab1a12015-09-28 23:53:554622}
4623
Steve Anton4171afb2017-11-20 18:20:224624std::vector<PeerConnection::RtpSenderInfo>*
4625PeerConnection::GetRemoteSenderInfos(cricket::MediaType media_type) {
4626 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
4627 media_type == cricket::MEDIA_TYPE_VIDEO);
4628 return (media_type == cricket::MEDIA_TYPE_AUDIO)
4629 ? &remote_audio_sender_infos_
4630 : &remote_video_sender_infos_;
4631}
4632
4633std::vector<PeerConnection::RtpSenderInfo>* PeerConnection::GetLocalSenderInfos(
deadbeefab9b2d12015-10-14 18:33:114634 cricket::MediaType media_type) {
4635 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
4636 media_type == cricket::MEDIA_TYPE_VIDEO);
Steve Anton4171afb2017-11-20 18:20:224637 return (media_type == cricket::MEDIA_TYPE_AUDIO) ? &local_audio_sender_infos_
4638 : &local_video_sender_infos_;
deadbeefab9b2d12015-10-14 18:33:114639}
4640
Steve Anton4171afb2017-11-20 18:20:224641const PeerConnection::RtpSenderInfo* PeerConnection::FindSenderInfo(
4642 const std::vector<PeerConnection::RtpSenderInfo>& infos,
Emircan Uysalerbc609eaa2018-03-27 21:57:184643 const std::string& stream_id,
Steve Anton4171afb2017-11-20 18:20:224644 const std::string sender_id) const {
4645 for (const RtpSenderInfo& sender_info : infos) {
Emircan Uysalerbc609eaa2018-03-27 21:57:184646 if (sender_info.stream_id == stream_id &&
4647 sender_info.sender_id == sender_id) {
Steve Anton4171afb2017-11-20 18:20:224648 return &sender_info;
deadbeefab9b2d12015-10-14 18:33:114649 }
4650 }
4651 return nullptr;
4652}
4653
4654DataChannel* PeerConnection::FindDataChannelBySid(int sid) const {
4655 for (const auto& channel : sctp_data_channels_) {
4656 if (channel->id() == sid) {
4657 return channel;
4658 }
4659 }
4660 return nullptr;
4661}
4662
deadbeef91dd5672016-05-18 23:55:304663bool PeerConnection::InitializePortAllocator_n(
Taylor Brandstettera1c30352016-05-13 15:15:114664 const RTCConfiguration& configuration) {
4665 cricket::ServerAddresses stun_servers;
4666 std::vector<cricket::RelayServerConfig> turn_servers;
deadbeef293e9262017-01-11 20:28:304667 if (ParseIceServers(configuration.servers, &stun_servers, &turn_servers) !=
4668 RTCErrorType::NONE) {
Taylor Brandstettera1c30352016-05-13 15:15:114669 return false;
4670 }
4671
Taylor Brandstetterf8e65772016-06-28 00:20:154672 port_allocator_->Initialize();
Taylor Brandstettera1c30352016-05-13 15:15:114673 // To handle both internal and externally created port allocator, we will
4674 // enable BUNDLE here.
Qingsi Wanga2d60672018-04-11 23:57:454675 port_allocator_flags_ = port_allocator_->flags();
4676 port_allocator_flags_ |= cricket::PORTALLOCATOR_ENABLE_SHARED_SOCKET |
4677 cricket::PORTALLOCATOR_ENABLE_IPV6 |
4678 cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI;
Taylor Brandstettera1c30352016-05-13 15:15:114679 // If the disable-IPv6 flag was specified, we'll not override it
4680 // by experiment.
4681 if (configuration.disable_ipv6) {
Qingsi Wanga2d60672018-04-11 23:57:454682 port_allocator_flags_ &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
sprangc1b57a12017-02-28 16:50:474683 } else if (webrtc::field_trial::FindFullName("WebRTC-IPv6Default")
4684 .find("Disabled") == 0) {
Qingsi Wanga2d60672018-04-11 23:57:454685 port_allocator_flags_ &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
Taylor Brandstettera1c30352016-05-13 15:15:114686 }
4687
zhihuangb09b3f92017-03-07 22:40:514688 if (configuration.disable_ipv6_on_wifi) {
Qingsi Wanga2d60672018-04-11 23:57:454689 port_allocator_flags_ &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI);
Mirko Bonadei675513b2017-11-09 10:09:254690 RTC_LOG(LS_INFO) << "IPv6 candidates on Wi-Fi are disabled.";
zhihuangb09b3f92017-03-07 22:40:514691 }
4692
Taylor Brandstettera1c30352016-05-13 15:15:114693 if (configuration.tcp_candidate_policy == kTcpCandidatePolicyDisabled) {
Qingsi Wanga2d60672018-04-11 23:57:454694 port_allocator_flags_ |= cricket::PORTALLOCATOR_DISABLE_TCP;
Mirko Bonadei675513b2017-11-09 10:09:254695 RTC_LOG(LS_INFO) << "TCP candidates are disabled.";
Taylor Brandstettera1c30352016-05-13 15:15:114696 }
4697
honghaiz60347052016-06-01 01:29:124698 if (configuration.candidate_network_policy ==
4699 kCandidateNetworkPolicyLowCost) {
Qingsi Wanga2d60672018-04-11 23:57:454700 port_allocator_flags_ |= cricket::PORTALLOCATOR_DISABLE_COSTLY_NETWORKS;
Mirko Bonadei675513b2017-11-09 10:09:254701 RTC_LOG(LS_INFO) << "Do not gather candidates on high-cost networks";
honghaiz60347052016-06-01 01:29:124702 }
4703
Daniel Lazarenko2870b0a2018-01-25 09:30:224704 if (configuration.disable_link_local_networks) {
Qingsi Wanga2d60672018-04-11 23:57:454705 port_allocator_flags_ |= cricket::PORTALLOCATOR_DISABLE_LINK_LOCAL_NETWORKS;
Daniel Lazarenko2870b0a2018-01-25 09:30:224706 RTC_LOG(LS_INFO) << "Disable candidates on link-local network interfaces.";
4707 }
4708
Qingsi Wanga2d60672018-04-11 23:57:454709 port_allocator_->set_flags(port_allocator_flags_);
Taylor Brandstettera1c30352016-05-13 15:15:114710 // No step delay is used while allocating ports.
4711 port_allocator_->set_step_delay(cricket::kMinimumStepDelay);
4712 port_allocator_->set_candidate_filter(
4713 ConvertIceTransportTypeToCandidateFilter(configuration.type));
deadbeefd21eab3e2017-07-26 23:50:114714 port_allocator_->set_max_ipv6_networks(configuration.max_ipv6_networks);
Taylor Brandstettera1c30352016-05-13 15:15:114715
Benjamin Wrightd6f86e82018-05-08 20:12:254716 if (tls_cert_verifier_ != nullptr) {
4717 for (auto& turn_server : turn_servers) {
4718 turn_server.tls_cert_verifier = tls_cert_verifier_.get();
4719 }
4720 }
Taylor Brandstettera1c30352016-05-13 15:15:114721 // Call this last since it may create pooled allocator sessions using the
4722 // properties set above.
Qingsi Wangdb53f8e2018-02-20 22:45:494723 port_allocator_->SetConfiguration(
4724 stun_servers, turn_servers, configuration.ice_candidate_pool_size,
4725 configuration.prune_turn_ports, configuration.turn_customizer,
4726 configuration.stun_candidate_keepalive_interval);
Taylor Brandstettera1c30352016-05-13 15:15:114727 return true;
4728}
4729
deadbeef91dd5672016-05-18 23:55:304730bool PeerConnection::ReconfigurePortAllocator_n(
deadbeef293e9262017-01-11 20:28:304731 const cricket::ServerAddresses& stun_servers,
4732 const std::vector<cricket::RelayServerConfig>& turn_servers,
4733 IceTransportsType type,
4734 int candidate_pool_size,
Jonas Orelandbdcee282017-10-10 12:01:404735 bool prune_turn_ports,
Qingsi Wangdb53f8e2018-02-20 22:45:494736 webrtc::TurnCustomizer* turn_customizer,
4737 rtc::Optional<int> stun_candidate_keepalive_interval) {
Taylor Brandstettera1c30352016-05-13 15:15:114738 port_allocator_->set_candidate_filter(
deadbeef293e9262017-01-11 20:28:304739 ConvertIceTransportTypeToCandidateFilter(type));
Qingsi Wanga2d60672018-04-11 23:57:454740 // According to JSEP, after setLocalDescription, changing the candidate pool
4741 // size is not allowed, and changing the set of ICE servers will not result
4742 // in new candidates being gathered.
4743 if (local_description()) {
4744 port_allocator_->FreezeCandidatePool();
4745 }
Taylor Brandstettera1c30352016-05-13 15:15:114746 // Call this last since it may create pooled allocator sessions using the
4747 // candidate filter set above.
deadbeef6de92f92016-12-13 02:49:324748 return port_allocator_->SetConfiguration(
Jonas Orelandbdcee282017-10-10 12:01:404749 stun_servers, turn_servers, candidate_pool_size, prune_turn_ports,
Qingsi Wangdb53f8e2018-02-20 22:45:494750 turn_customizer, stun_candidate_keepalive_interval);
Taylor Brandstettera1c30352016-05-13 15:15:114751}
4752
Steve Antonba818672017-11-06 18:21:574753cricket::ChannelManager* PeerConnection::channel_manager() const {
4754 return factory_->channel_manager();
4755}
4756
4757MetricsObserverInterface* PeerConnection::metrics_observer() const {
4758 return uma_observer_;
4759}
4760
Elad Alon99c3fe52017-10-13 14:29:404761bool PeerConnection::StartRtcEventLog_w(
Bjorn Tereliusde939432017-11-20 16:38:144762 std::unique_ptr<RtcEventLogOutput> output,
4763 int64_t output_period_ms) {
zhihuang77985012017-02-07 23:45:164764 if (!event_log_) {
4765 return false;
4766 }
Bjorn Tereliusde939432017-11-20 16:38:144767 return event_log_->StartLogging(std::move(output), output_period_ms);
ivoc14d5dbe2016-07-04 14:06:554768}
4769
4770void PeerConnection::StopRtcEventLog_w() {
zhihuang77985012017-02-07 23:45:164771 if (event_log_) {
4772 event_log_->StopLogging();
4773 }
ivoc14d5dbe2016-07-04 14:06:554774}
nisseeaabdf62017-05-05 09:23:024775
Steve Anton75737c02017-11-06 18:37:174776cricket::BaseChannel* PeerConnection::GetChannel(
4777 const std::string& content_name) {
Steve Antondcc3c022017-12-23 00:02:544778 for (auto transceiver : transceivers_) {
4779 cricket::BaseChannel* channel = transceiver->internal()->channel();
4780 if (channel && channel->content_name() == content_name) {
4781 return channel;
4782 }
Steve Anton75737c02017-11-06 18:37:174783 }
4784 if (rtp_data_channel() &&
4785 rtp_data_channel()->content_name() == content_name) {
4786 return rtp_data_channel();
4787 }
4788 return nullptr;
4789}
4790
4791bool PeerConnection::GetSctpSslRole(rtc::SSLRole* role) {
4792 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 10:09:254793 RTC_LOG(LS_INFO)
4794 << "Local and Remote descriptions must be applied to get the "
Jonas Olsson45cc8902018-02-13 09:37:074795 "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 18:37:174796 return false;
4797 }
4798 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 10:09:254799 RTC_LOG(LS_INFO) << "Non-rejected SCTP m= section is needed to get the "
Jonas Olsson45cc8902018-02-13 09:37:074800 "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 18:37:174801 return false;
4802 }
4803
Zhi Huange830e682018-03-30 17:48:354804 auto dtls_role = transport_controller_->GetDtlsRole(*sctp_mid_);
4805 if (dtls_role) {
4806 *role = *dtls_role;
4807 return true;
4808 }
4809 return false;
Steve Anton75737c02017-11-06 18:37:174810}
4811
4812bool PeerConnection::GetSslRole(const std::string& content_name,
4813 rtc::SSLRole* role) {
4814 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 10:09:254815 RTC_LOG(LS_INFO)
4816 << "Local and Remote descriptions must be applied to get the "
Jonas Olsson45cc8902018-02-13 09:37:074817 "SSL Role of the session.";
Steve Anton75737c02017-11-06 18:37:174818 return false;
4819 }
4820
Zhi Huange830e682018-03-30 17:48:354821 auto dtls_role = transport_controller_->GetDtlsRole(content_name);
4822 if (dtls_role) {
4823 *role = *dtls_role;
4824 return true;
4825 }
4826 return false;
Steve Anton75737c02017-11-06 18:37:174827}
4828
Steve Antonf8470812017-12-04 18:46:214829void PeerConnection::SetSessionError(SessionError error,
4830 const std::string& error_desc) {
4831 RTC_DCHECK_RUN_ON(signaling_thread());
4832 if (error != session_error_) {
4833 session_error_ = error;
4834 session_error_desc_ = error_desc;
Steve Anton75737c02017-11-06 18:37:174835 }
4836}
4837
Zhi Huange830e682018-03-30 17:48:354838RTCError PeerConnection::UpdateSessionState(
4839 SdpType type,
4840 cricket::ContentSource source,
4841 const cricket::SessionDescription* description) {
Steve Anton8a006912017-12-04 23:25:564842 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 18:37:174843
4844 // If there's already a pending error then no state transition should happen.
4845 // But all call-sites should be verifying this before calling us!
Steve Antonf8470812017-12-04 18:46:214846 RTC_DCHECK(session_error() == SessionError::kNone);
Steve Anton6d6a2ae2017-12-05 01:19:474847
Steve Anton6d6a2ae2017-12-05 01:19:474848 // If this is answer-ish we're ready to let media flow.
Steve Anton3828c062017-12-06 18:34:514849 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Antoned10bd92017-12-05 18:52:594850 EnableSending();
Steve Anton6d6a2ae2017-12-05 01:19:474851 }
4852
4853 // Update the signaling state according to the specified state machine (see
4854 // https://w3c.github.io/webrtc-pc/#rtcsignalingstate-enum).
Steve Anton3828c062017-12-06 18:34:514855 if (type == SdpType::kOffer) {
Steve Anton6d6a2ae2017-12-05 01:19:474856 ChangeSignalingState(source == cricket::CS_LOCAL
4857 ? PeerConnectionInterface::kHaveLocalOffer
4858 : PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton3828c062017-12-06 18:34:514859 } else if (type == SdpType::kPrAnswer) {
Steve Anton6d6a2ae2017-12-05 01:19:474860 ChangeSignalingState(source == cricket::CS_LOCAL
4861 ? PeerConnectionInterface::kHaveLocalPrAnswer
4862 : PeerConnectionInterface::kHaveRemotePrAnswer);
4863 } else {
Steve Anton3828c062017-12-06 18:34:514864 RTC_DCHECK(type == SdpType::kAnswer);
Steve Anton6d6a2ae2017-12-05 01:19:474865 ChangeSignalingState(PeerConnectionInterface::kStable);
4866 }
4867
4868 // Update internal objects according to the session description's media
4869 // descriptions.
Zhi Huange830e682018-03-30 17:48:354870 RTCError error = PushdownMediaDescription(type, source);
Steve Anton6d6a2ae2017-12-05 01:19:474871 if (!error.ok()) {
Steve Anton80dd7b52018-02-17 01:08:424872 return error;
Steve Anton6d6a2ae2017-12-05 01:19:474873 }
4874
Steve Anton8a006912017-12-04 23:25:564875 return RTCError::OK();
Steve Anton75737c02017-11-06 18:37:174876}
4877
Steve Anton8a006912017-12-04 23:25:564878RTCError PeerConnection::PushdownMediaDescription(
Steve Anton3828c062017-12-06 18:34:514879 SdpType type,
Steve Anton8a006912017-12-04 23:25:564880 cricket::ContentSource source) {
Steve Antoned10bd92017-12-05 18:52:594881 const SessionDescriptionInterface* sdesc =
4882 (source == cricket::CS_LOCAL ? local_description()
4883 : remote_description());
Steve Anton75737c02017-11-06 18:37:174884 RTC_DCHECK(sdesc);
Steve Antoned10bd92017-12-05 18:52:594885
4886 // Push down the new SDP media section for each audio/video transceiver.
4887 for (auto transceiver : transceivers_) {
Steve Anton75737c02017-11-06 18:37:174888 const ContentInfo* content_info =
Steve Antoned10bd92017-12-05 18:52:594889 FindMediaSectionForTransceiver(transceiver, sdesc);
4890 cricket::BaseChannel* channel = transceiver->internal()->channel();
4891 if (!channel || !content_info || content_info->rejected) {
Steve Anton75737c02017-11-06 18:37:174892 continue;
4893 }
4894 const MediaContentDescription* content_desc =
Steve Antonb1c1de12017-12-21 23:14:304895 content_info->media_description();
Steve Antoned10bd92017-12-05 18:52:594896 if (!content_desc) {
4897 continue;
4898 }
4899 std::string error;
4900 bool success =
4901 (source == cricket::CS_LOCAL)
Steve Anton3828c062017-12-06 18:34:514902 ? channel->SetLocalContent(content_desc, type, &error)
4903 : channel->SetRemoteContent(content_desc, type, &error);
Steve Antoned10bd92017-12-05 18:52:594904 if (!success) {
4905 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, std::move(error));
4906 }
4907 }
4908
4909 // If using the RtpDataChannel, push down the new SDP section for it too.
4910 if (rtp_data_channel_) {
4911 const ContentInfo* data_content =
4912 cricket::GetFirstDataContent(sdesc->description());
4913 if (data_content && !data_content->rejected) {
4914 const MediaContentDescription* data_desc =
Steve Antonb1c1de12017-12-21 23:14:304915 data_content->media_description();
Steve Antoned10bd92017-12-05 18:52:594916 if (data_desc) {
4917 std::string error;
4918 bool success =
4919 (source == cricket::CS_LOCAL)
Steve Anton3828c062017-12-06 18:34:514920 ? rtp_data_channel_->SetLocalContent(data_desc, type, &error)
4921 : rtp_data_channel_->SetRemoteContent(data_desc, type,
Steve Antoned10bd92017-12-05 18:52:594922 &error);
4923 if (!success) {
4924 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
4925 std::move(error));
4926 }
Steve Anton75737c02017-11-06 18:37:174927 }
4928 }
4929 }
Steve Antoned10bd92017-12-05 18:52:594930
Steve Anton75737c02017-11-06 18:37:174931 // Need complete offer/answer with an SCTP m= section before starting SCTP,
4932 // according to https://tools.ietf.org/html/draft-ietf-mmusic-sctp-sdp-19
4933 if (sctp_transport_ && local_description() && remote_description() &&
4934 cricket::GetFirstDataContent(local_description()->description()) &&
4935 cricket::GetFirstDataContent(remote_description()->description())) {
Steve Anton8a006912017-12-04 23:25:564936 bool success = network_thread()->Invoke<bool>(
Steve Anton75737c02017-11-06 18:37:174937 RTC_FROM_HERE,
4938 rtc::Bind(&PeerConnection::PushdownSctpParameters_n, this, source));
Steve Anton8a006912017-12-04 23:25:564939 if (!success) {
4940 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
4941 "Failed to push down SCTP parameters.");
4942 }
Steve Anton75737c02017-11-06 18:37:174943 }
Steve Antoned10bd92017-12-05 18:52:594944
Steve Anton8a006912017-12-04 23:25:564945 return RTCError::OK();
Steve Anton75737c02017-11-06 18:37:174946}
4947
4948bool PeerConnection::PushdownSctpParameters_n(cricket::ContentSource source) {
4949 RTC_DCHECK(network_thread()->IsCurrent());
4950 RTC_DCHECK(local_description());
4951 RTC_DCHECK(remote_description());
4952 // Apply the SCTP port (which is hidden inside a DataCodec structure...)
4953 // When we support "max-message-size", that would also be pushed down here.
4954 return sctp_transport_->Start(
4955 GetSctpPort(local_description()->description()),
4956 GetSctpPort(remote_description()->description()));
4957}
4958
Steve Anton8a006912017-12-04 23:25:564959RTCError PeerConnection::PushdownTransportDescription(
4960 cricket::ContentSource source,
Steve Anton3828c062017-12-06 18:34:514961 SdpType type) {
Steve Anton8a006912017-12-04 23:25:564962 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 18:37:174963
Zhi Huange830e682018-03-30 17:48:354964 if (source == cricket::CS_LOCAL) {
4965 const SessionDescriptionInterface* sdesc = local_description();
4966 RTC_DCHECK(sdesc);
4967 return transport_controller_->SetLocalDescription(type,
4968 sdesc->description());
4969 } else {
4970 const SessionDescriptionInterface* sdesc = remote_description();
4971 RTC_DCHECK(sdesc);
4972 return transport_controller_->SetRemoteDescription(type,
4973 sdesc->description());
Steve Anton75737c02017-11-06 18:37:174974 }
Steve Anton75737c02017-11-06 18:37:174975}
4976
4977bool PeerConnection::GetTransportDescription(
4978 const SessionDescription* description,
4979 const std::string& content_name,
4980 cricket::TransportDescription* tdesc) {
4981 if (!description || !tdesc) {
4982 return false;
4983 }
4984 const TransportInfo* transport_info =
4985 description->GetTransportInfoByName(content_name);
4986 if (!transport_info) {
4987 return false;
4988 }
4989 *tdesc = transport_info->description;
4990 return true;
4991}
4992
Steve Anton75737c02017-11-06 18:37:174993cricket::IceConfig PeerConnection::ParseIceConfig(
4994 const PeerConnectionInterface::RTCConfiguration& config) const {
4995 cricket::ContinualGatheringPolicy gathering_policy;
Steve Anton75737c02017-11-06 18:37:174996 switch (config.continual_gathering_policy) {
4997 case PeerConnectionInterface::GATHER_ONCE:
4998 gathering_policy = cricket::GATHER_ONCE;
4999 break;
5000 case PeerConnectionInterface::GATHER_CONTINUALLY:
5001 gathering_policy = cricket::GATHER_CONTINUALLY;
5002 break;
5003 default:
5004 RTC_NOTREACHED();
5005 gathering_policy = cricket::GATHER_ONCE;
5006 }
Qingsi Wang9a5c6f82018-02-01 18:38:405007
Steve Anton75737c02017-11-06 18:37:175008 cricket::IceConfig ice_config;
Qingsi Wang866e08d2018-03-23 00:54:235009 ice_config.receiving_timeout = RTCConfigurationToIceConfigOptionalInt(
5010 config.ice_connection_receiving_timeout);
Steve Anton75737c02017-11-06 18:37:175011 ice_config.prioritize_most_likely_candidate_pairs =
5012 config.prioritize_most_likely_ice_candidate_pairs;
5013 ice_config.backup_connection_ping_interval =
Qingsi Wang866e08d2018-03-23 00:54:235014 RTCConfigurationToIceConfigOptionalInt(
5015 config.ice_backup_candidate_pair_ping_interval);
Steve Anton75737c02017-11-06 18:37:175016 ice_config.continual_gathering_policy = gathering_policy;
5017 ice_config.presume_writable_when_fully_relayed =
5018 config.presume_writable_when_fully_relayed;
Qingsi Wange6826d22018-03-08 22:55:145019 ice_config.ice_check_interval_strong_connectivity =
5020 config.ice_check_interval_strong_connectivity;
5021 ice_config.ice_check_interval_weak_connectivity =
5022 config.ice_check_interval_weak_connectivity;
Steve Anton75737c02017-11-06 18:37:175023 ice_config.ice_check_min_interval = config.ice_check_min_interval;
Qingsi Wangdb53f8e2018-02-20 22:45:495024 ice_config.stun_keepalive_interval = config.stun_candidate_keepalive_interval;
Steve Anton75737c02017-11-06 18:37:175025 ice_config.regather_all_networks_interval_range =
5026 config.ice_regather_interval_range;
Qingsi Wang9a5c6f82018-02-01 18:38:405027 ice_config.network_preference = config.network_preference;
Steve Anton75737c02017-11-06 18:37:175028 return ice_config;
5029}
5030
Steve Anton75737c02017-11-06 18:37:175031bool PeerConnection::GetLocalTrackIdBySsrc(uint32_t ssrc,
5032 std::string* track_id) {
5033 if (!local_description()) {
5034 return false;
5035 }
5036 return webrtc::GetTrackIdBySsrc(local_description()->description(), ssrc,
5037 track_id);
5038}
5039
5040bool PeerConnection::GetRemoteTrackIdBySsrc(uint32_t ssrc,
5041 std::string* track_id) {
5042 if (!remote_description()) {
5043 return false;
5044 }
5045 return webrtc::GetTrackIdBySsrc(remote_description()->description(), ssrc,
5046 track_id);
5047}
5048
5049bool PeerConnection::SendData(const cricket::SendDataParams& params,
5050 const rtc::CopyOnWriteBuffer& payload,
5051 cricket::SendDataResult* result) {
5052 if (!rtp_data_channel_ && !sctp_transport_) {
Mirko Bonadei675513b2017-11-09 10:09:255053 RTC_LOG(LS_ERROR) << "SendData called when rtp_data_channel_ "
Jonas Olsson45cc8902018-02-13 09:37:075054 "and sctp_transport_ are NULL.";
Steve Anton75737c02017-11-06 18:37:175055 return false;
5056 }
5057 return rtp_data_channel_
5058 ? rtp_data_channel_->SendData(params, payload, result)
5059 : network_thread()->Invoke<bool>(
5060 RTC_FROM_HERE,
5061 Bind(&cricket::SctpTransportInternal::SendData,
5062 sctp_transport_.get(), params, payload, result));
5063}
5064
5065bool PeerConnection::ConnectDataChannel(DataChannel* webrtc_data_channel) {
5066 if (!rtp_data_channel_ && !sctp_transport_) {
5067 // Don't log an error here, because DataChannels are expected to call
5068 // ConnectDataChannel in this state. It's the only way to initially tell
5069 // whether or not the underlying transport is ready.
5070 return false;
5071 }
5072 if (rtp_data_channel_) {
5073 rtp_data_channel_->SignalReadyToSendData.connect(
5074 webrtc_data_channel, &DataChannel::OnChannelReady);
5075 rtp_data_channel_->SignalDataReceived.connect(webrtc_data_channel,
5076 &DataChannel::OnDataReceived);
5077 } else {
5078 SignalSctpReadyToSendData.connect(webrtc_data_channel,
5079 &DataChannel::OnChannelReady);
5080 SignalSctpDataReceived.connect(webrtc_data_channel,
5081 &DataChannel::OnDataReceived);
Taylor Brandstettercdd05f02018-05-31 20:23:325082 SignalSctpClosingProcedureStartedRemotely.connect(
5083 webrtc_data_channel, &DataChannel::OnClosingProcedureStartedRemotely);
5084 SignalSctpClosingProcedureComplete.connect(
5085 webrtc_data_channel, &DataChannel::OnClosingProcedureComplete);
Steve Anton75737c02017-11-06 18:37:175086 }
5087 return true;
5088}
5089
5090void PeerConnection::DisconnectDataChannel(DataChannel* webrtc_data_channel) {
5091 if (!rtp_data_channel_ && !sctp_transport_) {
Mirko Bonadei675513b2017-11-09 10:09:255092 RTC_LOG(LS_ERROR)
5093 << "DisconnectDataChannel called when rtp_data_channel_ and "
5094 "sctp_transport_ are NULL.";
Steve Anton75737c02017-11-06 18:37:175095 return;
5096 }
5097 if (rtp_data_channel_) {
5098 rtp_data_channel_->SignalReadyToSendData.disconnect(webrtc_data_channel);
5099 rtp_data_channel_->SignalDataReceived.disconnect(webrtc_data_channel);
5100 } else {
5101 SignalSctpReadyToSendData.disconnect(webrtc_data_channel);
5102 SignalSctpDataReceived.disconnect(webrtc_data_channel);
Taylor Brandstettercdd05f02018-05-31 20:23:325103 SignalSctpClosingProcedureStartedRemotely.disconnect(webrtc_data_channel);
5104 SignalSctpClosingProcedureComplete.disconnect(webrtc_data_channel);
Steve Anton75737c02017-11-06 18:37:175105 }
5106}
5107
5108void PeerConnection::AddSctpDataStream(int sid) {
5109 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 10:09:255110 RTC_LOG(LS_ERROR)
5111 << "AddSctpDataStream called when sctp_transport_ is NULL.";
Steve Anton75737c02017-11-06 18:37:175112 return;
5113 }
5114 network_thread()->Invoke<void>(
5115 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::OpenStream,
5116 sctp_transport_.get(), sid));
5117}
5118
5119void PeerConnection::RemoveSctpDataStream(int sid) {
5120 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 10:09:255121 RTC_LOG(LS_ERROR) << "RemoveSctpDataStream called when sctp_transport_ is "
Jonas Olsson45cc8902018-02-13 09:37:075122 "NULL.";
Steve Anton75737c02017-11-06 18:37:175123 return;
5124 }
5125 network_thread()->Invoke<void>(
5126 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::ResetStream,
5127 sctp_transport_.get(), sid));
5128}
5129
5130bool PeerConnection::ReadyToSendData() const {
5131 return (rtp_data_channel_ && rtp_data_channel_->ready_to_send_data()) ||
5132 sctp_ready_to_send_data_;
5133}
5134
Zhi Huange830e682018-03-30 17:48:355135rtc::Optional<std::string> PeerConnection::sctp_transport_name() const {
5136 if (sctp_mid_ && transport_controller_) {
5137 auto dtls_transport = transport_controller_->GetDtlsTransport(*sctp_mid_);
5138 if (dtls_transport) {
5139 return dtls_transport->transport_name();
5140 }
5141 return rtc::Optional<std::string>();
5142 }
5143 return rtc::Optional<std::string>();
5144}
5145
Qingsi Wang72a43a12018-02-21 00:03:185146cricket::CandidateStatsList PeerConnection::GetPooledCandidateStats() const {
5147 cricket::CandidateStatsList candidate_states_list;
Qingsi Wanga2d60672018-04-11 23:57:455148 network_thread()->Invoke<void>(
5149 RTC_FROM_HERE,
5150 rtc::Bind(&cricket::PortAllocator::GetCandidateStatsFromPooledSessions,
5151 port_allocator_.get(), &candidate_states_list));
Qingsi Wang72a43a12018-02-21 00:03:185152 return candidate_states_list;
5153}
5154
Steve Anton5dfde182018-02-06 18:34:405155std::map<std::string, std::string> PeerConnection::GetTransportNamesByMid()
5156 const {
5157 std::map<std::string, std::string> transport_names_by_mid;
5158 for (auto transceiver : transceivers_) {
5159 cricket::BaseChannel* channel = transceiver->internal()->channel();
5160 if (channel) {
5161 transport_names_by_mid[channel->content_name()] =
5162 channel->transport_name();
5163 }
Steve Anton75737c02017-11-06 18:37:175164 }
Steve Anton5dfde182018-02-06 18:34:405165 if (rtp_data_channel_) {
5166 transport_names_by_mid[rtp_data_channel_->content_name()] =
5167 rtp_data_channel_->transport_name();
Steve Anton75737c02017-11-06 18:37:175168 }
5169 if (sctp_transport_) {
Zhi Huange830e682018-03-30 17:48:355170 rtc::Optional<std::string> transport_name = sctp_transport_name();
5171 RTC_DCHECK(transport_name);
5172 transport_names_by_mid[*sctp_mid_] = *transport_name;
Steve Anton75737c02017-11-06 18:37:175173 }
Steve Anton5dfde182018-02-06 18:34:405174 return transport_names_by_mid;
Steve Anton75737c02017-11-06 18:37:175175}
5176
Steve Anton5dfde182018-02-06 18:34:405177std::map<std::string, cricket::TransportStats>
5178PeerConnection::GetTransportStatsByNames(
5179 const std::set<std::string>& transport_names) {
5180 if (!network_thread()->IsCurrent()) {
5181 return network_thread()
5182 ->Invoke<std::map<std::string, cricket::TransportStats>>(
5183 RTC_FROM_HERE,
5184 [&] { return GetTransportStatsByNames(transport_names); });
Steve Anton75737c02017-11-06 18:37:175185 }
Steve Anton5dfde182018-02-06 18:34:405186 std::map<std::string, cricket::TransportStats> transport_stats_by_name;
5187 for (const std::string& transport_name : transport_names) {
5188 cricket::TransportStats transport_stats;
5189 bool success =
5190 transport_controller_->GetStats(transport_name, &transport_stats);
5191 if (success) {
5192 transport_stats_by_name[transport_name] = std::move(transport_stats);
5193 } else {
5194 RTC_LOG(LS_ERROR) << "Failed to get transport stats for transport_name="
5195 << transport_name;
5196 }
5197 }
5198 return transport_stats_by_name;
Steve Anton75737c02017-11-06 18:37:175199}
5200
5201bool PeerConnection::GetLocalCertificate(
5202 const std::string& transport_name,
5203 rtc::scoped_refptr<rtc::RTCCertificate>* certificate) {
Zhi Huange830e682018-03-30 17:48:355204 if (!certificate) {
5205 return false;
5206 }
5207 *certificate = transport_controller_->GetLocalCertificate(transport_name);
5208 return *certificate != nullptr;
Steve Anton75737c02017-11-06 18:37:175209}
5210
Taylor Brandstetterc3928662018-02-23 21:04:515211std::unique_ptr<rtc::SSLCertChain> PeerConnection::GetRemoteSSLCertChain(
Steve Anton75737c02017-11-06 18:37:175212 const std::string& transport_name) {
Taylor Brandstetterc3928662018-02-23 21:04:515213 return transport_controller_->GetRemoteSSLCertChain(transport_name);
Steve Anton75737c02017-11-06 18:37:175214}
5215
5216cricket::DataChannelType PeerConnection::data_channel_type() const {
5217 return data_channel_type_;
5218}
5219
5220bool PeerConnection::IceRestartPending(const std::string& content_name) const {
5221 return pending_ice_restarts_.find(content_name) !=
5222 pending_ice_restarts_.end();
5223}
5224
Steve Anton75737c02017-11-06 18:37:175225bool PeerConnection::NeedsIceRestart(const std::string& content_name) const {
5226 return transport_controller_->NeedsIceRestart(content_name);
5227}
5228
5229void PeerConnection::OnCertificateReady(
5230 const rtc::scoped_refptr<rtc::RTCCertificate>& certificate) {
5231 transport_controller_->SetLocalCertificate(certificate);
5232}
5233
5234void PeerConnection::OnDtlsSrtpSetupFailure(cricket::BaseChannel*, bool rtcp) {
Steve Antonf8470812017-12-04 18:46:215235 SetSessionError(SessionError::kTransport,
5236 rtcp ? kDtlsSrtpSetupFailureRtcp : kDtlsSrtpSetupFailureRtp);
Steve Anton75737c02017-11-06 18:37:175237}
5238
5239void PeerConnection::OnTransportControllerConnectionState(
5240 cricket::IceConnectionState state) {
5241 switch (state) {
5242 case cricket::kIceConnectionConnecting:
5243 // If the current state is Connected or Completed, then there were
5244 // writable channels but now there are not, so the next state must
5245 // be Disconnected.
5246 // kIceConnectionConnecting is currently used as the default,
5247 // un-connected state by the TransportController, so its only use is
5248 // detecting disconnections.
5249 if (ice_connection_state_ ==
5250 PeerConnectionInterface::kIceConnectionConnected ||
5251 ice_connection_state_ ==
5252 PeerConnectionInterface::kIceConnectionCompleted) {
5253 SetIceConnectionState(
5254 PeerConnectionInterface::kIceConnectionDisconnected);
5255 }
5256 break;
5257 case cricket::kIceConnectionFailed:
5258 SetIceConnectionState(PeerConnectionInterface::kIceConnectionFailed);
5259 break;
5260 case cricket::kIceConnectionConnected:
Mirko Bonadei675513b2017-11-09 10:09:255261 RTC_LOG(LS_INFO) << "Changing to ICE connected state because "
Jonas Olsson45cc8902018-02-13 09:37:075262 "all transports are writable.";
Steve Anton75737c02017-11-06 18:37:175263 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
Harald Alvestrand8ebba742018-05-31 12:00:345264 NoteUsageEvent(UsageEvent::ICE_STATE_CONNECTED);
Steve Anton75737c02017-11-06 18:37:175265 break;
5266 case cricket::kIceConnectionCompleted:
Mirko Bonadei675513b2017-11-09 10:09:255267 RTC_LOG(LS_INFO) << "Changing to ICE completed state because "
Jonas Olsson45cc8902018-02-13 09:37:075268 "all transports are complete.";
Steve Anton75737c02017-11-06 18:37:175269 if (ice_connection_state_ !=
5270 PeerConnectionInterface::kIceConnectionConnected) {
5271 // If jumping directly from "checking" to "connected",
5272 // signal "connected" first.
5273 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
5274 }
5275 SetIceConnectionState(PeerConnectionInterface::kIceConnectionCompleted);
Harald Alvestrand8ebba742018-05-31 12:00:345276 NoteUsageEvent(UsageEvent::ICE_STATE_CONNECTED);
Steve Anton75737c02017-11-06 18:37:175277 if (metrics_observer()) {
5278 ReportTransportStats();
5279 }
5280 break;
5281 default:
5282 RTC_NOTREACHED();
5283 }
5284}
5285
5286void PeerConnection::OnTransportControllerCandidatesGathered(
5287 const std::string& transport_name,
5288 const cricket::Candidates& candidates) {
5289 RTC_DCHECK(signaling_thread()->IsCurrent());
5290 int sdp_mline_index;
5291 if (!GetLocalCandidateMediaIndex(transport_name, &sdp_mline_index)) {
Mirko Bonadei675513b2017-11-09 10:09:255292 RTC_LOG(LS_ERROR)
5293 << "OnTransportControllerCandidatesGathered: content name "
5294 << transport_name << " not found";
Steve Anton75737c02017-11-06 18:37:175295 return;
5296 }
5297
5298 for (cricket::Candidates::const_iterator citer = candidates.begin();
5299 citer != candidates.end(); ++citer) {
5300 // Use transport_name as the candidate media id.
5301 std::unique_ptr<JsepIceCandidate> candidate(
5302 new JsepIceCandidate(transport_name, sdp_mline_index, *citer));
5303 if (local_description()) {
5304 mutable_local_description()->AddCandidate(candidate.get());
5305 }
5306 OnIceCandidate(std::move(candidate));
5307 }
5308}
5309
5310void PeerConnection::OnTransportControllerCandidatesRemoved(
5311 const std::vector<cricket::Candidate>& candidates) {
5312 RTC_DCHECK(signaling_thread()->IsCurrent());
5313 // Sanity check.
5314 for (const cricket::Candidate& candidate : candidates) {
5315 if (candidate.transport_name().empty()) {
Mirko Bonadei675513b2017-11-09 10:09:255316 RTC_LOG(LS_ERROR) << "OnTransportControllerCandidatesRemoved: "
Jonas Olsson45cc8902018-02-13 09:37:075317 "empty content name in candidate "
Mirko Bonadei675513b2017-11-09 10:09:255318 << candidate.ToString();
Steve Anton75737c02017-11-06 18:37:175319 return;
5320 }
5321 }
5322
5323 if (local_description()) {
5324 mutable_local_description()->RemoveCandidates(candidates);
5325 }
5326 OnIceCandidatesRemoved(candidates);
5327}
5328
5329void PeerConnection::OnTransportControllerDtlsHandshakeError(
5330 rtc::SSLHandshakeError error) {
5331 if (metrics_observer()) {
5332 metrics_observer()->IncrementEnumCounter(
5333 webrtc::kEnumCounterDtlsHandshakeError, static_cast<int>(error),
5334 static_cast<int>(rtc::SSLHandshakeError::MAX_VALUE));
5335 }
5336}
5337
Steve Antoned10bd92017-12-05 18:52:595338void PeerConnection::EnableSending() {
5339 for (auto transceiver : transceivers_) {
5340 cricket::BaseChannel* channel = transceiver->internal()->channel();
5341 if (channel && !channel->enabled()) {
5342 channel->Enable(true);
5343 }
Steve Anton75737c02017-11-06 18:37:175344 }
5345
Steve Anton4171afb2017-11-20 18:20:225346 if (rtp_data_channel_ && !rtp_data_channel_->enabled()) {
Steve Anton75737c02017-11-06 18:37:175347 rtp_data_channel_->Enable(true);
Steve Anton4171afb2017-11-20 18:20:225348 }
Steve Anton75737c02017-11-06 18:37:175349}
5350
5351// Returns the media index for a local ice candidate given the content name.
5352bool PeerConnection::GetLocalCandidateMediaIndex(
5353 const std::string& content_name,
5354 int* sdp_mline_index) {
5355 if (!local_description() || !sdp_mline_index) {
5356 return false;
5357 }
5358
5359 bool content_found = false;
5360 const ContentInfos& contents = local_description()->description()->contents();
5361 for (size_t index = 0; index < contents.size(); ++index) {
5362 if (contents[index].name == content_name) {
5363 *sdp_mline_index = static_cast<int>(index);
5364 content_found = true;
5365 break;
5366 }
5367 }
5368 return content_found;
5369}
5370
5371bool PeerConnection::UseCandidatesInSessionDescription(
5372 const SessionDescriptionInterface* remote_desc) {
5373 if (!remote_desc) {
5374 return true;
5375 }
5376 bool ret = true;
5377
5378 for (size_t m = 0; m < remote_desc->number_of_mediasections(); ++m) {
5379 const IceCandidateCollection* candidates = remote_desc->candidates(m);
5380 for (size_t n = 0; n < candidates->count(); ++n) {
5381 const IceCandidateInterface* candidate = candidates->at(n);
5382 bool valid = false;
5383 if (!ReadyToUseRemoteCandidate(candidate, remote_desc, &valid)) {
5384 if (valid) {
Mirko Bonadei675513b2017-11-09 10:09:255385 RTC_LOG(LS_INFO)
5386 << "UseCandidatesInSessionDescription: Not ready to use "
Jonas Olsson45cc8902018-02-13 09:37:075387 "candidate.";
Steve Anton75737c02017-11-06 18:37:175388 }
5389 continue;
5390 }
5391 ret = UseCandidate(candidate);
5392 if (!ret) {
5393 break;
5394 }
5395 }
5396 }
5397 return ret;
5398}
5399
5400bool PeerConnection::UseCandidate(const IceCandidateInterface* candidate) {
5401 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
5402 size_t remote_content_size =
5403 remote_description()->description()->contents().size();
5404 if (mediacontent_index >= remote_content_size) {
Mirko Bonadei675513b2017-11-09 10:09:255405 RTC_LOG(LS_ERROR) << "UseCandidate: Invalid candidate media index.";
Steve Anton75737c02017-11-06 18:37:175406 return false;
5407 }
5408
5409 cricket::ContentInfo content =
5410 remote_description()->description()->contents()[mediacontent_index];
5411 std::vector<cricket::Candidate> candidates;
5412 candidates.push_back(candidate->candidate());
5413 // Invoking BaseSession method to handle remote candidates.
Zhi Huange830e682018-03-30 17:48:355414 RTCError error =
5415 transport_controller_->AddRemoteCandidates(content.name, candidates);
Henrik Boström5d8f8fa2018-04-13 15:22:505416 if (error.ok()) {
5417 // Candidates successfully submitted for checking.
5418 if (ice_connection_state_ == PeerConnectionInterface::kIceConnectionNew ||
5419 ice_connection_state_ ==
5420 PeerConnectionInterface::kIceConnectionDisconnected) {
5421 // If state is New, then the session has just gotten its first remote ICE
5422 // candidates, so go to Checking.
5423 // If state is Disconnected, the session is re-using old candidates or
5424 // receiving additional ones, so go to Checking.
5425 // If state is Connected, stay Connected.
5426 // TODO(bemasc): If state is Connected, and the new candidates are for a
5427 // newly added transport, then the state actually _should_ move to
5428 // checking. Add a way to distinguish that case.
5429 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
5430 }
5431 // TODO(bemasc): If state is Completed, go back to Connected.
5432 } else if (error.message()) {
Zhi Huange830e682018-03-30 17:48:355433 RTC_LOG(LS_WARNING) << error.message();
Steve Anton75737c02017-11-06 18:37:175434 }
5435 return true;
5436}
5437
5438void PeerConnection::RemoveUnusedChannels(const SessionDescription* desc) {
Steve Anton75737c02017-11-06 18:37:175439 // Destroy video channel first since it may have a pointer to the
5440 // voice channel.
5441 const cricket::ContentInfo* video_info = cricket::GetFirstVideoContent(desc);
Steve Anton6fec8802017-12-04 18:37:295442 if (!video_info || video_info->rejected) {
5443 DestroyTransceiverChannel(GetVideoTransceiver());
Steve Anton75737c02017-11-06 18:37:175444 }
5445
Steve Anton6fec8802017-12-04 18:37:295446 const cricket::ContentInfo* audio_info = cricket::GetFirstAudioContent(desc);
5447 if (!audio_info || audio_info->rejected) {
5448 DestroyTransceiverChannel(GetAudioTransceiver());
Steve Anton75737c02017-11-06 18:37:175449 }
5450
5451 const cricket::ContentInfo* data_info = cricket::GetFirstDataContent(desc);
5452 if (!data_info || data_info->rejected) {
Steve Anton6fec8802017-12-04 18:37:295453 DestroyDataChannel();
Steve Anton75737c02017-11-06 18:37:175454 }
5455}
5456
Steve Antondcc3c022017-12-23 00:02:545457RTCErrorOr<const cricket::ContentGroup*> PeerConnection::GetEarlyBundleGroup(
5458 const SessionDescription& desc) const {
Steve Anton75737c02017-11-06 18:37:175459 const cricket::ContentGroup* bundle_group = nullptr;
5460 if (configuration_.bundle_policy ==
5461 PeerConnectionInterface::kBundlePolicyMaxBundle) {
Steve Antondcc3c022017-12-23 00:02:545462 bundle_group = desc.GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton75737c02017-11-06 18:37:175463 if (!bundle_group) {
Steve Anton8a006912017-12-04 23:25:565464 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5465 "max-bundle configured but session description "
5466 "has no BUNDLE group");
Steve Anton75737c02017-11-06 18:37:175467 }
5468 }
Steve Antondcc3c022017-12-23 00:02:545469 return std::move(bundle_group);
5470}
5471
5472RTCError PeerConnection::CreateChannels(const SessionDescription& desc) {
Zhi Huange830e682018-03-30 17:48:355473 // Creating the media channels. Transports should already have been created
5474 // at this point.
Steve Antondcc3c022017-12-23 00:02:545475 const cricket::ContentInfo* voice = cricket::GetFirstAudioContent(&desc);
Steve Antoneda6ccd2017-12-04 18:21:555476 if (voice && !voice->rejected &&
5477 !GetAudioTransceiver()->internal()->channel()) {
Zhi Huange830e682018-03-30 17:48:355478 cricket::VoiceChannel* voice_channel = CreateVoiceChannel(voice->name);
Steve Antoneda6ccd2017-12-04 18:21:555479 if (!voice_channel) {
Steve Anton8a006912017-12-04 23:25:565480 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5481 "Failed to create voice channel.");
Steve Antoneda6ccd2017-12-04 18:21:555482 }
5483 GetAudioTransceiver()->internal()->SetChannel(voice_channel);
5484 }
5485
Steve Antondcc3c022017-12-23 00:02:545486 const cricket::ContentInfo* video = cricket::GetFirstVideoContent(&desc);
Steve Antoneda6ccd2017-12-04 18:21:555487 if (video && !video->rejected &&
5488 !GetVideoTransceiver()->internal()->channel()) {
Zhi Huange830e682018-03-30 17:48:355489 cricket::VideoChannel* video_channel = CreateVideoChannel(video->name);
Steve Antoneda6ccd2017-12-04 18:21:555490 if (!video_channel) {
Steve Anton8a006912017-12-04 23:25:565491 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5492 "Failed to create video channel.");
Steve Anton75737c02017-11-06 18:37:175493 }
Steve Antoneda6ccd2017-12-04 18:21:555494 GetVideoTransceiver()->internal()->SetChannel(video_channel);
Steve Anton75737c02017-11-06 18:37:175495 }
5496
Steve Antondcc3c022017-12-23 00:02:545497 const cricket::ContentInfo* data = cricket::GetFirstDataContent(&desc);
Steve Anton75737c02017-11-06 18:37:175498 if (data_channel_type_ != cricket::DCT_NONE && data && !data->rejected &&
5499 !rtp_data_channel_ && !sctp_transport_) {
Zhi Huange830e682018-03-30 17:48:355500 if (!CreateDataChannel(data->name)) {
Steve Anton8a006912017-12-04 23:25:565501 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5502 "Failed to create data channel.");
Steve Anton75737c02017-11-06 18:37:175503 }
5504 }
5505
Steve Anton8a006912017-12-04 23:25:565506 return RTCError::OK();
Steve Anton75737c02017-11-06 18:37:175507}
5508
Steve Anton4171afb2017-11-20 18:20:225509// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 18:21:555510cricket::VoiceChannel* PeerConnection::CreateVoiceChannel(
Zhi Huange830e682018-03-30 17:48:355511 const std::string& mid) {
5512 RtpTransportInternal* rtp_transport =
5513 transport_controller_->GetRtpTransport(mid);
5514 RTC_DCHECK(rtp_transport);
Steve Anton75737c02017-11-06 18:37:175515 cricket::VoiceChannel* voice_channel = channel_manager()->CreateVoiceChannel(
Zhi Huange830e682018-03-30 17:48:355516 call_.get(), configuration_.media_config, rtp_transport,
5517 signaling_thread(), mid, SrtpRequired(),
5518 factory_->options().crypto_options, audio_options_);
Steve Anton75737c02017-11-06 18:37:175519 if (!voice_channel) {
Steve Antoneda6ccd2017-12-04 18:21:555520 return nullptr;
Steve Anton75737c02017-11-06 18:37:175521 }
Steve Anton75737c02017-11-06 18:37:175522 voice_channel->SignalDtlsSrtpSetupFailure.connect(
5523 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 18:37:175524 voice_channel->SignalSentPacket.connect(this,
5525 &PeerConnection::OnSentPacket_w);
Zhi Huange830e682018-03-30 17:48:355526 voice_channel->SetRtpTransport(rtp_transport);
Steve Antondb67ba12018-03-20 00:41:425527 if (uma_observer_) {
5528 voice_channel->SetMetricsObserver(uma_observer_);
5529 }
Steve Anton4171afb2017-11-20 18:20:225530
Steve Antoneda6ccd2017-12-04 18:21:555531 return voice_channel;
Steve Anton75737c02017-11-06 18:37:175532}
5533
Steve Anton4171afb2017-11-20 18:20:225534// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 18:21:555535cricket::VideoChannel* PeerConnection::CreateVideoChannel(
Zhi Huange830e682018-03-30 17:48:355536 const std::string& mid) {
5537 RtpTransportInternal* rtp_transport =
5538 transport_controller_->GetRtpTransport(mid);
5539 RTC_DCHECK(rtp_transport);
Steve Anton75737c02017-11-06 18:37:175540 cricket::VideoChannel* video_channel = channel_manager()->CreateVideoChannel(
Zhi Huange830e682018-03-30 17:48:355541 call_.get(), configuration_.media_config, rtp_transport,
5542 signaling_thread(), mid, SrtpRequired(),
5543 factory_->options().crypto_options, video_options_);
Steve Anton75737c02017-11-06 18:37:175544 if (!video_channel) {
Steve Antoneda6ccd2017-12-04 18:21:555545 return nullptr;
Steve Anton75737c02017-11-06 18:37:175546 }
Steve Anton75737c02017-11-06 18:37:175547 video_channel->SignalDtlsSrtpSetupFailure.connect(
5548 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 18:37:175549 video_channel->SignalSentPacket.connect(this,
5550 &PeerConnection::OnSentPacket_w);
Zhi Huange830e682018-03-30 17:48:355551 video_channel->SetRtpTransport(rtp_transport);
Steve Antondb67ba12018-03-20 00:41:425552 if (uma_observer_) {
5553 video_channel->SetMetricsObserver(uma_observer_);
5554 }
Steve Anton4171afb2017-11-20 18:20:225555
Steve Antoneda6ccd2017-12-04 18:21:555556 return video_channel;
Steve Anton75737c02017-11-06 18:37:175557}
5558
Zhi Huange830e682018-03-30 17:48:355559bool PeerConnection::CreateDataChannel(const std::string& mid) {
Steve Anton75737c02017-11-06 18:37:175560 bool sctp = (data_channel_type_ == cricket::DCT_SCTP);
5561 if (sctp) {
5562 if (!sctp_factory_) {
Mirko Bonadei675513b2017-11-09 10:09:255563 RTC_LOG(LS_ERROR)
Steve Anton75737c02017-11-06 18:37:175564 << "Trying to create SCTP transport, but didn't compile with "
5565 "SCTP support (HAVE_SCTP)";
5566 return false;
5567 }
5568 if (!network_thread()->Invoke<bool>(
Zhi Huange830e682018-03-30 17:48:355569 RTC_FROM_HERE,
5570 rtc::Bind(&PeerConnection::CreateSctpTransport_n, this, mid))) {
Steve Anton75737c02017-11-06 18:37:175571 return false;
5572 }
Steve Antoneda6ccd2017-12-04 18:21:555573 for (const auto& channel : sctp_data_channels_) {
5574 channel->OnTransportChannelCreated();
5575 }
Steve Anton75737c02017-11-06 18:37:175576 } else {
Zhi Huange830e682018-03-30 17:48:355577 RtpTransportInternal* rtp_transport =
5578 transport_controller_->GetRtpTransport(mid);
5579 RTC_DCHECK(rtp_transport);
Steve Anton75737c02017-11-06 18:37:175580 rtp_data_channel_ = channel_manager()->CreateRtpDataChannel(
Zhi Huange830e682018-03-30 17:48:355581 configuration_.media_config, rtp_transport, signaling_thread(), mid,
5582 SrtpRequired(), factory_->options().crypto_options);
Steve Anton75737c02017-11-06 18:37:175583 if (!rtp_data_channel_) {
Steve Anton75737c02017-11-06 18:37:175584 return false;
5585 }
Steve Anton75737c02017-11-06 18:37:175586 rtp_data_channel_->SignalDtlsSrtpSetupFailure.connect(
5587 this, &PeerConnection::OnDtlsSrtpSetupFailure);
5588 rtp_data_channel_->SignalSentPacket.connect(
5589 this, &PeerConnection::OnSentPacket_w);
Zhi Huange830e682018-03-30 17:48:355590 rtp_data_channel_->SetRtpTransport(rtp_transport);
Steve Antondb67ba12018-03-20 00:41:425591 if (uma_observer_) {
5592 rtp_data_channel_->SetMetricsObserver(uma_observer_);
5593 }
Steve Anton75737c02017-11-06 18:37:175594 }
5595
Steve Anton75737c02017-11-06 18:37:175596 return true;
5597}
5598
5599Call::Stats PeerConnection::GetCallStats() {
5600 if (!worker_thread()->IsCurrent()) {
5601 return worker_thread()->Invoke<Call::Stats>(
5602 RTC_FROM_HERE, rtc::Bind(&PeerConnection::GetCallStats, this));
5603 }
5604 if (call_) {
5605 return call_->GetStats();
5606 } else {
5607 return Call::Stats();
5608 }
5609}
5610
Zhi Huange830e682018-03-30 17:48:355611bool PeerConnection::CreateSctpTransport_n(const std::string& mid) {
Steve Anton75737c02017-11-06 18:37:175612 RTC_DCHECK(network_thread()->IsCurrent());
5613 RTC_DCHECK(sctp_factory_);
Zhi Huang644fde42018-04-03 02:16:265614 cricket::DtlsTransportInternal* dtls_transport =
Zhi Huange830e682018-03-30 17:48:355615 transport_controller_->GetDtlsTransport(mid);
Zhi Huang644fde42018-04-03 02:16:265616 RTC_DCHECK(dtls_transport);
5617 sctp_transport_ = sctp_factory_->CreateSctpTransport(dtls_transport);
Steve Anton75737c02017-11-06 18:37:175618 RTC_DCHECK(sctp_transport_);
5619 sctp_invoker_.reset(new rtc::AsyncInvoker());
5620 sctp_transport_->SignalReadyToSendData.connect(
5621 this, &PeerConnection::OnSctpTransportReadyToSendData_n);
5622 sctp_transport_->SignalDataReceived.connect(
5623 this, &PeerConnection::OnSctpTransportDataReceived_n);
Taylor Brandstettercdd05f02018-05-31 20:23:325624 // TODO(deadbeef): All we do here is AsyncInvoke to fire the signal on
5625 // another thread. Would be nice if there was a helper class similar to
5626 // sigslot::repeater that did this for us, eliminating a bunch of boilerplate
5627 // code.
5628 sctp_transport_->SignalClosingProcedureStartedRemotely.connect(
5629 this, &PeerConnection::OnSctpClosingProcedureStartedRemotely_n);
5630 sctp_transport_->SignalClosingProcedureComplete.connect(
5631 this, &PeerConnection::OnSctpClosingProcedureComplete_n);
Zhi Huange830e682018-03-30 17:48:355632 sctp_mid_ = mid;
Zhi Huang644fde42018-04-03 02:16:265633 sctp_transport_->SetDtlsTransport(dtls_transport);
Zhi Huange830e682018-03-30 17:48:355634 return true;
Steve Anton75737c02017-11-06 18:37:175635}
5636
5637void PeerConnection::DestroySctpTransport_n() {
5638 RTC_DCHECK(network_thread()->IsCurrent());
5639 sctp_transport_.reset(nullptr);
Zhi Huange830e682018-03-30 17:48:355640 sctp_mid_.reset();
Steve Anton75737c02017-11-06 18:37:175641 sctp_invoker_.reset(nullptr);
5642 sctp_ready_to_send_data_ = false;
5643}
5644
5645void PeerConnection::OnSctpTransportReadyToSendData_n() {
5646 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5647 RTC_DCHECK(network_thread()->IsCurrent());
5648 // Note: Cannot use rtc::Bind here because it will grab a reference to
5649 // PeerConnection and potentially cause PeerConnection to live longer than
5650 // expected. It is safe not to grab a reference since the sctp_invoker_ will
5651 // be destroyed before PeerConnection is destroyed, and at that point all
5652 // pending tasks will be cleared.
5653 sctp_invoker_->AsyncInvoke<void>(RTC_FROM_HERE, signaling_thread(), [this] {
5654 OnSctpTransportReadyToSendData_s(true);
5655 });
5656}
5657
5658void PeerConnection::OnSctpTransportReadyToSendData_s(bool ready) {
5659 RTC_DCHECK(signaling_thread()->IsCurrent());
5660 sctp_ready_to_send_data_ = ready;
5661 SignalSctpReadyToSendData(ready);
5662}
5663
5664void PeerConnection::OnSctpTransportDataReceived_n(
5665 const cricket::ReceiveDataParams& params,
5666 const rtc::CopyOnWriteBuffer& payload) {
5667 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5668 RTC_DCHECK(network_thread()->IsCurrent());
5669 // Note: Cannot use rtc::Bind here because it will grab a reference to
5670 // PeerConnection and potentially cause PeerConnection to live longer than
5671 // expected. It is safe not to grab a reference since the sctp_invoker_ will
5672 // be destroyed before PeerConnection is destroyed, and at that point all
5673 // pending tasks will be cleared.
5674 sctp_invoker_->AsyncInvoke<void>(
5675 RTC_FROM_HERE, signaling_thread(), [this, params, payload] {
5676 OnSctpTransportDataReceived_s(params, payload);
5677 });
5678}
5679
5680void PeerConnection::OnSctpTransportDataReceived_s(
5681 const cricket::ReceiveDataParams& params,
5682 const rtc::CopyOnWriteBuffer& payload) {
5683 RTC_DCHECK(signaling_thread()->IsCurrent());
5684 if (params.type == cricket::DMT_CONTROL && IsOpenMessage(payload)) {
5685 // Received OPEN message; parse and signal that a new data channel should
5686 // be created.
5687 std::string label;
5688 InternalDataChannelInit config;
5689 config.id = params.ssrc;
5690 if (!ParseDataChannelOpenMessage(payload, &label, &config)) {
Mirko Bonadei675513b2017-11-09 10:09:255691 RTC_LOG(LS_WARNING) << "Failed to parse the OPEN message for sid "
5692 << params.ssrc;
Steve Anton75737c02017-11-06 18:37:175693 return;
5694 }
5695 config.open_handshake_role = InternalDataChannelInit::kAcker;
5696 OnDataChannelOpenMessage(label, config);
5697 } else {
5698 // Otherwise just forward the signal.
5699 SignalSctpDataReceived(params, payload);
5700 }
5701}
5702
Taylor Brandstettercdd05f02018-05-31 20:23:325703void PeerConnection::OnSctpClosingProcedureStartedRemotely_n(int sid) {
Steve Anton75737c02017-11-06 18:37:175704 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5705 RTC_DCHECK(network_thread()->IsCurrent());
5706 sctp_invoker_->AsyncInvoke<void>(
5707 RTC_FROM_HERE, signaling_thread(),
5708 rtc::Bind(&sigslot::signal1<int>::operator(),
Taylor Brandstettercdd05f02018-05-31 20:23:325709 &SignalSctpClosingProcedureStartedRemotely, sid));
5710}
5711
5712void PeerConnection::OnSctpClosingProcedureComplete_n(int sid) {
5713 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5714 RTC_DCHECK(network_thread()->IsCurrent());
5715 sctp_invoker_->AsyncInvoke<void>(
5716 RTC_FROM_HERE, signaling_thread(),
5717 rtc::Bind(&sigslot::signal1<int>::operator(),
5718 &SignalSctpClosingProcedureComplete, sid));
Steve Anton75737c02017-11-06 18:37:175719}
5720
5721// Returns false if bundle is enabled and rtcp_mux is disabled.
5722bool PeerConnection::ValidateBundleSettings(const SessionDescription* desc) {
5723 bool bundle_enabled = desc->HasGroup(cricket::GROUP_TYPE_BUNDLE);
5724 if (!bundle_enabled)
5725 return true;
5726
5727 const cricket::ContentGroup* bundle_group =
5728 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
5729 RTC_DCHECK(bundle_group != NULL);
5730
5731 const cricket::ContentInfos& contents = desc->contents();
5732 for (cricket::ContentInfos::const_iterator citer = contents.begin();
5733 citer != contents.end(); ++citer) {
5734 const cricket::ContentInfo* content = (&*citer);
5735 RTC_DCHECK(content != NULL);
5736 if (bundle_group->HasContentName(content->name) && !content->rejected &&
Steve Anton5adfafd2017-12-21 00:34:005737 content->type == MediaProtocolType::kRtp) {
Steve Anton75737c02017-11-06 18:37:175738 if (!HasRtcpMuxEnabled(content))
5739 return false;
5740 }
5741 }
5742 // RTCP-MUX is enabled in all the contents.
5743 return true;
5744}
5745
5746bool PeerConnection::HasRtcpMuxEnabled(const cricket::ContentInfo* content) {
Steve Antonb1c1de12017-12-21 23:14:305747 return content->media_description()->rtcp_mux();
Steve Anton75737c02017-11-06 18:37:175748}
5749
Steve Anton8a006912017-12-04 23:25:565750RTCError PeerConnection::ValidateSessionDescription(
Steve Anton75737c02017-11-06 18:37:175751 const SessionDescriptionInterface* sdesc,
Steve Anton8a006912017-12-04 23:25:565752 cricket::ContentSource source) {
Steve Antonf8470812017-12-04 18:46:215753 if (session_error() != SessionError::kNone) {
Steve Anton8a006912017-12-04 23:25:565754 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
Steve Anton75737c02017-11-06 18:37:175755 }
5756
5757 if (!sdesc || !sdesc->description()) {
Steve Anton8a006912017-12-04 23:25:565758 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidSdp);
Steve Anton75737c02017-11-06 18:37:175759 }
5760
Steve Anton3828c062017-12-06 18:34:515761 SdpType type = sdesc->GetType();
5762 if ((source == cricket::CS_LOCAL && !ExpectSetLocalDescription(type)) ||
5763 (source == cricket::CS_REMOTE && !ExpectSetRemoteDescription(type))) {
Steve Anton8a006912017-12-04 23:25:565764 LOG_AND_RETURN_ERROR(
Harald Alvestrand5081c0c2018-03-09 14:18:035765 RTCErrorType::INVALID_STATE,
Steve Anton8a006912017-12-04 23:25:565766 "Called in wrong state: " + GetSignalingStateString(signaling_state()));
Steve Anton75737c02017-11-06 18:37:175767 }
5768
5769 // Verify crypto settings.
5770 std::string crypto_error;
Steve Anton8a006912017-12-04 23:25:565771 if (webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED ||
5772 dtls_enabled_) {
Harald Alvestrand194939b2018-01-24 15:04:135773 RTCError crypto_error =
5774 VerifyCrypto(sdesc->description(), dtls_enabled_, uma_observer_);
Steve Anton8a006912017-12-04 23:25:565775 if (!crypto_error.ok()) {
5776 return crypto_error;
5777 }
Steve Anton75737c02017-11-06 18:37:175778 }
5779
5780 // Verify ice-ufrag and ice-pwd.
5781 if (!VerifyIceUfragPwdPresent(sdesc->description())) {
Steve Anton8a006912017-12-04 23:25:565782 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5783 kSdpWithoutIceUfragPwd);
Steve Anton75737c02017-11-06 18:37:175784 }
5785
5786 if (!ValidateBundleSettings(sdesc->description())) {
Steve Anton8a006912017-12-04 23:25:565787 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5788 kBundleWithoutRtcpMux);
Steve Anton75737c02017-11-06 18:37:175789 }
5790
5791 // TODO(skvlad): When the local rtcp-mux policy is Require, reject any
5792 // m-lines that do not rtcp-mux enabled.
5793
5794 // Verify m-lines in Answer when compared against Offer.
Steve Anton3828c062017-12-06 18:34:515795 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Seth Hampsonae8a90a2018-02-13 23:33:485796 // With an answer we want to compare the new answer session description with
5797 // the offer's session description from the current negotiation.
Steve Anton75737c02017-11-06 18:37:175798 const cricket::SessionDescription* offer_desc =
5799 (source == cricket::CS_LOCAL) ? remote_description()->description()
5800 : local_description()->description();
Seth Hampsonae8a90a2018-02-13 23:33:485801 if (!MediaSectionsHaveSameCount(*offer_desc, *sdesc->description()) ||
5802 !MediaSectionsInSameOrder(*offer_desc, nullptr, *sdesc->description(),
5803 type)) {
Steve Anton8a006912017-12-04 23:25:565804 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5805 kMlineMismatchInAnswer);
Steve Anton75737c02017-11-06 18:37:175806 }
5807 } else {
Steve Anton75737c02017-11-06 18:37:175808 // The re-offers should respect the order of m= sections in current
5809 // description. See RFC3264 Section 8 paragraph 4 for more details.
Seth Hampsonae8a90a2018-02-13 23:33:485810 // With a re-offer, either the current local or current remote descriptions
5811 // could be the most up to date, so we would like to check against both of
5812 // them if they exist. It could be the case that one of them has a 0 port
5813 // for a media section, but the other does not. This is important to check
5814 // against in the case that we are recycling an m= section.
5815 const cricket::SessionDescription* current_desc = nullptr;
5816 const cricket::SessionDescription* secondary_current_desc = nullptr;
5817 if (local_description()) {
5818 current_desc = local_description()->description();
5819 if (remote_description()) {
5820 secondary_current_desc = remote_description()->description();
5821 }
5822 } else if (remote_description()) {
5823 current_desc = remote_description()->description();
5824 }
Steve Anton75737c02017-11-06 18:37:175825 if (current_desc &&
Seth Hampsonae8a90a2018-02-13 23:33:485826 !MediaSectionsInSameOrder(*current_desc, secondary_current_desc,
5827 *sdesc->description(), type)) {
Steve Anton8a006912017-12-04 23:25:565828 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5829 kMlineMismatchInSubsequentOffer);
Steve Anton75737c02017-11-06 18:37:175830 }
5831 }
5832
Steve Antonba42e992018-04-09 21:10:015833 if (IsUnifiedPlan()) {
5834 // Ensure that each audio and video media section has at most one
5835 // "StreamParams". This will return an error if receiving a session
5836 // description from a "Plan B" endpoint which adds multiple tracks of the
5837 // same type. With Unified Plan, there can only be at most one track per
5838 // media section.
5839 for (const ContentInfo& content : sdesc->description()->contents()) {
5840 const MediaContentDescription& desc = *content.description;
5841 if ((desc.type() == cricket::MEDIA_TYPE_AUDIO ||
5842 desc.type() == cricket::MEDIA_TYPE_VIDEO) &&
5843 desc.streams().size() > 1u) {
5844 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5845 "Media section has more than one track specified "
5846 "with a=ssrc lines which is not supported with "
5847 "Unified Plan.");
5848 }
5849 }
5850 }
5851
Steve Anton8a006912017-12-04 23:25:565852 return RTCError::OK();
Steve Anton75737c02017-11-06 18:37:175853}
5854
Steve Anton3828c062017-12-06 18:34:515855bool PeerConnection::ExpectSetLocalDescription(SdpType type) {
Steve Anton75737c02017-11-06 18:37:175856 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 18:34:515857 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 18:37:175858 return (state == PeerConnectionInterface::kStable) ||
5859 (state == PeerConnectionInterface::kHaveLocalOffer);
Steve Anton20393062017-12-05 00:24:525860 } else {
Steve Anton3828c062017-12-06 18:34:515861 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 18:37:175862 return (state == PeerConnectionInterface::kHaveRemoteOffer) ||
5863 (state == PeerConnectionInterface::kHaveLocalPrAnswer);
5864 }
5865}
5866
Steve Anton3828c062017-12-06 18:34:515867bool PeerConnection::ExpectSetRemoteDescription(SdpType type) {
Steve Anton75737c02017-11-06 18:37:175868 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 18:34:515869 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 18:37:175870 return (state == PeerConnectionInterface::kStable) ||
5871 (state == PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton20393062017-12-05 00:24:525872 } else {
Steve Anton3828c062017-12-06 18:34:515873 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 18:37:175874 return (state == PeerConnectionInterface::kHaveLocalOffer) ||
5875 (state == PeerConnectionInterface::kHaveRemotePrAnswer);
5876 }
5877}
5878
Steve Antonf8470812017-12-04 18:46:215879const char* PeerConnection::SessionErrorToString(SessionError error) const {
5880 switch (error) {
5881 case SessionError::kNone:
5882 return "ERROR_NONE";
5883 case SessionError::kContent:
5884 return "ERROR_CONTENT";
5885 case SessionError::kTransport:
5886 return "ERROR_TRANSPORT";
5887 }
5888 RTC_NOTREACHED();
5889 return "";
5890}
5891
Steve Anton75737c02017-11-06 18:37:175892std::string PeerConnection::GetSessionErrorMsg() {
5893 std::ostringstream desc;
Steve Antonf8470812017-12-04 18:46:215894 desc << kSessionError << SessionErrorToString(session_error()) << ". ";
5895 desc << kSessionErrorDesc << session_error_desc() << ".";
Steve Anton75737c02017-11-06 18:37:175896 return desc.str();
5897}
5898
Steve Anton8e20f172018-03-06 18:55:045899void PeerConnection::ReportSdpFormatReceived(
5900 const SessionDescriptionInterface& remote_offer) {
5901 if (!uma_observer_) {
5902 return;
5903 }
5904 int num_audio_mlines = 0;
5905 int num_video_mlines = 0;
5906 int num_audio_tracks = 0;
5907 int num_video_tracks = 0;
5908 for (const ContentInfo& content : remote_offer.description()->contents()) {
5909 cricket::MediaType media_type = content.media_description()->type();
5910 int num_tracks = std::max(
5911 1, static_cast<int>(content.media_description()->streams().size()));
5912 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
5913 num_audio_mlines += 1;
5914 num_audio_tracks += num_tracks;
5915 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
5916 num_video_mlines += 1;
5917 num_video_tracks += num_tracks;
5918 }
5919 }
5920 SdpFormatReceived format = kSdpFormatReceivedNoTracks;
5921 if (num_audio_mlines > 1 || num_video_mlines > 1) {
5922 format = kSdpFormatReceivedComplexUnifiedPlan;
5923 } else if (num_audio_tracks > 1 || num_video_tracks > 1) {
5924 format = kSdpFormatReceivedComplexPlanB;
5925 } else if (num_audio_tracks > 0 || num_video_tracks > 0) {
5926 format = kSdpFormatReceivedSimple;
5927 }
5928 uma_observer_->IncrementEnumCounter(kEnumCounterSdpFormatReceived, format,
5929 kSdpFormatReceivedMax);
5930}
5931
Harald Alvestrand8ebba742018-05-31 12:00:345932void PeerConnection::NoteUsageEvent(UsageEvent event) {
5933 RTC_DCHECK_RUN_ON(signaling_thread());
5934 usage_event_accumulator_ |= static_cast<int>(event);
5935}
5936
5937void PeerConnection::ReportUsagePattern() const {
5938 RTC_DLOG(LS_INFO) << "Usage signature is " << usage_event_accumulator_;
5939 if (uma_observer_) {
5940 uma_observer_->IncrementSparseEnumCounter(kEnumCounterUsagePattern,
5941 usage_event_accumulator_);
5942 }
5943}
5944
Steve Anton0ffaaa22018-02-23 18:31:305945void PeerConnection::ReportNegotiatedSdpSemantics(
5946 const SessionDescriptionInterface& answer) {
5947 if (!uma_observer_) {
5948 return;
5949 }
5950 switch (answer.description()->msid_signaling()) {
5951 case 0:
5952 uma_observer_->IncrementEnumCounter(kEnumCounterSdpSemanticNegotiated,
5953 kSdpSemanticNegotiatedNone,
5954 kSdpSemanticNegotiatedMax);
5955 break;
5956 case cricket::kMsidSignalingMediaSection:
5957 uma_observer_->IncrementEnumCounter(kEnumCounterSdpSemanticNegotiated,
5958 kSdpSemanticNegotiatedUnifiedPlan,
5959 kSdpSemanticNegotiatedMax);
5960 break;
5961 case cricket::kMsidSignalingSsrcAttribute:
5962 uma_observer_->IncrementEnumCounter(kEnumCounterSdpSemanticNegotiated,
5963 kSdpSemanticNegotiatedPlanB,
5964 kSdpSemanticNegotiatedMax);
5965 break;
5966 case cricket::kMsidSignalingMediaSection |
5967 cricket::kMsidSignalingSsrcAttribute:
5968 uma_observer_->IncrementEnumCounter(kEnumCounterSdpSemanticNegotiated,
5969 kSdpSemanticNegotiatedMixed,
5970 kSdpSemanticNegotiatedMax);
5971 break;
5972 default:
5973 RTC_NOTREACHED();
5974 }
5975}
5976
Steve Anton75737c02017-11-06 18:37:175977// We need to check the local/remote description for the Transport instead of
5978// the session, because a new Transport added during renegotiation may have
5979// them unset while the session has them set from the previous negotiation.
5980// Not doing so may trigger the auto generation of transport description and
5981// mess up DTLS identity information, ICE credential, etc.
5982bool PeerConnection::ReadyToUseRemoteCandidate(
5983 const IceCandidateInterface* candidate,
5984 const SessionDescriptionInterface* remote_desc,
5985 bool* valid) {
5986 *valid = true;
5987
5988 const SessionDescriptionInterface* current_remote_desc =
5989 remote_desc ? remote_desc : remote_description();
5990
5991 if (!current_remote_desc) {
5992 return false;
5993 }
5994
5995 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
5996 size_t remote_content_size =
5997 current_remote_desc->description()->contents().size();
5998 if (mediacontent_index >= remote_content_size) {
Mirko Bonadei675513b2017-11-09 10:09:255999 RTC_LOG(LS_ERROR)
6000 << "ReadyToUseRemoteCandidate: Invalid candidate media index "
6001 << mediacontent_index;
Steve Anton75737c02017-11-06 18:37:176002
6003 *valid = false;
6004 return false;
6005 }
6006
6007 cricket::ContentInfo content =
6008 current_remote_desc->description()->contents()[mediacontent_index];
6009
6010 const std::string transport_name = GetTransportName(content.name);
6011 if (transport_name.empty()) {
6012 return false;
6013 }
Zhi Huange830e682018-03-30 17:48:356014 return true;
Steve Anton75737c02017-11-06 18:37:176015}
6016
6017bool PeerConnection::SrtpRequired() const {
6018 return dtls_enabled_ ||
6019 webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED;
6020}
6021
6022void PeerConnection::OnTransportControllerGatheringState(
6023 cricket::IceGatheringState state) {
6024 RTC_DCHECK(signaling_thread()->IsCurrent());
6025 if (state == cricket::kIceGatheringGathering) {
6026 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringGathering);
6027 } else if (state == cricket::kIceGatheringComplete) {
6028 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringComplete);
6029 }
6030}
6031
6032void PeerConnection::ReportTransportStats() {
Steve Antonc7b964c2018-02-01 22:39:456033 std::map<std::string, std::set<cricket::MediaType>>
6034 media_types_by_transport_name;
6035 for (auto transceiver : transceivers_) {
6036 if (transceiver->internal()->channel()) {
6037 const std::string& transport_name =
6038 transceiver->internal()->channel()->transport_name();
6039 media_types_by_transport_name[transport_name].insert(
Steve Anton69470252018-02-09 19:43:086040 transceiver->media_type());
Steve Antonc7b964c2018-02-01 22:39:456041 }
Steve Anton75737c02017-11-06 18:37:176042 }
6043 if (rtp_data_channel()) {
Steve Antonc7b964c2018-02-01 22:39:456044 media_types_by_transport_name[rtp_data_channel()->transport_name()].insert(
6045 cricket::MEDIA_TYPE_DATA);
Steve Anton75737c02017-11-06 18:37:176046 }
Zhi Huange830e682018-03-30 17:48:356047
6048 rtc::Optional<std::string> transport_name = sctp_transport_name();
6049 if (transport_name) {
6050 media_types_by_transport_name[*transport_name].insert(
Steve Antonc7b964c2018-02-01 22:39:456051 cricket::MEDIA_TYPE_DATA);
Steve Anton75737c02017-11-06 18:37:176052 }
Zhi Huange830e682018-03-30 17:48:356053
Steve Antonc7b964c2018-02-01 22:39:456054 for (const auto& entry : media_types_by_transport_name) {
6055 const std::string& transport_name = entry.first;
6056 const std::set<cricket::MediaType> media_types = entry.second;
Steve Anton75737c02017-11-06 18:37:176057 cricket::TransportStats stats;
Steve Antonc7b964c2018-02-01 22:39:456058 if (transport_controller_->GetStats(transport_name, &stats)) {
Steve Anton75737c02017-11-06 18:37:176059 ReportBestConnectionState(stats);
Steve Antonc7b964c2018-02-01 22:39:456060 ReportNegotiatedCiphers(stats, media_types);
Steve Anton75737c02017-11-06 18:37:176061 }
6062 }
6063}
6064// Walk through the ConnectionInfos to gather best connection usage
6065// for IPv4 and IPv6.
6066void PeerConnection::ReportBestConnectionState(
6067 const cricket::TransportStats& stats) {
6068 RTC_DCHECK(metrics_observer());
Steve Antonc7b964c2018-02-01 22:39:456069 for (const cricket::TransportChannelStats& channel_stats :
6070 stats.channel_stats) {
6071 for (const cricket::ConnectionInfo& connection_info :
6072 channel_stats.connection_infos) {
6073 if (!connection_info.best_connection) {
Steve Anton75737c02017-11-06 18:37:176074 continue;
6075 }
6076
6077 PeerConnectionEnumCounterType type = kPeerConnectionEnumCounterMax;
Steve Antonc7b964c2018-02-01 22:39:456078 const cricket::Candidate& local = connection_info.local_candidate;
6079 const cricket::Candidate& remote = connection_info.remote_candidate;
Steve Anton75737c02017-11-06 18:37:176080
6081 // Increment the counter for IceCandidatePairType.
6082 if (local.protocol() == cricket::TCP_PROTOCOL_NAME ||
6083 (local.type() == RELAY_PORT_TYPE &&
6084 local.relay_protocol() == cricket::TCP_PROTOCOL_NAME)) {
6085 type = kEnumCounterIceCandidatePairTypeTcp;
6086 } else if (local.protocol() == cricket::UDP_PROTOCOL_NAME) {
6087 type = kEnumCounterIceCandidatePairTypeUdp;
6088 } else {
6089 RTC_CHECK(0);
6090 }
6091 metrics_observer()->IncrementEnumCounter(
6092 type, GetIceCandidatePairCounter(local, remote),
6093 kIceCandidatePairMax);
6094
6095 // Increment the counter for IP type.
6096 if (local.address().family() == AF_INET) {
6097 metrics_observer()->IncrementEnumCounter(
6098 kEnumCounterAddressFamily, kBestConnections_IPv4,
6099 kPeerConnectionAddressFamilyCounter_Max);
6100
6101 } else if (local.address().family() == AF_INET6) {
6102 metrics_observer()->IncrementEnumCounter(
6103 kEnumCounterAddressFamily, kBestConnections_IPv6,
6104 kPeerConnectionAddressFamilyCounter_Max);
6105 } else {
6106 RTC_CHECK(0);
6107 }
6108
6109 return;
6110 }
6111 }
6112}
6113
6114void PeerConnection::ReportNegotiatedCiphers(
Steve Antonc7b964c2018-02-01 22:39:456115 const cricket::TransportStats& stats,
6116 const std::set<cricket::MediaType>& media_types) {
Steve Anton75737c02017-11-06 18:37:176117 RTC_DCHECK(metrics_observer());
6118 if (!dtls_enabled_ || stats.channel_stats.empty()) {
6119 return;
6120 }
6121
6122 int srtp_crypto_suite = stats.channel_stats[0].srtp_crypto_suite;
6123 int ssl_cipher_suite = stats.channel_stats[0].ssl_cipher_suite;
6124 if (srtp_crypto_suite == rtc::SRTP_INVALID_CRYPTO_SUITE &&
6125 ssl_cipher_suite == rtc::TLS_NULL_WITH_NULL_NULL) {
6126 return;
6127 }
6128
Steve Antonc7b964c2018-02-01 22:39:456129 for (cricket::MediaType media_type : media_types) {
6130 PeerConnectionEnumCounterType srtp_counter_type;
6131 PeerConnectionEnumCounterType ssl_counter_type;
6132 switch (media_type) {
6133 case cricket::MEDIA_TYPE_AUDIO:
6134 srtp_counter_type = kEnumCounterAudioSrtpCipher;
6135 ssl_counter_type = kEnumCounterAudioSslCipher;
6136 break;
6137 case cricket::MEDIA_TYPE_VIDEO:
6138 srtp_counter_type = kEnumCounterVideoSrtpCipher;
6139 ssl_counter_type = kEnumCounterVideoSslCipher;
6140 break;
6141 case cricket::MEDIA_TYPE_DATA:
6142 srtp_counter_type = kEnumCounterDataSrtpCipher;
6143 ssl_counter_type = kEnumCounterDataSslCipher;
6144 break;
6145 default:
6146 RTC_NOTREACHED();
6147 continue;
6148 }
6149 if (srtp_crypto_suite != rtc::SRTP_INVALID_CRYPTO_SUITE) {
6150 metrics_observer()->IncrementSparseEnumCounter(srtp_counter_type,
6151 srtp_crypto_suite);
6152 }
6153 if (ssl_cipher_suite != rtc::TLS_NULL_WITH_NULL_NULL) {
6154 metrics_observer()->IncrementSparseEnumCounter(ssl_counter_type,
6155 ssl_cipher_suite);
6156 }
Steve Anton75737c02017-11-06 18:37:176157 }
6158}
6159
6160void PeerConnection::OnSentPacket_w(const rtc::SentPacket& sent_packet) {
6161 RTC_DCHECK(worker_thread()->IsCurrent());
6162 RTC_DCHECK(call_);
6163 call_->OnSentPacket(sent_packet);
6164}
6165
6166const std::string PeerConnection::GetTransportName(
6167 const std::string& content_name) {
6168 cricket::BaseChannel* channel = GetChannel(content_name);
Steve Anton6fec8802017-12-04 18:37:296169 if (channel) {
6170 return channel->transport_name();
Steve Anton75737c02017-11-06 18:37:176171 }
Steve Anton6fec8802017-12-04 18:37:296172 if (sctp_transport_) {
Zhi Huange830e682018-03-30 17:48:356173 RTC_DCHECK(sctp_mid_);
6174 if (content_name == *sctp_mid_) {
6175 return *sctp_transport_name();
Steve Anton6fec8802017-12-04 18:37:296176 }
6177 }
6178 // Return an empty string if failed to retrieve the transport name.
6179 return "";
Steve Anton75737c02017-11-06 18:37:176180}
6181
Steve Anton6fec8802017-12-04 18:37:296182void PeerConnection::DestroyTransceiverChannel(
6183 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
6184 transceiver) {
6185 RTC_DCHECK(transceiver);
Steve Anton75737c02017-11-06 18:37:176186
Steve Anton6fec8802017-12-04 18:37:296187 cricket::BaseChannel* channel = transceiver->internal()->channel();
6188 if (channel) {
6189 transceiver->internal()->SetChannel(nullptr);
6190 DestroyBaseChannel(channel);
Steve Anton75737c02017-11-06 18:37:176191 }
6192}
6193
6194void PeerConnection::DestroyDataChannel() {
Steve Anton6fec8802017-12-04 18:37:296195 if (rtp_data_channel_) {
6196 OnDataChannelDestroyed();
6197 DestroyBaseChannel(rtp_data_channel_);
6198 rtp_data_channel_ = nullptr;
6199 }
6200
6201 // Note: Cannot use rtc::Bind to create a functor to invoke because it will
6202 // grab a reference to this PeerConnection. If this is called from the
6203 // PeerConnection destructor, the RefCountedObject vtable will have already
6204 // been destroyed (since it is a subclass of PeerConnection) and using
6205 // rtc::Bind will cause "Pure virtual function called" error to appear.
6206
6207 if (sctp_transport_) {
6208 OnDataChannelDestroyed();
6209 network_thread()->Invoke<void>(RTC_FROM_HERE,
6210 [this] { DestroySctpTransport_n(); });
6211 }
6212}
6213
6214void PeerConnection::DestroyBaseChannel(cricket::BaseChannel* channel) {
6215 RTC_DCHECK(channel);
Steve Anton6fec8802017-12-04 18:37:296216 switch (channel->media_type()) {
6217 case cricket::MEDIA_TYPE_AUDIO:
6218 channel_manager()->DestroyVoiceChannel(
6219 static_cast<cricket::VoiceChannel*>(channel));
6220 break;
6221 case cricket::MEDIA_TYPE_VIDEO:
6222 channel_manager()->DestroyVideoChannel(
6223 static_cast<cricket::VideoChannel*>(channel));
6224 break;
6225 case cricket::MEDIA_TYPE_DATA:
6226 channel_manager()->DestroyRtpDataChannel(
6227 static_cast<cricket::RtpDataChannel*>(channel));
6228 break;
6229 default:
6230 RTC_NOTREACHED() << "Unknown media type: " << channel->media_type();
6231 break;
6232 }
Zhi Huange830e682018-03-30 17:48:356233}
Steve Anton6fec8802017-12-04 18:37:296234
Taylor Brandstettercbaa2542018-04-16 23:42:146235bool PeerConnection::OnTransportChanged(
Zhi Huange830e682018-03-30 17:48:356236 const std::string& mid,
Taylor Brandstettercbaa2542018-04-16 23:42:146237 RtpTransportInternal* rtp_transport,
6238 cricket::DtlsTransportInternal* dtls_transport) {
6239 bool ret = true;
Zhi Huange830e682018-03-30 17:48:356240 auto base_channel = GetChannel(mid);
6241 if (base_channel) {
Taylor Brandstettercbaa2542018-04-16 23:42:146242 ret = base_channel->SetRtpTransport(rtp_transport);
Zhi Huange830e682018-03-30 17:48:356243 }
Taylor Brandstettercbaa2542018-04-16 23:42:146244 if (sctp_transport_ && mid == sctp_mid_) {
Zhi Huang644fde42018-04-03 02:16:266245 sctp_transport_->SetDtlsTransport(dtls_transport);
Steve Anton75737c02017-11-06 18:37:176246 }
Taylor Brandstettercbaa2542018-04-16 23:42:146247 return ret;
Steve Anton75737c02017-11-06 18:37:176248}
6249
Harald Alvestrand89061872018-01-02 13:08:346250void PeerConnection::ClearStatsCache() {
6251 if (stats_collector_) {
6252 stats_collector_->ClearCachedStatsReport();
6253 }
6254}
6255
henrike@webrtc.org28e20752013-07-10 00:45:366256} // namespace webrtc