blob: 17977ad31b03ab1388b61376fc4a6264ae24a0f2 [file] [log] [blame]
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001/*
kjellanderb24317b2016-02-10 07:54:43 -08002 * Copyright 2012 The WebRTC project authors. All Rights Reserved.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003 *
kjellanderb24317b2016-02-10 07:54:43 -08004 * Use of this source code is governed by a BSD-style license
5 * that can be found in the LICENSE file in the root of the source
6 * tree. An additional intellectual property rights grant can be found
7 * in the file PATENTS. All contributing project authors may
8 * be found in the AUTHORS file in the root of the source tree.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00009 */
10
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020011#include "pc/peerconnection.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000012
deadbeefeb459812015-12-15 19:24:43 -080013#include <algorithm>
Steve Antondcc3c022017-12-22 16:02:54 -080014#include <queue>
Steve Anton75737c02017-11-06 10:37:17 -080015#include <set>
kwiberg0eb15ed2015-12-17 03:04:15 -080016#include <utility>
17#include <vector>
henrike@webrtc.org28e20752013-07-10 00:45:36 +000018
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020019#include "api/jsepicecandidate.h"
20#include "api/jsepsessiondescription.h"
21#include "api/mediaconstraintsinterface.h"
22#include "api/mediastreamproxy.h"
23#include "api/mediastreamtrackproxy.h"
24#include "call/call.h"
Qingsi Wang93a84392018-01-30 17:13:09 -080025#include "logging/rtc_event_log/icelogger.h"
Elad Alon83ccca12017-10-04 13:18:26 +020026#include "logging/rtc_event_log/output/rtc_event_log_output_file.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020027#include "logging/rtc_event_log/rtc_event_log.h"
28#include "media/sctp/sctptransport.h"
29#include "pc/audiotrack.h"
Steve Anton75737c02017-11-06 10:37:17 -080030#include "pc/channel.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020031#include "pc/channelmanager.h"
32#include "pc/dtmfsender.h"
33#include "pc/mediastream.h"
34#include "pc/mediastreamobserver.h"
35#include "pc/remoteaudiosource.h"
Steve Anton1d03a752017-11-27 14:30:09 -080036#include "pc/rtpmediautils.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020037#include "pc/rtpreceiver.h"
38#include "pc/rtpsender.h"
Steve Anton75737c02017-11-06 10:37:17 -080039#include "pc/sctputils.h"
Steve Antona3a92c22017-12-07 10:27:41 -080040#include "pc/sdputils.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020041#include "pc/streamcollection.h"
42#include "pc/videocapturertracksource.h"
43#include "pc/videotrack.h"
44#include "rtc_base/bind.h"
45#include "rtc_base/checks.h"
46#include "rtc_base/logging.h"
Karl Wiberge40468b2017-11-22 10:42:26 +010047#include "rtc_base/numerics/safe_conversions.h"
Elad Alon83ccca12017-10-04 13:18:26 +020048#include "rtc_base/ptr_util.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020049#include "rtc_base/stringencode.h"
50#include "rtc_base/stringutils.h"
51#include "rtc_base/trace_event.h"
52#include "system_wrappers/include/clock.h"
53#include "system_wrappers/include/field_trial.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000054
Steve Anton75737c02017-11-06 10:37:17 -080055using cricket::ContentInfo;
56using cricket::ContentInfos;
57using cricket::MediaContentDescription;
58using cricket::SessionDescription;
Steve Anton5adfafd2017-12-20 16:34:00 -080059using cricket::MediaProtocolType;
Steve Anton75737c02017-11-06 10:37:17 -080060using cricket::TransportInfo;
61
62using cricket::LOCAL_PORT_TYPE;
63using cricket::STUN_PORT_TYPE;
64using cricket::RELAY_PORT_TYPE;
65using cricket::PRFLX_PORT_TYPE;
66
Steve Antonba818672017-11-06 10:21:57 -080067namespace webrtc {
68
Steve Anton75737c02017-11-06 10:37:17 -080069// Error messages
70const char kBundleWithoutRtcpMux[] =
71 "rtcp-mux must be enabled when BUNDLE "
72 "is enabled.";
Steve Anton75737c02017-11-06 10:37:17 -080073const char kInvalidCandidates[] = "Description contains invalid candidates.";
74const char kInvalidSdp[] = "Invalid session description.";
75const char kMlineMismatchInAnswer[] =
76 "The order of m-lines in answer doesn't match order in offer. Rejecting "
77 "answer.";
78const char kMlineMismatchInSubsequentOffer[] =
79 "The order of m-lines in subsequent offer doesn't match order from "
80 "previous offer/answer.";
Steve Anton75737c02017-11-06 10:37:17 -080081const char kSdpWithoutDtlsFingerprint[] =
82 "Called with SDP without DTLS fingerprint.";
83const char kSdpWithoutSdesCrypto[] = "Called with SDP without SDES crypto.";
84const char kSdpWithoutIceUfragPwd[] =
85 "Called with SDP without ice-ufrag and ice-pwd.";
86const char kSessionError[] = "Session error code: ";
87const char kSessionErrorDesc[] = "Session error description: ";
88const char kDtlsSrtpSetupFailureRtp[] =
89 "Couldn't set up DTLS-SRTP on RTP channel.";
90const char kDtlsSrtpSetupFailureRtcp[] =
91 "Couldn't set up DTLS-SRTP on RTCP channel.";
92const char kEnableBundleFailed[] = "Failed to enable BUNDLE.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +000093
Steve Anton75737c02017-11-06 10:37:17 -080094namespace {
henrike@webrtc.org28e20752013-07-10 00:45:36 +000095
Seth Hampson845e8782018-03-02 11:34:10 -080096static const char kDefaultStreamId[] = "default";
Steve Anton4171afb2017-11-20 10:20:22 -080097static const char kDefaultAudioSenderId[] = "defaulta0";
98static const char kDefaultVideoSenderId[] = "defaultv0";
deadbeefab9b2d12015-10-14 11:33:11 -070099
zhihuang8f65cdf2016-05-06 18:40:30 -0700100// The length of RTCP CNAMEs.
101static const int kRtcpCnameLength = 16;
102
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000103enum {
wu@webrtc.org91053e72013-08-10 07:18:04 +0000104 MSG_SET_SESSIONDESCRIPTION_SUCCESS = 0,
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000105 MSG_SET_SESSIONDESCRIPTION_FAILED,
deadbeefab9b2d12015-10-14 11:33:11 -0700106 MSG_CREATE_SESSIONDESCRIPTION_FAILED,
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000107 MSG_GETSTATS,
deadbeefbd292462015-12-14 18:15:29 -0800108 MSG_FREE_DATACHANNELS,
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000109};
110
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000111struct SetSessionDescriptionMsg : public rtc::MessageData {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000112 explicit SetSessionDescriptionMsg(
113 webrtc::SetSessionDescriptionObserver* observer)
114 : observer(observer) {
115 }
116
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000117 rtc::scoped_refptr<webrtc::SetSessionDescriptionObserver> observer;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +0100118 RTCError error;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000119};
120
deadbeefab9b2d12015-10-14 11:33:11 -0700121struct CreateSessionDescriptionMsg : public rtc::MessageData {
122 explicit CreateSessionDescriptionMsg(
123 webrtc::CreateSessionDescriptionObserver* observer)
124 : observer(observer) {}
125
126 rtc::scoped_refptr<webrtc::CreateSessionDescriptionObserver> observer;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +0100127 RTCError error;
deadbeefab9b2d12015-10-14 11:33:11 -0700128};
129
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000130struct GetStatsMsg : public rtc::MessageData {
tommi@webrtc.org5b06b062014-08-15 08:38:30 +0000131 GetStatsMsg(webrtc::StatsObserver* observer,
132 webrtc::MediaStreamTrackInterface* track)
133 : observer(observer), track(track) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000134 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000135 rtc::scoped_refptr<webrtc::StatsObserver> observer;
tommi@webrtc.org5b06b062014-08-15 08:38:30 +0000136 rtc::scoped_refptr<webrtc::MediaStreamTrackInterface> track;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000137};
138
deadbeefab9b2d12015-10-14 11:33:11 -0700139// Check if we can send |new_stream| on a PeerConnection.
140bool CanAddLocalMediaStream(webrtc::StreamCollectionInterface* current_streams,
141 webrtc::MediaStreamInterface* new_stream) {
142 if (!new_stream || !current_streams) {
143 return false;
144 }
Seth Hampson13b8bad2018-03-13 16:05:28 -0700145 if (current_streams->find(new_stream->id()) != nullptr) {
146 RTC_LOG(LS_ERROR) << "MediaStream with ID " << new_stream->id()
Mirko Bonadei675513b2017-11-09 11:09:25 +0100147 << " is already added.";
deadbeefab9b2d12015-10-14 11:33:11 -0700148 return false;
149 }
150 return true;
151}
152
deadbeef5e97fb52015-10-15 12:49:08 -0700153// If the direction is "recvonly" or "inactive", treat the description
154// as containing no streams.
155// See: https://code.google.com/p/webrtc/issues/detail?id=5054
156std::vector<cricket::StreamParams> GetActiveStreams(
157 const cricket::MediaContentDescription* desc) {
Steve Anton4e70a722017-11-28 14:57:10 -0800158 return RtpTransceiverDirectionHasSend(desc->direction())
deadbeef5e97fb52015-10-15 12:49:08 -0700159 ? desc->streams()
160 : std::vector<cricket::StreamParams>();
161}
162
deadbeefab9b2d12015-10-14 11:33:11 -0700163bool IsValidOfferToReceiveMedia(int value) {
164 typedef PeerConnectionInterface::RTCOfferAnswerOptions Options;
165 return (value >= Options::kUndefined) &&
166 (value <= Options::kMaxOfferToReceiveMedia);
167}
168
zhihuang1c378ed2017-08-17 14:10:50 -0700169// Add options to |[audio/video]_media_description_options| from |senders|.
170void AddRtpSenderOptions(
deadbeefa601f5c2016-06-06 14:27:39 -0700171 const std::vector<rtc::scoped_refptr<
172 RtpSenderProxyWithInternal<RtpSenderInternal>>>& senders,
zhihuang1c378ed2017-08-17 14:10:50 -0700173 cricket::MediaDescriptionOptions* audio_media_description_options,
174 cricket::MediaDescriptionOptions* video_media_description_options) {
olka3c747662017-08-17 06:50:32 -0700175 for (const auto& sender : senders) {
zhihuang1c378ed2017-08-17 14:10:50 -0700176 if (sender->media_type() == cricket::MEDIA_TYPE_AUDIO) {
177 if (audio_media_description_options) {
178 audio_media_description_options->AddAudioSender(
Steve Anton8ffb9c32017-08-31 15:45:38 -0700179 sender->id(), sender->internal()->stream_ids());
zhihuang1c378ed2017-08-17 14:10:50 -0700180 }
181 } else {
182 RTC_DCHECK(sender->media_type() == cricket::MEDIA_TYPE_VIDEO);
183 if (video_media_description_options) {
184 video_media_description_options->AddVideoSender(
Steve Anton8ffb9c32017-08-31 15:45:38 -0700185 sender->id(), sender->internal()->stream_ids(), 1);
zhihuang1c378ed2017-08-17 14:10:50 -0700186 }
187 }
zhihuanga77e6bb2017-08-14 18:17:48 -0700188 }
zhihuang1c378ed2017-08-17 14:10:50 -0700189}
olka3c747662017-08-17 06:50:32 -0700190
zhihuang1c378ed2017-08-17 14:10:50 -0700191// Add options to |session_options| from |rtp_data_channels|.
192void AddRtpDataChannelOptions(
193 const std::map<std::string, rtc::scoped_refptr<DataChannel>>&
194 rtp_data_channels,
195 cricket::MediaDescriptionOptions* data_media_description_options) {
196 if (!data_media_description_options) {
197 return;
198 }
deadbeefab9b2d12015-10-14 11:33:11 -0700199 // Check for data channels.
200 for (const auto& kv : rtp_data_channels) {
201 const DataChannel* channel = kv.second;
202 if (channel->state() == DataChannel::kConnecting ||
203 channel->state() == DataChannel::kOpen) {
zhihuang1c378ed2017-08-17 14:10:50 -0700204 // Legacy RTP data channels are signaled with the track/stream ID set to
205 // the data channel's label.
206 data_media_description_options->AddRtpDataChannel(channel->label(),
207 channel->label());
deadbeefab9b2d12015-10-14 11:33:11 -0700208 }
209 }
210}
211
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700212uint32_t ConvertIceTransportTypeToCandidateFilter(
213 PeerConnectionInterface::IceTransportsType type) {
214 switch (type) {
215 case PeerConnectionInterface::kNone:
216 return cricket::CF_NONE;
217 case PeerConnectionInterface::kRelay:
218 return cricket::CF_RELAY;
219 case PeerConnectionInterface::kNoHost:
220 return (cricket::CF_ALL & ~cricket::CF_HOST);
221 case PeerConnectionInterface::kAll:
222 return cricket::CF_ALL;
223 default:
nissec80e7412017-01-11 05:56:46 -0800224 RTC_NOTREACHED();
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700225 }
226 return cricket::CF_NONE;
227}
228
deadbeef293e9262017-01-11 12:28:30 -0800229// Helper to set an error and return from a method.
230bool SafeSetError(webrtc::RTCErrorType type, webrtc::RTCError* error) {
231 if (error) {
232 error->set_type(type);
233 }
234 return type == webrtc::RTCErrorType::NONE;
235}
236
Steve Anton038834f2017-07-14 15:59:59 -0700237bool SafeSetError(webrtc::RTCError error, webrtc::RTCError* error_out) {
238 if (error_out) {
239 *error_out = std::move(error);
240 }
241 return error.ok();
242}
243
Steve Antonba818672017-11-06 10:21:57 -0800244std::string GetSignalingStateString(
245 PeerConnectionInterface::SignalingState state) {
246 switch (state) {
247 case PeerConnectionInterface::kStable:
248 return "kStable";
249 case PeerConnectionInterface::kHaveLocalOffer:
250 return "kHaveLocalOffer";
251 case PeerConnectionInterface::kHaveLocalPrAnswer:
252 return "kHavePrAnswer";
253 case PeerConnectionInterface::kHaveRemoteOffer:
254 return "kHaveRemoteOffer";
255 case PeerConnectionInterface::kHaveRemotePrAnswer:
256 return "kHaveRemotePrAnswer";
257 case PeerConnectionInterface::kClosed:
258 return "kClosed";
259 }
260 RTC_NOTREACHED();
261 return "";
262}
deadbeef0a6c4ca2015-10-06 11:38:28 -0700263
Steve Anton75737c02017-11-06 10:37:17 -0800264IceCandidatePairType GetIceCandidatePairCounter(
265 const cricket::Candidate& local,
266 const cricket::Candidate& remote) {
267 const auto& l = local.type();
268 const auto& r = remote.type();
269 const auto& host = LOCAL_PORT_TYPE;
270 const auto& srflx = STUN_PORT_TYPE;
271 const auto& relay = RELAY_PORT_TYPE;
272 const auto& prflx = PRFLX_PORT_TYPE;
273 if (l == host && r == host) {
274 bool local_private = IPIsPrivate(local.address().ipaddr());
275 bool remote_private = IPIsPrivate(remote.address().ipaddr());
276 if (local_private) {
277 if (remote_private) {
278 return kIceCandidatePairHostPrivateHostPrivate;
279 } else {
280 return kIceCandidatePairHostPrivateHostPublic;
281 }
282 } else {
283 if (remote_private) {
284 return kIceCandidatePairHostPublicHostPrivate;
285 } else {
286 return kIceCandidatePairHostPublicHostPublic;
287 }
288 }
289 }
290 if (l == host && r == srflx)
291 return kIceCandidatePairHostSrflx;
292 if (l == host && r == relay)
293 return kIceCandidatePairHostRelay;
294 if (l == host && r == prflx)
295 return kIceCandidatePairHostPrflx;
296 if (l == srflx && r == host)
297 return kIceCandidatePairSrflxHost;
298 if (l == srflx && r == srflx)
299 return kIceCandidatePairSrflxSrflx;
300 if (l == srflx && r == relay)
301 return kIceCandidatePairSrflxRelay;
302 if (l == srflx && r == prflx)
303 return kIceCandidatePairSrflxPrflx;
304 if (l == relay && r == host)
305 return kIceCandidatePairRelayHost;
306 if (l == relay && r == srflx)
307 return kIceCandidatePairRelaySrflx;
308 if (l == relay && r == relay)
309 return kIceCandidatePairRelayRelay;
310 if (l == relay && r == prflx)
311 return kIceCandidatePairRelayPrflx;
312 if (l == prflx && r == host)
313 return kIceCandidatePairPrflxHost;
314 if (l == prflx && r == srflx)
315 return kIceCandidatePairPrflxSrflx;
316 if (l == prflx && r == relay)
317 return kIceCandidatePairPrflxRelay;
318 return kIceCandidatePairMax;
319}
320
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800321// Logic to decide if an m= section can be recycled. This means that the new
322// m= section is not rejected, but the old local or remote m= section is
323// rejected. |old_content_one| and |old_content_two| refer to the m= section
324// of the old remote and old local descriptions in no particular order.
325// We need to check both the old local and remote because either
326// could be the most current from the latest negotation.
327bool IsMediaSectionBeingRecycled(SdpType type,
328 const ContentInfo& content,
329 const ContentInfo* old_content_one,
330 const ContentInfo* old_content_two) {
331 return type == SdpType::kOffer && !content.rejected &&
332 ((old_content_one && old_content_one->rejected) ||
333 (old_content_two && old_content_two->rejected));
334}
335
Steve Anton75737c02017-11-06 10:37:17 -0800336// Verify that the order of media sections in |new_desc| matches
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800337// |current_desc|. The number of m= sections in |new_desc| should be no
338// less than |current_desc|. In the case of checking an answer's
339// |new_desc|, the |current_desc| is the last offer that was set as the
340// local or remote. In the case of checking an offer's |new_desc| we
341// check against the local and remote descriptions stored from the last
342// negotiation, because either of these could be the most up to date for
343// possible rejected m sections. These are the |current_desc| and
344// |secondary_current_desc|.
345bool MediaSectionsInSameOrder(const SessionDescription& current_desc,
346 const SessionDescription* secondary_current_desc,
347 const SessionDescription& new_desc,
348 const SdpType type) {
349 if (current_desc.contents().size() > new_desc.contents().size()) {
Steve Anton75737c02017-11-06 10:37:17 -0800350 return false;
351 }
352
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800353 for (size_t i = 0; i < current_desc.contents().size(); ++i) {
354 const cricket::ContentInfo* secondary_content_info = nullptr;
355 if (secondary_current_desc &&
356 i < secondary_current_desc->contents().size()) {
357 secondary_content_info = &secondary_current_desc->contents()[i];
358 }
359 if (IsMediaSectionBeingRecycled(type, new_desc.contents()[i],
360 &current_desc.contents()[i],
361 secondary_content_info)) {
362 // For new offer descriptions, if the media section can be recycled, it's
363 // valid for the MID and media type to change.
Steve Antondcc3c022017-12-22 16:02:54 -0800364 continue;
365 }
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800366 if (new_desc.contents()[i].name != current_desc.contents()[i].name) {
Steve Anton75737c02017-11-06 10:37:17 -0800367 return false;
368 }
369 const MediaContentDescription* new_desc_mdesc =
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800370 new_desc.contents()[i].media_description();
371 const MediaContentDescription* current_desc_mdesc =
372 current_desc.contents()[i].media_description();
373 if (new_desc_mdesc->type() != current_desc_mdesc->type()) {
Steve Anton75737c02017-11-06 10:37:17 -0800374 return false;
375 }
376 }
377 return true;
378}
379
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800380bool MediaSectionsHaveSameCount(const SessionDescription& desc1,
381 const SessionDescription& desc2) {
382 return desc1.contents().size() == desc2.contents().size();
Steve Anton75737c02017-11-06 10:37:17 -0800383}
384
Harald Alvestrandf9d0f1d2018-03-02 14:15:26 +0100385void NoteKeyProtocolAndMedia(
386 KeyExchangeProtocolType protocol_type,
387 cricket::MediaType media_type,
388 rtc::scoped_refptr<webrtc::UMAObserver> uma_observer) {
389 if (!uma_observer)
390 return;
391 uma_observer->IncrementEnumCounter(webrtc::kEnumCounterKeyProtocol,
392 protocol_type,
393 webrtc::kEnumCounterKeyProtocolMax);
394 static const std::map<std::pair<KeyExchangeProtocolType, cricket::MediaType>,
395 KeyExchangeProtocolMedia>
396 proto_media_counter_map = {
397 {{kEnumCounterKeyProtocolDtls, cricket::MEDIA_TYPE_AUDIO},
398 kEnumCounterKeyProtocolMediaTypeDtlsAudio},
399 {{kEnumCounterKeyProtocolDtls, cricket::MEDIA_TYPE_VIDEO},
400 kEnumCounterKeyProtocolMediaTypeDtlsVideo},
401 {{kEnumCounterKeyProtocolDtls, cricket::MEDIA_TYPE_DATA},
402 kEnumCounterKeyProtocolMediaTypeDtlsData},
403 {{kEnumCounterKeyProtocolSdes, cricket::MEDIA_TYPE_AUDIO},
404 kEnumCounterKeyProtocolMediaTypeSdesAudio},
405 {{kEnumCounterKeyProtocolSdes, cricket::MEDIA_TYPE_VIDEO},
406 kEnumCounterKeyProtocolMediaTypeSdesVideo},
407 {{kEnumCounterKeyProtocolSdes, cricket::MEDIA_TYPE_DATA},
408 kEnumCounterKeyProtocolMediaTypeSdesData}};
409
410 auto it = proto_media_counter_map.find({protocol_type, media_type});
411 if (it != proto_media_counter_map.end()) {
412 uma_observer->IncrementEnumCounter(webrtc::kEnumCounterKeyProtocolMediaType,
413 it->second,
414 kEnumCounterKeyProtocolMediaTypeMax);
415 }
416}
417
Steve Anton75737c02017-11-06 10:37:17 -0800418// Checks that each non-rejected content has SDES crypto keys or a DTLS
419// fingerprint, unless it's in a BUNDLE group, in which case only the
420// BUNDLE-tag section (first media section/description in the BUNDLE group)
421// needs a ufrag and pwd. Mismatches, such as replying with a DTLS fingerprint
422// to SDES keys, will be caught in JsepTransport negotiation, and backstopped
423// by Channel's |srtp_required| check.
Harald Alvestrand194939b2018-01-24 16:04:13 +0100424RTCError VerifyCrypto(const SessionDescription* desc,
425 bool dtls_enabled,
426 rtc::scoped_refptr<webrtc::UMAObserver> uma_observer) {
Steve Anton75737c02017-11-06 10:37:17 -0800427 const cricket::ContentGroup* bundle =
428 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton8a006912017-12-04 15:25:56 -0800429 for (const cricket::ContentInfo& content_info : desc->contents()) {
430 if (content_info.rejected) {
Steve Anton75737c02017-11-06 10:37:17 -0800431 continue;
432 }
Harald Alvestrand2e180612018-03-07 10:56:14 +0100433 // Note what media is used with each crypto protocol, for all sections.
434 NoteKeyProtocolAndMedia(dtls_enabled ? webrtc::kEnumCounterKeyProtocolDtls
435 : webrtc::kEnumCounterKeyProtocolSdes,
436 content_info.media_description()->type(),
437 uma_observer);
Steve Anton8a006912017-12-04 15:25:56 -0800438 const std::string& mid = content_info.name;
439 if (bundle && bundle->HasContentName(mid) &&
440 mid != *(bundle->FirstContentName())) {
Steve Anton75737c02017-11-06 10:37:17 -0800441 // This isn't the first media section in the BUNDLE group, so it's not
442 // required to have crypto attributes, since only the crypto attributes
443 // from the first section actually get used.
444 continue;
445 }
446
447 // If the content isn't rejected or bundled into another m= section, crypto
448 // must be present.
Steve Antonb1c1de12017-12-21 15:14:30 -0800449 const MediaContentDescription* media = content_info.media_description();
Steve Anton8a006912017-12-04 15:25:56 -0800450 const TransportInfo* tinfo = desc->GetTransportInfoByName(mid);
Steve Anton75737c02017-11-06 10:37:17 -0800451 if (!media || !tinfo) {
452 // Something is not right.
Steve Anton8a006912017-12-04 15:25:56 -0800453 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidSdp);
Steve Anton75737c02017-11-06 10:37:17 -0800454 }
455 if (dtls_enabled) {
456 if (!tinfo->description.identity_fingerprint) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100457 RTC_LOG(LS_WARNING)
458 << "Session description must have DTLS fingerprint if "
459 "DTLS enabled.";
Steve Anton8a006912017-12-04 15:25:56 -0800460 return RTCError(RTCErrorType::INVALID_PARAMETER,
461 kSdpWithoutDtlsFingerprint);
Steve Anton75737c02017-11-06 10:37:17 -0800462 }
463 } else {
464 if (media->cryptos().empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100465 RTC_LOG(LS_WARNING)
Steve Anton75737c02017-11-06 10:37:17 -0800466 << "Session description must have SDES when DTLS disabled.";
Steve Anton8a006912017-12-04 15:25:56 -0800467 return RTCError(RTCErrorType::INVALID_PARAMETER, kSdpWithoutSdesCrypto);
Steve Anton75737c02017-11-06 10:37:17 -0800468 }
469 }
470 }
Steve Anton8a006912017-12-04 15:25:56 -0800471 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -0800472}
473
474// Checks that each non-rejected content has ice-ufrag and ice-pwd set, unless
475// it's in a BUNDLE group, in which case only the BUNDLE-tag section (first
476// media section/description in the BUNDLE group) needs a ufrag and pwd.
477bool VerifyIceUfragPwdPresent(const SessionDescription* desc) {
478 const cricket::ContentGroup* bundle =
479 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton8a006912017-12-04 15:25:56 -0800480 for (const cricket::ContentInfo& content_info : desc->contents()) {
481 if (content_info.rejected) {
Steve Anton75737c02017-11-06 10:37:17 -0800482 continue;
483 }
Steve Anton8a006912017-12-04 15:25:56 -0800484 const std::string& mid = content_info.name;
485 if (bundle && bundle->HasContentName(mid) &&
486 mid != *(bundle->FirstContentName())) {
Steve Anton75737c02017-11-06 10:37:17 -0800487 // This isn't the first media section in the BUNDLE group, so it's not
488 // required to have ufrag/password, since only the ufrag/password from
489 // the first section actually get used.
490 continue;
491 }
492
493 // If the content isn't rejected or bundled into another m= section,
494 // ice-ufrag and ice-pwd must be present.
Steve Anton8a006912017-12-04 15:25:56 -0800495 const TransportInfo* tinfo = desc->GetTransportInfoByName(mid);
Steve Anton75737c02017-11-06 10:37:17 -0800496 if (!tinfo) {
497 // Something is not right.
Mirko Bonadei675513b2017-11-09 11:09:25 +0100498 RTC_LOG(LS_ERROR) << kInvalidSdp;
Steve Anton75737c02017-11-06 10:37:17 -0800499 return false;
500 }
501 if (tinfo->description.ice_ufrag.empty() ||
502 tinfo->description.ice_pwd.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100503 RTC_LOG(LS_ERROR) << "Session description must have ice ufrag and pwd.";
Steve Anton75737c02017-11-06 10:37:17 -0800504 return false;
505 }
506 }
507 return true;
508}
509
510bool GetTrackIdBySsrc(const SessionDescription* session_description,
511 uint32_t ssrc,
512 std::string* track_id) {
513 RTC_DCHECK(track_id != NULL);
514
Steve Antonb1c1de12017-12-21 15:14:30 -0800515 const cricket::AudioContentDescription* audio_desc =
516 cricket::GetFirstAudioContentDescription(session_description);
517 if (audio_desc) {
518 const auto* found = cricket::GetStreamBySsrc(audio_desc->streams(), ssrc);
Steve Anton75737c02017-11-06 10:37:17 -0800519 if (found) {
520 *track_id = found->id;
521 return true;
522 }
523 }
524
Steve Antonb1c1de12017-12-21 15:14:30 -0800525 const cricket::VideoContentDescription* video_desc =
526 cricket::GetFirstVideoContentDescription(session_description);
527 if (video_desc) {
528 const auto* found = cricket::GetStreamBySsrc(video_desc->streams(), ssrc);
Steve Anton75737c02017-11-06 10:37:17 -0800529 if (found) {
530 *track_id = found->id;
531 return true;
532 }
533 }
534 return false;
535}
536
537// Get the SCTP port out of a SessionDescription.
538// Return -1 if not found.
539int GetSctpPort(const SessionDescription* session_description) {
Steve Antonb1c1de12017-12-21 15:14:30 -0800540 const cricket::DataContentDescription* data_desc =
541 GetFirstDataContentDescription(session_description);
542 RTC_DCHECK(data_desc);
543 if (!data_desc) {
Steve Anton75737c02017-11-06 10:37:17 -0800544 return -1;
545 }
Steve Anton75737c02017-11-06 10:37:17 -0800546 std::string value;
547 cricket::DataCodec match_pattern(cricket::kGoogleSctpDataCodecPlType,
548 cricket::kGoogleSctpDataCodecName);
Steve Antonb1c1de12017-12-21 15:14:30 -0800549 for (const cricket::DataCodec& codec : data_desc->codecs()) {
Steve Anton75737c02017-11-06 10:37:17 -0800550 if (!codec.Matches(match_pattern)) {
551 continue;
552 }
553 if (codec.GetParam(cricket::kCodecParamPort, &value)) {
554 return rtc::FromString<int>(value);
555 }
556 }
557 return -1;
558}
559
Steve Anton75737c02017-11-06 10:37:17 -0800560// Returns true if |new_desc| requests an ICE restart (i.e., new ufrag/pwd).
561bool CheckForRemoteIceRestart(const SessionDescriptionInterface* old_desc,
562 const SessionDescriptionInterface* new_desc,
563 const std::string& content_name) {
564 if (!old_desc) {
565 return false;
566 }
567 const SessionDescription* new_sd = new_desc->description();
568 const SessionDescription* old_sd = old_desc->description();
569 const ContentInfo* cinfo = new_sd->GetContentByName(content_name);
570 if (!cinfo || cinfo->rejected) {
571 return false;
572 }
573 // If the content isn't rejected, check if ufrag and password has changed.
574 const cricket::TransportDescription* new_transport_desc =
575 new_sd->GetTransportDescriptionByName(content_name);
576 const cricket::TransportDescription* old_transport_desc =
577 old_sd->GetTransportDescriptionByName(content_name);
578 if (!new_transport_desc || !old_transport_desc) {
579 // No transport description exists. This is not an ICE restart.
580 return false;
581 }
582 if (cricket::IceCredentialsChanged(
583 old_transport_desc->ice_ufrag, old_transport_desc->ice_pwd,
584 new_transport_desc->ice_ufrag, new_transport_desc->ice_pwd)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100585 RTC_LOG(LS_INFO) << "Remote peer requests ICE restart for " << content_name
586 << ".";
Steve Anton75737c02017-11-06 10:37:17 -0800587 return true;
588 }
589 return false;
590}
591
Steve Anton80dd7b52018-02-16 17:08:42 -0800592// Generates a string error message for SetLocalDescription/SetRemoteDescription
593// from an RTCError.
594std::string GetSetDescriptionErrorMessage(cricket::ContentSource source,
595 SdpType type,
596 const RTCError& error) {
597 std::ostringstream oss;
598 oss << "Failed to set " << (source == cricket::CS_LOCAL ? "local" : "remote")
599 << " " << SdpTypeToString(type) << " sdp: " << error.message();
600 return oss.str();
601}
602
Steve Anton75737c02017-11-06 10:37:17 -0800603} // namespace
604
Henrik Boström31638672017-11-23 17:48:32 +0100605// Upon completion, posts a task to execute the callback of the
606// SetSessionDescriptionObserver asynchronously on the same thread. At this
607// point, the state of the peer connection might no longer reflect the effects
608// of the SetRemoteDescription operation, as the peer connection could have been
609// modified during the post.
610// TODO(hbos): Remove this class once we remove the version of
611// PeerConnectionInterface::SetRemoteDescription() that takes a
612// SetSessionDescriptionObserver as an argument.
613class PeerConnection::SetRemoteDescriptionObserverAdapter
614 : public rtc::RefCountedObject<SetRemoteDescriptionObserverInterface> {
615 public:
616 SetRemoteDescriptionObserverAdapter(
617 rtc::scoped_refptr<PeerConnection> pc,
618 rtc::scoped_refptr<SetSessionDescriptionObserver> wrapper)
619 : pc_(std::move(pc)), wrapper_(std::move(wrapper)) {}
620
621 // SetRemoteDescriptionObserverInterface implementation.
622 void OnSetRemoteDescriptionComplete(RTCError error) override {
623 if (error.ok())
624 pc_->PostSetSessionDescriptionSuccess(wrapper_);
625 else
Harald Alvestrand5081c0c2018-03-09 15:18:03 +0100626 pc_->PostSetSessionDescriptionFailure(wrapper_, std::move(error));
Henrik Boström31638672017-11-23 17:48:32 +0100627 }
628
629 private:
630 rtc::scoped_refptr<PeerConnection> pc_;
631 rtc::scoped_refptr<SetSessionDescriptionObserver> wrapper_;
632};
633
deadbeef293e9262017-01-11 12:28:30 -0800634bool PeerConnectionInterface::RTCConfiguration::operator==(
635 const PeerConnectionInterface::RTCConfiguration& o) const {
636 // This static_assert prevents us from accidentally breaking operator==.
Steve Anton300bf8e2017-07-14 10:13:10 -0700637 // Note: Order matters! Fields must be ordered the same as RTCConfiguration.
deadbeef293e9262017-01-11 12:28:30 -0800638 struct stuff_being_tested_for_equality {
Magnus Jedvert3beb2072017-07-14 14:23:56 +0000639 IceServers servers;
Steve Anton300bf8e2017-07-14 10:13:10 -0700640 IceTransportsType type;
deadbeef293e9262017-01-11 12:28:30 -0800641 BundlePolicy bundle_policy;
642 RtcpMuxPolicy rtcp_mux_policy;
Steve Anton300bf8e2017-07-14 10:13:10 -0700643 std::vector<rtc::scoped_refptr<rtc::RTCCertificate>> certificates;
644 int ice_candidate_pool_size;
645 bool disable_ipv6;
646 bool disable_ipv6_on_wifi;
deadbeefd21eab32017-07-26 16:50:11 -0700647 int max_ipv6_networks;
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +0100648 bool disable_link_local_networks;
Steve Anton300bf8e2017-07-14 10:13:10 -0700649 bool enable_rtp_data_channel;
650 rtc::Optional<int> screencast_min_bitrate;
651 rtc::Optional<bool> combined_audio_video_bwe;
652 rtc::Optional<bool> enable_dtls_srtp;
deadbeef293e9262017-01-11 12:28:30 -0800653 TcpCandidatePolicy tcp_candidate_policy;
654 CandidateNetworkPolicy candidate_network_policy;
655 int audio_jitter_buffer_max_packets;
656 bool audio_jitter_buffer_fast_accelerate;
657 int ice_connection_receiving_timeout;
658 int ice_backup_candidate_pair_ping_interval;
659 ContinualGatheringPolicy continual_gathering_policy;
deadbeef293e9262017-01-11 12:28:30 -0800660 bool prioritize_most_likely_ice_candidate_pairs;
661 struct cricket::MediaConfig media_config;
deadbeef293e9262017-01-11 12:28:30 -0800662 bool prune_turn_ports;
663 bool presume_writable_when_fully_relayed;
664 bool enable_ice_renomination;
665 bool redetermine_role_on_ice_restart;
Qingsi Wange6826d22018-03-08 14:55:14 -0800666 rtc::Optional<int> ice_check_interval_strong_connectivity;
667 rtc::Optional<int> ice_check_interval_weak_connectivity;
skvlad51072462017-02-02 11:50:14 -0800668 rtc::Optional<int> ice_check_min_interval;
Qingsi Wang22e623a2018-03-13 10:53:57 -0700669 rtc::Optional<int> ice_unwritable_timeout;
670 rtc::Optional<int> ice_unwritable_min_checks;
Qingsi Wangdb53f8e2018-02-20 14:45:49 -0800671 rtc::Optional<int> stun_candidate_keepalive_interval;
Steve Anton300bf8e2017-07-14 10:13:10 -0700672 rtc::Optional<rtc::IntervalRange> ice_regather_interval_range;
Jonas Orelandbdcee282017-10-10 14:01:40 +0200673 webrtc::TurnCustomizer* turn_customizer;
Steve Anton79e79602017-11-20 10:25:56 -0800674 SdpSemantics sdp_semantics;
Qingsi Wang9a5c6f82018-02-01 10:38:40 -0800675 rtc::Optional<rtc::AdapterType> network_preference;
deadbeef293e9262017-01-11 12:28:30 -0800676 };
677 static_assert(sizeof(stuff_being_tested_for_equality) == sizeof(*this),
678 "Did you add something to RTCConfiguration and forget to "
679 "update operator==?");
680 return type == o.type && servers == o.servers &&
681 bundle_policy == o.bundle_policy &&
682 rtcp_mux_policy == o.rtcp_mux_policy &&
683 tcp_candidate_policy == o.tcp_candidate_policy &&
684 candidate_network_policy == o.candidate_network_policy &&
685 audio_jitter_buffer_max_packets == o.audio_jitter_buffer_max_packets &&
686 audio_jitter_buffer_fast_accelerate ==
687 o.audio_jitter_buffer_fast_accelerate &&
688 ice_connection_receiving_timeout ==
689 o.ice_connection_receiving_timeout &&
690 ice_backup_candidate_pair_ping_interval ==
691 o.ice_backup_candidate_pair_ping_interval &&
692 continual_gathering_policy == o.continual_gathering_policy &&
693 certificates == o.certificates &&
694 prioritize_most_likely_ice_candidate_pairs ==
695 o.prioritize_most_likely_ice_candidate_pairs &&
696 media_config == o.media_config && disable_ipv6 == o.disable_ipv6 &&
zhihuangb09b3f92017-03-07 14:40:51 -0800697 disable_ipv6_on_wifi == o.disable_ipv6_on_wifi &&
deadbeefd21eab32017-07-26 16:50:11 -0700698 max_ipv6_networks == o.max_ipv6_networks &&
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +0100699 disable_link_local_networks == o.disable_link_local_networks &&
deadbeef293e9262017-01-11 12:28:30 -0800700 enable_rtp_data_channel == o.enable_rtp_data_channel &&
deadbeef293e9262017-01-11 12:28:30 -0800701 screencast_min_bitrate == o.screencast_min_bitrate &&
702 combined_audio_video_bwe == o.combined_audio_video_bwe &&
703 enable_dtls_srtp == o.enable_dtls_srtp &&
704 ice_candidate_pool_size == o.ice_candidate_pool_size &&
705 prune_turn_ports == o.prune_turn_ports &&
706 presume_writable_when_fully_relayed ==
707 o.presume_writable_when_fully_relayed &&
708 enable_ice_renomination == o.enable_ice_renomination &&
skvlad51072462017-02-02 11:50:14 -0800709 redetermine_role_on_ice_restart == o.redetermine_role_on_ice_restart &&
Qingsi Wange6826d22018-03-08 14:55:14 -0800710 ice_check_interval_strong_connectivity ==
711 o.ice_check_interval_strong_connectivity &&
712 ice_check_interval_weak_connectivity ==
713 o.ice_check_interval_weak_connectivity &&
Steve Anton300bf8e2017-07-14 10:13:10 -0700714 ice_check_min_interval == o.ice_check_min_interval &&
Qingsi Wang22e623a2018-03-13 10:53:57 -0700715 ice_unwritable_timeout == o.ice_unwritable_timeout &&
716 ice_unwritable_min_checks == o.ice_unwritable_min_checks &&
Qingsi Wangdb53f8e2018-02-20 14:45:49 -0800717 stun_candidate_keepalive_interval ==
718 o.stun_candidate_keepalive_interval &&
Jonas Orelandbdcee282017-10-10 14:01:40 +0200719 ice_regather_interval_range == o.ice_regather_interval_range &&
Steve Anton79e79602017-11-20 10:25:56 -0800720 turn_customizer == o.turn_customizer &&
Qingsi Wang9a5c6f82018-02-01 10:38:40 -0800721 sdp_semantics == o.sdp_semantics &&
722 network_preference == o.network_preference;
deadbeef293e9262017-01-11 12:28:30 -0800723}
724
725bool PeerConnectionInterface::RTCConfiguration::operator!=(
726 const PeerConnectionInterface::RTCConfiguration& o) const {
727 return !(*this == o);
deadbeef3edec7c2016-12-10 11:44:26 -0800728}
729
zhihuang8f65cdf2016-05-06 18:40:30 -0700730// Generate a RTCP CNAME when a PeerConnection is created.
731std::string GenerateRtcpCname() {
732 std::string cname;
733 if (!rtc::CreateRandomString(kRtcpCnameLength, &cname)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100734 RTC_LOG(LS_ERROR) << "Failed to generate CNAME.";
nisseeb4ca4e2017-01-12 02:24:27 -0800735 RTC_NOTREACHED();
zhihuang8f65cdf2016-05-06 18:40:30 -0700736 }
737 return cname;
738}
739
zhihuang1c378ed2017-08-17 14:10:50 -0700740bool ValidateOfferAnswerOptions(
741 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options) {
742 return IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_audio) &&
743 IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_video);
olka3c747662017-08-17 06:50:32 -0700744}
745
zhihuang1c378ed2017-08-17 14:10:50 -0700746// From |rtc_options|, fill parts of |session_options| shared by all generated
747// m= sections (in other words, nothing that involves a map/array).
748void ExtractSharedMediaSessionOptions(
749 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options,
750 cricket::MediaSessionOptions* session_options) {
751 session_options->vad_enabled = rtc_options.voice_activity_detection;
752 session_options->bundle_enabled = rtc_options.use_rtp_mux;
753}
zhihuanga77e6bb2017-08-14 18:17:48 -0700754
zhihuang1c378ed2017-08-17 14:10:50 -0700755bool ConvertConstraintsToOfferAnswerOptions(
756 const MediaConstraintsInterface* constraints,
757 PeerConnectionInterface::RTCOfferAnswerOptions* offer_answer_options) {
olka3c747662017-08-17 06:50:32 -0700758 if (!constraints) {
759 return true;
760 }
zhihuang1c378ed2017-08-17 14:10:50 -0700761
762 bool value = false;
763 size_t mandatory_constraints_satisfied = 0;
764
765 if (FindConstraint(constraints,
766 MediaConstraintsInterface::kOfferToReceiveAudio, &value,
767 &mandatory_constraints_satisfied)) {
768 offer_answer_options->offer_to_receive_audio =
769 value ? PeerConnectionInterface::RTCOfferAnswerOptions::
770 kOfferToReceiveMediaTrue
771 : 0;
772 }
773
774 if (FindConstraint(constraints,
775 MediaConstraintsInterface::kOfferToReceiveVideo, &value,
776 &mandatory_constraints_satisfied)) {
777 offer_answer_options->offer_to_receive_video =
778 value ? PeerConnectionInterface::RTCOfferAnswerOptions::
779 kOfferToReceiveMediaTrue
780 : 0;
781 }
782 if (FindConstraint(constraints,
783 MediaConstraintsInterface::kVoiceActivityDetection, &value,
784 &mandatory_constraints_satisfied)) {
785 offer_answer_options->voice_activity_detection = value;
786 }
787 if (FindConstraint(constraints, MediaConstraintsInterface::kUseRtpMux, &value,
788 &mandatory_constraints_satisfied)) {
789 offer_answer_options->use_rtp_mux = value;
790 }
791 if (FindConstraint(constraints, MediaConstraintsInterface::kIceRestart,
792 &value, &mandatory_constraints_satisfied)) {
793 offer_answer_options->ice_restart = value;
794 }
795
deadbeefab9b2d12015-10-14 11:33:11 -0700796 return mandatory_constraints_satisfied == constraints->GetMandatory().size();
797}
798
zhihuang38ede132017-06-15 12:52:32 -0700799PeerConnection::PeerConnection(PeerConnectionFactory* factory,
800 std::unique_ptr<RtcEventLog> event_log,
801 std::unique_ptr<Call> call)
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000802 : factory_(factory),
zhihuang38ede132017-06-15 12:52:32 -0700803 event_log_(std::move(event_log)),
zhihuang8f65cdf2016-05-06 18:40:30 -0700804 rtcp_cname_(GenerateRtcpCname()),
deadbeefab9b2d12015-10-14 11:33:11 -0700805 local_streams_(StreamCollection::Create()),
zhihuang38ede132017-06-15 12:52:32 -0700806 remote_streams_(StreamCollection::Create()),
807 call_(std::move(call)) {}
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000808
809PeerConnection::~PeerConnection() {
Peter Boström1a9d6152015-12-08 22:15:17 +0100810 TRACE_EVENT0("webrtc", "PeerConnection::~PeerConnection");
Steve Anton4171afb2017-11-20 10:20:22 -0800811 RTC_DCHECK_RUN_ON(signaling_thread());
812
Steve Anton8af21862017-12-15 11:20:13 -0800813 // Need to stop transceivers before destroying the stats collector because
814 // AudioRtpSender has a reference to the StatsCollector it will update when
815 // stopping.
816 for (auto transceiver : transceivers_) {
817 transceiver->Stop();
818 }
Steve Anton4171afb2017-11-20 10:20:22 -0800819
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700820 stats_.reset(nullptr);
hbosb78306a2016-12-19 05:06:57 -0800821 if (stats_collector_) {
822 stats_collector_->WaitForPendingRequest();
823 stats_collector_ = nullptr;
824 }
Steve Anton75737c02017-11-06 10:37:17 -0800825
Steve Anton8af21862017-12-15 11:20:13 -0800826 // Don't destroy BaseChannels until after stats has been cleaned up so that
827 // the last stats request can still read from the channels.
828 DestroyAllChannels();
829
Mirko Bonadei675513b2017-11-09 11:09:25 +0100830 RTC_LOG(LS_INFO) << "Session: " << session_id() << " is destroyed.";
Steve Anton75737c02017-11-06 10:37:17 -0800831
832 webrtc_session_desc_factory_.reset();
833 sctp_invoker_.reset();
834 sctp_factory_.reset();
835 transport_controller_.reset();
836
deadbeef91dd5672016-05-18 16:55:30 -0700837 // port_allocator_ lives on the network thread and should be destroyed there.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700838 network_thread()->Invoke<void>(RTC_FROM_HERE,
nisseeaabdf62017-05-05 02:23:02 -0700839 [this] { port_allocator_.reset(); });
eladalon248fd4f2017-09-06 05:18:15 -0700840 // call_ and event_log_ must be destroyed on the worker thread.
Steve Anton978b8762017-09-29 12:15:02 -0700841 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
eladalon248fd4f2017-09-06 05:18:15 -0700842 call_.reset();
Qingsi Wang93a84392018-01-30 17:13:09 -0800843 // The event log must outlive call (and any other object that uses it).
eladalon248fd4f2017-09-06 05:18:15 -0700844 event_log_.reset();
845 });
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000846}
847
Steve Anton8af21862017-12-15 11:20:13 -0800848void PeerConnection::DestroyAllChannels() {
Steve Anton3fe1b152017-12-12 10:20:08 -0800849 // Destroy video channels first since they may have a pointer to a voice
850 // channel.
851 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -0800852 if (transceiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton3fe1b152017-12-12 10:20:08 -0800853 DestroyTransceiverChannel(transceiver);
854 }
855 }
856 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -0800857 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton3fe1b152017-12-12 10:20:08 -0800858 DestroyTransceiverChannel(transceiver);
859 }
860 }
861 DestroyDataChannel();
862}
863
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000864bool PeerConnection::Initialize(
buildbot@webrtc.org41451d42014-05-03 05:39:45 +0000865 const PeerConnectionInterface::RTCConfiguration& configuration,
kwibergd1fe2812016-04-27 06:47:29 -0700866 std::unique_ptr<cricket::PortAllocator> allocator,
Henrik Boströmd03c23b2016-06-01 11:44:18 +0200867 std::unique_ptr<rtc::RTCCertificateGeneratorInterface> cert_generator,
deadbeef653b8e02015-11-11 12:55:10 -0800868 PeerConnectionObserver* observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100869 TRACE_EVENT0("webrtc", "PeerConnection::Initialize");
Steve Anton038834f2017-07-14 15:59:59 -0700870
871 RTCError config_error = ValidateConfiguration(configuration);
872 if (!config_error.ok()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100873 RTC_LOG(LS_ERROR) << "Invalid configuration: " << config_error.message();
Steve Anton038834f2017-07-14 15:59:59 -0700874 return false;
875 }
876
deadbeef293e9262017-01-11 12:28:30 -0800877 if (!allocator) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100878 RTC_LOG(LS_ERROR)
879 << "PeerConnection initialized without a PortAllocator? "
Jonas Olsson45cc8902018-02-13 10:37:07 +0100880 "This shouldn't happen if using PeerConnectionFactory.";
deadbeef293e9262017-01-11 12:28:30 -0800881 return false;
882 }
Jonas Orelandbdcee282017-10-10 14:01:40 +0200883
deadbeef653b8e02015-11-11 12:55:10 -0800884 if (!observer) {
deadbeef293e9262017-01-11 12:28:30 -0800885 // TODO(deadbeef): Why do we do this?
Mirko Bonadei675513b2017-11-09 11:09:25 +0100886 RTC_LOG(LS_ERROR) << "PeerConnection initialized without a "
Jonas Olsson45cc8902018-02-13 10:37:07 +0100887 "PeerConnectionObserver";
deadbeef653b8e02015-11-11 12:55:10 -0800888 return false;
889 }
pthatcher@webrtc.org877ac762015-02-04 22:03:09 +0000890 observer_ = observer;
kwiberg0eb15ed2015-12-17 03:04:15 -0800891 port_allocator_ = std::move(allocator);
deadbeef653b8e02015-11-11 12:55:10 -0800892
deadbeef91dd5672016-05-18 16:55:30 -0700893 // The port allocator lives on the network thread and should be initialized
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700894 // there.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700895 if (!network_thread()->Invoke<bool>(
896 RTC_FROM_HERE, rtc::Bind(&PeerConnection::InitializePortAllocator_n,
897 this, configuration))) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000898 return false;
899 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000900
Steve Anton75737c02017-11-06 10:37:17 -0800901 // RFC 3264: The numeric value of the session id and version in the
902 // o line MUST be representable with a "64 bit signed integer".
903 // Due to this constraint session id |session_id_| is max limited to
904 // LLONG_MAX.
905 session_id_ = rtc::ToString(rtc::CreateRandomId64() & LLONG_MAX);
906 transport_controller_.reset(factory_->CreateTransportController(
Qingsi Wang93a84392018-01-30 17:13:09 -0800907 port_allocator_.get(), configuration.redetermine_role_on_ice_restart,
908 event_log_.get()));
Steve Anton75737c02017-11-06 10:37:17 -0800909 transport_controller_->SetIceRole(cricket::ICEROLE_CONTROLLED);
910 transport_controller_->SignalConnectionState.connect(
911 this, &PeerConnection::OnTransportControllerConnectionState);
912 transport_controller_->SignalGatheringState.connect(
913 this, &PeerConnection::OnTransportControllerGatheringState);
914 transport_controller_->SignalCandidatesGathered.connect(
915 this, &PeerConnection::OnTransportControllerCandidatesGathered);
916 transport_controller_->SignalCandidatesRemoved.connect(
917 this, &PeerConnection::OnTransportControllerCandidatesRemoved);
918 transport_controller_->SignalDtlsHandshakeError.connect(
919 this, &PeerConnection::OnTransportControllerDtlsHandshakeError);
920
921 sctp_factory_ = factory_->CreateSctpTransportInternalFactory();
zhihuang29ff8442016-07-27 11:07:25 -0700922
deadbeefab9b2d12015-10-14 11:33:11 -0700923 stats_.reset(new StatsCollector(this));
hbos74e1a4f2016-09-15 23:33:01 -0700924 stats_collector_ = RTCStatsCollector::Create(this);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000925
Steve Antonba818672017-11-06 10:21:57 -0800926 configuration_ = configuration;
927
Steve Anton75737c02017-11-06 10:37:17 -0800928 const PeerConnectionFactoryInterface::Options& options = factory_->options();
929
930 transport_controller_->SetSslMaxProtocolVersion(options.ssl_max_version);
931
932 // Obtain a certificate from RTCConfiguration if any were provided (optional).
933 rtc::scoped_refptr<rtc::RTCCertificate> certificate;
934 if (!configuration.certificates.empty()) {
935 // TODO(hbos,torbjorng): Decide on certificate-selection strategy instead of
936 // just picking the first one. The decision should be made based on the DTLS
937 // handshake. The DTLS negotiations need to know about all certificates.
938 certificate = configuration.certificates[0];
939 }
940
Steve Antond25da372017-11-06 14:50:29 -0800941 transport_controller_->SetIceConfig(ParseIceConfig(configuration));
Steve Anton75737c02017-11-06 10:37:17 -0800942
943 if (options.disable_encryption) {
944 dtls_enabled_ = false;
945 } else {
946 // Enable DTLS by default if we have an identity store or a certificate.
947 dtls_enabled_ = (cert_generator || certificate);
948 // |configuration| can override the default |dtls_enabled_| value.
949 if (configuration.enable_dtls_srtp) {
950 dtls_enabled_ = *(configuration.enable_dtls_srtp);
951 }
952 }
953
954 // Enable creation of RTP data channels if the kEnableRtpDataChannels is set.
955 // It takes precendence over the disable_sctp_data_channels
956 // PeerConnectionFactoryInterface::Options.
957 if (configuration.enable_rtp_data_channel) {
958 data_channel_type_ = cricket::DCT_RTP;
959 } else {
960 // DTLS has to be enabled to use SCTP.
961 if (!options.disable_sctp_data_channels && dtls_enabled_) {
962 data_channel_type_ = cricket::DCT_SCTP;
963 }
964 }
965
966 video_options_.screencast_min_bitrate_kbps =
967 configuration.screencast_min_bitrate;
968 audio_options_.combined_audio_video_bwe =
969 configuration.combined_audio_video_bwe;
970
971 audio_options_.audio_jitter_buffer_max_packets =
Oskar Sundbom9b28a032017-11-16 10:53:30 +0100972 configuration.audio_jitter_buffer_max_packets;
Steve Anton75737c02017-11-06 10:37:17 -0800973
974 audio_options_.audio_jitter_buffer_fast_accelerate =
Oskar Sundbom9b28a032017-11-16 10:53:30 +0100975 configuration.audio_jitter_buffer_fast_accelerate;
Steve Anton75737c02017-11-06 10:37:17 -0800976
977 // Whether the certificate generator/certificate is null or not determines
978 // what PeerConnectionDescriptionFactory will do, so make sure that we give it
979 // the right instructions by clearing the variables if needed.
980 if (!dtls_enabled_) {
981 cert_generator.reset();
982 certificate = nullptr;
983 } else if (certificate) {
984 // Favor generated certificate over the certificate generator.
985 cert_generator.reset();
986 }
987
988 webrtc_session_desc_factory_.reset(new WebRtcSessionDescriptionFactory(
989 signaling_thread(), channel_manager(), this, session_id(),
990 std::move(cert_generator), certificate));
991 webrtc_session_desc_factory_->SignalCertificateReady.connect(
992 this, &PeerConnection::OnCertificateReady);
993
994 if (options.disable_encryption) {
995 webrtc_session_desc_factory_->SetSdesPolicy(cricket::SEC_DISABLED);
996 }
997
998 webrtc_session_desc_factory_->set_enable_encrypted_rtp_header_extensions(
999 options.crypto_options.enable_encrypted_rtp_header_extensions);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001000
Steve Anton4171afb2017-11-20 10:20:22 -08001001 // Add default audio/video transceivers for Plan B SDP.
1002 if (!IsUnifiedPlan()) {
1003 transceivers_.push_back(
1004 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1005 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_AUDIO)));
1006 transceivers_.push_back(
1007 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1008 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_VIDEO)));
1009 }
1010
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001011 return true;
1012}
1013
Steve Anton038834f2017-07-14 15:59:59 -07001014RTCError PeerConnection::ValidateConfiguration(
1015 const RTCConfiguration& config) const {
1016 if (config.ice_regather_interval_range &&
1017 config.continual_gathering_policy == GATHER_ONCE) {
1018 return RTCError(RTCErrorType::INVALID_PARAMETER,
1019 "ice_regather_interval_range specified but continual "
1020 "gathering policy is GATHER_ONCE");
1021 }
1022 return RTCError::OK();
1023}
1024
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001025rtc::scoped_refptr<StreamCollectionInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001026PeerConnection::local_streams() {
Steve Antonfc853712018-03-01 13:48:58 -08001027 RTC_CHECK(!IsUnifiedPlan()) << "local_streams is not available with Unified "
1028 "Plan SdpSemantics. Please use GetSenders "
1029 "instead.";
deadbeefab9b2d12015-10-14 11:33:11 -07001030 return local_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001031}
1032
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001033rtc::scoped_refptr<StreamCollectionInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001034PeerConnection::remote_streams() {
Steve Antonfc853712018-03-01 13:48:58 -08001035 RTC_CHECK(!IsUnifiedPlan()) << "remote_streams is not available with Unified "
1036 "Plan SdpSemantics. Please use GetReceivers "
1037 "instead.";
deadbeefab9b2d12015-10-14 11:33:11 -07001038 return remote_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001039}
1040
perkj@webrtc.orgc2dd5ee2014-11-04 11:31:29 +00001041bool PeerConnection::AddStream(MediaStreamInterface* local_stream) {
Steve Antonfc853712018-03-01 13:48:58 -08001042 RTC_CHECK(!IsUnifiedPlan()) << "AddStream is not available with Unified Plan "
1043 "SdpSemantics. Please use AddTrack instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001044 TRACE_EVENT0("webrtc", "PeerConnection::AddStream");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001045 if (IsClosed()) {
1046 return false;
1047 }
deadbeefab9b2d12015-10-14 11:33:11 -07001048 if (!CanAddLocalMediaStream(local_streams_, local_stream)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001049 return false;
1050 }
deadbeefab9b2d12015-10-14 11:33:11 -07001051
1052 local_streams_->AddStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -08001053 MediaStreamObserver* observer = new MediaStreamObserver(local_stream);
1054 observer->SignalAudioTrackAdded.connect(this,
1055 &PeerConnection::OnAudioTrackAdded);
1056 observer->SignalAudioTrackRemoved.connect(
1057 this, &PeerConnection::OnAudioTrackRemoved);
1058 observer->SignalVideoTrackAdded.connect(this,
1059 &PeerConnection::OnVideoTrackAdded);
1060 observer->SignalVideoTrackRemoved.connect(
1061 this, &PeerConnection::OnVideoTrackRemoved);
kwibergd1fe2812016-04-27 06:47:29 -07001062 stream_observers_.push_back(std::unique_ptr<MediaStreamObserver>(observer));
deadbeefab9b2d12015-10-14 11:33:11 -07001063
deadbeefab9b2d12015-10-14 11:33:11 -07001064 for (const auto& track : local_stream->GetAudioTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001065 AddAudioTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -07001066 }
1067 for (const auto& track : local_stream->GetVideoTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001068 AddVideoTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -07001069 }
1070
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001071 stats_->AddStream(local_stream);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001072 observer_->OnRenegotiationNeeded();
1073 return true;
1074}
1075
1076void PeerConnection::RemoveStream(MediaStreamInterface* local_stream) {
Steve Antonfc853712018-03-01 13:48:58 -08001077 RTC_CHECK(!IsUnifiedPlan()) << "RemoveStream is not available with Unified "
1078 "Plan SdpSemantics. Please use RemoveTrack "
1079 "instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001080 TRACE_EVENT0("webrtc", "PeerConnection::RemoveStream");
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001081 if (!IsClosed()) {
1082 for (const auto& track : local_stream->GetAudioTracks()) {
1083 RemoveAudioTrack(track.get(), local_stream);
1084 }
1085 for (const auto& track : local_stream->GetVideoTracks()) {
1086 RemoveVideoTrack(track.get(), local_stream);
1087 }
deadbeefab9b2d12015-10-14 11:33:11 -07001088 }
deadbeefab9b2d12015-10-14 11:33:11 -07001089 local_streams_->RemoveStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -08001090 stream_observers_.erase(
1091 std::remove_if(
1092 stream_observers_.begin(), stream_observers_.end(),
kwibergd1fe2812016-04-27 06:47:29 -07001093 [local_stream](const std::unique_ptr<MediaStreamObserver>& observer) {
Seth Hampson13b8bad2018-03-13 16:05:28 -07001094 return observer->stream()->id().compare(local_stream->id()) == 0;
deadbeefeb459812015-12-15 19:24:43 -08001095 }),
1096 stream_observers_.end());
deadbeefab9b2d12015-10-14 11:33:11 -07001097
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001098 if (IsClosed()) {
1099 return;
1100 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001101 observer_->OnRenegotiationNeeded();
1102}
1103
deadbeefe1f9d832016-01-14 15:35:42 -08001104rtc::scoped_refptr<RtpSenderInterface> PeerConnection::AddTrack(
1105 MediaStreamTrackInterface* track,
1106 std::vector<MediaStreamInterface*> streams) {
1107 TRACE_EVENT0("webrtc", "PeerConnection::AddTrack");
Seth Hampson845e8782018-03-02 11:34:10 -08001108 std::vector<std::string> stream_ids;
Steve Antonf9381f02017-12-14 10:23:57 -08001109 for (auto* stream : streams) {
1110 if (!stream) {
1111 RTC_LOG(LS_ERROR) << "Stream list has null element.";
1112 return nullptr;
1113 }
Seth Hampson13b8bad2018-03-13 16:05:28 -07001114 stream_ids.push_back(stream->id());
Steve Antonf9381f02017-12-14 10:23:57 -08001115 }
Seth Hampson845e8782018-03-02 11:34:10 -08001116 auto sender_or_error = AddTrack(track, stream_ids);
Steve Antonf9381f02017-12-14 10:23:57 -08001117 if (!sender_or_error.ok()) {
deadbeefe1f9d832016-01-14 15:35:42 -08001118 return nullptr;
1119 }
Steve Antonf9381f02017-12-14 10:23:57 -08001120 return sender_or_error.MoveValue();
1121}
1122
Steve Anton2d6c76a2018-01-05 17:10:52 -08001123RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::AddTrack(
Steve Antonf9381f02017-12-14 10:23:57 -08001124 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001125 const std::vector<std::string>& stream_ids) {
Steve Anton2d6c76a2018-01-05 17:10:52 -08001126 TRACE_EVENT0("webrtc", "PeerConnection::AddTrack");
Steve Antonf9381f02017-12-14 10:23:57 -08001127 if (!track) {
1128 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "Track is null.");
1129 }
1130 if (!(track->kind() == MediaStreamTrackInterface::kAudioKind ||
1131 track->kind() == MediaStreamTrackInterface::kVideoKind)) {
1132 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1133 "Track has invalid kind: " + track->kind());
1134 }
1135 // TODO(bugs.webrtc.org/7932): Support adding a track to multiple streams.
Seth Hampson845e8782018-03-02 11:34:10 -08001136 if (stream_ids.size() > 1u) {
Steve Antonf9381f02017-12-14 10:23:57 -08001137 LOG_AND_RETURN_ERROR(
1138 RTCErrorType::UNSUPPORTED_OPERATION,
1139 "AddTrack with more than one stream is not currently supported.");
1140 }
1141 if (IsClosed()) {
1142 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
1143 "PeerConnection is closed.");
deadbeefe1f9d832016-01-14 15:35:42 -08001144 }
Steve Anton4171afb2017-11-20 10:20:22 -08001145 if (FindSenderForTrack(track)) {
Steve Antonf9381f02017-12-14 10:23:57 -08001146 LOG_AND_RETURN_ERROR(
1147 RTCErrorType::INVALID_PARAMETER,
1148 "Sender already exists for track " + track->id() + ".");
deadbeefe1f9d832016-01-14 15:35:42 -08001149 }
Steve Antonf9381f02017-12-14 10:23:57 -08001150 // TODO(bugs.webrtc.org/7933): MediaSession expects the sender to have exactly
1151 // one stream. AddTrackInternal will return an error if there is more than one
1152 // stream, but if the caller specifies none then we need to generate a random
Seth Hampson845e8782018-03-02 11:34:10 -08001153 // stream id.
1154 std::vector<std::string> adjusted_stream_ids = stream_ids;
1155 if (stream_ids.empty()) {
1156 adjusted_stream_ids.push_back(rtc::CreateRandomUuid());
Steve Antonf9381f02017-12-14 10:23:57 -08001157 }
Seth Hampson845e8782018-03-02 11:34:10 -08001158 RTC_DCHECK_EQ(1, adjusted_stream_ids.size());
Steve Antonf9381f02017-12-14 10:23:57 -08001159 auto sender_or_error =
Seth Hampson845e8782018-03-02 11:34:10 -08001160 (IsUnifiedPlan() ? AddTrackUnifiedPlan(track, adjusted_stream_ids)
1161 : AddTrackPlanB(track, adjusted_stream_ids));
Steve Antonf9381f02017-12-14 10:23:57 -08001162 if (sender_or_error.ok()) {
1163 observer_->OnRenegotiationNeeded();
Steve Anton43a723a2018-01-04 15:48:17 -08001164 stats_->AddTrack(track);
Steve Antonf9381f02017-12-14 10:23:57 -08001165 }
1166 return sender_or_error;
1167}
deadbeefe1f9d832016-01-14 15:35:42 -08001168
Steve Antonf9381f02017-12-14 10:23:57 -08001169RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>>
1170PeerConnection::AddTrackPlanB(
1171 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001172 const std::vector<std::string>& stream_ids) {
Steve Anton02ee47c2018-01-10 16:26:06 -08001173 cricket::MediaType media_type =
1174 (track->kind() == MediaStreamTrackInterface::kAudioKind
1175 ? cricket::MEDIA_TYPE_AUDIO
1176 : cricket::MEDIA_TYPE_VIDEO);
Seth Hampson845e8782018-03-02 11:34:10 -08001177 auto new_sender = CreateSender(media_type, track, stream_ids);
deadbeefe1f9d832016-01-14 15:35:42 -08001178 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
Steve Anton57858b32018-02-15 15:19:50 -08001179 new_sender->internal()->SetVoiceMediaChannel(voice_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08001180 GetAudioTransceiver()->internal()->AddSender(new_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001181 const RtpSenderInfo* sender_info =
1182 FindSenderInfo(local_audio_sender_infos_,
1183 new_sender->internal()->stream_id(), track->id());
1184 if (sender_info) {
1185 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -08001186 }
Steve Antonf9381f02017-12-14 10:23:57 -08001187 } else {
1188 RTC_DCHECK_EQ(MediaStreamTrackInterface::kVideoKind, track->kind());
Steve Anton57858b32018-02-15 15:19:50 -08001189 new_sender->internal()->SetVideoMediaChannel(video_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08001190 GetVideoTransceiver()->internal()->AddSender(new_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001191 const RtpSenderInfo* sender_info =
1192 FindSenderInfo(local_video_sender_infos_,
1193 new_sender->internal()->stream_id(), track->id());
1194 if (sender_info) {
1195 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -08001196 }
deadbeefe1f9d832016-01-14 15:35:42 -08001197 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001198 return rtc::scoped_refptr<RtpSenderInterface>(new_sender);
Steve Antonf9381f02017-12-14 10:23:57 -08001199}
deadbeefe1f9d832016-01-14 15:35:42 -08001200
Steve Antonf9381f02017-12-14 10:23:57 -08001201RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>>
1202PeerConnection::AddTrackUnifiedPlan(
1203 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001204 const std::vector<std::string>& stream_ids) {
Steve Antonf9381f02017-12-14 10:23:57 -08001205 auto transceiver = FindFirstTransceiverForAddedTrack(track);
1206 if (transceiver) {
1207 if (transceiver->direction() == RtpTransceiverDirection::kRecvOnly) {
Steve Anton52d86772018-02-20 15:48:12 -08001208 transceiver->internal()->set_direction(
1209 RtpTransceiverDirection::kSendRecv);
Steve Antonf9381f02017-12-14 10:23:57 -08001210 } else if (transceiver->direction() == RtpTransceiverDirection::kInactive) {
Steve Anton52d86772018-02-20 15:48:12 -08001211 transceiver->internal()->set_direction(
1212 RtpTransceiverDirection::kSendOnly);
Steve Antonf9381f02017-12-14 10:23:57 -08001213 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001214 transceiver->sender()->SetTrack(track);
Seth Hampson845e8782018-03-02 11:34:10 -08001215 transceiver->internal()->sender_internal()->set_stream_ids(stream_ids);
Steve Antonf9381f02017-12-14 10:23:57 -08001216 } else {
1217 cricket::MediaType media_type =
1218 (track->kind() == MediaStreamTrackInterface::kAudioKind
1219 ? cricket::MEDIA_TYPE_AUDIO
1220 : cricket::MEDIA_TYPE_VIDEO);
Seth Hampson845e8782018-03-02 11:34:10 -08001221 auto sender = CreateSender(media_type, track, stream_ids);
Steve Anton02ee47c2018-01-10 16:26:06 -08001222 auto receiver = CreateReceiver(media_type, rtc::CreateRandomUuid());
1223 transceiver = CreateAndAddTransceiver(sender, receiver);
Steve Antonf9381f02017-12-14 10:23:57 -08001224 transceiver->internal()->set_created_by_addtrack(true);
Steve Anton52d86772018-02-20 15:48:12 -08001225 transceiver->internal()->set_direction(RtpTransceiverDirection::kSendRecv);
Steve Antonf9381f02017-12-14 10:23:57 -08001226 }
Steve Antonf9381f02017-12-14 10:23:57 -08001227 return transceiver->sender();
1228}
1229
1230rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1231PeerConnection::FindFirstTransceiverForAddedTrack(
1232 rtc::scoped_refptr<MediaStreamTrackInterface> track) {
1233 RTC_DCHECK(track);
1234 for (auto transceiver : transceivers_) {
1235 if (!transceiver->sender()->track() &&
Steve Anton69470252018-02-09 11:43:08 -08001236 cricket::MediaTypeToString(transceiver->media_type()) ==
Steve Antonf9381f02017-12-14 10:23:57 -08001237 track->kind() &&
Seth Hampson2f0d7022018-02-20 11:54:42 -08001238 !transceiver->internal()->has_ever_been_used_to_send() &&
1239 !transceiver->stopped()) {
Steve Antonf9381f02017-12-14 10:23:57 -08001240 return transceiver;
1241 }
1242 }
1243 return nullptr;
deadbeefe1f9d832016-01-14 15:35:42 -08001244}
1245
1246bool PeerConnection::RemoveTrack(RtpSenderInterface* sender) {
1247 TRACE_EVENT0("webrtc", "PeerConnection::RemoveTrack");
Steve Antonf9381f02017-12-14 10:23:57 -08001248 return RemoveTrackInternal(sender).ok();
1249}
1250
1251RTCError PeerConnection::RemoveTrackInternal(
1252 rtc::scoped_refptr<RtpSenderInterface> sender) {
1253 if (!sender) {
1254 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "Sender is null.");
1255 }
deadbeefe1f9d832016-01-14 15:35:42 -08001256 if (IsClosed()) {
Steve Antonf9381f02017-12-14 10:23:57 -08001257 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
1258 "PeerConnection is closed.");
deadbeefe1f9d832016-01-14 15:35:42 -08001259 }
Steve Antonf9381f02017-12-14 10:23:57 -08001260 if (IsUnifiedPlan()) {
1261 auto transceiver = FindTransceiverBySender(sender);
1262 if (!transceiver || !sender->track()) {
1263 return RTCError::OK();
1264 }
1265 sender->SetTrack(nullptr);
1266 if (transceiver->direction() == RtpTransceiverDirection::kSendRecv) {
Steve Anton52d86772018-02-20 15:48:12 -08001267 transceiver->internal()->set_direction(
1268 RtpTransceiverDirection::kRecvOnly);
Steve Antonf9381f02017-12-14 10:23:57 -08001269 } else if (transceiver->direction() == RtpTransceiverDirection::kSendOnly) {
Steve Anton52d86772018-02-20 15:48:12 -08001270 transceiver->internal()->set_direction(
1271 RtpTransceiverDirection::kInactive);
Steve Antonf9381f02017-12-14 10:23:57 -08001272 }
Steve Anton4171afb2017-11-20 10:20:22 -08001273 } else {
Steve Antonf9381f02017-12-14 10:23:57 -08001274 bool removed;
1275 if (sender->media_type() == cricket::MEDIA_TYPE_AUDIO) {
1276 removed = GetAudioTransceiver()->internal()->RemoveSender(sender);
1277 } else {
1278 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, sender->media_type());
1279 removed = GetVideoTransceiver()->internal()->RemoveSender(sender);
1280 }
1281 if (!removed) {
1282 LOG_AND_RETURN_ERROR(
1283 RTCErrorType::INVALID_PARAMETER,
1284 "Couldn't find sender " + sender->id() + " to remove.");
1285 }
Steve Anton4171afb2017-11-20 10:20:22 -08001286 }
deadbeefe1f9d832016-01-14 15:35:42 -08001287 observer_->OnRenegotiationNeeded();
Steve Antonf9381f02017-12-14 10:23:57 -08001288 return RTCError::OK();
1289}
1290
1291rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1292PeerConnection::FindTransceiverBySender(
1293 rtc::scoped_refptr<RtpSenderInterface> sender) {
1294 for (auto transceiver : transceivers_) {
1295 if (transceiver->sender() == sender) {
1296 return transceiver;
1297 }
1298 }
1299 return nullptr;
deadbeefe1f9d832016-01-14 15:35:42 -08001300}
1301
Steve Anton9158ef62017-11-27 13:01:52 -08001302RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1303PeerConnection::AddTransceiver(
1304 rtc::scoped_refptr<MediaStreamTrackInterface> track) {
1305 return AddTransceiver(track, RtpTransceiverInit());
1306}
1307
1308RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1309PeerConnection::AddTransceiver(
1310 rtc::scoped_refptr<MediaStreamTrackInterface> track,
1311 const RtpTransceiverInit& init) {
Steve Antonfc853712018-03-01 13:48:58 -08001312 RTC_CHECK(IsUnifiedPlan())
1313 << "AddTransceiver is only available with Unified Plan SdpSemantics";
Steve Anton9158ef62017-11-27 13:01:52 -08001314 if (!track) {
1315 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "track is null");
1316 }
1317 cricket::MediaType media_type;
1318 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
1319 media_type = cricket::MEDIA_TYPE_AUDIO;
1320 } else if (track->kind() == MediaStreamTrackInterface::kVideoKind) {
1321 media_type = cricket::MEDIA_TYPE_VIDEO;
1322 } else {
1323 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1324 "Track kind is not audio or video");
1325 }
1326 return AddTransceiver(media_type, track, init);
1327}
1328
1329RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1330PeerConnection::AddTransceiver(cricket::MediaType media_type) {
1331 return AddTransceiver(media_type, RtpTransceiverInit());
1332}
1333
1334RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1335PeerConnection::AddTransceiver(cricket::MediaType media_type,
1336 const RtpTransceiverInit& init) {
Steve Antonfc853712018-03-01 13:48:58 -08001337 RTC_CHECK(IsUnifiedPlan())
1338 << "AddTransceiver is only available with Unified Plan SdpSemantics";
Steve Anton9158ef62017-11-27 13:01:52 -08001339 if (!(media_type == cricket::MEDIA_TYPE_AUDIO ||
1340 media_type == cricket::MEDIA_TYPE_VIDEO)) {
1341 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1342 "media type is not audio or video");
1343 }
1344 return AddTransceiver(media_type, nullptr, init);
1345}
1346
1347RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1348PeerConnection::AddTransceiver(
1349 cricket::MediaType media_type,
1350 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Steve Anton22da89f2018-01-25 13:58:07 -08001351 const RtpTransceiverInit& init,
1352 bool fire_callback) {
Steve Anton9158ef62017-11-27 13:01:52 -08001353 RTC_DCHECK((media_type == cricket::MEDIA_TYPE_AUDIO ||
1354 media_type == cricket::MEDIA_TYPE_VIDEO));
1355 if (track) {
1356 RTC_DCHECK_EQ(media_type,
1357 (track->kind() == MediaStreamTrackInterface::kAudioKind
1358 ? cricket::MEDIA_TYPE_AUDIO
1359 : cricket::MEDIA_TYPE_VIDEO));
1360 }
1361
1362 // TODO(bugs.webrtc.org/7600): Verify init.
1363
Seth Hampson513449e2018-03-06 09:35:56 -08001364 if (init.stream_ids.size() > 1u) {
Steve Anton02ee47c2018-01-10 16:26:06 -08001365 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
1366 "More than one stream is not yet supported.");
Steve Antonf9381f02017-12-14 10:23:57 -08001367 }
1368
Seth Hampson513449e2018-03-06 09:35:56 -08001369 std::vector<std::string> stream_ids = {
1370 !init.stream_ids.empty() ? init.stream_ids[0] : rtc::CreateRandomUuid()};
Steve Anton02ee47c2018-01-10 16:26:06 -08001371
Seth Hampson845e8782018-03-02 11:34:10 -08001372 auto sender = CreateSender(media_type, track, stream_ids);
Steve Anton02ee47c2018-01-10 16:26:06 -08001373 auto receiver = CreateReceiver(media_type, rtc::CreateRandomUuid());
1374 auto transceiver = CreateAndAddTransceiver(sender, receiver);
1375 transceiver->internal()->set_direction(init.direction);
1376
Steve Anton22da89f2018-01-25 13:58:07 -08001377 if (fire_callback) {
1378 observer_->OnRenegotiationNeeded();
1379 }
Steve Antonf9381f02017-12-14 10:23:57 -08001380
1381 return rtc::scoped_refptr<RtpTransceiverInterface>(transceiver);
1382}
1383
Steve Anton02ee47c2018-01-10 16:26:06 -08001384rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
1385PeerConnection::CreateSender(
1386 cricket::MediaType media_type,
1387 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001388 const std::vector<std::string>& stream_ids) {
Steve Anton9158ef62017-11-27 13:01:52 -08001389 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> sender;
Steve Anton02ee47c2018-01-10 16:26:06 -08001390 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
1391 RTC_DCHECK(!track ||
1392 (track->kind() == MediaStreamTrackInterface::kAudioKind));
1393 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
1394 signaling_thread(),
Steve Anton47136dd2018-01-12 10:49:35 -08001395 new AudioRtpSender(worker_thread(),
1396 static_cast<AudioTrackInterface*>(track.get()),
Seth Hampson845e8782018-03-02 11:34:10 -08001397 stream_ids, stats_.get()));
Steve Anton02ee47c2018-01-10 16:26:06 -08001398 } else {
1399 RTC_DCHECK_EQ(media_type, cricket::MEDIA_TYPE_VIDEO);
1400 RTC_DCHECK(!track ||
1401 (track->kind() == MediaStreamTrackInterface::kVideoKind));
1402 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
1403 signaling_thread(),
Steve Anton47136dd2018-01-12 10:49:35 -08001404 new VideoRtpSender(worker_thread(),
1405 static_cast<VideoTrackInterface*>(track.get()),
Seth Hampson845e8782018-03-02 11:34:10 -08001406 stream_ids));
Steve Anton02ee47c2018-01-10 16:26:06 -08001407 }
Seth Hampson845e8782018-03-02 11:34:10 -08001408 sender->internal()->set_stream_ids(stream_ids);
Steve Anton02ee47c2018-01-10 16:26:06 -08001409 return sender;
1410}
1411
1412rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1413PeerConnection::CreateReceiver(cricket::MediaType media_type,
1414 const std::string& receiver_id) {
Steve Anton9158ef62017-11-27 13:01:52 -08001415 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1416 receiver;
Steve Anton9158ef62017-11-27 13:01:52 -08001417 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton9158ef62017-11-27 13:01:52 -08001418 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
Steve Anton60776752018-01-10 11:51:34 -08001419 signaling_thread(),
Steve Antond3679212018-01-17 17:41:02 -08001420 new AudioRtpReceiver(worker_thread(), receiver_id, {}));
Steve Anton9158ef62017-11-27 13:01:52 -08001421 } else {
Steve Anton02ee47c2018-01-10 16:26:06 -08001422 RTC_DCHECK_EQ(media_type, cricket::MEDIA_TYPE_VIDEO);
Steve Anton9158ef62017-11-27 13:01:52 -08001423 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
1424 signaling_thread(),
Steve Antond3679212018-01-17 17:41:02 -08001425 new VideoRtpReceiver(worker_thread(), receiver_id, {}));
Steve Anton9158ef62017-11-27 13:01:52 -08001426 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001427 return receiver;
1428}
1429
1430rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1431PeerConnection::CreateAndAddTransceiver(
1432 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> sender,
1433 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1434 receiver) {
1435 auto transceiver = RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1436 signaling_thread(), new RtpTransceiver(sender, receiver));
Steve Anton9158ef62017-11-27 13:01:52 -08001437 transceivers_.push_back(transceiver);
Steve Anton52d86772018-02-20 15:48:12 -08001438 transceiver->internal()->SignalNegotiationNeeded.connect(
1439 this, &PeerConnection::OnNegotiationNeeded);
Steve Antonf9381f02017-12-14 10:23:57 -08001440 return transceiver;
Steve Anton9158ef62017-11-27 13:01:52 -08001441}
1442
Steve Anton52d86772018-02-20 15:48:12 -08001443void PeerConnection::OnNegotiationNeeded() {
1444 RTC_DCHECK_RUN_ON(signaling_thread());
1445 RTC_DCHECK(!IsClosed());
1446 observer_->OnRenegotiationNeeded();
1447}
1448
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001449rtc::scoped_refptr<DtmfSenderInterface> PeerConnection::CreateDtmfSender(
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001450 AudioTrackInterface* track) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001451 TRACE_EVENT0("webrtc", "PeerConnection::CreateDtmfSender");
zhihuang29ff8442016-07-27 11:07:25 -07001452 if (IsClosed()) {
1453 return nullptr;
1454 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001455 if (!track) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001456 RTC_LOG(LS_ERROR) << "CreateDtmfSender - track is NULL.";
deadbeef20cb0c12017-02-01 20:27:00 -08001457 return nullptr;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001458 }
Steve Anton4171afb2017-11-20 10:20:22 -08001459 auto track_sender = FindSenderForTrack(track);
1460 if (!track_sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001461 RTC_LOG(LS_ERROR) << "CreateDtmfSender called with a non-added track.";
deadbeef20cb0c12017-02-01 20:27:00 -08001462 return nullptr;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001463 }
1464
Steve Anton4171afb2017-11-20 10:20:22 -08001465 return track_sender->GetDtmfSender();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001466}
1467
deadbeeffac06552015-11-25 11:26:01 -08001468rtc::scoped_refptr<RtpSenderInterface> PeerConnection::CreateSender(
deadbeefbd7d8f72015-12-18 16:58:44 -08001469 const std::string& kind,
1470 const std::string& stream_id) {
Steve Antonfc853712018-03-01 13:48:58 -08001471 RTC_CHECK(!IsUnifiedPlan()) << "CreateSender is not available with Unified "
1472 "Plan SdpSemantics. Please use AddTransceiver "
1473 "instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001474 TRACE_EVENT0("webrtc", "PeerConnection::CreateSender");
zhihuang29ff8442016-07-27 11:07:25 -07001475 if (IsClosed()) {
1476 return nullptr;
1477 }
Steve Anton4171afb2017-11-20 10:20:22 -08001478
Seth Hampson845e8782018-03-02 11:34:10 -08001479 std::vector<std::string> stream_ids;
Steve Anton02ee47c2018-01-10 16:26:06 -08001480 if (!stream_id.empty()) {
Seth Hampson845e8782018-03-02 11:34:10 -08001481 stream_ids.push_back(stream_id);
Steve Anton02ee47c2018-01-10 16:26:06 -08001482 }
1483
Steve Anton4171afb2017-11-20 10:20:22 -08001484 // TODO(steveanton): Move construction of the RtpSenders to RtpTransceiver.
deadbeefa601f5c2016-06-06 14:27:39 -07001485 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender;
deadbeeffac06552015-11-25 11:26:01 -08001486 if (kind == MediaStreamTrackInterface::kAudioKind) {
Seth Hampson845e8782018-03-02 11:34:10 -08001487 auto* audio_sender =
1488 new AudioRtpSender(worker_thread(), nullptr, stream_ids, stats_.get());
Steve Anton57858b32018-02-15 15:19:50 -08001489 audio_sender->SetVoiceMediaChannel(voice_media_channel());
deadbeefa601f5c2016-06-06 14:27:39 -07001490 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton02ee47c2018-01-10 16:26:06 -08001491 signaling_thread(), audio_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001492 GetAudioTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 11:26:01 -08001493 } else if (kind == MediaStreamTrackInterface::kVideoKind) {
Steve Anton47136dd2018-01-12 10:49:35 -08001494 auto* video_sender =
Seth Hampson845e8782018-03-02 11:34:10 -08001495 new VideoRtpSender(worker_thread(), nullptr, stream_ids);
Steve Anton57858b32018-02-15 15:19:50 -08001496 video_sender->SetVideoMediaChannel(video_media_channel());
deadbeefa601f5c2016-06-06 14:27:39 -07001497 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton02ee47c2018-01-10 16:26:06 -08001498 signaling_thread(), video_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001499 GetVideoTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 11:26:01 -08001500 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001501 RTC_LOG(LS_ERROR) << "CreateSender called with invalid kind: " << kind;
Steve Anton4171afb2017-11-20 10:20:22 -08001502 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08001503 }
Steve Anton4171afb2017-11-20 10:20:22 -08001504
deadbeefe1f9d832016-01-14 15:35:42 -08001505 return new_sender;
deadbeeffac06552015-11-25 11:26:01 -08001506}
1507
deadbeef70ab1a12015-09-28 16:53:55 -07001508std::vector<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::GetSenders()
1509 const {
deadbeefa601f5c2016-06-06 14:27:39 -07001510 std::vector<rtc::scoped_refptr<RtpSenderInterface>> ret;
Steve Anton4171afb2017-11-20 10:20:22 -08001511 for (auto sender : GetSendersInternal()) {
1512 ret.push_back(sender);
deadbeefa601f5c2016-06-06 14:27:39 -07001513 }
1514 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -07001515}
1516
Steve Anton4171afb2017-11-20 10:20:22 -08001517std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1518PeerConnection::GetSendersInternal() const {
1519 std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1520 all_senders;
1521 for (auto transceiver : transceivers_) {
1522 auto senders = transceiver->internal()->senders();
1523 all_senders.insert(all_senders.end(), senders.begin(), senders.end());
1524 }
1525 return all_senders;
1526}
1527
deadbeef70ab1a12015-09-28 16:53:55 -07001528std::vector<rtc::scoped_refptr<RtpReceiverInterface>>
1529PeerConnection::GetReceivers() const {
deadbeefa601f5c2016-06-06 14:27:39 -07001530 std::vector<rtc::scoped_refptr<RtpReceiverInterface>> ret;
Steve Anton4171afb2017-11-20 10:20:22 -08001531 for (const auto& receiver : GetReceiversInternal()) {
1532 ret.push_back(receiver);
deadbeefa601f5c2016-06-06 14:27:39 -07001533 }
1534 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -07001535}
1536
Steve Anton4171afb2017-11-20 10:20:22 -08001537std::vector<
1538 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1539PeerConnection::GetReceiversInternal() const {
1540 std::vector<
1541 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1542 all_receivers;
1543 for (auto transceiver : transceivers_) {
1544 auto receivers = transceiver->internal()->receivers();
1545 all_receivers.insert(all_receivers.end(), receivers.begin(),
1546 receivers.end());
1547 }
1548 return all_receivers;
1549}
1550
Steve Anton9158ef62017-11-27 13:01:52 -08001551std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
1552PeerConnection::GetTransceivers() const {
Steve Antonfc853712018-03-01 13:48:58 -08001553 RTC_CHECK(IsUnifiedPlan())
1554 << "GetTransceivers is only supported with Unified Plan SdpSemantics.";
Steve Anton9158ef62017-11-27 13:01:52 -08001555 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> all_transceivers;
1556 for (auto transceiver : transceivers_) {
1557 all_transceivers.push_back(transceiver);
1558 }
1559 return all_transceivers;
1560}
1561
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001562bool PeerConnection::GetStats(StatsObserver* observer,
wu@webrtc.orgb9a088b2014-02-13 23:18:49 +00001563 MediaStreamTrackInterface* track,
1564 StatsOutputLevel level) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001565 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
deadbeef0a6c4ca2015-10-06 11:38:28 -07001566 RTC_DCHECK(signaling_thread()->IsCurrent());
nisse7ce109a2017-01-31 00:57:56 -08001567 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001568 RTC_LOG(LS_ERROR) << "GetStats - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001569 return false;
1570 }
1571
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001572 stats_->UpdateStats(level);
zhihuange9e94c32016-11-04 11:38:15 -07001573 // The StatsCollector is used to tell if a track is valid because it may
1574 // remember tracks that the PeerConnection previously removed.
1575 if (track && !stats_->IsValidTrack(track->id())) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001576 RTC_LOG(LS_WARNING) << "GetStats is called with an invalid track: "
1577 << track->id();
zhihuange9e94c32016-11-04 11:38:15 -07001578 return false;
1579 }
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001580 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_GETSTATS,
tommi@webrtc.org5b06b062014-08-15 08:38:30 +00001581 new GetStatsMsg(observer, track));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001582 return true;
1583}
1584
hbos74e1a4f2016-09-15 23:33:01 -07001585void PeerConnection::GetStats(RTCStatsCollectorCallback* callback) {
1586 RTC_DCHECK(stats_collector_);
1587 stats_collector_->GetStatsReport(callback);
1588}
1589
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001590PeerConnectionInterface::SignalingState PeerConnection::signaling_state() {
1591 return signaling_state_;
1592}
1593
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001594PeerConnectionInterface::IceConnectionState
1595PeerConnection::ice_connection_state() {
1596 return ice_connection_state_;
1597}
1598
1599PeerConnectionInterface::IceGatheringState
1600PeerConnection::ice_gathering_state() {
1601 return ice_gathering_state_;
1602}
1603
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001604rtc::scoped_refptr<DataChannelInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001605PeerConnection::CreateDataChannel(
1606 const std::string& label,
1607 const DataChannelInit* config) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001608 TRACE_EVENT0("webrtc", "PeerConnection::CreateDataChannel");
zhihuang9763d562016-08-05 11:14:50 -07001609
deadbeefab9b2d12015-10-14 11:33:11 -07001610 bool first_datachannel = !HasDataChannels();
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001611
kwibergd1fe2812016-04-27 06:47:29 -07001612 std::unique_ptr<InternalDataChannelInit> internal_config;
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00001613 if (config) {
1614 internal_config.reset(new InternalDataChannelInit(*config));
1615 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001616 rtc::scoped_refptr<DataChannelInterface> channel(
deadbeefab9b2d12015-10-14 11:33:11 -07001617 InternalCreateDataChannel(label, internal_config.get()));
1618 if (!channel.get()) {
1619 return nullptr;
1620 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001621
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001622 // Trigger the onRenegotiationNeeded event for every new RTP DataChannel, or
1623 // the first SCTP DataChannel.
Steve Anton75737c02017-11-06 10:37:17 -08001624 if (data_channel_type() == cricket::DCT_RTP || first_datachannel) {
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001625 observer_->OnRenegotiationNeeded();
1626 }
wu@webrtc.org91053e72013-08-10 07:18:04 +00001627
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001628 return DataChannelProxy::Create(signaling_thread(), channel.get());
1629}
1630
1631void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
1632 const MediaConstraintsInterface* constraints) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001633 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
Steve Anton8d3444d2017-10-20 15:30:51 -07001634
zhihuang1c378ed2017-08-17 14:10:50 -07001635 PeerConnectionInterface::RTCOfferAnswerOptions offer_answer_options;
1636 // Always create an offer even if |ConvertConstraintsToOfferAnswerOptions|
1637 // returns false for now. Because |ConvertConstraintsToOfferAnswerOptions|
1638 // compares the mandatory fields parsed with the mandatory fields added in the
1639 // |constraints| and some downstream applications might create offers with
1640 // mandatory fields which would not be parsed in the helper method. For
1641 // example, in Chromium/remoting, |kEnableDtlsSrtp| is added to the
1642 // |constraints| as a mandatory field but it is not parsed.
1643 ConvertConstraintsToOfferAnswerOptions(constraints, &offer_answer_options);
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001644
zhihuang1c378ed2017-08-17 14:10:50 -07001645 CreateOffer(observer, offer_answer_options);
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001646}
1647
1648void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
1649 const RTCOfferAnswerOptions& options) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001650 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
Steve Anton8d3444d2017-10-20 15:30:51 -07001651
nisse7ce109a2017-01-31 00:57:56 -08001652 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001653 RTC_LOG(LS_ERROR) << "CreateOffer - observer is NULL.";
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001654 return;
1655 }
deadbeefab9b2d12015-10-14 11:33:11 -07001656
Steve Anton8d3444d2017-10-20 15:30:51 -07001657 if (IsClosed()) {
1658 std::string error = "CreateOffer called when PeerConnection is closed.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001659 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001660 PostCreateSessionDescriptionFailure(
1661 observer, RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error)));
Steve Anton8d3444d2017-10-20 15:30:51 -07001662 return;
1663 }
1664
zhihuang1c378ed2017-08-17 14:10:50 -07001665 if (!ValidateOfferAnswerOptions(options)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001666 std::string error = "CreateOffer called with invalid options.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001667 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001668 PostCreateSessionDescriptionFailure(
1669 observer, RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error)));
deadbeefab9b2d12015-10-14 11:33:11 -07001670 return;
1671 }
1672
Steve Anton22da89f2018-01-25 13:58:07 -08001673 // Legacy handling for offer_to_receive_audio and offer_to_receive_video.
1674 // Specified in WebRTC section 4.4.3.2 "Legacy configuration extensions".
1675 if (IsUnifiedPlan()) {
1676 RTCError error = HandleLegacyOfferOptions(options);
1677 if (!error.ok()) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001678 PostCreateSessionDescriptionFailure(observer, std::move(error));
Steve Anton22da89f2018-01-25 13:58:07 -08001679 return;
1680 }
1681 }
1682
zhihuang1c378ed2017-08-17 14:10:50 -07001683 cricket::MediaSessionOptions session_options;
1684 GetOptionsForOffer(options, &session_options);
Steve Antond25da372017-11-06 14:50:29 -08001685 webrtc_session_desc_factory_->CreateOffer(observer, options, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001686}
1687
Steve Anton22da89f2018-01-25 13:58:07 -08001688RTCError PeerConnection::HandleLegacyOfferOptions(
1689 const RTCOfferAnswerOptions& options) {
1690 RTC_DCHECK(IsUnifiedPlan());
1691
1692 if (options.offer_to_receive_audio == 0) {
1693 RemoveRecvDirectionFromReceivingTransceiversOfType(
1694 cricket::MEDIA_TYPE_AUDIO);
1695 } else if (options.offer_to_receive_audio == 1) {
1696 AddUpToOneReceivingTransceiverOfType(cricket::MEDIA_TYPE_AUDIO);
1697 } else if (options.offer_to_receive_audio > 1) {
1698 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
1699 "offer_to_receive_audio > 1 is not supported.");
1700 }
1701
1702 if (options.offer_to_receive_video == 0) {
1703 RemoveRecvDirectionFromReceivingTransceiversOfType(
1704 cricket::MEDIA_TYPE_VIDEO);
1705 } else if (options.offer_to_receive_video == 1) {
1706 AddUpToOneReceivingTransceiverOfType(cricket::MEDIA_TYPE_VIDEO);
1707 } else if (options.offer_to_receive_video > 1) {
1708 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
1709 "offer_to_receive_video > 1 is not supported.");
1710 }
1711
1712 return RTCError::OK();
1713}
1714
1715void PeerConnection::RemoveRecvDirectionFromReceivingTransceiversOfType(
1716 cricket::MediaType media_type) {
1717 for (auto transceiver : GetReceivingTransceiversOfType(media_type)) {
1718 transceiver->internal()->set_direction(
1719 RtpTransceiverDirectionWithRecvSet(transceiver->direction(), false));
1720 }
1721}
1722
1723void PeerConnection::AddUpToOneReceivingTransceiverOfType(
1724 cricket::MediaType media_type) {
1725 if (GetReceivingTransceiversOfType(media_type).empty()) {
1726 RtpTransceiverInit init;
1727 init.direction = RtpTransceiverDirection::kRecvOnly;
1728 AddTransceiver(media_type, nullptr, init, /*fire_callback=*/false);
1729 }
1730}
1731
1732std::vector<rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
1733PeerConnection::GetReceivingTransceiversOfType(cricket::MediaType media_type) {
1734 std::vector<
1735 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
1736 receiving_transceivers;
1737 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08001738 if (!transceiver->stopped() && transceiver->media_type() == media_type &&
Steve Anton22da89f2018-01-25 13:58:07 -08001739 RtpTransceiverDirectionHasRecv(transceiver->direction())) {
1740 receiving_transceivers.push_back(transceiver);
1741 }
1742 }
1743 return receiving_transceivers;
1744}
1745
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001746void PeerConnection::CreateAnswer(
1747 CreateSessionDescriptionObserver* observer,
1748 const MediaConstraintsInterface* constraints) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001749 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
Steve Anton8d3444d2017-10-20 15:30:51 -07001750
nisse7ce109a2017-01-31 00:57:56 -08001751 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001752 RTC_LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001753 return;
1754 }
deadbeefab9b2d12015-10-14 11:33:11 -07001755
zhihuang1c378ed2017-08-17 14:10:50 -07001756 PeerConnectionInterface::RTCOfferAnswerOptions offer_answer_options;
1757 if (!ConvertConstraintsToOfferAnswerOptions(constraints,
1758 &offer_answer_options)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001759 std::string error = "CreateAnswer called with invalid constraints.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001760 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001761 PostCreateSessionDescriptionFailure(
1762 observer, RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error)));
deadbeefab9b2d12015-10-14 11:33:11 -07001763 return;
1764 }
1765
Steve Anton8d3444d2017-10-20 15:30:51 -07001766 CreateAnswer(observer, offer_answer_options);
htaa2a49d92016-03-04 02:51:39 -08001767}
1768
1769void PeerConnection::CreateAnswer(CreateSessionDescriptionObserver* observer,
1770 const RTCOfferAnswerOptions& options) {
1771 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
nisse7ce109a2017-01-31 00:57:56 -08001772 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001773 RTC_LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
htaa2a49d92016-03-04 02:51:39 -08001774 return;
1775 }
1776
Steve Antondffead82018-02-06 10:31:29 -08001777 if (!(signaling_state_ == kHaveRemoteOffer ||
1778 signaling_state_ == kHaveLocalPrAnswer)) {
1779 std::string error =
1780 "PeerConnection cannot create an answer in a state other than "
1781 "have-remote-offer or have-local-pranswer.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001782 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001783 PostCreateSessionDescriptionFailure(
1784 observer, RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error)));
Steve Anton8d3444d2017-10-20 15:30:51 -07001785 return;
1786 }
1787
Steve Antondffead82018-02-06 10:31:29 -08001788 // The remote description should be set if we're in the right state.
1789 RTC_DCHECK(remote_description());
Steve Anton8d3444d2017-10-20 15:30:51 -07001790
Steve Anton22da89f2018-01-25 13:58:07 -08001791 if (IsUnifiedPlan()) {
1792 if (options.offer_to_receive_audio != RTCOfferAnswerOptions::kUndefined) {
1793 RTC_LOG(LS_WARNING) << "CreateAnswer: offer_to_receive_audio is not "
1794 "supported with Unified Plan semantics. Use the "
1795 "RtpTransceiver API instead.";
1796 }
1797 if (options.offer_to_receive_video != RTCOfferAnswerOptions::kUndefined) {
1798 RTC_LOG(LS_WARNING) << "CreateAnswer: offer_to_receive_video is not "
1799 "supported with Unified Plan semantics. Use the "
1800 "RtpTransceiver API instead.";
1801 }
1802 }
1803
htaa2a49d92016-03-04 02:51:39 -08001804 cricket::MediaSessionOptions session_options;
zhihuang1c378ed2017-08-17 14:10:50 -07001805 GetOptionsForAnswer(options, &session_options);
htaa2a49d92016-03-04 02:51:39 -08001806
Steve Antond25da372017-11-06 14:50:29 -08001807 webrtc_session_desc_factory_->CreateAnswer(observer, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001808}
1809
1810void PeerConnection::SetLocalDescription(
1811 SetSessionDescriptionObserver* observer,
Steve Anton80dd7b52018-02-16 17:08:42 -08001812 SessionDescriptionInterface* desc_ptr) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001813 TRACE_EVENT0("webrtc", "PeerConnection::SetLocalDescription");
Steve Anton8a006912017-12-04 15:25:56 -08001814
Steve Anton80dd7b52018-02-16 17:08:42 -08001815 // The SetLocalDescription contract is that we take ownership of the session
1816 // description regardless of the outcome, so wrap it in a unique_ptr right
1817 // away. Ideally, SetLocalDescription's signature will be changed to take the
1818 // description as a unique_ptr argument to formalize this agreement.
1819 std::unique_ptr<SessionDescriptionInterface> desc(desc_ptr);
1820
nisse7ce109a2017-01-31 00:57:56 -08001821 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001822 RTC_LOG(LS_ERROR) << "SetLocalDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001823 return;
1824 }
Steve Anton8a006912017-12-04 15:25:56 -08001825
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001826 if (!desc) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001827 PostSetSessionDescriptionFailure(
1828 observer,
1829 RTCError(RTCErrorType::INTERNAL_ERROR, "SessionDescription is NULL."));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001830 return;
1831 }
Steve Anton8d3444d2017-10-20 15:30:51 -07001832
Steve Anton80dd7b52018-02-16 17:08:42 -08001833 // If a session error has occurred the PeerConnection is in a possibly
1834 // inconsistent state so fail right away.
1835 if (session_error() != SessionError::kNone) {
1836 std::string error_message = GetSessionErrorMsg();
1837 RTC_LOG(LS_ERROR) << "SetLocalDescription: " << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001838 PostSetSessionDescriptionFailure(
1839 observer,
1840 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton80dd7b52018-02-16 17:08:42 -08001841 return;
1842 }
Steve Anton8d3444d2017-10-20 15:30:51 -07001843
Steve Anton80dd7b52018-02-16 17:08:42 -08001844 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_LOCAL);
1845 if (!error.ok()) {
1846 std::string error_message = GetSetDescriptionErrorMessage(
1847 cricket::CS_LOCAL, desc->GetType(), error);
1848 RTC_LOG(LS_ERROR) << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001849 PostSetSessionDescriptionFailure(
1850 observer,
1851 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton80dd7b52018-02-16 17:08:42 -08001852 return;
1853 }
1854
1855 // Grab the description type before moving ownership to ApplyLocalDescription,
1856 // which may destroy it before returning.
1857 const SdpType type = desc->GetType();
1858
1859 error = ApplyLocalDescription(std::move(desc));
Steve Anton8a006912017-12-04 15:25:56 -08001860 // |desc| may be destroyed at this point.
1861
1862 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08001863 // If ApplyLocalDescription fails, the PeerConnection could be in an
1864 // inconsistent state, so act conservatively here and set the session error
1865 // so that future calls to SetLocalDescription/SetRemoteDescription fail.
1866 SetSessionError(SessionError::kContent, error.message());
1867 std::string error_message =
1868 GetSetDescriptionErrorMessage(cricket::CS_LOCAL, type, error);
1869 RTC_LOG(LS_ERROR) << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001870 PostSetSessionDescriptionFailure(
1871 observer,
1872 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton8d3444d2017-10-20 15:30:51 -07001873 return;
1874 }
Steve Anton8a006912017-12-04 15:25:56 -08001875 RTC_DCHECK(local_description());
1876
1877 PostSetSessionDescriptionSuccess(observer);
1878
1879 // According to JSEP, after setLocalDescription, changing the candidate pool
1880 // size is not allowed, and changing the set of ICE servers will not result
1881 // in new candidates being gathered.
1882 port_allocator_->FreezeCandidatePool();
1883
1884 // MaybeStartGathering needs to be called after posting
1885 // MSG_SET_SESSIONDESCRIPTION_SUCCESS, so that we don't signal any candidates
1886 // before signaling that SetLocalDescription completed.
1887 transport_controller_->MaybeStartGathering();
1888
Steve Antona3a92c22017-12-07 10:27:41 -08001889 if (local_description()->GetType() == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08001890 // TODO(deadbeef): We already had to hop to the network thread for
1891 // MaybeStartGathering...
1892 network_thread()->Invoke<void>(
1893 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
1894 port_allocator_.get()));
Steve Anton0ffaaa22018-02-23 10:31:30 -08001895 // Make UMA notes about what was agreed to.
1896 ReportNegotiatedSdpSemantics(*local_description());
Steve Anton8a006912017-12-04 15:25:56 -08001897 }
1898}
1899
1900RTCError PeerConnection::ApplyLocalDescription(
1901 std::unique_ptr<SessionDescriptionInterface> desc) {
1902 RTC_DCHECK_RUN_ON(signaling_thread());
1903 RTC_DCHECK(desc);
1904
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001905 // Update stats here so that we have the most recent stats for tracks and
1906 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001907 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 15:25:56 -08001908
1909 // Update the initial_offerer flag if this session is the initial_offerer.
Steve Anton3828c062017-12-06 10:34:51 -08001910 SdpType type = desc->GetType();
Steve Anton8a006912017-12-04 15:25:56 -08001911 if (!initial_offerer_.has_value()) {
Steve Anton3828c062017-12-06 10:34:51 -08001912 initial_offerer_.emplace(type == SdpType::kOffer);
Steve Anton8a006912017-12-04 15:25:56 -08001913 if (*initial_offerer_) {
1914 transport_controller_->SetIceRole(cricket::ICEROLE_CONTROLLING);
1915 } else {
1916 transport_controller_->SetIceRole(cricket::ICEROLE_CONTROLLED);
1917 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001918 }
Steve Anton8a006912017-12-04 15:25:56 -08001919
Steve Antondcc3c022017-12-22 16:02:54 -08001920 // Take a reference to the old local description since it's used below to
1921 // compare against the new local description. When setting the new local
1922 // description, grab ownership of the replaced session description in case it
1923 // is the same as |old_local_description|, to keep it alive for the duration
1924 // of the method.
1925 const SessionDescriptionInterface* old_local_description =
1926 local_description();
1927 std::unique_ptr<SessionDescriptionInterface> replaced_local_description;
Steve Anton3828c062017-12-06 10:34:51 -08001928 if (type == SdpType::kAnswer) {
Steve Antondcc3c022017-12-22 16:02:54 -08001929 replaced_local_description = pending_local_description_
1930 ? std::move(pending_local_description_)
1931 : std::move(current_local_description_);
Steve Anton8a006912017-12-04 15:25:56 -08001932 current_local_description_ = std::move(desc);
1933 pending_local_description_ = nullptr;
1934 current_remote_description_ = std::move(pending_remote_description_);
1935 } else {
Steve Antondcc3c022017-12-22 16:02:54 -08001936 replaced_local_description = std::move(pending_local_description_);
Steve Anton8a006912017-12-04 15:25:56 -08001937 pending_local_description_ = std::move(desc);
1938 }
1939 // The session description to apply now must be accessed by
1940 // |local_description()|.
Henrik Boströmfdb92012017-11-09 19:55:44 +01001941 RTC_DCHECK(local_description());
deadbeefab9b2d12015-10-14 11:33:11 -07001942
Steve Antondcc3c022017-12-22 16:02:54 -08001943 if (IsUnifiedPlan()) {
1944 RTCError error = UpdateTransceiversAndDataChannels(
Seth Hampsonae8a90a2018-02-13 15:33:48 -08001945 cricket::CS_LOCAL, *local_description(), old_local_description,
1946 remote_description());
Steve Anton8a006912017-12-04 15:25:56 -08001947 if (!error.ok()) {
1948 return error;
1949 }
Steve Antondcc3c022017-12-22 16:02:54 -08001950 for (auto transceiver : transceivers_) {
1951 const ContentInfo* content =
1952 FindMediaSectionForTransceiver(transceiver, local_description());
1953 if (!content) {
1954 continue;
1955 }
1956 const MediaContentDescription* media_desc = content->media_description();
1957 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
1958 transceiver->internal()->set_current_direction(media_desc->direction());
1959 }
1960 if (content->rejected && !transceiver->stopped()) {
1961 transceiver->Stop();
1962 }
1963 }
1964 } else {
1965 // Transport and Media channels will be created only when offer is set.
1966 if (type == SdpType::kOffer) {
1967 // TODO(bugs.webrtc.org/4676) - Handle CreateChannel failure, as new local
1968 // description is applied. Restore back to old description.
1969 RTCError error = CreateChannels(*local_description()->description());
1970 if (!error.ok()) {
1971 return error;
1972 }
1973 }
Steve Anton8a006912017-12-04 15:25:56 -08001974
Steve Antondcc3c022017-12-22 16:02:54 -08001975 // Remove unused channels if MediaContentDescription is rejected.
1976 RemoveUnusedChannels(local_description()->description());
1977 }
Steve Anton8a006912017-12-04 15:25:56 -08001978
Steve Anton80dd7b52018-02-16 17:08:42 -08001979 RTCError error = UpdateSessionState(type, cricket::CS_LOCAL);
Steve Anton8a006912017-12-04 15:25:56 -08001980 if (!error.ok()) {
1981 return error;
1982 }
Steve Antondcc3c022017-12-22 16:02:54 -08001983
Steve Anton8a006912017-12-04 15:25:56 -08001984 if (remote_description()) {
1985 // Now that we have a local description, we can push down remote candidates.
1986 UseCandidatesInSessionDescription(remote_description());
1987 }
1988
1989 pending_ice_restarts_.clear();
1990 if (session_error() != SessionError::kNone) {
1991 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
1992 }
1993
deadbeefab9b2d12015-10-14 11:33:11 -07001994 // If setting the description decided our SSL role, allocate any necessary
1995 // SCTP sids.
1996 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08001997 if (data_channel_type() == cricket::DCT_SCTP && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001998 AllocateSctpSids(role);
1999 }
2000
Steve Antond3679212018-01-17 17:41:02 -08002001 if (IsUnifiedPlan()) {
2002 for (auto transceiver : transceivers_) {
2003 const ContentInfo* content =
2004 FindMediaSectionForTransceiver(transceiver, local_description());
2005 if (!content) {
2006 continue;
2007 }
2008 if (content->rejected && !transceiver->stopped()) {
2009 transceiver->Stop();
2010 }
Steve Anton74255ff2018-01-24 18:32:57 -08002011 const auto& streams = content->media_description()->streams();
2012 if (!content->rejected && !streams.empty()) {
Steve Antond3679212018-01-17 17:41:02 -08002013 transceiver->internal()->sender_internal()->set_stream_ids(
Seth Hampson845e8782018-03-02 11:34:10 -08002014 streams[0].stream_ids());
Steve Antond3679212018-01-17 17:41:02 -08002015 transceiver->internal()->sender_internal()->SetSsrc(
Steve Anton74255ff2018-01-24 18:32:57 -08002016 streams[0].first_ssrc());
Steve Antond3679212018-01-17 17:41:02 -08002017 }
2018 }
2019 } else {
2020 // Plan B semantics.
2021
Steve Antondcc3c022017-12-22 16:02:54 -08002022 // Update state and SSRC of local MediaStreams and DataChannels based on the
2023 // local session description.
2024 const cricket::ContentInfo* audio_content =
2025 GetFirstAudioContent(local_description()->description());
2026 if (audio_content) {
2027 if (audio_content->rejected) {
2028 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
2029 } else {
2030 const cricket::AudioContentDescription* audio_desc =
2031 audio_content->media_description()->as_audio();
2032 UpdateLocalSenders(audio_desc->streams(), audio_desc->type());
2033 }
deadbeeffaac4972015-11-12 15:33:07 -08002034 }
deadbeefab9b2d12015-10-14 11:33:11 -07002035
Steve Antondcc3c022017-12-22 16:02:54 -08002036 const cricket::ContentInfo* video_content =
2037 GetFirstVideoContent(local_description()->description());
2038 if (video_content) {
2039 if (video_content->rejected) {
2040 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
2041 } else {
2042 const cricket::VideoContentDescription* video_desc =
2043 video_content->media_description()->as_video();
2044 UpdateLocalSenders(video_desc->streams(), video_desc->type());
2045 }
deadbeeffaac4972015-11-12 15:33:07 -08002046 }
deadbeefab9b2d12015-10-14 11:33:11 -07002047 }
2048
2049 const cricket::ContentInfo* data_content =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002050 GetFirstDataContent(local_description()->description());
deadbeefab9b2d12015-10-14 11:33:11 -07002051 if (data_content) {
2052 const cricket::DataContentDescription* data_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08002053 data_content->media_description()->as_data();
deadbeefab9b2d12015-10-14 11:33:11 -07002054 if (rtc::starts_with(data_desc->protocol().data(),
2055 cricket::kMediaProtocolRtpPrefix)) {
2056 UpdateLocalRtpDataChannels(data_desc->streams());
2057 }
2058 }
2059
Steve Anton8a006912017-12-04 15:25:56 -08002060 return RTCError::OK();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002061}
2062
2063void PeerConnection::SetRemoteDescription(
Henrik Boströma4ecf552017-11-23 14:17:07 +00002064 SetSessionDescriptionObserver* observer,
2065 SessionDescriptionInterface* desc) {
Henrik Boström31638672017-11-23 17:48:32 +01002066 SetRemoteDescription(
2067 std::unique_ptr<SessionDescriptionInterface>(desc),
2068 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface>(
2069 new SetRemoteDescriptionObserverAdapter(this, observer)));
2070}
2071
2072void PeerConnection::SetRemoteDescription(
2073 std::unique_ptr<SessionDescriptionInterface> desc,
2074 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface> observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +01002075 TRACE_EVENT0("webrtc", "PeerConnection::SetRemoteDescription");
Steve Anton8a006912017-12-04 15:25:56 -08002076
nisse7ce109a2017-01-31 00:57:56 -08002077 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002078 RTC_LOG(LS_ERROR) << "SetRemoteDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002079 return;
2080 }
Steve Anton8a006912017-12-04 15:25:56 -08002081
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002082 if (!desc) {
Henrik Boström31638672017-11-23 17:48:32 +01002083 observer->OnSetRemoteDescriptionComplete(RTCError(
Steve Anton8a006912017-12-04 15:25:56 -08002084 RTCErrorType::INVALID_PARAMETER, "SessionDescription is NULL."));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002085 return;
2086 }
Steve Anton8d3444d2017-10-20 15:30:51 -07002087
Steve Anton80dd7b52018-02-16 17:08:42 -08002088 // If a session error has occurred the PeerConnection is in a possibly
2089 // inconsistent state so fail right away.
2090 if (session_error() != SessionError::kNone) {
2091 std::string error_message = GetSessionErrorMsg();
2092 RTC_LOG(LS_ERROR) << "SetRemoteDescription: " << error_message;
2093 observer->OnSetRemoteDescriptionComplete(
2094 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
2095 return;
2096 }
Steve Anton71439a62018-02-15 11:53:06 -08002097
Steve Anton80dd7b52018-02-16 17:08:42 -08002098 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_REMOTE);
Steve Anton71439a62018-02-15 11:53:06 -08002099 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08002100 std::string error_message = GetSetDescriptionErrorMessage(
2101 cricket::CS_REMOTE, desc->GetType(), error);
2102 RTC_LOG(LS_ERROR) << error_message;
Steve Anton71439a62018-02-15 11:53:06 -08002103 observer->OnSetRemoteDescriptionComplete(
2104 RTCError(error.type(), std::move(error_message)));
2105 return;
2106 }
Steve Anton71439a62018-02-15 11:53:06 -08002107
Steve Anton80dd7b52018-02-16 17:08:42 -08002108 // Grab the description type before moving ownership to
2109 // ApplyRemoteDescription, which may destroy it before returning.
2110 const SdpType type = desc->GetType();
2111
2112 error = ApplyRemoteDescription(std::move(desc));
2113 // |desc| may be destroyed at this point.
2114
2115 if (!error.ok()) {
2116 // If ApplyRemoteDescription fails, the PeerConnection could be in an
2117 // inconsistent state, so act conservatively here and set the session error
2118 // so that future calls to SetLocalDescription/SetRemoteDescription fail.
2119 SetSessionError(SessionError::kContent, error.message());
2120 std::string error_message =
2121 GetSetDescriptionErrorMessage(cricket::CS_REMOTE, type, error);
2122 RTC_LOG(LS_ERROR) << error_message;
2123 observer->OnSetRemoteDescriptionComplete(
2124 RTCError(error.type(), std::move(error_message)));
2125 return;
2126 }
2127 RTC_DCHECK(remote_description());
2128
Steve Anton8e20f172018-03-06 10:55:04 -08002129 if (type == SdpType::kOffer) {
2130 // Report to UMA the format of the received offer.
2131 ReportSdpFormatReceived(*remote_description());
2132 }
2133
Steve Anton80dd7b52018-02-16 17:08:42 -08002134 if (type == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002135 // TODO(deadbeef): We already had to hop to the network thread for
2136 // MaybeStartGathering...
2137 network_thread()->Invoke<void>(
2138 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
2139 port_allocator_.get()));
Harald Alvestrand5dbb5862018-02-13 23:48:00 +01002140 // Make UMA notes about what was agreed to.
Steve Anton0ffaaa22018-02-23 10:31:30 -08002141 ReportNegotiatedSdpSemantics(*remote_description());
Steve Anton8a006912017-12-04 15:25:56 -08002142 }
2143
2144 observer->OnSetRemoteDescriptionComplete(RTCError::OK());
2145}
2146
2147RTCError PeerConnection::ApplyRemoteDescription(
2148 std::unique_ptr<SessionDescriptionInterface> desc) {
2149 RTC_DCHECK_RUN_ON(signaling_thread());
2150 RTC_DCHECK(desc);
2151
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002152 // Update stats here so that we have the most recent stats for tracks and
2153 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00002154 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 15:25:56 -08002155
Steve Antondcc3c022017-12-22 16:02:54 -08002156 // Take a reference to the old remote description since it's used below to
2157 // compare against the new remote description. When setting the new remote
2158 // description, grab ownership of the replaced session description in case it
2159 // is the same as |old_remote_description|, to keep it alive for the duration
2160 // of the method.
Steve Anton8a006912017-12-04 15:25:56 -08002161 const SessionDescriptionInterface* old_remote_description =
2162 remote_description();
Steve Anton8a006912017-12-04 15:25:56 -08002163 std::unique_ptr<SessionDescriptionInterface> replaced_remote_description;
Steve Anton3828c062017-12-06 10:34:51 -08002164 SdpType type = desc->GetType();
2165 if (type == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002166 replaced_remote_description = pending_remote_description_
2167 ? std::move(pending_remote_description_)
2168 : std::move(current_remote_description_);
2169 current_remote_description_ = std::move(desc);
2170 pending_remote_description_ = nullptr;
2171 current_local_description_ = std::move(pending_local_description_);
2172 } else {
2173 replaced_remote_description = std::move(pending_remote_description_);
2174 pending_remote_description_ = std::move(desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002175 }
Steve Anton8a006912017-12-04 15:25:56 -08002176 // The session description to apply now must be accessed by
2177 // |remote_description()|.
Henrik Boströmfdb92012017-11-09 19:55:44 +01002178 RTC_DCHECK(remote_description());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002179
Steve Anton8a006912017-12-04 15:25:56 -08002180 // Transport and Media channels will be created only when offer is set.
Steve Antondcc3c022017-12-22 16:02:54 -08002181 if (IsUnifiedPlan()) {
2182 RTCError error = UpdateTransceiversAndDataChannels(
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002183 cricket::CS_REMOTE, *remote_description(), local_description(),
2184 old_remote_description);
Steve Anton8a006912017-12-04 15:25:56 -08002185 if (!error.ok()) {
2186 return error;
2187 }
Steve Antondcc3c022017-12-22 16:02:54 -08002188 } else {
2189 if (type == SdpType::kOffer) {
2190 // TODO(bugs.webrtc.org/4676) - Handle CreateChannel failure, as new local
2191 // description is applied. Restore back to old description.
2192 RTCError error = CreateChannels(*remote_description()->description());
2193 if (!error.ok()) {
2194 return error;
2195 }
2196 }
Steve Anton8a006912017-12-04 15:25:56 -08002197
Steve Antondcc3c022017-12-22 16:02:54 -08002198 // Remove unused channels if MediaContentDescription is rejected.
2199 RemoveUnusedChannels(remote_description()->description());
2200 }
Steve Anton8a006912017-12-04 15:25:56 -08002201
2202 // NOTE: Candidates allocation will be initiated only when SetLocalDescription
2203 // is called.
Steve Anton80dd7b52018-02-16 17:08:42 -08002204 RTCError error = UpdateSessionState(type, cricket::CS_REMOTE);
Steve Anton8a006912017-12-04 15:25:56 -08002205 if (!error.ok()) {
2206 return error;
2207 }
2208
2209 if (local_description() &&
2210 !UseCandidatesInSessionDescription(remote_description())) {
2211 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidCandidates);
2212 }
2213
2214 if (old_remote_description) {
2215 for (const cricket::ContentInfo& content :
2216 old_remote_description->description()->contents()) {
2217 // Check if this new SessionDescription contains new ICE ufrag and
2218 // password that indicates the remote peer requests an ICE restart.
2219 // TODO(deadbeef): When we start storing both the current and pending
2220 // remote description, this should reset pending_ice_restarts and compare
2221 // against the current description.
2222 if (CheckForRemoteIceRestart(old_remote_description, remote_description(),
2223 content.name)) {
Steve Anton3828c062017-12-06 10:34:51 -08002224 if (type == SdpType::kOffer) {
Steve Anton8a006912017-12-04 15:25:56 -08002225 pending_ice_restarts_.insert(content.name);
2226 }
2227 } else {
2228 // We retain all received candidates only if ICE is not restarted.
2229 // When ICE is restarted, all previous candidates belong to an old
2230 // generation and should not be kept.
2231 // TODO(deadbeef): This goes against the W3C spec which says the remote
2232 // description should only contain candidates from the last set remote
2233 // description plus any candidates added since then. We should remove
2234 // this once we're sure it won't break anything.
2235 WebRtcSessionDescriptionFactory::CopyCandidatesFromSessionDescription(
2236 old_remote_description, content.name, mutable_remote_description());
2237 }
2238 }
2239 }
2240
2241 if (session_error() != SessionError::kNone) {
2242 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
2243 }
2244
2245 // Set the the ICE connection state to connecting since the connection may
2246 // become writable with peer reflexive candidates before any remote candidate
2247 // is signaled.
2248 // TODO(pthatcher): This is a short-term solution for crbug/446908. A real fix
2249 // is to have a new signal the indicates a change in checking state from the
2250 // transport and expose a new checking() member from transport that can be
2251 // read to determine the current checking state. The existing SignalConnecting
2252 // actually means "gathering candidates", so cannot be be used here.
Steve Antona3a92c22017-12-07 10:27:41 -08002253 if (remote_description()->GetType() != SdpType::kOffer &&
Steve Anton8a006912017-12-04 15:25:56 -08002254 ice_connection_state() == PeerConnectionInterface::kIceConnectionNew) {
2255 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
2256 }
2257
deadbeefab9b2d12015-10-14 11:33:11 -07002258 // If setting the description decided our SSL role, allocate any necessary
2259 // SCTP sids.
2260 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08002261 if (data_channel_type() == cricket::DCT_SCTP && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07002262 AllocateSctpSids(role);
2263 }
2264
Steve Antondcc3c022017-12-22 16:02:54 -08002265 if (IsUnifiedPlan()) {
Steve Anton8b815cd2018-02-16 16:14:42 -08002266 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
2267 receiving_transceivers;
Steve Antonc49bcd92018-02-14 14:28:13 -08002268 std::vector<rtc::scoped_refptr<MediaStreamInterface>> added_streams;
Steve Antondcc3c022017-12-22 16:02:54 -08002269 for (auto transceiver : transceivers_) {
2270 const ContentInfo* content =
2271 FindMediaSectionForTransceiver(transceiver, remote_description());
2272 if (!content) {
2273 continue;
2274 }
2275 const MediaContentDescription* media_desc = content->media_description();
2276 RtpTransceiverDirection local_direction =
2277 RtpTransceiverDirectionReversed(media_desc->direction());
2278 // From the WebRTC specification, steps 2.2.8.5/6 of section 4.4.1.6 "Set
2279 // the RTCSessionDescription: If direction is sendrecv or recvonly, and
2280 // transceiver's current direction is neither sendrecv nor recvonly,
2281 // process the addition of a remote track for the media description.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002282 //
2283 // Create a sync label in the case of an unsignalled msid.
2284 std::string sync_label = rtc::CreateRandomUuid();
2285 if (!media_desc->streams().empty()) {
Steve Anton5a26a3a2018-02-28 11:38:47 -08002286 const cricket::StreamParams& stream_params = media_desc->streams()[0];
Seth Hampson845e8782018-03-02 11:34:10 -08002287 if (!stream_params.stream_ids().empty()) {
2288 sync_label = stream_params.stream_ids()[0];
Steve Anton5a26a3a2018-02-28 11:38:47 -08002289 }
Seth Hampson2f0d7022018-02-20 11:54:42 -08002290 }
Steve Antondcc3c022017-12-22 16:02:54 -08002291 if (RtpTransceiverDirectionHasRecv(local_direction) &&
2292 (!transceiver->current_direction() ||
2293 !RtpTransceiverDirectionHasRecv(
Seth Hampson2f0d7022018-02-20 11:54:42 -08002294 *transceiver->current_direction()))) {
Steve Antonef65ef12018-01-10 17:15:20 -08002295 rtc::scoped_refptr<MediaStreamInterface> stream =
2296 remote_streams_->find(sync_label);
2297 if (!stream) {
2298 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
2299 MediaStream::Create(sync_label));
2300 remote_streams_->AddStream(stream);
Steve Antonc49bcd92018-02-14 14:28:13 -08002301 added_streams.push_back(stream);
Steve Antonef65ef12018-01-10 17:15:20 -08002302 }
2303 transceiver->internal()->receiver_internal()->SetStreams({stream});
Steve Anton8b815cd2018-02-16 16:14:42 -08002304 receiving_transceivers.push_back(transceiver);
Steve Antondcc3c022017-12-22 16:02:54 -08002305 }
2306 // If direction is sendonly or inactive, and transceiver's current
2307 // direction is neither sendonly nor inactive, process the removal of a
2308 // remote track for the media description.
2309 if (!RtpTransceiverDirectionHasRecv(local_direction) &&
Steve Antonef65ef12018-01-10 17:15:20 -08002310 (transceiver->current_direction() &&
Steve Antondcc3c022017-12-22 16:02:54 -08002311 RtpTransceiverDirectionHasRecv(*transceiver->current_direction()))) {
Steve Antonef65ef12018-01-10 17:15:20 -08002312 transceiver->internal()->receiver_internal()->SetStreams({});
Steve Antondcc3c022017-12-22 16:02:54 -08002313 }
2314 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
2315 transceiver->internal()->set_current_direction(local_direction);
2316 }
2317 if (content->rejected && !transceiver->stopped()) {
2318 transceiver->Stop();
2319 }
Seth Hampson2f0d7022018-02-20 11:54:42 -08002320 if (!content->rejected &&
2321 RtpTransceiverDirectionHasRecv(local_direction)) {
2322 // Set ssrc to 0 in the case of an unsignalled ssrc.
2323 uint32_t ssrc = 0;
2324 if (!media_desc->streams().empty()) {
2325 ssrc = media_desc->streams()[0].first_ssrc();
2326 }
2327 transceiver->internal()->receiver_internal()->SetupMediaChannel(ssrc);
Steve Antond3679212018-01-17 17:41:02 -08002328 }
Steve Antondcc3c022017-12-22 16:02:54 -08002329 }
Steve Antonc49bcd92018-02-14 14:28:13 -08002330 // Once all processing has finished, fire off callbacks.
Steve Anton8b815cd2018-02-16 16:14:42 -08002331 for (auto transceiver : receiving_transceivers) {
Steve Anton6e221372018-02-20 12:59:16 -08002332 stats_->AddTrack(transceiver->receiver()->track());
Steve Anton8b815cd2018-02-16 16:14:42 -08002333 observer_->OnTrack(transceiver);
2334 observer_->OnAddTrack(transceiver->receiver(),
2335 transceiver->receiver()->streams());
Steve Antonef65ef12018-01-10 17:15:20 -08002336 }
Steve Antonc49bcd92018-02-14 14:28:13 -08002337 for (auto stream : added_streams) {
2338 observer_->OnAddStream(stream);
2339 }
Steve Antondcc3c022017-12-22 16:02:54 -08002340 }
2341
Henrik Boströmfdb92012017-11-09 19:55:44 +01002342 const cricket::ContentInfo* audio_content =
2343 GetFirstAudioContent(remote_description()->description());
2344 const cricket::ContentInfo* video_content =
2345 GetFirstVideoContent(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002346 const cricket::AudioContentDescription* audio_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002347 GetFirstAudioContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002348 const cricket::VideoContentDescription* video_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002349 GetFirstVideoContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002350 const cricket::DataContentDescription* data_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002351 GetFirstDataContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002352
2353 // Check if the descriptions include streams, just in case the peer supports
2354 // MSID, but doesn't indicate so with "a=msid-semantic".
Henrik Boströmfdb92012017-11-09 19:55:44 +01002355 if (remote_description()->description()->msid_supported() ||
deadbeefbda7e0b2015-12-08 17:13:40 -08002356 (audio_desc && !audio_desc->streams().empty()) ||
2357 (video_desc && !video_desc->streams().empty())) {
2358 remote_peer_supports_msid_ = true;
2359 }
deadbeefab9b2d12015-10-14 11:33:11 -07002360
2361 // We wait to signal new streams until we finish processing the description,
2362 // since only at that point will new streams have all their tracks.
2363 rtc::scoped_refptr<StreamCollection> new_streams(StreamCollection::Create());
2364
Steve Antondcc3c022017-12-22 16:02:54 -08002365 if (!IsUnifiedPlan()) {
2366 // TODO(steveanton): When removing RTP senders/receivers in response to a
2367 // rejected media section, there is some cleanup logic that expects the
2368 // voice/ video channel to still be set. But in this method the voice/video
2369 // channel would have been destroyed by the SetRemoteDescription caller
2370 // above so the cleanup that relies on them fails to run. The RemoveSenders
2371 // calls should be moved to right before the DestroyChannel calls to fix
2372 // this.
Steve Anton8d3444d2017-10-20 15:30:51 -07002373
Steve Antondcc3c022017-12-22 16:02:54 -08002374 // Find all audio rtp streams and create corresponding remote AudioTracks
2375 // and MediaStreams.
2376 if (audio_content) {
2377 if (audio_content->rejected) {
2378 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
2379 } else {
2380 bool default_audio_track_needed =
2381 !remote_peer_supports_msid_ &&
2382 RtpTransceiverDirectionHasSend(audio_desc->direction());
2383 UpdateRemoteSendersList(GetActiveStreams(audio_desc),
2384 default_audio_track_needed, audio_desc->type(),
2385 new_streams);
2386 }
deadbeeffaac4972015-11-12 15:33:07 -08002387 }
deadbeefab9b2d12015-10-14 11:33:11 -07002388
Steve Antondcc3c022017-12-22 16:02:54 -08002389 // Find all video rtp streams and create corresponding remote VideoTracks
2390 // and MediaStreams.
2391 if (video_content) {
2392 if (video_content->rejected) {
2393 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
2394 } else {
2395 bool default_video_track_needed =
2396 !remote_peer_supports_msid_ &&
2397 RtpTransceiverDirectionHasSend(video_desc->direction());
2398 UpdateRemoteSendersList(GetActiveStreams(video_desc),
2399 default_video_track_needed, video_desc->type(),
2400 new_streams);
2401 }
deadbeeffaac4972015-11-12 15:33:07 -08002402 }
deadbeefab9b2d12015-10-14 11:33:11 -07002403
Steve Antondcc3c022017-12-22 16:02:54 -08002404 // Update the DataChannels with the information from the remote peer.
2405 if (data_desc) {
2406 if (rtc::starts_with(data_desc->protocol().data(),
2407 cricket::kMediaProtocolRtpPrefix)) {
2408 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
2409 }
deadbeefab9b2d12015-10-14 11:33:11 -07002410 }
deadbeefab9b2d12015-10-14 11:33:11 -07002411
Steve Antondcc3c022017-12-22 16:02:54 -08002412 // Iterate new_streams and notify the observer about new MediaStreams.
2413 for (size_t i = 0; i < new_streams->count(); ++i) {
2414 MediaStreamInterface* new_stream = new_streams->at(i);
2415 stats_->AddStream(new_stream);
2416 observer_->OnAddStream(
2417 rtc::scoped_refptr<MediaStreamInterface>(new_stream));
2418 }
deadbeefab9b2d12015-10-14 11:33:11 -07002419
Steve Antondcc3c022017-12-22 16:02:54 -08002420 UpdateEndedRemoteMediaStreams();
2421 }
deadbeefab9b2d12015-10-14 11:33:11 -07002422
Steve Anton8a006912017-12-04 15:25:56 -08002423 return RTCError::OK();
deadbeeffc648b62015-10-13 16:42:33 -07002424}
2425
Steve Antondcc3c022017-12-22 16:02:54 -08002426RTCError PeerConnection::UpdateTransceiversAndDataChannels(
2427 cricket::ContentSource source,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002428 const SessionDescriptionInterface& new_session,
2429 const SessionDescriptionInterface* old_local_description,
2430 const SessionDescriptionInterface* old_remote_description) {
Steve Antondcc3c022017-12-22 16:02:54 -08002431 RTC_DCHECK(IsUnifiedPlan());
2432
Steve Anton7464fca2018-01-19 11:10:37 -08002433 const cricket::ContentGroup* bundle_group = nullptr;
2434 if (new_session.GetType() == SdpType::kOffer) {
2435 auto bundle_group_or_error =
2436 GetEarlyBundleGroup(*new_session.description());
2437 if (!bundle_group_or_error.ok()) {
2438 return bundle_group_or_error.MoveError();
2439 }
2440 bundle_group = bundle_group_or_error.MoveValue();
Steve Antondcc3c022017-12-22 16:02:54 -08002441 }
Steve Antondcc3c022017-12-22 16:02:54 -08002442
Steve Antondcc3c022017-12-22 16:02:54 -08002443 const ContentInfos& new_contents = new_session.description()->contents();
Steve Antondcc3c022017-12-22 16:02:54 -08002444 for (size_t i = 0; i < new_contents.size(); ++i) {
2445 const cricket::ContentInfo& new_content = new_contents[i];
Steve Antondcc3c022017-12-22 16:02:54 -08002446 cricket::MediaType media_type = new_content.media_description()->type();
2447 seen_mids_.insert(new_content.name);
2448 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
2449 media_type == cricket::MEDIA_TYPE_VIDEO) {
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002450 const cricket::ContentInfo* old_local_content = nullptr;
2451 if (old_local_description &&
2452 i < old_local_description->description()->contents().size()) {
2453 old_local_content =
2454 &old_local_description->description()->contents()[i];
2455 }
2456 const cricket::ContentInfo* old_remote_content = nullptr;
2457 if (old_remote_description &&
2458 i < old_remote_description->description()->contents().size()) {
2459 old_remote_content =
2460 &old_remote_description->description()->contents()[i];
2461 }
Steve Antondcc3c022017-12-22 16:02:54 -08002462 auto transceiver_or_error =
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002463 AssociateTransceiver(source, new_session.GetType(), i, new_content,
2464 old_local_content, old_remote_content);
Steve Antondcc3c022017-12-22 16:02:54 -08002465 if (!transceiver_or_error.ok()) {
2466 return transceiver_or_error.MoveError();
2467 }
2468 auto transceiver = transceiver_or_error.MoveValue();
Steve Antondcc3c022017-12-22 16:02:54 -08002469 RTCError error =
2470 UpdateTransceiverChannel(transceiver, new_content, bundle_group);
2471 if (!error.ok()) {
2472 return error;
2473 }
2474 } else if (media_type == cricket::MEDIA_TYPE_DATA) {
Steve Antonfa2260d2017-12-28 16:38:23 -08002475 if (GetDataMid() && new_content.name != *GetDataMid()) {
2476 // Ignore all but the first data section.
2477 continue;
2478 }
2479 RTCError error = UpdateDataChannel(source, new_content, bundle_group);
2480 if (!error.ok()) {
2481 return error;
2482 }
Steve Antondcc3c022017-12-22 16:02:54 -08002483 } else {
2484 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
2485 "Unknown section type.");
2486 }
2487 }
2488
2489 return RTCError::OK();
2490}
2491
2492RTCError PeerConnection::UpdateTransceiverChannel(
2493 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2494 transceiver,
2495 const cricket::ContentInfo& content,
2496 const cricket::ContentGroup* bundle_group) {
2497 RTC_DCHECK(IsUnifiedPlan());
2498 RTC_DCHECK(transceiver);
2499 cricket::BaseChannel* channel = transceiver->internal()->channel();
2500 if (content.rejected) {
2501 if (channel) {
2502 transceiver->internal()->SetChannel(nullptr);
2503 DestroyBaseChannel(channel);
2504 }
2505 } else {
2506 if (!channel) {
Steve Anton69470252018-02-09 11:43:08 -08002507 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Steve Antondcc3c022017-12-22 16:02:54 -08002508 channel = CreateVoiceChannel(
2509 content.name,
2510 GetTransportNameForMediaSection(content.name, bundle_group));
2511 } else {
Steve Anton69470252018-02-09 11:43:08 -08002512 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, transceiver->media_type());
Steve Antondcc3c022017-12-22 16:02:54 -08002513 channel = CreateVideoChannel(
2514 content.name,
2515 GetTransportNameForMediaSection(content.name, bundle_group));
2516 }
2517 if (!channel) {
2518 LOG_AND_RETURN_ERROR(
2519 RTCErrorType::INTERNAL_ERROR,
2520 "Failed to create channel for mid=" + content.name);
2521 }
2522 transceiver->internal()->SetChannel(channel);
2523 }
2524 }
2525 return RTCError::OK();
2526}
2527
Steve Antonfa2260d2017-12-28 16:38:23 -08002528RTCError PeerConnection::UpdateDataChannel(
2529 cricket::ContentSource source,
2530 const cricket::ContentInfo& content,
2531 const cricket::ContentGroup* bundle_group) {
2532 if (data_channel_type_ == cricket::DCT_NONE) {
Steve Antondbf9d032018-01-19 15:23:40 -08002533 // If data channels are disabled, ignore this media section. CreateAnswer
2534 // will take care of rejecting it.
2535 return RTCError::OK();
Steve Antonfa2260d2017-12-28 16:38:23 -08002536 }
2537 if (content.rejected) {
2538 DestroyDataChannel();
2539 } else {
2540 if (!rtp_data_channel_ && !sctp_transport_) {
2541 if (!CreateDataChannel(content.name, GetTransportNameForMediaSection(
2542 content.name, bundle_group))) {
2543 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
2544 "Failed to create data channel.");
2545 }
2546 }
2547 if (source == cricket::CS_REMOTE) {
2548 const MediaContentDescription* data_desc = content.media_description();
2549 if (data_desc && cricket::IsRtpProtocol(data_desc->protocol())) {
2550 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
2551 }
2552 }
2553 }
2554 return RTCError::OK();
2555}
2556
Steve Antondcc3c022017-12-22 16:02:54 -08002557RTCErrorOr<rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
2558PeerConnection::AssociateTransceiver(cricket::ContentSource source,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002559 SdpType type,
Steve Antondcc3c022017-12-22 16:02:54 -08002560 size_t mline_index,
2561 const ContentInfo& content,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002562 const ContentInfo* old_local_content,
2563 const ContentInfo* old_remote_content) {
Steve Antondcc3c022017-12-22 16:02:54 -08002564 RTC_DCHECK(IsUnifiedPlan());
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002565 // If this is an offer then the m= section might be recycled. If the m=
2566 // section is being recycled (defined as: rejected in the current local or
2567 // remote description and not rejected in new description), dissociate the
2568 // currently associated RtpTransceiver by setting its mid property to null,
2569 // and discard the mapping between the transceiver and its m= section index.
2570 if (IsMediaSectionBeingRecycled(type, content, old_local_content,
2571 old_remote_content)) {
2572 // We want to dissociate the transceiver that has the rejected mid.
2573 const std::string& old_mid =
2574 (old_local_content && old_local_content->rejected)
2575 ? old_local_content->name
2576 : old_remote_content->name;
2577 auto old_transceiver = GetAssociatedTransceiver(old_mid);
Steve Antondcc3c022017-12-22 16:02:54 -08002578 if (old_transceiver) {
2579 old_transceiver->internal()->set_mid(rtc::nullopt);
2580 old_transceiver->internal()->set_mline_index(rtc::nullopt);
2581 }
2582 }
2583 const MediaContentDescription* media_desc = content.media_description();
2584 auto transceiver = GetAssociatedTransceiver(content.name);
2585 if (source == cricket::CS_LOCAL) {
2586 // Find the RtpTransceiver that corresponds to this m= section, using the
2587 // mapping between transceivers and m= section indices established when
2588 // creating the offer.
2589 if (!transceiver) {
2590 transceiver = GetTransceiverByMLineIndex(mline_index);
2591 }
2592 if (!transceiver) {
2593 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2594 "Unknown transceiver");
2595 }
2596 } else {
2597 RTC_DCHECK_EQ(source, cricket::CS_REMOTE);
2598 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers
2599 // of the same type...
2600 if (!transceiver &&
2601 RtpTransceiverDirectionHasRecv(media_desc->direction())) {
2602 transceiver = FindAvailableTransceiverToReceive(media_desc->type());
2603 }
2604 // If no RtpTransceiver was found in the previous step, create one with a
2605 // recvonly direction.
2606 if (!transceiver) {
Steve Anton02ee47c2018-01-10 16:26:06 -08002607 auto sender =
2608 CreateSender(media_desc->type(), nullptr, {rtc::CreateRandomUuid()});
Steve Anton5f94aa22018-02-01 10:58:30 -08002609 std::string receiver_id;
2610 if (!media_desc->streams().empty()) {
2611 receiver_id = media_desc->streams()[0].id;
2612 } else {
2613 receiver_id = rtc::CreateRandomUuid();
2614 }
2615 auto receiver = CreateReceiver(media_desc->type(), receiver_id);
Steve Anton02ee47c2018-01-10 16:26:06 -08002616 transceiver = CreateAndAddTransceiver(sender, receiver);
Steve Antondcc3c022017-12-22 16:02:54 -08002617 transceiver->internal()->set_direction(
2618 RtpTransceiverDirection::kRecvOnly);
2619 }
2620 }
2621 RTC_DCHECK(transceiver);
Steve Anton69470252018-02-09 11:43:08 -08002622 if (transceiver->media_type() != media_desc->type()) {
Steve Antondcc3c022017-12-22 16:02:54 -08002623 LOG_AND_RETURN_ERROR(
2624 RTCErrorType::INVALID_PARAMETER,
2625 "Transceiver type does not match media description type.");
2626 }
2627 // Associate the found or created RtpTransceiver with the m= section by
2628 // setting the value of the RtpTransceiver's mid property to the MID of the m=
2629 // section, and establish a mapping between the transceiver and the index of
2630 // the m= section.
2631 transceiver->internal()->set_mid(content.name);
2632 transceiver->internal()->set_mline_index(mline_index);
2633 return std::move(transceiver);
2634}
2635
2636rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2637PeerConnection::GetAssociatedTransceiver(const std::string& mid) const {
2638 RTC_DCHECK(IsUnifiedPlan());
2639 for (auto transceiver : transceivers_) {
2640 if (transceiver->mid() == mid) {
2641 return transceiver;
2642 }
2643 }
2644 return nullptr;
2645}
2646
2647rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2648PeerConnection::GetTransceiverByMLineIndex(size_t mline_index) const {
2649 RTC_DCHECK(IsUnifiedPlan());
2650 for (auto transceiver : transceivers_) {
2651 if (transceiver->internal()->mline_index() == mline_index) {
2652 return transceiver;
2653 }
2654 }
2655 return nullptr;
2656}
2657
2658rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2659PeerConnection::FindAvailableTransceiverToReceive(
2660 cricket::MediaType media_type) const {
2661 RTC_DCHECK(IsUnifiedPlan());
2662 // From JSEP section 5.10 (Applying a Remote Description):
2663 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers of
2664 // the same type that were added to the PeerConnection by addTrack and are not
2665 // associated with any m= section and are not stopped, find the first such
2666 // RtpTransceiver.
2667 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08002668 if (transceiver->media_type() == media_type &&
Steve Antondcc3c022017-12-22 16:02:54 -08002669 transceiver->internal()->created_by_addtrack() && !transceiver->mid() &&
2670 !transceiver->stopped()) {
2671 return transceiver;
2672 }
2673 }
2674 return nullptr;
2675}
2676
Steve Antoned10bd92017-12-05 10:52:59 -08002677const cricket::ContentInfo* PeerConnection::FindMediaSectionForTransceiver(
2678 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2679 transceiver,
2680 const SessionDescriptionInterface* sdesc) const {
2681 RTC_DCHECK(transceiver);
2682 RTC_DCHECK(sdesc);
2683 if (IsUnifiedPlan()) {
2684 if (!transceiver->internal()->mid()) {
2685 // This transceiver is not associated with a media section yet.
2686 return nullptr;
2687 }
2688 return sdesc->description()->GetContentByName(
2689 *transceiver->internal()->mid());
2690 } else {
2691 // Plan B only allows at most one audio and one video section, so use the
2692 // first media section of that type.
2693 return cricket::GetFirstMediaContent(sdesc->description()->contents(),
Steve Anton69470252018-02-09 11:43:08 -08002694 transceiver->media_type());
Steve Antoned10bd92017-12-05 10:52:59 -08002695 }
2696}
2697
deadbeef46c73892016-11-16 19:42:04 -08002698PeerConnectionInterface::RTCConfiguration PeerConnection::GetConfiguration() {
2699 return configuration_;
2700}
2701
deadbeef293e9262017-01-11 12:28:30 -08002702bool PeerConnection::SetConfiguration(const RTCConfiguration& configuration,
2703 RTCError* error) {
Peter Boström1a9d6152015-12-08 22:15:17 +01002704 TRACE_EVENT0("webrtc", "PeerConnection::SetConfiguration");
deadbeef6de92f92016-12-12 18:49:32 -08002705
Steve Anton75737c02017-11-06 10:37:17 -08002706 if (local_description() && configuration.ice_candidate_pool_size !=
2707 configuration_.ice_candidate_pool_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002708 RTC_LOG(LS_ERROR) << "Can't change candidate pool size after calling "
2709 "SetLocalDescription.";
deadbeef293e9262017-01-11 12:28:30 -08002710 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00002711 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002712
deadbeef293e9262017-01-11 12:28:30 -08002713 // The simplest (and most future-compatible) way to tell if the config was
2714 // modified in an invalid way is to copy each property we do support
2715 // modifying, then use operator==. There are far more properties we don't
2716 // support modifying than those we do, and more could be added.
2717 RTCConfiguration modified_config = configuration_;
2718 modified_config.servers = configuration.servers;
2719 modified_config.type = configuration.type;
2720 modified_config.ice_candidate_pool_size =
2721 configuration.ice_candidate_pool_size;
2722 modified_config.prune_turn_ports = configuration.prune_turn_ports;
skvladd1f5fda2017-02-03 16:54:05 -08002723 modified_config.ice_check_min_interval = configuration.ice_check_min_interval;
Qingsi Wange6826d22018-03-08 14:55:14 -08002724 modified_config.ice_check_interval_strong_connectivity =
2725 configuration.ice_check_interval_strong_connectivity;
2726 modified_config.ice_check_interval_weak_connectivity =
2727 configuration.ice_check_interval_weak_connectivity;
Qingsi Wang22e623a2018-03-13 10:53:57 -07002728 modified_config.ice_unwritable_timeout = configuration.ice_unwritable_timeout;
2729 modified_config.ice_unwritable_min_checks =
2730 configuration.ice_unwritable_min_checks;
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08002731 modified_config.stun_candidate_keepalive_interval =
2732 configuration.stun_candidate_keepalive_interval;
Jonas Orelandbdcee282017-10-10 14:01:40 +02002733 modified_config.turn_customizer = configuration.turn_customizer;
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08002734 modified_config.network_preference = configuration.network_preference;
deadbeef293e9262017-01-11 12:28:30 -08002735 if (configuration != modified_config) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002736 RTC_LOG(LS_ERROR) << "Modifying the configuration in an unsupported way.";
deadbeef293e9262017-01-11 12:28:30 -08002737 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
2738 }
2739
Steve Anton038834f2017-07-14 15:59:59 -07002740 // Validate the modified configuration.
2741 RTCError validate_error = ValidateConfiguration(modified_config);
2742 if (!validate_error.ok()) {
2743 return SafeSetError(std::move(validate_error), error);
2744 }
2745
deadbeef293e9262017-01-11 12:28:30 -08002746 // Note that this isn't possible through chromium, since it's an unsigned
2747 // short in WebIDL.
2748 if (configuration.ice_candidate_pool_size < 0 ||
2749 configuration.ice_candidate_pool_size > UINT16_MAX) {
2750 return SafeSetError(RTCErrorType::INVALID_RANGE, error);
2751 }
2752
2753 // Parse ICE servers before hopping to network thread.
2754 cricket::ServerAddresses stun_servers;
2755 std::vector<cricket::RelayServerConfig> turn_servers;
2756 RTCErrorType parse_error =
2757 ParseIceServers(configuration.servers, &stun_servers, &turn_servers);
2758 if (parse_error != RTCErrorType::NONE) {
2759 return SafeSetError(parse_error, error);
2760 }
2761
2762 // In theory this shouldn't fail.
2763 if (!network_thread()->Invoke<bool>(
2764 RTC_FROM_HERE,
2765 rtc::Bind(&PeerConnection::ReconfigurePortAllocator_n, this,
2766 stun_servers, turn_servers, modified_config.type,
2767 modified_config.ice_candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02002768 modified_config.prune_turn_ports,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08002769 modified_config.turn_customizer,
2770 modified_config.stun_candidate_keepalive_interval))) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002771 RTC_LOG(LS_ERROR) << "Failed to apply configuration to PortAllocator.";
deadbeef293e9262017-01-11 12:28:30 -08002772 return SafeSetError(RTCErrorType::INTERNAL_ERROR, error);
2773 }
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07002774
deadbeefd1a38b52016-12-10 13:15:33 -08002775 // As described in JSEP, calling setConfiguration with new ICE servers or
2776 // candidate policy must set a "needs-ice-restart" bit so that the next offer
2777 // triggers an ICE restart which will pick up the changes.
deadbeef293e9262017-01-11 12:28:30 -08002778 if (modified_config.servers != configuration_.servers ||
2779 modified_config.type != configuration_.type ||
2780 modified_config.prune_turn_ports != configuration_.prune_turn_ports) {
Steve Antond25da372017-11-06 14:50:29 -08002781 transport_controller_->SetNeedsIceRestartFlag();
deadbeefd1a38b52016-12-10 13:15:33 -08002782 }
skvladd1f5fda2017-02-03 16:54:05 -08002783
Qingsi Wang9c98f0c2018-02-15 15:10:59 -08002784 transport_controller_->SetIceConfig(ParseIceConfig(modified_config));
skvladd1f5fda2017-02-03 16:54:05 -08002785
deadbeef293e9262017-01-11 12:28:30 -08002786 configuration_ = modified_config;
2787 return SafeSetError(RTCErrorType::NONE, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00002788}
2789
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002790bool PeerConnection::AddIceCandidate(
2791 const IceCandidateInterface* ice_candidate) {
Peter Boström1a9d6152015-12-08 22:15:17 +01002792 TRACE_EVENT0("webrtc", "PeerConnection::AddIceCandidate");
zhihuang29ff8442016-07-27 11:07:25 -07002793 if (IsClosed()) {
2794 return false;
2795 }
Steve Antond25da372017-11-06 14:50:29 -08002796
2797 if (!remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002798 RTC_LOG(LS_ERROR) << "ProcessIceMessage: ICE candidates can't be added "
Jonas Olsson45cc8902018-02-13 10:37:07 +01002799 "without any remote session description.";
Steve Antond25da372017-11-06 14:50:29 -08002800 return false;
2801 }
2802
2803 if (!ice_candidate) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002804 RTC_LOG(LS_ERROR) << "ProcessIceMessage: Candidate is NULL.";
Steve Antond25da372017-11-06 14:50:29 -08002805 return false;
2806 }
2807
2808 bool valid = false;
2809 bool ready = ReadyToUseRemoteCandidate(ice_candidate, nullptr, &valid);
2810 if (!valid) {
2811 return false;
2812 }
2813
2814 // Add this candidate to the remote session description.
2815 if (!mutable_remote_description()->AddCandidate(ice_candidate)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002816 RTC_LOG(LS_ERROR) << "ProcessIceMessage: Candidate cannot be used.";
Steve Antond25da372017-11-06 14:50:29 -08002817 return false;
2818 }
2819
2820 if (ready) {
2821 return UseCandidate(ice_candidate);
2822 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002823 RTC_LOG(LS_INFO) << "ProcessIceMessage: Not ready to use candidate.";
Steve Antond25da372017-11-06 14:50:29 -08002824 return true;
2825 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002826}
2827
Honghai Zhang7fb69db2016-03-14 11:59:18 -07002828bool PeerConnection::RemoveIceCandidates(
2829 const std::vector<cricket::Candidate>& candidates) {
2830 TRACE_EVENT0("webrtc", "PeerConnection::RemoveIceCandidates");
Steve Antond25da372017-11-06 14:50:29 -08002831 if (!remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002832 RTC_LOG(LS_ERROR) << "RemoveRemoteIceCandidates: ICE candidates can't be "
Jonas Olsson45cc8902018-02-13 10:37:07 +01002833 "removed without any remote session description.";
Steve Antond25da372017-11-06 14:50:29 -08002834 return false;
2835 }
2836
2837 if (candidates.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002838 RTC_LOG(LS_ERROR) << "RemoveRemoteIceCandidates: candidates are empty.";
Steve Antond25da372017-11-06 14:50:29 -08002839 return false;
2840 }
2841
2842 size_t number_removed =
2843 mutable_remote_description()->RemoveCandidates(candidates);
2844 if (number_removed != candidates.size()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002845 RTC_LOG(LS_ERROR)
2846 << "RemoveRemoteIceCandidates: Failed to remove candidates. "
Jonas Olsson45cc8902018-02-13 10:37:07 +01002847 "Requested "
2848 << candidates.size() << " but only " << number_removed
Mirko Bonadei675513b2017-11-09 11:09:25 +01002849 << " are removed.";
Steve Antond25da372017-11-06 14:50:29 -08002850 }
2851
2852 // Remove the candidates from the transport controller.
2853 std::string error;
2854 bool res = transport_controller_->RemoveRemoteCandidates(candidates, &error);
2855 if (!res && !error.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002856 RTC_LOG(LS_ERROR) << "Error when removing remote candidates: " << error;
Steve Antond25da372017-11-06 14:50:29 -08002857 }
2858 return true;
Honghai Zhang7fb69db2016-03-14 11:59:18 -07002859}
2860
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00002861void PeerConnection::RegisterUMAObserver(UMAObserver* observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +01002862 TRACE_EVENT0("webrtc", "PeerConnection::RegisterUmaObserver");
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00002863 uma_observer_ = observer;
guoweis@webrtc.org7169afd2014-12-04 17:59:29 +00002864
Steve Anton75737c02017-11-06 10:37:17 -08002865 if (transport_controller()) {
2866 transport_controller()->SetMetricsObserver(uma_observer_);
guoweis@webrtc.org7169afd2014-12-04 17:59:29 +00002867 }
2868
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00002869 // Send information about IPv4/IPv6 status.
deadbeef293e9262017-01-11 12:28:30 -08002870 if (uma_observer_) {
Honghai Zhangd93f50c2016-10-05 11:47:22 -07002871 port_allocator_->SetMetricsObserver(uma_observer_);
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00002872 if (port_allocator_->flags() & cricket::PORTALLOCATOR_ENABLE_IPV6) {
Guo-wei Shiehdfbe6792015-09-03 17:12:07 -07002873 uma_observer_->IncrementEnumCounter(
2874 kEnumCounterAddressFamily, kPeerConnection_IPv6,
2875 kPeerConnectionAddressFamilyCounter_Max);
mallinath@webrtc.orgb445f262014-05-23 22:19:37 +00002876 } else {
Guo-wei Shiehdfbe6792015-09-03 17:12:07 -07002877 uma_observer_->IncrementEnumCounter(
2878 kEnumCounterAddressFamily, kPeerConnection_IPv4,
2879 kPeerConnectionAddressFamilyCounter_Max);
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00002880 }
Harald Alvestrand5dbb5862018-02-13 23:48:00 +01002881 // Send information about the requested SDP semantics.
2882 switch (configuration_.sdp_semantics) {
2883 case SdpSemantics::kDefault:
2884 uma_observer_->IncrementEnumCounter(kEnumCounterSdpSemanticRequested,
2885 kSdpSemanticRequestDefault,
2886 kSdpSemanticRequestMax);
2887
2888 break;
2889 case SdpSemantics::kPlanB:
2890 uma_observer_->IncrementEnumCounter(kEnumCounterSdpSemanticRequested,
2891 kSdpSemanticRequestPlanB,
2892 kSdpSemanticRequestMax);
2893 break;
2894 case SdpSemantics::kUnifiedPlan:
2895 uma_observer_->IncrementEnumCounter(kEnumCounterSdpSemanticRequested,
2896 kSdpSemanticRequestUnifiedPlan,
2897 kSdpSemanticRequestMax);
2898 break;
2899 default:
2900 RTC_NOTREACHED();
2901 }
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00002902 }
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00002903}
2904
zstein4b979802017-06-02 14:37:37 -07002905RTCError PeerConnection::SetBitrate(const BitrateParameters& bitrate) {
Steve Anton978b8762017-09-29 12:15:02 -07002906 if (!worker_thread()->IsCurrent()) {
2907 return worker_thread()->Invoke<RTCError>(
zstein4b979802017-06-02 14:37:37 -07002908 RTC_FROM_HERE, rtc::Bind(&PeerConnection::SetBitrate, this, bitrate));
2909 }
2910
2911 const bool has_min = static_cast<bool>(bitrate.min_bitrate_bps);
2912 const bool has_current = static_cast<bool>(bitrate.current_bitrate_bps);
2913 const bool has_max = static_cast<bool>(bitrate.max_bitrate_bps);
2914 if (has_min && *bitrate.min_bitrate_bps < 0) {
2915 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2916 "min_bitrate_bps <= 0");
2917 }
2918 if (has_current) {
2919 if (has_min && *bitrate.current_bitrate_bps < *bitrate.min_bitrate_bps) {
2920 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2921 "current_bitrate_bps < min_bitrate_bps");
2922 } else if (*bitrate.current_bitrate_bps < 0) {
2923 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2924 "curent_bitrate_bps < 0");
2925 }
2926 }
2927 if (has_max) {
2928 if (has_current &&
2929 *bitrate.max_bitrate_bps < *bitrate.current_bitrate_bps) {
2930 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2931 "max_bitrate_bps < current_bitrate_bps");
2932 } else if (has_min && *bitrate.max_bitrate_bps < *bitrate.min_bitrate_bps) {
2933 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2934 "max_bitrate_bps < min_bitrate_bps");
2935 } else if (*bitrate.max_bitrate_bps < 0) {
2936 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2937 "max_bitrate_bps < 0");
2938 }
2939 }
2940
Sebastian Janssonfc8d26b2018-02-21 09:52:06 +01002941 BitrateConstraintsMask mask;
zstein4b979802017-06-02 14:37:37 -07002942 mask.min_bitrate_bps = bitrate.min_bitrate_bps;
2943 mask.start_bitrate_bps = bitrate.current_bitrate_bps;
2944 mask.max_bitrate_bps = bitrate.max_bitrate_bps;
2945
2946 RTC_DCHECK(call_.get());
Sebastian Jansson8f83b422018-02-21 13:07:13 +01002947 call_->GetTransportControllerSend()->SetClientBitratePreferences(mask);
zstein4b979802017-06-02 14:37:37 -07002948
2949 return RTCError::OK();
2950}
2951
Alex Narest78609d52017-10-20 10:37:47 +02002952void PeerConnection::SetBitrateAllocationStrategy(
2953 std::unique_ptr<rtc::BitrateAllocationStrategy>
2954 bitrate_allocation_strategy) {
2955 rtc::Thread* worker_thread = factory_->worker_thread();
2956 if (!worker_thread->IsCurrent()) {
2957 rtc::BitrateAllocationStrategy* strategy_raw =
2958 bitrate_allocation_strategy.release();
2959 auto functor = [this, strategy_raw]() {
2960 call_->SetBitrateAllocationStrategy(
2961 rtc::WrapUnique<rtc::BitrateAllocationStrategy>(strategy_raw));
2962 };
2963 worker_thread->Invoke<void>(RTC_FROM_HERE, functor);
2964 return;
2965 }
2966 RTC_DCHECK(call_.get());
2967 call_->SetBitrateAllocationStrategy(std::move(bitrate_allocation_strategy));
2968}
2969
henrika5f6bf242017-11-01 11:06:56 +01002970void PeerConnection::SetAudioPlayout(bool playout) {
2971 if (!worker_thread()->IsCurrent()) {
2972 worker_thread()->Invoke<void>(
2973 RTC_FROM_HERE,
2974 rtc::Bind(&PeerConnection::SetAudioPlayout, this, playout));
2975 return;
2976 }
2977 auto audio_state =
2978 factory_->channel_manager()->media_engine()->GetAudioState();
2979 audio_state->SetPlayout(playout);
2980}
2981
2982void PeerConnection::SetAudioRecording(bool recording) {
2983 if (!worker_thread()->IsCurrent()) {
2984 worker_thread()->Invoke<void>(
2985 RTC_FROM_HERE,
2986 rtc::Bind(&PeerConnection::SetAudioRecording, this, recording));
2987 return;
2988 }
2989 auto audio_state =
2990 factory_->channel_manager()->media_engine()->GetAudioState();
2991 audio_state->SetRecording(recording);
2992}
2993
Steve Anton8c0f7a72017-10-03 10:03:10 -07002994std::unique_ptr<rtc::SSLCertificate>
2995PeerConnection::GetRemoteAudioSSLCertificate() {
Taylor Brandstetterc3928662018-02-23 13:04:51 -08002996 std::unique_ptr<rtc::SSLCertChain> chain = GetRemoteAudioSSLCertChain();
2997 if (!chain || !chain->GetSize()) {
Steve Anton8c0f7a72017-10-03 10:03:10 -07002998 return nullptr;
2999 }
Taylor Brandstetterc3928662018-02-23 13:04:51 -08003000 return chain->Get(0).GetUniqueReference();
Steve Anton8c0f7a72017-10-03 10:03:10 -07003001}
3002
Zhi Huang70b820f2018-01-27 14:16:15 -08003003std::unique_ptr<rtc::SSLCertChain>
3004PeerConnection::GetRemoteAudioSSLCertChain() {
Steve Antonafb0bb72018-02-20 11:35:37 -08003005 auto audio_transceiver = GetFirstAudioTransceiver();
3006 if (!audio_transceiver || !audio_transceiver->internal()->channel()) {
Zhi Huang70b820f2018-01-27 14:16:15 -08003007 return nullptr;
3008 }
Zhi Huang70b820f2018-01-27 14:16:15 -08003009 return transport_controller_->GetRemoteSSLCertChain(
Steve Antonafb0bb72018-02-20 11:35:37 -08003010 audio_transceiver->internal()->channel()->transport_name());
3011}
3012
3013rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3014PeerConnection::GetFirstAudioTransceiver() const {
3015 for (auto transceiver : transceivers_) {
3016 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
3017 return transceiver;
3018 }
3019 }
3020 return nullptr;
Zhi Huang70b820f2018-01-27 14:16:15 -08003021}
3022
ivoc14d5dbe2016-07-04 07:06:55 -07003023bool PeerConnection::StartRtcEventLog(rtc::PlatformFile file,
3024 int64_t max_size_bytes) {
Elad Alon99c3fe52017-10-13 16:29:40 +02003025 // TODO(eladalon): It would be better to not allow negative values into PC.
3026 const size_t max_size = (max_size_bytes < 0)
3027 ? RtcEventLog::kUnlimitedOutput
3028 : rtc::saturated_cast<size_t>(max_size_bytes);
3029 return StartRtcEventLog(
Bjorn Tereliusde939432017-11-20 17:38:14 +01003030 rtc::MakeUnique<RtcEventLogOutputFile>(file, max_size),
3031 webrtc::RtcEventLog::kImmediateOutput);
Elad Alon99c3fe52017-10-13 16:29:40 +02003032}
3033
Bjorn Tereliusde939432017-11-20 17:38:14 +01003034bool PeerConnection::StartRtcEventLog(std::unique_ptr<RtcEventLogOutput> output,
3035 int64_t output_period_ms) {
Karl Wibergd6b48192017-10-16 23:01:06 +02003036 // TODO(eladalon): In C++14, this can be done with a lambda.
3037 struct Functor {
Bjorn Tereliusde939432017-11-20 17:38:14 +01003038 bool operator()() {
3039 return pc->StartRtcEventLog_w(std::move(output), output_period_ms);
3040 }
Karl Wibergd6b48192017-10-16 23:01:06 +02003041 PeerConnection* const pc;
3042 std::unique_ptr<RtcEventLogOutput> output;
Bjorn Tereliusde939432017-11-20 17:38:14 +01003043 const int64_t output_period_ms;
Elad Alon99c3fe52017-10-13 16:29:40 +02003044 };
Bjorn Tereliusde939432017-11-20 17:38:14 +01003045 return worker_thread()->Invoke<bool>(
3046 RTC_FROM_HERE, Functor{this, std::move(output), output_period_ms});
ivoc14d5dbe2016-07-04 07:06:55 -07003047}
3048
3049void PeerConnection::StopRtcEventLog() {
Steve Anton978b8762017-09-29 12:15:02 -07003050 worker_thread()->Invoke<void>(
ivoc14d5dbe2016-07-04 07:06:55 -07003051 RTC_FROM_HERE, rtc::Bind(&PeerConnection::StopRtcEventLog_w, this));
3052}
3053
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003054const SessionDescriptionInterface* PeerConnection::local_description() const {
Steve Anton75737c02017-11-06 10:37:17 -08003055 return pending_local_description_ ? pending_local_description_.get()
3056 : current_local_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003057}
3058
3059const SessionDescriptionInterface* PeerConnection::remote_description() const {
Steve Anton75737c02017-11-06 10:37:17 -08003060 return pending_remote_description_ ? pending_remote_description_.get()
3061 : current_remote_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003062}
3063
deadbeeffe4a8a42016-12-20 17:56:17 -08003064const SessionDescriptionInterface* PeerConnection::current_local_description()
3065 const {
Steve Anton75737c02017-11-06 10:37:17 -08003066 return current_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003067}
3068
3069const SessionDescriptionInterface* PeerConnection::current_remote_description()
3070 const {
Steve Anton75737c02017-11-06 10:37:17 -08003071 return current_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003072}
3073
3074const SessionDescriptionInterface* PeerConnection::pending_local_description()
3075 const {
Steve Anton75737c02017-11-06 10:37:17 -08003076 return pending_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003077}
3078
3079const SessionDescriptionInterface* PeerConnection::pending_remote_description()
3080 const {
Steve Anton75737c02017-11-06 10:37:17 -08003081 return pending_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003082}
3083
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003084void PeerConnection::Close() {
Peter Boström1a9d6152015-12-08 22:15:17 +01003085 TRACE_EVENT0("webrtc", "PeerConnection::Close");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003086 // Update stats here so that we have the most recent stats for tracks and
3087 // streams before the channels are closed.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00003088 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003089
Steve Anton75737c02017-11-06 10:37:17 -08003090 ChangeSignalingState(PeerConnectionInterface::kClosed);
Steve Anton3fe1b152017-12-12 10:20:08 -08003091
Steve Anton8af21862017-12-15 11:20:13 -08003092 for (auto transceiver : transceivers_) {
3093 transceiver->Stop();
3094 }
3095 DestroyAllChannels();
Steve Anton75737c02017-11-06 10:37:17 -08003096
Qingsi Wang93a84392018-01-30 17:13:09 -08003097 // The event log is used in the transport controller, which must be outlived
3098 // by the former. CreateOffer by the peer connection is implemented
3099 // asynchronously and if the peer connection is closed without resetting the
3100 // WebRTC session description factory, the session description factory would
3101 // call the transport controller.
3102 webrtc_session_desc_factory_.reset();
3103 transport_controller_.reset();
3104
deadbeef42a42632017-03-10 15:18:00 -08003105 network_thread()->Invoke<void>(
3106 RTC_FROM_HERE,
3107 rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
3108 port_allocator_.get()));
nisseeaabdf62017-05-05 02:23:02 -07003109
Steve Anton978b8762017-09-29 12:15:02 -07003110 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
eladalon248fd4f2017-09-06 05:18:15 -07003111 call_.reset();
3112 // The event log must outlive call (and any other object that uses it).
3113 event_log_.reset();
3114 });
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003115}
3116
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003117void PeerConnection::OnMessage(rtc::Message* msg) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003118 switch (msg->message_id) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003119 case MSG_SET_SESSIONDESCRIPTION_SUCCESS: {
3120 SetSessionDescriptionMsg* param =
3121 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
3122 param->observer->OnSuccess();
3123 delete param;
3124 break;
3125 }
3126 case MSG_SET_SESSIONDESCRIPTION_FAILED: {
3127 SetSessionDescriptionMsg* param =
3128 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01003129 param->observer->OnFailure(std::move(param->error));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003130 delete param;
3131 break;
3132 }
deadbeefab9b2d12015-10-14 11:33:11 -07003133 case MSG_CREATE_SESSIONDESCRIPTION_FAILED: {
3134 CreateSessionDescriptionMsg* param =
3135 static_cast<CreateSessionDescriptionMsg*>(msg->pdata);
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01003136 param->observer->OnFailure(std::move(param->error));
deadbeefab9b2d12015-10-14 11:33:11 -07003137 delete param;
3138 break;
3139 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003140 case MSG_GETSTATS: {
3141 GetStatsMsg* param = static_cast<GetStatsMsg*>(msg->pdata);
nissee8abe3e2017-01-18 05:00:34 -08003142 StatsReports reports;
3143 stats_->GetStats(param->track, &reports);
3144 param->observer->OnComplete(reports);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003145 delete param;
3146 break;
3147 }
deadbeefbd292462015-12-14 18:15:29 -08003148 case MSG_FREE_DATACHANNELS: {
3149 sctp_data_channels_to_free_.clear();
3150 break;
3151 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003152 default:
nisseeb4ca4e2017-01-12 02:24:27 -08003153 RTC_NOTREACHED() << "Not implemented";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003154 break;
3155 }
3156}
3157
Steve Antonafb0bb72018-02-20 11:35:37 -08003158cricket::VoiceMediaChannel* PeerConnection::voice_media_channel() const {
3159 RTC_DCHECK(!IsUnifiedPlan());
3160 auto* voice_channel = static_cast<cricket::VoiceChannel*>(
3161 GetAudioTransceiver()->internal()->channel());
3162 if (voice_channel) {
3163 return voice_channel->media_channel();
3164 } else {
3165 return nullptr;
3166 }
3167}
3168
3169cricket::VideoMediaChannel* PeerConnection::video_media_channel() const {
3170 RTC_DCHECK(!IsUnifiedPlan());
3171 auto* video_channel = static_cast<cricket::VideoChannel*>(
3172 GetVideoTransceiver()->internal()->channel());
3173 if (video_channel) {
3174 return video_channel->media_channel();
3175 } else {
3176 return nullptr;
3177 }
3178}
3179
Steve Anton4171afb2017-11-20 10:20:22 -08003180void PeerConnection::CreateAudioReceiver(
3181 MediaStreamInterface* stream,
3182 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01003183 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
3184 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Steve Antond3679212018-01-17 17:41:02 -08003185 auto* audio_receiver = new AudioRtpReceiver(
3186 worker_thread(), remote_sender_info.sender_id, streams);
Steve Anton57858b32018-02-15 15:19:50 -08003187 audio_receiver->SetVoiceMediaChannel(voice_media_channel());
Steve Antond3679212018-01-17 17:41:02 -08003188 audio_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
3189 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
3190 signaling_thread(), audio_receiver);
Steve Anton4171afb2017-11-20 10:20:22 -08003191 GetAudioTransceiver()->internal()->AddReceiver(receiver);
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01003192 observer_->OnAddTrack(receiver, std::move(streams));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003193}
3194
Steve Anton4171afb2017-11-20 10:20:22 -08003195void PeerConnection::CreateVideoReceiver(
3196 MediaStreamInterface* stream,
3197 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01003198 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
3199 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Steve Antond3679212018-01-17 17:41:02 -08003200 auto* video_receiver = new VideoRtpReceiver(
3201 worker_thread(), remote_sender_info.sender_id, streams);
Steve Anton57858b32018-02-15 15:19:50 -08003202 video_receiver->SetVideoMediaChannel(video_media_channel());
Steve Antond3679212018-01-17 17:41:02 -08003203 video_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
3204 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
3205 signaling_thread(), video_receiver);
Steve Anton4171afb2017-11-20 10:20:22 -08003206 GetVideoTransceiver()->internal()->AddReceiver(receiver);
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01003207 observer_->OnAddTrack(receiver, std::move(streams));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003208}
3209
deadbeef70ab1a12015-09-28 16:53:55 -07003210// TODO(deadbeef): Keep RtpReceivers around even if track goes away in remote
3211// description.
Henrik Boström933d8b02017-10-10 10:05:16 -07003212rtc::scoped_refptr<RtpReceiverInterface> PeerConnection::RemoveAndStopReceiver(
Steve Anton4171afb2017-11-20 10:20:22 -08003213 const RtpSenderInfo& remote_sender_info) {
3214 auto receiver = FindReceiverById(remote_sender_info.sender_id);
3215 if (!receiver) {
3216 RTC_LOG(LS_WARNING) << "RtpReceiver for track with id "
3217 << remote_sender_info.sender_id << " doesn't exist.";
Henrik Boström933d8b02017-10-10 10:05:16 -07003218 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07003219 }
Steve Anton4171afb2017-11-20 10:20:22 -08003220 if (receiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
3221 GetAudioTransceiver()->internal()->RemoveReceiver(receiver);
3222 } else {
3223 GetVideoTransceiver()->internal()->RemoveReceiver(receiver);
3224 }
Henrik Boström933d8b02017-10-10 10:05:16 -07003225 return receiver;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003226}
3227
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003228void PeerConnection::AddAudioTrack(AudioTrackInterface* track,
3229 MediaStreamInterface* stream) {
3230 RTC_DCHECK(!IsClosed());
3231 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003232 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003233 // We already have a sender for this track, so just change the stream_id
3234 // so that it's correct in the next call to CreateOffer.
Seth Hampson13b8bad2018-03-13 16:05:28 -07003235 sender->internal()->set_stream_id(stream->id());
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003236 return;
3237 }
3238
3239 // Normal case; we've never seen this track before.
Steve Anton02ee47c2018-01-10 16:26:06 -08003240 auto new_sender =
Seth Hampson13b8bad2018-03-13 16:05:28 -07003241 CreateSender(cricket::MEDIA_TYPE_AUDIO, track, {stream->id()});
Steve Anton57858b32018-02-15 15:19:50 -08003242 new_sender->internal()->SetVoiceMediaChannel(voice_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08003243 GetAudioTransceiver()->internal()->AddSender(new_sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003244 // If the sender has already been configured in SDP, we call SetSsrc,
3245 // which will connect the sender to the underlying transport. This can
3246 // occur if a local session description that contains the ID of the sender
3247 // is set before AddStream is called. It can also occur if the local
3248 // session description is not changed and RemoveStream is called, and
3249 // later AddStream is called again with the same stream.
Steve Anton4171afb2017-11-20 10:20:22 -08003250 const RtpSenderInfo* sender_info =
Seth Hampson13b8bad2018-03-13 16:05:28 -07003251 FindSenderInfo(local_audio_sender_infos_, stream->id(), track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08003252 if (sender_info) {
3253 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003254 }
3255}
3256
3257// TODO(deadbeef): Don't destroy RtpSenders here; they should be kept around
3258// indefinitely, when we have unified plan SDP.
3259void PeerConnection::RemoveAudioTrack(AudioTrackInterface* track,
3260 MediaStreamInterface* stream) {
3261 RTC_DCHECK(!IsClosed());
3262 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003263 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003264 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
3265 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003266 return;
3267 }
Steve Anton4171afb2017-11-20 10:20:22 -08003268 GetAudioTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003269}
3270
3271void PeerConnection::AddVideoTrack(VideoTrackInterface* track,
3272 MediaStreamInterface* stream) {
3273 RTC_DCHECK(!IsClosed());
3274 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003275 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003276 // We already have a sender for this track, so just change the stream_id
3277 // so that it's correct in the next call to CreateOffer.
Seth Hampson13b8bad2018-03-13 16:05:28 -07003278 sender->internal()->set_stream_id(stream->id());
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003279 return;
3280 }
3281
3282 // Normal case; we've never seen this track before.
Steve Anton02ee47c2018-01-10 16:26:06 -08003283 auto new_sender =
Seth Hampson13b8bad2018-03-13 16:05:28 -07003284 CreateSender(cricket::MEDIA_TYPE_VIDEO, track, {stream->id()});
Steve Anton57858b32018-02-15 15:19:50 -08003285 new_sender->internal()->SetVideoMediaChannel(video_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08003286 GetVideoTransceiver()->internal()->AddSender(new_sender);
3287 const RtpSenderInfo* sender_info =
Seth Hampson13b8bad2018-03-13 16:05:28 -07003288 FindSenderInfo(local_video_sender_infos_, stream->id(), track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08003289 if (sender_info) {
3290 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003291 }
3292}
3293
3294void PeerConnection::RemoveVideoTrack(VideoTrackInterface* track,
3295 MediaStreamInterface* stream) {
3296 RTC_DCHECK(!IsClosed());
3297 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003298 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003299 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
3300 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003301 return;
3302 }
Steve Anton4171afb2017-11-20 10:20:22 -08003303 GetVideoTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003304}
3305
Steve Antonba818672017-11-06 10:21:57 -08003306void PeerConnection::SetIceConnectionState(IceConnectionState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07003307 RTC_DCHECK(signaling_thread()->IsCurrent());
Steve Antonba818672017-11-06 10:21:57 -08003308 if (ice_connection_state_ == new_state) {
3309 return;
3310 }
3311
deadbeefcbecd352015-09-23 11:50:27 -07003312 // After transitioning to "closed", ignore any additional states from
Steve Antonba818672017-11-06 10:21:57 -08003313 // TransportController (such as "disconnected").
deadbeefab9b2d12015-10-14 11:33:11 -07003314 if (IsClosed()) {
deadbeefcbecd352015-09-23 11:50:27 -07003315 return;
3316 }
Steve Antonba818672017-11-06 10:21:57 -08003317
Mirko Bonadei675513b2017-11-09 11:09:25 +01003318 RTC_LOG(LS_INFO) << "Changing IceConnectionState " << ice_connection_state_
3319 << " => " << new_state;
Steve Antonba818672017-11-06 10:21:57 -08003320 RTC_DCHECK(ice_connection_state_ !=
3321 PeerConnectionInterface::kIceConnectionClosed);
3322
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003323 ice_connection_state_ = new_state;
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00003324 observer_->OnIceConnectionChange(ice_connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003325}
3326
3327void PeerConnection::OnIceGatheringChange(
3328 PeerConnectionInterface::IceGatheringState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07003329 RTC_DCHECK(signaling_thread()->IsCurrent());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003330 if (IsClosed()) {
3331 return;
3332 }
3333 ice_gathering_state_ = new_state;
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00003334 observer_->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003335}
3336
jbauch81bf7b02017-03-25 08:31:12 -07003337void PeerConnection::OnIceCandidate(
3338 std::unique_ptr<IceCandidateInterface> candidate) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07003339 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07003340 if (IsClosed()) {
3341 return;
3342 }
jbauch81bf7b02017-03-25 08:31:12 -07003343 observer_->OnIceCandidate(candidate.get());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003344}
3345
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003346void PeerConnection::OnIceCandidatesRemoved(
3347 const std::vector<cricket::Candidate>& candidates) {
3348 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07003349 if (IsClosed()) {
3350 return;
3351 }
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003352 observer_->OnIceCandidatesRemoved(candidates);
3353}
3354
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003355void PeerConnection::ChangeSignalingState(
3356 PeerConnectionInterface::SignalingState signaling_state) {
Steve Antonba818672017-11-06 10:21:57 -08003357 RTC_DCHECK(signaling_thread()->IsCurrent());
3358 if (signaling_state_ == signaling_state) {
3359 return;
3360 }
Mirko Bonadei675513b2017-11-09 11:09:25 +01003361 RTC_LOG(LS_INFO) << "Session: " << session_id() << " Old state: "
3362 << GetSignalingStateString(signaling_state_)
3363 << " New state: "
3364 << GetSignalingStateString(signaling_state);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003365 signaling_state_ = signaling_state;
3366 if (signaling_state == kClosed) {
3367 ice_connection_state_ = kIceConnectionClosed;
3368 observer_->OnIceConnectionChange(ice_connection_state_);
3369 if (ice_gathering_state_ != kIceGatheringComplete) {
3370 ice_gathering_state_ = kIceGatheringComplete;
3371 observer_->OnIceGatheringChange(ice_gathering_state_);
3372 }
3373 }
3374 observer_->OnSignalingChange(signaling_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003375}
3376
deadbeefeb459812015-12-15 19:24:43 -08003377void PeerConnection::OnAudioTrackAdded(AudioTrackInterface* track,
3378 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003379 if (IsClosed()) {
3380 return;
3381 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003382 AddAudioTrack(track, stream);
3383 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003384}
3385
deadbeefeb459812015-12-15 19:24:43 -08003386void PeerConnection::OnAudioTrackRemoved(AudioTrackInterface* track,
3387 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003388 if (IsClosed()) {
3389 return;
3390 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003391 RemoveAudioTrack(track, stream);
3392 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003393}
3394
3395void PeerConnection::OnVideoTrackAdded(VideoTrackInterface* track,
3396 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003397 if (IsClosed()) {
3398 return;
3399 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003400 AddVideoTrack(track, stream);
3401 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003402}
3403
3404void PeerConnection::OnVideoTrackRemoved(VideoTrackInterface* track,
3405 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003406 if (IsClosed()) {
3407 return;
3408 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003409 RemoveVideoTrack(track, stream);
3410 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003411}
3412
Henrik Boström31638672017-11-23 17:48:32 +01003413void PeerConnection::PostSetSessionDescriptionSuccess(
3414 SetSessionDescriptionObserver* observer) {
3415 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
3416 signaling_thread()->Post(RTC_FROM_HERE, this,
3417 MSG_SET_SESSIONDESCRIPTION_SUCCESS, msg);
3418}
3419
deadbeefab9b2d12015-10-14 11:33:11 -07003420void PeerConnection::PostSetSessionDescriptionFailure(
3421 SetSessionDescriptionObserver* observer,
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01003422 RTCError&& error) {
3423 RTC_DCHECK(!error.ok());
deadbeefab9b2d12015-10-14 11:33:11 -07003424 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01003425 msg->error = std::move(error);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07003426 signaling_thread()->Post(RTC_FROM_HERE, this,
3427 MSG_SET_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07003428}
3429
3430void PeerConnection::PostCreateSessionDescriptionFailure(
3431 CreateSessionDescriptionObserver* observer,
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01003432 RTCError error) {
3433 RTC_DCHECK(!error.ok());
deadbeefab9b2d12015-10-14 11:33:11 -07003434 CreateSessionDescriptionMsg* msg = new CreateSessionDescriptionMsg(observer);
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01003435 msg->error = std::move(error);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07003436 signaling_thread()->Post(RTC_FROM_HERE, this,
3437 MSG_CREATE_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07003438}
3439
zhihuang1c378ed2017-08-17 14:10:50 -07003440void PeerConnection::GetOptionsForOffer(
Steve Antondcc3c022017-12-22 16:02:54 -08003441 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
deadbeefab9b2d12015-10-14 11:33:11 -07003442 cricket::MediaSessionOptions* session_options) {
Steve Antondcc3c022017-12-22 16:02:54 -08003443 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
zhihuang1c378ed2017-08-17 14:10:50 -07003444
Steve Antondcc3c022017-12-22 16:02:54 -08003445 if (IsUnifiedPlan()) {
3446 GetOptionsForUnifiedPlanOffer(offer_answer_options, session_options);
3447 } else {
3448 GetOptionsForPlanBOffer(offer_answer_options, session_options);
3449 }
3450
Steve Antonfa2260d2017-12-28 16:38:23 -08003451 // Intentionally unset the data channel type for RTP data channel with the
3452 // second condition. Otherwise the RTP data channels would be successfully
3453 // negotiated by default and the unit tests in WebRtcDataBrowserTest will fail
3454 // when building with chromium. We want to leave RTP data channels broken, so
3455 // people won't try to use them.
3456 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
3457 session_options->data_channel_type = data_channel_type();
3458 }
3459
Steve Antondcc3c022017-12-22 16:02:54 -08003460 // Apply ICE restart flag and renomination flag.
3461 for (auto& options : session_options->media_description_options) {
3462 options.transport_options.ice_restart = offer_answer_options.ice_restart;
3463 options.transport_options.enable_ice_renomination =
3464 configuration_.enable_ice_renomination;
3465 }
3466
3467 session_options->rtcp_cname = rtcp_cname_;
3468 session_options->crypto_options = factory_->options().crypto_options;
Steve Antone831b8c2018-02-01 12:22:16 -08003469 session_options->is_unified_plan = IsUnifiedPlan();
Steve Antondcc3c022017-12-22 16:02:54 -08003470}
3471
3472void PeerConnection::GetOptionsForPlanBOffer(
3473 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
3474 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07003475 // Figure out transceiver directional preferences.
3476 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
3477 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
3478
3479 // By default, generate sendrecv/recvonly m= sections.
3480 bool recv_audio = true;
3481 bool recv_video = true;
3482
3483 // By default, only offer a new m= section if we have media to send with it.
3484 bool offer_new_audio_description = send_audio;
3485 bool offer_new_video_description = send_video;
3486 bool offer_new_data_description = HasDataChannels();
3487
3488 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-22 16:02:54 -08003489 if (offer_answer_options.offer_to_receive_audio !=
3490 RTCOfferAnswerOptions::kUndefined) {
3491 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003492 offer_new_audio_description =
Steve Antondcc3c022017-12-22 16:02:54 -08003493 offer_new_audio_description ||
3494 (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003495 }
Steve Antondcc3c022017-12-22 16:02:54 -08003496 if (offer_answer_options.offer_to_receive_video !=
3497 RTCOfferAnswerOptions::kUndefined) {
3498 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003499 offer_new_video_description =
Steve Antondcc3c022017-12-22 16:02:54 -08003500 offer_new_video_description ||
3501 (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003502 }
3503
3504 rtc::Optional<size_t> audio_index;
3505 rtc::Optional<size_t> video_index;
3506 rtc::Optional<size_t> data_index;
3507 // If a current description exists, generate m= sections in the same order,
3508 // using the first audio/video/data section that appears and rejecting
3509 // extraneous ones.
Steve Anton75737c02017-11-06 10:37:17 -08003510 if (local_description()) {
zhihuang1c378ed2017-08-17 14:10:50 -07003511 GenerateMediaDescriptionOptions(
Steve Anton75737c02017-11-06 10:37:17 -08003512 local_description(),
Steve Anton1d03a752017-11-27 14:30:09 -08003513 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
3514 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
3515 &audio_index, &video_index, &data_index, session_options);
deadbeefab9b2d12015-10-14 11:33:11 -07003516 }
3517
zhihuang1c378ed2017-08-17 14:10:50 -07003518 // Add audio/video/data m= sections to the end if needed.
3519 if (!audio_index && offer_new_audio_description) {
3520 session_options->media_description_options.push_back(
3521 cricket::MediaDescriptionOptions(
3522 cricket::MEDIA_TYPE_AUDIO, cricket::CN_AUDIO,
Steve Anton1d03a752017-11-27 14:30:09 -08003523 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
3524 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003525 audio_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07003526 }
zhihuang1c378ed2017-08-17 14:10:50 -07003527 if (!video_index && offer_new_video_description) {
3528 session_options->media_description_options.push_back(
3529 cricket::MediaDescriptionOptions(
3530 cricket::MEDIA_TYPE_VIDEO, cricket::CN_VIDEO,
Steve Anton1d03a752017-11-27 14:30:09 -08003531 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
3532 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003533 video_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07003534 }
zhihuang1c378ed2017-08-17 14:10:50 -07003535 if (!data_index && offer_new_data_description) {
3536 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08003537 GetMediaDescriptionOptionsForActiveData(cricket::CN_DATA));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003538 data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07003539 }
3540
3541 cricket::MediaDescriptionOptions* audio_media_description_options =
3542 !audio_index ? nullptr
3543 : &session_options->media_description_options[*audio_index];
3544 cricket::MediaDescriptionOptions* video_media_description_options =
3545 !video_index ? nullptr
3546 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 14:10:50 -07003547
Steve Anton4171afb2017-11-20 10:20:22 -08003548 AddRtpSenderOptions(GetSendersInternal(), audio_media_description_options,
zhihuang1c378ed2017-08-17 14:10:50 -07003549 video_media_description_options);
Steve Antondcc3c022017-12-22 16:02:54 -08003550}
3551
3552// Find a new MID that is not already in |used_mids|, then add it to |used_mids|
3553// and return a reference to it.
3554// Generated MIDs should be no more than 3 bytes long to take up less space in
3555// the RTP packet.
3556static const std::string& AllocateMid(std::set<std::string>* used_mids) {
3557 RTC_DCHECK(used_mids);
3558 // We're boring: just generate MIDs 0, 1, 2, ...
3559 size_t i = 0;
3560 std::set<std::string>::iterator it;
3561 bool inserted;
3562 do {
3563 std::string mid = rtc::ToString(i++);
3564 auto insert_result = used_mids->insert(mid);
3565 it = insert_result.first;
3566 inserted = insert_result.second;
3567 } while (!inserted);
3568 return *it;
3569}
3570
3571static cricket::MediaDescriptionOptions
3572GetMediaDescriptionOptionsForTransceiver(
3573 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3574 transceiver,
3575 const std::string& mid) {
3576 cricket::MediaDescriptionOptions media_description_options(
Steve Anton69470252018-02-09 11:43:08 -08003577 transceiver->media_type(), mid, transceiver->direction(),
Steve Antondcc3c022017-12-22 16:02:54 -08003578 transceiver->stopped());
Steve Anton5f94aa22018-02-01 10:58:30 -08003579 // This behavior is specified in JSEP. The gist is that:
3580 // 1. The MSID is included if the RtpTransceiver's direction is sendonly or
3581 // sendrecv.
3582 // 2. If the MSID is included, then it must be included in any subsequent
3583 // offer/answer exactly the same until the RtpTransceiver is stopped.
3584 if (!transceiver->stopped() &&
3585 (RtpTransceiverDirectionHasSend(transceiver->direction()) ||
3586 transceiver->internal()->has_ever_been_used_to_send())) {
3587 cricket::SenderOptions sender_options;
3588 sender_options.track_id = transceiver->sender()->id();
3589 sender_options.stream_ids = transceiver->sender()->stream_ids();
3590 // TODO(bugs.webrtc.org/7600): Set num_sim_layers to the number of encodings
3591 // set in the RTP parameters when the transceiver was added.
3592 sender_options.num_sim_layers = 1;
3593 media_description_options.sender_options.push_back(sender_options);
3594 }
Steve Antondcc3c022017-12-22 16:02:54 -08003595 return media_description_options;
3596}
3597
3598void PeerConnection::GetOptionsForUnifiedPlanOffer(
3599 const RTCOfferAnswerOptions& offer_answer_options,
3600 cricket::MediaSessionOptions* session_options) {
3601 // Rules for generating an offer are dictated by JSEP sections 5.2.1 (Initial
3602 // Offers) and 5.2.2 (Subsequent Offers).
3603 RTC_DCHECK_EQ(session_options->media_description_options.size(), 0);
3604 const ContentInfos& local_contents =
3605 (local_description() ? local_description()->description()->contents()
3606 : ContentInfos());
3607 const ContentInfos& remote_contents =
3608 (remote_description() ? remote_description()->description()->contents()
3609 : ContentInfos());
3610 // The mline indices that can be recycled. New transceivers should reuse these
3611 // slots first.
3612 std::queue<size_t> recycleable_mline_indices;
3613 // Track the MIDs used in previous offer/answer exchanges and the current
3614 // offer so that new, unique MIDs are generated.
3615 std::set<std::string> used_mids = seen_mids_;
3616 // First, go through each media section that exists in either the local or
3617 // remote description and generate a media section in this offer for the
3618 // associated transceiver. If a media section can be recycled, generate a
3619 // default, rejected media section here that can be later overwritten.
3620 for (size_t i = 0;
3621 i < std::max(local_contents.size(), remote_contents.size()); ++i) {
3622 // Either |local_content| or |remote_content| is non-null.
3623 const ContentInfo* local_content =
3624 (i < local_contents.size() ? &local_contents[i] : nullptr);
3625 const ContentInfo* remote_content =
3626 (i < remote_contents.size() ? &remote_contents[i] : nullptr);
3627 bool had_been_rejected = (local_content && local_content->rejected) ||
3628 (remote_content && remote_content->rejected);
3629 const std::string& mid =
3630 (local_content ? local_content->name : remote_content->name);
3631 cricket::MediaType media_type =
3632 (local_content ? local_content->media_description()->type()
3633 : remote_content->media_description()->type());
3634 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
3635 media_type == cricket::MEDIA_TYPE_VIDEO) {
3636 auto transceiver = GetAssociatedTransceiver(mid);
3637 RTC_CHECK(transceiver);
3638 // A media section is considered eligible for recycling if it is marked as
3639 // rejected in either the local or remote description.
Seth Hampsonae8a90a2018-02-13 15:33:48 -08003640 if (had_been_rejected && transceiver->stopped()) {
Steve Antondcc3c022017-12-22 16:02:54 -08003641 session_options->media_description_options.push_back(
Steve Anton69470252018-02-09 11:43:08 -08003642 cricket::MediaDescriptionOptions(transceiver->media_type(), mid,
3643 RtpTransceiverDirection::kInactive,
3644 /*stopped=*/true));
Steve Antondcc3c022017-12-22 16:02:54 -08003645 recycleable_mline_indices.push(i);
3646 } else {
3647 session_options->media_description_options.push_back(
3648 GetMediaDescriptionOptionsForTransceiver(transceiver, mid));
3649 // CreateOffer shouldn't really cause any state changes in
3650 // PeerConnection, but we need a way to match new transceivers to new
3651 // media sections in SetLocalDescription and JSEP specifies this is done
3652 // by recording the index of the media section generated for the
3653 // transceiver in the offer.
3654 transceiver->internal()->set_mline_index(i);
3655 }
3656 } else {
3657 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antonfa2260d2017-12-28 16:38:23 -08003658 RTC_CHECK(GetDataMid());
3659 if (had_been_rejected || mid != *GetDataMid()) {
3660 session_options->media_description_options.push_back(
3661 GetMediaDescriptionOptionsForRejectedData(mid));
3662 } else {
3663 session_options->media_description_options.push_back(
3664 GetMediaDescriptionOptionsForActiveData(mid));
3665 }
Steve Antondcc3c022017-12-22 16:02:54 -08003666 }
3667 }
3668 // Next, look for transceivers that are newly added (that is, are not stopped
3669 // and not associated). Reuse media sections marked as recyclable first,
3670 // otherwise append to the end of the offer. New media sections should be
3671 // added in the order they were added to the PeerConnection.
3672 for (auto transceiver : transceivers_) {
3673 if (transceiver->mid() || transceiver->stopped()) {
3674 continue;
3675 }
3676 size_t mline_index;
3677 if (!recycleable_mline_indices.empty()) {
3678 mline_index = recycleable_mline_indices.front();
3679 recycleable_mline_indices.pop();
3680 session_options->media_description_options[mline_index] =
3681 GetMediaDescriptionOptionsForTransceiver(transceiver,
3682 AllocateMid(&used_mids));
3683 } else {
3684 mline_index = session_options->media_description_options.size();
3685 session_options->media_description_options.push_back(
3686 GetMediaDescriptionOptionsForTransceiver(transceiver,
3687 AllocateMid(&used_mids)));
3688 }
3689 // See comment above for why CreateOffer changes the transceiver's state.
3690 transceiver->internal()->set_mline_index(mline_index);
3691 }
Steve Antonfa2260d2017-12-28 16:38:23 -08003692 // Lastly, add a m-section if we have local data channels and an m section
3693 // does not already exist.
3694 if (!GetDataMid() && HasDataChannels()) {
3695 session_options->media_description_options.push_back(
3696 GetMediaDescriptionOptionsForActiveData(AllocateMid(&used_mids)));
3697 }
Steve Antondcc3c022017-12-22 16:02:54 -08003698}
3699
3700void PeerConnection::GetOptionsForAnswer(
3701 const RTCOfferAnswerOptions& offer_answer_options,
3702 cricket::MediaSessionOptions* session_options) {
3703 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
3704
3705 if (IsUnifiedPlan()) {
3706 GetOptionsForUnifiedPlanAnswer(offer_answer_options, session_options);
3707 } else {
3708 GetOptionsForPlanBAnswer(offer_answer_options, session_options);
3709 }
3710
Steve Antonfa2260d2017-12-28 16:38:23 -08003711 // Intentionally unset the data channel type for RTP data channel. Otherwise
3712 // the RTP data channels would be successfully negotiated by default and the
3713 // unit tests in WebRtcDataBrowserTest will fail when building with chromium.
3714 // We want to leave RTP data channels broken, so people won't try to use them.
3715 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
3716 session_options->data_channel_type = data_channel_type();
3717 }
3718
Steve Antondcc3c022017-12-22 16:02:54 -08003719 // Apply ICE renomination flag.
3720 for (auto& options : session_options->media_description_options) {
3721 options.transport_options.enable_ice_renomination =
3722 configuration_.enable_ice_renomination;
3723 }
zhihuang8f65cdf2016-05-06 18:40:30 -07003724
3725 session_options->rtcp_cname = rtcp_cname_;
jbauchcb560652016-08-04 05:20:32 -07003726 session_options->crypto_options = factory_->options().crypto_options;
Steve Antone831b8c2018-02-01 12:22:16 -08003727 session_options->is_unified_plan = IsUnifiedPlan();
deadbeefab9b2d12015-10-14 11:33:11 -07003728}
3729
Steve Antondcc3c022017-12-22 16:02:54 -08003730void PeerConnection::GetOptionsForPlanBAnswer(
3731 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07003732 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07003733 // Figure out transceiver directional preferences.
3734 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
3735 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
3736
3737 // By default, generate sendrecv/recvonly m= sections. The direction is also
3738 // restricted by the direction in the offer.
3739 bool recv_audio = true;
3740 bool recv_video = true;
3741
3742 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-22 16:02:54 -08003743 if (offer_answer_options.offer_to_receive_audio !=
3744 RTCOfferAnswerOptions::kUndefined) {
3745 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
deadbeef0ed85b22016-02-23 17:24:52 -08003746 }
Steve Antondcc3c022017-12-22 16:02:54 -08003747 if (offer_answer_options.offer_to_receive_video !=
3748 RTCOfferAnswerOptions::kUndefined) {
3749 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003750 }
3751
3752 rtc::Optional<size_t> audio_index;
3753 rtc::Optional<size_t> video_index;
3754 rtc::Optional<size_t> data_index;
Steve Antondffead82018-02-06 10:31:29 -08003755
3756 // Generate m= sections that match those in the offer.
3757 // Note that mediasession.cc will handle intersection our preferred
3758 // direction with the offered direction.
3759 GenerateMediaDescriptionOptions(
3760 remote_description(),
3761 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
3762 RtpTransceiverDirectionFromSendRecv(send_video, recv_video), &audio_index,
3763 &video_index, &data_index, session_options);
zhihuang1c378ed2017-08-17 14:10:50 -07003764
3765 cricket::MediaDescriptionOptions* audio_media_description_options =
3766 !audio_index ? nullptr
3767 : &session_options->media_description_options[*audio_index];
3768 cricket::MediaDescriptionOptions* video_media_description_options =
3769 !video_index ? nullptr
3770 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 14:10:50 -07003771
Steve Anton4171afb2017-11-20 10:20:22 -08003772 AddRtpSenderOptions(GetSendersInternal(), audio_media_description_options,
zhihuang1c378ed2017-08-17 14:10:50 -07003773 video_media_description_options);
Steve Antondcc3c022017-12-22 16:02:54 -08003774}
zhihuangaf388472016-11-02 16:49:48 -07003775
Steve Antondcc3c022017-12-22 16:02:54 -08003776void PeerConnection::GetOptionsForUnifiedPlanAnswer(
3777 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
3778 cricket::MediaSessionOptions* session_options) {
3779 // Rules for generating an answer are dictated by JSEP sections 5.3.1 (Initial
3780 // Answers) and 5.3.2 (Subsequent Answers).
3781 RTC_DCHECK(remote_description());
3782 RTC_DCHECK(remote_description()->GetType() == SdpType::kOffer);
3783 for (const ContentInfo& content :
3784 remote_description()->description()->contents()) {
3785 cricket::MediaType media_type = content.media_description()->type();
3786 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
3787 media_type == cricket::MEDIA_TYPE_VIDEO) {
3788 auto transceiver = GetAssociatedTransceiver(content.name);
3789 RTC_CHECK(transceiver);
3790 session_options->media_description_options.push_back(
3791 GetMediaDescriptionOptionsForTransceiver(transceiver, content.name));
3792 } else {
3793 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antondbf9d032018-01-19 15:23:40 -08003794 // Reject all data sections if data channels are disabled.
3795 // Reject a data section if it has already been rejected.
3796 // Reject all data sections except for the first one.
3797 if (data_channel_type_ == cricket::DCT_NONE || content.rejected ||
3798 content.name != *GetDataMid()) {
Steve Antonfa2260d2017-12-28 16:38:23 -08003799 session_options->media_description_options.push_back(
3800 GetMediaDescriptionOptionsForRejectedData(content.name));
3801 } else {
3802 session_options->media_description_options.push_back(
3803 GetMediaDescriptionOptionsForActiveData(content.name));
3804 }
Steve Antondcc3c022017-12-22 16:02:54 -08003805 }
3806 }
htaa2a49d92016-03-04 02:51:39 -08003807}
3808
zhihuang1c378ed2017-08-17 14:10:50 -07003809void PeerConnection::GenerateMediaDescriptionOptions(
3810 const SessionDescriptionInterface* session_desc,
Steve Anton1d03a752017-11-27 14:30:09 -08003811 RtpTransceiverDirection audio_direction,
3812 RtpTransceiverDirection video_direction,
zhihuang1c378ed2017-08-17 14:10:50 -07003813 rtc::Optional<size_t>* audio_index,
3814 rtc::Optional<size_t>* video_index,
3815 rtc::Optional<size_t>* data_index,
htaa2a49d92016-03-04 02:51:39 -08003816 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07003817 for (const cricket::ContentInfo& content :
3818 session_desc->description()->contents()) {
3819 if (IsAudioContent(&content)) {
3820 // If we already have an audio m= section, reject this extra one.
3821 if (*audio_index) {
3822 session_options->media_description_options.push_back(
3823 cricket::MediaDescriptionOptions(
3824 cricket::MEDIA_TYPE_AUDIO, content.name,
Steve Anton1d03a752017-11-27 14:30:09 -08003825 RtpTransceiverDirection::kInactive, true));
zhihuang1c378ed2017-08-17 14:10:50 -07003826 } else {
3827 session_options->media_description_options.push_back(
3828 cricket::MediaDescriptionOptions(
3829 cricket::MEDIA_TYPE_AUDIO, content.name, audio_direction,
Steve Anton1d03a752017-11-27 14:30:09 -08003830 audio_direction == RtpTransceiverDirection::kInactive));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003831 *audio_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07003832 }
3833 } else if (IsVideoContent(&content)) {
3834 // If we already have an video m= section, reject this extra one.
3835 if (*video_index) {
3836 session_options->media_description_options.push_back(
3837 cricket::MediaDescriptionOptions(
3838 cricket::MEDIA_TYPE_VIDEO, content.name,
Steve Anton1d03a752017-11-27 14:30:09 -08003839 RtpTransceiverDirection::kInactive, true));
zhihuang1c378ed2017-08-17 14:10:50 -07003840 } else {
3841 session_options->media_description_options.push_back(
3842 cricket::MediaDescriptionOptions(
3843 cricket::MEDIA_TYPE_VIDEO, content.name, video_direction,
Steve Anton1d03a752017-11-27 14:30:09 -08003844 video_direction == RtpTransceiverDirection::kInactive));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003845 *video_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07003846 }
3847 } else {
3848 RTC_DCHECK(IsDataContent(&content));
3849 // If we already have an data m= section, reject this extra one.
3850 if (*data_index) {
3851 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08003852 GetMediaDescriptionOptionsForRejectedData(content.name));
zhihuang1c378ed2017-08-17 14:10:50 -07003853 } else {
3854 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08003855 GetMediaDescriptionOptionsForActiveData(content.name));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003856 *data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07003857 }
3858 }
htaa2a49d92016-03-04 02:51:39 -08003859 }
deadbeefab9b2d12015-10-14 11:33:11 -07003860}
3861
Steve Antonfa2260d2017-12-28 16:38:23 -08003862cricket::MediaDescriptionOptions
3863PeerConnection::GetMediaDescriptionOptionsForActiveData(
3864 const std::string& mid) const {
3865 // Direction for data sections is meaningless, but legacy endpoints might
3866 // expect sendrecv.
3867 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
3868 RtpTransceiverDirection::kSendRecv,
3869 /*stopped=*/false);
3870 AddRtpDataChannelOptions(rtp_data_channels_, &options);
3871 return options;
3872}
3873
3874cricket::MediaDescriptionOptions
3875PeerConnection::GetMediaDescriptionOptionsForRejectedData(
3876 const std::string& mid) const {
3877 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
3878 RtpTransceiverDirection::kInactive,
3879 /*stopped=*/true);
3880 AddRtpDataChannelOptions(rtp_data_channels_, &options);
3881 return options;
3882}
3883
3884rtc::Optional<std::string> PeerConnection::GetDataMid() const {
3885 switch (data_channel_type_) {
3886 case cricket::DCT_RTP:
3887 if (!rtp_data_channel_) {
3888 return rtc::nullopt;
3889 }
3890 return rtp_data_channel_->content_name();
3891 case cricket::DCT_SCTP:
3892 return sctp_content_name_;
3893 default:
3894 return rtc::nullopt;
3895 }
3896}
3897
Steve Anton4171afb2017-11-20 10:20:22 -08003898void PeerConnection::RemoveSenders(cricket::MediaType media_type) {
3899 UpdateLocalSenders(std::vector<cricket::StreamParams>(), media_type);
3900 UpdateRemoteSendersList(std::vector<cricket::StreamParams>(), false,
deadbeefbda7e0b2015-12-08 17:13:40 -08003901 media_type, nullptr);
deadbeeffaac4972015-11-12 15:33:07 -08003902}
3903
Steve Anton4171afb2017-11-20 10:20:22 -08003904void PeerConnection::UpdateRemoteSendersList(
deadbeefab9b2d12015-10-14 11:33:11 -07003905 const cricket::StreamParamsVec& streams,
Steve Anton4171afb2017-11-20 10:20:22 -08003906 bool default_sender_needed,
deadbeefab9b2d12015-10-14 11:33:11 -07003907 cricket::MediaType media_type,
3908 StreamCollection* new_streams) {
Steve Anton4171afb2017-11-20 10:20:22 -08003909 std::vector<RtpSenderInfo>* current_senders =
3910 GetRemoteSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07003911
Steve Anton4171afb2017-11-20 10:20:22 -08003912 // Find removed senders. I.e., senders where the sender id or ssrc don't match
deadbeeffac06552015-11-25 11:26:01 -08003913 // the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08003914 for (auto sender_it = current_senders->begin();
3915 sender_it != current_senders->end();
3916 /* incremented manually */) {
3917 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07003918 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08003919 cricket::GetStreamBySsrc(streams, info.first_ssrc);
3920 bool sender_exists = params && params->id == info.sender_id;
deadbeefbda7e0b2015-12-08 17:13:40 -08003921 // If this is a default track, and we still need it, don't remove it.
Seth Hampson845e8782018-03-02 11:34:10 -08003922 if ((info.stream_id == kDefaultStreamId && default_sender_needed) ||
Steve Anton4171afb2017-11-20 10:20:22 -08003923 sender_exists) {
3924 ++sender_it;
deadbeefbda7e0b2015-12-08 17:13:40 -08003925 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08003926 OnRemoteSenderRemoved(info, media_type);
3927 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07003928 }
3929 }
3930
Steve Anton4171afb2017-11-20 10:20:22 -08003931 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07003932 for (const cricket::StreamParams& params : streams) {
Seth Hampson845e8782018-03-02 11:34:10 -08003933 // |params.id| is the sender id and the stream id uses the first of
3934 // |params.stream_ids|.
3935 // TODO(bugs.webrtc.org/7932): Add support for multiple stream ids.
3936 const std::string& stream_id =
3937 (!params.stream_ids().empty() ? params.stream_ids()[0] : "");
Steve Anton4171afb2017-11-20 10:20:22 -08003938 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07003939 uint32_t ssrc = params.first_ssrc();
3940
3941 rtc::scoped_refptr<MediaStreamInterface> stream =
Seth Hampson845e8782018-03-02 11:34:10 -08003942 remote_streams_->find(stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07003943 if (!stream) {
3944 // This is a new MediaStream. Create a new remote MediaStream.
perkjd61bf802016-03-24 03:16:19 -07003945 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
Seth Hampson845e8782018-03-02 11:34:10 -08003946 MediaStream::Create(stream_id));
deadbeefab9b2d12015-10-14 11:33:11 -07003947 remote_streams_->AddStream(stream);
3948 new_streams->AddStream(stream);
3949 }
3950
Steve Anton4171afb2017-11-20 10:20:22 -08003951 const RtpSenderInfo* sender_info =
Seth Hampson845e8782018-03-02 11:34:10 -08003952 FindSenderInfo(*current_senders, stream_id, sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08003953 if (!sender_info) {
Seth Hampson845e8782018-03-02 11:34:10 -08003954 current_senders->push_back(RtpSenderInfo(stream_id, sender_id, ssrc));
Steve Anton4171afb2017-11-20 10:20:22 -08003955 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07003956 }
3957 }
deadbeefbda7e0b2015-12-08 17:13:40 -08003958
Steve Anton4171afb2017-11-20 10:20:22 -08003959 // Add default sender if necessary.
3960 if (default_sender_needed) {
deadbeefbda7e0b2015-12-08 17:13:40 -08003961 rtc::scoped_refptr<MediaStreamInterface> default_stream =
Seth Hampson845e8782018-03-02 11:34:10 -08003962 remote_streams_->find(kDefaultStreamId);
deadbeefbda7e0b2015-12-08 17:13:40 -08003963 if (!default_stream) {
3964 // Create the new default MediaStream.
perkjd61bf802016-03-24 03:16:19 -07003965 default_stream = MediaStreamProxy::Create(
Seth Hampson845e8782018-03-02 11:34:10 -08003966 rtc::Thread::Current(), MediaStream::Create(kDefaultStreamId));
deadbeefbda7e0b2015-12-08 17:13:40 -08003967 remote_streams_->AddStream(default_stream);
3968 new_streams->AddStream(default_stream);
3969 }
Steve Anton4171afb2017-11-20 10:20:22 -08003970 std::string default_sender_id = (media_type == cricket::MEDIA_TYPE_AUDIO)
3971 ? kDefaultAudioSenderId
3972 : kDefaultVideoSenderId;
Seth Hampson845e8782018-03-02 11:34:10 -08003973 const RtpSenderInfo* default_sender_info =
3974 FindSenderInfo(*current_senders, kDefaultStreamId, default_sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08003975 if (!default_sender_info) {
3976 current_senders->push_back(
Seth Hampson845e8782018-03-02 11:34:10 -08003977 RtpSenderInfo(kDefaultStreamId, default_sender_id, 0));
Steve Anton4171afb2017-11-20 10:20:22 -08003978 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefbda7e0b2015-12-08 17:13:40 -08003979 }
3980 }
deadbeefab9b2d12015-10-14 11:33:11 -07003981}
3982
Steve Anton4171afb2017-11-20 10:20:22 -08003983void PeerConnection::OnRemoteSenderAdded(const RtpSenderInfo& sender_info,
3984 cricket::MediaType media_type) {
Seth Hampson845e8782018-03-02 11:34:10 -08003985 MediaStreamInterface* stream = remote_streams_->find(sender_info.stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07003986
3987 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 10:20:22 -08003988 CreateAudioReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07003989 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 10:20:22 -08003990 CreateVideoReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07003991 } else {
nisseeb4ca4e2017-01-12 02:24:27 -08003992 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07003993 }
3994}
3995
Steve Anton4171afb2017-11-20 10:20:22 -08003996void PeerConnection::OnRemoteSenderRemoved(const RtpSenderInfo& sender_info,
3997 cricket::MediaType media_type) {
Seth Hampson845e8782018-03-02 11:34:10 -08003998 MediaStreamInterface* stream = remote_streams_->find(sender_info.stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07003999
Henrik Boström933d8b02017-10-10 10:05:16 -07004000 rtc::scoped_refptr<RtpReceiverInterface> receiver;
deadbeefab9b2d12015-10-14 11:33:11 -07004001 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
perkjd61bf802016-03-24 03:16:19 -07004002 // When the MediaEngine audio channel is destroyed, the RemoteAudioSource
4003 // will be notified which will end the AudioRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08004004 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004005 rtc::scoped_refptr<AudioTrackInterface> audio_track =
Steve Anton4171afb2017-11-20 10:20:22 -08004006 stream->FindAudioTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004007 if (audio_track) {
deadbeefab9b2d12015-10-14 11:33:11 -07004008 stream->RemoveTrack(audio_track);
deadbeefab9b2d12015-10-14 11:33:11 -07004009 }
4010 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
perkjd61bf802016-03-24 03:16:19 -07004011 // Stopping or destroying a VideoRtpReceiver will end the
4012 // VideoRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08004013 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004014 rtc::scoped_refptr<VideoTrackInterface> video_track =
Steve Anton4171afb2017-11-20 10:20:22 -08004015 stream->FindVideoTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004016 if (video_track) {
perkjd61bf802016-03-24 03:16:19 -07004017 // There's no guarantee the track is still available, e.g. the track may
4018 // have been removed from the stream by an application.
deadbeefab9b2d12015-10-14 11:33:11 -07004019 stream->RemoveTrack(video_track);
deadbeefab9b2d12015-10-14 11:33:11 -07004020 }
4021 } else {
nisseede5da42017-01-12 05:15:36 -08004022 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07004023 }
Henrik Boström933d8b02017-10-10 10:05:16 -07004024 if (receiver) {
4025 observer_->OnRemoveTrack(receiver);
4026 }
deadbeefab9b2d12015-10-14 11:33:11 -07004027}
4028
4029void PeerConnection::UpdateEndedRemoteMediaStreams() {
4030 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams_to_remove;
4031 for (size_t i = 0; i < remote_streams_->count(); ++i) {
4032 MediaStreamInterface* stream = remote_streams_->at(i);
4033 if (stream->GetAudioTracks().empty() && stream->GetVideoTracks().empty()) {
4034 streams_to_remove.push_back(stream);
4035 }
4036 }
4037
Taylor Brandstetter98cde262016-05-31 13:02:21 -07004038 for (auto& stream : streams_to_remove) {
deadbeefab9b2d12015-10-14 11:33:11 -07004039 remote_streams_->RemoveStream(stream);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07004040 observer_->OnRemoveStream(std::move(stream));
deadbeefab9b2d12015-10-14 11:33:11 -07004041 }
4042}
4043
Steve Anton4171afb2017-11-20 10:20:22 -08004044void PeerConnection::UpdateLocalSenders(
deadbeefab9b2d12015-10-14 11:33:11 -07004045 const std::vector<cricket::StreamParams>& streams,
4046 cricket::MediaType media_type) {
Steve Anton4171afb2017-11-20 10:20:22 -08004047 std::vector<RtpSenderInfo>* current_senders = GetLocalSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004048
Seth Hampson845e8782018-03-02 11:34:10 -08004049 // Find removed tracks. I.e., tracks where the track id, stream id or ssrc
deadbeefab9b2d12015-10-14 11:33:11 -07004050 // don't match the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08004051 for (auto sender_it = current_senders->begin();
4052 sender_it != current_senders->end();
4053 /* incremented manually */) {
4054 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07004055 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08004056 cricket::GetStreamBySsrc(streams, info.first_ssrc);
4057 if (!params || params->id != info.sender_id ||
Seth Hampson845e8782018-03-02 11:34:10 -08004058 params->first_stream_id() != info.stream_id) {
Steve Anton4171afb2017-11-20 10:20:22 -08004059 OnLocalSenderRemoved(info, media_type);
4060 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07004061 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08004062 ++sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07004063 }
4064 }
4065
Steve Anton4171afb2017-11-20 10:20:22 -08004066 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07004067 for (const cricket::StreamParams& params : streams) {
4068 // The sync_label is the MediaStream label and the |stream.id| is the
Steve Anton4171afb2017-11-20 10:20:22 -08004069 // sender id.
Seth Hampson845e8782018-03-02 11:34:10 -08004070 const std::string& stream_id = params.first_stream_id();
Steve Anton4171afb2017-11-20 10:20:22 -08004071 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07004072 uint32_t ssrc = params.first_ssrc();
Steve Anton4171afb2017-11-20 10:20:22 -08004073 const RtpSenderInfo* sender_info =
Seth Hampson845e8782018-03-02 11:34:10 -08004074 FindSenderInfo(*current_senders, stream_id, sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08004075 if (!sender_info) {
Seth Hampson845e8782018-03-02 11:34:10 -08004076 current_senders->push_back(RtpSenderInfo(stream_id, sender_id, ssrc));
Steve Anton4171afb2017-11-20 10:20:22 -08004077 OnLocalSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004078 }
4079 }
4080}
4081
Steve Anton4171afb2017-11-20 10:20:22 -08004082void PeerConnection::OnLocalSenderAdded(const RtpSenderInfo& sender_info,
4083 cricket::MediaType media_type) {
4084 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08004085 if (!sender) {
Steve Anton4171afb2017-11-20 10:20:22 -08004086 RTC_LOG(LS_WARNING) << "An unknown RtpSender with id "
4087 << sender_info.sender_id
Mirko Bonadei675513b2017-11-09 11:09:25 +01004088 << " has been configured in the local description.";
deadbeefab9b2d12015-10-14 11:33:11 -07004089 return;
4090 }
4091
deadbeeffac06552015-11-25 11:26:01 -08004092 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004093 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
Jonas Olsson45cc8902018-02-13 10:37:07 +01004094 " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08004095 return;
deadbeefab9b2d12015-10-14 11:33:11 -07004096 }
deadbeeffac06552015-11-25 11:26:01 -08004097
Seth Hampson845e8782018-03-02 11:34:10 -08004098 sender->internal()->set_stream_id(sender_info.stream_id);
Steve Anton4171afb2017-11-20 10:20:22 -08004099 sender->internal()->SetSsrc(sender_info.first_ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07004100}
4101
Steve Anton4171afb2017-11-20 10:20:22 -08004102void PeerConnection::OnLocalSenderRemoved(const RtpSenderInfo& sender_info,
4103 cricket::MediaType media_type) {
4104 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08004105 if (!sender) {
4106 // This is the normal case. I.e., RemoveStream has been called and the
deadbeefab9b2d12015-10-14 11:33:11 -07004107 // SessionDescriptions has been renegotiated.
4108 return;
4109 }
deadbeeffac06552015-11-25 11:26:01 -08004110
4111 // A sender has been removed from the SessionDescription but it's still
4112 // associated with the PeerConnection. This only occurs if the SDP doesn't
4113 // match with the calls to CreateSender, AddStream and RemoveStream.
4114 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004115 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
Jonas Olsson45cc8902018-02-13 10:37:07 +01004116 " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08004117 return;
deadbeefab9b2d12015-10-14 11:33:11 -07004118 }
deadbeeffac06552015-11-25 11:26:01 -08004119
Steve Anton4171afb2017-11-20 10:20:22 -08004120 sender->internal()->SetSsrc(0);
deadbeefab9b2d12015-10-14 11:33:11 -07004121}
4122
4123void PeerConnection::UpdateLocalRtpDataChannels(
4124 const cricket::StreamParamsVec& streams) {
4125 std::vector<std::string> existing_channels;
4126
4127 // Find new and active data channels.
4128 for (const cricket::StreamParams& params : streams) {
4129 // |it->sync_label| is actually the data channel label. The reason is that
4130 // we use the same naming of data channels as we do for
4131 // MediaStreams and Tracks.
4132 // For MediaStreams, the sync_label is the MediaStream label and the
4133 // track label is the same as |streamid|.
Seth Hampson845e8782018-03-02 11:34:10 -08004134 const std::string& channel_label = params.first_stream_id();
deadbeefab9b2d12015-10-14 11:33:11 -07004135 auto data_channel_it = rtp_data_channels_.find(channel_label);
nisse7ce109a2017-01-31 00:57:56 -08004136 if (data_channel_it == rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004137 RTC_LOG(LS_ERROR) << "channel label not found";
deadbeefab9b2d12015-10-14 11:33:11 -07004138 continue;
4139 }
4140 // Set the SSRC the data channel should use for sending.
4141 data_channel_it->second->SetSendSsrc(params.first_ssrc());
4142 existing_channels.push_back(data_channel_it->first);
4143 }
4144
4145 UpdateClosingRtpDataChannels(existing_channels, true);
4146}
4147
4148void PeerConnection::UpdateRemoteRtpDataChannels(
4149 const cricket::StreamParamsVec& streams) {
4150 std::vector<std::string> existing_channels;
4151
4152 // Find new and active data channels.
4153 for (const cricket::StreamParams& params : streams) {
4154 // The data channel label is either the mslabel or the SSRC if the mslabel
4155 // does not exist. Ex a=ssrc:444330170 mslabel:test1.
Seth Hampson845e8782018-03-02 11:34:10 -08004156 std::string label = params.first_stream_id().empty()
deadbeefab9b2d12015-10-14 11:33:11 -07004157 ? rtc::ToString(params.first_ssrc())
Seth Hampson845e8782018-03-02 11:34:10 -08004158 : params.first_stream_id();
deadbeefab9b2d12015-10-14 11:33:11 -07004159 auto data_channel_it = rtp_data_channels_.find(label);
4160 if (data_channel_it == rtp_data_channels_.end()) {
4161 // This is a new data channel.
4162 CreateRemoteRtpDataChannel(label, params.first_ssrc());
4163 } else {
4164 data_channel_it->second->SetReceiveSsrc(params.first_ssrc());
4165 }
4166 existing_channels.push_back(label);
4167 }
4168
4169 UpdateClosingRtpDataChannels(existing_channels, false);
4170}
4171
4172void PeerConnection::UpdateClosingRtpDataChannels(
4173 const std::vector<std::string>& active_channels,
4174 bool is_local_update) {
4175 auto it = rtp_data_channels_.begin();
4176 while (it != rtp_data_channels_.end()) {
4177 DataChannel* data_channel = it->second;
4178 if (std::find(active_channels.begin(), active_channels.end(),
4179 data_channel->label()) != active_channels.end()) {
4180 ++it;
4181 continue;
4182 }
4183
4184 if (is_local_update) {
4185 data_channel->SetSendSsrc(0);
4186 } else {
4187 data_channel->RemotePeerRequestClose();
4188 }
4189
4190 if (data_channel->state() == DataChannel::kClosed) {
4191 rtp_data_channels_.erase(it);
4192 it = rtp_data_channels_.begin();
4193 } else {
4194 ++it;
4195 }
4196 }
4197}
4198
4199void PeerConnection::CreateRemoteRtpDataChannel(const std::string& label,
4200 uint32_t remote_ssrc) {
4201 rtc::scoped_refptr<DataChannel> channel(
4202 InternalCreateDataChannel(label, nullptr));
4203 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004204 RTC_LOG(LS_WARNING) << "Remote peer requested a DataChannel but"
Jonas Olsson45cc8902018-02-13 10:37:07 +01004205 "CreateDataChannel failed.";
deadbeefab9b2d12015-10-14 11:33:11 -07004206 return;
4207 }
4208 channel->SetReceiveSsrc(remote_ssrc);
deadbeefa601f5c2016-06-06 14:27:39 -07004209 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
4210 DataChannelProxy::Create(signaling_thread(), channel);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07004211 observer_->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07004212}
4213
4214rtc::scoped_refptr<DataChannel> PeerConnection::InternalCreateDataChannel(
4215 const std::string& label,
4216 const InternalDataChannelInit* config) {
4217 if (IsClosed()) {
4218 return nullptr;
4219 }
Steve Anton75737c02017-11-06 10:37:17 -08004220 if (data_channel_type() == cricket::DCT_NONE) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004221 RTC_LOG(LS_ERROR)
deadbeefab9b2d12015-10-14 11:33:11 -07004222 << "InternalCreateDataChannel: Data is not supported in this call.";
4223 return nullptr;
4224 }
4225 InternalDataChannelInit new_config =
4226 config ? (*config) : InternalDataChannelInit();
Steve Anton75737c02017-11-06 10:37:17 -08004227 if (data_channel_type() == cricket::DCT_SCTP) {
deadbeefab9b2d12015-10-14 11:33:11 -07004228 if (new_config.id < 0) {
4229 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08004230 if ((GetSctpSslRole(&role)) &&
deadbeefab9b2d12015-10-14 11:33:11 -07004231 !sid_allocator_.AllocateSid(role, &new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004232 RTC_LOG(LS_ERROR)
4233 << "No id can be allocated for the SCTP data channel.";
deadbeefab9b2d12015-10-14 11:33:11 -07004234 return nullptr;
4235 }
4236 } else if (!sid_allocator_.ReserveSid(new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004237 RTC_LOG(LS_ERROR) << "Failed to create a SCTP data channel "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004238 "because the id is already in use or out of range.";
deadbeefab9b2d12015-10-14 11:33:11 -07004239 return nullptr;
4240 }
4241 }
4242
Steve Anton75737c02017-11-06 10:37:17 -08004243 rtc::scoped_refptr<DataChannel> channel(
4244 DataChannel::Create(this, data_channel_type(), label, new_config));
deadbeefab9b2d12015-10-14 11:33:11 -07004245 if (!channel) {
4246 sid_allocator_.ReleaseSid(new_config.id);
4247 return nullptr;
4248 }
4249
4250 if (channel->data_channel_type() == cricket::DCT_RTP) {
4251 if (rtp_data_channels_.find(channel->label()) != rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004252 RTC_LOG(LS_ERROR) << "DataChannel with label " << channel->label()
4253 << " already exists.";
deadbeefab9b2d12015-10-14 11:33:11 -07004254 return nullptr;
4255 }
4256 rtp_data_channels_[channel->label()] = channel;
4257 } else {
4258 RTC_DCHECK(channel->data_channel_type() == cricket::DCT_SCTP);
4259 sctp_data_channels_.push_back(channel);
4260 channel->SignalClosed.connect(this,
4261 &PeerConnection::OnSctpDataChannelClosed);
4262 }
4263
Steve Anton2d8609c2018-01-23 16:38:46 -08004264 SignalDataChannelCreated_(channel.get());
deadbeefab9b2d12015-10-14 11:33:11 -07004265 return channel;
4266}
4267
4268bool PeerConnection::HasDataChannels() const {
4269 return !rtp_data_channels_.empty() || !sctp_data_channels_.empty();
4270}
4271
4272void PeerConnection::AllocateSctpSids(rtc::SSLRole role) {
4273 for (const auto& channel : sctp_data_channels_) {
4274 if (channel->id() < 0) {
4275 int sid;
4276 if (!sid_allocator_.AllocateSid(role, &sid)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004277 RTC_LOG(LS_ERROR) << "Failed to allocate SCTP sid.";
deadbeefab9b2d12015-10-14 11:33:11 -07004278 continue;
4279 }
4280 channel->SetSctpSid(sid);
4281 }
4282 }
4283}
4284
4285void PeerConnection::OnSctpDataChannelClosed(DataChannel* channel) {
deadbeefbd292462015-12-14 18:15:29 -08004286 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeefab9b2d12015-10-14 11:33:11 -07004287 for (auto it = sctp_data_channels_.begin(); it != sctp_data_channels_.end();
4288 ++it) {
4289 if (it->get() == channel) {
4290 if (channel->id() >= 0) {
4291 sid_allocator_.ReleaseSid(channel->id());
4292 }
deadbeefbd292462015-12-14 18:15:29 -08004293 // Since this method is triggered by a signal from the DataChannel,
4294 // we can't free it directly here; we need to free it asynchronously.
4295 sctp_data_channels_to_free_.push_back(*it);
deadbeefab9b2d12015-10-14 11:33:11 -07004296 sctp_data_channels_.erase(it);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07004297 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_FREE_DATACHANNELS,
4298 nullptr);
deadbeefab9b2d12015-10-14 11:33:11 -07004299 return;
4300 }
4301 }
4302}
4303
deadbeefab9b2d12015-10-14 11:33:11 -07004304void PeerConnection::OnDataChannelDestroyed() {
4305 // Use a temporary copy of the RTP/SCTP DataChannel list because the
4306 // DataChannel may callback to us and try to modify the list.
4307 std::map<std::string, rtc::scoped_refptr<DataChannel>> temp_rtp_dcs;
4308 temp_rtp_dcs.swap(rtp_data_channels_);
4309 for (const auto& kv : temp_rtp_dcs) {
4310 kv.second->OnTransportChannelDestroyed();
4311 }
4312
4313 std::vector<rtc::scoped_refptr<DataChannel>> temp_sctp_dcs;
4314 temp_sctp_dcs.swap(sctp_data_channels_);
4315 for (const auto& channel : temp_sctp_dcs) {
4316 channel->OnTransportChannelDestroyed();
4317 }
4318}
4319
4320void PeerConnection::OnDataChannelOpenMessage(
4321 const std::string& label,
4322 const InternalDataChannelInit& config) {
4323 rtc::scoped_refptr<DataChannel> channel(
4324 InternalCreateDataChannel(label, &config));
4325 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004326 RTC_LOG(LS_ERROR) << "Failed to create DataChannel from the OPEN message.";
deadbeefab9b2d12015-10-14 11:33:11 -07004327 return;
4328 }
4329
deadbeefa601f5c2016-06-06 14:27:39 -07004330 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
4331 DataChannelProxy::Create(signaling_thread(), channel);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07004332 observer_->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07004333}
4334
Steve Anton4171afb2017-11-20 10:20:22 -08004335rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
4336PeerConnection::GetAudioTransceiver() const {
4337 // This method only works with Plan B SDP, where there is a single
4338 // audio/video transceiver.
4339 RTC_DCHECK(!IsUnifiedPlan());
4340 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08004341 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004342 return transceiver;
4343 }
4344 }
4345 RTC_NOTREACHED();
4346 return nullptr;
4347}
4348
4349rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
4350PeerConnection::GetVideoTransceiver() const {
4351 // This method only works with Plan B SDP, where there is a single
4352 // audio/video transceiver.
4353 RTC_DCHECK(!IsUnifiedPlan());
4354 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08004355 if (transceiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004356 return transceiver;
4357 }
4358 }
4359 RTC_NOTREACHED();
4360 return nullptr;
4361}
4362
4363// TODO(bugs.webrtc.org/7600): Remove this when multiple transceivers with
4364// individual transceiver directions are supported.
zhihuang1c378ed2017-08-17 14:10:50 -07004365bool PeerConnection::HasRtpSender(cricket::MediaType type) const {
Steve Anton4171afb2017-11-20 10:20:22 -08004366 switch (type) {
4367 case cricket::MEDIA_TYPE_AUDIO:
4368 return !GetAudioTransceiver()->internal()->senders().empty();
4369 case cricket::MEDIA_TYPE_VIDEO:
4370 return !GetVideoTransceiver()->internal()->senders().empty();
4371 case cricket::MEDIA_TYPE_DATA:
4372 return false;
4373 }
4374 RTC_NOTREACHED();
4375 return false;
zhihuang1c378ed2017-08-17 14:10:50 -07004376}
4377
Steve Anton4171afb2017-11-20 10:20:22 -08004378rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
4379PeerConnection::FindSenderForTrack(MediaStreamTrackInterface* track) const {
4380 for (auto transceiver : transceivers_) {
4381 for (auto sender : transceiver->internal()->senders()) {
4382 if (sender->track() == track) {
4383 return sender;
4384 }
4385 }
4386 }
4387 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08004388}
4389
Steve Anton4171afb2017-11-20 10:20:22 -08004390rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
4391PeerConnection::FindSenderById(const std::string& sender_id) const {
4392 for (auto transceiver : transceivers_) {
4393 for (auto sender : transceiver->internal()->senders()) {
4394 if (sender->id() == sender_id) {
4395 return sender;
4396 }
4397 }
4398 }
4399 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07004400}
4401
Steve Anton4171afb2017-11-20 10:20:22 -08004402rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
4403PeerConnection::FindReceiverById(const std::string& receiver_id) const {
4404 for (auto transceiver : transceivers_) {
4405 for (auto receiver : transceiver->internal()->receivers()) {
4406 if (receiver->id() == receiver_id) {
4407 return receiver;
4408 }
4409 }
4410 }
4411 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07004412}
4413
Steve Anton4171afb2017-11-20 10:20:22 -08004414std::vector<PeerConnection::RtpSenderInfo>*
4415PeerConnection::GetRemoteSenderInfos(cricket::MediaType media_type) {
4416 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
4417 media_type == cricket::MEDIA_TYPE_VIDEO);
4418 return (media_type == cricket::MEDIA_TYPE_AUDIO)
4419 ? &remote_audio_sender_infos_
4420 : &remote_video_sender_infos_;
4421}
4422
4423std::vector<PeerConnection::RtpSenderInfo>* PeerConnection::GetLocalSenderInfos(
deadbeefab9b2d12015-10-14 11:33:11 -07004424 cricket::MediaType media_type) {
4425 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
4426 media_type == cricket::MEDIA_TYPE_VIDEO);
Steve Anton4171afb2017-11-20 10:20:22 -08004427 return (media_type == cricket::MEDIA_TYPE_AUDIO) ? &local_audio_sender_infos_
4428 : &local_video_sender_infos_;
deadbeefab9b2d12015-10-14 11:33:11 -07004429}
4430
Steve Anton4171afb2017-11-20 10:20:22 -08004431const PeerConnection::RtpSenderInfo* PeerConnection::FindSenderInfo(
4432 const std::vector<PeerConnection::RtpSenderInfo>& infos,
Seth Hampson845e8782018-03-02 11:34:10 -08004433 const std::string& stream_id,
Steve Anton4171afb2017-11-20 10:20:22 -08004434 const std::string sender_id) const {
4435 for (const RtpSenderInfo& sender_info : infos) {
Seth Hampson845e8782018-03-02 11:34:10 -08004436 if (sender_info.stream_id == stream_id &&
Steve Anton4171afb2017-11-20 10:20:22 -08004437 sender_info.sender_id == sender_id) {
4438 return &sender_info;
deadbeefab9b2d12015-10-14 11:33:11 -07004439 }
4440 }
4441 return nullptr;
4442}
4443
4444DataChannel* PeerConnection::FindDataChannelBySid(int sid) const {
4445 for (const auto& channel : sctp_data_channels_) {
4446 if (channel->id() == sid) {
4447 return channel;
4448 }
4449 }
4450 return nullptr;
4451}
4452
deadbeef91dd5672016-05-18 16:55:30 -07004453bool PeerConnection::InitializePortAllocator_n(
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004454 const RTCConfiguration& configuration) {
4455 cricket::ServerAddresses stun_servers;
4456 std::vector<cricket::RelayServerConfig> turn_servers;
deadbeef293e9262017-01-11 12:28:30 -08004457 if (ParseIceServers(configuration.servers, &stun_servers, &turn_servers) !=
4458 RTCErrorType::NONE) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004459 return false;
4460 }
4461
Taylor Brandstetterf8e65772016-06-27 17:20:15 -07004462 port_allocator_->Initialize();
4463
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004464 // To handle both internal and externally created port allocator, we will
4465 // enable BUNDLE here.
4466 int portallocator_flags = port_allocator_->flags();
4467 portallocator_flags |= cricket::PORTALLOCATOR_ENABLE_SHARED_SOCKET |
zhihuangb09b3f92017-03-07 14:40:51 -08004468 cricket::PORTALLOCATOR_ENABLE_IPV6 |
4469 cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI;
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004470 // If the disable-IPv6 flag was specified, we'll not override it
4471 // by experiment.
4472 if (configuration.disable_ipv6) {
4473 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
sprangc1b57a12017-02-28 08:50:47 -08004474 } else if (webrtc::field_trial::FindFullName("WebRTC-IPv6Default")
4475 .find("Disabled") == 0) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004476 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
4477 }
4478
zhihuangb09b3f92017-03-07 14:40:51 -08004479 if (configuration.disable_ipv6_on_wifi) {
4480 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI);
Mirko Bonadei675513b2017-11-09 11:09:25 +01004481 RTC_LOG(LS_INFO) << "IPv6 candidates on Wi-Fi are disabled.";
zhihuangb09b3f92017-03-07 14:40:51 -08004482 }
4483
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004484 if (configuration.tcp_candidate_policy == kTcpCandidatePolicyDisabled) {
4485 portallocator_flags |= cricket::PORTALLOCATOR_DISABLE_TCP;
Mirko Bonadei675513b2017-11-09 11:09:25 +01004486 RTC_LOG(LS_INFO) << "TCP candidates are disabled.";
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004487 }
4488
honghaiz60347052016-05-31 18:29:12 -07004489 if (configuration.candidate_network_policy ==
4490 kCandidateNetworkPolicyLowCost) {
4491 portallocator_flags |= cricket::PORTALLOCATOR_DISABLE_COSTLY_NETWORKS;
Mirko Bonadei675513b2017-11-09 11:09:25 +01004492 RTC_LOG(LS_INFO) << "Do not gather candidates on high-cost networks";
honghaiz60347052016-05-31 18:29:12 -07004493 }
4494
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +01004495 if (configuration.disable_link_local_networks) {
4496 portallocator_flags |= cricket::PORTALLOCATOR_DISABLE_LINK_LOCAL_NETWORKS;
4497 RTC_LOG(LS_INFO) << "Disable candidates on link-local network interfaces.";
4498 }
4499
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004500 port_allocator_->set_flags(portallocator_flags);
4501 // No step delay is used while allocating ports.
4502 port_allocator_->set_step_delay(cricket::kMinimumStepDelay);
4503 port_allocator_->set_candidate_filter(
4504 ConvertIceTransportTypeToCandidateFilter(configuration.type));
deadbeefd21eab32017-07-26 16:50:11 -07004505 port_allocator_->set_max_ipv6_networks(configuration.max_ipv6_networks);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004506
4507 // Call this last since it may create pooled allocator sessions using the
4508 // properties set above.
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08004509 port_allocator_->SetConfiguration(
4510 stun_servers, turn_servers, configuration.ice_candidate_pool_size,
4511 configuration.prune_turn_ports, configuration.turn_customizer,
4512 configuration.stun_candidate_keepalive_interval);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004513 return true;
4514}
4515
deadbeef91dd5672016-05-18 16:55:30 -07004516bool PeerConnection::ReconfigurePortAllocator_n(
deadbeef293e9262017-01-11 12:28:30 -08004517 const cricket::ServerAddresses& stun_servers,
4518 const std::vector<cricket::RelayServerConfig>& turn_servers,
4519 IceTransportsType type,
4520 int candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02004521 bool prune_turn_ports,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08004522 webrtc::TurnCustomizer* turn_customizer,
4523 rtc::Optional<int> stun_candidate_keepalive_interval) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004524 port_allocator_->set_candidate_filter(
deadbeef293e9262017-01-11 12:28:30 -08004525 ConvertIceTransportTypeToCandidateFilter(type));
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004526 // Call this last since it may create pooled allocator sessions using the
4527 // candidate filter set above.
deadbeef6de92f92016-12-12 18:49:32 -08004528 return port_allocator_->SetConfiguration(
Jonas Orelandbdcee282017-10-10 14:01:40 +02004529 stun_servers, turn_servers, candidate_pool_size, prune_turn_ports,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08004530 turn_customizer, stun_candidate_keepalive_interval);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004531}
4532
Steve Antonba818672017-11-06 10:21:57 -08004533cricket::ChannelManager* PeerConnection::channel_manager() const {
4534 return factory_->channel_manager();
4535}
4536
4537MetricsObserverInterface* PeerConnection::metrics_observer() const {
4538 return uma_observer_;
4539}
4540
Elad Alon99c3fe52017-10-13 16:29:40 +02004541bool PeerConnection::StartRtcEventLog_w(
Bjorn Tereliusde939432017-11-20 17:38:14 +01004542 std::unique_ptr<RtcEventLogOutput> output,
4543 int64_t output_period_ms) {
zhihuang77985012017-02-07 15:45:16 -08004544 if (!event_log_) {
4545 return false;
4546 }
Bjorn Tereliusde939432017-11-20 17:38:14 +01004547 return event_log_->StartLogging(std::move(output), output_period_ms);
ivoc14d5dbe2016-07-04 07:06:55 -07004548}
4549
4550void PeerConnection::StopRtcEventLog_w() {
zhihuang77985012017-02-07 15:45:16 -08004551 if (event_log_) {
4552 event_log_->StopLogging();
4553 }
ivoc14d5dbe2016-07-04 07:06:55 -07004554}
nisseeaabdf62017-05-05 02:23:02 -07004555
Steve Anton75737c02017-11-06 10:37:17 -08004556cricket::BaseChannel* PeerConnection::GetChannel(
4557 const std::string& content_name) {
Steve Antondcc3c022017-12-22 16:02:54 -08004558 for (auto transceiver : transceivers_) {
4559 cricket::BaseChannel* channel = transceiver->internal()->channel();
4560 if (channel && channel->content_name() == content_name) {
4561 return channel;
4562 }
Steve Anton75737c02017-11-06 10:37:17 -08004563 }
4564 if (rtp_data_channel() &&
4565 rtp_data_channel()->content_name() == content_name) {
4566 return rtp_data_channel();
4567 }
4568 return nullptr;
4569}
4570
4571bool PeerConnection::GetSctpSslRole(rtc::SSLRole* role) {
4572 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004573 RTC_LOG(LS_INFO)
4574 << "Local and Remote descriptions must be applied to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004575 "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08004576 return false;
4577 }
4578 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004579 RTC_LOG(LS_INFO) << "Non-rejected SCTP m= section is needed to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004580 "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08004581 return false;
4582 }
4583
4584 return transport_controller_->GetSslRole(*sctp_transport_name_, role);
4585}
4586
4587bool PeerConnection::GetSslRole(const std::string& content_name,
4588 rtc::SSLRole* role) {
4589 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004590 RTC_LOG(LS_INFO)
4591 << "Local and Remote descriptions must be applied to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004592 "SSL Role of the session.";
Steve Anton75737c02017-11-06 10:37:17 -08004593 return false;
4594 }
4595
4596 return transport_controller_->GetSslRole(GetTransportName(content_name),
4597 role);
4598}
4599
Steve Antonf8470812017-12-04 10:46:21 -08004600void PeerConnection::SetSessionError(SessionError error,
4601 const std::string& error_desc) {
4602 RTC_DCHECK_RUN_ON(signaling_thread());
4603 if (error != session_error_) {
4604 session_error_ = error;
4605 session_error_desc_ = error_desc;
Steve Anton75737c02017-11-06 10:37:17 -08004606 }
4607}
4608
Steve Anton3828c062017-12-06 10:34:51 -08004609RTCError PeerConnection::UpdateSessionState(SdpType type,
Steve Anton8a006912017-12-04 15:25:56 -08004610 cricket::ContentSource source) {
4611 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08004612
4613 // If there's already a pending error then no state transition should happen.
4614 // But all call-sites should be verifying this before calling us!
Steve Antonf8470812017-12-04 10:46:21 -08004615 RTC_DCHECK(session_error() == SessionError::kNone);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004616
4617 // If this is an answer then we know whether to BUNDLE or not. If both the
4618 // local and remote side have agreed to BUNDLE, go ahead and enable it.
Steve Anton3828c062017-12-06 10:34:51 -08004619 if (type == SdpType::kAnswer) {
Steve Anton75737c02017-11-06 10:37:17 -08004620 const cricket::ContentGroup* local_bundle =
4621 local_description()->description()->GetGroupByName(
4622 cricket::GROUP_TYPE_BUNDLE);
4623 const cricket::ContentGroup* remote_bundle =
4624 remote_description()->description()->GetGroupByName(
4625 cricket::GROUP_TYPE_BUNDLE);
4626 if (local_bundle && remote_bundle) {
4627 // The answerer decides the transport to bundle on.
4628 const cricket::ContentGroup* answer_bundle =
4629 (source == cricket::CS_LOCAL ? local_bundle : remote_bundle);
4630 if (!EnableBundle(*answer_bundle)) {
Steve Anton8a006912017-12-04 15:25:56 -08004631 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
4632 kEnableBundleFailed);
Steve Anton75737c02017-11-06 10:37:17 -08004633 }
4634 }
Steve Anton75737c02017-11-06 10:37:17 -08004635 }
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004636
4637 // Only push down the transport description after potentially enabling BUNDLE;
4638 // we don't want to push down a description on a transport about to be
4639 // destroyed.
Steve Anton3828c062017-12-06 10:34:51 -08004640 RTCError error = PushdownTransportDescription(source, type);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004641 if (!error.ok()) {
4642 return error;
4643 }
4644
4645 // If this is answer-ish we're ready to let media flow.
Steve Anton3828c062017-12-06 10:34:51 -08004646 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Antoned10bd92017-12-05 10:52:59 -08004647 EnableSending();
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004648 }
4649
4650 // Update the signaling state according to the specified state machine (see
4651 // https://w3c.github.io/webrtc-pc/#rtcsignalingstate-enum).
Steve Anton3828c062017-12-06 10:34:51 -08004652 if (type == SdpType::kOffer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004653 ChangeSignalingState(source == cricket::CS_LOCAL
4654 ? PeerConnectionInterface::kHaveLocalOffer
4655 : PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton3828c062017-12-06 10:34:51 -08004656 } else if (type == SdpType::kPrAnswer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004657 ChangeSignalingState(source == cricket::CS_LOCAL
4658 ? PeerConnectionInterface::kHaveLocalPrAnswer
4659 : PeerConnectionInterface::kHaveRemotePrAnswer);
4660 } else {
Steve Anton3828c062017-12-06 10:34:51 -08004661 RTC_DCHECK(type == SdpType::kAnswer);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004662 ChangeSignalingState(PeerConnectionInterface::kStable);
4663 }
4664
4665 // Update internal objects according to the session description's media
4666 // descriptions.
Steve Anton3828c062017-12-06 10:34:51 -08004667 error = PushdownMediaDescription(type, source);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004668 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08004669 return error;
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004670 }
4671
Steve Anton8a006912017-12-04 15:25:56 -08004672 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08004673}
4674
Steve Anton8a006912017-12-04 15:25:56 -08004675RTCError PeerConnection::PushdownMediaDescription(
Steve Anton3828c062017-12-06 10:34:51 -08004676 SdpType type,
Steve Anton8a006912017-12-04 15:25:56 -08004677 cricket::ContentSource source) {
Steve Antoned10bd92017-12-05 10:52:59 -08004678 const SessionDescriptionInterface* sdesc =
4679 (source == cricket::CS_LOCAL ? local_description()
4680 : remote_description());
Steve Anton75737c02017-11-06 10:37:17 -08004681 RTC_DCHECK(sdesc);
Steve Antoned10bd92017-12-05 10:52:59 -08004682
4683 // Push down the new SDP media section for each audio/video transceiver.
4684 for (auto transceiver : transceivers_) {
Steve Anton75737c02017-11-06 10:37:17 -08004685 const ContentInfo* content_info =
Steve Antoned10bd92017-12-05 10:52:59 -08004686 FindMediaSectionForTransceiver(transceiver, sdesc);
4687 cricket::BaseChannel* channel = transceiver->internal()->channel();
4688 if (!channel || !content_info || content_info->rejected) {
Steve Anton75737c02017-11-06 10:37:17 -08004689 continue;
4690 }
4691 const MediaContentDescription* content_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08004692 content_info->media_description();
Steve Antoned10bd92017-12-05 10:52:59 -08004693 if (!content_desc) {
4694 continue;
4695 }
4696 std::string error;
4697 bool success =
4698 (source == cricket::CS_LOCAL)
Steve Anton3828c062017-12-06 10:34:51 -08004699 ? channel->SetLocalContent(content_desc, type, &error)
4700 : channel->SetRemoteContent(content_desc, type, &error);
Steve Antoned10bd92017-12-05 10:52:59 -08004701 if (!success) {
4702 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, std::move(error));
4703 }
4704 }
4705
4706 // If using the RtpDataChannel, push down the new SDP section for it too.
4707 if (rtp_data_channel_) {
4708 const ContentInfo* data_content =
4709 cricket::GetFirstDataContent(sdesc->description());
4710 if (data_content && !data_content->rejected) {
4711 const MediaContentDescription* data_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08004712 data_content->media_description();
Steve Antoned10bd92017-12-05 10:52:59 -08004713 if (data_desc) {
4714 std::string error;
4715 bool success =
4716 (source == cricket::CS_LOCAL)
Steve Anton3828c062017-12-06 10:34:51 -08004717 ? rtp_data_channel_->SetLocalContent(data_desc, type, &error)
4718 : rtp_data_channel_->SetRemoteContent(data_desc, type,
Steve Antoned10bd92017-12-05 10:52:59 -08004719 &error);
4720 if (!success) {
4721 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
4722 std::move(error));
4723 }
Steve Anton75737c02017-11-06 10:37:17 -08004724 }
4725 }
4726 }
Steve Antoned10bd92017-12-05 10:52:59 -08004727
Steve Anton75737c02017-11-06 10:37:17 -08004728 // Need complete offer/answer with an SCTP m= section before starting SCTP,
4729 // according to https://tools.ietf.org/html/draft-ietf-mmusic-sctp-sdp-19
4730 if (sctp_transport_ && local_description() && remote_description() &&
4731 cricket::GetFirstDataContent(local_description()->description()) &&
4732 cricket::GetFirstDataContent(remote_description()->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08004733 bool success = network_thread()->Invoke<bool>(
Steve Anton75737c02017-11-06 10:37:17 -08004734 RTC_FROM_HERE,
4735 rtc::Bind(&PeerConnection::PushdownSctpParameters_n, this, source));
Steve Anton8a006912017-12-04 15:25:56 -08004736 if (!success) {
4737 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
4738 "Failed to push down SCTP parameters.");
4739 }
Steve Anton75737c02017-11-06 10:37:17 -08004740 }
Steve Antoned10bd92017-12-05 10:52:59 -08004741
Steve Anton8a006912017-12-04 15:25:56 -08004742 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08004743}
4744
4745bool PeerConnection::PushdownSctpParameters_n(cricket::ContentSource source) {
4746 RTC_DCHECK(network_thread()->IsCurrent());
4747 RTC_DCHECK(local_description());
4748 RTC_DCHECK(remote_description());
4749 // Apply the SCTP port (which is hidden inside a DataCodec structure...)
4750 // When we support "max-message-size", that would also be pushed down here.
4751 return sctp_transport_->Start(
4752 GetSctpPort(local_description()->description()),
4753 GetSctpPort(remote_description()->description()));
4754}
4755
Steve Anton8a006912017-12-04 15:25:56 -08004756RTCError PeerConnection::PushdownTransportDescription(
4757 cricket::ContentSource source,
Steve Anton3828c062017-12-06 10:34:51 -08004758 SdpType type) {
Steve Anton8a006912017-12-04 15:25:56 -08004759 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08004760
Steve Anton8a006912017-12-04 15:25:56 -08004761 const SessionDescriptionInterface* sdesc =
4762 (source == cricket::CS_LOCAL ? local_description()
4763 : remote_description());
4764 RTC_DCHECK(sdesc);
4765 for (const cricket::TransportInfo& tinfo :
4766 sdesc->description()->transport_infos()) {
4767 std::string error;
4768 bool success;
4769 if (source == cricket::CS_LOCAL) {
4770 success = transport_controller_->SetLocalTransportDescription(
Steve Anton3828c062017-12-06 10:34:51 -08004771 tinfo.content_name, tinfo.description, type, &error);
Steve Anton8a006912017-12-04 15:25:56 -08004772 } else {
4773 success = transport_controller_->SetRemoteTransportDescription(
Steve Anton3828c062017-12-06 10:34:51 -08004774 tinfo.content_name, tinfo.description, type, &error);
Steve Anton8a006912017-12-04 15:25:56 -08004775 }
4776 if (!success) {
Steve Antondcc3c022017-12-22 16:02:54 -08004777 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
4778 "Failed to push down transport description for " +
4779 tinfo.content_name + ": " + error);
Steve Anton75737c02017-11-06 10:37:17 -08004780 }
4781 }
4782
Steve Anton8a006912017-12-04 15:25:56 -08004783 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08004784}
4785
4786bool PeerConnection::GetTransportDescription(
4787 const SessionDescription* description,
4788 const std::string& content_name,
4789 cricket::TransportDescription* tdesc) {
4790 if (!description || !tdesc) {
4791 return false;
4792 }
4793 const TransportInfo* transport_info =
4794 description->GetTransportInfoByName(content_name);
4795 if (!transport_info) {
4796 return false;
4797 }
4798 *tdesc = transport_info->description;
4799 return true;
4800}
4801
4802bool PeerConnection::EnableBundle(const cricket::ContentGroup& bundle) {
4803 const std::string* first_content_name = bundle.FirstContentName();
4804 if (!first_content_name) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004805 RTC_LOG(LS_WARNING) << "Tried to BUNDLE with no contents.";
Steve Anton75737c02017-11-06 10:37:17 -08004806 return false;
4807 }
4808 const std::string& transport_name = *first_content_name;
4809
4810 auto maybe_set_transport = [this, bundle,
4811 transport_name](cricket::BaseChannel* ch) {
4812 if (!ch || !bundle.HasContentName(ch->content_name())) {
Steve Antoned10bd92017-12-05 10:52:59 -08004813 return;
Steve Anton75737c02017-11-06 10:37:17 -08004814 }
4815
4816 std::string old_transport_name = ch->transport_name();
4817 if (old_transport_name == transport_name) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004818 RTC_LOG(LS_INFO) << "BUNDLE already enabled for " << ch->content_name()
4819 << " on " << transport_name << ".";
Steve Antoned10bd92017-12-05 10:52:59 -08004820 return;
Steve Anton75737c02017-11-06 10:37:17 -08004821 }
4822
4823 cricket::DtlsTransportInternal* rtp_dtls_transport =
4824 transport_controller_->CreateDtlsTransport(
4825 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4826 bool need_rtcp = (ch->rtcp_dtls_transport() != nullptr);
4827 cricket::DtlsTransportInternal* rtcp_dtls_transport = nullptr;
4828 if (need_rtcp) {
4829 rtcp_dtls_transport = transport_controller_->CreateDtlsTransport(
4830 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
4831 }
4832
4833 ch->SetTransports(rtp_dtls_transport, rtcp_dtls_transport);
Mirko Bonadei675513b2017-11-09 11:09:25 +01004834 RTC_LOG(LS_INFO) << "Enabled BUNDLE for " << ch->content_name() << " on "
4835 << transport_name << ".";
Steve Anton75737c02017-11-06 10:37:17 -08004836 transport_controller_->DestroyDtlsTransport(
4837 old_transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4838 // If the channel needs rtcp, it means that the channel used to have a
4839 // rtcp transport which needs to be deleted now.
4840 if (need_rtcp) {
4841 transport_controller_->DestroyDtlsTransport(
4842 old_transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
4843 }
Steve Anton75737c02017-11-06 10:37:17 -08004844 };
4845
Steve Antoned10bd92017-12-05 10:52:59 -08004846 for (auto transceiver : transceivers_) {
4847 maybe_set_transport(transceiver->internal()->channel());
Steve Anton75737c02017-11-06 10:37:17 -08004848 }
Steve Antoned10bd92017-12-05 10:52:59 -08004849 maybe_set_transport(rtp_data_channel_);
4850
Steve Anton75737c02017-11-06 10:37:17 -08004851 // For SCTP, transport creation/deletion happens here instead of in the
4852 // object itself.
4853 if (sctp_transport_) {
4854 RTC_DCHECK(sctp_transport_name_);
4855 RTC_DCHECK(sctp_content_name_);
4856 if (transport_name != *sctp_transport_name_ &&
4857 bundle.HasContentName(*sctp_content_name_)) {
4858 network_thread()->Invoke<void>(
4859 RTC_FROM_HERE, rtc::Bind(&PeerConnection::ChangeSctpTransport_n, this,
4860 transport_name));
4861 }
4862 }
4863
4864 return true;
4865}
4866
Steve Anton75737c02017-11-06 10:37:17 -08004867cricket::IceConfig PeerConnection::ParseIceConfig(
4868 const PeerConnectionInterface::RTCConfiguration& config) const {
4869 cricket::ContinualGatheringPolicy gathering_policy;
4870 // TODO(honghaiz): Add the third continual gathering policy in
4871 // PeerConnectionInterface and map it to GATHER_CONTINUALLY_AND_RECOVER.
4872 switch (config.continual_gathering_policy) {
4873 case PeerConnectionInterface::GATHER_ONCE:
4874 gathering_policy = cricket::GATHER_ONCE;
4875 break;
4876 case PeerConnectionInterface::GATHER_CONTINUALLY:
4877 gathering_policy = cricket::GATHER_CONTINUALLY;
4878 break;
4879 default:
4880 RTC_NOTREACHED();
4881 gathering_policy = cricket::GATHER_ONCE;
4882 }
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08004883
Steve Anton75737c02017-11-06 10:37:17 -08004884 cricket::IceConfig ice_config;
4885 ice_config.receiving_timeout = config.ice_connection_receiving_timeout;
4886 ice_config.prioritize_most_likely_candidate_pairs =
4887 config.prioritize_most_likely_ice_candidate_pairs;
4888 ice_config.backup_connection_ping_interval =
4889 config.ice_backup_candidate_pair_ping_interval;
4890 ice_config.continual_gathering_policy = gathering_policy;
4891 ice_config.presume_writable_when_fully_relayed =
4892 config.presume_writable_when_fully_relayed;
Qingsi Wange6826d22018-03-08 14:55:14 -08004893 ice_config.ice_check_interval_strong_connectivity =
4894 config.ice_check_interval_strong_connectivity;
4895 ice_config.ice_check_interval_weak_connectivity =
4896 config.ice_check_interval_weak_connectivity;
Steve Anton75737c02017-11-06 10:37:17 -08004897 ice_config.ice_check_min_interval = config.ice_check_min_interval;
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08004898 ice_config.stun_keepalive_interval = config.stun_candidate_keepalive_interval;
Steve Anton75737c02017-11-06 10:37:17 -08004899 ice_config.regather_all_networks_interval_range =
4900 config.ice_regather_interval_range;
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08004901 ice_config.network_preference = config.network_preference;
Steve Anton75737c02017-11-06 10:37:17 -08004902 return ice_config;
4903}
4904
Steve Anton75737c02017-11-06 10:37:17 -08004905bool PeerConnection::GetLocalTrackIdBySsrc(uint32_t ssrc,
4906 std::string* track_id) {
4907 if (!local_description()) {
4908 return false;
4909 }
4910 return webrtc::GetTrackIdBySsrc(local_description()->description(), ssrc,
4911 track_id);
4912}
4913
4914bool PeerConnection::GetRemoteTrackIdBySsrc(uint32_t ssrc,
4915 std::string* track_id) {
4916 if (!remote_description()) {
4917 return false;
4918 }
4919 return webrtc::GetTrackIdBySsrc(remote_description()->description(), ssrc,
4920 track_id);
4921}
4922
4923bool PeerConnection::SendData(const cricket::SendDataParams& params,
4924 const rtc::CopyOnWriteBuffer& payload,
4925 cricket::SendDataResult* result) {
4926 if (!rtp_data_channel_ && !sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004927 RTC_LOG(LS_ERROR) << "SendData called when rtp_data_channel_ "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004928 "and sctp_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08004929 return false;
4930 }
4931 return rtp_data_channel_
4932 ? rtp_data_channel_->SendData(params, payload, result)
4933 : network_thread()->Invoke<bool>(
4934 RTC_FROM_HERE,
4935 Bind(&cricket::SctpTransportInternal::SendData,
4936 sctp_transport_.get(), params, payload, result));
4937}
4938
4939bool PeerConnection::ConnectDataChannel(DataChannel* webrtc_data_channel) {
4940 if (!rtp_data_channel_ && !sctp_transport_) {
4941 // Don't log an error here, because DataChannels are expected to call
4942 // ConnectDataChannel in this state. It's the only way to initially tell
4943 // whether or not the underlying transport is ready.
4944 return false;
4945 }
4946 if (rtp_data_channel_) {
4947 rtp_data_channel_->SignalReadyToSendData.connect(
4948 webrtc_data_channel, &DataChannel::OnChannelReady);
4949 rtp_data_channel_->SignalDataReceived.connect(webrtc_data_channel,
4950 &DataChannel::OnDataReceived);
4951 } else {
4952 SignalSctpReadyToSendData.connect(webrtc_data_channel,
4953 &DataChannel::OnChannelReady);
4954 SignalSctpDataReceived.connect(webrtc_data_channel,
4955 &DataChannel::OnDataReceived);
4956 SignalSctpStreamClosedRemotely.connect(
4957 webrtc_data_channel, &DataChannel::OnStreamClosedRemotely);
4958 }
4959 return true;
4960}
4961
4962void PeerConnection::DisconnectDataChannel(DataChannel* webrtc_data_channel) {
4963 if (!rtp_data_channel_ && !sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004964 RTC_LOG(LS_ERROR)
4965 << "DisconnectDataChannel called when rtp_data_channel_ and "
4966 "sctp_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08004967 return;
4968 }
4969 if (rtp_data_channel_) {
4970 rtp_data_channel_->SignalReadyToSendData.disconnect(webrtc_data_channel);
4971 rtp_data_channel_->SignalDataReceived.disconnect(webrtc_data_channel);
4972 } else {
4973 SignalSctpReadyToSendData.disconnect(webrtc_data_channel);
4974 SignalSctpDataReceived.disconnect(webrtc_data_channel);
4975 SignalSctpStreamClosedRemotely.disconnect(webrtc_data_channel);
4976 }
4977}
4978
4979void PeerConnection::AddSctpDataStream(int sid) {
4980 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004981 RTC_LOG(LS_ERROR)
4982 << "AddSctpDataStream called when sctp_transport_ is NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08004983 return;
4984 }
4985 network_thread()->Invoke<void>(
4986 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::OpenStream,
4987 sctp_transport_.get(), sid));
4988}
4989
4990void PeerConnection::RemoveSctpDataStream(int sid) {
4991 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004992 RTC_LOG(LS_ERROR) << "RemoveSctpDataStream called when sctp_transport_ is "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004993 "NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08004994 return;
4995 }
4996 network_thread()->Invoke<void>(
4997 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::ResetStream,
4998 sctp_transport_.get(), sid));
4999}
5000
5001bool PeerConnection::ReadyToSendData() const {
5002 return (rtp_data_channel_ && rtp_data_channel_->ready_to_send_data()) ||
5003 sctp_ready_to_send_data_;
5004}
5005
Qingsi Wang72a43a12018-02-20 16:03:18 -08005006cricket::CandidateStatsList PeerConnection::GetPooledCandidateStats() const {
5007 cricket::CandidateStatsList candidate_states_list;
5008 port_allocator_->GetCandidateStatsFromPooledSessions(&candidate_states_list);
5009 return candidate_states_list;
5010}
5011
Steve Anton5dfde182018-02-06 10:34:40 -08005012std::map<std::string, std::string> PeerConnection::GetTransportNamesByMid()
5013 const {
5014 std::map<std::string, std::string> transport_names_by_mid;
5015 for (auto transceiver : transceivers_) {
5016 cricket::BaseChannel* channel = transceiver->internal()->channel();
5017 if (channel) {
5018 transport_names_by_mid[channel->content_name()] =
5019 channel->transport_name();
5020 }
Steve Anton75737c02017-11-06 10:37:17 -08005021 }
Steve Anton5dfde182018-02-06 10:34:40 -08005022 if (rtp_data_channel_) {
5023 transport_names_by_mid[rtp_data_channel_->content_name()] =
5024 rtp_data_channel_->transport_name();
Steve Anton75737c02017-11-06 10:37:17 -08005025 }
5026 if (sctp_transport_) {
Steve Anton5dfde182018-02-06 10:34:40 -08005027 transport_names_by_mid[*sctp_content_name_] = *sctp_transport_name_;
Steve Anton75737c02017-11-06 10:37:17 -08005028 }
Steve Anton5dfde182018-02-06 10:34:40 -08005029 return transport_names_by_mid;
Steve Anton75737c02017-11-06 10:37:17 -08005030}
5031
Steve Anton5dfde182018-02-06 10:34:40 -08005032std::map<std::string, cricket::TransportStats>
5033PeerConnection::GetTransportStatsByNames(
5034 const std::set<std::string>& transport_names) {
5035 if (!network_thread()->IsCurrent()) {
5036 return network_thread()
5037 ->Invoke<std::map<std::string, cricket::TransportStats>>(
5038 RTC_FROM_HERE,
5039 [&] { return GetTransportStatsByNames(transport_names); });
Steve Anton75737c02017-11-06 10:37:17 -08005040 }
Steve Anton5dfde182018-02-06 10:34:40 -08005041 std::map<std::string, cricket::TransportStats> transport_stats_by_name;
5042 for (const std::string& transport_name : transport_names) {
5043 cricket::TransportStats transport_stats;
5044 bool success =
5045 transport_controller_->GetStats(transport_name, &transport_stats);
5046 if (success) {
5047 transport_stats_by_name[transport_name] = std::move(transport_stats);
5048 } else {
5049 RTC_LOG(LS_ERROR) << "Failed to get transport stats for transport_name="
5050 << transport_name;
5051 }
5052 }
5053 return transport_stats_by_name;
Steve Anton75737c02017-11-06 10:37:17 -08005054}
5055
5056bool PeerConnection::GetLocalCertificate(
5057 const std::string& transport_name,
5058 rtc::scoped_refptr<rtc::RTCCertificate>* certificate) {
5059 return transport_controller_->GetLocalCertificate(transport_name,
5060 certificate);
5061}
5062
Taylor Brandstetterc3928662018-02-23 13:04:51 -08005063std::unique_ptr<rtc::SSLCertChain> PeerConnection::GetRemoteSSLCertChain(
Steve Anton75737c02017-11-06 10:37:17 -08005064 const std::string& transport_name) {
Taylor Brandstetterc3928662018-02-23 13:04:51 -08005065 return transport_controller_->GetRemoteSSLCertChain(transport_name);
Steve Anton75737c02017-11-06 10:37:17 -08005066}
5067
5068cricket::DataChannelType PeerConnection::data_channel_type() const {
5069 return data_channel_type_;
5070}
5071
5072bool PeerConnection::IceRestartPending(const std::string& content_name) const {
5073 return pending_ice_restarts_.find(content_name) !=
5074 pending_ice_restarts_.end();
5075}
5076
Steve Anton75737c02017-11-06 10:37:17 -08005077bool PeerConnection::NeedsIceRestart(const std::string& content_name) const {
5078 return transport_controller_->NeedsIceRestart(content_name);
5079}
5080
5081void PeerConnection::OnCertificateReady(
5082 const rtc::scoped_refptr<rtc::RTCCertificate>& certificate) {
5083 transport_controller_->SetLocalCertificate(certificate);
5084}
5085
5086void PeerConnection::OnDtlsSrtpSetupFailure(cricket::BaseChannel*, bool rtcp) {
Steve Antonf8470812017-12-04 10:46:21 -08005087 SetSessionError(SessionError::kTransport,
5088 rtcp ? kDtlsSrtpSetupFailureRtcp : kDtlsSrtpSetupFailureRtp);
Steve Anton75737c02017-11-06 10:37:17 -08005089}
5090
5091void PeerConnection::OnTransportControllerConnectionState(
5092 cricket::IceConnectionState state) {
5093 switch (state) {
5094 case cricket::kIceConnectionConnecting:
5095 // If the current state is Connected or Completed, then there were
5096 // writable channels but now there are not, so the next state must
5097 // be Disconnected.
5098 // kIceConnectionConnecting is currently used as the default,
5099 // un-connected state by the TransportController, so its only use is
5100 // detecting disconnections.
5101 if (ice_connection_state_ ==
5102 PeerConnectionInterface::kIceConnectionConnected ||
5103 ice_connection_state_ ==
5104 PeerConnectionInterface::kIceConnectionCompleted) {
5105 SetIceConnectionState(
5106 PeerConnectionInterface::kIceConnectionDisconnected);
5107 }
5108 break;
5109 case cricket::kIceConnectionFailed:
5110 SetIceConnectionState(PeerConnectionInterface::kIceConnectionFailed);
5111 break;
5112 case cricket::kIceConnectionConnected:
Mirko Bonadei675513b2017-11-09 11:09:25 +01005113 RTC_LOG(LS_INFO) << "Changing to ICE connected state because "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005114 "all transports are writable.";
Steve Anton75737c02017-11-06 10:37:17 -08005115 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
5116 break;
5117 case cricket::kIceConnectionCompleted:
Mirko Bonadei675513b2017-11-09 11:09:25 +01005118 RTC_LOG(LS_INFO) << "Changing to ICE completed state because "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005119 "all transports are complete.";
Steve Anton75737c02017-11-06 10:37:17 -08005120 if (ice_connection_state_ !=
5121 PeerConnectionInterface::kIceConnectionConnected) {
5122 // If jumping directly from "checking" to "connected",
5123 // signal "connected" first.
5124 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
5125 }
5126 SetIceConnectionState(PeerConnectionInterface::kIceConnectionCompleted);
5127 if (metrics_observer()) {
5128 ReportTransportStats();
5129 }
5130 break;
5131 default:
5132 RTC_NOTREACHED();
5133 }
5134}
5135
5136void PeerConnection::OnTransportControllerCandidatesGathered(
5137 const std::string& transport_name,
5138 const cricket::Candidates& candidates) {
5139 RTC_DCHECK(signaling_thread()->IsCurrent());
5140 int sdp_mline_index;
5141 if (!GetLocalCandidateMediaIndex(transport_name, &sdp_mline_index)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005142 RTC_LOG(LS_ERROR)
5143 << "OnTransportControllerCandidatesGathered: content name "
5144 << transport_name << " not found";
Steve Anton75737c02017-11-06 10:37:17 -08005145 return;
5146 }
5147
5148 for (cricket::Candidates::const_iterator citer = candidates.begin();
5149 citer != candidates.end(); ++citer) {
5150 // Use transport_name as the candidate media id.
5151 std::unique_ptr<JsepIceCandidate> candidate(
5152 new JsepIceCandidate(transport_name, sdp_mline_index, *citer));
5153 if (local_description()) {
5154 mutable_local_description()->AddCandidate(candidate.get());
5155 }
5156 OnIceCandidate(std::move(candidate));
5157 }
5158}
5159
5160void PeerConnection::OnTransportControllerCandidatesRemoved(
5161 const std::vector<cricket::Candidate>& candidates) {
5162 RTC_DCHECK(signaling_thread()->IsCurrent());
5163 // Sanity check.
5164 for (const cricket::Candidate& candidate : candidates) {
5165 if (candidate.transport_name().empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005166 RTC_LOG(LS_ERROR) << "OnTransportControllerCandidatesRemoved: "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005167 "empty content name in candidate "
Mirko Bonadei675513b2017-11-09 11:09:25 +01005168 << candidate.ToString();
Steve Anton75737c02017-11-06 10:37:17 -08005169 return;
5170 }
5171 }
5172
5173 if (local_description()) {
5174 mutable_local_description()->RemoveCandidates(candidates);
5175 }
5176 OnIceCandidatesRemoved(candidates);
5177}
5178
5179void PeerConnection::OnTransportControllerDtlsHandshakeError(
5180 rtc::SSLHandshakeError error) {
5181 if (metrics_observer()) {
5182 metrics_observer()->IncrementEnumCounter(
5183 webrtc::kEnumCounterDtlsHandshakeError, static_cast<int>(error),
5184 static_cast<int>(rtc::SSLHandshakeError::MAX_VALUE));
5185 }
5186}
5187
Steve Antoned10bd92017-12-05 10:52:59 -08005188void PeerConnection::EnableSending() {
5189 for (auto transceiver : transceivers_) {
5190 cricket::BaseChannel* channel = transceiver->internal()->channel();
5191 if (channel && !channel->enabled()) {
5192 channel->Enable(true);
5193 }
Steve Anton75737c02017-11-06 10:37:17 -08005194 }
5195
Steve Anton4171afb2017-11-20 10:20:22 -08005196 if (rtp_data_channel_ && !rtp_data_channel_->enabled()) {
Steve Anton75737c02017-11-06 10:37:17 -08005197 rtp_data_channel_->Enable(true);
Steve Anton4171afb2017-11-20 10:20:22 -08005198 }
Steve Anton75737c02017-11-06 10:37:17 -08005199}
5200
5201// Returns the media index for a local ice candidate given the content name.
5202bool PeerConnection::GetLocalCandidateMediaIndex(
5203 const std::string& content_name,
5204 int* sdp_mline_index) {
5205 if (!local_description() || !sdp_mline_index) {
5206 return false;
5207 }
5208
5209 bool content_found = false;
5210 const ContentInfos& contents = local_description()->description()->contents();
5211 for (size_t index = 0; index < contents.size(); ++index) {
5212 if (contents[index].name == content_name) {
5213 *sdp_mline_index = static_cast<int>(index);
5214 content_found = true;
5215 break;
5216 }
5217 }
5218 return content_found;
5219}
5220
5221bool PeerConnection::UseCandidatesInSessionDescription(
5222 const SessionDescriptionInterface* remote_desc) {
5223 if (!remote_desc) {
5224 return true;
5225 }
5226 bool ret = true;
5227
5228 for (size_t m = 0; m < remote_desc->number_of_mediasections(); ++m) {
5229 const IceCandidateCollection* candidates = remote_desc->candidates(m);
5230 for (size_t n = 0; n < candidates->count(); ++n) {
5231 const IceCandidateInterface* candidate = candidates->at(n);
5232 bool valid = false;
5233 if (!ReadyToUseRemoteCandidate(candidate, remote_desc, &valid)) {
5234 if (valid) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005235 RTC_LOG(LS_INFO)
5236 << "UseCandidatesInSessionDescription: Not ready to use "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005237 "candidate.";
Steve Anton75737c02017-11-06 10:37:17 -08005238 }
5239 continue;
5240 }
5241 ret = UseCandidate(candidate);
5242 if (!ret) {
5243 break;
5244 }
5245 }
5246 }
5247 return ret;
5248}
5249
5250bool PeerConnection::UseCandidate(const IceCandidateInterface* candidate) {
5251 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
5252 size_t remote_content_size =
5253 remote_description()->description()->contents().size();
5254 if (mediacontent_index >= remote_content_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005255 RTC_LOG(LS_ERROR) << "UseCandidate: Invalid candidate media index.";
Steve Anton75737c02017-11-06 10:37:17 -08005256 return false;
5257 }
5258
5259 cricket::ContentInfo content =
5260 remote_description()->description()->contents()[mediacontent_index];
5261 std::vector<cricket::Candidate> candidates;
5262 candidates.push_back(candidate->candidate());
5263 // Invoking BaseSession method to handle remote candidates.
5264 std::string error;
5265 if (transport_controller_->AddRemoteCandidates(content.name, candidates,
5266 &error)) {
5267 // Candidates successfully submitted for checking.
5268 if (ice_connection_state_ == PeerConnectionInterface::kIceConnectionNew ||
5269 ice_connection_state_ ==
5270 PeerConnectionInterface::kIceConnectionDisconnected) {
5271 // If state is New, then the session has just gotten its first remote ICE
5272 // candidates, so go to Checking.
5273 // If state is Disconnected, the session is re-using old candidates or
5274 // receiving additional ones, so go to Checking.
5275 // If state is Connected, stay Connected.
5276 // TODO(bemasc): If state is Connected, and the new candidates are for a
5277 // newly added transport, then the state actually _should_ move to
5278 // checking. Add a way to distinguish that case.
5279 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
5280 }
5281 // TODO(bemasc): If state is Completed, go back to Connected.
5282 } else {
5283 if (!error.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005284 RTC_LOG(LS_WARNING) << error;
Steve Anton75737c02017-11-06 10:37:17 -08005285 }
5286 }
5287 return true;
5288}
5289
5290void PeerConnection::RemoveUnusedChannels(const SessionDescription* desc) {
Steve Anton75737c02017-11-06 10:37:17 -08005291 // Destroy video channel first since it may have a pointer to the
5292 // voice channel.
5293 const cricket::ContentInfo* video_info = cricket::GetFirstVideoContent(desc);
Steve Anton6fec8802017-12-04 10:37:29 -08005294 if (!video_info || video_info->rejected) {
5295 DestroyTransceiverChannel(GetVideoTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08005296 }
5297
Steve Anton6fec8802017-12-04 10:37:29 -08005298 const cricket::ContentInfo* audio_info = cricket::GetFirstAudioContent(desc);
5299 if (!audio_info || audio_info->rejected) {
5300 DestroyTransceiverChannel(GetAudioTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08005301 }
5302
5303 const cricket::ContentInfo* data_info = cricket::GetFirstDataContent(desc);
5304 if (!data_info || data_info->rejected) {
Steve Anton6fec8802017-12-04 10:37:29 -08005305 DestroyDataChannel();
Steve Anton75737c02017-11-06 10:37:17 -08005306 }
5307}
5308
Steve Antoneda6ccd2017-12-04 10:21:55 -08005309std::string PeerConnection::GetTransportNameForMediaSection(
5310 const std::string& mid,
5311 const cricket::ContentGroup* bundle_group) const {
5312 if (!bundle_group) {
5313 return mid;
Steve Anton75737c02017-11-06 10:37:17 -08005314 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005315 const std::string* first_content_name = bundle_group->FirstContentName();
Steve Anton75737c02017-11-06 10:37:17 -08005316 if (!first_content_name) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005317 RTC_LOG(LS_WARNING) << "Tried to BUNDLE with no contents.";
Steve Antoneda6ccd2017-12-04 10:21:55 -08005318 return mid;
Steve Anton75737c02017-11-06 10:37:17 -08005319 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005320 if (!bundle_group->HasContentName(mid)) {
5321 RTC_LOG(LS_WARNING) << mid << " is not part of any bundle group";
5322 return mid;
Steve Anton75737c02017-11-06 10:37:17 -08005323 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005324 RTC_LOG(LS_INFO) << "Bundling " << mid << " on " << *first_content_name;
5325 return *first_content_name;
Steve Anton75737c02017-11-06 10:37:17 -08005326}
5327
Steve Antondcc3c022017-12-22 16:02:54 -08005328RTCErrorOr<const cricket::ContentGroup*> PeerConnection::GetEarlyBundleGroup(
5329 const SessionDescription& desc) const {
Steve Anton75737c02017-11-06 10:37:17 -08005330 const cricket::ContentGroup* bundle_group = nullptr;
5331 if (configuration_.bundle_policy ==
5332 PeerConnectionInterface::kBundlePolicyMaxBundle) {
Steve Antondcc3c022017-12-22 16:02:54 -08005333 bundle_group = desc.GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton75737c02017-11-06 10:37:17 -08005334 if (!bundle_group) {
Steve Anton8a006912017-12-04 15:25:56 -08005335 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5336 "max-bundle configured but session description "
5337 "has no BUNDLE group");
Steve Anton75737c02017-11-06 10:37:17 -08005338 }
5339 }
Steve Antondcc3c022017-12-22 16:02:54 -08005340 return std::move(bundle_group);
5341}
5342
5343RTCError PeerConnection::CreateChannels(const SessionDescription& desc) {
5344 auto bundle_group_or_error = GetEarlyBundleGroup(desc);
5345 if (!bundle_group_or_error.ok()) {
5346 return bundle_group_or_error.MoveError();
5347 }
5348 const cricket::ContentGroup* bundle_group = bundle_group_or_error.MoveValue();
Steve Anton75737c02017-11-06 10:37:17 -08005349
Steve Antoneda6ccd2017-12-04 10:21:55 -08005350 // Creating the media channels and transport proxies.
Steve Antondcc3c022017-12-22 16:02:54 -08005351 const cricket::ContentInfo* voice = cricket::GetFirstAudioContent(&desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08005352 if (voice && !voice->rejected &&
5353 !GetAudioTransceiver()->internal()->channel()) {
5354 cricket::VoiceChannel* voice_channel = CreateVoiceChannel(
5355 voice->name,
5356 GetTransportNameForMediaSection(voice->name, bundle_group));
5357 if (!voice_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08005358 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5359 "Failed to create voice channel.");
Steve Antoneda6ccd2017-12-04 10:21:55 -08005360 }
5361 GetAudioTransceiver()->internal()->SetChannel(voice_channel);
5362 }
5363
Steve Antondcc3c022017-12-22 16:02:54 -08005364 const cricket::ContentInfo* video = cricket::GetFirstVideoContent(&desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08005365 if (video && !video->rejected &&
5366 !GetVideoTransceiver()->internal()->channel()) {
5367 cricket::VideoChannel* video_channel = CreateVideoChannel(
5368 video->name,
5369 GetTransportNameForMediaSection(video->name, bundle_group));
5370 if (!video_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08005371 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5372 "Failed to create video channel.");
Steve Anton75737c02017-11-06 10:37:17 -08005373 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005374 GetVideoTransceiver()->internal()->SetChannel(video_channel);
Steve Anton75737c02017-11-06 10:37:17 -08005375 }
5376
Steve Antondcc3c022017-12-22 16:02:54 -08005377 const cricket::ContentInfo* data = cricket::GetFirstDataContent(&desc);
Steve Anton75737c02017-11-06 10:37:17 -08005378 if (data_channel_type_ != cricket::DCT_NONE && data && !data->rejected &&
5379 !rtp_data_channel_ && !sctp_transport_) {
Steve Antoneda6ccd2017-12-04 10:21:55 -08005380 if (!CreateDataChannel(data->name, GetTransportNameForMediaSection(
5381 data->name, bundle_group))) {
Steve Anton8a006912017-12-04 15:25:56 -08005382 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5383 "Failed to create data channel.");
Steve Anton75737c02017-11-06 10:37:17 -08005384 }
5385 }
5386
Steve Anton8a006912017-12-04 15:25:56 -08005387 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08005388}
5389
Steve Anton4171afb2017-11-20 10:20:22 -08005390// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08005391cricket::VoiceChannel* PeerConnection::CreateVoiceChannel(
5392 const std::string& mid,
5393 const std::string& transport_name) {
Steve Anton75737c02017-11-06 10:37:17 -08005394 cricket::DtlsTransportInternal* rtp_dtls_transport =
5395 transport_controller_->CreateDtlsTransport(
5396 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5397 cricket::DtlsTransportInternal* rtcp_dtls_transport = nullptr;
5398 if (configuration_.rtcp_mux_policy !=
5399 PeerConnectionInterface::kRtcpMuxPolicyRequire) {
5400 rtcp_dtls_transport = transport_controller_->CreateDtlsTransport(
5401 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
5402 }
5403
5404 cricket::VoiceChannel* voice_channel = channel_manager()->CreateVoiceChannel(
5405 call_.get(), configuration_.media_config, rtp_dtls_transport,
Steve Antoneda6ccd2017-12-04 10:21:55 -08005406 rtcp_dtls_transport, signaling_thread(), mid, SrtpRequired(),
5407 audio_options_);
Steve Anton75737c02017-11-06 10:37:17 -08005408 if (!voice_channel) {
5409 transport_controller_->DestroyDtlsTransport(
5410 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5411 if (rtcp_dtls_transport) {
5412 transport_controller_->DestroyDtlsTransport(
5413 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
5414 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005415 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08005416 }
Steve Anton75737c02017-11-06 10:37:17 -08005417 voice_channel->SignalRtcpMuxFullyActive.connect(
5418 this, &PeerConnection::DestroyRtcpTransport_n);
5419 voice_channel->SignalDtlsSrtpSetupFailure.connect(
5420 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08005421 voice_channel->SignalSentPacket.connect(this,
5422 &PeerConnection::OnSentPacket_w);
Steve Anton4171afb2017-11-20 10:20:22 -08005423
Steve Antoneda6ccd2017-12-04 10:21:55 -08005424 return voice_channel;
Steve Anton75737c02017-11-06 10:37:17 -08005425}
5426
Steve Anton4171afb2017-11-20 10:20:22 -08005427// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08005428cricket::VideoChannel* PeerConnection::CreateVideoChannel(
5429 const std::string& mid,
5430 const std::string& transport_name) {
Steve Anton75737c02017-11-06 10:37:17 -08005431 cricket::DtlsTransportInternal* rtp_dtls_transport =
5432 transport_controller_->CreateDtlsTransport(
5433 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5434 cricket::DtlsTransportInternal* rtcp_dtls_transport = nullptr;
5435 if (configuration_.rtcp_mux_policy !=
5436 PeerConnectionInterface::kRtcpMuxPolicyRequire) {
5437 rtcp_dtls_transport = transport_controller_->CreateDtlsTransport(
5438 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
5439 }
5440
5441 cricket::VideoChannel* video_channel = channel_manager()->CreateVideoChannel(
5442 call_.get(), configuration_.media_config, rtp_dtls_transport,
Steve Antoneda6ccd2017-12-04 10:21:55 -08005443 rtcp_dtls_transport, signaling_thread(), mid, SrtpRequired(),
5444 video_options_);
Steve Anton75737c02017-11-06 10:37:17 -08005445
5446 if (!video_channel) {
5447 transport_controller_->DestroyDtlsTransport(
5448 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5449 if (rtcp_dtls_transport) {
5450 transport_controller_->DestroyDtlsTransport(
5451 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
5452 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005453 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08005454 }
Steve Anton75737c02017-11-06 10:37:17 -08005455 video_channel->SignalRtcpMuxFullyActive.connect(
5456 this, &PeerConnection::DestroyRtcpTransport_n);
5457 video_channel->SignalDtlsSrtpSetupFailure.connect(
5458 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08005459 video_channel->SignalSentPacket.connect(this,
5460 &PeerConnection::OnSentPacket_w);
Steve Anton4171afb2017-11-20 10:20:22 -08005461
Steve Antoneda6ccd2017-12-04 10:21:55 -08005462 return video_channel;
Steve Anton75737c02017-11-06 10:37:17 -08005463}
5464
Steve Antoneda6ccd2017-12-04 10:21:55 -08005465bool PeerConnection::CreateDataChannel(const std::string& mid,
5466 const std::string& transport_name) {
Steve Anton75737c02017-11-06 10:37:17 -08005467 bool sctp = (data_channel_type_ == cricket::DCT_SCTP);
5468 if (sctp) {
5469 if (!sctp_factory_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005470 RTC_LOG(LS_ERROR)
Steve Anton75737c02017-11-06 10:37:17 -08005471 << "Trying to create SCTP transport, but didn't compile with "
5472 "SCTP support (HAVE_SCTP)";
5473 return false;
5474 }
5475 if (!network_thread()->Invoke<bool>(
5476 RTC_FROM_HERE, rtc::Bind(&PeerConnection::CreateSctpTransport_n,
Steve Antoneda6ccd2017-12-04 10:21:55 -08005477 this, mid, transport_name))) {
Steve Anton75737c02017-11-06 10:37:17 -08005478 return false;
5479 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005480 for (const auto& channel : sctp_data_channels_) {
5481 channel->OnTransportChannelCreated();
5482 }
Steve Anton75737c02017-11-06 10:37:17 -08005483 } else {
Steve Anton75737c02017-11-06 10:37:17 -08005484 cricket::DtlsTransportInternal* rtp_dtls_transport =
5485 transport_controller_->CreateDtlsTransport(
5486 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5487 cricket::DtlsTransportInternal* rtcp_dtls_transport = nullptr;
5488 if (configuration_.rtcp_mux_policy !=
5489 PeerConnectionInterface::kRtcpMuxPolicyRequire) {
5490 rtcp_dtls_transport = transport_controller_->CreateDtlsTransport(
5491 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
5492 }
5493
5494 rtp_data_channel_ = channel_manager()->CreateRtpDataChannel(
5495 configuration_.media_config, rtp_dtls_transport, rtcp_dtls_transport,
Steve Antoneda6ccd2017-12-04 10:21:55 -08005496 signaling_thread(), mid, SrtpRequired());
Steve Anton75737c02017-11-06 10:37:17 -08005497
5498 if (!rtp_data_channel_) {
5499 transport_controller_->DestroyDtlsTransport(
5500 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5501 if (rtcp_dtls_transport) {
5502 transport_controller_->DestroyDtlsTransport(
5503 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
5504 }
5505 return false;
5506 }
5507
5508 rtp_data_channel_->SignalRtcpMuxFullyActive.connect(
5509 this, &PeerConnection::DestroyRtcpTransport_n);
5510 rtp_data_channel_->SignalDtlsSrtpSetupFailure.connect(
5511 this, &PeerConnection::OnDtlsSrtpSetupFailure);
5512 rtp_data_channel_->SignalSentPacket.connect(
5513 this, &PeerConnection::OnSentPacket_w);
5514 }
5515
Steve Anton75737c02017-11-06 10:37:17 -08005516 return true;
5517}
5518
5519Call::Stats PeerConnection::GetCallStats() {
5520 if (!worker_thread()->IsCurrent()) {
5521 return worker_thread()->Invoke<Call::Stats>(
5522 RTC_FROM_HERE, rtc::Bind(&PeerConnection::GetCallStats, this));
5523 }
5524 if (call_) {
5525 return call_->GetStats();
5526 } else {
5527 return Call::Stats();
5528 }
5529}
5530
Steve Anton75737c02017-11-06 10:37:17 -08005531bool PeerConnection::CreateSctpTransport_n(const std::string& content_name,
5532 const std::string& transport_name) {
5533 RTC_DCHECK(network_thread()->IsCurrent());
5534 RTC_DCHECK(sctp_factory_);
5535 cricket::DtlsTransportInternal* tc =
5536 transport_controller_->CreateDtlsTransport_n(
5537 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5538 sctp_transport_ = sctp_factory_->CreateSctpTransport(tc);
5539 RTC_DCHECK(sctp_transport_);
5540 sctp_invoker_.reset(new rtc::AsyncInvoker());
5541 sctp_transport_->SignalReadyToSendData.connect(
5542 this, &PeerConnection::OnSctpTransportReadyToSendData_n);
5543 sctp_transport_->SignalDataReceived.connect(
5544 this, &PeerConnection::OnSctpTransportDataReceived_n);
5545 sctp_transport_->SignalStreamClosedRemotely.connect(
5546 this, &PeerConnection::OnSctpStreamClosedRemotely_n);
Oskar Sundbom9b28a032017-11-16 10:53:30 +01005547 sctp_transport_name_ = transport_name;
5548 sctp_content_name_ = content_name;
Steve Anton75737c02017-11-06 10:37:17 -08005549 return true;
5550}
5551
5552void PeerConnection::ChangeSctpTransport_n(const std::string& transport_name) {
5553 RTC_DCHECK(network_thread()->IsCurrent());
5554 RTC_DCHECK(sctp_transport_);
5555 RTC_DCHECK(sctp_transport_name_);
5556 std::string old_sctp_transport_name = *sctp_transport_name_;
Oskar Sundbom9b28a032017-11-16 10:53:30 +01005557 sctp_transport_name_ = transport_name;
Steve Anton75737c02017-11-06 10:37:17 -08005558 cricket::DtlsTransportInternal* tc =
5559 transport_controller_->CreateDtlsTransport_n(
5560 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5561 sctp_transport_->SetTransportChannel(tc);
5562 transport_controller_->DestroyDtlsTransport_n(
5563 old_sctp_transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5564}
5565
5566void PeerConnection::DestroySctpTransport_n() {
5567 RTC_DCHECK(network_thread()->IsCurrent());
5568 sctp_transport_.reset(nullptr);
Taylor Brandstetter389a97c2018-01-03 16:26:06 -08005569 transport_controller_->DestroyDtlsTransport_n(
5570 *sctp_transport_name_, cricket::ICE_CANDIDATE_COMPONENT_RTP);
Steve Anton75737c02017-11-06 10:37:17 -08005571 sctp_content_name_.reset();
5572 sctp_transport_name_.reset();
5573 sctp_invoker_.reset(nullptr);
5574 sctp_ready_to_send_data_ = false;
5575}
5576
5577void PeerConnection::OnSctpTransportReadyToSendData_n() {
5578 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5579 RTC_DCHECK(network_thread()->IsCurrent());
5580 // Note: Cannot use rtc::Bind here because it will grab a reference to
5581 // PeerConnection and potentially cause PeerConnection to live longer than
5582 // expected. It is safe not to grab a reference since the sctp_invoker_ will
5583 // be destroyed before PeerConnection is destroyed, and at that point all
5584 // pending tasks will be cleared.
5585 sctp_invoker_->AsyncInvoke<void>(RTC_FROM_HERE, signaling_thread(), [this] {
5586 OnSctpTransportReadyToSendData_s(true);
5587 });
5588}
5589
5590void PeerConnection::OnSctpTransportReadyToSendData_s(bool ready) {
5591 RTC_DCHECK(signaling_thread()->IsCurrent());
5592 sctp_ready_to_send_data_ = ready;
5593 SignalSctpReadyToSendData(ready);
5594}
5595
5596void PeerConnection::OnSctpTransportDataReceived_n(
5597 const cricket::ReceiveDataParams& params,
5598 const rtc::CopyOnWriteBuffer& payload) {
5599 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5600 RTC_DCHECK(network_thread()->IsCurrent());
5601 // Note: Cannot use rtc::Bind here because it will grab a reference to
5602 // PeerConnection and potentially cause PeerConnection to live longer than
5603 // expected. It is safe not to grab a reference since the sctp_invoker_ will
5604 // be destroyed before PeerConnection is destroyed, and at that point all
5605 // pending tasks will be cleared.
5606 sctp_invoker_->AsyncInvoke<void>(
5607 RTC_FROM_HERE, signaling_thread(), [this, params, payload] {
5608 OnSctpTransportDataReceived_s(params, payload);
5609 });
5610}
5611
5612void PeerConnection::OnSctpTransportDataReceived_s(
5613 const cricket::ReceiveDataParams& params,
5614 const rtc::CopyOnWriteBuffer& payload) {
5615 RTC_DCHECK(signaling_thread()->IsCurrent());
5616 if (params.type == cricket::DMT_CONTROL && IsOpenMessage(payload)) {
5617 // Received OPEN message; parse and signal that a new data channel should
5618 // be created.
5619 std::string label;
5620 InternalDataChannelInit config;
5621 config.id = params.ssrc;
5622 if (!ParseDataChannelOpenMessage(payload, &label, &config)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005623 RTC_LOG(LS_WARNING) << "Failed to parse the OPEN message for sid "
5624 << params.ssrc;
Steve Anton75737c02017-11-06 10:37:17 -08005625 return;
5626 }
5627 config.open_handshake_role = InternalDataChannelInit::kAcker;
5628 OnDataChannelOpenMessage(label, config);
5629 } else {
5630 // Otherwise just forward the signal.
5631 SignalSctpDataReceived(params, payload);
5632 }
5633}
5634
5635void PeerConnection::OnSctpStreamClosedRemotely_n(int sid) {
5636 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5637 RTC_DCHECK(network_thread()->IsCurrent());
5638 sctp_invoker_->AsyncInvoke<void>(
5639 RTC_FROM_HERE, signaling_thread(),
5640 rtc::Bind(&sigslot::signal1<int>::operator(),
5641 &SignalSctpStreamClosedRemotely, sid));
5642}
5643
5644// Returns false if bundle is enabled and rtcp_mux is disabled.
5645bool PeerConnection::ValidateBundleSettings(const SessionDescription* desc) {
5646 bool bundle_enabled = desc->HasGroup(cricket::GROUP_TYPE_BUNDLE);
5647 if (!bundle_enabled)
5648 return true;
5649
5650 const cricket::ContentGroup* bundle_group =
5651 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
5652 RTC_DCHECK(bundle_group != NULL);
5653
5654 const cricket::ContentInfos& contents = desc->contents();
5655 for (cricket::ContentInfos::const_iterator citer = contents.begin();
5656 citer != contents.end(); ++citer) {
5657 const cricket::ContentInfo* content = (&*citer);
5658 RTC_DCHECK(content != NULL);
5659 if (bundle_group->HasContentName(content->name) && !content->rejected &&
Steve Anton5adfafd2017-12-20 16:34:00 -08005660 content->type == MediaProtocolType::kRtp) {
Steve Anton75737c02017-11-06 10:37:17 -08005661 if (!HasRtcpMuxEnabled(content))
5662 return false;
5663 }
5664 }
5665 // RTCP-MUX is enabled in all the contents.
5666 return true;
5667}
5668
5669bool PeerConnection::HasRtcpMuxEnabled(const cricket::ContentInfo* content) {
Steve Antonb1c1de12017-12-21 15:14:30 -08005670 return content->media_description()->rtcp_mux();
Steve Anton75737c02017-11-06 10:37:17 -08005671}
5672
Steve Anton8a006912017-12-04 15:25:56 -08005673RTCError PeerConnection::ValidateSessionDescription(
Steve Anton75737c02017-11-06 10:37:17 -08005674 const SessionDescriptionInterface* sdesc,
Steve Anton8a006912017-12-04 15:25:56 -08005675 cricket::ContentSource source) {
Steve Antonf8470812017-12-04 10:46:21 -08005676 if (session_error() != SessionError::kNone) {
Steve Anton8a006912017-12-04 15:25:56 -08005677 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
Steve Anton75737c02017-11-06 10:37:17 -08005678 }
5679
5680 if (!sdesc || !sdesc->description()) {
Steve Anton8a006912017-12-04 15:25:56 -08005681 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidSdp);
Steve Anton75737c02017-11-06 10:37:17 -08005682 }
5683
Steve Anton3828c062017-12-06 10:34:51 -08005684 SdpType type = sdesc->GetType();
5685 if ((source == cricket::CS_LOCAL && !ExpectSetLocalDescription(type)) ||
5686 (source == cricket::CS_REMOTE && !ExpectSetRemoteDescription(type))) {
Steve Anton8a006912017-12-04 15:25:56 -08005687 LOG_AND_RETURN_ERROR(
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01005688 RTCErrorType::INVALID_STATE,
Steve Anton8a006912017-12-04 15:25:56 -08005689 "Called in wrong state: " + GetSignalingStateString(signaling_state()));
Steve Anton75737c02017-11-06 10:37:17 -08005690 }
5691
5692 // Verify crypto settings.
5693 std::string crypto_error;
Steve Anton8a006912017-12-04 15:25:56 -08005694 if (webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED ||
5695 dtls_enabled_) {
Harald Alvestrand194939b2018-01-24 16:04:13 +01005696 RTCError crypto_error =
5697 VerifyCrypto(sdesc->description(), dtls_enabled_, uma_observer_);
Steve Anton8a006912017-12-04 15:25:56 -08005698 if (!crypto_error.ok()) {
5699 return crypto_error;
5700 }
Steve Anton75737c02017-11-06 10:37:17 -08005701 }
5702
5703 // Verify ice-ufrag and ice-pwd.
5704 if (!VerifyIceUfragPwdPresent(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08005705 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5706 kSdpWithoutIceUfragPwd);
Steve Anton75737c02017-11-06 10:37:17 -08005707 }
5708
5709 if (!ValidateBundleSettings(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08005710 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5711 kBundleWithoutRtcpMux);
Steve Anton75737c02017-11-06 10:37:17 -08005712 }
5713
5714 // TODO(skvlad): When the local rtcp-mux policy is Require, reject any
5715 // m-lines that do not rtcp-mux enabled.
5716
5717 // Verify m-lines in Answer when compared against Offer.
Steve Anton3828c062017-12-06 10:34:51 -08005718 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Seth Hampsonae8a90a2018-02-13 15:33:48 -08005719 // With an answer we want to compare the new answer session description with
5720 // the offer's session description from the current negotiation.
Steve Anton75737c02017-11-06 10:37:17 -08005721 const cricket::SessionDescription* offer_desc =
5722 (source == cricket::CS_LOCAL) ? remote_description()->description()
5723 : local_description()->description();
Seth Hampsonae8a90a2018-02-13 15:33:48 -08005724 if (!MediaSectionsHaveSameCount(*offer_desc, *sdesc->description()) ||
5725 !MediaSectionsInSameOrder(*offer_desc, nullptr, *sdesc->description(),
5726 type)) {
Steve Anton8a006912017-12-04 15:25:56 -08005727 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5728 kMlineMismatchInAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08005729 }
5730 } else {
Steve Anton75737c02017-11-06 10:37:17 -08005731 // The re-offers should respect the order of m= sections in current
5732 // description. See RFC3264 Section 8 paragraph 4 for more details.
Seth Hampsonae8a90a2018-02-13 15:33:48 -08005733 // With a re-offer, either the current local or current remote descriptions
5734 // could be the most up to date, so we would like to check against both of
5735 // them if they exist. It could be the case that one of them has a 0 port
5736 // for a media section, but the other does not. This is important to check
5737 // against in the case that we are recycling an m= section.
5738 const cricket::SessionDescription* current_desc = nullptr;
5739 const cricket::SessionDescription* secondary_current_desc = nullptr;
5740 if (local_description()) {
5741 current_desc = local_description()->description();
5742 if (remote_description()) {
5743 secondary_current_desc = remote_description()->description();
5744 }
5745 } else if (remote_description()) {
5746 current_desc = remote_description()->description();
5747 }
Steve Anton75737c02017-11-06 10:37:17 -08005748 if (current_desc &&
Seth Hampsonae8a90a2018-02-13 15:33:48 -08005749 !MediaSectionsInSameOrder(*current_desc, secondary_current_desc,
5750 *sdesc->description(), type)) {
Steve Anton8a006912017-12-04 15:25:56 -08005751 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5752 kMlineMismatchInSubsequentOffer);
Steve Anton75737c02017-11-06 10:37:17 -08005753 }
5754 }
5755
Steve Anton8a006912017-12-04 15:25:56 -08005756 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08005757}
5758
Steve Anton3828c062017-12-06 10:34:51 -08005759bool PeerConnection::ExpectSetLocalDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08005760 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08005761 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08005762 return (state == PeerConnectionInterface::kStable) ||
5763 (state == PeerConnectionInterface::kHaveLocalOffer);
Steve Anton20393062017-12-04 16:24:52 -08005764 } else {
Steve Anton3828c062017-12-06 10:34:51 -08005765 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08005766 return (state == PeerConnectionInterface::kHaveRemoteOffer) ||
5767 (state == PeerConnectionInterface::kHaveLocalPrAnswer);
5768 }
5769}
5770
Steve Anton3828c062017-12-06 10:34:51 -08005771bool PeerConnection::ExpectSetRemoteDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08005772 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08005773 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08005774 return (state == PeerConnectionInterface::kStable) ||
5775 (state == PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton20393062017-12-04 16:24:52 -08005776 } else {
Steve Anton3828c062017-12-06 10:34:51 -08005777 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08005778 return (state == PeerConnectionInterface::kHaveLocalOffer) ||
5779 (state == PeerConnectionInterface::kHaveRemotePrAnswer);
5780 }
5781}
5782
Steve Antonf8470812017-12-04 10:46:21 -08005783const char* PeerConnection::SessionErrorToString(SessionError error) const {
5784 switch (error) {
5785 case SessionError::kNone:
5786 return "ERROR_NONE";
5787 case SessionError::kContent:
5788 return "ERROR_CONTENT";
5789 case SessionError::kTransport:
5790 return "ERROR_TRANSPORT";
5791 }
5792 RTC_NOTREACHED();
5793 return "";
5794}
5795
Steve Anton75737c02017-11-06 10:37:17 -08005796std::string PeerConnection::GetSessionErrorMsg() {
5797 std::ostringstream desc;
Steve Antonf8470812017-12-04 10:46:21 -08005798 desc << kSessionError << SessionErrorToString(session_error()) << ". ";
5799 desc << kSessionErrorDesc << session_error_desc() << ".";
Steve Anton75737c02017-11-06 10:37:17 -08005800 return desc.str();
5801}
5802
Steve Anton8e20f172018-03-06 10:55:04 -08005803void PeerConnection::ReportSdpFormatReceived(
5804 const SessionDescriptionInterface& remote_offer) {
5805 if (!uma_observer_) {
5806 return;
5807 }
5808 int num_audio_mlines = 0;
5809 int num_video_mlines = 0;
5810 int num_audio_tracks = 0;
5811 int num_video_tracks = 0;
5812 for (const ContentInfo& content : remote_offer.description()->contents()) {
5813 cricket::MediaType media_type = content.media_description()->type();
5814 int num_tracks = std::max(
5815 1, static_cast<int>(content.media_description()->streams().size()));
5816 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
5817 num_audio_mlines += 1;
5818 num_audio_tracks += num_tracks;
5819 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
5820 num_video_mlines += 1;
5821 num_video_tracks += num_tracks;
5822 }
5823 }
5824 SdpFormatReceived format = kSdpFormatReceivedNoTracks;
5825 if (num_audio_mlines > 1 || num_video_mlines > 1) {
5826 format = kSdpFormatReceivedComplexUnifiedPlan;
5827 } else if (num_audio_tracks > 1 || num_video_tracks > 1) {
5828 format = kSdpFormatReceivedComplexPlanB;
5829 } else if (num_audio_tracks > 0 || num_video_tracks > 0) {
5830 format = kSdpFormatReceivedSimple;
5831 }
5832 uma_observer_->IncrementEnumCounter(kEnumCounterSdpFormatReceived, format,
5833 kSdpFormatReceivedMax);
5834}
5835
Steve Anton0ffaaa22018-02-23 10:31:30 -08005836void PeerConnection::ReportNegotiatedSdpSemantics(
5837 const SessionDescriptionInterface& answer) {
5838 if (!uma_observer_) {
5839 return;
5840 }
5841 switch (answer.description()->msid_signaling()) {
5842 case 0:
5843 uma_observer_->IncrementEnumCounter(kEnumCounterSdpSemanticNegotiated,
5844 kSdpSemanticNegotiatedNone,
5845 kSdpSemanticNegotiatedMax);
5846 break;
5847 case cricket::kMsidSignalingMediaSection:
5848 uma_observer_->IncrementEnumCounter(kEnumCounterSdpSemanticNegotiated,
5849 kSdpSemanticNegotiatedUnifiedPlan,
5850 kSdpSemanticNegotiatedMax);
5851 break;
5852 case cricket::kMsidSignalingSsrcAttribute:
5853 uma_observer_->IncrementEnumCounter(kEnumCounterSdpSemanticNegotiated,
5854 kSdpSemanticNegotiatedPlanB,
5855 kSdpSemanticNegotiatedMax);
5856 break;
5857 case cricket::kMsidSignalingMediaSection |
5858 cricket::kMsidSignalingSsrcAttribute:
5859 uma_observer_->IncrementEnumCounter(kEnumCounterSdpSemanticNegotiated,
5860 kSdpSemanticNegotiatedMixed,
5861 kSdpSemanticNegotiatedMax);
5862 break;
5863 default:
5864 RTC_NOTREACHED();
5865 }
5866}
5867
Steve Anton75737c02017-11-06 10:37:17 -08005868// We need to check the local/remote description for the Transport instead of
5869// the session, because a new Transport added during renegotiation may have
5870// them unset while the session has them set from the previous negotiation.
5871// Not doing so may trigger the auto generation of transport description and
5872// mess up DTLS identity information, ICE credential, etc.
5873bool PeerConnection::ReadyToUseRemoteCandidate(
5874 const IceCandidateInterface* candidate,
5875 const SessionDescriptionInterface* remote_desc,
5876 bool* valid) {
5877 *valid = true;
5878
5879 const SessionDescriptionInterface* current_remote_desc =
5880 remote_desc ? remote_desc : remote_description();
5881
5882 if (!current_remote_desc) {
5883 return false;
5884 }
5885
5886 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
5887 size_t remote_content_size =
5888 current_remote_desc->description()->contents().size();
5889 if (mediacontent_index >= remote_content_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005890 RTC_LOG(LS_ERROR)
5891 << "ReadyToUseRemoteCandidate: Invalid candidate media index "
5892 << mediacontent_index;
Steve Anton75737c02017-11-06 10:37:17 -08005893
5894 *valid = false;
5895 return false;
5896 }
5897
5898 cricket::ContentInfo content =
5899 current_remote_desc->description()->contents()[mediacontent_index];
5900
5901 const std::string transport_name = GetTransportName(content.name);
5902 if (transport_name.empty()) {
5903 return false;
5904 }
5905 return transport_controller_->ReadyForRemoteCandidates(transport_name);
5906}
5907
5908bool PeerConnection::SrtpRequired() const {
5909 return dtls_enabled_ ||
5910 webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED;
5911}
5912
5913void PeerConnection::OnTransportControllerGatheringState(
5914 cricket::IceGatheringState state) {
5915 RTC_DCHECK(signaling_thread()->IsCurrent());
5916 if (state == cricket::kIceGatheringGathering) {
5917 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringGathering);
5918 } else if (state == cricket::kIceGatheringComplete) {
5919 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringComplete);
5920 }
5921}
5922
5923void PeerConnection::ReportTransportStats() {
Steve Antonc7b964c2018-02-01 14:39:45 -08005924 std::map<std::string, std::set<cricket::MediaType>>
5925 media_types_by_transport_name;
5926 for (auto transceiver : transceivers_) {
5927 if (transceiver->internal()->channel()) {
5928 const std::string& transport_name =
5929 transceiver->internal()->channel()->transport_name();
5930 media_types_by_transport_name[transport_name].insert(
Steve Anton69470252018-02-09 11:43:08 -08005931 transceiver->media_type());
Steve Antonc7b964c2018-02-01 14:39:45 -08005932 }
Steve Anton75737c02017-11-06 10:37:17 -08005933 }
5934 if (rtp_data_channel()) {
Steve Antonc7b964c2018-02-01 14:39:45 -08005935 media_types_by_transport_name[rtp_data_channel()->transport_name()].insert(
5936 cricket::MEDIA_TYPE_DATA);
Steve Anton75737c02017-11-06 10:37:17 -08005937 }
5938 if (sctp_transport_name_) {
Steve Antonc7b964c2018-02-01 14:39:45 -08005939 media_types_by_transport_name[*sctp_transport_name_].insert(
5940 cricket::MEDIA_TYPE_DATA);
Steve Anton75737c02017-11-06 10:37:17 -08005941 }
Steve Antonc7b964c2018-02-01 14:39:45 -08005942 for (const auto& entry : media_types_by_transport_name) {
5943 const std::string& transport_name = entry.first;
5944 const std::set<cricket::MediaType> media_types = entry.second;
Steve Anton75737c02017-11-06 10:37:17 -08005945 cricket::TransportStats stats;
Steve Antonc7b964c2018-02-01 14:39:45 -08005946 if (transport_controller_->GetStats(transport_name, &stats)) {
Steve Anton75737c02017-11-06 10:37:17 -08005947 ReportBestConnectionState(stats);
Steve Antonc7b964c2018-02-01 14:39:45 -08005948 ReportNegotiatedCiphers(stats, media_types);
Steve Anton75737c02017-11-06 10:37:17 -08005949 }
5950 }
5951}
5952// Walk through the ConnectionInfos to gather best connection usage
5953// for IPv4 and IPv6.
5954void PeerConnection::ReportBestConnectionState(
5955 const cricket::TransportStats& stats) {
5956 RTC_DCHECK(metrics_observer());
Steve Antonc7b964c2018-02-01 14:39:45 -08005957 for (const cricket::TransportChannelStats& channel_stats :
5958 stats.channel_stats) {
5959 for (const cricket::ConnectionInfo& connection_info :
5960 channel_stats.connection_infos) {
5961 if (!connection_info.best_connection) {
Steve Anton75737c02017-11-06 10:37:17 -08005962 continue;
5963 }
5964
5965 PeerConnectionEnumCounterType type = kPeerConnectionEnumCounterMax;
Steve Antonc7b964c2018-02-01 14:39:45 -08005966 const cricket::Candidate& local = connection_info.local_candidate;
5967 const cricket::Candidate& remote = connection_info.remote_candidate;
Steve Anton75737c02017-11-06 10:37:17 -08005968
5969 // Increment the counter for IceCandidatePairType.
5970 if (local.protocol() == cricket::TCP_PROTOCOL_NAME ||
5971 (local.type() == RELAY_PORT_TYPE &&
5972 local.relay_protocol() == cricket::TCP_PROTOCOL_NAME)) {
5973 type = kEnumCounterIceCandidatePairTypeTcp;
5974 } else if (local.protocol() == cricket::UDP_PROTOCOL_NAME) {
5975 type = kEnumCounterIceCandidatePairTypeUdp;
5976 } else {
5977 RTC_CHECK(0);
5978 }
5979 metrics_observer()->IncrementEnumCounter(
5980 type, GetIceCandidatePairCounter(local, remote),
5981 kIceCandidatePairMax);
5982
5983 // Increment the counter for IP type.
5984 if (local.address().family() == AF_INET) {
5985 metrics_observer()->IncrementEnumCounter(
5986 kEnumCounterAddressFamily, kBestConnections_IPv4,
5987 kPeerConnectionAddressFamilyCounter_Max);
5988
5989 } else if (local.address().family() == AF_INET6) {
5990 metrics_observer()->IncrementEnumCounter(
5991 kEnumCounterAddressFamily, kBestConnections_IPv6,
5992 kPeerConnectionAddressFamilyCounter_Max);
5993 } else {
5994 RTC_CHECK(0);
5995 }
5996
5997 return;
5998 }
5999 }
6000}
6001
6002void PeerConnection::ReportNegotiatedCiphers(
Steve Antonc7b964c2018-02-01 14:39:45 -08006003 const cricket::TransportStats& stats,
6004 const std::set<cricket::MediaType>& media_types) {
Steve Anton75737c02017-11-06 10:37:17 -08006005 RTC_DCHECK(metrics_observer());
6006 if (!dtls_enabled_ || stats.channel_stats.empty()) {
6007 return;
6008 }
6009
6010 int srtp_crypto_suite = stats.channel_stats[0].srtp_crypto_suite;
6011 int ssl_cipher_suite = stats.channel_stats[0].ssl_cipher_suite;
6012 if (srtp_crypto_suite == rtc::SRTP_INVALID_CRYPTO_SUITE &&
6013 ssl_cipher_suite == rtc::TLS_NULL_WITH_NULL_NULL) {
6014 return;
6015 }
6016
Steve Antonc7b964c2018-02-01 14:39:45 -08006017 for (cricket::MediaType media_type : media_types) {
6018 PeerConnectionEnumCounterType srtp_counter_type;
6019 PeerConnectionEnumCounterType ssl_counter_type;
6020 switch (media_type) {
6021 case cricket::MEDIA_TYPE_AUDIO:
6022 srtp_counter_type = kEnumCounterAudioSrtpCipher;
6023 ssl_counter_type = kEnumCounterAudioSslCipher;
6024 break;
6025 case cricket::MEDIA_TYPE_VIDEO:
6026 srtp_counter_type = kEnumCounterVideoSrtpCipher;
6027 ssl_counter_type = kEnumCounterVideoSslCipher;
6028 break;
6029 case cricket::MEDIA_TYPE_DATA:
6030 srtp_counter_type = kEnumCounterDataSrtpCipher;
6031 ssl_counter_type = kEnumCounterDataSslCipher;
6032 break;
6033 default:
6034 RTC_NOTREACHED();
6035 continue;
6036 }
6037 if (srtp_crypto_suite != rtc::SRTP_INVALID_CRYPTO_SUITE) {
6038 metrics_observer()->IncrementSparseEnumCounter(srtp_counter_type,
6039 srtp_crypto_suite);
6040 }
6041 if (ssl_cipher_suite != rtc::TLS_NULL_WITH_NULL_NULL) {
6042 metrics_observer()->IncrementSparseEnumCounter(ssl_counter_type,
6043 ssl_cipher_suite);
6044 }
Steve Anton75737c02017-11-06 10:37:17 -08006045 }
6046}
6047
6048void PeerConnection::OnSentPacket_w(const rtc::SentPacket& sent_packet) {
6049 RTC_DCHECK(worker_thread()->IsCurrent());
6050 RTC_DCHECK(call_);
6051 call_->OnSentPacket(sent_packet);
6052}
6053
6054const std::string PeerConnection::GetTransportName(
6055 const std::string& content_name) {
6056 cricket::BaseChannel* channel = GetChannel(content_name);
Steve Anton6fec8802017-12-04 10:37:29 -08006057 if (channel) {
6058 return channel->transport_name();
Steve Anton75737c02017-11-06 10:37:17 -08006059 }
Steve Anton6fec8802017-12-04 10:37:29 -08006060 if (sctp_transport_) {
6061 RTC_DCHECK(sctp_content_name_);
6062 RTC_DCHECK(sctp_transport_name_);
6063 if (content_name == *sctp_content_name_) {
6064 return *sctp_transport_name_;
6065 }
6066 }
6067 // Return an empty string if failed to retrieve the transport name.
6068 return "";
Steve Anton75737c02017-11-06 10:37:17 -08006069}
6070
6071void PeerConnection::DestroyRtcpTransport_n(const std::string& transport_name) {
6072 RTC_DCHECK(network_thread()->IsCurrent());
6073 transport_controller_->DestroyDtlsTransport_n(
6074 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
6075}
6076
Steve Anton6fec8802017-12-04 10:37:29 -08006077void PeerConnection::DestroyTransceiverChannel(
6078 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
6079 transceiver) {
6080 RTC_DCHECK(transceiver);
Steve Anton75737c02017-11-06 10:37:17 -08006081
Steve Anton6fec8802017-12-04 10:37:29 -08006082 cricket::BaseChannel* channel = transceiver->internal()->channel();
6083 if (channel) {
6084 transceiver->internal()->SetChannel(nullptr);
6085 DestroyBaseChannel(channel);
Steve Anton75737c02017-11-06 10:37:17 -08006086 }
6087}
6088
6089void PeerConnection::DestroyDataChannel() {
Steve Anton6fec8802017-12-04 10:37:29 -08006090 if (rtp_data_channel_) {
6091 OnDataChannelDestroyed();
6092 DestroyBaseChannel(rtp_data_channel_);
6093 rtp_data_channel_ = nullptr;
6094 }
6095
6096 // Note: Cannot use rtc::Bind to create a functor to invoke because it will
6097 // grab a reference to this PeerConnection. If this is called from the
6098 // PeerConnection destructor, the RefCountedObject vtable will have already
6099 // been destroyed (since it is a subclass of PeerConnection) and using
6100 // rtc::Bind will cause "Pure virtual function called" error to appear.
6101
6102 if (sctp_transport_) {
6103 OnDataChannelDestroyed();
6104 network_thread()->Invoke<void>(RTC_FROM_HERE,
6105 [this] { DestroySctpTransport_n(); });
6106 }
6107}
6108
6109void PeerConnection::DestroyBaseChannel(cricket::BaseChannel* channel) {
6110 RTC_DCHECK(channel);
6111 RTC_DCHECK(channel->rtp_dtls_transport());
6112
6113 // Need to cache these before destroying the base channel so that we do not
6114 // access uninitialized memory.
6115 const std::string transport_name =
6116 channel->rtp_dtls_transport()->transport_name();
6117 const bool need_to_delete_rtcp = (channel->rtcp_dtls_transport() != nullptr);
6118
6119 switch (channel->media_type()) {
6120 case cricket::MEDIA_TYPE_AUDIO:
6121 channel_manager()->DestroyVoiceChannel(
6122 static_cast<cricket::VoiceChannel*>(channel));
6123 break;
6124 case cricket::MEDIA_TYPE_VIDEO:
6125 channel_manager()->DestroyVideoChannel(
6126 static_cast<cricket::VideoChannel*>(channel));
6127 break;
6128 case cricket::MEDIA_TYPE_DATA:
6129 channel_manager()->DestroyRtpDataChannel(
6130 static_cast<cricket::RtpDataChannel*>(channel));
6131 break;
6132 default:
6133 RTC_NOTREACHED() << "Unknown media type: " << channel->media_type();
6134 break;
6135 }
6136
6137 // |channel| can no longer be used.
6138
Steve Anton75737c02017-11-06 10:37:17 -08006139 transport_controller_->DestroyDtlsTransport(
6140 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
6141 if (need_to_delete_rtcp) {
6142 transport_controller_->DestroyDtlsTransport(
6143 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
6144 }
6145}
6146
Harald Alvestrand89061872018-01-02 14:08:34 +01006147void PeerConnection::ClearStatsCache() {
6148 if (stats_collector_) {
6149 stats_collector_->ClearCachedStatsReport();
6150 }
6151}
6152
henrike@webrtc.org28e20752013-07-10 00:45:36 +00006153} // namespace webrtc