blob: ca54c442567a11fa01d8b018c2fe25b4e38821c0 [file] [log] [blame]
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001/*
kjellanderb24317b2016-02-10 07:54:43 -08002 * Copyright 2012 The WebRTC project authors. All Rights Reserved.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003 *
kjellanderb24317b2016-02-10 07:54:43 -08004 * Use of this source code is governed by a BSD-style license
5 * that can be found in the LICENSE file in the root of the source
6 * tree. An additional intellectual property rights grant can be found
7 * in the file PATENTS. All contributing project authors may
8 * be found in the AUTHORS file in the root of the source tree.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00009 */
10
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020011#include "pc/peerconnection.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000012
deadbeefeb459812015-12-15 19:24:43 -080013#include <algorithm>
Steve Antondcc3c022017-12-22 16:02:54 -080014#include <queue>
Steve Anton75737c02017-11-06 10:37:17 -080015#include <set>
kwiberg0eb15ed2015-12-17 03:04:15 -080016#include <utility>
17#include <vector>
henrike@webrtc.org28e20752013-07-10 00:45:36 +000018
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020019#include "api/jsepicecandidate.h"
20#include "api/jsepsessiondescription.h"
21#include "api/mediaconstraintsinterface.h"
22#include "api/mediastreamproxy.h"
23#include "api/mediastreamtrackproxy.h"
24#include "call/call.h"
Qingsi Wang93a84392018-01-30 17:13:09 -080025#include "logging/rtc_event_log/icelogger.h"
Elad Alon83ccca12017-10-04 13:18:26 +020026#include "logging/rtc_event_log/output/rtc_event_log_output_file.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020027#include "logging/rtc_event_log/rtc_event_log.h"
28#include "media/sctp/sctptransport.h"
29#include "pc/audiotrack.h"
Steve Anton75737c02017-11-06 10:37:17 -080030#include "pc/channel.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020031#include "pc/channelmanager.h"
32#include "pc/dtmfsender.h"
33#include "pc/mediastream.h"
34#include "pc/mediastreamobserver.h"
35#include "pc/remoteaudiosource.h"
Steve Anton1d03a752017-11-27 14:30:09 -080036#include "pc/rtpmediautils.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020037#include "pc/rtpreceiver.h"
38#include "pc/rtpsender.h"
Steve Anton75737c02017-11-06 10:37:17 -080039#include "pc/sctputils.h"
Steve Antona3a92c22017-12-07 10:27:41 -080040#include "pc/sdputils.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020041#include "pc/streamcollection.h"
42#include "pc/videocapturertracksource.h"
43#include "pc/videotrack.h"
44#include "rtc_base/bind.h"
45#include "rtc_base/checks.h"
46#include "rtc_base/logging.h"
Karl Wiberge40468b2017-11-22 10:42:26 +010047#include "rtc_base/numerics/safe_conversions.h"
Elad Alon83ccca12017-10-04 13:18:26 +020048#include "rtc_base/ptr_util.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020049#include "rtc_base/stringencode.h"
50#include "rtc_base/stringutils.h"
51#include "rtc_base/trace_event.h"
52#include "system_wrappers/include/clock.h"
53#include "system_wrappers/include/field_trial.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000054
Steve Anton75737c02017-11-06 10:37:17 -080055using cricket::ContentInfo;
56using cricket::ContentInfos;
57using cricket::MediaContentDescription;
58using cricket::SessionDescription;
Steve Anton5adfafd2017-12-20 16:34:00 -080059using cricket::MediaProtocolType;
Steve Anton75737c02017-11-06 10:37:17 -080060using cricket::TransportInfo;
61
62using cricket::LOCAL_PORT_TYPE;
63using cricket::STUN_PORT_TYPE;
64using cricket::RELAY_PORT_TYPE;
65using cricket::PRFLX_PORT_TYPE;
66
Steve Antonba818672017-11-06 10:21:57 -080067namespace webrtc {
68
Steve Anton75737c02017-11-06 10:37:17 -080069// Error messages
70const char kBundleWithoutRtcpMux[] =
71 "rtcp-mux must be enabled when BUNDLE "
72 "is enabled.";
Steve Anton75737c02017-11-06 10:37:17 -080073const char kInvalidCandidates[] = "Description contains invalid candidates.";
74const char kInvalidSdp[] = "Invalid session description.";
75const char kMlineMismatchInAnswer[] =
76 "The order of m-lines in answer doesn't match order in offer. Rejecting "
77 "answer.";
78const char kMlineMismatchInSubsequentOffer[] =
79 "The order of m-lines in subsequent offer doesn't match order from "
80 "previous offer/answer.";
Steve Anton75737c02017-11-06 10:37:17 -080081const char kSdpWithoutDtlsFingerprint[] =
82 "Called with SDP without DTLS fingerprint.";
83const char kSdpWithoutSdesCrypto[] = "Called with SDP without SDES crypto.";
84const char kSdpWithoutIceUfragPwd[] =
85 "Called with SDP without ice-ufrag and ice-pwd.";
86const char kSessionError[] = "Session error code: ";
87const char kSessionErrorDesc[] = "Session error description: ";
88const char kDtlsSrtpSetupFailureRtp[] =
89 "Couldn't set up DTLS-SRTP on RTP channel.";
90const char kDtlsSrtpSetupFailureRtcp[] =
91 "Couldn't set up DTLS-SRTP on RTCP channel.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +000092
Steve Anton75737c02017-11-06 10:37:17 -080093namespace {
henrike@webrtc.org28e20752013-07-10 00:45:36 +000094
Seth Hampson845e8782018-03-02 11:34:10 -080095static const char kDefaultStreamId[] = "default";
Steve Anton4171afb2017-11-20 10:20:22 -080096static const char kDefaultAudioSenderId[] = "defaulta0";
97static const char kDefaultVideoSenderId[] = "defaultv0";
deadbeefab9b2d12015-10-14 11:33:11 -070098
zhihuang8f65cdf2016-05-06 18:40:30 -070099// The length of RTCP CNAMEs.
100static const int kRtcpCnameLength = 16;
101
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000102enum {
wu@webrtc.org91053e72013-08-10 07:18:04 +0000103 MSG_SET_SESSIONDESCRIPTION_SUCCESS = 0,
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000104 MSG_SET_SESSIONDESCRIPTION_FAILED,
deadbeefab9b2d12015-10-14 11:33:11 -0700105 MSG_CREATE_SESSIONDESCRIPTION_FAILED,
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000106 MSG_GETSTATS,
deadbeefbd292462015-12-14 18:15:29 -0800107 MSG_FREE_DATACHANNELS,
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000108};
109
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000110struct SetSessionDescriptionMsg : public rtc::MessageData {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000111 explicit SetSessionDescriptionMsg(
112 webrtc::SetSessionDescriptionObserver* observer)
113 : observer(observer) {
114 }
115
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000116 rtc::scoped_refptr<webrtc::SetSessionDescriptionObserver> observer;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +0100117 RTCError error;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000118};
119
deadbeefab9b2d12015-10-14 11:33:11 -0700120struct 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 15:18:03 +0100126 RTCError error;
deadbeefab9b2d12015-10-14 11:33:11 -0700127};
128
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000129struct GetStatsMsg : public rtc::MessageData {
tommi@webrtc.org5b06b062014-08-15 08:38:30 +0000130 GetStatsMsg(webrtc::StatsObserver* observer,
131 webrtc::MediaStreamTrackInterface* track)
132 : observer(observer), track(track) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000133 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000134 rtc::scoped_refptr<webrtc::StatsObserver> observer;
tommi@webrtc.org5b06b062014-08-15 08:38:30 +0000135 rtc::scoped_refptr<webrtc::MediaStreamTrackInterface> track;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000136};
137
deadbeefab9b2d12015-10-14 11:33:11 -0700138// 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 16:05:28 -0700144 if (current_streams->find(new_stream->id()) != nullptr) {
145 RTC_LOG(LS_ERROR) << "MediaStream with ID " << new_stream->id()
Mirko Bonadei675513b2017-11-09 11:09:25 +0100146 << " is already added.";
deadbeefab9b2d12015-10-14 11:33:11 -0700147 return false;
148 }
149 return true;
150}
151
deadbeef5e97fb52015-10-15 12:49:08 -0700152// 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 14:57:10 -0800157 return RtpTransceiverDirectionHasSend(desc->direction())
deadbeef5e97fb52015-10-15 12:49:08 -0700158 ? desc->streams()
159 : std::vector<cricket::StreamParams>();
160}
161
deadbeefab9b2d12015-10-14 11:33:11 -0700162bool IsValidOfferToReceiveMedia(int value) {
163 typedef PeerConnectionInterface::RTCOfferAnswerOptions Options;
164 return (value >= Options::kUndefined) &&
165 (value <= Options::kMaxOfferToReceiveMedia);
166}
167
zhihuang1c378ed2017-08-17 14:10:50 -0700168// Add options to |[audio/video]_media_description_options| from |senders|.
169void AddRtpSenderOptions(
deadbeefa601f5c2016-06-06 14:27:39 -0700170 const std::vector<rtc::scoped_refptr<
171 RtpSenderProxyWithInternal<RtpSenderInternal>>>& senders,
zhihuang1c378ed2017-08-17 14:10:50 -0700172 cricket::MediaDescriptionOptions* audio_media_description_options,
173 cricket::MediaDescriptionOptions* video_media_description_options) {
olka3c747662017-08-17 06:50:32 -0700174 for (const auto& sender : senders) {
zhihuang1c378ed2017-08-17 14:10:50 -0700175 if (sender->media_type() == cricket::MEDIA_TYPE_AUDIO) {
176 if (audio_media_description_options) {
177 audio_media_description_options->AddAudioSender(
Steve Anton8ffb9c32017-08-31 15:45:38 -0700178 sender->id(), sender->internal()->stream_ids());
zhihuang1c378ed2017-08-17 14:10:50 -0700179 }
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 15:45:38 -0700184 sender->id(), sender->internal()->stream_ids(), 1);
zhihuang1c378ed2017-08-17 14:10:50 -0700185 }
186 }
zhihuanga77e6bb2017-08-14 18:17:48 -0700187 }
zhihuang1c378ed2017-08-17 14:10:50 -0700188}
olka3c747662017-08-17 06:50:32 -0700189
zhihuang1c378ed2017-08-17 14:10:50 -0700190// 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 11:33:11 -0700198 // 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 14:10:50 -0700203 // 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 11:33:11 -0700207 }
208 }
209}
210
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700211uint32_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 05:56:46 -0800223 RTC_NOTREACHED();
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700224 }
225 return cricket::CF_NONE;
226}
227
deadbeef293e9262017-01-11 12:28:30 -0800228// 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 15:59:59 -0700236bool 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 10:21:57 -0800243std::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 11:38:28 -0700262
Steve Anton75737c02017-11-06 10:37:17 -0800263IceCandidatePairType 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 15:33:48 -0800320// 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 10:37:17 -0800335// Verify that the order of media sections in |new_desc| matches
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800336// |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 10:37:17 -0800349 return false;
350 }
351
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800352 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-22 16:02:54 -0800363 continue;
364 }
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800365 if (new_desc.contents()[i].name != current_desc.contents()[i].name) {
Steve Anton75737c02017-11-06 10:37:17 -0800366 return false;
367 }
368 const MediaContentDescription* new_desc_mdesc =
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800369 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 10:37:17 -0800373 return false;
374 }
375 }
376 return true;
377}
378
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800379bool MediaSectionsHaveSameCount(const SessionDescription& desc1,
380 const SessionDescription& desc2) {
381 return desc1.contents().size() == desc2.contents().size();
Steve Anton75737c02017-11-06 10:37:17 -0800382}
383
Harald Alvestrandf9d0f1d2018-03-02 14:15:26 +0100384void 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 10:37:17 -0800417// 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 16:04:13 +0100423RTCError VerifyCrypto(const SessionDescription* desc,
424 bool dtls_enabled,
425 rtc::scoped_refptr<webrtc::UMAObserver> uma_observer) {
Steve Anton75737c02017-11-06 10:37:17 -0800426 const cricket::ContentGroup* bundle =
427 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton8a006912017-12-04 15:25:56 -0800428 for (const cricket::ContentInfo& content_info : desc->contents()) {
429 if (content_info.rejected) {
Steve Anton75737c02017-11-06 10:37:17 -0800430 continue;
431 }
Harald Alvestrand2e180612018-03-07 10:56:14 +0100432 // 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 15:25:56 -0800437 const std::string& mid = content_info.name;
438 if (bundle && bundle->HasContentName(mid) &&
439 mid != *(bundle->FirstContentName())) {
Steve Anton75737c02017-11-06 10:37:17 -0800440 // 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 15:14:30 -0800448 const MediaContentDescription* media = content_info.media_description();
Steve Anton8a006912017-12-04 15:25:56 -0800449 const TransportInfo* tinfo = desc->GetTransportInfoByName(mid);
Steve Anton75737c02017-11-06 10:37:17 -0800450 if (!media || !tinfo) {
451 // Something is not right.
Steve Anton8a006912017-12-04 15:25:56 -0800452 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidSdp);
Steve Anton75737c02017-11-06 10:37:17 -0800453 }
454 if (dtls_enabled) {
455 if (!tinfo->description.identity_fingerprint) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100456 RTC_LOG(LS_WARNING)
457 << "Session description must have DTLS fingerprint if "
458 "DTLS enabled.";
Steve Anton8a006912017-12-04 15:25:56 -0800459 return RTCError(RTCErrorType::INVALID_PARAMETER,
460 kSdpWithoutDtlsFingerprint);
Steve Anton75737c02017-11-06 10:37:17 -0800461 }
462 } else {
463 if (media->cryptos().empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100464 RTC_LOG(LS_WARNING)
Steve Anton75737c02017-11-06 10:37:17 -0800465 << "Session description must have SDES when DTLS disabled.";
Steve Anton8a006912017-12-04 15:25:56 -0800466 return RTCError(RTCErrorType::INVALID_PARAMETER, kSdpWithoutSdesCrypto);
Steve Anton75737c02017-11-06 10:37:17 -0800467 }
468 }
469 }
Steve Anton8a006912017-12-04 15:25:56 -0800470 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -0800471}
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 15:25:56 -0800479 for (const cricket::ContentInfo& content_info : desc->contents()) {
480 if (content_info.rejected) {
Steve Anton75737c02017-11-06 10:37:17 -0800481 continue;
482 }
Steve Anton8a006912017-12-04 15:25:56 -0800483 const std::string& mid = content_info.name;
484 if (bundle && bundle->HasContentName(mid) &&
485 mid != *(bundle->FirstContentName())) {
Steve Anton75737c02017-11-06 10:37:17 -0800486 // 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 15:25:56 -0800494 const TransportInfo* tinfo = desc->GetTransportInfoByName(mid);
Steve Anton75737c02017-11-06 10:37:17 -0800495 if (!tinfo) {
496 // Something is not right.
Mirko Bonadei675513b2017-11-09 11:09:25 +0100497 RTC_LOG(LS_ERROR) << kInvalidSdp;
Steve Anton75737c02017-11-06 10:37:17 -0800498 return false;
499 }
500 if (tinfo->description.ice_ufrag.empty() ||
501 tinfo->description.ice_pwd.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100502 RTC_LOG(LS_ERROR) << "Session description must have ice ufrag and pwd.";
Steve Anton75737c02017-11-06 10:37:17 -0800503 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 15:14:30 -0800514 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 10:37:17 -0800518 if (found) {
519 *track_id = found->id;
520 return true;
521 }
522 }
523
Steve Antonb1c1de12017-12-21 15:14:30 -0800524 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 10:37:17 -0800528 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 15:14:30 -0800539 const cricket::DataContentDescription* data_desc =
540 GetFirstDataContentDescription(session_description);
541 RTC_DCHECK(data_desc);
542 if (!data_desc) {
Steve Anton75737c02017-11-06 10:37:17 -0800543 return -1;
544 }
Steve Anton75737c02017-11-06 10:37:17 -0800545 std::string value;
546 cricket::DataCodec match_pattern(cricket::kGoogleSctpDataCodecPlType,
547 cricket::kGoogleSctpDataCodecName);
Steve Antonb1c1de12017-12-21 15:14:30 -0800548 for (const cricket::DataCodec& codec : data_desc->codecs()) {
Steve Anton75737c02017-11-06 10:37:17 -0800549 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 10:37:17 -0800559// 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 11:09:25 +0100584 RTC_LOG(LS_INFO) << "Remote peer requests ICE restart for " << content_name
585 << ".";
Steve Anton75737c02017-11-06 10:37:17 -0800586 return true;
587 }
588 return false;
589}
590
Steve Anton80dd7b52018-02-16 17:08:42 -0800591// 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
Qingsi Wang866e08d2018-03-22 17:54:23 -0700602rtc::Optional<int> RTCConfigurationToIceConfigOptionalInt(
603 int rtc_configuration_parameter) {
604 if (rtc_configuration_parameter ==
605 webrtc::PeerConnectionInterface::RTCConfiguration::kUndefined) {
606 return rtc::nullopt;
607 }
608 return rtc_configuration_parameter;
609}
610
Steve Anton75737c02017-11-06 10:37:17 -0800611} // namespace
612
Henrik Boström31638672017-11-23 17:48:32 +0100613// Upon completion, posts a task to execute the callback of the
614// SetSessionDescriptionObserver asynchronously on the same thread. At this
615// point, the state of the peer connection might no longer reflect the effects
616// of the SetRemoteDescription operation, as the peer connection could have been
617// modified during the post.
618// TODO(hbos): Remove this class once we remove the version of
619// PeerConnectionInterface::SetRemoteDescription() that takes a
620// SetSessionDescriptionObserver as an argument.
621class PeerConnection::SetRemoteDescriptionObserverAdapter
622 : public rtc::RefCountedObject<SetRemoteDescriptionObserverInterface> {
623 public:
624 SetRemoteDescriptionObserverAdapter(
625 rtc::scoped_refptr<PeerConnection> pc,
626 rtc::scoped_refptr<SetSessionDescriptionObserver> wrapper)
627 : pc_(std::move(pc)), wrapper_(std::move(wrapper)) {}
628
629 // SetRemoteDescriptionObserverInterface implementation.
630 void OnSetRemoteDescriptionComplete(RTCError error) override {
631 if (error.ok())
632 pc_->PostSetSessionDescriptionSuccess(wrapper_);
633 else
Harald Alvestrand5081c0c2018-03-09 15:18:03 +0100634 pc_->PostSetSessionDescriptionFailure(wrapper_, std::move(error));
Henrik Boström31638672017-11-23 17:48:32 +0100635 }
636
637 private:
638 rtc::scoped_refptr<PeerConnection> pc_;
639 rtc::scoped_refptr<SetSessionDescriptionObserver> wrapper_;
640};
641
deadbeef293e9262017-01-11 12:28:30 -0800642bool PeerConnectionInterface::RTCConfiguration::operator==(
643 const PeerConnectionInterface::RTCConfiguration& o) const {
644 // This static_assert prevents us from accidentally breaking operator==.
Steve Anton300bf8e2017-07-14 10:13:10 -0700645 // Note: Order matters! Fields must be ordered the same as RTCConfiguration.
deadbeef293e9262017-01-11 12:28:30 -0800646 struct stuff_being_tested_for_equality {
Magnus Jedvert3beb2072017-07-14 14:23:56 +0000647 IceServers servers;
Steve Anton300bf8e2017-07-14 10:13:10 -0700648 IceTransportsType type;
deadbeef293e9262017-01-11 12:28:30 -0800649 BundlePolicy bundle_policy;
650 RtcpMuxPolicy rtcp_mux_policy;
Steve Anton300bf8e2017-07-14 10:13:10 -0700651 std::vector<rtc::scoped_refptr<rtc::RTCCertificate>> certificates;
652 int ice_candidate_pool_size;
653 bool disable_ipv6;
654 bool disable_ipv6_on_wifi;
deadbeefd21eab32017-07-26 16:50:11 -0700655 int max_ipv6_networks;
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +0100656 bool disable_link_local_networks;
Steve Anton300bf8e2017-07-14 10:13:10 -0700657 bool enable_rtp_data_channel;
658 rtc::Optional<int> screencast_min_bitrate;
659 rtc::Optional<bool> combined_audio_video_bwe;
660 rtc::Optional<bool> enable_dtls_srtp;
deadbeef293e9262017-01-11 12:28:30 -0800661 TcpCandidatePolicy tcp_candidate_policy;
662 CandidateNetworkPolicy candidate_network_policy;
663 int audio_jitter_buffer_max_packets;
664 bool audio_jitter_buffer_fast_accelerate;
665 int ice_connection_receiving_timeout;
666 int ice_backup_candidate_pair_ping_interval;
667 ContinualGatheringPolicy continual_gathering_policy;
deadbeef293e9262017-01-11 12:28:30 -0800668 bool prioritize_most_likely_ice_candidate_pairs;
669 struct cricket::MediaConfig media_config;
deadbeef293e9262017-01-11 12:28:30 -0800670 bool prune_turn_ports;
671 bool presume_writable_when_fully_relayed;
672 bool enable_ice_renomination;
673 bool redetermine_role_on_ice_restart;
Qingsi Wange6826d22018-03-08 14:55:14 -0800674 rtc::Optional<int> ice_check_interval_strong_connectivity;
675 rtc::Optional<int> ice_check_interval_weak_connectivity;
skvlad51072462017-02-02 11:50:14 -0800676 rtc::Optional<int> ice_check_min_interval;
Qingsi Wang22e623a2018-03-13 10:53:57 -0700677 rtc::Optional<int> ice_unwritable_timeout;
678 rtc::Optional<int> ice_unwritable_min_checks;
Qingsi Wangdb53f8e2018-02-20 14:45:49 -0800679 rtc::Optional<int> stun_candidate_keepalive_interval;
Steve Anton300bf8e2017-07-14 10:13:10 -0700680 rtc::Optional<rtc::IntervalRange> ice_regather_interval_range;
Jonas Orelandbdcee282017-10-10 14:01:40 +0200681 webrtc::TurnCustomizer* turn_customizer;
Steve Anton79e79602017-11-20 10:25:56 -0800682 SdpSemantics sdp_semantics;
Qingsi Wang9a5c6f82018-02-01 10:38:40 -0800683 rtc::Optional<rtc::AdapterType> network_preference;
deadbeef293e9262017-01-11 12:28:30 -0800684 };
685 static_assert(sizeof(stuff_being_tested_for_equality) == sizeof(*this),
686 "Did you add something to RTCConfiguration and forget to "
687 "update operator==?");
688 return type == o.type && servers == o.servers &&
689 bundle_policy == o.bundle_policy &&
690 rtcp_mux_policy == o.rtcp_mux_policy &&
691 tcp_candidate_policy == o.tcp_candidate_policy &&
692 candidate_network_policy == o.candidate_network_policy &&
693 audio_jitter_buffer_max_packets == o.audio_jitter_buffer_max_packets &&
694 audio_jitter_buffer_fast_accelerate ==
695 o.audio_jitter_buffer_fast_accelerate &&
696 ice_connection_receiving_timeout ==
697 o.ice_connection_receiving_timeout &&
698 ice_backup_candidate_pair_ping_interval ==
699 o.ice_backup_candidate_pair_ping_interval &&
700 continual_gathering_policy == o.continual_gathering_policy &&
701 certificates == o.certificates &&
702 prioritize_most_likely_ice_candidate_pairs ==
703 o.prioritize_most_likely_ice_candidate_pairs &&
704 media_config == o.media_config && disable_ipv6 == o.disable_ipv6 &&
zhihuangb09b3f92017-03-07 14:40:51 -0800705 disable_ipv6_on_wifi == o.disable_ipv6_on_wifi &&
deadbeefd21eab32017-07-26 16:50:11 -0700706 max_ipv6_networks == o.max_ipv6_networks &&
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +0100707 disable_link_local_networks == o.disable_link_local_networks &&
deadbeef293e9262017-01-11 12:28:30 -0800708 enable_rtp_data_channel == o.enable_rtp_data_channel &&
deadbeef293e9262017-01-11 12:28:30 -0800709 screencast_min_bitrate == o.screencast_min_bitrate &&
710 combined_audio_video_bwe == o.combined_audio_video_bwe &&
711 enable_dtls_srtp == o.enable_dtls_srtp &&
712 ice_candidate_pool_size == o.ice_candidate_pool_size &&
713 prune_turn_ports == o.prune_turn_ports &&
714 presume_writable_when_fully_relayed ==
715 o.presume_writable_when_fully_relayed &&
716 enable_ice_renomination == o.enable_ice_renomination &&
skvlad51072462017-02-02 11:50:14 -0800717 redetermine_role_on_ice_restart == o.redetermine_role_on_ice_restart &&
Qingsi Wange6826d22018-03-08 14:55:14 -0800718 ice_check_interval_strong_connectivity ==
719 o.ice_check_interval_strong_connectivity &&
720 ice_check_interval_weak_connectivity ==
721 o.ice_check_interval_weak_connectivity &&
Steve Anton300bf8e2017-07-14 10:13:10 -0700722 ice_check_min_interval == o.ice_check_min_interval &&
Qingsi Wang22e623a2018-03-13 10:53:57 -0700723 ice_unwritable_timeout == o.ice_unwritable_timeout &&
724 ice_unwritable_min_checks == o.ice_unwritable_min_checks &&
Qingsi Wangdb53f8e2018-02-20 14:45:49 -0800725 stun_candidate_keepalive_interval ==
726 o.stun_candidate_keepalive_interval &&
Jonas Orelandbdcee282017-10-10 14:01:40 +0200727 ice_regather_interval_range == o.ice_regather_interval_range &&
Steve Anton79e79602017-11-20 10:25:56 -0800728 turn_customizer == o.turn_customizer &&
Qingsi Wang9a5c6f82018-02-01 10:38:40 -0800729 sdp_semantics == o.sdp_semantics &&
730 network_preference == o.network_preference;
deadbeef293e9262017-01-11 12:28:30 -0800731}
732
733bool PeerConnectionInterface::RTCConfiguration::operator!=(
734 const PeerConnectionInterface::RTCConfiguration& o) const {
735 return !(*this == o);
deadbeef3edec7c2016-12-10 11:44:26 -0800736}
737
zhihuang8f65cdf2016-05-06 18:40:30 -0700738// Generate a RTCP CNAME when a PeerConnection is created.
739std::string GenerateRtcpCname() {
740 std::string cname;
741 if (!rtc::CreateRandomString(kRtcpCnameLength, &cname)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100742 RTC_LOG(LS_ERROR) << "Failed to generate CNAME.";
nisseeb4ca4e2017-01-12 02:24:27 -0800743 RTC_NOTREACHED();
zhihuang8f65cdf2016-05-06 18:40:30 -0700744 }
745 return cname;
746}
747
zhihuang1c378ed2017-08-17 14:10:50 -0700748bool ValidateOfferAnswerOptions(
749 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options) {
750 return IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_audio) &&
751 IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_video);
olka3c747662017-08-17 06:50:32 -0700752}
753
zhihuang1c378ed2017-08-17 14:10:50 -0700754// From |rtc_options|, fill parts of |session_options| shared by all generated
755// m= sections (in other words, nothing that involves a map/array).
756void ExtractSharedMediaSessionOptions(
757 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options,
758 cricket::MediaSessionOptions* session_options) {
759 session_options->vad_enabled = rtc_options.voice_activity_detection;
760 session_options->bundle_enabled = rtc_options.use_rtp_mux;
761}
zhihuanga77e6bb2017-08-14 18:17:48 -0700762
zhihuang1c378ed2017-08-17 14:10:50 -0700763bool ConvertConstraintsToOfferAnswerOptions(
764 const MediaConstraintsInterface* constraints,
765 PeerConnectionInterface::RTCOfferAnswerOptions* offer_answer_options) {
olka3c747662017-08-17 06:50:32 -0700766 if (!constraints) {
767 return true;
768 }
zhihuang1c378ed2017-08-17 14:10:50 -0700769
770 bool value = false;
771 size_t mandatory_constraints_satisfied = 0;
772
773 if (FindConstraint(constraints,
774 MediaConstraintsInterface::kOfferToReceiveAudio, &value,
775 &mandatory_constraints_satisfied)) {
776 offer_answer_options->offer_to_receive_audio =
777 value ? PeerConnectionInterface::RTCOfferAnswerOptions::
778 kOfferToReceiveMediaTrue
779 : 0;
780 }
781
782 if (FindConstraint(constraints,
783 MediaConstraintsInterface::kOfferToReceiveVideo, &value,
784 &mandatory_constraints_satisfied)) {
785 offer_answer_options->offer_to_receive_video =
786 value ? PeerConnectionInterface::RTCOfferAnswerOptions::
787 kOfferToReceiveMediaTrue
788 : 0;
789 }
790 if (FindConstraint(constraints,
791 MediaConstraintsInterface::kVoiceActivityDetection, &value,
792 &mandatory_constraints_satisfied)) {
793 offer_answer_options->voice_activity_detection = value;
794 }
795 if (FindConstraint(constraints, MediaConstraintsInterface::kUseRtpMux, &value,
796 &mandatory_constraints_satisfied)) {
797 offer_answer_options->use_rtp_mux = value;
798 }
799 if (FindConstraint(constraints, MediaConstraintsInterface::kIceRestart,
800 &value, &mandatory_constraints_satisfied)) {
801 offer_answer_options->ice_restart = value;
802 }
803
deadbeefab9b2d12015-10-14 11:33:11 -0700804 return mandatory_constraints_satisfied == constraints->GetMandatory().size();
805}
806
zhihuang38ede132017-06-15 12:52:32 -0700807PeerConnection::PeerConnection(PeerConnectionFactory* factory,
808 std::unique_ptr<RtcEventLog> event_log,
809 std::unique_ptr<Call> call)
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000810 : factory_(factory),
zhihuang38ede132017-06-15 12:52:32 -0700811 event_log_(std::move(event_log)),
zhihuang8f65cdf2016-05-06 18:40:30 -0700812 rtcp_cname_(GenerateRtcpCname()),
deadbeefab9b2d12015-10-14 11:33:11 -0700813 local_streams_(StreamCollection::Create()),
zhihuang38ede132017-06-15 12:52:32 -0700814 remote_streams_(StreamCollection::Create()),
815 call_(std::move(call)) {}
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000816
817PeerConnection::~PeerConnection() {
Peter Boström1a9d6152015-12-08 22:15:17 +0100818 TRACE_EVENT0("webrtc", "PeerConnection::~PeerConnection");
Steve Anton4171afb2017-11-20 10:20:22 -0800819 RTC_DCHECK_RUN_ON(signaling_thread());
820
Steve Anton8af21862017-12-15 11:20:13 -0800821 // Need to stop transceivers before destroying the stats collector because
822 // AudioRtpSender has a reference to the StatsCollector it will update when
823 // stopping.
824 for (auto transceiver : transceivers_) {
825 transceiver->Stop();
826 }
Steve Anton4171afb2017-11-20 10:20:22 -0800827
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700828 stats_.reset(nullptr);
hbosb78306a2016-12-19 05:06:57 -0800829 if (stats_collector_) {
830 stats_collector_->WaitForPendingRequest();
831 stats_collector_ = nullptr;
832 }
Steve Anton75737c02017-11-06 10:37:17 -0800833
Steve Anton8af21862017-12-15 11:20:13 -0800834 // Don't destroy BaseChannels until after stats has been cleaned up so that
835 // the last stats request can still read from the channels.
836 DestroyAllChannels();
837
Mirko Bonadei675513b2017-11-09 11:09:25 +0100838 RTC_LOG(LS_INFO) << "Session: " << session_id() << " is destroyed.";
Steve Anton75737c02017-11-06 10:37:17 -0800839
840 webrtc_session_desc_factory_.reset();
841 sctp_invoker_.reset();
842 sctp_factory_.reset();
843 transport_controller_.reset();
844
deadbeef91dd5672016-05-18 16:55:30 -0700845 // port_allocator_ lives on the network thread and should be destroyed there.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700846 network_thread()->Invoke<void>(RTC_FROM_HERE,
nisseeaabdf62017-05-05 02:23:02 -0700847 [this] { port_allocator_.reset(); });
eladalon248fd4f2017-09-06 05:18:15 -0700848 // call_ and event_log_ must be destroyed on the worker thread.
Steve Anton978b8762017-09-29 12:15:02 -0700849 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
eladalon248fd4f2017-09-06 05:18:15 -0700850 call_.reset();
Qingsi Wang93a84392018-01-30 17:13:09 -0800851 // The event log must outlive call (and any other object that uses it).
eladalon248fd4f2017-09-06 05:18:15 -0700852 event_log_.reset();
853 });
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000854}
855
Steve Anton8af21862017-12-15 11:20:13 -0800856void PeerConnection::DestroyAllChannels() {
Steve Anton3fe1b152017-12-12 10:20:08 -0800857 // Destroy video channels first since they may have a pointer to a voice
858 // channel.
859 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -0800860 if (transceiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton3fe1b152017-12-12 10:20:08 -0800861 DestroyTransceiverChannel(transceiver);
862 }
863 }
864 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -0800865 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton3fe1b152017-12-12 10:20:08 -0800866 DestroyTransceiverChannel(transceiver);
867 }
868 }
869 DestroyDataChannel();
870}
871
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000872bool PeerConnection::Initialize(
buildbot@webrtc.org41451d42014-05-03 05:39:45 +0000873 const PeerConnectionInterface::RTCConfiguration& configuration,
kwibergd1fe2812016-04-27 06:47:29 -0700874 std::unique_ptr<cricket::PortAllocator> allocator,
Henrik Boströmd03c23b2016-06-01 11:44:18 +0200875 std::unique_ptr<rtc::RTCCertificateGeneratorInterface> cert_generator,
deadbeef653b8e02015-11-11 12:55:10 -0800876 PeerConnectionObserver* observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100877 TRACE_EVENT0("webrtc", "PeerConnection::Initialize");
Steve Anton038834f2017-07-14 15:59:59 -0700878
879 RTCError config_error = ValidateConfiguration(configuration);
880 if (!config_error.ok()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100881 RTC_LOG(LS_ERROR) << "Invalid configuration: " << config_error.message();
Steve Anton038834f2017-07-14 15:59:59 -0700882 return false;
883 }
884
deadbeef293e9262017-01-11 12:28:30 -0800885 if (!allocator) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100886 RTC_LOG(LS_ERROR)
887 << "PeerConnection initialized without a PortAllocator? "
Jonas Olsson45cc8902018-02-13 10:37:07 +0100888 "This shouldn't happen if using PeerConnectionFactory.";
deadbeef293e9262017-01-11 12:28:30 -0800889 return false;
890 }
Jonas Orelandbdcee282017-10-10 14:01:40 +0200891
deadbeef653b8e02015-11-11 12:55:10 -0800892 if (!observer) {
deadbeef293e9262017-01-11 12:28:30 -0800893 // TODO(deadbeef): Why do we do this?
Mirko Bonadei675513b2017-11-09 11:09:25 +0100894 RTC_LOG(LS_ERROR) << "PeerConnection initialized without a "
Jonas Olsson45cc8902018-02-13 10:37:07 +0100895 "PeerConnectionObserver";
deadbeef653b8e02015-11-11 12:55:10 -0800896 return false;
897 }
pthatcher@webrtc.org877ac762015-02-04 22:03:09 +0000898 observer_ = observer;
kwiberg0eb15ed2015-12-17 03:04:15 -0800899 port_allocator_ = std::move(allocator);
deadbeef653b8e02015-11-11 12:55:10 -0800900
deadbeef91dd5672016-05-18 16:55:30 -0700901 // The port allocator lives on the network thread and should be initialized
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700902 // there.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700903 if (!network_thread()->Invoke<bool>(
904 RTC_FROM_HERE, rtc::Bind(&PeerConnection::InitializePortAllocator_n,
905 this, configuration))) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000906 return false;
907 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000908
Zhi Huange830e682018-03-30 10:48:35 -0700909 const PeerConnectionFactoryInterface::Options& options = factory_->options();
910
Steve Anton75737c02017-11-06 10:37:17 -0800911 // RFC 3264: The numeric value of the session id and version in the
912 // o line MUST be representable with a "64 bit signed integer".
913 // Due to this constraint session id |session_id_| is max limited to
914 // LLONG_MAX.
915 session_id_ = rtc::ToString(rtc::CreateRandomId64() & LLONG_MAX);
Zhi Huange830e682018-03-30 10:48:35 -0700916 JsepTransportController::Config config;
917 config.redetermine_role_on_ice_restart =
918 configuration.redetermine_role_on_ice_restart;
919 config.ssl_max_version = factory_->options().ssl_max_version;
920 config.disable_encryption = options.disable_encryption;
921 config.bundle_policy = configuration.bundle_policy;
922 config.rtcp_mux_policy = configuration.rtcp_mux_policy;
923 config.crypto_options = options.crypto_options;
924#if defined(ENABLE_EXTERNAL_AUTH)
925 config.enable_external_auth = true;
926#endif
927 transport_controller_.reset(new JsepTransportController(
928 signaling_thread(), network_thread(), port_allocator_.get(), config));
929 transport_controller_->SignalIceConnectionState.connect(
Steve Anton75737c02017-11-06 10:37:17 -0800930 this, &PeerConnection::OnTransportControllerConnectionState);
Zhi Huange830e682018-03-30 10:48:35 -0700931 transport_controller_->SignalIceGatheringState.connect(
Steve Anton75737c02017-11-06 10:37:17 -0800932 this, &PeerConnection::OnTransportControllerGatheringState);
Zhi Huange830e682018-03-30 10:48:35 -0700933 transport_controller_->SignalIceCandidatesGathered.connect(
Steve Anton75737c02017-11-06 10:37:17 -0800934 this, &PeerConnection::OnTransportControllerCandidatesGathered);
Zhi Huange830e682018-03-30 10:48:35 -0700935 transport_controller_->SignalIceCandidatesRemoved.connect(
Steve Anton75737c02017-11-06 10:37:17 -0800936 this, &PeerConnection::OnTransportControllerCandidatesRemoved);
937 transport_controller_->SignalDtlsHandshakeError.connect(
938 this, &PeerConnection::OnTransportControllerDtlsHandshakeError);
Zhi Huange830e682018-03-30 10:48:35 -0700939 transport_controller_->SignalRtpTransportChanged.connect(
940 this, &PeerConnection::OnRtpTransportChanged);
941 transport_controller_->SignalDtlsTransportChanged.connect(
942 this, &PeerConnection::OnDtlsTransportChanged);
Steve Anton75737c02017-11-06 10:37:17 -0800943
944 sctp_factory_ = factory_->CreateSctpTransportInternalFactory();
zhihuang29ff8442016-07-27 11:07:25 -0700945
deadbeefab9b2d12015-10-14 11:33:11 -0700946 stats_.reset(new StatsCollector(this));
hbos74e1a4f2016-09-15 23:33:01 -0700947 stats_collector_ = RTCStatsCollector::Create(this);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000948
Steve Antonba818672017-11-06 10:21:57 -0800949 configuration_ = configuration;
950
Steve Anton75737c02017-11-06 10:37:17 -0800951 // Obtain a certificate from RTCConfiguration if any were provided (optional).
952 rtc::scoped_refptr<rtc::RTCCertificate> certificate;
953 if (!configuration.certificates.empty()) {
954 // TODO(hbos,torbjorng): Decide on certificate-selection strategy instead of
955 // just picking the first one. The decision should be made based on the DTLS
956 // handshake. The DTLS negotiations need to know about all certificates.
957 certificate = configuration.certificates[0];
958 }
959
Steve Antond25da372017-11-06 14:50:29 -0800960 transport_controller_->SetIceConfig(ParseIceConfig(configuration));
Steve Anton75737c02017-11-06 10:37:17 -0800961
962 if (options.disable_encryption) {
963 dtls_enabled_ = false;
964 } else {
965 // Enable DTLS by default if we have an identity store or a certificate.
966 dtls_enabled_ = (cert_generator || certificate);
967 // |configuration| can override the default |dtls_enabled_| value.
968 if (configuration.enable_dtls_srtp) {
969 dtls_enabled_ = *(configuration.enable_dtls_srtp);
970 }
971 }
972
973 // Enable creation of RTP data channels if the kEnableRtpDataChannels is set.
974 // It takes precendence over the disable_sctp_data_channels
975 // PeerConnectionFactoryInterface::Options.
976 if (configuration.enable_rtp_data_channel) {
977 data_channel_type_ = cricket::DCT_RTP;
978 } else {
979 // DTLS has to be enabled to use SCTP.
980 if (!options.disable_sctp_data_channels && dtls_enabled_) {
981 data_channel_type_ = cricket::DCT_SCTP;
982 }
983 }
984
985 video_options_.screencast_min_bitrate_kbps =
986 configuration.screencast_min_bitrate;
987 audio_options_.combined_audio_video_bwe =
988 configuration.combined_audio_video_bwe;
989
990 audio_options_.audio_jitter_buffer_max_packets =
Oskar Sundbom9b28a032017-11-16 10:53:30 +0100991 configuration.audio_jitter_buffer_max_packets;
Steve Anton75737c02017-11-06 10:37:17 -0800992
993 audio_options_.audio_jitter_buffer_fast_accelerate =
Oskar Sundbom9b28a032017-11-16 10:53:30 +0100994 configuration.audio_jitter_buffer_fast_accelerate;
Steve Anton75737c02017-11-06 10:37:17 -0800995
996 // Whether the certificate generator/certificate is null or not determines
997 // what PeerConnectionDescriptionFactory will do, so make sure that we give it
998 // the right instructions by clearing the variables if needed.
999 if (!dtls_enabled_) {
1000 cert_generator.reset();
1001 certificate = nullptr;
1002 } else if (certificate) {
1003 // Favor generated certificate over the certificate generator.
1004 cert_generator.reset();
1005 }
1006
1007 webrtc_session_desc_factory_.reset(new WebRtcSessionDescriptionFactory(
1008 signaling_thread(), channel_manager(), this, session_id(),
1009 std::move(cert_generator), certificate));
1010 webrtc_session_desc_factory_->SignalCertificateReady.connect(
1011 this, &PeerConnection::OnCertificateReady);
1012
1013 if (options.disable_encryption) {
1014 webrtc_session_desc_factory_->SetSdesPolicy(cricket::SEC_DISABLED);
1015 }
1016
1017 webrtc_session_desc_factory_->set_enable_encrypted_rtp_header_extensions(
1018 options.crypto_options.enable_encrypted_rtp_header_extensions);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001019
Steve Anton4171afb2017-11-20 10:20:22 -08001020 // Add default audio/video transceivers for Plan B SDP.
1021 if (!IsUnifiedPlan()) {
1022 transceivers_.push_back(
1023 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1024 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_AUDIO)));
1025 transceivers_.push_back(
1026 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1027 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_VIDEO)));
1028 }
1029
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001030 return true;
1031}
1032
Steve Anton038834f2017-07-14 15:59:59 -07001033RTCError PeerConnection::ValidateConfiguration(
1034 const RTCConfiguration& config) const {
1035 if (config.ice_regather_interval_range &&
1036 config.continual_gathering_policy == GATHER_ONCE) {
1037 return RTCError(RTCErrorType::INVALID_PARAMETER,
1038 "ice_regather_interval_range specified but continual "
1039 "gathering policy is GATHER_ONCE");
1040 }
Qingsi Wangdea68892018-03-27 10:55:21 -07001041 auto result =
1042 cricket::P2PTransportChannel::ValidateIceConfig(ParseIceConfig(config));
1043 return result;
Steve Anton038834f2017-07-14 15:59:59 -07001044}
1045
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001046rtc::scoped_refptr<StreamCollectionInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001047PeerConnection::local_streams() {
Steve Antonfc853712018-03-01 13:48:58 -08001048 RTC_CHECK(!IsUnifiedPlan()) << "local_streams is not available with Unified "
1049 "Plan SdpSemantics. Please use GetSenders "
1050 "instead.";
deadbeefab9b2d12015-10-14 11:33:11 -07001051 return local_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001052}
1053
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001054rtc::scoped_refptr<StreamCollectionInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001055PeerConnection::remote_streams() {
Steve Antonfc853712018-03-01 13:48:58 -08001056 RTC_CHECK(!IsUnifiedPlan()) << "remote_streams is not available with Unified "
1057 "Plan SdpSemantics. Please use GetReceivers "
1058 "instead.";
deadbeefab9b2d12015-10-14 11:33:11 -07001059 return remote_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001060}
1061
perkj@webrtc.orgc2dd5ee2014-11-04 11:31:29 +00001062bool PeerConnection::AddStream(MediaStreamInterface* local_stream) {
Steve Antonfc853712018-03-01 13:48:58 -08001063 RTC_CHECK(!IsUnifiedPlan()) << "AddStream is not available with Unified Plan "
1064 "SdpSemantics. Please use AddTrack instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001065 TRACE_EVENT0("webrtc", "PeerConnection::AddStream");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001066 if (IsClosed()) {
1067 return false;
1068 }
deadbeefab9b2d12015-10-14 11:33:11 -07001069 if (!CanAddLocalMediaStream(local_streams_, local_stream)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001070 return false;
1071 }
deadbeefab9b2d12015-10-14 11:33:11 -07001072
1073 local_streams_->AddStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -08001074 MediaStreamObserver* observer = new MediaStreamObserver(local_stream);
1075 observer->SignalAudioTrackAdded.connect(this,
1076 &PeerConnection::OnAudioTrackAdded);
1077 observer->SignalAudioTrackRemoved.connect(
1078 this, &PeerConnection::OnAudioTrackRemoved);
1079 observer->SignalVideoTrackAdded.connect(this,
1080 &PeerConnection::OnVideoTrackAdded);
1081 observer->SignalVideoTrackRemoved.connect(
1082 this, &PeerConnection::OnVideoTrackRemoved);
kwibergd1fe2812016-04-27 06:47:29 -07001083 stream_observers_.push_back(std::unique_ptr<MediaStreamObserver>(observer));
deadbeefab9b2d12015-10-14 11:33:11 -07001084
deadbeefab9b2d12015-10-14 11:33:11 -07001085 for (const auto& track : local_stream->GetAudioTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001086 AddAudioTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -07001087 }
1088 for (const auto& track : local_stream->GetVideoTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001089 AddVideoTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -07001090 }
1091
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001092 stats_->AddStream(local_stream);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001093 observer_->OnRenegotiationNeeded();
1094 return true;
1095}
1096
1097void PeerConnection::RemoveStream(MediaStreamInterface* local_stream) {
Steve Antonfc853712018-03-01 13:48:58 -08001098 RTC_CHECK(!IsUnifiedPlan()) << "RemoveStream is not available with Unified "
1099 "Plan SdpSemantics. Please use RemoveTrack "
1100 "instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001101 TRACE_EVENT0("webrtc", "PeerConnection::RemoveStream");
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001102 if (!IsClosed()) {
1103 for (const auto& track : local_stream->GetAudioTracks()) {
1104 RemoveAudioTrack(track.get(), local_stream);
1105 }
1106 for (const auto& track : local_stream->GetVideoTracks()) {
1107 RemoveVideoTrack(track.get(), local_stream);
1108 }
deadbeefab9b2d12015-10-14 11:33:11 -07001109 }
deadbeefab9b2d12015-10-14 11:33:11 -07001110 local_streams_->RemoveStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -08001111 stream_observers_.erase(
1112 std::remove_if(
1113 stream_observers_.begin(), stream_observers_.end(),
kwibergd1fe2812016-04-27 06:47:29 -07001114 [local_stream](const std::unique_ptr<MediaStreamObserver>& observer) {
Seth Hampson13b8bad2018-03-13 16:05:28 -07001115 return observer->stream()->id().compare(local_stream->id()) == 0;
deadbeefeb459812015-12-15 19:24:43 -08001116 }),
1117 stream_observers_.end());
deadbeefab9b2d12015-10-14 11:33:11 -07001118
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001119 if (IsClosed()) {
1120 return;
1121 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001122 observer_->OnRenegotiationNeeded();
1123}
1124
deadbeefe1f9d832016-01-14 15:35:42 -08001125rtc::scoped_refptr<RtpSenderInterface> PeerConnection::AddTrack(
1126 MediaStreamTrackInterface* track,
1127 std::vector<MediaStreamInterface*> streams) {
1128 TRACE_EVENT0("webrtc", "PeerConnection::AddTrack");
Seth Hampson845e8782018-03-02 11:34:10 -08001129 std::vector<std::string> stream_ids;
Steve Antonf9381f02017-12-14 10:23:57 -08001130 for (auto* stream : streams) {
1131 if (!stream) {
1132 RTC_LOG(LS_ERROR) << "Stream list has null element.";
1133 return nullptr;
1134 }
Seth Hampson13b8bad2018-03-13 16:05:28 -07001135 stream_ids.push_back(stream->id());
Steve Antonf9381f02017-12-14 10:23:57 -08001136 }
Seth Hampson845e8782018-03-02 11:34:10 -08001137 auto sender_or_error = AddTrack(track, stream_ids);
Steve Antonf9381f02017-12-14 10:23:57 -08001138 if (!sender_or_error.ok()) {
deadbeefe1f9d832016-01-14 15:35:42 -08001139 return nullptr;
1140 }
Steve Antonf9381f02017-12-14 10:23:57 -08001141 return sender_or_error.MoveValue();
1142}
1143
Steve Anton2d6c76a2018-01-05 17:10:52 -08001144RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::AddTrack(
Steve Antonf9381f02017-12-14 10:23:57 -08001145 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001146 const std::vector<std::string>& stream_ids) {
Steve Anton2d6c76a2018-01-05 17:10:52 -08001147 TRACE_EVENT0("webrtc", "PeerConnection::AddTrack");
Steve Antonf9381f02017-12-14 10:23:57 -08001148 if (!track) {
1149 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "Track is null.");
1150 }
1151 if (!(track->kind() == MediaStreamTrackInterface::kAudioKind ||
1152 track->kind() == MediaStreamTrackInterface::kVideoKind)) {
1153 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1154 "Track has invalid kind: " + track->kind());
1155 }
Tomas Gunnarsson191bf5c2018-03-30 10:44:43 +00001156 // TODO(bugs.webrtc.org/7932): Support adding a track to multiple streams.
1157 if (stream_ids.size() > 1u) {
1158 LOG_AND_RETURN_ERROR(
1159 RTCErrorType::UNSUPPORTED_OPERATION,
1160 "AddTrack with more than one stream is not currently supported.");
1161 }
Steve Antonf9381f02017-12-14 10:23:57 -08001162 if (IsClosed()) {
1163 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
1164 "PeerConnection is closed.");
deadbeefe1f9d832016-01-14 15:35:42 -08001165 }
Steve Anton4171afb2017-11-20 10:20:22 -08001166 if (FindSenderForTrack(track)) {
Steve Antonf9381f02017-12-14 10:23:57 -08001167 LOG_AND_RETURN_ERROR(
1168 RTCErrorType::INVALID_PARAMETER,
1169 "Sender already exists for track " + track->id() + ".");
deadbeefe1f9d832016-01-14 15:35:42 -08001170 }
Tomas Gunnarsson191bf5c2018-03-30 10:44:43 +00001171 // TODO(bugs.webrtc.org/7933): MediaSession expects the sender to have exactly
1172 // one stream. AddTrackInternal will return an error if there is more than one
1173 // stream, but if the caller specifies none then we need to generate a random
1174 // stream id.
1175 std::vector<std::string> adjusted_stream_ids = stream_ids;
1176 if (stream_ids.empty()) {
1177 adjusted_stream_ids.push_back(rtc::CreateRandomUuid());
1178 }
1179 RTC_DCHECK_EQ(1, adjusted_stream_ids.size());
Steve Antonf9381f02017-12-14 10:23:57 -08001180 auto sender_or_error =
Tomas Gunnarsson191bf5c2018-03-30 10:44:43 +00001181 (IsUnifiedPlan() ? AddTrackUnifiedPlan(track, adjusted_stream_ids)
1182 : AddTrackPlanB(track, adjusted_stream_ids));
Steve Antonf9381f02017-12-14 10:23:57 -08001183 if (sender_or_error.ok()) {
1184 observer_->OnRenegotiationNeeded();
Steve Anton43a723a2018-01-04 15:48:17 -08001185 stats_->AddTrack(track);
Steve Antonf9381f02017-12-14 10:23:57 -08001186 }
1187 return sender_or_error;
1188}
deadbeefe1f9d832016-01-14 15:35:42 -08001189
Steve Antonf9381f02017-12-14 10:23:57 -08001190RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>>
1191PeerConnection::AddTrackPlanB(
1192 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001193 const std::vector<std::string>& stream_ids) {
Steve Anton02ee47c2018-01-10 16:26:06 -08001194 cricket::MediaType media_type =
1195 (track->kind() == MediaStreamTrackInterface::kAudioKind
1196 ? cricket::MEDIA_TYPE_AUDIO
1197 : cricket::MEDIA_TYPE_VIDEO);
Tomas Gunnarsson191bf5c2018-03-30 10:44:43 +00001198 auto new_sender = CreateSender(media_type, track, stream_ids);
deadbeefe1f9d832016-01-14 15:35:42 -08001199 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
Steve Anton57858b32018-02-15 15:19:50 -08001200 new_sender->internal()->SetVoiceMediaChannel(voice_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08001201 GetAudioTransceiver()->internal()->AddSender(new_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001202 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00001203 FindSenderInfo(local_audio_sender_infos_,
Tomas Gunnarsson191bf5c2018-03-30 10:44:43 +00001204 new_sender->internal()->stream_id(), track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08001205 if (sender_info) {
1206 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -08001207 }
Steve Antonf9381f02017-12-14 10:23:57 -08001208 } else {
1209 RTC_DCHECK_EQ(MediaStreamTrackInterface::kVideoKind, track->kind());
Steve Anton57858b32018-02-15 15:19:50 -08001210 new_sender->internal()->SetVideoMediaChannel(video_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08001211 GetVideoTransceiver()->internal()->AddSender(new_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001212 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00001213 FindSenderInfo(local_video_sender_infos_,
Tomas Gunnarsson191bf5c2018-03-30 10:44:43 +00001214 new_sender->internal()->stream_id(), track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08001215 if (sender_info) {
1216 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -08001217 }
deadbeefe1f9d832016-01-14 15:35:42 -08001218 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001219 return rtc::scoped_refptr<RtpSenderInterface>(new_sender);
Steve Antonf9381f02017-12-14 10:23:57 -08001220}
deadbeefe1f9d832016-01-14 15:35:42 -08001221
Steve Antonf9381f02017-12-14 10:23:57 -08001222RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>>
1223PeerConnection::AddTrackUnifiedPlan(
1224 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001225 const std::vector<std::string>& stream_ids) {
Steve Antonf9381f02017-12-14 10:23:57 -08001226 auto transceiver = FindFirstTransceiverForAddedTrack(track);
1227 if (transceiver) {
1228 if (transceiver->direction() == RtpTransceiverDirection::kRecvOnly) {
Steve Anton52d86772018-02-20 15:48:12 -08001229 transceiver->internal()->set_direction(
1230 RtpTransceiverDirection::kSendRecv);
Steve Antonf9381f02017-12-14 10:23:57 -08001231 } else if (transceiver->direction() == RtpTransceiverDirection::kInactive) {
Steve Anton52d86772018-02-20 15:48:12 -08001232 transceiver->internal()->set_direction(
1233 RtpTransceiverDirection::kSendOnly);
Steve Antonf9381f02017-12-14 10:23:57 -08001234 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001235 transceiver->sender()->SetTrack(track);
Seth Hampson845e8782018-03-02 11:34:10 -08001236 transceiver->internal()->sender_internal()->set_stream_ids(stream_ids);
Steve Antonf9381f02017-12-14 10:23:57 -08001237 } else {
1238 cricket::MediaType media_type =
1239 (track->kind() == MediaStreamTrackInterface::kAudioKind
1240 ? cricket::MEDIA_TYPE_AUDIO
1241 : cricket::MEDIA_TYPE_VIDEO);
Seth Hampson845e8782018-03-02 11:34:10 -08001242 auto sender = CreateSender(media_type, track, stream_ids);
Steve Anton02ee47c2018-01-10 16:26:06 -08001243 auto receiver = CreateReceiver(media_type, rtc::CreateRandomUuid());
1244 transceiver = CreateAndAddTransceiver(sender, receiver);
Steve Antonf9381f02017-12-14 10:23:57 -08001245 transceiver->internal()->set_created_by_addtrack(true);
Steve Anton52d86772018-02-20 15:48:12 -08001246 transceiver->internal()->set_direction(RtpTransceiverDirection::kSendRecv);
Steve Antonf9381f02017-12-14 10:23:57 -08001247 }
Steve Antonf9381f02017-12-14 10:23:57 -08001248 return transceiver->sender();
1249}
1250
1251rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1252PeerConnection::FindFirstTransceiverForAddedTrack(
1253 rtc::scoped_refptr<MediaStreamTrackInterface> track) {
1254 RTC_DCHECK(track);
1255 for (auto transceiver : transceivers_) {
1256 if (!transceiver->sender()->track() &&
Steve Anton69470252018-02-09 11:43:08 -08001257 cricket::MediaTypeToString(transceiver->media_type()) ==
Steve Antonf9381f02017-12-14 10:23:57 -08001258 track->kind() &&
Seth Hampson2f0d7022018-02-20 11:54:42 -08001259 !transceiver->internal()->has_ever_been_used_to_send() &&
1260 !transceiver->stopped()) {
Steve Antonf9381f02017-12-14 10:23:57 -08001261 return transceiver;
1262 }
1263 }
1264 return nullptr;
deadbeefe1f9d832016-01-14 15:35:42 -08001265}
1266
1267bool PeerConnection::RemoveTrack(RtpSenderInterface* sender) {
1268 TRACE_EVENT0("webrtc", "PeerConnection::RemoveTrack");
Steve Antonf9381f02017-12-14 10:23:57 -08001269 return RemoveTrackInternal(sender).ok();
1270}
1271
1272RTCError PeerConnection::RemoveTrackInternal(
1273 rtc::scoped_refptr<RtpSenderInterface> sender) {
1274 if (!sender) {
1275 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "Sender is null.");
1276 }
deadbeefe1f9d832016-01-14 15:35:42 -08001277 if (IsClosed()) {
Steve Antonf9381f02017-12-14 10:23:57 -08001278 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
1279 "PeerConnection is closed.");
deadbeefe1f9d832016-01-14 15:35:42 -08001280 }
Steve Antonf9381f02017-12-14 10:23:57 -08001281 if (IsUnifiedPlan()) {
1282 auto transceiver = FindTransceiverBySender(sender);
1283 if (!transceiver || !sender->track()) {
1284 return RTCError::OK();
1285 }
1286 sender->SetTrack(nullptr);
1287 if (transceiver->direction() == RtpTransceiverDirection::kSendRecv) {
Steve Anton52d86772018-02-20 15:48:12 -08001288 transceiver->internal()->set_direction(
1289 RtpTransceiverDirection::kRecvOnly);
Steve Antonf9381f02017-12-14 10:23:57 -08001290 } else if (transceiver->direction() == RtpTransceiverDirection::kSendOnly) {
Steve Anton52d86772018-02-20 15:48:12 -08001291 transceiver->internal()->set_direction(
1292 RtpTransceiverDirection::kInactive);
Steve Antonf9381f02017-12-14 10:23:57 -08001293 }
Steve Anton4171afb2017-11-20 10:20:22 -08001294 } else {
Steve Antonf9381f02017-12-14 10:23:57 -08001295 bool removed;
1296 if (sender->media_type() == cricket::MEDIA_TYPE_AUDIO) {
1297 removed = GetAudioTransceiver()->internal()->RemoveSender(sender);
1298 } else {
1299 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, sender->media_type());
1300 removed = GetVideoTransceiver()->internal()->RemoveSender(sender);
1301 }
1302 if (!removed) {
1303 LOG_AND_RETURN_ERROR(
1304 RTCErrorType::INVALID_PARAMETER,
1305 "Couldn't find sender " + sender->id() + " to remove.");
1306 }
Steve Anton4171afb2017-11-20 10:20:22 -08001307 }
deadbeefe1f9d832016-01-14 15:35:42 -08001308 observer_->OnRenegotiationNeeded();
Steve Antonf9381f02017-12-14 10:23:57 -08001309 return RTCError::OK();
1310}
1311
1312rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1313PeerConnection::FindTransceiverBySender(
1314 rtc::scoped_refptr<RtpSenderInterface> sender) {
1315 for (auto transceiver : transceivers_) {
1316 if (transceiver->sender() == sender) {
1317 return transceiver;
1318 }
1319 }
1320 return nullptr;
deadbeefe1f9d832016-01-14 15:35:42 -08001321}
1322
Steve Anton9158ef62017-11-27 13:01:52 -08001323RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1324PeerConnection::AddTransceiver(
1325 rtc::scoped_refptr<MediaStreamTrackInterface> track) {
1326 return AddTransceiver(track, RtpTransceiverInit());
1327}
1328
1329RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1330PeerConnection::AddTransceiver(
1331 rtc::scoped_refptr<MediaStreamTrackInterface> track,
1332 const RtpTransceiverInit& init) {
Steve Antonfc853712018-03-01 13:48:58 -08001333 RTC_CHECK(IsUnifiedPlan())
1334 << "AddTransceiver is only available with Unified Plan SdpSemantics";
Steve Anton9158ef62017-11-27 13:01:52 -08001335 if (!track) {
1336 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "track is null");
1337 }
1338 cricket::MediaType media_type;
1339 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
1340 media_type = cricket::MEDIA_TYPE_AUDIO;
1341 } else if (track->kind() == MediaStreamTrackInterface::kVideoKind) {
1342 media_type = cricket::MEDIA_TYPE_VIDEO;
1343 } else {
1344 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1345 "Track kind is not audio or video");
1346 }
1347 return AddTransceiver(media_type, track, init);
1348}
1349
1350RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1351PeerConnection::AddTransceiver(cricket::MediaType media_type) {
1352 return AddTransceiver(media_type, RtpTransceiverInit());
1353}
1354
1355RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1356PeerConnection::AddTransceiver(cricket::MediaType media_type,
1357 const RtpTransceiverInit& init) {
Steve Antonfc853712018-03-01 13:48:58 -08001358 RTC_CHECK(IsUnifiedPlan())
1359 << "AddTransceiver is only available with Unified Plan SdpSemantics";
Steve Anton9158ef62017-11-27 13:01:52 -08001360 if (!(media_type == cricket::MEDIA_TYPE_AUDIO ||
1361 media_type == cricket::MEDIA_TYPE_VIDEO)) {
1362 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1363 "media type is not audio or video");
1364 }
1365 return AddTransceiver(media_type, nullptr, init);
1366}
1367
1368RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1369PeerConnection::AddTransceiver(
1370 cricket::MediaType media_type,
1371 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Steve Anton22da89f2018-01-25 13:58:07 -08001372 const RtpTransceiverInit& init,
1373 bool fire_callback) {
Steve Anton9158ef62017-11-27 13:01:52 -08001374 RTC_DCHECK((media_type == cricket::MEDIA_TYPE_AUDIO ||
1375 media_type == cricket::MEDIA_TYPE_VIDEO));
1376 if (track) {
1377 RTC_DCHECK_EQ(media_type,
1378 (track->kind() == MediaStreamTrackInterface::kAudioKind
1379 ? cricket::MEDIA_TYPE_AUDIO
1380 : cricket::MEDIA_TYPE_VIDEO));
1381 }
1382
1383 // TODO(bugs.webrtc.org/7600): Verify init.
1384
Tomas Gunnarsson191bf5c2018-03-30 10:44:43 +00001385 if (init.stream_ids.size() > 1u) {
1386 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
1387 "More than one stream is not yet supported.");
1388 }
1389
1390 std::vector<std::string> stream_ids = {
1391 !init.stream_ids.empty() ? init.stream_ids[0] : rtc::CreateRandomUuid()};
1392
1393 auto sender = CreateSender(media_type, track, stream_ids);
Steve Anton02ee47c2018-01-10 16:26:06 -08001394 auto receiver = CreateReceiver(media_type, rtc::CreateRandomUuid());
1395 auto transceiver = CreateAndAddTransceiver(sender, receiver);
1396 transceiver->internal()->set_direction(init.direction);
1397
Steve Anton22da89f2018-01-25 13:58:07 -08001398 if (fire_callback) {
1399 observer_->OnRenegotiationNeeded();
1400 }
Steve Antonf9381f02017-12-14 10:23:57 -08001401
1402 return rtc::scoped_refptr<RtpTransceiverInterface>(transceiver);
1403}
1404
Steve Anton02ee47c2018-01-10 16:26:06 -08001405rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
1406PeerConnection::CreateSender(
1407 cricket::MediaType media_type,
1408 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001409 const std::vector<std::string>& stream_ids) {
Steve Anton9158ef62017-11-27 13:01:52 -08001410 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> sender;
Steve Anton02ee47c2018-01-10 16:26:06 -08001411 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
1412 RTC_DCHECK(!track ||
1413 (track->kind() == MediaStreamTrackInterface::kAudioKind));
1414 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
1415 signaling_thread(),
Steve Anton47136dd2018-01-12 10:49:35 -08001416 new AudioRtpSender(worker_thread(),
1417 static_cast<AudioTrackInterface*>(track.get()),
Seth Hampson845e8782018-03-02 11:34:10 -08001418 stream_ids, stats_.get()));
Steve Anton02ee47c2018-01-10 16:26:06 -08001419 } else {
1420 RTC_DCHECK_EQ(media_type, cricket::MEDIA_TYPE_VIDEO);
1421 RTC_DCHECK(!track ||
1422 (track->kind() == MediaStreamTrackInterface::kVideoKind));
1423 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
1424 signaling_thread(),
Steve Anton47136dd2018-01-12 10:49:35 -08001425 new VideoRtpSender(worker_thread(),
1426 static_cast<VideoTrackInterface*>(track.get()),
Seth Hampson845e8782018-03-02 11:34:10 -08001427 stream_ids));
Steve Anton02ee47c2018-01-10 16:26:06 -08001428 }
Seth Hampson845e8782018-03-02 11:34:10 -08001429 sender->internal()->set_stream_ids(stream_ids);
Steve Anton02ee47c2018-01-10 16:26:06 -08001430 return sender;
1431}
1432
1433rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1434PeerConnection::CreateReceiver(cricket::MediaType media_type,
1435 const std::string& receiver_id) {
Steve Anton9158ef62017-11-27 13:01:52 -08001436 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1437 receiver;
Steve Anton9158ef62017-11-27 13:01:52 -08001438 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton9158ef62017-11-27 13:01:52 -08001439 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
Steve Anton60776752018-01-10 11:51:34 -08001440 signaling_thread(),
Steve Antond3679212018-01-17 17:41:02 -08001441 new AudioRtpReceiver(worker_thread(), receiver_id, {}));
Steve Anton9158ef62017-11-27 13:01:52 -08001442 } else {
Steve Anton02ee47c2018-01-10 16:26:06 -08001443 RTC_DCHECK_EQ(media_type, cricket::MEDIA_TYPE_VIDEO);
Steve Anton9158ef62017-11-27 13:01:52 -08001444 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
1445 signaling_thread(),
Steve Antond3679212018-01-17 17:41:02 -08001446 new VideoRtpReceiver(worker_thread(), receiver_id, {}));
Steve Anton9158ef62017-11-27 13:01:52 -08001447 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001448 return receiver;
1449}
1450
1451rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1452PeerConnection::CreateAndAddTransceiver(
1453 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> sender,
1454 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1455 receiver) {
1456 auto transceiver = RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1457 signaling_thread(), new RtpTransceiver(sender, receiver));
Steve Anton9158ef62017-11-27 13:01:52 -08001458 transceivers_.push_back(transceiver);
Steve Anton52d86772018-02-20 15:48:12 -08001459 transceiver->internal()->SignalNegotiationNeeded.connect(
1460 this, &PeerConnection::OnNegotiationNeeded);
Steve Antonf9381f02017-12-14 10:23:57 -08001461 return transceiver;
Steve Anton9158ef62017-11-27 13:01:52 -08001462}
1463
Steve Anton52d86772018-02-20 15:48:12 -08001464void PeerConnection::OnNegotiationNeeded() {
1465 RTC_DCHECK_RUN_ON(signaling_thread());
1466 RTC_DCHECK(!IsClosed());
1467 observer_->OnRenegotiationNeeded();
1468}
1469
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001470rtc::scoped_refptr<DtmfSenderInterface> PeerConnection::CreateDtmfSender(
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001471 AudioTrackInterface* track) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001472 TRACE_EVENT0("webrtc", "PeerConnection::CreateDtmfSender");
zhihuang29ff8442016-07-27 11:07:25 -07001473 if (IsClosed()) {
1474 return nullptr;
1475 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001476 if (!track) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001477 RTC_LOG(LS_ERROR) << "CreateDtmfSender - track is NULL.";
deadbeef20cb0c12017-02-01 20:27:00 -08001478 return nullptr;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001479 }
Steve Anton4171afb2017-11-20 10:20:22 -08001480 auto track_sender = FindSenderForTrack(track);
1481 if (!track_sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001482 RTC_LOG(LS_ERROR) << "CreateDtmfSender called with a non-added track.";
deadbeef20cb0c12017-02-01 20:27:00 -08001483 return nullptr;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001484 }
1485
Steve Anton4171afb2017-11-20 10:20:22 -08001486 return track_sender->GetDtmfSender();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001487}
1488
deadbeeffac06552015-11-25 11:26:01 -08001489rtc::scoped_refptr<RtpSenderInterface> PeerConnection::CreateSender(
deadbeefbd7d8f72015-12-18 16:58:44 -08001490 const std::string& kind,
1491 const std::string& stream_id) {
Steve Antonfc853712018-03-01 13:48:58 -08001492 RTC_CHECK(!IsUnifiedPlan()) << "CreateSender is not available with Unified "
1493 "Plan SdpSemantics. Please use AddTransceiver "
1494 "instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001495 TRACE_EVENT0("webrtc", "PeerConnection::CreateSender");
zhihuang29ff8442016-07-27 11:07:25 -07001496 if (IsClosed()) {
1497 return nullptr;
1498 }
Steve Anton4171afb2017-11-20 10:20:22 -08001499
Seth Hampson845e8782018-03-02 11:34:10 -08001500 std::vector<std::string> stream_ids;
Tomas Gunnarsson191bf5c2018-03-30 10:44:43 +00001501 if (!stream_id.empty()) {
Seth Hampson845e8782018-03-02 11:34:10 -08001502 stream_ids.push_back(stream_id);
Steve Anton02ee47c2018-01-10 16:26:06 -08001503 }
1504
Steve Anton4171afb2017-11-20 10:20:22 -08001505 // TODO(steveanton): Move construction of the RtpSenders to RtpTransceiver.
deadbeefa601f5c2016-06-06 14:27:39 -07001506 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender;
deadbeeffac06552015-11-25 11:26:01 -08001507 if (kind == MediaStreamTrackInterface::kAudioKind) {
Seth Hampson845e8782018-03-02 11:34:10 -08001508 auto* audio_sender =
1509 new AudioRtpSender(worker_thread(), nullptr, stream_ids, stats_.get());
Steve Anton57858b32018-02-15 15:19:50 -08001510 audio_sender->SetVoiceMediaChannel(voice_media_channel());
deadbeefa601f5c2016-06-06 14:27:39 -07001511 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton02ee47c2018-01-10 16:26:06 -08001512 signaling_thread(), audio_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001513 GetAudioTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 11:26:01 -08001514 } else if (kind == MediaStreamTrackInterface::kVideoKind) {
Steve Anton47136dd2018-01-12 10:49:35 -08001515 auto* video_sender =
Seth Hampson845e8782018-03-02 11:34:10 -08001516 new VideoRtpSender(worker_thread(), nullptr, stream_ids);
Steve Anton57858b32018-02-15 15:19:50 -08001517 video_sender->SetVideoMediaChannel(video_media_channel());
deadbeefa601f5c2016-06-06 14:27:39 -07001518 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton02ee47c2018-01-10 16:26:06 -08001519 signaling_thread(), video_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001520 GetVideoTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 11:26:01 -08001521 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001522 RTC_LOG(LS_ERROR) << "CreateSender called with invalid kind: " << kind;
Steve Anton4171afb2017-11-20 10:20:22 -08001523 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08001524 }
Steve Anton4171afb2017-11-20 10:20:22 -08001525
deadbeefe1f9d832016-01-14 15:35:42 -08001526 return new_sender;
deadbeeffac06552015-11-25 11:26:01 -08001527}
1528
deadbeef70ab1a12015-09-28 16:53:55 -07001529std::vector<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::GetSenders()
1530 const {
deadbeefa601f5c2016-06-06 14:27:39 -07001531 std::vector<rtc::scoped_refptr<RtpSenderInterface>> ret;
Steve Anton4171afb2017-11-20 10:20:22 -08001532 for (auto sender : GetSendersInternal()) {
1533 ret.push_back(sender);
deadbeefa601f5c2016-06-06 14:27:39 -07001534 }
1535 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -07001536}
1537
Steve Anton4171afb2017-11-20 10:20:22 -08001538std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1539PeerConnection::GetSendersInternal() const {
1540 std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1541 all_senders;
1542 for (auto transceiver : transceivers_) {
1543 auto senders = transceiver->internal()->senders();
1544 all_senders.insert(all_senders.end(), senders.begin(), senders.end());
1545 }
1546 return all_senders;
1547}
1548
deadbeef70ab1a12015-09-28 16:53:55 -07001549std::vector<rtc::scoped_refptr<RtpReceiverInterface>>
1550PeerConnection::GetReceivers() const {
deadbeefa601f5c2016-06-06 14:27:39 -07001551 std::vector<rtc::scoped_refptr<RtpReceiverInterface>> ret;
Steve Anton4171afb2017-11-20 10:20:22 -08001552 for (const auto& receiver : GetReceiversInternal()) {
1553 ret.push_back(receiver);
deadbeefa601f5c2016-06-06 14:27:39 -07001554 }
1555 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -07001556}
1557
Steve Anton4171afb2017-11-20 10:20:22 -08001558std::vector<
1559 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1560PeerConnection::GetReceiversInternal() const {
1561 std::vector<
1562 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1563 all_receivers;
1564 for (auto transceiver : transceivers_) {
1565 auto receivers = transceiver->internal()->receivers();
1566 all_receivers.insert(all_receivers.end(), receivers.begin(),
1567 receivers.end());
1568 }
1569 return all_receivers;
1570}
1571
Steve Anton9158ef62017-11-27 13:01:52 -08001572std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
1573PeerConnection::GetTransceivers() const {
Steve Antonfc853712018-03-01 13:48:58 -08001574 RTC_CHECK(IsUnifiedPlan())
1575 << "GetTransceivers is only supported with Unified Plan SdpSemantics.";
Steve Anton9158ef62017-11-27 13:01:52 -08001576 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> all_transceivers;
1577 for (auto transceiver : transceivers_) {
1578 all_transceivers.push_back(transceiver);
1579 }
1580 return all_transceivers;
1581}
1582
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001583bool PeerConnection::GetStats(StatsObserver* observer,
wu@webrtc.orgb9a088b2014-02-13 23:18:49 +00001584 MediaStreamTrackInterface* track,
1585 StatsOutputLevel level) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001586 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
deadbeef0a6c4ca2015-10-06 11:38:28 -07001587 RTC_DCHECK(signaling_thread()->IsCurrent());
nisse7ce109a2017-01-31 00:57:56 -08001588 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001589 RTC_LOG(LS_ERROR) << "GetStats - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001590 return false;
1591 }
1592
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001593 stats_->UpdateStats(level);
zhihuange9e94c32016-11-04 11:38:15 -07001594 // The StatsCollector is used to tell if a track is valid because it may
1595 // remember tracks that the PeerConnection previously removed.
1596 if (track && !stats_->IsValidTrack(track->id())) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001597 RTC_LOG(LS_WARNING) << "GetStats is called with an invalid track: "
1598 << track->id();
zhihuange9e94c32016-11-04 11:38:15 -07001599 return false;
1600 }
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001601 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_GETSTATS,
tommi@webrtc.org5b06b062014-08-15 08:38:30 +00001602 new GetStatsMsg(observer, track));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001603 return true;
1604}
1605
hbos74e1a4f2016-09-15 23:33:01 -07001606void PeerConnection::GetStats(RTCStatsCollectorCallback* callback) {
Henrik Boström1df1bf82018-03-20 13:24:20 +01001607 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
hbos74e1a4f2016-09-15 23:33:01 -07001608 RTC_DCHECK(stats_collector_);
Henrik Boström1df1bf82018-03-20 13:24:20 +01001609 RTC_DCHECK(callback);
hbos74e1a4f2016-09-15 23:33:01 -07001610 stats_collector_->GetStatsReport(callback);
1611}
1612
Henrik Boström1df1bf82018-03-20 13:24:20 +01001613void PeerConnection::GetStats(
1614 rtc::scoped_refptr<RtpSenderInterface> selector,
1615 rtc::scoped_refptr<RTCStatsCollectorCallback> callback) {
1616 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
1617 RTC_DCHECK(callback);
1618 RTC_DCHECK(stats_collector_);
1619 rtc::scoped_refptr<RtpSenderInternal> internal_sender;
1620 if (selector) {
1621 for (const auto& proxy_transceiver : transceivers_) {
1622 for (const auto& proxy_sender :
1623 proxy_transceiver->internal()->senders()) {
1624 if (proxy_sender == selector) {
1625 internal_sender = proxy_sender->internal();
1626 break;
1627 }
1628 }
1629 if (internal_sender)
1630 break;
1631 }
1632 }
1633 // If there is no |internal_sender| then |selector| is either null or does not
1634 // belong to the PeerConnection (in Plan B, senders can be removed from the
1635 // PeerConnection). This means that "all the stats objects representing the
1636 // selector" is an empty set. Invoking GetStatsReport() with a null selector
1637 // produces an empty stats report.
1638 stats_collector_->GetStatsReport(internal_sender, callback);
1639}
1640
1641void PeerConnection::GetStats(
1642 rtc::scoped_refptr<RtpReceiverInterface> selector,
1643 rtc::scoped_refptr<RTCStatsCollectorCallback> callback) {
1644 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
1645 RTC_DCHECK(callback);
1646 RTC_DCHECK(stats_collector_);
1647 rtc::scoped_refptr<RtpReceiverInternal> internal_receiver;
1648 if (selector) {
1649 for (const auto& proxy_transceiver : transceivers_) {
1650 for (const auto& proxy_receiver :
1651 proxy_transceiver->internal()->receivers()) {
1652 if (proxy_receiver == selector) {
1653 internal_receiver = proxy_receiver->internal();
1654 break;
1655 }
1656 }
1657 if (internal_receiver)
1658 break;
1659 }
1660 }
1661 // If there is no |internal_receiver| then |selector| is either null or does
1662 // not belong to the PeerConnection (in Plan B, receivers can be removed from
1663 // the PeerConnection). This means that "all the stats objects representing
1664 // the selector" is an empty set. Invoking GetStatsReport() with a null
1665 // selector produces an empty stats report.
1666 stats_collector_->GetStatsReport(internal_receiver, callback);
1667}
1668
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001669PeerConnectionInterface::SignalingState PeerConnection::signaling_state() {
1670 return signaling_state_;
1671}
1672
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001673PeerConnectionInterface::IceConnectionState
1674PeerConnection::ice_connection_state() {
1675 return ice_connection_state_;
1676}
1677
1678PeerConnectionInterface::IceGatheringState
1679PeerConnection::ice_gathering_state() {
1680 return ice_gathering_state_;
1681}
1682
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001683rtc::scoped_refptr<DataChannelInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001684PeerConnection::CreateDataChannel(
1685 const std::string& label,
1686 const DataChannelInit* config) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001687 TRACE_EVENT0("webrtc", "PeerConnection::CreateDataChannel");
zhihuang9763d562016-08-05 11:14:50 -07001688
deadbeefab9b2d12015-10-14 11:33:11 -07001689 bool first_datachannel = !HasDataChannels();
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001690
kwibergd1fe2812016-04-27 06:47:29 -07001691 std::unique_ptr<InternalDataChannelInit> internal_config;
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00001692 if (config) {
1693 internal_config.reset(new InternalDataChannelInit(*config));
1694 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001695 rtc::scoped_refptr<DataChannelInterface> channel(
deadbeefab9b2d12015-10-14 11:33:11 -07001696 InternalCreateDataChannel(label, internal_config.get()));
1697 if (!channel.get()) {
1698 return nullptr;
1699 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001700
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001701 // Trigger the onRenegotiationNeeded event for every new RTP DataChannel, or
1702 // the first SCTP DataChannel.
Steve Anton75737c02017-11-06 10:37:17 -08001703 if (data_channel_type() == cricket::DCT_RTP || first_datachannel) {
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001704 observer_->OnRenegotiationNeeded();
1705 }
wu@webrtc.org91053e72013-08-10 07:18:04 +00001706
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001707 return DataChannelProxy::Create(signaling_thread(), channel.get());
1708}
1709
1710void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
1711 const MediaConstraintsInterface* constraints) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001712 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
Steve Anton8d3444d2017-10-20 15:30:51 -07001713
zhihuang1c378ed2017-08-17 14:10:50 -07001714 PeerConnectionInterface::RTCOfferAnswerOptions offer_answer_options;
1715 // Always create an offer even if |ConvertConstraintsToOfferAnswerOptions|
1716 // returns false for now. Because |ConvertConstraintsToOfferAnswerOptions|
1717 // compares the mandatory fields parsed with the mandatory fields added in the
1718 // |constraints| and some downstream applications might create offers with
1719 // mandatory fields which would not be parsed in the helper method. For
1720 // example, in Chromium/remoting, |kEnableDtlsSrtp| is added to the
1721 // |constraints| as a mandatory field but it is not parsed.
1722 ConvertConstraintsToOfferAnswerOptions(constraints, &offer_answer_options);
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001723
zhihuang1c378ed2017-08-17 14:10:50 -07001724 CreateOffer(observer, offer_answer_options);
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001725}
1726
1727void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
1728 const RTCOfferAnswerOptions& options) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001729 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
Steve Anton8d3444d2017-10-20 15:30:51 -07001730
nisse7ce109a2017-01-31 00:57:56 -08001731 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001732 RTC_LOG(LS_ERROR) << "CreateOffer - observer is NULL.";
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001733 return;
1734 }
deadbeefab9b2d12015-10-14 11:33:11 -07001735
Steve Anton8d3444d2017-10-20 15:30:51 -07001736 if (IsClosed()) {
1737 std::string error = "CreateOffer called when PeerConnection is closed.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001738 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001739 PostCreateSessionDescriptionFailure(
1740 observer, RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error)));
Steve Anton8d3444d2017-10-20 15:30:51 -07001741 return;
1742 }
1743
zhihuang1c378ed2017-08-17 14:10:50 -07001744 if (!ValidateOfferAnswerOptions(options)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001745 std::string error = "CreateOffer called with invalid options.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001746 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001747 PostCreateSessionDescriptionFailure(
1748 observer, RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error)));
deadbeefab9b2d12015-10-14 11:33:11 -07001749 return;
1750 }
1751
Steve Anton22da89f2018-01-25 13:58:07 -08001752 // Legacy handling for offer_to_receive_audio and offer_to_receive_video.
1753 // Specified in WebRTC section 4.4.3.2 "Legacy configuration extensions".
1754 if (IsUnifiedPlan()) {
1755 RTCError error = HandleLegacyOfferOptions(options);
1756 if (!error.ok()) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001757 PostCreateSessionDescriptionFailure(observer, std::move(error));
Steve Anton22da89f2018-01-25 13:58:07 -08001758 return;
1759 }
1760 }
1761
zhihuang1c378ed2017-08-17 14:10:50 -07001762 cricket::MediaSessionOptions session_options;
1763 GetOptionsForOffer(options, &session_options);
Steve Antond25da372017-11-06 14:50:29 -08001764 webrtc_session_desc_factory_->CreateOffer(observer, options, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001765}
1766
Steve Anton22da89f2018-01-25 13:58:07 -08001767RTCError PeerConnection::HandleLegacyOfferOptions(
1768 const RTCOfferAnswerOptions& options) {
1769 RTC_DCHECK(IsUnifiedPlan());
1770
1771 if (options.offer_to_receive_audio == 0) {
1772 RemoveRecvDirectionFromReceivingTransceiversOfType(
1773 cricket::MEDIA_TYPE_AUDIO);
1774 } else if (options.offer_to_receive_audio == 1) {
1775 AddUpToOneReceivingTransceiverOfType(cricket::MEDIA_TYPE_AUDIO);
1776 } else if (options.offer_to_receive_audio > 1) {
1777 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
1778 "offer_to_receive_audio > 1 is not supported.");
1779 }
1780
1781 if (options.offer_to_receive_video == 0) {
1782 RemoveRecvDirectionFromReceivingTransceiversOfType(
1783 cricket::MEDIA_TYPE_VIDEO);
1784 } else if (options.offer_to_receive_video == 1) {
1785 AddUpToOneReceivingTransceiverOfType(cricket::MEDIA_TYPE_VIDEO);
1786 } else if (options.offer_to_receive_video > 1) {
1787 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
1788 "offer_to_receive_video > 1 is not supported.");
1789 }
1790
1791 return RTCError::OK();
1792}
1793
1794void PeerConnection::RemoveRecvDirectionFromReceivingTransceiversOfType(
1795 cricket::MediaType media_type) {
1796 for (auto transceiver : GetReceivingTransceiversOfType(media_type)) {
1797 transceiver->internal()->set_direction(
1798 RtpTransceiverDirectionWithRecvSet(transceiver->direction(), false));
1799 }
1800}
1801
1802void PeerConnection::AddUpToOneReceivingTransceiverOfType(
1803 cricket::MediaType media_type) {
1804 if (GetReceivingTransceiversOfType(media_type).empty()) {
1805 RtpTransceiverInit init;
1806 init.direction = RtpTransceiverDirection::kRecvOnly;
1807 AddTransceiver(media_type, nullptr, init, /*fire_callback=*/false);
1808 }
1809}
1810
1811std::vector<rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
1812PeerConnection::GetReceivingTransceiversOfType(cricket::MediaType media_type) {
1813 std::vector<
1814 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
1815 receiving_transceivers;
1816 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08001817 if (!transceiver->stopped() && transceiver->media_type() == media_type &&
Steve Anton22da89f2018-01-25 13:58:07 -08001818 RtpTransceiverDirectionHasRecv(transceiver->direction())) {
1819 receiving_transceivers.push_back(transceiver);
1820 }
1821 }
1822 return receiving_transceivers;
1823}
1824
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001825void PeerConnection::CreateAnswer(
1826 CreateSessionDescriptionObserver* observer,
1827 const MediaConstraintsInterface* constraints) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001828 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
Steve Anton8d3444d2017-10-20 15:30:51 -07001829
nisse7ce109a2017-01-31 00:57:56 -08001830 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001831 RTC_LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001832 return;
1833 }
deadbeefab9b2d12015-10-14 11:33:11 -07001834
zhihuang1c378ed2017-08-17 14:10:50 -07001835 PeerConnectionInterface::RTCOfferAnswerOptions offer_answer_options;
1836 if (!ConvertConstraintsToOfferAnswerOptions(constraints,
1837 &offer_answer_options)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001838 std::string error = "CreateAnswer called with invalid constraints.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001839 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001840 PostCreateSessionDescriptionFailure(
1841 observer, RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error)));
deadbeefab9b2d12015-10-14 11:33:11 -07001842 return;
1843 }
1844
Steve Anton8d3444d2017-10-20 15:30:51 -07001845 CreateAnswer(observer, offer_answer_options);
htaa2a49d92016-03-04 02:51:39 -08001846}
1847
1848void PeerConnection::CreateAnswer(CreateSessionDescriptionObserver* observer,
1849 const RTCOfferAnswerOptions& options) {
1850 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
nisse7ce109a2017-01-31 00:57:56 -08001851 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001852 RTC_LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
htaa2a49d92016-03-04 02:51:39 -08001853 return;
1854 }
1855
Steve Antondffead82018-02-06 10:31:29 -08001856 if (!(signaling_state_ == kHaveRemoteOffer ||
1857 signaling_state_ == kHaveLocalPrAnswer)) {
1858 std::string error =
1859 "PeerConnection cannot create an answer in a state other than "
1860 "have-remote-offer or have-local-pranswer.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001861 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001862 PostCreateSessionDescriptionFailure(
1863 observer, RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error)));
Steve Anton8d3444d2017-10-20 15:30:51 -07001864 return;
1865 }
1866
Steve Antondffead82018-02-06 10:31:29 -08001867 // The remote description should be set if we're in the right state.
1868 RTC_DCHECK(remote_description());
Steve Anton8d3444d2017-10-20 15:30:51 -07001869
Steve Anton22da89f2018-01-25 13:58:07 -08001870 if (IsUnifiedPlan()) {
1871 if (options.offer_to_receive_audio != RTCOfferAnswerOptions::kUndefined) {
1872 RTC_LOG(LS_WARNING) << "CreateAnswer: offer_to_receive_audio is not "
1873 "supported with Unified Plan semantics. Use the "
1874 "RtpTransceiver API instead.";
1875 }
1876 if (options.offer_to_receive_video != RTCOfferAnswerOptions::kUndefined) {
1877 RTC_LOG(LS_WARNING) << "CreateAnswer: offer_to_receive_video is not "
1878 "supported with Unified Plan semantics. Use the "
1879 "RtpTransceiver API instead.";
1880 }
1881 }
1882
htaa2a49d92016-03-04 02:51:39 -08001883 cricket::MediaSessionOptions session_options;
zhihuang1c378ed2017-08-17 14:10:50 -07001884 GetOptionsForAnswer(options, &session_options);
htaa2a49d92016-03-04 02:51:39 -08001885
Steve Antond25da372017-11-06 14:50:29 -08001886 webrtc_session_desc_factory_->CreateAnswer(observer, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001887}
1888
1889void PeerConnection::SetLocalDescription(
1890 SetSessionDescriptionObserver* observer,
Steve Anton80dd7b52018-02-16 17:08:42 -08001891 SessionDescriptionInterface* desc_ptr) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001892 TRACE_EVENT0("webrtc", "PeerConnection::SetLocalDescription");
Steve Anton8a006912017-12-04 15:25:56 -08001893
Steve Anton80dd7b52018-02-16 17:08:42 -08001894 // The SetLocalDescription contract is that we take ownership of the session
1895 // description regardless of the outcome, so wrap it in a unique_ptr right
1896 // away. Ideally, SetLocalDescription's signature will be changed to take the
1897 // description as a unique_ptr argument to formalize this agreement.
1898 std::unique_ptr<SessionDescriptionInterface> desc(desc_ptr);
1899
nisse7ce109a2017-01-31 00:57:56 -08001900 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001901 RTC_LOG(LS_ERROR) << "SetLocalDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001902 return;
1903 }
Steve Anton8a006912017-12-04 15:25:56 -08001904
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001905 if (!desc) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001906 PostSetSessionDescriptionFailure(
1907 observer,
1908 RTCError(RTCErrorType::INTERNAL_ERROR, "SessionDescription is NULL."));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001909 return;
1910 }
Steve Anton8d3444d2017-10-20 15:30:51 -07001911
Steve Anton80dd7b52018-02-16 17:08:42 -08001912 // If a session error has occurred the PeerConnection is in a possibly
1913 // inconsistent state so fail right away.
1914 if (session_error() != SessionError::kNone) {
1915 std::string error_message = GetSessionErrorMsg();
1916 RTC_LOG(LS_ERROR) << "SetLocalDescription: " << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001917 PostSetSessionDescriptionFailure(
1918 observer,
1919 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton80dd7b52018-02-16 17:08:42 -08001920 return;
1921 }
Steve Anton8d3444d2017-10-20 15:30:51 -07001922
Steve Anton80dd7b52018-02-16 17:08:42 -08001923 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_LOCAL);
1924 if (!error.ok()) {
1925 std::string error_message = GetSetDescriptionErrorMessage(
1926 cricket::CS_LOCAL, desc->GetType(), error);
1927 RTC_LOG(LS_ERROR) << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001928 PostSetSessionDescriptionFailure(
1929 observer,
1930 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton80dd7b52018-02-16 17:08:42 -08001931 return;
1932 }
1933
1934 // Grab the description type before moving ownership to ApplyLocalDescription,
1935 // which may destroy it before returning.
1936 const SdpType type = desc->GetType();
1937
1938 error = ApplyLocalDescription(std::move(desc));
Steve Anton8a006912017-12-04 15:25:56 -08001939 // |desc| may be destroyed at this point.
1940
1941 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08001942 // If ApplyLocalDescription fails, the PeerConnection could be in an
1943 // inconsistent state, so act conservatively here and set the session error
1944 // so that future calls to SetLocalDescription/SetRemoteDescription fail.
1945 SetSessionError(SessionError::kContent, error.message());
1946 std::string error_message =
1947 GetSetDescriptionErrorMessage(cricket::CS_LOCAL, type, error);
1948 RTC_LOG(LS_ERROR) << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001949 PostSetSessionDescriptionFailure(
1950 observer,
1951 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton8d3444d2017-10-20 15:30:51 -07001952 return;
1953 }
Steve Anton8a006912017-12-04 15:25:56 -08001954 RTC_DCHECK(local_description());
1955
1956 PostSetSessionDescriptionSuccess(observer);
1957
1958 // According to JSEP, after setLocalDescription, changing the candidate pool
1959 // size is not allowed, and changing the set of ICE servers will not result
1960 // in new candidates being gathered.
1961 port_allocator_->FreezeCandidatePool();
1962
1963 // MaybeStartGathering needs to be called after posting
1964 // MSG_SET_SESSIONDESCRIPTION_SUCCESS, so that we don't signal any candidates
1965 // before signaling that SetLocalDescription completed.
1966 transport_controller_->MaybeStartGathering();
1967
Steve Antona3a92c22017-12-07 10:27:41 -08001968 if (local_description()->GetType() == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08001969 // TODO(deadbeef): We already had to hop to the network thread for
1970 // MaybeStartGathering...
1971 network_thread()->Invoke<void>(
1972 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
1973 port_allocator_.get()));
Steve Anton0ffaaa22018-02-23 10:31:30 -08001974 // Make UMA notes about what was agreed to.
1975 ReportNegotiatedSdpSemantics(*local_description());
Steve Anton8a006912017-12-04 15:25:56 -08001976 }
1977}
1978
1979RTCError PeerConnection::ApplyLocalDescription(
1980 std::unique_ptr<SessionDescriptionInterface> desc) {
1981 RTC_DCHECK_RUN_ON(signaling_thread());
1982 RTC_DCHECK(desc);
1983
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001984 // Update stats here so that we have the most recent stats for tracks and
1985 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001986 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 15:25:56 -08001987
Steve Antondcc3c022017-12-22 16:02:54 -08001988 // Take a reference to the old local description since it's used below to
1989 // compare against the new local description. When setting the new local
1990 // description, grab ownership of the replaced session description in case it
1991 // is the same as |old_local_description|, to keep it alive for the duration
1992 // of the method.
1993 const SessionDescriptionInterface* old_local_description =
1994 local_description();
1995 std::unique_ptr<SessionDescriptionInterface> replaced_local_description;
Zhi Huange830e682018-03-30 10:48:35 -07001996 SdpType type = desc->GetType();
Steve Anton3828c062017-12-06 10:34:51 -08001997 if (type == SdpType::kAnswer) {
Steve Antondcc3c022017-12-22 16:02:54 -08001998 replaced_local_description = pending_local_description_
1999 ? std::move(pending_local_description_)
2000 : std::move(current_local_description_);
Steve Anton8a006912017-12-04 15:25:56 -08002001 current_local_description_ = std::move(desc);
2002 pending_local_description_ = nullptr;
2003 current_remote_description_ = std::move(pending_remote_description_);
2004 } else {
Steve Antondcc3c022017-12-22 16:02:54 -08002005 replaced_local_description = std::move(pending_local_description_);
Steve Anton8a006912017-12-04 15:25:56 -08002006 pending_local_description_ = std::move(desc);
2007 }
2008 // The session description to apply now must be accessed by
2009 // |local_description()|.
Henrik Boströmfdb92012017-11-09 19:55:44 +01002010 RTC_DCHECK(local_description());
deadbeefab9b2d12015-10-14 11:33:11 -07002011
Zhi Huange830e682018-03-30 10:48:35 -07002012 RTCError error = PushdownTransportDescription(cricket::CS_LOCAL, type);
2013 if (!error.ok()) {
2014 return error;
2015 }
2016
Steve Antondcc3c022017-12-22 16:02:54 -08002017 if (IsUnifiedPlan()) {
2018 RTCError error = UpdateTransceiversAndDataChannels(
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002019 cricket::CS_LOCAL, *local_description(), old_local_description,
2020 remote_description());
Steve Anton8a006912017-12-04 15:25:56 -08002021 if (!error.ok()) {
2022 return error;
2023 }
Steve Antondcc3c022017-12-22 16:02:54 -08002024 for (auto transceiver : transceivers_) {
2025 const ContentInfo* content =
2026 FindMediaSectionForTransceiver(transceiver, local_description());
2027 if (!content) {
2028 continue;
2029 }
2030 const MediaContentDescription* media_desc = content->media_description();
2031 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
2032 transceiver->internal()->set_current_direction(media_desc->direction());
2033 }
2034 if (content->rejected && !transceiver->stopped()) {
2035 transceiver->Stop();
2036 }
2037 }
2038 } else {
Zhi Huange830e682018-03-30 10:48:35 -07002039 // Media channels will be created only when offer is set. These may use new
2040 // transports just created by PushdownTransportDescription.
Steve Antondcc3c022017-12-22 16:02:54 -08002041 if (type == SdpType::kOffer) {
2042 // TODO(bugs.webrtc.org/4676) - Handle CreateChannel failure, as new local
2043 // description is applied. Restore back to old description.
2044 RTCError error = CreateChannels(*local_description()->description());
2045 if (!error.ok()) {
2046 return error;
2047 }
2048 }
Steve Antondcc3c022017-12-22 16:02:54 -08002049 // Remove unused channels if MediaContentDescription is rejected.
2050 RemoveUnusedChannels(local_description()->description());
2051 }
Steve Anton8a006912017-12-04 15:25:56 -08002052
Zhi Huange830e682018-03-30 10:48:35 -07002053 error = UpdateSessionState(type, cricket::CS_LOCAL,
2054 local_description()->description());
Steve Anton8a006912017-12-04 15:25:56 -08002055 if (!error.ok()) {
2056 return error;
2057 }
Steve Antondcc3c022017-12-22 16:02:54 -08002058
Steve Anton8a006912017-12-04 15:25:56 -08002059 if (remote_description()) {
2060 // Now that we have a local description, we can push down remote candidates.
2061 UseCandidatesInSessionDescription(remote_description());
2062 }
2063
2064 pending_ice_restarts_.clear();
2065 if (session_error() != SessionError::kNone) {
2066 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
2067 }
2068
deadbeefab9b2d12015-10-14 11:33:11 -07002069 // If setting the description decided our SSL role, allocate any necessary
2070 // SCTP sids.
2071 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08002072 if (data_channel_type() == cricket::DCT_SCTP && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07002073 AllocateSctpSids(role);
2074 }
2075
Steve Antond3679212018-01-17 17:41:02 -08002076 if (IsUnifiedPlan()) {
2077 for (auto transceiver : transceivers_) {
2078 const ContentInfo* content =
2079 FindMediaSectionForTransceiver(transceiver, local_description());
2080 if (!content) {
2081 continue;
2082 }
2083 if (content->rejected && !transceiver->stopped()) {
2084 transceiver->Stop();
2085 }
Steve Anton74255ff2018-01-24 18:32:57 -08002086 const auto& streams = content->media_description()->streams();
2087 if (!content->rejected && !streams.empty()) {
Steve Antond3679212018-01-17 17:41:02 -08002088 transceiver->internal()->sender_internal()->set_stream_ids(
Seth Hampson845e8782018-03-02 11:34:10 -08002089 streams[0].stream_ids());
Steve Antond3679212018-01-17 17:41:02 -08002090 transceiver->internal()->sender_internal()->SetSsrc(
Steve Anton74255ff2018-01-24 18:32:57 -08002091 streams[0].first_ssrc());
Steve Antond3679212018-01-17 17:41:02 -08002092 }
2093 }
2094 } else {
2095 // Plan B semantics.
2096
Steve Antondcc3c022017-12-22 16:02:54 -08002097 // Update state and SSRC of local MediaStreams and DataChannels based on the
2098 // local session description.
2099 const cricket::ContentInfo* audio_content =
2100 GetFirstAudioContent(local_description()->description());
2101 if (audio_content) {
2102 if (audio_content->rejected) {
2103 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
2104 } else {
2105 const cricket::AudioContentDescription* audio_desc =
2106 audio_content->media_description()->as_audio();
2107 UpdateLocalSenders(audio_desc->streams(), audio_desc->type());
2108 }
deadbeeffaac4972015-11-12 15:33:07 -08002109 }
deadbeefab9b2d12015-10-14 11:33:11 -07002110
Steve Antondcc3c022017-12-22 16:02:54 -08002111 const cricket::ContentInfo* video_content =
2112 GetFirstVideoContent(local_description()->description());
2113 if (video_content) {
2114 if (video_content->rejected) {
2115 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
2116 } else {
2117 const cricket::VideoContentDescription* video_desc =
2118 video_content->media_description()->as_video();
2119 UpdateLocalSenders(video_desc->streams(), video_desc->type());
2120 }
deadbeeffaac4972015-11-12 15:33:07 -08002121 }
deadbeefab9b2d12015-10-14 11:33:11 -07002122 }
2123
2124 const cricket::ContentInfo* data_content =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002125 GetFirstDataContent(local_description()->description());
deadbeefab9b2d12015-10-14 11:33:11 -07002126 if (data_content) {
2127 const cricket::DataContentDescription* data_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08002128 data_content->media_description()->as_data();
deadbeefab9b2d12015-10-14 11:33:11 -07002129 if (rtc::starts_with(data_desc->protocol().data(),
2130 cricket::kMediaProtocolRtpPrefix)) {
2131 UpdateLocalRtpDataChannels(data_desc->streams());
2132 }
2133 }
2134
Steve Anton8a006912017-12-04 15:25:56 -08002135 return RTCError::OK();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002136}
2137
2138void PeerConnection::SetRemoteDescription(
Henrik Boströma4ecf552017-11-23 14:17:07 +00002139 SetSessionDescriptionObserver* observer,
2140 SessionDescriptionInterface* desc) {
Henrik Boström31638672017-11-23 17:48:32 +01002141 SetRemoteDescription(
2142 std::unique_ptr<SessionDescriptionInterface>(desc),
2143 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface>(
2144 new SetRemoteDescriptionObserverAdapter(this, observer)));
2145}
2146
2147void PeerConnection::SetRemoteDescription(
2148 std::unique_ptr<SessionDescriptionInterface> desc,
2149 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface> observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +01002150 TRACE_EVENT0("webrtc", "PeerConnection::SetRemoteDescription");
Steve Anton8a006912017-12-04 15:25:56 -08002151
nisse7ce109a2017-01-31 00:57:56 -08002152 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002153 RTC_LOG(LS_ERROR) << "SetRemoteDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002154 return;
2155 }
Steve Anton8a006912017-12-04 15:25:56 -08002156
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002157 if (!desc) {
Henrik Boström31638672017-11-23 17:48:32 +01002158 observer->OnSetRemoteDescriptionComplete(RTCError(
Steve Anton8a006912017-12-04 15:25:56 -08002159 RTCErrorType::INVALID_PARAMETER, "SessionDescription is NULL."));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002160 return;
2161 }
Steve Anton8d3444d2017-10-20 15:30:51 -07002162
Steve Anton80dd7b52018-02-16 17:08:42 -08002163 // If a session error has occurred the PeerConnection is in a possibly
2164 // inconsistent state so fail right away.
2165 if (session_error() != SessionError::kNone) {
2166 std::string error_message = GetSessionErrorMsg();
2167 RTC_LOG(LS_ERROR) << "SetRemoteDescription: " << error_message;
2168 observer->OnSetRemoteDescriptionComplete(
2169 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
2170 return;
2171 }
Steve Anton71439a62018-02-15 11:53:06 -08002172
Steve Anton80dd7b52018-02-16 17:08:42 -08002173 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_REMOTE);
Steve Anton71439a62018-02-15 11:53:06 -08002174 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08002175 std::string error_message = GetSetDescriptionErrorMessage(
2176 cricket::CS_REMOTE, desc->GetType(), error);
2177 RTC_LOG(LS_ERROR) << error_message;
Steve Anton71439a62018-02-15 11:53:06 -08002178 observer->OnSetRemoteDescriptionComplete(
2179 RTCError(error.type(), std::move(error_message)));
2180 return;
2181 }
Steve Anton71439a62018-02-15 11:53:06 -08002182
Steve Anton80dd7b52018-02-16 17:08:42 -08002183 // Grab the description type before moving ownership to
2184 // ApplyRemoteDescription, which may destroy it before returning.
2185 const SdpType type = desc->GetType();
2186
2187 error = ApplyRemoteDescription(std::move(desc));
2188 // |desc| may be destroyed at this point.
2189
2190 if (!error.ok()) {
2191 // If ApplyRemoteDescription fails, the PeerConnection could be in an
2192 // inconsistent state, so act conservatively here and set the session error
2193 // so that future calls to SetLocalDescription/SetRemoteDescription fail.
2194 SetSessionError(SessionError::kContent, error.message());
2195 std::string error_message =
2196 GetSetDescriptionErrorMessage(cricket::CS_REMOTE, type, error);
2197 RTC_LOG(LS_ERROR) << error_message;
2198 observer->OnSetRemoteDescriptionComplete(
2199 RTCError(error.type(), std::move(error_message)));
2200 return;
2201 }
2202 RTC_DCHECK(remote_description());
2203
Steve Anton8e20f172018-03-06 10:55:04 -08002204 if (type == SdpType::kOffer) {
2205 // Report to UMA the format of the received offer.
2206 ReportSdpFormatReceived(*remote_description());
2207 }
2208
Steve Anton80dd7b52018-02-16 17:08:42 -08002209 if (type == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002210 // TODO(deadbeef): We already had to hop to the network thread for
2211 // MaybeStartGathering...
2212 network_thread()->Invoke<void>(
2213 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
2214 port_allocator_.get()));
Harald Alvestrand5dbb5862018-02-13 23:48:00 +01002215 // Make UMA notes about what was agreed to.
Steve Anton0ffaaa22018-02-23 10:31:30 -08002216 ReportNegotiatedSdpSemantics(*remote_description());
Steve Anton8a006912017-12-04 15:25:56 -08002217 }
2218
2219 observer->OnSetRemoteDescriptionComplete(RTCError::OK());
2220}
2221
2222RTCError PeerConnection::ApplyRemoteDescription(
2223 std::unique_ptr<SessionDescriptionInterface> desc) {
2224 RTC_DCHECK_RUN_ON(signaling_thread());
2225 RTC_DCHECK(desc);
2226
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002227 // Update stats here so that we have the most recent stats for tracks and
2228 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00002229 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 15:25:56 -08002230
Steve Antondcc3c022017-12-22 16:02:54 -08002231 // Take a reference to the old remote description since it's used below to
2232 // compare against the new remote description. When setting the new remote
2233 // description, grab ownership of the replaced session description in case it
2234 // is the same as |old_remote_description|, to keep it alive for the duration
2235 // of the method.
Steve Anton8a006912017-12-04 15:25:56 -08002236 const SessionDescriptionInterface* old_remote_description =
2237 remote_description();
Steve Anton8a006912017-12-04 15:25:56 -08002238 std::unique_ptr<SessionDescriptionInterface> replaced_remote_description;
Steve Anton3828c062017-12-06 10:34:51 -08002239 SdpType type = desc->GetType();
2240 if (type == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002241 replaced_remote_description = pending_remote_description_
2242 ? std::move(pending_remote_description_)
2243 : std::move(current_remote_description_);
2244 current_remote_description_ = std::move(desc);
2245 pending_remote_description_ = nullptr;
2246 current_local_description_ = std::move(pending_local_description_);
2247 } else {
2248 replaced_remote_description = std::move(pending_remote_description_);
2249 pending_remote_description_ = std::move(desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002250 }
Steve Anton8a006912017-12-04 15:25:56 -08002251 // The session description to apply now must be accessed by
2252 // |remote_description()|.
Henrik Boströmfdb92012017-11-09 19:55:44 +01002253 RTC_DCHECK(remote_description());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002254
Zhi Huange830e682018-03-30 10:48:35 -07002255 RTCError error = PushdownTransportDescription(cricket::CS_REMOTE, type);
2256 if (!error.ok()) {
2257 return error;
2258 }
Steve Anton8a006912017-12-04 15:25:56 -08002259 // Transport and Media channels will be created only when offer is set.
Steve Antondcc3c022017-12-22 16:02:54 -08002260 if (IsUnifiedPlan()) {
2261 RTCError error = UpdateTransceiversAndDataChannels(
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002262 cricket::CS_REMOTE, *remote_description(), local_description(),
2263 old_remote_description);
Steve Anton8a006912017-12-04 15:25:56 -08002264 if (!error.ok()) {
2265 return error;
2266 }
Steve Antondcc3c022017-12-22 16:02:54 -08002267 } else {
Zhi Huange830e682018-03-30 10:48:35 -07002268 // Media channels will be created only when offer is set. These may use new
2269 // transports just created by PushdownTransportDescription.
Steve Antondcc3c022017-12-22 16:02:54 -08002270 if (type == SdpType::kOffer) {
Zhi Huange830e682018-03-30 10:48:35 -07002271 // TODO(mallinath) - Handle CreateChannel failure, as new local
Steve Antondcc3c022017-12-22 16:02:54 -08002272 // description is applied. Restore back to old description.
2273 RTCError error = CreateChannels(*remote_description()->description());
2274 if (!error.ok()) {
2275 return error;
2276 }
2277 }
Steve Antondcc3c022017-12-22 16:02:54 -08002278 // Remove unused channels if MediaContentDescription is rejected.
2279 RemoveUnusedChannels(remote_description()->description());
2280 }
Steve Anton8a006912017-12-04 15:25:56 -08002281
Zhi Huange830e682018-03-30 10:48:35 -07002282 // NOTE: Candidates allocation will be initiated only when
2283 // SetLocalDescription is called.
2284 error = UpdateSessionState(type, cricket::CS_REMOTE,
2285 remote_description()->description());
Steve Anton8a006912017-12-04 15:25:56 -08002286 if (!error.ok()) {
2287 return error;
2288 }
2289
2290 if (local_description() &&
2291 !UseCandidatesInSessionDescription(remote_description())) {
2292 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidCandidates);
2293 }
2294
2295 if (old_remote_description) {
2296 for (const cricket::ContentInfo& content :
2297 old_remote_description->description()->contents()) {
2298 // Check if this new SessionDescription contains new ICE ufrag and
2299 // password that indicates the remote peer requests an ICE restart.
2300 // TODO(deadbeef): When we start storing both the current and pending
2301 // remote description, this should reset pending_ice_restarts and compare
2302 // against the current description.
2303 if (CheckForRemoteIceRestart(old_remote_description, remote_description(),
2304 content.name)) {
Steve Anton3828c062017-12-06 10:34:51 -08002305 if (type == SdpType::kOffer) {
Steve Anton8a006912017-12-04 15:25:56 -08002306 pending_ice_restarts_.insert(content.name);
2307 }
2308 } else {
2309 // We retain all received candidates only if ICE is not restarted.
2310 // When ICE is restarted, all previous candidates belong to an old
2311 // generation and should not be kept.
2312 // TODO(deadbeef): This goes against the W3C spec which says the remote
2313 // description should only contain candidates from the last set remote
2314 // description plus any candidates added since then. We should remove
2315 // this once we're sure it won't break anything.
2316 WebRtcSessionDescriptionFactory::CopyCandidatesFromSessionDescription(
2317 old_remote_description, content.name, mutable_remote_description());
2318 }
2319 }
2320 }
2321
2322 if (session_error() != SessionError::kNone) {
2323 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
2324 }
2325
2326 // Set the the ICE connection state to connecting since the connection may
2327 // become writable with peer reflexive candidates before any remote candidate
2328 // is signaled.
2329 // TODO(pthatcher): This is a short-term solution for crbug/446908. A real fix
2330 // is to have a new signal the indicates a change in checking state from the
2331 // transport and expose a new checking() member from transport that can be
2332 // read to determine the current checking state. The existing SignalConnecting
2333 // actually means "gathering candidates", so cannot be be used here.
Steve Antona3a92c22017-12-07 10:27:41 -08002334 if (remote_description()->GetType() != SdpType::kOffer &&
Steve Anton8a006912017-12-04 15:25:56 -08002335 ice_connection_state() == PeerConnectionInterface::kIceConnectionNew) {
2336 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
2337 }
2338
deadbeefab9b2d12015-10-14 11:33:11 -07002339 // If setting the description decided our SSL role, allocate any necessary
2340 // SCTP sids.
2341 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08002342 if (data_channel_type() == cricket::DCT_SCTP && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07002343 AllocateSctpSids(role);
2344 }
2345
Steve Antondcc3c022017-12-22 16:02:54 -08002346 if (IsUnifiedPlan()) {
Steve Anton8b815cd2018-02-16 16:14:42 -08002347 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
2348 receiving_transceivers;
Steve Antonc49bcd92018-02-14 14:28:13 -08002349 std::vector<rtc::scoped_refptr<MediaStreamInterface>> added_streams;
Steve Antondcc3c022017-12-22 16:02:54 -08002350 for (auto transceiver : transceivers_) {
2351 const ContentInfo* content =
2352 FindMediaSectionForTransceiver(transceiver, remote_description());
2353 if (!content) {
2354 continue;
2355 }
2356 const MediaContentDescription* media_desc = content->media_description();
2357 RtpTransceiverDirection local_direction =
2358 RtpTransceiverDirectionReversed(media_desc->direction());
2359 // From the WebRTC specification, steps 2.2.8.5/6 of section 4.4.1.6 "Set
2360 // the RTCSessionDescription: If direction is sendrecv or recvonly, and
2361 // transceiver's current direction is neither sendrecv nor recvonly,
2362 // process the addition of a remote track for the media description.
Tomas Gunnarsson191bf5c2018-03-30 10:44:43 +00002363 //
2364 // Create a sync label in the case of an unsignalled msid.
2365 std::string sync_label = rtc::CreateRandomUuid();
Seth Hampson2f0d7022018-02-20 11:54:42 -08002366 if (!media_desc->streams().empty()) {
Steve Anton5a26a3a2018-02-28 11:38:47 -08002367 const cricket::StreamParams& stream_params = media_desc->streams()[0];
Seth Hampson845e8782018-03-02 11:34:10 -08002368 if (!stream_params.stream_ids().empty()) {
Tomas Gunnarsson191bf5c2018-03-30 10:44:43 +00002369 sync_label = stream_params.stream_ids()[0];
Steve Anton5a26a3a2018-02-28 11:38:47 -08002370 }
Seth Hampson2f0d7022018-02-20 11:54:42 -08002371 }
Steve Antondcc3c022017-12-22 16:02:54 -08002372 if (RtpTransceiverDirectionHasRecv(local_direction) &&
2373 (!transceiver->current_direction() ||
2374 !RtpTransceiverDirectionHasRecv(
Seth Hampson2f0d7022018-02-20 11:54:42 -08002375 *transceiver->current_direction()))) {
Tomas Gunnarsson191bf5c2018-03-30 10:44:43 +00002376 rtc::scoped_refptr<MediaStreamInterface> stream =
2377 remote_streams_->find(sync_label);
2378 if (!stream) {
2379 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
2380 MediaStream::Create(sync_label));
2381 remote_streams_->AddStream(stream);
2382 added_streams.push_back(stream);
Steve Antonef65ef12018-01-10 17:15:20 -08002383 }
Tomas Gunnarsson191bf5c2018-03-30 10:44:43 +00002384 transceiver->internal()->receiver_internal()->SetStreams({stream});
Steve Anton8b815cd2018-02-16 16:14:42 -08002385 receiving_transceivers.push_back(transceiver);
Steve Antondcc3c022017-12-22 16:02:54 -08002386 }
2387 // If direction is sendonly or inactive, and transceiver's current
2388 // direction is neither sendonly nor inactive, process the removal of a
2389 // remote track for the media description.
2390 if (!RtpTransceiverDirectionHasRecv(local_direction) &&
Steve Antonef65ef12018-01-10 17:15:20 -08002391 (transceiver->current_direction() &&
Steve Antondcc3c022017-12-22 16:02:54 -08002392 RtpTransceiverDirectionHasRecv(*transceiver->current_direction()))) {
Steve Antonef65ef12018-01-10 17:15:20 -08002393 transceiver->internal()->receiver_internal()->SetStreams({});
Steve Antondcc3c022017-12-22 16:02:54 -08002394 }
2395 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
2396 transceiver->internal()->set_current_direction(local_direction);
2397 }
2398 if (content->rejected && !transceiver->stopped()) {
2399 transceiver->Stop();
2400 }
Seth Hampson2f0d7022018-02-20 11:54:42 -08002401 if (!content->rejected &&
2402 RtpTransceiverDirectionHasRecv(local_direction)) {
2403 // Set ssrc to 0 in the case of an unsignalled ssrc.
2404 uint32_t ssrc = 0;
2405 if (!media_desc->streams().empty()) {
2406 ssrc = media_desc->streams()[0].first_ssrc();
2407 }
2408 transceiver->internal()->receiver_internal()->SetupMediaChannel(ssrc);
Steve Antond3679212018-01-17 17:41:02 -08002409 }
Steve Antondcc3c022017-12-22 16:02:54 -08002410 }
Steve Antonc49bcd92018-02-14 14:28:13 -08002411 // Once all processing has finished, fire off callbacks.
Steve Anton8b815cd2018-02-16 16:14:42 -08002412 for (auto transceiver : receiving_transceivers) {
Steve Anton6e221372018-02-20 12:59:16 -08002413 stats_->AddTrack(transceiver->receiver()->track());
Steve Anton8b815cd2018-02-16 16:14:42 -08002414 observer_->OnTrack(transceiver);
2415 observer_->OnAddTrack(transceiver->receiver(),
2416 transceiver->receiver()->streams());
Steve Antonef65ef12018-01-10 17:15:20 -08002417 }
Steve Antonc49bcd92018-02-14 14:28:13 -08002418 for (auto stream : added_streams) {
2419 observer_->OnAddStream(stream);
2420 }
Steve Antondcc3c022017-12-22 16:02:54 -08002421 }
2422
Henrik Boströmfdb92012017-11-09 19:55:44 +01002423 const cricket::ContentInfo* audio_content =
2424 GetFirstAudioContent(remote_description()->description());
2425 const cricket::ContentInfo* video_content =
2426 GetFirstVideoContent(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002427 const cricket::AudioContentDescription* audio_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002428 GetFirstAudioContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002429 const cricket::VideoContentDescription* video_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002430 GetFirstVideoContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002431 const cricket::DataContentDescription* data_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002432 GetFirstDataContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002433
2434 // Check if the descriptions include streams, just in case the peer supports
2435 // MSID, but doesn't indicate so with "a=msid-semantic".
Henrik Boströmfdb92012017-11-09 19:55:44 +01002436 if (remote_description()->description()->msid_supported() ||
deadbeefbda7e0b2015-12-08 17:13:40 -08002437 (audio_desc && !audio_desc->streams().empty()) ||
2438 (video_desc && !video_desc->streams().empty())) {
2439 remote_peer_supports_msid_ = true;
2440 }
deadbeefab9b2d12015-10-14 11:33:11 -07002441
2442 // We wait to signal new streams until we finish processing the description,
2443 // since only at that point will new streams have all their tracks.
2444 rtc::scoped_refptr<StreamCollection> new_streams(StreamCollection::Create());
2445
Steve Antondcc3c022017-12-22 16:02:54 -08002446 if (!IsUnifiedPlan()) {
2447 // TODO(steveanton): When removing RTP senders/receivers in response to a
2448 // rejected media section, there is some cleanup logic that expects the
2449 // voice/ video channel to still be set. But in this method the voice/video
2450 // channel would have been destroyed by the SetRemoteDescription caller
2451 // above so the cleanup that relies on them fails to run. The RemoveSenders
2452 // calls should be moved to right before the DestroyChannel calls to fix
2453 // this.
Steve Anton8d3444d2017-10-20 15:30:51 -07002454
Steve Antondcc3c022017-12-22 16:02:54 -08002455 // Find all audio rtp streams and create corresponding remote AudioTracks
2456 // and MediaStreams.
2457 if (audio_content) {
2458 if (audio_content->rejected) {
2459 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
2460 } else {
2461 bool default_audio_track_needed =
2462 !remote_peer_supports_msid_ &&
2463 RtpTransceiverDirectionHasSend(audio_desc->direction());
2464 UpdateRemoteSendersList(GetActiveStreams(audio_desc),
2465 default_audio_track_needed, audio_desc->type(),
2466 new_streams);
2467 }
deadbeeffaac4972015-11-12 15:33:07 -08002468 }
deadbeefab9b2d12015-10-14 11:33:11 -07002469
Steve Antondcc3c022017-12-22 16:02:54 -08002470 // Find all video rtp streams and create corresponding remote VideoTracks
2471 // and MediaStreams.
2472 if (video_content) {
2473 if (video_content->rejected) {
2474 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
2475 } else {
2476 bool default_video_track_needed =
2477 !remote_peer_supports_msid_ &&
2478 RtpTransceiverDirectionHasSend(video_desc->direction());
2479 UpdateRemoteSendersList(GetActiveStreams(video_desc),
2480 default_video_track_needed, video_desc->type(),
2481 new_streams);
2482 }
deadbeeffaac4972015-11-12 15:33:07 -08002483 }
deadbeefab9b2d12015-10-14 11:33:11 -07002484
Steve Antondcc3c022017-12-22 16:02:54 -08002485 // Update the DataChannels with the information from the remote peer.
2486 if (data_desc) {
2487 if (rtc::starts_with(data_desc->protocol().data(),
2488 cricket::kMediaProtocolRtpPrefix)) {
2489 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
2490 }
deadbeefab9b2d12015-10-14 11:33:11 -07002491 }
deadbeefab9b2d12015-10-14 11:33:11 -07002492
Steve Antondcc3c022017-12-22 16:02:54 -08002493 // Iterate new_streams and notify the observer about new MediaStreams.
2494 for (size_t i = 0; i < new_streams->count(); ++i) {
2495 MediaStreamInterface* new_stream = new_streams->at(i);
2496 stats_->AddStream(new_stream);
2497 observer_->OnAddStream(
2498 rtc::scoped_refptr<MediaStreamInterface>(new_stream));
2499 }
deadbeefab9b2d12015-10-14 11:33:11 -07002500
Steve Antondcc3c022017-12-22 16:02:54 -08002501 UpdateEndedRemoteMediaStreams();
2502 }
deadbeefab9b2d12015-10-14 11:33:11 -07002503
Steve Anton8a006912017-12-04 15:25:56 -08002504 return RTCError::OK();
deadbeeffc648b62015-10-13 16:42:33 -07002505}
2506
Steve Antondcc3c022017-12-22 16:02:54 -08002507RTCError PeerConnection::UpdateTransceiversAndDataChannels(
2508 cricket::ContentSource source,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002509 const SessionDescriptionInterface& new_session,
2510 const SessionDescriptionInterface* old_local_description,
2511 const SessionDescriptionInterface* old_remote_description) {
Steve Antondcc3c022017-12-22 16:02:54 -08002512 RTC_DCHECK(IsUnifiedPlan());
2513
Steve Anton7464fca2018-01-19 11:10:37 -08002514 const cricket::ContentGroup* bundle_group = nullptr;
2515 if (new_session.GetType() == SdpType::kOffer) {
2516 auto bundle_group_or_error =
2517 GetEarlyBundleGroup(*new_session.description());
2518 if (!bundle_group_or_error.ok()) {
2519 return bundle_group_or_error.MoveError();
2520 }
2521 bundle_group = bundle_group_or_error.MoveValue();
Steve Antondcc3c022017-12-22 16:02:54 -08002522 }
Steve Antondcc3c022017-12-22 16:02:54 -08002523
Steve Antondcc3c022017-12-22 16:02:54 -08002524 const ContentInfos& new_contents = new_session.description()->contents();
Steve Antondcc3c022017-12-22 16:02:54 -08002525 for (size_t i = 0; i < new_contents.size(); ++i) {
2526 const cricket::ContentInfo& new_content = new_contents[i];
Steve Antondcc3c022017-12-22 16:02:54 -08002527 cricket::MediaType media_type = new_content.media_description()->type();
2528 seen_mids_.insert(new_content.name);
2529 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
2530 media_type == cricket::MEDIA_TYPE_VIDEO) {
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002531 const cricket::ContentInfo* old_local_content = nullptr;
2532 if (old_local_description &&
2533 i < old_local_description->description()->contents().size()) {
2534 old_local_content =
2535 &old_local_description->description()->contents()[i];
2536 }
2537 const cricket::ContentInfo* old_remote_content = nullptr;
2538 if (old_remote_description &&
2539 i < old_remote_description->description()->contents().size()) {
2540 old_remote_content =
2541 &old_remote_description->description()->contents()[i];
2542 }
Steve Antondcc3c022017-12-22 16:02:54 -08002543 auto transceiver_or_error =
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002544 AssociateTransceiver(source, new_session.GetType(), i, new_content,
2545 old_local_content, old_remote_content);
Steve Antondcc3c022017-12-22 16:02:54 -08002546 if (!transceiver_or_error.ok()) {
2547 return transceiver_or_error.MoveError();
2548 }
2549 auto transceiver = transceiver_or_error.MoveValue();
Steve Antondcc3c022017-12-22 16:02:54 -08002550 RTCError error =
2551 UpdateTransceiverChannel(transceiver, new_content, bundle_group);
2552 if (!error.ok()) {
2553 return error;
2554 }
2555 } else if (media_type == cricket::MEDIA_TYPE_DATA) {
Steve Antonfa2260d2017-12-28 16:38:23 -08002556 if (GetDataMid() && new_content.name != *GetDataMid()) {
2557 // Ignore all but the first data section.
2558 continue;
2559 }
2560 RTCError error = UpdateDataChannel(source, new_content, bundle_group);
2561 if (!error.ok()) {
2562 return error;
2563 }
Steve Antondcc3c022017-12-22 16:02:54 -08002564 } else {
2565 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
2566 "Unknown section type.");
2567 }
2568 }
2569
2570 return RTCError::OK();
2571}
2572
2573RTCError PeerConnection::UpdateTransceiverChannel(
2574 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2575 transceiver,
2576 const cricket::ContentInfo& content,
2577 const cricket::ContentGroup* bundle_group) {
2578 RTC_DCHECK(IsUnifiedPlan());
2579 RTC_DCHECK(transceiver);
2580 cricket::BaseChannel* channel = transceiver->internal()->channel();
2581 if (content.rejected) {
2582 if (channel) {
2583 transceiver->internal()->SetChannel(nullptr);
2584 DestroyBaseChannel(channel);
2585 }
2586 } else {
2587 if (!channel) {
Steve Anton69470252018-02-09 11:43:08 -08002588 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Zhi Huange830e682018-03-30 10:48:35 -07002589 channel = CreateVoiceChannel(content.name);
Steve Antondcc3c022017-12-22 16:02:54 -08002590 } else {
Steve Anton69470252018-02-09 11:43:08 -08002591 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, transceiver->media_type());
Zhi Huange830e682018-03-30 10:48:35 -07002592 channel = CreateVideoChannel(content.name);
Steve Antondcc3c022017-12-22 16:02:54 -08002593 }
2594 if (!channel) {
2595 LOG_AND_RETURN_ERROR(
2596 RTCErrorType::INTERNAL_ERROR,
2597 "Failed to create channel for mid=" + content.name);
2598 }
2599 transceiver->internal()->SetChannel(channel);
2600 }
2601 }
2602 return RTCError::OK();
2603}
2604
Steve Antonfa2260d2017-12-28 16:38:23 -08002605RTCError PeerConnection::UpdateDataChannel(
2606 cricket::ContentSource source,
2607 const cricket::ContentInfo& content,
2608 const cricket::ContentGroup* bundle_group) {
2609 if (data_channel_type_ == cricket::DCT_NONE) {
Steve Antondbf9d032018-01-19 15:23:40 -08002610 // If data channels are disabled, ignore this media section. CreateAnswer
2611 // will take care of rejecting it.
2612 return RTCError::OK();
Steve Antonfa2260d2017-12-28 16:38:23 -08002613 }
2614 if (content.rejected) {
2615 DestroyDataChannel();
2616 } else {
2617 if (!rtp_data_channel_ && !sctp_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07002618 if (!CreateDataChannel(content.name)) {
Steve Antonfa2260d2017-12-28 16:38:23 -08002619 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
2620 "Failed to create data channel.");
2621 }
2622 }
2623 if (source == cricket::CS_REMOTE) {
2624 const MediaContentDescription* data_desc = content.media_description();
2625 if (data_desc && cricket::IsRtpProtocol(data_desc->protocol())) {
2626 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
2627 }
2628 }
2629 }
2630 return RTCError::OK();
2631}
2632
Steve Antondcc3c022017-12-22 16:02:54 -08002633RTCErrorOr<rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
2634PeerConnection::AssociateTransceiver(cricket::ContentSource source,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002635 SdpType type,
Steve Antondcc3c022017-12-22 16:02:54 -08002636 size_t mline_index,
2637 const ContentInfo& content,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002638 const ContentInfo* old_local_content,
2639 const ContentInfo* old_remote_content) {
Steve Antondcc3c022017-12-22 16:02:54 -08002640 RTC_DCHECK(IsUnifiedPlan());
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002641 // If this is an offer then the m= section might be recycled. If the m=
2642 // section is being recycled (defined as: rejected in the current local or
2643 // remote description and not rejected in new description), dissociate the
2644 // currently associated RtpTransceiver by setting its mid property to null,
2645 // and discard the mapping between the transceiver and its m= section index.
2646 if (IsMediaSectionBeingRecycled(type, content, old_local_content,
2647 old_remote_content)) {
2648 // We want to dissociate the transceiver that has the rejected mid.
2649 const std::string& old_mid =
2650 (old_local_content && old_local_content->rejected)
2651 ? old_local_content->name
2652 : old_remote_content->name;
2653 auto old_transceiver = GetAssociatedTransceiver(old_mid);
Steve Antondcc3c022017-12-22 16:02:54 -08002654 if (old_transceiver) {
2655 old_transceiver->internal()->set_mid(rtc::nullopt);
2656 old_transceiver->internal()->set_mline_index(rtc::nullopt);
2657 }
2658 }
2659 const MediaContentDescription* media_desc = content.media_description();
2660 auto transceiver = GetAssociatedTransceiver(content.name);
2661 if (source == cricket::CS_LOCAL) {
2662 // Find the RtpTransceiver that corresponds to this m= section, using the
2663 // mapping between transceivers and m= section indices established when
2664 // creating the offer.
2665 if (!transceiver) {
2666 transceiver = GetTransceiverByMLineIndex(mline_index);
2667 }
2668 if (!transceiver) {
2669 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2670 "Unknown transceiver");
2671 }
2672 } else {
2673 RTC_DCHECK_EQ(source, cricket::CS_REMOTE);
2674 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers
2675 // of the same type...
2676 if (!transceiver &&
2677 RtpTransceiverDirectionHasRecv(media_desc->direction())) {
2678 transceiver = FindAvailableTransceiverToReceive(media_desc->type());
2679 }
2680 // If no RtpTransceiver was found in the previous step, create one with a
2681 // recvonly direction.
2682 if (!transceiver) {
Steve Anton02ee47c2018-01-10 16:26:06 -08002683 auto sender =
2684 CreateSender(media_desc->type(), nullptr, {rtc::CreateRandomUuid()});
Steve Anton5f94aa22018-02-01 10:58:30 -08002685 std::string receiver_id;
2686 if (!media_desc->streams().empty()) {
2687 receiver_id = media_desc->streams()[0].id;
2688 } else {
2689 receiver_id = rtc::CreateRandomUuid();
2690 }
2691 auto receiver = CreateReceiver(media_desc->type(), receiver_id);
Steve Anton02ee47c2018-01-10 16:26:06 -08002692 transceiver = CreateAndAddTransceiver(sender, receiver);
Steve Antondcc3c022017-12-22 16:02:54 -08002693 transceiver->internal()->set_direction(
2694 RtpTransceiverDirection::kRecvOnly);
2695 }
2696 }
2697 RTC_DCHECK(transceiver);
Steve Anton69470252018-02-09 11:43:08 -08002698 if (transceiver->media_type() != media_desc->type()) {
Steve Antondcc3c022017-12-22 16:02:54 -08002699 LOG_AND_RETURN_ERROR(
2700 RTCErrorType::INVALID_PARAMETER,
2701 "Transceiver type does not match media description type.");
2702 }
2703 // Associate the found or created RtpTransceiver with the m= section by
2704 // setting the value of the RtpTransceiver's mid property to the MID of the m=
2705 // section, and establish a mapping between the transceiver and the index of
2706 // the m= section.
2707 transceiver->internal()->set_mid(content.name);
2708 transceiver->internal()->set_mline_index(mline_index);
2709 return std::move(transceiver);
2710}
2711
2712rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2713PeerConnection::GetAssociatedTransceiver(const std::string& mid) const {
2714 RTC_DCHECK(IsUnifiedPlan());
2715 for (auto transceiver : transceivers_) {
2716 if (transceiver->mid() == mid) {
2717 return transceiver;
2718 }
2719 }
2720 return nullptr;
2721}
2722
2723rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2724PeerConnection::GetTransceiverByMLineIndex(size_t mline_index) const {
2725 RTC_DCHECK(IsUnifiedPlan());
2726 for (auto transceiver : transceivers_) {
2727 if (transceiver->internal()->mline_index() == mline_index) {
2728 return transceiver;
2729 }
2730 }
2731 return nullptr;
2732}
2733
2734rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2735PeerConnection::FindAvailableTransceiverToReceive(
2736 cricket::MediaType media_type) const {
2737 RTC_DCHECK(IsUnifiedPlan());
2738 // From JSEP section 5.10 (Applying a Remote Description):
2739 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers of
2740 // the same type that were added to the PeerConnection by addTrack and are not
2741 // associated with any m= section and are not stopped, find the first such
2742 // RtpTransceiver.
2743 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08002744 if (transceiver->media_type() == media_type &&
Steve Antondcc3c022017-12-22 16:02:54 -08002745 transceiver->internal()->created_by_addtrack() && !transceiver->mid() &&
2746 !transceiver->stopped()) {
2747 return transceiver;
2748 }
2749 }
2750 return nullptr;
2751}
2752
Steve Antoned10bd92017-12-05 10:52:59 -08002753const cricket::ContentInfo* PeerConnection::FindMediaSectionForTransceiver(
2754 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2755 transceiver,
2756 const SessionDescriptionInterface* sdesc) const {
2757 RTC_DCHECK(transceiver);
2758 RTC_DCHECK(sdesc);
2759 if (IsUnifiedPlan()) {
2760 if (!transceiver->internal()->mid()) {
2761 // This transceiver is not associated with a media section yet.
2762 return nullptr;
2763 }
2764 return sdesc->description()->GetContentByName(
2765 *transceiver->internal()->mid());
2766 } else {
2767 // Plan B only allows at most one audio and one video section, so use the
2768 // first media section of that type.
2769 return cricket::GetFirstMediaContent(sdesc->description()->contents(),
Steve Anton69470252018-02-09 11:43:08 -08002770 transceiver->media_type());
Steve Antoned10bd92017-12-05 10:52:59 -08002771 }
2772}
2773
deadbeef46c73892016-11-16 19:42:04 -08002774PeerConnectionInterface::RTCConfiguration PeerConnection::GetConfiguration() {
2775 return configuration_;
2776}
2777
deadbeef293e9262017-01-11 12:28:30 -08002778bool PeerConnection::SetConfiguration(const RTCConfiguration& configuration,
2779 RTCError* error) {
Peter Boström1a9d6152015-12-08 22:15:17 +01002780 TRACE_EVENT0("webrtc", "PeerConnection::SetConfiguration");
deadbeef6de92f92016-12-12 18:49:32 -08002781
Steve Anton75737c02017-11-06 10:37:17 -08002782 if (local_description() && configuration.ice_candidate_pool_size !=
2783 configuration_.ice_candidate_pool_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002784 RTC_LOG(LS_ERROR) << "Can't change candidate pool size after calling "
2785 "SetLocalDescription.";
deadbeef293e9262017-01-11 12:28:30 -08002786 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00002787 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002788
deadbeef293e9262017-01-11 12:28:30 -08002789 // The simplest (and most future-compatible) way to tell if the config was
2790 // modified in an invalid way is to copy each property we do support
2791 // modifying, then use operator==. There are far more properties we don't
2792 // support modifying than those we do, and more could be added.
2793 RTCConfiguration modified_config = configuration_;
2794 modified_config.servers = configuration.servers;
2795 modified_config.type = configuration.type;
2796 modified_config.ice_candidate_pool_size =
2797 configuration.ice_candidate_pool_size;
2798 modified_config.prune_turn_ports = configuration.prune_turn_ports;
skvladd1f5fda2017-02-03 16:54:05 -08002799 modified_config.ice_check_min_interval = configuration.ice_check_min_interval;
Qingsi Wange6826d22018-03-08 14:55:14 -08002800 modified_config.ice_check_interval_strong_connectivity =
2801 configuration.ice_check_interval_strong_connectivity;
2802 modified_config.ice_check_interval_weak_connectivity =
2803 configuration.ice_check_interval_weak_connectivity;
Qingsi Wang22e623a2018-03-13 10:53:57 -07002804 modified_config.ice_unwritable_timeout = configuration.ice_unwritable_timeout;
2805 modified_config.ice_unwritable_min_checks =
2806 configuration.ice_unwritable_min_checks;
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08002807 modified_config.stun_candidate_keepalive_interval =
2808 configuration.stun_candidate_keepalive_interval;
Jonas Orelandbdcee282017-10-10 14:01:40 +02002809 modified_config.turn_customizer = configuration.turn_customizer;
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08002810 modified_config.network_preference = configuration.network_preference;
deadbeef293e9262017-01-11 12:28:30 -08002811 if (configuration != modified_config) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002812 RTC_LOG(LS_ERROR) << "Modifying the configuration in an unsupported way.";
deadbeef293e9262017-01-11 12:28:30 -08002813 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
2814 }
2815
Steve Anton038834f2017-07-14 15:59:59 -07002816 // Validate the modified configuration.
2817 RTCError validate_error = ValidateConfiguration(modified_config);
2818 if (!validate_error.ok()) {
2819 return SafeSetError(std::move(validate_error), error);
2820 }
2821
deadbeef293e9262017-01-11 12:28:30 -08002822 // Note that this isn't possible through chromium, since it's an unsigned
2823 // short in WebIDL.
2824 if (configuration.ice_candidate_pool_size < 0 ||
2825 configuration.ice_candidate_pool_size > UINT16_MAX) {
2826 return SafeSetError(RTCErrorType::INVALID_RANGE, error);
2827 }
2828
2829 // Parse ICE servers before hopping to network thread.
2830 cricket::ServerAddresses stun_servers;
2831 std::vector<cricket::RelayServerConfig> turn_servers;
2832 RTCErrorType parse_error =
2833 ParseIceServers(configuration.servers, &stun_servers, &turn_servers);
2834 if (parse_error != RTCErrorType::NONE) {
2835 return SafeSetError(parse_error, error);
2836 }
2837
2838 // In theory this shouldn't fail.
2839 if (!network_thread()->Invoke<bool>(
2840 RTC_FROM_HERE,
2841 rtc::Bind(&PeerConnection::ReconfigurePortAllocator_n, this,
2842 stun_servers, turn_servers, modified_config.type,
2843 modified_config.ice_candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02002844 modified_config.prune_turn_ports,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08002845 modified_config.turn_customizer,
2846 modified_config.stun_candidate_keepalive_interval))) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002847 RTC_LOG(LS_ERROR) << "Failed to apply configuration to PortAllocator.";
deadbeef293e9262017-01-11 12:28:30 -08002848 return SafeSetError(RTCErrorType::INTERNAL_ERROR, error);
2849 }
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07002850
deadbeefd1a38b52016-12-10 13:15:33 -08002851 // As described in JSEP, calling setConfiguration with new ICE servers or
2852 // candidate policy must set a "needs-ice-restart" bit so that the next offer
2853 // triggers an ICE restart which will pick up the changes.
deadbeef293e9262017-01-11 12:28:30 -08002854 if (modified_config.servers != configuration_.servers ||
2855 modified_config.type != configuration_.type ||
2856 modified_config.prune_turn_ports != configuration_.prune_turn_ports) {
Steve Antond25da372017-11-06 14:50:29 -08002857 transport_controller_->SetNeedsIceRestartFlag();
deadbeefd1a38b52016-12-10 13:15:33 -08002858 }
skvladd1f5fda2017-02-03 16:54:05 -08002859
Qingsi Wang9c98f0c2018-02-15 15:10:59 -08002860 transport_controller_->SetIceConfig(ParseIceConfig(modified_config));
skvladd1f5fda2017-02-03 16:54:05 -08002861
deadbeef293e9262017-01-11 12:28:30 -08002862 configuration_ = modified_config;
2863 return SafeSetError(RTCErrorType::NONE, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00002864}
2865
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002866bool PeerConnection::AddIceCandidate(
2867 const IceCandidateInterface* ice_candidate) {
Peter Boström1a9d6152015-12-08 22:15:17 +01002868 TRACE_EVENT0("webrtc", "PeerConnection::AddIceCandidate");
zhihuang29ff8442016-07-27 11:07:25 -07002869 if (IsClosed()) {
2870 return false;
2871 }
Steve Antond25da372017-11-06 14:50:29 -08002872
2873 if (!remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002874 RTC_LOG(LS_ERROR) << "ProcessIceMessage: ICE candidates can't be added "
Jonas Olsson45cc8902018-02-13 10:37:07 +01002875 "without any remote session description.";
Steve Antond25da372017-11-06 14:50:29 -08002876 return false;
2877 }
2878
2879 if (!ice_candidate) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002880 RTC_LOG(LS_ERROR) << "ProcessIceMessage: Candidate is NULL.";
Steve Antond25da372017-11-06 14:50:29 -08002881 return false;
2882 }
2883
2884 bool valid = false;
2885 bool ready = ReadyToUseRemoteCandidate(ice_candidate, nullptr, &valid);
2886 if (!valid) {
2887 return false;
2888 }
2889
2890 // Add this candidate to the remote session description.
2891 if (!mutable_remote_description()->AddCandidate(ice_candidate)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002892 RTC_LOG(LS_ERROR) << "ProcessIceMessage: Candidate cannot be used.";
Steve Antond25da372017-11-06 14:50:29 -08002893 return false;
2894 }
2895
2896 if (ready) {
2897 return UseCandidate(ice_candidate);
2898 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002899 RTC_LOG(LS_INFO) << "ProcessIceMessage: Not ready to use candidate.";
Steve Antond25da372017-11-06 14:50:29 -08002900 return true;
2901 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002902}
2903
Honghai Zhang7fb69db2016-03-14 11:59:18 -07002904bool PeerConnection::RemoveIceCandidates(
2905 const std::vector<cricket::Candidate>& candidates) {
2906 TRACE_EVENT0("webrtc", "PeerConnection::RemoveIceCandidates");
Steve Antond25da372017-11-06 14:50:29 -08002907 if (!remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002908 RTC_LOG(LS_ERROR) << "RemoveRemoteIceCandidates: ICE candidates can't be "
Jonas Olsson45cc8902018-02-13 10:37:07 +01002909 "removed without any remote session description.";
Steve Antond25da372017-11-06 14:50:29 -08002910 return false;
2911 }
2912
2913 if (candidates.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002914 RTC_LOG(LS_ERROR) << "RemoveRemoteIceCandidates: candidates are empty.";
Steve Antond25da372017-11-06 14:50:29 -08002915 return false;
2916 }
2917
2918 size_t number_removed =
2919 mutable_remote_description()->RemoveCandidates(candidates);
2920 if (number_removed != candidates.size()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002921 RTC_LOG(LS_ERROR)
2922 << "RemoveRemoteIceCandidates: Failed to remove candidates. "
Jonas Olsson45cc8902018-02-13 10:37:07 +01002923 "Requested "
2924 << candidates.size() << " but only " << number_removed
Mirko Bonadei675513b2017-11-09 11:09:25 +01002925 << " are removed.";
Steve Antond25da372017-11-06 14:50:29 -08002926 }
2927
2928 // Remove the candidates from the transport controller.
Zhi Huange830e682018-03-30 10:48:35 -07002929 RTCError error = transport_controller_->RemoveRemoteCandidates(candidates);
2930 if (!error.ok()) {
2931 RTC_LOG(LS_ERROR) << "Error when removing remote candidates: "
2932 << error.message();
Steve Antond25da372017-11-06 14:50:29 -08002933 }
2934 return true;
Honghai Zhang7fb69db2016-03-14 11:59:18 -07002935}
2936
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00002937void PeerConnection::RegisterUMAObserver(UMAObserver* observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +01002938 TRACE_EVENT0("webrtc", "PeerConnection::RegisterUmaObserver");
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00002939 uma_observer_ = observer;
guoweis@webrtc.org7169afd2014-12-04 17:59:29 +00002940
Steve Anton75737c02017-11-06 10:37:17 -08002941 if (transport_controller()) {
2942 transport_controller()->SetMetricsObserver(uma_observer_);
guoweis@webrtc.org7169afd2014-12-04 17:59:29 +00002943 }
2944
Steve Antondb67ba12018-03-19 17:41:42 -07002945 for (auto transceiver : transceivers_) {
2946 auto* channel = transceiver->internal()->channel();
2947 if (channel) {
2948 channel->SetMetricsObserver(uma_observer_);
2949 }
2950 }
2951
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00002952 // Send information about IPv4/IPv6 status.
deadbeef293e9262017-01-11 12:28:30 -08002953 if (uma_observer_) {
Honghai Zhangd93f50c2016-10-05 11:47:22 -07002954 port_allocator_->SetMetricsObserver(uma_observer_);
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00002955 if (port_allocator_->flags() & cricket::PORTALLOCATOR_ENABLE_IPV6) {
Guo-wei Shiehdfbe6792015-09-03 17:12:07 -07002956 uma_observer_->IncrementEnumCounter(
2957 kEnumCounterAddressFamily, kPeerConnection_IPv6,
2958 kPeerConnectionAddressFamilyCounter_Max);
mallinath@webrtc.orgb445f262014-05-23 22:19:37 +00002959 } else {
Guo-wei Shiehdfbe6792015-09-03 17:12:07 -07002960 uma_observer_->IncrementEnumCounter(
2961 kEnumCounterAddressFamily, kPeerConnection_IPv4,
2962 kPeerConnectionAddressFamilyCounter_Max);
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00002963 }
Harald Alvestrand5dbb5862018-02-13 23:48:00 +01002964 // Send information about the requested SDP semantics.
2965 switch (configuration_.sdp_semantics) {
2966 case SdpSemantics::kDefault:
2967 uma_observer_->IncrementEnumCounter(kEnumCounterSdpSemanticRequested,
2968 kSdpSemanticRequestDefault,
2969 kSdpSemanticRequestMax);
2970
2971 break;
2972 case SdpSemantics::kPlanB:
2973 uma_observer_->IncrementEnumCounter(kEnumCounterSdpSemanticRequested,
2974 kSdpSemanticRequestPlanB,
2975 kSdpSemanticRequestMax);
2976 break;
2977 case SdpSemantics::kUnifiedPlan:
2978 uma_observer_->IncrementEnumCounter(kEnumCounterSdpSemanticRequested,
2979 kSdpSemanticRequestUnifiedPlan,
2980 kSdpSemanticRequestMax);
2981 break;
2982 default:
2983 RTC_NOTREACHED();
2984 }
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00002985 }
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00002986}
2987
zstein4b979802017-06-02 14:37:37 -07002988RTCError PeerConnection::SetBitrate(const BitrateParameters& bitrate) {
Steve Anton978b8762017-09-29 12:15:02 -07002989 if (!worker_thread()->IsCurrent()) {
2990 return worker_thread()->Invoke<RTCError>(
zstein4b979802017-06-02 14:37:37 -07002991 RTC_FROM_HERE, rtc::Bind(&PeerConnection::SetBitrate, this, bitrate));
2992 }
2993
2994 const bool has_min = static_cast<bool>(bitrate.min_bitrate_bps);
2995 const bool has_current = static_cast<bool>(bitrate.current_bitrate_bps);
2996 const bool has_max = static_cast<bool>(bitrate.max_bitrate_bps);
2997 if (has_min && *bitrate.min_bitrate_bps < 0) {
2998 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2999 "min_bitrate_bps <= 0");
3000 }
3001 if (has_current) {
3002 if (has_min && *bitrate.current_bitrate_bps < *bitrate.min_bitrate_bps) {
3003 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3004 "current_bitrate_bps < min_bitrate_bps");
3005 } else if (*bitrate.current_bitrate_bps < 0) {
3006 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3007 "curent_bitrate_bps < 0");
3008 }
3009 }
3010 if (has_max) {
3011 if (has_current &&
3012 *bitrate.max_bitrate_bps < *bitrate.current_bitrate_bps) {
3013 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3014 "max_bitrate_bps < current_bitrate_bps");
3015 } else if (has_min && *bitrate.max_bitrate_bps < *bitrate.min_bitrate_bps) {
3016 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3017 "max_bitrate_bps < min_bitrate_bps");
3018 } else if (*bitrate.max_bitrate_bps < 0) {
3019 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3020 "max_bitrate_bps < 0");
3021 }
3022 }
3023
Sebastian Janssonfc8d26b2018-02-21 09:52:06 +01003024 BitrateConstraintsMask mask;
zstein4b979802017-06-02 14:37:37 -07003025 mask.min_bitrate_bps = bitrate.min_bitrate_bps;
3026 mask.start_bitrate_bps = bitrate.current_bitrate_bps;
3027 mask.max_bitrate_bps = bitrate.max_bitrate_bps;
3028
3029 RTC_DCHECK(call_.get());
Sebastian Jansson8f83b422018-02-21 13:07:13 +01003030 call_->GetTransportControllerSend()->SetClientBitratePreferences(mask);
zstein4b979802017-06-02 14:37:37 -07003031
3032 return RTCError::OK();
3033}
3034
Alex Narest78609d52017-10-20 10:37:47 +02003035void PeerConnection::SetBitrateAllocationStrategy(
3036 std::unique_ptr<rtc::BitrateAllocationStrategy>
3037 bitrate_allocation_strategy) {
3038 rtc::Thread* worker_thread = factory_->worker_thread();
3039 if (!worker_thread->IsCurrent()) {
3040 rtc::BitrateAllocationStrategy* strategy_raw =
3041 bitrate_allocation_strategy.release();
3042 auto functor = [this, strategy_raw]() {
3043 call_->SetBitrateAllocationStrategy(
3044 rtc::WrapUnique<rtc::BitrateAllocationStrategy>(strategy_raw));
3045 };
3046 worker_thread->Invoke<void>(RTC_FROM_HERE, functor);
3047 return;
3048 }
3049 RTC_DCHECK(call_.get());
3050 call_->SetBitrateAllocationStrategy(std::move(bitrate_allocation_strategy));
3051}
3052
henrika5f6bf242017-11-01 11:06:56 +01003053void PeerConnection::SetAudioPlayout(bool playout) {
3054 if (!worker_thread()->IsCurrent()) {
3055 worker_thread()->Invoke<void>(
3056 RTC_FROM_HERE,
3057 rtc::Bind(&PeerConnection::SetAudioPlayout, this, playout));
3058 return;
3059 }
3060 auto audio_state =
3061 factory_->channel_manager()->media_engine()->GetAudioState();
3062 audio_state->SetPlayout(playout);
3063}
3064
3065void PeerConnection::SetAudioRecording(bool recording) {
3066 if (!worker_thread()->IsCurrent()) {
3067 worker_thread()->Invoke<void>(
3068 RTC_FROM_HERE,
3069 rtc::Bind(&PeerConnection::SetAudioRecording, this, recording));
3070 return;
3071 }
3072 auto audio_state =
3073 factory_->channel_manager()->media_engine()->GetAudioState();
3074 audio_state->SetRecording(recording);
3075}
3076
Steve Anton8c0f7a72017-10-03 10:03:10 -07003077std::unique_ptr<rtc::SSLCertificate>
3078PeerConnection::GetRemoteAudioSSLCertificate() {
Taylor Brandstetterc3928662018-02-23 13:04:51 -08003079 std::unique_ptr<rtc::SSLCertChain> chain = GetRemoteAudioSSLCertChain();
3080 if (!chain || !chain->GetSize()) {
Steve Anton8c0f7a72017-10-03 10:03:10 -07003081 return nullptr;
3082 }
Taylor Brandstetterc3928662018-02-23 13:04:51 -08003083 return chain->Get(0).GetUniqueReference();
Steve Anton8c0f7a72017-10-03 10:03:10 -07003084}
3085
Zhi Huang70b820f2018-01-27 14:16:15 -08003086std::unique_ptr<rtc::SSLCertChain>
3087PeerConnection::GetRemoteAudioSSLCertChain() {
Steve Antonafb0bb72018-02-20 11:35:37 -08003088 auto audio_transceiver = GetFirstAudioTransceiver();
3089 if (!audio_transceiver || !audio_transceiver->internal()->channel()) {
Zhi Huang70b820f2018-01-27 14:16:15 -08003090 return nullptr;
3091 }
Zhi Huang70b820f2018-01-27 14:16:15 -08003092 return transport_controller_->GetRemoteSSLCertChain(
Steve Antonafb0bb72018-02-20 11:35:37 -08003093 audio_transceiver->internal()->channel()->transport_name());
3094}
3095
3096rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3097PeerConnection::GetFirstAudioTransceiver() const {
3098 for (auto transceiver : transceivers_) {
3099 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
3100 return transceiver;
3101 }
3102 }
3103 return nullptr;
Zhi Huang70b820f2018-01-27 14:16:15 -08003104}
3105
ivoc14d5dbe2016-07-04 07:06:55 -07003106bool PeerConnection::StartRtcEventLog(rtc::PlatformFile file,
3107 int64_t max_size_bytes) {
Elad Alon99c3fe52017-10-13 16:29:40 +02003108 // TODO(eladalon): It would be better to not allow negative values into PC.
3109 const size_t max_size = (max_size_bytes < 0)
3110 ? RtcEventLog::kUnlimitedOutput
3111 : rtc::saturated_cast<size_t>(max_size_bytes);
3112 return StartRtcEventLog(
Bjorn Tereliusde939432017-11-20 17:38:14 +01003113 rtc::MakeUnique<RtcEventLogOutputFile>(file, max_size),
3114 webrtc::RtcEventLog::kImmediateOutput);
Elad Alon99c3fe52017-10-13 16:29:40 +02003115}
3116
Bjorn Tereliusde939432017-11-20 17:38:14 +01003117bool PeerConnection::StartRtcEventLog(std::unique_ptr<RtcEventLogOutput> output,
3118 int64_t output_period_ms) {
Karl Wibergd6b48192017-10-16 23:01:06 +02003119 // TODO(eladalon): In C++14, this can be done with a lambda.
3120 struct Functor {
Bjorn Tereliusde939432017-11-20 17:38:14 +01003121 bool operator()() {
3122 return pc->StartRtcEventLog_w(std::move(output), output_period_ms);
3123 }
Karl Wibergd6b48192017-10-16 23:01:06 +02003124 PeerConnection* const pc;
3125 std::unique_ptr<RtcEventLogOutput> output;
Bjorn Tereliusde939432017-11-20 17:38:14 +01003126 const int64_t output_period_ms;
Elad Alon99c3fe52017-10-13 16:29:40 +02003127 };
Bjorn Tereliusde939432017-11-20 17:38:14 +01003128 return worker_thread()->Invoke<bool>(
3129 RTC_FROM_HERE, Functor{this, std::move(output), output_period_ms});
ivoc14d5dbe2016-07-04 07:06:55 -07003130}
3131
3132void PeerConnection::StopRtcEventLog() {
Steve Anton978b8762017-09-29 12:15:02 -07003133 worker_thread()->Invoke<void>(
ivoc14d5dbe2016-07-04 07:06:55 -07003134 RTC_FROM_HERE, rtc::Bind(&PeerConnection::StopRtcEventLog_w, this));
3135}
3136
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003137const SessionDescriptionInterface* PeerConnection::local_description() const {
Steve Anton75737c02017-11-06 10:37:17 -08003138 return pending_local_description_ ? pending_local_description_.get()
3139 : current_local_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003140}
3141
3142const SessionDescriptionInterface* PeerConnection::remote_description() const {
Steve Anton75737c02017-11-06 10:37:17 -08003143 return pending_remote_description_ ? pending_remote_description_.get()
3144 : current_remote_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003145}
3146
deadbeeffe4a8a42016-12-20 17:56:17 -08003147const SessionDescriptionInterface* PeerConnection::current_local_description()
3148 const {
Steve Anton75737c02017-11-06 10:37:17 -08003149 return current_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003150}
3151
3152const SessionDescriptionInterface* PeerConnection::current_remote_description()
3153 const {
Steve Anton75737c02017-11-06 10:37:17 -08003154 return current_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003155}
3156
3157const SessionDescriptionInterface* PeerConnection::pending_local_description()
3158 const {
Steve Anton75737c02017-11-06 10:37:17 -08003159 return pending_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003160}
3161
3162const SessionDescriptionInterface* PeerConnection::pending_remote_description()
3163 const {
Steve Anton75737c02017-11-06 10:37:17 -08003164 return pending_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003165}
3166
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003167void PeerConnection::Close() {
Peter Boström1a9d6152015-12-08 22:15:17 +01003168 TRACE_EVENT0("webrtc", "PeerConnection::Close");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003169 // Update stats here so that we have the most recent stats for tracks and
3170 // streams before the channels are closed.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00003171 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003172
Steve Anton75737c02017-11-06 10:37:17 -08003173 ChangeSignalingState(PeerConnectionInterface::kClosed);
Steve Anton3fe1b152017-12-12 10:20:08 -08003174
Steve Anton8af21862017-12-15 11:20:13 -08003175 for (auto transceiver : transceivers_) {
3176 transceiver->Stop();
3177 }
3178 DestroyAllChannels();
Steve Anton75737c02017-11-06 10:37:17 -08003179
Qingsi Wang93a84392018-01-30 17:13:09 -08003180 // The event log is used in the transport controller, which must be outlived
3181 // by the former. CreateOffer by the peer connection is implemented
3182 // asynchronously and if the peer connection is closed without resetting the
3183 // WebRTC session description factory, the session description factory would
3184 // call the transport controller.
3185 webrtc_session_desc_factory_.reset();
3186 transport_controller_.reset();
3187
deadbeef42a42632017-03-10 15:18:00 -08003188 network_thread()->Invoke<void>(
3189 RTC_FROM_HERE,
3190 rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
3191 port_allocator_.get()));
nisseeaabdf62017-05-05 02:23:02 -07003192
Steve Anton978b8762017-09-29 12:15:02 -07003193 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
eladalon248fd4f2017-09-06 05:18:15 -07003194 call_.reset();
3195 // The event log must outlive call (and any other object that uses it).
3196 event_log_.reset();
3197 });
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003198}
3199
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003200void PeerConnection::OnMessage(rtc::Message* msg) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003201 switch (msg->message_id) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003202 case MSG_SET_SESSIONDESCRIPTION_SUCCESS: {
3203 SetSessionDescriptionMsg* param =
3204 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
3205 param->observer->OnSuccess();
3206 delete param;
3207 break;
3208 }
3209 case MSG_SET_SESSIONDESCRIPTION_FAILED: {
3210 SetSessionDescriptionMsg* param =
3211 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01003212 param->observer->OnFailure(std::move(param->error));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003213 delete param;
3214 break;
3215 }
deadbeefab9b2d12015-10-14 11:33:11 -07003216 case MSG_CREATE_SESSIONDESCRIPTION_FAILED: {
3217 CreateSessionDescriptionMsg* param =
3218 static_cast<CreateSessionDescriptionMsg*>(msg->pdata);
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01003219 param->observer->OnFailure(std::move(param->error));
deadbeefab9b2d12015-10-14 11:33:11 -07003220 delete param;
3221 break;
3222 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003223 case MSG_GETSTATS: {
3224 GetStatsMsg* param = static_cast<GetStatsMsg*>(msg->pdata);
nissee8abe3e2017-01-18 05:00:34 -08003225 StatsReports reports;
3226 stats_->GetStats(param->track, &reports);
3227 param->observer->OnComplete(reports);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003228 delete param;
3229 break;
3230 }
deadbeefbd292462015-12-14 18:15:29 -08003231 case MSG_FREE_DATACHANNELS: {
3232 sctp_data_channels_to_free_.clear();
3233 break;
3234 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003235 default:
nisseeb4ca4e2017-01-12 02:24:27 -08003236 RTC_NOTREACHED() << "Not implemented";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003237 break;
3238 }
3239}
3240
Steve Antonafb0bb72018-02-20 11:35:37 -08003241cricket::VoiceMediaChannel* PeerConnection::voice_media_channel() const {
3242 RTC_DCHECK(!IsUnifiedPlan());
3243 auto* voice_channel = static_cast<cricket::VoiceChannel*>(
3244 GetAudioTransceiver()->internal()->channel());
3245 if (voice_channel) {
3246 return voice_channel->media_channel();
3247 } else {
3248 return nullptr;
3249 }
3250}
3251
3252cricket::VideoMediaChannel* PeerConnection::video_media_channel() const {
3253 RTC_DCHECK(!IsUnifiedPlan());
3254 auto* video_channel = static_cast<cricket::VideoChannel*>(
3255 GetVideoTransceiver()->internal()->channel());
3256 if (video_channel) {
3257 return video_channel->media_channel();
3258 } else {
3259 return nullptr;
3260 }
3261}
3262
Steve Anton4171afb2017-11-20 10:20:22 -08003263void PeerConnection::CreateAudioReceiver(
3264 MediaStreamInterface* stream,
3265 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01003266 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
3267 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Steve Antond3679212018-01-17 17:41:02 -08003268 auto* audio_receiver = new AudioRtpReceiver(
3269 worker_thread(), remote_sender_info.sender_id, streams);
Steve Anton57858b32018-02-15 15:19:50 -08003270 audio_receiver->SetVoiceMediaChannel(voice_media_channel());
Steve Antond3679212018-01-17 17:41:02 -08003271 audio_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
3272 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
3273 signaling_thread(), audio_receiver);
Steve Anton4171afb2017-11-20 10:20:22 -08003274 GetAudioTransceiver()->internal()->AddReceiver(receiver);
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01003275 observer_->OnAddTrack(receiver, std::move(streams));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003276}
3277
Steve Anton4171afb2017-11-20 10:20:22 -08003278void PeerConnection::CreateVideoReceiver(
3279 MediaStreamInterface* stream,
3280 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01003281 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
3282 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Steve Antond3679212018-01-17 17:41:02 -08003283 auto* video_receiver = new VideoRtpReceiver(
3284 worker_thread(), remote_sender_info.sender_id, streams);
Steve Anton57858b32018-02-15 15:19:50 -08003285 video_receiver->SetVideoMediaChannel(video_media_channel());
Steve Antond3679212018-01-17 17:41:02 -08003286 video_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
3287 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
3288 signaling_thread(), video_receiver);
Steve Anton4171afb2017-11-20 10:20:22 -08003289 GetVideoTransceiver()->internal()->AddReceiver(receiver);
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01003290 observer_->OnAddTrack(receiver, std::move(streams));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003291}
3292
deadbeef70ab1a12015-09-28 16:53:55 -07003293// TODO(deadbeef): Keep RtpReceivers around even if track goes away in remote
3294// description.
Henrik Boström933d8b02017-10-10 10:05:16 -07003295rtc::scoped_refptr<RtpReceiverInterface> PeerConnection::RemoveAndStopReceiver(
Steve Anton4171afb2017-11-20 10:20:22 -08003296 const RtpSenderInfo& remote_sender_info) {
3297 auto receiver = FindReceiverById(remote_sender_info.sender_id);
3298 if (!receiver) {
3299 RTC_LOG(LS_WARNING) << "RtpReceiver for track with id "
3300 << remote_sender_info.sender_id << " doesn't exist.";
Henrik Boström933d8b02017-10-10 10:05:16 -07003301 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07003302 }
Steve Anton4171afb2017-11-20 10:20:22 -08003303 if (receiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
3304 GetAudioTransceiver()->internal()->RemoveReceiver(receiver);
3305 } else {
3306 GetVideoTransceiver()->internal()->RemoveReceiver(receiver);
3307 }
Henrik Boström933d8b02017-10-10 10:05:16 -07003308 return receiver;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003309}
3310
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003311void PeerConnection::AddAudioTrack(AudioTrackInterface* track,
3312 MediaStreamInterface* stream) {
3313 RTC_DCHECK(!IsClosed());
3314 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003315 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003316 // We already have a sender for this track, so just change the stream_id
3317 // so that it's correct in the next call to CreateOffer.
Tomas Gunnarsson191bf5c2018-03-30 10:44:43 +00003318 sender->internal()->set_stream_id(stream->id());
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003319 return;
3320 }
3321
3322 // Normal case; we've never seen this track before.
Steve Anton02ee47c2018-01-10 16:26:06 -08003323 auto new_sender =
Seth Hampson13b8bad2018-03-13 16:05:28 -07003324 CreateSender(cricket::MEDIA_TYPE_AUDIO, track, {stream->id()});
Steve Anton57858b32018-02-15 15:19:50 -08003325 new_sender->internal()->SetVoiceMediaChannel(voice_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08003326 GetAudioTransceiver()->internal()->AddSender(new_sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003327 // If the sender has already been configured in SDP, we call SetSsrc,
3328 // which will connect the sender to the underlying transport. This can
3329 // occur if a local session description that contains the ID of the sender
3330 // is set before AddStream is called. It can also occur if the local
3331 // session description is not changed and RemoveStream is called, and
3332 // later AddStream is called again with the same stream.
Steve Anton4171afb2017-11-20 10:20:22 -08003333 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00003334 FindSenderInfo(local_audio_sender_infos_, stream->id(), track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08003335 if (sender_info) {
3336 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003337 }
3338}
3339
3340// TODO(deadbeef): Don't destroy RtpSenders here; they should be kept around
3341// indefinitely, when we have unified plan SDP.
3342void PeerConnection::RemoveAudioTrack(AudioTrackInterface* track,
3343 MediaStreamInterface* stream) {
3344 RTC_DCHECK(!IsClosed());
3345 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003346 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003347 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
3348 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003349 return;
3350 }
Steve Anton4171afb2017-11-20 10:20:22 -08003351 GetAudioTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003352}
3353
3354void PeerConnection::AddVideoTrack(VideoTrackInterface* track,
3355 MediaStreamInterface* stream) {
3356 RTC_DCHECK(!IsClosed());
3357 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003358 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003359 // We already have a sender for this track, so just change the stream_id
3360 // so that it's correct in the next call to CreateOffer.
Tomas Gunnarsson191bf5c2018-03-30 10:44:43 +00003361 sender->internal()->set_stream_id(stream->id());
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003362 return;
3363 }
3364
3365 // Normal case; we've never seen this track before.
Steve Anton02ee47c2018-01-10 16:26:06 -08003366 auto new_sender =
Seth Hampson13b8bad2018-03-13 16:05:28 -07003367 CreateSender(cricket::MEDIA_TYPE_VIDEO, track, {stream->id()});
Steve Anton57858b32018-02-15 15:19:50 -08003368 new_sender->internal()->SetVideoMediaChannel(video_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08003369 GetVideoTransceiver()->internal()->AddSender(new_sender);
3370 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00003371 FindSenderInfo(local_video_sender_infos_, stream->id(), track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08003372 if (sender_info) {
3373 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003374 }
3375}
3376
3377void PeerConnection::RemoveVideoTrack(VideoTrackInterface* track,
3378 MediaStreamInterface* stream) {
3379 RTC_DCHECK(!IsClosed());
3380 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003381 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003382 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
3383 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003384 return;
3385 }
Steve Anton4171afb2017-11-20 10:20:22 -08003386 GetVideoTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003387}
3388
Steve Antonba818672017-11-06 10:21:57 -08003389void PeerConnection::SetIceConnectionState(IceConnectionState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07003390 RTC_DCHECK(signaling_thread()->IsCurrent());
Steve Antonba818672017-11-06 10:21:57 -08003391 if (ice_connection_state_ == new_state) {
3392 return;
3393 }
3394
deadbeefcbecd352015-09-23 11:50:27 -07003395 // After transitioning to "closed", ignore any additional states from
Steve Antonba818672017-11-06 10:21:57 -08003396 // TransportController (such as "disconnected").
deadbeefab9b2d12015-10-14 11:33:11 -07003397 if (IsClosed()) {
deadbeefcbecd352015-09-23 11:50:27 -07003398 return;
3399 }
Steve Antonba818672017-11-06 10:21:57 -08003400
Mirko Bonadei675513b2017-11-09 11:09:25 +01003401 RTC_LOG(LS_INFO) << "Changing IceConnectionState " << ice_connection_state_
3402 << " => " << new_state;
Steve Antonba818672017-11-06 10:21:57 -08003403 RTC_DCHECK(ice_connection_state_ !=
3404 PeerConnectionInterface::kIceConnectionClosed);
3405
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003406 ice_connection_state_ = new_state;
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00003407 observer_->OnIceConnectionChange(ice_connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003408}
3409
3410void PeerConnection::OnIceGatheringChange(
3411 PeerConnectionInterface::IceGatheringState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07003412 RTC_DCHECK(signaling_thread()->IsCurrent());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003413 if (IsClosed()) {
3414 return;
3415 }
3416 ice_gathering_state_ = new_state;
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00003417 observer_->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003418}
3419
jbauch81bf7b02017-03-25 08:31:12 -07003420void PeerConnection::OnIceCandidate(
3421 std::unique_ptr<IceCandidateInterface> candidate) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07003422 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07003423 if (IsClosed()) {
3424 return;
3425 }
jbauch81bf7b02017-03-25 08:31:12 -07003426 observer_->OnIceCandidate(candidate.get());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003427}
3428
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003429void PeerConnection::OnIceCandidatesRemoved(
3430 const std::vector<cricket::Candidate>& candidates) {
3431 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07003432 if (IsClosed()) {
3433 return;
3434 }
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003435 observer_->OnIceCandidatesRemoved(candidates);
3436}
3437
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003438void PeerConnection::ChangeSignalingState(
3439 PeerConnectionInterface::SignalingState signaling_state) {
Steve Antonba818672017-11-06 10:21:57 -08003440 RTC_DCHECK(signaling_thread()->IsCurrent());
3441 if (signaling_state_ == signaling_state) {
3442 return;
3443 }
Mirko Bonadei675513b2017-11-09 11:09:25 +01003444 RTC_LOG(LS_INFO) << "Session: " << session_id() << " Old state: "
3445 << GetSignalingStateString(signaling_state_)
3446 << " New state: "
3447 << GetSignalingStateString(signaling_state);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003448 signaling_state_ = signaling_state;
3449 if (signaling_state == kClosed) {
3450 ice_connection_state_ = kIceConnectionClosed;
3451 observer_->OnIceConnectionChange(ice_connection_state_);
3452 if (ice_gathering_state_ != kIceGatheringComplete) {
3453 ice_gathering_state_ = kIceGatheringComplete;
3454 observer_->OnIceGatheringChange(ice_gathering_state_);
3455 }
3456 }
3457 observer_->OnSignalingChange(signaling_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003458}
3459
deadbeefeb459812015-12-15 19:24:43 -08003460void PeerConnection::OnAudioTrackAdded(AudioTrackInterface* track,
3461 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003462 if (IsClosed()) {
3463 return;
3464 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003465 AddAudioTrack(track, stream);
3466 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003467}
3468
deadbeefeb459812015-12-15 19:24:43 -08003469void PeerConnection::OnAudioTrackRemoved(AudioTrackInterface* track,
3470 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003471 if (IsClosed()) {
3472 return;
3473 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003474 RemoveAudioTrack(track, stream);
3475 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003476}
3477
3478void PeerConnection::OnVideoTrackAdded(VideoTrackInterface* track,
3479 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003480 if (IsClosed()) {
3481 return;
3482 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003483 AddVideoTrack(track, stream);
3484 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003485}
3486
3487void PeerConnection::OnVideoTrackRemoved(VideoTrackInterface* track,
3488 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003489 if (IsClosed()) {
3490 return;
3491 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003492 RemoveVideoTrack(track, stream);
3493 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003494}
3495
Henrik Boström31638672017-11-23 17:48:32 +01003496void PeerConnection::PostSetSessionDescriptionSuccess(
3497 SetSessionDescriptionObserver* observer) {
3498 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
3499 signaling_thread()->Post(RTC_FROM_HERE, this,
3500 MSG_SET_SESSIONDESCRIPTION_SUCCESS, msg);
3501}
3502
deadbeefab9b2d12015-10-14 11:33:11 -07003503void PeerConnection::PostSetSessionDescriptionFailure(
3504 SetSessionDescriptionObserver* observer,
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01003505 RTCError&& error) {
3506 RTC_DCHECK(!error.ok());
deadbeefab9b2d12015-10-14 11:33:11 -07003507 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01003508 msg->error = std::move(error);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07003509 signaling_thread()->Post(RTC_FROM_HERE, this,
3510 MSG_SET_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07003511}
3512
3513void PeerConnection::PostCreateSessionDescriptionFailure(
3514 CreateSessionDescriptionObserver* observer,
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01003515 RTCError error) {
3516 RTC_DCHECK(!error.ok());
deadbeefab9b2d12015-10-14 11:33:11 -07003517 CreateSessionDescriptionMsg* msg = new CreateSessionDescriptionMsg(observer);
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01003518 msg->error = std::move(error);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07003519 signaling_thread()->Post(RTC_FROM_HERE, this,
3520 MSG_CREATE_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07003521}
3522
zhihuang1c378ed2017-08-17 14:10:50 -07003523void PeerConnection::GetOptionsForOffer(
Steve Antondcc3c022017-12-22 16:02:54 -08003524 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
deadbeefab9b2d12015-10-14 11:33:11 -07003525 cricket::MediaSessionOptions* session_options) {
Steve Antondcc3c022017-12-22 16:02:54 -08003526 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
zhihuang1c378ed2017-08-17 14:10:50 -07003527
Steve Antondcc3c022017-12-22 16:02:54 -08003528 if (IsUnifiedPlan()) {
3529 GetOptionsForUnifiedPlanOffer(offer_answer_options, session_options);
3530 } else {
3531 GetOptionsForPlanBOffer(offer_answer_options, session_options);
3532 }
3533
Steve Antonfa2260d2017-12-28 16:38:23 -08003534 // Intentionally unset the data channel type for RTP data channel with the
3535 // second condition. Otherwise the RTP data channels would be successfully
3536 // negotiated by default and the unit tests in WebRtcDataBrowserTest will fail
3537 // when building with chromium. We want to leave RTP data channels broken, so
3538 // people won't try to use them.
3539 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
3540 session_options->data_channel_type = data_channel_type();
3541 }
3542
Steve Antondcc3c022017-12-22 16:02:54 -08003543 // Apply ICE restart flag and renomination flag.
3544 for (auto& options : session_options->media_description_options) {
3545 options.transport_options.ice_restart = offer_answer_options.ice_restart;
3546 options.transport_options.enable_ice_renomination =
3547 configuration_.enable_ice_renomination;
3548 }
3549
3550 session_options->rtcp_cname = rtcp_cname_;
3551 session_options->crypto_options = factory_->options().crypto_options;
Steve Antone831b8c2018-02-01 12:22:16 -08003552 session_options->is_unified_plan = IsUnifiedPlan();
Steve Antondcc3c022017-12-22 16:02:54 -08003553}
3554
3555void PeerConnection::GetOptionsForPlanBOffer(
3556 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
3557 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07003558 // Figure out transceiver directional preferences.
3559 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
3560 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
3561
3562 // By default, generate sendrecv/recvonly m= sections.
3563 bool recv_audio = true;
3564 bool recv_video = true;
3565
3566 // By default, only offer a new m= section if we have media to send with it.
3567 bool offer_new_audio_description = send_audio;
3568 bool offer_new_video_description = send_video;
3569 bool offer_new_data_description = HasDataChannels();
3570
3571 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-22 16:02:54 -08003572 if (offer_answer_options.offer_to_receive_audio !=
3573 RTCOfferAnswerOptions::kUndefined) {
3574 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003575 offer_new_audio_description =
Steve Antondcc3c022017-12-22 16:02:54 -08003576 offer_new_audio_description ||
3577 (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003578 }
Steve Antondcc3c022017-12-22 16:02:54 -08003579 if (offer_answer_options.offer_to_receive_video !=
3580 RTCOfferAnswerOptions::kUndefined) {
3581 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003582 offer_new_video_description =
Steve Antondcc3c022017-12-22 16:02:54 -08003583 offer_new_video_description ||
3584 (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003585 }
3586
3587 rtc::Optional<size_t> audio_index;
3588 rtc::Optional<size_t> video_index;
3589 rtc::Optional<size_t> data_index;
3590 // If a current description exists, generate m= sections in the same order,
3591 // using the first audio/video/data section that appears and rejecting
3592 // extraneous ones.
Steve Anton75737c02017-11-06 10:37:17 -08003593 if (local_description()) {
zhihuang1c378ed2017-08-17 14:10:50 -07003594 GenerateMediaDescriptionOptions(
Steve Anton75737c02017-11-06 10:37:17 -08003595 local_description(),
Steve Anton1d03a752017-11-27 14:30:09 -08003596 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
3597 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
3598 &audio_index, &video_index, &data_index, session_options);
deadbeefab9b2d12015-10-14 11:33:11 -07003599 }
3600
zhihuang1c378ed2017-08-17 14:10:50 -07003601 // Add audio/video/data m= sections to the end if needed.
3602 if (!audio_index && offer_new_audio_description) {
3603 session_options->media_description_options.push_back(
3604 cricket::MediaDescriptionOptions(
3605 cricket::MEDIA_TYPE_AUDIO, cricket::CN_AUDIO,
Steve Anton1d03a752017-11-27 14:30:09 -08003606 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
3607 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003608 audio_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07003609 }
zhihuang1c378ed2017-08-17 14:10:50 -07003610 if (!video_index && offer_new_video_description) {
3611 session_options->media_description_options.push_back(
3612 cricket::MediaDescriptionOptions(
3613 cricket::MEDIA_TYPE_VIDEO, cricket::CN_VIDEO,
Steve Anton1d03a752017-11-27 14:30:09 -08003614 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
3615 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003616 video_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07003617 }
zhihuang1c378ed2017-08-17 14:10:50 -07003618 if (!data_index && offer_new_data_description) {
3619 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08003620 GetMediaDescriptionOptionsForActiveData(cricket::CN_DATA));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003621 data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07003622 }
3623
3624 cricket::MediaDescriptionOptions* audio_media_description_options =
3625 !audio_index ? nullptr
3626 : &session_options->media_description_options[*audio_index];
3627 cricket::MediaDescriptionOptions* video_media_description_options =
3628 !video_index ? nullptr
3629 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 14:10:50 -07003630
Steve Anton4171afb2017-11-20 10:20:22 -08003631 AddRtpSenderOptions(GetSendersInternal(), audio_media_description_options,
zhihuang1c378ed2017-08-17 14:10:50 -07003632 video_media_description_options);
Steve Antondcc3c022017-12-22 16:02:54 -08003633}
3634
3635// Find a new MID that is not already in |used_mids|, then add it to |used_mids|
3636// and return a reference to it.
3637// Generated MIDs should be no more than 3 bytes long to take up less space in
3638// the RTP packet.
3639static const std::string& AllocateMid(std::set<std::string>* used_mids) {
3640 RTC_DCHECK(used_mids);
3641 // We're boring: just generate MIDs 0, 1, 2, ...
3642 size_t i = 0;
3643 std::set<std::string>::iterator it;
3644 bool inserted;
3645 do {
3646 std::string mid = rtc::ToString(i++);
3647 auto insert_result = used_mids->insert(mid);
3648 it = insert_result.first;
3649 inserted = insert_result.second;
3650 } while (!inserted);
3651 return *it;
3652}
3653
3654static cricket::MediaDescriptionOptions
3655GetMediaDescriptionOptionsForTransceiver(
3656 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3657 transceiver,
3658 const std::string& mid) {
3659 cricket::MediaDescriptionOptions media_description_options(
Steve Anton69470252018-02-09 11:43:08 -08003660 transceiver->media_type(), mid, transceiver->direction(),
Steve Antondcc3c022017-12-22 16:02:54 -08003661 transceiver->stopped());
Steve Anton5f94aa22018-02-01 10:58:30 -08003662 // This behavior is specified in JSEP. The gist is that:
3663 // 1. The MSID is included if the RtpTransceiver's direction is sendonly or
3664 // sendrecv.
3665 // 2. If the MSID is included, then it must be included in any subsequent
3666 // offer/answer exactly the same until the RtpTransceiver is stopped.
3667 if (!transceiver->stopped() &&
3668 (RtpTransceiverDirectionHasSend(transceiver->direction()) ||
3669 transceiver->internal()->has_ever_been_used_to_send())) {
3670 cricket::SenderOptions sender_options;
3671 sender_options.track_id = transceiver->sender()->id();
3672 sender_options.stream_ids = transceiver->sender()->stream_ids();
3673 // TODO(bugs.webrtc.org/7600): Set num_sim_layers to the number of encodings
3674 // set in the RTP parameters when the transceiver was added.
3675 sender_options.num_sim_layers = 1;
3676 media_description_options.sender_options.push_back(sender_options);
3677 }
Steve Antondcc3c022017-12-22 16:02:54 -08003678 return media_description_options;
3679}
3680
3681void PeerConnection::GetOptionsForUnifiedPlanOffer(
3682 const RTCOfferAnswerOptions& offer_answer_options,
3683 cricket::MediaSessionOptions* session_options) {
3684 // Rules for generating an offer are dictated by JSEP sections 5.2.1 (Initial
3685 // Offers) and 5.2.2 (Subsequent Offers).
3686 RTC_DCHECK_EQ(session_options->media_description_options.size(), 0);
3687 const ContentInfos& local_contents =
3688 (local_description() ? local_description()->description()->contents()
3689 : ContentInfos());
3690 const ContentInfos& remote_contents =
3691 (remote_description() ? remote_description()->description()->contents()
3692 : ContentInfos());
3693 // The mline indices that can be recycled. New transceivers should reuse these
3694 // slots first.
3695 std::queue<size_t> recycleable_mline_indices;
3696 // Track the MIDs used in previous offer/answer exchanges and the current
3697 // offer so that new, unique MIDs are generated.
3698 std::set<std::string> used_mids = seen_mids_;
3699 // First, go through each media section that exists in either the local or
3700 // remote description and generate a media section in this offer for the
3701 // associated transceiver. If a media section can be recycled, generate a
3702 // default, rejected media section here that can be later overwritten.
3703 for (size_t i = 0;
3704 i < std::max(local_contents.size(), remote_contents.size()); ++i) {
3705 // Either |local_content| or |remote_content| is non-null.
3706 const ContentInfo* local_content =
3707 (i < local_contents.size() ? &local_contents[i] : nullptr);
3708 const ContentInfo* remote_content =
3709 (i < remote_contents.size() ? &remote_contents[i] : nullptr);
3710 bool had_been_rejected = (local_content && local_content->rejected) ||
3711 (remote_content && remote_content->rejected);
3712 const std::string& mid =
3713 (local_content ? local_content->name : remote_content->name);
3714 cricket::MediaType media_type =
3715 (local_content ? local_content->media_description()->type()
3716 : remote_content->media_description()->type());
3717 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
3718 media_type == cricket::MEDIA_TYPE_VIDEO) {
3719 auto transceiver = GetAssociatedTransceiver(mid);
3720 RTC_CHECK(transceiver);
3721 // A media section is considered eligible for recycling if it is marked as
3722 // rejected in either the local or remote description.
Seth Hampsonae8a90a2018-02-13 15:33:48 -08003723 if (had_been_rejected && transceiver->stopped()) {
Steve Antondcc3c022017-12-22 16:02:54 -08003724 session_options->media_description_options.push_back(
Steve Anton69470252018-02-09 11:43:08 -08003725 cricket::MediaDescriptionOptions(transceiver->media_type(), mid,
3726 RtpTransceiverDirection::kInactive,
3727 /*stopped=*/true));
Steve Antondcc3c022017-12-22 16:02:54 -08003728 recycleable_mline_indices.push(i);
3729 } else {
3730 session_options->media_description_options.push_back(
3731 GetMediaDescriptionOptionsForTransceiver(transceiver, mid));
3732 // CreateOffer shouldn't really cause any state changes in
3733 // PeerConnection, but we need a way to match new transceivers to new
3734 // media sections in SetLocalDescription and JSEP specifies this is done
3735 // by recording the index of the media section generated for the
3736 // transceiver in the offer.
3737 transceiver->internal()->set_mline_index(i);
3738 }
3739 } else {
3740 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antonfa2260d2017-12-28 16:38:23 -08003741 RTC_CHECK(GetDataMid());
3742 if (had_been_rejected || mid != *GetDataMid()) {
3743 session_options->media_description_options.push_back(
3744 GetMediaDescriptionOptionsForRejectedData(mid));
3745 } else {
3746 session_options->media_description_options.push_back(
3747 GetMediaDescriptionOptionsForActiveData(mid));
3748 }
Steve Antondcc3c022017-12-22 16:02:54 -08003749 }
3750 }
3751 // Next, look for transceivers that are newly added (that is, are not stopped
3752 // and not associated). Reuse media sections marked as recyclable first,
3753 // otherwise append to the end of the offer. New media sections should be
3754 // added in the order they were added to the PeerConnection.
3755 for (auto transceiver : transceivers_) {
3756 if (transceiver->mid() || transceiver->stopped()) {
3757 continue;
3758 }
3759 size_t mline_index;
3760 if (!recycleable_mline_indices.empty()) {
3761 mline_index = recycleable_mline_indices.front();
3762 recycleable_mline_indices.pop();
3763 session_options->media_description_options[mline_index] =
3764 GetMediaDescriptionOptionsForTransceiver(transceiver,
3765 AllocateMid(&used_mids));
3766 } else {
3767 mline_index = session_options->media_description_options.size();
3768 session_options->media_description_options.push_back(
3769 GetMediaDescriptionOptionsForTransceiver(transceiver,
3770 AllocateMid(&used_mids)));
3771 }
3772 // See comment above for why CreateOffer changes the transceiver's state.
3773 transceiver->internal()->set_mline_index(mline_index);
3774 }
Steve Antonfa2260d2017-12-28 16:38:23 -08003775 // Lastly, add a m-section if we have local data channels and an m section
3776 // does not already exist.
3777 if (!GetDataMid() && HasDataChannels()) {
3778 session_options->media_description_options.push_back(
3779 GetMediaDescriptionOptionsForActiveData(AllocateMid(&used_mids)));
3780 }
Steve Antondcc3c022017-12-22 16:02:54 -08003781}
3782
3783void PeerConnection::GetOptionsForAnswer(
3784 const RTCOfferAnswerOptions& offer_answer_options,
3785 cricket::MediaSessionOptions* session_options) {
3786 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
3787
3788 if (IsUnifiedPlan()) {
3789 GetOptionsForUnifiedPlanAnswer(offer_answer_options, session_options);
3790 } else {
3791 GetOptionsForPlanBAnswer(offer_answer_options, session_options);
3792 }
3793
Steve Antonfa2260d2017-12-28 16:38:23 -08003794 // Intentionally unset the data channel type for RTP data channel. Otherwise
3795 // the RTP data channels would be successfully negotiated by default and the
3796 // unit tests in WebRtcDataBrowserTest will fail when building with chromium.
3797 // We want to leave RTP data channels broken, so people won't try to use them.
3798 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
3799 session_options->data_channel_type = data_channel_type();
3800 }
3801
Steve Antondcc3c022017-12-22 16:02:54 -08003802 // Apply ICE renomination flag.
3803 for (auto& options : session_options->media_description_options) {
3804 options.transport_options.enable_ice_renomination =
3805 configuration_.enable_ice_renomination;
3806 }
zhihuang8f65cdf2016-05-06 18:40:30 -07003807
3808 session_options->rtcp_cname = rtcp_cname_;
jbauchcb560652016-08-04 05:20:32 -07003809 session_options->crypto_options = factory_->options().crypto_options;
Steve Antone831b8c2018-02-01 12:22:16 -08003810 session_options->is_unified_plan = IsUnifiedPlan();
deadbeefab9b2d12015-10-14 11:33:11 -07003811}
3812
Steve Antondcc3c022017-12-22 16:02:54 -08003813void PeerConnection::GetOptionsForPlanBAnswer(
3814 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07003815 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07003816 // Figure out transceiver directional preferences.
3817 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
3818 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
3819
3820 // By default, generate sendrecv/recvonly m= sections. The direction is also
3821 // restricted by the direction in the offer.
3822 bool recv_audio = true;
3823 bool recv_video = true;
3824
3825 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-22 16:02:54 -08003826 if (offer_answer_options.offer_to_receive_audio !=
3827 RTCOfferAnswerOptions::kUndefined) {
3828 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
deadbeef0ed85b22016-02-23 17:24:52 -08003829 }
Steve Antondcc3c022017-12-22 16:02:54 -08003830 if (offer_answer_options.offer_to_receive_video !=
3831 RTCOfferAnswerOptions::kUndefined) {
3832 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003833 }
3834
3835 rtc::Optional<size_t> audio_index;
3836 rtc::Optional<size_t> video_index;
3837 rtc::Optional<size_t> data_index;
Steve Antondffead82018-02-06 10:31:29 -08003838
3839 // Generate m= sections that match those in the offer.
3840 // Note that mediasession.cc will handle intersection our preferred
3841 // direction with the offered direction.
3842 GenerateMediaDescriptionOptions(
3843 remote_description(),
3844 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
3845 RtpTransceiverDirectionFromSendRecv(send_video, recv_video), &audio_index,
3846 &video_index, &data_index, session_options);
zhihuang1c378ed2017-08-17 14:10:50 -07003847
3848 cricket::MediaDescriptionOptions* audio_media_description_options =
3849 !audio_index ? nullptr
3850 : &session_options->media_description_options[*audio_index];
3851 cricket::MediaDescriptionOptions* video_media_description_options =
3852 !video_index ? nullptr
3853 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 14:10:50 -07003854
Steve Anton4171afb2017-11-20 10:20:22 -08003855 AddRtpSenderOptions(GetSendersInternal(), audio_media_description_options,
zhihuang1c378ed2017-08-17 14:10:50 -07003856 video_media_description_options);
Steve Antondcc3c022017-12-22 16:02:54 -08003857}
zhihuangaf388472016-11-02 16:49:48 -07003858
Steve Antondcc3c022017-12-22 16:02:54 -08003859void PeerConnection::GetOptionsForUnifiedPlanAnswer(
3860 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
3861 cricket::MediaSessionOptions* session_options) {
3862 // Rules for generating an answer are dictated by JSEP sections 5.3.1 (Initial
3863 // Answers) and 5.3.2 (Subsequent Answers).
3864 RTC_DCHECK(remote_description());
3865 RTC_DCHECK(remote_description()->GetType() == SdpType::kOffer);
3866 for (const ContentInfo& content :
3867 remote_description()->description()->contents()) {
3868 cricket::MediaType media_type = content.media_description()->type();
3869 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
3870 media_type == cricket::MEDIA_TYPE_VIDEO) {
3871 auto transceiver = GetAssociatedTransceiver(content.name);
3872 RTC_CHECK(transceiver);
3873 session_options->media_description_options.push_back(
3874 GetMediaDescriptionOptionsForTransceiver(transceiver, content.name));
3875 } else {
3876 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antondbf9d032018-01-19 15:23:40 -08003877 // Reject all data sections if data channels are disabled.
3878 // Reject a data section if it has already been rejected.
3879 // Reject all data sections except for the first one.
3880 if (data_channel_type_ == cricket::DCT_NONE || content.rejected ||
3881 content.name != *GetDataMid()) {
Steve Antonfa2260d2017-12-28 16:38:23 -08003882 session_options->media_description_options.push_back(
3883 GetMediaDescriptionOptionsForRejectedData(content.name));
3884 } else {
3885 session_options->media_description_options.push_back(
3886 GetMediaDescriptionOptionsForActiveData(content.name));
3887 }
Steve Antondcc3c022017-12-22 16:02:54 -08003888 }
3889 }
htaa2a49d92016-03-04 02:51:39 -08003890}
3891
zhihuang1c378ed2017-08-17 14:10:50 -07003892void PeerConnection::GenerateMediaDescriptionOptions(
3893 const SessionDescriptionInterface* session_desc,
Steve Anton1d03a752017-11-27 14:30:09 -08003894 RtpTransceiverDirection audio_direction,
3895 RtpTransceiverDirection video_direction,
zhihuang1c378ed2017-08-17 14:10:50 -07003896 rtc::Optional<size_t>* audio_index,
3897 rtc::Optional<size_t>* video_index,
3898 rtc::Optional<size_t>* data_index,
htaa2a49d92016-03-04 02:51:39 -08003899 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07003900 for (const cricket::ContentInfo& content :
3901 session_desc->description()->contents()) {
3902 if (IsAudioContent(&content)) {
3903 // If we already have an audio m= section, reject this extra one.
3904 if (*audio_index) {
3905 session_options->media_description_options.push_back(
3906 cricket::MediaDescriptionOptions(
3907 cricket::MEDIA_TYPE_AUDIO, content.name,
Steve Anton1d03a752017-11-27 14:30:09 -08003908 RtpTransceiverDirection::kInactive, true));
zhihuang1c378ed2017-08-17 14:10:50 -07003909 } else {
3910 session_options->media_description_options.push_back(
3911 cricket::MediaDescriptionOptions(
3912 cricket::MEDIA_TYPE_AUDIO, content.name, audio_direction,
Steve Anton1d03a752017-11-27 14:30:09 -08003913 audio_direction == RtpTransceiverDirection::kInactive));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003914 *audio_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07003915 }
3916 } else if (IsVideoContent(&content)) {
3917 // If we already have an video m= section, reject this extra one.
3918 if (*video_index) {
3919 session_options->media_description_options.push_back(
3920 cricket::MediaDescriptionOptions(
3921 cricket::MEDIA_TYPE_VIDEO, content.name,
Steve Anton1d03a752017-11-27 14:30:09 -08003922 RtpTransceiverDirection::kInactive, true));
zhihuang1c378ed2017-08-17 14:10:50 -07003923 } else {
3924 session_options->media_description_options.push_back(
3925 cricket::MediaDescriptionOptions(
3926 cricket::MEDIA_TYPE_VIDEO, content.name, video_direction,
Steve Anton1d03a752017-11-27 14:30:09 -08003927 video_direction == RtpTransceiverDirection::kInactive));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003928 *video_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07003929 }
3930 } else {
3931 RTC_DCHECK(IsDataContent(&content));
3932 // If we already have an data m= section, reject this extra one.
3933 if (*data_index) {
3934 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08003935 GetMediaDescriptionOptionsForRejectedData(content.name));
zhihuang1c378ed2017-08-17 14:10:50 -07003936 } else {
3937 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08003938 GetMediaDescriptionOptionsForActiveData(content.name));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003939 *data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07003940 }
3941 }
htaa2a49d92016-03-04 02:51:39 -08003942 }
deadbeefab9b2d12015-10-14 11:33:11 -07003943}
3944
Steve Antonfa2260d2017-12-28 16:38:23 -08003945cricket::MediaDescriptionOptions
3946PeerConnection::GetMediaDescriptionOptionsForActiveData(
3947 const std::string& mid) const {
3948 // Direction for data sections is meaningless, but legacy endpoints might
3949 // expect sendrecv.
3950 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
3951 RtpTransceiverDirection::kSendRecv,
3952 /*stopped=*/false);
3953 AddRtpDataChannelOptions(rtp_data_channels_, &options);
3954 return options;
3955}
3956
3957cricket::MediaDescriptionOptions
3958PeerConnection::GetMediaDescriptionOptionsForRejectedData(
3959 const std::string& mid) const {
3960 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
3961 RtpTransceiverDirection::kInactive,
3962 /*stopped=*/true);
3963 AddRtpDataChannelOptions(rtp_data_channels_, &options);
3964 return options;
3965}
3966
3967rtc::Optional<std::string> PeerConnection::GetDataMid() const {
3968 switch (data_channel_type_) {
3969 case cricket::DCT_RTP:
3970 if (!rtp_data_channel_) {
3971 return rtc::nullopt;
3972 }
3973 return rtp_data_channel_->content_name();
3974 case cricket::DCT_SCTP:
Zhi Huange830e682018-03-30 10:48:35 -07003975 return sctp_mid_;
Steve Antonfa2260d2017-12-28 16:38:23 -08003976 default:
3977 return rtc::nullopt;
3978 }
3979}
3980
Steve Anton4171afb2017-11-20 10:20:22 -08003981void PeerConnection::RemoveSenders(cricket::MediaType media_type) {
3982 UpdateLocalSenders(std::vector<cricket::StreamParams>(), media_type);
3983 UpdateRemoteSendersList(std::vector<cricket::StreamParams>(), false,
deadbeefbda7e0b2015-12-08 17:13:40 -08003984 media_type, nullptr);
deadbeeffaac4972015-11-12 15:33:07 -08003985}
3986
Steve Anton4171afb2017-11-20 10:20:22 -08003987void PeerConnection::UpdateRemoteSendersList(
deadbeefab9b2d12015-10-14 11:33:11 -07003988 const cricket::StreamParamsVec& streams,
Steve Anton4171afb2017-11-20 10:20:22 -08003989 bool default_sender_needed,
deadbeefab9b2d12015-10-14 11:33:11 -07003990 cricket::MediaType media_type,
3991 StreamCollection* new_streams) {
Steve Anton4171afb2017-11-20 10:20:22 -08003992 std::vector<RtpSenderInfo>* current_senders =
3993 GetRemoteSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07003994
Steve Anton4171afb2017-11-20 10:20:22 -08003995 // Find removed senders. I.e., senders where the sender id or ssrc don't match
deadbeeffac06552015-11-25 11:26:01 -08003996 // the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08003997 for (auto sender_it = current_senders->begin();
3998 sender_it != current_senders->end();
3999 /* incremented manually */) {
4000 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07004001 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08004002 cricket::GetStreamBySsrc(streams, info.first_ssrc);
Tomas Gunnarsson191bf5c2018-03-30 10:44:43 +00004003 bool sender_exists = params && params->id == info.sender_id;
deadbeefbda7e0b2015-12-08 17:13:40 -08004004 // If this is a default track, and we still need it, don't remove it.
Seth Hampson845e8782018-03-02 11:34:10 -08004005 if ((info.stream_id == kDefaultStreamId && default_sender_needed) ||
Steve Anton4171afb2017-11-20 10:20:22 -08004006 sender_exists) {
4007 ++sender_it;
deadbeefbda7e0b2015-12-08 17:13:40 -08004008 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08004009 OnRemoteSenderRemoved(info, media_type);
4010 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07004011 }
4012 }
4013
Steve Anton4171afb2017-11-20 10:20:22 -08004014 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07004015 for (const cricket::StreamParams& params : streams) {
Seth Hampson845e8782018-03-02 11:34:10 -08004016 // |params.id| is the sender id and the stream id uses the first of
Tomas Gunnarsson191bf5c2018-03-30 10:44:43 +00004017 // |params.stream_ids|.
4018 // TODO(bugs.webrtc.org/7932): Add support for multiple stream ids.
Seth Hampson845e8782018-03-02 11:34:10 -08004019 const std::string& stream_id =
Tomas Gunnarsson191bf5c2018-03-30 10:44:43 +00004020 (!params.stream_ids().empty() ? params.stream_ids()[0] : "");
Steve Anton4171afb2017-11-20 10:20:22 -08004021 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07004022 uint32_t ssrc = params.first_ssrc();
4023
4024 rtc::scoped_refptr<MediaStreamInterface> stream =
Seth Hampson845e8782018-03-02 11:34:10 -08004025 remote_streams_->find(stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004026 if (!stream) {
4027 // This is a new MediaStream. Create a new remote MediaStream.
perkjd61bf802016-03-24 03:16:19 -07004028 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
Seth Hampson845e8782018-03-02 11:34:10 -08004029 MediaStream::Create(stream_id));
deadbeefab9b2d12015-10-14 11:33:11 -07004030 remote_streams_->AddStream(stream);
4031 new_streams->AddStream(stream);
4032 }
4033
Steve Anton4171afb2017-11-20 10:20:22 -08004034 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004035 FindSenderInfo(*current_senders, stream_id, sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08004036 if (!sender_info) {
Seth Hampson845e8782018-03-02 11:34:10 -08004037 current_senders->push_back(RtpSenderInfo(stream_id, sender_id, ssrc));
Steve Anton4171afb2017-11-20 10:20:22 -08004038 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004039 }
4040 }
deadbeefbda7e0b2015-12-08 17:13:40 -08004041
Steve Anton4171afb2017-11-20 10:20:22 -08004042 // Add default sender if necessary.
4043 if (default_sender_needed) {
deadbeefbda7e0b2015-12-08 17:13:40 -08004044 rtc::scoped_refptr<MediaStreamInterface> default_stream =
Seth Hampson845e8782018-03-02 11:34:10 -08004045 remote_streams_->find(kDefaultStreamId);
deadbeefbda7e0b2015-12-08 17:13:40 -08004046 if (!default_stream) {
4047 // Create the new default MediaStream.
perkjd61bf802016-03-24 03:16:19 -07004048 default_stream = MediaStreamProxy::Create(
Seth Hampson845e8782018-03-02 11:34:10 -08004049 rtc::Thread::Current(), MediaStream::Create(kDefaultStreamId));
deadbeefbda7e0b2015-12-08 17:13:40 -08004050 remote_streams_->AddStream(default_stream);
4051 new_streams->AddStream(default_stream);
4052 }
Steve Anton4171afb2017-11-20 10:20:22 -08004053 std::string default_sender_id = (media_type == cricket::MEDIA_TYPE_AUDIO)
4054 ? kDefaultAudioSenderId
4055 : kDefaultVideoSenderId;
Seth Hampson845e8782018-03-02 11:34:10 -08004056 const RtpSenderInfo* default_sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004057 FindSenderInfo(*current_senders, kDefaultStreamId, default_sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08004058 if (!default_sender_info) {
4059 current_senders->push_back(
Seth Hampson845e8782018-03-02 11:34:10 -08004060 RtpSenderInfo(kDefaultStreamId, default_sender_id, 0));
Steve Anton4171afb2017-11-20 10:20:22 -08004061 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefbda7e0b2015-12-08 17:13:40 -08004062 }
4063 }
deadbeefab9b2d12015-10-14 11:33:11 -07004064}
4065
Steve Anton4171afb2017-11-20 10:20:22 -08004066void PeerConnection::OnRemoteSenderAdded(const RtpSenderInfo& sender_info,
4067 cricket::MediaType media_type) {
Seth Hampson845e8782018-03-02 11:34:10 -08004068 MediaStreamInterface* stream = remote_streams_->find(sender_info.stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004069
4070 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004071 CreateAudioReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004072 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004073 CreateVideoReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004074 } else {
nisseeb4ca4e2017-01-12 02:24:27 -08004075 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07004076 }
4077}
4078
Steve Anton4171afb2017-11-20 10:20:22 -08004079void PeerConnection::OnRemoteSenderRemoved(const RtpSenderInfo& sender_info,
4080 cricket::MediaType media_type) {
Seth Hampson845e8782018-03-02 11:34:10 -08004081 MediaStreamInterface* stream = remote_streams_->find(sender_info.stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004082
Henrik Boström933d8b02017-10-10 10:05:16 -07004083 rtc::scoped_refptr<RtpReceiverInterface> receiver;
deadbeefab9b2d12015-10-14 11:33:11 -07004084 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
perkjd61bf802016-03-24 03:16:19 -07004085 // When the MediaEngine audio channel is destroyed, the RemoteAudioSource
4086 // will be notified which will end the AudioRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08004087 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004088 rtc::scoped_refptr<AudioTrackInterface> audio_track =
Steve Anton4171afb2017-11-20 10:20:22 -08004089 stream->FindAudioTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004090 if (audio_track) {
deadbeefab9b2d12015-10-14 11:33:11 -07004091 stream->RemoveTrack(audio_track);
deadbeefab9b2d12015-10-14 11:33:11 -07004092 }
4093 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
perkjd61bf802016-03-24 03:16:19 -07004094 // Stopping or destroying a VideoRtpReceiver will end the
4095 // VideoRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08004096 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004097 rtc::scoped_refptr<VideoTrackInterface> video_track =
Steve Anton4171afb2017-11-20 10:20:22 -08004098 stream->FindVideoTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004099 if (video_track) {
perkjd61bf802016-03-24 03:16:19 -07004100 // There's no guarantee the track is still available, e.g. the track may
4101 // have been removed from the stream by an application.
deadbeefab9b2d12015-10-14 11:33:11 -07004102 stream->RemoveTrack(video_track);
deadbeefab9b2d12015-10-14 11:33:11 -07004103 }
4104 } else {
nisseede5da42017-01-12 05:15:36 -08004105 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07004106 }
Henrik Boström933d8b02017-10-10 10:05:16 -07004107 if (receiver) {
4108 observer_->OnRemoveTrack(receiver);
4109 }
deadbeefab9b2d12015-10-14 11:33:11 -07004110}
4111
4112void PeerConnection::UpdateEndedRemoteMediaStreams() {
4113 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams_to_remove;
4114 for (size_t i = 0; i < remote_streams_->count(); ++i) {
4115 MediaStreamInterface* stream = remote_streams_->at(i);
4116 if (stream->GetAudioTracks().empty() && stream->GetVideoTracks().empty()) {
4117 streams_to_remove.push_back(stream);
4118 }
4119 }
4120
Taylor Brandstetter98cde262016-05-31 13:02:21 -07004121 for (auto& stream : streams_to_remove) {
deadbeefab9b2d12015-10-14 11:33:11 -07004122 remote_streams_->RemoveStream(stream);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07004123 observer_->OnRemoveStream(std::move(stream));
deadbeefab9b2d12015-10-14 11:33:11 -07004124 }
4125}
4126
Steve Anton4171afb2017-11-20 10:20:22 -08004127void PeerConnection::UpdateLocalSenders(
deadbeefab9b2d12015-10-14 11:33:11 -07004128 const std::vector<cricket::StreamParams>& streams,
4129 cricket::MediaType media_type) {
Steve Anton4171afb2017-11-20 10:20:22 -08004130 std::vector<RtpSenderInfo>* current_senders = GetLocalSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004131
Seth Hampson845e8782018-03-02 11:34:10 -08004132 // Find removed tracks. I.e., tracks where the track id, stream id or ssrc
deadbeefab9b2d12015-10-14 11:33:11 -07004133 // don't match the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08004134 for (auto sender_it = current_senders->begin();
4135 sender_it != current_senders->end();
4136 /* incremented manually */) {
4137 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07004138 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08004139 cricket::GetStreamBySsrc(streams, info.first_ssrc);
4140 if (!params || params->id != info.sender_id ||
Seth Hampson845e8782018-03-02 11:34:10 -08004141 params->first_stream_id() != info.stream_id) {
Steve Anton4171afb2017-11-20 10:20:22 -08004142 OnLocalSenderRemoved(info, media_type);
4143 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07004144 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08004145 ++sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07004146 }
4147 }
4148
Steve Anton4171afb2017-11-20 10:20:22 -08004149 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07004150 for (const cricket::StreamParams& params : streams) {
4151 // The sync_label is the MediaStream label and the |stream.id| is the
Steve Anton4171afb2017-11-20 10:20:22 -08004152 // sender id.
Seth Hampson845e8782018-03-02 11:34:10 -08004153 const std::string& stream_id = params.first_stream_id();
Steve Anton4171afb2017-11-20 10:20:22 -08004154 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07004155 uint32_t ssrc = params.first_ssrc();
Steve Anton4171afb2017-11-20 10:20:22 -08004156 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004157 FindSenderInfo(*current_senders, stream_id, sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08004158 if (!sender_info) {
Seth Hampson845e8782018-03-02 11:34:10 -08004159 current_senders->push_back(RtpSenderInfo(stream_id, sender_id, ssrc));
Steve Anton4171afb2017-11-20 10:20:22 -08004160 OnLocalSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004161 }
4162 }
4163}
4164
Steve Anton4171afb2017-11-20 10:20:22 -08004165void PeerConnection::OnLocalSenderAdded(const RtpSenderInfo& sender_info,
4166 cricket::MediaType media_type) {
4167 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08004168 if (!sender) {
Steve Anton4171afb2017-11-20 10:20:22 -08004169 RTC_LOG(LS_WARNING) << "An unknown RtpSender with id "
4170 << sender_info.sender_id
Mirko Bonadei675513b2017-11-09 11:09:25 +01004171 << " has been configured in the local description.";
deadbeefab9b2d12015-10-14 11:33:11 -07004172 return;
4173 }
4174
deadbeeffac06552015-11-25 11:26:01 -08004175 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004176 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
Jonas Olsson45cc8902018-02-13 10:37:07 +01004177 " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08004178 return;
deadbeefab9b2d12015-10-14 11:33:11 -07004179 }
deadbeeffac06552015-11-25 11:26:01 -08004180
Tomas Gunnarsson191bf5c2018-03-30 10:44:43 +00004181 sender->internal()->set_stream_id(sender_info.stream_id);
Steve Anton4171afb2017-11-20 10:20:22 -08004182 sender->internal()->SetSsrc(sender_info.first_ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07004183}
4184
Steve Anton4171afb2017-11-20 10:20:22 -08004185void PeerConnection::OnLocalSenderRemoved(const RtpSenderInfo& sender_info,
4186 cricket::MediaType media_type) {
4187 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08004188 if (!sender) {
4189 // This is the normal case. I.e., RemoveStream has been called and the
deadbeefab9b2d12015-10-14 11:33:11 -07004190 // SessionDescriptions has been renegotiated.
4191 return;
4192 }
deadbeeffac06552015-11-25 11:26:01 -08004193
4194 // A sender has been removed from the SessionDescription but it's still
4195 // associated with the PeerConnection. This only occurs if the SDP doesn't
4196 // match with the calls to CreateSender, AddStream and RemoveStream.
4197 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004198 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
Jonas Olsson45cc8902018-02-13 10:37:07 +01004199 " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08004200 return;
deadbeefab9b2d12015-10-14 11:33:11 -07004201 }
deadbeeffac06552015-11-25 11:26:01 -08004202
Steve Anton4171afb2017-11-20 10:20:22 -08004203 sender->internal()->SetSsrc(0);
deadbeefab9b2d12015-10-14 11:33:11 -07004204}
4205
4206void PeerConnection::UpdateLocalRtpDataChannels(
4207 const cricket::StreamParamsVec& streams) {
4208 std::vector<std::string> existing_channels;
4209
4210 // Find new and active data channels.
4211 for (const cricket::StreamParams& params : streams) {
4212 // |it->sync_label| is actually the data channel label. The reason is that
4213 // we use the same naming of data channels as we do for
4214 // MediaStreams and Tracks.
4215 // For MediaStreams, the sync_label is the MediaStream label and the
4216 // track label is the same as |streamid|.
Seth Hampson845e8782018-03-02 11:34:10 -08004217 const std::string& channel_label = params.first_stream_id();
deadbeefab9b2d12015-10-14 11:33:11 -07004218 auto data_channel_it = rtp_data_channels_.find(channel_label);
nisse7ce109a2017-01-31 00:57:56 -08004219 if (data_channel_it == rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004220 RTC_LOG(LS_ERROR) << "channel label not found";
deadbeefab9b2d12015-10-14 11:33:11 -07004221 continue;
4222 }
4223 // Set the SSRC the data channel should use for sending.
4224 data_channel_it->second->SetSendSsrc(params.first_ssrc());
4225 existing_channels.push_back(data_channel_it->first);
4226 }
4227
4228 UpdateClosingRtpDataChannels(existing_channels, true);
4229}
4230
4231void PeerConnection::UpdateRemoteRtpDataChannels(
4232 const cricket::StreamParamsVec& streams) {
4233 std::vector<std::string> existing_channels;
4234
4235 // Find new and active data channels.
4236 for (const cricket::StreamParams& params : streams) {
4237 // The data channel label is either the mslabel or the SSRC if the mslabel
4238 // does not exist. Ex a=ssrc:444330170 mslabel:test1.
Seth Hampson845e8782018-03-02 11:34:10 -08004239 std::string label = params.first_stream_id().empty()
deadbeefab9b2d12015-10-14 11:33:11 -07004240 ? rtc::ToString(params.first_ssrc())
Seth Hampson845e8782018-03-02 11:34:10 -08004241 : params.first_stream_id();
deadbeefab9b2d12015-10-14 11:33:11 -07004242 auto data_channel_it = rtp_data_channels_.find(label);
4243 if (data_channel_it == rtp_data_channels_.end()) {
4244 // This is a new data channel.
4245 CreateRemoteRtpDataChannel(label, params.first_ssrc());
4246 } else {
4247 data_channel_it->second->SetReceiveSsrc(params.first_ssrc());
4248 }
4249 existing_channels.push_back(label);
4250 }
4251
4252 UpdateClosingRtpDataChannels(existing_channels, false);
4253}
4254
4255void PeerConnection::UpdateClosingRtpDataChannels(
4256 const std::vector<std::string>& active_channels,
4257 bool is_local_update) {
4258 auto it = rtp_data_channels_.begin();
4259 while (it != rtp_data_channels_.end()) {
4260 DataChannel* data_channel = it->second;
4261 if (std::find(active_channels.begin(), active_channels.end(),
4262 data_channel->label()) != active_channels.end()) {
4263 ++it;
4264 continue;
4265 }
4266
4267 if (is_local_update) {
4268 data_channel->SetSendSsrc(0);
4269 } else {
4270 data_channel->RemotePeerRequestClose();
4271 }
4272
4273 if (data_channel->state() == DataChannel::kClosed) {
4274 rtp_data_channels_.erase(it);
4275 it = rtp_data_channels_.begin();
4276 } else {
4277 ++it;
4278 }
4279 }
4280}
4281
4282void PeerConnection::CreateRemoteRtpDataChannel(const std::string& label,
4283 uint32_t remote_ssrc) {
4284 rtc::scoped_refptr<DataChannel> channel(
4285 InternalCreateDataChannel(label, nullptr));
4286 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004287 RTC_LOG(LS_WARNING) << "Remote peer requested a DataChannel but"
Jonas Olsson45cc8902018-02-13 10:37:07 +01004288 "CreateDataChannel failed.";
deadbeefab9b2d12015-10-14 11:33:11 -07004289 return;
4290 }
4291 channel->SetReceiveSsrc(remote_ssrc);
deadbeefa601f5c2016-06-06 14:27:39 -07004292 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
4293 DataChannelProxy::Create(signaling_thread(), channel);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07004294 observer_->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07004295}
4296
4297rtc::scoped_refptr<DataChannel> PeerConnection::InternalCreateDataChannel(
4298 const std::string& label,
4299 const InternalDataChannelInit* config) {
4300 if (IsClosed()) {
4301 return nullptr;
4302 }
Steve Anton75737c02017-11-06 10:37:17 -08004303 if (data_channel_type() == cricket::DCT_NONE) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004304 RTC_LOG(LS_ERROR)
deadbeefab9b2d12015-10-14 11:33:11 -07004305 << "InternalCreateDataChannel: Data is not supported in this call.";
4306 return nullptr;
4307 }
4308 InternalDataChannelInit new_config =
4309 config ? (*config) : InternalDataChannelInit();
Steve Anton75737c02017-11-06 10:37:17 -08004310 if (data_channel_type() == cricket::DCT_SCTP) {
deadbeefab9b2d12015-10-14 11:33:11 -07004311 if (new_config.id < 0) {
4312 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08004313 if ((GetSctpSslRole(&role)) &&
deadbeefab9b2d12015-10-14 11:33:11 -07004314 !sid_allocator_.AllocateSid(role, &new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004315 RTC_LOG(LS_ERROR)
4316 << "No id can be allocated for the SCTP data channel.";
deadbeefab9b2d12015-10-14 11:33:11 -07004317 return nullptr;
4318 }
4319 } else if (!sid_allocator_.ReserveSid(new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004320 RTC_LOG(LS_ERROR) << "Failed to create a SCTP data channel "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004321 "because the id is already in use or out of range.";
deadbeefab9b2d12015-10-14 11:33:11 -07004322 return nullptr;
4323 }
4324 }
4325
Steve Anton75737c02017-11-06 10:37:17 -08004326 rtc::scoped_refptr<DataChannel> channel(
4327 DataChannel::Create(this, data_channel_type(), label, new_config));
deadbeefab9b2d12015-10-14 11:33:11 -07004328 if (!channel) {
4329 sid_allocator_.ReleaseSid(new_config.id);
4330 return nullptr;
4331 }
4332
4333 if (channel->data_channel_type() == cricket::DCT_RTP) {
4334 if (rtp_data_channels_.find(channel->label()) != rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004335 RTC_LOG(LS_ERROR) << "DataChannel with label " << channel->label()
4336 << " already exists.";
deadbeefab9b2d12015-10-14 11:33:11 -07004337 return nullptr;
4338 }
4339 rtp_data_channels_[channel->label()] = channel;
4340 } else {
4341 RTC_DCHECK(channel->data_channel_type() == cricket::DCT_SCTP);
4342 sctp_data_channels_.push_back(channel);
4343 channel->SignalClosed.connect(this,
4344 &PeerConnection::OnSctpDataChannelClosed);
4345 }
4346
Steve Anton2d8609c2018-01-23 16:38:46 -08004347 SignalDataChannelCreated_(channel.get());
deadbeefab9b2d12015-10-14 11:33:11 -07004348 return channel;
4349}
4350
4351bool PeerConnection::HasDataChannels() const {
4352 return !rtp_data_channels_.empty() || !sctp_data_channels_.empty();
4353}
4354
4355void PeerConnection::AllocateSctpSids(rtc::SSLRole role) {
4356 for (const auto& channel : sctp_data_channels_) {
4357 if (channel->id() < 0) {
4358 int sid;
4359 if (!sid_allocator_.AllocateSid(role, &sid)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004360 RTC_LOG(LS_ERROR) << "Failed to allocate SCTP sid.";
deadbeefab9b2d12015-10-14 11:33:11 -07004361 continue;
4362 }
4363 channel->SetSctpSid(sid);
4364 }
4365 }
4366}
4367
4368void PeerConnection::OnSctpDataChannelClosed(DataChannel* channel) {
deadbeefbd292462015-12-14 18:15:29 -08004369 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeefab9b2d12015-10-14 11:33:11 -07004370 for (auto it = sctp_data_channels_.begin(); it != sctp_data_channels_.end();
4371 ++it) {
4372 if (it->get() == channel) {
4373 if (channel->id() >= 0) {
4374 sid_allocator_.ReleaseSid(channel->id());
4375 }
deadbeefbd292462015-12-14 18:15:29 -08004376 // Since this method is triggered by a signal from the DataChannel,
4377 // we can't free it directly here; we need to free it asynchronously.
4378 sctp_data_channels_to_free_.push_back(*it);
deadbeefab9b2d12015-10-14 11:33:11 -07004379 sctp_data_channels_.erase(it);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07004380 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_FREE_DATACHANNELS,
4381 nullptr);
deadbeefab9b2d12015-10-14 11:33:11 -07004382 return;
4383 }
4384 }
4385}
4386
deadbeefab9b2d12015-10-14 11:33:11 -07004387void PeerConnection::OnDataChannelDestroyed() {
4388 // Use a temporary copy of the RTP/SCTP DataChannel list because the
4389 // DataChannel may callback to us and try to modify the list.
4390 std::map<std::string, rtc::scoped_refptr<DataChannel>> temp_rtp_dcs;
4391 temp_rtp_dcs.swap(rtp_data_channels_);
4392 for (const auto& kv : temp_rtp_dcs) {
4393 kv.second->OnTransportChannelDestroyed();
4394 }
4395
4396 std::vector<rtc::scoped_refptr<DataChannel>> temp_sctp_dcs;
4397 temp_sctp_dcs.swap(sctp_data_channels_);
4398 for (const auto& channel : temp_sctp_dcs) {
4399 channel->OnTransportChannelDestroyed();
4400 }
4401}
4402
4403void PeerConnection::OnDataChannelOpenMessage(
4404 const std::string& label,
4405 const InternalDataChannelInit& config) {
4406 rtc::scoped_refptr<DataChannel> channel(
4407 InternalCreateDataChannel(label, &config));
4408 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004409 RTC_LOG(LS_ERROR) << "Failed to create DataChannel from the OPEN message.";
deadbeefab9b2d12015-10-14 11:33:11 -07004410 return;
4411 }
4412
deadbeefa601f5c2016-06-06 14:27:39 -07004413 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
4414 DataChannelProxy::Create(signaling_thread(), channel);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07004415 observer_->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07004416}
4417
Steve Anton4171afb2017-11-20 10:20:22 -08004418rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
4419PeerConnection::GetAudioTransceiver() const {
4420 // This method only works with Plan B SDP, where there is a single
4421 // audio/video transceiver.
4422 RTC_DCHECK(!IsUnifiedPlan());
4423 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08004424 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004425 return transceiver;
4426 }
4427 }
4428 RTC_NOTREACHED();
4429 return nullptr;
4430}
4431
4432rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
4433PeerConnection::GetVideoTransceiver() const {
4434 // This method only works with Plan B SDP, where there is a single
4435 // audio/video transceiver.
4436 RTC_DCHECK(!IsUnifiedPlan());
4437 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08004438 if (transceiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004439 return transceiver;
4440 }
4441 }
4442 RTC_NOTREACHED();
4443 return nullptr;
4444}
4445
4446// TODO(bugs.webrtc.org/7600): Remove this when multiple transceivers with
4447// individual transceiver directions are supported.
zhihuang1c378ed2017-08-17 14:10:50 -07004448bool PeerConnection::HasRtpSender(cricket::MediaType type) const {
Steve Anton4171afb2017-11-20 10:20:22 -08004449 switch (type) {
4450 case cricket::MEDIA_TYPE_AUDIO:
4451 return !GetAudioTransceiver()->internal()->senders().empty();
4452 case cricket::MEDIA_TYPE_VIDEO:
4453 return !GetVideoTransceiver()->internal()->senders().empty();
4454 case cricket::MEDIA_TYPE_DATA:
4455 return false;
4456 }
4457 RTC_NOTREACHED();
4458 return false;
zhihuang1c378ed2017-08-17 14:10:50 -07004459}
4460
Steve Anton4171afb2017-11-20 10:20:22 -08004461rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
4462PeerConnection::FindSenderForTrack(MediaStreamTrackInterface* track) const {
4463 for (auto transceiver : transceivers_) {
4464 for (auto sender : transceiver->internal()->senders()) {
4465 if (sender->track() == track) {
4466 return sender;
4467 }
4468 }
4469 }
4470 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08004471}
4472
Steve Anton4171afb2017-11-20 10:20:22 -08004473rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
4474PeerConnection::FindSenderById(const std::string& sender_id) const {
4475 for (auto transceiver : transceivers_) {
4476 for (auto sender : transceiver->internal()->senders()) {
4477 if (sender->id() == sender_id) {
4478 return sender;
4479 }
4480 }
4481 }
4482 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07004483}
4484
Steve Anton4171afb2017-11-20 10:20:22 -08004485rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
4486PeerConnection::FindReceiverById(const std::string& receiver_id) const {
4487 for (auto transceiver : transceivers_) {
4488 for (auto receiver : transceiver->internal()->receivers()) {
4489 if (receiver->id() == receiver_id) {
4490 return receiver;
4491 }
4492 }
4493 }
4494 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07004495}
4496
Steve Anton4171afb2017-11-20 10:20:22 -08004497std::vector<PeerConnection::RtpSenderInfo>*
4498PeerConnection::GetRemoteSenderInfos(cricket::MediaType media_type) {
4499 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
4500 media_type == cricket::MEDIA_TYPE_VIDEO);
4501 return (media_type == cricket::MEDIA_TYPE_AUDIO)
4502 ? &remote_audio_sender_infos_
4503 : &remote_video_sender_infos_;
4504}
4505
4506std::vector<PeerConnection::RtpSenderInfo>* PeerConnection::GetLocalSenderInfos(
deadbeefab9b2d12015-10-14 11:33:11 -07004507 cricket::MediaType media_type) {
4508 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
4509 media_type == cricket::MEDIA_TYPE_VIDEO);
Steve Anton4171afb2017-11-20 10:20:22 -08004510 return (media_type == cricket::MEDIA_TYPE_AUDIO) ? &local_audio_sender_infos_
4511 : &local_video_sender_infos_;
deadbeefab9b2d12015-10-14 11:33:11 -07004512}
4513
Steve Anton4171afb2017-11-20 10:20:22 -08004514const PeerConnection::RtpSenderInfo* PeerConnection::FindSenderInfo(
4515 const std::vector<PeerConnection::RtpSenderInfo>& infos,
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004516 const std::string& stream_id,
Steve Anton4171afb2017-11-20 10:20:22 -08004517 const std::string sender_id) const {
4518 for (const RtpSenderInfo& sender_info : infos) {
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004519 if (sender_info.stream_id == stream_id &&
4520 sender_info.sender_id == sender_id) {
Steve Anton4171afb2017-11-20 10:20:22 -08004521 return &sender_info;
deadbeefab9b2d12015-10-14 11:33:11 -07004522 }
4523 }
4524 return nullptr;
4525}
4526
4527DataChannel* PeerConnection::FindDataChannelBySid(int sid) const {
4528 for (const auto& channel : sctp_data_channels_) {
4529 if (channel->id() == sid) {
4530 return channel;
4531 }
4532 }
4533 return nullptr;
4534}
4535
deadbeef91dd5672016-05-18 16:55:30 -07004536bool PeerConnection::InitializePortAllocator_n(
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004537 const RTCConfiguration& configuration) {
4538 cricket::ServerAddresses stun_servers;
4539 std::vector<cricket::RelayServerConfig> turn_servers;
deadbeef293e9262017-01-11 12:28:30 -08004540 if (ParseIceServers(configuration.servers, &stun_servers, &turn_servers) !=
4541 RTCErrorType::NONE) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004542 return false;
4543 }
4544
Taylor Brandstetterf8e65772016-06-27 17:20:15 -07004545 port_allocator_->Initialize();
4546
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004547 // To handle both internal and externally created port allocator, we will
4548 // enable BUNDLE here.
4549 int portallocator_flags = port_allocator_->flags();
4550 portallocator_flags |= cricket::PORTALLOCATOR_ENABLE_SHARED_SOCKET |
zhihuangb09b3f92017-03-07 14:40:51 -08004551 cricket::PORTALLOCATOR_ENABLE_IPV6 |
4552 cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI;
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004553 // If the disable-IPv6 flag was specified, we'll not override it
4554 // by experiment.
4555 if (configuration.disable_ipv6) {
4556 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
sprangc1b57a12017-02-28 08:50:47 -08004557 } else if (webrtc::field_trial::FindFullName("WebRTC-IPv6Default")
4558 .find("Disabled") == 0) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004559 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
4560 }
4561
zhihuangb09b3f92017-03-07 14:40:51 -08004562 if (configuration.disable_ipv6_on_wifi) {
4563 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI);
Mirko Bonadei675513b2017-11-09 11:09:25 +01004564 RTC_LOG(LS_INFO) << "IPv6 candidates on Wi-Fi are disabled.";
zhihuangb09b3f92017-03-07 14:40:51 -08004565 }
4566
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004567 if (configuration.tcp_candidate_policy == kTcpCandidatePolicyDisabled) {
4568 portallocator_flags |= cricket::PORTALLOCATOR_DISABLE_TCP;
Mirko Bonadei675513b2017-11-09 11:09:25 +01004569 RTC_LOG(LS_INFO) << "TCP candidates are disabled.";
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004570 }
4571
honghaiz60347052016-05-31 18:29:12 -07004572 if (configuration.candidate_network_policy ==
4573 kCandidateNetworkPolicyLowCost) {
4574 portallocator_flags |= cricket::PORTALLOCATOR_DISABLE_COSTLY_NETWORKS;
Mirko Bonadei675513b2017-11-09 11:09:25 +01004575 RTC_LOG(LS_INFO) << "Do not gather candidates on high-cost networks";
honghaiz60347052016-05-31 18:29:12 -07004576 }
4577
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +01004578 if (configuration.disable_link_local_networks) {
4579 portallocator_flags |= cricket::PORTALLOCATOR_DISABLE_LINK_LOCAL_NETWORKS;
4580 RTC_LOG(LS_INFO) << "Disable candidates on link-local network interfaces.";
4581 }
4582
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004583 port_allocator_->set_flags(portallocator_flags);
4584 // No step delay is used while allocating ports.
4585 port_allocator_->set_step_delay(cricket::kMinimumStepDelay);
4586 port_allocator_->set_candidate_filter(
4587 ConvertIceTransportTypeToCandidateFilter(configuration.type));
deadbeefd21eab32017-07-26 16:50:11 -07004588 port_allocator_->set_max_ipv6_networks(configuration.max_ipv6_networks);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004589
4590 // Call this last since it may create pooled allocator sessions using the
4591 // properties set above.
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08004592 port_allocator_->SetConfiguration(
4593 stun_servers, turn_servers, configuration.ice_candidate_pool_size,
4594 configuration.prune_turn_ports, configuration.turn_customizer,
4595 configuration.stun_candidate_keepalive_interval);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004596 return true;
4597}
4598
deadbeef91dd5672016-05-18 16:55:30 -07004599bool PeerConnection::ReconfigurePortAllocator_n(
deadbeef293e9262017-01-11 12:28:30 -08004600 const cricket::ServerAddresses& stun_servers,
4601 const std::vector<cricket::RelayServerConfig>& turn_servers,
4602 IceTransportsType type,
4603 int candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02004604 bool prune_turn_ports,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08004605 webrtc::TurnCustomizer* turn_customizer,
4606 rtc::Optional<int> stun_candidate_keepalive_interval) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004607 port_allocator_->set_candidate_filter(
deadbeef293e9262017-01-11 12:28:30 -08004608 ConvertIceTransportTypeToCandidateFilter(type));
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004609 // Call this last since it may create pooled allocator sessions using the
4610 // candidate filter set above.
deadbeef6de92f92016-12-12 18:49:32 -08004611 return port_allocator_->SetConfiguration(
Jonas Orelandbdcee282017-10-10 14:01:40 +02004612 stun_servers, turn_servers, candidate_pool_size, prune_turn_ports,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08004613 turn_customizer, stun_candidate_keepalive_interval);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004614}
4615
Steve Antonba818672017-11-06 10:21:57 -08004616cricket::ChannelManager* PeerConnection::channel_manager() const {
4617 return factory_->channel_manager();
4618}
4619
4620MetricsObserverInterface* PeerConnection::metrics_observer() const {
4621 return uma_observer_;
4622}
4623
Elad Alon99c3fe52017-10-13 16:29:40 +02004624bool PeerConnection::StartRtcEventLog_w(
Bjorn Tereliusde939432017-11-20 17:38:14 +01004625 std::unique_ptr<RtcEventLogOutput> output,
4626 int64_t output_period_ms) {
zhihuang77985012017-02-07 15:45:16 -08004627 if (!event_log_) {
4628 return false;
4629 }
Bjorn Tereliusde939432017-11-20 17:38:14 +01004630 return event_log_->StartLogging(std::move(output), output_period_ms);
ivoc14d5dbe2016-07-04 07:06:55 -07004631}
4632
4633void PeerConnection::StopRtcEventLog_w() {
zhihuang77985012017-02-07 15:45:16 -08004634 if (event_log_) {
4635 event_log_->StopLogging();
4636 }
ivoc14d5dbe2016-07-04 07:06:55 -07004637}
nisseeaabdf62017-05-05 02:23:02 -07004638
Steve Anton75737c02017-11-06 10:37:17 -08004639cricket::BaseChannel* PeerConnection::GetChannel(
4640 const std::string& content_name) {
Steve Antondcc3c022017-12-22 16:02:54 -08004641 for (auto transceiver : transceivers_) {
4642 cricket::BaseChannel* channel = transceiver->internal()->channel();
4643 if (channel && channel->content_name() == content_name) {
4644 return channel;
4645 }
Steve Anton75737c02017-11-06 10:37:17 -08004646 }
4647 if (rtp_data_channel() &&
4648 rtp_data_channel()->content_name() == content_name) {
4649 return rtp_data_channel();
4650 }
4651 return nullptr;
4652}
4653
4654bool PeerConnection::GetSctpSslRole(rtc::SSLRole* role) {
4655 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004656 RTC_LOG(LS_INFO)
4657 << "Local and Remote descriptions must be applied to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004658 "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08004659 return false;
4660 }
4661 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004662 RTC_LOG(LS_INFO) << "Non-rejected SCTP m= section is needed to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004663 "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08004664 return false;
4665 }
4666
Zhi Huange830e682018-03-30 10:48:35 -07004667 auto dtls_role = transport_controller_->GetDtlsRole(*sctp_mid_);
4668 if (dtls_role) {
4669 *role = *dtls_role;
4670 return true;
4671 }
4672 return false;
Steve Anton75737c02017-11-06 10:37:17 -08004673}
4674
4675bool PeerConnection::GetSslRole(const std::string& content_name,
4676 rtc::SSLRole* role) {
4677 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004678 RTC_LOG(LS_INFO)
4679 << "Local and Remote descriptions must be applied to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004680 "SSL Role of the session.";
Steve Anton75737c02017-11-06 10:37:17 -08004681 return false;
4682 }
4683
Zhi Huange830e682018-03-30 10:48:35 -07004684 auto dtls_role = transport_controller_->GetDtlsRole(content_name);
4685 if (dtls_role) {
4686 *role = *dtls_role;
4687 return true;
4688 }
4689 return false;
Steve Anton75737c02017-11-06 10:37:17 -08004690}
4691
Steve Antonf8470812017-12-04 10:46:21 -08004692void PeerConnection::SetSessionError(SessionError error,
4693 const std::string& error_desc) {
4694 RTC_DCHECK_RUN_ON(signaling_thread());
4695 if (error != session_error_) {
4696 session_error_ = error;
4697 session_error_desc_ = error_desc;
Steve Anton75737c02017-11-06 10:37:17 -08004698 }
4699}
4700
Zhi Huange830e682018-03-30 10:48:35 -07004701RTCError PeerConnection::UpdateSessionState(
4702 SdpType type,
4703 cricket::ContentSource source,
4704 const cricket::SessionDescription* description) {
Steve Anton8a006912017-12-04 15:25:56 -08004705 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08004706
4707 // If there's already a pending error then no state transition should happen.
4708 // But all call-sites should be verifying this before calling us!
Steve Antonf8470812017-12-04 10:46:21 -08004709 RTC_DCHECK(session_error() == SessionError::kNone);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004710
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004711 // If this is answer-ish we're ready to let media flow.
Steve Anton3828c062017-12-06 10:34:51 -08004712 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Antoned10bd92017-12-05 10:52:59 -08004713 EnableSending();
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004714 }
4715
4716 // Update the signaling state according to the specified state machine (see
4717 // https://w3c.github.io/webrtc-pc/#rtcsignalingstate-enum).
Steve Anton3828c062017-12-06 10:34:51 -08004718 if (type == SdpType::kOffer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004719 ChangeSignalingState(source == cricket::CS_LOCAL
4720 ? PeerConnectionInterface::kHaveLocalOffer
4721 : PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton3828c062017-12-06 10:34:51 -08004722 } else if (type == SdpType::kPrAnswer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004723 ChangeSignalingState(source == cricket::CS_LOCAL
4724 ? PeerConnectionInterface::kHaveLocalPrAnswer
4725 : PeerConnectionInterface::kHaveRemotePrAnswer);
4726 } else {
Steve Anton3828c062017-12-06 10:34:51 -08004727 RTC_DCHECK(type == SdpType::kAnswer);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004728 ChangeSignalingState(PeerConnectionInterface::kStable);
4729 }
4730
4731 // Update internal objects according to the session description's media
4732 // descriptions.
Zhi Huange830e682018-03-30 10:48:35 -07004733 RTCError error = PushdownMediaDescription(type, source);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004734 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08004735 return error;
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004736 }
4737
Steve Anton8a006912017-12-04 15:25:56 -08004738 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08004739}
4740
Steve Anton8a006912017-12-04 15:25:56 -08004741RTCError PeerConnection::PushdownMediaDescription(
Steve Anton3828c062017-12-06 10:34:51 -08004742 SdpType type,
Steve Anton8a006912017-12-04 15:25:56 -08004743 cricket::ContentSource source) {
Steve Antoned10bd92017-12-05 10:52:59 -08004744 const SessionDescriptionInterface* sdesc =
4745 (source == cricket::CS_LOCAL ? local_description()
4746 : remote_description());
Steve Anton75737c02017-11-06 10:37:17 -08004747 RTC_DCHECK(sdesc);
Steve Antoned10bd92017-12-05 10:52:59 -08004748
4749 // Push down the new SDP media section for each audio/video transceiver.
4750 for (auto transceiver : transceivers_) {
Steve Anton75737c02017-11-06 10:37:17 -08004751 const ContentInfo* content_info =
Steve Antoned10bd92017-12-05 10:52:59 -08004752 FindMediaSectionForTransceiver(transceiver, sdesc);
4753 cricket::BaseChannel* channel = transceiver->internal()->channel();
4754 if (!channel || !content_info || content_info->rejected) {
Steve Anton75737c02017-11-06 10:37:17 -08004755 continue;
4756 }
4757 const MediaContentDescription* content_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08004758 content_info->media_description();
Steve Antoned10bd92017-12-05 10:52:59 -08004759 if (!content_desc) {
4760 continue;
4761 }
4762 std::string error;
4763 bool success =
4764 (source == cricket::CS_LOCAL)
Steve Anton3828c062017-12-06 10:34:51 -08004765 ? channel->SetLocalContent(content_desc, type, &error)
4766 : channel->SetRemoteContent(content_desc, type, &error);
Steve Antoned10bd92017-12-05 10:52:59 -08004767 if (!success) {
4768 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, std::move(error));
4769 }
4770 }
4771
4772 // If using the RtpDataChannel, push down the new SDP section for it too.
4773 if (rtp_data_channel_) {
4774 const ContentInfo* data_content =
4775 cricket::GetFirstDataContent(sdesc->description());
4776 if (data_content && !data_content->rejected) {
4777 const MediaContentDescription* data_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08004778 data_content->media_description();
Steve Antoned10bd92017-12-05 10:52:59 -08004779 if (data_desc) {
4780 std::string error;
4781 bool success =
4782 (source == cricket::CS_LOCAL)
Steve Anton3828c062017-12-06 10:34:51 -08004783 ? rtp_data_channel_->SetLocalContent(data_desc, type, &error)
4784 : rtp_data_channel_->SetRemoteContent(data_desc, type,
Steve Antoned10bd92017-12-05 10:52:59 -08004785 &error);
4786 if (!success) {
4787 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
4788 std::move(error));
4789 }
Steve Anton75737c02017-11-06 10:37:17 -08004790 }
4791 }
4792 }
Steve Antoned10bd92017-12-05 10:52:59 -08004793
Steve Anton75737c02017-11-06 10:37:17 -08004794 // Need complete offer/answer with an SCTP m= section before starting SCTP,
4795 // according to https://tools.ietf.org/html/draft-ietf-mmusic-sctp-sdp-19
4796 if (sctp_transport_ && local_description() && remote_description() &&
4797 cricket::GetFirstDataContent(local_description()->description()) &&
4798 cricket::GetFirstDataContent(remote_description()->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08004799 bool success = network_thread()->Invoke<bool>(
Steve Anton75737c02017-11-06 10:37:17 -08004800 RTC_FROM_HERE,
4801 rtc::Bind(&PeerConnection::PushdownSctpParameters_n, this, source));
Steve Anton8a006912017-12-04 15:25:56 -08004802 if (!success) {
4803 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
4804 "Failed to push down SCTP parameters.");
4805 }
Steve Anton75737c02017-11-06 10:37:17 -08004806 }
Steve Antoned10bd92017-12-05 10:52:59 -08004807
Steve Anton8a006912017-12-04 15:25:56 -08004808 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08004809}
4810
4811bool PeerConnection::PushdownSctpParameters_n(cricket::ContentSource source) {
4812 RTC_DCHECK(network_thread()->IsCurrent());
4813 RTC_DCHECK(local_description());
4814 RTC_DCHECK(remote_description());
4815 // Apply the SCTP port (which is hidden inside a DataCodec structure...)
4816 // When we support "max-message-size", that would also be pushed down here.
4817 return sctp_transport_->Start(
4818 GetSctpPort(local_description()->description()),
4819 GetSctpPort(remote_description()->description()));
4820}
4821
Steve Anton8a006912017-12-04 15:25:56 -08004822RTCError PeerConnection::PushdownTransportDescription(
4823 cricket::ContentSource source,
Steve Anton3828c062017-12-06 10:34:51 -08004824 SdpType type) {
Steve Anton8a006912017-12-04 15:25:56 -08004825 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08004826
Zhi Huange830e682018-03-30 10:48:35 -07004827 if (source == cricket::CS_LOCAL) {
4828 const SessionDescriptionInterface* sdesc = local_description();
4829 RTC_DCHECK(sdesc);
4830 return transport_controller_->SetLocalDescription(type,
4831 sdesc->description());
4832 } else {
4833 const SessionDescriptionInterface* sdesc = remote_description();
4834 RTC_DCHECK(sdesc);
4835 return transport_controller_->SetRemoteDescription(type,
4836 sdesc->description());
Steve Anton75737c02017-11-06 10:37:17 -08004837 }
Steve Anton75737c02017-11-06 10:37:17 -08004838}
4839
4840bool PeerConnection::GetTransportDescription(
4841 const SessionDescription* description,
4842 const std::string& content_name,
4843 cricket::TransportDescription* tdesc) {
4844 if (!description || !tdesc) {
4845 return false;
4846 }
4847 const TransportInfo* transport_info =
4848 description->GetTransportInfoByName(content_name);
4849 if (!transport_info) {
4850 return false;
4851 }
4852 *tdesc = transport_info->description;
4853 return true;
4854}
4855
Steve Anton75737c02017-11-06 10:37:17 -08004856cricket::IceConfig PeerConnection::ParseIceConfig(
4857 const PeerConnectionInterface::RTCConfiguration& config) const {
4858 cricket::ContinualGatheringPolicy gathering_policy;
4859 // TODO(honghaiz): Add the third continual gathering policy in
4860 // PeerConnectionInterface and map it to GATHER_CONTINUALLY_AND_RECOVER.
4861 switch (config.continual_gathering_policy) {
4862 case PeerConnectionInterface::GATHER_ONCE:
4863 gathering_policy = cricket::GATHER_ONCE;
4864 break;
4865 case PeerConnectionInterface::GATHER_CONTINUALLY:
4866 gathering_policy = cricket::GATHER_CONTINUALLY;
4867 break;
4868 default:
4869 RTC_NOTREACHED();
4870 gathering_policy = cricket::GATHER_ONCE;
4871 }
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08004872
Steve Anton75737c02017-11-06 10:37:17 -08004873 cricket::IceConfig ice_config;
Qingsi Wang866e08d2018-03-22 17:54:23 -07004874 ice_config.receiving_timeout = RTCConfigurationToIceConfigOptionalInt(
4875 config.ice_connection_receiving_timeout);
Steve Anton75737c02017-11-06 10:37:17 -08004876 ice_config.prioritize_most_likely_candidate_pairs =
4877 config.prioritize_most_likely_ice_candidate_pairs;
4878 ice_config.backup_connection_ping_interval =
Qingsi Wang866e08d2018-03-22 17:54:23 -07004879 RTCConfigurationToIceConfigOptionalInt(
4880 config.ice_backup_candidate_pair_ping_interval);
Steve Anton75737c02017-11-06 10:37:17 -08004881 ice_config.continual_gathering_policy = gathering_policy;
4882 ice_config.presume_writable_when_fully_relayed =
4883 config.presume_writable_when_fully_relayed;
Qingsi Wange6826d22018-03-08 14:55:14 -08004884 ice_config.ice_check_interval_strong_connectivity =
4885 config.ice_check_interval_strong_connectivity;
4886 ice_config.ice_check_interval_weak_connectivity =
4887 config.ice_check_interval_weak_connectivity;
Steve Anton75737c02017-11-06 10:37:17 -08004888 ice_config.ice_check_min_interval = config.ice_check_min_interval;
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08004889 ice_config.stun_keepalive_interval = config.stun_candidate_keepalive_interval;
Steve Anton75737c02017-11-06 10:37:17 -08004890 ice_config.regather_all_networks_interval_range =
4891 config.ice_regather_interval_range;
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08004892 ice_config.network_preference = config.network_preference;
Steve Anton75737c02017-11-06 10:37:17 -08004893 return ice_config;
4894}
4895
Steve Anton75737c02017-11-06 10:37:17 -08004896bool PeerConnection::GetLocalTrackIdBySsrc(uint32_t ssrc,
4897 std::string* track_id) {
4898 if (!local_description()) {
4899 return false;
4900 }
4901 return webrtc::GetTrackIdBySsrc(local_description()->description(), ssrc,
4902 track_id);
4903}
4904
4905bool PeerConnection::GetRemoteTrackIdBySsrc(uint32_t ssrc,
4906 std::string* track_id) {
4907 if (!remote_description()) {
4908 return false;
4909 }
4910 return webrtc::GetTrackIdBySsrc(remote_description()->description(), ssrc,
4911 track_id);
4912}
4913
4914bool PeerConnection::SendData(const cricket::SendDataParams& params,
4915 const rtc::CopyOnWriteBuffer& payload,
4916 cricket::SendDataResult* result) {
4917 if (!rtp_data_channel_ && !sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004918 RTC_LOG(LS_ERROR) << "SendData called when rtp_data_channel_ "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004919 "and sctp_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08004920 return false;
4921 }
4922 return rtp_data_channel_
4923 ? rtp_data_channel_->SendData(params, payload, result)
4924 : network_thread()->Invoke<bool>(
4925 RTC_FROM_HERE,
4926 Bind(&cricket::SctpTransportInternal::SendData,
4927 sctp_transport_.get(), params, payload, result));
4928}
4929
4930bool PeerConnection::ConnectDataChannel(DataChannel* webrtc_data_channel) {
4931 if (!rtp_data_channel_ && !sctp_transport_) {
4932 // Don't log an error here, because DataChannels are expected to call
4933 // ConnectDataChannel in this state. It's the only way to initially tell
4934 // whether or not the underlying transport is ready.
4935 return false;
4936 }
4937 if (rtp_data_channel_) {
4938 rtp_data_channel_->SignalReadyToSendData.connect(
4939 webrtc_data_channel, &DataChannel::OnChannelReady);
4940 rtp_data_channel_->SignalDataReceived.connect(webrtc_data_channel,
4941 &DataChannel::OnDataReceived);
4942 } else {
4943 SignalSctpReadyToSendData.connect(webrtc_data_channel,
4944 &DataChannel::OnChannelReady);
4945 SignalSctpDataReceived.connect(webrtc_data_channel,
4946 &DataChannel::OnDataReceived);
4947 SignalSctpStreamClosedRemotely.connect(
4948 webrtc_data_channel, &DataChannel::OnStreamClosedRemotely);
4949 }
4950 return true;
4951}
4952
4953void PeerConnection::DisconnectDataChannel(DataChannel* webrtc_data_channel) {
4954 if (!rtp_data_channel_ && !sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004955 RTC_LOG(LS_ERROR)
4956 << "DisconnectDataChannel called when rtp_data_channel_ and "
4957 "sctp_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08004958 return;
4959 }
4960 if (rtp_data_channel_) {
4961 rtp_data_channel_->SignalReadyToSendData.disconnect(webrtc_data_channel);
4962 rtp_data_channel_->SignalDataReceived.disconnect(webrtc_data_channel);
4963 } else {
4964 SignalSctpReadyToSendData.disconnect(webrtc_data_channel);
4965 SignalSctpDataReceived.disconnect(webrtc_data_channel);
4966 SignalSctpStreamClosedRemotely.disconnect(webrtc_data_channel);
4967 }
4968}
4969
4970void PeerConnection::AddSctpDataStream(int sid) {
4971 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004972 RTC_LOG(LS_ERROR)
4973 << "AddSctpDataStream called when sctp_transport_ is NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08004974 return;
4975 }
4976 network_thread()->Invoke<void>(
4977 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::OpenStream,
4978 sctp_transport_.get(), sid));
4979}
4980
4981void PeerConnection::RemoveSctpDataStream(int sid) {
4982 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004983 RTC_LOG(LS_ERROR) << "RemoveSctpDataStream called when sctp_transport_ is "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004984 "NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08004985 return;
4986 }
4987 network_thread()->Invoke<void>(
4988 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::ResetStream,
4989 sctp_transport_.get(), sid));
4990}
4991
4992bool PeerConnection::ReadyToSendData() const {
4993 return (rtp_data_channel_ && rtp_data_channel_->ready_to_send_data()) ||
4994 sctp_ready_to_send_data_;
4995}
4996
Zhi Huange830e682018-03-30 10:48:35 -07004997rtc::Optional<std::string> PeerConnection::sctp_transport_name() const {
4998 if (sctp_mid_ && transport_controller_) {
4999 auto dtls_transport = transport_controller_->GetDtlsTransport(*sctp_mid_);
5000 if (dtls_transport) {
5001 return dtls_transport->transport_name();
5002 }
5003 return rtc::Optional<std::string>();
5004 }
5005 return rtc::Optional<std::string>();
5006}
5007
Qingsi Wang72a43a12018-02-20 16:03:18 -08005008cricket::CandidateStatsList PeerConnection::GetPooledCandidateStats() const {
5009 cricket::CandidateStatsList candidate_states_list;
5010 port_allocator_->GetCandidateStatsFromPooledSessions(&candidate_states_list);
5011 return candidate_states_list;
5012}
5013
Steve Anton5dfde182018-02-06 10:34:40 -08005014std::map<std::string, std::string> PeerConnection::GetTransportNamesByMid()
5015 const {
5016 std::map<std::string, std::string> transport_names_by_mid;
5017 for (auto transceiver : transceivers_) {
5018 cricket::BaseChannel* channel = transceiver->internal()->channel();
5019 if (channel) {
5020 transport_names_by_mid[channel->content_name()] =
5021 channel->transport_name();
5022 }
Steve Anton75737c02017-11-06 10:37:17 -08005023 }
Steve Anton5dfde182018-02-06 10:34:40 -08005024 if (rtp_data_channel_) {
5025 transport_names_by_mid[rtp_data_channel_->content_name()] =
5026 rtp_data_channel_->transport_name();
Steve Anton75737c02017-11-06 10:37:17 -08005027 }
5028 if (sctp_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07005029 rtc::Optional<std::string> transport_name = sctp_transport_name();
5030 RTC_DCHECK(transport_name);
5031 transport_names_by_mid[*sctp_mid_] = *transport_name;
Steve Anton75737c02017-11-06 10:37:17 -08005032 }
Steve Anton5dfde182018-02-06 10:34:40 -08005033 return transport_names_by_mid;
Steve Anton75737c02017-11-06 10:37:17 -08005034}
5035
Steve Anton5dfde182018-02-06 10:34:40 -08005036std::map<std::string, cricket::TransportStats>
5037PeerConnection::GetTransportStatsByNames(
5038 const std::set<std::string>& transport_names) {
5039 if (!network_thread()->IsCurrent()) {
5040 return network_thread()
5041 ->Invoke<std::map<std::string, cricket::TransportStats>>(
5042 RTC_FROM_HERE,
5043 [&] { return GetTransportStatsByNames(transport_names); });
Steve Anton75737c02017-11-06 10:37:17 -08005044 }
Steve Anton5dfde182018-02-06 10:34:40 -08005045 std::map<std::string, cricket::TransportStats> transport_stats_by_name;
5046 for (const std::string& transport_name : transport_names) {
5047 cricket::TransportStats transport_stats;
5048 bool success =
5049 transport_controller_->GetStats(transport_name, &transport_stats);
5050 if (success) {
5051 transport_stats_by_name[transport_name] = std::move(transport_stats);
5052 } else {
5053 RTC_LOG(LS_ERROR) << "Failed to get transport stats for transport_name="
5054 << transport_name;
5055 }
5056 }
5057 return transport_stats_by_name;
Steve Anton75737c02017-11-06 10:37:17 -08005058}
5059
5060bool PeerConnection::GetLocalCertificate(
5061 const std::string& transport_name,
5062 rtc::scoped_refptr<rtc::RTCCertificate>* certificate) {
Zhi Huange830e682018-03-30 10:48:35 -07005063 if (!certificate) {
5064 return false;
5065 }
5066 *certificate = transport_controller_->GetLocalCertificate(transport_name);
5067 return *certificate != nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08005068}
5069
Taylor Brandstetterc3928662018-02-23 13:04:51 -08005070std::unique_ptr<rtc::SSLCertChain> PeerConnection::GetRemoteSSLCertChain(
Steve Anton75737c02017-11-06 10:37:17 -08005071 const std::string& transport_name) {
Taylor Brandstetterc3928662018-02-23 13:04:51 -08005072 return transport_controller_->GetRemoteSSLCertChain(transport_name);
Steve Anton75737c02017-11-06 10:37:17 -08005073}
5074
5075cricket::DataChannelType PeerConnection::data_channel_type() const {
5076 return data_channel_type_;
5077}
5078
5079bool PeerConnection::IceRestartPending(const std::string& content_name) const {
5080 return pending_ice_restarts_.find(content_name) !=
5081 pending_ice_restarts_.end();
5082}
5083
Steve Anton75737c02017-11-06 10:37:17 -08005084bool PeerConnection::NeedsIceRestart(const std::string& content_name) const {
5085 return transport_controller_->NeedsIceRestart(content_name);
5086}
5087
5088void PeerConnection::OnCertificateReady(
5089 const rtc::scoped_refptr<rtc::RTCCertificate>& certificate) {
5090 transport_controller_->SetLocalCertificate(certificate);
5091}
5092
5093void PeerConnection::OnDtlsSrtpSetupFailure(cricket::BaseChannel*, bool rtcp) {
Steve Antonf8470812017-12-04 10:46:21 -08005094 SetSessionError(SessionError::kTransport,
5095 rtcp ? kDtlsSrtpSetupFailureRtcp : kDtlsSrtpSetupFailureRtp);
Steve Anton75737c02017-11-06 10:37:17 -08005096}
5097
5098void PeerConnection::OnTransportControllerConnectionState(
5099 cricket::IceConnectionState state) {
5100 switch (state) {
5101 case cricket::kIceConnectionConnecting:
5102 // If the current state is Connected or Completed, then there were
5103 // writable channels but now there are not, so the next state must
5104 // be Disconnected.
5105 // kIceConnectionConnecting is currently used as the default,
5106 // un-connected state by the TransportController, so its only use is
5107 // detecting disconnections.
5108 if (ice_connection_state_ ==
5109 PeerConnectionInterface::kIceConnectionConnected ||
5110 ice_connection_state_ ==
5111 PeerConnectionInterface::kIceConnectionCompleted) {
5112 SetIceConnectionState(
5113 PeerConnectionInterface::kIceConnectionDisconnected);
5114 }
5115 break;
5116 case cricket::kIceConnectionFailed:
5117 SetIceConnectionState(PeerConnectionInterface::kIceConnectionFailed);
5118 break;
5119 case cricket::kIceConnectionConnected:
Mirko Bonadei675513b2017-11-09 11:09:25 +01005120 RTC_LOG(LS_INFO) << "Changing to ICE connected state because "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005121 "all transports are writable.";
Steve Anton75737c02017-11-06 10:37:17 -08005122 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
5123 break;
5124 case cricket::kIceConnectionCompleted:
Mirko Bonadei675513b2017-11-09 11:09:25 +01005125 RTC_LOG(LS_INFO) << "Changing to ICE completed state because "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005126 "all transports are complete.";
Steve Anton75737c02017-11-06 10:37:17 -08005127 if (ice_connection_state_ !=
5128 PeerConnectionInterface::kIceConnectionConnected) {
5129 // If jumping directly from "checking" to "connected",
5130 // signal "connected" first.
5131 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
5132 }
5133 SetIceConnectionState(PeerConnectionInterface::kIceConnectionCompleted);
5134 if (metrics_observer()) {
5135 ReportTransportStats();
5136 }
5137 break;
5138 default:
5139 RTC_NOTREACHED();
5140 }
5141}
5142
5143void PeerConnection::OnTransportControllerCandidatesGathered(
5144 const std::string& transport_name,
5145 const cricket::Candidates& candidates) {
5146 RTC_DCHECK(signaling_thread()->IsCurrent());
5147 int sdp_mline_index;
5148 if (!GetLocalCandidateMediaIndex(transport_name, &sdp_mline_index)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005149 RTC_LOG(LS_ERROR)
5150 << "OnTransportControllerCandidatesGathered: content name "
5151 << transport_name << " not found";
Steve Anton75737c02017-11-06 10:37:17 -08005152 return;
5153 }
5154
5155 for (cricket::Candidates::const_iterator citer = candidates.begin();
5156 citer != candidates.end(); ++citer) {
5157 // Use transport_name as the candidate media id.
5158 std::unique_ptr<JsepIceCandidate> candidate(
5159 new JsepIceCandidate(transport_name, sdp_mline_index, *citer));
5160 if (local_description()) {
5161 mutable_local_description()->AddCandidate(candidate.get());
5162 }
5163 OnIceCandidate(std::move(candidate));
5164 }
5165}
5166
5167void PeerConnection::OnTransportControllerCandidatesRemoved(
5168 const std::vector<cricket::Candidate>& candidates) {
5169 RTC_DCHECK(signaling_thread()->IsCurrent());
5170 // Sanity check.
5171 for (const cricket::Candidate& candidate : candidates) {
5172 if (candidate.transport_name().empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005173 RTC_LOG(LS_ERROR) << "OnTransportControllerCandidatesRemoved: "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005174 "empty content name in candidate "
Mirko Bonadei675513b2017-11-09 11:09:25 +01005175 << candidate.ToString();
Steve Anton75737c02017-11-06 10:37:17 -08005176 return;
5177 }
5178 }
5179
5180 if (local_description()) {
5181 mutable_local_description()->RemoveCandidates(candidates);
5182 }
5183 OnIceCandidatesRemoved(candidates);
5184}
5185
5186void PeerConnection::OnTransportControllerDtlsHandshakeError(
5187 rtc::SSLHandshakeError error) {
5188 if (metrics_observer()) {
5189 metrics_observer()->IncrementEnumCounter(
5190 webrtc::kEnumCounterDtlsHandshakeError, static_cast<int>(error),
5191 static_cast<int>(rtc::SSLHandshakeError::MAX_VALUE));
5192 }
5193}
5194
Steve Antoned10bd92017-12-05 10:52:59 -08005195void PeerConnection::EnableSending() {
5196 for (auto transceiver : transceivers_) {
5197 cricket::BaseChannel* channel = transceiver->internal()->channel();
5198 if (channel && !channel->enabled()) {
5199 channel->Enable(true);
5200 }
Steve Anton75737c02017-11-06 10:37:17 -08005201 }
5202
Steve Anton4171afb2017-11-20 10:20:22 -08005203 if (rtp_data_channel_ && !rtp_data_channel_->enabled()) {
Steve Anton75737c02017-11-06 10:37:17 -08005204 rtp_data_channel_->Enable(true);
Steve Anton4171afb2017-11-20 10:20:22 -08005205 }
Steve Anton75737c02017-11-06 10:37:17 -08005206}
5207
5208// Returns the media index for a local ice candidate given the content name.
5209bool PeerConnection::GetLocalCandidateMediaIndex(
5210 const std::string& content_name,
5211 int* sdp_mline_index) {
5212 if (!local_description() || !sdp_mline_index) {
5213 return false;
5214 }
5215
5216 bool content_found = false;
5217 const ContentInfos& contents = local_description()->description()->contents();
5218 for (size_t index = 0; index < contents.size(); ++index) {
5219 if (contents[index].name == content_name) {
5220 *sdp_mline_index = static_cast<int>(index);
5221 content_found = true;
5222 break;
5223 }
5224 }
5225 return content_found;
5226}
5227
5228bool PeerConnection::UseCandidatesInSessionDescription(
5229 const SessionDescriptionInterface* remote_desc) {
5230 if (!remote_desc) {
5231 return true;
5232 }
5233 bool ret = true;
5234
5235 for (size_t m = 0; m < remote_desc->number_of_mediasections(); ++m) {
5236 const IceCandidateCollection* candidates = remote_desc->candidates(m);
5237 for (size_t n = 0; n < candidates->count(); ++n) {
5238 const IceCandidateInterface* candidate = candidates->at(n);
5239 bool valid = false;
5240 if (!ReadyToUseRemoteCandidate(candidate, remote_desc, &valid)) {
5241 if (valid) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005242 RTC_LOG(LS_INFO)
5243 << "UseCandidatesInSessionDescription: Not ready to use "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005244 "candidate.";
Steve Anton75737c02017-11-06 10:37:17 -08005245 }
5246 continue;
5247 }
5248 ret = UseCandidate(candidate);
5249 if (!ret) {
5250 break;
5251 }
5252 }
5253 }
5254 return ret;
5255}
5256
5257bool PeerConnection::UseCandidate(const IceCandidateInterface* candidate) {
5258 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
5259 size_t remote_content_size =
5260 remote_description()->description()->contents().size();
5261 if (mediacontent_index >= remote_content_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005262 RTC_LOG(LS_ERROR) << "UseCandidate: Invalid candidate media index.";
Steve Anton75737c02017-11-06 10:37:17 -08005263 return false;
5264 }
5265
5266 cricket::ContentInfo content =
5267 remote_description()->description()->contents()[mediacontent_index];
5268 std::vector<cricket::Candidate> candidates;
5269 candidates.push_back(candidate->candidate());
5270 // Invoking BaseSession method to handle remote candidates.
Zhi Huange830e682018-03-30 10:48:35 -07005271 RTCError error =
5272 transport_controller_->AddRemoteCandidates(content.name, candidates);
5273 if (error.ok()) {
Steve Anton75737c02017-11-06 10:37:17 -08005274 // Candidates successfully submitted for checking.
5275 if (ice_connection_state_ == PeerConnectionInterface::kIceConnectionNew ||
5276 ice_connection_state_ ==
5277 PeerConnectionInterface::kIceConnectionDisconnected) {
5278 // If state is New, then the session has just gotten its first remote ICE
5279 // candidates, so go to Checking.
5280 // If state is Disconnected, the session is re-using old candidates or
5281 // receiving additional ones, so go to Checking.
5282 // If state is Connected, stay Connected.
5283 // TODO(bemasc): If state is Connected, and the new candidates are for a
5284 // newly added transport, then the state actually _should_ move to
5285 // checking. Add a way to distinguish that case.
5286 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
5287 }
5288 // TODO(bemasc): If state is Completed, go back to Connected.
Zhi Huange830e682018-03-30 10:48:35 -07005289 } else if (error.message()) {
5290 RTC_LOG(LS_WARNING) << error.message();
Steve Anton75737c02017-11-06 10:37:17 -08005291 }
5292 return true;
5293}
5294
5295void PeerConnection::RemoveUnusedChannels(const SessionDescription* desc) {
Steve Anton75737c02017-11-06 10:37:17 -08005296 // Destroy video channel first since it may have a pointer to the
5297 // voice channel.
5298 const cricket::ContentInfo* video_info = cricket::GetFirstVideoContent(desc);
Steve Anton6fec8802017-12-04 10:37:29 -08005299 if (!video_info || video_info->rejected) {
5300 DestroyTransceiverChannel(GetVideoTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08005301 }
5302
Steve Anton6fec8802017-12-04 10:37:29 -08005303 const cricket::ContentInfo* audio_info = cricket::GetFirstAudioContent(desc);
5304 if (!audio_info || audio_info->rejected) {
5305 DestroyTransceiverChannel(GetAudioTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08005306 }
5307
5308 const cricket::ContentInfo* data_info = cricket::GetFirstDataContent(desc);
5309 if (!data_info || data_info->rejected) {
Steve Anton6fec8802017-12-04 10:37:29 -08005310 DestroyDataChannel();
Steve Anton75737c02017-11-06 10:37:17 -08005311 }
5312}
5313
Steve Antondcc3c022017-12-22 16:02:54 -08005314RTCErrorOr<const cricket::ContentGroup*> PeerConnection::GetEarlyBundleGroup(
5315 const SessionDescription& desc) const {
Steve Anton75737c02017-11-06 10:37:17 -08005316 const cricket::ContentGroup* bundle_group = nullptr;
5317 if (configuration_.bundle_policy ==
5318 PeerConnectionInterface::kBundlePolicyMaxBundle) {
Steve Antondcc3c022017-12-22 16:02:54 -08005319 bundle_group = desc.GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton75737c02017-11-06 10:37:17 -08005320 if (!bundle_group) {
Steve Anton8a006912017-12-04 15:25:56 -08005321 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5322 "max-bundle configured but session description "
5323 "has no BUNDLE group");
Steve Anton75737c02017-11-06 10:37:17 -08005324 }
5325 }
Steve Antondcc3c022017-12-22 16:02:54 -08005326 return std::move(bundle_group);
5327}
5328
5329RTCError PeerConnection::CreateChannels(const SessionDescription& desc) {
Zhi Huange830e682018-03-30 10:48:35 -07005330 // Creating the media channels. Transports should already have been created
5331 // at this point.
Steve Antondcc3c022017-12-22 16:02:54 -08005332 const cricket::ContentInfo* voice = cricket::GetFirstAudioContent(&desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08005333 if (voice && !voice->rejected &&
5334 !GetAudioTransceiver()->internal()->channel()) {
Zhi Huange830e682018-03-30 10:48:35 -07005335 cricket::VoiceChannel* voice_channel = CreateVoiceChannel(voice->name);
Steve Antoneda6ccd2017-12-04 10:21:55 -08005336 if (!voice_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08005337 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5338 "Failed to create voice channel.");
Steve Antoneda6ccd2017-12-04 10:21:55 -08005339 }
5340 GetAudioTransceiver()->internal()->SetChannel(voice_channel);
5341 }
5342
Steve Antondcc3c022017-12-22 16:02:54 -08005343 const cricket::ContentInfo* video = cricket::GetFirstVideoContent(&desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08005344 if (video && !video->rejected &&
5345 !GetVideoTransceiver()->internal()->channel()) {
Zhi Huange830e682018-03-30 10:48:35 -07005346 cricket::VideoChannel* video_channel = CreateVideoChannel(video->name);
Steve Antoneda6ccd2017-12-04 10:21:55 -08005347 if (!video_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08005348 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5349 "Failed to create video channel.");
Steve Anton75737c02017-11-06 10:37:17 -08005350 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005351 GetVideoTransceiver()->internal()->SetChannel(video_channel);
Steve Anton75737c02017-11-06 10:37:17 -08005352 }
5353
Steve Antondcc3c022017-12-22 16:02:54 -08005354 const cricket::ContentInfo* data = cricket::GetFirstDataContent(&desc);
Steve Anton75737c02017-11-06 10:37:17 -08005355 if (data_channel_type_ != cricket::DCT_NONE && data && !data->rejected &&
5356 !rtp_data_channel_ && !sctp_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07005357 if (!CreateDataChannel(data->name)) {
Steve Anton8a006912017-12-04 15:25:56 -08005358 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5359 "Failed to create data channel.");
Steve Anton75737c02017-11-06 10:37:17 -08005360 }
5361 }
5362
Steve Anton8a006912017-12-04 15:25:56 -08005363 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08005364}
5365
Steve Anton4171afb2017-11-20 10:20:22 -08005366// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08005367cricket::VoiceChannel* PeerConnection::CreateVoiceChannel(
Zhi Huange830e682018-03-30 10:48:35 -07005368 const std::string& mid) {
5369 RtpTransportInternal* rtp_transport =
5370 transport_controller_->GetRtpTransport(mid);
5371 RTC_DCHECK(rtp_transport);
Steve Anton75737c02017-11-06 10:37:17 -08005372 cricket::VoiceChannel* voice_channel = channel_manager()->CreateVoiceChannel(
Zhi Huange830e682018-03-30 10:48:35 -07005373 call_.get(), configuration_.media_config, rtp_transport,
5374 signaling_thread(), mid, SrtpRequired(),
5375 factory_->options().crypto_options, audio_options_);
Steve Anton75737c02017-11-06 10:37:17 -08005376 if (!voice_channel) {
Steve Antoneda6ccd2017-12-04 10:21:55 -08005377 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08005378 }
Steve Anton75737c02017-11-06 10:37:17 -08005379 voice_channel->SignalDtlsSrtpSetupFailure.connect(
5380 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08005381 voice_channel->SignalSentPacket.connect(this,
5382 &PeerConnection::OnSentPacket_w);
Zhi Huange830e682018-03-30 10:48:35 -07005383 voice_channel->SetRtpTransport(rtp_transport);
5384 if (factory_->options().disable_encryption) {
5385 voice_channel->DisableEncryption(true);
5386 }
Steve Antondb67ba12018-03-19 17:41:42 -07005387 if (uma_observer_) {
5388 voice_channel->SetMetricsObserver(uma_observer_);
5389 }
Steve Anton4171afb2017-11-20 10:20:22 -08005390
Steve Antoneda6ccd2017-12-04 10:21:55 -08005391 return voice_channel;
Steve Anton75737c02017-11-06 10:37:17 -08005392}
5393
Steve Anton4171afb2017-11-20 10:20:22 -08005394// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08005395cricket::VideoChannel* PeerConnection::CreateVideoChannel(
Zhi Huange830e682018-03-30 10:48:35 -07005396 const std::string& mid) {
5397 RtpTransportInternal* rtp_transport =
5398 transport_controller_->GetRtpTransport(mid);
5399 RTC_DCHECK(rtp_transport);
Steve Anton75737c02017-11-06 10:37:17 -08005400 cricket::VideoChannel* video_channel = channel_manager()->CreateVideoChannel(
Zhi Huange830e682018-03-30 10:48:35 -07005401 call_.get(), configuration_.media_config, rtp_transport,
5402 signaling_thread(), mid, SrtpRequired(),
5403 factory_->options().crypto_options, video_options_);
Steve Anton75737c02017-11-06 10:37:17 -08005404 if (!video_channel) {
Steve Antoneda6ccd2017-12-04 10:21:55 -08005405 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08005406 }
Steve Anton75737c02017-11-06 10:37:17 -08005407 video_channel->SignalDtlsSrtpSetupFailure.connect(
5408 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08005409 video_channel->SignalSentPacket.connect(this,
5410 &PeerConnection::OnSentPacket_w);
Zhi Huange830e682018-03-30 10:48:35 -07005411 video_channel->SetRtpTransport(rtp_transport);
5412 if (factory_->options().disable_encryption) {
5413 video_channel->DisableEncryption(true);
5414 }
Steve Antondb67ba12018-03-19 17:41:42 -07005415 if (uma_observer_) {
5416 video_channel->SetMetricsObserver(uma_observer_);
5417 }
Steve Anton4171afb2017-11-20 10:20:22 -08005418
Steve Antoneda6ccd2017-12-04 10:21:55 -08005419 return video_channel;
Steve Anton75737c02017-11-06 10:37:17 -08005420}
5421
Zhi Huange830e682018-03-30 10:48:35 -07005422bool PeerConnection::CreateDataChannel(const std::string& mid) {
Steve Anton75737c02017-11-06 10:37:17 -08005423 bool sctp = (data_channel_type_ == cricket::DCT_SCTP);
5424 if (sctp) {
5425 if (!sctp_factory_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005426 RTC_LOG(LS_ERROR)
Steve Anton75737c02017-11-06 10:37:17 -08005427 << "Trying to create SCTP transport, but didn't compile with "
5428 "SCTP support (HAVE_SCTP)";
5429 return false;
5430 }
5431 if (!network_thread()->Invoke<bool>(
Zhi Huange830e682018-03-30 10:48:35 -07005432 RTC_FROM_HERE,
5433 rtc::Bind(&PeerConnection::CreateSctpTransport_n, this, mid))) {
Steve Anton75737c02017-11-06 10:37:17 -08005434 return false;
5435 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005436 for (const auto& channel : sctp_data_channels_) {
5437 channel->OnTransportChannelCreated();
5438 }
Steve Anton75737c02017-11-06 10:37:17 -08005439 } else {
Zhi Huange830e682018-03-30 10:48:35 -07005440 RtpTransportInternal* rtp_transport =
5441 transport_controller_->GetRtpTransport(mid);
5442 RTC_DCHECK(rtp_transport);
Steve Anton75737c02017-11-06 10:37:17 -08005443 rtp_data_channel_ = channel_manager()->CreateRtpDataChannel(
Zhi Huange830e682018-03-30 10:48:35 -07005444 configuration_.media_config, rtp_transport, signaling_thread(), mid,
5445 SrtpRequired(), factory_->options().crypto_options);
Steve Anton75737c02017-11-06 10:37:17 -08005446 if (!rtp_data_channel_) {
Steve Anton75737c02017-11-06 10:37:17 -08005447 return false;
5448 }
Steve Anton75737c02017-11-06 10:37:17 -08005449 rtp_data_channel_->SignalDtlsSrtpSetupFailure.connect(
5450 this, &PeerConnection::OnDtlsSrtpSetupFailure);
5451 rtp_data_channel_->SignalSentPacket.connect(
5452 this, &PeerConnection::OnSentPacket_w);
Zhi Huange830e682018-03-30 10:48:35 -07005453 rtp_data_channel_->SetRtpTransport(rtp_transport);
5454 if (factory_->options().disable_encryption) {
5455 rtp_data_channel_->DisableEncryption(true);
5456 }
Steve Antondb67ba12018-03-19 17:41:42 -07005457 if (uma_observer_) {
5458 rtp_data_channel_->SetMetricsObserver(uma_observer_);
5459 }
Steve Anton75737c02017-11-06 10:37:17 -08005460 }
5461
Steve Anton75737c02017-11-06 10:37:17 -08005462 return true;
5463}
5464
5465Call::Stats PeerConnection::GetCallStats() {
5466 if (!worker_thread()->IsCurrent()) {
5467 return worker_thread()->Invoke<Call::Stats>(
5468 RTC_FROM_HERE, rtc::Bind(&PeerConnection::GetCallStats, this));
5469 }
5470 if (call_) {
5471 return call_->GetStats();
5472 } else {
5473 return Call::Stats();
5474 }
5475}
5476
Zhi Huange830e682018-03-30 10:48:35 -07005477bool PeerConnection::CreateSctpTransport_n(const std::string& mid) {
Steve Anton75737c02017-11-06 10:37:17 -08005478 RTC_DCHECK(network_thread()->IsCurrent());
5479 RTC_DCHECK(sctp_factory_);
5480 cricket::DtlsTransportInternal* tc =
Zhi Huange830e682018-03-30 10:48:35 -07005481 transport_controller_->GetDtlsTransport(mid);
5482 RTC_DCHECK(tc);
Steve Anton75737c02017-11-06 10:37:17 -08005483 sctp_transport_ = sctp_factory_->CreateSctpTransport(tc);
5484 RTC_DCHECK(sctp_transport_);
5485 sctp_invoker_.reset(new rtc::AsyncInvoker());
5486 sctp_transport_->SignalReadyToSendData.connect(
5487 this, &PeerConnection::OnSctpTransportReadyToSendData_n);
5488 sctp_transport_->SignalDataReceived.connect(
5489 this, &PeerConnection::OnSctpTransportDataReceived_n);
5490 sctp_transport_->SignalStreamClosedRemotely.connect(
5491 this, &PeerConnection::OnSctpStreamClosedRemotely_n);
Zhi Huange830e682018-03-30 10:48:35 -07005492 sctp_mid_ = mid;
Steve Anton75737c02017-11-06 10:37:17 -08005493 sctp_transport_->SetTransportChannel(tc);
Zhi Huange830e682018-03-30 10:48:35 -07005494 return true;
Steve Anton75737c02017-11-06 10:37:17 -08005495}
5496
5497void PeerConnection::DestroySctpTransport_n() {
5498 RTC_DCHECK(network_thread()->IsCurrent());
5499 sctp_transport_.reset(nullptr);
Zhi Huange830e682018-03-30 10:48:35 -07005500 sctp_mid_.reset();
Steve Anton75737c02017-11-06 10:37:17 -08005501 sctp_invoker_.reset(nullptr);
5502 sctp_ready_to_send_data_ = false;
5503}
5504
5505void PeerConnection::OnSctpTransportReadyToSendData_n() {
5506 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5507 RTC_DCHECK(network_thread()->IsCurrent());
5508 // Note: Cannot use rtc::Bind here because it will grab a reference to
5509 // PeerConnection and potentially cause PeerConnection to live longer than
5510 // expected. It is safe not to grab a reference since the sctp_invoker_ will
5511 // be destroyed before PeerConnection is destroyed, and at that point all
5512 // pending tasks will be cleared.
5513 sctp_invoker_->AsyncInvoke<void>(RTC_FROM_HERE, signaling_thread(), [this] {
5514 OnSctpTransportReadyToSendData_s(true);
5515 });
5516}
5517
5518void PeerConnection::OnSctpTransportReadyToSendData_s(bool ready) {
5519 RTC_DCHECK(signaling_thread()->IsCurrent());
5520 sctp_ready_to_send_data_ = ready;
5521 SignalSctpReadyToSendData(ready);
5522}
5523
5524void PeerConnection::OnSctpTransportDataReceived_n(
5525 const cricket::ReceiveDataParams& params,
5526 const rtc::CopyOnWriteBuffer& payload) {
5527 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5528 RTC_DCHECK(network_thread()->IsCurrent());
5529 // Note: Cannot use rtc::Bind here because it will grab a reference to
5530 // PeerConnection and potentially cause PeerConnection to live longer than
5531 // expected. It is safe not to grab a reference since the sctp_invoker_ will
5532 // be destroyed before PeerConnection is destroyed, and at that point all
5533 // pending tasks will be cleared.
5534 sctp_invoker_->AsyncInvoke<void>(
5535 RTC_FROM_HERE, signaling_thread(), [this, params, payload] {
5536 OnSctpTransportDataReceived_s(params, payload);
5537 });
5538}
5539
5540void PeerConnection::OnSctpTransportDataReceived_s(
5541 const cricket::ReceiveDataParams& params,
5542 const rtc::CopyOnWriteBuffer& payload) {
5543 RTC_DCHECK(signaling_thread()->IsCurrent());
5544 if (params.type == cricket::DMT_CONTROL && IsOpenMessage(payload)) {
5545 // Received OPEN message; parse and signal that a new data channel should
5546 // be created.
5547 std::string label;
5548 InternalDataChannelInit config;
5549 config.id = params.ssrc;
5550 if (!ParseDataChannelOpenMessage(payload, &label, &config)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005551 RTC_LOG(LS_WARNING) << "Failed to parse the OPEN message for sid "
5552 << params.ssrc;
Steve Anton75737c02017-11-06 10:37:17 -08005553 return;
5554 }
5555 config.open_handshake_role = InternalDataChannelInit::kAcker;
5556 OnDataChannelOpenMessage(label, config);
5557 } else {
5558 // Otherwise just forward the signal.
5559 SignalSctpDataReceived(params, payload);
5560 }
5561}
5562
5563void PeerConnection::OnSctpStreamClosedRemotely_n(int sid) {
5564 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5565 RTC_DCHECK(network_thread()->IsCurrent());
5566 sctp_invoker_->AsyncInvoke<void>(
5567 RTC_FROM_HERE, signaling_thread(),
5568 rtc::Bind(&sigslot::signal1<int>::operator(),
5569 &SignalSctpStreamClosedRemotely, sid));
5570}
5571
5572// Returns false if bundle is enabled and rtcp_mux is disabled.
5573bool PeerConnection::ValidateBundleSettings(const SessionDescription* desc) {
5574 bool bundle_enabled = desc->HasGroup(cricket::GROUP_TYPE_BUNDLE);
5575 if (!bundle_enabled)
5576 return true;
5577
5578 const cricket::ContentGroup* bundle_group =
5579 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
5580 RTC_DCHECK(bundle_group != NULL);
5581
5582 const cricket::ContentInfos& contents = desc->contents();
5583 for (cricket::ContentInfos::const_iterator citer = contents.begin();
5584 citer != contents.end(); ++citer) {
5585 const cricket::ContentInfo* content = (&*citer);
5586 RTC_DCHECK(content != NULL);
5587 if (bundle_group->HasContentName(content->name) && !content->rejected &&
Steve Anton5adfafd2017-12-20 16:34:00 -08005588 content->type == MediaProtocolType::kRtp) {
Steve Anton75737c02017-11-06 10:37:17 -08005589 if (!HasRtcpMuxEnabled(content))
5590 return false;
5591 }
5592 }
5593 // RTCP-MUX is enabled in all the contents.
5594 return true;
5595}
5596
5597bool PeerConnection::HasRtcpMuxEnabled(const cricket::ContentInfo* content) {
Steve Antonb1c1de12017-12-21 15:14:30 -08005598 return content->media_description()->rtcp_mux();
Steve Anton75737c02017-11-06 10:37:17 -08005599}
5600
Steve Anton8a006912017-12-04 15:25:56 -08005601RTCError PeerConnection::ValidateSessionDescription(
Steve Anton75737c02017-11-06 10:37:17 -08005602 const SessionDescriptionInterface* sdesc,
Steve Anton8a006912017-12-04 15:25:56 -08005603 cricket::ContentSource source) {
Steve Antonf8470812017-12-04 10:46:21 -08005604 if (session_error() != SessionError::kNone) {
Steve Anton8a006912017-12-04 15:25:56 -08005605 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
Steve Anton75737c02017-11-06 10:37:17 -08005606 }
5607
5608 if (!sdesc || !sdesc->description()) {
Steve Anton8a006912017-12-04 15:25:56 -08005609 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidSdp);
Steve Anton75737c02017-11-06 10:37:17 -08005610 }
5611
Steve Anton3828c062017-12-06 10:34:51 -08005612 SdpType type = sdesc->GetType();
5613 if ((source == cricket::CS_LOCAL && !ExpectSetLocalDescription(type)) ||
5614 (source == cricket::CS_REMOTE && !ExpectSetRemoteDescription(type))) {
Steve Anton8a006912017-12-04 15:25:56 -08005615 LOG_AND_RETURN_ERROR(
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01005616 RTCErrorType::INVALID_STATE,
Steve Anton8a006912017-12-04 15:25:56 -08005617 "Called in wrong state: " + GetSignalingStateString(signaling_state()));
Steve Anton75737c02017-11-06 10:37:17 -08005618 }
5619
5620 // Verify crypto settings.
5621 std::string crypto_error;
Steve Anton8a006912017-12-04 15:25:56 -08005622 if (webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED ||
5623 dtls_enabled_) {
Harald Alvestrand194939b2018-01-24 16:04:13 +01005624 RTCError crypto_error =
5625 VerifyCrypto(sdesc->description(), dtls_enabled_, uma_observer_);
Steve Anton8a006912017-12-04 15:25:56 -08005626 if (!crypto_error.ok()) {
5627 return crypto_error;
5628 }
Steve Anton75737c02017-11-06 10:37:17 -08005629 }
5630
5631 // Verify ice-ufrag and ice-pwd.
5632 if (!VerifyIceUfragPwdPresent(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08005633 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5634 kSdpWithoutIceUfragPwd);
Steve Anton75737c02017-11-06 10:37:17 -08005635 }
5636
5637 if (!ValidateBundleSettings(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08005638 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5639 kBundleWithoutRtcpMux);
Steve Anton75737c02017-11-06 10:37:17 -08005640 }
5641
5642 // TODO(skvlad): When the local rtcp-mux policy is Require, reject any
5643 // m-lines that do not rtcp-mux enabled.
5644
5645 // Verify m-lines in Answer when compared against Offer.
Steve Anton3828c062017-12-06 10:34:51 -08005646 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Seth Hampsonae8a90a2018-02-13 15:33:48 -08005647 // With an answer we want to compare the new answer session description with
5648 // the offer's session description from the current negotiation.
Steve Anton75737c02017-11-06 10:37:17 -08005649 const cricket::SessionDescription* offer_desc =
5650 (source == cricket::CS_LOCAL) ? remote_description()->description()
5651 : local_description()->description();
Seth Hampsonae8a90a2018-02-13 15:33:48 -08005652 if (!MediaSectionsHaveSameCount(*offer_desc, *sdesc->description()) ||
5653 !MediaSectionsInSameOrder(*offer_desc, nullptr, *sdesc->description(),
5654 type)) {
Steve Anton8a006912017-12-04 15:25:56 -08005655 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5656 kMlineMismatchInAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08005657 }
5658 } else {
Steve Anton75737c02017-11-06 10:37:17 -08005659 // The re-offers should respect the order of m= sections in current
5660 // description. See RFC3264 Section 8 paragraph 4 for more details.
Seth Hampsonae8a90a2018-02-13 15:33:48 -08005661 // With a re-offer, either the current local or current remote descriptions
5662 // could be the most up to date, so we would like to check against both of
5663 // them if they exist. It could be the case that one of them has a 0 port
5664 // for a media section, but the other does not. This is important to check
5665 // against in the case that we are recycling an m= section.
5666 const cricket::SessionDescription* current_desc = nullptr;
5667 const cricket::SessionDescription* secondary_current_desc = nullptr;
5668 if (local_description()) {
5669 current_desc = local_description()->description();
5670 if (remote_description()) {
5671 secondary_current_desc = remote_description()->description();
5672 }
5673 } else if (remote_description()) {
5674 current_desc = remote_description()->description();
5675 }
Steve Anton75737c02017-11-06 10:37:17 -08005676 if (current_desc &&
Seth Hampsonae8a90a2018-02-13 15:33:48 -08005677 !MediaSectionsInSameOrder(*current_desc, secondary_current_desc,
5678 *sdesc->description(), type)) {
Steve Anton8a006912017-12-04 15:25:56 -08005679 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5680 kMlineMismatchInSubsequentOffer);
Steve Anton75737c02017-11-06 10:37:17 -08005681 }
5682 }
5683
Steve Anton8a006912017-12-04 15:25:56 -08005684 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08005685}
5686
Steve Anton3828c062017-12-06 10:34:51 -08005687bool PeerConnection::ExpectSetLocalDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08005688 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08005689 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08005690 return (state == PeerConnectionInterface::kStable) ||
5691 (state == PeerConnectionInterface::kHaveLocalOffer);
Steve Anton20393062017-12-04 16:24:52 -08005692 } else {
Steve Anton3828c062017-12-06 10:34:51 -08005693 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08005694 return (state == PeerConnectionInterface::kHaveRemoteOffer) ||
5695 (state == PeerConnectionInterface::kHaveLocalPrAnswer);
5696 }
5697}
5698
Steve Anton3828c062017-12-06 10:34:51 -08005699bool PeerConnection::ExpectSetRemoteDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08005700 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08005701 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08005702 return (state == PeerConnectionInterface::kStable) ||
5703 (state == PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton20393062017-12-04 16:24:52 -08005704 } else {
Steve Anton3828c062017-12-06 10:34:51 -08005705 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08005706 return (state == PeerConnectionInterface::kHaveLocalOffer) ||
5707 (state == PeerConnectionInterface::kHaveRemotePrAnswer);
5708 }
5709}
5710
Steve Antonf8470812017-12-04 10:46:21 -08005711const char* PeerConnection::SessionErrorToString(SessionError error) const {
5712 switch (error) {
5713 case SessionError::kNone:
5714 return "ERROR_NONE";
5715 case SessionError::kContent:
5716 return "ERROR_CONTENT";
5717 case SessionError::kTransport:
5718 return "ERROR_TRANSPORT";
5719 }
5720 RTC_NOTREACHED();
5721 return "";
5722}
5723
Steve Anton75737c02017-11-06 10:37:17 -08005724std::string PeerConnection::GetSessionErrorMsg() {
5725 std::ostringstream desc;
Steve Antonf8470812017-12-04 10:46:21 -08005726 desc << kSessionError << SessionErrorToString(session_error()) << ". ";
5727 desc << kSessionErrorDesc << session_error_desc() << ".";
Steve Anton75737c02017-11-06 10:37:17 -08005728 return desc.str();
5729}
5730
Steve Anton8e20f172018-03-06 10:55:04 -08005731void PeerConnection::ReportSdpFormatReceived(
5732 const SessionDescriptionInterface& remote_offer) {
5733 if (!uma_observer_) {
5734 return;
5735 }
5736 int num_audio_mlines = 0;
5737 int num_video_mlines = 0;
5738 int num_audio_tracks = 0;
5739 int num_video_tracks = 0;
5740 for (const ContentInfo& content : remote_offer.description()->contents()) {
5741 cricket::MediaType media_type = content.media_description()->type();
5742 int num_tracks = std::max(
5743 1, static_cast<int>(content.media_description()->streams().size()));
5744 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
5745 num_audio_mlines += 1;
5746 num_audio_tracks += num_tracks;
5747 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
5748 num_video_mlines += 1;
5749 num_video_tracks += num_tracks;
5750 }
5751 }
5752 SdpFormatReceived format = kSdpFormatReceivedNoTracks;
5753 if (num_audio_mlines > 1 || num_video_mlines > 1) {
5754 format = kSdpFormatReceivedComplexUnifiedPlan;
5755 } else if (num_audio_tracks > 1 || num_video_tracks > 1) {
5756 format = kSdpFormatReceivedComplexPlanB;
5757 } else if (num_audio_tracks > 0 || num_video_tracks > 0) {
5758 format = kSdpFormatReceivedSimple;
5759 }
5760 uma_observer_->IncrementEnumCounter(kEnumCounterSdpFormatReceived, format,
5761 kSdpFormatReceivedMax);
5762}
5763
Steve Anton0ffaaa22018-02-23 10:31:30 -08005764void PeerConnection::ReportNegotiatedSdpSemantics(
5765 const SessionDescriptionInterface& answer) {
5766 if (!uma_observer_) {
5767 return;
5768 }
5769 switch (answer.description()->msid_signaling()) {
5770 case 0:
5771 uma_observer_->IncrementEnumCounter(kEnumCounterSdpSemanticNegotiated,
5772 kSdpSemanticNegotiatedNone,
5773 kSdpSemanticNegotiatedMax);
5774 break;
5775 case cricket::kMsidSignalingMediaSection:
5776 uma_observer_->IncrementEnumCounter(kEnumCounterSdpSemanticNegotiated,
5777 kSdpSemanticNegotiatedUnifiedPlan,
5778 kSdpSemanticNegotiatedMax);
5779 break;
5780 case cricket::kMsidSignalingSsrcAttribute:
5781 uma_observer_->IncrementEnumCounter(kEnumCounterSdpSemanticNegotiated,
5782 kSdpSemanticNegotiatedPlanB,
5783 kSdpSemanticNegotiatedMax);
5784 break;
5785 case cricket::kMsidSignalingMediaSection |
5786 cricket::kMsidSignalingSsrcAttribute:
5787 uma_observer_->IncrementEnumCounter(kEnumCounterSdpSemanticNegotiated,
5788 kSdpSemanticNegotiatedMixed,
5789 kSdpSemanticNegotiatedMax);
5790 break;
5791 default:
5792 RTC_NOTREACHED();
5793 }
5794}
5795
Steve Anton75737c02017-11-06 10:37:17 -08005796// We need to check the local/remote description for the Transport instead of
5797// the session, because a new Transport added during renegotiation may have
5798// them unset while the session has them set from the previous negotiation.
5799// Not doing so may trigger the auto generation of transport description and
5800// mess up DTLS identity information, ICE credential, etc.
5801bool PeerConnection::ReadyToUseRemoteCandidate(
5802 const IceCandidateInterface* candidate,
5803 const SessionDescriptionInterface* remote_desc,
5804 bool* valid) {
5805 *valid = true;
5806
5807 const SessionDescriptionInterface* current_remote_desc =
5808 remote_desc ? remote_desc : remote_description();
5809
5810 if (!current_remote_desc) {
5811 return false;
5812 }
5813
5814 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
5815 size_t remote_content_size =
5816 current_remote_desc->description()->contents().size();
5817 if (mediacontent_index >= remote_content_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005818 RTC_LOG(LS_ERROR)
5819 << "ReadyToUseRemoteCandidate: Invalid candidate media index "
5820 << mediacontent_index;
Steve Anton75737c02017-11-06 10:37:17 -08005821
5822 *valid = false;
5823 return false;
5824 }
5825
5826 cricket::ContentInfo content =
5827 current_remote_desc->description()->contents()[mediacontent_index];
5828
5829 const std::string transport_name = GetTransportName(content.name);
5830 if (transport_name.empty()) {
5831 return false;
5832 }
Zhi Huange830e682018-03-30 10:48:35 -07005833 return true;
Steve Anton75737c02017-11-06 10:37:17 -08005834}
5835
5836bool PeerConnection::SrtpRequired() const {
5837 return dtls_enabled_ ||
5838 webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED;
5839}
5840
5841void PeerConnection::OnTransportControllerGatheringState(
5842 cricket::IceGatheringState state) {
5843 RTC_DCHECK(signaling_thread()->IsCurrent());
5844 if (state == cricket::kIceGatheringGathering) {
5845 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringGathering);
5846 } else if (state == cricket::kIceGatheringComplete) {
5847 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringComplete);
5848 }
5849}
5850
5851void PeerConnection::ReportTransportStats() {
Steve Antonc7b964c2018-02-01 14:39:45 -08005852 std::map<std::string, std::set<cricket::MediaType>>
5853 media_types_by_transport_name;
5854 for (auto transceiver : transceivers_) {
5855 if (transceiver->internal()->channel()) {
5856 const std::string& transport_name =
5857 transceiver->internal()->channel()->transport_name();
5858 media_types_by_transport_name[transport_name].insert(
Steve Anton69470252018-02-09 11:43:08 -08005859 transceiver->media_type());
Steve Antonc7b964c2018-02-01 14:39:45 -08005860 }
Steve Anton75737c02017-11-06 10:37:17 -08005861 }
5862 if (rtp_data_channel()) {
Steve Antonc7b964c2018-02-01 14:39:45 -08005863 media_types_by_transport_name[rtp_data_channel()->transport_name()].insert(
5864 cricket::MEDIA_TYPE_DATA);
Steve Anton75737c02017-11-06 10:37:17 -08005865 }
Zhi Huange830e682018-03-30 10:48:35 -07005866
5867 rtc::Optional<std::string> transport_name = sctp_transport_name();
5868 if (transport_name) {
5869 media_types_by_transport_name[*transport_name].insert(
Steve Antonc7b964c2018-02-01 14:39:45 -08005870 cricket::MEDIA_TYPE_DATA);
Steve Anton75737c02017-11-06 10:37:17 -08005871 }
Zhi Huange830e682018-03-30 10:48:35 -07005872
Steve Antonc7b964c2018-02-01 14:39:45 -08005873 for (const auto& entry : media_types_by_transport_name) {
5874 const std::string& transport_name = entry.first;
5875 const std::set<cricket::MediaType> media_types = entry.second;
Steve Anton75737c02017-11-06 10:37:17 -08005876 cricket::TransportStats stats;
Steve Antonc7b964c2018-02-01 14:39:45 -08005877 if (transport_controller_->GetStats(transport_name, &stats)) {
Steve Anton75737c02017-11-06 10:37:17 -08005878 ReportBestConnectionState(stats);
Steve Antonc7b964c2018-02-01 14:39:45 -08005879 ReportNegotiatedCiphers(stats, media_types);
Steve Anton75737c02017-11-06 10:37:17 -08005880 }
5881 }
5882}
5883// Walk through the ConnectionInfos to gather best connection usage
5884// for IPv4 and IPv6.
5885void PeerConnection::ReportBestConnectionState(
5886 const cricket::TransportStats& stats) {
5887 RTC_DCHECK(metrics_observer());
Steve Antonc7b964c2018-02-01 14:39:45 -08005888 for (const cricket::TransportChannelStats& channel_stats :
5889 stats.channel_stats) {
5890 for (const cricket::ConnectionInfo& connection_info :
5891 channel_stats.connection_infos) {
5892 if (!connection_info.best_connection) {
Steve Anton75737c02017-11-06 10:37:17 -08005893 continue;
5894 }
5895
5896 PeerConnectionEnumCounterType type = kPeerConnectionEnumCounterMax;
Steve Antonc7b964c2018-02-01 14:39:45 -08005897 const cricket::Candidate& local = connection_info.local_candidate;
5898 const cricket::Candidate& remote = connection_info.remote_candidate;
Steve Anton75737c02017-11-06 10:37:17 -08005899
5900 // Increment the counter for IceCandidatePairType.
5901 if (local.protocol() == cricket::TCP_PROTOCOL_NAME ||
5902 (local.type() == RELAY_PORT_TYPE &&
5903 local.relay_protocol() == cricket::TCP_PROTOCOL_NAME)) {
5904 type = kEnumCounterIceCandidatePairTypeTcp;
5905 } else if (local.protocol() == cricket::UDP_PROTOCOL_NAME) {
5906 type = kEnumCounterIceCandidatePairTypeUdp;
5907 } else {
5908 RTC_CHECK(0);
5909 }
5910 metrics_observer()->IncrementEnumCounter(
5911 type, GetIceCandidatePairCounter(local, remote),
5912 kIceCandidatePairMax);
5913
5914 // Increment the counter for IP type.
5915 if (local.address().family() == AF_INET) {
5916 metrics_observer()->IncrementEnumCounter(
5917 kEnumCounterAddressFamily, kBestConnections_IPv4,
5918 kPeerConnectionAddressFamilyCounter_Max);
5919
5920 } else if (local.address().family() == AF_INET6) {
5921 metrics_observer()->IncrementEnumCounter(
5922 kEnumCounterAddressFamily, kBestConnections_IPv6,
5923 kPeerConnectionAddressFamilyCounter_Max);
5924 } else {
5925 RTC_CHECK(0);
5926 }
5927
5928 return;
5929 }
5930 }
5931}
5932
5933void PeerConnection::ReportNegotiatedCiphers(
Steve Antonc7b964c2018-02-01 14:39:45 -08005934 const cricket::TransportStats& stats,
5935 const std::set<cricket::MediaType>& media_types) {
Steve Anton75737c02017-11-06 10:37:17 -08005936 RTC_DCHECK(metrics_observer());
5937 if (!dtls_enabled_ || stats.channel_stats.empty()) {
5938 return;
5939 }
5940
5941 int srtp_crypto_suite = stats.channel_stats[0].srtp_crypto_suite;
5942 int ssl_cipher_suite = stats.channel_stats[0].ssl_cipher_suite;
5943 if (srtp_crypto_suite == rtc::SRTP_INVALID_CRYPTO_SUITE &&
5944 ssl_cipher_suite == rtc::TLS_NULL_WITH_NULL_NULL) {
5945 return;
5946 }
5947
Steve Antonc7b964c2018-02-01 14:39:45 -08005948 for (cricket::MediaType media_type : media_types) {
5949 PeerConnectionEnumCounterType srtp_counter_type;
5950 PeerConnectionEnumCounterType ssl_counter_type;
5951 switch (media_type) {
5952 case cricket::MEDIA_TYPE_AUDIO:
5953 srtp_counter_type = kEnumCounterAudioSrtpCipher;
5954 ssl_counter_type = kEnumCounterAudioSslCipher;
5955 break;
5956 case cricket::MEDIA_TYPE_VIDEO:
5957 srtp_counter_type = kEnumCounterVideoSrtpCipher;
5958 ssl_counter_type = kEnumCounterVideoSslCipher;
5959 break;
5960 case cricket::MEDIA_TYPE_DATA:
5961 srtp_counter_type = kEnumCounterDataSrtpCipher;
5962 ssl_counter_type = kEnumCounterDataSslCipher;
5963 break;
5964 default:
5965 RTC_NOTREACHED();
5966 continue;
5967 }
5968 if (srtp_crypto_suite != rtc::SRTP_INVALID_CRYPTO_SUITE) {
5969 metrics_observer()->IncrementSparseEnumCounter(srtp_counter_type,
5970 srtp_crypto_suite);
5971 }
5972 if (ssl_cipher_suite != rtc::TLS_NULL_WITH_NULL_NULL) {
5973 metrics_observer()->IncrementSparseEnumCounter(ssl_counter_type,
5974 ssl_cipher_suite);
5975 }
Steve Anton75737c02017-11-06 10:37:17 -08005976 }
5977}
5978
5979void PeerConnection::OnSentPacket_w(const rtc::SentPacket& sent_packet) {
5980 RTC_DCHECK(worker_thread()->IsCurrent());
5981 RTC_DCHECK(call_);
5982 call_->OnSentPacket(sent_packet);
5983}
5984
5985const std::string PeerConnection::GetTransportName(
5986 const std::string& content_name) {
5987 cricket::BaseChannel* channel = GetChannel(content_name);
Steve Anton6fec8802017-12-04 10:37:29 -08005988 if (channel) {
5989 return channel->transport_name();
Steve Anton75737c02017-11-06 10:37:17 -08005990 }
Steve Anton6fec8802017-12-04 10:37:29 -08005991 if (sctp_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07005992 RTC_DCHECK(sctp_mid_);
5993 if (content_name == *sctp_mid_) {
5994 return *sctp_transport_name();
Steve Anton6fec8802017-12-04 10:37:29 -08005995 }
5996 }
5997 // Return an empty string if failed to retrieve the transport name.
5998 return "";
Steve Anton75737c02017-11-06 10:37:17 -08005999}
6000
Steve Anton6fec8802017-12-04 10:37:29 -08006001void PeerConnection::DestroyTransceiverChannel(
6002 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
6003 transceiver) {
6004 RTC_DCHECK(transceiver);
Steve Anton75737c02017-11-06 10:37:17 -08006005
Steve Anton6fec8802017-12-04 10:37:29 -08006006 cricket::BaseChannel* channel = transceiver->internal()->channel();
6007 if (channel) {
6008 transceiver->internal()->SetChannel(nullptr);
6009 DestroyBaseChannel(channel);
Steve Anton75737c02017-11-06 10:37:17 -08006010 }
6011}
6012
6013void PeerConnection::DestroyDataChannel() {
Steve Anton6fec8802017-12-04 10:37:29 -08006014 if (rtp_data_channel_) {
6015 OnDataChannelDestroyed();
6016 DestroyBaseChannel(rtp_data_channel_);
6017 rtp_data_channel_ = nullptr;
6018 }
6019
6020 // Note: Cannot use rtc::Bind to create a functor to invoke because it will
6021 // grab a reference to this PeerConnection. If this is called from the
6022 // PeerConnection destructor, the RefCountedObject vtable will have already
6023 // been destroyed (since it is a subclass of PeerConnection) and using
6024 // rtc::Bind will cause "Pure virtual function called" error to appear.
6025
6026 if (sctp_transport_) {
6027 OnDataChannelDestroyed();
6028 network_thread()->Invoke<void>(RTC_FROM_HERE,
6029 [this] { DestroySctpTransport_n(); });
6030 }
6031}
6032
6033void PeerConnection::DestroyBaseChannel(cricket::BaseChannel* channel) {
6034 RTC_DCHECK(channel);
Steve Anton6fec8802017-12-04 10:37:29 -08006035
6036 switch (channel->media_type()) {
6037 case cricket::MEDIA_TYPE_AUDIO:
6038 channel_manager()->DestroyVoiceChannel(
6039 static_cast<cricket::VoiceChannel*>(channel));
6040 break;
6041 case cricket::MEDIA_TYPE_VIDEO:
6042 channel_manager()->DestroyVideoChannel(
6043 static_cast<cricket::VideoChannel*>(channel));
6044 break;
6045 case cricket::MEDIA_TYPE_DATA:
6046 channel_manager()->DestroyRtpDataChannel(
6047 static_cast<cricket::RtpDataChannel*>(channel));
6048 break;
6049 default:
6050 RTC_NOTREACHED() << "Unknown media type: " << channel->media_type();
6051 break;
6052 }
Zhi Huange830e682018-03-30 10:48:35 -07006053}
Steve Anton6fec8802017-12-04 10:37:29 -08006054
Zhi Huange830e682018-03-30 10:48:35 -07006055void PeerConnection::OnRtpTransportChanged(
6056 const std::string& mid,
6057 RtpTransportInternal* rtp_transport) {
6058 auto base_channel = GetChannel(mid);
6059 if (base_channel) {
6060 base_channel->SetRtpTransport(rtp_transport);
6061 }
6062}
Steve Anton6fec8802017-12-04 10:37:29 -08006063
Zhi Huange830e682018-03-30 10:48:35 -07006064void PeerConnection::OnDtlsTransportChanged(
6065 const std::string& mid,
6066 cricket::DtlsTransportInternal* dtls_transport) {
6067 if (sctp_transport_) {
6068 RTC_DCHECK(mid == sctp_mid_);
6069 sctp_transport_->SetTransportChannel(dtls_transport);
Steve Anton75737c02017-11-06 10:37:17 -08006070 }
6071}
6072
Harald Alvestrand89061872018-01-02 14:08:34 +01006073void PeerConnection::ClearStatsCache() {
6074 if (stats_collector_) {
6075 stats_collector_->ClearCachedStatsReport();
6076 }
6077}
6078
henrike@webrtc.org28e20752013-07-10 00:45:36 +00006079} // namespace webrtc