blob: c7dc73b23f67677d29203a9fc18768868861ad69 [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;
Zhi Huang365381f2018-04-13 23:44:34935 config.transport_observer = this;
Zhi Huange830e682018-03-30 17:48:35936#if defined(ENABLE_EXTERNAL_AUTH)
937 config.enable_external_auth = true;
938#endif
939 transport_controller_.reset(new JsepTransportController(
940 signaling_thread(), network_thread(), port_allocator_.get(), config));
941 transport_controller_->SignalIceConnectionState.connect(
Steve Anton75737c02017-11-06 18:37:17942 this, &PeerConnection::OnTransportControllerConnectionState);
Zhi Huange830e682018-03-30 17:48:35943 transport_controller_->SignalIceGatheringState.connect(
Steve Anton75737c02017-11-06 18:37:17944 this, &PeerConnection::OnTransportControllerGatheringState);
Zhi Huange830e682018-03-30 17:48:35945 transport_controller_->SignalIceCandidatesGathered.connect(
Steve Anton75737c02017-11-06 18:37:17946 this, &PeerConnection::OnTransportControllerCandidatesGathered);
Zhi Huange830e682018-03-30 17:48:35947 transport_controller_->SignalIceCandidatesRemoved.connect(
Steve Anton75737c02017-11-06 18:37:17948 this, &PeerConnection::OnTransportControllerCandidatesRemoved);
949 transport_controller_->SignalDtlsHandshakeError.connect(
950 this, &PeerConnection::OnTransportControllerDtlsHandshakeError);
951
952 sctp_factory_ = factory_->CreateSctpTransportInternalFactory();
zhihuang29ff8442016-07-27 18:07:25953
deadbeefab9b2d12015-10-14 18:33:11954 stats_.reset(new StatsCollector(this));
hbos74e1a4f2016-09-16 06:33:01955 stats_collector_ = RTCStatsCollector::Create(this);
henrike@webrtc.org28e20752013-07-10 00:45:36956
Steve Antonba818672017-11-06 18:21:57957 configuration_ = configuration;
958
Steve Anton75737c02017-11-06 18:37:17959 // Obtain a certificate from RTCConfiguration if any were provided (optional).
960 rtc::scoped_refptr<rtc::RTCCertificate> certificate;
961 if (!configuration.certificates.empty()) {
962 // TODO(hbos,torbjorng): Decide on certificate-selection strategy instead of
963 // just picking the first one. The decision should be made based on the DTLS
964 // handshake. The DTLS negotiations need to know about all certificates.
965 certificate = configuration.certificates[0];
966 }
967
Steve Antond25da372017-11-06 22:50:29968 transport_controller_->SetIceConfig(ParseIceConfig(configuration));
Steve Anton75737c02017-11-06 18:37:17969
970 if (options.disable_encryption) {
971 dtls_enabled_ = false;
972 } else {
973 // Enable DTLS by default if we have an identity store or a certificate.
974 dtls_enabled_ = (cert_generator || certificate);
975 // |configuration| can override the default |dtls_enabled_| value.
976 if (configuration.enable_dtls_srtp) {
977 dtls_enabled_ = *(configuration.enable_dtls_srtp);
978 }
979 }
980
981 // Enable creation of RTP data channels if the kEnableRtpDataChannels is set.
982 // It takes precendence over the disable_sctp_data_channels
983 // PeerConnectionFactoryInterface::Options.
984 if (configuration.enable_rtp_data_channel) {
985 data_channel_type_ = cricket::DCT_RTP;
986 } else {
987 // DTLS has to be enabled to use SCTP.
988 if (!options.disable_sctp_data_channels && dtls_enabled_) {
989 data_channel_type_ = cricket::DCT_SCTP;
990 }
991 }
992
993 video_options_.screencast_min_bitrate_kbps =
994 configuration.screencast_min_bitrate;
995 audio_options_.combined_audio_video_bwe =
996 configuration.combined_audio_video_bwe;
997
998 audio_options_.audio_jitter_buffer_max_packets =
Oskar Sundbom9b28a032017-11-16 09:53:30999 configuration.audio_jitter_buffer_max_packets;
Steve Anton75737c02017-11-06 18:37:171000
1001 audio_options_.audio_jitter_buffer_fast_accelerate =
Oskar Sundbom9b28a032017-11-16 09:53:301002 configuration.audio_jitter_buffer_fast_accelerate;
Steve Anton75737c02017-11-06 18:37:171003
1004 // Whether the certificate generator/certificate is null or not determines
1005 // what PeerConnectionDescriptionFactory will do, so make sure that we give it
1006 // the right instructions by clearing the variables if needed.
1007 if (!dtls_enabled_) {
1008 cert_generator.reset();
1009 certificate = nullptr;
1010 } else if (certificate) {
1011 // Favor generated certificate over the certificate generator.
1012 cert_generator.reset();
1013 }
1014
1015 webrtc_session_desc_factory_.reset(new WebRtcSessionDescriptionFactory(
1016 signaling_thread(), channel_manager(), this, session_id(),
1017 std::move(cert_generator), certificate));
1018 webrtc_session_desc_factory_->SignalCertificateReady.connect(
1019 this, &PeerConnection::OnCertificateReady);
1020
1021 if (options.disable_encryption) {
1022 webrtc_session_desc_factory_->SetSdesPolicy(cricket::SEC_DISABLED);
1023 }
1024
1025 webrtc_session_desc_factory_->set_enable_encrypted_rtp_header_extensions(
1026 options.crypto_options.enable_encrypted_rtp_header_extensions);
henrike@webrtc.org28e20752013-07-10 00:45:361027
Steve Anton4171afb2017-11-20 18:20:221028 // Add default audio/video transceivers for Plan B SDP.
1029 if (!IsUnifiedPlan()) {
1030 transceivers_.push_back(
1031 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1032 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_AUDIO)));
1033 transceivers_.push_back(
1034 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1035 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_VIDEO)));
1036 }
1037
henrike@webrtc.org28e20752013-07-10 00:45:361038 return true;
1039}
1040
Steve Anton038834f2017-07-14 22:59:591041RTCError PeerConnection::ValidateConfiguration(
1042 const RTCConfiguration& config) const {
1043 if (config.ice_regather_interval_range &&
1044 config.continual_gathering_policy == GATHER_ONCE) {
1045 return RTCError(RTCErrorType::INVALID_PARAMETER,
1046 "ice_regather_interval_range specified but continual "
1047 "gathering policy is GATHER_ONCE");
1048 }
Qingsi Wangdea68892018-03-27 17:55:211049 auto result =
1050 cricket::P2PTransportChannel::ValidateIceConfig(ParseIceConfig(config));
1051 return result;
Steve Anton038834f2017-07-14 22:59:591052}
1053
buildbot@webrtc.orgd4e598d2014-07-29 17:36:521054rtc::scoped_refptr<StreamCollectionInterface>
henrike@webrtc.org28e20752013-07-10 00:45:361055PeerConnection::local_streams() {
Steve Antonfc853712018-03-01 21:48:581056 RTC_CHECK(!IsUnifiedPlan()) << "local_streams is not available with Unified "
1057 "Plan SdpSemantics. Please use GetSenders "
1058 "instead.";
deadbeefab9b2d12015-10-14 18:33:111059 return local_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:361060}
1061
buildbot@webrtc.orgd4e598d2014-07-29 17:36:521062rtc::scoped_refptr<StreamCollectionInterface>
henrike@webrtc.org28e20752013-07-10 00:45:361063PeerConnection::remote_streams() {
Steve Antonfc853712018-03-01 21:48:581064 RTC_CHECK(!IsUnifiedPlan()) << "remote_streams is not available with Unified "
1065 "Plan SdpSemantics. Please use GetReceivers "
1066 "instead.";
deadbeefab9b2d12015-10-14 18:33:111067 return remote_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:361068}
1069
perkj@webrtc.orgc2dd5ee2014-11-04 11:31:291070bool PeerConnection::AddStream(MediaStreamInterface* local_stream) {
Steve Antonfc853712018-03-01 21:48:581071 RTC_CHECK(!IsUnifiedPlan()) << "AddStream is not available with Unified Plan "
1072 "SdpSemantics. Please use AddTrack instead.";
Peter Boström1a9d6152015-12-08 21:15:171073 TRACE_EVENT0("webrtc", "PeerConnection::AddStream");
henrike@webrtc.org28e20752013-07-10 00:45:361074 if (IsClosed()) {
1075 return false;
1076 }
deadbeefab9b2d12015-10-14 18:33:111077 if (!CanAddLocalMediaStream(local_streams_, local_stream)) {
henrike@webrtc.org28e20752013-07-10 00:45:361078 return false;
1079 }
deadbeefab9b2d12015-10-14 18:33:111080
1081 local_streams_->AddStream(local_stream);
deadbeefeb459812015-12-16 03:24:431082 MediaStreamObserver* observer = new MediaStreamObserver(local_stream);
1083 observer->SignalAudioTrackAdded.connect(this,
1084 &PeerConnection::OnAudioTrackAdded);
1085 observer->SignalAudioTrackRemoved.connect(
1086 this, &PeerConnection::OnAudioTrackRemoved);
1087 observer->SignalVideoTrackAdded.connect(this,
1088 &PeerConnection::OnVideoTrackAdded);
1089 observer->SignalVideoTrackRemoved.connect(
1090 this, &PeerConnection::OnVideoTrackRemoved);
kwibergd1fe2812016-04-27 13:47:291091 stream_observers_.push_back(std::unique_ptr<MediaStreamObserver>(observer));
deadbeefab9b2d12015-10-14 18:33:111092
deadbeefab9b2d12015-10-14 18:33:111093 for (const auto& track : local_stream->GetAudioTracks()) {
korniltsev.anatolyec390b52017-07-25 00:00:251094 AddAudioTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 18:33:111095 }
1096 for (const auto& track : local_stream->GetVideoTracks()) {
korniltsev.anatolyec390b52017-07-25 00:00:251097 AddVideoTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 18:33:111098 }
1099
tommi@webrtc.org03505bc2014-07-14 20:15:261100 stats_->AddStream(local_stream);
henrike@webrtc.org28e20752013-07-10 00:45:361101 observer_->OnRenegotiationNeeded();
1102 return true;
1103}
1104
1105void PeerConnection::RemoveStream(MediaStreamInterface* local_stream) {
Steve Antonfc853712018-03-01 21:48:581106 RTC_CHECK(!IsUnifiedPlan()) << "RemoveStream is not available with Unified "
1107 "Plan SdpSemantics. Please use RemoveTrack "
1108 "instead.";
Peter Boström1a9d6152015-12-08 21:15:171109 TRACE_EVENT0("webrtc", "PeerConnection::RemoveStream");
korniltsev.anatolyec390b52017-07-25 00:00:251110 if (!IsClosed()) {
1111 for (const auto& track : local_stream->GetAudioTracks()) {
1112 RemoveAudioTrack(track.get(), local_stream);
1113 }
1114 for (const auto& track : local_stream->GetVideoTracks()) {
1115 RemoveVideoTrack(track.get(), local_stream);
1116 }
deadbeefab9b2d12015-10-14 18:33:111117 }
deadbeefab9b2d12015-10-14 18:33:111118 local_streams_->RemoveStream(local_stream);
deadbeefeb459812015-12-16 03:24:431119 stream_observers_.erase(
1120 std::remove_if(
1121 stream_observers_.begin(), stream_observers_.end(),
kwibergd1fe2812016-04-27 13:47:291122 [local_stream](const std::unique_ptr<MediaStreamObserver>& observer) {
Seth Hampson13b8bad2018-03-13 23:05:281123 return observer->stream()->id().compare(local_stream->id()) == 0;
deadbeefeb459812015-12-16 03:24:431124 }),
1125 stream_observers_.end());
deadbeefab9b2d12015-10-14 18:33:111126
henrike@webrtc.org28e20752013-07-10 00:45:361127 if (IsClosed()) {
1128 return;
1129 }
henrike@webrtc.org28e20752013-07-10 00:45:361130 observer_->OnRenegotiationNeeded();
1131}
1132
deadbeefe1f9d832016-01-14 23:35:421133rtc::scoped_refptr<RtpSenderInterface> PeerConnection::AddTrack(
1134 MediaStreamTrackInterface* track,
1135 std::vector<MediaStreamInterface*> streams) {
1136 TRACE_EVENT0("webrtc", "PeerConnection::AddTrack");
Seth Hampson845e8782018-03-02 19:34:101137 std::vector<std::string> stream_ids;
Steve Antonf9381f02017-12-14 18:23:571138 for (auto* stream : streams) {
1139 if (!stream) {
1140 RTC_LOG(LS_ERROR) << "Stream list has null element.";
1141 return nullptr;
1142 }
Seth Hampson13b8bad2018-03-13 23:05:281143 stream_ids.push_back(stream->id());
Steve Antonf9381f02017-12-14 18:23:571144 }
Seth Hampson845e8782018-03-02 19:34:101145 auto sender_or_error = AddTrack(track, stream_ids);
Steve Antonf9381f02017-12-14 18:23:571146 if (!sender_or_error.ok()) {
deadbeefe1f9d832016-01-14 23:35:421147 return nullptr;
1148 }
Steve Antonf9381f02017-12-14 18:23:571149 return sender_or_error.MoveValue();
1150}
1151
Steve Anton2d6c76a2018-01-06 01:10:521152RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::AddTrack(
Steve Antonf9381f02017-12-14 18:23:571153 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 19:34:101154 const std::vector<std::string>& stream_ids) {
Steve Anton2d6c76a2018-01-06 01:10:521155 TRACE_EVENT0("webrtc", "PeerConnection::AddTrack");
Steve Antonf9381f02017-12-14 18:23:571156 if (!track) {
1157 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "Track is null.");
1158 }
1159 if (!(track->kind() == MediaStreamTrackInterface::kAudioKind ||
1160 track->kind() == MediaStreamTrackInterface::kVideoKind)) {
1161 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1162 "Track has invalid kind: " + track->kind());
1163 }
Steve Antonf9381f02017-12-14 18:23:571164 if (IsClosed()) {
1165 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
1166 "PeerConnection is closed.");
deadbeefe1f9d832016-01-14 23:35:421167 }
Steve Anton4171afb2017-11-20 18:20:221168 if (FindSenderForTrack(track)) {
Steve Antonf9381f02017-12-14 18:23:571169 LOG_AND_RETURN_ERROR(
1170 RTCErrorType::INVALID_PARAMETER,
1171 "Sender already exists for track " + track->id() + ".");
deadbeefe1f9d832016-01-14 23:35:421172 }
Steve Antonf9381f02017-12-14 18:23:571173 auto sender_or_error =
Seth Hampson5b4f0752018-04-02 23:31:361174 (IsUnifiedPlan() ? AddTrackUnifiedPlan(track, stream_ids)
1175 : AddTrackPlanB(track, stream_ids));
Steve Antonf9381f02017-12-14 18:23:571176 if (sender_or_error.ok()) {
1177 observer_->OnRenegotiationNeeded();
Steve Anton43a723a2018-01-04 23:48:171178 stats_->AddTrack(track);
Steve Antonf9381f02017-12-14 18:23:571179 }
1180 return sender_or_error;
1181}
deadbeefe1f9d832016-01-14 23:35:421182
Steve Antonf9381f02017-12-14 18:23:571183RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>>
1184PeerConnection::AddTrackPlanB(
1185 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 19:34:101186 const std::vector<std::string>& stream_ids) {
Seth Hampson5b4f0752018-04-02 23:31:361187 if (stream_ids.size() > 1u) {
1188 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_OPERATION,
1189 "AddTrack with more than one stream is not "
1190 "supported with Plan B semantics.");
1191 }
1192 std::vector<std::string> adjusted_stream_ids = stream_ids;
1193 if (adjusted_stream_ids.empty()) {
1194 adjusted_stream_ids.push_back(rtc::CreateRandomUuid());
1195 }
Steve Anton02ee47c2018-01-11 00:26:061196 cricket::MediaType media_type =
1197 (track->kind() == MediaStreamTrackInterface::kAudioKind
1198 ? cricket::MEDIA_TYPE_AUDIO
1199 : cricket::MEDIA_TYPE_VIDEO);
Seth Hampson5b4f0752018-04-02 23:31:361200 auto new_sender = CreateSender(media_type, track, adjusted_stream_ids);
deadbeefe1f9d832016-01-14 23:35:421201 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
Steve Anton57858b32018-02-15 23:19:501202 new_sender->internal()->SetVoiceMediaChannel(voice_media_channel());
Steve Anton4171afb2017-11-20 18:20:221203 GetAudioTransceiver()->internal()->AddSender(new_sender);
Steve Anton4171afb2017-11-20 18:20:221204 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609eaa2018-03-27 21:57:181205 FindSenderInfo(local_audio_sender_infos_,
Seth Hampson5b4f0752018-04-02 23:31:361206 new_sender->internal()->stream_ids()[0], track->id());
Steve Anton4171afb2017-11-20 18:20:221207 if (sender_info) {
1208 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 23:35:421209 }
Steve Antonf9381f02017-12-14 18:23:571210 } else {
1211 RTC_DCHECK_EQ(MediaStreamTrackInterface::kVideoKind, track->kind());
Steve Anton57858b32018-02-15 23:19:501212 new_sender->internal()->SetVideoMediaChannel(video_media_channel());
Steve Anton4171afb2017-11-20 18:20:221213 GetVideoTransceiver()->internal()->AddSender(new_sender);
Steve Anton4171afb2017-11-20 18:20:221214 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609eaa2018-03-27 21:57:181215 FindSenderInfo(local_video_sender_infos_,
Seth Hampson5b4f0752018-04-02 23:31:361216 new_sender->internal()->stream_ids()[0], track->id());
Steve Anton4171afb2017-11-20 18:20:221217 if (sender_info) {
1218 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 23:35:421219 }
deadbeefe1f9d832016-01-14 23:35:421220 }
Steve Anton02ee47c2018-01-11 00:26:061221 return rtc::scoped_refptr<RtpSenderInterface>(new_sender);
Steve Antonf9381f02017-12-14 18:23:571222}
deadbeefe1f9d832016-01-14 23:35:421223
Steve Antonf9381f02017-12-14 18:23:571224RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>>
1225PeerConnection::AddTrackUnifiedPlan(
1226 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 19:34:101227 const std::vector<std::string>& stream_ids) {
Steve Antonf9381f02017-12-14 18:23:571228 auto transceiver = FindFirstTransceiverForAddedTrack(track);
1229 if (transceiver) {
Steve Anton3d954a62018-04-02 18:27:231230 RTC_LOG(LS_INFO) << "Reusing an existing "
1231 << cricket::MediaTypeToString(transceiver->media_type())
1232 << " transceiver for AddTrack.";
Steve Antonf9381f02017-12-14 18:23:571233 if (transceiver->direction() == RtpTransceiverDirection::kRecvOnly) {
Steve Anton52d86772018-02-20 23:48:121234 transceiver->internal()->set_direction(
1235 RtpTransceiverDirection::kSendRecv);
Steve Antonf9381f02017-12-14 18:23:571236 } else if (transceiver->direction() == RtpTransceiverDirection::kInactive) {
Steve Anton52d86772018-02-20 23:48:121237 transceiver->internal()->set_direction(
1238 RtpTransceiverDirection::kSendOnly);
Steve Antonf9381f02017-12-14 18:23:571239 }
Steve Anton02ee47c2018-01-11 00:26:061240 transceiver->sender()->SetTrack(track);
Seth Hampson845e8782018-03-02 19:34:101241 transceiver->internal()->sender_internal()->set_stream_ids(stream_ids);
Steve Antonf9381f02017-12-14 18:23:571242 } else {
1243 cricket::MediaType media_type =
1244 (track->kind() == MediaStreamTrackInterface::kAudioKind
1245 ? cricket::MEDIA_TYPE_AUDIO
1246 : cricket::MEDIA_TYPE_VIDEO);
Steve Anton3d954a62018-04-02 18:27:231247 RTC_LOG(LS_INFO) << "Adding " << cricket::MediaTypeToString(media_type)
1248 << " transceiver in response to a call to AddTrack.";
Seth Hampson845e8782018-03-02 19:34:101249 auto sender = CreateSender(media_type, track, stream_ids);
Steve Anton02ee47c2018-01-11 00:26:061250 auto receiver = CreateReceiver(media_type, rtc::CreateRandomUuid());
1251 transceiver = CreateAndAddTransceiver(sender, receiver);
Steve Antonf9381f02017-12-14 18:23:571252 transceiver->internal()->set_created_by_addtrack(true);
Steve Anton52d86772018-02-20 23:48:121253 transceiver->internal()->set_direction(RtpTransceiverDirection::kSendRecv);
Steve Antonf9381f02017-12-14 18:23:571254 }
Steve Antonf9381f02017-12-14 18:23:571255 return transceiver->sender();
1256}
1257
1258rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1259PeerConnection::FindFirstTransceiverForAddedTrack(
1260 rtc::scoped_refptr<MediaStreamTrackInterface> track) {
1261 RTC_DCHECK(track);
1262 for (auto transceiver : transceivers_) {
1263 if (!transceiver->sender()->track() &&
Steve Anton69470252018-02-09 19:43:081264 cricket::MediaTypeToString(transceiver->media_type()) ==
Steve Antonf9381f02017-12-14 18:23:571265 track->kind() &&
Seth Hampson2f0d7022018-02-20 19:54:421266 !transceiver->internal()->has_ever_been_used_to_send() &&
1267 !transceiver->stopped()) {
Steve Antonf9381f02017-12-14 18:23:571268 return transceiver;
1269 }
1270 }
1271 return nullptr;
deadbeefe1f9d832016-01-14 23:35:421272}
1273
1274bool PeerConnection::RemoveTrack(RtpSenderInterface* sender) {
1275 TRACE_EVENT0("webrtc", "PeerConnection::RemoveTrack");
Steve Antonf9381f02017-12-14 18:23:571276 return RemoveTrackInternal(sender).ok();
1277}
1278
1279RTCError PeerConnection::RemoveTrackInternal(
1280 rtc::scoped_refptr<RtpSenderInterface> sender) {
1281 if (!sender) {
1282 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "Sender is null.");
1283 }
deadbeefe1f9d832016-01-14 23:35:421284 if (IsClosed()) {
Steve Antonf9381f02017-12-14 18:23:571285 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
1286 "PeerConnection is closed.");
deadbeefe1f9d832016-01-14 23:35:421287 }
Steve Antonf9381f02017-12-14 18:23:571288 if (IsUnifiedPlan()) {
1289 auto transceiver = FindTransceiverBySender(sender);
1290 if (!transceiver || !sender->track()) {
1291 return RTCError::OK();
1292 }
1293 sender->SetTrack(nullptr);
1294 if (transceiver->direction() == RtpTransceiverDirection::kSendRecv) {
Steve Anton52d86772018-02-20 23:48:121295 transceiver->internal()->set_direction(
1296 RtpTransceiverDirection::kRecvOnly);
Steve Antonf9381f02017-12-14 18:23:571297 } else if (transceiver->direction() == RtpTransceiverDirection::kSendOnly) {
Steve Anton52d86772018-02-20 23:48:121298 transceiver->internal()->set_direction(
1299 RtpTransceiverDirection::kInactive);
Steve Antonf9381f02017-12-14 18:23:571300 }
Steve Anton4171afb2017-11-20 18:20:221301 } else {
Steve Antonf9381f02017-12-14 18:23:571302 bool removed;
1303 if (sender->media_type() == cricket::MEDIA_TYPE_AUDIO) {
1304 removed = GetAudioTransceiver()->internal()->RemoveSender(sender);
1305 } else {
1306 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, sender->media_type());
1307 removed = GetVideoTransceiver()->internal()->RemoveSender(sender);
1308 }
1309 if (!removed) {
1310 LOG_AND_RETURN_ERROR(
1311 RTCErrorType::INVALID_PARAMETER,
1312 "Couldn't find sender " + sender->id() + " to remove.");
1313 }
Steve Anton4171afb2017-11-20 18:20:221314 }
deadbeefe1f9d832016-01-14 23:35:421315 observer_->OnRenegotiationNeeded();
Steve Antonf9381f02017-12-14 18:23:571316 return RTCError::OK();
1317}
1318
1319rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1320PeerConnection::FindTransceiverBySender(
1321 rtc::scoped_refptr<RtpSenderInterface> sender) {
1322 for (auto transceiver : transceivers_) {
1323 if (transceiver->sender() == sender) {
1324 return transceiver;
1325 }
1326 }
1327 return nullptr;
deadbeefe1f9d832016-01-14 23:35:421328}
1329
Steve Anton9158ef62017-11-27 21:01:521330RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1331PeerConnection::AddTransceiver(
1332 rtc::scoped_refptr<MediaStreamTrackInterface> track) {
1333 return AddTransceiver(track, RtpTransceiverInit());
1334}
1335
1336RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1337PeerConnection::AddTransceiver(
1338 rtc::scoped_refptr<MediaStreamTrackInterface> track,
1339 const RtpTransceiverInit& init) {
Steve Antonfc853712018-03-01 21:48:581340 RTC_CHECK(IsUnifiedPlan())
1341 << "AddTransceiver is only available with Unified Plan SdpSemantics";
Steve Anton9158ef62017-11-27 21:01:521342 if (!track) {
1343 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "track is null");
1344 }
1345 cricket::MediaType media_type;
1346 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
1347 media_type = cricket::MEDIA_TYPE_AUDIO;
1348 } else if (track->kind() == MediaStreamTrackInterface::kVideoKind) {
1349 media_type = cricket::MEDIA_TYPE_VIDEO;
1350 } else {
1351 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1352 "Track kind is not audio or video");
1353 }
1354 return AddTransceiver(media_type, track, init);
1355}
1356
1357RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1358PeerConnection::AddTransceiver(cricket::MediaType media_type) {
1359 return AddTransceiver(media_type, RtpTransceiverInit());
1360}
1361
1362RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1363PeerConnection::AddTransceiver(cricket::MediaType media_type,
1364 const RtpTransceiverInit& init) {
Steve Antonfc853712018-03-01 21:48:581365 RTC_CHECK(IsUnifiedPlan())
1366 << "AddTransceiver is only available with Unified Plan SdpSemantics";
Steve Anton9158ef62017-11-27 21:01:521367 if (!(media_type == cricket::MEDIA_TYPE_AUDIO ||
1368 media_type == cricket::MEDIA_TYPE_VIDEO)) {
1369 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1370 "media type is not audio or video");
1371 }
1372 return AddTransceiver(media_type, nullptr, init);
1373}
1374
1375RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1376PeerConnection::AddTransceiver(
1377 cricket::MediaType media_type,
1378 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Steve Anton22da89f2018-01-25 21:58:071379 const RtpTransceiverInit& init,
1380 bool fire_callback) {
Steve Anton9158ef62017-11-27 21:01:521381 RTC_DCHECK((media_type == cricket::MEDIA_TYPE_AUDIO ||
1382 media_type == cricket::MEDIA_TYPE_VIDEO));
1383 if (track) {
1384 RTC_DCHECK_EQ(media_type,
1385 (track->kind() == MediaStreamTrackInterface::kAudioKind
1386 ? cricket::MEDIA_TYPE_AUDIO
1387 : cricket::MEDIA_TYPE_VIDEO));
1388 }
1389
1390 // TODO(bugs.webrtc.org/7600): Verify init.
1391
Steve Anton3d954a62018-04-02 18:27:231392 RTC_LOG(LS_INFO) << "Adding " << cricket::MediaTypeToString(media_type)
1393 << " transceiver in response to a call to AddTransceiver.";
Seth Hampson5b4f0752018-04-02 23:31:361394 auto sender = CreateSender(media_type, track, init.stream_ids);
Steve Anton02ee47c2018-01-11 00:26:061395 auto receiver = CreateReceiver(media_type, rtc::CreateRandomUuid());
1396 auto transceiver = CreateAndAddTransceiver(sender, receiver);
1397 transceiver->internal()->set_direction(init.direction);
1398
Steve Anton22da89f2018-01-25 21:58:071399 if (fire_callback) {
1400 observer_->OnRenegotiationNeeded();
1401 }
Steve Antonf9381f02017-12-14 18:23:571402
1403 return rtc::scoped_refptr<RtpTransceiverInterface>(transceiver);
1404}
1405
Steve Anton02ee47c2018-01-11 00:26:061406rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
1407PeerConnection::CreateSender(
1408 cricket::MediaType media_type,
1409 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 19:34:101410 const std::vector<std::string>& stream_ids) {
Steve Anton9158ef62017-11-27 21:01:521411 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> sender;
Steve Anton02ee47c2018-01-11 00:26:061412 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
1413 RTC_DCHECK(!track ||
1414 (track->kind() == MediaStreamTrackInterface::kAudioKind));
1415 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
1416 signaling_thread(),
Steve Anton47136dd2018-01-12 18:49:351417 new AudioRtpSender(worker_thread(),
1418 static_cast<AudioTrackInterface*>(track.get()),
Seth Hampson845e8782018-03-02 19:34:101419 stream_ids, stats_.get()));
Steve Anton02ee47c2018-01-11 00:26:061420 } else {
1421 RTC_DCHECK_EQ(media_type, cricket::MEDIA_TYPE_VIDEO);
1422 RTC_DCHECK(!track ||
1423 (track->kind() == MediaStreamTrackInterface::kVideoKind));
1424 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
1425 signaling_thread(),
Steve Anton47136dd2018-01-12 18:49:351426 new VideoRtpSender(worker_thread(),
1427 static_cast<VideoTrackInterface*>(track.get()),
Seth Hampson845e8782018-03-02 19:34:101428 stream_ids));
Steve Anton02ee47c2018-01-11 00:26:061429 }
Seth Hampson845e8782018-03-02 19:34:101430 sender->internal()->set_stream_ids(stream_ids);
Steve Anton02ee47c2018-01-11 00:26:061431 return sender;
1432}
1433
1434rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1435PeerConnection::CreateReceiver(cricket::MediaType media_type,
1436 const std::string& receiver_id) {
Steve Anton9158ef62017-11-27 21:01:521437 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1438 receiver;
Steve Anton9158ef62017-11-27 21:01:521439 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton9158ef62017-11-27 21:01:521440 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
Steve Anton60776752018-01-10 19:51:341441 signaling_thread(),
Steve Antond3679212018-01-18 01:41:021442 new AudioRtpReceiver(worker_thread(), receiver_id, {}));
Steve Anton9158ef62017-11-27 21:01:521443 } else {
Steve Anton02ee47c2018-01-11 00:26:061444 RTC_DCHECK_EQ(media_type, cricket::MEDIA_TYPE_VIDEO);
Steve Anton9158ef62017-11-27 21:01:521445 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
1446 signaling_thread(),
Steve Antond3679212018-01-18 01:41:021447 new VideoRtpReceiver(worker_thread(), receiver_id, {}));
Steve Anton9158ef62017-11-27 21:01:521448 }
Steve Anton02ee47c2018-01-11 00:26:061449 return receiver;
1450}
1451
1452rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1453PeerConnection::CreateAndAddTransceiver(
1454 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> sender,
1455 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1456 receiver) {
1457 auto transceiver = RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1458 signaling_thread(), new RtpTransceiver(sender, receiver));
Steve Anton9158ef62017-11-27 21:01:521459 transceivers_.push_back(transceiver);
Steve Anton52d86772018-02-20 23:48:121460 transceiver->internal()->SignalNegotiationNeeded.connect(
1461 this, &PeerConnection::OnNegotiationNeeded);
Steve Antonf9381f02017-12-14 18:23:571462 return transceiver;
Steve Anton9158ef62017-11-27 21:01:521463}
1464
Steve Anton52d86772018-02-20 23:48:121465void PeerConnection::OnNegotiationNeeded() {
1466 RTC_DCHECK_RUN_ON(signaling_thread());
1467 RTC_DCHECK(!IsClosed());
1468 observer_->OnRenegotiationNeeded();
1469}
1470
buildbot@webrtc.orgd4e598d2014-07-29 17:36:521471rtc::scoped_refptr<DtmfSenderInterface> PeerConnection::CreateDtmfSender(
henrike@webrtc.org28e20752013-07-10 00:45:361472 AudioTrackInterface* track) {
Peter Boström1a9d6152015-12-08 21:15:171473 TRACE_EVENT0("webrtc", "PeerConnection::CreateDtmfSender");
zhihuang29ff8442016-07-27 18:07:251474 if (IsClosed()) {
1475 return nullptr;
1476 }
henrike@webrtc.org28e20752013-07-10 00:45:361477 if (!track) {
Mirko Bonadei675513b2017-11-09 10:09:251478 RTC_LOG(LS_ERROR) << "CreateDtmfSender - track is NULL.";
deadbeef20cb0c12017-02-02 04:27:001479 return nullptr;
henrike@webrtc.org28e20752013-07-10 00:45:361480 }
Steve Anton4171afb2017-11-20 18:20:221481 auto track_sender = FindSenderForTrack(track);
1482 if (!track_sender) {
Mirko Bonadei675513b2017-11-09 10:09:251483 RTC_LOG(LS_ERROR) << "CreateDtmfSender called with a non-added track.";
deadbeef20cb0c12017-02-02 04:27:001484 return nullptr;
henrike@webrtc.org28e20752013-07-10 00:45:361485 }
1486
Steve Anton4171afb2017-11-20 18:20:221487 return track_sender->GetDtmfSender();
henrike@webrtc.org28e20752013-07-10 00:45:361488}
1489
deadbeeffac06552015-11-25 19:26:011490rtc::scoped_refptr<RtpSenderInterface> PeerConnection::CreateSender(
deadbeefbd7d8f72015-12-19 00:58:441491 const std::string& kind,
1492 const std::string& stream_id) {
Steve Antonfc853712018-03-01 21:48:581493 RTC_CHECK(!IsUnifiedPlan()) << "CreateSender is not available with Unified "
1494 "Plan SdpSemantics. Please use AddTransceiver "
1495 "instead.";
Peter Boström1a9d6152015-12-08 21:15:171496 TRACE_EVENT0("webrtc", "PeerConnection::CreateSender");
zhihuang29ff8442016-07-27 18:07:251497 if (IsClosed()) {
1498 return nullptr;
1499 }
Steve Anton4171afb2017-11-20 18:20:221500
Seth Hampson5b4f0752018-04-02 23:31:361501 // Internally we need to have one stream with Plan B semantics, so we
1502 // generate a random stream ID if not specified.
Seth Hampson845e8782018-03-02 19:34:101503 std::vector<std::string> stream_ids;
Seth Hampson5b4f0752018-04-02 23:31:361504 if (stream_id.empty()) {
1505 stream_ids.push_back(rtc::CreateRandomUuid());
1506 RTC_LOG(LS_INFO)
1507 << "No stream_id specified for sender. Generated stream ID: "
1508 << stream_ids[0];
1509 } else {
Seth Hampson845e8782018-03-02 19:34:101510 stream_ids.push_back(stream_id);
Steve Anton02ee47c2018-01-11 00:26:061511 }
1512
Steve Anton4171afb2017-11-20 18:20:221513 // TODO(steveanton): Move construction of the RtpSenders to RtpTransceiver.
deadbeefa601f5c2016-06-06 21:27:391514 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender;
deadbeeffac06552015-11-25 19:26:011515 if (kind == MediaStreamTrackInterface::kAudioKind) {
Seth Hampson845e8782018-03-02 19:34:101516 auto* audio_sender =
1517 new AudioRtpSender(worker_thread(), nullptr, stream_ids, stats_.get());
Steve Anton57858b32018-02-15 23:19:501518 audio_sender->SetVoiceMediaChannel(voice_media_channel());
deadbeefa601f5c2016-06-06 21:27:391519 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton02ee47c2018-01-11 00:26:061520 signaling_thread(), audio_sender);
Steve Anton4171afb2017-11-20 18:20:221521 GetAudioTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 19:26:011522 } else if (kind == MediaStreamTrackInterface::kVideoKind) {
Steve Anton47136dd2018-01-12 18:49:351523 auto* video_sender =
Seth Hampson845e8782018-03-02 19:34:101524 new VideoRtpSender(worker_thread(), nullptr, stream_ids);
Steve Anton57858b32018-02-15 23:19:501525 video_sender->SetVideoMediaChannel(video_media_channel());
deadbeefa601f5c2016-06-06 21:27:391526 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton02ee47c2018-01-11 00:26:061527 signaling_thread(), video_sender);
Steve Anton4171afb2017-11-20 18:20:221528 GetVideoTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 19:26:011529 } else {
Mirko Bonadei675513b2017-11-09 10:09:251530 RTC_LOG(LS_ERROR) << "CreateSender called with invalid kind: " << kind;
Steve Anton4171afb2017-11-20 18:20:221531 return nullptr;
deadbeeffac06552015-11-25 19:26:011532 }
Steve Anton4171afb2017-11-20 18:20:221533
deadbeefe1f9d832016-01-14 23:35:421534 return new_sender;
deadbeeffac06552015-11-25 19:26:011535}
1536
deadbeef70ab1a12015-09-28 23:53:551537std::vector<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::GetSenders()
1538 const {
deadbeefa601f5c2016-06-06 21:27:391539 std::vector<rtc::scoped_refptr<RtpSenderInterface>> ret;
Steve Anton4171afb2017-11-20 18:20:221540 for (auto sender : GetSendersInternal()) {
1541 ret.push_back(sender);
deadbeefa601f5c2016-06-06 21:27:391542 }
1543 return ret;
deadbeef70ab1a12015-09-28 23:53:551544}
1545
Steve Anton4171afb2017-11-20 18:20:221546std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1547PeerConnection::GetSendersInternal() const {
1548 std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1549 all_senders;
1550 for (auto transceiver : transceivers_) {
1551 auto senders = transceiver->internal()->senders();
1552 all_senders.insert(all_senders.end(), senders.begin(), senders.end());
1553 }
1554 return all_senders;
1555}
1556
deadbeef70ab1a12015-09-28 23:53:551557std::vector<rtc::scoped_refptr<RtpReceiverInterface>>
1558PeerConnection::GetReceivers() const {
deadbeefa601f5c2016-06-06 21:27:391559 std::vector<rtc::scoped_refptr<RtpReceiverInterface>> ret;
Steve Anton4171afb2017-11-20 18:20:221560 for (const auto& receiver : GetReceiversInternal()) {
1561 ret.push_back(receiver);
deadbeefa601f5c2016-06-06 21:27:391562 }
1563 return ret;
deadbeef70ab1a12015-09-28 23:53:551564}
1565
Steve Anton4171afb2017-11-20 18:20:221566std::vector<
1567 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1568PeerConnection::GetReceiversInternal() const {
1569 std::vector<
1570 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1571 all_receivers;
1572 for (auto transceiver : transceivers_) {
1573 auto receivers = transceiver->internal()->receivers();
1574 all_receivers.insert(all_receivers.end(), receivers.begin(),
1575 receivers.end());
1576 }
1577 return all_receivers;
1578}
1579
Steve Anton9158ef62017-11-27 21:01:521580std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
1581PeerConnection::GetTransceivers() const {
Steve Antonfc853712018-03-01 21:48:581582 RTC_CHECK(IsUnifiedPlan())
1583 << "GetTransceivers is only supported with Unified Plan SdpSemantics.";
Steve Anton9158ef62017-11-27 21:01:521584 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> all_transceivers;
1585 for (auto transceiver : transceivers_) {
1586 all_transceivers.push_back(transceiver);
1587 }
1588 return all_transceivers;
1589}
1590
henrike@webrtc.org28e20752013-07-10 00:45:361591bool PeerConnection::GetStats(StatsObserver* observer,
wu@webrtc.orgb9a088b2014-02-13 23:18:491592 MediaStreamTrackInterface* track,
1593 StatsOutputLevel level) {
Peter Boström1a9d6152015-12-08 21:15:171594 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
deadbeef0a6c4ca2015-10-06 18:38:281595 RTC_DCHECK(signaling_thread()->IsCurrent());
nisse7ce109a2017-01-31 08:57:561596 if (!observer) {
Mirko Bonadei675513b2017-11-09 10:09:251597 RTC_LOG(LS_ERROR) << "GetStats - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:361598 return false;
1599 }
1600
tommi@webrtc.org03505bc2014-07-14 20:15:261601 stats_->UpdateStats(level);
zhihuange9e94c32016-11-04 18:38:151602 // The StatsCollector is used to tell if a track is valid because it may
1603 // remember tracks that the PeerConnection previously removed.
1604 if (track && !stats_->IsValidTrack(track->id())) {
Mirko Bonadei675513b2017-11-09 10:09:251605 RTC_LOG(LS_WARNING) << "GetStats is called with an invalid track: "
1606 << track->id();
zhihuange9e94c32016-11-04 18:38:151607 return false;
1608 }
Taylor Brandstetter5d97a9a2016-06-10 21:17:271609 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_GETSTATS,
tommi@webrtc.org5b06b062014-08-15 08:38:301610 new GetStatsMsg(observer, track));
henrike@webrtc.org28e20752013-07-10 00:45:361611 return true;
1612}
1613
hbos74e1a4f2016-09-16 06:33:011614void PeerConnection::GetStats(RTCStatsCollectorCallback* callback) {
Henrik Boström1df1bf82018-03-20 12:24:201615 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
hbos74e1a4f2016-09-16 06:33:011616 RTC_DCHECK(stats_collector_);
Henrik Boström1df1bf82018-03-20 12:24:201617 RTC_DCHECK(callback);
hbos74e1a4f2016-09-16 06:33:011618 stats_collector_->GetStatsReport(callback);
1619}
1620
Henrik Boström1df1bf82018-03-20 12:24:201621void PeerConnection::GetStats(
1622 rtc::scoped_refptr<RtpSenderInterface> selector,
1623 rtc::scoped_refptr<RTCStatsCollectorCallback> callback) {
1624 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
1625 RTC_DCHECK(callback);
1626 RTC_DCHECK(stats_collector_);
1627 rtc::scoped_refptr<RtpSenderInternal> internal_sender;
1628 if (selector) {
1629 for (const auto& proxy_transceiver : transceivers_) {
1630 for (const auto& proxy_sender :
1631 proxy_transceiver->internal()->senders()) {
1632 if (proxy_sender == selector) {
1633 internal_sender = proxy_sender->internal();
1634 break;
1635 }
1636 }
1637 if (internal_sender)
1638 break;
1639 }
1640 }
1641 // If there is no |internal_sender| then |selector| is either null or does not
1642 // belong to the PeerConnection (in Plan B, senders can be removed from the
1643 // PeerConnection). This means that "all the stats objects representing the
1644 // selector" is an empty set. Invoking GetStatsReport() with a null selector
1645 // produces an empty stats report.
1646 stats_collector_->GetStatsReport(internal_sender, callback);
1647}
1648
1649void PeerConnection::GetStats(
1650 rtc::scoped_refptr<RtpReceiverInterface> selector,
1651 rtc::scoped_refptr<RTCStatsCollectorCallback> callback) {
1652 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
1653 RTC_DCHECK(callback);
1654 RTC_DCHECK(stats_collector_);
1655 rtc::scoped_refptr<RtpReceiverInternal> internal_receiver;
1656 if (selector) {
1657 for (const auto& proxy_transceiver : transceivers_) {
1658 for (const auto& proxy_receiver :
1659 proxy_transceiver->internal()->receivers()) {
1660 if (proxy_receiver == selector) {
1661 internal_receiver = proxy_receiver->internal();
1662 break;
1663 }
1664 }
1665 if (internal_receiver)
1666 break;
1667 }
1668 }
1669 // If there is no |internal_receiver| then |selector| is either null or does
1670 // not belong to the PeerConnection (in Plan B, receivers can be removed from
1671 // the PeerConnection). This means that "all the stats objects representing
1672 // the selector" is an empty set. Invoking GetStatsReport() with a null
1673 // selector produces an empty stats report.
1674 stats_collector_->GetStatsReport(internal_receiver, callback);
1675}
1676
henrike@webrtc.org28e20752013-07-10 00:45:361677PeerConnectionInterface::SignalingState PeerConnection::signaling_state() {
1678 return signaling_state_;
1679}
1680
henrike@webrtc.org28e20752013-07-10 00:45:361681PeerConnectionInterface::IceConnectionState
1682PeerConnection::ice_connection_state() {
1683 return ice_connection_state_;
1684}
1685
1686PeerConnectionInterface::IceGatheringState
1687PeerConnection::ice_gathering_state() {
1688 return ice_gathering_state_;
1689}
1690
buildbot@webrtc.orgd4e598d2014-07-29 17:36:521691rtc::scoped_refptr<DataChannelInterface>
henrike@webrtc.org28e20752013-07-10 00:45:361692PeerConnection::CreateDataChannel(
1693 const std::string& label,
1694 const DataChannelInit* config) {
Peter Boström1a9d6152015-12-08 21:15:171695 TRACE_EVENT0("webrtc", "PeerConnection::CreateDataChannel");
zhihuang9763d562016-08-05 18:14:501696
deadbeefab9b2d12015-10-14 18:33:111697 bool first_datachannel = !HasDataChannels();
jiayl@webrtc.org001fd2d2014-05-29 15:31:111698
kwibergd1fe2812016-04-27 13:47:291699 std::unique_ptr<InternalDataChannelInit> internal_config;
henrika@webrtc.orgaebb1ad2014-01-14 10:00:581700 if (config) {
1701 internal_config.reset(new InternalDataChannelInit(*config));
1702 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:521703 rtc::scoped_refptr<DataChannelInterface> channel(
deadbeefab9b2d12015-10-14 18:33:111704 InternalCreateDataChannel(label, internal_config.get()));
1705 if (!channel.get()) {
1706 return nullptr;
1707 }
henrike@webrtc.org28e20752013-07-10 00:45:361708
jiayl@webrtc.org001fd2d2014-05-29 15:31:111709 // Trigger the onRenegotiationNeeded event for every new RTP DataChannel, or
1710 // the first SCTP DataChannel.
Steve Anton75737c02017-11-06 18:37:171711 if (data_channel_type() == cricket::DCT_RTP || first_datachannel) {
jiayl@webrtc.org001fd2d2014-05-29 15:31:111712 observer_->OnRenegotiationNeeded();
1713 }
wu@webrtc.org91053e72013-08-10 07:18:041714
henrike@webrtc.org28e20752013-07-10 00:45:361715 return DataChannelProxy::Create(signaling_thread(), channel.get());
1716}
1717
1718void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
1719 const MediaConstraintsInterface* constraints) {
Peter Boström1a9d6152015-12-08 21:15:171720 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
Steve Anton8d3444d2017-10-20 22:30:511721
zhihuang1c378ed2017-08-17 21:10:501722 PeerConnectionInterface::RTCOfferAnswerOptions offer_answer_options;
1723 // Always create an offer even if |ConvertConstraintsToOfferAnswerOptions|
1724 // returns false for now. Because |ConvertConstraintsToOfferAnswerOptions|
1725 // compares the mandatory fields parsed with the mandatory fields added in the
1726 // |constraints| and some downstream applications might create offers with
1727 // mandatory fields which would not be parsed in the helper method. For
1728 // example, in Chromium/remoting, |kEnableDtlsSrtp| is added to the
1729 // |constraints| as a mandatory field but it is not parsed.
1730 ConvertConstraintsToOfferAnswerOptions(constraints, &offer_answer_options);
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:161731
zhihuang1c378ed2017-08-17 21:10:501732 CreateOffer(observer, offer_answer_options);
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:161733}
1734
1735void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
1736 const RTCOfferAnswerOptions& options) {
Peter Boström1a9d6152015-12-08 21:15:171737 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
Steve Anton8d3444d2017-10-20 22:30:511738
nisse7ce109a2017-01-31 08:57:561739 if (!observer) {
Mirko Bonadei675513b2017-11-09 10:09:251740 RTC_LOG(LS_ERROR) << "CreateOffer - observer is NULL.";
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:161741 return;
1742 }
deadbeefab9b2d12015-10-14 18:33:111743
Steve Anton8d3444d2017-10-20 22:30:511744 if (IsClosed()) {
1745 std::string error = "CreateOffer called when PeerConnection is closed.";
Mirko Bonadei675513b2017-11-09 10:09:251746 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 14:18:031747 PostCreateSessionDescriptionFailure(
1748 observer, RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error)));
Steve Anton8d3444d2017-10-20 22:30:511749 return;
1750 }
1751
zhihuang1c378ed2017-08-17 21:10:501752 if (!ValidateOfferAnswerOptions(options)) {
deadbeefab9b2d12015-10-14 18:33:111753 std::string error = "CreateOffer called with invalid options.";
Mirko Bonadei675513b2017-11-09 10:09:251754 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 14:18:031755 PostCreateSessionDescriptionFailure(
1756 observer, RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error)));
deadbeefab9b2d12015-10-14 18:33:111757 return;
1758 }
1759
Steve Anton22da89f2018-01-25 21:58:071760 // Legacy handling for offer_to_receive_audio and offer_to_receive_video.
1761 // Specified in WebRTC section 4.4.3.2 "Legacy configuration extensions".
1762 if (IsUnifiedPlan()) {
1763 RTCError error = HandleLegacyOfferOptions(options);
1764 if (!error.ok()) {
Harald Alvestrand5081c0c2018-03-09 14:18:031765 PostCreateSessionDescriptionFailure(observer, std::move(error));
Steve Anton22da89f2018-01-25 21:58:071766 return;
1767 }
1768 }
1769
zhihuang1c378ed2017-08-17 21:10:501770 cricket::MediaSessionOptions session_options;
1771 GetOptionsForOffer(options, &session_options);
Steve Antond25da372017-11-06 22:50:291772 webrtc_session_desc_factory_->CreateOffer(observer, options, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:361773}
1774
Steve Anton22da89f2018-01-25 21:58:071775RTCError PeerConnection::HandleLegacyOfferOptions(
1776 const RTCOfferAnswerOptions& options) {
1777 RTC_DCHECK(IsUnifiedPlan());
1778
1779 if (options.offer_to_receive_audio == 0) {
1780 RemoveRecvDirectionFromReceivingTransceiversOfType(
1781 cricket::MEDIA_TYPE_AUDIO);
1782 } else if (options.offer_to_receive_audio == 1) {
1783 AddUpToOneReceivingTransceiverOfType(cricket::MEDIA_TYPE_AUDIO);
1784 } else if (options.offer_to_receive_audio > 1) {
1785 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
1786 "offer_to_receive_audio > 1 is not supported.");
1787 }
1788
1789 if (options.offer_to_receive_video == 0) {
1790 RemoveRecvDirectionFromReceivingTransceiversOfType(
1791 cricket::MEDIA_TYPE_VIDEO);
1792 } else if (options.offer_to_receive_video == 1) {
1793 AddUpToOneReceivingTransceiverOfType(cricket::MEDIA_TYPE_VIDEO);
1794 } else if (options.offer_to_receive_video > 1) {
1795 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
1796 "offer_to_receive_video > 1 is not supported.");
1797 }
1798
1799 return RTCError::OK();
1800}
1801
1802void PeerConnection::RemoveRecvDirectionFromReceivingTransceiversOfType(
1803 cricket::MediaType media_type) {
1804 for (auto transceiver : GetReceivingTransceiversOfType(media_type)) {
Steve Anton3d954a62018-04-02 18:27:231805 RtpTransceiverDirection new_direction =
1806 RtpTransceiverDirectionWithRecvSet(transceiver->direction(), false);
1807 if (new_direction != transceiver->direction()) {
1808 RTC_LOG(LS_INFO) << "Changing " << cricket::MediaTypeToString(media_type)
1809 << " transceiver (MID="
1810 << transceiver->mid().value_or("<not set>") << ") from "
1811 << RtpTransceiverDirectionToString(
1812 transceiver->direction())
1813 << " to "
1814 << RtpTransceiverDirectionToString(new_direction)
1815 << " since CreateOffer specified offer_to_receive=0";
1816 transceiver->internal()->set_direction(new_direction);
1817 }
Steve Anton22da89f2018-01-25 21:58:071818 }
1819}
1820
1821void PeerConnection::AddUpToOneReceivingTransceiverOfType(
1822 cricket::MediaType media_type) {
1823 if (GetReceivingTransceiversOfType(media_type).empty()) {
Steve Anton3d954a62018-04-02 18:27:231824 RTC_LOG(LS_INFO)
1825 << "Adding one recvonly " << cricket::MediaTypeToString(media_type)
1826 << " transceiver since CreateOffer specified offer_to_receive=1";
Steve Anton22da89f2018-01-25 21:58:071827 RtpTransceiverInit init;
1828 init.direction = RtpTransceiverDirection::kRecvOnly;
1829 AddTransceiver(media_type, nullptr, init, /*fire_callback=*/false);
1830 }
1831}
1832
1833std::vector<rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
1834PeerConnection::GetReceivingTransceiversOfType(cricket::MediaType media_type) {
1835 std::vector<
1836 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
1837 receiving_transceivers;
1838 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 19:43:081839 if (!transceiver->stopped() && transceiver->media_type() == media_type &&
Steve Anton22da89f2018-01-25 21:58:071840 RtpTransceiverDirectionHasRecv(transceiver->direction())) {
1841 receiving_transceivers.push_back(transceiver);
1842 }
1843 }
1844 return receiving_transceivers;
1845}
1846
henrike@webrtc.org28e20752013-07-10 00:45:361847void PeerConnection::CreateAnswer(
1848 CreateSessionDescriptionObserver* observer,
1849 const MediaConstraintsInterface* constraints) {
Peter Boström1a9d6152015-12-08 21:15:171850 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
Steve Anton8d3444d2017-10-20 22:30:511851
nisse7ce109a2017-01-31 08:57:561852 if (!observer) {
Mirko Bonadei675513b2017-11-09 10:09:251853 RTC_LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:361854 return;
1855 }
deadbeefab9b2d12015-10-14 18:33:111856
zhihuang1c378ed2017-08-17 21:10:501857 PeerConnectionInterface::RTCOfferAnswerOptions offer_answer_options;
1858 if (!ConvertConstraintsToOfferAnswerOptions(constraints,
1859 &offer_answer_options)) {
deadbeefab9b2d12015-10-14 18:33:111860 std::string error = "CreateAnswer called with invalid constraints.";
Mirko Bonadei675513b2017-11-09 10:09:251861 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 14:18:031862 PostCreateSessionDescriptionFailure(
1863 observer, RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error)));
deadbeefab9b2d12015-10-14 18:33:111864 return;
1865 }
1866
Steve Anton8d3444d2017-10-20 22:30:511867 CreateAnswer(observer, offer_answer_options);
htaa2a49d92016-03-04 10:51:391868}
1869
1870void PeerConnection::CreateAnswer(CreateSessionDescriptionObserver* observer,
1871 const RTCOfferAnswerOptions& options) {
1872 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
nisse7ce109a2017-01-31 08:57:561873 if (!observer) {
Mirko Bonadei675513b2017-11-09 10:09:251874 RTC_LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
htaa2a49d92016-03-04 10:51:391875 return;
1876 }
1877
Steve Antondffead82018-02-06 18:31:291878 if (!(signaling_state_ == kHaveRemoteOffer ||
1879 signaling_state_ == kHaveLocalPrAnswer)) {
1880 std::string error =
1881 "PeerConnection cannot create an answer in a state other than "
1882 "have-remote-offer or have-local-pranswer.";
Mirko Bonadei675513b2017-11-09 10:09:251883 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 14:18:031884 PostCreateSessionDescriptionFailure(
1885 observer, RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error)));
Steve Anton8d3444d2017-10-20 22:30:511886 return;
1887 }
1888
Steve Antondffead82018-02-06 18:31:291889 // The remote description should be set if we're in the right state.
1890 RTC_DCHECK(remote_description());
Steve Anton8d3444d2017-10-20 22:30:511891
Steve Anton22da89f2018-01-25 21:58:071892 if (IsUnifiedPlan()) {
1893 if (options.offer_to_receive_audio != RTCOfferAnswerOptions::kUndefined) {
1894 RTC_LOG(LS_WARNING) << "CreateAnswer: offer_to_receive_audio is not "
1895 "supported with Unified Plan semantics. Use the "
1896 "RtpTransceiver API instead.";
1897 }
1898 if (options.offer_to_receive_video != RTCOfferAnswerOptions::kUndefined) {
1899 RTC_LOG(LS_WARNING) << "CreateAnswer: offer_to_receive_video is not "
1900 "supported with Unified Plan semantics. Use the "
1901 "RtpTransceiver API instead.";
1902 }
1903 }
1904
htaa2a49d92016-03-04 10:51:391905 cricket::MediaSessionOptions session_options;
zhihuang1c378ed2017-08-17 21:10:501906 GetOptionsForAnswer(options, &session_options);
htaa2a49d92016-03-04 10:51:391907
Steve Antond25da372017-11-06 22:50:291908 webrtc_session_desc_factory_->CreateAnswer(observer, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:361909}
1910
1911void PeerConnection::SetLocalDescription(
1912 SetSessionDescriptionObserver* observer,
Steve Anton80dd7b52018-02-17 01:08:421913 SessionDescriptionInterface* desc_ptr) {
Peter Boström1a9d6152015-12-08 21:15:171914 TRACE_EVENT0("webrtc", "PeerConnection::SetLocalDescription");
Steve Anton8a006912017-12-04 23:25:561915
Steve Anton80dd7b52018-02-17 01:08:421916 // The SetLocalDescription contract is that we take ownership of the session
1917 // description regardless of the outcome, so wrap it in a unique_ptr right
1918 // away. Ideally, SetLocalDescription's signature will be changed to take the
1919 // description as a unique_ptr argument to formalize this agreement.
1920 std::unique_ptr<SessionDescriptionInterface> desc(desc_ptr);
1921
nisse7ce109a2017-01-31 08:57:561922 if (!observer) {
Mirko Bonadei675513b2017-11-09 10:09:251923 RTC_LOG(LS_ERROR) << "SetLocalDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:361924 return;
1925 }
Steve Anton8a006912017-12-04 23:25:561926
henrike@webrtc.org28e20752013-07-10 00:45:361927 if (!desc) {
Harald Alvestrand5081c0c2018-03-09 14:18:031928 PostSetSessionDescriptionFailure(
1929 observer,
1930 RTCError(RTCErrorType::INTERNAL_ERROR, "SessionDescription is NULL."));
henrike@webrtc.org28e20752013-07-10 00:45:361931 return;
1932 }
Steve Anton8d3444d2017-10-20 22:30:511933
Steve Anton80dd7b52018-02-17 01:08:421934 // If a session error has occurred the PeerConnection is in a possibly
1935 // inconsistent state so fail right away.
1936 if (session_error() != SessionError::kNone) {
1937 std::string error_message = GetSessionErrorMsg();
1938 RTC_LOG(LS_ERROR) << "SetLocalDescription: " << error_message;
Harald Alvestrand5081c0c2018-03-09 14:18:031939 PostSetSessionDescriptionFailure(
1940 observer,
1941 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton80dd7b52018-02-17 01:08:421942 return;
1943 }
Steve Anton8d3444d2017-10-20 22:30:511944
Steve Anton80dd7b52018-02-17 01:08:421945 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_LOCAL);
1946 if (!error.ok()) {
1947 std::string error_message = GetSetDescriptionErrorMessage(
1948 cricket::CS_LOCAL, desc->GetType(), error);
1949 RTC_LOG(LS_ERROR) << error_message;
Harald Alvestrand5081c0c2018-03-09 14:18:031950 PostSetSessionDescriptionFailure(
1951 observer,
1952 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton80dd7b52018-02-17 01:08:421953 return;
1954 }
1955
1956 // Grab the description type before moving ownership to ApplyLocalDescription,
1957 // which may destroy it before returning.
1958 const SdpType type = desc->GetType();
1959
1960 error = ApplyLocalDescription(std::move(desc));
Steve Anton8a006912017-12-04 23:25:561961 // |desc| may be destroyed at this point.
1962
1963 if (!error.ok()) {
Steve Anton80dd7b52018-02-17 01:08:421964 // If ApplyLocalDescription fails, the PeerConnection could be in an
1965 // inconsistent state, so act conservatively here and set the session error
1966 // so that future calls to SetLocalDescription/SetRemoteDescription fail.
1967 SetSessionError(SessionError::kContent, error.message());
1968 std::string error_message =
1969 GetSetDescriptionErrorMessage(cricket::CS_LOCAL, type, error);
1970 RTC_LOG(LS_ERROR) << error_message;
Harald Alvestrand5081c0c2018-03-09 14:18:031971 PostSetSessionDescriptionFailure(
1972 observer,
1973 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton8d3444d2017-10-20 22:30:511974 return;
1975 }
Steve Anton8a006912017-12-04 23:25:561976 RTC_DCHECK(local_description());
1977
1978 PostSetSessionDescriptionSuccess(observer);
1979
Patrik Höglund3dc41062018-04-11 11:13:571980 // According to JSEP, after setLocalDescription, changing the candidate pool
1981 // size is not allowed, and changing the set of ICE servers will not result
1982 // in new candidates being gathered.
1983 port_allocator_->FreezeCandidatePool();
1984
Steve Anton8a006912017-12-04 23:25:561985 // MaybeStartGathering needs to be called after posting
1986 // MSG_SET_SESSIONDESCRIPTION_SUCCESS, so that we don't signal any candidates
1987 // before signaling that SetLocalDescription completed.
1988 transport_controller_->MaybeStartGathering();
1989
Steve Antona3a92c22017-12-07 18:27:411990 if (local_description()->GetType() == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 23:25:561991 // TODO(deadbeef): We already had to hop to the network thread for
1992 // MaybeStartGathering...
1993 network_thread()->Invoke<void>(
1994 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
1995 port_allocator_.get()));
Steve Anton0ffaaa22018-02-23 18:31:301996 // Make UMA notes about what was agreed to.
1997 ReportNegotiatedSdpSemantics(*local_description());
Steve Anton8a006912017-12-04 23:25:561998 }
1999}
2000
2001RTCError PeerConnection::ApplyLocalDescription(
2002 std::unique_ptr<SessionDescriptionInterface> desc) {
2003 RTC_DCHECK_RUN_ON(signaling_thread());
2004 RTC_DCHECK(desc);
2005
henrike@webrtc.org28e20752013-07-10 00:45:362006 // Update stats here so that we have the most recent stats for tracks and
2007 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:262008 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 23:25:562009
Steve Antondcc3c022017-12-23 00:02:542010 // Take a reference to the old local description since it's used below to
2011 // compare against the new local description. When setting the new local
2012 // description, grab ownership of the replaced session description in case it
2013 // is the same as |old_local_description|, to keep it alive for the duration
2014 // of the method.
2015 const SessionDescriptionInterface* old_local_description =
2016 local_description();
2017 std::unique_ptr<SessionDescriptionInterface> replaced_local_description;
Zhi Huange830e682018-03-30 17:48:352018 SdpType type = desc->GetType();
Steve Anton3828c062017-12-06 18:34:512019 if (type == SdpType::kAnswer) {
Steve Antondcc3c022017-12-23 00:02:542020 replaced_local_description = pending_local_description_
2021 ? std::move(pending_local_description_)
2022 : std::move(current_local_description_);
Steve Anton8a006912017-12-04 23:25:562023 current_local_description_ = std::move(desc);
2024 pending_local_description_ = nullptr;
2025 current_remote_description_ = std::move(pending_remote_description_);
2026 } else {
Steve Antondcc3c022017-12-23 00:02:542027 replaced_local_description = std::move(pending_local_description_);
Steve Anton8a006912017-12-04 23:25:562028 pending_local_description_ = std::move(desc);
2029 }
2030 // The session description to apply now must be accessed by
2031 // |local_description()|.
Henrik Boströmfdb92012017-11-09 18:55:442032 RTC_DCHECK(local_description());
deadbeefab9b2d12015-10-14 18:33:112033
Zhi Huange830e682018-03-30 17:48:352034 RTCError error = PushdownTransportDescription(cricket::CS_LOCAL, type);
2035 if (!error.ok()) {
2036 return error;
2037 }
2038
Steve Antondcc3c022017-12-23 00:02:542039 if (IsUnifiedPlan()) {
2040 RTCError error = UpdateTransceiversAndDataChannels(
Seth Hampsonae8a90a2018-02-13 23:33:482041 cricket::CS_LOCAL, *local_description(), old_local_description,
2042 remote_description());
Steve Anton8a006912017-12-04 23:25:562043 if (!error.ok()) {
2044 return error;
2045 }
Steve Antondcc3c022017-12-23 00:02:542046 for (auto transceiver : transceivers_) {
2047 const ContentInfo* content =
2048 FindMediaSectionForTransceiver(transceiver, local_description());
2049 if (!content) {
2050 continue;
2051 }
2052 const MediaContentDescription* media_desc = content->media_description();
2053 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
2054 transceiver->internal()->set_current_direction(media_desc->direction());
2055 }
2056 if (content->rejected && !transceiver->stopped()) {
Steve Anton3d954a62018-04-02 18:27:232057 RTC_LOG(LS_INFO) << "Stopping transceiver for MID=" << content->name
2058 << " since the media section was rejected.";
Steve Antondcc3c022017-12-23 00:02:542059 transceiver->Stop();
2060 }
2061 }
2062 } else {
Zhi Huange830e682018-03-30 17:48:352063 // Media channels will be created only when offer is set. These may use new
2064 // transports just created by PushdownTransportDescription.
Steve Antondcc3c022017-12-23 00:02:542065 if (type == SdpType::kOffer) {
2066 // TODO(bugs.webrtc.org/4676) - Handle CreateChannel failure, as new local
2067 // description is applied. Restore back to old description.
2068 RTCError error = CreateChannels(*local_description()->description());
2069 if (!error.ok()) {
2070 return error;
2071 }
2072 }
Steve Antondcc3c022017-12-23 00:02:542073 // Remove unused channels if MediaContentDescription is rejected.
2074 RemoveUnusedChannels(local_description()->description());
2075 }
Steve Anton8a006912017-12-04 23:25:562076
Zhi Huange830e682018-03-30 17:48:352077 error = UpdateSessionState(type, cricket::CS_LOCAL,
2078 local_description()->description());
Steve Anton8a006912017-12-04 23:25:562079 if (!error.ok()) {
2080 return error;
2081 }
Steve Antondcc3c022017-12-23 00:02:542082
Steve Anton8a006912017-12-04 23:25:562083 if (remote_description()) {
2084 // Now that we have a local description, we can push down remote candidates.
2085 UseCandidatesInSessionDescription(remote_description());
2086 }
2087
2088 pending_ice_restarts_.clear();
2089 if (session_error() != SessionError::kNone) {
2090 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
2091 }
2092
deadbeefab9b2d12015-10-14 18:33:112093 // If setting the description decided our SSL role, allocate any necessary
2094 // SCTP sids.
2095 rtc::SSLRole role;
Steve Anton75737c02017-11-06 18:37:172096 if (data_channel_type() == cricket::DCT_SCTP && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 18:33:112097 AllocateSctpSids(role);
2098 }
2099
Steve Antond3679212018-01-18 01:41:022100 if (IsUnifiedPlan()) {
2101 for (auto transceiver : transceivers_) {
2102 const ContentInfo* content =
2103 FindMediaSectionForTransceiver(transceiver, local_description());
2104 if (!content) {
2105 continue;
2106 }
Steve Anton74255ff2018-01-25 02:32:572107 const auto& streams = content->media_description()->streams();
2108 if (!content->rejected && !streams.empty()) {
Steve Antond3679212018-01-18 01:41:022109 transceiver->internal()->sender_internal()->set_stream_ids(
Seth Hampson845e8782018-03-02 19:34:102110 streams[0].stream_ids());
Steve Antond3679212018-01-18 01:41:022111 transceiver->internal()->sender_internal()->SetSsrc(
Steve Anton74255ff2018-01-25 02:32:572112 streams[0].first_ssrc());
Steve Antond3679212018-01-18 01:41:022113 }
2114 }
2115 } else {
2116 // Plan B semantics.
2117
Steve Antondcc3c022017-12-23 00:02:542118 // Update state and SSRC of local MediaStreams and DataChannels based on the
2119 // local session description.
2120 const cricket::ContentInfo* audio_content =
2121 GetFirstAudioContent(local_description()->description());
2122 if (audio_content) {
2123 if (audio_content->rejected) {
2124 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
2125 } else {
2126 const cricket::AudioContentDescription* audio_desc =
2127 audio_content->media_description()->as_audio();
2128 UpdateLocalSenders(audio_desc->streams(), audio_desc->type());
2129 }
deadbeeffaac4972015-11-12 23:33:072130 }
deadbeefab9b2d12015-10-14 18:33:112131
Steve Antondcc3c022017-12-23 00:02:542132 const cricket::ContentInfo* video_content =
2133 GetFirstVideoContent(local_description()->description());
2134 if (video_content) {
2135 if (video_content->rejected) {
2136 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
2137 } else {
2138 const cricket::VideoContentDescription* video_desc =
2139 video_content->media_description()->as_video();
2140 UpdateLocalSenders(video_desc->streams(), video_desc->type());
2141 }
deadbeeffaac4972015-11-12 23:33:072142 }
deadbeefab9b2d12015-10-14 18:33:112143 }
2144
2145 const cricket::ContentInfo* data_content =
Henrik Boströmfdb92012017-11-09 18:55:442146 GetFirstDataContent(local_description()->description());
deadbeefab9b2d12015-10-14 18:33:112147 if (data_content) {
2148 const cricket::DataContentDescription* data_desc =
Steve Antonb1c1de12017-12-21 23:14:302149 data_content->media_description()->as_data();
deadbeefab9b2d12015-10-14 18:33:112150 if (rtc::starts_with(data_desc->protocol().data(),
2151 cricket::kMediaProtocolRtpPrefix)) {
2152 UpdateLocalRtpDataChannels(data_desc->streams());
2153 }
2154 }
2155
Steve Anton8a006912017-12-04 23:25:562156 return RTCError::OK();
henrike@webrtc.org28e20752013-07-10 00:45:362157}
2158
2159void PeerConnection::SetRemoteDescription(
Henrik Boströma4ecf552017-11-23 14:17:072160 SetSessionDescriptionObserver* observer,
2161 SessionDescriptionInterface* desc) {
Henrik Boström31638672017-11-23 16:48:322162 SetRemoteDescription(
2163 std::unique_ptr<SessionDescriptionInterface>(desc),
2164 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface>(
2165 new SetRemoteDescriptionObserverAdapter(this, observer)));
2166}
2167
2168void PeerConnection::SetRemoteDescription(
2169 std::unique_ptr<SessionDescriptionInterface> desc,
2170 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface> observer) {
Peter Boström1a9d6152015-12-08 21:15:172171 TRACE_EVENT0("webrtc", "PeerConnection::SetRemoteDescription");
Steve Anton8a006912017-12-04 23:25:562172
nisse7ce109a2017-01-31 08:57:562173 if (!observer) {
Mirko Bonadei675513b2017-11-09 10:09:252174 RTC_LOG(LS_ERROR) << "SetRemoteDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:362175 return;
2176 }
Steve Anton8a006912017-12-04 23:25:562177
henrike@webrtc.org28e20752013-07-10 00:45:362178 if (!desc) {
Henrik Boström31638672017-11-23 16:48:322179 observer->OnSetRemoteDescriptionComplete(RTCError(
Steve Anton8a006912017-12-04 23:25:562180 RTCErrorType::INVALID_PARAMETER, "SessionDescription is NULL."));
henrike@webrtc.org28e20752013-07-10 00:45:362181 return;
2182 }
Steve Anton8d3444d2017-10-20 22:30:512183
Steve Anton80dd7b52018-02-17 01:08:422184 // If a session error has occurred the PeerConnection is in a possibly
2185 // inconsistent state so fail right away.
2186 if (session_error() != SessionError::kNone) {
2187 std::string error_message = GetSessionErrorMsg();
2188 RTC_LOG(LS_ERROR) << "SetRemoteDescription: " << error_message;
2189 observer->OnSetRemoteDescriptionComplete(
2190 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
2191 return;
2192 }
Steve Anton71439a62018-02-15 19:53:062193
Steve Antonba42e992018-04-09 21:10:012194 if (desc->GetType() == SdpType::kOffer) {
2195 // Report to UMA the format of the received offer.
2196 ReportSdpFormatReceived(*desc);
2197 }
2198
Steve Anton80dd7b52018-02-17 01:08:422199 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_REMOTE);
Steve Anton71439a62018-02-15 19:53:062200 if (!error.ok()) {
Steve Anton80dd7b52018-02-17 01:08:422201 std::string error_message = GetSetDescriptionErrorMessage(
2202 cricket::CS_REMOTE, desc->GetType(), error);
2203 RTC_LOG(LS_ERROR) << error_message;
Steve Anton71439a62018-02-15 19:53:062204 observer->OnSetRemoteDescriptionComplete(
2205 RTCError(error.type(), std::move(error_message)));
2206 return;
2207 }
Steve Anton71439a62018-02-15 19:53:062208
Steve Anton80dd7b52018-02-17 01:08:422209 // Grab the description type before moving ownership to
2210 // ApplyRemoteDescription, which may destroy it before returning.
2211 const SdpType type = desc->GetType();
2212
2213 error = ApplyRemoteDescription(std::move(desc));
2214 // |desc| may be destroyed at this point.
2215
2216 if (!error.ok()) {
2217 // If ApplyRemoteDescription fails, the PeerConnection could be in an
2218 // inconsistent state, so act conservatively here and set the session error
2219 // so that future calls to SetLocalDescription/SetRemoteDescription fail.
2220 SetSessionError(SessionError::kContent, error.message());
2221 std::string error_message =
2222 GetSetDescriptionErrorMessage(cricket::CS_REMOTE, type, error);
2223 RTC_LOG(LS_ERROR) << error_message;
2224 observer->OnSetRemoteDescriptionComplete(
2225 RTCError(error.type(), std::move(error_message)));
2226 return;
2227 }
2228 RTC_DCHECK(remote_description());
2229
2230 if (type == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 23:25:562231 // TODO(deadbeef): We already had to hop to the network thread for
2232 // MaybeStartGathering...
2233 network_thread()->Invoke<void>(
2234 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
2235 port_allocator_.get()));
Harald Alvestrand5dbb5862018-02-13 22:48:002236 // Make UMA notes about what was agreed to.
Steve Anton0ffaaa22018-02-23 18:31:302237 ReportNegotiatedSdpSemantics(*remote_description());
Steve Anton8a006912017-12-04 23:25:562238 }
2239
2240 observer->OnSetRemoteDescriptionComplete(RTCError::OK());
2241}
2242
2243RTCError PeerConnection::ApplyRemoteDescription(
2244 std::unique_ptr<SessionDescriptionInterface> desc) {
2245 RTC_DCHECK_RUN_ON(signaling_thread());
2246 RTC_DCHECK(desc);
2247
henrike@webrtc.org28e20752013-07-10 00:45:362248 // Update stats here so that we have the most recent stats for tracks and
2249 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:262250 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 23:25:562251
Steve Antondcc3c022017-12-23 00:02:542252 // Take a reference to the old remote description since it's used below to
2253 // compare against the new remote description. When setting the new remote
2254 // description, grab ownership of the replaced session description in case it
2255 // is the same as |old_remote_description|, to keep it alive for the duration
2256 // of the method.
Steve Anton8a006912017-12-04 23:25:562257 const SessionDescriptionInterface* old_remote_description =
2258 remote_description();
Steve Anton8a006912017-12-04 23:25:562259 std::unique_ptr<SessionDescriptionInterface> replaced_remote_description;
Steve Anton3828c062017-12-06 18:34:512260 SdpType type = desc->GetType();
2261 if (type == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 23:25:562262 replaced_remote_description = pending_remote_description_
2263 ? std::move(pending_remote_description_)
2264 : std::move(current_remote_description_);
2265 current_remote_description_ = std::move(desc);
2266 pending_remote_description_ = nullptr;
2267 current_local_description_ = std::move(pending_local_description_);
2268 } else {
2269 replaced_remote_description = std::move(pending_remote_description_);
2270 pending_remote_description_ = std::move(desc);
henrike@webrtc.org28e20752013-07-10 00:45:362271 }
Steve Anton8a006912017-12-04 23:25:562272 // The session description to apply now must be accessed by
2273 // |remote_description()|.
Henrik Boströmfdb92012017-11-09 18:55:442274 RTC_DCHECK(remote_description());
henrike@webrtc.org28e20752013-07-10 00:45:362275
Zhi Huange830e682018-03-30 17:48:352276 RTCError error = PushdownTransportDescription(cricket::CS_REMOTE, type);
2277 if (!error.ok()) {
2278 return error;
2279 }
Steve Anton8a006912017-12-04 23:25:562280 // Transport and Media channels will be created only when offer is set.
Steve Antondcc3c022017-12-23 00:02:542281 if (IsUnifiedPlan()) {
2282 RTCError error = UpdateTransceiversAndDataChannels(
Seth Hampsonae8a90a2018-02-13 23:33:482283 cricket::CS_REMOTE, *remote_description(), local_description(),
2284 old_remote_description);
Steve Anton8a006912017-12-04 23:25:562285 if (!error.ok()) {
2286 return error;
2287 }
Steve Antondcc3c022017-12-23 00:02:542288 } else {
Zhi Huange830e682018-03-30 17:48:352289 // Media channels will be created only when offer is set. These may use new
2290 // transports just created by PushdownTransportDescription.
Steve Antondcc3c022017-12-23 00:02:542291 if (type == SdpType::kOffer) {
Zhi Huange830e682018-03-30 17:48:352292 // TODO(mallinath) - Handle CreateChannel failure, as new local
Steve Antondcc3c022017-12-23 00:02:542293 // description is applied. Restore back to old description.
2294 RTCError error = CreateChannels(*remote_description()->description());
2295 if (!error.ok()) {
2296 return error;
2297 }
2298 }
Steve Antondcc3c022017-12-23 00:02:542299 // Remove unused channels if MediaContentDescription is rejected.
2300 RemoveUnusedChannels(remote_description()->description());
2301 }
Steve Anton8a006912017-12-04 23:25:562302
Zhi Huange830e682018-03-30 17:48:352303 // NOTE: Candidates allocation will be initiated only when
2304 // SetLocalDescription is called.
2305 error = UpdateSessionState(type, cricket::CS_REMOTE,
2306 remote_description()->description());
Steve Anton8a006912017-12-04 23:25:562307 if (!error.ok()) {
2308 return error;
2309 }
2310
2311 if (local_description() &&
2312 !UseCandidatesInSessionDescription(remote_description())) {
2313 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidCandidates);
2314 }
2315
2316 if (old_remote_description) {
2317 for (const cricket::ContentInfo& content :
2318 old_remote_description->description()->contents()) {
2319 // Check if this new SessionDescription contains new ICE ufrag and
2320 // password that indicates the remote peer requests an ICE restart.
2321 // TODO(deadbeef): When we start storing both the current and pending
2322 // remote description, this should reset pending_ice_restarts and compare
2323 // against the current description.
2324 if (CheckForRemoteIceRestart(old_remote_description, remote_description(),
2325 content.name)) {
Steve Anton3828c062017-12-06 18:34:512326 if (type == SdpType::kOffer) {
Steve Anton8a006912017-12-04 23:25:562327 pending_ice_restarts_.insert(content.name);
2328 }
2329 } else {
2330 // We retain all received candidates only if ICE is not restarted.
2331 // When ICE is restarted, all previous candidates belong to an old
2332 // generation and should not be kept.
2333 // TODO(deadbeef): This goes against the W3C spec which says the remote
2334 // description should only contain candidates from the last set remote
2335 // description plus any candidates added since then. We should remove
2336 // this once we're sure it won't break anything.
2337 WebRtcSessionDescriptionFactory::CopyCandidatesFromSessionDescription(
2338 old_remote_description, content.name, mutable_remote_description());
2339 }
2340 }
2341 }
2342
2343 if (session_error() != SessionError::kNone) {
2344 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
2345 }
2346
2347 // Set the the ICE connection state to connecting since the connection may
2348 // become writable with peer reflexive candidates before any remote candidate
2349 // is signaled.
2350 // TODO(pthatcher): This is a short-term solution for crbug/446908. A real fix
2351 // is to have a new signal the indicates a change in checking state from the
2352 // transport and expose a new checking() member from transport that can be
2353 // read to determine the current checking state. The existing SignalConnecting
2354 // actually means "gathering candidates", so cannot be be used here.
Steve Antona3a92c22017-12-07 18:27:412355 if (remote_description()->GetType() != SdpType::kOffer &&
Steve Anton8a006912017-12-04 23:25:562356 ice_connection_state() == PeerConnectionInterface::kIceConnectionNew) {
2357 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
2358 }
2359
deadbeefab9b2d12015-10-14 18:33:112360 // If setting the description decided our SSL role, allocate any necessary
2361 // SCTP sids.
2362 rtc::SSLRole role;
Steve Anton75737c02017-11-06 18:37:172363 if (data_channel_type() == cricket::DCT_SCTP && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 18:33:112364 AllocateSctpSids(role);
2365 }
2366
Steve Antondcc3c022017-12-23 00:02:542367 if (IsUnifiedPlan()) {
Steve Anton8b815cd2018-02-17 00:14:422368 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
2369 receiving_transceivers;
Steve Antonc49bcd92018-02-14 22:28:132370 std::vector<rtc::scoped_refptr<MediaStreamInterface>> added_streams;
Steve Antondcc3c022017-12-23 00:02:542371 for (auto transceiver : transceivers_) {
2372 const ContentInfo* content =
2373 FindMediaSectionForTransceiver(transceiver, remote_description());
2374 if (!content) {
2375 continue;
2376 }
2377 const MediaContentDescription* media_desc = content->media_description();
2378 RtpTransceiverDirection local_direction =
2379 RtpTransceiverDirectionReversed(media_desc->direction());
2380 // From the WebRTC specification, steps 2.2.8.5/6 of section 4.4.1.6 "Set
2381 // the RTCSessionDescription: If direction is sendrecv or recvonly, and
2382 // transceiver's current direction is neither sendrecv nor recvonly,
2383 // process the addition of a remote track for the media description.
Seth Hampson5b4f0752018-04-02 23:31:362384 std::vector<std::string> stream_ids;
Seth Hampson2f0d7022018-02-20 19:54:422385 if (!media_desc->streams().empty()) {
Seth Hampson5897a6e2018-04-03 18:16:332386 // The remote description has signaled the stream IDs.
2387 stream_ids = media_desc->streams()[0].stream_ids();
Seth Hampson2f0d7022018-02-20 19:54:422388 }
Steve Antondcc3c022017-12-23 00:02:542389 if (RtpTransceiverDirectionHasRecv(local_direction) &&
2390 (!transceiver->current_direction() ||
2391 !RtpTransceiverDirectionHasRecv(
Seth Hampson2f0d7022018-02-20 19:54:422392 *transceiver->current_direction()))) {
Steve Anton3d954a62018-04-02 18:27:232393 RTC_LOG(LS_INFO) << "Processing the addition of a new track for MID="
Seth Hampson5b4f0752018-04-02 23:31:362394 << content->name << " (added to "
2395 << GetStreamIdsString(stream_ids) << ").";
2396
2397 std::vector<rtc::scoped_refptr<MediaStreamInterface>> media_streams;
2398 for (const std::string& stream_id : stream_ids) {
2399 rtc::scoped_refptr<MediaStreamInterface> stream =
2400 remote_streams_->find(stream_id);
2401 if (!stream) {
2402 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
2403 MediaStream::Create(stream_id));
2404 remote_streams_->AddStream(stream);
2405 added_streams.push_back(stream);
2406 }
2407 media_streams.push_back(stream);
Steve Antonef65ef12018-01-11 01:15:202408 }
Seth Hampson5b4f0752018-04-02 23:31:362409 transceiver->internal()->receiver_internal()->SetStreams(media_streams);
Steve Anton8b815cd2018-02-17 00:14:422410 receiving_transceivers.push_back(transceiver);
Steve Antondcc3c022017-12-23 00:02:542411 }
2412 // If direction is sendonly or inactive, and transceiver's current
2413 // direction is neither sendonly nor inactive, process the removal of a
2414 // remote track for the media description.
2415 if (!RtpTransceiverDirectionHasRecv(local_direction) &&
Steve Antonef65ef12018-01-11 01:15:202416 (transceiver->current_direction() &&
Steve Antondcc3c022017-12-23 00:02:542417 RtpTransceiverDirectionHasRecv(*transceiver->current_direction()))) {
Steve Anton3d954a62018-04-02 18:27:232418 RTC_LOG(LS_INFO) << "Processing the removal of a track for MID="
2419 << content->name;
Steve Antonef65ef12018-01-11 01:15:202420 transceiver->internal()->receiver_internal()->SetStreams({});
Steve Antondcc3c022017-12-23 00:02:542421 }
2422 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
2423 transceiver->internal()->set_current_direction(local_direction);
2424 }
2425 if (content->rejected && !transceiver->stopped()) {
Steve Anton3d954a62018-04-02 18:27:232426 RTC_LOG(LS_INFO) << "Stopping transceiver for MID=" << content->name
2427 << " since the media section was rejected.";
Steve Antondcc3c022017-12-23 00:02:542428 transceiver->Stop();
2429 }
Seth Hampson2f0d7022018-02-20 19:54:422430 if (!content->rejected &&
2431 RtpTransceiverDirectionHasRecv(local_direction)) {
2432 // Set ssrc to 0 in the case of an unsignalled ssrc.
2433 uint32_t ssrc = 0;
Seth Hampson5897a6e2018-04-03 18:16:332434 if (!media_desc->streams().empty() &&
2435 media_desc->streams()[0].has_ssrcs()) {
Seth Hampson2f0d7022018-02-20 19:54:422436 ssrc = media_desc->streams()[0].first_ssrc();
2437 }
2438 transceiver->internal()->receiver_internal()->SetupMediaChannel(ssrc);
Steve Antond3679212018-01-18 01:41:022439 }
Steve Antondcc3c022017-12-23 00:02:542440 }
Steve Antonc49bcd92018-02-14 22:28:132441 // Once all processing has finished, fire off callbacks.
Steve Anton8b815cd2018-02-17 00:14:422442 for (auto transceiver : receiving_transceivers) {
Steve Anton6e221372018-02-20 20:59:162443 stats_->AddTrack(transceiver->receiver()->track());
Steve Anton8b815cd2018-02-17 00:14:422444 observer_->OnTrack(transceiver);
2445 observer_->OnAddTrack(transceiver->receiver(),
2446 transceiver->receiver()->streams());
Steve Antonef65ef12018-01-11 01:15:202447 }
Steve Antonc49bcd92018-02-14 22:28:132448 for (auto stream : added_streams) {
2449 observer_->OnAddStream(stream);
2450 }
Steve Antondcc3c022017-12-23 00:02:542451 }
2452
Henrik Boströmfdb92012017-11-09 18:55:442453 const cricket::ContentInfo* audio_content =
2454 GetFirstAudioContent(remote_description()->description());
2455 const cricket::ContentInfo* video_content =
2456 GetFirstVideoContent(remote_description()->description());
deadbeefbda7e0b2015-12-09 01:13:402457 const cricket::AudioContentDescription* audio_desc =
Henrik Boströmfdb92012017-11-09 18:55:442458 GetFirstAudioContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-09 01:13:402459 const cricket::VideoContentDescription* video_desc =
Henrik Boströmfdb92012017-11-09 18:55:442460 GetFirstVideoContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-09 01:13:402461 const cricket::DataContentDescription* data_desc =
Henrik Boströmfdb92012017-11-09 18:55:442462 GetFirstDataContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-09 01:13:402463
2464 // Check if the descriptions include streams, just in case the peer supports
2465 // MSID, but doesn't indicate so with "a=msid-semantic".
Henrik Boströmfdb92012017-11-09 18:55:442466 if (remote_description()->description()->msid_supported() ||
deadbeefbda7e0b2015-12-09 01:13:402467 (audio_desc && !audio_desc->streams().empty()) ||
2468 (video_desc && !video_desc->streams().empty())) {
2469 remote_peer_supports_msid_ = true;
2470 }
deadbeefab9b2d12015-10-14 18:33:112471
2472 // We wait to signal new streams until we finish processing the description,
2473 // since only at that point will new streams have all their tracks.
2474 rtc::scoped_refptr<StreamCollection> new_streams(StreamCollection::Create());
2475
Steve Antondcc3c022017-12-23 00:02:542476 if (!IsUnifiedPlan()) {
2477 // TODO(steveanton): When removing RTP senders/receivers in response to a
2478 // rejected media section, there is some cleanup logic that expects the
2479 // voice/ video channel to still be set. But in this method the voice/video
2480 // channel would have been destroyed by the SetRemoteDescription caller
2481 // above so the cleanup that relies on them fails to run. The RemoveSenders
2482 // calls should be moved to right before the DestroyChannel calls to fix
2483 // this.
Steve Anton8d3444d2017-10-20 22:30:512484
Steve Antondcc3c022017-12-23 00:02:542485 // Find all audio rtp streams and create corresponding remote AudioTracks
2486 // and MediaStreams.
2487 if (audio_content) {
2488 if (audio_content->rejected) {
2489 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
2490 } else {
2491 bool default_audio_track_needed =
2492 !remote_peer_supports_msid_ &&
2493 RtpTransceiverDirectionHasSend(audio_desc->direction());
2494 UpdateRemoteSendersList(GetActiveStreams(audio_desc),
2495 default_audio_track_needed, audio_desc->type(),
2496 new_streams);
2497 }
deadbeeffaac4972015-11-12 23:33:072498 }
deadbeefab9b2d12015-10-14 18:33:112499
Steve Antondcc3c022017-12-23 00:02:542500 // Find all video rtp streams and create corresponding remote VideoTracks
2501 // and MediaStreams.
2502 if (video_content) {
2503 if (video_content->rejected) {
2504 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
2505 } else {
2506 bool default_video_track_needed =
2507 !remote_peer_supports_msid_ &&
2508 RtpTransceiverDirectionHasSend(video_desc->direction());
2509 UpdateRemoteSendersList(GetActiveStreams(video_desc),
2510 default_video_track_needed, video_desc->type(),
2511 new_streams);
2512 }
deadbeeffaac4972015-11-12 23:33:072513 }
deadbeefab9b2d12015-10-14 18:33:112514
Steve Antondcc3c022017-12-23 00:02:542515 // Update the DataChannels with the information from the remote peer.
2516 if (data_desc) {
2517 if (rtc::starts_with(data_desc->protocol().data(),
2518 cricket::kMediaProtocolRtpPrefix)) {
2519 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
2520 }
deadbeefab9b2d12015-10-14 18:33:112521 }
deadbeefab9b2d12015-10-14 18:33:112522
Steve Antondcc3c022017-12-23 00:02:542523 // Iterate new_streams and notify the observer about new MediaStreams.
2524 for (size_t i = 0; i < new_streams->count(); ++i) {
2525 MediaStreamInterface* new_stream = new_streams->at(i);
2526 stats_->AddStream(new_stream);
2527 observer_->OnAddStream(
2528 rtc::scoped_refptr<MediaStreamInterface>(new_stream));
2529 }
deadbeefab9b2d12015-10-14 18:33:112530
Steve Antondcc3c022017-12-23 00:02:542531 UpdateEndedRemoteMediaStreams();
2532 }
deadbeefab9b2d12015-10-14 18:33:112533
Steve Anton8a006912017-12-04 23:25:562534 return RTCError::OK();
deadbeeffc648b62015-10-13 23:42:332535}
2536
Steve Antondcc3c022017-12-23 00:02:542537RTCError PeerConnection::UpdateTransceiversAndDataChannels(
2538 cricket::ContentSource source,
Seth Hampsonae8a90a2018-02-13 23:33:482539 const SessionDescriptionInterface& new_session,
2540 const SessionDescriptionInterface* old_local_description,
2541 const SessionDescriptionInterface* old_remote_description) {
Steve Antondcc3c022017-12-23 00:02:542542 RTC_DCHECK(IsUnifiedPlan());
2543
Steve Anton7464fca2018-01-19 19:10:372544 const cricket::ContentGroup* bundle_group = nullptr;
2545 if (new_session.GetType() == SdpType::kOffer) {
2546 auto bundle_group_or_error =
2547 GetEarlyBundleGroup(*new_session.description());
2548 if (!bundle_group_or_error.ok()) {
2549 return bundle_group_or_error.MoveError();
2550 }
2551 bundle_group = bundle_group_or_error.MoveValue();
Steve Antondcc3c022017-12-23 00:02:542552 }
Steve Antondcc3c022017-12-23 00:02:542553
Steve Antondcc3c022017-12-23 00:02:542554 const ContentInfos& new_contents = new_session.description()->contents();
Steve Antondcc3c022017-12-23 00:02:542555 for (size_t i = 0; i < new_contents.size(); ++i) {
2556 const cricket::ContentInfo& new_content = new_contents[i];
Steve Antondcc3c022017-12-23 00:02:542557 cricket::MediaType media_type = new_content.media_description()->type();
2558 seen_mids_.insert(new_content.name);
2559 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
2560 media_type == cricket::MEDIA_TYPE_VIDEO) {
Seth Hampsonae8a90a2018-02-13 23:33:482561 const cricket::ContentInfo* old_local_content = nullptr;
2562 if (old_local_description &&
2563 i < old_local_description->description()->contents().size()) {
2564 old_local_content =
2565 &old_local_description->description()->contents()[i];
2566 }
2567 const cricket::ContentInfo* old_remote_content = nullptr;
2568 if (old_remote_description &&
2569 i < old_remote_description->description()->contents().size()) {
2570 old_remote_content =
2571 &old_remote_description->description()->contents()[i];
2572 }
Steve Antondcc3c022017-12-23 00:02:542573 auto transceiver_or_error =
Seth Hampsonae8a90a2018-02-13 23:33:482574 AssociateTransceiver(source, new_session.GetType(), i, new_content,
2575 old_local_content, old_remote_content);
Steve Antondcc3c022017-12-23 00:02:542576 if (!transceiver_or_error.ok()) {
2577 return transceiver_or_error.MoveError();
2578 }
2579 auto transceiver = transceiver_or_error.MoveValue();
Steve Antondcc3c022017-12-23 00:02:542580 RTCError error =
2581 UpdateTransceiverChannel(transceiver, new_content, bundle_group);
2582 if (!error.ok()) {
2583 return error;
2584 }
2585 } else if (media_type == cricket::MEDIA_TYPE_DATA) {
Steve Antonfa2260d2017-12-29 00:38:232586 if (GetDataMid() && new_content.name != *GetDataMid()) {
2587 // Ignore all but the first data section.
Steve Anton3d954a62018-04-02 18:27:232588 RTC_LOG(LS_INFO) << "Ignoring data media section with MID="
2589 << new_content.name;
Steve Antonfa2260d2017-12-29 00:38:232590 continue;
2591 }
2592 RTCError error = UpdateDataChannel(source, new_content, bundle_group);
2593 if (!error.ok()) {
2594 return error;
2595 }
Steve Antondcc3c022017-12-23 00:02:542596 } else {
2597 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
2598 "Unknown section type.");
2599 }
2600 }
2601
2602 return RTCError::OK();
2603}
2604
2605RTCError PeerConnection::UpdateTransceiverChannel(
2606 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2607 transceiver,
2608 const cricket::ContentInfo& content,
2609 const cricket::ContentGroup* bundle_group) {
2610 RTC_DCHECK(IsUnifiedPlan());
2611 RTC_DCHECK(transceiver);
2612 cricket::BaseChannel* channel = transceiver->internal()->channel();
2613 if (content.rejected) {
2614 if (channel) {
2615 transceiver->internal()->SetChannel(nullptr);
2616 DestroyBaseChannel(channel);
2617 }
2618 } else {
2619 if (!channel) {
Steve Anton69470252018-02-09 19:43:082620 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Zhi Huange830e682018-03-30 17:48:352621 channel = CreateVoiceChannel(content.name);
Steve Antondcc3c022017-12-23 00:02:542622 } else {
Steve Anton69470252018-02-09 19:43:082623 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, transceiver->media_type());
Zhi Huange830e682018-03-30 17:48:352624 channel = CreateVideoChannel(content.name);
Steve Antondcc3c022017-12-23 00:02:542625 }
2626 if (!channel) {
2627 LOG_AND_RETURN_ERROR(
2628 RTCErrorType::INTERNAL_ERROR,
2629 "Failed to create channel for mid=" + content.name);
2630 }
2631 transceiver->internal()->SetChannel(channel);
2632 }
2633 }
2634 return RTCError::OK();
2635}
2636
Steve Antonfa2260d2017-12-29 00:38:232637RTCError PeerConnection::UpdateDataChannel(
2638 cricket::ContentSource source,
2639 const cricket::ContentInfo& content,
2640 const cricket::ContentGroup* bundle_group) {
2641 if (data_channel_type_ == cricket::DCT_NONE) {
Steve Antondbf9d032018-01-19 23:23:402642 // If data channels are disabled, ignore this media section. CreateAnswer
2643 // will take care of rejecting it.
2644 return RTCError::OK();
Steve Antonfa2260d2017-12-29 00:38:232645 }
2646 if (content.rejected) {
2647 DestroyDataChannel();
2648 } else {
2649 if (!rtp_data_channel_ && !sctp_transport_) {
Zhi Huange830e682018-03-30 17:48:352650 if (!CreateDataChannel(content.name)) {
Steve Antonfa2260d2017-12-29 00:38:232651 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
2652 "Failed to create data channel.");
2653 }
2654 }
2655 if (source == cricket::CS_REMOTE) {
2656 const MediaContentDescription* data_desc = content.media_description();
2657 if (data_desc && cricket::IsRtpProtocol(data_desc->protocol())) {
2658 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
2659 }
2660 }
2661 }
2662 return RTCError::OK();
2663}
2664
Steve Antondcc3c022017-12-23 00:02:542665RTCErrorOr<rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
2666PeerConnection::AssociateTransceiver(cricket::ContentSource source,
Seth Hampsonae8a90a2018-02-13 23:33:482667 SdpType type,
Steve Antondcc3c022017-12-23 00:02:542668 size_t mline_index,
2669 const ContentInfo& content,
Seth Hampsonae8a90a2018-02-13 23:33:482670 const ContentInfo* old_local_content,
2671 const ContentInfo* old_remote_content) {
Steve Antondcc3c022017-12-23 00:02:542672 RTC_DCHECK(IsUnifiedPlan());
Seth Hampsonae8a90a2018-02-13 23:33:482673 // If this is an offer then the m= section might be recycled. If the m=
2674 // section is being recycled (defined as: rejected in the current local or
2675 // remote description and not rejected in new description), dissociate the
2676 // currently associated RtpTransceiver by setting its mid property to null,
2677 // and discard the mapping between the transceiver and its m= section index.
2678 if (IsMediaSectionBeingRecycled(type, content, old_local_content,
2679 old_remote_content)) {
2680 // We want to dissociate the transceiver that has the rejected mid.
2681 const std::string& old_mid =
2682 (old_local_content && old_local_content->rejected)
2683 ? old_local_content->name
2684 : old_remote_content->name;
2685 auto old_transceiver = GetAssociatedTransceiver(old_mid);
Steve Antondcc3c022017-12-23 00:02:542686 if (old_transceiver) {
Steve Anton3d954a62018-04-02 18:27:232687 RTC_LOG(LS_INFO) << "Dissociating transceiver for MID=" << old_mid
2688 << " since the media section is being recycled.";
Steve Antondcc3c022017-12-23 00:02:542689 old_transceiver->internal()->set_mid(rtc::nullopt);
2690 old_transceiver->internal()->set_mline_index(rtc::nullopt);
2691 }
2692 }
2693 const MediaContentDescription* media_desc = content.media_description();
2694 auto transceiver = GetAssociatedTransceiver(content.name);
2695 if (source == cricket::CS_LOCAL) {
2696 // Find the RtpTransceiver that corresponds to this m= section, using the
2697 // mapping between transceivers and m= section indices established when
2698 // creating the offer.
2699 if (!transceiver) {
2700 transceiver = GetTransceiverByMLineIndex(mline_index);
2701 }
2702 if (!transceiver) {
2703 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2704 "Unknown transceiver");
2705 }
2706 } else {
2707 RTC_DCHECK_EQ(source, cricket::CS_REMOTE);
2708 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers
2709 // of the same type...
2710 if (!transceiver &&
2711 RtpTransceiverDirectionHasRecv(media_desc->direction())) {
2712 transceiver = FindAvailableTransceiverToReceive(media_desc->type());
2713 }
2714 // If no RtpTransceiver was found in the previous step, create one with a
2715 // recvonly direction.
2716 if (!transceiver) {
Steve Anton3d954a62018-04-02 18:27:232717 RTC_LOG(LS_INFO) << "Adding "
2718 << cricket::MediaTypeToString(media_desc->type())
2719 << " transceiver for MID=" << content.name
2720 << " at i=" << mline_index
2721 << " in response to the remote description.";
Steve Anton02ee47c2018-01-11 00:26:062722 auto sender =
2723 CreateSender(media_desc->type(), nullptr, {rtc::CreateRandomUuid()});
Steve Anton5f94aa22018-02-01 18:58:302724 std::string receiver_id;
2725 if (!media_desc->streams().empty()) {
2726 receiver_id = media_desc->streams()[0].id;
2727 } else {
2728 receiver_id = rtc::CreateRandomUuid();
2729 }
2730 auto receiver = CreateReceiver(media_desc->type(), receiver_id);
Steve Anton02ee47c2018-01-11 00:26:062731 transceiver = CreateAndAddTransceiver(sender, receiver);
Steve Antondcc3c022017-12-23 00:02:542732 transceiver->internal()->set_direction(
2733 RtpTransceiverDirection::kRecvOnly);
2734 }
2735 }
2736 RTC_DCHECK(transceiver);
Steve Anton69470252018-02-09 19:43:082737 if (transceiver->media_type() != media_desc->type()) {
Steve Antondcc3c022017-12-23 00:02:542738 LOG_AND_RETURN_ERROR(
2739 RTCErrorType::INVALID_PARAMETER,
2740 "Transceiver type does not match media description type.");
2741 }
2742 // Associate the found or created RtpTransceiver with the m= section by
2743 // setting the value of the RtpTransceiver's mid property to the MID of the m=
2744 // section, and establish a mapping between the transceiver and the index of
2745 // the m= section.
2746 transceiver->internal()->set_mid(content.name);
2747 transceiver->internal()->set_mline_index(mline_index);
2748 return std::move(transceiver);
2749}
2750
2751rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2752PeerConnection::GetAssociatedTransceiver(const std::string& mid) const {
2753 RTC_DCHECK(IsUnifiedPlan());
2754 for (auto transceiver : transceivers_) {
2755 if (transceiver->mid() == mid) {
2756 return transceiver;
2757 }
2758 }
2759 return nullptr;
2760}
2761
2762rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2763PeerConnection::GetTransceiverByMLineIndex(size_t mline_index) const {
2764 RTC_DCHECK(IsUnifiedPlan());
2765 for (auto transceiver : transceivers_) {
2766 if (transceiver->internal()->mline_index() == mline_index) {
2767 return transceiver;
2768 }
2769 }
2770 return nullptr;
2771}
2772
2773rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2774PeerConnection::FindAvailableTransceiverToReceive(
2775 cricket::MediaType media_type) const {
2776 RTC_DCHECK(IsUnifiedPlan());
2777 // From JSEP section 5.10 (Applying a Remote Description):
2778 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers of
2779 // the same type that were added to the PeerConnection by addTrack and are not
2780 // associated with any m= section and are not stopped, find the first such
2781 // RtpTransceiver.
2782 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 19:43:082783 if (transceiver->media_type() == media_type &&
Steve Antondcc3c022017-12-23 00:02:542784 transceiver->internal()->created_by_addtrack() && !transceiver->mid() &&
2785 !transceiver->stopped()) {
2786 return transceiver;
2787 }
2788 }
2789 return nullptr;
2790}
2791
Steve Antoned10bd92017-12-05 18:52:592792const cricket::ContentInfo* PeerConnection::FindMediaSectionForTransceiver(
2793 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2794 transceiver,
2795 const SessionDescriptionInterface* sdesc) const {
2796 RTC_DCHECK(transceiver);
2797 RTC_DCHECK(sdesc);
2798 if (IsUnifiedPlan()) {
2799 if (!transceiver->internal()->mid()) {
2800 // This transceiver is not associated with a media section yet.
2801 return nullptr;
2802 }
2803 return sdesc->description()->GetContentByName(
2804 *transceiver->internal()->mid());
2805 } else {
2806 // Plan B only allows at most one audio and one video section, so use the
2807 // first media section of that type.
2808 return cricket::GetFirstMediaContent(sdesc->description()->contents(),
Steve Anton69470252018-02-09 19:43:082809 transceiver->media_type());
Steve Antoned10bd92017-12-05 18:52:592810 }
2811}
2812
deadbeef46c73892016-11-17 03:42:042813PeerConnectionInterface::RTCConfiguration PeerConnection::GetConfiguration() {
2814 return configuration_;
2815}
2816
deadbeef293e9262017-01-11 20:28:302817bool PeerConnection::SetConfiguration(const RTCConfiguration& configuration,
2818 RTCError* error) {
Peter Boström1a9d6152015-12-08 21:15:172819 TRACE_EVENT0("webrtc", "PeerConnection::SetConfiguration");
deadbeef6de92f92016-12-13 02:49:322820
Steve Anton75737c02017-11-06 18:37:172821 if (local_description() && configuration.ice_candidate_pool_size !=
2822 configuration_.ice_candidate_pool_size) {
Mirko Bonadei675513b2017-11-09 10:09:252823 RTC_LOG(LS_ERROR) << "Can't change candidate pool size after calling "
2824 "SetLocalDescription.";
deadbeef293e9262017-01-11 20:28:302825 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
buildbot@webrtc.org41451d42014-05-03 05:39:452826 }
Taylor Brandstettera1c30352016-05-13 15:15:112827
deadbeef293e9262017-01-11 20:28:302828 // The simplest (and most future-compatible) way to tell if the config was
2829 // modified in an invalid way is to copy each property we do support
2830 // modifying, then use operator==. There are far more properties we don't
2831 // support modifying than those we do, and more could be added.
2832 RTCConfiguration modified_config = configuration_;
2833 modified_config.servers = configuration.servers;
2834 modified_config.type = configuration.type;
2835 modified_config.ice_candidate_pool_size =
2836 configuration.ice_candidate_pool_size;
2837 modified_config.prune_turn_ports = configuration.prune_turn_ports;
skvladd1f5fda2017-02-04 00:54:052838 modified_config.ice_check_min_interval = configuration.ice_check_min_interval;
Qingsi Wange6826d22018-03-08 22:55:142839 modified_config.ice_check_interval_strong_connectivity =
2840 configuration.ice_check_interval_strong_connectivity;
2841 modified_config.ice_check_interval_weak_connectivity =
2842 configuration.ice_check_interval_weak_connectivity;
Qingsi Wang22e623a2018-03-13 17:53:572843 modified_config.ice_unwritable_timeout = configuration.ice_unwritable_timeout;
2844 modified_config.ice_unwritable_min_checks =
2845 configuration.ice_unwritable_min_checks;
Qingsi Wangdb53f8e2018-02-20 22:45:492846 modified_config.stun_candidate_keepalive_interval =
2847 configuration.stun_candidate_keepalive_interval;
Jonas Orelandbdcee282017-10-10 12:01:402848 modified_config.turn_customizer = configuration.turn_customizer;
Qingsi Wang9a5c6f82018-02-01 18:38:402849 modified_config.network_preference = configuration.network_preference;
deadbeef293e9262017-01-11 20:28:302850 if (configuration != modified_config) {
Mirko Bonadei675513b2017-11-09 10:09:252851 RTC_LOG(LS_ERROR) << "Modifying the configuration in an unsupported way.";
deadbeef293e9262017-01-11 20:28:302852 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
2853 }
2854
Steve Anton038834f2017-07-14 22:59:592855 // Validate the modified configuration.
2856 RTCError validate_error = ValidateConfiguration(modified_config);
2857 if (!validate_error.ok()) {
2858 return SafeSetError(std::move(validate_error), error);
2859 }
2860
deadbeef293e9262017-01-11 20:28:302861 // Note that this isn't possible through chromium, since it's an unsigned
2862 // short in WebIDL.
2863 if (configuration.ice_candidate_pool_size < 0 ||
2864 configuration.ice_candidate_pool_size > UINT16_MAX) {
2865 return SafeSetError(RTCErrorType::INVALID_RANGE, error);
2866 }
2867
2868 // Parse ICE servers before hopping to network thread.
2869 cricket::ServerAddresses stun_servers;
2870 std::vector<cricket::RelayServerConfig> turn_servers;
2871 RTCErrorType parse_error =
2872 ParseIceServers(configuration.servers, &stun_servers, &turn_servers);
2873 if (parse_error != RTCErrorType::NONE) {
2874 return SafeSetError(parse_error, error);
2875 }
2876
2877 // In theory this shouldn't fail.
2878 if (!network_thread()->Invoke<bool>(
2879 RTC_FROM_HERE,
2880 rtc::Bind(&PeerConnection::ReconfigurePortAllocator_n, this,
2881 stun_servers, turn_servers, modified_config.type,
2882 modified_config.ice_candidate_pool_size,
Jonas Orelandbdcee282017-10-10 12:01:402883 modified_config.prune_turn_ports,
Qingsi Wangdb53f8e2018-02-20 22:45:492884 modified_config.turn_customizer,
2885 modified_config.stun_candidate_keepalive_interval))) {
Mirko Bonadei675513b2017-11-09 10:09:252886 RTC_LOG(LS_ERROR) << "Failed to apply configuration to PortAllocator.";
deadbeef293e9262017-01-11 20:28:302887 return SafeSetError(RTCErrorType::INTERNAL_ERROR, error);
2888 }
Honghai Zhang4cedf2b2016-08-31 15:18:112889
deadbeefd1a38b52016-12-10 21:15:332890 // As described in JSEP, calling setConfiguration with new ICE servers or
2891 // candidate policy must set a "needs-ice-restart" bit so that the next offer
2892 // triggers an ICE restart which will pick up the changes.
deadbeef293e9262017-01-11 20:28:302893 if (modified_config.servers != configuration_.servers ||
2894 modified_config.type != configuration_.type ||
2895 modified_config.prune_turn_ports != configuration_.prune_turn_ports) {
Steve Antond25da372017-11-06 22:50:292896 transport_controller_->SetNeedsIceRestartFlag();
deadbeefd1a38b52016-12-10 21:15:332897 }
skvladd1f5fda2017-02-04 00:54:052898
Qingsi Wang9c98f0c2018-02-15 23:10:592899 transport_controller_->SetIceConfig(ParseIceConfig(modified_config));
skvladd1f5fda2017-02-04 00:54:052900
deadbeef293e9262017-01-11 20:28:302901 configuration_ = modified_config;
2902 return SafeSetError(RTCErrorType::NONE, error);
buildbot@webrtc.org41451d42014-05-03 05:39:452903}
2904
henrike@webrtc.org28e20752013-07-10 00:45:362905bool PeerConnection::AddIceCandidate(
2906 const IceCandidateInterface* ice_candidate) {
Peter Boström1a9d6152015-12-08 21:15:172907 TRACE_EVENT0("webrtc", "PeerConnection::AddIceCandidate");
zhihuang29ff8442016-07-27 18:07:252908 if (IsClosed()) {
2909 return false;
2910 }
Steve Antond25da372017-11-06 22:50:292911
2912 if (!remote_description()) {
Mirko Bonadei675513b2017-11-09 10:09:252913 RTC_LOG(LS_ERROR) << "ProcessIceMessage: ICE candidates can't be added "
Jonas Olsson45cc8902018-02-13 09:37:072914 "without any remote session description.";
Steve Antond25da372017-11-06 22:50:292915 return false;
2916 }
2917
2918 if (!ice_candidate) {
Mirko Bonadei675513b2017-11-09 10:09:252919 RTC_LOG(LS_ERROR) << "ProcessIceMessage: Candidate is NULL.";
Steve Antond25da372017-11-06 22:50:292920 return false;
2921 }
2922
2923 bool valid = false;
2924 bool ready = ReadyToUseRemoteCandidate(ice_candidate, nullptr, &valid);
2925 if (!valid) {
2926 return false;
2927 }
2928
2929 // Add this candidate to the remote session description.
2930 if (!mutable_remote_description()->AddCandidate(ice_candidate)) {
Mirko Bonadei675513b2017-11-09 10:09:252931 RTC_LOG(LS_ERROR) << "ProcessIceMessage: Candidate cannot be used.";
Steve Antond25da372017-11-06 22:50:292932 return false;
2933 }
2934
2935 if (ready) {
2936 return UseCandidate(ice_candidate);
2937 } else {
Mirko Bonadei675513b2017-11-09 10:09:252938 RTC_LOG(LS_INFO) << "ProcessIceMessage: Not ready to use candidate.";
Steve Antond25da372017-11-06 22:50:292939 return true;
2940 }
henrike@webrtc.org28e20752013-07-10 00:45:362941}
2942
Honghai Zhang7fb69db2016-03-14 18:59:182943bool PeerConnection::RemoveIceCandidates(
2944 const std::vector<cricket::Candidate>& candidates) {
2945 TRACE_EVENT0("webrtc", "PeerConnection::RemoveIceCandidates");
Steve Antond25da372017-11-06 22:50:292946 if (!remote_description()) {
Mirko Bonadei675513b2017-11-09 10:09:252947 RTC_LOG(LS_ERROR) << "RemoveRemoteIceCandidates: ICE candidates can't be "
Jonas Olsson45cc8902018-02-13 09:37:072948 "removed without any remote session description.";
Steve Antond25da372017-11-06 22:50:292949 return false;
2950 }
2951
2952 if (candidates.empty()) {
Mirko Bonadei675513b2017-11-09 10:09:252953 RTC_LOG(LS_ERROR) << "RemoveRemoteIceCandidates: candidates are empty.";
Steve Antond25da372017-11-06 22:50:292954 return false;
2955 }
2956
2957 size_t number_removed =
2958 mutable_remote_description()->RemoveCandidates(candidates);
2959 if (number_removed != candidates.size()) {
Mirko Bonadei675513b2017-11-09 10:09:252960 RTC_LOG(LS_ERROR)
2961 << "RemoveRemoteIceCandidates: Failed to remove candidates. "
Jonas Olsson45cc8902018-02-13 09:37:072962 "Requested "
2963 << candidates.size() << " but only " << number_removed
Mirko Bonadei675513b2017-11-09 10:09:252964 << " are removed.";
Steve Antond25da372017-11-06 22:50:292965 }
2966
2967 // Remove the candidates from the transport controller.
Zhi Huange830e682018-03-30 17:48:352968 RTCError error = transport_controller_->RemoveRemoteCandidates(candidates);
2969 if (!error.ok()) {
2970 RTC_LOG(LS_ERROR) << "Error when removing remote candidates: "
2971 << error.message();
Steve Antond25da372017-11-06 22:50:292972 }
2973 return true;
Honghai Zhang7fb69db2016-03-14 18:59:182974}
2975
buildbot@webrtc.org1567b8c2014-05-08 19:54:162976void PeerConnection::RegisterUMAObserver(UMAObserver* observer) {
Peter Boström1a9d6152015-12-08 21:15:172977 TRACE_EVENT0("webrtc", "PeerConnection::RegisterUmaObserver");
Patrik Höglund3dc41062018-04-11 11:13:572978 uma_observer_ = observer;
2979
2980 if (transport_controller()) {
2981 transport_controller()->SetMetricsObserver(uma_observer_);
2982 }
2983
2984 for (auto transceiver : transceivers_) {
2985 auto* channel = transceiver->internal()->channel();
2986 if (channel) {
2987 channel->SetMetricsObserver(uma_observer_);
2988 }
2989 }
2990
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:182991 // Send information about IPv4/IPv6 status.
deadbeef293e9262017-01-11 20:28:302992 if (uma_observer_) {
Patrik Höglund3dc41062018-04-11 11:13:572993 port_allocator_->SetMetricsObserver(uma_observer_);
2994 if (port_allocator_->flags() & cricket::PORTALLOCATOR_ENABLE_IPV6) {
Guo-wei Shiehdfbe6792015-09-04 00:12:072995 uma_observer_->IncrementEnumCounter(
2996 kEnumCounterAddressFamily, kPeerConnection_IPv6,
2997 kPeerConnectionAddressFamilyCounter_Max);
mallinath@webrtc.orgb445f262014-05-23 22:19:372998 } else {
Guo-wei Shiehdfbe6792015-09-04 00:12:072999 uma_observer_->IncrementEnumCounter(
3000 kEnumCounterAddressFamily, kPeerConnection_IPv4,
3001 kPeerConnectionAddressFamilyCounter_Max);
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:183002 }
3003 }
buildbot@webrtc.org1567b8c2014-05-08 19:54:163004}
3005
zstein4b979802017-06-02 21:37:373006RTCError PeerConnection::SetBitrate(const BitrateParameters& bitrate) {
Steve Anton978b8762017-09-29 19:15:023007 if (!worker_thread()->IsCurrent()) {
3008 return worker_thread()->Invoke<RTCError>(
zstein4b979802017-06-02 21:37:373009 RTC_FROM_HERE, rtc::Bind(&PeerConnection::SetBitrate, this, bitrate));
3010 }
3011
3012 const bool has_min = static_cast<bool>(bitrate.min_bitrate_bps);
3013 const bool has_current = static_cast<bool>(bitrate.current_bitrate_bps);
3014 const bool has_max = static_cast<bool>(bitrate.max_bitrate_bps);
3015 if (has_min && *bitrate.min_bitrate_bps < 0) {
3016 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3017 "min_bitrate_bps <= 0");
3018 }
3019 if (has_current) {
3020 if (has_min && *bitrate.current_bitrate_bps < *bitrate.min_bitrate_bps) {
3021 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3022 "current_bitrate_bps < min_bitrate_bps");
3023 } else if (*bitrate.current_bitrate_bps < 0) {
3024 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3025 "curent_bitrate_bps < 0");
3026 }
3027 }
3028 if (has_max) {
3029 if (has_current &&
3030 *bitrate.max_bitrate_bps < *bitrate.current_bitrate_bps) {
3031 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3032 "max_bitrate_bps < current_bitrate_bps");
3033 } else if (has_min && *bitrate.max_bitrate_bps < *bitrate.min_bitrate_bps) {
3034 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3035 "max_bitrate_bps < min_bitrate_bps");
3036 } else if (*bitrate.max_bitrate_bps < 0) {
3037 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3038 "max_bitrate_bps < 0");
3039 }
3040 }
3041
Sebastian Janssonfc8d26b2018-02-21 08:52:063042 BitrateConstraintsMask mask;
zstein4b979802017-06-02 21:37:373043 mask.min_bitrate_bps = bitrate.min_bitrate_bps;
3044 mask.start_bitrate_bps = bitrate.current_bitrate_bps;
3045 mask.max_bitrate_bps = bitrate.max_bitrate_bps;
3046
3047 RTC_DCHECK(call_.get());
Sebastian Jansson8f83b422018-02-21 12:07:133048 call_->GetTransportControllerSend()->SetClientBitratePreferences(mask);
zstein4b979802017-06-02 21:37:373049
3050 return RTCError::OK();
3051}
3052
Alex Narest78609d52017-10-20 08:37:473053void PeerConnection::SetBitrateAllocationStrategy(
3054 std::unique_ptr<rtc::BitrateAllocationStrategy>
3055 bitrate_allocation_strategy) {
3056 rtc::Thread* worker_thread = factory_->worker_thread();
3057 if (!worker_thread->IsCurrent()) {
3058 rtc::BitrateAllocationStrategy* strategy_raw =
3059 bitrate_allocation_strategy.release();
3060 auto functor = [this, strategy_raw]() {
3061 call_->SetBitrateAllocationStrategy(
3062 rtc::WrapUnique<rtc::BitrateAllocationStrategy>(strategy_raw));
3063 };
3064 worker_thread->Invoke<void>(RTC_FROM_HERE, functor);
3065 return;
3066 }
3067 RTC_DCHECK(call_.get());
3068 call_->SetBitrateAllocationStrategy(std::move(bitrate_allocation_strategy));
3069}
3070
henrika5f6bf242017-11-01 10:06:563071void PeerConnection::SetAudioPlayout(bool playout) {
3072 if (!worker_thread()->IsCurrent()) {
3073 worker_thread()->Invoke<void>(
3074 RTC_FROM_HERE,
3075 rtc::Bind(&PeerConnection::SetAudioPlayout, this, playout));
3076 return;
3077 }
3078 auto audio_state =
3079 factory_->channel_manager()->media_engine()->GetAudioState();
3080 audio_state->SetPlayout(playout);
3081}
3082
3083void PeerConnection::SetAudioRecording(bool recording) {
3084 if (!worker_thread()->IsCurrent()) {
3085 worker_thread()->Invoke<void>(
3086 RTC_FROM_HERE,
3087 rtc::Bind(&PeerConnection::SetAudioRecording, this, recording));
3088 return;
3089 }
3090 auto audio_state =
3091 factory_->channel_manager()->media_engine()->GetAudioState();
3092 audio_state->SetRecording(recording);
3093}
3094
Steve Anton8c0f7a72017-10-03 17:03:103095std::unique_ptr<rtc::SSLCertificate>
3096PeerConnection::GetRemoteAudioSSLCertificate() {
Taylor Brandstetterc3928662018-02-23 21:04:513097 std::unique_ptr<rtc::SSLCertChain> chain = GetRemoteAudioSSLCertChain();
3098 if (!chain || !chain->GetSize()) {
Steve Anton8c0f7a72017-10-03 17:03:103099 return nullptr;
3100 }
Taylor Brandstetterc3928662018-02-23 21:04:513101 return chain->Get(0).GetUniqueReference();
Steve Anton8c0f7a72017-10-03 17:03:103102}
3103
Zhi Huang70b820f2018-01-27 22:16:153104std::unique_ptr<rtc::SSLCertChain>
3105PeerConnection::GetRemoteAudioSSLCertChain() {
Steve Antonafb0bb72018-02-20 19:35:373106 auto audio_transceiver = GetFirstAudioTransceiver();
3107 if (!audio_transceiver || !audio_transceiver->internal()->channel()) {
Zhi Huang70b820f2018-01-27 22:16:153108 return nullptr;
3109 }
Zhi Huang70b820f2018-01-27 22:16:153110 return transport_controller_->GetRemoteSSLCertChain(
Steve Antonafb0bb72018-02-20 19:35:373111 audio_transceiver->internal()->channel()->transport_name());
3112}
3113
3114rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3115PeerConnection::GetFirstAudioTransceiver() const {
3116 for (auto transceiver : transceivers_) {
3117 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
3118 return transceiver;
3119 }
3120 }
3121 return nullptr;
Zhi Huang70b820f2018-01-27 22:16:153122}
3123
ivoc14d5dbe2016-07-04 14:06:553124bool PeerConnection::StartRtcEventLog(rtc::PlatformFile file,
3125 int64_t max_size_bytes) {
Elad Alon99c3fe52017-10-13 14:29:403126 // TODO(eladalon): It would be better to not allow negative values into PC.
3127 const size_t max_size = (max_size_bytes < 0)
3128 ? RtcEventLog::kUnlimitedOutput
3129 : rtc::saturated_cast<size_t>(max_size_bytes);
3130 return StartRtcEventLog(
Bjorn Tereliusde939432017-11-20 16:38:143131 rtc::MakeUnique<RtcEventLogOutputFile>(file, max_size),
3132 webrtc::RtcEventLog::kImmediateOutput);
Elad Alon99c3fe52017-10-13 14:29:403133}
3134
Bjorn Tereliusde939432017-11-20 16:38:143135bool PeerConnection::StartRtcEventLog(std::unique_ptr<RtcEventLogOutput> output,
3136 int64_t output_period_ms) {
Karl Wibergd6b48192017-10-16 21:01:063137 // TODO(eladalon): In C++14, this can be done with a lambda.
3138 struct Functor {
Bjorn Tereliusde939432017-11-20 16:38:143139 bool operator()() {
3140 return pc->StartRtcEventLog_w(std::move(output), output_period_ms);
3141 }
Karl Wibergd6b48192017-10-16 21:01:063142 PeerConnection* const pc;
3143 std::unique_ptr<RtcEventLogOutput> output;
Bjorn Tereliusde939432017-11-20 16:38:143144 const int64_t output_period_ms;
Elad Alon99c3fe52017-10-13 14:29:403145 };
Bjorn Tereliusde939432017-11-20 16:38:143146 return worker_thread()->Invoke<bool>(
3147 RTC_FROM_HERE, Functor{this, std::move(output), output_period_ms});
ivoc14d5dbe2016-07-04 14:06:553148}
3149
3150void PeerConnection::StopRtcEventLog() {
Steve Anton978b8762017-09-29 19:15:023151 worker_thread()->Invoke<void>(
ivoc14d5dbe2016-07-04 14:06:553152 RTC_FROM_HERE, rtc::Bind(&PeerConnection::StopRtcEventLog_w, this));
3153}
3154
henrike@webrtc.org28e20752013-07-10 00:45:363155const SessionDescriptionInterface* PeerConnection::local_description() const {
Steve Anton75737c02017-11-06 18:37:173156 return pending_local_description_ ? pending_local_description_.get()
3157 : current_local_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:363158}
3159
3160const SessionDescriptionInterface* PeerConnection::remote_description() const {
Steve Anton75737c02017-11-06 18:37:173161 return pending_remote_description_ ? pending_remote_description_.get()
3162 : current_remote_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:363163}
3164
deadbeeffe4a8a42016-12-21 01:56:173165const SessionDescriptionInterface* PeerConnection::current_local_description()
3166 const {
Steve Anton75737c02017-11-06 18:37:173167 return current_local_description_.get();
deadbeeffe4a8a42016-12-21 01:56:173168}
3169
3170const SessionDescriptionInterface* PeerConnection::current_remote_description()
3171 const {
Steve Anton75737c02017-11-06 18:37:173172 return current_remote_description_.get();
deadbeeffe4a8a42016-12-21 01:56:173173}
3174
3175const SessionDescriptionInterface* PeerConnection::pending_local_description()
3176 const {
Steve Anton75737c02017-11-06 18:37:173177 return pending_local_description_.get();
deadbeeffe4a8a42016-12-21 01:56:173178}
3179
3180const SessionDescriptionInterface* PeerConnection::pending_remote_description()
3181 const {
Steve Anton75737c02017-11-06 18:37:173182 return pending_remote_description_.get();
deadbeeffe4a8a42016-12-21 01:56:173183}
3184
henrike@webrtc.org28e20752013-07-10 00:45:363185void PeerConnection::Close() {
Peter Boström1a9d6152015-12-08 21:15:173186 TRACE_EVENT0("webrtc", "PeerConnection::Close");
henrike@webrtc.org28e20752013-07-10 00:45:363187 // Update stats here so that we have the most recent stats for tracks and
3188 // streams before the channels are closed.
tommi@webrtc.org03505bc2014-07-14 20:15:263189 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:363190
Steve Anton75737c02017-11-06 18:37:173191 ChangeSignalingState(PeerConnectionInterface::kClosed);
Steve Anton3fe1b152017-12-12 18:20:083192
Steve Anton8af21862017-12-15 19:20:133193 for (auto transceiver : transceivers_) {
3194 transceiver->Stop();
3195 }
3196 DestroyAllChannels();
Steve Anton75737c02017-11-06 18:37:173197
Qingsi Wang93a84392018-01-31 01:13:093198 // The event log is used in the transport controller, which must be outlived
3199 // by the former. CreateOffer by the peer connection is implemented
3200 // asynchronously and if the peer connection is closed without resetting the
3201 // WebRTC session description factory, the session description factory would
3202 // call the transport controller.
3203 webrtc_session_desc_factory_.reset();
3204 transport_controller_.reset();
3205
deadbeef42a42632017-03-10 23:18:003206 network_thread()->Invoke<void>(
3207 RTC_FROM_HERE,
3208 rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
3209 port_allocator_.get()));
nisseeaabdf62017-05-05 09:23:023210
Steve Anton978b8762017-09-29 19:15:023211 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
eladalon248fd4f2017-09-06 12:18:153212 call_.reset();
3213 // The event log must outlive call (and any other object that uses it).
3214 event_log_.reset();
3215 });
henrike@webrtc.org28e20752013-07-10 00:45:363216}
3217
buildbot@webrtc.orgd4e598d2014-07-29 17:36:523218void PeerConnection::OnMessage(rtc::Message* msg) {
henrike@webrtc.org28e20752013-07-10 00:45:363219 switch (msg->message_id) {
henrike@webrtc.org28e20752013-07-10 00:45:363220 case MSG_SET_SESSIONDESCRIPTION_SUCCESS: {
3221 SetSessionDescriptionMsg* param =
3222 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
3223 param->observer->OnSuccess();
3224 delete param;
3225 break;
3226 }
3227 case MSG_SET_SESSIONDESCRIPTION_FAILED: {
3228 SetSessionDescriptionMsg* param =
3229 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
Harald Alvestrand5081c0c2018-03-09 14:18:033230 param->observer->OnFailure(std::move(param->error));
henrike@webrtc.org28e20752013-07-10 00:45:363231 delete param;
3232 break;
3233 }
deadbeefab9b2d12015-10-14 18:33:113234 case MSG_CREATE_SESSIONDESCRIPTION_FAILED: {
3235 CreateSessionDescriptionMsg* param =
3236 static_cast<CreateSessionDescriptionMsg*>(msg->pdata);
Harald Alvestrand5081c0c2018-03-09 14:18:033237 param->observer->OnFailure(std::move(param->error));
deadbeefab9b2d12015-10-14 18:33:113238 delete param;
3239 break;
3240 }
henrike@webrtc.org28e20752013-07-10 00:45:363241 case MSG_GETSTATS: {
3242 GetStatsMsg* param = static_cast<GetStatsMsg*>(msg->pdata);
nissee8abe3e2017-01-18 13:00:343243 StatsReports reports;
3244 stats_->GetStats(param->track, &reports);
3245 param->observer->OnComplete(reports);
henrike@webrtc.org28e20752013-07-10 00:45:363246 delete param;
3247 break;
3248 }
deadbeefbd292462015-12-15 02:15:293249 case MSG_FREE_DATACHANNELS: {
3250 sctp_data_channels_to_free_.clear();
3251 break;
3252 }
henrike@webrtc.org28e20752013-07-10 00:45:363253 default:
nisseeb4ca4e2017-01-12 10:24:273254 RTC_NOTREACHED() << "Not implemented";
henrike@webrtc.org28e20752013-07-10 00:45:363255 break;
3256 }
3257}
3258
Steve Antonafb0bb72018-02-20 19:35:373259cricket::VoiceMediaChannel* PeerConnection::voice_media_channel() const {
3260 RTC_DCHECK(!IsUnifiedPlan());
3261 auto* voice_channel = static_cast<cricket::VoiceChannel*>(
3262 GetAudioTransceiver()->internal()->channel());
3263 if (voice_channel) {
3264 return voice_channel->media_channel();
3265 } else {
3266 return nullptr;
3267 }
3268}
3269
3270cricket::VideoMediaChannel* PeerConnection::video_media_channel() const {
3271 RTC_DCHECK(!IsUnifiedPlan());
3272 auto* video_channel = static_cast<cricket::VideoChannel*>(
3273 GetVideoTransceiver()->internal()->channel());
3274 if (video_channel) {
3275 return video_channel->media_channel();
3276 } else {
3277 return nullptr;
3278 }
3279}
3280
Steve Anton4171afb2017-11-20 18:20:223281void PeerConnection::CreateAudioReceiver(
3282 MediaStreamInterface* stream,
3283 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 12:41:513284 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
3285 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Steve Antond3679212018-01-18 01:41:023286 auto* audio_receiver = new AudioRtpReceiver(
3287 worker_thread(), remote_sender_info.sender_id, streams);
Steve Anton57858b32018-02-15 23:19:503288 audio_receiver->SetVoiceMediaChannel(voice_media_channel());
Steve Antond3679212018-01-18 01:41:023289 audio_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
3290 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
3291 signaling_thread(), audio_receiver);
Steve Anton4171afb2017-11-20 18:20:223292 GetAudioTransceiver()->internal()->AddReceiver(receiver);
Henrik Boström9e6fd2b2017-11-21 12:41:513293 observer_->OnAddTrack(receiver, std::move(streams));
henrike@webrtc.org28e20752013-07-10 00:45:363294}
3295
Steve Anton4171afb2017-11-20 18:20:223296void PeerConnection::CreateVideoReceiver(
3297 MediaStreamInterface* stream,
3298 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 12:41:513299 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
3300 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Steve Antond3679212018-01-18 01:41:023301 auto* video_receiver = new VideoRtpReceiver(
3302 worker_thread(), remote_sender_info.sender_id, streams);
Steve Anton57858b32018-02-15 23:19:503303 video_receiver->SetVideoMediaChannel(video_media_channel());
Steve Antond3679212018-01-18 01:41:023304 video_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
3305 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
3306 signaling_thread(), video_receiver);
Steve Anton4171afb2017-11-20 18:20:223307 GetVideoTransceiver()->internal()->AddReceiver(receiver);
Henrik Boström9e6fd2b2017-11-21 12:41:513308 observer_->OnAddTrack(receiver, std::move(streams));
henrike@webrtc.org28e20752013-07-10 00:45:363309}
3310
deadbeef70ab1a12015-09-28 23:53:553311// TODO(deadbeef): Keep RtpReceivers around even if track goes away in remote
3312// description.
Henrik Boström933d8b02017-10-10 17:05:163313rtc::scoped_refptr<RtpReceiverInterface> PeerConnection::RemoveAndStopReceiver(
Steve Anton4171afb2017-11-20 18:20:223314 const RtpSenderInfo& remote_sender_info) {
3315 auto receiver = FindReceiverById(remote_sender_info.sender_id);
3316 if (!receiver) {
3317 RTC_LOG(LS_WARNING) << "RtpReceiver for track with id "
3318 << remote_sender_info.sender_id << " doesn't exist.";
Henrik Boström933d8b02017-10-10 17:05:163319 return nullptr;
deadbeef70ab1a12015-09-28 23:53:553320 }
Steve Anton4171afb2017-11-20 18:20:223321 if (receiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
3322 GetAudioTransceiver()->internal()->RemoveReceiver(receiver);
3323 } else {
3324 GetVideoTransceiver()->internal()->RemoveReceiver(receiver);
3325 }
Henrik Boström933d8b02017-10-10 17:05:163326 return receiver;
henrike@webrtc.org28e20752013-07-10 00:45:363327}
3328
korniltsev.anatolyec390b52017-07-25 00:00:253329void PeerConnection::AddAudioTrack(AudioTrackInterface* track,
3330 MediaStreamInterface* stream) {
3331 RTC_DCHECK(!IsClosed());
3332 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 18:20:223333 if (sender) {
korniltsev.anatolyec390b52017-07-25 00:00:253334 // We already have a sender for this track, so just change the stream_id
3335 // so that it's correct in the next call to CreateOffer.
Seth Hampson5b4f0752018-04-02 23:31:363336 sender->internal()->set_stream_ids({stream->id()});
korniltsev.anatolyec390b52017-07-25 00:00:253337 return;
3338 }
3339
3340 // Normal case; we've never seen this track before.
Steve Anton02ee47c2018-01-11 00:26:063341 auto new_sender =
Seth Hampson13b8bad2018-03-13 23:05:283342 CreateSender(cricket::MEDIA_TYPE_AUDIO, track, {stream->id()});
Steve Anton57858b32018-02-15 23:19:503343 new_sender->internal()->SetVoiceMediaChannel(voice_media_channel());
Steve Anton4171afb2017-11-20 18:20:223344 GetAudioTransceiver()->internal()->AddSender(new_sender);
korniltsev.anatolyec390b52017-07-25 00:00:253345 // If the sender has already been configured in SDP, we call SetSsrc,
3346 // which will connect the sender to the underlying transport. This can
3347 // occur if a local session description that contains the ID of the sender
3348 // is set before AddStream is called. It can also occur if the local
3349 // session description is not changed and RemoveStream is called, and
3350 // later AddStream is called again with the same stream.
Steve Anton4171afb2017-11-20 18:20:223351 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609eaa2018-03-27 21:57:183352 FindSenderInfo(local_audio_sender_infos_, stream->id(), track->id());
Steve Anton4171afb2017-11-20 18:20:223353 if (sender_info) {
3354 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-25 00:00:253355 }
3356}
3357
3358// TODO(deadbeef): Don't destroy RtpSenders here; they should be kept around
3359// indefinitely, when we have unified plan SDP.
3360void PeerConnection::RemoveAudioTrack(AudioTrackInterface* track,
3361 MediaStreamInterface* stream) {
3362 RTC_DCHECK(!IsClosed());
3363 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 18:20:223364 if (!sender) {
Mirko Bonadei675513b2017-11-09 10:09:253365 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
3366 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-25 00:00:253367 return;
3368 }
Steve Anton4171afb2017-11-20 18:20:223369 GetAudioTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-25 00:00:253370}
3371
3372void PeerConnection::AddVideoTrack(VideoTrackInterface* track,
3373 MediaStreamInterface* stream) {
3374 RTC_DCHECK(!IsClosed());
3375 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 18:20:223376 if (sender) {
korniltsev.anatolyec390b52017-07-25 00:00:253377 // We already have a sender for this track, so just change the stream_id
3378 // so that it's correct in the next call to CreateOffer.
Seth Hampson5b4f0752018-04-02 23:31:363379 sender->internal()->set_stream_ids({stream->id()});
korniltsev.anatolyec390b52017-07-25 00:00:253380 return;
3381 }
3382
3383 // Normal case; we've never seen this track before.
Steve Anton02ee47c2018-01-11 00:26:063384 auto new_sender =
Seth Hampson13b8bad2018-03-13 23:05:283385 CreateSender(cricket::MEDIA_TYPE_VIDEO, track, {stream->id()});
Steve Anton57858b32018-02-15 23:19:503386 new_sender->internal()->SetVideoMediaChannel(video_media_channel());
Steve Anton4171afb2017-11-20 18:20:223387 GetVideoTransceiver()->internal()->AddSender(new_sender);
3388 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609eaa2018-03-27 21:57:183389 FindSenderInfo(local_video_sender_infos_, stream->id(), track->id());
Steve Anton4171afb2017-11-20 18:20:223390 if (sender_info) {
3391 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-25 00:00:253392 }
3393}
3394
3395void PeerConnection::RemoveVideoTrack(VideoTrackInterface* track,
3396 MediaStreamInterface* stream) {
3397 RTC_DCHECK(!IsClosed());
3398 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 18:20:223399 if (!sender) {
Mirko Bonadei675513b2017-11-09 10:09:253400 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
3401 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-25 00:00:253402 return;
3403 }
Steve Anton4171afb2017-11-20 18:20:223404 GetVideoTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-25 00:00:253405}
3406
Steve Antonba818672017-11-06 18:21:573407void PeerConnection::SetIceConnectionState(IceConnectionState new_state) {
deadbeef0a6c4ca2015-10-06 18:38:283408 RTC_DCHECK(signaling_thread()->IsCurrent());
Steve Antonba818672017-11-06 18:21:573409 if (ice_connection_state_ == new_state) {
3410 return;
3411 }
3412
deadbeefcbecd352015-09-23 18:50:273413 // After transitioning to "closed", ignore any additional states from
Steve Antonba818672017-11-06 18:21:573414 // TransportController (such as "disconnected").
deadbeefab9b2d12015-10-14 18:33:113415 if (IsClosed()) {
deadbeefcbecd352015-09-23 18:50:273416 return;
3417 }
Steve Antonba818672017-11-06 18:21:573418
Mirko Bonadei675513b2017-11-09 10:09:253419 RTC_LOG(LS_INFO) << "Changing IceConnectionState " << ice_connection_state_
3420 << " => " << new_state;
Steve Antonba818672017-11-06 18:21:573421 RTC_DCHECK(ice_connection_state_ !=
3422 PeerConnectionInterface::kIceConnectionClosed);
3423
henrike@webrtc.org28e20752013-07-10 00:45:363424 ice_connection_state_ = new_state;
mallinath@webrtc.orgd3dc4242014-03-01 00:05:523425 observer_->OnIceConnectionChange(ice_connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:363426}
3427
3428void PeerConnection::OnIceGatheringChange(
3429 PeerConnectionInterface::IceGatheringState new_state) {
deadbeef0a6c4ca2015-10-06 18:38:283430 RTC_DCHECK(signaling_thread()->IsCurrent());
henrike@webrtc.org28e20752013-07-10 00:45:363431 if (IsClosed()) {
3432 return;
3433 }
3434 ice_gathering_state_ = new_state;
mallinath@webrtc.orgd3dc4242014-03-01 00:05:523435 observer_->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:363436}
3437
jbauch81bf7b02017-03-25 15:31:123438void PeerConnection::OnIceCandidate(
3439 std::unique_ptr<IceCandidateInterface> candidate) {
deadbeef0a6c4ca2015-10-06 18:38:283440 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 18:07:253441 if (IsClosed()) {
3442 return;
3443 }
jbauch81bf7b02017-03-25 15:31:123444 observer_->OnIceCandidate(candidate.get());
henrike@webrtc.org28e20752013-07-10 00:45:363445}
3446
Honghai Zhang7fb69db2016-03-14 18:59:183447void PeerConnection::OnIceCandidatesRemoved(
3448 const std::vector<cricket::Candidate>& candidates) {
3449 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 18:07:253450 if (IsClosed()) {
3451 return;
3452 }
Honghai Zhang7fb69db2016-03-14 18:59:183453 observer_->OnIceCandidatesRemoved(candidates);
3454}
3455
henrike@webrtc.org28e20752013-07-10 00:45:363456void PeerConnection::ChangeSignalingState(
3457 PeerConnectionInterface::SignalingState signaling_state) {
Steve Antonba818672017-11-06 18:21:573458 RTC_DCHECK(signaling_thread()->IsCurrent());
3459 if (signaling_state_ == signaling_state) {
3460 return;
3461 }
Mirko Bonadei675513b2017-11-09 10:09:253462 RTC_LOG(LS_INFO) << "Session: " << session_id() << " Old state: "
3463 << GetSignalingStateString(signaling_state_)
3464 << " New state: "
3465 << GetSignalingStateString(signaling_state);
henrike@webrtc.org28e20752013-07-10 00:45:363466 signaling_state_ = signaling_state;
3467 if (signaling_state == kClosed) {
3468 ice_connection_state_ = kIceConnectionClosed;
3469 observer_->OnIceConnectionChange(ice_connection_state_);
3470 if (ice_gathering_state_ != kIceGatheringComplete) {
3471 ice_gathering_state_ = kIceGatheringComplete;
3472 observer_->OnIceGatheringChange(ice_gathering_state_);
3473 }
3474 }
3475 observer_->OnSignalingChange(signaling_state_);
henrike@webrtc.org28e20752013-07-10 00:45:363476}
3477
deadbeefeb459812015-12-16 03:24:433478void PeerConnection::OnAudioTrackAdded(AudioTrackInterface* track,
3479 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 18:07:253480 if (IsClosed()) {
3481 return;
3482 }
korniltsev.anatolyec390b52017-07-25 00:00:253483 AddAudioTrack(track, stream);
3484 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-16 03:24:433485}
3486
deadbeefeb459812015-12-16 03:24:433487void PeerConnection::OnAudioTrackRemoved(AudioTrackInterface* track,
3488 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 18:07:253489 if (IsClosed()) {
3490 return;
3491 }
korniltsev.anatolyec390b52017-07-25 00:00:253492 RemoveAudioTrack(track, stream);
3493 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-16 03:24:433494}
3495
3496void PeerConnection::OnVideoTrackAdded(VideoTrackInterface* track,
3497 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 18:07:253498 if (IsClosed()) {
3499 return;
3500 }
korniltsev.anatolyec390b52017-07-25 00:00:253501 AddVideoTrack(track, stream);
3502 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-16 03:24:433503}
3504
3505void PeerConnection::OnVideoTrackRemoved(VideoTrackInterface* track,
3506 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 18:07:253507 if (IsClosed()) {
3508 return;
3509 }
korniltsev.anatolyec390b52017-07-25 00:00:253510 RemoveVideoTrack(track, stream);
3511 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-16 03:24:433512}
3513
Henrik Boström31638672017-11-23 16:48:323514void PeerConnection::PostSetSessionDescriptionSuccess(
3515 SetSessionDescriptionObserver* observer) {
3516 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
3517 signaling_thread()->Post(RTC_FROM_HERE, this,
3518 MSG_SET_SESSIONDESCRIPTION_SUCCESS, msg);
3519}
3520
deadbeefab9b2d12015-10-14 18:33:113521void PeerConnection::PostSetSessionDescriptionFailure(
3522 SetSessionDescriptionObserver* observer,
Harald Alvestrand5081c0c2018-03-09 14:18:033523 RTCError&& error) {
3524 RTC_DCHECK(!error.ok());
deadbeefab9b2d12015-10-14 18:33:113525 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
Harald Alvestrand5081c0c2018-03-09 14:18:033526 msg->error = std::move(error);
Taylor Brandstetter5d97a9a2016-06-10 21:17:273527 signaling_thread()->Post(RTC_FROM_HERE, this,
3528 MSG_SET_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 18:33:113529}
3530
3531void PeerConnection::PostCreateSessionDescriptionFailure(
3532 CreateSessionDescriptionObserver* observer,
Harald Alvestrand5081c0c2018-03-09 14:18:033533 RTCError error) {
3534 RTC_DCHECK(!error.ok());
deadbeefab9b2d12015-10-14 18:33:113535 CreateSessionDescriptionMsg* msg = new CreateSessionDescriptionMsg(observer);
Harald Alvestrand5081c0c2018-03-09 14:18:033536 msg->error = std::move(error);
Taylor Brandstetter5d97a9a2016-06-10 21:17:273537 signaling_thread()->Post(RTC_FROM_HERE, this,
3538 MSG_CREATE_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 18:33:113539}
3540
zhihuang1c378ed2017-08-17 21:10:503541void PeerConnection::GetOptionsForOffer(
Steve Antondcc3c022017-12-23 00:02:543542 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
deadbeefab9b2d12015-10-14 18:33:113543 cricket::MediaSessionOptions* session_options) {
Steve Antondcc3c022017-12-23 00:02:543544 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
zhihuang1c378ed2017-08-17 21:10:503545
Steve Antondcc3c022017-12-23 00:02:543546 if (IsUnifiedPlan()) {
3547 GetOptionsForUnifiedPlanOffer(offer_answer_options, session_options);
3548 } else {
3549 GetOptionsForPlanBOffer(offer_answer_options, session_options);
3550 }
3551
Steve Antonfa2260d2017-12-29 00:38:233552 // Intentionally unset the data channel type for RTP data channel with the
3553 // second condition. Otherwise the RTP data channels would be successfully
3554 // negotiated by default and the unit tests in WebRtcDataBrowserTest will fail
3555 // when building with chromium. We want to leave RTP data channels broken, so
3556 // people won't try to use them.
3557 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
3558 session_options->data_channel_type = data_channel_type();
3559 }
3560
Steve Antondcc3c022017-12-23 00:02:543561 // Apply ICE restart flag and renomination flag.
3562 for (auto& options : session_options->media_description_options) {
3563 options.transport_options.ice_restart = offer_answer_options.ice_restart;
3564 options.transport_options.enable_ice_renomination =
3565 configuration_.enable_ice_renomination;
3566 }
3567
3568 session_options->rtcp_cname = rtcp_cname_;
3569 session_options->crypto_options = factory_->options().crypto_options;
Steve Antone831b8c2018-02-01 20:22:163570 session_options->is_unified_plan = IsUnifiedPlan();
Steve Antondcc3c022017-12-23 00:02:543571}
3572
3573void PeerConnection::GetOptionsForPlanBOffer(
3574 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
3575 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 21:10:503576 // Figure out transceiver directional preferences.
3577 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
3578 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
3579
3580 // By default, generate sendrecv/recvonly m= sections.
3581 bool recv_audio = true;
3582 bool recv_video = true;
3583
3584 // By default, only offer a new m= section if we have media to send with it.
3585 bool offer_new_audio_description = send_audio;
3586 bool offer_new_video_description = send_video;
3587 bool offer_new_data_description = HasDataChannels();
3588
3589 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-23 00:02:543590 if (offer_answer_options.offer_to_receive_audio !=
3591 RTCOfferAnswerOptions::kUndefined) {
3592 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 21:10:503593 offer_new_audio_description =
Steve Antondcc3c022017-12-23 00:02:543594 offer_new_audio_description ||
3595 (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 21:10:503596 }
Steve Antondcc3c022017-12-23 00:02:543597 if (offer_answer_options.offer_to_receive_video !=
3598 RTCOfferAnswerOptions::kUndefined) {
3599 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 21:10:503600 offer_new_video_description =
Steve Antondcc3c022017-12-23 00:02:543601 offer_new_video_description ||
3602 (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 21:10:503603 }
3604
3605 rtc::Optional<size_t> audio_index;
3606 rtc::Optional<size_t> video_index;
3607 rtc::Optional<size_t> data_index;
3608 // If a current description exists, generate m= sections in the same order,
3609 // using the first audio/video/data section that appears and rejecting
3610 // extraneous ones.
Steve Anton75737c02017-11-06 18:37:173611 if (local_description()) {
zhihuang1c378ed2017-08-17 21:10:503612 GenerateMediaDescriptionOptions(
Steve Anton75737c02017-11-06 18:37:173613 local_description(),
Steve Anton1d03a752017-11-27 22:30:093614 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
3615 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
3616 &audio_index, &video_index, &data_index, session_options);
deadbeefab9b2d12015-10-14 18:33:113617 }
3618
zhihuang1c378ed2017-08-17 21:10:503619 // Add audio/video/data m= sections to the end if needed.
3620 if (!audio_index && offer_new_audio_description) {
3621 session_options->media_description_options.push_back(
3622 cricket::MediaDescriptionOptions(
3623 cricket::MEDIA_TYPE_AUDIO, cricket::CN_AUDIO,
Steve Anton1d03a752017-11-27 22:30:093624 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
3625 false));
Oskar Sundbom9b28a032017-11-16 09:53:303626 audio_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 20:14:453627 }
zhihuang1c378ed2017-08-17 21:10:503628 if (!video_index && offer_new_video_description) {
3629 session_options->media_description_options.push_back(
3630 cricket::MediaDescriptionOptions(
3631 cricket::MEDIA_TYPE_VIDEO, cricket::CN_VIDEO,
Steve Anton1d03a752017-11-27 22:30:093632 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
3633 false));
Oskar Sundbom9b28a032017-11-16 09:53:303634 video_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 20:14:453635 }
zhihuang1c378ed2017-08-17 21:10:503636 if (!data_index && offer_new_data_description) {
3637 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-29 00:38:233638 GetMediaDescriptionOptionsForActiveData(cricket::CN_DATA));
Oskar Sundbom9b28a032017-11-16 09:53:303639 data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 21:10:503640 }
3641
3642 cricket::MediaDescriptionOptions* audio_media_description_options =
3643 !audio_index ? nullptr
3644 : &session_options->media_description_options[*audio_index];
3645 cricket::MediaDescriptionOptions* video_media_description_options =
3646 !video_index ? nullptr
3647 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 21:10:503648
Steve Anton4171afb2017-11-20 18:20:223649 AddRtpSenderOptions(GetSendersInternal(), audio_media_description_options,
zhihuang1c378ed2017-08-17 21:10:503650 video_media_description_options);
Steve Antondcc3c022017-12-23 00:02:543651}
3652
3653// Find a new MID that is not already in |used_mids|, then add it to |used_mids|
3654// and return a reference to it.
3655// Generated MIDs should be no more than 3 bytes long to take up less space in
3656// the RTP packet.
3657static const std::string& AllocateMid(std::set<std::string>* used_mids) {
3658 RTC_DCHECK(used_mids);
3659 // We're boring: just generate MIDs 0, 1, 2, ...
3660 size_t i = 0;
3661 std::set<std::string>::iterator it;
3662 bool inserted;
3663 do {
3664 std::string mid = rtc::ToString(i++);
3665 auto insert_result = used_mids->insert(mid);
3666 it = insert_result.first;
3667 inserted = insert_result.second;
3668 } while (!inserted);
3669 return *it;
3670}
3671
3672static cricket::MediaDescriptionOptions
3673GetMediaDescriptionOptionsForTransceiver(
3674 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3675 transceiver,
3676 const std::string& mid) {
3677 cricket::MediaDescriptionOptions media_description_options(
Steve Anton69470252018-02-09 19:43:083678 transceiver->media_type(), mid, transceiver->direction(),
Steve Antondcc3c022017-12-23 00:02:543679 transceiver->stopped());
Steve Anton5f94aa22018-02-01 18:58:303680 // This behavior is specified in JSEP. The gist is that:
3681 // 1. The MSID is included if the RtpTransceiver's direction is sendonly or
3682 // sendrecv.
3683 // 2. If the MSID is included, then it must be included in any subsequent
3684 // offer/answer exactly the same until the RtpTransceiver is stopped.
3685 if (!transceiver->stopped() &&
3686 (RtpTransceiverDirectionHasSend(transceiver->direction()) ||
3687 transceiver->internal()->has_ever_been_used_to_send())) {
3688 cricket::SenderOptions sender_options;
3689 sender_options.track_id = transceiver->sender()->id();
3690 sender_options.stream_ids = transceiver->sender()->stream_ids();
3691 // TODO(bugs.webrtc.org/7600): Set num_sim_layers to the number of encodings
3692 // set in the RTP parameters when the transceiver was added.
3693 sender_options.num_sim_layers = 1;
3694 media_description_options.sender_options.push_back(sender_options);
3695 }
Steve Antondcc3c022017-12-23 00:02:543696 return media_description_options;
3697}
3698
3699void PeerConnection::GetOptionsForUnifiedPlanOffer(
3700 const RTCOfferAnswerOptions& offer_answer_options,
3701 cricket::MediaSessionOptions* session_options) {
3702 // Rules for generating an offer are dictated by JSEP sections 5.2.1 (Initial
3703 // Offers) and 5.2.2 (Subsequent Offers).
3704 RTC_DCHECK_EQ(session_options->media_description_options.size(), 0);
3705 const ContentInfos& local_contents =
3706 (local_description() ? local_description()->description()->contents()
3707 : ContentInfos());
3708 const ContentInfos& remote_contents =
3709 (remote_description() ? remote_description()->description()->contents()
3710 : ContentInfos());
3711 // The mline indices that can be recycled. New transceivers should reuse these
3712 // slots first.
3713 std::queue<size_t> recycleable_mline_indices;
3714 // Track the MIDs used in previous offer/answer exchanges and the current
3715 // offer so that new, unique MIDs are generated.
3716 std::set<std::string> used_mids = seen_mids_;
3717 // First, go through each media section that exists in either the local or
3718 // remote description and generate a media section in this offer for the
3719 // associated transceiver. If a media section can be recycled, generate a
3720 // default, rejected media section here that can be later overwritten.
3721 for (size_t i = 0;
3722 i < std::max(local_contents.size(), remote_contents.size()); ++i) {
3723 // Either |local_content| or |remote_content| is non-null.
3724 const ContentInfo* local_content =
3725 (i < local_contents.size() ? &local_contents[i] : nullptr);
3726 const ContentInfo* remote_content =
3727 (i < remote_contents.size() ? &remote_contents[i] : nullptr);
3728 bool had_been_rejected = (local_content && local_content->rejected) ||
3729 (remote_content && remote_content->rejected);
3730 const std::string& mid =
3731 (local_content ? local_content->name : remote_content->name);
3732 cricket::MediaType media_type =
3733 (local_content ? local_content->media_description()->type()
3734 : remote_content->media_description()->type());
3735 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
3736 media_type == cricket::MEDIA_TYPE_VIDEO) {
3737 auto transceiver = GetAssociatedTransceiver(mid);
3738 RTC_CHECK(transceiver);
3739 // A media section is considered eligible for recycling if it is marked as
3740 // rejected in either the local or remote description.
Seth Hampsonae8a90a2018-02-13 23:33:483741 if (had_been_rejected && transceiver->stopped()) {
Steve Antondcc3c022017-12-23 00:02:543742 session_options->media_description_options.push_back(
Steve Anton69470252018-02-09 19:43:083743 cricket::MediaDescriptionOptions(transceiver->media_type(), mid,
3744 RtpTransceiverDirection::kInactive,
3745 /*stopped=*/true));
Steve Antondcc3c022017-12-23 00:02:543746 recycleable_mline_indices.push(i);
3747 } else {
3748 session_options->media_description_options.push_back(
3749 GetMediaDescriptionOptionsForTransceiver(transceiver, mid));
3750 // CreateOffer shouldn't really cause any state changes in
3751 // PeerConnection, but we need a way to match new transceivers to new
3752 // media sections in SetLocalDescription and JSEP specifies this is done
3753 // by recording the index of the media section generated for the
3754 // transceiver in the offer.
3755 transceiver->internal()->set_mline_index(i);
3756 }
3757 } else {
3758 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antonfa2260d2017-12-29 00:38:233759 RTC_CHECK(GetDataMid());
3760 if (had_been_rejected || mid != *GetDataMid()) {
3761 session_options->media_description_options.push_back(
3762 GetMediaDescriptionOptionsForRejectedData(mid));
3763 } else {
3764 session_options->media_description_options.push_back(
3765 GetMediaDescriptionOptionsForActiveData(mid));
3766 }
Steve Antondcc3c022017-12-23 00:02:543767 }
3768 }
3769 // Next, look for transceivers that are newly added (that is, are not stopped
3770 // and not associated). Reuse media sections marked as recyclable first,
3771 // otherwise append to the end of the offer. New media sections should be
3772 // added in the order they were added to the PeerConnection.
3773 for (auto transceiver : transceivers_) {
3774 if (transceiver->mid() || transceiver->stopped()) {
3775 continue;
3776 }
3777 size_t mline_index;
3778 if (!recycleable_mline_indices.empty()) {
3779 mline_index = recycleable_mline_indices.front();
3780 recycleable_mline_indices.pop();
3781 session_options->media_description_options[mline_index] =
3782 GetMediaDescriptionOptionsForTransceiver(transceiver,
3783 AllocateMid(&used_mids));
3784 } else {
3785 mline_index = session_options->media_description_options.size();
3786 session_options->media_description_options.push_back(
3787 GetMediaDescriptionOptionsForTransceiver(transceiver,
3788 AllocateMid(&used_mids)));
3789 }
3790 // See comment above for why CreateOffer changes the transceiver's state.
3791 transceiver->internal()->set_mline_index(mline_index);
3792 }
Steve Antonfa2260d2017-12-29 00:38:233793 // Lastly, add a m-section if we have local data channels and an m section
3794 // does not already exist.
3795 if (!GetDataMid() && HasDataChannels()) {
3796 session_options->media_description_options.push_back(
3797 GetMediaDescriptionOptionsForActiveData(AllocateMid(&used_mids)));
3798 }
Steve Antondcc3c022017-12-23 00:02:543799}
3800
3801void PeerConnection::GetOptionsForAnswer(
3802 const RTCOfferAnswerOptions& offer_answer_options,
3803 cricket::MediaSessionOptions* session_options) {
3804 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
3805
3806 if (IsUnifiedPlan()) {
3807 GetOptionsForUnifiedPlanAnswer(offer_answer_options, session_options);
3808 } else {
3809 GetOptionsForPlanBAnswer(offer_answer_options, session_options);
3810 }
3811
Steve Antonfa2260d2017-12-29 00:38:233812 // Intentionally unset the data channel type for RTP data channel. Otherwise
3813 // the RTP data channels would be successfully negotiated by default and the
3814 // unit tests in WebRtcDataBrowserTest will fail when building with chromium.
3815 // We want to leave RTP data channels broken, so people won't try to use them.
3816 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
3817 session_options->data_channel_type = data_channel_type();
3818 }
3819
Steve Antondcc3c022017-12-23 00:02:543820 // Apply ICE renomination flag.
3821 for (auto& options : session_options->media_description_options) {
3822 options.transport_options.enable_ice_renomination =
3823 configuration_.enable_ice_renomination;
3824 }
zhihuang8f65cdf2016-05-07 01:40:303825
3826 session_options->rtcp_cname = rtcp_cname_;
jbauchcb560652016-08-04 12:20:323827 session_options->crypto_options = factory_->options().crypto_options;
Steve Antone831b8c2018-02-01 20:22:163828 session_options->is_unified_plan = IsUnifiedPlan();
deadbeefab9b2d12015-10-14 18:33:113829}
3830
Steve Antondcc3c022017-12-23 00:02:543831void PeerConnection::GetOptionsForPlanBAnswer(
3832 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
Honghai Zhang4cedf2b2016-08-31 15:18:113833 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 21:10:503834 // Figure out transceiver directional preferences.
3835 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
3836 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
3837
3838 // By default, generate sendrecv/recvonly m= sections. The direction is also
3839 // restricted by the direction in the offer.
3840 bool recv_audio = true;
3841 bool recv_video = true;
3842
3843 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-23 00:02:543844 if (offer_answer_options.offer_to_receive_audio !=
3845 RTCOfferAnswerOptions::kUndefined) {
3846 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
deadbeef0ed85b22016-02-24 01:24:523847 }
Steve Antondcc3c022017-12-23 00:02:543848 if (offer_answer_options.offer_to_receive_video !=
3849 RTCOfferAnswerOptions::kUndefined) {
3850 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 21:10:503851 }
3852
3853 rtc::Optional<size_t> audio_index;
3854 rtc::Optional<size_t> video_index;
3855 rtc::Optional<size_t> data_index;
Steve Antondffead82018-02-06 18:31:293856
3857 // Generate m= sections that match those in the offer.
3858 // Note that mediasession.cc will handle intersection our preferred
3859 // direction with the offered direction.
3860 GenerateMediaDescriptionOptions(
3861 remote_description(),
3862 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
3863 RtpTransceiverDirectionFromSendRecv(send_video, recv_video), &audio_index,
3864 &video_index, &data_index, session_options);
zhihuang1c378ed2017-08-17 21:10:503865
3866 cricket::MediaDescriptionOptions* audio_media_description_options =
3867 !audio_index ? nullptr
3868 : &session_options->media_description_options[*audio_index];
3869 cricket::MediaDescriptionOptions* video_media_description_options =
3870 !video_index ? nullptr
3871 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 21:10:503872
Steve Anton4171afb2017-11-20 18:20:223873 AddRtpSenderOptions(GetSendersInternal(), audio_media_description_options,
zhihuang1c378ed2017-08-17 21:10:503874 video_media_description_options);
Steve Antondcc3c022017-12-23 00:02:543875}
zhihuangaf388472016-11-02 23:49:483876
Steve Antondcc3c022017-12-23 00:02:543877void PeerConnection::GetOptionsForUnifiedPlanAnswer(
3878 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
3879 cricket::MediaSessionOptions* session_options) {
3880 // Rules for generating an answer are dictated by JSEP sections 5.3.1 (Initial
3881 // Answers) and 5.3.2 (Subsequent Answers).
3882 RTC_DCHECK(remote_description());
3883 RTC_DCHECK(remote_description()->GetType() == SdpType::kOffer);
3884 for (const ContentInfo& content :
3885 remote_description()->description()->contents()) {
3886 cricket::MediaType media_type = content.media_description()->type();
3887 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
3888 media_type == cricket::MEDIA_TYPE_VIDEO) {
3889 auto transceiver = GetAssociatedTransceiver(content.name);
3890 RTC_CHECK(transceiver);
3891 session_options->media_description_options.push_back(
3892 GetMediaDescriptionOptionsForTransceiver(transceiver, content.name));
3893 } else {
3894 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antondbf9d032018-01-19 23:23:403895 // Reject all data sections if data channels are disabled.
3896 // Reject a data section if it has already been rejected.
3897 // Reject all data sections except for the first one.
3898 if (data_channel_type_ == cricket::DCT_NONE || content.rejected ||
3899 content.name != *GetDataMid()) {
Steve Antonfa2260d2017-12-29 00:38:233900 session_options->media_description_options.push_back(
3901 GetMediaDescriptionOptionsForRejectedData(content.name));
3902 } else {
3903 session_options->media_description_options.push_back(
3904 GetMediaDescriptionOptionsForActiveData(content.name));
3905 }
Steve Antondcc3c022017-12-23 00:02:543906 }
3907 }
htaa2a49d92016-03-04 10:51:393908}
3909
zhihuang1c378ed2017-08-17 21:10:503910void PeerConnection::GenerateMediaDescriptionOptions(
3911 const SessionDescriptionInterface* session_desc,
Steve Anton1d03a752017-11-27 22:30:093912 RtpTransceiverDirection audio_direction,
3913 RtpTransceiverDirection video_direction,
zhihuang1c378ed2017-08-17 21:10:503914 rtc::Optional<size_t>* audio_index,
3915 rtc::Optional<size_t>* video_index,
3916 rtc::Optional<size_t>* data_index,
htaa2a49d92016-03-04 10:51:393917 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 21:10:503918 for (const cricket::ContentInfo& content :
3919 session_desc->description()->contents()) {
3920 if (IsAudioContent(&content)) {
3921 // If we already have an audio m= section, reject this extra one.
3922 if (*audio_index) {
3923 session_options->media_description_options.push_back(
3924 cricket::MediaDescriptionOptions(
3925 cricket::MEDIA_TYPE_AUDIO, content.name,
Steve Anton1d03a752017-11-27 22:30:093926 RtpTransceiverDirection::kInactive, true));
zhihuang1c378ed2017-08-17 21:10:503927 } else {
3928 session_options->media_description_options.push_back(
3929 cricket::MediaDescriptionOptions(
3930 cricket::MEDIA_TYPE_AUDIO, content.name, audio_direction,
Steve Anton1d03a752017-11-27 22:30:093931 audio_direction == RtpTransceiverDirection::kInactive));
Oskar Sundbom9b28a032017-11-16 09:53:303932 *audio_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 21:10:503933 }
3934 } else if (IsVideoContent(&content)) {
3935 // If we already have an video m= section, reject this extra one.
3936 if (*video_index) {
3937 session_options->media_description_options.push_back(
3938 cricket::MediaDescriptionOptions(
3939 cricket::MEDIA_TYPE_VIDEO, content.name,
Steve Anton1d03a752017-11-27 22:30:093940 RtpTransceiverDirection::kInactive, true));
zhihuang1c378ed2017-08-17 21:10:503941 } else {
3942 session_options->media_description_options.push_back(
3943 cricket::MediaDescriptionOptions(
3944 cricket::MEDIA_TYPE_VIDEO, content.name, video_direction,
Steve Anton1d03a752017-11-27 22:30:093945 video_direction == RtpTransceiverDirection::kInactive));
Oskar Sundbom9b28a032017-11-16 09:53:303946 *video_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 21:10:503947 }
3948 } else {
3949 RTC_DCHECK(IsDataContent(&content));
3950 // If we already have an data m= section, reject this extra one.
3951 if (*data_index) {
3952 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-29 00:38:233953 GetMediaDescriptionOptionsForRejectedData(content.name));
zhihuang1c378ed2017-08-17 21:10:503954 } else {
3955 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-29 00:38:233956 GetMediaDescriptionOptionsForActiveData(content.name));
Oskar Sundbom9b28a032017-11-16 09:53:303957 *data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 21:10:503958 }
3959 }
htaa2a49d92016-03-04 10:51:393960 }
deadbeefab9b2d12015-10-14 18:33:113961}
3962
Steve Antonfa2260d2017-12-29 00:38:233963cricket::MediaDescriptionOptions
3964PeerConnection::GetMediaDescriptionOptionsForActiveData(
3965 const std::string& mid) const {
3966 // Direction for data sections is meaningless, but legacy endpoints might
3967 // expect sendrecv.
3968 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
3969 RtpTransceiverDirection::kSendRecv,
3970 /*stopped=*/false);
3971 AddRtpDataChannelOptions(rtp_data_channels_, &options);
3972 return options;
3973}
3974
3975cricket::MediaDescriptionOptions
3976PeerConnection::GetMediaDescriptionOptionsForRejectedData(
3977 const std::string& mid) const {
3978 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
3979 RtpTransceiverDirection::kInactive,
3980 /*stopped=*/true);
3981 AddRtpDataChannelOptions(rtp_data_channels_, &options);
3982 return options;
3983}
3984
3985rtc::Optional<std::string> PeerConnection::GetDataMid() const {
3986 switch (data_channel_type_) {
3987 case cricket::DCT_RTP:
3988 if (!rtp_data_channel_) {
3989 return rtc::nullopt;
3990 }
3991 return rtp_data_channel_->content_name();
3992 case cricket::DCT_SCTP:
Zhi Huange830e682018-03-30 17:48:353993 return sctp_mid_;
Steve Antonfa2260d2017-12-29 00:38:233994 default:
3995 return rtc::nullopt;
3996 }
3997}
3998
Steve Anton4171afb2017-11-20 18:20:223999void PeerConnection::RemoveSenders(cricket::MediaType media_type) {
4000 UpdateLocalSenders(std::vector<cricket::StreamParams>(), media_type);
4001 UpdateRemoteSendersList(std::vector<cricket::StreamParams>(), false,
deadbeefbda7e0b2015-12-09 01:13:404002 media_type, nullptr);
deadbeeffaac4972015-11-12 23:33:074003}
4004
Steve Anton4171afb2017-11-20 18:20:224005void PeerConnection::UpdateRemoteSendersList(
deadbeefab9b2d12015-10-14 18:33:114006 const cricket::StreamParamsVec& streams,
Steve Anton4171afb2017-11-20 18:20:224007 bool default_sender_needed,
deadbeefab9b2d12015-10-14 18:33:114008 cricket::MediaType media_type,
4009 StreamCollection* new_streams) {
Seth Hampson5b4f0752018-04-02 23:31:364010 RTC_DCHECK(!IsUnifiedPlan());
4011
Steve Anton4171afb2017-11-20 18:20:224012 std::vector<RtpSenderInfo>* current_senders =
4013 GetRemoteSenderInfos(media_type);
deadbeefab9b2d12015-10-14 18:33:114014
Steve Anton4171afb2017-11-20 18:20:224015 // Find removed senders. I.e., senders where the sender id or ssrc don't match
deadbeeffac06552015-11-25 19:26:014016 // the new StreamParam.
Steve Anton4171afb2017-11-20 18:20:224017 for (auto sender_it = current_senders->begin();
4018 sender_it != current_senders->end();
4019 /* incremented manually */) {
4020 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 18:33:114021 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 18:20:224022 cricket::GetStreamBySsrc(streams, info.first_ssrc);
Seth Hampson83d676b2018-04-06 01:12:094023 std::string params_stream_id;
4024 if (params) {
4025 params_stream_id =
4026 (!params->first_stream_id().empty() ? params->first_stream_id()
4027 : kDefaultStreamId);
4028 }
Seth Hampson5b4f0752018-04-02 23:31:364029 bool sender_exists = params && params->id == info.sender_id &&
Seth Hampson83d676b2018-04-06 01:12:094030 params_stream_id == info.stream_id;
deadbeefbda7e0b2015-12-09 01:13:404031 // If this is a default track, and we still need it, don't remove it.
Seth Hampson845e8782018-03-02 19:34:104032 if ((info.stream_id == kDefaultStreamId && default_sender_needed) ||
Steve Anton4171afb2017-11-20 18:20:224033 sender_exists) {
4034 ++sender_it;
deadbeefbda7e0b2015-12-09 01:13:404035 } else {
Steve Anton4171afb2017-11-20 18:20:224036 OnRemoteSenderRemoved(info, media_type);
4037 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 18:33:114038 }
4039 }
4040
Steve Anton4171afb2017-11-20 18:20:224041 // Find new and active senders.
deadbeefab9b2d12015-10-14 18:33:114042 for (const cricket::StreamParams& params : streams) {
Seth Hampson5897a6e2018-04-03 18:16:334043 if (!params.has_ssrcs()) {
4044 // The remote endpoint has streams, but didn't signal ssrcs. For an active
4045 // sender, this means it is coming from a Unified Plan endpoint,so we just
4046 // create a default.
4047 default_sender_needed = true;
4048 break;
4049 }
4050
Seth Hampson845e8782018-03-02 19:34:104051 // |params.id| is the sender id and the stream id uses the first of
Seth Hampson5b4f0752018-04-02 23:31:364052 // |params.stream_ids|. The remote description could come from a Unified
Seth Hampson5897a6e2018-04-03 18:16:334053 // Plan endpoint, with multiple or no stream_ids() signaled. Since this is
4054 // not supported in Plan B, we just take the first here and create the
4055 // default stream ID if none is specified.
Seth Hampson845e8782018-03-02 19:34:104056 const std::string& stream_id =
Seth Hampson83d676b2018-04-06 01:12:094057 (!params.first_stream_id().empty() ? params.first_stream_id()
4058 : kDefaultStreamId);
Steve Anton4171afb2017-11-20 18:20:224059 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 18:33:114060 uint32_t ssrc = params.first_ssrc();
4061
4062 rtc::scoped_refptr<MediaStreamInterface> stream =
Seth Hampson845e8782018-03-02 19:34:104063 remote_streams_->find(stream_id);
deadbeefab9b2d12015-10-14 18:33:114064 if (!stream) {
4065 // This is a new MediaStream. Create a new remote MediaStream.
perkjd61bf802016-03-24 10:16:194066 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
Seth Hampson845e8782018-03-02 19:34:104067 MediaStream::Create(stream_id));
deadbeefab9b2d12015-10-14 18:33:114068 remote_streams_->AddStream(stream);
4069 new_streams->AddStream(stream);
4070 }
4071
Steve Anton4171afb2017-11-20 18:20:224072 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609eaa2018-03-27 21:57:184073 FindSenderInfo(*current_senders, stream_id, sender_id);
Steve Anton4171afb2017-11-20 18:20:224074 if (!sender_info) {
Seth Hampson845e8782018-03-02 19:34:104075 current_senders->push_back(RtpSenderInfo(stream_id, sender_id, ssrc));
Steve Anton4171afb2017-11-20 18:20:224076 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 18:33:114077 }
4078 }
deadbeefbda7e0b2015-12-09 01:13:404079
Steve Anton4171afb2017-11-20 18:20:224080 // Add default sender if necessary.
4081 if (default_sender_needed) {
deadbeefbda7e0b2015-12-09 01:13:404082 rtc::scoped_refptr<MediaStreamInterface> default_stream =
Seth Hampson845e8782018-03-02 19:34:104083 remote_streams_->find(kDefaultStreamId);
deadbeefbda7e0b2015-12-09 01:13:404084 if (!default_stream) {
4085 // Create the new default MediaStream.
perkjd61bf802016-03-24 10:16:194086 default_stream = MediaStreamProxy::Create(
Seth Hampson845e8782018-03-02 19:34:104087 rtc::Thread::Current(), MediaStream::Create(kDefaultStreamId));
deadbeefbda7e0b2015-12-09 01:13:404088 remote_streams_->AddStream(default_stream);
4089 new_streams->AddStream(default_stream);
4090 }
Steve Anton4171afb2017-11-20 18:20:224091 std::string default_sender_id = (media_type == cricket::MEDIA_TYPE_AUDIO)
4092 ? kDefaultAudioSenderId
4093 : kDefaultVideoSenderId;
Seth Hampson845e8782018-03-02 19:34:104094 const RtpSenderInfo* default_sender_info =
Emircan Uysalerbc609eaa2018-03-27 21:57:184095 FindSenderInfo(*current_senders, kDefaultStreamId, default_sender_id);
Steve Anton4171afb2017-11-20 18:20:224096 if (!default_sender_info) {
4097 current_senders->push_back(
Seth Hampson845e8782018-03-02 19:34:104098 RtpSenderInfo(kDefaultStreamId, default_sender_id, 0));
Steve Anton4171afb2017-11-20 18:20:224099 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefbda7e0b2015-12-09 01:13:404100 }
4101 }
deadbeefab9b2d12015-10-14 18:33:114102}
4103
Steve Anton4171afb2017-11-20 18:20:224104void PeerConnection::OnRemoteSenderAdded(const RtpSenderInfo& sender_info,
4105 cricket::MediaType media_type) {
Steve Anton3d954a62018-04-02 18:27:234106 RTC_LOG(LS_INFO) << "Creating " << cricket::MediaTypeToString(media_type)
4107 << " receiver for track_id=" << sender_info.sender_id
4108 << " and stream_id=" << sender_info.stream_id;
deadbeefab9b2d12015-10-14 18:33:114109
Steve Anton3d954a62018-04-02 18:27:234110 MediaStreamInterface* stream = remote_streams_->find(sender_info.stream_id);
deadbeefab9b2d12015-10-14 18:33:114111 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 18:20:224112 CreateAudioReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 18:33:114113 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 18:20:224114 CreateVideoReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 18:33:114115 } else {
nisseeb4ca4e2017-01-12 10:24:274116 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 18:33:114117 }
4118}
4119
Steve Anton4171afb2017-11-20 18:20:224120void PeerConnection::OnRemoteSenderRemoved(const RtpSenderInfo& sender_info,
4121 cricket::MediaType media_type) {
Seth Hampson83d676b2018-04-06 01:12:094122 RTC_LOG(LS_INFO) << "Removing " << cricket::MediaTypeToString(media_type)
4123 << " receiver for track_id=" << sender_info.sender_id
4124 << " and stream_id=" << sender_info.stream_id;
4125
Seth Hampson845e8782018-03-02 19:34:104126 MediaStreamInterface* stream = remote_streams_->find(sender_info.stream_id);
deadbeefab9b2d12015-10-14 18:33:114127
Henrik Boström933d8b02017-10-10 17:05:164128 rtc::scoped_refptr<RtpReceiverInterface> receiver;
deadbeefab9b2d12015-10-14 18:33:114129 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
perkjd61bf802016-03-24 10:16:194130 // When the MediaEngine audio channel is destroyed, the RemoteAudioSource
4131 // will be notified which will end the AudioRtpReceiver::track().
Steve Anton4171afb2017-11-20 18:20:224132 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 18:33:114133 rtc::scoped_refptr<AudioTrackInterface> audio_track =
Steve Anton4171afb2017-11-20 18:20:224134 stream->FindAudioTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 18:33:114135 if (audio_track) {
deadbeefab9b2d12015-10-14 18:33:114136 stream->RemoveTrack(audio_track);
deadbeefab9b2d12015-10-14 18:33:114137 }
4138 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
perkjd61bf802016-03-24 10:16:194139 // Stopping or destroying a VideoRtpReceiver will end the
4140 // VideoRtpReceiver::track().
Steve Anton4171afb2017-11-20 18:20:224141 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 18:33:114142 rtc::scoped_refptr<VideoTrackInterface> video_track =
Steve Anton4171afb2017-11-20 18:20:224143 stream->FindVideoTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 18:33:114144 if (video_track) {
perkjd61bf802016-03-24 10:16:194145 // There's no guarantee the track is still available, e.g. the track may
4146 // have been removed from the stream by an application.
deadbeefab9b2d12015-10-14 18:33:114147 stream->RemoveTrack(video_track);
deadbeefab9b2d12015-10-14 18:33:114148 }
4149 } else {
nisseede5da42017-01-12 13:15:364150 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 18:33:114151 }
Henrik Boström933d8b02017-10-10 17:05:164152 if (receiver) {
4153 observer_->OnRemoveTrack(receiver);
4154 }
deadbeefab9b2d12015-10-14 18:33:114155}
4156
4157void PeerConnection::UpdateEndedRemoteMediaStreams() {
4158 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams_to_remove;
4159 for (size_t i = 0; i < remote_streams_->count(); ++i) {
4160 MediaStreamInterface* stream = remote_streams_->at(i);
4161 if (stream->GetAudioTracks().empty() && stream->GetVideoTracks().empty()) {
4162 streams_to_remove.push_back(stream);
4163 }
4164 }
4165
Taylor Brandstetter98cde262016-05-31 20:02:214166 for (auto& stream : streams_to_remove) {
deadbeefab9b2d12015-10-14 18:33:114167 remote_streams_->RemoveStream(stream);
Taylor Brandstetter98cde262016-05-31 20:02:214168 observer_->OnRemoveStream(std::move(stream));
deadbeefab9b2d12015-10-14 18:33:114169 }
4170}
4171
Steve Anton4171afb2017-11-20 18:20:224172void PeerConnection::UpdateLocalSenders(
deadbeefab9b2d12015-10-14 18:33:114173 const std::vector<cricket::StreamParams>& streams,
4174 cricket::MediaType media_type) {
Steve Anton4171afb2017-11-20 18:20:224175 std::vector<RtpSenderInfo>* current_senders = GetLocalSenderInfos(media_type);
deadbeefab9b2d12015-10-14 18:33:114176
Seth Hampson845e8782018-03-02 19:34:104177 // Find removed tracks. I.e., tracks where the track id, stream id or ssrc
deadbeefab9b2d12015-10-14 18:33:114178 // don't match the new StreamParam.
Steve Anton4171afb2017-11-20 18:20:224179 for (auto sender_it = current_senders->begin();
4180 sender_it != current_senders->end();
4181 /* incremented manually */) {
4182 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 18:33:114183 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 18:20:224184 cricket::GetStreamBySsrc(streams, info.first_ssrc);
4185 if (!params || params->id != info.sender_id ||
Seth Hampson845e8782018-03-02 19:34:104186 params->first_stream_id() != info.stream_id) {
Steve Anton4171afb2017-11-20 18:20:224187 OnLocalSenderRemoved(info, media_type);
4188 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 18:33:114189 } else {
Steve Anton4171afb2017-11-20 18:20:224190 ++sender_it;
deadbeefab9b2d12015-10-14 18:33:114191 }
4192 }
4193
Steve Anton4171afb2017-11-20 18:20:224194 // Find new and active senders.
deadbeefab9b2d12015-10-14 18:33:114195 for (const cricket::StreamParams& params : streams) {
4196 // The sync_label is the MediaStream label and the |stream.id| is the
Steve Anton4171afb2017-11-20 18:20:224197 // sender id.
Seth Hampson845e8782018-03-02 19:34:104198 const std::string& stream_id = params.first_stream_id();
Steve Anton4171afb2017-11-20 18:20:224199 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 18:33:114200 uint32_t ssrc = params.first_ssrc();
Steve Anton4171afb2017-11-20 18:20:224201 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609eaa2018-03-27 21:57:184202 FindSenderInfo(*current_senders, stream_id, sender_id);
Steve Anton4171afb2017-11-20 18:20:224203 if (!sender_info) {
Seth Hampson845e8782018-03-02 19:34:104204 current_senders->push_back(RtpSenderInfo(stream_id, sender_id, ssrc));
Steve Anton4171afb2017-11-20 18:20:224205 OnLocalSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 18:33:114206 }
4207 }
4208}
4209
Steve Anton4171afb2017-11-20 18:20:224210void PeerConnection::OnLocalSenderAdded(const RtpSenderInfo& sender_info,
4211 cricket::MediaType media_type) {
Seth Hampson5b4f0752018-04-02 23:31:364212 RTC_DCHECK(!IsUnifiedPlan());
Steve Anton4171afb2017-11-20 18:20:224213 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 19:26:014214 if (!sender) {
Steve Anton4171afb2017-11-20 18:20:224215 RTC_LOG(LS_WARNING) << "An unknown RtpSender with id "
4216 << sender_info.sender_id
Mirko Bonadei675513b2017-11-09 10:09:254217 << " has been configured in the local description.";
deadbeefab9b2d12015-10-14 18:33:114218 return;
4219 }
4220
deadbeeffac06552015-11-25 19:26:014221 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 10:09:254222 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
Jonas Olsson45cc8902018-02-13 09:37:074223 " description with an unexpected media type.";
deadbeeffac06552015-11-25 19:26:014224 return;
deadbeefab9b2d12015-10-14 18:33:114225 }
deadbeeffac06552015-11-25 19:26:014226
Seth Hampson5b4f0752018-04-02 23:31:364227 sender->internal()->set_stream_ids({sender_info.stream_id});
Steve Anton4171afb2017-11-20 18:20:224228 sender->internal()->SetSsrc(sender_info.first_ssrc);
deadbeefab9b2d12015-10-14 18:33:114229}
4230
Steve Anton4171afb2017-11-20 18:20:224231void PeerConnection::OnLocalSenderRemoved(const RtpSenderInfo& sender_info,
4232 cricket::MediaType media_type) {
4233 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 19:26:014234 if (!sender) {
4235 // This is the normal case. I.e., RemoveStream has been called and the
deadbeefab9b2d12015-10-14 18:33:114236 // SessionDescriptions has been renegotiated.
4237 return;
4238 }
deadbeeffac06552015-11-25 19:26:014239
4240 // A sender has been removed from the SessionDescription but it's still
4241 // associated with the PeerConnection. This only occurs if the SDP doesn't
4242 // match with the calls to CreateSender, AddStream and RemoveStream.
4243 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 10:09:254244 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
Jonas Olsson45cc8902018-02-13 09:37:074245 " description with an unexpected media type.";
deadbeeffac06552015-11-25 19:26:014246 return;
deadbeefab9b2d12015-10-14 18:33:114247 }
deadbeeffac06552015-11-25 19:26:014248
Steve Anton4171afb2017-11-20 18:20:224249 sender->internal()->SetSsrc(0);
deadbeefab9b2d12015-10-14 18:33:114250}
4251
4252void PeerConnection::UpdateLocalRtpDataChannels(
4253 const cricket::StreamParamsVec& streams) {
4254 std::vector<std::string> existing_channels;
4255
4256 // Find new and active data channels.
4257 for (const cricket::StreamParams& params : streams) {
4258 // |it->sync_label| is actually the data channel label. The reason is that
4259 // we use the same naming of data channels as we do for
4260 // MediaStreams and Tracks.
4261 // For MediaStreams, the sync_label is the MediaStream label and the
4262 // track label is the same as |streamid|.
Seth Hampson845e8782018-03-02 19:34:104263 const std::string& channel_label = params.first_stream_id();
deadbeefab9b2d12015-10-14 18:33:114264 auto data_channel_it = rtp_data_channels_.find(channel_label);
nisse7ce109a2017-01-31 08:57:564265 if (data_channel_it == rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 10:09:254266 RTC_LOG(LS_ERROR) << "channel label not found";
deadbeefab9b2d12015-10-14 18:33:114267 continue;
4268 }
4269 // Set the SSRC the data channel should use for sending.
4270 data_channel_it->second->SetSendSsrc(params.first_ssrc());
4271 existing_channels.push_back(data_channel_it->first);
4272 }
4273
4274 UpdateClosingRtpDataChannels(existing_channels, true);
4275}
4276
4277void PeerConnection::UpdateRemoteRtpDataChannels(
4278 const cricket::StreamParamsVec& streams) {
4279 std::vector<std::string> existing_channels;
4280
4281 // Find new and active data channels.
4282 for (const cricket::StreamParams& params : streams) {
4283 // The data channel label is either the mslabel or the SSRC if the mslabel
4284 // does not exist. Ex a=ssrc:444330170 mslabel:test1.
Seth Hampson845e8782018-03-02 19:34:104285 std::string label = params.first_stream_id().empty()
deadbeefab9b2d12015-10-14 18:33:114286 ? rtc::ToString(params.first_ssrc())
Seth Hampson845e8782018-03-02 19:34:104287 : params.first_stream_id();
deadbeefab9b2d12015-10-14 18:33:114288 auto data_channel_it = rtp_data_channels_.find(label);
4289 if (data_channel_it == rtp_data_channels_.end()) {
4290 // This is a new data channel.
4291 CreateRemoteRtpDataChannel(label, params.first_ssrc());
4292 } else {
4293 data_channel_it->second->SetReceiveSsrc(params.first_ssrc());
4294 }
4295 existing_channels.push_back(label);
4296 }
4297
4298 UpdateClosingRtpDataChannels(existing_channels, false);
4299}
4300
4301void PeerConnection::UpdateClosingRtpDataChannels(
4302 const std::vector<std::string>& active_channels,
4303 bool is_local_update) {
4304 auto it = rtp_data_channels_.begin();
4305 while (it != rtp_data_channels_.end()) {
4306 DataChannel* data_channel = it->second;
4307 if (std::find(active_channels.begin(), active_channels.end(),
4308 data_channel->label()) != active_channels.end()) {
4309 ++it;
4310 continue;
4311 }
4312
4313 if (is_local_update) {
4314 data_channel->SetSendSsrc(0);
4315 } else {
4316 data_channel->RemotePeerRequestClose();
4317 }
4318
4319 if (data_channel->state() == DataChannel::kClosed) {
4320 rtp_data_channels_.erase(it);
4321 it = rtp_data_channels_.begin();
4322 } else {
4323 ++it;
4324 }
4325 }
4326}
4327
4328void PeerConnection::CreateRemoteRtpDataChannel(const std::string& label,
4329 uint32_t remote_ssrc) {
4330 rtc::scoped_refptr<DataChannel> channel(
4331 InternalCreateDataChannel(label, nullptr));
4332 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 10:09:254333 RTC_LOG(LS_WARNING) << "Remote peer requested a DataChannel but"
Jonas Olsson45cc8902018-02-13 09:37:074334 "CreateDataChannel failed.";
deadbeefab9b2d12015-10-14 18:33:114335 return;
4336 }
4337 channel->SetReceiveSsrc(remote_ssrc);
deadbeefa601f5c2016-06-06 21:27:394338 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
4339 DataChannelProxy::Create(signaling_thread(), channel);
Taylor Brandstetter98cde262016-05-31 20:02:214340 observer_->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 18:33:114341}
4342
4343rtc::scoped_refptr<DataChannel> PeerConnection::InternalCreateDataChannel(
4344 const std::string& label,
4345 const InternalDataChannelInit* config) {
4346 if (IsClosed()) {
4347 return nullptr;
4348 }
Steve Anton75737c02017-11-06 18:37:174349 if (data_channel_type() == cricket::DCT_NONE) {
Mirko Bonadei675513b2017-11-09 10:09:254350 RTC_LOG(LS_ERROR)
deadbeefab9b2d12015-10-14 18:33:114351 << "InternalCreateDataChannel: Data is not supported in this call.";
4352 return nullptr;
4353 }
4354 InternalDataChannelInit new_config =
4355 config ? (*config) : InternalDataChannelInit();
Steve Anton75737c02017-11-06 18:37:174356 if (data_channel_type() == cricket::DCT_SCTP) {
deadbeefab9b2d12015-10-14 18:33:114357 if (new_config.id < 0) {
4358 rtc::SSLRole role;
Steve Anton75737c02017-11-06 18:37:174359 if ((GetSctpSslRole(&role)) &&
deadbeefab9b2d12015-10-14 18:33:114360 !sid_allocator_.AllocateSid(role, &new_config.id)) {
Mirko Bonadei675513b2017-11-09 10:09:254361 RTC_LOG(LS_ERROR)
4362 << "No id can be allocated for the SCTP data channel.";
deadbeefab9b2d12015-10-14 18:33:114363 return nullptr;
4364 }
4365 } else if (!sid_allocator_.ReserveSid(new_config.id)) {
Mirko Bonadei675513b2017-11-09 10:09:254366 RTC_LOG(LS_ERROR) << "Failed to create a SCTP data channel "
Jonas Olsson45cc8902018-02-13 09:37:074367 "because the id is already in use or out of range.";
deadbeefab9b2d12015-10-14 18:33:114368 return nullptr;
4369 }
4370 }
4371
Steve Anton75737c02017-11-06 18:37:174372 rtc::scoped_refptr<DataChannel> channel(
4373 DataChannel::Create(this, data_channel_type(), label, new_config));
deadbeefab9b2d12015-10-14 18:33:114374 if (!channel) {
4375 sid_allocator_.ReleaseSid(new_config.id);
4376 return nullptr;
4377 }
4378
4379 if (channel->data_channel_type() == cricket::DCT_RTP) {
4380 if (rtp_data_channels_.find(channel->label()) != rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 10:09:254381 RTC_LOG(LS_ERROR) << "DataChannel with label " << channel->label()
4382 << " already exists.";
deadbeefab9b2d12015-10-14 18:33:114383 return nullptr;
4384 }
4385 rtp_data_channels_[channel->label()] = channel;
4386 } else {
4387 RTC_DCHECK(channel->data_channel_type() == cricket::DCT_SCTP);
4388 sctp_data_channels_.push_back(channel);
4389 channel->SignalClosed.connect(this,
4390 &PeerConnection::OnSctpDataChannelClosed);
4391 }
4392
Steve Anton2d8609c2018-01-24 00:38:464393 SignalDataChannelCreated_(channel.get());
deadbeefab9b2d12015-10-14 18:33:114394 return channel;
4395}
4396
4397bool PeerConnection::HasDataChannels() const {
4398 return !rtp_data_channels_.empty() || !sctp_data_channels_.empty();
4399}
4400
4401void PeerConnection::AllocateSctpSids(rtc::SSLRole role) {
4402 for (const auto& channel : sctp_data_channels_) {
4403 if (channel->id() < 0) {
4404 int sid;
4405 if (!sid_allocator_.AllocateSid(role, &sid)) {
Mirko Bonadei675513b2017-11-09 10:09:254406 RTC_LOG(LS_ERROR) << "Failed to allocate SCTP sid.";
deadbeefab9b2d12015-10-14 18:33:114407 continue;
4408 }
4409 channel->SetSctpSid(sid);
4410 }
4411 }
4412}
4413
4414void PeerConnection::OnSctpDataChannelClosed(DataChannel* channel) {
deadbeefbd292462015-12-15 02:15:294415 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeefab9b2d12015-10-14 18:33:114416 for (auto it = sctp_data_channels_.begin(); it != sctp_data_channels_.end();
4417 ++it) {
4418 if (it->get() == channel) {
4419 if (channel->id() >= 0) {
4420 sid_allocator_.ReleaseSid(channel->id());
4421 }
deadbeefbd292462015-12-15 02:15:294422 // Since this method is triggered by a signal from the DataChannel,
4423 // we can't free it directly here; we need to free it asynchronously.
4424 sctp_data_channels_to_free_.push_back(*it);
deadbeefab9b2d12015-10-14 18:33:114425 sctp_data_channels_.erase(it);
Taylor Brandstetter5d97a9a2016-06-10 21:17:274426 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_FREE_DATACHANNELS,
4427 nullptr);
deadbeefab9b2d12015-10-14 18:33:114428 return;
4429 }
4430 }
4431}
4432
deadbeefab9b2d12015-10-14 18:33:114433void PeerConnection::OnDataChannelDestroyed() {
4434 // Use a temporary copy of the RTP/SCTP DataChannel list because the
4435 // DataChannel may callback to us and try to modify the list.
4436 std::map<std::string, rtc::scoped_refptr<DataChannel>> temp_rtp_dcs;
4437 temp_rtp_dcs.swap(rtp_data_channels_);
4438 for (const auto& kv : temp_rtp_dcs) {
4439 kv.second->OnTransportChannelDestroyed();
4440 }
4441
4442 std::vector<rtc::scoped_refptr<DataChannel>> temp_sctp_dcs;
4443 temp_sctp_dcs.swap(sctp_data_channels_);
4444 for (const auto& channel : temp_sctp_dcs) {
4445 channel->OnTransportChannelDestroyed();
4446 }
4447}
4448
4449void PeerConnection::OnDataChannelOpenMessage(
4450 const std::string& label,
4451 const InternalDataChannelInit& config) {
4452 rtc::scoped_refptr<DataChannel> channel(
4453 InternalCreateDataChannel(label, &config));
4454 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 10:09:254455 RTC_LOG(LS_ERROR) << "Failed to create DataChannel from the OPEN message.";
deadbeefab9b2d12015-10-14 18:33:114456 return;
4457 }
4458
deadbeefa601f5c2016-06-06 21:27:394459 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
4460 DataChannelProxy::Create(signaling_thread(), channel);
Taylor Brandstetter98cde262016-05-31 20:02:214461 observer_->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 18:33:114462}
4463
Steve Anton4171afb2017-11-20 18:20:224464rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
4465PeerConnection::GetAudioTransceiver() const {
4466 // This method only works with Plan B SDP, where there is a single
4467 // audio/video transceiver.
4468 RTC_DCHECK(!IsUnifiedPlan());
4469 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 19:43:084470 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 18:20:224471 return transceiver;
4472 }
4473 }
4474 RTC_NOTREACHED();
4475 return nullptr;
4476}
4477
4478rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
4479PeerConnection::GetVideoTransceiver() const {
4480 // This method only works with Plan B SDP, where there is a single
4481 // audio/video transceiver.
4482 RTC_DCHECK(!IsUnifiedPlan());
4483 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 19:43:084484 if (transceiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 18:20:224485 return transceiver;
4486 }
4487 }
4488 RTC_NOTREACHED();
4489 return nullptr;
4490}
4491
4492// TODO(bugs.webrtc.org/7600): Remove this when multiple transceivers with
4493// individual transceiver directions are supported.
zhihuang1c378ed2017-08-17 21:10:504494bool PeerConnection::HasRtpSender(cricket::MediaType type) const {
Steve Anton4171afb2017-11-20 18:20:224495 switch (type) {
4496 case cricket::MEDIA_TYPE_AUDIO:
4497 return !GetAudioTransceiver()->internal()->senders().empty();
4498 case cricket::MEDIA_TYPE_VIDEO:
4499 return !GetVideoTransceiver()->internal()->senders().empty();
4500 case cricket::MEDIA_TYPE_DATA:
4501 return false;
4502 }
4503 RTC_NOTREACHED();
4504 return false;
zhihuang1c378ed2017-08-17 21:10:504505}
4506
Steve Anton4171afb2017-11-20 18:20:224507rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
4508PeerConnection::FindSenderForTrack(MediaStreamTrackInterface* track) const {
4509 for (auto transceiver : transceivers_) {
4510 for (auto sender : transceiver->internal()->senders()) {
4511 if (sender->track() == track) {
4512 return sender;
4513 }
4514 }
4515 }
4516 return nullptr;
deadbeeffac06552015-11-25 19:26:014517}
4518
Steve Anton4171afb2017-11-20 18:20:224519rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
4520PeerConnection::FindSenderById(const std::string& sender_id) const {
4521 for (auto transceiver : transceivers_) {
4522 for (auto sender : transceiver->internal()->senders()) {
4523 if (sender->id() == sender_id) {
4524 return sender;
4525 }
4526 }
4527 }
4528 return nullptr;
deadbeef70ab1a12015-09-28 23:53:554529}
4530
Steve Anton4171afb2017-11-20 18:20:224531rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
4532PeerConnection::FindReceiverById(const std::string& receiver_id) const {
4533 for (auto transceiver : transceivers_) {
4534 for (auto receiver : transceiver->internal()->receivers()) {
4535 if (receiver->id() == receiver_id) {
4536 return receiver;
4537 }
4538 }
4539 }
4540 return nullptr;
deadbeef70ab1a12015-09-28 23:53:554541}
4542
Steve Anton4171afb2017-11-20 18:20:224543std::vector<PeerConnection::RtpSenderInfo>*
4544PeerConnection::GetRemoteSenderInfos(cricket::MediaType media_type) {
4545 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
4546 media_type == cricket::MEDIA_TYPE_VIDEO);
4547 return (media_type == cricket::MEDIA_TYPE_AUDIO)
4548 ? &remote_audio_sender_infos_
4549 : &remote_video_sender_infos_;
4550}
4551
4552std::vector<PeerConnection::RtpSenderInfo>* PeerConnection::GetLocalSenderInfos(
deadbeefab9b2d12015-10-14 18:33:114553 cricket::MediaType media_type) {
4554 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
4555 media_type == cricket::MEDIA_TYPE_VIDEO);
Steve Anton4171afb2017-11-20 18:20:224556 return (media_type == cricket::MEDIA_TYPE_AUDIO) ? &local_audio_sender_infos_
4557 : &local_video_sender_infos_;
deadbeefab9b2d12015-10-14 18:33:114558}
4559
Steve Anton4171afb2017-11-20 18:20:224560const PeerConnection::RtpSenderInfo* PeerConnection::FindSenderInfo(
4561 const std::vector<PeerConnection::RtpSenderInfo>& infos,
Emircan Uysalerbc609eaa2018-03-27 21:57:184562 const std::string& stream_id,
Steve Anton4171afb2017-11-20 18:20:224563 const std::string sender_id) const {
4564 for (const RtpSenderInfo& sender_info : infos) {
Emircan Uysalerbc609eaa2018-03-27 21:57:184565 if (sender_info.stream_id == stream_id &&
4566 sender_info.sender_id == sender_id) {
Steve Anton4171afb2017-11-20 18:20:224567 return &sender_info;
deadbeefab9b2d12015-10-14 18:33:114568 }
4569 }
4570 return nullptr;
4571}
4572
4573DataChannel* PeerConnection::FindDataChannelBySid(int sid) const {
4574 for (const auto& channel : sctp_data_channels_) {
4575 if (channel->id() == sid) {
4576 return channel;
4577 }
4578 }
4579 return nullptr;
4580}
4581
deadbeef91dd5672016-05-18 23:55:304582bool PeerConnection::InitializePortAllocator_n(
Taylor Brandstettera1c30352016-05-13 15:15:114583 const RTCConfiguration& configuration) {
4584 cricket::ServerAddresses stun_servers;
4585 std::vector<cricket::RelayServerConfig> turn_servers;
deadbeef293e9262017-01-11 20:28:304586 if (ParseIceServers(configuration.servers, &stun_servers, &turn_servers) !=
4587 RTCErrorType::NONE) {
Taylor Brandstettera1c30352016-05-13 15:15:114588 return false;
4589 }
4590
Taylor Brandstetterf8e65772016-06-28 00:20:154591 port_allocator_->Initialize();
Patrik Höglund3dc41062018-04-11 11:13:574592
Taylor Brandstettera1c30352016-05-13 15:15:114593 // To handle both internal and externally created port allocator, we will
4594 // enable BUNDLE here.
Patrik Höglund3dc41062018-04-11 11:13:574595 int portallocator_flags = port_allocator_->flags();
4596 portallocator_flags |= cricket::PORTALLOCATOR_ENABLE_SHARED_SOCKET |
4597 cricket::PORTALLOCATOR_ENABLE_IPV6 |
4598 cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI;
Taylor Brandstettera1c30352016-05-13 15:15:114599 // If the disable-IPv6 flag was specified, we'll not override it
4600 // by experiment.
4601 if (configuration.disable_ipv6) {
Patrik Höglund3dc41062018-04-11 11:13:574602 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
sprangc1b57a12017-02-28 16:50:474603 } else if (webrtc::field_trial::FindFullName("WebRTC-IPv6Default")
4604 .find("Disabled") == 0) {
Patrik Höglund3dc41062018-04-11 11:13:574605 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
Taylor Brandstettera1c30352016-05-13 15:15:114606 }
4607
zhihuangb09b3f92017-03-07 22:40:514608 if (configuration.disable_ipv6_on_wifi) {
Patrik Höglund3dc41062018-04-11 11:13:574609 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI);
Mirko Bonadei675513b2017-11-09 10:09:254610 RTC_LOG(LS_INFO) << "IPv6 candidates on Wi-Fi are disabled.";
zhihuangb09b3f92017-03-07 22:40:514611 }
4612
Taylor Brandstettera1c30352016-05-13 15:15:114613 if (configuration.tcp_candidate_policy == kTcpCandidatePolicyDisabled) {
Patrik Höglund3dc41062018-04-11 11:13:574614 portallocator_flags |= cricket::PORTALLOCATOR_DISABLE_TCP;
Mirko Bonadei675513b2017-11-09 10:09:254615 RTC_LOG(LS_INFO) << "TCP candidates are disabled.";
Taylor Brandstettera1c30352016-05-13 15:15:114616 }
4617
honghaiz60347052016-06-01 01:29:124618 if (configuration.candidate_network_policy ==
4619 kCandidateNetworkPolicyLowCost) {
Patrik Höglund3dc41062018-04-11 11:13:574620 portallocator_flags |= cricket::PORTALLOCATOR_DISABLE_COSTLY_NETWORKS;
Mirko Bonadei675513b2017-11-09 10:09:254621 RTC_LOG(LS_INFO) << "Do not gather candidates on high-cost networks";
honghaiz60347052016-06-01 01:29:124622 }
4623
Daniel Lazarenko2870b0a2018-01-25 09:30:224624 if (configuration.disable_link_local_networks) {
Patrik Höglund3dc41062018-04-11 11:13:574625 portallocator_flags |= cricket::PORTALLOCATOR_DISABLE_LINK_LOCAL_NETWORKS;
Daniel Lazarenko2870b0a2018-01-25 09:30:224626 RTC_LOG(LS_INFO) << "Disable candidates on link-local network interfaces.";
4627 }
4628
Patrik Höglund3dc41062018-04-11 11:13:574629 port_allocator_->set_flags(portallocator_flags);
Taylor Brandstettera1c30352016-05-13 15:15:114630 // No step delay is used while allocating ports.
4631 port_allocator_->set_step_delay(cricket::kMinimumStepDelay);
4632 port_allocator_->set_candidate_filter(
4633 ConvertIceTransportTypeToCandidateFilter(configuration.type));
deadbeefd21eab3e2017-07-26 23:50:114634 port_allocator_->set_max_ipv6_networks(configuration.max_ipv6_networks);
Taylor Brandstettera1c30352016-05-13 15:15:114635
4636 // Call this last since it may create pooled allocator sessions using the
4637 // properties set above.
Qingsi Wangdb53f8e2018-02-20 22:45:494638 port_allocator_->SetConfiguration(
4639 stun_servers, turn_servers, configuration.ice_candidate_pool_size,
4640 configuration.prune_turn_ports, configuration.turn_customizer,
4641 configuration.stun_candidate_keepalive_interval);
Taylor Brandstettera1c30352016-05-13 15:15:114642 return true;
4643}
4644
deadbeef91dd5672016-05-18 23:55:304645bool PeerConnection::ReconfigurePortAllocator_n(
deadbeef293e9262017-01-11 20:28:304646 const cricket::ServerAddresses& stun_servers,
4647 const std::vector<cricket::RelayServerConfig>& turn_servers,
4648 IceTransportsType type,
4649 int candidate_pool_size,
Jonas Orelandbdcee282017-10-10 12:01:404650 bool prune_turn_ports,
Qingsi Wangdb53f8e2018-02-20 22:45:494651 webrtc::TurnCustomizer* turn_customizer,
4652 rtc::Optional<int> stun_candidate_keepalive_interval) {
Taylor Brandstettera1c30352016-05-13 15:15:114653 port_allocator_->set_candidate_filter(
deadbeef293e9262017-01-11 20:28:304654 ConvertIceTransportTypeToCandidateFilter(type));
Taylor Brandstettera1c30352016-05-13 15:15:114655 // Call this last since it may create pooled allocator sessions using the
4656 // candidate filter set above.
deadbeef6de92f92016-12-13 02:49:324657 return port_allocator_->SetConfiguration(
Jonas Orelandbdcee282017-10-10 12:01:404658 stun_servers, turn_servers, candidate_pool_size, prune_turn_ports,
Qingsi Wangdb53f8e2018-02-20 22:45:494659 turn_customizer, stun_candidate_keepalive_interval);
Taylor Brandstettera1c30352016-05-13 15:15:114660}
4661
Steve Antonba818672017-11-06 18:21:574662cricket::ChannelManager* PeerConnection::channel_manager() const {
4663 return factory_->channel_manager();
4664}
4665
4666MetricsObserverInterface* PeerConnection::metrics_observer() const {
4667 return uma_observer_;
4668}
4669
Elad Alon99c3fe52017-10-13 14:29:404670bool PeerConnection::StartRtcEventLog_w(
Bjorn Tereliusde939432017-11-20 16:38:144671 std::unique_ptr<RtcEventLogOutput> output,
4672 int64_t output_period_ms) {
zhihuang77985012017-02-07 23:45:164673 if (!event_log_) {
4674 return false;
4675 }
Bjorn Tereliusde939432017-11-20 16:38:144676 return event_log_->StartLogging(std::move(output), output_period_ms);
ivoc14d5dbe2016-07-04 14:06:554677}
4678
4679void PeerConnection::StopRtcEventLog_w() {
zhihuang77985012017-02-07 23:45:164680 if (event_log_) {
4681 event_log_->StopLogging();
4682 }
ivoc14d5dbe2016-07-04 14:06:554683}
nisseeaabdf62017-05-05 09:23:024684
Steve Anton75737c02017-11-06 18:37:174685cricket::BaseChannel* PeerConnection::GetChannel(
4686 const std::string& content_name) {
Steve Antondcc3c022017-12-23 00:02:544687 for (auto transceiver : transceivers_) {
4688 cricket::BaseChannel* channel = transceiver->internal()->channel();
4689 if (channel && channel->content_name() == content_name) {
4690 return channel;
4691 }
Steve Anton75737c02017-11-06 18:37:174692 }
4693 if (rtp_data_channel() &&
4694 rtp_data_channel()->content_name() == content_name) {
4695 return rtp_data_channel();
4696 }
4697 return nullptr;
4698}
4699
4700bool PeerConnection::GetSctpSslRole(rtc::SSLRole* role) {
4701 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 10:09:254702 RTC_LOG(LS_INFO)
4703 << "Local and Remote descriptions must be applied to get the "
Jonas Olsson45cc8902018-02-13 09:37:074704 "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 18:37:174705 return false;
4706 }
4707 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 10:09:254708 RTC_LOG(LS_INFO) << "Non-rejected SCTP m= section is needed to get the "
Jonas Olsson45cc8902018-02-13 09:37:074709 "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 18:37:174710 return false;
4711 }
4712
Zhi Huange830e682018-03-30 17:48:354713 auto dtls_role = transport_controller_->GetDtlsRole(*sctp_mid_);
4714 if (dtls_role) {
4715 *role = *dtls_role;
4716 return true;
4717 }
4718 return false;
Steve Anton75737c02017-11-06 18:37:174719}
4720
4721bool PeerConnection::GetSslRole(const std::string& content_name,
4722 rtc::SSLRole* role) {
4723 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 10:09:254724 RTC_LOG(LS_INFO)
4725 << "Local and Remote descriptions must be applied to get the "
Jonas Olsson45cc8902018-02-13 09:37:074726 "SSL Role of the session.";
Steve Anton75737c02017-11-06 18:37:174727 return false;
4728 }
4729
Zhi Huange830e682018-03-30 17:48:354730 auto dtls_role = transport_controller_->GetDtlsRole(content_name);
4731 if (dtls_role) {
4732 *role = *dtls_role;
4733 return true;
4734 }
4735 return false;
Steve Anton75737c02017-11-06 18:37:174736}
4737
Steve Antonf8470812017-12-04 18:46:214738void PeerConnection::SetSessionError(SessionError error,
4739 const std::string& error_desc) {
4740 RTC_DCHECK_RUN_ON(signaling_thread());
4741 if (error != session_error_) {
4742 session_error_ = error;
4743 session_error_desc_ = error_desc;
Steve Anton75737c02017-11-06 18:37:174744 }
4745}
4746
Zhi Huange830e682018-03-30 17:48:354747RTCError PeerConnection::UpdateSessionState(
4748 SdpType type,
4749 cricket::ContentSource source,
4750 const cricket::SessionDescription* description) {
Steve Anton8a006912017-12-04 23:25:564751 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 18:37:174752
4753 // If there's already a pending error then no state transition should happen.
4754 // But all call-sites should be verifying this before calling us!
Steve Antonf8470812017-12-04 18:46:214755 RTC_DCHECK(session_error() == SessionError::kNone);
Steve Anton6d6a2ae2017-12-05 01:19:474756
Steve Anton6d6a2ae2017-12-05 01:19:474757 // If this is answer-ish we're ready to let media flow.
Steve Anton3828c062017-12-06 18:34:514758 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Antoned10bd92017-12-05 18:52:594759 EnableSending();
Steve Anton6d6a2ae2017-12-05 01:19:474760 }
4761
4762 // Update the signaling state according to the specified state machine (see
4763 // https://w3c.github.io/webrtc-pc/#rtcsignalingstate-enum).
Steve Anton3828c062017-12-06 18:34:514764 if (type == SdpType::kOffer) {
Steve Anton6d6a2ae2017-12-05 01:19:474765 ChangeSignalingState(source == cricket::CS_LOCAL
4766 ? PeerConnectionInterface::kHaveLocalOffer
4767 : PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton3828c062017-12-06 18:34:514768 } else if (type == SdpType::kPrAnswer) {
Steve Anton6d6a2ae2017-12-05 01:19:474769 ChangeSignalingState(source == cricket::CS_LOCAL
4770 ? PeerConnectionInterface::kHaveLocalPrAnswer
4771 : PeerConnectionInterface::kHaveRemotePrAnswer);
4772 } else {
Steve Anton3828c062017-12-06 18:34:514773 RTC_DCHECK(type == SdpType::kAnswer);
Steve Anton6d6a2ae2017-12-05 01:19:474774 ChangeSignalingState(PeerConnectionInterface::kStable);
4775 }
4776
4777 // Update internal objects according to the session description's media
4778 // descriptions.
Zhi Huange830e682018-03-30 17:48:354779 RTCError error = PushdownMediaDescription(type, source);
Steve Anton6d6a2ae2017-12-05 01:19:474780 if (!error.ok()) {
Steve Anton80dd7b52018-02-17 01:08:424781 return error;
Steve Anton6d6a2ae2017-12-05 01:19:474782 }
4783
Steve Anton8a006912017-12-04 23:25:564784 return RTCError::OK();
Steve Anton75737c02017-11-06 18:37:174785}
4786
Steve Anton8a006912017-12-04 23:25:564787RTCError PeerConnection::PushdownMediaDescription(
Steve Anton3828c062017-12-06 18:34:514788 SdpType type,
Steve Anton8a006912017-12-04 23:25:564789 cricket::ContentSource source) {
Steve Antoned10bd92017-12-05 18:52:594790 const SessionDescriptionInterface* sdesc =
4791 (source == cricket::CS_LOCAL ? local_description()
4792 : remote_description());
Steve Anton75737c02017-11-06 18:37:174793 RTC_DCHECK(sdesc);
Steve Antoned10bd92017-12-05 18:52:594794
4795 // Push down the new SDP media section for each audio/video transceiver.
4796 for (auto transceiver : transceivers_) {
Steve Anton75737c02017-11-06 18:37:174797 const ContentInfo* content_info =
Steve Antoned10bd92017-12-05 18:52:594798 FindMediaSectionForTransceiver(transceiver, sdesc);
4799 cricket::BaseChannel* channel = transceiver->internal()->channel();
4800 if (!channel || !content_info || content_info->rejected) {
Steve Anton75737c02017-11-06 18:37:174801 continue;
4802 }
4803 const MediaContentDescription* content_desc =
Steve Antonb1c1de12017-12-21 23:14:304804 content_info->media_description();
Steve Antoned10bd92017-12-05 18:52:594805 if (!content_desc) {
4806 continue;
4807 }
4808 std::string error;
4809 bool success =
4810 (source == cricket::CS_LOCAL)
Steve Anton3828c062017-12-06 18:34:514811 ? channel->SetLocalContent(content_desc, type, &error)
4812 : channel->SetRemoteContent(content_desc, type, &error);
Steve Antoned10bd92017-12-05 18:52:594813 if (!success) {
4814 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, std::move(error));
4815 }
4816 }
4817
4818 // If using the RtpDataChannel, push down the new SDP section for it too.
4819 if (rtp_data_channel_) {
4820 const ContentInfo* data_content =
4821 cricket::GetFirstDataContent(sdesc->description());
4822 if (data_content && !data_content->rejected) {
4823 const MediaContentDescription* data_desc =
Steve Antonb1c1de12017-12-21 23:14:304824 data_content->media_description();
Steve Antoned10bd92017-12-05 18:52:594825 if (data_desc) {
4826 std::string error;
4827 bool success =
4828 (source == cricket::CS_LOCAL)
Steve Anton3828c062017-12-06 18:34:514829 ? rtp_data_channel_->SetLocalContent(data_desc, type, &error)
4830 : rtp_data_channel_->SetRemoteContent(data_desc, type,
Steve Antoned10bd92017-12-05 18:52:594831 &error);
4832 if (!success) {
4833 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
4834 std::move(error));
4835 }
Steve Anton75737c02017-11-06 18:37:174836 }
4837 }
4838 }
Steve Antoned10bd92017-12-05 18:52:594839
Steve Anton75737c02017-11-06 18:37:174840 // Need complete offer/answer with an SCTP m= section before starting SCTP,
4841 // according to https://tools.ietf.org/html/draft-ietf-mmusic-sctp-sdp-19
4842 if (sctp_transport_ && local_description() && remote_description() &&
4843 cricket::GetFirstDataContent(local_description()->description()) &&
4844 cricket::GetFirstDataContent(remote_description()->description())) {
Steve Anton8a006912017-12-04 23:25:564845 bool success = network_thread()->Invoke<bool>(
Steve Anton75737c02017-11-06 18:37:174846 RTC_FROM_HERE,
4847 rtc::Bind(&PeerConnection::PushdownSctpParameters_n, this, source));
Steve Anton8a006912017-12-04 23:25:564848 if (!success) {
4849 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
4850 "Failed to push down SCTP parameters.");
4851 }
Steve Anton75737c02017-11-06 18:37:174852 }
Steve Antoned10bd92017-12-05 18:52:594853
Steve Anton8a006912017-12-04 23:25:564854 return RTCError::OK();
Steve Anton75737c02017-11-06 18:37:174855}
4856
4857bool PeerConnection::PushdownSctpParameters_n(cricket::ContentSource source) {
4858 RTC_DCHECK(network_thread()->IsCurrent());
4859 RTC_DCHECK(local_description());
4860 RTC_DCHECK(remote_description());
4861 // Apply the SCTP port (which is hidden inside a DataCodec structure...)
4862 // When we support "max-message-size", that would also be pushed down here.
4863 return sctp_transport_->Start(
4864 GetSctpPort(local_description()->description()),
4865 GetSctpPort(remote_description()->description()));
4866}
4867
Steve Anton8a006912017-12-04 23:25:564868RTCError PeerConnection::PushdownTransportDescription(
4869 cricket::ContentSource source,
Steve Anton3828c062017-12-06 18:34:514870 SdpType type) {
Steve Anton8a006912017-12-04 23:25:564871 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 18:37:174872
Zhi Huange830e682018-03-30 17:48:354873 if (source == cricket::CS_LOCAL) {
4874 const SessionDescriptionInterface* sdesc = local_description();
4875 RTC_DCHECK(sdesc);
4876 return transport_controller_->SetLocalDescription(type,
4877 sdesc->description());
4878 } else {
4879 const SessionDescriptionInterface* sdesc = remote_description();
4880 RTC_DCHECK(sdesc);
4881 return transport_controller_->SetRemoteDescription(type,
4882 sdesc->description());
Steve Anton75737c02017-11-06 18:37:174883 }
Steve Anton75737c02017-11-06 18:37:174884}
4885
4886bool PeerConnection::GetTransportDescription(
4887 const SessionDescription* description,
4888 const std::string& content_name,
4889 cricket::TransportDescription* tdesc) {
4890 if (!description || !tdesc) {
4891 return false;
4892 }
4893 const TransportInfo* transport_info =
4894 description->GetTransportInfoByName(content_name);
4895 if (!transport_info) {
4896 return false;
4897 }
4898 *tdesc = transport_info->description;
4899 return true;
4900}
4901
Steve Anton75737c02017-11-06 18:37:174902cricket::IceConfig PeerConnection::ParseIceConfig(
4903 const PeerConnectionInterface::RTCConfiguration& config) const {
4904 cricket::ContinualGatheringPolicy gathering_policy;
4905 // TODO(honghaiz): Add the third continual gathering policy in
4906 // PeerConnectionInterface and map it to GATHER_CONTINUALLY_AND_RECOVER.
4907 switch (config.continual_gathering_policy) {
4908 case PeerConnectionInterface::GATHER_ONCE:
4909 gathering_policy = cricket::GATHER_ONCE;
4910 break;
4911 case PeerConnectionInterface::GATHER_CONTINUALLY:
4912 gathering_policy = cricket::GATHER_CONTINUALLY;
4913 break;
4914 default:
4915 RTC_NOTREACHED();
4916 gathering_policy = cricket::GATHER_ONCE;
4917 }
Qingsi Wang9a5c6f82018-02-01 18:38:404918
Steve Anton75737c02017-11-06 18:37:174919 cricket::IceConfig ice_config;
Qingsi Wang866e08d2018-03-23 00:54:234920 ice_config.receiving_timeout = RTCConfigurationToIceConfigOptionalInt(
4921 config.ice_connection_receiving_timeout);
Steve Anton75737c02017-11-06 18:37:174922 ice_config.prioritize_most_likely_candidate_pairs =
4923 config.prioritize_most_likely_ice_candidate_pairs;
4924 ice_config.backup_connection_ping_interval =
Qingsi Wang866e08d2018-03-23 00:54:234925 RTCConfigurationToIceConfigOptionalInt(
4926 config.ice_backup_candidate_pair_ping_interval);
Steve Anton75737c02017-11-06 18:37:174927 ice_config.continual_gathering_policy = gathering_policy;
4928 ice_config.presume_writable_when_fully_relayed =
4929 config.presume_writable_when_fully_relayed;
Qingsi Wange6826d22018-03-08 22:55:144930 ice_config.ice_check_interval_strong_connectivity =
4931 config.ice_check_interval_strong_connectivity;
4932 ice_config.ice_check_interval_weak_connectivity =
4933 config.ice_check_interval_weak_connectivity;
Steve Anton75737c02017-11-06 18:37:174934 ice_config.ice_check_min_interval = config.ice_check_min_interval;
Qingsi Wangdb53f8e2018-02-20 22:45:494935 ice_config.stun_keepalive_interval = config.stun_candidate_keepalive_interval;
Steve Anton75737c02017-11-06 18:37:174936 ice_config.regather_all_networks_interval_range =
4937 config.ice_regather_interval_range;
Qingsi Wang9a5c6f82018-02-01 18:38:404938 ice_config.network_preference = config.network_preference;
Steve Anton75737c02017-11-06 18:37:174939 return ice_config;
4940}
4941
Steve Anton75737c02017-11-06 18:37:174942bool PeerConnection::GetLocalTrackIdBySsrc(uint32_t ssrc,
4943 std::string* track_id) {
4944 if (!local_description()) {
4945 return false;
4946 }
4947 return webrtc::GetTrackIdBySsrc(local_description()->description(), ssrc,
4948 track_id);
4949}
4950
4951bool PeerConnection::GetRemoteTrackIdBySsrc(uint32_t ssrc,
4952 std::string* track_id) {
4953 if (!remote_description()) {
4954 return false;
4955 }
4956 return webrtc::GetTrackIdBySsrc(remote_description()->description(), ssrc,
4957 track_id);
4958}
4959
4960bool PeerConnection::SendData(const cricket::SendDataParams& params,
4961 const rtc::CopyOnWriteBuffer& payload,
4962 cricket::SendDataResult* result) {
4963 if (!rtp_data_channel_ && !sctp_transport_) {
Mirko Bonadei675513b2017-11-09 10:09:254964 RTC_LOG(LS_ERROR) << "SendData called when rtp_data_channel_ "
Jonas Olsson45cc8902018-02-13 09:37:074965 "and sctp_transport_ are NULL.";
Steve Anton75737c02017-11-06 18:37:174966 return false;
4967 }
4968 return rtp_data_channel_
4969 ? rtp_data_channel_->SendData(params, payload, result)
4970 : network_thread()->Invoke<bool>(
4971 RTC_FROM_HERE,
4972 Bind(&cricket::SctpTransportInternal::SendData,
4973 sctp_transport_.get(), params, payload, result));
4974}
4975
4976bool PeerConnection::ConnectDataChannel(DataChannel* webrtc_data_channel) {
4977 if (!rtp_data_channel_ && !sctp_transport_) {
4978 // Don't log an error here, because DataChannels are expected to call
4979 // ConnectDataChannel in this state. It's the only way to initially tell
4980 // whether or not the underlying transport is ready.
4981 return false;
4982 }
4983 if (rtp_data_channel_) {
4984 rtp_data_channel_->SignalReadyToSendData.connect(
4985 webrtc_data_channel, &DataChannel::OnChannelReady);
4986 rtp_data_channel_->SignalDataReceived.connect(webrtc_data_channel,
4987 &DataChannel::OnDataReceived);
4988 } else {
4989 SignalSctpReadyToSendData.connect(webrtc_data_channel,
4990 &DataChannel::OnChannelReady);
4991 SignalSctpDataReceived.connect(webrtc_data_channel,
4992 &DataChannel::OnDataReceived);
4993 SignalSctpStreamClosedRemotely.connect(
4994 webrtc_data_channel, &DataChannel::OnStreamClosedRemotely);
4995 }
4996 return true;
4997}
4998
4999void PeerConnection::DisconnectDataChannel(DataChannel* webrtc_data_channel) {
5000 if (!rtp_data_channel_ && !sctp_transport_) {
Mirko Bonadei675513b2017-11-09 10:09:255001 RTC_LOG(LS_ERROR)
5002 << "DisconnectDataChannel called when rtp_data_channel_ and "
5003 "sctp_transport_ are NULL.";
Steve Anton75737c02017-11-06 18:37:175004 return;
5005 }
5006 if (rtp_data_channel_) {
5007 rtp_data_channel_->SignalReadyToSendData.disconnect(webrtc_data_channel);
5008 rtp_data_channel_->SignalDataReceived.disconnect(webrtc_data_channel);
5009 } else {
5010 SignalSctpReadyToSendData.disconnect(webrtc_data_channel);
5011 SignalSctpDataReceived.disconnect(webrtc_data_channel);
5012 SignalSctpStreamClosedRemotely.disconnect(webrtc_data_channel);
5013 }
5014}
5015
5016void PeerConnection::AddSctpDataStream(int sid) {
5017 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 10:09:255018 RTC_LOG(LS_ERROR)
5019 << "AddSctpDataStream called when sctp_transport_ is NULL.";
Steve Anton75737c02017-11-06 18:37:175020 return;
5021 }
5022 network_thread()->Invoke<void>(
5023 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::OpenStream,
5024 sctp_transport_.get(), sid));
5025}
5026
5027void PeerConnection::RemoveSctpDataStream(int sid) {
5028 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 10:09:255029 RTC_LOG(LS_ERROR) << "RemoveSctpDataStream called when sctp_transport_ is "
Jonas Olsson45cc8902018-02-13 09:37:075030 "NULL.";
Steve Anton75737c02017-11-06 18:37:175031 return;
5032 }
5033 network_thread()->Invoke<void>(
5034 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::ResetStream,
5035 sctp_transport_.get(), sid));
5036}
5037
5038bool PeerConnection::ReadyToSendData() const {
5039 return (rtp_data_channel_ && rtp_data_channel_->ready_to_send_data()) ||
5040 sctp_ready_to_send_data_;
5041}
5042
Zhi Huange830e682018-03-30 17:48:355043rtc::Optional<std::string> PeerConnection::sctp_transport_name() const {
5044 if (sctp_mid_ && transport_controller_) {
5045 auto dtls_transport = transport_controller_->GetDtlsTransport(*sctp_mid_);
5046 if (dtls_transport) {
5047 return dtls_transport->transport_name();
5048 }
5049 return rtc::Optional<std::string>();
5050 }
5051 return rtc::Optional<std::string>();
5052}
5053
Qingsi Wang72a43a12018-02-21 00:03:185054cricket::CandidateStatsList PeerConnection::GetPooledCandidateStats() const {
5055 cricket::CandidateStatsList candidate_states_list;
Patrik Höglund3dc41062018-04-11 11:13:575056 port_allocator_->GetCandidateStatsFromPooledSessions(&candidate_states_list);
Qingsi Wang72a43a12018-02-21 00:03:185057 return candidate_states_list;
5058}
5059
Steve Anton5dfde182018-02-06 18:34:405060std::map<std::string, std::string> PeerConnection::GetTransportNamesByMid()
5061 const {
5062 std::map<std::string, std::string> transport_names_by_mid;
5063 for (auto transceiver : transceivers_) {
5064 cricket::BaseChannel* channel = transceiver->internal()->channel();
5065 if (channel) {
5066 transport_names_by_mid[channel->content_name()] =
5067 channel->transport_name();
5068 }
Steve Anton75737c02017-11-06 18:37:175069 }
Steve Anton5dfde182018-02-06 18:34:405070 if (rtp_data_channel_) {
5071 transport_names_by_mid[rtp_data_channel_->content_name()] =
5072 rtp_data_channel_->transport_name();
Steve Anton75737c02017-11-06 18:37:175073 }
5074 if (sctp_transport_) {
Zhi Huange830e682018-03-30 17:48:355075 rtc::Optional<std::string> transport_name = sctp_transport_name();
5076 RTC_DCHECK(transport_name);
5077 transport_names_by_mid[*sctp_mid_] = *transport_name;
Steve Anton75737c02017-11-06 18:37:175078 }
Steve Anton5dfde182018-02-06 18:34:405079 return transport_names_by_mid;
Steve Anton75737c02017-11-06 18:37:175080}
5081
Steve Anton5dfde182018-02-06 18:34:405082std::map<std::string, cricket::TransportStats>
5083PeerConnection::GetTransportStatsByNames(
5084 const std::set<std::string>& transport_names) {
5085 if (!network_thread()->IsCurrent()) {
5086 return network_thread()
5087 ->Invoke<std::map<std::string, cricket::TransportStats>>(
5088 RTC_FROM_HERE,
5089 [&] { return GetTransportStatsByNames(transport_names); });
Steve Anton75737c02017-11-06 18:37:175090 }
Steve Anton5dfde182018-02-06 18:34:405091 std::map<std::string, cricket::TransportStats> transport_stats_by_name;
5092 for (const std::string& transport_name : transport_names) {
5093 cricket::TransportStats transport_stats;
5094 bool success =
5095 transport_controller_->GetStats(transport_name, &transport_stats);
5096 if (success) {
5097 transport_stats_by_name[transport_name] = std::move(transport_stats);
5098 } else {
5099 RTC_LOG(LS_ERROR) << "Failed to get transport stats for transport_name="
5100 << transport_name;
5101 }
5102 }
5103 return transport_stats_by_name;
Steve Anton75737c02017-11-06 18:37:175104}
5105
5106bool PeerConnection::GetLocalCertificate(
5107 const std::string& transport_name,
5108 rtc::scoped_refptr<rtc::RTCCertificate>* certificate) {
Zhi Huange830e682018-03-30 17:48:355109 if (!certificate) {
5110 return false;
5111 }
5112 *certificate = transport_controller_->GetLocalCertificate(transport_name);
5113 return *certificate != nullptr;
Steve Anton75737c02017-11-06 18:37:175114}
5115
Taylor Brandstetterc3928662018-02-23 21:04:515116std::unique_ptr<rtc::SSLCertChain> PeerConnection::GetRemoteSSLCertChain(
Steve Anton75737c02017-11-06 18:37:175117 const std::string& transport_name) {
Taylor Brandstetterc3928662018-02-23 21:04:515118 return transport_controller_->GetRemoteSSLCertChain(transport_name);
Steve Anton75737c02017-11-06 18:37:175119}
5120
5121cricket::DataChannelType PeerConnection::data_channel_type() const {
5122 return data_channel_type_;
5123}
5124
5125bool PeerConnection::IceRestartPending(const std::string& content_name) const {
5126 return pending_ice_restarts_.find(content_name) !=
5127 pending_ice_restarts_.end();
5128}
5129
Steve Anton75737c02017-11-06 18:37:175130bool PeerConnection::NeedsIceRestart(const std::string& content_name) const {
5131 return transport_controller_->NeedsIceRestart(content_name);
5132}
5133
5134void PeerConnection::OnCertificateReady(
5135 const rtc::scoped_refptr<rtc::RTCCertificate>& certificate) {
5136 transport_controller_->SetLocalCertificate(certificate);
5137}
5138
5139void PeerConnection::OnDtlsSrtpSetupFailure(cricket::BaseChannel*, bool rtcp) {
Steve Antonf8470812017-12-04 18:46:215140 SetSessionError(SessionError::kTransport,
5141 rtcp ? kDtlsSrtpSetupFailureRtcp : kDtlsSrtpSetupFailureRtp);
Steve Anton75737c02017-11-06 18:37:175142}
5143
5144void PeerConnection::OnTransportControllerConnectionState(
5145 cricket::IceConnectionState state) {
5146 switch (state) {
5147 case cricket::kIceConnectionConnecting:
5148 // If the current state is Connected or Completed, then there were
5149 // writable channels but now there are not, so the next state must
5150 // be Disconnected.
5151 // kIceConnectionConnecting is currently used as the default,
5152 // un-connected state by the TransportController, so its only use is
5153 // detecting disconnections.
5154 if (ice_connection_state_ ==
5155 PeerConnectionInterface::kIceConnectionConnected ||
5156 ice_connection_state_ ==
5157 PeerConnectionInterface::kIceConnectionCompleted) {
5158 SetIceConnectionState(
5159 PeerConnectionInterface::kIceConnectionDisconnected);
5160 }
5161 break;
5162 case cricket::kIceConnectionFailed:
5163 SetIceConnectionState(PeerConnectionInterface::kIceConnectionFailed);
5164 break;
5165 case cricket::kIceConnectionConnected:
Mirko Bonadei675513b2017-11-09 10:09:255166 RTC_LOG(LS_INFO) << "Changing to ICE connected state because "
Jonas Olsson45cc8902018-02-13 09:37:075167 "all transports are writable.";
Steve Anton75737c02017-11-06 18:37:175168 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
5169 break;
5170 case cricket::kIceConnectionCompleted:
Mirko Bonadei675513b2017-11-09 10:09:255171 RTC_LOG(LS_INFO) << "Changing to ICE completed state because "
Jonas Olsson45cc8902018-02-13 09:37:075172 "all transports are complete.";
Steve Anton75737c02017-11-06 18:37:175173 if (ice_connection_state_ !=
5174 PeerConnectionInterface::kIceConnectionConnected) {
5175 // If jumping directly from "checking" to "connected",
5176 // signal "connected" first.
5177 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
5178 }
5179 SetIceConnectionState(PeerConnectionInterface::kIceConnectionCompleted);
5180 if (metrics_observer()) {
5181 ReportTransportStats();
5182 }
5183 break;
5184 default:
5185 RTC_NOTREACHED();
5186 }
5187}
5188
5189void PeerConnection::OnTransportControllerCandidatesGathered(
5190 const std::string& transport_name,
5191 const cricket::Candidates& candidates) {
5192 RTC_DCHECK(signaling_thread()->IsCurrent());
5193 int sdp_mline_index;
5194 if (!GetLocalCandidateMediaIndex(transport_name, &sdp_mline_index)) {
Mirko Bonadei675513b2017-11-09 10:09:255195 RTC_LOG(LS_ERROR)
5196 << "OnTransportControllerCandidatesGathered: content name "
5197 << transport_name << " not found";
Steve Anton75737c02017-11-06 18:37:175198 return;
5199 }
5200
5201 for (cricket::Candidates::const_iterator citer = candidates.begin();
5202 citer != candidates.end(); ++citer) {
5203 // Use transport_name as the candidate media id.
5204 std::unique_ptr<JsepIceCandidate> candidate(
5205 new JsepIceCandidate(transport_name, sdp_mline_index, *citer));
5206 if (local_description()) {
5207 mutable_local_description()->AddCandidate(candidate.get());
5208 }
5209 OnIceCandidate(std::move(candidate));
5210 }
5211}
5212
5213void PeerConnection::OnTransportControllerCandidatesRemoved(
5214 const std::vector<cricket::Candidate>& candidates) {
5215 RTC_DCHECK(signaling_thread()->IsCurrent());
5216 // Sanity check.
5217 for (const cricket::Candidate& candidate : candidates) {
5218 if (candidate.transport_name().empty()) {
Mirko Bonadei675513b2017-11-09 10:09:255219 RTC_LOG(LS_ERROR) << "OnTransportControllerCandidatesRemoved: "
Jonas Olsson45cc8902018-02-13 09:37:075220 "empty content name in candidate "
Mirko Bonadei675513b2017-11-09 10:09:255221 << candidate.ToString();
Steve Anton75737c02017-11-06 18:37:175222 return;
5223 }
5224 }
5225
5226 if (local_description()) {
5227 mutable_local_description()->RemoveCandidates(candidates);
5228 }
5229 OnIceCandidatesRemoved(candidates);
5230}
5231
5232void PeerConnection::OnTransportControllerDtlsHandshakeError(
5233 rtc::SSLHandshakeError error) {
5234 if (metrics_observer()) {
5235 metrics_observer()->IncrementEnumCounter(
5236 webrtc::kEnumCounterDtlsHandshakeError, static_cast<int>(error),
5237 static_cast<int>(rtc::SSLHandshakeError::MAX_VALUE));
5238 }
5239}
5240
Steve Antoned10bd92017-12-05 18:52:595241void PeerConnection::EnableSending() {
5242 for (auto transceiver : transceivers_) {
5243 cricket::BaseChannel* channel = transceiver->internal()->channel();
5244 if (channel && !channel->enabled()) {
5245 channel->Enable(true);
5246 }
Steve Anton75737c02017-11-06 18:37:175247 }
5248
Steve Anton4171afb2017-11-20 18:20:225249 if (rtp_data_channel_ && !rtp_data_channel_->enabled()) {
Steve Anton75737c02017-11-06 18:37:175250 rtp_data_channel_->Enable(true);
Steve Anton4171afb2017-11-20 18:20:225251 }
Steve Anton75737c02017-11-06 18:37:175252}
5253
5254// Returns the media index for a local ice candidate given the content name.
5255bool PeerConnection::GetLocalCandidateMediaIndex(
5256 const std::string& content_name,
5257 int* sdp_mline_index) {
5258 if (!local_description() || !sdp_mline_index) {
5259 return false;
5260 }
5261
5262 bool content_found = false;
5263 const ContentInfos& contents = local_description()->description()->contents();
5264 for (size_t index = 0; index < contents.size(); ++index) {
5265 if (contents[index].name == content_name) {
5266 *sdp_mline_index = static_cast<int>(index);
5267 content_found = true;
5268 break;
5269 }
5270 }
5271 return content_found;
5272}
5273
5274bool PeerConnection::UseCandidatesInSessionDescription(
5275 const SessionDescriptionInterface* remote_desc) {
5276 if (!remote_desc) {
5277 return true;
5278 }
5279 bool ret = true;
5280
5281 for (size_t m = 0; m < remote_desc->number_of_mediasections(); ++m) {
5282 const IceCandidateCollection* candidates = remote_desc->candidates(m);
5283 for (size_t n = 0; n < candidates->count(); ++n) {
5284 const IceCandidateInterface* candidate = candidates->at(n);
5285 bool valid = false;
5286 if (!ReadyToUseRemoteCandidate(candidate, remote_desc, &valid)) {
5287 if (valid) {
Mirko Bonadei675513b2017-11-09 10:09:255288 RTC_LOG(LS_INFO)
5289 << "UseCandidatesInSessionDescription: Not ready to use "
Jonas Olsson45cc8902018-02-13 09:37:075290 "candidate.";
Steve Anton75737c02017-11-06 18:37:175291 }
5292 continue;
5293 }
5294 ret = UseCandidate(candidate);
5295 if (!ret) {
5296 break;
5297 }
5298 }
5299 }
5300 return ret;
5301}
5302
5303bool PeerConnection::UseCandidate(const IceCandidateInterface* candidate) {
5304 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
5305 size_t remote_content_size =
5306 remote_description()->description()->contents().size();
5307 if (mediacontent_index >= remote_content_size) {
Mirko Bonadei675513b2017-11-09 10:09:255308 RTC_LOG(LS_ERROR) << "UseCandidate: Invalid candidate media index.";
Steve Anton75737c02017-11-06 18:37:175309 return false;
5310 }
5311
5312 cricket::ContentInfo content =
5313 remote_description()->description()->contents()[mediacontent_index];
5314 std::vector<cricket::Candidate> candidates;
5315 candidates.push_back(candidate->candidate());
5316 // Invoking BaseSession method to handle remote candidates.
Zhi Huange830e682018-03-30 17:48:355317 RTCError error =
5318 transport_controller_->AddRemoteCandidates(content.name, candidates);
Henrik Boström5d8f8fa2018-04-13 15:22:505319 if (error.ok()) {
5320 // Candidates successfully submitted for checking.
5321 if (ice_connection_state_ == PeerConnectionInterface::kIceConnectionNew ||
5322 ice_connection_state_ ==
5323 PeerConnectionInterface::kIceConnectionDisconnected) {
5324 // If state is New, then the session has just gotten its first remote ICE
5325 // candidates, so go to Checking.
5326 // If state is Disconnected, the session is re-using old candidates or
5327 // receiving additional ones, so go to Checking.
5328 // If state is Connected, stay Connected.
5329 // TODO(bemasc): If state is Connected, and the new candidates are for a
5330 // newly added transport, then the state actually _should_ move to
5331 // checking. Add a way to distinguish that case.
5332 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
5333 }
5334 // TODO(bemasc): If state is Completed, go back to Connected.
5335 } else if (error.message()) {
Zhi Huange830e682018-03-30 17:48:355336 RTC_LOG(LS_WARNING) << error.message();
Steve Anton75737c02017-11-06 18:37:175337 }
5338 return true;
5339}
5340
5341void PeerConnection::RemoveUnusedChannels(const SessionDescription* desc) {
Steve Anton75737c02017-11-06 18:37:175342 // Destroy video channel first since it may have a pointer to the
5343 // voice channel.
5344 const cricket::ContentInfo* video_info = cricket::GetFirstVideoContent(desc);
Steve Anton6fec8802017-12-04 18:37:295345 if (!video_info || video_info->rejected) {
5346 DestroyTransceiverChannel(GetVideoTransceiver());
Steve Anton75737c02017-11-06 18:37:175347 }
5348
Steve Anton6fec8802017-12-04 18:37:295349 const cricket::ContentInfo* audio_info = cricket::GetFirstAudioContent(desc);
5350 if (!audio_info || audio_info->rejected) {
5351 DestroyTransceiverChannel(GetAudioTransceiver());
Steve Anton75737c02017-11-06 18:37:175352 }
5353
5354 const cricket::ContentInfo* data_info = cricket::GetFirstDataContent(desc);
5355 if (!data_info || data_info->rejected) {
Steve Anton6fec8802017-12-04 18:37:295356 DestroyDataChannel();
Steve Anton75737c02017-11-06 18:37:175357 }
5358}
5359
Steve Antondcc3c022017-12-23 00:02:545360RTCErrorOr<const cricket::ContentGroup*> PeerConnection::GetEarlyBundleGroup(
5361 const SessionDescription& desc) const {
Steve Anton75737c02017-11-06 18:37:175362 const cricket::ContentGroup* bundle_group = nullptr;
5363 if (configuration_.bundle_policy ==
5364 PeerConnectionInterface::kBundlePolicyMaxBundle) {
Steve Antondcc3c022017-12-23 00:02:545365 bundle_group = desc.GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton75737c02017-11-06 18:37:175366 if (!bundle_group) {
Steve Anton8a006912017-12-04 23:25:565367 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5368 "max-bundle configured but session description "
5369 "has no BUNDLE group");
Steve Anton75737c02017-11-06 18:37:175370 }
5371 }
Steve Antondcc3c022017-12-23 00:02:545372 return std::move(bundle_group);
5373}
5374
5375RTCError PeerConnection::CreateChannels(const SessionDescription& desc) {
Zhi Huange830e682018-03-30 17:48:355376 // Creating the media channels. Transports should already have been created
5377 // at this point.
Steve Antondcc3c022017-12-23 00:02:545378 const cricket::ContentInfo* voice = cricket::GetFirstAudioContent(&desc);
Steve Antoneda6ccd2017-12-04 18:21:555379 if (voice && !voice->rejected &&
5380 !GetAudioTransceiver()->internal()->channel()) {
Zhi Huange830e682018-03-30 17:48:355381 cricket::VoiceChannel* voice_channel = CreateVoiceChannel(voice->name);
Steve Antoneda6ccd2017-12-04 18:21:555382 if (!voice_channel) {
Steve Anton8a006912017-12-04 23:25:565383 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5384 "Failed to create voice channel.");
Steve Antoneda6ccd2017-12-04 18:21:555385 }
5386 GetAudioTransceiver()->internal()->SetChannel(voice_channel);
5387 }
5388
Steve Antondcc3c022017-12-23 00:02:545389 const cricket::ContentInfo* video = cricket::GetFirstVideoContent(&desc);
Steve Antoneda6ccd2017-12-04 18:21:555390 if (video && !video->rejected &&
5391 !GetVideoTransceiver()->internal()->channel()) {
Zhi Huange830e682018-03-30 17:48:355392 cricket::VideoChannel* video_channel = CreateVideoChannel(video->name);
Steve Antoneda6ccd2017-12-04 18:21:555393 if (!video_channel) {
Steve Anton8a006912017-12-04 23:25:565394 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5395 "Failed to create video channel.");
Steve Anton75737c02017-11-06 18:37:175396 }
Steve Antoneda6ccd2017-12-04 18:21:555397 GetVideoTransceiver()->internal()->SetChannel(video_channel);
Steve Anton75737c02017-11-06 18:37:175398 }
5399
Steve Antondcc3c022017-12-23 00:02:545400 const cricket::ContentInfo* data = cricket::GetFirstDataContent(&desc);
Steve Anton75737c02017-11-06 18:37:175401 if (data_channel_type_ != cricket::DCT_NONE && data && !data->rejected &&
5402 !rtp_data_channel_ && !sctp_transport_) {
Zhi Huange830e682018-03-30 17:48:355403 if (!CreateDataChannel(data->name)) {
Steve Anton8a006912017-12-04 23:25:565404 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5405 "Failed to create data channel.");
Steve Anton75737c02017-11-06 18:37:175406 }
5407 }
5408
Steve Anton8a006912017-12-04 23:25:565409 return RTCError::OK();
Steve Anton75737c02017-11-06 18:37:175410}
5411
Steve Anton4171afb2017-11-20 18:20:225412// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 18:21:555413cricket::VoiceChannel* PeerConnection::CreateVoiceChannel(
Zhi Huange830e682018-03-30 17:48:355414 const std::string& mid) {
5415 RtpTransportInternal* rtp_transport =
5416 transport_controller_->GetRtpTransport(mid);
5417 RTC_DCHECK(rtp_transport);
Steve Anton75737c02017-11-06 18:37:175418 cricket::VoiceChannel* voice_channel = channel_manager()->CreateVoiceChannel(
Zhi Huange830e682018-03-30 17:48:355419 call_.get(), configuration_.media_config, rtp_transport,
5420 signaling_thread(), mid, SrtpRequired(),
5421 factory_->options().crypto_options, audio_options_);
Steve Anton75737c02017-11-06 18:37:175422 if (!voice_channel) {
Steve Antoneda6ccd2017-12-04 18:21:555423 return nullptr;
Steve Anton75737c02017-11-06 18:37:175424 }
Steve Anton75737c02017-11-06 18:37:175425 voice_channel->SignalDtlsSrtpSetupFailure.connect(
5426 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 18:37:175427 voice_channel->SignalSentPacket.connect(this,
5428 &PeerConnection::OnSentPacket_w);
Zhi Huange830e682018-03-30 17:48:355429 voice_channel->SetRtpTransport(rtp_transport);
Steve Antondb67ba12018-03-20 00:41:425430 if (uma_observer_) {
5431 voice_channel->SetMetricsObserver(uma_observer_);
5432 }
Steve Anton4171afb2017-11-20 18:20:225433
Steve Antoneda6ccd2017-12-04 18:21:555434 return voice_channel;
Steve Anton75737c02017-11-06 18:37:175435}
5436
Steve Anton4171afb2017-11-20 18:20:225437// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 18:21:555438cricket::VideoChannel* PeerConnection::CreateVideoChannel(
Zhi Huange830e682018-03-30 17:48:355439 const std::string& mid) {
5440 RtpTransportInternal* rtp_transport =
5441 transport_controller_->GetRtpTransport(mid);
5442 RTC_DCHECK(rtp_transport);
Steve Anton75737c02017-11-06 18:37:175443 cricket::VideoChannel* video_channel = channel_manager()->CreateVideoChannel(
Zhi Huange830e682018-03-30 17:48:355444 call_.get(), configuration_.media_config, rtp_transport,
5445 signaling_thread(), mid, SrtpRequired(),
5446 factory_->options().crypto_options, video_options_);
Steve Anton75737c02017-11-06 18:37:175447 if (!video_channel) {
Steve Antoneda6ccd2017-12-04 18:21:555448 return nullptr;
Steve Anton75737c02017-11-06 18:37:175449 }
Steve Anton75737c02017-11-06 18:37:175450 video_channel->SignalDtlsSrtpSetupFailure.connect(
5451 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 18:37:175452 video_channel->SignalSentPacket.connect(this,
5453 &PeerConnection::OnSentPacket_w);
Zhi Huange830e682018-03-30 17:48:355454 video_channel->SetRtpTransport(rtp_transport);
Steve Antondb67ba12018-03-20 00:41:425455 if (uma_observer_) {
5456 video_channel->SetMetricsObserver(uma_observer_);
5457 }
Steve Anton4171afb2017-11-20 18:20:225458
Steve Antoneda6ccd2017-12-04 18:21:555459 return video_channel;
Steve Anton75737c02017-11-06 18:37:175460}
5461
Zhi Huange830e682018-03-30 17:48:355462bool PeerConnection::CreateDataChannel(const std::string& mid) {
Steve Anton75737c02017-11-06 18:37:175463 bool sctp = (data_channel_type_ == cricket::DCT_SCTP);
5464 if (sctp) {
5465 if (!sctp_factory_) {
Mirko Bonadei675513b2017-11-09 10:09:255466 RTC_LOG(LS_ERROR)
Steve Anton75737c02017-11-06 18:37:175467 << "Trying to create SCTP transport, but didn't compile with "
5468 "SCTP support (HAVE_SCTP)";
5469 return false;
5470 }
5471 if (!network_thread()->Invoke<bool>(
Zhi Huange830e682018-03-30 17:48:355472 RTC_FROM_HERE,
5473 rtc::Bind(&PeerConnection::CreateSctpTransport_n, this, mid))) {
Steve Anton75737c02017-11-06 18:37:175474 return false;
5475 }
Steve Antoneda6ccd2017-12-04 18:21:555476 for (const auto& channel : sctp_data_channels_) {
5477 channel->OnTransportChannelCreated();
5478 }
Steve Anton75737c02017-11-06 18:37:175479 } else {
Zhi Huange830e682018-03-30 17:48:355480 RtpTransportInternal* rtp_transport =
5481 transport_controller_->GetRtpTransport(mid);
5482 RTC_DCHECK(rtp_transport);
Steve Anton75737c02017-11-06 18:37:175483 rtp_data_channel_ = channel_manager()->CreateRtpDataChannel(
Zhi Huange830e682018-03-30 17:48:355484 configuration_.media_config, rtp_transport, signaling_thread(), mid,
5485 SrtpRequired(), factory_->options().crypto_options);
Steve Anton75737c02017-11-06 18:37:175486 if (!rtp_data_channel_) {
Steve Anton75737c02017-11-06 18:37:175487 return false;
5488 }
Steve Anton75737c02017-11-06 18:37:175489 rtp_data_channel_->SignalDtlsSrtpSetupFailure.connect(
5490 this, &PeerConnection::OnDtlsSrtpSetupFailure);
5491 rtp_data_channel_->SignalSentPacket.connect(
5492 this, &PeerConnection::OnSentPacket_w);
Zhi Huange830e682018-03-30 17:48:355493 rtp_data_channel_->SetRtpTransport(rtp_transport);
Steve Antondb67ba12018-03-20 00:41:425494 if (uma_observer_) {
5495 rtp_data_channel_->SetMetricsObserver(uma_observer_);
5496 }
Steve Anton75737c02017-11-06 18:37:175497 }
5498
Steve Anton75737c02017-11-06 18:37:175499 return true;
5500}
5501
5502Call::Stats PeerConnection::GetCallStats() {
5503 if (!worker_thread()->IsCurrent()) {
5504 return worker_thread()->Invoke<Call::Stats>(
5505 RTC_FROM_HERE, rtc::Bind(&PeerConnection::GetCallStats, this));
5506 }
5507 if (call_) {
5508 return call_->GetStats();
5509 } else {
5510 return Call::Stats();
5511 }
5512}
5513
Zhi Huange830e682018-03-30 17:48:355514bool PeerConnection::CreateSctpTransport_n(const std::string& mid) {
Steve Anton75737c02017-11-06 18:37:175515 RTC_DCHECK(network_thread()->IsCurrent());
5516 RTC_DCHECK(sctp_factory_);
Zhi Huang644fde42018-04-03 02:16:265517 cricket::DtlsTransportInternal* dtls_transport =
Zhi Huange830e682018-03-30 17:48:355518 transport_controller_->GetDtlsTransport(mid);
Zhi Huang644fde42018-04-03 02:16:265519 RTC_DCHECK(dtls_transport);
5520 sctp_transport_ = sctp_factory_->CreateSctpTransport(dtls_transport);
Steve Anton75737c02017-11-06 18:37:175521 RTC_DCHECK(sctp_transport_);
5522 sctp_invoker_.reset(new rtc::AsyncInvoker());
5523 sctp_transport_->SignalReadyToSendData.connect(
5524 this, &PeerConnection::OnSctpTransportReadyToSendData_n);
5525 sctp_transport_->SignalDataReceived.connect(
5526 this, &PeerConnection::OnSctpTransportDataReceived_n);
5527 sctp_transport_->SignalStreamClosedRemotely.connect(
5528 this, &PeerConnection::OnSctpStreamClosedRemotely_n);
Zhi Huange830e682018-03-30 17:48:355529 sctp_mid_ = mid;
Zhi Huang644fde42018-04-03 02:16:265530 sctp_transport_->SetDtlsTransport(dtls_transport);
Zhi Huange830e682018-03-30 17:48:355531 return true;
Steve Anton75737c02017-11-06 18:37:175532}
5533
5534void PeerConnection::DestroySctpTransport_n() {
5535 RTC_DCHECK(network_thread()->IsCurrent());
5536 sctp_transport_.reset(nullptr);
Zhi Huange830e682018-03-30 17:48:355537 sctp_mid_.reset();
Steve Anton75737c02017-11-06 18:37:175538 sctp_invoker_.reset(nullptr);
5539 sctp_ready_to_send_data_ = false;
5540}
5541
5542void PeerConnection::OnSctpTransportReadyToSendData_n() {
5543 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5544 RTC_DCHECK(network_thread()->IsCurrent());
5545 // Note: Cannot use rtc::Bind here because it will grab a reference to
5546 // PeerConnection and potentially cause PeerConnection to live longer than
5547 // expected. It is safe not to grab a reference since the sctp_invoker_ will
5548 // be destroyed before PeerConnection is destroyed, and at that point all
5549 // pending tasks will be cleared.
5550 sctp_invoker_->AsyncInvoke<void>(RTC_FROM_HERE, signaling_thread(), [this] {
5551 OnSctpTransportReadyToSendData_s(true);
5552 });
5553}
5554
5555void PeerConnection::OnSctpTransportReadyToSendData_s(bool ready) {
5556 RTC_DCHECK(signaling_thread()->IsCurrent());
5557 sctp_ready_to_send_data_ = ready;
5558 SignalSctpReadyToSendData(ready);
5559}
5560
5561void PeerConnection::OnSctpTransportDataReceived_n(
5562 const cricket::ReceiveDataParams& params,
5563 const rtc::CopyOnWriteBuffer& payload) {
5564 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5565 RTC_DCHECK(network_thread()->IsCurrent());
5566 // Note: Cannot use rtc::Bind here because it will grab a reference to
5567 // PeerConnection and potentially cause PeerConnection to live longer than
5568 // expected. It is safe not to grab a reference since the sctp_invoker_ will
5569 // be destroyed before PeerConnection is destroyed, and at that point all
5570 // pending tasks will be cleared.
5571 sctp_invoker_->AsyncInvoke<void>(
5572 RTC_FROM_HERE, signaling_thread(), [this, params, payload] {
5573 OnSctpTransportDataReceived_s(params, payload);
5574 });
5575}
5576
5577void PeerConnection::OnSctpTransportDataReceived_s(
5578 const cricket::ReceiveDataParams& params,
5579 const rtc::CopyOnWriteBuffer& payload) {
5580 RTC_DCHECK(signaling_thread()->IsCurrent());
5581 if (params.type == cricket::DMT_CONTROL && IsOpenMessage(payload)) {
5582 // Received OPEN message; parse and signal that a new data channel should
5583 // be created.
5584 std::string label;
5585 InternalDataChannelInit config;
5586 config.id = params.ssrc;
5587 if (!ParseDataChannelOpenMessage(payload, &label, &config)) {
Mirko Bonadei675513b2017-11-09 10:09:255588 RTC_LOG(LS_WARNING) << "Failed to parse the OPEN message for sid "
5589 << params.ssrc;
Steve Anton75737c02017-11-06 18:37:175590 return;
5591 }
5592 config.open_handshake_role = InternalDataChannelInit::kAcker;
5593 OnDataChannelOpenMessage(label, config);
5594 } else {
5595 // Otherwise just forward the signal.
5596 SignalSctpDataReceived(params, payload);
5597 }
5598}
5599
5600void PeerConnection::OnSctpStreamClosedRemotely_n(int sid) {
5601 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5602 RTC_DCHECK(network_thread()->IsCurrent());
5603 sctp_invoker_->AsyncInvoke<void>(
5604 RTC_FROM_HERE, signaling_thread(),
5605 rtc::Bind(&sigslot::signal1<int>::operator(),
5606 &SignalSctpStreamClosedRemotely, sid));
5607}
5608
5609// Returns false if bundle is enabled and rtcp_mux is disabled.
5610bool PeerConnection::ValidateBundleSettings(const SessionDescription* desc) {
5611 bool bundle_enabled = desc->HasGroup(cricket::GROUP_TYPE_BUNDLE);
5612 if (!bundle_enabled)
5613 return true;
5614
5615 const cricket::ContentGroup* bundle_group =
5616 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
5617 RTC_DCHECK(bundle_group != NULL);
5618
5619 const cricket::ContentInfos& contents = desc->contents();
5620 for (cricket::ContentInfos::const_iterator citer = contents.begin();
5621 citer != contents.end(); ++citer) {
5622 const cricket::ContentInfo* content = (&*citer);
5623 RTC_DCHECK(content != NULL);
5624 if (bundle_group->HasContentName(content->name) && !content->rejected &&
Steve Anton5adfafd2017-12-21 00:34:005625 content->type == MediaProtocolType::kRtp) {
Steve Anton75737c02017-11-06 18:37:175626 if (!HasRtcpMuxEnabled(content))
5627 return false;
5628 }
5629 }
5630 // RTCP-MUX is enabled in all the contents.
5631 return true;
5632}
5633
5634bool PeerConnection::HasRtcpMuxEnabled(const cricket::ContentInfo* content) {
Steve Antonb1c1de12017-12-21 23:14:305635 return content->media_description()->rtcp_mux();
Steve Anton75737c02017-11-06 18:37:175636}
5637
Steve Anton8a006912017-12-04 23:25:565638RTCError PeerConnection::ValidateSessionDescription(
Steve Anton75737c02017-11-06 18:37:175639 const SessionDescriptionInterface* sdesc,
Steve Anton8a006912017-12-04 23:25:565640 cricket::ContentSource source) {
Steve Antonf8470812017-12-04 18:46:215641 if (session_error() != SessionError::kNone) {
Steve Anton8a006912017-12-04 23:25:565642 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
Steve Anton75737c02017-11-06 18:37:175643 }
5644
5645 if (!sdesc || !sdesc->description()) {
Steve Anton8a006912017-12-04 23:25:565646 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidSdp);
Steve Anton75737c02017-11-06 18:37:175647 }
5648
Steve Anton3828c062017-12-06 18:34:515649 SdpType type = sdesc->GetType();
5650 if ((source == cricket::CS_LOCAL && !ExpectSetLocalDescription(type)) ||
5651 (source == cricket::CS_REMOTE && !ExpectSetRemoteDescription(type))) {
Steve Anton8a006912017-12-04 23:25:565652 LOG_AND_RETURN_ERROR(
Harald Alvestrand5081c0c2018-03-09 14:18:035653 RTCErrorType::INVALID_STATE,
Steve Anton8a006912017-12-04 23:25:565654 "Called in wrong state: " + GetSignalingStateString(signaling_state()));
Steve Anton75737c02017-11-06 18:37:175655 }
5656
5657 // Verify crypto settings.
5658 std::string crypto_error;
Steve Anton8a006912017-12-04 23:25:565659 if (webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED ||
5660 dtls_enabled_) {
Harald Alvestrand194939b2018-01-24 15:04:135661 RTCError crypto_error =
5662 VerifyCrypto(sdesc->description(), dtls_enabled_, uma_observer_);
Steve Anton8a006912017-12-04 23:25:565663 if (!crypto_error.ok()) {
5664 return crypto_error;
5665 }
Steve Anton75737c02017-11-06 18:37:175666 }
5667
5668 // Verify ice-ufrag and ice-pwd.
5669 if (!VerifyIceUfragPwdPresent(sdesc->description())) {
Steve Anton8a006912017-12-04 23:25:565670 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5671 kSdpWithoutIceUfragPwd);
Steve Anton75737c02017-11-06 18:37:175672 }
5673
5674 if (!ValidateBundleSettings(sdesc->description())) {
Steve Anton8a006912017-12-04 23:25:565675 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5676 kBundleWithoutRtcpMux);
Steve Anton75737c02017-11-06 18:37:175677 }
5678
5679 // TODO(skvlad): When the local rtcp-mux policy is Require, reject any
5680 // m-lines that do not rtcp-mux enabled.
5681
5682 // Verify m-lines in Answer when compared against Offer.
Steve Anton3828c062017-12-06 18:34:515683 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Seth Hampsonae8a90a2018-02-13 23:33:485684 // With an answer we want to compare the new answer session description with
5685 // the offer's session description from the current negotiation.
Steve Anton75737c02017-11-06 18:37:175686 const cricket::SessionDescription* offer_desc =
5687 (source == cricket::CS_LOCAL) ? remote_description()->description()
5688 : local_description()->description();
Seth Hampsonae8a90a2018-02-13 23:33:485689 if (!MediaSectionsHaveSameCount(*offer_desc, *sdesc->description()) ||
5690 !MediaSectionsInSameOrder(*offer_desc, nullptr, *sdesc->description(),
5691 type)) {
Steve Anton8a006912017-12-04 23:25:565692 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5693 kMlineMismatchInAnswer);
Steve Anton75737c02017-11-06 18:37:175694 }
5695 } else {
Steve Anton75737c02017-11-06 18:37:175696 // The re-offers should respect the order of m= sections in current
5697 // description. See RFC3264 Section 8 paragraph 4 for more details.
Seth Hampsonae8a90a2018-02-13 23:33:485698 // With a re-offer, either the current local or current remote descriptions
5699 // could be the most up to date, so we would like to check against both of
5700 // them if they exist. It could be the case that one of them has a 0 port
5701 // for a media section, but the other does not. This is important to check
5702 // against in the case that we are recycling an m= section.
5703 const cricket::SessionDescription* current_desc = nullptr;
5704 const cricket::SessionDescription* secondary_current_desc = nullptr;
5705 if (local_description()) {
5706 current_desc = local_description()->description();
5707 if (remote_description()) {
5708 secondary_current_desc = remote_description()->description();
5709 }
5710 } else if (remote_description()) {
5711 current_desc = remote_description()->description();
5712 }
Steve Anton75737c02017-11-06 18:37:175713 if (current_desc &&
Seth Hampsonae8a90a2018-02-13 23:33:485714 !MediaSectionsInSameOrder(*current_desc, secondary_current_desc,
5715 *sdesc->description(), type)) {
Steve Anton8a006912017-12-04 23:25:565716 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5717 kMlineMismatchInSubsequentOffer);
Steve Anton75737c02017-11-06 18:37:175718 }
5719 }
5720
Steve Antonba42e992018-04-09 21:10:015721 if (IsUnifiedPlan()) {
5722 // Ensure that each audio and video media section has at most one
5723 // "StreamParams". This will return an error if receiving a session
5724 // description from a "Plan B" endpoint which adds multiple tracks of the
5725 // same type. With Unified Plan, there can only be at most one track per
5726 // media section.
5727 for (const ContentInfo& content : sdesc->description()->contents()) {
5728 const MediaContentDescription& desc = *content.description;
5729 if ((desc.type() == cricket::MEDIA_TYPE_AUDIO ||
5730 desc.type() == cricket::MEDIA_TYPE_VIDEO) &&
5731 desc.streams().size() > 1u) {
5732 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5733 "Media section has more than one track specified "
5734 "with a=ssrc lines which is not supported with "
5735 "Unified Plan.");
5736 }
5737 }
5738 }
5739
Steve Anton8a006912017-12-04 23:25:565740 return RTCError::OK();
Steve Anton75737c02017-11-06 18:37:175741}
5742
Steve Anton3828c062017-12-06 18:34:515743bool PeerConnection::ExpectSetLocalDescription(SdpType type) {
Steve Anton75737c02017-11-06 18:37:175744 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 18:34:515745 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 18:37:175746 return (state == PeerConnectionInterface::kStable) ||
5747 (state == PeerConnectionInterface::kHaveLocalOffer);
Steve Anton20393062017-12-05 00:24:525748 } else {
Steve Anton3828c062017-12-06 18:34:515749 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 18:37:175750 return (state == PeerConnectionInterface::kHaveRemoteOffer) ||
5751 (state == PeerConnectionInterface::kHaveLocalPrAnswer);
5752 }
5753}
5754
Steve Anton3828c062017-12-06 18:34:515755bool PeerConnection::ExpectSetRemoteDescription(SdpType type) {
Steve Anton75737c02017-11-06 18:37:175756 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 18:34:515757 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 18:37:175758 return (state == PeerConnectionInterface::kStable) ||
5759 (state == PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton20393062017-12-05 00:24:525760 } else {
Steve Anton3828c062017-12-06 18:34:515761 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 18:37:175762 return (state == PeerConnectionInterface::kHaveLocalOffer) ||
5763 (state == PeerConnectionInterface::kHaveRemotePrAnswer);
5764 }
5765}
5766
Steve Antonf8470812017-12-04 18:46:215767const char* PeerConnection::SessionErrorToString(SessionError error) const {
5768 switch (error) {
5769 case SessionError::kNone:
5770 return "ERROR_NONE";
5771 case SessionError::kContent:
5772 return "ERROR_CONTENT";
5773 case SessionError::kTransport:
5774 return "ERROR_TRANSPORT";
5775 }
5776 RTC_NOTREACHED();
5777 return "";
5778}
5779
Steve Anton75737c02017-11-06 18:37:175780std::string PeerConnection::GetSessionErrorMsg() {
5781 std::ostringstream desc;
Steve Antonf8470812017-12-04 18:46:215782 desc << kSessionError << SessionErrorToString(session_error()) << ". ";
5783 desc << kSessionErrorDesc << session_error_desc() << ".";
Steve Anton75737c02017-11-06 18:37:175784 return desc.str();
5785}
5786
Steve Anton8e20f172018-03-06 18:55:045787void PeerConnection::ReportSdpFormatReceived(
5788 const SessionDescriptionInterface& remote_offer) {
5789 if (!uma_observer_) {
5790 return;
5791 }
5792 int num_audio_mlines = 0;
5793 int num_video_mlines = 0;
5794 int num_audio_tracks = 0;
5795 int num_video_tracks = 0;
5796 for (const ContentInfo& content : remote_offer.description()->contents()) {
5797 cricket::MediaType media_type = content.media_description()->type();
5798 int num_tracks = std::max(
5799 1, static_cast<int>(content.media_description()->streams().size()));
5800 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
5801 num_audio_mlines += 1;
5802 num_audio_tracks += num_tracks;
5803 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
5804 num_video_mlines += 1;
5805 num_video_tracks += num_tracks;
5806 }
5807 }
5808 SdpFormatReceived format = kSdpFormatReceivedNoTracks;
5809 if (num_audio_mlines > 1 || num_video_mlines > 1) {
5810 format = kSdpFormatReceivedComplexUnifiedPlan;
5811 } else if (num_audio_tracks > 1 || num_video_tracks > 1) {
5812 format = kSdpFormatReceivedComplexPlanB;
5813 } else if (num_audio_tracks > 0 || num_video_tracks > 0) {
5814 format = kSdpFormatReceivedSimple;
5815 }
5816 uma_observer_->IncrementEnumCounter(kEnumCounterSdpFormatReceived, format,
5817 kSdpFormatReceivedMax);
5818}
5819
Steve Anton0ffaaa22018-02-23 18:31:305820void PeerConnection::ReportNegotiatedSdpSemantics(
5821 const SessionDescriptionInterface& answer) {
5822 if (!uma_observer_) {
5823 return;
5824 }
5825 switch (answer.description()->msid_signaling()) {
5826 case 0:
5827 uma_observer_->IncrementEnumCounter(kEnumCounterSdpSemanticNegotiated,
5828 kSdpSemanticNegotiatedNone,
5829 kSdpSemanticNegotiatedMax);
5830 break;
5831 case cricket::kMsidSignalingMediaSection:
5832 uma_observer_->IncrementEnumCounter(kEnumCounterSdpSemanticNegotiated,
5833 kSdpSemanticNegotiatedUnifiedPlan,
5834 kSdpSemanticNegotiatedMax);
5835 break;
5836 case cricket::kMsidSignalingSsrcAttribute:
5837 uma_observer_->IncrementEnumCounter(kEnumCounterSdpSemanticNegotiated,
5838 kSdpSemanticNegotiatedPlanB,
5839 kSdpSemanticNegotiatedMax);
5840 break;
5841 case cricket::kMsidSignalingMediaSection |
5842 cricket::kMsidSignalingSsrcAttribute:
5843 uma_observer_->IncrementEnumCounter(kEnumCounterSdpSemanticNegotiated,
5844 kSdpSemanticNegotiatedMixed,
5845 kSdpSemanticNegotiatedMax);
5846 break;
5847 default:
5848 RTC_NOTREACHED();
5849 }
5850}
5851
Steve Anton75737c02017-11-06 18:37:175852// We need to check the local/remote description for the Transport instead of
5853// the session, because a new Transport added during renegotiation may have
5854// them unset while the session has them set from the previous negotiation.
5855// Not doing so may trigger the auto generation of transport description and
5856// mess up DTLS identity information, ICE credential, etc.
5857bool PeerConnection::ReadyToUseRemoteCandidate(
5858 const IceCandidateInterface* candidate,
5859 const SessionDescriptionInterface* remote_desc,
5860 bool* valid) {
5861 *valid = true;
5862
5863 const SessionDescriptionInterface* current_remote_desc =
5864 remote_desc ? remote_desc : remote_description();
5865
5866 if (!current_remote_desc) {
5867 return false;
5868 }
5869
5870 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
5871 size_t remote_content_size =
5872 current_remote_desc->description()->contents().size();
5873 if (mediacontent_index >= remote_content_size) {
Mirko Bonadei675513b2017-11-09 10:09:255874 RTC_LOG(LS_ERROR)
5875 << "ReadyToUseRemoteCandidate: Invalid candidate media index "
5876 << mediacontent_index;
Steve Anton75737c02017-11-06 18:37:175877
5878 *valid = false;
5879 return false;
5880 }
5881
5882 cricket::ContentInfo content =
5883 current_remote_desc->description()->contents()[mediacontent_index];
5884
5885 const std::string transport_name = GetTransportName(content.name);
5886 if (transport_name.empty()) {
5887 return false;
5888 }
Zhi Huange830e682018-03-30 17:48:355889 return true;
Steve Anton75737c02017-11-06 18:37:175890}
5891
5892bool PeerConnection::SrtpRequired() const {
5893 return dtls_enabled_ ||
5894 webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED;
5895}
5896
5897void PeerConnection::OnTransportControllerGatheringState(
5898 cricket::IceGatheringState state) {
5899 RTC_DCHECK(signaling_thread()->IsCurrent());
5900 if (state == cricket::kIceGatheringGathering) {
5901 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringGathering);
5902 } else if (state == cricket::kIceGatheringComplete) {
5903 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringComplete);
5904 }
5905}
5906
5907void PeerConnection::ReportTransportStats() {
Steve Antonc7b964c2018-02-01 22:39:455908 std::map<std::string, std::set<cricket::MediaType>>
5909 media_types_by_transport_name;
5910 for (auto transceiver : transceivers_) {
5911 if (transceiver->internal()->channel()) {
5912 const std::string& transport_name =
5913 transceiver->internal()->channel()->transport_name();
5914 media_types_by_transport_name[transport_name].insert(
Steve Anton69470252018-02-09 19:43:085915 transceiver->media_type());
Steve Antonc7b964c2018-02-01 22:39:455916 }
Steve Anton75737c02017-11-06 18:37:175917 }
5918 if (rtp_data_channel()) {
Steve Antonc7b964c2018-02-01 22:39:455919 media_types_by_transport_name[rtp_data_channel()->transport_name()].insert(
5920 cricket::MEDIA_TYPE_DATA);
Steve Anton75737c02017-11-06 18:37:175921 }
Zhi Huange830e682018-03-30 17:48:355922
5923 rtc::Optional<std::string> transport_name = sctp_transport_name();
5924 if (transport_name) {
5925 media_types_by_transport_name[*transport_name].insert(
Steve Antonc7b964c2018-02-01 22:39:455926 cricket::MEDIA_TYPE_DATA);
Steve Anton75737c02017-11-06 18:37:175927 }
Zhi Huange830e682018-03-30 17:48:355928
Steve Antonc7b964c2018-02-01 22:39:455929 for (const auto& entry : media_types_by_transport_name) {
5930 const std::string& transport_name = entry.first;
5931 const std::set<cricket::MediaType> media_types = entry.second;
Steve Anton75737c02017-11-06 18:37:175932 cricket::TransportStats stats;
Steve Antonc7b964c2018-02-01 22:39:455933 if (transport_controller_->GetStats(transport_name, &stats)) {
Steve Anton75737c02017-11-06 18:37:175934 ReportBestConnectionState(stats);
Steve Antonc7b964c2018-02-01 22:39:455935 ReportNegotiatedCiphers(stats, media_types);
Steve Anton75737c02017-11-06 18:37:175936 }
5937 }
5938}
5939// Walk through the ConnectionInfos to gather best connection usage
5940// for IPv4 and IPv6.
5941void PeerConnection::ReportBestConnectionState(
5942 const cricket::TransportStats& stats) {
5943 RTC_DCHECK(metrics_observer());
Steve Antonc7b964c2018-02-01 22:39:455944 for (const cricket::TransportChannelStats& channel_stats :
5945 stats.channel_stats) {
5946 for (const cricket::ConnectionInfo& connection_info :
5947 channel_stats.connection_infos) {
5948 if (!connection_info.best_connection) {
Steve Anton75737c02017-11-06 18:37:175949 continue;
5950 }
5951
5952 PeerConnectionEnumCounterType type = kPeerConnectionEnumCounterMax;
Steve Antonc7b964c2018-02-01 22:39:455953 const cricket::Candidate& local = connection_info.local_candidate;
5954 const cricket::Candidate& remote = connection_info.remote_candidate;
Steve Anton75737c02017-11-06 18:37:175955
5956 // Increment the counter for IceCandidatePairType.
5957 if (local.protocol() == cricket::TCP_PROTOCOL_NAME ||
5958 (local.type() == RELAY_PORT_TYPE &&
5959 local.relay_protocol() == cricket::TCP_PROTOCOL_NAME)) {
5960 type = kEnumCounterIceCandidatePairTypeTcp;
5961 } else if (local.protocol() == cricket::UDP_PROTOCOL_NAME) {
5962 type = kEnumCounterIceCandidatePairTypeUdp;
5963 } else {
5964 RTC_CHECK(0);
5965 }
5966 metrics_observer()->IncrementEnumCounter(
5967 type, GetIceCandidatePairCounter(local, remote),
5968 kIceCandidatePairMax);
5969
5970 // Increment the counter for IP type.
5971 if (local.address().family() == AF_INET) {
5972 metrics_observer()->IncrementEnumCounter(
5973 kEnumCounterAddressFamily, kBestConnections_IPv4,
5974 kPeerConnectionAddressFamilyCounter_Max);
5975
5976 } else if (local.address().family() == AF_INET6) {
5977 metrics_observer()->IncrementEnumCounter(
5978 kEnumCounterAddressFamily, kBestConnections_IPv6,
5979 kPeerConnectionAddressFamilyCounter_Max);
5980 } else {
5981 RTC_CHECK(0);
5982 }
5983
5984 return;
5985 }
5986 }
5987}
5988
5989void PeerConnection::ReportNegotiatedCiphers(
Steve Antonc7b964c2018-02-01 22:39:455990 const cricket::TransportStats& stats,
5991 const std::set<cricket::MediaType>& media_types) {
Steve Anton75737c02017-11-06 18:37:175992 RTC_DCHECK(metrics_observer());
5993 if (!dtls_enabled_ || stats.channel_stats.empty()) {
5994 return;
5995 }
5996
5997 int srtp_crypto_suite = stats.channel_stats[0].srtp_crypto_suite;
5998 int ssl_cipher_suite = stats.channel_stats[0].ssl_cipher_suite;
5999 if (srtp_crypto_suite == rtc::SRTP_INVALID_CRYPTO_SUITE &&
6000 ssl_cipher_suite == rtc::TLS_NULL_WITH_NULL_NULL) {
6001 return;
6002 }
6003
Steve Antonc7b964c2018-02-01 22:39:456004 for (cricket::MediaType media_type : media_types) {
6005 PeerConnectionEnumCounterType srtp_counter_type;
6006 PeerConnectionEnumCounterType ssl_counter_type;
6007 switch (media_type) {
6008 case cricket::MEDIA_TYPE_AUDIO:
6009 srtp_counter_type = kEnumCounterAudioSrtpCipher;
6010 ssl_counter_type = kEnumCounterAudioSslCipher;
6011 break;
6012 case cricket::MEDIA_TYPE_VIDEO:
6013 srtp_counter_type = kEnumCounterVideoSrtpCipher;
6014 ssl_counter_type = kEnumCounterVideoSslCipher;
6015 break;
6016 case cricket::MEDIA_TYPE_DATA:
6017 srtp_counter_type = kEnumCounterDataSrtpCipher;
6018 ssl_counter_type = kEnumCounterDataSslCipher;
6019 break;
6020 default:
6021 RTC_NOTREACHED();
6022 continue;
6023 }
6024 if (srtp_crypto_suite != rtc::SRTP_INVALID_CRYPTO_SUITE) {
6025 metrics_observer()->IncrementSparseEnumCounter(srtp_counter_type,
6026 srtp_crypto_suite);
6027 }
6028 if (ssl_cipher_suite != rtc::TLS_NULL_WITH_NULL_NULL) {
6029 metrics_observer()->IncrementSparseEnumCounter(ssl_counter_type,
6030 ssl_cipher_suite);
6031 }
Steve Anton75737c02017-11-06 18:37:176032 }
6033}
6034
6035void PeerConnection::OnSentPacket_w(const rtc::SentPacket& sent_packet) {
6036 RTC_DCHECK(worker_thread()->IsCurrent());
6037 RTC_DCHECK(call_);
6038 call_->OnSentPacket(sent_packet);
6039}
6040
6041const std::string PeerConnection::GetTransportName(
6042 const std::string& content_name) {
6043 cricket::BaseChannel* channel = GetChannel(content_name);
Steve Anton6fec8802017-12-04 18:37:296044 if (channel) {
6045 return channel->transport_name();
Steve Anton75737c02017-11-06 18:37:176046 }
Steve Anton6fec8802017-12-04 18:37:296047 if (sctp_transport_) {
Zhi Huange830e682018-03-30 17:48:356048 RTC_DCHECK(sctp_mid_);
6049 if (content_name == *sctp_mid_) {
6050 return *sctp_transport_name();
Steve Anton6fec8802017-12-04 18:37:296051 }
6052 }
6053 // Return an empty string if failed to retrieve the transport name.
6054 return "";
Steve Anton75737c02017-11-06 18:37:176055}
6056
Steve Anton6fec8802017-12-04 18:37:296057void PeerConnection::DestroyTransceiverChannel(
6058 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
6059 transceiver) {
6060 RTC_DCHECK(transceiver);
Steve Anton75737c02017-11-06 18:37:176061
Steve Anton6fec8802017-12-04 18:37:296062 cricket::BaseChannel* channel = transceiver->internal()->channel();
6063 if (channel) {
6064 transceiver->internal()->SetChannel(nullptr);
6065 DestroyBaseChannel(channel);
Steve Anton75737c02017-11-06 18:37:176066 }
6067}
6068
6069void PeerConnection::DestroyDataChannel() {
Steve Anton6fec8802017-12-04 18:37:296070 if (rtp_data_channel_) {
6071 OnDataChannelDestroyed();
6072 DestroyBaseChannel(rtp_data_channel_);
6073 rtp_data_channel_ = nullptr;
6074 }
6075
6076 // Note: Cannot use rtc::Bind to create a functor to invoke because it will
6077 // grab a reference to this PeerConnection. If this is called from the
6078 // PeerConnection destructor, the RefCountedObject vtable will have already
6079 // been destroyed (since it is a subclass of PeerConnection) and using
6080 // rtc::Bind will cause "Pure virtual function called" error to appear.
6081
6082 if (sctp_transport_) {
6083 OnDataChannelDestroyed();
6084 network_thread()->Invoke<void>(RTC_FROM_HERE,
6085 [this] { DestroySctpTransport_n(); });
6086 }
6087}
6088
6089void PeerConnection::DestroyBaseChannel(cricket::BaseChannel* channel) {
6090 RTC_DCHECK(channel);
Steve Anton6fec8802017-12-04 18:37:296091 switch (channel->media_type()) {
6092 case cricket::MEDIA_TYPE_AUDIO:
6093 channel_manager()->DestroyVoiceChannel(
6094 static_cast<cricket::VoiceChannel*>(channel));
6095 break;
6096 case cricket::MEDIA_TYPE_VIDEO:
6097 channel_manager()->DestroyVideoChannel(
6098 static_cast<cricket::VideoChannel*>(channel));
6099 break;
6100 case cricket::MEDIA_TYPE_DATA:
6101 channel_manager()->DestroyRtpDataChannel(
6102 static_cast<cricket::RtpDataChannel*>(channel));
6103 break;
6104 default:
6105 RTC_NOTREACHED() << "Unknown media type: " << channel->media_type();
6106 break;
6107 }
Zhi Huange830e682018-03-30 17:48:356108}
Steve Anton6fec8802017-12-04 18:37:296109
Zhi Huang365381f2018-04-13 23:44:346110bool PeerConnection::OnRtpTransportChanged(
Zhi Huange830e682018-03-30 17:48:356111 const std::string& mid,
6112 RtpTransportInternal* rtp_transport) {
6113 auto base_channel = GetChannel(mid);
6114 if (base_channel) {
Zhi Huang365381f2018-04-13 23:44:346115 return base_channel->SetRtpTransport(rtp_transport);
Zhi Huange830e682018-03-30 17:48:356116 }
Zhi Huang365381f2018-04-13 23:44:346117 return true;
Zhi Huange830e682018-03-30 17:48:356118}
Steve Anton6fec8802017-12-04 18:37:296119
Zhi Huange830e682018-03-30 17:48:356120void PeerConnection::OnDtlsTransportChanged(
6121 const std::string& mid,
6122 cricket::DtlsTransportInternal* dtls_transport) {
6123 if (sctp_transport_) {
6124 RTC_DCHECK(mid == sctp_mid_);
Zhi Huang644fde42018-04-03 02:16:266125 sctp_transport_->SetDtlsTransport(dtls_transport);
Steve Anton75737c02017-11-06 18:37:176126 }
6127}
6128
Harald Alvestrand89061872018-01-02 13:08:346129void PeerConnection::ClearStatsCache() {
6130 if (stats_collector_) {
6131 stats_collector_->ClearCachedStatsReport();
6132 }
6133}
6134
henrike@webrtc.org28e20752013-07-10 00:45:366135} // namespace webrtc