blob: cce90216c1322456cb709052420f9c2e7aa58bf5 [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>
Steve Antondcc3c022017-12-23 00:02:5414#include <queue>
Steve Anton75737c02017-11-06 18:37:1715#include <set>
kwiberg0eb15ed2015-12-17 11:04:1516#include <utility>
17#include <vector>
henrike@webrtc.org28e20752013-07-10 00:45:3618
Mirko Bonadei92ea95e2017-09-15 04:47:3119#include "api/jsepicecandidate.h"
20#include "api/jsepsessiondescription.h"
21#include "api/mediaconstraintsinterface.h"
22#include "api/mediastreamproxy.h"
23#include "api/mediastreamtrackproxy.h"
24#include "call/call.h"
Qingsi Wang93a84392018-01-31 01:13:0925#include "logging/rtc_event_log/icelogger.h"
Elad Alon83ccca12017-10-04 11:18:2626#include "logging/rtc_event_log/output/rtc_event_log_output_file.h"
Mirko Bonadei92ea95e2017-09-15 04:47:3127#include "logging/rtc_event_log/rtc_event_log.h"
28#include "media/sctp/sctptransport.h"
29#include "pc/audiotrack.h"
Steve Anton75737c02017-11-06 18:37:1730#include "pc/channel.h"
Mirko Bonadei92ea95e2017-09-15 04:47:3131#include "pc/channelmanager.h"
32#include "pc/dtmfsender.h"
33#include "pc/mediastream.h"
34#include "pc/mediastreamobserver.h"
35#include "pc/remoteaudiosource.h"
Steve Anton1d03a752017-11-27 22:30:0936#include "pc/rtpmediautils.h"
Mirko Bonadei92ea95e2017-09-15 04:47:3137#include "pc/rtpreceiver.h"
38#include "pc/rtpsender.h"
Steve Anton75737c02017-11-06 18:37:1739#include "pc/sctputils.h"
Steve Antona3a92c22017-12-07 18:27:4140#include "pc/sdputils.h"
Mirko Bonadei92ea95e2017-09-15 04:47:3141#include "pc/streamcollection.h"
42#include "pc/videocapturertracksource.h"
43#include "pc/videotrack.h"
44#include "rtc_base/bind.h"
45#include "rtc_base/checks.h"
46#include "rtc_base/logging.h"
Karl Wiberge40468b2017-11-22 09:42:2647#include "rtc_base/numerics/safe_conversions.h"
Elad Alon83ccca12017-10-04 11:18:2648#include "rtc_base/ptr_util.h"
Mirko Bonadei92ea95e2017-09-15 04:47:3149#include "rtc_base/stringencode.h"
50#include "rtc_base/stringutils.h"
51#include "rtc_base/trace_event.h"
52#include "system_wrappers/include/clock.h"
53#include "system_wrappers/include/field_trial.h"
henrike@webrtc.org28e20752013-07-10 00:45:3654
Steve Anton75737c02017-11-06 18:37:1755using cricket::ContentInfo;
56using cricket::ContentInfos;
57using cricket::MediaContentDescription;
58using cricket::SessionDescription;
Steve Anton5adfafd2017-12-21 00:34:0059using cricket::MediaProtocolType;
Steve Anton75737c02017-11-06 18:37:1760using cricket::TransportInfo;
61
62using cricket::LOCAL_PORT_TYPE;
63using cricket::STUN_PORT_TYPE;
64using cricket::RELAY_PORT_TYPE;
65using cricket::PRFLX_PORT_TYPE;
66
Steve Antonba818672017-11-06 18:21:5767namespace webrtc {
68
Steve Anton75737c02017-11-06 18:37:1769// Error messages
70const char kBundleWithoutRtcpMux[] =
71 "rtcp-mux must be enabled when BUNDLE "
72 "is enabled.";
Steve Anton75737c02017-11-06 18:37:1773const char kInvalidCandidates[] = "Description contains invalid candidates.";
74const char kInvalidSdp[] = "Invalid session description.";
75const char kMlineMismatchInAnswer[] =
76 "The order of m-lines in answer doesn't match order in offer. Rejecting "
77 "answer.";
78const char kMlineMismatchInSubsequentOffer[] =
79 "The order of m-lines in subsequent offer doesn't match order from "
80 "previous offer/answer.";
Steve Anton75737c02017-11-06 18:37:1781const char kSdpWithoutDtlsFingerprint[] =
82 "Called with SDP without DTLS fingerprint.";
83const char kSdpWithoutSdesCrypto[] = "Called with SDP without SDES crypto.";
84const char kSdpWithoutIceUfragPwd[] =
85 "Called with SDP without ice-ufrag and ice-pwd.";
86const char kSessionError[] = "Session error code: ";
87const char kSessionErrorDesc[] = "Session error description: ";
88const char kDtlsSrtpSetupFailureRtp[] =
89 "Couldn't set up DTLS-SRTP on RTP channel.";
90const char kDtlsSrtpSetupFailureRtcp[] =
91 "Couldn't set up DTLS-SRTP on RTCP channel.";
henrike@webrtc.org28e20752013-07-10 00:45:3692
Steve Anton75737c02017-11-06 18:37:1793namespace {
henrike@webrtc.org28e20752013-07-10 00:45:3694
Seth Hampson845e8782018-03-02 19:34:1095static const char kDefaultStreamId[] = "default";
Steve Anton4171afb2017-11-20 18:20:2296static const char kDefaultAudioSenderId[] = "defaulta0";
97static const char kDefaultVideoSenderId[] = "defaultv0";
deadbeefab9b2d12015-10-14 18:33:1198
zhihuang8f65cdf2016-05-07 01:40:3099// The length of RTCP CNAMEs.
100static const int kRtcpCnameLength = 16;
101
henrike@webrtc.org28e20752013-07-10 00:45:36102enum {
wu@webrtc.org91053e72013-08-10 07:18:04103 MSG_SET_SESSIONDESCRIPTION_SUCCESS = 0,
henrike@webrtc.org28e20752013-07-10 00:45:36104 MSG_SET_SESSIONDESCRIPTION_FAILED,
deadbeefab9b2d12015-10-14 18:33:11105 MSG_CREATE_SESSIONDESCRIPTION_FAILED,
henrike@webrtc.org28e20752013-07-10 00:45:36106 MSG_GETSTATS,
deadbeefbd292462015-12-15 02:15:29107 MSG_FREE_DATACHANNELS,
henrike@webrtc.org28e20752013-07-10 00:45:36108};
109
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52110struct SetSessionDescriptionMsg : public rtc::MessageData {
henrike@webrtc.org28e20752013-07-10 00:45:36111 explicit SetSessionDescriptionMsg(
112 webrtc::SetSessionDescriptionObserver* observer)
113 : observer(observer) {
114 }
115
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52116 rtc::scoped_refptr<webrtc::SetSessionDescriptionObserver> observer;
Harald Alvestrand5081c0c2018-03-09 14:18:03117 RTCError error;
henrike@webrtc.org28e20752013-07-10 00:45:36118};
119
deadbeefab9b2d12015-10-14 18:33:11120struct CreateSessionDescriptionMsg : public rtc::MessageData {
121 explicit CreateSessionDescriptionMsg(
122 webrtc::CreateSessionDescriptionObserver* observer)
123 : observer(observer) {}
124
125 rtc::scoped_refptr<webrtc::CreateSessionDescriptionObserver> observer;
Harald Alvestrand5081c0c2018-03-09 14:18:03126 RTCError error;
deadbeefab9b2d12015-10-14 18:33:11127};
128
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52129struct GetStatsMsg : public rtc::MessageData {
tommi@webrtc.org5b06b062014-08-15 08:38:30130 GetStatsMsg(webrtc::StatsObserver* observer,
131 webrtc::MediaStreamTrackInterface* track)
132 : observer(observer), track(track) {
henrike@webrtc.org28e20752013-07-10 00:45:36133 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52134 rtc::scoped_refptr<webrtc::StatsObserver> observer;
tommi@webrtc.org5b06b062014-08-15 08:38:30135 rtc::scoped_refptr<webrtc::MediaStreamTrackInterface> track;
henrike@webrtc.org28e20752013-07-10 00:45:36136};
137
deadbeefab9b2d12015-10-14 18:33:11138// Check if we can send |new_stream| on a PeerConnection.
139bool CanAddLocalMediaStream(webrtc::StreamCollectionInterface* current_streams,
140 webrtc::MediaStreamInterface* new_stream) {
141 if (!new_stream || !current_streams) {
142 return false;
143 }
Seth Hampson13b8bad2018-03-13 23:05:28144 if (current_streams->find(new_stream->id()) != nullptr) {
145 RTC_LOG(LS_ERROR) << "MediaStream with ID " << new_stream->id()
Mirko Bonadei675513b2017-11-09 10:09:25146 << " is already added.";
deadbeefab9b2d12015-10-14 18:33:11147 return false;
148 }
149 return true;
150}
151
deadbeef5e97fb52015-10-15 19:49:08152// If the direction is "recvonly" or "inactive", treat the description
153// as containing no streams.
154// See: https://code.google.com/p/webrtc/issues/detail?id=5054
155std::vector<cricket::StreamParams> GetActiveStreams(
156 const cricket::MediaContentDescription* desc) {
Steve Anton4e70a722017-11-28 22:57:10157 return RtpTransceiverDirectionHasSend(desc->direction())
deadbeef5e97fb52015-10-15 19:49:08158 ? desc->streams()
159 : std::vector<cricket::StreamParams>();
160}
161
deadbeefab9b2d12015-10-14 18:33:11162bool IsValidOfferToReceiveMedia(int value) {
163 typedef PeerConnectionInterface::RTCOfferAnswerOptions Options;
164 return (value >= Options::kUndefined) &&
165 (value <= Options::kMaxOfferToReceiveMedia);
166}
167
zhihuang1c378ed2017-08-17 21:10:50168// Add options to |[audio/video]_media_description_options| from |senders|.
169void AddRtpSenderOptions(
deadbeefa601f5c2016-06-06 21:27:39170 const std::vector<rtc::scoped_refptr<
171 RtpSenderProxyWithInternal<RtpSenderInternal>>>& senders,
zhihuang1c378ed2017-08-17 21:10:50172 cricket::MediaDescriptionOptions* audio_media_description_options,
173 cricket::MediaDescriptionOptions* video_media_description_options) {
olka3c747662017-08-17 13:50:32174 for (const auto& sender : senders) {
zhihuang1c378ed2017-08-17 21:10:50175 if (sender->media_type() == cricket::MEDIA_TYPE_AUDIO) {
176 if (audio_media_description_options) {
177 audio_media_description_options->AddAudioSender(
Steve Anton8ffb9c32017-08-31 22:45:38178 sender->id(), sender->internal()->stream_ids());
zhihuang1c378ed2017-08-17 21:10:50179 }
180 } else {
181 RTC_DCHECK(sender->media_type() == cricket::MEDIA_TYPE_VIDEO);
182 if (video_media_description_options) {
183 video_media_description_options->AddVideoSender(
Steve Anton8ffb9c32017-08-31 22:45:38184 sender->id(), sender->internal()->stream_ids(), 1);
zhihuang1c378ed2017-08-17 21:10:50185 }
186 }
zhihuanga77e6bb2017-08-15 01:17:48187 }
zhihuang1c378ed2017-08-17 21:10:50188}
olka3c747662017-08-17 13:50:32189
zhihuang1c378ed2017-08-17 21:10:50190// Add options to |session_options| from |rtp_data_channels|.
191void AddRtpDataChannelOptions(
192 const std::map<std::string, rtc::scoped_refptr<DataChannel>>&
193 rtp_data_channels,
194 cricket::MediaDescriptionOptions* data_media_description_options) {
195 if (!data_media_description_options) {
196 return;
197 }
deadbeefab9b2d12015-10-14 18:33:11198 // Check for data channels.
199 for (const auto& kv : rtp_data_channels) {
200 const DataChannel* channel = kv.second;
201 if (channel->state() == DataChannel::kConnecting ||
202 channel->state() == DataChannel::kOpen) {
zhihuang1c378ed2017-08-17 21:10:50203 // Legacy RTP data channels are signaled with the track/stream ID set to
204 // the data channel's label.
205 data_media_description_options->AddRtpDataChannel(channel->label(),
206 channel->label());
deadbeefab9b2d12015-10-14 18:33:11207 }
208 }
209}
210
Taylor Brandstettera1c30352016-05-13 15:15:11211uint32_t ConvertIceTransportTypeToCandidateFilter(
212 PeerConnectionInterface::IceTransportsType type) {
213 switch (type) {
214 case PeerConnectionInterface::kNone:
215 return cricket::CF_NONE;
216 case PeerConnectionInterface::kRelay:
217 return cricket::CF_RELAY;
218 case PeerConnectionInterface::kNoHost:
219 return (cricket::CF_ALL & ~cricket::CF_HOST);
220 case PeerConnectionInterface::kAll:
221 return cricket::CF_ALL;
222 default:
nissec80e7412017-01-11 13:56:46223 RTC_NOTREACHED();
Taylor Brandstettera1c30352016-05-13 15:15:11224 }
225 return cricket::CF_NONE;
226}
227
deadbeef293e9262017-01-11 20:28:30228// Helper to set an error and return from a method.
229bool SafeSetError(webrtc::RTCErrorType type, webrtc::RTCError* error) {
230 if (error) {
231 error->set_type(type);
232 }
233 return type == webrtc::RTCErrorType::NONE;
234}
235
Steve Anton038834f2017-07-14 22:59:59236bool SafeSetError(webrtc::RTCError error, webrtc::RTCError* error_out) {
237 if (error_out) {
238 *error_out = std::move(error);
239 }
240 return error.ok();
241}
242
Steve Antonba818672017-11-06 18:21:57243std::string GetSignalingStateString(
244 PeerConnectionInterface::SignalingState state) {
245 switch (state) {
246 case PeerConnectionInterface::kStable:
247 return "kStable";
248 case PeerConnectionInterface::kHaveLocalOffer:
249 return "kHaveLocalOffer";
250 case PeerConnectionInterface::kHaveLocalPrAnswer:
251 return "kHavePrAnswer";
252 case PeerConnectionInterface::kHaveRemoteOffer:
253 return "kHaveRemoteOffer";
254 case PeerConnectionInterface::kHaveRemotePrAnswer:
255 return "kHaveRemotePrAnswer";
256 case PeerConnectionInterface::kClosed:
257 return "kClosed";
258 }
259 RTC_NOTREACHED();
260 return "";
261}
deadbeef0a6c4ca2015-10-06 18:38:28262
Steve Anton75737c02017-11-06 18:37:17263IceCandidatePairType GetIceCandidatePairCounter(
264 const cricket::Candidate& local,
265 const cricket::Candidate& remote) {
266 const auto& l = local.type();
267 const auto& r = remote.type();
268 const auto& host = LOCAL_PORT_TYPE;
269 const auto& srflx = STUN_PORT_TYPE;
270 const auto& relay = RELAY_PORT_TYPE;
271 const auto& prflx = PRFLX_PORT_TYPE;
272 if (l == host && r == host) {
273 bool local_private = IPIsPrivate(local.address().ipaddr());
274 bool remote_private = IPIsPrivate(remote.address().ipaddr());
275 if (local_private) {
276 if (remote_private) {
277 return kIceCandidatePairHostPrivateHostPrivate;
278 } else {
279 return kIceCandidatePairHostPrivateHostPublic;
280 }
281 } else {
282 if (remote_private) {
283 return kIceCandidatePairHostPublicHostPrivate;
284 } else {
285 return kIceCandidatePairHostPublicHostPublic;
286 }
287 }
288 }
289 if (l == host && r == srflx)
290 return kIceCandidatePairHostSrflx;
291 if (l == host && r == relay)
292 return kIceCandidatePairHostRelay;
293 if (l == host && r == prflx)
294 return kIceCandidatePairHostPrflx;
295 if (l == srflx && r == host)
296 return kIceCandidatePairSrflxHost;
297 if (l == srflx && r == srflx)
298 return kIceCandidatePairSrflxSrflx;
299 if (l == srflx && r == relay)
300 return kIceCandidatePairSrflxRelay;
301 if (l == srflx && r == prflx)
302 return kIceCandidatePairSrflxPrflx;
303 if (l == relay && r == host)
304 return kIceCandidatePairRelayHost;
305 if (l == relay && r == srflx)
306 return kIceCandidatePairRelaySrflx;
307 if (l == relay && r == relay)
308 return kIceCandidatePairRelayRelay;
309 if (l == relay && r == prflx)
310 return kIceCandidatePairRelayPrflx;
311 if (l == prflx && r == host)
312 return kIceCandidatePairPrflxHost;
313 if (l == prflx && r == srflx)
314 return kIceCandidatePairPrflxSrflx;
315 if (l == prflx && r == relay)
316 return kIceCandidatePairPrflxRelay;
317 return kIceCandidatePairMax;
318}
319
Seth Hampsonae8a90a2018-02-13 23:33:48320// Logic to decide if an m= section can be recycled. This means that the new
321// m= section is not rejected, but the old local or remote m= section is
322// rejected. |old_content_one| and |old_content_two| refer to the m= section
323// of the old remote and old local descriptions in no particular order.
324// We need to check both the old local and remote because either
325// could be the most current from the latest negotation.
326bool IsMediaSectionBeingRecycled(SdpType type,
327 const ContentInfo& content,
328 const ContentInfo* old_content_one,
329 const ContentInfo* old_content_two) {
330 return type == SdpType::kOffer && !content.rejected &&
331 ((old_content_one && old_content_one->rejected) ||
332 (old_content_two && old_content_two->rejected));
333}
334
Steve Anton75737c02017-11-06 18:37:17335// Verify that the order of media sections in |new_desc| matches
Seth Hampsonae8a90a2018-02-13 23:33:48336// |current_desc|. The number of m= sections in |new_desc| should be no
337// less than |current_desc|. In the case of checking an answer's
338// |new_desc|, the |current_desc| is the last offer that was set as the
339// local or remote. In the case of checking an offer's |new_desc| we
340// check against the local and remote descriptions stored from the last
341// negotiation, because either of these could be the most up to date for
342// possible rejected m sections. These are the |current_desc| and
343// |secondary_current_desc|.
344bool MediaSectionsInSameOrder(const SessionDescription& current_desc,
345 const SessionDescription* secondary_current_desc,
346 const SessionDescription& new_desc,
347 const SdpType type) {
348 if (current_desc.contents().size() > new_desc.contents().size()) {
Steve Anton75737c02017-11-06 18:37:17349 return false;
350 }
351
Seth Hampsonae8a90a2018-02-13 23:33:48352 for (size_t i = 0; i < current_desc.contents().size(); ++i) {
353 const cricket::ContentInfo* secondary_content_info = nullptr;
354 if (secondary_current_desc &&
355 i < secondary_current_desc->contents().size()) {
356 secondary_content_info = &secondary_current_desc->contents()[i];
357 }
358 if (IsMediaSectionBeingRecycled(type, new_desc.contents()[i],
359 &current_desc.contents()[i],
360 secondary_content_info)) {
361 // For new offer descriptions, if the media section can be recycled, it's
362 // valid for the MID and media type to change.
Steve Antondcc3c022017-12-23 00:02:54363 continue;
364 }
Seth Hampsonae8a90a2018-02-13 23:33:48365 if (new_desc.contents()[i].name != current_desc.contents()[i].name) {
Steve Anton75737c02017-11-06 18:37:17366 return false;
367 }
368 const MediaContentDescription* new_desc_mdesc =
Seth Hampsonae8a90a2018-02-13 23:33:48369 new_desc.contents()[i].media_description();
370 const MediaContentDescription* current_desc_mdesc =
371 current_desc.contents()[i].media_description();
372 if (new_desc_mdesc->type() != current_desc_mdesc->type()) {
Steve Anton75737c02017-11-06 18:37:17373 return false;
374 }
375 }
376 return true;
377}
378
Seth Hampsonae8a90a2018-02-13 23:33:48379bool MediaSectionsHaveSameCount(const SessionDescription& desc1,
380 const SessionDescription& desc2) {
381 return desc1.contents().size() == desc2.contents().size();
Steve Anton75737c02017-11-06 18:37:17382}
383
Harald Alvestrandf9d0f1d2018-03-02 13:15:26384void NoteKeyProtocolAndMedia(
385 KeyExchangeProtocolType protocol_type,
386 cricket::MediaType media_type,
387 rtc::scoped_refptr<webrtc::UMAObserver> uma_observer) {
388 if (!uma_observer)
389 return;
390 uma_observer->IncrementEnumCounter(webrtc::kEnumCounterKeyProtocol,
391 protocol_type,
392 webrtc::kEnumCounterKeyProtocolMax);
393 static const std::map<std::pair<KeyExchangeProtocolType, cricket::MediaType>,
394 KeyExchangeProtocolMedia>
395 proto_media_counter_map = {
396 {{kEnumCounterKeyProtocolDtls, cricket::MEDIA_TYPE_AUDIO},
397 kEnumCounterKeyProtocolMediaTypeDtlsAudio},
398 {{kEnumCounterKeyProtocolDtls, cricket::MEDIA_TYPE_VIDEO},
399 kEnumCounterKeyProtocolMediaTypeDtlsVideo},
400 {{kEnumCounterKeyProtocolDtls, cricket::MEDIA_TYPE_DATA},
401 kEnumCounterKeyProtocolMediaTypeDtlsData},
402 {{kEnumCounterKeyProtocolSdes, cricket::MEDIA_TYPE_AUDIO},
403 kEnumCounterKeyProtocolMediaTypeSdesAudio},
404 {{kEnumCounterKeyProtocolSdes, cricket::MEDIA_TYPE_VIDEO},
405 kEnumCounterKeyProtocolMediaTypeSdesVideo},
406 {{kEnumCounterKeyProtocolSdes, cricket::MEDIA_TYPE_DATA},
407 kEnumCounterKeyProtocolMediaTypeSdesData}};
408
409 auto it = proto_media_counter_map.find({protocol_type, media_type});
410 if (it != proto_media_counter_map.end()) {
411 uma_observer->IncrementEnumCounter(webrtc::kEnumCounterKeyProtocolMediaType,
412 it->second,
413 kEnumCounterKeyProtocolMediaTypeMax);
414 }
415}
416
Steve Anton75737c02017-11-06 18:37:17417// Checks that each non-rejected content has SDES crypto keys or a DTLS
418// fingerprint, unless it's in a BUNDLE group, in which case only the
419// BUNDLE-tag section (first media section/description in the BUNDLE group)
420// needs a ufrag and pwd. Mismatches, such as replying with a DTLS fingerprint
421// to SDES keys, will be caught in JsepTransport negotiation, and backstopped
422// by Channel's |srtp_required| check.
Harald Alvestrand194939b2018-01-24 15:04:13423RTCError VerifyCrypto(const SessionDescription* desc,
424 bool dtls_enabled,
425 rtc::scoped_refptr<webrtc::UMAObserver> uma_observer) {
Steve Anton75737c02017-11-06 18:37:17426 const cricket::ContentGroup* bundle =
427 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton8a006912017-12-04 23:25:56428 for (const cricket::ContentInfo& content_info : desc->contents()) {
429 if (content_info.rejected) {
Steve Anton75737c02017-11-06 18:37:17430 continue;
431 }
Harald Alvestrand2e180612018-03-07 09:56:14432 // Note what media is used with each crypto protocol, for all sections.
433 NoteKeyProtocolAndMedia(dtls_enabled ? webrtc::kEnumCounterKeyProtocolDtls
434 : webrtc::kEnumCounterKeyProtocolSdes,
435 content_info.media_description()->type(),
436 uma_observer);
Steve Anton8a006912017-12-04 23:25:56437 const std::string& mid = content_info.name;
438 if (bundle && bundle->HasContentName(mid) &&
439 mid != *(bundle->FirstContentName())) {
Steve Anton75737c02017-11-06 18:37:17440 // This isn't the first media section in the BUNDLE group, so it's not
441 // required to have crypto attributes, since only the crypto attributes
442 // from the first section actually get used.
443 continue;
444 }
445
446 // If the content isn't rejected or bundled into another m= section, crypto
447 // must be present.
Steve Antonb1c1de12017-12-21 23:14:30448 const MediaContentDescription* media = content_info.media_description();
Steve Anton8a006912017-12-04 23:25:56449 const TransportInfo* tinfo = desc->GetTransportInfoByName(mid);
Steve Anton75737c02017-11-06 18:37:17450 if (!media || !tinfo) {
451 // Something is not right.
Steve Anton8a006912017-12-04 23:25:56452 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidSdp);
Steve Anton75737c02017-11-06 18:37:17453 }
454 if (dtls_enabled) {
455 if (!tinfo->description.identity_fingerprint) {
Mirko Bonadei675513b2017-11-09 10:09:25456 RTC_LOG(LS_WARNING)
457 << "Session description must have DTLS fingerprint if "
458 "DTLS enabled.";
Steve Anton8a006912017-12-04 23:25:56459 return RTCError(RTCErrorType::INVALID_PARAMETER,
460 kSdpWithoutDtlsFingerprint);
Steve Anton75737c02017-11-06 18:37:17461 }
462 } else {
463 if (media->cryptos().empty()) {
Mirko Bonadei675513b2017-11-09 10:09:25464 RTC_LOG(LS_WARNING)
Steve Anton75737c02017-11-06 18:37:17465 << "Session description must have SDES when DTLS disabled.";
Steve Anton8a006912017-12-04 23:25:56466 return RTCError(RTCErrorType::INVALID_PARAMETER, kSdpWithoutSdesCrypto);
Steve Anton75737c02017-11-06 18:37:17467 }
468 }
469 }
Steve Anton8a006912017-12-04 23:25:56470 return RTCError::OK();
Steve Anton75737c02017-11-06 18:37:17471}
472
473// Checks that each non-rejected content has ice-ufrag and ice-pwd set, unless
474// it's in a BUNDLE group, in which case only the BUNDLE-tag section (first
475// media section/description in the BUNDLE group) needs a ufrag and pwd.
476bool VerifyIceUfragPwdPresent(const SessionDescription* desc) {
477 const cricket::ContentGroup* bundle =
478 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton8a006912017-12-04 23:25:56479 for (const cricket::ContentInfo& content_info : desc->contents()) {
480 if (content_info.rejected) {
Steve Anton75737c02017-11-06 18:37:17481 continue;
482 }
Steve Anton8a006912017-12-04 23:25:56483 const std::string& mid = content_info.name;
484 if (bundle && bundle->HasContentName(mid) &&
485 mid != *(bundle->FirstContentName())) {
Steve Anton75737c02017-11-06 18:37:17486 // This isn't the first media section in the BUNDLE group, so it's not
487 // required to have ufrag/password, since only the ufrag/password from
488 // the first section actually get used.
489 continue;
490 }
491
492 // If the content isn't rejected or bundled into another m= section,
493 // ice-ufrag and ice-pwd must be present.
Steve Anton8a006912017-12-04 23:25:56494 const TransportInfo* tinfo = desc->GetTransportInfoByName(mid);
Steve Anton75737c02017-11-06 18:37:17495 if (!tinfo) {
496 // Something is not right.
Mirko Bonadei675513b2017-11-09 10:09:25497 RTC_LOG(LS_ERROR) << kInvalidSdp;
Steve Anton75737c02017-11-06 18:37:17498 return false;
499 }
500 if (tinfo->description.ice_ufrag.empty() ||
501 tinfo->description.ice_pwd.empty()) {
Mirko Bonadei675513b2017-11-09 10:09:25502 RTC_LOG(LS_ERROR) << "Session description must have ice ufrag and pwd.";
Steve Anton75737c02017-11-06 18:37:17503 return false;
504 }
505 }
506 return true;
507}
508
509bool GetTrackIdBySsrc(const SessionDescription* session_description,
510 uint32_t ssrc,
511 std::string* track_id) {
512 RTC_DCHECK(track_id != NULL);
513
Steve Antonb1c1de12017-12-21 23:14:30514 const cricket::AudioContentDescription* audio_desc =
515 cricket::GetFirstAudioContentDescription(session_description);
516 if (audio_desc) {
517 const auto* found = cricket::GetStreamBySsrc(audio_desc->streams(), ssrc);
Steve Anton75737c02017-11-06 18:37:17518 if (found) {
519 *track_id = found->id;
520 return true;
521 }
522 }
523
Steve Antonb1c1de12017-12-21 23:14:30524 const cricket::VideoContentDescription* video_desc =
525 cricket::GetFirstVideoContentDescription(session_description);
526 if (video_desc) {
527 const auto* found = cricket::GetStreamBySsrc(video_desc->streams(), ssrc);
Steve Anton75737c02017-11-06 18:37:17528 if (found) {
529 *track_id = found->id;
530 return true;
531 }
532 }
533 return false;
534}
535
536// Get the SCTP port out of a SessionDescription.
537// Return -1 if not found.
538int GetSctpPort(const SessionDescription* session_description) {
Steve Antonb1c1de12017-12-21 23:14:30539 const cricket::DataContentDescription* data_desc =
540 GetFirstDataContentDescription(session_description);
541 RTC_DCHECK(data_desc);
542 if (!data_desc) {
Steve Anton75737c02017-11-06 18:37:17543 return -1;
544 }
Steve Anton75737c02017-11-06 18:37:17545 std::string value;
546 cricket::DataCodec match_pattern(cricket::kGoogleSctpDataCodecPlType,
547 cricket::kGoogleSctpDataCodecName);
Steve Antonb1c1de12017-12-21 23:14:30548 for (const cricket::DataCodec& codec : data_desc->codecs()) {
Steve Anton75737c02017-11-06 18:37:17549 if (!codec.Matches(match_pattern)) {
550 continue;
551 }
552 if (codec.GetParam(cricket::kCodecParamPort, &value)) {
553 return rtc::FromString<int>(value);
554 }
555 }
556 return -1;
557}
558
Steve Anton75737c02017-11-06 18:37:17559// Returns true if |new_desc| requests an ICE restart (i.e., new ufrag/pwd).
560bool CheckForRemoteIceRestart(const SessionDescriptionInterface* old_desc,
561 const SessionDescriptionInterface* new_desc,
562 const std::string& content_name) {
563 if (!old_desc) {
564 return false;
565 }
566 const SessionDescription* new_sd = new_desc->description();
567 const SessionDescription* old_sd = old_desc->description();
568 const ContentInfo* cinfo = new_sd->GetContentByName(content_name);
569 if (!cinfo || cinfo->rejected) {
570 return false;
571 }
572 // If the content isn't rejected, check if ufrag and password has changed.
573 const cricket::TransportDescription* new_transport_desc =
574 new_sd->GetTransportDescriptionByName(content_name);
575 const cricket::TransportDescription* old_transport_desc =
576 old_sd->GetTransportDescriptionByName(content_name);
577 if (!new_transport_desc || !old_transport_desc) {
578 // No transport description exists. This is not an ICE restart.
579 return false;
580 }
581 if (cricket::IceCredentialsChanged(
582 old_transport_desc->ice_ufrag, old_transport_desc->ice_pwd,
583 new_transport_desc->ice_ufrag, new_transport_desc->ice_pwd)) {
Mirko Bonadei675513b2017-11-09 10:09:25584 RTC_LOG(LS_INFO) << "Remote peer requests ICE restart for " << content_name
585 << ".";
Steve Anton75737c02017-11-06 18:37:17586 return true;
587 }
588 return false;
589}
590
Steve Anton80dd7b52018-02-17 01:08:42591// Generates a string error message for SetLocalDescription/SetRemoteDescription
592// from an RTCError.
593std::string GetSetDescriptionErrorMessage(cricket::ContentSource source,
594 SdpType type,
595 const RTCError& error) {
596 std::ostringstream oss;
597 oss << "Failed to set " << (source == cricket::CS_LOCAL ? "local" : "remote")
598 << " " << SdpTypeToString(type) << " sdp: " << error.message();
599 return oss.str();
600}
601
Seth Hampson5b4f0752018-04-02 23:31:36602std::string GetStreamIdsString(rtc::ArrayView<const std::string> stream_ids) {
603 std::string output = "streams=[";
604 const char* separator = "";
605 for (const auto& stream_id : stream_ids) {
606 output.append(separator).append(stream_id);
607 separator = ", ";
608 }
609 output.append("]");
610 return output;
611}
612
Qingsi Wang866e08d2018-03-23 00:54:23613rtc::Optional<int> RTCConfigurationToIceConfigOptionalInt(
614 int rtc_configuration_parameter) {
615 if (rtc_configuration_parameter ==
616 webrtc::PeerConnectionInterface::RTCConfiguration::kUndefined) {
617 return rtc::nullopt;
618 }
619 return rtc_configuration_parameter;
620}
621
Steve Anton75737c02017-11-06 18:37:17622} // namespace
623
Henrik Boström31638672017-11-23 16:48:32624// Upon completion, posts a task to execute the callback of the
625// SetSessionDescriptionObserver asynchronously on the same thread. At this
626// point, the state of the peer connection might no longer reflect the effects
627// of the SetRemoteDescription operation, as the peer connection could have been
628// modified during the post.
629// TODO(hbos): Remove this class once we remove the version of
630// PeerConnectionInterface::SetRemoteDescription() that takes a
631// SetSessionDescriptionObserver as an argument.
632class PeerConnection::SetRemoteDescriptionObserverAdapter
633 : public rtc::RefCountedObject<SetRemoteDescriptionObserverInterface> {
634 public:
635 SetRemoteDescriptionObserverAdapter(
636 rtc::scoped_refptr<PeerConnection> pc,
637 rtc::scoped_refptr<SetSessionDescriptionObserver> wrapper)
638 : pc_(std::move(pc)), wrapper_(std::move(wrapper)) {}
639
640 // SetRemoteDescriptionObserverInterface implementation.
641 void OnSetRemoteDescriptionComplete(RTCError error) override {
642 if (error.ok())
643 pc_->PostSetSessionDescriptionSuccess(wrapper_);
644 else
Harald Alvestrand5081c0c2018-03-09 14:18:03645 pc_->PostSetSessionDescriptionFailure(wrapper_, std::move(error));
Henrik Boström31638672017-11-23 16:48:32646 }
647
648 private:
649 rtc::scoped_refptr<PeerConnection> pc_;
650 rtc::scoped_refptr<SetSessionDescriptionObserver> wrapper_;
651};
652
deadbeef293e9262017-01-11 20:28:30653bool PeerConnectionInterface::RTCConfiguration::operator==(
654 const PeerConnectionInterface::RTCConfiguration& o) const {
655 // This static_assert prevents us from accidentally breaking operator==.
Steve Anton300bf8e2017-07-14 17:13:10656 // Note: Order matters! Fields must be ordered the same as RTCConfiguration.
deadbeef293e9262017-01-11 20:28:30657 struct stuff_being_tested_for_equality {
Magnus Jedvert3beb2072017-07-14 14:23:56658 IceServers servers;
Steve Anton300bf8e2017-07-14 17:13:10659 IceTransportsType type;
deadbeef293e9262017-01-11 20:28:30660 BundlePolicy bundle_policy;
661 RtcpMuxPolicy rtcp_mux_policy;
Steve Anton300bf8e2017-07-14 17:13:10662 std::vector<rtc::scoped_refptr<rtc::RTCCertificate>> certificates;
663 int ice_candidate_pool_size;
664 bool disable_ipv6;
665 bool disable_ipv6_on_wifi;
deadbeefd21eab3e2017-07-26 23:50:11666 int max_ipv6_networks;
Daniel Lazarenko2870b0a2018-01-25 09:30:22667 bool disable_link_local_networks;
Steve Anton300bf8e2017-07-14 17:13:10668 bool enable_rtp_data_channel;
669 rtc::Optional<int> screencast_min_bitrate;
670 rtc::Optional<bool> combined_audio_video_bwe;
671 rtc::Optional<bool> enable_dtls_srtp;
deadbeef293e9262017-01-11 20:28:30672 TcpCandidatePolicy tcp_candidate_policy;
673 CandidateNetworkPolicy candidate_network_policy;
674 int audio_jitter_buffer_max_packets;
675 bool audio_jitter_buffer_fast_accelerate;
676 int ice_connection_receiving_timeout;
677 int ice_backup_candidate_pair_ping_interval;
678 ContinualGatheringPolicy continual_gathering_policy;
deadbeef293e9262017-01-11 20:28:30679 bool prioritize_most_likely_ice_candidate_pairs;
680 struct cricket::MediaConfig media_config;
deadbeef293e9262017-01-11 20:28:30681 bool prune_turn_ports;
682 bool presume_writable_when_fully_relayed;
683 bool enable_ice_renomination;
684 bool redetermine_role_on_ice_restart;
Qingsi Wange6826d22018-03-08 22:55:14685 rtc::Optional<int> ice_check_interval_strong_connectivity;
686 rtc::Optional<int> ice_check_interval_weak_connectivity;
skvlad51072462017-02-02 19:50:14687 rtc::Optional<int> ice_check_min_interval;
Qingsi Wang22e623a2018-03-13 17:53:57688 rtc::Optional<int> ice_unwritable_timeout;
689 rtc::Optional<int> ice_unwritable_min_checks;
Qingsi Wangdb53f8e2018-02-20 22:45:49690 rtc::Optional<int> stun_candidate_keepalive_interval;
Steve Anton300bf8e2017-07-14 17:13:10691 rtc::Optional<rtc::IntervalRange> ice_regather_interval_range;
Jonas Orelandbdcee282017-10-10 12:01:40692 webrtc::TurnCustomizer* turn_customizer;
Steve Anton79e79602017-11-20 18:25:56693 SdpSemantics sdp_semantics;
Qingsi Wang9a5c6f82018-02-01 18:38:40694 rtc::Optional<rtc::AdapterType> network_preference;
deadbeef293e9262017-01-11 20:28:30695 };
696 static_assert(sizeof(stuff_being_tested_for_equality) == sizeof(*this),
697 "Did you add something to RTCConfiguration and forget to "
698 "update operator==?");
699 return type == o.type && servers == o.servers &&
700 bundle_policy == o.bundle_policy &&
701 rtcp_mux_policy == o.rtcp_mux_policy &&
702 tcp_candidate_policy == o.tcp_candidate_policy &&
703 candidate_network_policy == o.candidate_network_policy &&
704 audio_jitter_buffer_max_packets == o.audio_jitter_buffer_max_packets &&
705 audio_jitter_buffer_fast_accelerate ==
706 o.audio_jitter_buffer_fast_accelerate &&
707 ice_connection_receiving_timeout ==
708 o.ice_connection_receiving_timeout &&
709 ice_backup_candidate_pair_ping_interval ==
710 o.ice_backup_candidate_pair_ping_interval &&
711 continual_gathering_policy == o.continual_gathering_policy &&
712 certificates == o.certificates &&
713 prioritize_most_likely_ice_candidate_pairs ==
714 o.prioritize_most_likely_ice_candidate_pairs &&
715 media_config == o.media_config && disable_ipv6 == o.disable_ipv6 &&
zhihuangb09b3f92017-03-07 22:40:51716 disable_ipv6_on_wifi == o.disable_ipv6_on_wifi &&
deadbeefd21eab3e2017-07-26 23:50:11717 max_ipv6_networks == o.max_ipv6_networks &&
Daniel Lazarenko2870b0a2018-01-25 09:30:22718 disable_link_local_networks == o.disable_link_local_networks &&
deadbeef293e9262017-01-11 20:28:30719 enable_rtp_data_channel == o.enable_rtp_data_channel &&
deadbeef293e9262017-01-11 20:28:30720 screencast_min_bitrate == o.screencast_min_bitrate &&
721 combined_audio_video_bwe == o.combined_audio_video_bwe &&
722 enable_dtls_srtp == o.enable_dtls_srtp &&
723 ice_candidate_pool_size == o.ice_candidate_pool_size &&
724 prune_turn_ports == o.prune_turn_ports &&
725 presume_writable_when_fully_relayed ==
726 o.presume_writable_when_fully_relayed &&
727 enable_ice_renomination == o.enable_ice_renomination &&
skvlad51072462017-02-02 19:50:14728 redetermine_role_on_ice_restart == o.redetermine_role_on_ice_restart &&
Qingsi Wange6826d22018-03-08 22:55:14729 ice_check_interval_strong_connectivity ==
730 o.ice_check_interval_strong_connectivity &&
731 ice_check_interval_weak_connectivity ==
732 o.ice_check_interval_weak_connectivity &&
Steve Anton300bf8e2017-07-14 17:13:10733 ice_check_min_interval == o.ice_check_min_interval &&
Qingsi Wang22e623a2018-03-13 17:53:57734 ice_unwritable_timeout == o.ice_unwritable_timeout &&
735 ice_unwritable_min_checks == o.ice_unwritable_min_checks &&
Qingsi Wangdb53f8e2018-02-20 22:45:49736 stun_candidate_keepalive_interval ==
737 o.stun_candidate_keepalive_interval &&
Jonas Orelandbdcee282017-10-10 12:01:40738 ice_regather_interval_range == o.ice_regather_interval_range &&
Steve Anton79e79602017-11-20 18:25:56739 turn_customizer == o.turn_customizer &&
Qingsi Wang9a5c6f82018-02-01 18:38:40740 sdp_semantics == o.sdp_semantics &&
741 network_preference == o.network_preference;
deadbeef293e9262017-01-11 20:28:30742}
743
744bool PeerConnectionInterface::RTCConfiguration::operator!=(
745 const PeerConnectionInterface::RTCConfiguration& o) const {
746 return !(*this == o);
deadbeef3edec7c2016-12-10 19:44:26747}
748
zhihuang8f65cdf2016-05-07 01:40:30749// Generate a RTCP CNAME when a PeerConnection is created.
750std::string GenerateRtcpCname() {
751 std::string cname;
752 if (!rtc::CreateRandomString(kRtcpCnameLength, &cname)) {
Mirko Bonadei675513b2017-11-09 10:09:25753 RTC_LOG(LS_ERROR) << "Failed to generate CNAME.";
nisseeb4ca4e2017-01-12 10:24:27754 RTC_NOTREACHED();
zhihuang8f65cdf2016-05-07 01:40:30755 }
756 return cname;
757}
758
zhihuang1c378ed2017-08-17 21:10:50759bool ValidateOfferAnswerOptions(
760 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options) {
761 return IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_audio) &&
762 IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_video);
olka3c747662017-08-17 13:50:32763}
764
zhihuang1c378ed2017-08-17 21:10:50765// From |rtc_options|, fill parts of |session_options| shared by all generated
766// m= sections (in other words, nothing that involves a map/array).
767void ExtractSharedMediaSessionOptions(
768 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options,
769 cricket::MediaSessionOptions* session_options) {
770 session_options->vad_enabled = rtc_options.voice_activity_detection;
771 session_options->bundle_enabled = rtc_options.use_rtp_mux;
772}
zhihuanga77e6bb2017-08-15 01:17:48773
zhihuang1c378ed2017-08-17 21:10:50774bool ConvertConstraintsToOfferAnswerOptions(
775 const MediaConstraintsInterface* constraints,
776 PeerConnectionInterface::RTCOfferAnswerOptions* offer_answer_options) {
olka3c747662017-08-17 13:50:32777 if (!constraints) {
778 return true;
779 }
zhihuang1c378ed2017-08-17 21:10:50780
781 bool value = false;
782 size_t mandatory_constraints_satisfied = 0;
783
784 if (FindConstraint(constraints,
785 MediaConstraintsInterface::kOfferToReceiveAudio, &value,
786 &mandatory_constraints_satisfied)) {
787 offer_answer_options->offer_to_receive_audio =
788 value ? PeerConnectionInterface::RTCOfferAnswerOptions::
789 kOfferToReceiveMediaTrue
790 : 0;
791 }
792
793 if (FindConstraint(constraints,
794 MediaConstraintsInterface::kOfferToReceiveVideo, &value,
795 &mandatory_constraints_satisfied)) {
796 offer_answer_options->offer_to_receive_video =
797 value ? PeerConnectionInterface::RTCOfferAnswerOptions::
798 kOfferToReceiveMediaTrue
799 : 0;
800 }
801 if (FindConstraint(constraints,
802 MediaConstraintsInterface::kVoiceActivityDetection, &value,
803 &mandatory_constraints_satisfied)) {
804 offer_answer_options->voice_activity_detection = value;
805 }
806 if (FindConstraint(constraints, MediaConstraintsInterface::kUseRtpMux, &value,
807 &mandatory_constraints_satisfied)) {
808 offer_answer_options->use_rtp_mux = value;
809 }
810 if (FindConstraint(constraints, MediaConstraintsInterface::kIceRestart,
811 &value, &mandatory_constraints_satisfied)) {
812 offer_answer_options->ice_restart = value;
813 }
814
deadbeefab9b2d12015-10-14 18:33:11815 return mandatory_constraints_satisfied == constraints->GetMandatory().size();
816}
817
zhihuang38ede132017-06-15 19:52:32818PeerConnection::PeerConnection(PeerConnectionFactory* factory,
819 std::unique_ptr<RtcEventLog> event_log,
820 std::unique_ptr<Call> call)
henrike@webrtc.org28e20752013-07-10 00:45:36821 : factory_(factory),
zhihuang38ede132017-06-15 19:52:32822 event_log_(std::move(event_log)),
zhihuang8f65cdf2016-05-07 01:40:30823 rtcp_cname_(GenerateRtcpCname()),
deadbeefab9b2d12015-10-14 18:33:11824 local_streams_(StreamCollection::Create()),
zhihuang38ede132017-06-15 19:52:32825 remote_streams_(StreamCollection::Create()),
826 call_(std::move(call)) {}
henrike@webrtc.org28e20752013-07-10 00:45:36827
828PeerConnection::~PeerConnection() {
Peter Boström1a9d6152015-12-08 21:15:17829 TRACE_EVENT0("webrtc", "PeerConnection::~PeerConnection");
Steve Anton4171afb2017-11-20 18:20:22830 RTC_DCHECK_RUN_ON(signaling_thread());
831
Steve Anton8af21862017-12-15 19:20:13832 // Need to stop transceivers before destroying the stats collector because
833 // AudioRtpSender has a reference to the StatsCollector it will update when
834 // stopping.
835 for (auto transceiver : transceivers_) {
836 transceiver->Stop();
837 }
Steve Anton4171afb2017-11-20 18:20:22838
Taylor Brandstettera1c30352016-05-13 15:15:11839 stats_.reset(nullptr);
hbosb78306a2016-12-19 13:06:57840 if (stats_collector_) {
841 stats_collector_->WaitForPendingRequest();
842 stats_collector_ = nullptr;
843 }
Steve Anton75737c02017-11-06 18:37:17844
Steve Anton8af21862017-12-15 19:20:13845 // Don't destroy BaseChannels until after stats has been cleaned up so that
846 // the last stats request can still read from the channels.
847 DestroyAllChannels();
848
Mirko Bonadei675513b2017-11-09 10:09:25849 RTC_LOG(LS_INFO) << "Session: " << session_id() << " is destroyed.";
Steve Anton75737c02017-11-06 18:37:17850
851 webrtc_session_desc_factory_.reset();
852 sctp_invoker_.reset();
853 sctp_factory_.reset();
854 transport_controller_.reset();
855
deadbeef91dd5672016-05-18 23:55:30856 // port_allocator_ lives on the network thread and should be destroyed there.
Taylor Brandstetter5d97a9a2016-06-10 21:17:27857 network_thread()->Invoke<void>(RTC_FROM_HERE,
nisseeaabdf62017-05-05 09:23:02858 [this] { port_allocator_.reset(); });
eladalon248fd4f2017-09-06 12:18:15859 // call_ and event_log_ must be destroyed on the worker thread.
Steve Anton978b8762017-09-29 19:15:02860 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
eladalon248fd4f2017-09-06 12:18:15861 call_.reset();
Qingsi Wang93a84392018-01-31 01:13:09862 // The event log must outlive call (and any other object that uses it).
eladalon248fd4f2017-09-06 12:18:15863 event_log_.reset();
864 });
henrike@webrtc.org28e20752013-07-10 00:45:36865}
866
Steve Anton8af21862017-12-15 19:20:13867void PeerConnection::DestroyAllChannels() {
Steve Anton3fe1b152017-12-12 18:20:08868 // Destroy video channels first since they may have a pointer to a voice
869 // channel.
870 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 19:43:08871 if (transceiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton3fe1b152017-12-12 18:20:08872 DestroyTransceiverChannel(transceiver);
873 }
874 }
875 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 19:43:08876 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton3fe1b152017-12-12 18:20:08877 DestroyTransceiverChannel(transceiver);
878 }
879 }
880 DestroyDataChannel();
881}
882
henrike@webrtc.org28e20752013-07-10 00:45:36883bool PeerConnection::Initialize(
buildbot@webrtc.org41451d42014-05-03 05:39:45884 const PeerConnectionInterface::RTCConfiguration& configuration,
kwibergd1fe2812016-04-27 13:47:29885 std::unique_ptr<cricket::PortAllocator> allocator,
Henrik Boströmd03c23b2016-06-01 09:44:18886 std::unique_ptr<rtc::RTCCertificateGeneratorInterface> cert_generator,
deadbeef653b8e02015-11-11 20:55:10887 PeerConnectionObserver* observer) {
Peter Boström1a9d6152015-12-08 21:15:17888 TRACE_EVENT0("webrtc", "PeerConnection::Initialize");
Steve Anton038834f2017-07-14 22:59:59889
890 RTCError config_error = ValidateConfiguration(configuration);
891 if (!config_error.ok()) {
Mirko Bonadei675513b2017-11-09 10:09:25892 RTC_LOG(LS_ERROR) << "Invalid configuration: " << config_error.message();
Steve Anton038834f2017-07-14 22:59:59893 return false;
894 }
895
deadbeef293e9262017-01-11 20:28:30896 if (!allocator) {
Mirko Bonadei675513b2017-11-09 10:09:25897 RTC_LOG(LS_ERROR)
898 << "PeerConnection initialized without a PortAllocator? "
Jonas Olsson45cc8902018-02-13 09:37:07899 "This shouldn't happen if using PeerConnectionFactory.";
deadbeef293e9262017-01-11 20:28:30900 return false;
901 }
Jonas Orelandbdcee282017-10-10 12:01:40902
deadbeef653b8e02015-11-11 20:55:10903 if (!observer) {
deadbeef293e9262017-01-11 20:28:30904 // TODO(deadbeef): Why do we do this?
Mirko Bonadei675513b2017-11-09 10:09:25905 RTC_LOG(LS_ERROR) << "PeerConnection initialized without a "
Jonas Olsson45cc8902018-02-13 09:37:07906 "PeerConnectionObserver";
deadbeef653b8e02015-11-11 20:55:10907 return false;
908 }
pthatcher@webrtc.org877ac762015-02-04 22:03:09909 observer_ = observer;
kwiberg0eb15ed2015-12-17 11:04:15910 port_allocator_ = std::move(allocator);
deadbeef653b8e02015-11-11 20:55:10911
deadbeef91dd5672016-05-18 23:55:30912 // The port allocator lives on the network thread and should be initialized
Taylor Brandstettera1c30352016-05-13 15:15:11913 // there.
Taylor Brandstetter5d97a9a2016-06-10 21:17:27914 if (!network_thread()->Invoke<bool>(
915 RTC_FROM_HERE, rtc::Bind(&PeerConnection::InitializePortAllocator_n,
916 this, configuration))) {
henrike@webrtc.org28e20752013-07-10 00:45:36917 return false;
918 }
henrike@webrtc.org28e20752013-07-10 00:45:36919
Zhi Huange830e682018-03-30 17:48:35920 const PeerConnectionFactoryInterface::Options& options = factory_->options();
921
Steve Anton75737c02017-11-06 18:37:17922 // RFC 3264: The numeric value of the session id and version in the
923 // o line MUST be representable with a "64 bit signed integer".
924 // Due to this constraint session id |session_id_| is max limited to
925 // LLONG_MAX.
926 session_id_ = rtc::ToString(rtc::CreateRandomId64() & LLONG_MAX);
Zhi Huange830e682018-03-30 17:48:35927 JsepTransportController::Config config;
928 config.redetermine_role_on_ice_restart =
929 configuration.redetermine_role_on_ice_restart;
930 config.ssl_max_version = factory_->options().ssl_max_version;
931 config.disable_encryption = options.disable_encryption;
932 config.bundle_policy = configuration.bundle_policy;
933 config.rtcp_mux_policy = configuration.rtcp_mux_policy;
934 config.crypto_options = options.crypto_options;
935#if defined(ENABLE_EXTERNAL_AUTH)
936 config.enable_external_auth = true;
937#endif
938 transport_controller_.reset(new JsepTransportController(
939 signaling_thread(), network_thread(), port_allocator_.get(), config));
940 transport_controller_->SignalIceConnectionState.connect(
Steve Anton75737c02017-11-06 18:37:17941 this, &PeerConnection::OnTransportControllerConnectionState);
Zhi Huange830e682018-03-30 17:48:35942 transport_controller_->SignalIceGatheringState.connect(
Steve Anton75737c02017-11-06 18:37:17943 this, &PeerConnection::OnTransportControllerGatheringState);
Zhi Huange830e682018-03-30 17:48:35944 transport_controller_->SignalIceCandidatesGathered.connect(
Steve Anton75737c02017-11-06 18:37:17945 this, &PeerConnection::OnTransportControllerCandidatesGathered);
Zhi Huange830e682018-03-30 17:48:35946 transport_controller_->SignalIceCandidatesRemoved.connect(
Steve Anton75737c02017-11-06 18:37:17947 this, &PeerConnection::OnTransportControllerCandidatesRemoved);
948 transport_controller_->SignalDtlsHandshakeError.connect(
949 this, &PeerConnection::OnTransportControllerDtlsHandshakeError);
Zhi Huange830e682018-03-30 17:48:35950 transport_controller_->SignalRtpTransportChanged.connect(
951 this, &PeerConnection::OnRtpTransportChanged);
952 transport_controller_->SignalDtlsTransportChanged.connect(
953 this, &PeerConnection::OnDtlsTransportChanged);
Steve Anton75737c02017-11-06 18:37:17954
955 sctp_factory_ = factory_->CreateSctpTransportInternalFactory();
zhihuang29ff8442016-07-27 18:07:25956
deadbeefab9b2d12015-10-14 18:33:11957 stats_.reset(new StatsCollector(this));
hbos74e1a4f2016-09-16 06:33:01958 stats_collector_ = RTCStatsCollector::Create(this);
henrike@webrtc.org28e20752013-07-10 00:45:36959
Steve Antonba818672017-11-06 18:21:57960 configuration_ = configuration;
961
Steve Anton75737c02017-11-06 18:37:17962 // Obtain a certificate from RTCConfiguration if any were provided (optional).
963 rtc::scoped_refptr<rtc::RTCCertificate> certificate;
964 if (!configuration.certificates.empty()) {
965 // TODO(hbos,torbjorng): Decide on certificate-selection strategy instead of
966 // just picking the first one. The decision should be made based on the DTLS
967 // handshake. The DTLS negotiations need to know about all certificates.
968 certificate = configuration.certificates[0];
969 }
970
Steve Antond25da372017-11-06 22:50:29971 transport_controller_->SetIceConfig(ParseIceConfig(configuration));
Steve Anton75737c02017-11-06 18:37:17972
973 if (options.disable_encryption) {
974 dtls_enabled_ = false;
975 } else {
976 // Enable DTLS by default if we have an identity store or a certificate.
977 dtls_enabled_ = (cert_generator || certificate);
978 // |configuration| can override the default |dtls_enabled_| value.
979 if (configuration.enable_dtls_srtp) {
980 dtls_enabled_ = *(configuration.enable_dtls_srtp);
981 }
982 }
983
984 // Enable creation of RTP data channels if the kEnableRtpDataChannels is set.
985 // It takes precendence over the disable_sctp_data_channels
986 // PeerConnectionFactoryInterface::Options.
987 if (configuration.enable_rtp_data_channel) {
988 data_channel_type_ = cricket::DCT_RTP;
989 } else {
990 // DTLS has to be enabled to use SCTP.
991 if (!options.disable_sctp_data_channels && dtls_enabled_) {
992 data_channel_type_ = cricket::DCT_SCTP;
993 }
994 }
995
996 video_options_.screencast_min_bitrate_kbps =
997 configuration.screencast_min_bitrate;
998 audio_options_.combined_audio_video_bwe =
999 configuration.combined_audio_video_bwe;
1000
1001 audio_options_.audio_jitter_buffer_max_packets =
Oskar Sundbom9b28a032017-11-16 09:53:301002 configuration.audio_jitter_buffer_max_packets;
Steve Anton75737c02017-11-06 18:37:171003
1004 audio_options_.audio_jitter_buffer_fast_accelerate =
Oskar Sundbom9b28a032017-11-16 09:53:301005 configuration.audio_jitter_buffer_fast_accelerate;
Steve Anton75737c02017-11-06 18:37:171006
1007 // Whether the certificate generator/certificate is null or not determines
1008 // what PeerConnectionDescriptionFactory will do, so make sure that we give it
1009 // the right instructions by clearing the variables if needed.
1010 if (!dtls_enabled_) {
1011 cert_generator.reset();
1012 certificate = nullptr;
1013 } else if (certificate) {
1014 // Favor generated certificate over the certificate generator.
1015 cert_generator.reset();
1016 }
1017
1018 webrtc_session_desc_factory_.reset(new WebRtcSessionDescriptionFactory(
1019 signaling_thread(), channel_manager(), this, session_id(),
1020 std::move(cert_generator), certificate));
1021 webrtc_session_desc_factory_->SignalCertificateReady.connect(
1022 this, &PeerConnection::OnCertificateReady);
1023
1024 if (options.disable_encryption) {
1025 webrtc_session_desc_factory_->SetSdesPolicy(cricket::SEC_DISABLED);
1026 }
1027
1028 webrtc_session_desc_factory_->set_enable_encrypted_rtp_header_extensions(
1029 options.crypto_options.enable_encrypted_rtp_header_extensions);
henrike@webrtc.org28e20752013-07-10 00:45:361030
Steve Anton4171afb2017-11-20 18:20:221031 // Add default audio/video transceivers for Plan B SDP.
1032 if (!IsUnifiedPlan()) {
1033 transceivers_.push_back(
1034 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1035 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_AUDIO)));
1036 transceivers_.push_back(
1037 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1038 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_VIDEO)));
1039 }
1040
henrike@webrtc.org28e20752013-07-10 00:45:361041 return true;
1042}
1043
Steve Anton038834f2017-07-14 22:59:591044RTCError PeerConnection::ValidateConfiguration(
1045 const RTCConfiguration& config) const {
1046 if (config.ice_regather_interval_range &&
1047 config.continual_gathering_policy == GATHER_ONCE) {
1048 return RTCError(RTCErrorType::INVALID_PARAMETER,
1049 "ice_regather_interval_range specified but continual "
1050 "gathering policy is GATHER_ONCE");
1051 }
Qingsi Wangdea68892018-03-27 17:55:211052 auto result =
1053 cricket::P2PTransportChannel::ValidateIceConfig(ParseIceConfig(config));
1054 return result;
Steve Anton038834f2017-07-14 22:59:591055}
1056
buildbot@webrtc.orgd4e598d2014-07-29 17:36:521057rtc::scoped_refptr<StreamCollectionInterface>
henrike@webrtc.org28e20752013-07-10 00:45:361058PeerConnection::local_streams() {
Steve Antonfc853712018-03-01 21:48:581059 RTC_CHECK(!IsUnifiedPlan()) << "local_streams is not available with Unified "
1060 "Plan SdpSemantics. Please use GetSenders "
1061 "instead.";
deadbeefab9b2d12015-10-14 18:33:111062 return local_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:361063}
1064
buildbot@webrtc.orgd4e598d2014-07-29 17:36:521065rtc::scoped_refptr<StreamCollectionInterface>
henrike@webrtc.org28e20752013-07-10 00:45:361066PeerConnection::remote_streams() {
Steve Antonfc853712018-03-01 21:48:581067 RTC_CHECK(!IsUnifiedPlan()) << "remote_streams is not available with Unified "
1068 "Plan SdpSemantics. Please use GetReceivers "
1069 "instead.";
deadbeefab9b2d12015-10-14 18:33:111070 return remote_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:361071}
1072
perkj@webrtc.orgc2dd5ee2014-11-04 11:31:291073bool PeerConnection::AddStream(MediaStreamInterface* local_stream) {
Steve Antonfc853712018-03-01 21:48:581074 RTC_CHECK(!IsUnifiedPlan()) << "AddStream is not available with Unified Plan "
1075 "SdpSemantics. Please use AddTrack instead.";
Peter Boström1a9d6152015-12-08 21:15:171076 TRACE_EVENT0("webrtc", "PeerConnection::AddStream");
henrike@webrtc.org28e20752013-07-10 00:45:361077 if (IsClosed()) {
1078 return false;
1079 }
deadbeefab9b2d12015-10-14 18:33:111080 if (!CanAddLocalMediaStream(local_streams_, local_stream)) {
henrike@webrtc.org28e20752013-07-10 00:45:361081 return false;
1082 }
deadbeefab9b2d12015-10-14 18:33:111083
1084 local_streams_->AddStream(local_stream);
deadbeefeb459812015-12-16 03:24:431085 MediaStreamObserver* observer = new MediaStreamObserver(local_stream);
1086 observer->SignalAudioTrackAdded.connect(this,
1087 &PeerConnection::OnAudioTrackAdded);
1088 observer->SignalAudioTrackRemoved.connect(
1089 this, &PeerConnection::OnAudioTrackRemoved);
1090 observer->SignalVideoTrackAdded.connect(this,
1091 &PeerConnection::OnVideoTrackAdded);
1092 observer->SignalVideoTrackRemoved.connect(
1093 this, &PeerConnection::OnVideoTrackRemoved);
kwibergd1fe2812016-04-27 13:47:291094 stream_observers_.push_back(std::unique_ptr<MediaStreamObserver>(observer));
deadbeefab9b2d12015-10-14 18:33:111095
deadbeefab9b2d12015-10-14 18:33:111096 for (const auto& track : local_stream->GetAudioTracks()) {
korniltsev.anatolyec390b52017-07-25 00:00:251097 AddAudioTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 18:33:111098 }
1099 for (const auto& track : local_stream->GetVideoTracks()) {
korniltsev.anatolyec390b52017-07-25 00:00:251100 AddVideoTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 18:33:111101 }
1102
tommi@webrtc.org03505bc2014-07-14 20:15:261103 stats_->AddStream(local_stream);
henrike@webrtc.org28e20752013-07-10 00:45:361104 observer_->OnRenegotiationNeeded();
1105 return true;
1106}
1107
1108void PeerConnection::RemoveStream(MediaStreamInterface* local_stream) {
Steve Antonfc853712018-03-01 21:48:581109 RTC_CHECK(!IsUnifiedPlan()) << "RemoveStream is not available with Unified "
1110 "Plan SdpSemantics. Please use RemoveTrack "
1111 "instead.";
Peter Boström1a9d6152015-12-08 21:15:171112 TRACE_EVENT0("webrtc", "PeerConnection::RemoveStream");
korniltsev.anatolyec390b52017-07-25 00:00:251113 if (!IsClosed()) {
1114 for (const auto& track : local_stream->GetAudioTracks()) {
1115 RemoveAudioTrack(track.get(), local_stream);
1116 }
1117 for (const auto& track : local_stream->GetVideoTracks()) {
1118 RemoveVideoTrack(track.get(), local_stream);
1119 }
deadbeefab9b2d12015-10-14 18:33:111120 }
deadbeefab9b2d12015-10-14 18:33:111121 local_streams_->RemoveStream(local_stream);
deadbeefeb459812015-12-16 03:24:431122 stream_observers_.erase(
1123 std::remove_if(
1124 stream_observers_.begin(), stream_observers_.end(),
kwibergd1fe2812016-04-27 13:47:291125 [local_stream](const std::unique_ptr<MediaStreamObserver>& observer) {
Seth Hampson13b8bad2018-03-13 23:05:281126 return observer->stream()->id().compare(local_stream->id()) == 0;
deadbeefeb459812015-12-16 03:24:431127 }),
1128 stream_observers_.end());
deadbeefab9b2d12015-10-14 18:33:111129
henrike@webrtc.org28e20752013-07-10 00:45:361130 if (IsClosed()) {
1131 return;
1132 }
henrike@webrtc.org28e20752013-07-10 00:45:361133 observer_->OnRenegotiationNeeded();
1134}
1135
deadbeefe1f9d832016-01-14 23:35:421136rtc::scoped_refptr<RtpSenderInterface> PeerConnection::AddTrack(
1137 MediaStreamTrackInterface* track,
1138 std::vector<MediaStreamInterface*> streams) {
1139 TRACE_EVENT0("webrtc", "PeerConnection::AddTrack");
Seth Hampson845e8782018-03-02 19:34:101140 std::vector<std::string> stream_ids;
Steve Antonf9381f02017-12-14 18:23:571141 for (auto* stream : streams) {
1142 if (!stream) {
1143 RTC_LOG(LS_ERROR) << "Stream list has null element.";
1144 return nullptr;
1145 }
Seth Hampson13b8bad2018-03-13 23:05:281146 stream_ids.push_back(stream->id());
Steve Antonf9381f02017-12-14 18:23:571147 }
Seth Hampson845e8782018-03-02 19:34:101148 auto sender_or_error = AddTrack(track, stream_ids);
Steve Antonf9381f02017-12-14 18:23:571149 if (!sender_or_error.ok()) {
deadbeefe1f9d832016-01-14 23:35:421150 return nullptr;
1151 }
Steve Antonf9381f02017-12-14 18:23:571152 return sender_or_error.MoveValue();
1153}
1154
Steve Anton2d6c76a2018-01-06 01:10:521155RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::AddTrack(
Steve Antonf9381f02017-12-14 18:23:571156 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 19:34:101157 const std::vector<std::string>& stream_ids) {
Steve Anton2d6c76a2018-01-06 01:10:521158 TRACE_EVENT0("webrtc", "PeerConnection::AddTrack");
Steve Antonf9381f02017-12-14 18:23:571159 if (!track) {
1160 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "Track is null.");
1161 }
1162 if (!(track->kind() == MediaStreamTrackInterface::kAudioKind ||
1163 track->kind() == MediaStreamTrackInterface::kVideoKind)) {
1164 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1165 "Track has invalid kind: " + track->kind());
1166 }
Steve Antonf9381f02017-12-14 18:23:571167 if (IsClosed()) {
1168 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
1169 "PeerConnection is closed.");
deadbeefe1f9d832016-01-14 23:35:421170 }
Steve Anton4171afb2017-11-20 18:20:221171 if (FindSenderForTrack(track)) {
Steve Antonf9381f02017-12-14 18:23:571172 LOG_AND_RETURN_ERROR(
1173 RTCErrorType::INVALID_PARAMETER,
1174 "Sender already exists for track " + track->id() + ".");
deadbeefe1f9d832016-01-14 23:35:421175 }
Steve Antonf9381f02017-12-14 18:23:571176 auto sender_or_error =
Seth Hampson5b4f0752018-04-02 23:31:361177 (IsUnifiedPlan() ? AddTrackUnifiedPlan(track, stream_ids)
1178 : AddTrackPlanB(track, stream_ids));
Steve Antonf9381f02017-12-14 18:23:571179 if (sender_or_error.ok()) {
1180 observer_->OnRenegotiationNeeded();
Steve Anton43a723a2018-01-04 23:48:171181 stats_->AddTrack(track);
Steve Antonf9381f02017-12-14 18:23:571182 }
1183 return sender_or_error;
1184}
deadbeefe1f9d832016-01-14 23:35:421185
Steve Antonf9381f02017-12-14 18:23:571186RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>>
1187PeerConnection::AddTrackPlanB(
1188 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 19:34:101189 const std::vector<std::string>& stream_ids) {
Seth Hampson5b4f0752018-04-02 23:31:361190 if (stream_ids.size() > 1u) {
1191 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_OPERATION,
1192 "AddTrack with more than one stream is not "
1193 "supported with Plan B semantics.");
1194 }
1195 std::vector<std::string> adjusted_stream_ids = stream_ids;
1196 if (adjusted_stream_ids.empty()) {
1197 adjusted_stream_ids.push_back(rtc::CreateRandomUuid());
1198 }
Steve Anton02ee47c2018-01-11 00:26:061199 cricket::MediaType media_type =
1200 (track->kind() == MediaStreamTrackInterface::kAudioKind
1201 ? cricket::MEDIA_TYPE_AUDIO
1202 : cricket::MEDIA_TYPE_VIDEO);
Seth Hampson5b4f0752018-04-02 23:31:361203 auto new_sender = CreateSender(media_type, track, adjusted_stream_ids);
deadbeefe1f9d832016-01-14 23:35:421204 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
Steve Anton57858b32018-02-15 23:19:501205 new_sender->internal()->SetVoiceMediaChannel(voice_media_channel());
Steve Anton4171afb2017-11-20 18:20:221206 GetAudioTransceiver()->internal()->AddSender(new_sender);
Steve Anton4171afb2017-11-20 18:20:221207 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609eaa2018-03-27 21:57:181208 FindSenderInfo(local_audio_sender_infos_,
Seth Hampson5b4f0752018-04-02 23:31:361209 new_sender->internal()->stream_ids()[0], track->id());
Steve Anton4171afb2017-11-20 18:20:221210 if (sender_info) {
1211 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 23:35:421212 }
Steve Antonf9381f02017-12-14 18:23:571213 } else {
1214 RTC_DCHECK_EQ(MediaStreamTrackInterface::kVideoKind, track->kind());
Steve Anton57858b32018-02-15 23:19:501215 new_sender->internal()->SetVideoMediaChannel(video_media_channel());
Steve Anton4171afb2017-11-20 18:20:221216 GetVideoTransceiver()->internal()->AddSender(new_sender);
Steve Anton4171afb2017-11-20 18:20:221217 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609eaa2018-03-27 21:57:181218 FindSenderInfo(local_video_sender_infos_,
Seth Hampson5b4f0752018-04-02 23:31:361219 new_sender->internal()->stream_ids()[0], track->id());
Steve Anton4171afb2017-11-20 18:20:221220 if (sender_info) {
1221 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 23:35:421222 }
deadbeefe1f9d832016-01-14 23:35:421223 }
Steve Anton02ee47c2018-01-11 00:26:061224 return rtc::scoped_refptr<RtpSenderInterface>(new_sender);
Steve Antonf9381f02017-12-14 18:23:571225}
deadbeefe1f9d832016-01-14 23:35:421226
Steve Antonf9381f02017-12-14 18:23:571227RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>>
1228PeerConnection::AddTrackUnifiedPlan(
1229 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 19:34:101230 const std::vector<std::string>& stream_ids) {
Steve Antonf9381f02017-12-14 18:23:571231 auto transceiver = FindFirstTransceiverForAddedTrack(track);
1232 if (transceiver) {
Steve Anton3d954a62018-04-02 18:27:231233 RTC_LOG(LS_INFO) << "Reusing an existing "
1234 << cricket::MediaTypeToString(transceiver->media_type())
1235 << " transceiver for AddTrack.";
Steve Antonf9381f02017-12-14 18:23:571236 if (transceiver->direction() == RtpTransceiverDirection::kRecvOnly) {
Steve Anton52d86772018-02-20 23:48:121237 transceiver->internal()->set_direction(
1238 RtpTransceiverDirection::kSendRecv);
Steve Antonf9381f02017-12-14 18:23:571239 } else if (transceiver->direction() == RtpTransceiverDirection::kInactive) {
Steve Anton52d86772018-02-20 23:48:121240 transceiver->internal()->set_direction(
1241 RtpTransceiverDirection::kSendOnly);
Steve Antonf9381f02017-12-14 18:23:571242 }
Steve Anton02ee47c2018-01-11 00:26:061243 transceiver->sender()->SetTrack(track);
Seth Hampson845e8782018-03-02 19:34:101244 transceiver->internal()->sender_internal()->set_stream_ids(stream_ids);
Steve Antonf9381f02017-12-14 18:23:571245 } else {
1246 cricket::MediaType media_type =
1247 (track->kind() == MediaStreamTrackInterface::kAudioKind
1248 ? cricket::MEDIA_TYPE_AUDIO
1249 : cricket::MEDIA_TYPE_VIDEO);
Steve Anton3d954a62018-04-02 18:27:231250 RTC_LOG(LS_INFO) << "Adding " << cricket::MediaTypeToString(media_type)
1251 << " transceiver in response to a call to AddTrack.";
Seth Hampson845e8782018-03-02 19:34:101252 auto sender = CreateSender(media_type, track, stream_ids);
Steve Anton02ee47c2018-01-11 00:26:061253 auto receiver = CreateReceiver(media_type, rtc::CreateRandomUuid());
1254 transceiver = CreateAndAddTransceiver(sender, receiver);
Steve Antonf9381f02017-12-14 18:23:571255 transceiver->internal()->set_created_by_addtrack(true);
Steve Anton52d86772018-02-20 23:48:121256 transceiver->internal()->set_direction(RtpTransceiverDirection::kSendRecv);
Steve Antonf9381f02017-12-14 18:23:571257 }
Steve Antonf9381f02017-12-14 18:23:571258 return transceiver->sender();
1259}
1260
1261rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1262PeerConnection::FindFirstTransceiverForAddedTrack(
1263 rtc::scoped_refptr<MediaStreamTrackInterface> track) {
1264 RTC_DCHECK(track);
1265 for (auto transceiver : transceivers_) {
1266 if (!transceiver->sender()->track() &&
Steve Anton69470252018-02-09 19:43:081267 cricket::MediaTypeToString(transceiver->media_type()) ==
Steve Antonf9381f02017-12-14 18:23:571268 track->kind() &&
Seth Hampson2f0d7022018-02-20 19:54:421269 !transceiver->internal()->has_ever_been_used_to_send() &&
1270 !transceiver->stopped()) {
Steve Antonf9381f02017-12-14 18:23:571271 return transceiver;
1272 }
1273 }
1274 return nullptr;
deadbeefe1f9d832016-01-14 23:35:421275}
1276
1277bool PeerConnection::RemoveTrack(RtpSenderInterface* sender) {
1278 TRACE_EVENT0("webrtc", "PeerConnection::RemoveTrack");
Steve Antonf9381f02017-12-14 18:23:571279 return RemoveTrackInternal(sender).ok();
1280}
1281
1282RTCError PeerConnection::RemoveTrackInternal(
1283 rtc::scoped_refptr<RtpSenderInterface> sender) {
1284 if (!sender) {
1285 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "Sender is null.");
1286 }
deadbeefe1f9d832016-01-14 23:35:421287 if (IsClosed()) {
Steve Antonf9381f02017-12-14 18:23:571288 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
1289 "PeerConnection is closed.");
deadbeefe1f9d832016-01-14 23:35:421290 }
Steve Antonf9381f02017-12-14 18:23:571291 if (IsUnifiedPlan()) {
1292 auto transceiver = FindTransceiverBySender(sender);
1293 if (!transceiver || !sender->track()) {
1294 return RTCError::OK();
1295 }
1296 sender->SetTrack(nullptr);
1297 if (transceiver->direction() == RtpTransceiverDirection::kSendRecv) {
Steve Anton52d86772018-02-20 23:48:121298 transceiver->internal()->set_direction(
1299 RtpTransceiverDirection::kRecvOnly);
Steve Antonf9381f02017-12-14 18:23:571300 } else if (transceiver->direction() == RtpTransceiverDirection::kSendOnly) {
Steve Anton52d86772018-02-20 23:48:121301 transceiver->internal()->set_direction(
1302 RtpTransceiverDirection::kInactive);
Steve Antonf9381f02017-12-14 18:23:571303 }
Steve Anton4171afb2017-11-20 18:20:221304 } else {
Steve Antonf9381f02017-12-14 18:23:571305 bool removed;
1306 if (sender->media_type() == cricket::MEDIA_TYPE_AUDIO) {
1307 removed = GetAudioTransceiver()->internal()->RemoveSender(sender);
1308 } else {
1309 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, sender->media_type());
1310 removed = GetVideoTransceiver()->internal()->RemoveSender(sender);
1311 }
1312 if (!removed) {
1313 LOG_AND_RETURN_ERROR(
1314 RTCErrorType::INVALID_PARAMETER,
1315 "Couldn't find sender " + sender->id() + " to remove.");
1316 }
Steve Anton4171afb2017-11-20 18:20:221317 }
deadbeefe1f9d832016-01-14 23:35:421318 observer_->OnRenegotiationNeeded();
Steve Antonf9381f02017-12-14 18:23:571319 return RTCError::OK();
1320}
1321
1322rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1323PeerConnection::FindTransceiverBySender(
1324 rtc::scoped_refptr<RtpSenderInterface> sender) {
1325 for (auto transceiver : transceivers_) {
1326 if (transceiver->sender() == sender) {
1327 return transceiver;
1328 }
1329 }
1330 return nullptr;
deadbeefe1f9d832016-01-14 23:35:421331}
1332
Steve Anton9158ef62017-11-27 21:01:521333RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1334PeerConnection::AddTransceiver(
1335 rtc::scoped_refptr<MediaStreamTrackInterface> track) {
1336 return AddTransceiver(track, RtpTransceiverInit());
1337}
1338
1339RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1340PeerConnection::AddTransceiver(
1341 rtc::scoped_refptr<MediaStreamTrackInterface> track,
1342 const RtpTransceiverInit& init) {
Steve Antonfc853712018-03-01 21:48:581343 RTC_CHECK(IsUnifiedPlan())
1344 << "AddTransceiver is only available with Unified Plan SdpSemantics";
Steve Anton9158ef62017-11-27 21:01:521345 if (!track) {
1346 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "track is null");
1347 }
1348 cricket::MediaType media_type;
1349 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
1350 media_type = cricket::MEDIA_TYPE_AUDIO;
1351 } else if (track->kind() == MediaStreamTrackInterface::kVideoKind) {
1352 media_type = cricket::MEDIA_TYPE_VIDEO;
1353 } else {
1354 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1355 "Track kind is not audio or video");
1356 }
1357 return AddTransceiver(media_type, track, init);
1358}
1359
1360RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1361PeerConnection::AddTransceiver(cricket::MediaType media_type) {
1362 return AddTransceiver(media_type, RtpTransceiverInit());
1363}
1364
1365RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1366PeerConnection::AddTransceiver(cricket::MediaType media_type,
1367 const RtpTransceiverInit& init) {
Steve Antonfc853712018-03-01 21:48:581368 RTC_CHECK(IsUnifiedPlan())
1369 << "AddTransceiver is only available with Unified Plan SdpSemantics";
Steve Anton9158ef62017-11-27 21:01:521370 if (!(media_type == cricket::MEDIA_TYPE_AUDIO ||
1371 media_type == cricket::MEDIA_TYPE_VIDEO)) {
1372 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1373 "media type is not audio or video");
1374 }
1375 return AddTransceiver(media_type, nullptr, init);
1376}
1377
1378RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1379PeerConnection::AddTransceiver(
1380 cricket::MediaType media_type,
1381 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Steve Anton22da89f2018-01-25 21:58:071382 const RtpTransceiverInit& init,
1383 bool fire_callback) {
Steve Anton9158ef62017-11-27 21:01:521384 RTC_DCHECK((media_type == cricket::MEDIA_TYPE_AUDIO ||
1385 media_type == cricket::MEDIA_TYPE_VIDEO));
1386 if (track) {
1387 RTC_DCHECK_EQ(media_type,
1388 (track->kind() == MediaStreamTrackInterface::kAudioKind
1389 ? cricket::MEDIA_TYPE_AUDIO
1390 : cricket::MEDIA_TYPE_VIDEO));
1391 }
1392
1393 // TODO(bugs.webrtc.org/7600): Verify init.
1394
Steve Anton3d954a62018-04-02 18:27:231395 RTC_LOG(LS_INFO) << "Adding " << cricket::MediaTypeToString(media_type)
1396 << " transceiver in response to a call to AddTransceiver.";
Seth Hampson5b4f0752018-04-02 23:31:361397 auto sender = CreateSender(media_type, track, init.stream_ids);
Steve Anton02ee47c2018-01-11 00:26:061398 auto receiver = CreateReceiver(media_type, rtc::CreateRandomUuid());
1399 auto transceiver = CreateAndAddTransceiver(sender, receiver);
1400 transceiver->internal()->set_direction(init.direction);
1401
Steve Anton22da89f2018-01-25 21:58:071402 if (fire_callback) {
1403 observer_->OnRenegotiationNeeded();
1404 }
Steve Antonf9381f02017-12-14 18:23:571405
1406 return rtc::scoped_refptr<RtpTransceiverInterface>(transceiver);
1407}
1408
Steve Anton02ee47c2018-01-11 00:26:061409rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
1410PeerConnection::CreateSender(
1411 cricket::MediaType media_type,
1412 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 19:34:101413 const std::vector<std::string>& stream_ids) {
Steve Anton9158ef62017-11-27 21:01:521414 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> sender;
Steve Anton02ee47c2018-01-11 00:26:061415 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
1416 RTC_DCHECK(!track ||
1417 (track->kind() == MediaStreamTrackInterface::kAudioKind));
1418 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
1419 signaling_thread(),
Steve Anton47136dd2018-01-12 18:49:351420 new AudioRtpSender(worker_thread(),
1421 static_cast<AudioTrackInterface*>(track.get()),
Seth Hampson845e8782018-03-02 19:34:101422 stream_ids, stats_.get()));
Steve Anton02ee47c2018-01-11 00:26:061423 } else {
1424 RTC_DCHECK_EQ(media_type, cricket::MEDIA_TYPE_VIDEO);
1425 RTC_DCHECK(!track ||
1426 (track->kind() == MediaStreamTrackInterface::kVideoKind));
1427 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
1428 signaling_thread(),
Steve Anton47136dd2018-01-12 18:49:351429 new VideoRtpSender(worker_thread(),
1430 static_cast<VideoTrackInterface*>(track.get()),
Seth Hampson845e8782018-03-02 19:34:101431 stream_ids));
Steve Anton02ee47c2018-01-11 00:26:061432 }
Seth Hampson845e8782018-03-02 19:34:101433 sender->internal()->set_stream_ids(stream_ids);
Steve Anton02ee47c2018-01-11 00:26:061434 return sender;
1435}
1436
1437rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1438PeerConnection::CreateReceiver(cricket::MediaType media_type,
1439 const std::string& receiver_id) {
Steve Anton9158ef62017-11-27 21:01:521440 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1441 receiver;
Steve Anton9158ef62017-11-27 21:01:521442 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton9158ef62017-11-27 21:01:521443 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
Steve Anton60776752018-01-10 19:51:341444 signaling_thread(),
Steve Antond3679212018-01-18 01:41:021445 new AudioRtpReceiver(worker_thread(), receiver_id, {}));
Steve Anton9158ef62017-11-27 21:01:521446 } else {
Steve Anton02ee47c2018-01-11 00:26:061447 RTC_DCHECK_EQ(media_type, cricket::MEDIA_TYPE_VIDEO);
Steve Anton9158ef62017-11-27 21:01:521448 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
1449 signaling_thread(),
Steve Antond3679212018-01-18 01:41:021450 new VideoRtpReceiver(worker_thread(), receiver_id, {}));
Steve Anton9158ef62017-11-27 21:01:521451 }
Steve Anton02ee47c2018-01-11 00:26:061452 return receiver;
1453}
1454
1455rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1456PeerConnection::CreateAndAddTransceiver(
1457 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> sender,
1458 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1459 receiver) {
1460 auto transceiver = RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1461 signaling_thread(), new RtpTransceiver(sender, receiver));
Steve Anton9158ef62017-11-27 21:01:521462 transceivers_.push_back(transceiver);
Steve Anton52d86772018-02-20 23:48:121463 transceiver->internal()->SignalNegotiationNeeded.connect(
1464 this, &PeerConnection::OnNegotiationNeeded);
Steve Antonf9381f02017-12-14 18:23:571465 return transceiver;
Steve Anton9158ef62017-11-27 21:01:521466}
1467
Steve Anton52d86772018-02-20 23:48:121468void PeerConnection::OnNegotiationNeeded() {
1469 RTC_DCHECK_RUN_ON(signaling_thread());
1470 RTC_DCHECK(!IsClosed());
1471 observer_->OnRenegotiationNeeded();
1472}
1473
buildbot@webrtc.orgd4e598d2014-07-29 17:36:521474rtc::scoped_refptr<DtmfSenderInterface> PeerConnection::CreateDtmfSender(
henrike@webrtc.org28e20752013-07-10 00:45:361475 AudioTrackInterface* track) {
Peter Boström1a9d6152015-12-08 21:15:171476 TRACE_EVENT0("webrtc", "PeerConnection::CreateDtmfSender");
zhihuang29ff8442016-07-27 18:07:251477 if (IsClosed()) {
1478 return nullptr;
1479 }
henrike@webrtc.org28e20752013-07-10 00:45:361480 if (!track) {
Mirko Bonadei675513b2017-11-09 10:09:251481 RTC_LOG(LS_ERROR) << "CreateDtmfSender - track is NULL.";
deadbeef20cb0c12017-02-02 04:27:001482 return nullptr;
henrike@webrtc.org28e20752013-07-10 00:45:361483 }
Steve Anton4171afb2017-11-20 18:20:221484 auto track_sender = FindSenderForTrack(track);
1485 if (!track_sender) {
Mirko Bonadei675513b2017-11-09 10:09:251486 RTC_LOG(LS_ERROR) << "CreateDtmfSender called with a non-added track.";
deadbeef20cb0c12017-02-02 04:27:001487 return nullptr;
henrike@webrtc.org28e20752013-07-10 00:45:361488 }
1489
Steve Anton4171afb2017-11-20 18:20:221490 return track_sender->GetDtmfSender();
henrike@webrtc.org28e20752013-07-10 00:45:361491}
1492
deadbeeffac06552015-11-25 19:26:011493rtc::scoped_refptr<RtpSenderInterface> PeerConnection::CreateSender(
deadbeefbd7d8f72015-12-19 00:58:441494 const std::string& kind,
1495 const std::string& stream_id) {
Steve Antonfc853712018-03-01 21:48:581496 RTC_CHECK(!IsUnifiedPlan()) << "CreateSender is not available with Unified "
1497 "Plan SdpSemantics. Please use AddTransceiver "
1498 "instead.";
Peter Boström1a9d6152015-12-08 21:15:171499 TRACE_EVENT0("webrtc", "PeerConnection::CreateSender");
zhihuang29ff8442016-07-27 18:07:251500 if (IsClosed()) {
1501 return nullptr;
1502 }
Steve Anton4171afb2017-11-20 18:20:221503
Seth Hampson5b4f0752018-04-02 23:31:361504 // Internally we need to have one stream with Plan B semantics, so we
1505 // generate a random stream ID if not specified.
Seth Hampson845e8782018-03-02 19:34:101506 std::vector<std::string> stream_ids;
Seth Hampson5b4f0752018-04-02 23:31:361507 if (stream_id.empty()) {
1508 stream_ids.push_back(rtc::CreateRandomUuid());
1509 RTC_LOG(LS_INFO)
1510 << "No stream_id specified for sender. Generated stream ID: "
1511 << stream_ids[0];
1512 } else {
Seth Hampson845e8782018-03-02 19:34:101513 stream_ids.push_back(stream_id);
Steve Anton02ee47c2018-01-11 00:26:061514 }
1515
Steve Anton4171afb2017-11-20 18:20:221516 // TODO(steveanton): Move construction of the RtpSenders to RtpTransceiver.
deadbeefa601f5c2016-06-06 21:27:391517 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender;
deadbeeffac06552015-11-25 19:26:011518 if (kind == MediaStreamTrackInterface::kAudioKind) {
Seth Hampson845e8782018-03-02 19:34:101519 auto* audio_sender =
1520 new AudioRtpSender(worker_thread(), nullptr, stream_ids, stats_.get());
Steve Anton57858b32018-02-15 23:19:501521 audio_sender->SetVoiceMediaChannel(voice_media_channel());
deadbeefa601f5c2016-06-06 21:27:391522 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton02ee47c2018-01-11 00:26:061523 signaling_thread(), audio_sender);
Steve Anton4171afb2017-11-20 18:20:221524 GetAudioTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 19:26:011525 } else if (kind == MediaStreamTrackInterface::kVideoKind) {
Steve Anton47136dd2018-01-12 18:49:351526 auto* video_sender =
Seth Hampson845e8782018-03-02 19:34:101527 new VideoRtpSender(worker_thread(), nullptr, stream_ids);
Steve Anton57858b32018-02-15 23:19:501528 video_sender->SetVideoMediaChannel(video_media_channel());
deadbeefa601f5c2016-06-06 21:27:391529 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton02ee47c2018-01-11 00:26:061530 signaling_thread(), video_sender);
Steve Anton4171afb2017-11-20 18:20:221531 GetVideoTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 19:26:011532 } else {
Mirko Bonadei675513b2017-11-09 10:09:251533 RTC_LOG(LS_ERROR) << "CreateSender called with invalid kind: " << kind;
Steve Anton4171afb2017-11-20 18:20:221534 return nullptr;
deadbeeffac06552015-11-25 19:26:011535 }
Steve Anton4171afb2017-11-20 18:20:221536
deadbeefe1f9d832016-01-14 23:35:421537 return new_sender;
deadbeeffac06552015-11-25 19:26:011538}
1539
deadbeef70ab1a12015-09-28 23:53:551540std::vector<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::GetSenders()
1541 const {
deadbeefa601f5c2016-06-06 21:27:391542 std::vector<rtc::scoped_refptr<RtpSenderInterface>> ret;
Steve Anton4171afb2017-11-20 18:20:221543 for (auto sender : GetSendersInternal()) {
1544 ret.push_back(sender);
deadbeefa601f5c2016-06-06 21:27:391545 }
1546 return ret;
deadbeef70ab1a12015-09-28 23:53:551547}
1548
Steve Anton4171afb2017-11-20 18:20:221549std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1550PeerConnection::GetSendersInternal() const {
1551 std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1552 all_senders;
1553 for (auto transceiver : transceivers_) {
1554 auto senders = transceiver->internal()->senders();
1555 all_senders.insert(all_senders.end(), senders.begin(), senders.end());
1556 }
1557 return all_senders;
1558}
1559
deadbeef70ab1a12015-09-28 23:53:551560std::vector<rtc::scoped_refptr<RtpReceiverInterface>>
1561PeerConnection::GetReceivers() const {
deadbeefa601f5c2016-06-06 21:27:391562 std::vector<rtc::scoped_refptr<RtpReceiverInterface>> ret;
Steve Anton4171afb2017-11-20 18:20:221563 for (const auto& receiver : GetReceiversInternal()) {
1564 ret.push_back(receiver);
deadbeefa601f5c2016-06-06 21:27:391565 }
1566 return ret;
deadbeef70ab1a12015-09-28 23:53:551567}
1568
Steve Anton4171afb2017-11-20 18:20:221569std::vector<
1570 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1571PeerConnection::GetReceiversInternal() const {
1572 std::vector<
1573 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1574 all_receivers;
1575 for (auto transceiver : transceivers_) {
1576 auto receivers = transceiver->internal()->receivers();
1577 all_receivers.insert(all_receivers.end(), receivers.begin(),
1578 receivers.end());
1579 }
1580 return all_receivers;
1581}
1582
Steve Anton9158ef62017-11-27 21:01:521583std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
1584PeerConnection::GetTransceivers() const {
Steve Antonfc853712018-03-01 21:48:581585 RTC_CHECK(IsUnifiedPlan())
1586 << "GetTransceivers is only supported with Unified Plan SdpSemantics.";
Steve Anton9158ef62017-11-27 21:01:521587 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> all_transceivers;
1588 for (auto transceiver : transceivers_) {
1589 all_transceivers.push_back(transceiver);
1590 }
1591 return all_transceivers;
1592}
1593
henrike@webrtc.org28e20752013-07-10 00:45:361594bool PeerConnection::GetStats(StatsObserver* observer,
wu@webrtc.orgb9a088b2014-02-13 23:18:491595 MediaStreamTrackInterface* track,
1596 StatsOutputLevel level) {
Peter Boström1a9d6152015-12-08 21:15:171597 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
deadbeef0a6c4ca2015-10-06 18:38:281598 RTC_DCHECK(signaling_thread()->IsCurrent());
nisse7ce109a2017-01-31 08:57:561599 if (!observer) {
Mirko Bonadei675513b2017-11-09 10:09:251600 RTC_LOG(LS_ERROR) << "GetStats - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:361601 return false;
1602 }
1603
tommi@webrtc.org03505bc2014-07-14 20:15:261604 stats_->UpdateStats(level);
zhihuange9e94c32016-11-04 18:38:151605 // The StatsCollector is used to tell if a track is valid because it may
1606 // remember tracks that the PeerConnection previously removed.
1607 if (track && !stats_->IsValidTrack(track->id())) {
Mirko Bonadei675513b2017-11-09 10:09:251608 RTC_LOG(LS_WARNING) << "GetStats is called with an invalid track: "
1609 << track->id();
zhihuange9e94c32016-11-04 18:38:151610 return false;
1611 }
Taylor Brandstetter5d97a9a2016-06-10 21:17:271612 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_GETSTATS,
tommi@webrtc.org5b06b062014-08-15 08:38:301613 new GetStatsMsg(observer, track));
henrike@webrtc.org28e20752013-07-10 00:45:361614 return true;
1615}
1616
hbos74e1a4f2016-09-16 06:33:011617void PeerConnection::GetStats(RTCStatsCollectorCallback* callback) {
Henrik Boström1df1bf82018-03-20 12:24:201618 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
hbos74e1a4f2016-09-16 06:33:011619 RTC_DCHECK(stats_collector_);
Henrik Boström1df1bf82018-03-20 12:24:201620 RTC_DCHECK(callback);
hbos74e1a4f2016-09-16 06:33:011621 stats_collector_->GetStatsReport(callback);
1622}
1623
Henrik Boström1df1bf82018-03-20 12:24:201624void PeerConnection::GetStats(
1625 rtc::scoped_refptr<RtpSenderInterface> selector,
1626 rtc::scoped_refptr<RTCStatsCollectorCallback> callback) {
1627 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
1628 RTC_DCHECK(callback);
1629 RTC_DCHECK(stats_collector_);
1630 rtc::scoped_refptr<RtpSenderInternal> internal_sender;
1631 if (selector) {
1632 for (const auto& proxy_transceiver : transceivers_) {
1633 for (const auto& proxy_sender :
1634 proxy_transceiver->internal()->senders()) {
1635 if (proxy_sender == selector) {
1636 internal_sender = proxy_sender->internal();
1637 break;
1638 }
1639 }
1640 if (internal_sender)
1641 break;
1642 }
1643 }
1644 // If there is no |internal_sender| then |selector| is either null or does not
1645 // belong to the PeerConnection (in Plan B, senders can be removed from the
1646 // PeerConnection). This means that "all the stats objects representing the
1647 // selector" is an empty set. Invoking GetStatsReport() with a null selector
1648 // produces an empty stats report.
1649 stats_collector_->GetStatsReport(internal_sender, callback);
1650}
1651
1652void PeerConnection::GetStats(
1653 rtc::scoped_refptr<RtpReceiverInterface> selector,
1654 rtc::scoped_refptr<RTCStatsCollectorCallback> callback) {
1655 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
1656 RTC_DCHECK(callback);
1657 RTC_DCHECK(stats_collector_);
1658 rtc::scoped_refptr<RtpReceiverInternal> internal_receiver;
1659 if (selector) {
1660 for (const auto& proxy_transceiver : transceivers_) {
1661 for (const auto& proxy_receiver :
1662 proxy_transceiver->internal()->receivers()) {
1663 if (proxy_receiver == selector) {
1664 internal_receiver = proxy_receiver->internal();
1665 break;
1666 }
1667 }
1668 if (internal_receiver)
1669 break;
1670 }
1671 }
1672 // If there is no |internal_receiver| then |selector| is either null or does
1673 // not belong to the PeerConnection (in Plan B, receivers can be removed from
1674 // the PeerConnection). This means that "all the stats objects representing
1675 // the selector" is an empty set. Invoking GetStatsReport() with a null
1676 // selector produces an empty stats report.
1677 stats_collector_->GetStatsReport(internal_receiver, callback);
1678}
1679
henrike@webrtc.org28e20752013-07-10 00:45:361680PeerConnectionInterface::SignalingState PeerConnection::signaling_state() {
1681 return signaling_state_;
1682}
1683
henrike@webrtc.org28e20752013-07-10 00:45:361684PeerConnectionInterface::IceConnectionState
1685PeerConnection::ice_connection_state() {
1686 return ice_connection_state_;
1687}
1688
1689PeerConnectionInterface::IceGatheringState
1690PeerConnection::ice_gathering_state() {
1691 return ice_gathering_state_;
1692}
1693
buildbot@webrtc.orgd4e598d2014-07-29 17:36:521694rtc::scoped_refptr<DataChannelInterface>
henrike@webrtc.org28e20752013-07-10 00:45:361695PeerConnection::CreateDataChannel(
1696 const std::string& label,
1697 const DataChannelInit* config) {
Peter Boström1a9d6152015-12-08 21:15:171698 TRACE_EVENT0("webrtc", "PeerConnection::CreateDataChannel");
zhihuang9763d562016-08-05 18:14:501699
deadbeefab9b2d12015-10-14 18:33:111700 bool first_datachannel = !HasDataChannels();
jiayl@webrtc.org001fd2d2014-05-29 15:31:111701
kwibergd1fe2812016-04-27 13:47:291702 std::unique_ptr<InternalDataChannelInit> internal_config;
henrika@webrtc.orgaebb1ad2014-01-14 10:00:581703 if (config) {
1704 internal_config.reset(new InternalDataChannelInit(*config));
1705 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:521706 rtc::scoped_refptr<DataChannelInterface> channel(
deadbeefab9b2d12015-10-14 18:33:111707 InternalCreateDataChannel(label, internal_config.get()));
1708 if (!channel.get()) {
1709 return nullptr;
1710 }
henrike@webrtc.org28e20752013-07-10 00:45:361711
jiayl@webrtc.org001fd2d2014-05-29 15:31:111712 // Trigger the onRenegotiationNeeded event for every new RTP DataChannel, or
1713 // the first SCTP DataChannel.
Steve Anton75737c02017-11-06 18:37:171714 if (data_channel_type() == cricket::DCT_RTP || first_datachannel) {
jiayl@webrtc.org001fd2d2014-05-29 15:31:111715 observer_->OnRenegotiationNeeded();
1716 }
wu@webrtc.org91053e72013-08-10 07:18:041717
henrike@webrtc.org28e20752013-07-10 00:45:361718 return DataChannelProxy::Create(signaling_thread(), channel.get());
1719}
1720
1721void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
1722 const MediaConstraintsInterface* constraints) {
Peter Boström1a9d6152015-12-08 21:15:171723 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
Steve Anton8d3444d2017-10-20 22:30:511724
zhihuang1c378ed2017-08-17 21:10:501725 PeerConnectionInterface::RTCOfferAnswerOptions offer_answer_options;
1726 // Always create an offer even if |ConvertConstraintsToOfferAnswerOptions|
1727 // returns false for now. Because |ConvertConstraintsToOfferAnswerOptions|
1728 // compares the mandatory fields parsed with the mandatory fields added in the
1729 // |constraints| and some downstream applications might create offers with
1730 // mandatory fields which would not be parsed in the helper method. For
1731 // example, in Chromium/remoting, |kEnableDtlsSrtp| is added to the
1732 // |constraints| as a mandatory field but it is not parsed.
1733 ConvertConstraintsToOfferAnswerOptions(constraints, &offer_answer_options);
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:161734
zhihuang1c378ed2017-08-17 21:10:501735 CreateOffer(observer, offer_answer_options);
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:161736}
1737
1738void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
1739 const RTCOfferAnswerOptions& options) {
Peter Boström1a9d6152015-12-08 21:15:171740 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
Steve Anton8d3444d2017-10-20 22:30:511741
nisse7ce109a2017-01-31 08:57:561742 if (!observer) {
Mirko Bonadei675513b2017-11-09 10:09:251743 RTC_LOG(LS_ERROR) << "CreateOffer - observer is NULL.";
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:161744 return;
1745 }
deadbeefab9b2d12015-10-14 18:33:111746
Steve Anton8d3444d2017-10-20 22:30:511747 if (IsClosed()) {
1748 std::string error = "CreateOffer called when PeerConnection is closed.";
Mirko Bonadei675513b2017-11-09 10:09:251749 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 14:18:031750 PostCreateSessionDescriptionFailure(
1751 observer, RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error)));
Steve Anton8d3444d2017-10-20 22:30:511752 return;
1753 }
1754
zhihuang1c378ed2017-08-17 21:10:501755 if (!ValidateOfferAnswerOptions(options)) {
deadbeefab9b2d12015-10-14 18:33:111756 std::string error = "CreateOffer called with invalid options.";
Mirko Bonadei675513b2017-11-09 10:09:251757 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 14:18:031758 PostCreateSessionDescriptionFailure(
1759 observer, RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error)));
deadbeefab9b2d12015-10-14 18:33:111760 return;
1761 }
1762
Steve Anton22da89f2018-01-25 21:58:071763 // Legacy handling for offer_to_receive_audio and offer_to_receive_video.
1764 // Specified in WebRTC section 4.4.3.2 "Legacy configuration extensions".
1765 if (IsUnifiedPlan()) {
1766 RTCError error = HandleLegacyOfferOptions(options);
1767 if (!error.ok()) {
Harald Alvestrand5081c0c2018-03-09 14:18:031768 PostCreateSessionDescriptionFailure(observer, std::move(error));
Steve Anton22da89f2018-01-25 21:58:071769 return;
1770 }
1771 }
1772
zhihuang1c378ed2017-08-17 21:10:501773 cricket::MediaSessionOptions session_options;
1774 GetOptionsForOffer(options, &session_options);
Steve Antond25da372017-11-06 22:50:291775 webrtc_session_desc_factory_->CreateOffer(observer, options, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:361776}
1777
Steve Anton22da89f2018-01-25 21:58:071778RTCError PeerConnection::HandleLegacyOfferOptions(
1779 const RTCOfferAnswerOptions& options) {
1780 RTC_DCHECK(IsUnifiedPlan());
1781
1782 if (options.offer_to_receive_audio == 0) {
1783 RemoveRecvDirectionFromReceivingTransceiversOfType(
1784 cricket::MEDIA_TYPE_AUDIO);
1785 } else if (options.offer_to_receive_audio == 1) {
1786 AddUpToOneReceivingTransceiverOfType(cricket::MEDIA_TYPE_AUDIO);
1787 } else if (options.offer_to_receive_audio > 1) {
1788 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
1789 "offer_to_receive_audio > 1 is not supported.");
1790 }
1791
1792 if (options.offer_to_receive_video == 0) {
1793 RemoveRecvDirectionFromReceivingTransceiversOfType(
1794 cricket::MEDIA_TYPE_VIDEO);
1795 } else if (options.offer_to_receive_video == 1) {
1796 AddUpToOneReceivingTransceiverOfType(cricket::MEDIA_TYPE_VIDEO);
1797 } else if (options.offer_to_receive_video > 1) {
1798 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
1799 "offer_to_receive_video > 1 is not supported.");
1800 }
1801
1802 return RTCError::OK();
1803}
1804
1805void PeerConnection::RemoveRecvDirectionFromReceivingTransceiversOfType(
1806 cricket::MediaType media_type) {
1807 for (auto transceiver : GetReceivingTransceiversOfType(media_type)) {
Steve Anton3d954a62018-04-02 18:27:231808 RtpTransceiverDirection new_direction =
1809 RtpTransceiverDirectionWithRecvSet(transceiver->direction(), false);
1810 if (new_direction != transceiver->direction()) {
1811 RTC_LOG(LS_INFO) << "Changing " << cricket::MediaTypeToString(media_type)
1812 << " transceiver (MID="
1813 << transceiver->mid().value_or("<not set>") << ") from "
1814 << RtpTransceiverDirectionToString(
1815 transceiver->direction())
1816 << " to "
1817 << RtpTransceiverDirectionToString(new_direction)
1818 << " since CreateOffer specified offer_to_receive=0";
1819 transceiver->internal()->set_direction(new_direction);
1820 }
Steve Anton22da89f2018-01-25 21:58:071821 }
1822}
1823
1824void PeerConnection::AddUpToOneReceivingTransceiverOfType(
1825 cricket::MediaType media_type) {
1826 if (GetReceivingTransceiversOfType(media_type).empty()) {
Steve Anton3d954a62018-04-02 18:27:231827 RTC_LOG(LS_INFO)
1828 << "Adding one recvonly " << cricket::MediaTypeToString(media_type)
1829 << " transceiver since CreateOffer specified offer_to_receive=1";
Steve Anton22da89f2018-01-25 21:58:071830 RtpTransceiverInit init;
1831 init.direction = RtpTransceiverDirection::kRecvOnly;
1832 AddTransceiver(media_type, nullptr, init, /*fire_callback=*/false);
1833 }
1834}
1835
1836std::vector<rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
1837PeerConnection::GetReceivingTransceiversOfType(cricket::MediaType media_type) {
1838 std::vector<
1839 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
1840 receiving_transceivers;
1841 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 19:43:081842 if (!transceiver->stopped() && transceiver->media_type() == media_type &&
Steve Anton22da89f2018-01-25 21:58:071843 RtpTransceiverDirectionHasRecv(transceiver->direction())) {
1844 receiving_transceivers.push_back(transceiver);
1845 }
1846 }
1847 return receiving_transceivers;
1848}
1849
henrike@webrtc.org28e20752013-07-10 00:45:361850void PeerConnection::CreateAnswer(
1851 CreateSessionDescriptionObserver* observer,
1852 const MediaConstraintsInterface* constraints) {
Peter Boström1a9d6152015-12-08 21:15:171853 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
Steve Anton8d3444d2017-10-20 22:30:511854
nisse7ce109a2017-01-31 08:57:561855 if (!observer) {
Mirko Bonadei675513b2017-11-09 10:09:251856 RTC_LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:361857 return;
1858 }
deadbeefab9b2d12015-10-14 18:33:111859
zhihuang1c378ed2017-08-17 21:10:501860 PeerConnectionInterface::RTCOfferAnswerOptions offer_answer_options;
1861 if (!ConvertConstraintsToOfferAnswerOptions(constraints,
1862 &offer_answer_options)) {
deadbeefab9b2d12015-10-14 18:33:111863 std::string error = "CreateAnswer called with invalid constraints.";
Mirko Bonadei675513b2017-11-09 10:09:251864 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 14:18:031865 PostCreateSessionDescriptionFailure(
1866 observer, RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error)));
deadbeefab9b2d12015-10-14 18:33:111867 return;
1868 }
1869
Steve Anton8d3444d2017-10-20 22:30:511870 CreateAnswer(observer, offer_answer_options);
htaa2a49d92016-03-04 10:51:391871}
1872
1873void PeerConnection::CreateAnswer(CreateSessionDescriptionObserver* observer,
1874 const RTCOfferAnswerOptions& options) {
1875 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
nisse7ce109a2017-01-31 08:57:561876 if (!observer) {
Mirko Bonadei675513b2017-11-09 10:09:251877 RTC_LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
htaa2a49d92016-03-04 10:51:391878 return;
1879 }
1880
Steve Antondffead82018-02-06 18:31:291881 if (!(signaling_state_ == kHaveRemoteOffer ||
1882 signaling_state_ == kHaveLocalPrAnswer)) {
1883 std::string error =
1884 "PeerConnection cannot create an answer in a state other than "
1885 "have-remote-offer or have-local-pranswer.";
Mirko Bonadei675513b2017-11-09 10:09:251886 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 14:18:031887 PostCreateSessionDescriptionFailure(
1888 observer, RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error)));
Steve Anton8d3444d2017-10-20 22:30:511889 return;
1890 }
1891
Steve Antondffead82018-02-06 18:31:291892 // The remote description should be set if we're in the right state.
1893 RTC_DCHECK(remote_description());
Steve Anton8d3444d2017-10-20 22:30:511894
Steve Anton22da89f2018-01-25 21:58:071895 if (IsUnifiedPlan()) {
1896 if (options.offer_to_receive_audio != RTCOfferAnswerOptions::kUndefined) {
1897 RTC_LOG(LS_WARNING) << "CreateAnswer: offer_to_receive_audio is not "
1898 "supported with Unified Plan semantics. Use the "
1899 "RtpTransceiver API instead.";
1900 }
1901 if (options.offer_to_receive_video != RTCOfferAnswerOptions::kUndefined) {
1902 RTC_LOG(LS_WARNING) << "CreateAnswer: offer_to_receive_video is not "
1903 "supported with Unified Plan semantics. Use the "
1904 "RtpTransceiver API instead.";
1905 }
1906 }
1907
htaa2a49d92016-03-04 10:51:391908 cricket::MediaSessionOptions session_options;
zhihuang1c378ed2017-08-17 21:10:501909 GetOptionsForAnswer(options, &session_options);
htaa2a49d92016-03-04 10:51:391910
Steve Antond25da372017-11-06 22:50:291911 webrtc_session_desc_factory_->CreateAnswer(observer, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:361912}
1913
1914void PeerConnection::SetLocalDescription(
1915 SetSessionDescriptionObserver* observer,
Steve Anton80dd7b52018-02-17 01:08:421916 SessionDescriptionInterface* desc_ptr) {
Peter Boström1a9d6152015-12-08 21:15:171917 TRACE_EVENT0("webrtc", "PeerConnection::SetLocalDescription");
Steve Anton8a006912017-12-04 23:25:561918
Steve Anton80dd7b52018-02-17 01:08:421919 // The SetLocalDescription contract is that we take ownership of the session
1920 // description regardless of the outcome, so wrap it in a unique_ptr right
1921 // away. Ideally, SetLocalDescription's signature will be changed to take the
1922 // description as a unique_ptr argument to formalize this agreement.
1923 std::unique_ptr<SessionDescriptionInterface> desc(desc_ptr);
1924
nisse7ce109a2017-01-31 08:57:561925 if (!observer) {
Mirko Bonadei675513b2017-11-09 10:09:251926 RTC_LOG(LS_ERROR) << "SetLocalDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:361927 return;
1928 }
Steve Anton8a006912017-12-04 23:25:561929
henrike@webrtc.org28e20752013-07-10 00:45:361930 if (!desc) {
Harald Alvestrand5081c0c2018-03-09 14:18:031931 PostSetSessionDescriptionFailure(
1932 observer,
1933 RTCError(RTCErrorType::INTERNAL_ERROR, "SessionDescription is NULL."));
henrike@webrtc.org28e20752013-07-10 00:45:361934 return;
1935 }
Steve Anton8d3444d2017-10-20 22:30:511936
Steve Anton80dd7b52018-02-17 01:08:421937 // If a session error has occurred the PeerConnection is in a possibly
1938 // inconsistent state so fail right away.
1939 if (session_error() != SessionError::kNone) {
1940 std::string error_message = GetSessionErrorMsg();
1941 RTC_LOG(LS_ERROR) << "SetLocalDescription: " << error_message;
Harald Alvestrand5081c0c2018-03-09 14:18:031942 PostSetSessionDescriptionFailure(
1943 observer,
1944 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton80dd7b52018-02-17 01:08:421945 return;
1946 }
Steve Anton8d3444d2017-10-20 22:30:511947
Steve Anton80dd7b52018-02-17 01:08:421948 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_LOCAL);
1949 if (!error.ok()) {
1950 std::string error_message = GetSetDescriptionErrorMessage(
1951 cricket::CS_LOCAL, desc->GetType(), error);
1952 RTC_LOG(LS_ERROR) << error_message;
Harald Alvestrand5081c0c2018-03-09 14:18:031953 PostSetSessionDescriptionFailure(
1954 observer,
1955 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton80dd7b52018-02-17 01:08:421956 return;
1957 }
1958
1959 // Grab the description type before moving ownership to ApplyLocalDescription,
1960 // which may destroy it before returning.
1961 const SdpType type = desc->GetType();
1962
1963 error = ApplyLocalDescription(std::move(desc));
Steve Anton8a006912017-12-04 23:25:561964 // |desc| may be destroyed at this point.
1965
1966 if (!error.ok()) {
Steve Anton80dd7b52018-02-17 01:08:421967 // If ApplyLocalDescription fails, the PeerConnection could be in an
1968 // inconsistent state, so act conservatively here and set the session error
1969 // so that future calls to SetLocalDescription/SetRemoteDescription fail.
1970 SetSessionError(SessionError::kContent, error.message());
1971 std::string error_message =
1972 GetSetDescriptionErrorMessage(cricket::CS_LOCAL, type, error);
1973 RTC_LOG(LS_ERROR) << error_message;
Harald Alvestrand5081c0c2018-03-09 14:18:031974 PostSetSessionDescriptionFailure(
1975 observer,
1976 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton8d3444d2017-10-20 22:30:511977 return;
1978 }
Steve Anton8a006912017-12-04 23:25:561979 RTC_DCHECK(local_description());
1980
1981 PostSetSessionDescriptionSuccess(observer);
1982
Patrik Höglund3dc41062018-04-11 11:13:571983 // According to JSEP, after setLocalDescription, changing the candidate pool
1984 // size is not allowed, and changing the set of ICE servers will not result
1985 // in new candidates being gathered.
1986 port_allocator_->FreezeCandidatePool();
1987
Steve Anton8a006912017-12-04 23:25:561988 // MaybeStartGathering needs to be called after posting
1989 // MSG_SET_SESSIONDESCRIPTION_SUCCESS, so that we don't signal any candidates
1990 // before signaling that SetLocalDescription completed.
1991 transport_controller_->MaybeStartGathering();
1992
Steve Antona3a92c22017-12-07 18:27:411993 if (local_description()->GetType() == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 23:25:561994 // TODO(deadbeef): We already had to hop to the network thread for
1995 // MaybeStartGathering...
1996 network_thread()->Invoke<void>(
1997 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
1998 port_allocator_.get()));
Steve Anton0ffaaa22018-02-23 18:31:301999 // Make UMA notes about what was agreed to.
2000 ReportNegotiatedSdpSemantics(*local_description());
Steve Anton8a006912017-12-04 23:25:562001 }
2002}
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 Antond3679212018-01-18 01:41:022116 }
2117 }
2118 } else {
2119 // Plan B semantics.
2120
Steve Antondcc3c022017-12-23 00:02:542121 // Update state and SSRC of local MediaStreams and DataChannels based on the
2122 // local session description.
2123 const cricket::ContentInfo* audio_content =
2124 GetFirstAudioContent(local_description()->description());
2125 if (audio_content) {
2126 if (audio_content->rejected) {
2127 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
2128 } else {
2129 const cricket::AudioContentDescription* audio_desc =
2130 audio_content->media_description()->as_audio();
2131 UpdateLocalSenders(audio_desc->streams(), audio_desc->type());
2132 }
deadbeeffaac4972015-11-12 23:33:072133 }
deadbeefab9b2d12015-10-14 18:33:112134
Steve Antondcc3c022017-12-23 00:02:542135 const cricket::ContentInfo* video_content =
2136 GetFirstVideoContent(local_description()->description());
2137 if (video_content) {
2138 if (video_content->rejected) {
2139 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
2140 } else {
2141 const cricket::VideoContentDescription* video_desc =
2142 video_content->media_description()->as_video();
2143 UpdateLocalSenders(video_desc->streams(), video_desc->type());
2144 }
deadbeeffaac4972015-11-12 23:33:072145 }
deadbeefab9b2d12015-10-14 18:33:112146 }
2147
2148 const cricket::ContentInfo* data_content =
Henrik Boströmfdb92012017-11-09 18:55:442149 GetFirstDataContent(local_description()->description());
deadbeefab9b2d12015-10-14 18:33:112150 if (data_content) {
2151 const cricket::DataContentDescription* data_desc =
Steve Antonb1c1de12017-12-21 23:14:302152 data_content->media_description()->as_data();
deadbeefab9b2d12015-10-14 18:33:112153 if (rtc::starts_with(data_desc->protocol().data(),
2154 cricket::kMediaProtocolRtpPrefix)) {
2155 UpdateLocalRtpDataChannels(data_desc->streams());
2156 }
2157 }
2158
Steve Anton8a006912017-12-04 23:25:562159 return RTCError::OK();
henrike@webrtc.org28e20752013-07-10 00:45:362160}
2161
2162void PeerConnection::SetRemoteDescription(
Henrik Boströma4ecf552017-11-23 14:17:072163 SetSessionDescriptionObserver* observer,
2164 SessionDescriptionInterface* desc) {
Henrik Boström31638672017-11-23 16:48:322165 SetRemoteDescription(
2166 std::unique_ptr<SessionDescriptionInterface>(desc),
2167 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface>(
2168 new SetRemoteDescriptionObserverAdapter(this, observer)));
2169}
2170
2171void PeerConnection::SetRemoteDescription(
2172 std::unique_ptr<SessionDescriptionInterface> desc,
2173 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface> observer) {
Peter Boström1a9d6152015-12-08 21:15:172174 TRACE_EVENT0("webrtc", "PeerConnection::SetRemoteDescription");
Steve Anton8a006912017-12-04 23:25:562175
nisse7ce109a2017-01-31 08:57:562176 if (!observer) {
Mirko Bonadei675513b2017-11-09 10:09:252177 RTC_LOG(LS_ERROR) << "SetRemoteDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:362178 return;
2179 }
Steve Anton8a006912017-12-04 23:25:562180
henrike@webrtc.org28e20752013-07-10 00:45:362181 if (!desc) {
Henrik Boström31638672017-11-23 16:48:322182 observer->OnSetRemoteDescriptionComplete(RTCError(
Steve Anton8a006912017-12-04 23:25:562183 RTCErrorType::INVALID_PARAMETER, "SessionDescription is NULL."));
henrike@webrtc.org28e20752013-07-10 00:45:362184 return;
2185 }
Steve Anton8d3444d2017-10-20 22:30:512186
Steve Anton80dd7b52018-02-17 01:08:422187 // If a session error has occurred the PeerConnection is in a possibly
2188 // inconsistent state so fail right away.
2189 if (session_error() != SessionError::kNone) {
2190 std::string error_message = GetSessionErrorMsg();
2191 RTC_LOG(LS_ERROR) << "SetRemoteDescription: " << error_message;
2192 observer->OnSetRemoteDescriptionComplete(
2193 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
2194 return;
2195 }
Steve Anton71439a62018-02-15 19:53:062196
Steve Antonba42e992018-04-09 21:10:012197 if (desc->GetType() == SdpType::kOffer) {
2198 // Report to UMA the format of the received offer.
2199 ReportSdpFormatReceived(*desc);
2200 }
2201
Steve Anton80dd7b52018-02-17 01:08:422202 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_REMOTE);
Steve Anton71439a62018-02-15 19:53:062203 if (!error.ok()) {
Steve Anton80dd7b52018-02-17 01:08:422204 std::string error_message = GetSetDescriptionErrorMessage(
2205 cricket::CS_REMOTE, desc->GetType(), error);
2206 RTC_LOG(LS_ERROR) << error_message;
Steve Anton71439a62018-02-15 19:53:062207 observer->OnSetRemoteDescriptionComplete(
2208 RTCError(error.type(), std::move(error_message)));
2209 return;
2210 }
Steve Anton71439a62018-02-15 19:53:062211
Steve Anton80dd7b52018-02-17 01:08:422212 // Grab the description type before moving ownership to
2213 // ApplyRemoteDescription, which may destroy it before returning.
2214 const SdpType type = desc->GetType();
2215
2216 error = ApplyRemoteDescription(std::move(desc));
2217 // |desc| may be destroyed at this point.
2218
2219 if (!error.ok()) {
2220 // If ApplyRemoteDescription fails, the PeerConnection could be in an
2221 // inconsistent state, so act conservatively here and set the session error
2222 // so that future calls to SetLocalDescription/SetRemoteDescription fail.
2223 SetSessionError(SessionError::kContent, error.message());
2224 std::string error_message =
2225 GetSetDescriptionErrorMessage(cricket::CS_REMOTE, type, error);
2226 RTC_LOG(LS_ERROR) << error_message;
2227 observer->OnSetRemoteDescriptionComplete(
2228 RTCError(error.type(), std::move(error_message)));
2229 return;
2230 }
2231 RTC_DCHECK(remote_description());
2232
2233 if (type == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 23:25:562234 // TODO(deadbeef): We already had to hop to the network thread for
2235 // MaybeStartGathering...
2236 network_thread()->Invoke<void>(
2237 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
2238 port_allocator_.get()));
Harald Alvestrand5dbb5862018-02-13 22:48:002239 // Make UMA notes about what was agreed to.
Steve Anton0ffaaa22018-02-23 18:31:302240 ReportNegotiatedSdpSemantics(*remote_description());
Steve Anton8a006912017-12-04 23:25:562241 }
2242
2243 observer->OnSetRemoteDescriptionComplete(RTCError::OK());
2244}
2245
2246RTCError PeerConnection::ApplyRemoteDescription(
2247 std::unique_ptr<SessionDescriptionInterface> desc) {
2248 RTC_DCHECK_RUN_ON(signaling_thread());
2249 RTC_DCHECK(desc);
2250
henrike@webrtc.org28e20752013-07-10 00:45:362251 // Update stats here so that we have the most recent stats for tracks and
2252 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:262253 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 23:25:562254
Steve Antondcc3c022017-12-23 00:02:542255 // Take a reference to the old remote description since it's used below to
2256 // compare against the new remote description. When setting the new remote
2257 // description, grab ownership of the replaced session description in case it
2258 // is the same as |old_remote_description|, to keep it alive for the duration
2259 // of the method.
Steve Anton8a006912017-12-04 23:25:562260 const SessionDescriptionInterface* old_remote_description =
2261 remote_description();
Steve Anton8a006912017-12-04 23:25:562262 std::unique_ptr<SessionDescriptionInterface> replaced_remote_description;
Steve Anton3828c062017-12-06 18:34:512263 SdpType type = desc->GetType();
2264 if (type == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 23:25:562265 replaced_remote_description = pending_remote_description_
2266 ? std::move(pending_remote_description_)
2267 : std::move(current_remote_description_);
2268 current_remote_description_ = std::move(desc);
2269 pending_remote_description_ = nullptr;
2270 current_local_description_ = std::move(pending_local_description_);
2271 } else {
2272 replaced_remote_description = std::move(pending_remote_description_);
2273 pending_remote_description_ = std::move(desc);
henrike@webrtc.org28e20752013-07-10 00:45:362274 }
Steve Anton8a006912017-12-04 23:25:562275 // The session description to apply now must be accessed by
2276 // |remote_description()|.
Henrik Boströmfdb92012017-11-09 18:55:442277 RTC_DCHECK(remote_description());
henrike@webrtc.org28e20752013-07-10 00:45:362278
Zhi Huange830e682018-03-30 17:48:352279 RTCError error = PushdownTransportDescription(cricket::CS_REMOTE, type);
2280 if (!error.ok()) {
2281 return error;
2282 }
Steve Anton8a006912017-12-04 23:25:562283 // Transport and Media channels will be created only when offer is set.
Steve Antondcc3c022017-12-23 00:02:542284 if (IsUnifiedPlan()) {
2285 RTCError error = UpdateTransceiversAndDataChannels(
Seth Hampsonae8a90a2018-02-13 23:33:482286 cricket::CS_REMOTE, *remote_description(), local_description(),
2287 old_remote_description);
Steve Anton8a006912017-12-04 23:25:562288 if (!error.ok()) {
2289 return error;
2290 }
Steve Antondcc3c022017-12-23 00:02:542291 } else {
Zhi Huange830e682018-03-30 17:48:352292 // Media channels will be created only when offer is set. These may use new
2293 // transports just created by PushdownTransportDescription.
Steve Antondcc3c022017-12-23 00:02:542294 if (type == SdpType::kOffer) {
Zhi Huange830e682018-03-30 17:48:352295 // TODO(mallinath) - Handle CreateChannel failure, as new local
Steve Antondcc3c022017-12-23 00:02:542296 // description is applied. Restore back to old description.
2297 RTCError error = CreateChannels(*remote_description()->description());
2298 if (!error.ok()) {
2299 return error;
2300 }
2301 }
Steve Antondcc3c022017-12-23 00:02:542302 // Remove unused channels if MediaContentDescription is rejected.
2303 RemoveUnusedChannels(remote_description()->description());
2304 }
Steve Anton8a006912017-12-04 23:25:562305
Zhi Huange830e682018-03-30 17:48:352306 // NOTE: Candidates allocation will be initiated only when
2307 // SetLocalDescription is called.
2308 error = UpdateSessionState(type, cricket::CS_REMOTE,
2309 remote_description()->description());
Steve Anton8a006912017-12-04 23:25:562310 if (!error.ok()) {
2311 return error;
2312 }
2313
2314 if (local_description() &&
2315 !UseCandidatesInSessionDescription(remote_description())) {
2316 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidCandidates);
2317 }
2318
2319 if (old_remote_description) {
2320 for (const cricket::ContentInfo& content :
2321 old_remote_description->description()->contents()) {
2322 // Check if this new SessionDescription contains new ICE ufrag and
2323 // password that indicates the remote peer requests an ICE restart.
2324 // TODO(deadbeef): When we start storing both the current and pending
2325 // remote description, this should reset pending_ice_restarts and compare
2326 // against the current description.
2327 if (CheckForRemoteIceRestart(old_remote_description, remote_description(),
2328 content.name)) {
Steve Anton3828c062017-12-06 18:34:512329 if (type == SdpType::kOffer) {
Steve Anton8a006912017-12-04 23:25:562330 pending_ice_restarts_.insert(content.name);
2331 }
2332 } else {
2333 // We retain all received candidates only if ICE is not restarted.
2334 // When ICE is restarted, all previous candidates belong to an old
2335 // generation and should not be kept.
2336 // TODO(deadbeef): This goes against the W3C spec which says the remote
2337 // description should only contain candidates from the last set remote
2338 // description plus any candidates added since then. We should remove
2339 // this once we're sure it won't break anything.
2340 WebRtcSessionDescriptionFactory::CopyCandidatesFromSessionDescription(
2341 old_remote_description, content.name, mutable_remote_description());
2342 }
2343 }
2344 }
2345
2346 if (session_error() != SessionError::kNone) {
2347 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
2348 }
2349
2350 // Set the the ICE connection state to connecting since the connection may
2351 // become writable with peer reflexive candidates before any remote candidate
2352 // is signaled.
2353 // TODO(pthatcher): This is a short-term solution for crbug/446908. A real fix
2354 // is to have a new signal the indicates a change in checking state from the
2355 // transport and expose a new checking() member from transport that can be
2356 // read to determine the current checking state. The existing SignalConnecting
2357 // actually means "gathering candidates", so cannot be be used here.
Steve Antona3a92c22017-12-07 18:27:412358 if (remote_description()->GetType() != SdpType::kOffer &&
Steve Anton8a006912017-12-04 23:25:562359 ice_connection_state() == PeerConnectionInterface::kIceConnectionNew) {
2360 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
2361 }
2362
deadbeefab9b2d12015-10-14 18:33:112363 // If setting the description decided our SSL role, allocate any necessary
2364 // SCTP sids.
2365 rtc::SSLRole role;
Steve Anton75737c02017-11-06 18:37:172366 if (data_channel_type() == cricket::DCT_SCTP && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 18:33:112367 AllocateSctpSids(role);
2368 }
2369
Steve Antondcc3c022017-12-23 00:02:542370 if (IsUnifiedPlan()) {
Steve Anton8b815cd2018-02-17 00:14:422371 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
2372 receiving_transceivers;
Steve Antonc49bcd92018-02-14 22:28:132373 std::vector<rtc::scoped_refptr<MediaStreamInterface>> added_streams;
Steve Antondcc3c022017-12-23 00:02:542374 for (auto transceiver : transceivers_) {
2375 const ContentInfo* content =
2376 FindMediaSectionForTransceiver(transceiver, remote_description());
2377 if (!content) {
2378 continue;
2379 }
2380 const MediaContentDescription* media_desc = content->media_description();
2381 RtpTransceiverDirection local_direction =
2382 RtpTransceiverDirectionReversed(media_desc->direction());
2383 // From the WebRTC specification, steps 2.2.8.5/6 of section 4.4.1.6 "Set
2384 // the RTCSessionDescription: If direction is sendrecv or recvonly, and
2385 // transceiver's current direction is neither sendrecv nor recvonly,
2386 // process the addition of a remote track for the media description.
Seth Hampson5b4f0752018-04-02 23:31:362387 std::vector<std::string> stream_ids;
Seth Hampson2f0d7022018-02-20 19:54:422388 if (!media_desc->streams().empty()) {
Seth Hampson5897a6e2018-04-03 18:16:332389 // The remote description has signaled the stream IDs.
2390 stream_ids = media_desc->streams()[0].stream_ids();
Seth Hampson2f0d7022018-02-20 19:54:422391 }
Steve Antondcc3c022017-12-23 00:02:542392 if (RtpTransceiverDirectionHasRecv(local_direction) &&
2393 (!transceiver->current_direction() ||
2394 !RtpTransceiverDirectionHasRecv(
Seth Hampson2f0d7022018-02-20 19:54:422395 *transceiver->current_direction()))) {
Steve Anton3d954a62018-04-02 18:27:232396 RTC_LOG(LS_INFO) << "Processing the addition of a new track for MID="
Seth Hampson5b4f0752018-04-02 23:31:362397 << content->name << " (added to "
2398 << GetStreamIdsString(stream_ids) << ").";
2399
2400 std::vector<rtc::scoped_refptr<MediaStreamInterface>> media_streams;
2401 for (const std::string& stream_id : stream_ids) {
2402 rtc::scoped_refptr<MediaStreamInterface> stream =
2403 remote_streams_->find(stream_id);
2404 if (!stream) {
2405 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
2406 MediaStream::Create(stream_id));
2407 remote_streams_->AddStream(stream);
2408 added_streams.push_back(stream);
2409 }
2410 media_streams.push_back(stream);
Steve Antonef65ef12018-01-11 01:15:202411 }
Seth Hampson5b4f0752018-04-02 23:31:362412 transceiver->internal()->receiver_internal()->SetStreams(media_streams);
Steve Anton8b815cd2018-02-17 00:14:422413 receiving_transceivers.push_back(transceiver);
Steve Antondcc3c022017-12-23 00:02:542414 }
2415 // If direction is sendonly or inactive, and transceiver's current
2416 // direction is neither sendonly nor inactive, process the removal of a
2417 // remote track for the media description.
2418 if (!RtpTransceiverDirectionHasRecv(local_direction) &&
Steve Antonef65ef12018-01-11 01:15:202419 (transceiver->current_direction() &&
Steve Antondcc3c022017-12-23 00:02:542420 RtpTransceiverDirectionHasRecv(*transceiver->current_direction()))) {
Steve Anton3d954a62018-04-02 18:27:232421 RTC_LOG(LS_INFO) << "Processing the removal of a track for MID="
2422 << content->name;
Steve Antonef65ef12018-01-11 01:15:202423 transceiver->internal()->receiver_internal()->SetStreams({});
Steve Antondcc3c022017-12-23 00:02:542424 }
2425 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
2426 transceiver->internal()->set_current_direction(local_direction);
2427 }
2428 if (content->rejected && !transceiver->stopped()) {
Steve Anton3d954a62018-04-02 18:27:232429 RTC_LOG(LS_INFO) << "Stopping transceiver for MID=" << content->name
2430 << " since the media section was rejected.";
Steve Antondcc3c022017-12-23 00:02:542431 transceiver->Stop();
2432 }
Seth Hampson2f0d7022018-02-20 19:54:422433 if (!content->rejected &&
2434 RtpTransceiverDirectionHasRecv(local_direction)) {
2435 // Set ssrc to 0 in the case of an unsignalled ssrc.
2436 uint32_t ssrc = 0;
Seth Hampson5897a6e2018-04-03 18:16:332437 if (!media_desc->streams().empty() &&
2438 media_desc->streams()[0].has_ssrcs()) {
Seth Hampson2f0d7022018-02-20 19:54:422439 ssrc = media_desc->streams()[0].first_ssrc();
2440 }
2441 transceiver->internal()->receiver_internal()->SetupMediaChannel(ssrc);
Steve Antond3679212018-01-18 01:41:022442 }
Steve Antondcc3c022017-12-23 00:02:542443 }
Steve Antonc49bcd92018-02-14 22:28:132444 // Once all processing has finished, fire off callbacks.
Steve Anton8b815cd2018-02-17 00:14:422445 for (auto transceiver : receiving_transceivers) {
Steve Anton6e221372018-02-20 20:59:162446 stats_->AddTrack(transceiver->receiver()->track());
Steve Anton8b815cd2018-02-17 00:14:422447 observer_->OnTrack(transceiver);
2448 observer_->OnAddTrack(transceiver->receiver(),
2449 transceiver->receiver()->streams());
Steve Antonef65ef12018-01-11 01:15:202450 }
Steve Antonc49bcd92018-02-14 22:28:132451 for (auto stream : added_streams) {
2452 observer_->OnAddStream(stream);
2453 }
Steve Antondcc3c022017-12-23 00:02:542454 }
2455
Henrik Boströmfdb92012017-11-09 18:55:442456 const cricket::ContentInfo* audio_content =
2457 GetFirstAudioContent(remote_description()->description());
2458 const cricket::ContentInfo* video_content =
2459 GetFirstVideoContent(remote_description()->description());
deadbeefbda7e0b2015-12-09 01:13:402460 const cricket::AudioContentDescription* audio_desc =
Henrik Boströmfdb92012017-11-09 18:55:442461 GetFirstAudioContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-09 01:13:402462 const cricket::VideoContentDescription* video_desc =
Henrik Boströmfdb92012017-11-09 18:55:442463 GetFirstVideoContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-09 01:13:402464 const cricket::DataContentDescription* data_desc =
Henrik Boströmfdb92012017-11-09 18:55:442465 GetFirstDataContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-09 01:13:402466
2467 // Check if the descriptions include streams, just in case the peer supports
2468 // MSID, but doesn't indicate so with "a=msid-semantic".
Henrik Boströmfdb92012017-11-09 18:55:442469 if (remote_description()->description()->msid_supported() ||
deadbeefbda7e0b2015-12-09 01:13:402470 (audio_desc && !audio_desc->streams().empty()) ||
2471 (video_desc && !video_desc->streams().empty())) {
2472 remote_peer_supports_msid_ = true;
2473 }
deadbeefab9b2d12015-10-14 18:33:112474
2475 // We wait to signal new streams until we finish processing the description,
2476 // since only at that point will new streams have all their tracks.
2477 rtc::scoped_refptr<StreamCollection> new_streams(StreamCollection::Create());
2478
Steve Antondcc3c022017-12-23 00:02:542479 if (!IsUnifiedPlan()) {
2480 // TODO(steveanton): When removing RTP senders/receivers in response to a
2481 // rejected media section, there is some cleanup logic that expects the
2482 // voice/ video channel to still be set. But in this method the voice/video
2483 // channel would have been destroyed by the SetRemoteDescription caller
2484 // above so the cleanup that relies on them fails to run. The RemoveSenders
2485 // calls should be moved to right before the DestroyChannel calls to fix
2486 // this.
Steve Anton8d3444d2017-10-20 22:30:512487
Steve Antondcc3c022017-12-23 00:02:542488 // Find all audio rtp streams and create corresponding remote AudioTracks
2489 // and MediaStreams.
2490 if (audio_content) {
2491 if (audio_content->rejected) {
2492 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
2493 } else {
2494 bool default_audio_track_needed =
2495 !remote_peer_supports_msid_ &&
2496 RtpTransceiverDirectionHasSend(audio_desc->direction());
2497 UpdateRemoteSendersList(GetActiveStreams(audio_desc),
2498 default_audio_track_needed, audio_desc->type(),
2499 new_streams);
2500 }
deadbeeffaac4972015-11-12 23:33:072501 }
deadbeefab9b2d12015-10-14 18:33:112502
Steve Antondcc3c022017-12-23 00:02:542503 // Find all video rtp streams and create corresponding remote VideoTracks
2504 // and MediaStreams.
2505 if (video_content) {
2506 if (video_content->rejected) {
2507 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
2508 } else {
2509 bool default_video_track_needed =
2510 !remote_peer_supports_msid_ &&
2511 RtpTransceiverDirectionHasSend(video_desc->direction());
2512 UpdateRemoteSendersList(GetActiveStreams(video_desc),
2513 default_video_track_needed, video_desc->type(),
2514 new_streams);
2515 }
deadbeeffaac4972015-11-12 23:33:072516 }
deadbeefab9b2d12015-10-14 18:33:112517
Steve Antondcc3c022017-12-23 00:02:542518 // Update the DataChannels with the information from the remote peer.
2519 if (data_desc) {
2520 if (rtc::starts_with(data_desc->protocol().data(),
2521 cricket::kMediaProtocolRtpPrefix)) {
2522 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
2523 }
deadbeefab9b2d12015-10-14 18:33:112524 }
deadbeefab9b2d12015-10-14 18:33:112525
Steve Antondcc3c022017-12-23 00:02:542526 // Iterate new_streams and notify the observer about new MediaStreams.
2527 for (size_t i = 0; i < new_streams->count(); ++i) {
2528 MediaStreamInterface* new_stream = new_streams->at(i);
2529 stats_->AddStream(new_stream);
2530 observer_->OnAddStream(
2531 rtc::scoped_refptr<MediaStreamInterface>(new_stream));
2532 }
deadbeefab9b2d12015-10-14 18:33:112533
Steve Antondcc3c022017-12-23 00:02:542534 UpdateEndedRemoteMediaStreams();
2535 }
deadbeefab9b2d12015-10-14 18:33:112536
Steve Anton8a006912017-12-04 23:25:562537 return RTCError::OK();
deadbeeffc648b62015-10-13 23:42:332538}
2539
Steve Antondcc3c022017-12-23 00:02:542540RTCError PeerConnection::UpdateTransceiversAndDataChannels(
2541 cricket::ContentSource source,
Seth Hampsonae8a90a2018-02-13 23:33:482542 const SessionDescriptionInterface& new_session,
2543 const SessionDescriptionInterface* old_local_description,
2544 const SessionDescriptionInterface* old_remote_description) {
Steve Antondcc3c022017-12-23 00:02:542545 RTC_DCHECK(IsUnifiedPlan());
2546
Steve Anton7464fca2018-01-19 19:10:372547 const cricket::ContentGroup* bundle_group = nullptr;
2548 if (new_session.GetType() == SdpType::kOffer) {
2549 auto bundle_group_or_error =
2550 GetEarlyBundleGroup(*new_session.description());
2551 if (!bundle_group_or_error.ok()) {
2552 return bundle_group_or_error.MoveError();
2553 }
2554 bundle_group = bundle_group_or_error.MoveValue();
Steve Antondcc3c022017-12-23 00:02:542555 }
Steve Antondcc3c022017-12-23 00:02:542556
Steve Antondcc3c022017-12-23 00:02:542557 const ContentInfos& new_contents = new_session.description()->contents();
Steve Antondcc3c022017-12-23 00:02:542558 for (size_t i = 0; i < new_contents.size(); ++i) {
2559 const cricket::ContentInfo& new_content = new_contents[i];
Steve Antondcc3c022017-12-23 00:02:542560 cricket::MediaType media_type = new_content.media_description()->type();
2561 seen_mids_.insert(new_content.name);
2562 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
2563 media_type == cricket::MEDIA_TYPE_VIDEO) {
Seth Hampsonae8a90a2018-02-13 23:33:482564 const cricket::ContentInfo* old_local_content = nullptr;
2565 if (old_local_description &&
2566 i < old_local_description->description()->contents().size()) {
2567 old_local_content =
2568 &old_local_description->description()->contents()[i];
2569 }
2570 const cricket::ContentInfo* old_remote_content = nullptr;
2571 if (old_remote_description &&
2572 i < old_remote_description->description()->contents().size()) {
2573 old_remote_content =
2574 &old_remote_description->description()->contents()[i];
2575 }
Steve Antondcc3c022017-12-23 00:02:542576 auto transceiver_or_error =
Seth Hampsonae8a90a2018-02-13 23:33:482577 AssociateTransceiver(source, new_session.GetType(), i, new_content,
2578 old_local_content, old_remote_content);
Steve Antondcc3c022017-12-23 00:02:542579 if (!transceiver_or_error.ok()) {
2580 return transceiver_or_error.MoveError();
2581 }
2582 auto transceiver = transceiver_or_error.MoveValue();
Steve Antondcc3c022017-12-23 00:02:542583 RTCError error =
2584 UpdateTransceiverChannel(transceiver, new_content, bundle_group);
2585 if (!error.ok()) {
2586 return error;
2587 }
2588 } else if (media_type == cricket::MEDIA_TYPE_DATA) {
Steve Antonfa2260d2017-12-29 00:38:232589 if (GetDataMid() && new_content.name != *GetDataMid()) {
2590 // Ignore all but the first data section.
Steve Anton3d954a62018-04-02 18:27:232591 RTC_LOG(LS_INFO) << "Ignoring data media section with MID="
2592 << new_content.name;
Steve Antonfa2260d2017-12-29 00:38:232593 continue;
2594 }
2595 RTCError error = UpdateDataChannel(source, new_content, bundle_group);
2596 if (!error.ok()) {
2597 return error;
2598 }
Steve Antondcc3c022017-12-23 00:02:542599 } else {
2600 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
2601 "Unknown section type.");
2602 }
2603 }
2604
2605 return RTCError::OK();
2606}
2607
2608RTCError PeerConnection::UpdateTransceiverChannel(
2609 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2610 transceiver,
2611 const cricket::ContentInfo& content,
2612 const cricket::ContentGroup* bundle_group) {
2613 RTC_DCHECK(IsUnifiedPlan());
2614 RTC_DCHECK(transceiver);
2615 cricket::BaseChannel* channel = transceiver->internal()->channel();
2616 if (content.rejected) {
2617 if (channel) {
2618 transceiver->internal()->SetChannel(nullptr);
2619 DestroyBaseChannel(channel);
2620 }
2621 } else {
2622 if (!channel) {
Steve Anton69470252018-02-09 19:43:082623 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Zhi Huange830e682018-03-30 17:48:352624 channel = CreateVoiceChannel(content.name);
Steve Antondcc3c022017-12-23 00:02:542625 } else {
Steve Anton69470252018-02-09 19:43:082626 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, transceiver->media_type());
Zhi Huange830e682018-03-30 17:48:352627 channel = CreateVideoChannel(content.name);
Steve Antondcc3c022017-12-23 00:02:542628 }
2629 if (!channel) {
2630 LOG_AND_RETURN_ERROR(
2631 RTCErrorType::INTERNAL_ERROR,
2632 "Failed to create channel for mid=" + content.name);
2633 }
2634 transceiver->internal()->SetChannel(channel);
2635 }
2636 }
2637 return RTCError::OK();
2638}
2639
Steve Antonfa2260d2017-12-29 00:38:232640RTCError PeerConnection::UpdateDataChannel(
2641 cricket::ContentSource source,
2642 const cricket::ContentInfo& content,
2643 const cricket::ContentGroup* bundle_group) {
2644 if (data_channel_type_ == cricket::DCT_NONE) {
Steve Antondbf9d032018-01-19 23:23:402645 // If data channels are disabled, ignore this media section. CreateAnswer
2646 // will take care of rejecting it.
2647 return RTCError::OK();
Steve Antonfa2260d2017-12-29 00:38:232648 }
2649 if (content.rejected) {
2650 DestroyDataChannel();
2651 } else {
2652 if (!rtp_data_channel_ && !sctp_transport_) {
Zhi Huange830e682018-03-30 17:48:352653 if (!CreateDataChannel(content.name)) {
Steve Antonfa2260d2017-12-29 00:38:232654 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
2655 "Failed to create data channel.");
2656 }
2657 }
2658 if (source == cricket::CS_REMOTE) {
2659 const MediaContentDescription* data_desc = content.media_description();
2660 if (data_desc && cricket::IsRtpProtocol(data_desc->protocol())) {
2661 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
2662 }
2663 }
2664 }
2665 return RTCError::OK();
2666}
2667
Steve Antondcc3c022017-12-23 00:02:542668RTCErrorOr<rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
2669PeerConnection::AssociateTransceiver(cricket::ContentSource source,
Seth Hampsonae8a90a2018-02-13 23:33:482670 SdpType type,
Steve Antondcc3c022017-12-23 00:02:542671 size_t mline_index,
2672 const ContentInfo& content,
Seth Hampsonae8a90a2018-02-13 23:33:482673 const ContentInfo* old_local_content,
2674 const ContentInfo* old_remote_content) {
Steve Antondcc3c022017-12-23 00:02:542675 RTC_DCHECK(IsUnifiedPlan());
Seth Hampsonae8a90a2018-02-13 23:33:482676 // If this is an offer then the m= section might be recycled. If the m=
2677 // section is being recycled (defined as: rejected in the current local or
2678 // remote description and not rejected in new description), dissociate the
2679 // currently associated RtpTransceiver by setting its mid property to null,
2680 // and discard the mapping between the transceiver and its m= section index.
2681 if (IsMediaSectionBeingRecycled(type, content, old_local_content,
2682 old_remote_content)) {
2683 // We want to dissociate the transceiver that has the rejected mid.
2684 const std::string& old_mid =
2685 (old_local_content && old_local_content->rejected)
2686 ? old_local_content->name
2687 : old_remote_content->name;
2688 auto old_transceiver = GetAssociatedTransceiver(old_mid);
Steve Antondcc3c022017-12-23 00:02:542689 if (old_transceiver) {
Steve Anton3d954a62018-04-02 18:27:232690 RTC_LOG(LS_INFO) << "Dissociating transceiver for MID=" << old_mid
2691 << " since the media section is being recycled.";
Steve Antondcc3c022017-12-23 00:02:542692 old_transceiver->internal()->set_mid(rtc::nullopt);
2693 old_transceiver->internal()->set_mline_index(rtc::nullopt);
2694 }
2695 }
2696 const MediaContentDescription* media_desc = content.media_description();
2697 auto transceiver = GetAssociatedTransceiver(content.name);
2698 if (source == cricket::CS_LOCAL) {
2699 // Find the RtpTransceiver that corresponds to this m= section, using the
2700 // mapping between transceivers and m= section indices established when
2701 // creating the offer.
2702 if (!transceiver) {
2703 transceiver = GetTransceiverByMLineIndex(mline_index);
2704 }
2705 if (!transceiver) {
2706 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2707 "Unknown transceiver");
2708 }
2709 } else {
2710 RTC_DCHECK_EQ(source, cricket::CS_REMOTE);
2711 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers
2712 // of the same type...
2713 if (!transceiver &&
2714 RtpTransceiverDirectionHasRecv(media_desc->direction())) {
2715 transceiver = FindAvailableTransceiverToReceive(media_desc->type());
2716 }
2717 // If no RtpTransceiver was found in the previous step, create one with a
2718 // recvonly direction.
2719 if (!transceiver) {
Steve Anton3d954a62018-04-02 18:27:232720 RTC_LOG(LS_INFO) << "Adding "
2721 << cricket::MediaTypeToString(media_desc->type())
2722 << " transceiver for MID=" << content.name
2723 << " at i=" << mline_index
2724 << " in response to the remote description.";
Steve Anton02ee47c2018-01-11 00:26:062725 auto sender =
2726 CreateSender(media_desc->type(), nullptr, {rtc::CreateRandomUuid()});
Steve Anton5f94aa22018-02-01 18:58:302727 std::string receiver_id;
2728 if (!media_desc->streams().empty()) {
2729 receiver_id = media_desc->streams()[0].id;
2730 } else {
2731 receiver_id = rtc::CreateRandomUuid();
2732 }
2733 auto receiver = CreateReceiver(media_desc->type(), receiver_id);
Steve Anton02ee47c2018-01-11 00:26:062734 transceiver = CreateAndAddTransceiver(sender, receiver);
Steve Antondcc3c022017-12-23 00:02:542735 transceiver->internal()->set_direction(
2736 RtpTransceiverDirection::kRecvOnly);
2737 }
2738 }
2739 RTC_DCHECK(transceiver);
Steve Anton69470252018-02-09 19:43:082740 if (transceiver->media_type() != media_desc->type()) {
Steve Antondcc3c022017-12-23 00:02:542741 LOG_AND_RETURN_ERROR(
2742 RTCErrorType::INVALID_PARAMETER,
2743 "Transceiver type does not match media description type.");
2744 }
2745 // Associate the found or created RtpTransceiver with the m= section by
2746 // setting the value of the RtpTransceiver's mid property to the MID of the m=
2747 // section, and establish a mapping between the transceiver and the index of
2748 // the m= section.
2749 transceiver->internal()->set_mid(content.name);
2750 transceiver->internal()->set_mline_index(mline_index);
2751 return std::move(transceiver);
2752}
2753
2754rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2755PeerConnection::GetAssociatedTransceiver(const std::string& mid) const {
2756 RTC_DCHECK(IsUnifiedPlan());
2757 for (auto transceiver : transceivers_) {
2758 if (transceiver->mid() == mid) {
2759 return transceiver;
2760 }
2761 }
2762 return nullptr;
2763}
2764
2765rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2766PeerConnection::GetTransceiverByMLineIndex(size_t mline_index) const {
2767 RTC_DCHECK(IsUnifiedPlan());
2768 for (auto transceiver : transceivers_) {
2769 if (transceiver->internal()->mline_index() == mline_index) {
2770 return transceiver;
2771 }
2772 }
2773 return nullptr;
2774}
2775
2776rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2777PeerConnection::FindAvailableTransceiverToReceive(
2778 cricket::MediaType media_type) const {
2779 RTC_DCHECK(IsUnifiedPlan());
2780 // From JSEP section 5.10 (Applying a Remote Description):
2781 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers of
2782 // the same type that were added to the PeerConnection by addTrack and are not
2783 // associated with any m= section and are not stopped, find the first such
2784 // RtpTransceiver.
2785 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 19:43:082786 if (transceiver->media_type() == media_type &&
Steve Antondcc3c022017-12-23 00:02:542787 transceiver->internal()->created_by_addtrack() && !transceiver->mid() &&
2788 !transceiver->stopped()) {
2789 return transceiver;
2790 }
2791 }
2792 return nullptr;
2793}
2794
Steve Antoned10bd92017-12-05 18:52:592795const cricket::ContentInfo* PeerConnection::FindMediaSectionForTransceiver(
2796 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2797 transceiver,
2798 const SessionDescriptionInterface* sdesc) const {
2799 RTC_DCHECK(transceiver);
2800 RTC_DCHECK(sdesc);
2801 if (IsUnifiedPlan()) {
2802 if (!transceiver->internal()->mid()) {
2803 // This transceiver is not associated with a media section yet.
2804 return nullptr;
2805 }
2806 return sdesc->description()->GetContentByName(
2807 *transceiver->internal()->mid());
2808 } else {
2809 // Plan B only allows at most one audio and one video section, so use the
2810 // first media section of that type.
2811 return cricket::GetFirstMediaContent(sdesc->description()->contents(),
Steve Anton69470252018-02-09 19:43:082812 transceiver->media_type());
Steve Antoned10bd92017-12-05 18:52:592813 }
2814}
2815
deadbeef46c73892016-11-17 03:42:042816PeerConnectionInterface::RTCConfiguration PeerConnection::GetConfiguration() {
2817 return configuration_;
2818}
2819
deadbeef293e9262017-01-11 20:28:302820bool PeerConnection::SetConfiguration(const RTCConfiguration& configuration,
2821 RTCError* error) {
Peter Boström1a9d6152015-12-08 21:15:172822 TRACE_EVENT0("webrtc", "PeerConnection::SetConfiguration");
deadbeef6de92f92016-12-13 02:49:322823
Steve Anton75737c02017-11-06 18:37:172824 if (local_description() && configuration.ice_candidate_pool_size !=
2825 configuration_.ice_candidate_pool_size) {
Mirko Bonadei675513b2017-11-09 10:09:252826 RTC_LOG(LS_ERROR) << "Can't change candidate pool size after calling "
2827 "SetLocalDescription.";
deadbeef293e9262017-01-11 20:28:302828 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
buildbot@webrtc.org41451d42014-05-03 05:39:452829 }
Taylor Brandstettera1c30352016-05-13 15:15:112830
deadbeef293e9262017-01-11 20:28:302831 // The simplest (and most future-compatible) way to tell if the config was
2832 // modified in an invalid way is to copy each property we do support
2833 // modifying, then use operator==. There are far more properties we don't
2834 // support modifying than those we do, and more could be added.
2835 RTCConfiguration modified_config = configuration_;
2836 modified_config.servers = configuration.servers;
2837 modified_config.type = configuration.type;
2838 modified_config.ice_candidate_pool_size =
2839 configuration.ice_candidate_pool_size;
2840 modified_config.prune_turn_ports = configuration.prune_turn_ports;
skvladd1f5fda2017-02-04 00:54:052841 modified_config.ice_check_min_interval = configuration.ice_check_min_interval;
Qingsi Wange6826d22018-03-08 22:55:142842 modified_config.ice_check_interval_strong_connectivity =
2843 configuration.ice_check_interval_strong_connectivity;
2844 modified_config.ice_check_interval_weak_connectivity =
2845 configuration.ice_check_interval_weak_connectivity;
Qingsi Wang22e623a2018-03-13 17:53:572846 modified_config.ice_unwritable_timeout = configuration.ice_unwritable_timeout;
2847 modified_config.ice_unwritable_min_checks =
2848 configuration.ice_unwritable_min_checks;
Qingsi Wangdb53f8e2018-02-20 22:45:492849 modified_config.stun_candidate_keepalive_interval =
2850 configuration.stun_candidate_keepalive_interval;
Jonas Orelandbdcee282017-10-10 12:01:402851 modified_config.turn_customizer = configuration.turn_customizer;
Qingsi Wang9a5c6f82018-02-01 18:38:402852 modified_config.network_preference = configuration.network_preference;
deadbeef293e9262017-01-11 20:28:302853 if (configuration != modified_config) {
Mirko Bonadei675513b2017-11-09 10:09:252854 RTC_LOG(LS_ERROR) << "Modifying the configuration in an unsupported way.";
deadbeef293e9262017-01-11 20:28:302855 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
2856 }
2857
Steve Anton038834f2017-07-14 22:59:592858 // Validate the modified configuration.
2859 RTCError validate_error = ValidateConfiguration(modified_config);
2860 if (!validate_error.ok()) {
2861 return SafeSetError(std::move(validate_error), error);
2862 }
2863
deadbeef293e9262017-01-11 20:28:302864 // Note that this isn't possible through chromium, since it's an unsigned
2865 // short in WebIDL.
2866 if (configuration.ice_candidate_pool_size < 0 ||
2867 configuration.ice_candidate_pool_size > UINT16_MAX) {
2868 return SafeSetError(RTCErrorType::INVALID_RANGE, error);
2869 }
2870
2871 // Parse ICE servers before hopping to network thread.
2872 cricket::ServerAddresses stun_servers;
2873 std::vector<cricket::RelayServerConfig> turn_servers;
2874 RTCErrorType parse_error =
2875 ParseIceServers(configuration.servers, &stun_servers, &turn_servers);
2876 if (parse_error != RTCErrorType::NONE) {
2877 return SafeSetError(parse_error, error);
2878 }
2879
2880 // In theory this shouldn't fail.
2881 if (!network_thread()->Invoke<bool>(
2882 RTC_FROM_HERE,
2883 rtc::Bind(&PeerConnection::ReconfigurePortAllocator_n, this,
2884 stun_servers, turn_servers, modified_config.type,
2885 modified_config.ice_candidate_pool_size,
Jonas Orelandbdcee282017-10-10 12:01:402886 modified_config.prune_turn_ports,
Qingsi Wangdb53f8e2018-02-20 22:45:492887 modified_config.turn_customizer,
2888 modified_config.stun_candidate_keepalive_interval))) {
Mirko Bonadei675513b2017-11-09 10:09:252889 RTC_LOG(LS_ERROR) << "Failed to apply configuration to PortAllocator.";
deadbeef293e9262017-01-11 20:28:302890 return SafeSetError(RTCErrorType::INTERNAL_ERROR, error);
2891 }
Honghai Zhang4cedf2b2016-08-31 15:18:112892
deadbeefd1a38b52016-12-10 21:15:332893 // As described in JSEP, calling setConfiguration with new ICE servers or
2894 // candidate policy must set a "needs-ice-restart" bit so that the next offer
2895 // triggers an ICE restart which will pick up the changes.
deadbeef293e9262017-01-11 20:28:302896 if (modified_config.servers != configuration_.servers ||
2897 modified_config.type != configuration_.type ||
2898 modified_config.prune_turn_ports != configuration_.prune_turn_ports) {
Steve Antond25da372017-11-06 22:50:292899 transport_controller_->SetNeedsIceRestartFlag();
deadbeefd1a38b52016-12-10 21:15:332900 }
skvladd1f5fda2017-02-04 00:54:052901
Qingsi Wang9c98f0c2018-02-15 23:10:592902 transport_controller_->SetIceConfig(ParseIceConfig(modified_config));
skvladd1f5fda2017-02-04 00:54:052903
deadbeef293e9262017-01-11 20:28:302904 configuration_ = modified_config;
2905 return SafeSetError(RTCErrorType::NONE, error);
buildbot@webrtc.org41451d42014-05-03 05:39:452906}
2907
henrike@webrtc.org28e20752013-07-10 00:45:362908bool PeerConnection::AddIceCandidate(
2909 const IceCandidateInterface* ice_candidate) {
Peter Boström1a9d6152015-12-08 21:15:172910 TRACE_EVENT0("webrtc", "PeerConnection::AddIceCandidate");
zhihuang29ff8442016-07-27 18:07:252911 if (IsClosed()) {
2912 return false;
2913 }
Steve Antond25da372017-11-06 22:50:292914
2915 if (!remote_description()) {
Mirko Bonadei675513b2017-11-09 10:09:252916 RTC_LOG(LS_ERROR) << "ProcessIceMessage: ICE candidates can't be added "
Jonas Olsson45cc8902018-02-13 09:37:072917 "without any remote session description.";
Steve Antond25da372017-11-06 22:50:292918 return false;
2919 }
2920
2921 if (!ice_candidate) {
Mirko Bonadei675513b2017-11-09 10:09:252922 RTC_LOG(LS_ERROR) << "ProcessIceMessage: Candidate is NULL.";
Steve Antond25da372017-11-06 22:50:292923 return false;
2924 }
2925
2926 bool valid = false;
2927 bool ready = ReadyToUseRemoteCandidate(ice_candidate, nullptr, &valid);
2928 if (!valid) {
2929 return false;
2930 }
2931
2932 // Add this candidate to the remote session description.
2933 if (!mutable_remote_description()->AddCandidate(ice_candidate)) {
Mirko Bonadei675513b2017-11-09 10:09:252934 RTC_LOG(LS_ERROR) << "ProcessIceMessage: Candidate cannot be used.";
Steve Antond25da372017-11-06 22:50:292935 return false;
2936 }
2937
2938 if (ready) {
2939 return UseCandidate(ice_candidate);
2940 } else {
Mirko Bonadei675513b2017-11-09 10:09:252941 RTC_LOG(LS_INFO) << "ProcessIceMessage: Not ready to use candidate.";
Steve Antond25da372017-11-06 22:50:292942 return true;
2943 }
henrike@webrtc.org28e20752013-07-10 00:45:362944}
2945
Honghai Zhang7fb69db2016-03-14 18:59:182946bool PeerConnection::RemoveIceCandidates(
2947 const std::vector<cricket::Candidate>& candidates) {
2948 TRACE_EVENT0("webrtc", "PeerConnection::RemoveIceCandidates");
Steve Antond25da372017-11-06 22:50:292949 if (!remote_description()) {
Mirko Bonadei675513b2017-11-09 10:09:252950 RTC_LOG(LS_ERROR) << "RemoveRemoteIceCandidates: ICE candidates can't be "
Jonas Olsson45cc8902018-02-13 09:37:072951 "removed without any remote session description.";
Steve Antond25da372017-11-06 22:50:292952 return false;
2953 }
2954
2955 if (candidates.empty()) {
Mirko Bonadei675513b2017-11-09 10:09:252956 RTC_LOG(LS_ERROR) << "RemoveRemoteIceCandidates: candidates are empty.";
Steve Antond25da372017-11-06 22:50:292957 return false;
2958 }
2959
2960 size_t number_removed =
2961 mutable_remote_description()->RemoveCandidates(candidates);
2962 if (number_removed != candidates.size()) {
Mirko Bonadei675513b2017-11-09 10:09:252963 RTC_LOG(LS_ERROR)
2964 << "RemoveRemoteIceCandidates: Failed to remove candidates. "
Jonas Olsson45cc8902018-02-13 09:37:072965 "Requested "
2966 << candidates.size() << " but only " << number_removed
Mirko Bonadei675513b2017-11-09 10:09:252967 << " are removed.";
Steve Antond25da372017-11-06 22:50:292968 }
2969
2970 // Remove the candidates from the transport controller.
Zhi Huange830e682018-03-30 17:48:352971 RTCError error = transport_controller_->RemoveRemoteCandidates(candidates);
2972 if (!error.ok()) {
2973 RTC_LOG(LS_ERROR) << "Error when removing remote candidates: "
2974 << error.message();
Steve Antond25da372017-11-06 22:50:292975 }
2976 return true;
Honghai Zhang7fb69db2016-03-14 18:59:182977}
2978
buildbot@webrtc.org1567b8c2014-05-08 19:54:162979void PeerConnection::RegisterUMAObserver(UMAObserver* observer) {
Peter Boström1a9d6152015-12-08 21:15:172980 TRACE_EVENT0("webrtc", "PeerConnection::RegisterUmaObserver");
Patrik Höglund3dc41062018-04-11 11:13:572981 uma_observer_ = observer;
2982
2983 if (transport_controller()) {
2984 transport_controller()->SetMetricsObserver(uma_observer_);
2985 }
2986
2987 for (auto transceiver : transceivers_) {
2988 auto* channel = transceiver->internal()->channel();
2989 if (channel) {
2990 channel->SetMetricsObserver(uma_observer_);
2991 }
2992 }
2993
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:182994 // Send information about IPv4/IPv6 status.
deadbeef293e9262017-01-11 20:28:302995 if (uma_observer_) {
Patrik Höglund3dc41062018-04-11 11:13:572996 port_allocator_->SetMetricsObserver(uma_observer_);
2997 if (port_allocator_->flags() & cricket::PORTALLOCATOR_ENABLE_IPV6) {
Guo-wei Shiehdfbe6792015-09-04 00:12:072998 uma_observer_->IncrementEnumCounter(
2999 kEnumCounterAddressFamily, kPeerConnection_IPv6,
3000 kPeerConnectionAddressFamilyCounter_Max);
mallinath@webrtc.orgb445f262014-05-23 22:19:373001 } else {
Guo-wei Shiehdfbe6792015-09-04 00:12:073002 uma_observer_->IncrementEnumCounter(
3003 kEnumCounterAddressFamily, kPeerConnection_IPv4,
3004 kPeerConnectionAddressFamilyCounter_Max);
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:183005 }
Harald Alvestrand5dbb5862018-02-13 22:48:003006 // Send information about the requested SDP semantics.
3007 switch (configuration_.sdp_semantics) {
3008 case SdpSemantics::kDefault:
3009 uma_observer_->IncrementEnumCounter(kEnumCounterSdpSemanticRequested,
3010 kSdpSemanticRequestDefault,
3011 kSdpSemanticRequestMax);
3012
3013 break;
3014 case SdpSemantics::kPlanB:
3015 uma_observer_->IncrementEnumCounter(kEnumCounterSdpSemanticRequested,
3016 kSdpSemanticRequestPlanB,
3017 kSdpSemanticRequestMax);
3018 break;
3019 case SdpSemantics::kUnifiedPlan:
3020 uma_observer_->IncrementEnumCounter(kEnumCounterSdpSemanticRequested,
3021 kSdpSemanticRequestUnifiedPlan,
3022 kSdpSemanticRequestMax);
3023 break;
3024 default:
3025 RTC_NOTREACHED();
3026 }
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:183027 }
buildbot@webrtc.org1567b8c2014-05-08 19:54:163028}
3029
zstein4b979802017-06-02 21:37:373030RTCError PeerConnection::SetBitrate(const BitrateParameters& bitrate) {
Steve Anton978b8762017-09-29 19:15:023031 if (!worker_thread()->IsCurrent()) {
3032 return worker_thread()->Invoke<RTCError>(
zstein4b979802017-06-02 21:37:373033 RTC_FROM_HERE, rtc::Bind(&PeerConnection::SetBitrate, this, bitrate));
3034 }
3035
3036 const bool has_min = static_cast<bool>(bitrate.min_bitrate_bps);
3037 const bool has_current = static_cast<bool>(bitrate.current_bitrate_bps);
3038 const bool has_max = static_cast<bool>(bitrate.max_bitrate_bps);
3039 if (has_min && *bitrate.min_bitrate_bps < 0) {
3040 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3041 "min_bitrate_bps <= 0");
3042 }
3043 if (has_current) {
3044 if (has_min && *bitrate.current_bitrate_bps < *bitrate.min_bitrate_bps) {
3045 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3046 "current_bitrate_bps < min_bitrate_bps");
3047 } else if (*bitrate.current_bitrate_bps < 0) {
3048 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3049 "curent_bitrate_bps < 0");
3050 }
3051 }
3052 if (has_max) {
3053 if (has_current &&
3054 *bitrate.max_bitrate_bps < *bitrate.current_bitrate_bps) {
3055 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3056 "max_bitrate_bps < current_bitrate_bps");
3057 } else if (has_min && *bitrate.max_bitrate_bps < *bitrate.min_bitrate_bps) {
3058 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3059 "max_bitrate_bps < min_bitrate_bps");
3060 } else if (*bitrate.max_bitrate_bps < 0) {
3061 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3062 "max_bitrate_bps < 0");
3063 }
3064 }
3065
Sebastian Janssonfc8d26b2018-02-21 08:52:063066 BitrateConstraintsMask mask;
zstein4b979802017-06-02 21:37:373067 mask.min_bitrate_bps = bitrate.min_bitrate_bps;
3068 mask.start_bitrate_bps = bitrate.current_bitrate_bps;
3069 mask.max_bitrate_bps = bitrate.max_bitrate_bps;
3070
3071 RTC_DCHECK(call_.get());
Sebastian Jansson8f83b422018-02-21 12:07:133072 call_->GetTransportControllerSend()->SetClientBitratePreferences(mask);
zstein4b979802017-06-02 21:37:373073
3074 return RTCError::OK();
3075}
3076
Alex Narest78609d52017-10-20 08:37:473077void PeerConnection::SetBitrateAllocationStrategy(
3078 std::unique_ptr<rtc::BitrateAllocationStrategy>
3079 bitrate_allocation_strategy) {
3080 rtc::Thread* worker_thread = factory_->worker_thread();
3081 if (!worker_thread->IsCurrent()) {
3082 rtc::BitrateAllocationStrategy* strategy_raw =
3083 bitrate_allocation_strategy.release();
3084 auto functor = [this, strategy_raw]() {
3085 call_->SetBitrateAllocationStrategy(
3086 rtc::WrapUnique<rtc::BitrateAllocationStrategy>(strategy_raw));
3087 };
3088 worker_thread->Invoke<void>(RTC_FROM_HERE, functor);
3089 return;
3090 }
3091 RTC_DCHECK(call_.get());
3092 call_->SetBitrateAllocationStrategy(std::move(bitrate_allocation_strategy));
3093}
3094
henrika5f6bf242017-11-01 10:06:563095void PeerConnection::SetAudioPlayout(bool playout) {
3096 if (!worker_thread()->IsCurrent()) {
3097 worker_thread()->Invoke<void>(
3098 RTC_FROM_HERE,
3099 rtc::Bind(&PeerConnection::SetAudioPlayout, this, playout));
3100 return;
3101 }
3102 auto audio_state =
3103 factory_->channel_manager()->media_engine()->GetAudioState();
3104 audio_state->SetPlayout(playout);
3105}
3106
3107void PeerConnection::SetAudioRecording(bool recording) {
3108 if (!worker_thread()->IsCurrent()) {
3109 worker_thread()->Invoke<void>(
3110 RTC_FROM_HERE,
3111 rtc::Bind(&PeerConnection::SetAudioRecording, this, recording));
3112 return;
3113 }
3114 auto audio_state =
3115 factory_->channel_manager()->media_engine()->GetAudioState();
3116 audio_state->SetRecording(recording);
3117}
3118
Steve Anton8c0f7a72017-10-03 17:03:103119std::unique_ptr<rtc::SSLCertificate>
3120PeerConnection::GetRemoteAudioSSLCertificate() {
Taylor Brandstetterc3928662018-02-23 21:04:513121 std::unique_ptr<rtc::SSLCertChain> chain = GetRemoteAudioSSLCertChain();
3122 if (!chain || !chain->GetSize()) {
Steve Anton8c0f7a72017-10-03 17:03:103123 return nullptr;
3124 }
Taylor Brandstetterc3928662018-02-23 21:04:513125 return chain->Get(0).GetUniqueReference();
Steve Anton8c0f7a72017-10-03 17:03:103126}
3127
Zhi Huang70b820f2018-01-27 22:16:153128std::unique_ptr<rtc::SSLCertChain>
3129PeerConnection::GetRemoteAudioSSLCertChain() {
Steve Antonafb0bb72018-02-20 19:35:373130 auto audio_transceiver = GetFirstAudioTransceiver();
3131 if (!audio_transceiver || !audio_transceiver->internal()->channel()) {
Zhi Huang70b820f2018-01-27 22:16:153132 return nullptr;
3133 }
Zhi Huang70b820f2018-01-27 22:16:153134 return transport_controller_->GetRemoteSSLCertChain(
Steve Antonafb0bb72018-02-20 19:35:373135 audio_transceiver->internal()->channel()->transport_name());
3136}
3137
3138rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3139PeerConnection::GetFirstAudioTransceiver() const {
3140 for (auto transceiver : transceivers_) {
3141 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
3142 return transceiver;
3143 }
3144 }
3145 return nullptr;
Zhi Huang70b820f2018-01-27 22:16:153146}
3147
ivoc14d5dbe2016-07-04 14:06:553148bool PeerConnection::StartRtcEventLog(rtc::PlatformFile file,
3149 int64_t max_size_bytes) {
Elad Alon99c3fe52017-10-13 14:29:403150 // TODO(eladalon): It would be better to not allow negative values into PC.
3151 const size_t max_size = (max_size_bytes < 0)
3152 ? RtcEventLog::kUnlimitedOutput
3153 : rtc::saturated_cast<size_t>(max_size_bytes);
3154 return StartRtcEventLog(
Bjorn Tereliusde939432017-11-20 16:38:143155 rtc::MakeUnique<RtcEventLogOutputFile>(file, max_size),
3156 webrtc::RtcEventLog::kImmediateOutput);
Elad Alon99c3fe52017-10-13 14:29:403157}
3158
Bjorn Tereliusde939432017-11-20 16:38:143159bool PeerConnection::StartRtcEventLog(std::unique_ptr<RtcEventLogOutput> output,
3160 int64_t output_period_ms) {
Karl Wibergd6b48192017-10-16 21:01:063161 // TODO(eladalon): In C++14, this can be done with a lambda.
3162 struct Functor {
Bjorn Tereliusde939432017-11-20 16:38:143163 bool operator()() {
3164 return pc->StartRtcEventLog_w(std::move(output), output_period_ms);
3165 }
Karl Wibergd6b48192017-10-16 21:01:063166 PeerConnection* const pc;
3167 std::unique_ptr<RtcEventLogOutput> output;
Bjorn Tereliusde939432017-11-20 16:38:143168 const int64_t output_period_ms;
Elad Alon99c3fe52017-10-13 14:29:403169 };
Bjorn Tereliusde939432017-11-20 16:38:143170 return worker_thread()->Invoke<bool>(
3171 RTC_FROM_HERE, Functor{this, std::move(output), output_period_ms});
ivoc14d5dbe2016-07-04 14:06:553172}
3173
3174void PeerConnection::StopRtcEventLog() {
Steve Anton978b8762017-09-29 19:15:023175 worker_thread()->Invoke<void>(
ivoc14d5dbe2016-07-04 14:06:553176 RTC_FROM_HERE, rtc::Bind(&PeerConnection::StopRtcEventLog_w, this));
3177}
3178
henrike@webrtc.org28e20752013-07-10 00:45:363179const SessionDescriptionInterface* PeerConnection::local_description() const {
Steve Anton75737c02017-11-06 18:37:173180 return pending_local_description_ ? pending_local_description_.get()
3181 : current_local_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:363182}
3183
3184const SessionDescriptionInterface* PeerConnection::remote_description() const {
Steve Anton75737c02017-11-06 18:37:173185 return pending_remote_description_ ? pending_remote_description_.get()
3186 : current_remote_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:363187}
3188
deadbeeffe4a8a42016-12-21 01:56:173189const SessionDescriptionInterface* PeerConnection::current_local_description()
3190 const {
Steve Anton75737c02017-11-06 18:37:173191 return current_local_description_.get();
deadbeeffe4a8a42016-12-21 01:56:173192}
3193
3194const SessionDescriptionInterface* PeerConnection::current_remote_description()
3195 const {
Steve Anton75737c02017-11-06 18:37:173196 return current_remote_description_.get();
deadbeeffe4a8a42016-12-21 01:56:173197}
3198
3199const SessionDescriptionInterface* PeerConnection::pending_local_description()
3200 const {
Steve Anton75737c02017-11-06 18:37:173201 return pending_local_description_.get();
deadbeeffe4a8a42016-12-21 01:56:173202}
3203
3204const SessionDescriptionInterface* PeerConnection::pending_remote_description()
3205 const {
Steve Anton75737c02017-11-06 18:37:173206 return pending_remote_description_.get();
deadbeeffe4a8a42016-12-21 01:56:173207}
3208
henrike@webrtc.org28e20752013-07-10 00:45:363209void PeerConnection::Close() {
Peter Boström1a9d6152015-12-08 21:15:173210 TRACE_EVENT0("webrtc", "PeerConnection::Close");
henrike@webrtc.org28e20752013-07-10 00:45:363211 // Update stats here so that we have the most recent stats for tracks and
3212 // streams before the channels are closed.
tommi@webrtc.org03505bc2014-07-14 20:15:263213 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:363214
Steve Anton75737c02017-11-06 18:37:173215 ChangeSignalingState(PeerConnectionInterface::kClosed);
Steve Anton3fe1b152017-12-12 18:20:083216
Steve Anton8af21862017-12-15 19:20:133217 for (auto transceiver : transceivers_) {
3218 transceiver->Stop();
3219 }
3220 DestroyAllChannels();
Steve Anton75737c02017-11-06 18:37:173221
Qingsi Wang93a84392018-01-31 01:13:093222 // The event log is used in the transport controller, which must be outlived
3223 // by the former. CreateOffer by the peer connection is implemented
3224 // asynchronously and if the peer connection is closed without resetting the
3225 // WebRTC session description factory, the session description factory would
3226 // call the transport controller.
3227 webrtc_session_desc_factory_.reset();
3228 transport_controller_.reset();
3229
deadbeef42a42632017-03-10 23:18:003230 network_thread()->Invoke<void>(
3231 RTC_FROM_HERE,
3232 rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
3233 port_allocator_.get()));
nisseeaabdf62017-05-05 09:23:023234
Steve Anton978b8762017-09-29 19:15:023235 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
eladalon248fd4f2017-09-06 12:18:153236 call_.reset();
3237 // The event log must outlive call (and any other object that uses it).
3238 event_log_.reset();
3239 });
henrike@webrtc.org28e20752013-07-10 00:45:363240}
3241
buildbot@webrtc.orgd4e598d2014-07-29 17:36:523242void PeerConnection::OnMessage(rtc::Message* msg) {
henrike@webrtc.org28e20752013-07-10 00:45:363243 switch (msg->message_id) {
henrike@webrtc.org28e20752013-07-10 00:45:363244 case MSG_SET_SESSIONDESCRIPTION_SUCCESS: {
3245 SetSessionDescriptionMsg* param =
3246 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
3247 param->observer->OnSuccess();
3248 delete param;
3249 break;
3250 }
3251 case MSG_SET_SESSIONDESCRIPTION_FAILED: {
3252 SetSessionDescriptionMsg* param =
3253 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
Harald Alvestrand5081c0c2018-03-09 14:18:033254 param->observer->OnFailure(std::move(param->error));
henrike@webrtc.org28e20752013-07-10 00:45:363255 delete param;
3256 break;
3257 }
deadbeefab9b2d12015-10-14 18:33:113258 case MSG_CREATE_SESSIONDESCRIPTION_FAILED: {
3259 CreateSessionDescriptionMsg* param =
3260 static_cast<CreateSessionDescriptionMsg*>(msg->pdata);
Harald Alvestrand5081c0c2018-03-09 14:18:033261 param->observer->OnFailure(std::move(param->error));
deadbeefab9b2d12015-10-14 18:33:113262 delete param;
3263 break;
3264 }
henrike@webrtc.org28e20752013-07-10 00:45:363265 case MSG_GETSTATS: {
3266 GetStatsMsg* param = static_cast<GetStatsMsg*>(msg->pdata);
nissee8abe3e2017-01-18 13:00:343267 StatsReports reports;
3268 stats_->GetStats(param->track, &reports);
3269 param->observer->OnComplete(reports);
henrike@webrtc.org28e20752013-07-10 00:45:363270 delete param;
3271 break;
3272 }
deadbeefbd292462015-12-15 02:15:293273 case MSG_FREE_DATACHANNELS: {
3274 sctp_data_channels_to_free_.clear();
3275 break;
3276 }
henrike@webrtc.org28e20752013-07-10 00:45:363277 default:
nisseeb4ca4e2017-01-12 10:24:273278 RTC_NOTREACHED() << "Not implemented";
henrike@webrtc.org28e20752013-07-10 00:45:363279 break;
3280 }
3281}
3282
Steve Antonafb0bb72018-02-20 19:35:373283cricket::VoiceMediaChannel* PeerConnection::voice_media_channel() const {
3284 RTC_DCHECK(!IsUnifiedPlan());
3285 auto* voice_channel = static_cast<cricket::VoiceChannel*>(
3286 GetAudioTransceiver()->internal()->channel());
3287 if (voice_channel) {
3288 return voice_channel->media_channel();
3289 } else {
3290 return nullptr;
3291 }
3292}
3293
3294cricket::VideoMediaChannel* PeerConnection::video_media_channel() const {
3295 RTC_DCHECK(!IsUnifiedPlan());
3296 auto* video_channel = static_cast<cricket::VideoChannel*>(
3297 GetVideoTransceiver()->internal()->channel());
3298 if (video_channel) {
3299 return video_channel->media_channel();
3300 } else {
3301 return nullptr;
3302 }
3303}
3304
Steve Anton4171afb2017-11-20 18:20:223305void PeerConnection::CreateAudioReceiver(
3306 MediaStreamInterface* stream,
3307 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 12:41:513308 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
3309 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Steve Antond3679212018-01-18 01:41:023310 auto* audio_receiver = new AudioRtpReceiver(
3311 worker_thread(), remote_sender_info.sender_id, streams);
Steve Anton57858b32018-02-15 23:19:503312 audio_receiver->SetVoiceMediaChannel(voice_media_channel());
Steve Antond3679212018-01-18 01:41:023313 audio_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
3314 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
3315 signaling_thread(), audio_receiver);
Steve Anton4171afb2017-11-20 18:20:223316 GetAudioTransceiver()->internal()->AddReceiver(receiver);
Henrik Boström9e6fd2b2017-11-21 12:41:513317 observer_->OnAddTrack(receiver, std::move(streams));
henrike@webrtc.org28e20752013-07-10 00:45:363318}
3319
Steve Anton4171afb2017-11-20 18:20:223320void PeerConnection::CreateVideoReceiver(
3321 MediaStreamInterface* stream,
3322 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 12:41:513323 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
3324 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Steve Antond3679212018-01-18 01:41:023325 auto* video_receiver = new VideoRtpReceiver(
3326 worker_thread(), remote_sender_info.sender_id, streams);
Steve Anton57858b32018-02-15 23:19:503327 video_receiver->SetVideoMediaChannel(video_media_channel());
Steve Antond3679212018-01-18 01:41:023328 video_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
3329 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
3330 signaling_thread(), video_receiver);
Steve Anton4171afb2017-11-20 18:20:223331 GetVideoTransceiver()->internal()->AddReceiver(receiver);
Henrik Boström9e6fd2b2017-11-21 12:41:513332 observer_->OnAddTrack(receiver, std::move(streams));
henrike@webrtc.org28e20752013-07-10 00:45:363333}
3334
deadbeef70ab1a12015-09-28 23:53:553335// TODO(deadbeef): Keep RtpReceivers around even if track goes away in remote
3336// description.
Henrik Boström933d8b02017-10-10 17:05:163337rtc::scoped_refptr<RtpReceiverInterface> PeerConnection::RemoveAndStopReceiver(
Steve Anton4171afb2017-11-20 18:20:223338 const RtpSenderInfo& remote_sender_info) {
3339 auto receiver = FindReceiverById(remote_sender_info.sender_id);
3340 if (!receiver) {
3341 RTC_LOG(LS_WARNING) << "RtpReceiver for track with id "
3342 << remote_sender_info.sender_id << " doesn't exist.";
Henrik Boström933d8b02017-10-10 17:05:163343 return nullptr;
deadbeef70ab1a12015-09-28 23:53:553344 }
Steve Anton4171afb2017-11-20 18:20:223345 if (receiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
3346 GetAudioTransceiver()->internal()->RemoveReceiver(receiver);
3347 } else {
3348 GetVideoTransceiver()->internal()->RemoveReceiver(receiver);
3349 }
Henrik Boström933d8b02017-10-10 17:05:163350 return receiver;
henrike@webrtc.org28e20752013-07-10 00:45:363351}
3352
korniltsev.anatolyec390b52017-07-25 00:00:253353void PeerConnection::AddAudioTrack(AudioTrackInterface* track,
3354 MediaStreamInterface* stream) {
3355 RTC_DCHECK(!IsClosed());
3356 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 18:20:223357 if (sender) {
korniltsev.anatolyec390b52017-07-25 00:00:253358 // We already have a sender for this track, so just change the stream_id
3359 // so that it's correct in the next call to CreateOffer.
Seth Hampson5b4f0752018-04-02 23:31:363360 sender->internal()->set_stream_ids({stream->id()});
korniltsev.anatolyec390b52017-07-25 00:00:253361 return;
3362 }
3363
3364 // Normal case; we've never seen this track before.
Steve Anton02ee47c2018-01-11 00:26:063365 auto new_sender =
Seth Hampson13b8bad2018-03-13 23:05:283366 CreateSender(cricket::MEDIA_TYPE_AUDIO, track, {stream->id()});
Steve Anton57858b32018-02-15 23:19:503367 new_sender->internal()->SetVoiceMediaChannel(voice_media_channel());
Steve Anton4171afb2017-11-20 18:20:223368 GetAudioTransceiver()->internal()->AddSender(new_sender);
korniltsev.anatolyec390b52017-07-25 00:00:253369 // If the sender has already been configured in SDP, we call SetSsrc,
3370 // which will connect the sender to the underlying transport. This can
3371 // occur if a local session description that contains the ID of the sender
3372 // is set before AddStream is called. It can also occur if the local
3373 // session description is not changed and RemoveStream is called, and
3374 // later AddStream is called again with the same stream.
Steve Anton4171afb2017-11-20 18:20:223375 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609eaa2018-03-27 21:57:183376 FindSenderInfo(local_audio_sender_infos_, stream->id(), track->id());
Steve Anton4171afb2017-11-20 18:20:223377 if (sender_info) {
3378 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-25 00:00:253379 }
3380}
3381
3382// TODO(deadbeef): Don't destroy RtpSenders here; they should be kept around
3383// indefinitely, when we have unified plan SDP.
3384void PeerConnection::RemoveAudioTrack(AudioTrackInterface* track,
3385 MediaStreamInterface* stream) {
3386 RTC_DCHECK(!IsClosed());
3387 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 18:20:223388 if (!sender) {
Mirko Bonadei675513b2017-11-09 10:09:253389 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
3390 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-25 00:00:253391 return;
3392 }
Steve Anton4171afb2017-11-20 18:20:223393 GetAudioTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-25 00:00:253394}
3395
3396void PeerConnection::AddVideoTrack(VideoTrackInterface* track,
3397 MediaStreamInterface* stream) {
3398 RTC_DCHECK(!IsClosed());
3399 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 18:20:223400 if (sender) {
korniltsev.anatolyec390b52017-07-25 00:00:253401 // We already have a sender for this track, so just change the stream_id
3402 // so that it's correct in the next call to CreateOffer.
Seth Hampson5b4f0752018-04-02 23:31:363403 sender->internal()->set_stream_ids({stream->id()});
korniltsev.anatolyec390b52017-07-25 00:00:253404 return;
3405 }
3406
3407 // Normal case; we've never seen this track before.
Steve Anton02ee47c2018-01-11 00:26:063408 auto new_sender =
Seth Hampson13b8bad2018-03-13 23:05:283409 CreateSender(cricket::MEDIA_TYPE_VIDEO, track, {stream->id()});
Steve Anton57858b32018-02-15 23:19:503410 new_sender->internal()->SetVideoMediaChannel(video_media_channel());
Steve Anton4171afb2017-11-20 18:20:223411 GetVideoTransceiver()->internal()->AddSender(new_sender);
3412 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609eaa2018-03-27 21:57:183413 FindSenderInfo(local_video_sender_infos_, stream->id(), track->id());
Steve Anton4171afb2017-11-20 18:20:223414 if (sender_info) {
3415 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-25 00:00:253416 }
3417}
3418
3419void PeerConnection::RemoveVideoTrack(VideoTrackInterface* track,
3420 MediaStreamInterface* stream) {
3421 RTC_DCHECK(!IsClosed());
3422 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 18:20:223423 if (!sender) {
Mirko Bonadei675513b2017-11-09 10:09:253424 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
3425 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-25 00:00:253426 return;
3427 }
Steve Anton4171afb2017-11-20 18:20:223428 GetVideoTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-25 00:00:253429}
3430
Steve Antonba818672017-11-06 18:21:573431void PeerConnection::SetIceConnectionState(IceConnectionState new_state) {
deadbeef0a6c4ca2015-10-06 18:38:283432 RTC_DCHECK(signaling_thread()->IsCurrent());
Steve Antonba818672017-11-06 18:21:573433 if (ice_connection_state_ == new_state) {
3434 return;
3435 }
3436
deadbeefcbecd352015-09-23 18:50:273437 // After transitioning to "closed", ignore any additional states from
Steve Antonba818672017-11-06 18:21:573438 // TransportController (such as "disconnected").
deadbeefab9b2d12015-10-14 18:33:113439 if (IsClosed()) {
deadbeefcbecd352015-09-23 18:50:273440 return;
3441 }
Steve Antonba818672017-11-06 18:21:573442
Mirko Bonadei675513b2017-11-09 10:09:253443 RTC_LOG(LS_INFO) << "Changing IceConnectionState " << ice_connection_state_
3444 << " => " << new_state;
Steve Antonba818672017-11-06 18:21:573445 RTC_DCHECK(ice_connection_state_ !=
3446 PeerConnectionInterface::kIceConnectionClosed);
3447
henrike@webrtc.org28e20752013-07-10 00:45:363448 ice_connection_state_ = new_state;
mallinath@webrtc.orgd3dc4242014-03-01 00:05:523449 observer_->OnIceConnectionChange(ice_connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:363450}
3451
3452void PeerConnection::OnIceGatheringChange(
3453 PeerConnectionInterface::IceGatheringState new_state) {
deadbeef0a6c4ca2015-10-06 18:38:283454 RTC_DCHECK(signaling_thread()->IsCurrent());
henrike@webrtc.org28e20752013-07-10 00:45:363455 if (IsClosed()) {
3456 return;
3457 }
3458 ice_gathering_state_ = new_state;
mallinath@webrtc.orgd3dc4242014-03-01 00:05:523459 observer_->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:363460}
3461
jbauch81bf7b02017-03-25 15:31:123462void PeerConnection::OnIceCandidate(
3463 std::unique_ptr<IceCandidateInterface> candidate) {
deadbeef0a6c4ca2015-10-06 18:38:283464 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 18:07:253465 if (IsClosed()) {
3466 return;
3467 }
jbauch81bf7b02017-03-25 15:31:123468 observer_->OnIceCandidate(candidate.get());
henrike@webrtc.org28e20752013-07-10 00:45:363469}
3470
Honghai Zhang7fb69db2016-03-14 18:59:183471void PeerConnection::OnIceCandidatesRemoved(
3472 const std::vector<cricket::Candidate>& candidates) {
3473 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 18:07:253474 if (IsClosed()) {
3475 return;
3476 }
Honghai Zhang7fb69db2016-03-14 18:59:183477 observer_->OnIceCandidatesRemoved(candidates);
3478}
3479
henrike@webrtc.org28e20752013-07-10 00:45:363480void PeerConnection::ChangeSignalingState(
3481 PeerConnectionInterface::SignalingState signaling_state) {
Steve Antonba818672017-11-06 18:21:573482 RTC_DCHECK(signaling_thread()->IsCurrent());
3483 if (signaling_state_ == signaling_state) {
3484 return;
3485 }
Mirko Bonadei675513b2017-11-09 10:09:253486 RTC_LOG(LS_INFO) << "Session: " << session_id() << " Old state: "
3487 << GetSignalingStateString(signaling_state_)
3488 << " New state: "
3489 << GetSignalingStateString(signaling_state);
henrike@webrtc.org28e20752013-07-10 00:45:363490 signaling_state_ = signaling_state;
3491 if (signaling_state == kClosed) {
3492 ice_connection_state_ = kIceConnectionClosed;
3493 observer_->OnIceConnectionChange(ice_connection_state_);
3494 if (ice_gathering_state_ != kIceGatheringComplete) {
3495 ice_gathering_state_ = kIceGatheringComplete;
3496 observer_->OnIceGatheringChange(ice_gathering_state_);
3497 }
3498 }
3499 observer_->OnSignalingChange(signaling_state_);
henrike@webrtc.org28e20752013-07-10 00:45:363500}
3501
deadbeefeb459812015-12-16 03:24:433502void PeerConnection::OnAudioTrackAdded(AudioTrackInterface* track,
3503 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 18:07:253504 if (IsClosed()) {
3505 return;
3506 }
korniltsev.anatolyec390b52017-07-25 00:00:253507 AddAudioTrack(track, stream);
3508 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-16 03:24:433509}
3510
deadbeefeb459812015-12-16 03:24:433511void PeerConnection::OnAudioTrackRemoved(AudioTrackInterface* track,
3512 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 18:07:253513 if (IsClosed()) {
3514 return;
3515 }
korniltsev.anatolyec390b52017-07-25 00:00:253516 RemoveAudioTrack(track, stream);
3517 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-16 03:24:433518}
3519
3520void PeerConnection::OnVideoTrackAdded(VideoTrackInterface* track,
3521 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 18:07:253522 if (IsClosed()) {
3523 return;
3524 }
korniltsev.anatolyec390b52017-07-25 00:00:253525 AddVideoTrack(track, stream);
3526 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-16 03:24:433527}
3528
3529void PeerConnection::OnVideoTrackRemoved(VideoTrackInterface* track,
3530 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 18:07:253531 if (IsClosed()) {
3532 return;
3533 }
korniltsev.anatolyec390b52017-07-25 00:00:253534 RemoveVideoTrack(track, stream);
3535 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-16 03:24:433536}
3537
Henrik Boström31638672017-11-23 16:48:323538void PeerConnection::PostSetSessionDescriptionSuccess(
3539 SetSessionDescriptionObserver* observer) {
3540 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
3541 signaling_thread()->Post(RTC_FROM_HERE, this,
3542 MSG_SET_SESSIONDESCRIPTION_SUCCESS, msg);
3543}
3544
deadbeefab9b2d12015-10-14 18:33:113545void PeerConnection::PostSetSessionDescriptionFailure(
3546 SetSessionDescriptionObserver* observer,
Harald Alvestrand5081c0c2018-03-09 14:18:033547 RTCError&& error) {
3548 RTC_DCHECK(!error.ok());
deadbeefab9b2d12015-10-14 18:33:113549 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
Harald Alvestrand5081c0c2018-03-09 14:18:033550 msg->error = std::move(error);
Taylor Brandstetter5d97a9a2016-06-10 21:17:273551 signaling_thread()->Post(RTC_FROM_HERE, this,
3552 MSG_SET_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 18:33:113553}
3554
3555void PeerConnection::PostCreateSessionDescriptionFailure(
3556 CreateSessionDescriptionObserver* observer,
Harald Alvestrand5081c0c2018-03-09 14:18:033557 RTCError error) {
3558 RTC_DCHECK(!error.ok());
deadbeefab9b2d12015-10-14 18:33:113559 CreateSessionDescriptionMsg* msg = new CreateSessionDescriptionMsg(observer);
Harald Alvestrand5081c0c2018-03-09 14:18:033560 msg->error = std::move(error);
Taylor Brandstetter5d97a9a2016-06-10 21:17:273561 signaling_thread()->Post(RTC_FROM_HERE, this,
3562 MSG_CREATE_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 18:33:113563}
3564
zhihuang1c378ed2017-08-17 21:10:503565void PeerConnection::GetOptionsForOffer(
Steve Antondcc3c022017-12-23 00:02:543566 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
deadbeefab9b2d12015-10-14 18:33:113567 cricket::MediaSessionOptions* session_options) {
Steve Antondcc3c022017-12-23 00:02:543568 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
zhihuang1c378ed2017-08-17 21:10:503569
Steve Antondcc3c022017-12-23 00:02:543570 if (IsUnifiedPlan()) {
3571 GetOptionsForUnifiedPlanOffer(offer_answer_options, session_options);
3572 } else {
3573 GetOptionsForPlanBOffer(offer_answer_options, session_options);
3574 }
3575
Steve Antonfa2260d2017-12-29 00:38:233576 // Intentionally unset the data channel type for RTP data channel with the
3577 // second condition. Otherwise the RTP data channels would be successfully
3578 // negotiated by default and the unit tests in WebRtcDataBrowserTest will fail
3579 // when building with chromium. We want to leave RTP data channels broken, so
3580 // people won't try to use them.
3581 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
3582 session_options->data_channel_type = data_channel_type();
3583 }
3584
Steve Antondcc3c022017-12-23 00:02:543585 // Apply ICE restart flag and renomination flag.
3586 for (auto& options : session_options->media_description_options) {
3587 options.transport_options.ice_restart = offer_answer_options.ice_restart;
3588 options.transport_options.enable_ice_renomination =
3589 configuration_.enable_ice_renomination;
3590 }
3591
3592 session_options->rtcp_cname = rtcp_cname_;
3593 session_options->crypto_options = factory_->options().crypto_options;
Steve Antone831b8c2018-02-01 20:22:163594 session_options->is_unified_plan = IsUnifiedPlan();
Steve Antondcc3c022017-12-23 00:02:543595}
3596
3597void PeerConnection::GetOptionsForPlanBOffer(
3598 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
3599 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 21:10:503600 // Figure out transceiver directional preferences.
3601 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
3602 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
3603
3604 // By default, generate sendrecv/recvonly m= sections.
3605 bool recv_audio = true;
3606 bool recv_video = true;
3607
3608 // By default, only offer a new m= section if we have media to send with it.
3609 bool offer_new_audio_description = send_audio;
3610 bool offer_new_video_description = send_video;
3611 bool offer_new_data_description = HasDataChannels();
3612
3613 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-23 00:02:543614 if (offer_answer_options.offer_to_receive_audio !=
3615 RTCOfferAnswerOptions::kUndefined) {
3616 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 21:10:503617 offer_new_audio_description =
Steve Antondcc3c022017-12-23 00:02:543618 offer_new_audio_description ||
3619 (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 21:10:503620 }
Steve Antondcc3c022017-12-23 00:02:543621 if (offer_answer_options.offer_to_receive_video !=
3622 RTCOfferAnswerOptions::kUndefined) {
3623 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 21:10:503624 offer_new_video_description =
Steve Antondcc3c022017-12-23 00:02:543625 offer_new_video_description ||
3626 (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 21:10:503627 }
3628
3629 rtc::Optional<size_t> audio_index;
3630 rtc::Optional<size_t> video_index;
3631 rtc::Optional<size_t> data_index;
3632 // If a current description exists, generate m= sections in the same order,
3633 // using the first audio/video/data section that appears and rejecting
3634 // extraneous ones.
Steve Anton75737c02017-11-06 18:37:173635 if (local_description()) {
zhihuang1c378ed2017-08-17 21:10:503636 GenerateMediaDescriptionOptions(
Steve Anton75737c02017-11-06 18:37:173637 local_description(),
Steve Anton1d03a752017-11-27 22:30:093638 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
3639 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
3640 &audio_index, &video_index, &data_index, session_options);
deadbeefab9b2d12015-10-14 18:33:113641 }
3642
zhihuang1c378ed2017-08-17 21:10:503643 // Add audio/video/data m= sections to the end if needed.
3644 if (!audio_index && offer_new_audio_description) {
3645 session_options->media_description_options.push_back(
3646 cricket::MediaDescriptionOptions(
3647 cricket::MEDIA_TYPE_AUDIO, cricket::CN_AUDIO,
Steve Anton1d03a752017-11-27 22:30:093648 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
3649 false));
Oskar Sundbom9b28a032017-11-16 09:53:303650 audio_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 20:14:453651 }
zhihuang1c378ed2017-08-17 21:10:503652 if (!video_index && offer_new_video_description) {
3653 session_options->media_description_options.push_back(
3654 cricket::MediaDescriptionOptions(
3655 cricket::MEDIA_TYPE_VIDEO, cricket::CN_VIDEO,
Steve Anton1d03a752017-11-27 22:30:093656 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
3657 false));
Oskar Sundbom9b28a032017-11-16 09:53:303658 video_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 20:14:453659 }
zhihuang1c378ed2017-08-17 21:10:503660 if (!data_index && offer_new_data_description) {
3661 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-29 00:38:233662 GetMediaDescriptionOptionsForActiveData(cricket::CN_DATA));
Oskar Sundbom9b28a032017-11-16 09:53:303663 data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 21:10:503664 }
3665
3666 cricket::MediaDescriptionOptions* audio_media_description_options =
3667 !audio_index ? nullptr
3668 : &session_options->media_description_options[*audio_index];
3669 cricket::MediaDescriptionOptions* video_media_description_options =
3670 !video_index ? nullptr
3671 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 21:10:503672
Steve Anton4171afb2017-11-20 18:20:223673 AddRtpSenderOptions(GetSendersInternal(), audio_media_description_options,
zhihuang1c378ed2017-08-17 21:10:503674 video_media_description_options);
Steve Antondcc3c022017-12-23 00:02:543675}
3676
3677// Find a new MID that is not already in |used_mids|, then add it to |used_mids|
3678// and return a reference to it.
3679// Generated MIDs should be no more than 3 bytes long to take up less space in
3680// the RTP packet.
3681static const std::string& AllocateMid(std::set<std::string>* used_mids) {
3682 RTC_DCHECK(used_mids);
3683 // We're boring: just generate MIDs 0, 1, 2, ...
3684 size_t i = 0;
3685 std::set<std::string>::iterator it;
3686 bool inserted;
3687 do {
3688 std::string mid = rtc::ToString(i++);
3689 auto insert_result = used_mids->insert(mid);
3690 it = insert_result.first;
3691 inserted = insert_result.second;
3692 } while (!inserted);
3693 return *it;
3694}
3695
3696static cricket::MediaDescriptionOptions
3697GetMediaDescriptionOptionsForTransceiver(
3698 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3699 transceiver,
3700 const std::string& mid) {
3701 cricket::MediaDescriptionOptions media_description_options(
Steve Anton69470252018-02-09 19:43:083702 transceiver->media_type(), mid, transceiver->direction(),
Steve Antondcc3c022017-12-23 00:02:543703 transceiver->stopped());
Steve Anton5f94aa22018-02-01 18:58:303704 // This behavior is specified in JSEP. The gist is that:
3705 // 1. The MSID is included if the RtpTransceiver's direction is sendonly or
3706 // sendrecv.
3707 // 2. If the MSID is included, then it must be included in any subsequent
3708 // offer/answer exactly the same until the RtpTransceiver is stopped.
3709 if (!transceiver->stopped() &&
3710 (RtpTransceiverDirectionHasSend(transceiver->direction()) ||
3711 transceiver->internal()->has_ever_been_used_to_send())) {
3712 cricket::SenderOptions sender_options;
3713 sender_options.track_id = transceiver->sender()->id();
3714 sender_options.stream_ids = transceiver->sender()->stream_ids();
3715 // TODO(bugs.webrtc.org/7600): Set num_sim_layers to the number of encodings
3716 // set in the RTP parameters when the transceiver was added.
3717 sender_options.num_sim_layers = 1;
3718 media_description_options.sender_options.push_back(sender_options);
3719 }
Steve Antondcc3c022017-12-23 00:02:543720 return media_description_options;
3721}
3722
3723void PeerConnection::GetOptionsForUnifiedPlanOffer(
3724 const RTCOfferAnswerOptions& offer_answer_options,
3725 cricket::MediaSessionOptions* session_options) {
3726 // Rules for generating an offer are dictated by JSEP sections 5.2.1 (Initial
3727 // Offers) and 5.2.2 (Subsequent Offers).
3728 RTC_DCHECK_EQ(session_options->media_description_options.size(), 0);
3729 const ContentInfos& local_contents =
3730 (local_description() ? local_description()->description()->contents()
3731 : ContentInfos());
3732 const ContentInfos& remote_contents =
3733 (remote_description() ? remote_description()->description()->contents()
3734 : ContentInfos());
3735 // The mline indices that can be recycled. New transceivers should reuse these
3736 // slots first.
3737 std::queue<size_t> recycleable_mline_indices;
3738 // Track the MIDs used in previous offer/answer exchanges and the current
3739 // offer so that new, unique MIDs are generated.
3740 std::set<std::string> used_mids = seen_mids_;
3741 // First, go through each media section that exists in either the local or
3742 // remote description and generate a media section in this offer for the
3743 // associated transceiver. If a media section can be recycled, generate a
3744 // default, rejected media section here that can be later overwritten.
3745 for (size_t i = 0;
3746 i < std::max(local_contents.size(), remote_contents.size()); ++i) {
3747 // Either |local_content| or |remote_content| is non-null.
3748 const ContentInfo* local_content =
3749 (i < local_contents.size() ? &local_contents[i] : nullptr);
3750 const ContentInfo* remote_content =
3751 (i < remote_contents.size() ? &remote_contents[i] : nullptr);
3752 bool had_been_rejected = (local_content && local_content->rejected) ||
3753 (remote_content && remote_content->rejected);
3754 const std::string& mid =
3755 (local_content ? local_content->name : remote_content->name);
3756 cricket::MediaType media_type =
3757 (local_content ? local_content->media_description()->type()
3758 : remote_content->media_description()->type());
3759 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
3760 media_type == cricket::MEDIA_TYPE_VIDEO) {
3761 auto transceiver = GetAssociatedTransceiver(mid);
3762 RTC_CHECK(transceiver);
3763 // A media section is considered eligible for recycling if it is marked as
3764 // rejected in either the local or remote description.
Seth Hampsonae8a90a2018-02-13 23:33:483765 if (had_been_rejected && transceiver->stopped()) {
Steve Antondcc3c022017-12-23 00:02:543766 session_options->media_description_options.push_back(
Steve Anton69470252018-02-09 19:43:083767 cricket::MediaDescriptionOptions(transceiver->media_type(), mid,
3768 RtpTransceiverDirection::kInactive,
3769 /*stopped=*/true));
Steve Antondcc3c022017-12-23 00:02:543770 recycleable_mline_indices.push(i);
3771 } else {
3772 session_options->media_description_options.push_back(
3773 GetMediaDescriptionOptionsForTransceiver(transceiver, mid));
3774 // CreateOffer shouldn't really cause any state changes in
3775 // PeerConnection, but we need a way to match new transceivers to new
3776 // media sections in SetLocalDescription and JSEP specifies this is done
3777 // by recording the index of the media section generated for the
3778 // transceiver in the offer.
3779 transceiver->internal()->set_mline_index(i);
3780 }
3781 } else {
3782 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antonfa2260d2017-12-29 00:38:233783 RTC_CHECK(GetDataMid());
3784 if (had_been_rejected || mid != *GetDataMid()) {
3785 session_options->media_description_options.push_back(
3786 GetMediaDescriptionOptionsForRejectedData(mid));
3787 } else {
3788 session_options->media_description_options.push_back(
3789 GetMediaDescriptionOptionsForActiveData(mid));
3790 }
Steve Antondcc3c022017-12-23 00:02:543791 }
3792 }
3793 // Next, look for transceivers that are newly added (that is, are not stopped
3794 // and not associated). Reuse media sections marked as recyclable first,
3795 // otherwise append to the end of the offer. New media sections should be
3796 // added in the order they were added to the PeerConnection.
3797 for (auto transceiver : transceivers_) {
3798 if (transceiver->mid() || transceiver->stopped()) {
3799 continue;
3800 }
3801 size_t mline_index;
3802 if (!recycleable_mline_indices.empty()) {
3803 mline_index = recycleable_mline_indices.front();
3804 recycleable_mline_indices.pop();
3805 session_options->media_description_options[mline_index] =
3806 GetMediaDescriptionOptionsForTransceiver(transceiver,
3807 AllocateMid(&used_mids));
3808 } else {
3809 mline_index = session_options->media_description_options.size();
3810 session_options->media_description_options.push_back(
3811 GetMediaDescriptionOptionsForTransceiver(transceiver,
3812 AllocateMid(&used_mids)));
3813 }
3814 // See comment above for why CreateOffer changes the transceiver's state.
3815 transceiver->internal()->set_mline_index(mline_index);
3816 }
Steve Antonfa2260d2017-12-29 00:38:233817 // Lastly, add a m-section if we have local data channels and an m section
3818 // does not already exist.
3819 if (!GetDataMid() && HasDataChannels()) {
3820 session_options->media_description_options.push_back(
3821 GetMediaDescriptionOptionsForActiveData(AllocateMid(&used_mids)));
3822 }
Steve Antondcc3c022017-12-23 00:02:543823}
3824
3825void PeerConnection::GetOptionsForAnswer(
3826 const RTCOfferAnswerOptions& offer_answer_options,
3827 cricket::MediaSessionOptions* session_options) {
3828 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
3829
3830 if (IsUnifiedPlan()) {
3831 GetOptionsForUnifiedPlanAnswer(offer_answer_options, session_options);
3832 } else {
3833 GetOptionsForPlanBAnswer(offer_answer_options, session_options);
3834 }
3835
Steve Antonfa2260d2017-12-29 00:38:233836 // Intentionally unset the data channel type for RTP data channel. Otherwise
3837 // the RTP data channels would be successfully negotiated by default and the
3838 // unit tests in WebRtcDataBrowserTest will fail when building with chromium.
3839 // We want to leave RTP data channels broken, so people won't try to use them.
3840 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
3841 session_options->data_channel_type = data_channel_type();
3842 }
3843
Steve Antondcc3c022017-12-23 00:02:543844 // Apply ICE renomination flag.
3845 for (auto& options : session_options->media_description_options) {
3846 options.transport_options.enable_ice_renomination =
3847 configuration_.enable_ice_renomination;
3848 }
zhihuang8f65cdf2016-05-07 01:40:303849
3850 session_options->rtcp_cname = rtcp_cname_;
jbauchcb560652016-08-04 12:20:323851 session_options->crypto_options = factory_->options().crypto_options;
Steve Antone831b8c2018-02-01 20:22:163852 session_options->is_unified_plan = IsUnifiedPlan();
deadbeefab9b2d12015-10-14 18:33:113853}
3854
Steve Antondcc3c022017-12-23 00:02:543855void PeerConnection::GetOptionsForPlanBAnswer(
3856 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
Honghai Zhang4cedf2b2016-08-31 15:18:113857 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 21:10:503858 // Figure out transceiver directional preferences.
3859 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
3860 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
3861
3862 // By default, generate sendrecv/recvonly m= sections. The direction is also
3863 // restricted by the direction in the offer.
3864 bool recv_audio = true;
3865 bool recv_video = true;
3866
3867 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-23 00:02:543868 if (offer_answer_options.offer_to_receive_audio !=
3869 RTCOfferAnswerOptions::kUndefined) {
3870 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
deadbeef0ed85b22016-02-24 01:24:523871 }
Steve Antondcc3c022017-12-23 00:02:543872 if (offer_answer_options.offer_to_receive_video !=
3873 RTCOfferAnswerOptions::kUndefined) {
3874 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 21:10:503875 }
3876
3877 rtc::Optional<size_t> audio_index;
3878 rtc::Optional<size_t> video_index;
3879 rtc::Optional<size_t> data_index;
Steve Antondffead82018-02-06 18:31:293880
3881 // Generate m= sections that match those in the offer.
3882 // Note that mediasession.cc will handle intersection our preferred
3883 // direction with the offered direction.
3884 GenerateMediaDescriptionOptions(
3885 remote_description(),
3886 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
3887 RtpTransceiverDirectionFromSendRecv(send_video, recv_video), &audio_index,
3888 &video_index, &data_index, session_options);
zhihuang1c378ed2017-08-17 21:10:503889
3890 cricket::MediaDescriptionOptions* audio_media_description_options =
3891 !audio_index ? nullptr
3892 : &session_options->media_description_options[*audio_index];
3893 cricket::MediaDescriptionOptions* video_media_description_options =
3894 !video_index ? nullptr
3895 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 21:10:503896
Steve Anton4171afb2017-11-20 18:20:223897 AddRtpSenderOptions(GetSendersInternal(), audio_media_description_options,
zhihuang1c378ed2017-08-17 21:10:503898 video_media_description_options);
Steve Antondcc3c022017-12-23 00:02:543899}
zhihuangaf388472016-11-02 23:49:483900
Steve Antondcc3c022017-12-23 00:02:543901void PeerConnection::GetOptionsForUnifiedPlanAnswer(
3902 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
3903 cricket::MediaSessionOptions* session_options) {
3904 // Rules for generating an answer are dictated by JSEP sections 5.3.1 (Initial
3905 // Answers) and 5.3.2 (Subsequent Answers).
3906 RTC_DCHECK(remote_description());
3907 RTC_DCHECK(remote_description()->GetType() == SdpType::kOffer);
3908 for (const ContentInfo& content :
3909 remote_description()->description()->contents()) {
3910 cricket::MediaType media_type = content.media_description()->type();
3911 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
3912 media_type == cricket::MEDIA_TYPE_VIDEO) {
3913 auto transceiver = GetAssociatedTransceiver(content.name);
3914 RTC_CHECK(transceiver);
3915 session_options->media_description_options.push_back(
3916 GetMediaDescriptionOptionsForTransceiver(transceiver, content.name));
3917 } else {
3918 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antondbf9d032018-01-19 23:23:403919 // Reject all data sections if data channels are disabled.
3920 // Reject a data section if it has already been rejected.
3921 // Reject all data sections except for the first one.
3922 if (data_channel_type_ == cricket::DCT_NONE || content.rejected ||
3923 content.name != *GetDataMid()) {
Steve Antonfa2260d2017-12-29 00:38:233924 session_options->media_description_options.push_back(
3925 GetMediaDescriptionOptionsForRejectedData(content.name));
3926 } else {
3927 session_options->media_description_options.push_back(
3928 GetMediaDescriptionOptionsForActiveData(content.name));
3929 }
Steve Antondcc3c022017-12-23 00:02:543930 }
3931 }
htaa2a49d92016-03-04 10:51:393932}
3933
zhihuang1c378ed2017-08-17 21:10:503934void PeerConnection::GenerateMediaDescriptionOptions(
3935 const SessionDescriptionInterface* session_desc,
Steve Anton1d03a752017-11-27 22:30:093936 RtpTransceiverDirection audio_direction,
3937 RtpTransceiverDirection video_direction,
zhihuang1c378ed2017-08-17 21:10:503938 rtc::Optional<size_t>* audio_index,
3939 rtc::Optional<size_t>* video_index,
3940 rtc::Optional<size_t>* data_index,
htaa2a49d92016-03-04 10:51:393941 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 21:10:503942 for (const cricket::ContentInfo& content :
3943 session_desc->description()->contents()) {
3944 if (IsAudioContent(&content)) {
3945 // If we already have an audio m= section, reject this extra one.
3946 if (*audio_index) {
3947 session_options->media_description_options.push_back(
3948 cricket::MediaDescriptionOptions(
3949 cricket::MEDIA_TYPE_AUDIO, content.name,
Steve Anton1d03a752017-11-27 22:30:093950 RtpTransceiverDirection::kInactive, true));
zhihuang1c378ed2017-08-17 21:10:503951 } else {
3952 session_options->media_description_options.push_back(
3953 cricket::MediaDescriptionOptions(
3954 cricket::MEDIA_TYPE_AUDIO, content.name, audio_direction,
Steve Anton1d03a752017-11-27 22:30:093955 audio_direction == RtpTransceiverDirection::kInactive));
Oskar Sundbom9b28a032017-11-16 09:53:303956 *audio_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 21:10:503957 }
3958 } else if (IsVideoContent(&content)) {
3959 // If we already have an video m= section, reject this extra one.
3960 if (*video_index) {
3961 session_options->media_description_options.push_back(
3962 cricket::MediaDescriptionOptions(
3963 cricket::MEDIA_TYPE_VIDEO, content.name,
Steve Anton1d03a752017-11-27 22:30:093964 RtpTransceiverDirection::kInactive, true));
zhihuang1c378ed2017-08-17 21:10:503965 } else {
3966 session_options->media_description_options.push_back(
3967 cricket::MediaDescriptionOptions(
3968 cricket::MEDIA_TYPE_VIDEO, content.name, video_direction,
Steve Anton1d03a752017-11-27 22:30:093969 video_direction == RtpTransceiverDirection::kInactive));
Oskar Sundbom9b28a032017-11-16 09:53:303970 *video_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 21:10:503971 }
3972 } else {
3973 RTC_DCHECK(IsDataContent(&content));
3974 // If we already have an data m= section, reject this extra one.
3975 if (*data_index) {
3976 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-29 00:38:233977 GetMediaDescriptionOptionsForRejectedData(content.name));
zhihuang1c378ed2017-08-17 21:10:503978 } else {
3979 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-29 00:38:233980 GetMediaDescriptionOptionsForActiveData(content.name));
Oskar Sundbom9b28a032017-11-16 09:53:303981 *data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 21:10:503982 }
3983 }
htaa2a49d92016-03-04 10:51:393984 }
deadbeefab9b2d12015-10-14 18:33:113985}
3986
Steve Antonfa2260d2017-12-29 00:38:233987cricket::MediaDescriptionOptions
3988PeerConnection::GetMediaDescriptionOptionsForActiveData(
3989 const std::string& mid) const {
3990 // Direction for data sections is meaningless, but legacy endpoints might
3991 // expect sendrecv.
3992 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
3993 RtpTransceiverDirection::kSendRecv,
3994 /*stopped=*/false);
3995 AddRtpDataChannelOptions(rtp_data_channels_, &options);
3996 return options;
3997}
3998
3999cricket::MediaDescriptionOptions
4000PeerConnection::GetMediaDescriptionOptionsForRejectedData(
4001 const std::string& mid) const {
4002 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
4003 RtpTransceiverDirection::kInactive,
4004 /*stopped=*/true);
4005 AddRtpDataChannelOptions(rtp_data_channels_, &options);
4006 return options;
4007}
4008
4009rtc::Optional<std::string> PeerConnection::GetDataMid() const {
4010 switch (data_channel_type_) {
4011 case cricket::DCT_RTP:
4012 if (!rtp_data_channel_) {
4013 return rtc::nullopt;
4014 }
4015 return rtp_data_channel_->content_name();
4016 case cricket::DCT_SCTP:
Zhi Huange830e682018-03-30 17:48:354017 return sctp_mid_;
Steve Antonfa2260d2017-12-29 00:38:234018 default:
4019 return rtc::nullopt;
4020 }
4021}
4022
Steve Anton4171afb2017-11-20 18:20:224023void PeerConnection::RemoveSenders(cricket::MediaType media_type) {
4024 UpdateLocalSenders(std::vector<cricket::StreamParams>(), media_type);
4025 UpdateRemoteSendersList(std::vector<cricket::StreamParams>(), false,
deadbeefbda7e0b2015-12-09 01:13:404026 media_type, nullptr);
deadbeeffaac4972015-11-12 23:33:074027}
4028
Steve Anton4171afb2017-11-20 18:20:224029void PeerConnection::UpdateRemoteSendersList(
deadbeefab9b2d12015-10-14 18:33:114030 const cricket::StreamParamsVec& streams,
Steve Anton4171afb2017-11-20 18:20:224031 bool default_sender_needed,
deadbeefab9b2d12015-10-14 18:33:114032 cricket::MediaType media_type,
4033 StreamCollection* new_streams) {
Seth Hampson5b4f0752018-04-02 23:31:364034 RTC_DCHECK(!IsUnifiedPlan());
4035
Steve Anton4171afb2017-11-20 18:20:224036 std::vector<RtpSenderInfo>* current_senders =
4037 GetRemoteSenderInfos(media_type);
deadbeefab9b2d12015-10-14 18:33:114038
Steve Anton4171afb2017-11-20 18:20:224039 // Find removed senders. I.e., senders where the sender id or ssrc don't match
deadbeeffac06552015-11-25 19:26:014040 // the new StreamParam.
Steve Anton4171afb2017-11-20 18:20:224041 for (auto sender_it = current_senders->begin();
4042 sender_it != current_senders->end();
4043 /* incremented manually */) {
4044 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 18:33:114045 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 18:20:224046 cricket::GetStreamBySsrc(streams, info.first_ssrc);
Seth Hampson83d676b2018-04-06 01:12:094047 std::string params_stream_id;
4048 if (params) {
4049 params_stream_id =
4050 (!params->first_stream_id().empty() ? params->first_stream_id()
4051 : kDefaultStreamId);
4052 }
Seth Hampson5b4f0752018-04-02 23:31:364053 bool sender_exists = params && params->id == info.sender_id &&
Seth Hampson83d676b2018-04-06 01:12:094054 params_stream_id == info.stream_id;
deadbeefbda7e0b2015-12-09 01:13:404055 // If this is a default track, and we still need it, don't remove it.
Seth Hampson845e8782018-03-02 19:34:104056 if ((info.stream_id == kDefaultStreamId && default_sender_needed) ||
Steve Anton4171afb2017-11-20 18:20:224057 sender_exists) {
4058 ++sender_it;
deadbeefbda7e0b2015-12-09 01:13:404059 } else {
Steve Anton4171afb2017-11-20 18:20:224060 OnRemoteSenderRemoved(info, media_type);
4061 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 18:33:114062 }
4063 }
4064
Steve Anton4171afb2017-11-20 18:20:224065 // Find new and active senders.
deadbeefab9b2d12015-10-14 18:33:114066 for (const cricket::StreamParams& params : streams) {
Seth Hampson5897a6e2018-04-03 18:16:334067 if (!params.has_ssrcs()) {
4068 // The remote endpoint has streams, but didn't signal ssrcs. For an active
4069 // sender, this means it is coming from a Unified Plan endpoint,so we just
4070 // create a default.
4071 default_sender_needed = true;
4072 break;
4073 }
4074
Seth Hampson845e8782018-03-02 19:34:104075 // |params.id| is the sender id and the stream id uses the first of
Seth Hampson5b4f0752018-04-02 23:31:364076 // |params.stream_ids|. The remote description could come from a Unified
Seth Hampson5897a6e2018-04-03 18:16:334077 // Plan endpoint, with multiple or no stream_ids() signaled. Since this is
4078 // not supported in Plan B, we just take the first here and create the
4079 // default stream ID if none is specified.
Seth Hampson845e8782018-03-02 19:34:104080 const std::string& stream_id =
Seth Hampson83d676b2018-04-06 01:12:094081 (!params.first_stream_id().empty() ? params.first_stream_id()
4082 : kDefaultStreamId);
Steve Anton4171afb2017-11-20 18:20:224083 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 18:33:114084 uint32_t ssrc = params.first_ssrc();
4085
4086 rtc::scoped_refptr<MediaStreamInterface> stream =
Seth Hampson845e8782018-03-02 19:34:104087 remote_streams_->find(stream_id);
deadbeefab9b2d12015-10-14 18:33:114088 if (!stream) {
4089 // This is a new MediaStream. Create a new remote MediaStream.
perkjd61bf802016-03-24 10:16:194090 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
Seth Hampson845e8782018-03-02 19:34:104091 MediaStream::Create(stream_id));
deadbeefab9b2d12015-10-14 18:33:114092 remote_streams_->AddStream(stream);
4093 new_streams->AddStream(stream);
4094 }
4095
Steve Anton4171afb2017-11-20 18:20:224096 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609eaa2018-03-27 21:57:184097 FindSenderInfo(*current_senders, stream_id, sender_id);
Steve Anton4171afb2017-11-20 18:20:224098 if (!sender_info) {
Seth Hampson845e8782018-03-02 19:34:104099 current_senders->push_back(RtpSenderInfo(stream_id, sender_id, ssrc));
Steve Anton4171afb2017-11-20 18:20:224100 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 18:33:114101 }
4102 }
deadbeefbda7e0b2015-12-09 01:13:404103
Steve Anton4171afb2017-11-20 18:20:224104 // Add default sender if necessary.
4105 if (default_sender_needed) {
deadbeefbda7e0b2015-12-09 01:13:404106 rtc::scoped_refptr<MediaStreamInterface> default_stream =
Seth Hampson845e8782018-03-02 19:34:104107 remote_streams_->find(kDefaultStreamId);
deadbeefbda7e0b2015-12-09 01:13:404108 if (!default_stream) {
4109 // Create the new default MediaStream.
perkjd61bf802016-03-24 10:16:194110 default_stream = MediaStreamProxy::Create(
Seth Hampson845e8782018-03-02 19:34:104111 rtc::Thread::Current(), MediaStream::Create(kDefaultStreamId));
deadbeefbda7e0b2015-12-09 01:13:404112 remote_streams_->AddStream(default_stream);
4113 new_streams->AddStream(default_stream);
4114 }
Steve Anton4171afb2017-11-20 18:20:224115 std::string default_sender_id = (media_type == cricket::MEDIA_TYPE_AUDIO)
4116 ? kDefaultAudioSenderId
4117 : kDefaultVideoSenderId;
Seth Hampson845e8782018-03-02 19:34:104118 const RtpSenderInfo* default_sender_info =
Emircan Uysalerbc609eaa2018-03-27 21:57:184119 FindSenderInfo(*current_senders, kDefaultStreamId, default_sender_id);
Steve Anton4171afb2017-11-20 18:20:224120 if (!default_sender_info) {
4121 current_senders->push_back(
Seth Hampson845e8782018-03-02 19:34:104122 RtpSenderInfo(kDefaultStreamId, default_sender_id, 0));
Steve Anton4171afb2017-11-20 18:20:224123 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefbda7e0b2015-12-09 01:13:404124 }
4125 }
deadbeefab9b2d12015-10-14 18:33:114126}
4127
Steve Anton4171afb2017-11-20 18:20:224128void PeerConnection::OnRemoteSenderAdded(const RtpSenderInfo& sender_info,
4129 cricket::MediaType media_type) {
Steve Anton3d954a62018-04-02 18:27:234130 RTC_LOG(LS_INFO) << "Creating " << cricket::MediaTypeToString(media_type)
4131 << " receiver for track_id=" << sender_info.sender_id
4132 << " and stream_id=" << sender_info.stream_id;
deadbeefab9b2d12015-10-14 18:33:114133
Steve Anton3d954a62018-04-02 18:27:234134 MediaStreamInterface* stream = remote_streams_->find(sender_info.stream_id);
deadbeefab9b2d12015-10-14 18:33:114135 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 18:20:224136 CreateAudioReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 18:33:114137 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 18:20:224138 CreateVideoReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 18:33:114139 } else {
nisseeb4ca4e2017-01-12 10:24:274140 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 18:33:114141 }
4142}
4143
Steve Anton4171afb2017-11-20 18:20:224144void PeerConnection::OnRemoteSenderRemoved(const RtpSenderInfo& sender_info,
4145 cricket::MediaType media_type) {
Seth Hampson83d676b2018-04-06 01:12:094146 RTC_LOG(LS_INFO) << "Removing " << cricket::MediaTypeToString(media_type)
4147 << " receiver for track_id=" << sender_info.sender_id
4148 << " and stream_id=" << sender_info.stream_id;
4149
Seth Hampson845e8782018-03-02 19:34:104150 MediaStreamInterface* stream = remote_streams_->find(sender_info.stream_id);
deadbeefab9b2d12015-10-14 18:33:114151
Henrik Boström933d8b02017-10-10 17:05:164152 rtc::scoped_refptr<RtpReceiverInterface> receiver;
deadbeefab9b2d12015-10-14 18:33:114153 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
perkjd61bf802016-03-24 10:16:194154 // When the MediaEngine audio channel is destroyed, the RemoteAudioSource
4155 // will be notified which will end the AudioRtpReceiver::track().
Steve Anton4171afb2017-11-20 18:20:224156 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 18:33:114157 rtc::scoped_refptr<AudioTrackInterface> audio_track =
Steve Anton4171afb2017-11-20 18:20:224158 stream->FindAudioTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 18:33:114159 if (audio_track) {
deadbeefab9b2d12015-10-14 18:33:114160 stream->RemoveTrack(audio_track);
deadbeefab9b2d12015-10-14 18:33:114161 }
4162 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
perkjd61bf802016-03-24 10:16:194163 // Stopping or destroying a VideoRtpReceiver will end the
4164 // VideoRtpReceiver::track().
Steve Anton4171afb2017-11-20 18:20:224165 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 18:33:114166 rtc::scoped_refptr<VideoTrackInterface> video_track =
Steve Anton4171afb2017-11-20 18:20:224167 stream->FindVideoTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 18:33:114168 if (video_track) {
perkjd61bf802016-03-24 10:16:194169 // There's no guarantee the track is still available, e.g. the track may
4170 // have been removed from the stream by an application.
deadbeefab9b2d12015-10-14 18:33:114171 stream->RemoveTrack(video_track);
deadbeefab9b2d12015-10-14 18:33:114172 }
4173 } else {
nisseede5da42017-01-12 13:15:364174 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 18:33:114175 }
Henrik Boström933d8b02017-10-10 17:05:164176 if (receiver) {
4177 observer_->OnRemoveTrack(receiver);
4178 }
deadbeefab9b2d12015-10-14 18:33:114179}
4180
4181void PeerConnection::UpdateEndedRemoteMediaStreams() {
4182 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams_to_remove;
4183 for (size_t i = 0; i < remote_streams_->count(); ++i) {
4184 MediaStreamInterface* stream = remote_streams_->at(i);
4185 if (stream->GetAudioTracks().empty() && stream->GetVideoTracks().empty()) {
4186 streams_to_remove.push_back(stream);
4187 }
4188 }
4189
Taylor Brandstetter98cde262016-05-31 20:02:214190 for (auto& stream : streams_to_remove) {
deadbeefab9b2d12015-10-14 18:33:114191 remote_streams_->RemoveStream(stream);
Taylor Brandstetter98cde262016-05-31 20:02:214192 observer_->OnRemoveStream(std::move(stream));
deadbeefab9b2d12015-10-14 18:33:114193 }
4194}
4195
Steve Anton4171afb2017-11-20 18:20:224196void PeerConnection::UpdateLocalSenders(
deadbeefab9b2d12015-10-14 18:33:114197 const std::vector<cricket::StreamParams>& streams,
4198 cricket::MediaType media_type) {
Steve Anton4171afb2017-11-20 18:20:224199 std::vector<RtpSenderInfo>* current_senders = GetLocalSenderInfos(media_type);
deadbeefab9b2d12015-10-14 18:33:114200
Seth Hampson845e8782018-03-02 19:34:104201 // Find removed tracks. I.e., tracks where the track id, stream id or ssrc
deadbeefab9b2d12015-10-14 18:33:114202 // don't match the new StreamParam.
Steve Anton4171afb2017-11-20 18:20:224203 for (auto sender_it = current_senders->begin();
4204 sender_it != current_senders->end();
4205 /* incremented manually */) {
4206 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 18:33:114207 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 18:20:224208 cricket::GetStreamBySsrc(streams, info.first_ssrc);
4209 if (!params || params->id != info.sender_id ||
Seth Hampson845e8782018-03-02 19:34:104210 params->first_stream_id() != info.stream_id) {
Steve Anton4171afb2017-11-20 18:20:224211 OnLocalSenderRemoved(info, media_type);
4212 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 18:33:114213 } else {
Steve Anton4171afb2017-11-20 18:20:224214 ++sender_it;
deadbeefab9b2d12015-10-14 18:33:114215 }
4216 }
4217
Steve Anton4171afb2017-11-20 18:20:224218 // Find new and active senders.
deadbeefab9b2d12015-10-14 18:33:114219 for (const cricket::StreamParams& params : streams) {
4220 // The sync_label is the MediaStream label and the |stream.id| is the
Steve Anton4171afb2017-11-20 18:20:224221 // sender id.
Seth Hampson845e8782018-03-02 19:34:104222 const std::string& stream_id = params.first_stream_id();
Steve Anton4171afb2017-11-20 18:20:224223 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 18:33:114224 uint32_t ssrc = params.first_ssrc();
Steve Anton4171afb2017-11-20 18:20:224225 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609eaa2018-03-27 21:57:184226 FindSenderInfo(*current_senders, stream_id, sender_id);
Steve Anton4171afb2017-11-20 18:20:224227 if (!sender_info) {
Seth Hampson845e8782018-03-02 19:34:104228 current_senders->push_back(RtpSenderInfo(stream_id, sender_id, ssrc));
Steve Anton4171afb2017-11-20 18:20:224229 OnLocalSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 18:33:114230 }
4231 }
4232}
4233
Steve Anton4171afb2017-11-20 18:20:224234void PeerConnection::OnLocalSenderAdded(const RtpSenderInfo& sender_info,
4235 cricket::MediaType media_type) {
Seth Hampson5b4f0752018-04-02 23:31:364236 RTC_DCHECK(!IsUnifiedPlan());
Steve Anton4171afb2017-11-20 18:20:224237 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 19:26:014238 if (!sender) {
Steve Anton4171afb2017-11-20 18:20:224239 RTC_LOG(LS_WARNING) << "An unknown RtpSender with id "
4240 << sender_info.sender_id
Mirko Bonadei675513b2017-11-09 10:09:254241 << " has been configured in the local description.";
deadbeefab9b2d12015-10-14 18:33:114242 return;
4243 }
4244
deadbeeffac06552015-11-25 19:26:014245 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 10:09:254246 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
Jonas Olsson45cc8902018-02-13 09:37:074247 " description with an unexpected media type.";
deadbeeffac06552015-11-25 19:26:014248 return;
deadbeefab9b2d12015-10-14 18:33:114249 }
deadbeeffac06552015-11-25 19:26:014250
Seth Hampson5b4f0752018-04-02 23:31:364251 sender->internal()->set_stream_ids({sender_info.stream_id});
Steve Anton4171afb2017-11-20 18:20:224252 sender->internal()->SetSsrc(sender_info.first_ssrc);
deadbeefab9b2d12015-10-14 18:33:114253}
4254
Steve Anton4171afb2017-11-20 18:20:224255void PeerConnection::OnLocalSenderRemoved(const RtpSenderInfo& sender_info,
4256 cricket::MediaType media_type) {
4257 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 19:26:014258 if (!sender) {
4259 // This is the normal case. I.e., RemoveStream has been called and the
deadbeefab9b2d12015-10-14 18:33:114260 // SessionDescriptions has been renegotiated.
4261 return;
4262 }
deadbeeffac06552015-11-25 19:26:014263
4264 // A sender has been removed from the SessionDescription but it's still
4265 // associated with the PeerConnection. This only occurs if the SDP doesn't
4266 // match with the calls to CreateSender, AddStream and RemoveStream.
4267 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 10:09:254268 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
Jonas Olsson45cc8902018-02-13 09:37:074269 " description with an unexpected media type.";
deadbeeffac06552015-11-25 19:26:014270 return;
deadbeefab9b2d12015-10-14 18:33:114271 }
deadbeeffac06552015-11-25 19:26:014272
Steve Anton4171afb2017-11-20 18:20:224273 sender->internal()->SetSsrc(0);
deadbeefab9b2d12015-10-14 18:33:114274}
4275
4276void PeerConnection::UpdateLocalRtpDataChannels(
4277 const cricket::StreamParamsVec& streams) {
4278 std::vector<std::string> existing_channels;
4279
4280 // Find new and active data channels.
4281 for (const cricket::StreamParams& params : streams) {
4282 // |it->sync_label| is actually the data channel label. The reason is that
4283 // we use the same naming of data channels as we do for
4284 // MediaStreams and Tracks.
4285 // For MediaStreams, the sync_label is the MediaStream label and the
4286 // track label is the same as |streamid|.
Seth Hampson845e8782018-03-02 19:34:104287 const std::string& channel_label = params.first_stream_id();
deadbeefab9b2d12015-10-14 18:33:114288 auto data_channel_it = rtp_data_channels_.find(channel_label);
nisse7ce109a2017-01-31 08:57:564289 if (data_channel_it == rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 10:09:254290 RTC_LOG(LS_ERROR) << "channel label not found";
deadbeefab9b2d12015-10-14 18:33:114291 continue;
4292 }
4293 // Set the SSRC the data channel should use for sending.
4294 data_channel_it->second->SetSendSsrc(params.first_ssrc());
4295 existing_channels.push_back(data_channel_it->first);
4296 }
4297
4298 UpdateClosingRtpDataChannels(existing_channels, true);
4299}
4300
4301void PeerConnection::UpdateRemoteRtpDataChannels(
4302 const cricket::StreamParamsVec& streams) {
4303 std::vector<std::string> existing_channels;
4304
4305 // Find new and active data channels.
4306 for (const cricket::StreamParams& params : streams) {
4307 // The data channel label is either the mslabel or the SSRC if the mslabel
4308 // does not exist. Ex a=ssrc:444330170 mslabel:test1.
Seth Hampson845e8782018-03-02 19:34:104309 std::string label = params.first_stream_id().empty()
deadbeefab9b2d12015-10-14 18:33:114310 ? rtc::ToString(params.first_ssrc())
Seth Hampson845e8782018-03-02 19:34:104311 : params.first_stream_id();
deadbeefab9b2d12015-10-14 18:33:114312 auto data_channel_it = rtp_data_channels_.find(label);
4313 if (data_channel_it == rtp_data_channels_.end()) {
4314 // This is a new data channel.
4315 CreateRemoteRtpDataChannel(label, params.first_ssrc());
4316 } else {
4317 data_channel_it->second->SetReceiveSsrc(params.first_ssrc());
4318 }
4319 existing_channels.push_back(label);
4320 }
4321
4322 UpdateClosingRtpDataChannels(existing_channels, false);
4323}
4324
4325void PeerConnection::UpdateClosingRtpDataChannels(
4326 const std::vector<std::string>& active_channels,
4327 bool is_local_update) {
4328 auto it = rtp_data_channels_.begin();
4329 while (it != rtp_data_channels_.end()) {
4330 DataChannel* data_channel = it->second;
4331 if (std::find(active_channels.begin(), active_channels.end(),
4332 data_channel->label()) != active_channels.end()) {
4333 ++it;
4334 continue;
4335 }
4336
4337 if (is_local_update) {
4338 data_channel->SetSendSsrc(0);
4339 } else {
4340 data_channel->RemotePeerRequestClose();
4341 }
4342
4343 if (data_channel->state() == DataChannel::kClosed) {
4344 rtp_data_channels_.erase(it);
4345 it = rtp_data_channels_.begin();
4346 } else {
4347 ++it;
4348 }
4349 }
4350}
4351
4352void PeerConnection::CreateRemoteRtpDataChannel(const std::string& label,
4353 uint32_t remote_ssrc) {
4354 rtc::scoped_refptr<DataChannel> channel(
4355 InternalCreateDataChannel(label, nullptr));
4356 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 10:09:254357 RTC_LOG(LS_WARNING) << "Remote peer requested a DataChannel but"
Jonas Olsson45cc8902018-02-13 09:37:074358 "CreateDataChannel failed.";
deadbeefab9b2d12015-10-14 18:33:114359 return;
4360 }
4361 channel->SetReceiveSsrc(remote_ssrc);
deadbeefa601f5c2016-06-06 21:27:394362 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
4363 DataChannelProxy::Create(signaling_thread(), channel);
Taylor Brandstetter98cde262016-05-31 20:02:214364 observer_->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 18:33:114365}
4366
4367rtc::scoped_refptr<DataChannel> PeerConnection::InternalCreateDataChannel(
4368 const std::string& label,
4369 const InternalDataChannelInit* config) {
4370 if (IsClosed()) {
4371 return nullptr;
4372 }
Steve Anton75737c02017-11-06 18:37:174373 if (data_channel_type() == cricket::DCT_NONE) {
Mirko Bonadei675513b2017-11-09 10:09:254374 RTC_LOG(LS_ERROR)
deadbeefab9b2d12015-10-14 18:33:114375 << "InternalCreateDataChannel: Data is not supported in this call.";
4376 return nullptr;
4377 }
4378 InternalDataChannelInit new_config =
4379 config ? (*config) : InternalDataChannelInit();
Steve Anton75737c02017-11-06 18:37:174380 if (data_channel_type() == cricket::DCT_SCTP) {
deadbeefab9b2d12015-10-14 18:33:114381 if (new_config.id < 0) {
4382 rtc::SSLRole role;
Steve Anton75737c02017-11-06 18:37:174383 if ((GetSctpSslRole(&role)) &&
deadbeefab9b2d12015-10-14 18:33:114384 !sid_allocator_.AllocateSid(role, &new_config.id)) {
Mirko Bonadei675513b2017-11-09 10:09:254385 RTC_LOG(LS_ERROR)
4386 << "No id can be allocated for the SCTP data channel.";
deadbeefab9b2d12015-10-14 18:33:114387 return nullptr;
4388 }
4389 } else if (!sid_allocator_.ReserveSid(new_config.id)) {
Mirko Bonadei675513b2017-11-09 10:09:254390 RTC_LOG(LS_ERROR) << "Failed to create a SCTP data channel "
Jonas Olsson45cc8902018-02-13 09:37:074391 "because the id is already in use or out of range.";
deadbeefab9b2d12015-10-14 18:33:114392 return nullptr;
4393 }
4394 }
4395
Steve Anton75737c02017-11-06 18:37:174396 rtc::scoped_refptr<DataChannel> channel(
4397 DataChannel::Create(this, data_channel_type(), label, new_config));
deadbeefab9b2d12015-10-14 18:33:114398 if (!channel) {
4399 sid_allocator_.ReleaseSid(new_config.id);
4400 return nullptr;
4401 }
4402
4403 if (channel->data_channel_type() == cricket::DCT_RTP) {
4404 if (rtp_data_channels_.find(channel->label()) != rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 10:09:254405 RTC_LOG(LS_ERROR) << "DataChannel with label " << channel->label()
4406 << " already exists.";
deadbeefab9b2d12015-10-14 18:33:114407 return nullptr;
4408 }
4409 rtp_data_channels_[channel->label()] = channel;
4410 } else {
4411 RTC_DCHECK(channel->data_channel_type() == cricket::DCT_SCTP);
4412 sctp_data_channels_.push_back(channel);
4413 channel->SignalClosed.connect(this,
4414 &PeerConnection::OnSctpDataChannelClosed);
4415 }
4416
Steve Anton2d8609c2018-01-24 00:38:464417 SignalDataChannelCreated_(channel.get());
deadbeefab9b2d12015-10-14 18:33:114418 return channel;
4419}
4420
4421bool PeerConnection::HasDataChannels() const {
4422 return !rtp_data_channels_.empty() || !sctp_data_channels_.empty();
4423}
4424
4425void PeerConnection::AllocateSctpSids(rtc::SSLRole role) {
4426 for (const auto& channel : sctp_data_channels_) {
4427 if (channel->id() < 0) {
4428 int sid;
4429 if (!sid_allocator_.AllocateSid(role, &sid)) {
Mirko Bonadei675513b2017-11-09 10:09:254430 RTC_LOG(LS_ERROR) << "Failed to allocate SCTP sid.";
deadbeefab9b2d12015-10-14 18:33:114431 continue;
4432 }
4433 channel->SetSctpSid(sid);
4434 }
4435 }
4436}
4437
4438void PeerConnection::OnSctpDataChannelClosed(DataChannel* channel) {
deadbeefbd292462015-12-15 02:15:294439 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeefab9b2d12015-10-14 18:33:114440 for (auto it = sctp_data_channels_.begin(); it != sctp_data_channels_.end();
4441 ++it) {
4442 if (it->get() == channel) {
4443 if (channel->id() >= 0) {
4444 sid_allocator_.ReleaseSid(channel->id());
4445 }
deadbeefbd292462015-12-15 02:15:294446 // Since this method is triggered by a signal from the DataChannel,
4447 // we can't free it directly here; we need to free it asynchronously.
4448 sctp_data_channels_to_free_.push_back(*it);
deadbeefab9b2d12015-10-14 18:33:114449 sctp_data_channels_.erase(it);
Taylor Brandstetter5d97a9a2016-06-10 21:17:274450 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_FREE_DATACHANNELS,
4451 nullptr);
deadbeefab9b2d12015-10-14 18:33:114452 return;
4453 }
4454 }
4455}
4456
deadbeefab9b2d12015-10-14 18:33:114457void PeerConnection::OnDataChannelDestroyed() {
4458 // Use a temporary copy of the RTP/SCTP DataChannel list because the
4459 // DataChannel may callback to us and try to modify the list.
4460 std::map<std::string, rtc::scoped_refptr<DataChannel>> temp_rtp_dcs;
4461 temp_rtp_dcs.swap(rtp_data_channels_);
4462 for (const auto& kv : temp_rtp_dcs) {
4463 kv.second->OnTransportChannelDestroyed();
4464 }
4465
4466 std::vector<rtc::scoped_refptr<DataChannel>> temp_sctp_dcs;
4467 temp_sctp_dcs.swap(sctp_data_channels_);
4468 for (const auto& channel : temp_sctp_dcs) {
4469 channel->OnTransportChannelDestroyed();
4470 }
4471}
4472
4473void PeerConnection::OnDataChannelOpenMessage(
4474 const std::string& label,
4475 const InternalDataChannelInit& config) {
4476 rtc::scoped_refptr<DataChannel> channel(
4477 InternalCreateDataChannel(label, &config));
4478 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 10:09:254479 RTC_LOG(LS_ERROR) << "Failed to create DataChannel from the OPEN message.";
deadbeefab9b2d12015-10-14 18:33:114480 return;
4481 }
4482
deadbeefa601f5c2016-06-06 21:27:394483 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
4484 DataChannelProxy::Create(signaling_thread(), channel);
Taylor Brandstetter98cde262016-05-31 20:02:214485 observer_->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 18:33:114486}
4487
Steve Anton4171afb2017-11-20 18:20:224488rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
4489PeerConnection::GetAudioTransceiver() const {
4490 // This method only works with Plan B SDP, where there is a single
4491 // audio/video transceiver.
4492 RTC_DCHECK(!IsUnifiedPlan());
4493 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 19:43:084494 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 18:20:224495 return transceiver;
4496 }
4497 }
4498 RTC_NOTREACHED();
4499 return nullptr;
4500}
4501
4502rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
4503PeerConnection::GetVideoTransceiver() const {
4504 // This method only works with Plan B SDP, where there is a single
4505 // audio/video transceiver.
4506 RTC_DCHECK(!IsUnifiedPlan());
4507 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 19:43:084508 if (transceiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 18:20:224509 return transceiver;
4510 }
4511 }
4512 RTC_NOTREACHED();
4513 return nullptr;
4514}
4515
4516// TODO(bugs.webrtc.org/7600): Remove this when multiple transceivers with
4517// individual transceiver directions are supported.
zhihuang1c378ed2017-08-17 21:10:504518bool PeerConnection::HasRtpSender(cricket::MediaType type) const {
Steve Anton4171afb2017-11-20 18:20:224519 switch (type) {
4520 case cricket::MEDIA_TYPE_AUDIO:
4521 return !GetAudioTransceiver()->internal()->senders().empty();
4522 case cricket::MEDIA_TYPE_VIDEO:
4523 return !GetVideoTransceiver()->internal()->senders().empty();
4524 case cricket::MEDIA_TYPE_DATA:
4525 return false;
4526 }
4527 RTC_NOTREACHED();
4528 return false;
zhihuang1c378ed2017-08-17 21:10:504529}
4530
Steve Anton4171afb2017-11-20 18:20:224531rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
4532PeerConnection::FindSenderForTrack(MediaStreamTrackInterface* track) const {
4533 for (auto transceiver : transceivers_) {
4534 for (auto sender : transceiver->internal()->senders()) {
4535 if (sender->track() == track) {
4536 return sender;
4537 }
4538 }
4539 }
4540 return nullptr;
deadbeeffac06552015-11-25 19:26:014541}
4542
Steve Anton4171afb2017-11-20 18:20:224543rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
4544PeerConnection::FindSenderById(const std::string& sender_id) const {
4545 for (auto transceiver : transceivers_) {
4546 for (auto sender : transceiver->internal()->senders()) {
4547 if (sender->id() == sender_id) {
4548 return sender;
4549 }
4550 }
4551 }
4552 return nullptr;
deadbeef70ab1a12015-09-28 23:53:554553}
4554
Steve Anton4171afb2017-11-20 18:20:224555rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
4556PeerConnection::FindReceiverById(const std::string& receiver_id) const {
4557 for (auto transceiver : transceivers_) {
4558 for (auto receiver : transceiver->internal()->receivers()) {
4559 if (receiver->id() == receiver_id) {
4560 return receiver;
4561 }
4562 }
4563 }
4564 return nullptr;
deadbeef70ab1a12015-09-28 23:53:554565}
4566
Steve Anton4171afb2017-11-20 18:20:224567std::vector<PeerConnection::RtpSenderInfo>*
4568PeerConnection::GetRemoteSenderInfos(cricket::MediaType media_type) {
4569 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
4570 media_type == cricket::MEDIA_TYPE_VIDEO);
4571 return (media_type == cricket::MEDIA_TYPE_AUDIO)
4572 ? &remote_audio_sender_infos_
4573 : &remote_video_sender_infos_;
4574}
4575
4576std::vector<PeerConnection::RtpSenderInfo>* PeerConnection::GetLocalSenderInfos(
deadbeefab9b2d12015-10-14 18:33:114577 cricket::MediaType media_type) {
4578 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
4579 media_type == cricket::MEDIA_TYPE_VIDEO);
Steve Anton4171afb2017-11-20 18:20:224580 return (media_type == cricket::MEDIA_TYPE_AUDIO) ? &local_audio_sender_infos_
4581 : &local_video_sender_infos_;
deadbeefab9b2d12015-10-14 18:33:114582}
4583
Steve Anton4171afb2017-11-20 18:20:224584const PeerConnection::RtpSenderInfo* PeerConnection::FindSenderInfo(
4585 const std::vector<PeerConnection::RtpSenderInfo>& infos,
Emircan Uysalerbc609eaa2018-03-27 21:57:184586 const std::string& stream_id,
Steve Anton4171afb2017-11-20 18:20:224587 const std::string sender_id) const {
4588 for (const RtpSenderInfo& sender_info : infos) {
Emircan Uysalerbc609eaa2018-03-27 21:57:184589 if (sender_info.stream_id == stream_id &&
4590 sender_info.sender_id == sender_id) {
Steve Anton4171afb2017-11-20 18:20:224591 return &sender_info;
deadbeefab9b2d12015-10-14 18:33:114592 }
4593 }
4594 return nullptr;
4595}
4596
4597DataChannel* PeerConnection::FindDataChannelBySid(int sid) const {
4598 for (const auto& channel : sctp_data_channels_) {
4599 if (channel->id() == sid) {
4600 return channel;
4601 }
4602 }
4603 return nullptr;
4604}
4605
deadbeef91dd5672016-05-18 23:55:304606bool PeerConnection::InitializePortAllocator_n(
Taylor Brandstettera1c30352016-05-13 15:15:114607 const RTCConfiguration& configuration) {
4608 cricket::ServerAddresses stun_servers;
4609 std::vector<cricket::RelayServerConfig> turn_servers;
deadbeef293e9262017-01-11 20:28:304610 if (ParseIceServers(configuration.servers, &stun_servers, &turn_servers) !=
4611 RTCErrorType::NONE) {
Taylor Brandstettera1c30352016-05-13 15:15:114612 return false;
4613 }
4614
Taylor Brandstetterf8e65772016-06-28 00:20:154615 port_allocator_->Initialize();
Patrik Höglund3dc41062018-04-11 11:13:574616
Taylor Brandstettera1c30352016-05-13 15:15:114617 // To handle both internal and externally created port allocator, we will
4618 // enable BUNDLE here.
Patrik Höglund3dc41062018-04-11 11:13:574619 int portallocator_flags = port_allocator_->flags();
4620 portallocator_flags |= cricket::PORTALLOCATOR_ENABLE_SHARED_SOCKET |
4621 cricket::PORTALLOCATOR_ENABLE_IPV6 |
4622 cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI;
Taylor Brandstettera1c30352016-05-13 15:15:114623 // If the disable-IPv6 flag was specified, we'll not override it
4624 // by experiment.
4625 if (configuration.disable_ipv6) {
Patrik Höglund3dc41062018-04-11 11:13:574626 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
sprangc1b57a12017-02-28 16:50:474627 } else if (webrtc::field_trial::FindFullName("WebRTC-IPv6Default")
4628 .find("Disabled") == 0) {
Patrik Höglund3dc41062018-04-11 11:13:574629 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
Taylor Brandstettera1c30352016-05-13 15:15:114630 }
4631
zhihuangb09b3f92017-03-07 22:40:514632 if (configuration.disable_ipv6_on_wifi) {
Patrik Höglund3dc41062018-04-11 11:13:574633 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI);
Mirko Bonadei675513b2017-11-09 10:09:254634 RTC_LOG(LS_INFO) << "IPv6 candidates on Wi-Fi are disabled.";
zhihuangb09b3f92017-03-07 22:40:514635 }
4636
Taylor Brandstettera1c30352016-05-13 15:15:114637 if (configuration.tcp_candidate_policy == kTcpCandidatePolicyDisabled) {
Patrik Höglund3dc41062018-04-11 11:13:574638 portallocator_flags |= cricket::PORTALLOCATOR_DISABLE_TCP;
Mirko Bonadei675513b2017-11-09 10:09:254639 RTC_LOG(LS_INFO) << "TCP candidates are disabled.";
Taylor Brandstettera1c30352016-05-13 15:15:114640 }
4641
honghaiz60347052016-06-01 01:29:124642 if (configuration.candidate_network_policy ==
4643 kCandidateNetworkPolicyLowCost) {
Patrik Höglund3dc41062018-04-11 11:13:574644 portallocator_flags |= cricket::PORTALLOCATOR_DISABLE_COSTLY_NETWORKS;
Mirko Bonadei675513b2017-11-09 10:09:254645 RTC_LOG(LS_INFO) << "Do not gather candidates on high-cost networks";
honghaiz60347052016-06-01 01:29:124646 }
4647
Daniel Lazarenko2870b0a2018-01-25 09:30:224648 if (configuration.disable_link_local_networks) {
Patrik Höglund3dc41062018-04-11 11:13:574649 portallocator_flags |= cricket::PORTALLOCATOR_DISABLE_LINK_LOCAL_NETWORKS;
Daniel Lazarenko2870b0a2018-01-25 09:30:224650 RTC_LOG(LS_INFO) << "Disable candidates on link-local network interfaces.";
4651 }
4652
Patrik Höglund3dc41062018-04-11 11:13:574653 port_allocator_->set_flags(portallocator_flags);
Taylor Brandstettera1c30352016-05-13 15:15:114654 // No step delay is used while allocating ports.
4655 port_allocator_->set_step_delay(cricket::kMinimumStepDelay);
4656 port_allocator_->set_candidate_filter(
4657 ConvertIceTransportTypeToCandidateFilter(configuration.type));
deadbeefd21eab3e2017-07-26 23:50:114658 port_allocator_->set_max_ipv6_networks(configuration.max_ipv6_networks);
Taylor Brandstettera1c30352016-05-13 15:15:114659
4660 // Call this last since it may create pooled allocator sessions using the
4661 // properties set above.
Qingsi Wangdb53f8e2018-02-20 22:45:494662 port_allocator_->SetConfiguration(
4663 stun_servers, turn_servers, configuration.ice_candidate_pool_size,
4664 configuration.prune_turn_ports, configuration.turn_customizer,
4665 configuration.stun_candidate_keepalive_interval);
Taylor Brandstettera1c30352016-05-13 15:15:114666 return true;
4667}
4668
deadbeef91dd5672016-05-18 23:55:304669bool PeerConnection::ReconfigurePortAllocator_n(
deadbeef293e9262017-01-11 20:28:304670 const cricket::ServerAddresses& stun_servers,
4671 const std::vector<cricket::RelayServerConfig>& turn_servers,
4672 IceTransportsType type,
4673 int candidate_pool_size,
Jonas Orelandbdcee282017-10-10 12:01:404674 bool prune_turn_ports,
Qingsi Wangdb53f8e2018-02-20 22:45:494675 webrtc::TurnCustomizer* turn_customizer,
4676 rtc::Optional<int> stun_candidate_keepalive_interval) {
Taylor Brandstettera1c30352016-05-13 15:15:114677 port_allocator_->set_candidate_filter(
deadbeef293e9262017-01-11 20:28:304678 ConvertIceTransportTypeToCandidateFilter(type));
Taylor Brandstettera1c30352016-05-13 15:15:114679 // Call this last since it may create pooled allocator sessions using the
4680 // candidate filter set above.
deadbeef6de92f92016-12-13 02:49:324681 return port_allocator_->SetConfiguration(
Jonas Orelandbdcee282017-10-10 12:01:404682 stun_servers, turn_servers, candidate_pool_size, prune_turn_ports,
Qingsi Wangdb53f8e2018-02-20 22:45:494683 turn_customizer, stun_candidate_keepalive_interval);
Taylor Brandstettera1c30352016-05-13 15:15:114684}
4685
Steve Antonba818672017-11-06 18:21:574686cricket::ChannelManager* PeerConnection::channel_manager() const {
4687 return factory_->channel_manager();
4688}
4689
4690MetricsObserverInterface* PeerConnection::metrics_observer() const {
4691 return uma_observer_;
4692}
4693
Elad Alon99c3fe52017-10-13 14:29:404694bool PeerConnection::StartRtcEventLog_w(
Bjorn Tereliusde939432017-11-20 16:38:144695 std::unique_ptr<RtcEventLogOutput> output,
4696 int64_t output_period_ms) {
zhihuang77985012017-02-07 23:45:164697 if (!event_log_) {
4698 return false;
4699 }
Bjorn Tereliusde939432017-11-20 16:38:144700 return event_log_->StartLogging(std::move(output), output_period_ms);
ivoc14d5dbe2016-07-04 14:06:554701}
4702
4703void PeerConnection::StopRtcEventLog_w() {
zhihuang77985012017-02-07 23:45:164704 if (event_log_) {
4705 event_log_->StopLogging();
4706 }
ivoc14d5dbe2016-07-04 14:06:554707}
nisseeaabdf62017-05-05 09:23:024708
Steve Anton75737c02017-11-06 18:37:174709cricket::BaseChannel* PeerConnection::GetChannel(
4710 const std::string& content_name) {
Steve Antondcc3c022017-12-23 00:02:544711 for (auto transceiver : transceivers_) {
4712 cricket::BaseChannel* channel = transceiver->internal()->channel();
4713 if (channel && channel->content_name() == content_name) {
4714 return channel;
4715 }
Steve Anton75737c02017-11-06 18:37:174716 }
4717 if (rtp_data_channel() &&
4718 rtp_data_channel()->content_name() == content_name) {
4719 return rtp_data_channel();
4720 }
4721 return nullptr;
4722}
4723
4724bool PeerConnection::GetSctpSslRole(rtc::SSLRole* role) {
4725 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 10:09:254726 RTC_LOG(LS_INFO)
4727 << "Local and Remote descriptions must be applied to get the "
Jonas Olsson45cc8902018-02-13 09:37:074728 "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 18:37:174729 return false;
4730 }
4731 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 10:09:254732 RTC_LOG(LS_INFO) << "Non-rejected SCTP m= section is needed to get the "
Jonas Olsson45cc8902018-02-13 09:37:074733 "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 18:37:174734 return false;
4735 }
4736
Zhi Huange830e682018-03-30 17:48:354737 auto dtls_role = transport_controller_->GetDtlsRole(*sctp_mid_);
4738 if (dtls_role) {
4739 *role = *dtls_role;
4740 return true;
4741 }
4742 return false;
Steve Anton75737c02017-11-06 18:37:174743}
4744
4745bool PeerConnection::GetSslRole(const std::string& content_name,
4746 rtc::SSLRole* role) {
4747 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 10:09:254748 RTC_LOG(LS_INFO)
4749 << "Local and Remote descriptions must be applied to get the "
Jonas Olsson45cc8902018-02-13 09:37:074750 "SSL Role of the session.";
Steve Anton75737c02017-11-06 18:37:174751 return false;
4752 }
4753
Zhi Huange830e682018-03-30 17:48:354754 auto dtls_role = transport_controller_->GetDtlsRole(content_name);
4755 if (dtls_role) {
4756 *role = *dtls_role;
4757 return true;
4758 }
4759 return false;
Steve Anton75737c02017-11-06 18:37:174760}
4761
Steve Antonf8470812017-12-04 18:46:214762void PeerConnection::SetSessionError(SessionError error,
4763 const std::string& error_desc) {
4764 RTC_DCHECK_RUN_ON(signaling_thread());
4765 if (error != session_error_) {
4766 session_error_ = error;
4767 session_error_desc_ = error_desc;
Steve Anton75737c02017-11-06 18:37:174768 }
4769}
4770
Zhi Huange830e682018-03-30 17:48:354771RTCError PeerConnection::UpdateSessionState(
4772 SdpType type,
4773 cricket::ContentSource source,
4774 const cricket::SessionDescription* description) {
Steve Anton8a006912017-12-04 23:25:564775 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 18:37:174776
4777 // If there's already a pending error then no state transition should happen.
4778 // But all call-sites should be verifying this before calling us!
Steve Antonf8470812017-12-04 18:46:214779 RTC_DCHECK(session_error() == SessionError::kNone);
Steve Anton6d6a2ae2017-12-05 01:19:474780
Steve Anton6d6a2ae2017-12-05 01:19:474781 // If this is answer-ish we're ready to let media flow.
Steve Anton3828c062017-12-06 18:34:514782 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Antoned10bd92017-12-05 18:52:594783 EnableSending();
Steve Anton6d6a2ae2017-12-05 01:19:474784 }
4785
4786 // Update the signaling state according to the specified state machine (see
4787 // https://w3c.github.io/webrtc-pc/#rtcsignalingstate-enum).
Steve Anton3828c062017-12-06 18:34:514788 if (type == SdpType::kOffer) {
Steve Anton6d6a2ae2017-12-05 01:19:474789 ChangeSignalingState(source == cricket::CS_LOCAL
4790 ? PeerConnectionInterface::kHaveLocalOffer
4791 : PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton3828c062017-12-06 18:34:514792 } else if (type == SdpType::kPrAnswer) {
Steve Anton6d6a2ae2017-12-05 01:19:474793 ChangeSignalingState(source == cricket::CS_LOCAL
4794 ? PeerConnectionInterface::kHaveLocalPrAnswer
4795 : PeerConnectionInterface::kHaveRemotePrAnswer);
4796 } else {
Steve Anton3828c062017-12-06 18:34:514797 RTC_DCHECK(type == SdpType::kAnswer);
Steve Anton6d6a2ae2017-12-05 01:19:474798 ChangeSignalingState(PeerConnectionInterface::kStable);
4799 }
4800
4801 // Update internal objects according to the session description's media
4802 // descriptions.
Zhi Huange830e682018-03-30 17:48:354803 RTCError error = PushdownMediaDescription(type, source);
Steve Anton6d6a2ae2017-12-05 01:19:474804 if (!error.ok()) {
Steve Anton80dd7b52018-02-17 01:08:424805 return error;
Steve Anton6d6a2ae2017-12-05 01:19:474806 }
4807
Steve Anton8a006912017-12-04 23:25:564808 return RTCError::OK();
Steve Anton75737c02017-11-06 18:37:174809}
4810
Steve Anton8a006912017-12-04 23:25:564811RTCError PeerConnection::PushdownMediaDescription(
Steve Anton3828c062017-12-06 18:34:514812 SdpType type,
Steve Anton8a006912017-12-04 23:25:564813 cricket::ContentSource source) {
Steve Antoned10bd92017-12-05 18:52:594814 const SessionDescriptionInterface* sdesc =
4815 (source == cricket::CS_LOCAL ? local_description()
4816 : remote_description());
Steve Anton75737c02017-11-06 18:37:174817 RTC_DCHECK(sdesc);
Steve Antoned10bd92017-12-05 18:52:594818
4819 // Push down the new SDP media section for each audio/video transceiver.
4820 for (auto transceiver : transceivers_) {
Steve Anton75737c02017-11-06 18:37:174821 const ContentInfo* content_info =
Steve Antoned10bd92017-12-05 18:52:594822 FindMediaSectionForTransceiver(transceiver, sdesc);
4823 cricket::BaseChannel* channel = transceiver->internal()->channel();
4824 if (!channel || !content_info || content_info->rejected) {
Steve Anton75737c02017-11-06 18:37:174825 continue;
4826 }
4827 const MediaContentDescription* content_desc =
Steve Antonb1c1de12017-12-21 23:14:304828 content_info->media_description();
Steve Antoned10bd92017-12-05 18:52:594829 if (!content_desc) {
4830 continue;
4831 }
4832 std::string error;
4833 bool success =
4834 (source == cricket::CS_LOCAL)
Steve Anton3828c062017-12-06 18:34:514835 ? channel->SetLocalContent(content_desc, type, &error)
4836 : channel->SetRemoteContent(content_desc, type, &error);
Steve Antoned10bd92017-12-05 18:52:594837 if (!success) {
4838 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, std::move(error));
4839 }
4840 }
4841
4842 // If using the RtpDataChannel, push down the new SDP section for it too.
4843 if (rtp_data_channel_) {
4844 const ContentInfo* data_content =
4845 cricket::GetFirstDataContent(sdesc->description());
4846 if (data_content && !data_content->rejected) {
4847 const MediaContentDescription* data_desc =
Steve Antonb1c1de12017-12-21 23:14:304848 data_content->media_description();
Steve Antoned10bd92017-12-05 18:52:594849 if (data_desc) {
4850 std::string error;
4851 bool success =
4852 (source == cricket::CS_LOCAL)
Steve Anton3828c062017-12-06 18:34:514853 ? rtp_data_channel_->SetLocalContent(data_desc, type, &error)
4854 : rtp_data_channel_->SetRemoteContent(data_desc, type,
Steve Antoned10bd92017-12-05 18:52:594855 &error);
4856 if (!success) {
4857 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
4858 std::move(error));
4859 }
Steve Anton75737c02017-11-06 18:37:174860 }
4861 }
4862 }
Steve Antoned10bd92017-12-05 18:52:594863
Steve Anton75737c02017-11-06 18:37:174864 // Need complete offer/answer with an SCTP m= section before starting SCTP,
4865 // according to https://tools.ietf.org/html/draft-ietf-mmusic-sctp-sdp-19
4866 if (sctp_transport_ && local_description() && remote_description() &&
4867 cricket::GetFirstDataContent(local_description()->description()) &&
4868 cricket::GetFirstDataContent(remote_description()->description())) {
Steve Anton8a006912017-12-04 23:25:564869 bool success = network_thread()->Invoke<bool>(
Steve Anton75737c02017-11-06 18:37:174870 RTC_FROM_HERE,
4871 rtc::Bind(&PeerConnection::PushdownSctpParameters_n, this, source));
Steve Anton8a006912017-12-04 23:25:564872 if (!success) {
4873 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
4874 "Failed to push down SCTP parameters.");
4875 }
Steve Anton75737c02017-11-06 18:37:174876 }
Steve Antoned10bd92017-12-05 18:52:594877
Steve Anton8a006912017-12-04 23:25:564878 return RTCError::OK();
Steve Anton75737c02017-11-06 18:37:174879}
4880
4881bool PeerConnection::PushdownSctpParameters_n(cricket::ContentSource source) {
4882 RTC_DCHECK(network_thread()->IsCurrent());
4883 RTC_DCHECK(local_description());
4884 RTC_DCHECK(remote_description());
4885 // Apply the SCTP port (which is hidden inside a DataCodec structure...)
4886 // When we support "max-message-size", that would also be pushed down here.
4887 return sctp_transport_->Start(
4888 GetSctpPort(local_description()->description()),
4889 GetSctpPort(remote_description()->description()));
4890}
4891
Steve Anton8a006912017-12-04 23:25:564892RTCError PeerConnection::PushdownTransportDescription(
4893 cricket::ContentSource source,
Steve Anton3828c062017-12-06 18:34:514894 SdpType type) {
Steve Anton8a006912017-12-04 23:25:564895 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 18:37:174896
Zhi Huange830e682018-03-30 17:48:354897 if (source == cricket::CS_LOCAL) {
4898 const SessionDescriptionInterface* sdesc = local_description();
4899 RTC_DCHECK(sdesc);
4900 return transport_controller_->SetLocalDescription(type,
4901 sdesc->description());
4902 } else {
4903 const SessionDescriptionInterface* sdesc = remote_description();
4904 RTC_DCHECK(sdesc);
4905 return transport_controller_->SetRemoteDescription(type,
4906 sdesc->description());
Steve Anton75737c02017-11-06 18:37:174907 }
Steve Anton75737c02017-11-06 18:37:174908}
4909
4910bool PeerConnection::GetTransportDescription(
4911 const SessionDescription* description,
4912 const std::string& content_name,
4913 cricket::TransportDescription* tdesc) {
4914 if (!description || !tdesc) {
4915 return false;
4916 }
4917 const TransportInfo* transport_info =
4918 description->GetTransportInfoByName(content_name);
4919 if (!transport_info) {
4920 return false;
4921 }
4922 *tdesc = transport_info->description;
4923 return true;
4924}
4925
Steve Anton75737c02017-11-06 18:37:174926cricket::IceConfig PeerConnection::ParseIceConfig(
4927 const PeerConnectionInterface::RTCConfiguration& config) const {
4928 cricket::ContinualGatheringPolicy gathering_policy;
4929 // TODO(honghaiz): Add the third continual gathering policy in
4930 // PeerConnectionInterface and map it to GATHER_CONTINUALLY_AND_RECOVER.
4931 switch (config.continual_gathering_policy) {
4932 case PeerConnectionInterface::GATHER_ONCE:
4933 gathering_policy = cricket::GATHER_ONCE;
4934 break;
4935 case PeerConnectionInterface::GATHER_CONTINUALLY:
4936 gathering_policy = cricket::GATHER_CONTINUALLY;
4937 break;
4938 default:
4939 RTC_NOTREACHED();
4940 gathering_policy = cricket::GATHER_ONCE;
4941 }
Qingsi Wang9a5c6f82018-02-01 18:38:404942
Steve Anton75737c02017-11-06 18:37:174943 cricket::IceConfig ice_config;
Qingsi Wang866e08d2018-03-23 00:54:234944 ice_config.receiving_timeout = RTCConfigurationToIceConfigOptionalInt(
4945 config.ice_connection_receiving_timeout);
Steve Anton75737c02017-11-06 18:37:174946 ice_config.prioritize_most_likely_candidate_pairs =
4947 config.prioritize_most_likely_ice_candidate_pairs;
4948 ice_config.backup_connection_ping_interval =
Qingsi Wang866e08d2018-03-23 00:54:234949 RTCConfigurationToIceConfigOptionalInt(
4950 config.ice_backup_candidate_pair_ping_interval);
Steve Anton75737c02017-11-06 18:37:174951 ice_config.continual_gathering_policy = gathering_policy;
4952 ice_config.presume_writable_when_fully_relayed =
4953 config.presume_writable_when_fully_relayed;
Qingsi Wange6826d22018-03-08 22:55:144954 ice_config.ice_check_interval_strong_connectivity =
4955 config.ice_check_interval_strong_connectivity;
4956 ice_config.ice_check_interval_weak_connectivity =
4957 config.ice_check_interval_weak_connectivity;
Steve Anton75737c02017-11-06 18:37:174958 ice_config.ice_check_min_interval = config.ice_check_min_interval;
Qingsi Wangdb53f8e2018-02-20 22:45:494959 ice_config.stun_keepalive_interval = config.stun_candidate_keepalive_interval;
Steve Anton75737c02017-11-06 18:37:174960 ice_config.regather_all_networks_interval_range =
4961 config.ice_regather_interval_range;
Qingsi Wang9a5c6f82018-02-01 18:38:404962 ice_config.network_preference = config.network_preference;
Steve Anton75737c02017-11-06 18:37:174963 return ice_config;
4964}
4965
Steve Anton75737c02017-11-06 18:37:174966bool PeerConnection::GetLocalTrackIdBySsrc(uint32_t ssrc,
4967 std::string* track_id) {
4968 if (!local_description()) {
4969 return false;
4970 }
4971 return webrtc::GetTrackIdBySsrc(local_description()->description(), ssrc,
4972 track_id);
4973}
4974
4975bool PeerConnection::GetRemoteTrackIdBySsrc(uint32_t ssrc,
4976 std::string* track_id) {
4977 if (!remote_description()) {
4978 return false;
4979 }
4980 return webrtc::GetTrackIdBySsrc(remote_description()->description(), ssrc,
4981 track_id);
4982}
4983
4984bool PeerConnection::SendData(const cricket::SendDataParams& params,
4985 const rtc::CopyOnWriteBuffer& payload,
4986 cricket::SendDataResult* result) {
4987 if (!rtp_data_channel_ && !sctp_transport_) {
Mirko Bonadei675513b2017-11-09 10:09:254988 RTC_LOG(LS_ERROR) << "SendData called when rtp_data_channel_ "
Jonas Olsson45cc8902018-02-13 09:37:074989 "and sctp_transport_ are NULL.";
Steve Anton75737c02017-11-06 18:37:174990 return false;
4991 }
4992 return rtp_data_channel_
4993 ? rtp_data_channel_->SendData(params, payload, result)
4994 : network_thread()->Invoke<bool>(
4995 RTC_FROM_HERE,
4996 Bind(&cricket::SctpTransportInternal::SendData,
4997 sctp_transport_.get(), params, payload, result));
4998}
4999
5000bool PeerConnection::ConnectDataChannel(DataChannel* webrtc_data_channel) {
5001 if (!rtp_data_channel_ && !sctp_transport_) {
5002 // Don't log an error here, because DataChannels are expected to call
5003 // ConnectDataChannel in this state. It's the only way to initially tell
5004 // whether or not the underlying transport is ready.
5005 return false;
5006 }
5007 if (rtp_data_channel_) {
5008 rtp_data_channel_->SignalReadyToSendData.connect(
5009 webrtc_data_channel, &DataChannel::OnChannelReady);
5010 rtp_data_channel_->SignalDataReceived.connect(webrtc_data_channel,
5011 &DataChannel::OnDataReceived);
5012 } else {
5013 SignalSctpReadyToSendData.connect(webrtc_data_channel,
5014 &DataChannel::OnChannelReady);
5015 SignalSctpDataReceived.connect(webrtc_data_channel,
5016 &DataChannel::OnDataReceived);
5017 SignalSctpStreamClosedRemotely.connect(
5018 webrtc_data_channel, &DataChannel::OnStreamClosedRemotely);
5019 }
5020 return true;
5021}
5022
5023void PeerConnection::DisconnectDataChannel(DataChannel* webrtc_data_channel) {
5024 if (!rtp_data_channel_ && !sctp_transport_) {
Mirko Bonadei675513b2017-11-09 10:09:255025 RTC_LOG(LS_ERROR)
5026 << "DisconnectDataChannel called when rtp_data_channel_ and "
5027 "sctp_transport_ are NULL.";
Steve Anton75737c02017-11-06 18:37:175028 return;
5029 }
5030 if (rtp_data_channel_) {
5031 rtp_data_channel_->SignalReadyToSendData.disconnect(webrtc_data_channel);
5032 rtp_data_channel_->SignalDataReceived.disconnect(webrtc_data_channel);
5033 } else {
5034 SignalSctpReadyToSendData.disconnect(webrtc_data_channel);
5035 SignalSctpDataReceived.disconnect(webrtc_data_channel);
5036 SignalSctpStreamClosedRemotely.disconnect(webrtc_data_channel);
5037 }
5038}
5039
5040void PeerConnection::AddSctpDataStream(int sid) {
5041 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 10:09:255042 RTC_LOG(LS_ERROR)
5043 << "AddSctpDataStream called when sctp_transport_ is NULL.";
Steve Anton75737c02017-11-06 18:37:175044 return;
5045 }
5046 network_thread()->Invoke<void>(
5047 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::OpenStream,
5048 sctp_transport_.get(), sid));
5049}
5050
5051void PeerConnection::RemoveSctpDataStream(int sid) {
5052 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 10:09:255053 RTC_LOG(LS_ERROR) << "RemoveSctpDataStream called when sctp_transport_ is "
Jonas Olsson45cc8902018-02-13 09:37:075054 "NULL.";
Steve Anton75737c02017-11-06 18:37:175055 return;
5056 }
5057 network_thread()->Invoke<void>(
5058 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::ResetStream,
5059 sctp_transport_.get(), sid));
5060}
5061
5062bool PeerConnection::ReadyToSendData() const {
5063 return (rtp_data_channel_ && rtp_data_channel_->ready_to_send_data()) ||
5064 sctp_ready_to_send_data_;
5065}
5066
Zhi Huange830e682018-03-30 17:48:355067rtc::Optional<std::string> PeerConnection::sctp_transport_name() const {
5068 if (sctp_mid_ && transport_controller_) {
5069 auto dtls_transport = transport_controller_->GetDtlsTransport(*sctp_mid_);
5070 if (dtls_transport) {
5071 return dtls_transport->transport_name();
5072 }
5073 return rtc::Optional<std::string>();
5074 }
5075 return rtc::Optional<std::string>();
5076}
5077
Qingsi Wang72a43a12018-02-21 00:03:185078cricket::CandidateStatsList PeerConnection::GetPooledCandidateStats() const {
5079 cricket::CandidateStatsList candidate_states_list;
Patrik Höglund3dc41062018-04-11 11:13:575080 port_allocator_->GetCandidateStatsFromPooledSessions(&candidate_states_list);
Qingsi Wang72a43a12018-02-21 00:03:185081 return candidate_states_list;
5082}
5083
Steve Anton5dfde182018-02-06 18:34:405084std::map<std::string, std::string> PeerConnection::GetTransportNamesByMid()
5085 const {
5086 std::map<std::string, std::string> transport_names_by_mid;
5087 for (auto transceiver : transceivers_) {
5088 cricket::BaseChannel* channel = transceiver->internal()->channel();
5089 if (channel) {
5090 transport_names_by_mid[channel->content_name()] =
5091 channel->transport_name();
5092 }
Steve Anton75737c02017-11-06 18:37:175093 }
Steve Anton5dfde182018-02-06 18:34:405094 if (rtp_data_channel_) {
5095 transport_names_by_mid[rtp_data_channel_->content_name()] =
5096 rtp_data_channel_->transport_name();
Steve Anton75737c02017-11-06 18:37:175097 }
5098 if (sctp_transport_) {
Zhi Huange830e682018-03-30 17:48:355099 rtc::Optional<std::string> transport_name = sctp_transport_name();
5100 RTC_DCHECK(transport_name);
5101 transport_names_by_mid[*sctp_mid_] = *transport_name;
Steve Anton75737c02017-11-06 18:37:175102 }
Steve Anton5dfde182018-02-06 18:34:405103 return transport_names_by_mid;
Steve Anton75737c02017-11-06 18:37:175104}
5105
Steve Anton5dfde182018-02-06 18:34:405106std::map<std::string, cricket::TransportStats>
5107PeerConnection::GetTransportStatsByNames(
5108 const std::set<std::string>& transport_names) {
5109 if (!network_thread()->IsCurrent()) {
5110 return network_thread()
5111 ->Invoke<std::map<std::string, cricket::TransportStats>>(
5112 RTC_FROM_HERE,
5113 [&] { return GetTransportStatsByNames(transport_names); });
Steve Anton75737c02017-11-06 18:37:175114 }
Steve Anton5dfde182018-02-06 18:34:405115 std::map<std::string, cricket::TransportStats> transport_stats_by_name;
5116 for (const std::string& transport_name : transport_names) {
5117 cricket::TransportStats transport_stats;
5118 bool success =
5119 transport_controller_->GetStats(transport_name, &transport_stats);
5120 if (success) {
5121 transport_stats_by_name[transport_name] = std::move(transport_stats);
5122 } else {
5123 RTC_LOG(LS_ERROR) << "Failed to get transport stats for transport_name="
5124 << transport_name;
5125 }
5126 }
5127 return transport_stats_by_name;
Steve Anton75737c02017-11-06 18:37:175128}
5129
5130bool PeerConnection::GetLocalCertificate(
5131 const std::string& transport_name,
5132 rtc::scoped_refptr<rtc::RTCCertificate>* certificate) {
Zhi Huange830e682018-03-30 17:48:355133 if (!certificate) {
5134 return false;
5135 }
5136 *certificate = transport_controller_->GetLocalCertificate(transport_name);
5137 return *certificate != nullptr;
Steve Anton75737c02017-11-06 18:37:175138}
5139
Taylor Brandstetterc3928662018-02-23 21:04:515140std::unique_ptr<rtc::SSLCertChain> PeerConnection::GetRemoteSSLCertChain(
Steve Anton75737c02017-11-06 18:37:175141 const std::string& transport_name) {
Taylor Brandstetterc3928662018-02-23 21:04:515142 return transport_controller_->GetRemoteSSLCertChain(transport_name);
Steve Anton75737c02017-11-06 18:37:175143}
5144
5145cricket::DataChannelType PeerConnection::data_channel_type() const {
5146 return data_channel_type_;
5147}
5148
5149bool PeerConnection::IceRestartPending(const std::string& content_name) const {
5150 return pending_ice_restarts_.find(content_name) !=
5151 pending_ice_restarts_.end();
5152}
5153
Steve Anton75737c02017-11-06 18:37:175154bool PeerConnection::NeedsIceRestart(const std::string& content_name) const {
5155 return transport_controller_->NeedsIceRestart(content_name);
5156}
5157
5158void PeerConnection::OnCertificateReady(
5159 const rtc::scoped_refptr<rtc::RTCCertificate>& certificate) {
5160 transport_controller_->SetLocalCertificate(certificate);
5161}
5162
5163void PeerConnection::OnDtlsSrtpSetupFailure(cricket::BaseChannel*, bool rtcp) {
Steve Antonf8470812017-12-04 18:46:215164 SetSessionError(SessionError::kTransport,
5165 rtcp ? kDtlsSrtpSetupFailureRtcp : kDtlsSrtpSetupFailureRtp);
Steve Anton75737c02017-11-06 18:37:175166}
5167
5168void PeerConnection::OnTransportControllerConnectionState(
5169 cricket::IceConnectionState state) {
5170 switch (state) {
5171 case cricket::kIceConnectionConnecting:
5172 // If the current state is Connected or Completed, then there were
5173 // writable channels but now there are not, so the next state must
5174 // be Disconnected.
5175 // kIceConnectionConnecting is currently used as the default,
5176 // un-connected state by the TransportController, so its only use is
5177 // detecting disconnections.
5178 if (ice_connection_state_ ==
5179 PeerConnectionInterface::kIceConnectionConnected ||
5180 ice_connection_state_ ==
5181 PeerConnectionInterface::kIceConnectionCompleted) {
5182 SetIceConnectionState(
5183 PeerConnectionInterface::kIceConnectionDisconnected);
5184 }
5185 break;
5186 case cricket::kIceConnectionFailed:
5187 SetIceConnectionState(PeerConnectionInterface::kIceConnectionFailed);
5188 break;
5189 case cricket::kIceConnectionConnected:
Mirko Bonadei675513b2017-11-09 10:09:255190 RTC_LOG(LS_INFO) << "Changing to ICE connected state because "
Jonas Olsson45cc8902018-02-13 09:37:075191 "all transports are writable.";
Steve Anton75737c02017-11-06 18:37:175192 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
5193 break;
5194 case cricket::kIceConnectionCompleted:
Mirko Bonadei675513b2017-11-09 10:09:255195 RTC_LOG(LS_INFO) << "Changing to ICE completed state because "
Jonas Olsson45cc8902018-02-13 09:37:075196 "all transports are complete.";
Steve Anton75737c02017-11-06 18:37:175197 if (ice_connection_state_ !=
5198 PeerConnectionInterface::kIceConnectionConnected) {
5199 // If jumping directly from "checking" to "connected",
5200 // signal "connected" first.
5201 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
5202 }
5203 SetIceConnectionState(PeerConnectionInterface::kIceConnectionCompleted);
5204 if (metrics_observer()) {
5205 ReportTransportStats();
5206 }
5207 break;
5208 default:
5209 RTC_NOTREACHED();
5210 }
5211}
5212
5213void PeerConnection::OnTransportControllerCandidatesGathered(
5214 const std::string& transport_name,
5215 const cricket::Candidates& candidates) {
5216 RTC_DCHECK(signaling_thread()->IsCurrent());
5217 int sdp_mline_index;
5218 if (!GetLocalCandidateMediaIndex(transport_name, &sdp_mline_index)) {
Mirko Bonadei675513b2017-11-09 10:09:255219 RTC_LOG(LS_ERROR)
5220 << "OnTransportControllerCandidatesGathered: content name "
5221 << transport_name << " not found";
Steve Anton75737c02017-11-06 18:37:175222 return;
5223 }
5224
5225 for (cricket::Candidates::const_iterator citer = candidates.begin();
5226 citer != candidates.end(); ++citer) {
5227 // Use transport_name as the candidate media id.
5228 std::unique_ptr<JsepIceCandidate> candidate(
5229 new JsepIceCandidate(transport_name, sdp_mline_index, *citer));
5230 if (local_description()) {
5231 mutable_local_description()->AddCandidate(candidate.get());
5232 }
5233 OnIceCandidate(std::move(candidate));
5234 }
5235}
5236
5237void PeerConnection::OnTransportControllerCandidatesRemoved(
5238 const std::vector<cricket::Candidate>& candidates) {
5239 RTC_DCHECK(signaling_thread()->IsCurrent());
5240 // Sanity check.
5241 for (const cricket::Candidate& candidate : candidates) {
5242 if (candidate.transport_name().empty()) {
Mirko Bonadei675513b2017-11-09 10:09:255243 RTC_LOG(LS_ERROR) << "OnTransportControllerCandidatesRemoved: "
Jonas Olsson45cc8902018-02-13 09:37:075244 "empty content name in candidate "
Mirko Bonadei675513b2017-11-09 10:09:255245 << candidate.ToString();
Steve Anton75737c02017-11-06 18:37:175246 return;
5247 }
5248 }
5249
5250 if (local_description()) {
5251 mutable_local_description()->RemoveCandidates(candidates);
5252 }
5253 OnIceCandidatesRemoved(candidates);
5254}
5255
5256void PeerConnection::OnTransportControllerDtlsHandshakeError(
5257 rtc::SSLHandshakeError error) {
5258 if (metrics_observer()) {
5259 metrics_observer()->IncrementEnumCounter(
5260 webrtc::kEnumCounterDtlsHandshakeError, static_cast<int>(error),
5261 static_cast<int>(rtc::SSLHandshakeError::MAX_VALUE));
5262 }
5263}
5264
Steve Antoned10bd92017-12-05 18:52:595265void PeerConnection::EnableSending() {
5266 for (auto transceiver : transceivers_) {
5267 cricket::BaseChannel* channel = transceiver->internal()->channel();
5268 if (channel && !channel->enabled()) {
5269 channel->Enable(true);
5270 }
Steve Anton75737c02017-11-06 18:37:175271 }
5272
Steve Anton4171afb2017-11-20 18:20:225273 if (rtp_data_channel_ && !rtp_data_channel_->enabled()) {
Steve Anton75737c02017-11-06 18:37:175274 rtp_data_channel_->Enable(true);
Steve Anton4171afb2017-11-20 18:20:225275 }
Steve Anton75737c02017-11-06 18:37:175276}
5277
5278// Returns the media index for a local ice candidate given the content name.
5279bool PeerConnection::GetLocalCandidateMediaIndex(
5280 const std::string& content_name,
5281 int* sdp_mline_index) {
5282 if (!local_description() || !sdp_mline_index) {
5283 return false;
5284 }
5285
5286 bool content_found = false;
5287 const ContentInfos& contents = local_description()->description()->contents();
5288 for (size_t index = 0; index < contents.size(); ++index) {
5289 if (contents[index].name == content_name) {
5290 *sdp_mline_index = static_cast<int>(index);
5291 content_found = true;
5292 break;
5293 }
5294 }
5295 return content_found;
5296}
5297
5298bool PeerConnection::UseCandidatesInSessionDescription(
5299 const SessionDescriptionInterface* remote_desc) {
5300 if (!remote_desc) {
5301 return true;
5302 }
5303 bool ret = true;
5304
5305 for (size_t m = 0; m < remote_desc->number_of_mediasections(); ++m) {
5306 const IceCandidateCollection* candidates = remote_desc->candidates(m);
5307 for (size_t n = 0; n < candidates->count(); ++n) {
5308 const IceCandidateInterface* candidate = candidates->at(n);
5309 bool valid = false;
5310 if (!ReadyToUseRemoteCandidate(candidate, remote_desc, &valid)) {
5311 if (valid) {
Mirko Bonadei675513b2017-11-09 10:09:255312 RTC_LOG(LS_INFO)
5313 << "UseCandidatesInSessionDescription: Not ready to use "
Jonas Olsson45cc8902018-02-13 09:37:075314 "candidate.";
Steve Anton75737c02017-11-06 18:37:175315 }
5316 continue;
5317 }
5318 ret = UseCandidate(candidate);
5319 if (!ret) {
5320 break;
5321 }
5322 }
5323 }
5324 return ret;
5325}
5326
5327bool PeerConnection::UseCandidate(const IceCandidateInterface* candidate) {
5328 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
5329 size_t remote_content_size =
5330 remote_description()->description()->contents().size();
5331 if (mediacontent_index >= remote_content_size) {
Mirko Bonadei675513b2017-11-09 10:09:255332 RTC_LOG(LS_ERROR) << "UseCandidate: Invalid candidate media index.";
Steve Anton75737c02017-11-06 18:37:175333 return false;
5334 }
5335
5336 cricket::ContentInfo content =
5337 remote_description()->description()->contents()[mediacontent_index];
5338 std::vector<cricket::Candidate> candidates;
5339 candidates.push_back(candidate->candidate());
5340 // Invoking BaseSession method to handle remote candidates.
Zhi Huange830e682018-03-30 17:48:355341 RTCError error =
5342 transport_controller_->AddRemoteCandidates(content.name, candidates);
5343 if (error.ok()) {
Steve Anton75737c02017-11-06 18:37:175344 // Candidates successfully submitted for checking.
5345 if (ice_connection_state_ == PeerConnectionInterface::kIceConnectionNew ||
5346 ice_connection_state_ ==
5347 PeerConnectionInterface::kIceConnectionDisconnected) {
5348 // If state is New, then the session has just gotten its first remote ICE
5349 // candidates, so go to Checking.
5350 // If state is Disconnected, the session is re-using old candidates or
5351 // receiving additional ones, so go to Checking.
5352 // If state is Connected, stay Connected.
5353 // TODO(bemasc): If state is Connected, and the new candidates are for a
5354 // newly added transport, then the state actually _should_ move to
5355 // checking. Add a way to distinguish that case.
5356 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
5357 }
5358 // TODO(bemasc): If state is Completed, go back to Connected.
Zhi Huange830e682018-03-30 17:48:355359 } else if (error.message()) {
5360 RTC_LOG(LS_WARNING) << error.message();
Steve Anton75737c02017-11-06 18:37:175361 }
5362 return true;
5363}
5364
5365void PeerConnection::RemoveUnusedChannels(const SessionDescription* desc) {
Steve Anton75737c02017-11-06 18:37:175366 // Destroy video channel first since it may have a pointer to the
5367 // voice channel.
5368 const cricket::ContentInfo* video_info = cricket::GetFirstVideoContent(desc);
Steve Anton6fec8802017-12-04 18:37:295369 if (!video_info || video_info->rejected) {
5370 DestroyTransceiverChannel(GetVideoTransceiver());
Steve Anton75737c02017-11-06 18:37:175371 }
5372
Steve Anton6fec8802017-12-04 18:37:295373 const cricket::ContentInfo* audio_info = cricket::GetFirstAudioContent(desc);
5374 if (!audio_info || audio_info->rejected) {
5375 DestroyTransceiverChannel(GetAudioTransceiver());
Steve Anton75737c02017-11-06 18:37:175376 }
5377
5378 const cricket::ContentInfo* data_info = cricket::GetFirstDataContent(desc);
5379 if (!data_info || data_info->rejected) {
Steve Anton6fec8802017-12-04 18:37:295380 DestroyDataChannel();
Steve Anton75737c02017-11-06 18:37:175381 }
5382}
5383
Steve Antondcc3c022017-12-23 00:02:545384RTCErrorOr<const cricket::ContentGroup*> PeerConnection::GetEarlyBundleGroup(
5385 const SessionDescription& desc) const {
Steve Anton75737c02017-11-06 18:37:175386 const cricket::ContentGroup* bundle_group = nullptr;
5387 if (configuration_.bundle_policy ==
5388 PeerConnectionInterface::kBundlePolicyMaxBundle) {
Steve Antondcc3c022017-12-23 00:02:545389 bundle_group = desc.GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton75737c02017-11-06 18:37:175390 if (!bundle_group) {
Steve Anton8a006912017-12-04 23:25:565391 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5392 "max-bundle configured but session description "
5393 "has no BUNDLE group");
Steve Anton75737c02017-11-06 18:37:175394 }
5395 }
Steve Antondcc3c022017-12-23 00:02:545396 return std::move(bundle_group);
5397}
5398
5399RTCError PeerConnection::CreateChannels(const SessionDescription& desc) {
Zhi Huange830e682018-03-30 17:48:355400 // Creating the media channels. Transports should already have been created
5401 // at this point.
Steve Antondcc3c022017-12-23 00:02:545402 const cricket::ContentInfo* voice = cricket::GetFirstAudioContent(&desc);
Steve Antoneda6ccd2017-12-04 18:21:555403 if (voice && !voice->rejected &&
5404 !GetAudioTransceiver()->internal()->channel()) {
Zhi Huange830e682018-03-30 17:48:355405 cricket::VoiceChannel* voice_channel = CreateVoiceChannel(voice->name);
Steve Antoneda6ccd2017-12-04 18:21:555406 if (!voice_channel) {
Steve Anton8a006912017-12-04 23:25:565407 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5408 "Failed to create voice channel.");
Steve Antoneda6ccd2017-12-04 18:21:555409 }
5410 GetAudioTransceiver()->internal()->SetChannel(voice_channel);
5411 }
5412
Steve Antondcc3c022017-12-23 00:02:545413 const cricket::ContentInfo* video = cricket::GetFirstVideoContent(&desc);
Steve Antoneda6ccd2017-12-04 18:21:555414 if (video && !video->rejected &&
5415 !GetVideoTransceiver()->internal()->channel()) {
Zhi Huange830e682018-03-30 17:48:355416 cricket::VideoChannel* video_channel = CreateVideoChannel(video->name);
Steve Antoneda6ccd2017-12-04 18:21:555417 if (!video_channel) {
Steve Anton8a006912017-12-04 23:25:565418 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5419 "Failed to create video channel.");
Steve Anton75737c02017-11-06 18:37:175420 }
Steve Antoneda6ccd2017-12-04 18:21:555421 GetVideoTransceiver()->internal()->SetChannel(video_channel);
Steve Anton75737c02017-11-06 18:37:175422 }
5423
Steve Antondcc3c022017-12-23 00:02:545424 const cricket::ContentInfo* data = cricket::GetFirstDataContent(&desc);
Steve Anton75737c02017-11-06 18:37:175425 if (data_channel_type_ != cricket::DCT_NONE && data && !data->rejected &&
5426 !rtp_data_channel_ && !sctp_transport_) {
Zhi Huange830e682018-03-30 17:48:355427 if (!CreateDataChannel(data->name)) {
Steve Anton8a006912017-12-04 23:25:565428 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5429 "Failed to create data channel.");
Steve Anton75737c02017-11-06 18:37:175430 }
5431 }
5432
Steve Anton8a006912017-12-04 23:25:565433 return RTCError::OK();
Steve Anton75737c02017-11-06 18:37:175434}
5435
Steve Anton4171afb2017-11-20 18:20:225436// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 18:21:555437cricket::VoiceChannel* PeerConnection::CreateVoiceChannel(
Zhi Huange830e682018-03-30 17:48:355438 const std::string& mid) {
5439 RtpTransportInternal* rtp_transport =
5440 transport_controller_->GetRtpTransport(mid);
5441 RTC_DCHECK(rtp_transport);
Steve Anton75737c02017-11-06 18:37:175442 cricket::VoiceChannel* voice_channel = channel_manager()->CreateVoiceChannel(
Zhi Huange830e682018-03-30 17:48:355443 call_.get(), configuration_.media_config, rtp_transport,
5444 signaling_thread(), mid, SrtpRequired(),
5445 factory_->options().crypto_options, audio_options_);
Steve Anton75737c02017-11-06 18:37:175446 if (!voice_channel) {
Steve Antoneda6ccd2017-12-04 18:21:555447 return nullptr;
Steve Anton75737c02017-11-06 18:37:175448 }
Steve Anton75737c02017-11-06 18:37:175449 voice_channel->SignalDtlsSrtpSetupFailure.connect(
5450 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 18:37:175451 voice_channel->SignalSentPacket.connect(this,
5452 &PeerConnection::OnSentPacket_w);
Zhi Huange830e682018-03-30 17:48:355453 voice_channel->SetRtpTransport(rtp_transport);
5454 if (factory_->options().disable_encryption) {
5455 voice_channel->DisableEncryption(true);
5456 }
Steve Antondb67ba12018-03-20 00:41:425457 if (uma_observer_) {
5458 voice_channel->SetMetricsObserver(uma_observer_);
5459 }
Steve Anton4171afb2017-11-20 18:20:225460
Steve Antoneda6ccd2017-12-04 18:21:555461 return voice_channel;
Steve Anton75737c02017-11-06 18:37:175462}
5463
Steve Anton4171afb2017-11-20 18:20:225464// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 18:21:555465cricket::VideoChannel* PeerConnection::CreateVideoChannel(
Zhi Huange830e682018-03-30 17:48:355466 const std::string& mid) {
5467 RtpTransportInternal* rtp_transport =
5468 transport_controller_->GetRtpTransport(mid);
5469 RTC_DCHECK(rtp_transport);
Steve Anton75737c02017-11-06 18:37:175470 cricket::VideoChannel* video_channel = channel_manager()->CreateVideoChannel(
Zhi Huange830e682018-03-30 17:48:355471 call_.get(), configuration_.media_config, rtp_transport,
5472 signaling_thread(), mid, SrtpRequired(),
5473 factory_->options().crypto_options, video_options_);
Steve Anton75737c02017-11-06 18:37:175474 if (!video_channel) {
Steve Antoneda6ccd2017-12-04 18:21:555475 return nullptr;
Steve Anton75737c02017-11-06 18:37:175476 }
Steve Anton75737c02017-11-06 18:37:175477 video_channel->SignalDtlsSrtpSetupFailure.connect(
5478 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 18:37:175479 video_channel->SignalSentPacket.connect(this,
5480 &PeerConnection::OnSentPacket_w);
Zhi Huange830e682018-03-30 17:48:355481 video_channel->SetRtpTransport(rtp_transport);
5482 if (factory_->options().disable_encryption) {
5483 video_channel->DisableEncryption(true);
5484 }
Steve Antondb67ba12018-03-20 00:41:425485 if (uma_observer_) {
5486 video_channel->SetMetricsObserver(uma_observer_);
5487 }
Steve Anton4171afb2017-11-20 18:20:225488
Steve Antoneda6ccd2017-12-04 18:21:555489 return video_channel;
Steve Anton75737c02017-11-06 18:37:175490}
5491
Zhi Huange830e682018-03-30 17:48:355492bool PeerConnection::CreateDataChannel(const std::string& mid) {
Steve Anton75737c02017-11-06 18:37:175493 bool sctp = (data_channel_type_ == cricket::DCT_SCTP);
5494 if (sctp) {
5495 if (!sctp_factory_) {
Mirko Bonadei675513b2017-11-09 10:09:255496 RTC_LOG(LS_ERROR)
Steve Anton75737c02017-11-06 18:37:175497 << "Trying to create SCTP transport, but didn't compile with "
5498 "SCTP support (HAVE_SCTP)";
5499 return false;
5500 }
5501 if (!network_thread()->Invoke<bool>(
Zhi Huange830e682018-03-30 17:48:355502 RTC_FROM_HERE,
5503 rtc::Bind(&PeerConnection::CreateSctpTransport_n, this, mid))) {
Steve Anton75737c02017-11-06 18:37:175504 return false;
5505 }
Steve Antoneda6ccd2017-12-04 18:21:555506 for (const auto& channel : sctp_data_channels_) {
5507 channel->OnTransportChannelCreated();
5508 }
Steve Anton75737c02017-11-06 18:37:175509 } else {
Zhi Huange830e682018-03-30 17:48:355510 RtpTransportInternal* rtp_transport =
5511 transport_controller_->GetRtpTransport(mid);
5512 RTC_DCHECK(rtp_transport);
Steve Anton75737c02017-11-06 18:37:175513 rtp_data_channel_ = channel_manager()->CreateRtpDataChannel(
Zhi Huange830e682018-03-30 17:48:355514 configuration_.media_config, rtp_transport, signaling_thread(), mid,
5515 SrtpRequired(), factory_->options().crypto_options);
Steve Anton75737c02017-11-06 18:37:175516 if (!rtp_data_channel_) {
Steve Anton75737c02017-11-06 18:37:175517 return false;
5518 }
Steve Anton75737c02017-11-06 18:37:175519 rtp_data_channel_->SignalDtlsSrtpSetupFailure.connect(
5520 this, &PeerConnection::OnDtlsSrtpSetupFailure);
5521 rtp_data_channel_->SignalSentPacket.connect(
5522 this, &PeerConnection::OnSentPacket_w);
Zhi Huange830e682018-03-30 17:48:355523 rtp_data_channel_->SetRtpTransport(rtp_transport);
5524 if (factory_->options().disable_encryption) {
5525 rtp_data_channel_->DisableEncryption(true);
5526 }
Steve Antondb67ba12018-03-20 00:41:425527 if (uma_observer_) {
5528 rtp_data_channel_->SetMetricsObserver(uma_observer_);
5529 }
Steve Anton75737c02017-11-06 18:37:175530 }
5531
Steve Anton75737c02017-11-06 18:37:175532 return true;
5533}
5534
5535Call::Stats PeerConnection::GetCallStats() {
5536 if (!worker_thread()->IsCurrent()) {
5537 return worker_thread()->Invoke<Call::Stats>(
5538 RTC_FROM_HERE, rtc::Bind(&PeerConnection::GetCallStats, this));
5539 }
5540 if (call_) {
5541 return call_->GetStats();
5542 } else {
5543 return Call::Stats();
5544 }
5545}
5546
Zhi Huange830e682018-03-30 17:48:355547bool PeerConnection::CreateSctpTransport_n(const std::string& mid) {
Steve Anton75737c02017-11-06 18:37:175548 RTC_DCHECK(network_thread()->IsCurrent());
5549 RTC_DCHECK(sctp_factory_);
Zhi Huang644fde42018-04-03 02:16:265550 cricket::DtlsTransportInternal* dtls_transport =
Zhi Huange830e682018-03-30 17:48:355551 transport_controller_->GetDtlsTransport(mid);
Zhi Huang644fde42018-04-03 02:16:265552 RTC_DCHECK(dtls_transport);
5553 sctp_transport_ = sctp_factory_->CreateSctpTransport(dtls_transport);
Steve Anton75737c02017-11-06 18:37:175554 RTC_DCHECK(sctp_transport_);
5555 sctp_invoker_.reset(new rtc::AsyncInvoker());
5556 sctp_transport_->SignalReadyToSendData.connect(
5557 this, &PeerConnection::OnSctpTransportReadyToSendData_n);
5558 sctp_transport_->SignalDataReceived.connect(
5559 this, &PeerConnection::OnSctpTransportDataReceived_n);
5560 sctp_transport_->SignalStreamClosedRemotely.connect(
5561 this, &PeerConnection::OnSctpStreamClosedRemotely_n);
Zhi Huange830e682018-03-30 17:48:355562 sctp_mid_ = mid;
Zhi Huang644fde42018-04-03 02:16:265563 sctp_transport_->SetDtlsTransport(dtls_transport);
Zhi Huange830e682018-03-30 17:48:355564 return true;
Steve Anton75737c02017-11-06 18:37:175565}
5566
5567void PeerConnection::DestroySctpTransport_n() {
5568 RTC_DCHECK(network_thread()->IsCurrent());
5569 sctp_transport_.reset(nullptr);
Zhi Huange830e682018-03-30 17:48:355570 sctp_mid_.reset();
Steve Anton75737c02017-11-06 18:37:175571 sctp_invoker_.reset(nullptr);
5572 sctp_ready_to_send_data_ = false;
5573}
5574
5575void PeerConnection::OnSctpTransportReadyToSendData_n() {
5576 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5577 RTC_DCHECK(network_thread()->IsCurrent());
5578 // Note: Cannot use rtc::Bind here because it will grab a reference to
5579 // PeerConnection and potentially cause PeerConnection to live longer than
5580 // expected. It is safe not to grab a reference since the sctp_invoker_ will
5581 // be destroyed before PeerConnection is destroyed, and at that point all
5582 // pending tasks will be cleared.
5583 sctp_invoker_->AsyncInvoke<void>(RTC_FROM_HERE, signaling_thread(), [this] {
5584 OnSctpTransportReadyToSendData_s(true);
5585 });
5586}
5587
5588void PeerConnection::OnSctpTransportReadyToSendData_s(bool ready) {
5589 RTC_DCHECK(signaling_thread()->IsCurrent());
5590 sctp_ready_to_send_data_ = ready;
5591 SignalSctpReadyToSendData(ready);
5592}
5593
5594void PeerConnection::OnSctpTransportDataReceived_n(
5595 const cricket::ReceiveDataParams& params,
5596 const rtc::CopyOnWriteBuffer& payload) {
5597 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5598 RTC_DCHECK(network_thread()->IsCurrent());
5599 // Note: Cannot use rtc::Bind here because it will grab a reference to
5600 // PeerConnection and potentially cause PeerConnection to live longer than
5601 // expected. It is safe not to grab a reference since the sctp_invoker_ will
5602 // be destroyed before PeerConnection is destroyed, and at that point all
5603 // pending tasks will be cleared.
5604 sctp_invoker_->AsyncInvoke<void>(
5605 RTC_FROM_HERE, signaling_thread(), [this, params, payload] {
5606 OnSctpTransportDataReceived_s(params, payload);
5607 });
5608}
5609
5610void PeerConnection::OnSctpTransportDataReceived_s(
5611 const cricket::ReceiveDataParams& params,
5612 const rtc::CopyOnWriteBuffer& payload) {
5613 RTC_DCHECK(signaling_thread()->IsCurrent());
5614 if (params.type == cricket::DMT_CONTROL && IsOpenMessage(payload)) {
5615 // Received OPEN message; parse and signal that a new data channel should
5616 // be created.
5617 std::string label;
5618 InternalDataChannelInit config;
5619 config.id = params.ssrc;
5620 if (!ParseDataChannelOpenMessage(payload, &label, &config)) {
Mirko Bonadei675513b2017-11-09 10:09:255621 RTC_LOG(LS_WARNING) << "Failed to parse the OPEN message for sid "
5622 << params.ssrc;
Steve Anton75737c02017-11-06 18:37:175623 return;
5624 }
5625 config.open_handshake_role = InternalDataChannelInit::kAcker;
5626 OnDataChannelOpenMessage(label, config);
5627 } else {
5628 // Otherwise just forward the signal.
5629 SignalSctpDataReceived(params, payload);
5630 }
5631}
5632
5633void PeerConnection::OnSctpStreamClosedRemotely_n(int sid) {
5634 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5635 RTC_DCHECK(network_thread()->IsCurrent());
5636 sctp_invoker_->AsyncInvoke<void>(
5637 RTC_FROM_HERE, signaling_thread(),
5638 rtc::Bind(&sigslot::signal1<int>::operator(),
5639 &SignalSctpStreamClosedRemotely, sid));
5640}
5641
5642// Returns false if bundle is enabled and rtcp_mux is disabled.
5643bool PeerConnection::ValidateBundleSettings(const SessionDescription* desc) {
5644 bool bundle_enabled = desc->HasGroup(cricket::GROUP_TYPE_BUNDLE);
5645 if (!bundle_enabled)
5646 return true;
5647
5648 const cricket::ContentGroup* bundle_group =
5649 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
5650 RTC_DCHECK(bundle_group != NULL);
5651
5652 const cricket::ContentInfos& contents = desc->contents();
5653 for (cricket::ContentInfos::const_iterator citer = contents.begin();
5654 citer != contents.end(); ++citer) {
5655 const cricket::ContentInfo* content = (&*citer);
5656 RTC_DCHECK(content != NULL);
5657 if (bundle_group->HasContentName(content->name) && !content->rejected &&
Steve Anton5adfafd2017-12-21 00:34:005658 content->type == MediaProtocolType::kRtp) {
Steve Anton75737c02017-11-06 18:37:175659 if (!HasRtcpMuxEnabled(content))
5660 return false;
5661 }
5662 }
5663 // RTCP-MUX is enabled in all the contents.
5664 return true;
5665}
5666
5667bool PeerConnection::HasRtcpMuxEnabled(const cricket::ContentInfo* content) {
Steve Antonb1c1de12017-12-21 23:14:305668 return content->media_description()->rtcp_mux();
Steve Anton75737c02017-11-06 18:37:175669}
5670
Steve Anton8a006912017-12-04 23:25:565671RTCError PeerConnection::ValidateSessionDescription(
Steve Anton75737c02017-11-06 18:37:175672 const SessionDescriptionInterface* sdesc,
Steve Anton8a006912017-12-04 23:25:565673 cricket::ContentSource source) {
Steve Antonf8470812017-12-04 18:46:215674 if (session_error() != SessionError::kNone) {
Steve Anton8a006912017-12-04 23:25:565675 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
Steve Anton75737c02017-11-06 18:37:175676 }
5677
5678 if (!sdesc || !sdesc->description()) {
Steve Anton8a006912017-12-04 23:25:565679 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidSdp);
Steve Anton75737c02017-11-06 18:37:175680 }
5681
Steve Anton3828c062017-12-06 18:34:515682 SdpType type = sdesc->GetType();
5683 if ((source == cricket::CS_LOCAL && !ExpectSetLocalDescription(type)) ||
5684 (source == cricket::CS_REMOTE && !ExpectSetRemoteDescription(type))) {
Steve Anton8a006912017-12-04 23:25:565685 LOG_AND_RETURN_ERROR(
Harald Alvestrand5081c0c2018-03-09 14:18:035686 RTCErrorType::INVALID_STATE,
Steve Anton8a006912017-12-04 23:25:565687 "Called in wrong state: " + GetSignalingStateString(signaling_state()));
Steve Anton75737c02017-11-06 18:37:175688 }
5689
5690 // Verify crypto settings.
5691 std::string crypto_error;
Steve Anton8a006912017-12-04 23:25:565692 if (webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED ||
5693 dtls_enabled_) {
Harald Alvestrand194939b2018-01-24 15:04:135694 RTCError crypto_error =
5695 VerifyCrypto(sdesc->description(), dtls_enabled_, uma_observer_);
Steve Anton8a006912017-12-04 23:25:565696 if (!crypto_error.ok()) {
5697 return crypto_error;
5698 }
Steve Anton75737c02017-11-06 18:37:175699 }
5700
5701 // Verify ice-ufrag and ice-pwd.
5702 if (!VerifyIceUfragPwdPresent(sdesc->description())) {
Steve Anton8a006912017-12-04 23:25:565703 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5704 kSdpWithoutIceUfragPwd);
Steve Anton75737c02017-11-06 18:37:175705 }
5706
5707 if (!ValidateBundleSettings(sdesc->description())) {
Steve Anton8a006912017-12-04 23:25:565708 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5709 kBundleWithoutRtcpMux);
Steve Anton75737c02017-11-06 18:37:175710 }
5711
5712 // TODO(skvlad): When the local rtcp-mux policy is Require, reject any
5713 // m-lines that do not rtcp-mux enabled.
5714
5715 // Verify m-lines in Answer when compared against Offer.
Steve Anton3828c062017-12-06 18:34:515716 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Seth Hampsonae8a90a2018-02-13 23:33:485717 // With an answer we want to compare the new answer session description with
5718 // the offer's session description from the current negotiation.
Steve Anton75737c02017-11-06 18:37:175719 const cricket::SessionDescription* offer_desc =
5720 (source == cricket::CS_LOCAL) ? remote_description()->description()
5721 : local_description()->description();
Seth Hampsonae8a90a2018-02-13 23:33:485722 if (!MediaSectionsHaveSameCount(*offer_desc, *sdesc->description()) ||
5723 !MediaSectionsInSameOrder(*offer_desc, nullptr, *sdesc->description(),
5724 type)) {
Steve Anton8a006912017-12-04 23:25:565725 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5726 kMlineMismatchInAnswer);
Steve Anton75737c02017-11-06 18:37:175727 }
5728 } else {
Steve Anton75737c02017-11-06 18:37:175729 // The re-offers should respect the order of m= sections in current
5730 // description. See RFC3264 Section 8 paragraph 4 for more details.
Seth Hampsonae8a90a2018-02-13 23:33:485731 // With a re-offer, either the current local or current remote descriptions
5732 // could be the most up to date, so we would like to check against both of
5733 // them if they exist. It could be the case that one of them has a 0 port
5734 // for a media section, but the other does not. This is important to check
5735 // against in the case that we are recycling an m= section.
5736 const cricket::SessionDescription* current_desc = nullptr;
5737 const cricket::SessionDescription* secondary_current_desc = nullptr;
5738 if (local_description()) {
5739 current_desc = local_description()->description();
5740 if (remote_description()) {
5741 secondary_current_desc = remote_description()->description();
5742 }
5743 } else if (remote_description()) {
5744 current_desc = remote_description()->description();
5745 }
Steve Anton75737c02017-11-06 18:37:175746 if (current_desc &&
Seth Hampsonae8a90a2018-02-13 23:33:485747 !MediaSectionsInSameOrder(*current_desc, secondary_current_desc,
5748 *sdesc->description(), type)) {
Steve Anton8a006912017-12-04 23:25:565749 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5750 kMlineMismatchInSubsequentOffer);
Steve Anton75737c02017-11-06 18:37:175751 }
5752 }
5753
Steve Antonba42e992018-04-09 21:10:015754 if (IsUnifiedPlan()) {
5755 // Ensure that each audio and video media section has at most one
5756 // "StreamParams". This will return an error if receiving a session
5757 // description from a "Plan B" endpoint which adds multiple tracks of the
5758 // same type. With Unified Plan, there can only be at most one track per
5759 // media section.
5760 for (const ContentInfo& content : sdesc->description()->contents()) {
5761 const MediaContentDescription& desc = *content.description;
5762 if ((desc.type() == cricket::MEDIA_TYPE_AUDIO ||
5763 desc.type() == cricket::MEDIA_TYPE_VIDEO) &&
5764 desc.streams().size() > 1u) {
5765 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5766 "Media section has more than one track specified "
5767 "with a=ssrc lines which is not supported with "
5768 "Unified Plan.");
5769 }
5770 }
5771 }
5772
Steve Anton8a006912017-12-04 23:25:565773 return RTCError::OK();
Steve Anton75737c02017-11-06 18:37:175774}
5775
Steve Anton3828c062017-12-06 18:34:515776bool PeerConnection::ExpectSetLocalDescription(SdpType type) {
Steve Anton75737c02017-11-06 18:37:175777 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 18:34:515778 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 18:37:175779 return (state == PeerConnectionInterface::kStable) ||
5780 (state == PeerConnectionInterface::kHaveLocalOffer);
Steve Anton20393062017-12-05 00:24:525781 } else {
Steve Anton3828c062017-12-06 18:34:515782 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 18:37:175783 return (state == PeerConnectionInterface::kHaveRemoteOffer) ||
5784 (state == PeerConnectionInterface::kHaveLocalPrAnswer);
5785 }
5786}
5787
Steve Anton3828c062017-12-06 18:34:515788bool PeerConnection::ExpectSetRemoteDescription(SdpType type) {
Steve Anton75737c02017-11-06 18:37:175789 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 18:34:515790 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 18:37:175791 return (state == PeerConnectionInterface::kStable) ||
5792 (state == PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton20393062017-12-05 00:24:525793 } else {
Steve Anton3828c062017-12-06 18:34:515794 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 18:37:175795 return (state == PeerConnectionInterface::kHaveLocalOffer) ||
5796 (state == PeerConnectionInterface::kHaveRemotePrAnswer);
5797 }
5798}
5799
Steve Antonf8470812017-12-04 18:46:215800const char* PeerConnection::SessionErrorToString(SessionError error) const {
5801 switch (error) {
5802 case SessionError::kNone:
5803 return "ERROR_NONE";
5804 case SessionError::kContent:
5805 return "ERROR_CONTENT";
5806 case SessionError::kTransport:
5807 return "ERROR_TRANSPORT";
5808 }
5809 RTC_NOTREACHED();
5810 return "";
5811}
5812
Steve Anton75737c02017-11-06 18:37:175813std::string PeerConnection::GetSessionErrorMsg() {
5814 std::ostringstream desc;
Steve Antonf8470812017-12-04 18:46:215815 desc << kSessionError << SessionErrorToString(session_error()) << ". ";
5816 desc << kSessionErrorDesc << session_error_desc() << ".";
Steve Anton75737c02017-11-06 18:37:175817 return desc.str();
5818}
5819
Steve Anton8e20f172018-03-06 18:55:045820void PeerConnection::ReportSdpFormatReceived(
5821 const SessionDescriptionInterface& remote_offer) {
5822 if (!uma_observer_) {
5823 return;
5824 }
5825 int num_audio_mlines = 0;
5826 int num_video_mlines = 0;
5827 int num_audio_tracks = 0;
5828 int num_video_tracks = 0;
5829 for (const ContentInfo& content : remote_offer.description()->contents()) {
5830 cricket::MediaType media_type = content.media_description()->type();
5831 int num_tracks = std::max(
5832 1, static_cast<int>(content.media_description()->streams().size()));
5833 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
5834 num_audio_mlines += 1;
5835 num_audio_tracks += num_tracks;
5836 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
5837 num_video_mlines += 1;
5838 num_video_tracks += num_tracks;
5839 }
5840 }
5841 SdpFormatReceived format = kSdpFormatReceivedNoTracks;
5842 if (num_audio_mlines > 1 || num_video_mlines > 1) {
5843 format = kSdpFormatReceivedComplexUnifiedPlan;
5844 } else if (num_audio_tracks > 1 || num_video_tracks > 1) {
5845 format = kSdpFormatReceivedComplexPlanB;
5846 } else if (num_audio_tracks > 0 || num_video_tracks > 0) {
5847 format = kSdpFormatReceivedSimple;
5848 }
5849 uma_observer_->IncrementEnumCounter(kEnumCounterSdpFormatReceived, format,
5850 kSdpFormatReceivedMax);
5851}
5852
Steve Anton0ffaaa22018-02-23 18:31:305853void PeerConnection::ReportNegotiatedSdpSemantics(
5854 const SessionDescriptionInterface& answer) {
5855 if (!uma_observer_) {
5856 return;
5857 }
5858 switch (answer.description()->msid_signaling()) {
5859 case 0:
5860 uma_observer_->IncrementEnumCounter(kEnumCounterSdpSemanticNegotiated,
5861 kSdpSemanticNegotiatedNone,
5862 kSdpSemanticNegotiatedMax);
5863 break;
5864 case cricket::kMsidSignalingMediaSection:
5865 uma_observer_->IncrementEnumCounter(kEnumCounterSdpSemanticNegotiated,
5866 kSdpSemanticNegotiatedUnifiedPlan,
5867 kSdpSemanticNegotiatedMax);
5868 break;
5869 case cricket::kMsidSignalingSsrcAttribute:
5870 uma_observer_->IncrementEnumCounter(kEnumCounterSdpSemanticNegotiated,
5871 kSdpSemanticNegotiatedPlanB,
5872 kSdpSemanticNegotiatedMax);
5873 break;
5874 case cricket::kMsidSignalingMediaSection |
5875 cricket::kMsidSignalingSsrcAttribute:
5876 uma_observer_->IncrementEnumCounter(kEnumCounterSdpSemanticNegotiated,
5877 kSdpSemanticNegotiatedMixed,
5878 kSdpSemanticNegotiatedMax);
5879 break;
5880 default:
5881 RTC_NOTREACHED();
5882 }
5883}
5884
Steve Anton75737c02017-11-06 18:37:175885// We need to check the local/remote description for the Transport instead of
5886// the session, because a new Transport added during renegotiation may have
5887// them unset while the session has them set from the previous negotiation.
5888// Not doing so may trigger the auto generation of transport description and
5889// mess up DTLS identity information, ICE credential, etc.
5890bool PeerConnection::ReadyToUseRemoteCandidate(
5891 const IceCandidateInterface* candidate,
5892 const SessionDescriptionInterface* remote_desc,
5893 bool* valid) {
5894 *valid = true;
5895
5896 const SessionDescriptionInterface* current_remote_desc =
5897 remote_desc ? remote_desc : remote_description();
5898
5899 if (!current_remote_desc) {
5900 return false;
5901 }
5902
5903 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
5904 size_t remote_content_size =
5905 current_remote_desc->description()->contents().size();
5906 if (mediacontent_index >= remote_content_size) {
Mirko Bonadei675513b2017-11-09 10:09:255907 RTC_LOG(LS_ERROR)
5908 << "ReadyToUseRemoteCandidate: Invalid candidate media index "
5909 << mediacontent_index;
Steve Anton75737c02017-11-06 18:37:175910
5911 *valid = false;
5912 return false;
5913 }
5914
5915 cricket::ContentInfo content =
5916 current_remote_desc->description()->contents()[mediacontent_index];
5917
5918 const std::string transport_name = GetTransportName(content.name);
5919 if (transport_name.empty()) {
5920 return false;
5921 }
Zhi Huange830e682018-03-30 17:48:355922 return true;
Steve Anton75737c02017-11-06 18:37:175923}
5924
5925bool PeerConnection::SrtpRequired() const {
5926 return dtls_enabled_ ||
5927 webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED;
5928}
5929
5930void PeerConnection::OnTransportControllerGatheringState(
5931 cricket::IceGatheringState state) {
5932 RTC_DCHECK(signaling_thread()->IsCurrent());
5933 if (state == cricket::kIceGatheringGathering) {
5934 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringGathering);
5935 } else if (state == cricket::kIceGatheringComplete) {
5936 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringComplete);
5937 }
5938}
5939
5940void PeerConnection::ReportTransportStats() {
Steve Antonc7b964c2018-02-01 22:39:455941 std::map<std::string, std::set<cricket::MediaType>>
5942 media_types_by_transport_name;
5943 for (auto transceiver : transceivers_) {
5944 if (transceiver->internal()->channel()) {
5945 const std::string& transport_name =
5946 transceiver->internal()->channel()->transport_name();
5947 media_types_by_transport_name[transport_name].insert(
Steve Anton69470252018-02-09 19:43:085948 transceiver->media_type());
Steve Antonc7b964c2018-02-01 22:39:455949 }
Steve Anton75737c02017-11-06 18:37:175950 }
5951 if (rtp_data_channel()) {
Steve Antonc7b964c2018-02-01 22:39:455952 media_types_by_transport_name[rtp_data_channel()->transport_name()].insert(
5953 cricket::MEDIA_TYPE_DATA);
Steve Anton75737c02017-11-06 18:37:175954 }
Zhi Huange830e682018-03-30 17:48:355955
5956 rtc::Optional<std::string> transport_name = sctp_transport_name();
5957 if (transport_name) {
5958 media_types_by_transport_name[*transport_name].insert(
Steve Antonc7b964c2018-02-01 22:39:455959 cricket::MEDIA_TYPE_DATA);
Steve Anton75737c02017-11-06 18:37:175960 }
Zhi Huange830e682018-03-30 17:48:355961
Steve Antonc7b964c2018-02-01 22:39:455962 for (const auto& entry : media_types_by_transport_name) {
5963 const std::string& transport_name = entry.first;
5964 const std::set<cricket::MediaType> media_types = entry.second;
Steve Anton75737c02017-11-06 18:37:175965 cricket::TransportStats stats;
Steve Antonc7b964c2018-02-01 22:39:455966 if (transport_controller_->GetStats(transport_name, &stats)) {
Steve Anton75737c02017-11-06 18:37:175967 ReportBestConnectionState(stats);
Steve Antonc7b964c2018-02-01 22:39:455968 ReportNegotiatedCiphers(stats, media_types);
Steve Anton75737c02017-11-06 18:37:175969 }
5970 }
5971}
5972// Walk through the ConnectionInfos to gather best connection usage
5973// for IPv4 and IPv6.
5974void PeerConnection::ReportBestConnectionState(
5975 const cricket::TransportStats& stats) {
5976 RTC_DCHECK(metrics_observer());
Steve Antonc7b964c2018-02-01 22:39:455977 for (const cricket::TransportChannelStats& channel_stats :
5978 stats.channel_stats) {
5979 for (const cricket::ConnectionInfo& connection_info :
5980 channel_stats.connection_infos) {
5981 if (!connection_info.best_connection) {
Steve Anton75737c02017-11-06 18:37:175982 continue;
5983 }
5984
5985 PeerConnectionEnumCounterType type = kPeerConnectionEnumCounterMax;
Steve Antonc7b964c2018-02-01 22:39:455986 const cricket::Candidate& local = connection_info.local_candidate;
5987 const cricket::Candidate& remote = connection_info.remote_candidate;
Steve Anton75737c02017-11-06 18:37:175988
5989 // Increment the counter for IceCandidatePairType.
5990 if (local.protocol() == cricket::TCP_PROTOCOL_NAME ||
5991 (local.type() == RELAY_PORT_TYPE &&
5992 local.relay_protocol() == cricket::TCP_PROTOCOL_NAME)) {
5993 type = kEnumCounterIceCandidatePairTypeTcp;
5994 } else if (local.protocol() == cricket::UDP_PROTOCOL_NAME) {
5995 type = kEnumCounterIceCandidatePairTypeUdp;
5996 } else {
5997 RTC_CHECK(0);
5998 }
5999 metrics_observer()->IncrementEnumCounter(
6000 type, GetIceCandidatePairCounter(local, remote),
6001 kIceCandidatePairMax);
6002
6003 // Increment the counter for IP type.
6004 if (local.address().family() == AF_INET) {
6005 metrics_observer()->IncrementEnumCounter(
6006 kEnumCounterAddressFamily, kBestConnections_IPv4,
6007 kPeerConnectionAddressFamilyCounter_Max);
6008
6009 } else if (local.address().family() == AF_INET6) {
6010 metrics_observer()->IncrementEnumCounter(
6011 kEnumCounterAddressFamily, kBestConnections_IPv6,
6012 kPeerConnectionAddressFamilyCounter_Max);
6013 } else {
6014 RTC_CHECK(0);
6015 }
6016
6017 return;
6018 }
6019 }
6020}
6021
6022void PeerConnection::ReportNegotiatedCiphers(
Steve Antonc7b964c2018-02-01 22:39:456023 const cricket::TransportStats& stats,
6024 const std::set<cricket::MediaType>& media_types) {
Steve Anton75737c02017-11-06 18:37:176025 RTC_DCHECK(metrics_observer());
6026 if (!dtls_enabled_ || stats.channel_stats.empty()) {
6027 return;
6028 }
6029
6030 int srtp_crypto_suite = stats.channel_stats[0].srtp_crypto_suite;
6031 int ssl_cipher_suite = stats.channel_stats[0].ssl_cipher_suite;
6032 if (srtp_crypto_suite == rtc::SRTP_INVALID_CRYPTO_SUITE &&
6033 ssl_cipher_suite == rtc::TLS_NULL_WITH_NULL_NULL) {
6034 return;
6035 }
6036
Steve Antonc7b964c2018-02-01 22:39:456037 for (cricket::MediaType media_type : media_types) {
6038 PeerConnectionEnumCounterType srtp_counter_type;
6039 PeerConnectionEnumCounterType ssl_counter_type;
6040 switch (media_type) {
6041 case cricket::MEDIA_TYPE_AUDIO:
6042 srtp_counter_type = kEnumCounterAudioSrtpCipher;
6043 ssl_counter_type = kEnumCounterAudioSslCipher;
6044 break;
6045 case cricket::MEDIA_TYPE_VIDEO:
6046 srtp_counter_type = kEnumCounterVideoSrtpCipher;
6047 ssl_counter_type = kEnumCounterVideoSslCipher;
6048 break;
6049 case cricket::MEDIA_TYPE_DATA:
6050 srtp_counter_type = kEnumCounterDataSrtpCipher;
6051 ssl_counter_type = kEnumCounterDataSslCipher;
6052 break;
6053 default:
6054 RTC_NOTREACHED();
6055 continue;
6056 }
6057 if (srtp_crypto_suite != rtc::SRTP_INVALID_CRYPTO_SUITE) {
6058 metrics_observer()->IncrementSparseEnumCounter(srtp_counter_type,
6059 srtp_crypto_suite);
6060 }
6061 if (ssl_cipher_suite != rtc::TLS_NULL_WITH_NULL_NULL) {
6062 metrics_observer()->IncrementSparseEnumCounter(ssl_counter_type,
6063 ssl_cipher_suite);
6064 }
Steve Anton75737c02017-11-06 18:37:176065 }
6066}
6067
6068void PeerConnection::OnSentPacket_w(const rtc::SentPacket& sent_packet) {
6069 RTC_DCHECK(worker_thread()->IsCurrent());
6070 RTC_DCHECK(call_);
6071 call_->OnSentPacket(sent_packet);
6072}
6073
6074const std::string PeerConnection::GetTransportName(
6075 const std::string& content_name) {
6076 cricket::BaseChannel* channel = GetChannel(content_name);
Steve Anton6fec8802017-12-04 18:37:296077 if (channel) {
6078 return channel->transport_name();
Steve Anton75737c02017-11-06 18:37:176079 }
Steve Anton6fec8802017-12-04 18:37:296080 if (sctp_transport_) {
Zhi Huange830e682018-03-30 17:48:356081 RTC_DCHECK(sctp_mid_);
6082 if (content_name == *sctp_mid_) {
6083 return *sctp_transport_name();
Steve Anton6fec8802017-12-04 18:37:296084 }
6085 }
6086 // Return an empty string if failed to retrieve the transport name.
6087 return "";
Steve Anton75737c02017-11-06 18:37:176088}
6089
Steve Anton6fec8802017-12-04 18:37:296090void PeerConnection::DestroyTransceiverChannel(
6091 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
6092 transceiver) {
6093 RTC_DCHECK(transceiver);
Steve Anton75737c02017-11-06 18:37:176094
Steve Anton6fec8802017-12-04 18:37:296095 cricket::BaseChannel* channel = transceiver->internal()->channel();
6096 if (channel) {
6097 transceiver->internal()->SetChannel(nullptr);
6098 DestroyBaseChannel(channel);
Steve Anton75737c02017-11-06 18:37:176099 }
6100}
6101
6102void PeerConnection::DestroyDataChannel() {
Steve Anton6fec8802017-12-04 18:37:296103 if (rtp_data_channel_) {
6104 OnDataChannelDestroyed();
6105 DestroyBaseChannel(rtp_data_channel_);
6106 rtp_data_channel_ = nullptr;
6107 }
6108
6109 // Note: Cannot use rtc::Bind to create a functor to invoke because it will
6110 // grab a reference to this PeerConnection. If this is called from the
6111 // PeerConnection destructor, the RefCountedObject vtable will have already
6112 // been destroyed (since it is a subclass of PeerConnection) and using
6113 // rtc::Bind will cause "Pure virtual function called" error to appear.
6114
6115 if (sctp_transport_) {
6116 OnDataChannelDestroyed();
6117 network_thread()->Invoke<void>(RTC_FROM_HERE,
6118 [this] { DestroySctpTransport_n(); });
6119 }
6120}
6121
6122void PeerConnection::DestroyBaseChannel(cricket::BaseChannel* channel) {
6123 RTC_DCHECK(channel);
Steve Anton6fec8802017-12-04 18:37:296124
6125 switch (channel->media_type()) {
6126 case cricket::MEDIA_TYPE_AUDIO:
6127 channel_manager()->DestroyVoiceChannel(
6128 static_cast<cricket::VoiceChannel*>(channel));
6129 break;
6130 case cricket::MEDIA_TYPE_VIDEO:
6131 channel_manager()->DestroyVideoChannel(
6132 static_cast<cricket::VideoChannel*>(channel));
6133 break;
6134 case cricket::MEDIA_TYPE_DATA:
6135 channel_manager()->DestroyRtpDataChannel(
6136 static_cast<cricket::RtpDataChannel*>(channel));
6137 break;
6138 default:
6139 RTC_NOTREACHED() << "Unknown media type: " << channel->media_type();
6140 break;
6141 }
Zhi Huange830e682018-03-30 17:48:356142}
Steve Anton6fec8802017-12-04 18:37:296143
Zhi Huange830e682018-03-30 17:48:356144void PeerConnection::OnRtpTransportChanged(
6145 const std::string& mid,
6146 RtpTransportInternal* rtp_transport) {
6147 auto base_channel = GetChannel(mid);
6148 if (base_channel) {
6149 base_channel->SetRtpTransport(rtp_transport);
6150 }
6151}
Steve Anton6fec8802017-12-04 18:37:296152
Zhi Huange830e682018-03-30 17:48:356153void PeerConnection::OnDtlsTransportChanged(
6154 const std::string& mid,
6155 cricket::DtlsTransportInternal* dtls_transport) {
6156 if (sctp_transport_) {
6157 RTC_DCHECK(mid == sctp_mid_);
Zhi Huang644fde42018-04-03 02:16:266158 sctp_transport_->SetDtlsTransport(dtls_transport);
Steve Anton75737c02017-11-06 18:37:176159 }
6160}
6161
Harald Alvestrand89061872018-01-02 13:08:346162void PeerConnection::ClearStatsCache() {
6163 if (stats_collector_) {
6164 stats_collector_->ClearCachedStatsReport();
6165 }
6166}
6167
henrike@webrtc.org28e20752013-07-10 00:45:366168} // namespace webrtc