blob: b8bc67dc44fb5448625a8b7506a8e1441ceacf0d [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;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000118 std::string error;
119};
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;
127 std::string error;
128};
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 }
145 if (current_streams->find(new_stream->label()) != nullptr) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100146 RTC_LOG(LS_ERROR) << "MediaStream with label " << new_stream->label()
147 << " 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 }
Steve Anton8a006912017-12-04 15:25:56 -0800433 const std::string& mid = content_info.name;
434 if (bundle && bundle->HasContentName(mid) &&
435 mid != *(bundle->FirstContentName())) {
Steve Anton75737c02017-11-06 10:37:17 -0800436 // This isn't the first media section in the BUNDLE group, so it's not
437 // required to have crypto attributes, since only the crypto attributes
438 // from the first section actually get used.
439 continue;
440 }
441
442 // If the content isn't rejected or bundled into another m= section, crypto
443 // must be present.
Steve Antonb1c1de12017-12-21 15:14:30 -0800444 const MediaContentDescription* media = content_info.media_description();
Steve Anton8a006912017-12-04 15:25:56 -0800445 const TransportInfo* tinfo = desc->GetTransportInfoByName(mid);
Steve Anton75737c02017-11-06 10:37:17 -0800446 if (!media || !tinfo) {
447 // Something is not right.
Steve Anton8a006912017-12-04 15:25:56 -0800448 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidSdp);
Steve Anton75737c02017-11-06 10:37:17 -0800449 }
450 if (dtls_enabled) {
451 if (!tinfo->description.identity_fingerprint) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100452 RTC_LOG(LS_WARNING)
453 << "Session description must have DTLS fingerprint if "
454 "DTLS enabled.";
Steve Anton8a006912017-12-04 15:25:56 -0800455 return RTCError(RTCErrorType::INVALID_PARAMETER,
456 kSdpWithoutDtlsFingerprint);
Steve Anton75737c02017-11-06 10:37:17 -0800457 }
Harald Alvestrandf9d0f1d2018-03-02 14:15:26 +0100458 NoteKeyProtocolAndMedia(webrtc::kEnumCounterKeyProtocolDtls,
459 media->type(), uma_observer);
Steve Anton75737c02017-11-06 10:37:17 -0800460 } else {
461 if (media->cryptos().empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100462 RTC_LOG(LS_WARNING)
Steve Anton75737c02017-11-06 10:37:17 -0800463 << "Session description must have SDES when DTLS disabled.";
Steve Anton8a006912017-12-04 15:25:56 -0800464 return RTCError(RTCErrorType::INVALID_PARAMETER, kSdpWithoutSdesCrypto);
Steve Anton75737c02017-11-06 10:37:17 -0800465 }
Harald Alvestrandf9d0f1d2018-03-02 14:15:26 +0100466 NoteKeyProtocolAndMedia(webrtc::kEnumCounterKeyProtocolSdes,
467 media->type(), uma_observer);
Steve Anton75737c02017-11-06 10:37:17 -0800468 }
469 }
Steve Anton8a006912017-12-04 15:25:56 -0800470 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -0800471}
472
473// Checks that each non-rejected content has ice-ufrag and ice-pwd set, unless
474// it's in a BUNDLE group, in which case only the BUNDLE-tag section (first
475// media section/description in the BUNDLE group) needs a ufrag and pwd.
476bool VerifyIceUfragPwdPresent(const SessionDescription* desc) {
477 const cricket::ContentGroup* bundle =
478 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton8a006912017-12-04 15:25:56 -0800479 for (const cricket::ContentInfo& content_info : desc->contents()) {
480 if (content_info.rejected) {
Steve Anton75737c02017-11-06 10:37:17 -0800481 continue;
482 }
Steve Anton8a006912017-12-04 15:25:56 -0800483 const std::string& mid = content_info.name;
484 if (bundle && bundle->HasContentName(mid) &&
485 mid != *(bundle->FirstContentName())) {
Steve Anton75737c02017-11-06 10:37:17 -0800486 // This isn't the first media section in the BUNDLE group, so it's not
487 // required to have ufrag/password, since only the ufrag/password from
488 // the first section actually get used.
489 continue;
490 }
491
492 // If the content isn't rejected or bundled into another m= section,
493 // ice-ufrag and ice-pwd must be present.
Steve Anton8a006912017-12-04 15:25:56 -0800494 const TransportInfo* tinfo = desc->GetTransportInfoByName(mid);
Steve Anton75737c02017-11-06 10:37:17 -0800495 if (!tinfo) {
496 // Something is not right.
Mirko Bonadei675513b2017-11-09 11:09:25 +0100497 RTC_LOG(LS_ERROR) << kInvalidSdp;
Steve Anton75737c02017-11-06 10:37:17 -0800498 return false;
499 }
500 if (tinfo->description.ice_ufrag.empty() ||
501 tinfo->description.ice_pwd.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100502 RTC_LOG(LS_ERROR) << "Session description must have ice ufrag and pwd.";
Steve Anton75737c02017-11-06 10:37:17 -0800503 return false;
504 }
505 }
506 return true;
507}
508
509bool GetTrackIdBySsrc(const SessionDescription* session_description,
510 uint32_t ssrc,
511 std::string* track_id) {
512 RTC_DCHECK(track_id != NULL);
513
Steve Antonb1c1de12017-12-21 15:14:30 -0800514 const cricket::AudioContentDescription* audio_desc =
515 cricket::GetFirstAudioContentDescription(session_description);
516 if (audio_desc) {
517 const auto* found = cricket::GetStreamBySsrc(audio_desc->streams(), ssrc);
Steve Anton75737c02017-11-06 10:37:17 -0800518 if (found) {
519 *track_id = found->id;
520 return true;
521 }
522 }
523
Steve Antonb1c1de12017-12-21 15:14:30 -0800524 const cricket::VideoContentDescription* video_desc =
525 cricket::GetFirstVideoContentDescription(session_description);
526 if (video_desc) {
527 const auto* found = cricket::GetStreamBySsrc(video_desc->streams(), ssrc);
Steve Anton75737c02017-11-06 10:37:17 -0800528 if (found) {
529 *track_id = found->id;
530 return true;
531 }
532 }
533 return false;
534}
535
536// Get the SCTP port out of a SessionDescription.
537// Return -1 if not found.
538int GetSctpPort(const SessionDescription* session_description) {
Steve Antonb1c1de12017-12-21 15:14:30 -0800539 const cricket::DataContentDescription* data_desc =
540 GetFirstDataContentDescription(session_description);
541 RTC_DCHECK(data_desc);
542 if (!data_desc) {
Steve Anton75737c02017-11-06 10:37:17 -0800543 return -1;
544 }
Steve Anton75737c02017-11-06 10:37:17 -0800545 std::string value;
546 cricket::DataCodec match_pattern(cricket::kGoogleSctpDataCodecPlType,
547 cricket::kGoogleSctpDataCodecName);
Steve Antonb1c1de12017-12-21 15:14:30 -0800548 for (const cricket::DataCodec& codec : data_desc->codecs()) {
Steve Anton75737c02017-11-06 10:37:17 -0800549 if (!codec.Matches(match_pattern)) {
550 continue;
551 }
552 if (codec.GetParam(cricket::kCodecParamPort, &value)) {
553 return rtc::FromString<int>(value);
554 }
555 }
556 return -1;
557}
558
Steve Anton75737c02017-11-06 10:37:17 -0800559// Returns true if |new_desc| requests an ICE restart (i.e., new ufrag/pwd).
560bool CheckForRemoteIceRestart(const SessionDescriptionInterface* old_desc,
561 const SessionDescriptionInterface* new_desc,
562 const std::string& content_name) {
563 if (!old_desc) {
564 return false;
565 }
566 const SessionDescription* new_sd = new_desc->description();
567 const SessionDescription* old_sd = old_desc->description();
568 const ContentInfo* cinfo = new_sd->GetContentByName(content_name);
569 if (!cinfo || cinfo->rejected) {
570 return false;
571 }
572 // If the content isn't rejected, check if ufrag and password has changed.
573 const cricket::TransportDescription* new_transport_desc =
574 new_sd->GetTransportDescriptionByName(content_name);
575 const cricket::TransportDescription* old_transport_desc =
576 old_sd->GetTransportDescriptionByName(content_name);
577 if (!new_transport_desc || !old_transport_desc) {
578 // No transport description exists. This is not an ICE restart.
579 return false;
580 }
581 if (cricket::IceCredentialsChanged(
582 old_transport_desc->ice_ufrag, old_transport_desc->ice_pwd,
583 new_transport_desc->ice_ufrag, new_transport_desc->ice_pwd)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100584 RTC_LOG(LS_INFO) << "Remote peer requests ICE restart for " << content_name
585 << ".";
Steve Anton75737c02017-11-06 10:37:17 -0800586 return true;
587 }
588 return false;
589}
590
Steve Anton80dd7b52018-02-16 17:08:42 -0800591// Generates a string error message for SetLocalDescription/SetRemoteDescription
592// from an RTCError.
593std::string GetSetDescriptionErrorMessage(cricket::ContentSource source,
594 SdpType type,
595 const RTCError& error) {
596 std::ostringstream oss;
597 oss << "Failed to set " << (source == cricket::CS_LOCAL ? "local" : "remote")
598 << " " << SdpTypeToString(type) << " sdp: " << error.message();
599 return oss.str();
600}
601
Steve Anton75737c02017-11-06 10:37:17 -0800602} // namespace
603
Henrik Boström31638672017-11-23 17:48:32 +0100604// Upon completion, posts a task to execute the callback of the
605// SetSessionDescriptionObserver asynchronously on the same thread. At this
606// point, the state of the peer connection might no longer reflect the effects
607// of the SetRemoteDescription operation, as the peer connection could have been
608// modified during the post.
609// TODO(hbos): Remove this class once we remove the version of
610// PeerConnectionInterface::SetRemoteDescription() that takes a
611// SetSessionDescriptionObserver as an argument.
612class PeerConnection::SetRemoteDescriptionObserverAdapter
613 : public rtc::RefCountedObject<SetRemoteDescriptionObserverInterface> {
614 public:
615 SetRemoteDescriptionObserverAdapter(
616 rtc::scoped_refptr<PeerConnection> pc,
617 rtc::scoped_refptr<SetSessionDescriptionObserver> wrapper)
618 : pc_(std::move(pc)), wrapper_(std::move(wrapper)) {}
619
620 // SetRemoteDescriptionObserverInterface implementation.
621 void OnSetRemoteDescriptionComplete(RTCError error) override {
622 if (error.ok())
623 pc_->PostSetSessionDescriptionSuccess(wrapper_);
624 else
625 pc_->PostSetSessionDescriptionFailure(wrapper_, error.message());
626 }
627
628 private:
629 rtc::scoped_refptr<PeerConnection> pc_;
630 rtc::scoped_refptr<SetSessionDescriptionObserver> wrapper_;
631};
632
deadbeef293e9262017-01-11 12:28:30 -0800633bool PeerConnectionInterface::RTCConfiguration::operator==(
634 const PeerConnectionInterface::RTCConfiguration& o) const {
635 // This static_assert prevents us from accidentally breaking operator==.
Steve Anton300bf8e2017-07-14 10:13:10 -0700636 // Note: Order matters! Fields must be ordered the same as RTCConfiguration.
deadbeef293e9262017-01-11 12:28:30 -0800637 struct stuff_being_tested_for_equality {
Magnus Jedvert3beb2072017-07-14 14:23:56 +0000638 IceServers servers;
Steve Anton300bf8e2017-07-14 10:13:10 -0700639 IceTransportsType type;
deadbeef293e9262017-01-11 12:28:30 -0800640 BundlePolicy bundle_policy;
641 RtcpMuxPolicy rtcp_mux_policy;
Steve Anton300bf8e2017-07-14 10:13:10 -0700642 std::vector<rtc::scoped_refptr<rtc::RTCCertificate>> certificates;
643 int ice_candidate_pool_size;
644 bool disable_ipv6;
645 bool disable_ipv6_on_wifi;
deadbeefd21eab32017-07-26 16:50:11 -0700646 int max_ipv6_networks;
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +0100647 bool disable_link_local_networks;
Steve Anton300bf8e2017-07-14 10:13:10 -0700648 bool enable_rtp_data_channel;
649 rtc::Optional<int> screencast_min_bitrate;
650 rtc::Optional<bool> combined_audio_video_bwe;
651 rtc::Optional<bool> enable_dtls_srtp;
deadbeef293e9262017-01-11 12:28:30 -0800652 TcpCandidatePolicy tcp_candidate_policy;
653 CandidateNetworkPolicy candidate_network_policy;
654 int audio_jitter_buffer_max_packets;
655 bool audio_jitter_buffer_fast_accelerate;
656 int ice_connection_receiving_timeout;
657 int ice_backup_candidate_pair_ping_interval;
658 ContinualGatheringPolicy continual_gathering_policy;
deadbeef293e9262017-01-11 12:28:30 -0800659 bool prioritize_most_likely_ice_candidate_pairs;
660 struct cricket::MediaConfig media_config;
deadbeef293e9262017-01-11 12:28:30 -0800661 bool prune_turn_ports;
662 bool presume_writable_when_fully_relayed;
663 bool enable_ice_renomination;
664 bool redetermine_role_on_ice_restart;
skvlad51072462017-02-02 11:50:14 -0800665 rtc::Optional<int> ice_check_min_interval;
Qingsi Wangdb53f8e2018-02-20 14:45:49 -0800666 rtc::Optional<int> stun_candidate_keepalive_interval;
Steve Anton300bf8e2017-07-14 10:13:10 -0700667 rtc::Optional<rtc::IntervalRange> ice_regather_interval_range;
Jonas Orelandbdcee282017-10-10 14:01:40 +0200668 webrtc::TurnCustomizer* turn_customizer;
Steve Anton79e79602017-11-20 10:25:56 -0800669 SdpSemantics sdp_semantics;
Qingsi Wang9a5c6f82018-02-01 10:38:40 -0800670 rtc::Optional<rtc::AdapterType> network_preference;
deadbeef293e9262017-01-11 12:28:30 -0800671 };
672 static_assert(sizeof(stuff_being_tested_for_equality) == sizeof(*this),
673 "Did you add something to RTCConfiguration and forget to "
674 "update operator==?");
675 return type == o.type && servers == o.servers &&
676 bundle_policy == o.bundle_policy &&
677 rtcp_mux_policy == o.rtcp_mux_policy &&
678 tcp_candidate_policy == o.tcp_candidate_policy &&
679 candidate_network_policy == o.candidate_network_policy &&
680 audio_jitter_buffer_max_packets == o.audio_jitter_buffer_max_packets &&
681 audio_jitter_buffer_fast_accelerate ==
682 o.audio_jitter_buffer_fast_accelerate &&
683 ice_connection_receiving_timeout ==
684 o.ice_connection_receiving_timeout &&
685 ice_backup_candidate_pair_ping_interval ==
686 o.ice_backup_candidate_pair_ping_interval &&
687 continual_gathering_policy == o.continual_gathering_policy &&
688 certificates == o.certificates &&
689 prioritize_most_likely_ice_candidate_pairs ==
690 o.prioritize_most_likely_ice_candidate_pairs &&
691 media_config == o.media_config && disable_ipv6 == o.disable_ipv6 &&
zhihuangb09b3f92017-03-07 14:40:51 -0800692 disable_ipv6_on_wifi == o.disable_ipv6_on_wifi &&
deadbeefd21eab32017-07-26 16:50:11 -0700693 max_ipv6_networks == o.max_ipv6_networks &&
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +0100694 disable_link_local_networks == o.disable_link_local_networks &&
deadbeef293e9262017-01-11 12:28:30 -0800695 enable_rtp_data_channel == o.enable_rtp_data_channel &&
deadbeef293e9262017-01-11 12:28:30 -0800696 screencast_min_bitrate == o.screencast_min_bitrate &&
697 combined_audio_video_bwe == o.combined_audio_video_bwe &&
698 enable_dtls_srtp == o.enable_dtls_srtp &&
699 ice_candidate_pool_size == o.ice_candidate_pool_size &&
700 prune_turn_ports == o.prune_turn_ports &&
701 presume_writable_when_fully_relayed ==
702 o.presume_writable_when_fully_relayed &&
703 enable_ice_renomination == o.enable_ice_renomination &&
skvlad51072462017-02-02 11:50:14 -0800704 redetermine_role_on_ice_restart == o.redetermine_role_on_ice_restart &&
Steve Anton300bf8e2017-07-14 10:13:10 -0700705 ice_check_min_interval == o.ice_check_min_interval &&
Qingsi Wangdb53f8e2018-02-20 14:45:49 -0800706 stun_candidate_keepalive_interval ==
707 o.stun_candidate_keepalive_interval &&
Jonas Orelandbdcee282017-10-10 14:01:40 +0200708 ice_regather_interval_range == o.ice_regather_interval_range &&
Steve Anton79e79602017-11-20 10:25:56 -0800709 turn_customizer == o.turn_customizer &&
Qingsi Wang9a5c6f82018-02-01 10:38:40 -0800710 sdp_semantics == o.sdp_semantics &&
711 network_preference == o.network_preference;
deadbeef293e9262017-01-11 12:28:30 -0800712}
713
714bool PeerConnectionInterface::RTCConfiguration::operator!=(
715 const PeerConnectionInterface::RTCConfiguration& o) const {
716 return !(*this == o);
deadbeef3edec7c2016-12-10 11:44:26 -0800717}
718
zhihuang8f65cdf2016-05-06 18:40:30 -0700719// Generate a RTCP CNAME when a PeerConnection is created.
720std::string GenerateRtcpCname() {
721 std::string cname;
722 if (!rtc::CreateRandomString(kRtcpCnameLength, &cname)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100723 RTC_LOG(LS_ERROR) << "Failed to generate CNAME.";
nisseeb4ca4e2017-01-12 02:24:27 -0800724 RTC_NOTREACHED();
zhihuang8f65cdf2016-05-06 18:40:30 -0700725 }
726 return cname;
727}
728
zhihuang1c378ed2017-08-17 14:10:50 -0700729bool ValidateOfferAnswerOptions(
730 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options) {
731 return IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_audio) &&
732 IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_video);
olka3c747662017-08-17 06:50:32 -0700733}
734
zhihuang1c378ed2017-08-17 14:10:50 -0700735// From |rtc_options|, fill parts of |session_options| shared by all generated
736// m= sections (in other words, nothing that involves a map/array).
737void ExtractSharedMediaSessionOptions(
738 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options,
739 cricket::MediaSessionOptions* session_options) {
740 session_options->vad_enabled = rtc_options.voice_activity_detection;
741 session_options->bundle_enabled = rtc_options.use_rtp_mux;
742}
zhihuanga77e6bb2017-08-14 18:17:48 -0700743
zhihuang1c378ed2017-08-17 14:10:50 -0700744bool ConvertConstraintsToOfferAnswerOptions(
745 const MediaConstraintsInterface* constraints,
746 PeerConnectionInterface::RTCOfferAnswerOptions* offer_answer_options) {
olka3c747662017-08-17 06:50:32 -0700747 if (!constraints) {
748 return true;
749 }
zhihuang1c378ed2017-08-17 14:10:50 -0700750
751 bool value = false;
752 size_t mandatory_constraints_satisfied = 0;
753
754 if (FindConstraint(constraints,
755 MediaConstraintsInterface::kOfferToReceiveAudio, &value,
756 &mandatory_constraints_satisfied)) {
757 offer_answer_options->offer_to_receive_audio =
758 value ? PeerConnectionInterface::RTCOfferAnswerOptions::
759 kOfferToReceiveMediaTrue
760 : 0;
761 }
762
763 if (FindConstraint(constraints,
764 MediaConstraintsInterface::kOfferToReceiveVideo, &value,
765 &mandatory_constraints_satisfied)) {
766 offer_answer_options->offer_to_receive_video =
767 value ? PeerConnectionInterface::RTCOfferAnswerOptions::
768 kOfferToReceiveMediaTrue
769 : 0;
770 }
771 if (FindConstraint(constraints,
772 MediaConstraintsInterface::kVoiceActivityDetection, &value,
773 &mandatory_constraints_satisfied)) {
774 offer_answer_options->voice_activity_detection = value;
775 }
776 if (FindConstraint(constraints, MediaConstraintsInterface::kUseRtpMux, &value,
777 &mandatory_constraints_satisfied)) {
778 offer_answer_options->use_rtp_mux = value;
779 }
780 if (FindConstraint(constraints, MediaConstraintsInterface::kIceRestart,
781 &value, &mandatory_constraints_satisfied)) {
782 offer_answer_options->ice_restart = value;
783 }
784
deadbeefab9b2d12015-10-14 11:33:11 -0700785 return mandatory_constraints_satisfied == constraints->GetMandatory().size();
786}
787
zhihuang38ede132017-06-15 12:52:32 -0700788PeerConnection::PeerConnection(PeerConnectionFactory* factory,
789 std::unique_ptr<RtcEventLog> event_log,
790 std::unique_ptr<Call> call)
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000791 : factory_(factory),
zhihuang38ede132017-06-15 12:52:32 -0700792 event_log_(std::move(event_log)),
zhihuang8f65cdf2016-05-06 18:40:30 -0700793 rtcp_cname_(GenerateRtcpCname()),
deadbeefab9b2d12015-10-14 11:33:11 -0700794 local_streams_(StreamCollection::Create()),
zhihuang38ede132017-06-15 12:52:32 -0700795 remote_streams_(StreamCollection::Create()),
796 call_(std::move(call)) {}
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000797
798PeerConnection::~PeerConnection() {
Peter Boström1a9d6152015-12-08 22:15:17 +0100799 TRACE_EVENT0("webrtc", "PeerConnection::~PeerConnection");
Steve Anton4171afb2017-11-20 10:20:22 -0800800 RTC_DCHECK_RUN_ON(signaling_thread());
801
Steve Anton8af21862017-12-15 11:20:13 -0800802 // Need to stop transceivers before destroying the stats collector because
803 // AudioRtpSender has a reference to the StatsCollector it will update when
804 // stopping.
805 for (auto transceiver : transceivers_) {
806 transceiver->Stop();
807 }
Steve Anton4171afb2017-11-20 10:20:22 -0800808
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700809 stats_.reset(nullptr);
hbosb78306a2016-12-19 05:06:57 -0800810 if (stats_collector_) {
811 stats_collector_->WaitForPendingRequest();
812 stats_collector_ = nullptr;
813 }
Steve Anton75737c02017-11-06 10:37:17 -0800814
Steve Anton8af21862017-12-15 11:20:13 -0800815 // Don't destroy BaseChannels until after stats has been cleaned up so that
816 // the last stats request can still read from the channels.
817 DestroyAllChannels();
818
Mirko Bonadei675513b2017-11-09 11:09:25 +0100819 RTC_LOG(LS_INFO) << "Session: " << session_id() << " is destroyed.";
Steve Anton75737c02017-11-06 10:37:17 -0800820
821 webrtc_session_desc_factory_.reset();
822 sctp_invoker_.reset();
823 sctp_factory_.reset();
824 transport_controller_.reset();
825
deadbeef91dd5672016-05-18 16:55:30 -0700826 // port_allocator_ lives on the network thread and should be destroyed there.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700827 network_thread()->Invoke<void>(RTC_FROM_HERE,
nisseeaabdf62017-05-05 02:23:02 -0700828 [this] { port_allocator_.reset(); });
eladalon248fd4f2017-09-06 05:18:15 -0700829 // call_ and event_log_ must be destroyed on the worker thread.
Steve Anton978b8762017-09-29 12:15:02 -0700830 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
eladalon248fd4f2017-09-06 05:18:15 -0700831 call_.reset();
Qingsi Wang93a84392018-01-30 17:13:09 -0800832 // The event log must outlive call (and any other object that uses it).
eladalon248fd4f2017-09-06 05:18:15 -0700833 event_log_.reset();
834 });
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000835}
836
Steve Anton8af21862017-12-15 11:20:13 -0800837void PeerConnection::DestroyAllChannels() {
Steve Anton3fe1b152017-12-12 10:20:08 -0800838 // Destroy video channels first since they may have a pointer to a voice
839 // channel.
840 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -0800841 if (transceiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton3fe1b152017-12-12 10:20:08 -0800842 DestroyTransceiverChannel(transceiver);
843 }
844 }
845 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -0800846 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton3fe1b152017-12-12 10:20:08 -0800847 DestroyTransceiverChannel(transceiver);
848 }
849 }
850 DestroyDataChannel();
851}
852
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000853bool PeerConnection::Initialize(
buildbot@webrtc.org41451d42014-05-03 05:39:45 +0000854 const PeerConnectionInterface::RTCConfiguration& configuration,
kwibergd1fe2812016-04-27 06:47:29 -0700855 std::unique_ptr<cricket::PortAllocator> allocator,
Henrik Boströmd03c23b2016-06-01 11:44:18 +0200856 std::unique_ptr<rtc::RTCCertificateGeneratorInterface> cert_generator,
deadbeef653b8e02015-11-11 12:55:10 -0800857 PeerConnectionObserver* observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100858 TRACE_EVENT0("webrtc", "PeerConnection::Initialize");
Steve Anton038834f2017-07-14 15:59:59 -0700859
860 RTCError config_error = ValidateConfiguration(configuration);
861 if (!config_error.ok()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100862 RTC_LOG(LS_ERROR) << "Invalid configuration: " << config_error.message();
Steve Anton038834f2017-07-14 15:59:59 -0700863 return false;
864 }
865
deadbeef293e9262017-01-11 12:28:30 -0800866 if (!allocator) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100867 RTC_LOG(LS_ERROR)
868 << "PeerConnection initialized without a PortAllocator? "
Jonas Olsson45cc8902018-02-13 10:37:07 +0100869 "This shouldn't happen if using PeerConnectionFactory.";
deadbeef293e9262017-01-11 12:28:30 -0800870 return false;
871 }
Jonas Orelandbdcee282017-10-10 14:01:40 +0200872
deadbeef653b8e02015-11-11 12:55:10 -0800873 if (!observer) {
deadbeef293e9262017-01-11 12:28:30 -0800874 // TODO(deadbeef): Why do we do this?
Mirko Bonadei675513b2017-11-09 11:09:25 +0100875 RTC_LOG(LS_ERROR) << "PeerConnection initialized without a "
Jonas Olsson45cc8902018-02-13 10:37:07 +0100876 "PeerConnectionObserver";
deadbeef653b8e02015-11-11 12:55:10 -0800877 return false;
878 }
pthatcher@webrtc.org877ac762015-02-04 22:03:09 +0000879 observer_ = observer;
kwiberg0eb15ed2015-12-17 03:04:15 -0800880 port_allocator_ = std::move(allocator);
deadbeef653b8e02015-11-11 12:55:10 -0800881
deadbeef91dd5672016-05-18 16:55:30 -0700882 // The port allocator lives on the network thread and should be initialized
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700883 // there.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700884 if (!network_thread()->Invoke<bool>(
885 RTC_FROM_HERE, rtc::Bind(&PeerConnection::InitializePortAllocator_n,
886 this, configuration))) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000887 return false;
888 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000889
Steve Anton75737c02017-11-06 10:37:17 -0800890 // RFC 3264: The numeric value of the session id and version in the
891 // o line MUST be representable with a "64 bit signed integer".
892 // Due to this constraint session id |session_id_| is max limited to
893 // LLONG_MAX.
894 session_id_ = rtc::ToString(rtc::CreateRandomId64() & LLONG_MAX);
895 transport_controller_.reset(factory_->CreateTransportController(
Qingsi Wang93a84392018-01-30 17:13:09 -0800896 port_allocator_.get(), configuration.redetermine_role_on_ice_restart,
897 event_log_.get()));
Steve Anton75737c02017-11-06 10:37:17 -0800898 transport_controller_->SetIceRole(cricket::ICEROLE_CONTROLLED);
899 transport_controller_->SignalConnectionState.connect(
900 this, &PeerConnection::OnTransportControllerConnectionState);
901 transport_controller_->SignalGatheringState.connect(
902 this, &PeerConnection::OnTransportControllerGatheringState);
903 transport_controller_->SignalCandidatesGathered.connect(
904 this, &PeerConnection::OnTransportControllerCandidatesGathered);
905 transport_controller_->SignalCandidatesRemoved.connect(
906 this, &PeerConnection::OnTransportControllerCandidatesRemoved);
907 transport_controller_->SignalDtlsHandshakeError.connect(
908 this, &PeerConnection::OnTransportControllerDtlsHandshakeError);
909
910 sctp_factory_ = factory_->CreateSctpTransportInternalFactory();
zhihuang29ff8442016-07-27 11:07:25 -0700911
deadbeefab9b2d12015-10-14 11:33:11 -0700912 stats_.reset(new StatsCollector(this));
hbos74e1a4f2016-09-15 23:33:01 -0700913 stats_collector_ = RTCStatsCollector::Create(this);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000914
Steve Antonba818672017-11-06 10:21:57 -0800915 configuration_ = configuration;
916
Steve Anton75737c02017-11-06 10:37:17 -0800917 const PeerConnectionFactoryInterface::Options& options = factory_->options();
918
919 transport_controller_->SetSslMaxProtocolVersion(options.ssl_max_version);
920
921 // Obtain a certificate from RTCConfiguration if any were provided (optional).
922 rtc::scoped_refptr<rtc::RTCCertificate> certificate;
923 if (!configuration.certificates.empty()) {
924 // TODO(hbos,torbjorng): Decide on certificate-selection strategy instead of
925 // just picking the first one. The decision should be made based on the DTLS
926 // handshake. The DTLS negotiations need to know about all certificates.
927 certificate = configuration.certificates[0];
928 }
929
Steve Antond25da372017-11-06 14:50:29 -0800930 transport_controller_->SetIceConfig(ParseIceConfig(configuration));
Steve Anton75737c02017-11-06 10:37:17 -0800931
932 if (options.disable_encryption) {
933 dtls_enabled_ = false;
934 } else {
935 // Enable DTLS by default if we have an identity store or a certificate.
936 dtls_enabled_ = (cert_generator || certificate);
937 // |configuration| can override the default |dtls_enabled_| value.
938 if (configuration.enable_dtls_srtp) {
939 dtls_enabled_ = *(configuration.enable_dtls_srtp);
940 }
941 }
942
943 // Enable creation of RTP data channels if the kEnableRtpDataChannels is set.
944 // It takes precendence over the disable_sctp_data_channels
945 // PeerConnectionFactoryInterface::Options.
946 if (configuration.enable_rtp_data_channel) {
947 data_channel_type_ = cricket::DCT_RTP;
948 } else {
949 // DTLS has to be enabled to use SCTP.
950 if (!options.disable_sctp_data_channels && dtls_enabled_) {
951 data_channel_type_ = cricket::DCT_SCTP;
952 }
953 }
954
955 video_options_.screencast_min_bitrate_kbps =
956 configuration.screencast_min_bitrate;
957 audio_options_.combined_audio_video_bwe =
958 configuration.combined_audio_video_bwe;
959
960 audio_options_.audio_jitter_buffer_max_packets =
Oskar Sundbom9b28a032017-11-16 10:53:30 +0100961 configuration.audio_jitter_buffer_max_packets;
Steve Anton75737c02017-11-06 10:37:17 -0800962
963 audio_options_.audio_jitter_buffer_fast_accelerate =
Oskar Sundbom9b28a032017-11-16 10:53:30 +0100964 configuration.audio_jitter_buffer_fast_accelerate;
Steve Anton75737c02017-11-06 10:37:17 -0800965
966 // Whether the certificate generator/certificate is null or not determines
967 // what PeerConnectionDescriptionFactory will do, so make sure that we give it
968 // the right instructions by clearing the variables if needed.
969 if (!dtls_enabled_) {
970 cert_generator.reset();
971 certificate = nullptr;
972 } else if (certificate) {
973 // Favor generated certificate over the certificate generator.
974 cert_generator.reset();
975 }
976
977 webrtc_session_desc_factory_.reset(new WebRtcSessionDescriptionFactory(
978 signaling_thread(), channel_manager(), this, session_id(),
979 std::move(cert_generator), certificate));
980 webrtc_session_desc_factory_->SignalCertificateReady.connect(
981 this, &PeerConnection::OnCertificateReady);
982
983 if (options.disable_encryption) {
984 webrtc_session_desc_factory_->SetSdesPolicy(cricket::SEC_DISABLED);
985 }
986
987 webrtc_session_desc_factory_->set_enable_encrypted_rtp_header_extensions(
988 options.crypto_options.enable_encrypted_rtp_header_extensions);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000989
Steve Anton4171afb2017-11-20 10:20:22 -0800990 // Add default audio/video transceivers for Plan B SDP.
991 if (!IsUnifiedPlan()) {
992 transceivers_.push_back(
993 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
994 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_AUDIO)));
995 transceivers_.push_back(
996 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
997 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_VIDEO)));
998 }
999
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001000 return true;
1001}
1002
Steve Anton038834f2017-07-14 15:59:59 -07001003RTCError PeerConnection::ValidateConfiguration(
1004 const RTCConfiguration& config) const {
1005 if (config.ice_regather_interval_range &&
1006 config.continual_gathering_policy == GATHER_ONCE) {
1007 return RTCError(RTCErrorType::INVALID_PARAMETER,
1008 "ice_regather_interval_range specified but continual "
1009 "gathering policy is GATHER_ONCE");
1010 }
1011 return RTCError::OK();
1012}
1013
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001014rtc::scoped_refptr<StreamCollectionInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001015PeerConnection::local_streams() {
Steve Antonfc853712018-03-01 13:48:58 -08001016 RTC_CHECK(!IsUnifiedPlan()) << "local_streams is not available with Unified "
1017 "Plan SdpSemantics. Please use GetSenders "
1018 "instead.";
deadbeefab9b2d12015-10-14 11:33:11 -07001019 return local_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001020}
1021
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001022rtc::scoped_refptr<StreamCollectionInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001023PeerConnection::remote_streams() {
Steve Antonfc853712018-03-01 13:48:58 -08001024 RTC_CHECK(!IsUnifiedPlan()) << "remote_streams is not available with Unified "
1025 "Plan SdpSemantics. Please use GetReceivers "
1026 "instead.";
deadbeefab9b2d12015-10-14 11:33:11 -07001027 return remote_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001028}
1029
perkj@webrtc.orgc2dd5ee2014-11-04 11:31:29 +00001030bool PeerConnection::AddStream(MediaStreamInterface* local_stream) {
Steve Antonfc853712018-03-01 13:48:58 -08001031 RTC_CHECK(!IsUnifiedPlan()) << "AddStream is not available with Unified Plan "
1032 "SdpSemantics. Please use AddTrack instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001033 TRACE_EVENT0("webrtc", "PeerConnection::AddStream");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001034 if (IsClosed()) {
1035 return false;
1036 }
deadbeefab9b2d12015-10-14 11:33:11 -07001037 if (!CanAddLocalMediaStream(local_streams_, local_stream)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001038 return false;
1039 }
deadbeefab9b2d12015-10-14 11:33:11 -07001040
1041 local_streams_->AddStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -08001042 MediaStreamObserver* observer = new MediaStreamObserver(local_stream);
1043 observer->SignalAudioTrackAdded.connect(this,
1044 &PeerConnection::OnAudioTrackAdded);
1045 observer->SignalAudioTrackRemoved.connect(
1046 this, &PeerConnection::OnAudioTrackRemoved);
1047 observer->SignalVideoTrackAdded.connect(this,
1048 &PeerConnection::OnVideoTrackAdded);
1049 observer->SignalVideoTrackRemoved.connect(
1050 this, &PeerConnection::OnVideoTrackRemoved);
kwibergd1fe2812016-04-27 06:47:29 -07001051 stream_observers_.push_back(std::unique_ptr<MediaStreamObserver>(observer));
deadbeefab9b2d12015-10-14 11:33:11 -07001052
deadbeefab9b2d12015-10-14 11:33:11 -07001053 for (const auto& track : local_stream->GetAudioTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001054 AddAudioTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -07001055 }
1056 for (const auto& track : local_stream->GetVideoTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001057 AddVideoTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -07001058 }
1059
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001060 stats_->AddStream(local_stream);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001061 observer_->OnRenegotiationNeeded();
1062 return true;
1063}
1064
1065void PeerConnection::RemoveStream(MediaStreamInterface* local_stream) {
Steve Antonfc853712018-03-01 13:48:58 -08001066 RTC_CHECK(!IsUnifiedPlan()) << "RemoveStream is not available with Unified "
1067 "Plan SdpSemantics. Please use RemoveTrack "
1068 "instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001069 TRACE_EVENT0("webrtc", "PeerConnection::RemoveStream");
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001070 if (!IsClosed()) {
1071 for (const auto& track : local_stream->GetAudioTracks()) {
1072 RemoveAudioTrack(track.get(), local_stream);
1073 }
1074 for (const auto& track : local_stream->GetVideoTracks()) {
1075 RemoveVideoTrack(track.get(), local_stream);
1076 }
deadbeefab9b2d12015-10-14 11:33:11 -07001077 }
deadbeefab9b2d12015-10-14 11:33:11 -07001078 local_streams_->RemoveStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -08001079 stream_observers_.erase(
1080 std::remove_if(
1081 stream_observers_.begin(), stream_observers_.end(),
kwibergd1fe2812016-04-27 06:47:29 -07001082 [local_stream](const std::unique_ptr<MediaStreamObserver>& observer) {
deadbeefeb459812015-12-15 19:24:43 -08001083 return observer->stream()->label().compare(local_stream->label()) ==
1084 0;
1085 }),
1086 stream_observers_.end());
deadbeefab9b2d12015-10-14 11:33:11 -07001087
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001088 if (IsClosed()) {
1089 return;
1090 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001091 observer_->OnRenegotiationNeeded();
1092}
1093
deadbeefe1f9d832016-01-14 15:35:42 -08001094rtc::scoped_refptr<RtpSenderInterface> PeerConnection::AddTrack(
1095 MediaStreamTrackInterface* track,
1096 std::vector<MediaStreamInterface*> streams) {
1097 TRACE_EVENT0("webrtc", "PeerConnection::AddTrack");
Seth Hampson845e8782018-03-02 11:34:10 -08001098 std::vector<std::string> stream_ids;
Steve Antonf9381f02017-12-14 10:23:57 -08001099 for (auto* stream : streams) {
1100 if (!stream) {
1101 RTC_LOG(LS_ERROR) << "Stream list has null element.";
1102 return nullptr;
1103 }
Seth Hampson845e8782018-03-02 11:34:10 -08001104 stream_ids.push_back(stream->label());
Steve Antonf9381f02017-12-14 10:23:57 -08001105 }
Seth Hampson845e8782018-03-02 11:34:10 -08001106 auto sender_or_error = AddTrack(track, stream_ids);
Steve Antonf9381f02017-12-14 10:23:57 -08001107 if (!sender_or_error.ok()) {
deadbeefe1f9d832016-01-14 15:35:42 -08001108 return nullptr;
1109 }
Steve Antonf9381f02017-12-14 10:23:57 -08001110 return sender_or_error.MoveValue();
1111}
1112
Steve Anton2d6c76a2018-01-05 17:10:52 -08001113RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::AddTrack(
Steve Antonf9381f02017-12-14 10:23:57 -08001114 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001115 const std::vector<std::string>& stream_ids) {
Steve Anton2d6c76a2018-01-05 17:10:52 -08001116 TRACE_EVENT0("webrtc", "PeerConnection::AddTrack");
Steve Antonf9381f02017-12-14 10:23:57 -08001117 if (!track) {
1118 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "Track is null.");
1119 }
1120 if (!(track->kind() == MediaStreamTrackInterface::kAudioKind ||
1121 track->kind() == MediaStreamTrackInterface::kVideoKind)) {
1122 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1123 "Track has invalid kind: " + track->kind());
1124 }
1125 // TODO(bugs.webrtc.org/7932): Support adding a track to multiple streams.
Seth Hampson845e8782018-03-02 11:34:10 -08001126 if (stream_ids.size() > 1u) {
Steve Antonf9381f02017-12-14 10:23:57 -08001127 LOG_AND_RETURN_ERROR(
1128 RTCErrorType::UNSUPPORTED_OPERATION,
1129 "AddTrack with more than one stream is not currently supported.");
1130 }
1131 if (IsClosed()) {
1132 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
1133 "PeerConnection is closed.");
deadbeefe1f9d832016-01-14 15:35:42 -08001134 }
Steve Anton4171afb2017-11-20 10:20:22 -08001135 if (FindSenderForTrack(track)) {
Steve Antonf9381f02017-12-14 10:23:57 -08001136 LOG_AND_RETURN_ERROR(
1137 RTCErrorType::INVALID_PARAMETER,
1138 "Sender already exists for track " + track->id() + ".");
deadbeefe1f9d832016-01-14 15:35:42 -08001139 }
Steve Antonf9381f02017-12-14 10:23:57 -08001140 // TODO(bugs.webrtc.org/7933): MediaSession expects the sender to have exactly
1141 // one stream. AddTrackInternal will return an error if there is more than one
1142 // stream, but if the caller specifies none then we need to generate a random
Seth Hampson845e8782018-03-02 11:34:10 -08001143 // stream id.
1144 std::vector<std::string> adjusted_stream_ids = stream_ids;
1145 if (stream_ids.empty()) {
1146 adjusted_stream_ids.push_back(rtc::CreateRandomUuid());
Steve Antonf9381f02017-12-14 10:23:57 -08001147 }
Seth Hampson845e8782018-03-02 11:34:10 -08001148 RTC_DCHECK_EQ(1, adjusted_stream_ids.size());
Steve Antonf9381f02017-12-14 10:23:57 -08001149 auto sender_or_error =
Seth Hampson845e8782018-03-02 11:34:10 -08001150 (IsUnifiedPlan() ? AddTrackUnifiedPlan(track, adjusted_stream_ids)
1151 : AddTrackPlanB(track, adjusted_stream_ids));
Steve Antonf9381f02017-12-14 10:23:57 -08001152 if (sender_or_error.ok()) {
1153 observer_->OnRenegotiationNeeded();
Steve Anton43a723a2018-01-04 15:48:17 -08001154 stats_->AddTrack(track);
Steve Antonf9381f02017-12-14 10:23:57 -08001155 }
1156 return sender_or_error;
1157}
deadbeefe1f9d832016-01-14 15:35:42 -08001158
Steve Antonf9381f02017-12-14 10:23:57 -08001159RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>>
1160PeerConnection::AddTrackPlanB(
1161 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001162 const std::vector<std::string>& stream_ids) {
Steve Anton02ee47c2018-01-10 16:26:06 -08001163 cricket::MediaType media_type =
1164 (track->kind() == MediaStreamTrackInterface::kAudioKind
1165 ? cricket::MEDIA_TYPE_AUDIO
1166 : cricket::MEDIA_TYPE_VIDEO);
Seth Hampson845e8782018-03-02 11:34:10 -08001167 auto new_sender = CreateSender(media_type, track, stream_ids);
deadbeefe1f9d832016-01-14 15:35:42 -08001168 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
Steve Anton57858b32018-02-15 15:19:50 -08001169 new_sender->internal()->SetVoiceMediaChannel(voice_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08001170 GetAudioTransceiver()->internal()->AddSender(new_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001171 const RtpSenderInfo* sender_info =
1172 FindSenderInfo(local_audio_sender_infos_,
1173 new_sender->internal()->stream_id(), track->id());
1174 if (sender_info) {
1175 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -08001176 }
Steve Antonf9381f02017-12-14 10:23:57 -08001177 } else {
1178 RTC_DCHECK_EQ(MediaStreamTrackInterface::kVideoKind, track->kind());
Steve Anton57858b32018-02-15 15:19:50 -08001179 new_sender->internal()->SetVideoMediaChannel(video_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08001180 GetVideoTransceiver()->internal()->AddSender(new_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001181 const RtpSenderInfo* sender_info =
1182 FindSenderInfo(local_video_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 }
deadbeefe1f9d832016-01-14 15:35:42 -08001187 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001188 return rtc::scoped_refptr<RtpSenderInterface>(new_sender);
Steve Antonf9381f02017-12-14 10:23:57 -08001189}
deadbeefe1f9d832016-01-14 15:35:42 -08001190
Steve Antonf9381f02017-12-14 10:23:57 -08001191RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>>
1192PeerConnection::AddTrackUnifiedPlan(
1193 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001194 const std::vector<std::string>& stream_ids) {
Steve Antonf9381f02017-12-14 10:23:57 -08001195 auto transceiver = FindFirstTransceiverForAddedTrack(track);
1196 if (transceiver) {
1197 if (transceiver->direction() == RtpTransceiverDirection::kRecvOnly) {
Steve Anton52d86772018-02-20 15:48:12 -08001198 transceiver->internal()->set_direction(
1199 RtpTransceiverDirection::kSendRecv);
Steve Antonf9381f02017-12-14 10:23:57 -08001200 } else if (transceiver->direction() == RtpTransceiverDirection::kInactive) {
Steve Anton52d86772018-02-20 15:48:12 -08001201 transceiver->internal()->set_direction(
1202 RtpTransceiverDirection::kSendOnly);
Steve Antonf9381f02017-12-14 10:23:57 -08001203 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001204 transceiver->sender()->SetTrack(track);
Seth Hampson845e8782018-03-02 11:34:10 -08001205 transceiver->internal()->sender_internal()->set_stream_ids(stream_ids);
Steve Antonf9381f02017-12-14 10:23:57 -08001206 } else {
1207 cricket::MediaType media_type =
1208 (track->kind() == MediaStreamTrackInterface::kAudioKind
1209 ? cricket::MEDIA_TYPE_AUDIO
1210 : cricket::MEDIA_TYPE_VIDEO);
Seth Hampson845e8782018-03-02 11:34:10 -08001211 auto sender = CreateSender(media_type, track, stream_ids);
Steve Anton02ee47c2018-01-10 16:26:06 -08001212 auto receiver = CreateReceiver(media_type, rtc::CreateRandomUuid());
1213 transceiver = CreateAndAddTransceiver(sender, receiver);
Steve Antonf9381f02017-12-14 10:23:57 -08001214 transceiver->internal()->set_created_by_addtrack(true);
Steve Anton52d86772018-02-20 15:48:12 -08001215 transceiver->internal()->set_direction(RtpTransceiverDirection::kSendRecv);
Steve Antonf9381f02017-12-14 10:23:57 -08001216 }
Steve Antonf9381f02017-12-14 10:23:57 -08001217 return transceiver->sender();
1218}
1219
1220rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1221PeerConnection::FindFirstTransceiverForAddedTrack(
1222 rtc::scoped_refptr<MediaStreamTrackInterface> track) {
1223 RTC_DCHECK(track);
1224 for (auto transceiver : transceivers_) {
1225 if (!transceiver->sender()->track() &&
Steve Anton69470252018-02-09 11:43:08 -08001226 cricket::MediaTypeToString(transceiver->media_type()) ==
Steve Antonf9381f02017-12-14 10:23:57 -08001227 track->kind() &&
Seth Hampson2f0d7022018-02-20 11:54:42 -08001228 !transceiver->internal()->has_ever_been_used_to_send() &&
1229 !transceiver->stopped()) {
Steve Antonf9381f02017-12-14 10:23:57 -08001230 return transceiver;
1231 }
1232 }
1233 return nullptr;
deadbeefe1f9d832016-01-14 15:35:42 -08001234}
1235
1236bool PeerConnection::RemoveTrack(RtpSenderInterface* sender) {
1237 TRACE_EVENT0("webrtc", "PeerConnection::RemoveTrack");
Steve Antonf9381f02017-12-14 10:23:57 -08001238 return RemoveTrackInternal(sender).ok();
1239}
1240
1241RTCError PeerConnection::RemoveTrackInternal(
1242 rtc::scoped_refptr<RtpSenderInterface> sender) {
1243 if (!sender) {
1244 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "Sender is null.");
1245 }
deadbeefe1f9d832016-01-14 15:35:42 -08001246 if (IsClosed()) {
Steve Antonf9381f02017-12-14 10:23:57 -08001247 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
1248 "PeerConnection is closed.");
deadbeefe1f9d832016-01-14 15:35:42 -08001249 }
Steve Antonf9381f02017-12-14 10:23:57 -08001250 if (IsUnifiedPlan()) {
1251 auto transceiver = FindTransceiverBySender(sender);
1252 if (!transceiver || !sender->track()) {
1253 return RTCError::OK();
1254 }
1255 sender->SetTrack(nullptr);
1256 if (transceiver->direction() == RtpTransceiverDirection::kSendRecv) {
Steve Anton52d86772018-02-20 15:48:12 -08001257 transceiver->internal()->set_direction(
1258 RtpTransceiverDirection::kRecvOnly);
Steve Antonf9381f02017-12-14 10:23:57 -08001259 } else if (transceiver->direction() == RtpTransceiverDirection::kSendOnly) {
Steve Anton52d86772018-02-20 15:48:12 -08001260 transceiver->internal()->set_direction(
1261 RtpTransceiverDirection::kInactive);
Steve Antonf9381f02017-12-14 10:23:57 -08001262 }
Steve Anton4171afb2017-11-20 10:20:22 -08001263 } else {
Steve Antonf9381f02017-12-14 10:23:57 -08001264 bool removed;
1265 if (sender->media_type() == cricket::MEDIA_TYPE_AUDIO) {
1266 removed = GetAudioTransceiver()->internal()->RemoveSender(sender);
1267 } else {
1268 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, sender->media_type());
1269 removed = GetVideoTransceiver()->internal()->RemoveSender(sender);
1270 }
1271 if (!removed) {
1272 LOG_AND_RETURN_ERROR(
1273 RTCErrorType::INVALID_PARAMETER,
1274 "Couldn't find sender " + sender->id() + " to remove.");
1275 }
Steve Anton4171afb2017-11-20 10:20:22 -08001276 }
deadbeefe1f9d832016-01-14 15:35:42 -08001277 observer_->OnRenegotiationNeeded();
Steve Antonf9381f02017-12-14 10:23:57 -08001278 return RTCError::OK();
1279}
1280
1281rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1282PeerConnection::FindTransceiverBySender(
1283 rtc::scoped_refptr<RtpSenderInterface> sender) {
1284 for (auto transceiver : transceivers_) {
1285 if (transceiver->sender() == sender) {
1286 return transceiver;
1287 }
1288 }
1289 return nullptr;
deadbeefe1f9d832016-01-14 15:35:42 -08001290}
1291
Steve Anton9158ef62017-11-27 13:01:52 -08001292RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1293PeerConnection::AddTransceiver(
1294 rtc::scoped_refptr<MediaStreamTrackInterface> track) {
1295 return AddTransceiver(track, RtpTransceiverInit());
1296}
1297
1298RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1299PeerConnection::AddTransceiver(
1300 rtc::scoped_refptr<MediaStreamTrackInterface> track,
1301 const RtpTransceiverInit& init) {
Steve Antonfc853712018-03-01 13:48:58 -08001302 RTC_CHECK(IsUnifiedPlan())
1303 << "AddTransceiver is only available with Unified Plan SdpSemantics";
Steve Anton9158ef62017-11-27 13:01:52 -08001304 if (!track) {
1305 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "track is null");
1306 }
1307 cricket::MediaType media_type;
1308 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
1309 media_type = cricket::MEDIA_TYPE_AUDIO;
1310 } else if (track->kind() == MediaStreamTrackInterface::kVideoKind) {
1311 media_type = cricket::MEDIA_TYPE_VIDEO;
1312 } else {
1313 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1314 "Track kind is not audio or video");
1315 }
1316 return AddTransceiver(media_type, track, init);
1317}
1318
1319RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1320PeerConnection::AddTransceiver(cricket::MediaType media_type) {
1321 return AddTransceiver(media_type, RtpTransceiverInit());
1322}
1323
1324RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1325PeerConnection::AddTransceiver(cricket::MediaType media_type,
1326 const RtpTransceiverInit& init) {
Steve Antonfc853712018-03-01 13:48:58 -08001327 RTC_CHECK(IsUnifiedPlan())
1328 << "AddTransceiver is only available with Unified Plan SdpSemantics";
Steve Anton9158ef62017-11-27 13:01:52 -08001329 if (!(media_type == cricket::MEDIA_TYPE_AUDIO ||
1330 media_type == cricket::MEDIA_TYPE_VIDEO)) {
1331 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1332 "media type is not audio or video");
1333 }
1334 return AddTransceiver(media_type, nullptr, init);
1335}
1336
1337RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1338PeerConnection::AddTransceiver(
1339 cricket::MediaType media_type,
1340 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Steve Anton22da89f2018-01-25 13:58:07 -08001341 const RtpTransceiverInit& init,
1342 bool fire_callback) {
Steve Anton9158ef62017-11-27 13:01:52 -08001343 RTC_DCHECK((media_type == cricket::MEDIA_TYPE_AUDIO ||
1344 media_type == cricket::MEDIA_TYPE_VIDEO));
1345 if (track) {
1346 RTC_DCHECK_EQ(media_type,
1347 (track->kind() == MediaStreamTrackInterface::kAudioKind
1348 ? cricket::MEDIA_TYPE_AUDIO
1349 : cricket::MEDIA_TYPE_VIDEO));
1350 }
1351
1352 // TODO(bugs.webrtc.org/7600): Verify init.
1353
Seth Hampson513449e2018-03-06 09:35:56 -08001354 if (init.stream_ids.size() > 1u) {
Steve Anton02ee47c2018-01-10 16:26:06 -08001355 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
1356 "More than one stream is not yet supported.");
Steve Antonf9381f02017-12-14 10:23:57 -08001357 }
1358
Seth Hampson513449e2018-03-06 09:35:56 -08001359 std::vector<std::string> stream_ids = {
1360 !init.stream_ids.empty() ? init.stream_ids[0] : rtc::CreateRandomUuid()};
Steve Anton02ee47c2018-01-10 16:26:06 -08001361
Seth Hampson845e8782018-03-02 11:34:10 -08001362 auto sender = CreateSender(media_type, track, stream_ids);
Steve Anton02ee47c2018-01-10 16:26:06 -08001363 auto receiver = CreateReceiver(media_type, rtc::CreateRandomUuid());
1364 auto transceiver = CreateAndAddTransceiver(sender, receiver);
1365 transceiver->internal()->set_direction(init.direction);
1366
Steve Anton22da89f2018-01-25 13:58:07 -08001367 if (fire_callback) {
1368 observer_->OnRenegotiationNeeded();
1369 }
Steve Antonf9381f02017-12-14 10:23:57 -08001370
1371 return rtc::scoped_refptr<RtpTransceiverInterface>(transceiver);
1372}
1373
Steve Anton02ee47c2018-01-10 16:26:06 -08001374rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
1375PeerConnection::CreateSender(
1376 cricket::MediaType media_type,
1377 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001378 const std::vector<std::string>& stream_ids) {
Steve Anton9158ef62017-11-27 13:01:52 -08001379 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> sender;
Steve Anton02ee47c2018-01-10 16:26:06 -08001380 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
1381 RTC_DCHECK(!track ||
1382 (track->kind() == MediaStreamTrackInterface::kAudioKind));
1383 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
1384 signaling_thread(),
Steve Anton47136dd2018-01-12 10:49:35 -08001385 new AudioRtpSender(worker_thread(),
1386 static_cast<AudioTrackInterface*>(track.get()),
Seth Hampson845e8782018-03-02 11:34:10 -08001387 stream_ids, stats_.get()));
Steve Anton02ee47c2018-01-10 16:26:06 -08001388 } else {
1389 RTC_DCHECK_EQ(media_type, cricket::MEDIA_TYPE_VIDEO);
1390 RTC_DCHECK(!track ||
1391 (track->kind() == MediaStreamTrackInterface::kVideoKind));
1392 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
1393 signaling_thread(),
Steve Anton47136dd2018-01-12 10:49:35 -08001394 new VideoRtpSender(worker_thread(),
1395 static_cast<VideoTrackInterface*>(track.get()),
Seth Hampson845e8782018-03-02 11:34:10 -08001396 stream_ids));
Steve Anton02ee47c2018-01-10 16:26:06 -08001397 }
Seth Hampson845e8782018-03-02 11:34:10 -08001398 sender->internal()->set_stream_ids(stream_ids);
Steve Anton02ee47c2018-01-10 16:26:06 -08001399 return sender;
1400}
1401
1402rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1403PeerConnection::CreateReceiver(cricket::MediaType media_type,
1404 const std::string& receiver_id) {
Steve Anton9158ef62017-11-27 13:01:52 -08001405 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1406 receiver;
Steve Anton9158ef62017-11-27 13:01:52 -08001407 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton9158ef62017-11-27 13:01:52 -08001408 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
Steve Anton60776752018-01-10 11:51:34 -08001409 signaling_thread(),
Steve Antond3679212018-01-17 17:41:02 -08001410 new AudioRtpReceiver(worker_thread(), receiver_id, {}));
Steve Anton9158ef62017-11-27 13:01:52 -08001411 } else {
Steve Anton02ee47c2018-01-10 16:26:06 -08001412 RTC_DCHECK_EQ(media_type, cricket::MEDIA_TYPE_VIDEO);
Steve Anton9158ef62017-11-27 13:01:52 -08001413 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
1414 signaling_thread(),
Steve Antond3679212018-01-17 17:41:02 -08001415 new VideoRtpReceiver(worker_thread(), receiver_id, {}));
Steve Anton9158ef62017-11-27 13:01:52 -08001416 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001417 return receiver;
1418}
1419
1420rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1421PeerConnection::CreateAndAddTransceiver(
1422 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> sender,
1423 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1424 receiver) {
1425 auto transceiver = RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1426 signaling_thread(), new RtpTransceiver(sender, receiver));
Steve Anton9158ef62017-11-27 13:01:52 -08001427 transceivers_.push_back(transceiver);
Steve Anton52d86772018-02-20 15:48:12 -08001428 transceiver->internal()->SignalNegotiationNeeded.connect(
1429 this, &PeerConnection::OnNegotiationNeeded);
Steve Antonf9381f02017-12-14 10:23:57 -08001430 return transceiver;
Steve Anton9158ef62017-11-27 13:01:52 -08001431}
1432
Steve Anton52d86772018-02-20 15:48:12 -08001433void PeerConnection::OnNegotiationNeeded() {
1434 RTC_DCHECK_RUN_ON(signaling_thread());
1435 RTC_DCHECK(!IsClosed());
1436 observer_->OnRenegotiationNeeded();
1437}
1438
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001439rtc::scoped_refptr<DtmfSenderInterface> PeerConnection::CreateDtmfSender(
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001440 AudioTrackInterface* track) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001441 TRACE_EVENT0("webrtc", "PeerConnection::CreateDtmfSender");
zhihuang29ff8442016-07-27 11:07:25 -07001442 if (IsClosed()) {
1443 return nullptr;
1444 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001445 if (!track) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001446 RTC_LOG(LS_ERROR) << "CreateDtmfSender - track is NULL.";
deadbeef20cb0c12017-02-01 20:27:00 -08001447 return nullptr;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001448 }
Steve Anton4171afb2017-11-20 10:20:22 -08001449 auto track_sender = FindSenderForTrack(track);
1450 if (!track_sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001451 RTC_LOG(LS_ERROR) << "CreateDtmfSender called with a non-added track.";
deadbeef20cb0c12017-02-01 20:27:00 -08001452 return nullptr;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001453 }
1454
Steve Anton4171afb2017-11-20 10:20:22 -08001455 return track_sender->GetDtmfSender();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001456}
1457
deadbeeffac06552015-11-25 11:26:01 -08001458rtc::scoped_refptr<RtpSenderInterface> PeerConnection::CreateSender(
deadbeefbd7d8f72015-12-18 16:58:44 -08001459 const std::string& kind,
1460 const std::string& stream_id) {
Steve Antonfc853712018-03-01 13:48:58 -08001461 RTC_CHECK(!IsUnifiedPlan()) << "CreateSender is not available with Unified "
1462 "Plan SdpSemantics. Please use AddTransceiver "
1463 "instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001464 TRACE_EVENT0("webrtc", "PeerConnection::CreateSender");
zhihuang29ff8442016-07-27 11:07:25 -07001465 if (IsClosed()) {
1466 return nullptr;
1467 }
Steve Anton4171afb2017-11-20 10:20:22 -08001468
Seth Hampson845e8782018-03-02 11:34:10 -08001469 std::vector<std::string> stream_ids;
Steve Anton02ee47c2018-01-10 16:26:06 -08001470 if (!stream_id.empty()) {
Seth Hampson845e8782018-03-02 11:34:10 -08001471 stream_ids.push_back(stream_id);
Steve Anton02ee47c2018-01-10 16:26:06 -08001472 }
1473
Steve Anton4171afb2017-11-20 10:20:22 -08001474 // TODO(steveanton): Move construction of the RtpSenders to RtpTransceiver.
deadbeefa601f5c2016-06-06 14:27:39 -07001475 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender;
deadbeeffac06552015-11-25 11:26:01 -08001476 if (kind == MediaStreamTrackInterface::kAudioKind) {
Seth Hampson845e8782018-03-02 11:34:10 -08001477 auto* audio_sender =
1478 new AudioRtpSender(worker_thread(), nullptr, stream_ids, stats_.get());
Steve Anton57858b32018-02-15 15:19:50 -08001479 audio_sender->SetVoiceMediaChannel(voice_media_channel());
deadbeefa601f5c2016-06-06 14:27:39 -07001480 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton02ee47c2018-01-10 16:26:06 -08001481 signaling_thread(), audio_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001482 GetAudioTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 11:26:01 -08001483 } else if (kind == MediaStreamTrackInterface::kVideoKind) {
Steve Anton47136dd2018-01-12 10:49:35 -08001484 auto* video_sender =
Seth Hampson845e8782018-03-02 11:34:10 -08001485 new VideoRtpSender(worker_thread(), nullptr, stream_ids);
Steve Anton57858b32018-02-15 15:19:50 -08001486 video_sender->SetVideoMediaChannel(video_media_channel());
deadbeefa601f5c2016-06-06 14:27:39 -07001487 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton02ee47c2018-01-10 16:26:06 -08001488 signaling_thread(), video_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001489 GetVideoTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 11:26:01 -08001490 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001491 RTC_LOG(LS_ERROR) << "CreateSender called with invalid kind: " << kind;
Steve Anton4171afb2017-11-20 10:20:22 -08001492 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08001493 }
Steve Anton4171afb2017-11-20 10:20:22 -08001494
deadbeefe1f9d832016-01-14 15:35:42 -08001495 return new_sender;
deadbeeffac06552015-11-25 11:26:01 -08001496}
1497
deadbeef70ab1a12015-09-28 16:53:55 -07001498std::vector<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::GetSenders()
1499 const {
deadbeefa601f5c2016-06-06 14:27:39 -07001500 std::vector<rtc::scoped_refptr<RtpSenderInterface>> ret;
Steve Anton4171afb2017-11-20 10:20:22 -08001501 for (auto sender : GetSendersInternal()) {
1502 ret.push_back(sender);
deadbeefa601f5c2016-06-06 14:27:39 -07001503 }
1504 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -07001505}
1506
Steve Anton4171afb2017-11-20 10:20:22 -08001507std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1508PeerConnection::GetSendersInternal() const {
1509 std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1510 all_senders;
1511 for (auto transceiver : transceivers_) {
1512 auto senders = transceiver->internal()->senders();
1513 all_senders.insert(all_senders.end(), senders.begin(), senders.end());
1514 }
1515 return all_senders;
1516}
1517
deadbeef70ab1a12015-09-28 16:53:55 -07001518std::vector<rtc::scoped_refptr<RtpReceiverInterface>>
1519PeerConnection::GetReceivers() const {
deadbeefa601f5c2016-06-06 14:27:39 -07001520 std::vector<rtc::scoped_refptr<RtpReceiverInterface>> ret;
Steve Anton4171afb2017-11-20 10:20:22 -08001521 for (const auto& receiver : GetReceiversInternal()) {
1522 ret.push_back(receiver);
deadbeefa601f5c2016-06-06 14:27:39 -07001523 }
1524 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -07001525}
1526
Steve Anton4171afb2017-11-20 10:20:22 -08001527std::vector<
1528 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1529PeerConnection::GetReceiversInternal() const {
1530 std::vector<
1531 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1532 all_receivers;
1533 for (auto transceiver : transceivers_) {
1534 auto receivers = transceiver->internal()->receivers();
1535 all_receivers.insert(all_receivers.end(), receivers.begin(),
1536 receivers.end());
1537 }
1538 return all_receivers;
1539}
1540
Steve Anton9158ef62017-11-27 13:01:52 -08001541std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
1542PeerConnection::GetTransceivers() const {
Steve Antonfc853712018-03-01 13:48:58 -08001543 RTC_CHECK(IsUnifiedPlan())
1544 << "GetTransceivers is only supported with Unified Plan SdpSemantics.";
Steve Anton9158ef62017-11-27 13:01:52 -08001545 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> all_transceivers;
1546 for (auto transceiver : transceivers_) {
1547 all_transceivers.push_back(transceiver);
1548 }
1549 return all_transceivers;
1550}
1551
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001552bool PeerConnection::GetStats(StatsObserver* observer,
wu@webrtc.orgb9a088b2014-02-13 23:18:49 +00001553 MediaStreamTrackInterface* track,
1554 StatsOutputLevel level) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001555 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
deadbeef0a6c4ca2015-10-06 11:38:28 -07001556 RTC_DCHECK(signaling_thread()->IsCurrent());
nisse7ce109a2017-01-31 00:57:56 -08001557 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001558 RTC_LOG(LS_ERROR) << "GetStats - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001559 return false;
1560 }
1561
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001562 stats_->UpdateStats(level);
zhihuange9e94c32016-11-04 11:38:15 -07001563 // The StatsCollector is used to tell if a track is valid because it may
1564 // remember tracks that the PeerConnection previously removed.
1565 if (track && !stats_->IsValidTrack(track->id())) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001566 RTC_LOG(LS_WARNING) << "GetStats is called with an invalid track: "
1567 << track->id();
zhihuange9e94c32016-11-04 11:38:15 -07001568 return false;
1569 }
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001570 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_GETSTATS,
tommi@webrtc.org5b06b062014-08-15 08:38:30 +00001571 new GetStatsMsg(observer, track));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001572 return true;
1573}
1574
hbos74e1a4f2016-09-15 23:33:01 -07001575void PeerConnection::GetStats(RTCStatsCollectorCallback* callback) {
1576 RTC_DCHECK(stats_collector_);
1577 stats_collector_->GetStatsReport(callback);
1578}
1579
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001580PeerConnectionInterface::SignalingState PeerConnection::signaling_state() {
1581 return signaling_state_;
1582}
1583
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001584PeerConnectionInterface::IceConnectionState
1585PeerConnection::ice_connection_state() {
1586 return ice_connection_state_;
1587}
1588
1589PeerConnectionInterface::IceGatheringState
1590PeerConnection::ice_gathering_state() {
1591 return ice_gathering_state_;
1592}
1593
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001594rtc::scoped_refptr<DataChannelInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001595PeerConnection::CreateDataChannel(
1596 const std::string& label,
1597 const DataChannelInit* config) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001598 TRACE_EVENT0("webrtc", "PeerConnection::CreateDataChannel");
zhihuang9763d562016-08-05 11:14:50 -07001599
deadbeefab9b2d12015-10-14 11:33:11 -07001600 bool first_datachannel = !HasDataChannels();
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001601
kwibergd1fe2812016-04-27 06:47:29 -07001602 std::unique_ptr<InternalDataChannelInit> internal_config;
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00001603 if (config) {
1604 internal_config.reset(new InternalDataChannelInit(*config));
1605 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001606 rtc::scoped_refptr<DataChannelInterface> channel(
deadbeefab9b2d12015-10-14 11:33:11 -07001607 InternalCreateDataChannel(label, internal_config.get()));
1608 if (!channel.get()) {
1609 return nullptr;
1610 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001611
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001612 // Trigger the onRenegotiationNeeded event for every new RTP DataChannel, or
1613 // the first SCTP DataChannel.
Steve Anton75737c02017-11-06 10:37:17 -08001614 if (data_channel_type() == cricket::DCT_RTP || first_datachannel) {
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001615 observer_->OnRenegotiationNeeded();
1616 }
wu@webrtc.org91053e72013-08-10 07:18:04 +00001617
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001618 return DataChannelProxy::Create(signaling_thread(), channel.get());
1619}
1620
1621void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
1622 const MediaConstraintsInterface* constraints) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001623 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
Steve Anton8d3444d2017-10-20 15:30:51 -07001624
zhihuang1c378ed2017-08-17 14:10:50 -07001625 PeerConnectionInterface::RTCOfferAnswerOptions offer_answer_options;
1626 // Always create an offer even if |ConvertConstraintsToOfferAnswerOptions|
1627 // returns false for now. Because |ConvertConstraintsToOfferAnswerOptions|
1628 // compares the mandatory fields parsed with the mandatory fields added in the
1629 // |constraints| and some downstream applications might create offers with
1630 // mandatory fields which would not be parsed in the helper method. For
1631 // example, in Chromium/remoting, |kEnableDtlsSrtp| is added to the
1632 // |constraints| as a mandatory field but it is not parsed.
1633 ConvertConstraintsToOfferAnswerOptions(constraints, &offer_answer_options);
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001634
zhihuang1c378ed2017-08-17 14:10:50 -07001635 CreateOffer(observer, offer_answer_options);
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001636}
1637
1638void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
1639 const RTCOfferAnswerOptions& options) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001640 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
Steve Anton8d3444d2017-10-20 15:30:51 -07001641
nisse7ce109a2017-01-31 00:57:56 -08001642 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001643 RTC_LOG(LS_ERROR) << "CreateOffer - observer is NULL.";
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001644 return;
1645 }
deadbeefab9b2d12015-10-14 11:33:11 -07001646
Steve Anton8d3444d2017-10-20 15:30:51 -07001647 if (IsClosed()) {
1648 std::string error = "CreateOffer called when PeerConnection is closed.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001649 RTC_LOG(LS_ERROR) << error;
Steve Anton8d3444d2017-10-20 15:30:51 -07001650 PostCreateSessionDescriptionFailure(observer, error);
1651 return;
1652 }
1653
zhihuang1c378ed2017-08-17 14:10:50 -07001654 if (!ValidateOfferAnswerOptions(options)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001655 std::string error = "CreateOffer called with invalid options.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001656 RTC_LOG(LS_ERROR) << error;
deadbeefab9b2d12015-10-14 11:33:11 -07001657 PostCreateSessionDescriptionFailure(observer, error);
1658 return;
1659 }
1660
Steve Anton22da89f2018-01-25 13:58:07 -08001661 // Legacy handling for offer_to_receive_audio and offer_to_receive_video.
1662 // Specified in WebRTC section 4.4.3.2 "Legacy configuration extensions".
1663 if (IsUnifiedPlan()) {
1664 RTCError error = HandleLegacyOfferOptions(options);
1665 if (!error.ok()) {
1666 PostCreateSessionDescriptionFailure(observer, error.message());
1667 return;
1668 }
1669 }
1670
zhihuang1c378ed2017-08-17 14:10:50 -07001671 cricket::MediaSessionOptions session_options;
1672 GetOptionsForOffer(options, &session_options);
Steve Antond25da372017-11-06 14:50:29 -08001673 webrtc_session_desc_factory_->CreateOffer(observer, options, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001674}
1675
Steve Anton22da89f2018-01-25 13:58:07 -08001676RTCError PeerConnection::HandleLegacyOfferOptions(
1677 const RTCOfferAnswerOptions& options) {
1678 RTC_DCHECK(IsUnifiedPlan());
1679
1680 if (options.offer_to_receive_audio == 0) {
1681 RemoveRecvDirectionFromReceivingTransceiversOfType(
1682 cricket::MEDIA_TYPE_AUDIO);
1683 } else if (options.offer_to_receive_audio == 1) {
1684 AddUpToOneReceivingTransceiverOfType(cricket::MEDIA_TYPE_AUDIO);
1685 } else if (options.offer_to_receive_audio > 1) {
1686 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
1687 "offer_to_receive_audio > 1 is not supported.");
1688 }
1689
1690 if (options.offer_to_receive_video == 0) {
1691 RemoveRecvDirectionFromReceivingTransceiversOfType(
1692 cricket::MEDIA_TYPE_VIDEO);
1693 } else if (options.offer_to_receive_video == 1) {
1694 AddUpToOneReceivingTransceiverOfType(cricket::MEDIA_TYPE_VIDEO);
1695 } else if (options.offer_to_receive_video > 1) {
1696 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
1697 "offer_to_receive_video > 1 is not supported.");
1698 }
1699
1700 return RTCError::OK();
1701}
1702
1703void PeerConnection::RemoveRecvDirectionFromReceivingTransceiversOfType(
1704 cricket::MediaType media_type) {
1705 for (auto transceiver : GetReceivingTransceiversOfType(media_type)) {
1706 transceiver->internal()->set_direction(
1707 RtpTransceiverDirectionWithRecvSet(transceiver->direction(), false));
1708 }
1709}
1710
1711void PeerConnection::AddUpToOneReceivingTransceiverOfType(
1712 cricket::MediaType media_type) {
1713 if (GetReceivingTransceiversOfType(media_type).empty()) {
1714 RtpTransceiverInit init;
1715 init.direction = RtpTransceiverDirection::kRecvOnly;
1716 AddTransceiver(media_type, nullptr, init, /*fire_callback=*/false);
1717 }
1718}
1719
1720std::vector<rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
1721PeerConnection::GetReceivingTransceiversOfType(cricket::MediaType media_type) {
1722 std::vector<
1723 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
1724 receiving_transceivers;
1725 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08001726 if (!transceiver->stopped() && transceiver->media_type() == media_type &&
Steve Anton22da89f2018-01-25 13:58:07 -08001727 RtpTransceiverDirectionHasRecv(transceiver->direction())) {
1728 receiving_transceivers.push_back(transceiver);
1729 }
1730 }
1731 return receiving_transceivers;
1732}
1733
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001734void PeerConnection::CreateAnswer(
1735 CreateSessionDescriptionObserver* observer,
1736 const MediaConstraintsInterface* constraints) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001737 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
Steve Anton8d3444d2017-10-20 15:30:51 -07001738
nisse7ce109a2017-01-31 00:57:56 -08001739 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001740 RTC_LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001741 return;
1742 }
deadbeefab9b2d12015-10-14 11:33:11 -07001743
zhihuang1c378ed2017-08-17 14:10:50 -07001744 PeerConnectionInterface::RTCOfferAnswerOptions offer_answer_options;
1745 if (!ConvertConstraintsToOfferAnswerOptions(constraints,
1746 &offer_answer_options)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001747 std::string error = "CreateAnswer called with invalid constraints.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001748 RTC_LOG(LS_ERROR) << error;
deadbeefab9b2d12015-10-14 11:33:11 -07001749 PostCreateSessionDescriptionFailure(observer, error);
1750 return;
1751 }
1752
Steve Anton8d3444d2017-10-20 15:30:51 -07001753 CreateAnswer(observer, offer_answer_options);
htaa2a49d92016-03-04 02:51:39 -08001754}
1755
1756void PeerConnection::CreateAnswer(CreateSessionDescriptionObserver* observer,
1757 const RTCOfferAnswerOptions& options) {
1758 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
nisse7ce109a2017-01-31 00:57:56 -08001759 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001760 RTC_LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
htaa2a49d92016-03-04 02:51:39 -08001761 return;
1762 }
1763
Steve Antondffead82018-02-06 10:31:29 -08001764 if (!(signaling_state_ == kHaveRemoteOffer ||
1765 signaling_state_ == kHaveLocalPrAnswer)) {
1766 std::string error =
1767 "PeerConnection cannot create an answer in a state other than "
1768 "have-remote-offer or have-local-pranswer.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001769 RTC_LOG(LS_ERROR) << error;
Steve Anton8d3444d2017-10-20 15:30:51 -07001770 PostCreateSessionDescriptionFailure(observer, error);
1771 return;
1772 }
1773
Steve Antondffead82018-02-06 10:31:29 -08001774 // The remote description should be set if we're in the right state.
1775 RTC_DCHECK(remote_description());
Steve Anton8d3444d2017-10-20 15:30:51 -07001776
Steve Anton22da89f2018-01-25 13:58:07 -08001777 if (IsUnifiedPlan()) {
1778 if (options.offer_to_receive_audio != RTCOfferAnswerOptions::kUndefined) {
1779 RTC_LOG(LS_WARNING) << "CreateAnswer: offer_to_receive_audio is not "
1780 "supported with Unified Plan semantics. Use the "
1781 "RtpTransceiver API instead.";
1782 }
1783 if (options.offer_to_receive_video != RTCOfferAnswerOptions::kUndefined) {
1784 RTC_LOG(LS_WARNING) << "CreateAnswer: offer_to_receive_video is not "
1785 "supported with Unified Plan semantics. Use the "
1786 "RtpTransceiver API instead.";
1787 }
1788 }
1789
htaa2a49d92016-03-04 02:51:39 -08001790 cricket::MediaSessionOptions session_options;
zhihuang1c378ed2017-08-17 14:10:50 -07001791 GetOptionsForAnswer(options, &session_options);
htaa2a49d92016-03-04 02:51:39 -08001792
Steve Antond25da372017-11-06 14:50:29 -08001793 webrtc_session_desc_factory_->CreateAnswer(observer, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001794}
1795
1796void PeerConnection::SetLocalDescription(
1797 SetSessionDescriptionObserver* observer,
Steve Anton80dd7b52018-02-16 17:08:42 -08001798 SessionDescriptionInterface* desc_ptr) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001799 TRACE_EVENT0("webrtc", "PeerConnection::SetLocalDescription");
Steve Anton8a006912017-12-04 15:25:56 -08001800
Steve Anton80dd7b52018-02-16 17:08:42 -08001801 // The SetLocalDescription contract is that we take ownership of the session
1802 // description regardless of the outcome, so wrap it in a unique_ptr right
1803 // away. Ideally, SetLocalDescription's signature will be changed to take the
1804 // description as a unique_ptr argument to formalize this agreement.
1805 std::unique_ptr<SessionDescriptionInterface> desc(desc_ptr);
1806
nisse7ce109a2017-01-31 00:57:56 -08001807 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001808 RTC_LOG(LS_ERROR) << "SetLocalDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001809 return;
1810 }
Steve Anton8a006912017-12-04 15:25:56 -08001811
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001812 if (!desc) {
1813 PostSetSessionDescriptionFailure(observer, "SessionDescription is NULL.");
1814 return;
1815 }
Steve Anton8d3444d2017-10-20 15:30:51 -07001816
Steve Anton80dd7b52018-02-16 17:08:42 -08001817 // If a session error has occurred the PeerConnection is in a possibly
1818 // inconsistent state so fail right away.
1819 if (session_error() != SessionError::kNone) {
1820 std::string error_message = GetSessionErrorMsg();
1821 RTC_LOG(LS_ERROR) << "SetLocalDescription: " << error_message;
1822 PostSetSessionDescriptionFailure(observer, std::move(error_message));
1823 return;
1824 }
Steve Anton8d3444d2017-10-20 15:30:51 -07001825
Steve Anton80dd7b52018-02-16 17:08:42 -08001826 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_LOCAL);
1827 if (!error.ok()) {
1828 std::string error_message = GetSetDescriptionErrorMessage(
1829 cricket::CS_LOCAL, desc->GetType(), error);
1830 RTC_LOG(LS_ERROR) << error_message;
1831 PostSetSessionDescriptionFailure(observer, std::move(error_message));
1832 return;
1833 }
1834
1835 // Grab the description type before moving ownership to ApplyLocalDescription,
1836 // which may destroy it before returning.
1837 const SdpType type = desc->GetType();
1838
1839 error = ApplyLocalDescription(std::move(desc));
Steve Anton8a006912017-12-04 15:25:56 -08001840 // |desc| may be destroyed at this point.
1841
1842 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08001843 // If ApplyLocalDescription fails, the PeerConnection could be in an
1844 // inconsistent state, so act conservatively here and set the session error
1845 // so that future calls to SetLocalDescription/SetRemoteDescription fail.
1846 SetSessionError(SessionError::kContent, error.message());
1847 std::string error_message =
1848 GetSetDescriptionErrorMessage(cricket::CS_LOCAL, type, error);
1849 RTC_LOG(LS_ERROR) << error_message;
Steve Anton8a006912017-12-04 15:25:56 -08001850 PostSetSessionDescriptionFailure(observer, std::move(error_message));
Steve Anton8d3444d2017-10-20 15:30:51 -07001851 return;
1852 }
Steve Anton8a006912017-12-04 15:25:56 -08001853 RTC_DCHECK(local_description());
1854
1855 PostSetSessionDescriptionSuccess(observer);
1856
1857 // According to JSEP, after setLocalDescription, changing the candidate pool
1858 // size is not allowed, and changing the set of ICE servers will not result
1859 // in new candidates being gathered.
1860 port_allocator_->FreezeCandidatePool();
1861
1862 // MaybeStartGathering needs to be called after posting
1863 // MSG_SET_SESSIONDESCRIPTION_SUCCESS, so that we don't signal any candidates
1864 // before signaling that SetLocalDescription completed.
1865 transport_controller_->MaybeStartGathering();
1866
Steve Antona3a92c22017-12-07 10:27:41 -08001867 if (local_description()->GetType() == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08001868 // TODO(deadbeef): We already had to hop to the network thread for
1869 // MaybeStartGathering...
1870 network_thread()->Invoke<void>(
1871 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
1872 port_allocator_.get()));
Steve Anton0ffaaa22018-02-23 10:31:30 -08001873 // Make UMA notes about what was agreed to.
1874 ReportNegotiatedSdpSemantics(*local_description());
Steve Anton8a006912017-12-04 15:25:56 -08001875 }
1876}
1877
1878RTCError PeerConnection::ApplyLocalDescription(
1879 std::unique_ptr<SessionDescriptionInterface> desc) {
1880 RTC_DCHECK_RUN_ON(signaling_thread());
1881 RTC_DCHECK(desc);
1882
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001883 // Update stats here so that we have the most recent stats for tracks and
1884 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001885 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 15:25:56 -08001886
1887 // Update the initial_offerer flag if this session is the initial_offerer.
Steve Anton3828c062017-12-06 10:34:51 -08001888 SdpType type = desc->GetType();
Steve Anton8a006912017-12-04 15:25:56 -08001889 if (!initial_offerer_.has_value()) {
Steve Anton3828c062017-12-06 10:34:51 -08001890 initial_offerer_.emplace(type == SdpType::kOffer);
Steve Anton8a006912017-12-04 15:25:56 -08001891 if (*initial_offerer_) {
1892 transport_controller_->SetIceRole(cricket::ICEROLE_CONTROLLING);
1893 } else {
1894 transport_controller_->SetIceRole(cricket::ICEROLE_CONTROLLED);
1895 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001896 }
Steve Anton8a006912017-12-04 15:25:56 -08001897
Steve Antondcc3c022017-12-22 16:02:54 -08001898 // Take a reference to the old local description since it's used below to
1899 // compare against the new local description. When setting the new local
1900 // description, grab ownership of the replaced session description in case it
1901 // is the same as |old_local_description|, to keep it alive for the duration
1902 // of the method.
1903 const SessionDescriptionInterface* old_local_description =
1904 local_description();
1905 std::unique_ptr<SessionDescriptionInterface> replaced_local_description;
Steve Anton3828c062017-12-06 10:34:51 -08001906 if (type == SdpType::kAnswer) {
Steve Antondcc3c022017-12-22 16:02:54 -08001907 replaced_local_description = pending_local_description_
1908 ? std::move(pending_local_description_)
1909 : std::move(current_local_description_);
Steve Anton8a006912017-12-04 15:25:56 -08001910 current_local_description_ = std::move(desc);
1911 pending_local_description_ = nullptr;
1912 current_remote_description_ = std::move(pending_remote_description_);
1913 } else {
Steve Antondcc3c022017-12-22 16:02:54 -08001914 replaced_local_description = std::move(pending_local_description_);
Steve Anton8a006912017-12-04 15:25:56 -08001915 pending_local_description_ = std::move(desc);
1916 }
1917 // The session description to apply now must be accessed by
1918 // |local_description()|.
Henrik Boströmfdb92012017-11-09 19:55:44 +01001919 RTC_DCHECK(local_description());
deadbeefab9b2d12015-10-14 11:33:11 -07001920
Steve Antondcc3c022017-12-22 16:02:54 -08001921 if (IsUnifiedPlan()) {
1922 RTCError error = UpdateTransceiversAndDataChannels(
Seth Hampsonae8a90a2018-02-13 15:33:48 -08001923 cricket::CS_LOCAL, *local_description(), old_local_description,
1924 remote_description());
Steve Anton8a006912017-12-04 15:25:56 -08001925 if (!error.ok()) {
1926 return error;
1927 }
Steve Antondcc3c022017-12-22 16:02:54 -08001928 for (auto transceiver : transceivers_) {
1929 const ContentInfo* content =
1930 FindMediaSectionForTransceiver(transceiver, local_description());
1931 if (!content) {
1932 continue;
1933 }
1934 const MediaContentDescription* media_desc = content->media_description();
1935 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
1936 transceiver->internal()->set_current_direction(media_desc->direction());
1937 }
1938 if (content->rejected && !transceiver->stopped()) {
1939 transceiver->Stop();
1940 }
1941 }
1942 } else {
1943 // Transport and Media channels will be created only when offer is set.
1944 if (type == SdpType::kOffer) {
1945 // TODO(bugs.webrtc.org/4676) - Handle CreateChannel failure, as new local
1946 // description is applied. Restore back to old description.
1947 RTCError error = CreateChannels(*local_description()->description());
1948 if (!error.ok()) {
1949 return error;
1950 }
1951 }
Steve Anton8a006912017-12-04 15:25:56 -08001952
Steve Antondcc3c022017-12-22 16:02:54 -08001953 // Remove unused channels if MediaContentDescription is rejected.
1954 RemoveUnusedChannels(local_description()->description());
1955 }
Steve Anton8a006912017-12-04 15:25:56 -08001956
Steve Anton80dd7b52018-02-16 17:08:42 -08001957 RTCError error = UpdateSessionState(type, cricket::CS_LOCAL);
Steve Anton8a006912017-12-04 15:25:56 -08001958 if (!error.ok()) {
1959 return error;
1960 }
Steve Antondcc3c022017-12-22 16:02:54 -08001961
Steve Anton8a006912017-12-04 15:25:56 -08001962 if (remote_description()) {
1963 // Now that we have a local description, we can push down remote candidates.
1964 UseCandidatesInSessionDescription(remote_description());
1965 }
1966
1967 pending_ice_restarts_.clear();
1968 if (session_error() != SessionError::kNone) {
1969 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
1970 }
1971
deadbeefab9b2d12015-10-14 11:33:11 -07001972 // If setting the description decided our SSL role, allocate any necessary
1973 // SCTP sids.
1974 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08001975 if (data_channel_type() == cricket::DCT_SCTP && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001976 AllocateSctpSids(role);
1977 }
1978
Steve Antond3679212018-01-17 17:41:02 -08001979 if (IsUnifiedPlan()) {
1980 for (auto transceiver : transceivers_) {
1981 const ContentInfo* content =
1982 FindMediaSectionForTransceiver(transceiver, local_description());
1983 if (!content) {
1984 continue;
1985 }
1986 if (content->rejected && !transceiver->stopped()) {
1987 transceiver->Stop();
1988 }
Steve Anton74255ff2018-01-24 18:32:57 -08001989 const auto& streams = content->media_description()->streams();
1990 if (!content->rejected && !streams.empty()) {
Steve Antond3679212018-01-17 17:41:02 -08001991 transceiver->internal()->sender_internal()->set_stream_ids(
Seth Hampson845e8782018-03-02 11:34:10 -08001992 streams[0].stream_ids());
Steve Antond3679212018-01-17 17:41:02 -08001993 transceiver->internal()->sender_internal()->SetSsrc(
Steve Anton74255ff2018-01-24 18:32:57 -08001994 streams[0].first_ssrc());
Steve Antond3679212018-01-17 17:41:02 -08001995 }
1996 }
1997 } else {
1998 // Plan B semantics.
1999
Steve Antondcc3c022017-12-22 16:02:54 -08002000 // Update state and SSRC of local MediaStreams and DataChannels based on the
2001 // local session description.
2002 const cricket::ContentInfo* audio_content =
2003 GetFirstAudioContent(local_description()->description());
2004 if (audio_content) {
2005 if (audio_content->rejected) {
2006 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
2007 } else {
2008 const cricket::AudioContentDescription* audio_desc =
2009 audio_content->media_description()->as_audio();
2010 UpdateLocalSenders(audio_desc->streams(), audio_desc->type());
2011 }
deadbeeffaac4972015-11-12 15:33:07 -08002012 }
deadbeefab9b2d12015-10-14 11:33:11 -07002013
Steve Antondcc3c022017-12-22 16:02:54 -08002014 const cricket::ContentInfo* video_content =
2015 GetFirstVideoContent(local_description()->description());
2016 if (video_content) {
2017 if (video_content->rejected) {
2018 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
2019 } else {
2020 const cricket::VideoContentDescription* video_desc =
2021 video_content->media_description()->as_video();
2022 UpdateLocalSenders(video_desc->streams(), video_desc->type());
2023 }
deadbeeffaac4972015-11-12 15:33:07 -08002024 }
deadbeefab9b2d12015-10-14 11:33:11 -07002025 }
2026
2027 const cricket::ContentInfo* data_content =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002028 GetFirstDataContent(local_description()->description());
deadbeefab9b2d12015-10-14 11:33:11 -07002029 if (data_content) {
2030 const cricket::DataContentDescription* data_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08002031 data_content->media_description()->as_data();
deadbeefab9b2d12015-10-14 11:33:11 -07002032 if (rtc::starts_with(data_desc->protocol().data(),
2033 cricket::kMediaProtocolRtpPrefix)) {
2034 UpdateLocalRtpDataChannels(data_desc->streams());
2035 }
2036 }
2037
Steve Anton8a006912017-12-04 15:25:56 -08002038 return RTCError::OK();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002039}
2040
2041void PeerConnection::SetRemoteDescription(
Henrik Boströma4ecf552017-11-23 14:17:07 +00002042 SetSessionDescriptionObserver* observer,
2043 SessionDescriptionInterface* desc) {
Henrik Boström31638672017-11-23 17:48:32 +01002044 SetRemoteDescription(
2045 std::unique_ptr<SessionDescriptionInterface>(desc),
2046 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface>(
2047 new SetRemoteDescriptionObserverAdapter(this, observer)));
2048}
2049
2050void PeerConnection::SetRemoteDescription(
2051 std::unique_ptr<SessionDescriptionInterface> desc,
2052 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface> observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +01002053 TRACE_EVENT0("webrtc", "PeerConnection::SetRemoteDescription");
Steve Anton8a006912017-12-04 15:25:56 -08002054
nisse7ce109a2017-01-31 00:57:56 -08002055 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002056 RTC_LOG(LS_ERROR) << "SetRemoteDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002057 return;
2058 }
Steve Anton8a006912017-12-04 15:25:56 -08002059
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002060 if (!desc) {
Henrik Boström31638672017-11-23 17:48:32 +01002061 observer->OnSetRemoteDescriptionComplete(RTCError(
Steve Anton8a006912017-12-04 15:25:56 -08002062 RTCErrorType::INVALID_PARAMETER, "SessionDescription is NULL."));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002063 return;
2064 }
Steve Anton8d3444d2017-10-20 15:30:51 -07002065
Steve Anton80dd7b52018-02-16 17:08:42 -08002066 // If a session error has occurred the PeerConnection is in a possibly
2067 // inconsistent state so fail right away.
2068 if (session_error() != SessionError::kNone) {
2069 std::string error_message = GetSessionErrorMsg();
2070 RTC_LOG(LS_ERROR) << "SetRemoteDescription: " << error_message;
2071 observer->OnSetRemoteDescriptionComplete(
2072 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
2073 return;
2074 }
Steve Anton71439a62018-02-15 11:53:06 -08002075
Steve Anton80dd7b52018-02-16 17:08:42 -08002076 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_REMOTE);
Steve Anton71439a62018-02-15 11:53:06 -08002077 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08002078 std::string error_message = GetSetDescriptionErrorMessage(
2079 cricket::CS_REMOTE, desc->GetType(), error);
2080 RTC_LOG(LS_ERROR) << error_message;
Steve Anton71439a62018-02-15 11:53:06 -08002081 observer->OnSetRemoteDescriptionComplete(
2082 RTCError(error.type(), std::move(error_message)));
2083 return;
2084 }
Steve Anton71439a62018-02-15 11:53:06 -08002085
Steve Anton80dd7b52018-02-16 17:08:42 -08002086 // Grab the description type before moving ownership to
2087 // ApplyRemoteDescription, which may destroy it before returning.
2088 const SdpType type = desc->GetType();
2089
2090 error = ApplyRemoteDescription(std::move(desc));
2091 // |desc| may be destroyed at this point.
2092
2093 if (!error.ok()) {
2094 // If ApplyRemoteDescription fails, the PeerConnection could be in an
2095 // inconsistent state, so act conservatively here and set the session error
2096 // so that future calls to SetLocalDescription/SetRemoteDescription fail.
2097 SetSessionError(SessionError::kContent, error.message());
2098 std::string error_message =
2099 GetSetDescriptionErrorMessage(cricket::CS_REMOTE, type, error);
2100 RTC_LOG(LS_ERROR) << error_message;
2101 observer->OnSetRemoteDescriptionComplete(
2102 RTCError(error.type(), std::move(error_message)));
2103 return;
2104 }
2105 RTC_DCHECK(remote_description());
2106
Steve Anton8e20f172018-03-06 10:55:04 -08002107 if (type == SdpType::kOffer) {
2108 // Report to UMA the format of the received offer.
2109 ReportSdpFormatReceived(*remote_description());
2110 }
2111
Steve Anton80dd7b52018-02-16 17:08:42 -08002112 if (type == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002113 // TODO(deadbeef): We already had to hop to the network thread for
2114 // MaybeStartGathering...
2115 network_thread()->Invoke<void>(
2116 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
2117 port_allocator_.get()));
Harald Alvestrand5dbb5862018-02-13 23:48:00 +01002118 // Make UMA notes about what was agreed to.
Steve Anton0ffaaa22018-02-23 10:31:30 -08002119 ReportNegotiatedSdpSemantics(*remote_description());
Steve Anton8a006912017-12-04 15:25:56 -08002120 }
2121
2122 observer->OnSetRemoteDescriptionComplete(RTCError::OK());
2123}
2124
2125RTCError PeerConnection::ApplyRemoteDescription(
2126 std::unique_ptr<SessionDescriptionInterface> desc) {
2127 RTC_DCHECK_RUN_ON(signaling_thread());
2128 RTC_DCHECK(desc);
2129
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002130 // Update stats here so that we have the most recent stats for tracks and
2131 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00002132 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 15:25:56 -08002133
Steve Antondcc3c022017-12-22 16:02:54 -08002134 // Take a reference to the old remote description since it's used below to
2135 // compare against the new remote description. When setting the new remote
2136 // description, grab ownership of the replaced session description in case it
2137 // is the same as |old_remote_description|, to keep it alive for the duration
2138 // of the method.
Steve Anton8a006912017-12-04 15:25:56 -08002139 const SessionDescriptionInterface* old_remote_description =
2140 remote_description();
Steve Anton8a006912017-12-04 15:25:56 -08002141 std::unique_ptr<SessionDescriptionInterface> replaced_remote_description;
Steve Anton3828c062017-12-06 10:34:51 -08002142 SdpType type = desc->GetType();
2143 if (type == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002144 replaced_remote_description = pending_remote_description_
2145 ? std::move(pending_remote_description_)
2146 : std::move(current_remote_description_);
2147 current_remote_description_ = std::move(desc);
2148 pending_remote_description_ = nullptr;
2149 current_local_description_ = std::move(pending_local_description_);
2150 } else {
2151 replaced_remote_description = std::move(pending_remote_description_);
2152 pending_remote_description_ = std::move(desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002153 }
Steve Anton8a006912017-12-04 15:25:56 -08002154 // The session description to apply now must be accessed by
2155 // |remote_description()|.
Henrik Boströmfdb92012017-11-09 19:55:44 +01002156 RTC_DCHECK(remote_description());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002157
Steve Anton8a006912017-12-04 15:25:56 -08002158 // Transport and Media channels will be created only when offer is set.
Steve Antondcc3c022017-12-22 16:02:54 -08002159 if (IsUnifiedPlan()) {
2160 RTCError error = UpdateTransceiversAndDataChannels(
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002161 cricket::CS_REMOTE, *remote_description(), local_description(),
2162 old_remote_description);
Steve Anton8a006912017-12-04 15:25:56 -08002163 if (!error.ok()) {
2164 return error;
2165 }
Steve Antondcc3c022017-12-22 16:02:54 -08002166 } else {
2167 if (type == SdpType::kOffer) {
2168 // TODO(bugs.webrtc.org/4676) - Handle CreateChannel failure, as new local
2169 // description is applied. Restore back to old description.
2170 RTCError error = CreateChannels(*remote_description()->description());
2171 if (!error.ok()) {
2172 return error;
2173 }
2174 }
Steve Anton8a006912017-12-04 15:25:56 -08002175
Steve Antondcc3c022017-12-22 16:02:54 -08002176 // Remove unused channels if MediaContentDescription is rejected.
2177 RemoveUnusedChannels(remote_description()->description());
2178 }
Steve Anton8a006912017-12-04 15:25:56 -08002179
2180 // NOTE: Candidates allocation will be initiated only when SetLocalDescription
2181 // is called.
Steve Anton80dd7b52018-02-16 17:08:42 -08002182 RTCError error = UpdateSessionState(type, cricket::CS_REMOTE);
Steve Anton8a006912017-12-04 15:25:56 -08002183 if (!error.ok()) {
2184 return error;
2185 }
2186
2187 if (local_description() &&
2188 !UseCandidatesInSessionDescription(remote_description())) {
2189 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidCandidates);
2190 }
2191
2192 if (old_remote_description) {
2193 for (const cricket::ContentInfo& content :
2194 old_remote_description->description()->contents()) {
2195 // Check if this new SessionDescription contains new ICE ufrag and
2196 // password that indicates the remote peer requests an ICE restart.
2197 // TODO(deadbeef): When we start storing both the current and pending
2198 // remote description, this should reset pending_ice_restarts and compare
2199 // against the current description.
2200 if (CheckForRemoteIceRestart(old_remote_description, remote_description(),
2201 content.name)) {
Steve Anton3828c062017-12-06 10:34:51 -08002202 if (type == SdpType::kOffer) {
Steve Anton8a006912017-12-04 15:25:56 -08002203 pending_ice_restarts_.insert(content.name);
2204 }
2205 } else {
2206 // We retain all received candidates only if ICE is not restarted.
2207 // When ICE is restarted, all previous candidates belong to an old
2208 // generation and should not be kept.
2209 // TODO(deadbeef): This goes against the W3C spec which says the remote
2210 // description should only contain candidates from the last set remote
2211 // description plus any candidates added since then. We should remove
2212 // this once we're sure it won't break anything.
2213 WebRtcSessionDescriptionFactory::CopyCandidatesFromSessionDescription(
2214 old_remote_description, content.name, mutable_remote_description());
2215 }
2216 }
2217 }
2218
2219 if (session_error() != SessionError::kNone) {
2220 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
2221 }
2222
2223 // Set the the ICE connection state to connecting since the connection may
2224 // become writable with peer reflexive candidates before any remote candidate
2225 // is signaled.
2226 // TODO(pthatcher): This is a short-term solution for crbug/446908. A real fix
2227 // is to have a new signal the indicates a change in checking state from the
2228 // transport and expose a new checking() member from transport that can be
2229 // read to determine the current checking state. The existing SignalConnecting
2230 // actually means "gathering candidates", so cannot be be used here.
Steve Antona3a92c22017-12-07 10:27:41 -08002231 if (remote_description()->GetType() != SdpType::kOffer &&
Steve Anton8a006912017-12-04 15:25:56 -08002232 ice_connection_state() == PeerConnectionInterface::kIceConnectionNew) {
2233 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
2234 }
2235
deadbeefab9b2d12015-10-14 11:33:11 -07002236 // If setting the description decided our SSL role, allocate any necessary
2237 // SCTP sids.
2238 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08002239 if (data_channel_type() == cricket::DCT_SCTP && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07002240 AllocateSctpSids(role);
2241 }
2242
Steve Antondcc3c022017-12-22 16:02:54 -08002243 if (IsUnifiedPlan()) {
Steve Anton8b815cd2018-02-16 16:14:42 -08002244 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
2245 receiving_transceivers;
Steve Antonc49bcd92018-02-14 14:28:13 -08002246 std::vector<rtc::scoped_refptr<MediaStreamInterface>> added_streams;
Steve Antondcc3c022017-12-22 16:02:54 -08002247 for (auto transceiver : transceivers_) {
2248 const ContentInfo* content =
2249 FindMediaSectionForTransceiver(transceiver, remote_description());
2250 if (!content) {
2251 continue;
2252 }
2253 const MediaContentDescription* media_desc = content->media_description();
2254 RtpTransceiverDirection local_direction =
2255 RtpTransceiverDirectionReversed(media_desc->direction());
2256 // From the WebRTC specification, steps 2.2.8.5/6 of section 4.4.1.6 "Set
2257 // the RTCSessionDescription: If direction is sendrecv or recvonly, and
2258 // transceiver's current direction is neither sendrecv nor recvonly,
2259 // process the addition of a remote track for the media description.
Seth Hampson2f0d7022018-02-20 11:54:42 -08002260 //
2261 // Create a sync label in the case of an unsignalled msid.
2262 std::string sync_label = rtc::CreateRandomUuid();
2263 if (!media_desc->streams().empty()) {
Steve Anton5a26a3a2018-02-28 11:38:47 -08002264 const cricket::StreamParams& stream_params = media_desc->streams()[0];
Seth Hampson845e8782018-03-02 11:34:10 -08002265 if (!stream_params.stream_ids().empty()) {
2266 sync_label = stream_params.stream_ids()[0];
Steve Anton5a26a3a2018-02-28 11:38:47 -08002267 }
Seth Hampson2f0d7022018-02-20 11:54:42 -08002268 }
Steve Antondcc3c022017-12-22 16:02:54 -08002269 if (RtpTransceiverDirectionHasRecv(local_direction) &&
2270 (!transceiver->current_direction() ||
2271 !RtpTransceiverDirectionHasRecv(
Seth Hampson2f0d7022018-02-20 11:54:42 -08002272 *transceiver->current_direction()))) {
Steve Antonef65ef12018-01-10 17:15:20 -08002273 rtc::scoped_refptr<MediaStreamInterface> stream =
2274 remote_streams_->find(sync_label);
2275 if (!stream) {
2276 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
2277 MediaStream::Create(sync_label));
2278 remote_streams_->AddStream(stream);
Steve Antonc49bcd92018-02-14 14:28:13 -08002279 added_streams.push_back(stream);
Steve Antonef65ef12018-01-10 17:15:20 -08002280 }
2281 transceiver->internal()->receiver_internal()->SetStreams({stream});
Steve Anton8b815cd2018-02-16 16:14:42 -08002282 receiving_transceivers.push_back(transceiver);
Steve Antondcc3c022017-12-22 16:02:54 -08002283 }
2284 // If direction is sendonly or inactive, and transceiver's current
2285 // direction is neither sendonly nor inactive, process the removal of a
2286 // remote track for the media description.
2287 if (!RtpTransceiverDirectionHasRecv(local_direction) &&
Steve Antonef65ef12018-01-10 17:15:20 -08002288 (transceiver->current_direction() &&
Steve Antondcc3c022017-12-22 16:02:54 -08002289 RtpTransceiverDirectionHasRecv(*transceiver->current_direction()))) {
Steve Antonef65ef12018-01-10 17:15:20 -08002290 transceiver->internal()->receiver_internal()->SetStreams({});
Steve Antondcc3c022017-12-22 16:02:54 -08002291 }
2292 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
2293 transceiver->internal()->set_current_direction(local_direction);
2294 }
2295 if (content->rejected && !transceiver->stopped()) {
2296 transceiver->Stop();
2297 }
Seth Hampson2f0d7022018-02-20 11:54:42 -08002298 if (!content->rejected &&
2299 RtpTransceiverDirectionHasRecv(local_direction)) {
2300 // Set ssrc to 0 in the case of an unsignalled ssrc.
2301 uint32_t ssrc = 0;
2302 if (!media_desc->streams().empty()) {
2303 ssrc = media_desc->streams()[0].first_ssrc();
2304 }
2305 transceiver->internal()->receiver_internal()->SetupMediaChannel(ssrc);
Steve Antond3679212018-01-17 17:41:02 -08002306 }
Steve Antondcc3c022017-12-22 16:02:54 -08002307 }
Steve Antonc49bcd92018-02-14 14:28:13 -08002308 // Once all processing has finished, fire off callbacks.
Steve Anton8b815cd2018-02-16 16:14:42 -08002309 for (auto transceiver : receiving_transceivers) {
Steve Anton6e221372018-02-20 12:59:16 -08002310 stats_->AddTrack(transceiver->receiver()->track());
Steve Anton8b815cd2018-02-16 16:14:42 -08002311 observer_->OnTrack(transceiver);
2312 observer_->OnAddTrack(transceiver->receiver(),
2313 transceiver->receiver()->streams());
Steve Antonef65ef12018-01-10 17:15:20 -08002314 }
Steve Antonc49bcd92018-02-14 14:28:13 -08002315 for (auto stream : added_streams) {
2316 observer_->OnAddStream(stream);
2317 }
Steve Antondcc3c022017-12-22 16:02:54 -08002318 }
2319
Henrik Boströmfdb92012017-11-09 19:55:44 +01002320 const cricket::ContentInfo* audio_content =
2321 GetFirstAudioContent(remote_description()->description());
2322 const cricket::ContentInfo* video_content =
2323 GetFirstVideoContent(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002324 const cricket::AudioContentDescription* audio_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002325 GetFirstAudioContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002326 const cricket::VideoContentDescription* video_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002327 GetFirstVideoContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002328 const cricket::DataContentDescription* data_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002329 GetFirstDataContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002330
2331 // Check if the descriptions include streams, just in case the peer supports
2332 // MSID, but doesn't indicate so with "a=msid-semantic".
Henrik Boströmfdb92012017-11-09 19:55:44 +01002333 if (remote_description()->description()->msid_supported() ||
deadbeefbda7e0b2015-12-08 17:13:40 -08002334 (audio_desc && !audio_desc->streams().empty()) ||
2335 (video_desc && !video_desc->streams().empty())) {
2336 remote_peer_supports_msid_ = true;
2337 }
deadbeefab9b2d12015-10-14 11:33:11 -07002338
2339 // We wait to signal new streams until we finish processing the description,
2340 // since only at that point will new streams have all their tracks.
2341 rtc::scoped_refptr<StreamCollection> new_streams(StreamCollection::Create());
2342
Steve Antondcc3c022017-12-22 16:02:54 -08002343 if (!IsUnifiedPlan()) {
2344 // TODO(steveanton): When removing RTP senders/receivers in response to a
2345 // rejected media section, there is some cleanup logic that expects the
2346 // voice/ video channel to still be set. But in this method the voice/video
2347 // channel would have been destroyed by the SetRemoteDescription caller
2348 // above so the cleanup that relies on them fails to run. The RemoveSenders
2349 // calls should be moved to right before the DestroyChannel calls to fix
2350 // this.
Steve Anton8d3444d2017-10-20 15:30:51 -07002351
Steve Antondcc3c022017-12-22 16:02:54 -08002352 // Find all audio rtp streams and create corresponding remote AudioTracks
2353 // and MediaStreams.
2354 if (audio_content) {
2355 if (audio_content->rejected) {
2356 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
2357 } else {
2358 bool default_audio_track_needed =
2359 !remote_peer_supports_msid_ &&
2360 RtpTransceiverDirectionHasSend(audio_desc->direction());
2361 UpdateRemoteSendersList(GetActiveStreams(audio_desc),
2362 default_audio_track_needed, audio_desc->type(),
2363 new_streams);
2364 }
deadbeeffaac4972015-11-12 15:33:07 -08002365 }
deadbeefab9b2d12015-10-14 11:33:11 -07002366
Steve Antondcc3c022017-12-22 16:02:54 -08002367 // Find all video rtp streams and create corresponding remote VideoTracks
2368 // and MediaStreams.
2369 if (video_content) {
2370 if (video_content->rejected) {
2371 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
2372 } else {
2373 bool default_video_track_needed =
2374 !remote_peer_supports_msid_ &&
2375 RtpTransceiverDirectionHasSend(video_desc->direction());
2376 UpdateRemoteSendersList(GetActiveStreams(video_desc),
2377 default_video_track_needed, video_desc->type(),
2378 new_streams);
2379 }
deadbeeffaac4972015-11-12 15:33:07 -08002380 }
deadbeefab9b2d12015-10-14 11:33:11 -07002381
Steve Antondcc3c022017-12-22 16:02:54 -08002382 // Update the DataChannels with the information from the remote peer.
2383 if (data_desc) {
2384 if (rtc::starts_with(data_desc->protocol().data(),
2385 cricket::kMediaProtocolRtpPrefix)) {
2386 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
2387 }
deadbeefab9b2d12015-10-14 11:33:11 -07002388 }
deadbeefab9b2d12015-10-14 11:33:11 -07002389
Steve Antondcc3c022017-12-22 16:02:54 -08002390 // Iterate new_streams and notify the observer about new MediaStreams.
2391 for (size_t i = 0; i < new_streams->count(); ++i) {
2392 MediaStreamInterface* new_stream = new_streams->at(i);
2393 stats_->AddStream(new_stream);
2394 observer_->OnAddStream(
2395 rtc::scoped_refptr<MediaStreamInterface>(new_stream));
2396 }
deadbeefab9b2d12015-10-14 11:33:11 -07002397
Steve Antondcc3c022017-12-22 16:02:54 -08002398 UpdateEndedRemoteMediaStreams();
2399 }
deadbeefab9b2d12015-10-14 11:33:11 -07002400
Steve Anton8a006912017-12-04 15:25:56 -08002401 return RTCError::OK();
deadbeeffc648b62015-10-13 16:42:33 -07002402}
2403
Steve Antondcc3c022017-12-22 16:02:54 -08002404RTCError PeerConnection::UpdateTransceiversAndDataChannels(
2405 cricket::ContentSource source,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002406 const SessionDescriptionInterface& new_session,
2407 const SessionDescriptionInterface* old_local_description,
2408 const SessionDescriptionInterface* old_remote_description) {
Steve Antondcc3c022017-12-22 16:02:54 -08002409 RTC_DCHECK(IsUnifiedPlan());
2410
Steve Anton7464fca2018-01-19 11:10:37 -08002411 const cricket::ContentGroup* bundle_group = nullptr;
2412 if (new_session.GetType() == SdpType::kOffer) {
2413 auto bundle_group_or_error =
2414 GetEarlyBundleGroup(*new_session.description());
2415 if (!bundle_group_or_error.ok()) {
2416 return bundle_group_or_error.MoveError();
2417 }
2418 bundle_group = bundle_group_or_error.MoveValue();
Steve Antondcc3c022017-12-22 16:02:54 -08002419 }
Steve Antondcc3c022017-12-22 16:02:54 -08002420
Steve Antondcc3c022017-12-22 16:02:54 -08002421 const ContentInfos& new_contents = new_session.description()->contents();
Steve Antondcc3c022017-12-22 16:02:54 -08002422 for (size_t i = 0; i < new_contents.size(); ++i) {
2423 const cricket::ContentInfo& new_content = new_contents[i];
Steve Antondcc3c022017-12-22 16:02:54 -08002424 cricket::MediaType media_type = new_content.media_description()->type();
2425 seen_mids_.insert(new_content.name);
2426 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
2427 media_type == cricket::MEDIA_TYPE_VIDEO) {
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002428 const cricket::ContentInfo* old_local_content = nullptr;
2429 if (old_local_description &&
2430 i < old_local_description->description()->contents().size()) {
2431 old_local_content =
2432 &old_local_description->description()->contents()[i];
2433 }
2434 const cricket::ContentInfo* old_remote_content = nullptr;
2435 if (old_remote_description &&
2436 i < old_remote_description->description()->contents().size()) {
2437 old_remote_content =
2438 &old_remote_description->description()->contents()[i];
2439 }
Steve Antondcc3c022017-12-22 16:02:54 -08002440 auto transceiver_or_error =
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002441 AssociateTransceiver(source, new_session.GetType(), i, new_content,
2442 old_local_content, old_remote_content);
Steve Antondcc3c022017-12-22 16:02:54 -08002443 if (!transceiver_or_error.ok()) {
2444 return transceiver_or_error.MoveError();
2445 }
2446 auto transceiver = transceiver_or_error.MoveValue();
Steve Antondcc3c022017-12-22 16:02:54 -08002447 RTCError error =
2448 UpdateTransceiverChannel(transceiver, new_content, bundle_group);
2449 if (!error.ok()) {
2450 return error;
2451 }
2452 } else if (media_type == cricket::MEDIA_TYPE_DATA) {
Steve Antonfa2260d2017-12-28 16:38:23 -08002453 if (GetDataMid() && new_content.name != *GetDataMid()) {
2454 // Ignore all but the first data section.
2455 continue;
2456 }
2457 RTCError error = UpdateDataChannel(source, new_content, bundle_group);
2458 if (!error.ok()) {
2459 return error;
2460 }
Steve Antondcc3c022017-12-22 16:02:54 -08002461 } else {
2462 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
2463 "Unknown section type.");
2464 }
2465 }
2466
2467 return RTCError::OK();
2468}
2469
2470RTCError PeerConnection::UpdateTransceiverChannel(
2471 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2472 transceiver,
2473 const cricket::ContentInfo& content,
2474 const cricket::ContentGroup* bundle_group) {
2475 RTC_DCHECK(IsUnifiedPlan());
2476 RTC_DCHECK(transceiver);
2477 cricket::BaseChannel* channel = transceiver->internal()->channel();
2478 if (content.rejected) {
2479 if (channel) {
2480 transceiver->internal()->SetChannel(nullptr);
2481 DestroyBaseChannel(channel);
2482 }
2483 } else {
2484 if (!channel) {
Steve Anton69470252018-02-09 11:43:08 -08002485 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Steve Antondcc3c022017-12-22 16:02:54 -08002486 channel = CreateVoiceChannel(
2487 content.name,
2488 GetTransportNameForMediaSection(content.name, bundle_group));
2489 } else {
Steve Anton69470252018-02-09 11:43:08 -08002490 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, transceiver->media_type());
Steve Antondcc3c022017-12-22 16:02:54 -08002491 channel = CreateVideoChannel(
2492 content.name,
2493 GetTransportNameForMediaSection(content.name, bundle_group));
2494 }
2495 if (!channel) {
2496 LOG_AND_RETURN_ERROR(
2497 RTCErrorType::INTERNAL_ERROR,
2498 "Failed to create channel for mid=" + content.name);
2499 }
2500 transceiver->internal()->SetChannel(channel);
2501 }
2502 }
2503 return RTCError::OK();
2504}
2505
Steve Antonfa2260d2017-12-28 16:38:23 -08002506RTCError PeerConnection::UpdateDataChannel(
2507 cricket::ContentSource source,
2508 const cricket::ContentInfo& content,
2509 const cricket::ContentGroup* bundle_group) {
2510 if (data_channel_type_ == cricket::DCT_NONE) {
Steve Antondbf9d032018-01-19 15:23:40 -08002511 // If data channels are disabled, ignore this media section. CreateAnswer
2512 // will take care of rejecting it.
2513 return RTCError::OK();
Steve Antonfa2260d2017-12-28 16:38:23 -08002514 }
2515 if (content.rejected) {
2516 DestroyDataChannel();
2517 } else {
2518 if (!rtp_data_channel_ && !sctp_transport_) {
2519 if (!CreateDataChannel(content.name, GetTransportNameForMediaSection(
2520 content.name, bundle_group))) {
2521 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
2522 "Failed to create data channel.");
2523 }
2524 }
2525 if (source == cricket::CS_REMOTE) {
2526 const MediaContentDescription* data_desc = content.media_description();
2527 if (data_desc && cricket::IsRtpProtocol(data_desc->protocol())) {
2528 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
2529 }
2530 }
2531 }
2532 return RTCError::OK();
2533}
2534
Steve Antondcc3c022017-12-22 16:02:54 -08002535RTCErrorOr<rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
2536PeerConnection::AssociateTransceiver(cricket::ContentSource source,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002537 SdpType type,
Steve Antondcc3c022017-12-22 16:02:54 -08002538 size_t mline_index,
2539 const ContentInfo& content,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002540 const ContentInfo* old_local_content,
2541 const ContentInfo* old_remote_content) {
Steve Antondcc3c022017-12-22 16:02:54 -08002542 RTC_DCHECK(IsUnifiedPlan());
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002543 // If this is an offer then the m= section might be recycled. If the m=
2544 // section is being recycled (defined as: rejected in the current local or
2545 // remote description and not rejected in new description), dissociate the
2546 // currently associated RtpTransceiver by setting its mid property to null,
2547 // and discard the mapping between the transceiver and its m= section index.
2548 if (IsMediaSectionBeingRecycled(type, content, old_local_content,
2549 old_remote_content)) {
2550 // We want to dissociate the transceiver that has the rejected mid.
2551 const std::string& old_mid =
2552 (old_local_content && old_local_content->rejected)
2553 ? old_local_content->name
2554 : old_remote_content->name;
2555 auto old_transceiver = GetAssociatedTransceiver(old_mid);
Steve Antondcc3c022017-12-22 16:02:54 -08002556 if (old_transceiver) {
2557 old_transceiver->internal()->set_mid(rtc::nullopt);
2558 old_transceiver->internal()->set_mline_index(rtc::nullopt);
2559 }
2560 }
2561 const MediaContentDescription* media_desc = content.media_description();
2562 auto transceiver = GetAssociatedTransceiver(content.name);
2563 if (source == cricket::CS_LOCAL) {
2564 // Find the RtpTransceiver that corresponds to this m= section, using the
2565 // mapping between transceivers and m= section indices established when
2566 // creating the offer.
2567 if (!transceiver) {
2568 transceiver = GetTransceiverByMLineIndex(mline_index);
2569 }
2570 if (!transceiver) {
2571 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2572 "Unknown transceiver");
2573 }
2574 } else {
2575 RTC_DCHECK_EQ(source, cricket::CS_REMOTE);
2576 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers
2577 // of the same type...
2578 if (!transceiver &&
2579 RtpTransceiverDirectionHasRecv(media_desc->direction())) {
2580 transceiver = FindAvailableTransceiverToReceive(media_desc->type());
2581 }
2582 // If no RtpTransceiver was found in the previous step, create one with a
2583 // recvonly direction.
2584 if (!transceiver) {
Steve Anton02ee47c2018-01-10 16:26:06 -08002585 auto sender =
2586 CreateSender(media_desc->type(), nullptr, {rtc::CreateRandomUuid()});
Steve Anton5f94aa22018-02-01 10:58:30 -08002587 std::string receiver_id;
2588 if (!media_desc->streams().empty()) {
2589 receiver_id = media_desc->streams()[0].id;
2590 } else {
2591 receiver_id = rtc::CreateRandomUuid();
2592 }
2593 auto receiver = CreateReceiver(media_desc->type(), receiver_id);
Steve Anton02ee47c2018-01-10 16:26:06 -08002594 transceiver = CreateAndAddTransceiver(sender, receiver);
Steve Antondcc3c022017-12-22 16:02:54 -08002595 transceiver->internal()->set_direction(
2596 RtpTransceiverDirection::kRecvOnly);
2597 }
2598 }
2599 RTC_DCHECK(transceiver);
Steve Anton69470252018-02-09 11:43:08 -08002600 if (transceiver->media_type() != media_desc->type()) {
Steve Antondcc3c022017-12-22 16:02:54 -08002601 LOG_AND_RETURN_ERROR(
2602 RTCErrorType::INVALID_PARAMETER,
2603 "Transceiver type does not match media description type.");
2604 }
2605 // Associate the found or created RtpTransceiver with the m= section by
2606 // setting the value of the RtpTransceiver's mid property to the MID of the m=
2607 // section, and establish a mapping between the transceiver and the index of
2608 // the m= section.
2609 transceiver->internal()->set_mid(content.name);
2610 transceiver->internal()->set_mline_index(mline_index);
2611 return std::move(transceiver);
2612}
2613
2614rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2615PeerConnection::GetAssociatedTransceiver(const std::string& mid) const {
2616 RTC_DCHECK(IsUnifiedPlan());
2617 for (auto transceiver : transceivers_) {
2618 if (transceiver->mid() == mid) {
2619 return transceiver;
2620 }
2621 }
2622 return nullptr;
2623}
2624
2625rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2626PeerConnection::GetTransceiverByMLineIndex(size_t mline_index) const {
2627 RTC_DCHECK(IsUnifiedPlan());
2628 for (auto transceiver : transceivers_) {
2629 if (transceiver->internal()->mline_index() == mline_index) {
2630 return transceiver;
2631 }
2632 }
2633 return nullptr;
2634}
2635
2636rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2637PeerConnection::FindAvailableTransceiverToReceive(
2638 cricket::MediaType media_type) const {
2639 RTC_DCHECK(IsUnifiedPlan());
2640 // From JSEP section 5.10 (Applying a Remote Description):
2641 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers of
2642 // the same type that were added to the PeerConnection by addTrack and are not
2643 // associated with any m= section and are not stopped, find the first such
2644 // RtpTransceiver.
2645 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08002646 if (transceiver->media_type() == media_type &&
Steve Antondcc3c022017-12-22 16:02:54 -08002647 transceiver->internal()->created_by_addtrack() && !transceiver->mid() &&
2648 !transceiver->stopped()) {
2649 return transceiver;
2650 }
2651 }
2652 return nullptr;
2653}
2654
Steve Antoned10bd92017-12-05 10:52:59 -08002655const cricket::ContentInfo* PeerConnection::FindMediaSectionForTransceiver(
2656 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2657 transceiver,
2658 const SessionDescriptionInterface* sdesc) const {
2659 RTC_DCHECK(transceiver);
2660 RTC_DCHECK(sdesc);
2661 if (IsUnifiedPlan()) {
2662 if (!transceiver->internal()->mid()) {
2663 // This transceiver is not associated with a media section yet.
2664 return nullptr;
2665 }
2666 return sdesc->description()->GetContentByName(
2667 *transceiver->internal()->mid());
2668 } else {
2669 // Plan B only allows at most one audio and one video section, so use the
2670 // first media section of that type.
2671 return cricket::GetFirstMediaContent(sdesc->description()->contents(),
Steve Anton69470252018-02-09 11:43:08 -08002672 transceiver->media_type());
Steve Antoned10bd92017-12-05 10:52:59 -08002673 }
2674}
2675
deadbeef46c73892016-11-16 19:42:04 -08002676PeerConnectionInterface::RTCConfiguration PeerConnection::GetConfiguration() {
2677 return configuration_;
2678}
2679
deadbeef293e9262017-01-11 12:28:30 -08002680bool PeerConnection::SetConfiguration(const RTCConfiguration& configuration,
2681 RTCError* error) {
Peter Boström1a9d6152015-12-08 22:15:17 +01002682 TRACE_EVENT0("webrtc", "PeerConnection::SetConfiguration");
deadbeef6de92f92016-12-12 18:49:32 -08002683
Steve Anton75737c02017-11-06 10:37:17 -08002684 if (local_description() && configuration.ice_candidate_pool_size !=
2685 configuration_.ice_candidate_pool_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002686 RTC_LOG(LS_ERROR) << "Can't change candidate pool size after calling "
2687 "SetLocalDescription.";
deadbeef293e9262017-01-11 12:28:30 -08002688 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00002689 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002690
deadbeef293e9262017-01-11 12:28:30 -08002691 // The simplest (and most future-compatible) way to tell if the config was
2692 // modified in an invalid way is to copy each property we do support
2693 // modifying, then use operator==. There are far more properties we don't
2694 // support modifying than those we do, and more could be added.
2695 RTCConfiguration modified_config = configuration_;
2696 modified_config.servers = configuration.servers;
2697 modified_config.type = configuration.type;
2698 modified_config.ice_candidate_pool_size =
2699 configuration.ice_candidate_pool_size;
2700 modified_config.prune_turn_ports = configuration.prune_turn_ports;
skvladd1f5fda2017-02-03 16:54:05 -08002701 modified_config.ice_check_min_interval = configuration.ice_check_min_interval;
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08002702 modified_config.stun_candidate_keepalive_interval =
2703 configuration.stun_candidate_keepalive_interval;
Jonas Orelandbdcee282017-10-10 14:01:40 +02002704 modified_config.turn_customizer = configuration.turn_customizer;
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08002705 modified_config.network_preference = configuration.network_preference;
deadbeef293e9262017-01-11 12:28:30 -08002706 if (configuration != modified_config) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002707 RTC_LOG(LS_ERROR) << "Modifying the configuration in an unsupported way.";
deadbeef293e9262017-01-11 12:28:30 -08002708 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
2709 }
2710
Steve Anton038834f2017-07-14 15:59:59 -07002711 // Validate the modified configuration.
2712 RTCError validate_error = ValidateConfiguration(modified_config);
2713 if (!validate_error.ok()) {
2714 return SafeSetError(std::move(validate_error), error);
2715 }
2716
deadbeef293e9262017-01-11 12:28:30 -08002717 // Note that this isn't possible through chromium, since it's an unsigned
2718 // short in WebIDL.
2719 if (configuration.ice_candidate_pool_size < 0 ||
2720 configuration.ice_candidate_pool_size > UINT16_MAX) {
2721 return SafeSetError(RTCErrorType::INVALID_RANGE, error);
2722 }
2723
2724 // Parse ICE servers before hopping to network thread.
2725 cricket::ServerAddresses stun_servers;
2726 std::vector<cricket::RelayServerConfig> turn_servers;
2727 RTCErrorType parse_error =
2728 ParseIceServers(configuration.servers, &stun_servers, &turn_servers);
2729 if (parse_error != RTCErrorType::NONE) {
2730 return SafeSetError(parse_error, error);
2731 }
2732
2733 // In theory this shouldn't fail.
2734 if (!network_thread()->Invoke<bool>(
2735 RTC_FROM_HERE,
2736 rtc::Bind(&PeerConnection::ReconfigurePortAllocator_n, this,
2737 stun_servers, turn_servers, modified_config.type,
2738 modified_config.ice_candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02002739 modified_config.prune_turn_ports,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08002740 modified_config.turn_customizer,
2741 modified_config.stun_candidate_keepalive_interval))) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002742 RTC_LOG(LS_ERROR) << "Failed to apply configuration to PortAllocator.";
deadbeef293e9262017-01-11 12:28:30 -08002743 return SafeSetError(RTCErrorType::INTERNAL_ERROR, error);
2744 }
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07002745
deadbeefd1a38b52016-12-10 13:15:33 -08002746 // As described in JSEP, calling setConfiguration with new ICE servers or
2747 // candidate policy must set a "needs-ice-restart" bit so that the next offer
2748 // triggers an ICE restart which will pick up the changes.
deadbeef293e9262017-01-11 12:28:30 -08002749 if (modified_config.servers != configuration_.servers ||
2750 modified_config.type != configuration_.type ||
2751 modified_config.prune_turn_ports != configuration_.prune_turn_ports) {
Steve Antond25da372017-11-06 14:50:29 -08002752 transport_controller_->SetNeedsIceRestartFlag();
deadbeefd1a38b52016-12-10 13:15:33 -08002753 }
skvladd1f5fda2017-02-03 16:54:05 -08002754
Qingsi Wang9c98f0c2018-02-15 15:10:59 -08002755 transport_controller_->SetIceConfig(ParseIceConfig(modified_config));
skvladd1f5fda2017-02-03 16:54:05 -08002756
deadbeef293e9262017-01-11 12:28:30 -08002757 configuration_ = modified_config;
2758 return SafeSetError(RTCErrorType::NONE, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00002759}
2760
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002761bool PeerConnection::AddIceCandidate(
2762 const IceCandidateInterface* ice_candidate) {
Peter Boström1a9d6152015-12-08 22:15:17 +01002763 TRACE_EVENT0("webrtc", "PeerConnection::AddIceCandidate");
zhihuang29ff8442016-07-27 11:07:25 -07002764 if (IsClosed()) {
2765 return false;
2766 }
Steve Antond25da372017-11-06 14:50:29 -08002767
2768 if (!remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002769 RTC_LOG(LS_ERROR) << "ProcessIceMessage: ICE candidates can't be added "
Jonas Olsson45cc8902018-02-13 10:37:07 +01002770 "without any remote session description.";
Steve Antond25da372017-11-06 14:50:29 -08002771 return false;
2772 }
2773
2774 if (!ice_candidate) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002775 RTC_LOG(LS_ERROR) << "ProcessIceMessage: Candidate is NULL.";
Steve Antond25da372017-11-06 14:50:29 -08002776 return false;
2777 }
2778
2779 bool valid = false;
2780 bool ready = ReadyToUseRemoteCandidate(ice_candidate, nullptr, &valid);
2781 if (!valid) {
2782 return false;
2783 }
2784
2785 // Add this candidate to the remote session description.
2786 if (!mutable_remote_description()->AddCandidate(ice_candidate)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002787 RTC_LOG(LS_ERROR) << "ProcessIceMessage: Candidate cannot be used.";
Steve Antond25da372017-11-06 14:50:29 -08002788 return false;
2789 }
2790
2791 if (ready) {
2792 return UseCandidate(ice_candidate);
2793 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002794 RTC_LOG(LS_INFO) << "ProcessIceMessage: Not ready to use candidate.";
Steve Antond25da372017-11-06 14:50:29 -08002795 return true;
2796 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002797}
2798
Honghai Zhang7fb69db2016-03-14 11:59:18 -07002799bool PeerConnection::RemoveIceCandidates(
2800 const std::vector<cricket::Candidate>& candidates) {
2801 TRACE_EVENT0("webrtc", "PeerConnection::RemoveIceCandidates");
Steve Antond25da372017-11-06 14:50:29 -08002802 if (!remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002803 RTC_LOG(LS_ERROR) << "RemoveRemoteIceCandidates: ICE candidates can't be "
Jonas Olsson45cc8902018-02-13 10:37:07 +01002804 "removed without any remote session description.";
Steve Antond25da372017-11-06 14:50:29 -08002805 return false;
2806 }
2807
2808 if (candidates.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002809 RTC_LOG(LS_ERROR) << "RemoveRemoteIceCandidates: candidates are empty.";
Steve Antond25da372017-11-06 14:50:29 -08002810 return false;
2811 }
2812
2813 size_t number_removed =
2814 mutable_remote_description()->RemoveCandidates(candidates);
2815 if (number_removed != candidates.size()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002816 RTC_LOG(LS_ERROR)
2817 << "RemoveRemoteIceCandidates: Failed to remove candidates. "
Jonas Olsson45cc8902018-02-13 10:37:07 +01002818 "Requested "
2819 << candidates.size() << " but only " << number_removed
Mirko Bonadei675513b2017-11-09 11:09:25 +01002820 << " are removed.";
Steve Antond25da372017-11-06 14:50:29 -08002821 }
2822
2823 // Remove the candidates from the transport controller.
2824 std::string error;
2825 bool res = transport_controller_->RemoveRemoteCandidates(candidates, &error);
2826 if (!res && !error.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002827 RTC_LOG(LS_ERROR) << "Error when removing remote candidates: " << error;
Steve Antond25da372017-11-06 14:50:29 -08002828 }
2829 return true;
Honghai Zhang7fb69db2016-03-14 11:59:18 -07002830}
2831
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00002832void PeerConnection::RegisterUMAObserver(UMAObserver* observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +01002833 TRACE_EVENT0("webrtc", "PeerConnection::RegisterUmaObserver");
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00002834 uma_observer_ = observer;
guoweis@webrtc.org7169afd2014-12-04 17:59:29 +00002835
Steve Anton75737c02017-11-06 10:37:17 -08002836 if (transport_controller()) {
2837 transport_controller()->SetMetricsObserver(uma_observer_);
guoweis@webrtc.org7169afd2014-12-04 17:59:29 +00002838 }
2839
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00002840 // Send information about IPv4/IPv6 status.
deadbeef293e9262017-01-11 12:28:30 -08002841 if (uma_observer_) {
Honghai Zhangd93f50c2016-10-05 11:47:22 -07002842 port_allocator_->SetMetricsObserver(uma_observer_);
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00002843 if (port_allocator_->flags() & cricket::PORTALLOCATOR_ENABLE_IPV6) {
Guo-wei Shiehdfbe6792015-09-03 17:12:07 -07002844 uma_observer_->IncrementEnumCounter(
2845 kEnumCounterAddressFamily, kPeerConnection_IPv6,
2846 kPeerConnectionAddressFamilyCounter_Max);
mallinath@webrtc.orgb445f262014-05-23 22:19:37 +00002847 } else {
Guo-wei Shiehdfbe6792015-09-03 17:12:07 -07002848 uma_observer_->IncrementEnumCounter(
2849 kEnumCounterAddressFamily, kPeerConnection_IPv4,
2850 kPeerConnectionAddressFamilyCounter_Max);
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00002851 }
Harald Alvestrand5dbb5862018-02-13 23:48:00 +01002852 // Send information about the requested SDP semantics.
2853 switch (configuration_.sdp_semantics) {
2854 case SdpSemantics::kDefault:
2855 uma_observer_->IncrementEnumCounter(kEnumCounterSdpSemanticRequested,
2856 kSdpSemanticRequestDefault,
2857 kSdpSemanticRequestMax);
2858
2859 break;
2860 case SdpSemantics::kPlanB:
2861 uma_observer_->IncrementEnumCounter(kEnumCounterSdpSemanticRequested,
2862 kSdpSemanticRequestPlanB,
2863 kSdpSemanticRequestMax);
2864 break;
2865 case SdpSemantics::kUnifiedPlan:
2866 uma_observer_->IncrementEnumCounter(kEnumCounterSdpSemanticRequested,
2867 kSdpSemanticRequestUnifiedPlan,
2868 kSdpSemanticRequestMax);
2869 break;
2870 default:
2871 RTC_NOTREACHED();
2872 }
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00002873 }
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00002874}
2875
zstein4b979802017-06-02 14:37:37 -07002876RTCError PeerConnection::SetBitrate(const BitrateParameters& bitrate) {
Steve Anton978b8762017-09-29 12:15:02 -07002877 if (!worker_thread()->IsCurrent()) {
2878 return worker_thread()->Invoke<RTCError>(
zstein4b979802017-06-02 14:37:37 -07002879 RTC_FROM_HERE, rtc::Bind(&PeerConnection::SetBitrate, this, bitrate));
2880 }
2881
2882 const bool has_min = static_cast<bool>(bitrate.min_bitrate_bps);
2883 const bool has_current = static_cast<bool>(bitrate.current_bitrate_bps);
2884 const bool has_max = static_cast<bool>(bitrate.max_bitrate_bps);
2885 if (has_min && *bitrate.min_bitrate_bps < 0) {
2886 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2887 "min_bitrate_bps <= 0");
2888 }
2889 if (has_current) {
2890 if (has_min && *bitrate.current_bitrate_bps < *bitrate.min_bitrate_bps) {
2891 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2892 "current_bitrate_bps < min_bitrate_bps");
2893 } else if (*bitrate.current_bitrate_bps < 0) {
2894 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2895 "curent_bitrate_bps < 0");
2896 }
2897 }
2898 if (has_max) {
2899 if (has_current &&
2900 *bitrate.max_bitrate_bps < *bitrate.current_bitrate_bps) {
2901 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2902 "max_bitrate_bps < current_bitrate_bps");
2903 } else if (has_min && *bitrate.max_bitrate_bps < *bitrate.min_bitrate_bps) {
2904 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2905 "max_bitrate_bps < min_bitrate_bps");
2906 } else if (*bitrate.max_bitrate_bps < 0) {
2907 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2908 "max_bitrate_bps < 0");
2909 }
2910 }
2911
Sebastian Janssonfc8d26b2018-02-21 09:52:06 +01002912 BitrateConstraintsMask mask;
zstein4b979802017-06-02 14:37:37 -07002913 mask.min_bitrate_bps = bitrate.min_bitrate_bps;
2914 mask.start_bitrate_bps = bitrate.current_bitrate_bps;
2915 mask.max_bitrate_bps = bitrate.max_bitrate_bps;
2916
2917 RTC_DCHECK(call_.get());
Sebastian Jansson8f83b422018-02-21 13:07:13 +01002918 call_->GetTransportControllerSend()->SetClientBitratePreferences(mask);
zstein4b979802017-06-02 14:37:37 -07002919
2920 return RTCError::OK();
2921}
2922
Alex Narest78609d52017-10-20 10:37:47 +02002923void PeerConnection::SetBitrateAllocationStrategy(
2924 std::unique_ptr<rtc::BitrateAllocationStrategy>
2925 bitrate_allocation_strategy) {
2926 rtc::Thread* worker_thread = factory_->worker_thread();
2927 if (!worker_thread->IsCurrent()) {
2928 rtc::BitrateAllocationStrategy* strategy_raw =
2929 bitrate_allocation_strategy.release();
2930 auto functor = [this, strategy_raw]() {
2931 call_->SetBitrateAllocationStrategy(
2932 rtc::WrapUnique<rtc::BitrateAllocationStrategy>(strategy_raw));
2933 };
2934 worker_thread->Invoke<void>(RTC_FROM_HERE, functor);
2935 return;
2936 }
2937 RTC_DCHECK(call_.get());
2938 call_->SetBitrateAllocationStrategy(std::move(bitrate_allocation_strategy));
2939}
2940
henrika5f6bf242017-11-01 11:06:56 +01002941void PeerConnection::SetAudioPlayout(bool playout) {
2942 if (!worker_thread()->IsCurrent()) {
2943 worker_thread()->Invoke<void>(
2944 RTC_FROM_HERE,
2945 rtc::Bind(&PeerConnection::SetAudioPlayout, this, playout));
2946 return;
2947 }
2948 auto audio_state =
2949 factory_->channel_manager()->media_engine()->GetAudioState();
2950 audio_state->SetPlayout(playout);
2951}
2952
2953void PeerConnection::SetAudioRecording(bool recording) {
2954 if (!worker_thread()->IsCurrent()) {
2955 worker_thread()->Invoke<void>(
2956 RTC_FROM_HERE,
2957 rtc::Bind(&PeerConnection::SetAudioRecording, this, recording));
2958 return;
2959 }
2960 auto audio_state =
2961 factory_->channel_manager()->media_engine()->GetAudioState();
2962 audio_state->SetRecording(recording);
2963}
2964
Steve Anton8c0f7a72017-10-03 10:03:10 -07002965std::unique_ptr<rtc::SSLCertificate>
2966PeerConnection::GetRemoteAudioSSLCertificate() {
Taylor Brandstetterc3928662018-02-23 13:04:51 -08002967 std::unique_ptr<rtc::SSLCertChain> chain = GetRemoteAudioSSLCertChain();
2968 if (!chain || !chain->GetSize()) {
Steve Anton8c0f7a72017-10-03 10:03:10 -07002969 return nullptr;
2970 }
Taylor Brandstetterc3928662018-02-23 13:04:51 -08002971 return chain->Get(0).GetUniqueReference();
Steve Anton8c0f7a72017-10-03 10:03:10 -07002972}
2973
Zhi Huang70b820f2018-01-27 14:16:15 -08002974std::unique_ptr<rtc::SSLCertChain>
2975PeerConnection::GetRemoteAudioSSLCertChain() {
Steve Antonafb0bb72018-02-20 11:35:37 -08002976 auto audio_transceiver = GetFirstAudioTransceiver();
2977 if (!audio_transceiver || !audio_transceiver->internal()->channel()) {
Zhi Huang70b820f2018-01-27 14:16:15 -08002978 return nullptr;
2979 }
Zhi Huang70b820f2018-01-27 14:16:15 -08002980 return transport_controller_->GetRemoteSSLCertChain(
Steve Antonafb0bb72018-02-20 11:35:37 -08002981 audio_transceiver->internal()->channel()->transport_name());
2982}
2983
2984rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2985PeerConnection::GetFirstAudioTransceiver() const {
2986 for (auto transceiver : transceivers_) {
2987 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
2988 return transceiver;
2989 }
2990 }
2991 return nullptr;
Zhi Huang70b820f2018-01-27 14:16:15 -08002992}
2993
ivoc14d5dbe2016-07-04 07:06:55 -07002994bool PeerConnection::StartRtcEventLog(rtc::PlatformFile file,
2995 int64_t max_size_bytes) {
Elad Alon99c3fe52017-10-13 16:29:40 +02002996 // TODO(eladalon): It would be better to not allow negative values into PC.
2997 const size_t max_size = (max_size_bytes < 0)
2998 ? RtcEventLog::kUnlimitedOutput
2999 : rtc::saturated_cast<size_t>(max_size_bytes);
3000 return StartRtcEventLog(
Bjorn Tereliusde939432017-11-20 17:38:14 +01003001 rtc::MakeUnique<RtcEventLogOutputFile>(file, max_size),
3002 webrtc::RtcEventLog::kImmediateOutput);
Elad Alon99c3fe52017-10-13 16:29:40 +02003003}
3004
Bjorn Tereliusde939432017-11-20 17:38:14 +01003005bool PeerConnection::StartRtcEventLog(std::unique_ptr<RtcEventLogOutput> output,
3006 int64_t output_period_ms) {
Karl Wibergd6b48192017-10-16 23:01:06 +02003007 // TODO(eladalon): In C++14, this can be done with a lambda.
3008 struct Functor {
Bjorn Tereliusde939432017-11-20 17:38:14 +01003009 bool operator()() {
3010 return pc->StartRtcEventLog_w(std::move(output), output_period_ms);
3011 }
Karl Wibergd6b48192017-10-16 23:01:06 +02003012 PeerConnection* const pc;
3013 std::unique_ptr<RtcEventLogOutput> output;
Bjorn Tereliusde939432017-11-20 17:38:14 +01003014 const int64_t output_period_ms;
Elad Alon99c3fe52017-10-13 16:29:40 +02003015 };
Bjorn Tereliusde939432017-11-20 17:38:14 +01003016 return worker_thread()->Invoke<bool>(
3017 RTC_FROM_HERE, Functor{this, std::move(output), output_period_ms});
ivoc14d5dbe2016-07-04 07:06:55 -07003018}
3019
3020void PeerConnection::StopRtcEventLog() {
Steve Anton978b8762017-09-29 12:15:02 -07003021 worker_thread()->Invoke<void>(
ivoc14d5dbe2016-07-04 07:06:55 -07003022 RTC_FROM_HERE, rtc::Bind(&PeerConnection::StopRtcEventLog_w, this));
3023}
3024
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003025const SessionDescriptionInterface* PeerConnection::local_description() const {
Steve Anton75737c02017-11-06 10:37:17 -08003026 return pending_local_description_ ? pending_local_description_.get()
3027 : current_local_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003028}
3029
3030const SessionDescriptionInterface* PeerConnection::remote_description() const {
Steve Anton75737c02017-11-06 10:37:17 -08003031 return pending_remote_description_ ? pending_remote_description_.get()
3032 : current_remote_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003033}
3034
deadbeeffe4a8a42016-12-20 17:56:17 -08003035const SessionDescriptionInterface* PeerConnection::current_local_description()
3036 const {
Steve Anton75737c02017-11-06 10:37:17 -08003037 return current_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003038}
3039
3040const SessionDescriptionInterface* PeerConnection::current_remote_description()
3041 const {
Steve Anton75737c02017-11-06 10:37:17 -08003042 return current_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003043}
3044
3045const SessionDescriptionInterface* PeerConnection::pending_local_description()
3046 const {
Steve Anton75737c02017-11-06 10:37:17 -08003047 return pending_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003048}
3049
3050const SessionDescriptionInterface* PeerConnection::pending_remote_description()
3051 const {
Steve Anton75737c02017-11-06 10:37:17 -08003052 return pending_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003053}
3054
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003055void PeerConnection::Close() {
Peter Boström1a9d6152015-12-08 22:15:17 +01003056 TRACE_EVENT0("webrtc", "PeerConnection::Close");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003057 // Update stats here so that we have the most recent stats for tracks and
3058 // streams before the channels are closed.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00003059 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003060
Steve Anton75737c02017-11-06 10:37:17 -08003061 ChangeSignalingState(PeerConnectionInterface::kClosed);
Steve Anton3fe1b152017-12-12 10:20:08 -08003062
Steve Anton8af21862017-12-15 11:20:13 -08003063 for (auto transceiver : transceivers_) {
3064 transceiver->Stop();
3065 }
3066 DestroyAllChannels();
Steve Anton75737c02017-11-06 10:37:17 -08003067
Qingsi Wang93a84392018-01-30 17:13:09 -08003068 // The event log is used in the transport controller, which must be outlived
3069 // by the former. CreateOffer by the peer connection is implemented
3070 // asynchronously and if the peer connection is closed without resetting the
3071 // WebRTC session description factory, the session description factory would
3072 // call the transport controller.
3073 webrtc_session_desc_factory_.reset();
3074 transport_controller_.reset();
3075
deadbeef42a42632017-03-10 15:18:00 -08003076 network_thread()->Invoke<void>(
3077 RTC_FROM_HERE,
3078 rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
3079 port_allocator_.get()));
nisseeaabdf62017-05-05 02:23:02 -07003080
Steve Anton978b8762017-09-29 12:15:02 -07003081 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
eladalon248fd4f2017-09-06 05:18:15 -07003082 call_.reset();
3083 // The event log must outlive call (and any other object that uses it).
3084 event_log_.reset();
3085 });
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003086}
3087
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003088void PeerConnection::OnMessage(rtc::Message* msg) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003089 switch (msg->message_id) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003090 case MSG_SET_SESSIONDESCRIPTION_SUCCESS: {
3091 SetSessionDescriptionMsg* param =
3092 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
3093 param->observer->OnSuccess();
3094 delete param;
3095 break;
3096 }
3097 case MSG_SET_SESSIONDESCRIPTION_FAILED: {
3098 SetSessionDescriptionMsg* param =
3099 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
3100 param->observer->OnFailure(param->error);
3101 delete param;
3102 break;
3103 }
deadbeefab9b2d12015-10-14 11:33:11 -07003104 case MSG_CREATE_SESSIONDESCRIPTION_FAILED: {
3105 CreateSessionDescriptionMsg* param =
3106 static_cast<CreateSessionDescriptionMsg*>(msg->pdata);
3107 param->observer->OnFailure(param->error);
3108 delete param;
3109 break;
3110 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003111 case MSG_GETSTATS: {
3112 GetStatsMsg* param = static_cast<GetStatsMsg*>(msg->pdata);
nissee8abe3e2017-01-18 05:00:34 -08003113 StatsReports reports;
3114 stats_->GetStats(param->track, &reports);
3115 param->observer->OnComplete(reports);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003116 delete param;
3117 break;
3118 }
deadbeefbd292462015-12-14 18:15:29 -08003119 case MSG_FREE_DATACHANNELS: {
3120 sctp_data_channels_to_free_.clear();
3121 break;
3122 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003123 default:
nisseeb4ca4e2017-01-12 02:24:27 -08003124 RTC_NOTREACHED() << "Not implemented";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003125 break;
3126 }
3127}
3128
Steve Antonafb0bb72018-02-20 11:35:37 -08003129cricket::VoiceMediaChannel* PeerConnection::voice_media_channel() const {
3130 RTC_DCHECK(!IsUnifiedPlan());
3131 auto* voice_channel = static_cast<cricket::VoiceChannel*>(
3132 GetAudioTransceiver()->internal()->channel());
3133 if (voice_channel) {
3134 return voice_channel->media_channel();
3135 } else {
3136 return nullptr;
3137 }
3138}
3139
3140cricket::VideoMediaChannel* PeerConnection::video_media_channel() const {
3141 RTC_DCHECK(!IsUnifiedPlan());
3142 auto* video_channel = static_cast<cricket::VideoChannel*>(
3143 GetVideoTransceiver()->internal()->channel());
3144 if (video_channel) {
3145 return video_channel->media_channel();
3146 } else {
3147 return nullptr;
3148 }
3149}
3150
Steve Anton4171afb2017-11-20 10:20:22 -08003151void PeerConnection::CreateAudioReceiver(
3152 MediaStreamInterface* stream,
3153 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01003154 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
3155 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Steve Antond3679212018-01-17 17:41:02 -08003156 auto* audio_receiver = new AudioRtpReceiver(
3157 worker_thread(), remote_sender_info.sender_id, streams);
Steve Anton57858b32018-02-15 15:19:50 -08003158 audio_receiver->SetVoiceMediaChannel(voice_media_channel());
Steve Antond3679212018-01-17 17:41:02 -08003159 audio_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
3160 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
3161 signaling_thread(), audio_receiver);
Steve Anton4171afb2017-11-20 10:20:22 -08003162 GetAudioTransceiver()->internal()->AddReceiver(receiver);
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01003163 observer_->OnAddTrack(receiver, std::move(streams));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003164}
3165
Steve Anton4171afb2017-11-20 10:20:22 -08003166void PeerConnection::CreateVideoReceiver(
3167 MediaStreamInterface* stream,
3168 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01003169 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
3170 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Steve Antond3679212018-01-17 17:41:02 -08003171 auto* video_receiver = new VideoRtpReceiver(
3172 worker_thread(), remote_sender_info.sender_id, streams);
Steve Anton57858b32018-02-15 15:19:50 -08003173 video_receiver->SetVideoMediaChannel(video_media_channel());
Steve Antond3679212018-01-17 17:41:02 -08003174 video_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
3175 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
3176 signaling_thread(), video_receiver);
Steve Anton4171afb2017-11-20 10:20:22 -08003177 GetVideoTransceiver()->internal()->AddReceiver(receiver);
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01003178 observer_->OnAddTrack(receiver, std::move(streams));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003179}
3180
deadbeef70ab1a12015-09-28 16:53:55 -07003181// TODO(deadbeef): Keep RtpReceivers around even if track goes away in remote
3182// description.
Henrik Boström933d8b02017-10-10 10:05:16 -07003183rtc::scoped_refptr<RtpReceiverInterface> PeerConnection::RemoveAndStopReceiver(
Steve Anton4171afb2017-11-20 10:20:22 -08003184 const RtpSenderInfo& remote_sender_info) {
3185 auto receiver = FindReceiverById(remote_sender_info.sender_id);
3186 if (!receiver) {
3187 RTC_LOG(LS_WARNING) << "RtpReceiver for track with id "
3188 << remote_sender_info.sender_id << " doesn't exist.";
Henrik Boström933d8b02017-10-10 10:05:16 -07003189 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07003190 }
Steve Anton4171afb2017-11-20 10:20:22 -08003191 if (receiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
3192 GetAudioTransceiver()->internal()->RemoveReceiver(receiver);
3193 } else {
3194 GetVideoTransceiver()->internal()->RemoveReceiver(receiver);
3195 }
Henrik Boström933d8b02017-10-10 10:05:16 -07003196 return receiver;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003197}
3198
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003199void PeerConnection::AddAudioTrack(AudioTrackInterface* track,
3200 MediaStreamInterface* stream) {
3201 RTC_DCHECK(!IsClosed());
3202 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003203 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003204 // We already have a sender for this track, so just change the stream_id
3205 // so that it's correct in the next call to CreateOffer.
Steve Anton4171afb2017-11-20 10:20:22 -08003206 sender->internal()->set_stream_id(stream->label());
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003207 return;
3208 }
3209
3210 // Normal case; we've never seen this track before.
Steve Anton02ee47c2018-01-10 16:26:06 -08003211 auto new_sender =
3212 CreateSender(cricket::MEDIA_TYPE_AUDIO, track, {stream->label()});
Steve Anton57858b32018-02-15 15:19:50 -08003213 new_sender->internal()->SetVoiceMediaChannel(voice_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08003214 GetAudioTransceiver()->internal()->AddSender(new_sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003215 // If the sender has already been configured in SDP, we call SetSsrc,
3216 // which will connect the sender to the underlying transport. This can
3217 // occur if a local session description that contains the ID of the sender
3218 // is set before AddStream is called. It can also occur if the local
3219 // session description is not changed and RemoveStream is called, and
3220 // later AddStream is called again with the same stream.
Steve Anton4171afb2017-11-20 10:20:22 -08003221 const RtpSenderInfo* sender_info =
3222 FindSenderInfo(local_audio_sender_infos_, stream->label(), track->id());
3223 if (sender_info) {
3224 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003225 }
3226}
3227
3228// TODO(deadbeef): Don't destroy RtpSenders here; they should be kept around
3229// indefinitely, when we have unified plan SDP.
3230void PeerConnection::RemoveAudioTrack(AudioTrackInterface* track,
3231 MediaStreamInterface* stream) {
3232 RTC_DCHECK(!IsClosed());
3233 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003234 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003235 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
3236 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003237 return;
3238 }
Steve Anton4171afb2017-11-20 10:20:22 -08003239 GetAudioTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003240}
3241
3242void PeerConnection::AddVideoTrack(VideoTrackInterface* track,
3243 MediaStreamInterface* stream) {
3244 RTC_DCHECK(!IsClosed());
3245 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003246 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003247 // We already have a sender for this track, so just change the stream_id
3248 // so that it's correct in the next call to CreateOffer.
Steve Anton4171afb2017-11-20 10:20:22 -08003249 sender->internal()->set_stream_id(stream->label());
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003250 return;
3251 }
3252
3253 // Normal case; we've never seen this track before.
Steve Anton02ee47c2018-01-10 16:26:06 -08003254 auto new_sender =
3255 CreateSender(cricket::MEDIA_TYPE_VIDEO, track, {stream->label()});
Steve Anton57858b32018-02-15 15:19:50 -08003256 new_sender->internal()->SetVideoMediaChannel(video_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08003257 GetVideoTransceiver()->internal()->AddSender(new_sender);
3258 const RtpSenderInfo* sender_info =
3259 FindSenderInfo(local_video_sender_infos_, stream->label(), track->id());
3260 if (sender_info) {
3261 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003262 }
3263}
3264
3265void PeerConnection::RemoveVideoTrack(VideoTrackInterface* track,
3266 MediaStreamInterface* stream) {
3267 RTC_DCHECK(!IsClosed());
3268 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003269 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003270 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
3271 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003272 return;
3273 }
Steve Anton4171afb2017-11-20 10:20:22 -08003274 GetVideoTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003275}
3276
Steve Antonba818672017-11-06 10:21:57 -08003277void PeerConnection::SetIceConnectionState(IceConnectionState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07003278 RTC_DCHECK(signaling_thread()->IsCurrent());
Steve Antonba818672017-11-06 10:21:57 -08003279 if (ice_connection_state_ == new_state) {
3280 return;
3281 }
3282
deadbeefcbecd352015-09-23 11:50:27 -07003283 // After transitioning to "closed", ignore any additional states from
Steve Antonba818672017-11-06 10:21:57 -08003284 // TransportController (such as "disconnected").
deadbeefab9b2d12015-10-14 11:33:11 -07003285 if (IsClosed()) {
deadbeefcbecd352015-09-23 11:50:27 -07003286 return;
3287 }
Steve Antonba818672017-11-06 10:21:57 -08003288
Mirko Bonadei675513b2017-11-09 11:09:25 +01003289 RTC_LOG(LS_INFO) << "Changing IceConnectionState " << ice_connection_state_
3290 << " => " << new_state;
Steve Antonba818672017-11-06 10:21:57 -08003291 RTC_DCHECK(ice_connection_state_ !=
3292 PeerConnectionInterface::kIceConnectionClosed);
3293
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003294 ice_connection_state_ = new_state;
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00003295 observer_->OnIceConnectionChange(ice_connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003296}
3297
3298void PeerConnection::OnIceGatheringChange(
3299 PeerConnectionInterface::IceGatheringState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07003300 RTC_DCHECK(signaling_thread()->IsCurrent());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003301 if (IsClosed()) {
3302 return;
3303 }
3304 ice_gathering_state_ = new_state;
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00003305 observer_->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003306}
3307
jbauch81bf7b02017-03-25 08:31:12 -07003308void PeerConnection::OnIceCandidate(
3309 std::unique_ptr<IceCandidateInterface> candidate) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07003310 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07003311 if (IsClosed()) {
3312 return;
3313 }
jbauch81bf7b02017-03-25 08:31:12 -07003314 observer_->OnIceCandidate(candidate.get());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003315}
3316
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003317void PeerConnection::OnIceCandidatesRemoved(
3318 const std::vector<cricket::Candidate>& candidates) {
3319 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07003320 if (IsClosed()) {
3321 return;
3322 }
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003323 observer_->OnIceCandidatesRemoved(candidates);
3324}
3325
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003326void PeerConnection::ChangeSignalingState(
3327 PeerConnectionInterface::SignalingState signaling_state) {
Steve Antonba818672017-11-06 10:21:57 -08003328 RTC_DCHECK(signaling_thread()->IsCurrent());
3329 if (signaling_state_ == signaling_state) {
3330 return;
3331 }
Mirko Bonadei675513b2017-11-09 11:09:25 +01003332 RTC_LOG(LS_INFO) << "Session: " << session_id() << " Old state: "
3333 << GetSignalingStateString(signaling_state_)
3334 << " New state: "
3335 << GetSignalingStateString(signaling_state);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003336 signaling_state_ = signaling_state;
3337 if (signaling_state == kClosed) {
3338 ice_connection_state_ = kIceConnectionClosed;
3339 observer_->OnIceConnectionChange(ice_connection_state_);
3340 if (ice_gathering_state_ != kIceGatheringComplete) {
3341 ice_gathering_state_ = kIceGatheringComplete;
3342 observer_->OnIceGatheringChange(ice_gathering_state_);
3343 }
3344 }
3345 observer_->OnSignalingChange(signaling_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003346}
3347
deadbeefeb459812015-12-15 19:24:43 -08003348void PeerConnection::OnAudioTrackAdded(AudioTrackInterface* track,
3349 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003350 if (IsClosed()) {
3351 return;
3352 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003353 AddAudioTrack(track, stream);
3354 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003355}
3356
deadbeefeb459812015-12-15 19:24:43 -08003357void PeerConnection::OnAudioTrackRemoved(AudioTrackInterface* track,
3358 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003359 if (IsClosed()) {
3360 return;
3361 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003362 RemoveAudioTrack(track, stream);
3363 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003364}
3365
3366void PeerConnection::OnVideoTrackAdded(VideoTrackInterface* track,
3367 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003368 if (IsClosed()) {
3369 return;
3370 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003371 AddVideoTrack(track, stream);
3372 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003373}
3374
3375void PeerConnection::OnVideoTrackRemoved(VideoTrackInterface* track,
3376 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003377 if (IsClosed()) {
3378 return;
3379 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003380 RemoveVideoTrack(track, stream);
3381 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003382}
3383
Henrik Boström31638672017-11-23 17:48:32 +01003384void PeerConnection::PostSetSessionDescriptionSuccess(
3385 SetSessionDescriptionObserver* observer) {
3386 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
3387 signaling_thread()->Post(RTC_FROM_HERE, this,
3388 MSG_SET_SESSIONDESCRIPTION_SUCCESS, msg);
3389}
3390
deadbeefab9b2d12015-10-14 11:33:11 -07003391void PeerConnection::PostSetSessionDescriptionFailure(
3392 SetSessionDescriptionObserver* observer,
3393 const std::string& error) {
3394 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
3395 msg->error = error;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07003396 signaling_thread()->Post(RTC_FROM_HERE, this,
3397 MSG_SET_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07003398}
3399
3400void PeerConnection::PostCreateSessionDescriptionFailure(
3401 CreateSessionDescriptionObserver* observer,
3402 const std::string& error) {
3403 CreateSessionDescriptionMsg* msg = new CreateSessionDescriptionMsg(observer);
3404 msg->error = error;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07003405 signaling_thread()->Post(RTC_FROM_HERE, this,
3406 MSG_CREATE_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07003407}
3408
zhihuang1c378ed2017-08-17 14:10:50 -07003409void PeerConnection::GetOptionsForOffer(
Steve Antondcc3c022017-12-22 16:02:54 -08003410 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
deadbeefab9b2d12015-10-14 11:33:11 -07003411 cricket::MediaSessionOptions* session_options) {
Steve Antondcc3c022017-12-22 16:02:54 -08003412 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
zhihuang1c378ed2017-08-17 14:10:50 -07003413
Steve Antondcc3c022017-12-22 16:02:54 -08003414 if (IsUnifiedPlan()) {
3415 GetOptionsForUnifiedPlanOffer(offer_answer_options, session_options);
3416 } else {
3417 GetOptionsForPlanBOffer(offer_answer_options, session_options);
3418 }
3419
Steve Antonfa2260d2017-12-28 16:38:23 -08003420 // Intentionally unset the data channel type for RTP data channel with the
3421 // second condition. Otherwise the RTP data channels would be successfully
3422 // negotiated by default and the unit tests in WebRtcDataBrowserTest will fail
3423 // when building with chromium. We want to leave RTP data channels broken, so
3424 // people won't try to use them.
3425 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
3426 session_options->data_channel_type = data_channel_type();
3427 }
3428
Steve Antondcc3c022017-12-22 16:02:54 -08003429 // Apply ICE restart flag and renomination flag.
3430 for (auto& options : session_options->media_description_options) {
3431 options.transport_options.ice_restart = offer_answer_options.ice_restart;
3432 options.transport_options.enable_ice_renomination =
3433 configuration_.enable_ice_renomination;
3434 }
3435
3436 session_options->rtcp_cname = rtcp_cname_;
3437 session_options->crypto_options = factory_->options().crypto_options;
Steve Antone831b8c2018-02-01 12:22:16 -08003438 session_options->is_unified_plan = IsUnifiedPlan();
Steve Antondcc3c022017-12-22 16:02:54 -08003439}
3440
3441void PeerConnection::GetOptionsForPlanBOffer(
3442 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
3443 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07003444 // Figure out transceiver directional preferences.
3445 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
3446 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
3447
3448 // By default, generate sendrecv/recvonly m= sections.
3449 bool recv_audio = true;
3450 bool recv_video = true;
3451
3452 // By default, only offer a new m= section if we have media to send with it.
3453 bool offer_new_audio_description = send_audio;
3454 bool offer_new_video_description = send_video;
3455 bool offer_new_data_description = HasDataChannels();
3456
3457 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-22 16:02:54 -08003458 if (offer_answer_options.offer_to_receive_audio !=
3459 RTCOfferAnswerOptions::kUndefined) {
3460 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003461 offer_new_audio_description =
Steve Antondcc3c022017-12-22 16:02:54 -08003462 offer_new_audio_description ||
3463 (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003464 }
Steve Antondcc3c022017-12-22 16:02:54 -08003465 if (offer_answer_options.offer_to_receive_video !=
3466 RTCOfferAnswerOptions::kUndefined) {
3467 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003468 offer_new_video_description =
Steve Antondcc3c022017-12-22 16:02:54 -08003469 offer_new_video_description ||
3470 (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003471 }
3472
3473 rtc::Optional<size_t> audio_index;
3474 rtc::Optional<size_t> video_index;
3475 rtc::Optional<size_t> data_index;
3476 // If a current description exists, generate m= sections in the same order,
3477 // using the first audio/video/data section that appears and rejecting
3478 // extraneous ones.
Steve Anton75737c02017-11-06 10:37:17 -08003479 if (local_description()) {
zhihuang1c378ed2017-08-17 14:10:50 -07003480 GenerateMediaDescriptionOptions(
Steve Anton75737c02017-11-06 10:37:17 -08003481 local_description(),
Steve Anton1d03a752017-11-27 14:30:09 -08003482 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
3483 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
3484 &audio_index, &video_index, &data_index, session_options);
deadbeefab9b2d12015-10-14 11:33:11 -07003485 }
3486
zhihuang1c378ed2017-08-17 14:10:50 -07003487 // Add audio/video/data m= sections to the end if needed.
3488 if (!audio_index && offer_new_audio_description) {
3489 session_options->media_description_options.push_back(
3490 cricket::MediaDescriptionOptions(
3491 cricket::MEDIA_TYPE_AUDIO, cricket::CN_AUDIO,
Steve Anton1d03a752017-11-27 14:30:09 -08003492 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
3493 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003494 audio_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07003495 }
zhihuang1c378ed2017-08-17 14:10:50 -07003496 if (!video_index && offer_new_video_description) {
3497 session_options->media_description_options.push_back(
3498 cricket::MediaDescriptionOptions(
3499 cricket::MEDIA_TYPE_VIDEO, cricket::CN_VIDEO,
Steve Anton1d03a752017-11-27 14:30:09 -08003500 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
3501 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003502 video_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07003503 }
zhihuang1c378ed2017-08-17 14:10:50 -07003504 if (!data_index && offer_new_data_description) {
3505 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08003506 GetMediaDescriptionOptionsForActiveData(cricket::CN_DATA));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003507 data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07003508 }
3509
3510 cricket::MediaDescriptionOptions* audio_media_description_options =
3511 !audio_index ? nullptr
3512 : &session_options->media_description_options[*audio_index];
3513 cricket::MediaDescriptionOptions* video_media_description_options =
3514 !video_index ? nullptr
3515 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 14:10:50 -07003516
Steve Anton4171afb2017-11-20 10:20:22 -08003517 AddRtpSenderOptions(GetSendersInternal(), audio_media_description_options,
zhihuang1c378ed2017-08-17 14:10:50 -07003518 video_media_description_options);
Steve Antondcc3c022017-12-22 16:02:54 -08003519}
3520
3521// Find a new MID that is not already in |used_mids|, then add it to |used_mids|
3522// and return a reference to it.
3523// Generated MIDs should be no more than 3 bytes long to take up less space in
3524// the RTP packet.
3525static const std::string& AllocateMid(std::set<std::string>* used_mids) {
3526 RTC_DCHECK(used_mids);
3527 // We're boring: just generate MIDs 0, 1, 2, ...
3528 size_t i = 0;
3529 std::set<std::string>::iterator it;
3530 bool inserted;
3531 do {
3532 std::string mid = rtc::ToString(i++);
3533 auto insert_result = used_mids->insert(mid);
3534 it = insert_result.first;
3535 inserted = insert_result.second;
3536 } while (!inserted);
3537 return *it;
3538}
3539
3540static cricket::MediaDescriptionOptions
3541GetMediaDescriptionOptionsForTransceiver(
3542 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3543 transceiver,
3544 const std::string& mid) {
3545 cricket::MediaDescriptionOptions media_description_options(
Steve Anton69470252018-02-09 11:43:08 -08003546 transceiver->media_type(), mid, transceiver->direction(),
Steve Antondcc3c022017-12-22 16:02:54 -08003547 transceiver->stopped());
Steve Anton5f94aa22018-02-01 10:58:30 -08003548 // This behavior is specified in JSEP. The gist is that:
3549 // 1. The MSID is included if the RtpTransceiver's direction is sendonly or
3550 // sendrecv.
3551 // 2. If the MSID is included, then it must be included in any subsequent
3552 // offer/answer exactly the same until the RtpTransceiver is stopped.
3553 if (!transceiver->stopped() &&
3554 (RtpTransceiverDirectionHasSend(transceiver->direction()) ||
3555 transceiver->internal()->has_ever_been_used_to_send())) {
3556 cricket::SenderOptions sender_options;
3557 sender_options.track_id = transceiver->sender()->id();
3558 sender_options.stream_ids = transceiver->sender()->stream_ids();
3559 // TODO(bugs.webrtc.org/7600): Set num_sim_layers to the number of encodings
3560 // set in the RTP parameters when the transceiver was added.
3561 sender_options.num_sim_layers = 1;
3562 media_description_options.sender_options.push_back(sender_options);
3563 }
Steve Antondcc3c022017-12-22 16:02:54 -08003564 return media_description_options;
3565}
3566
3567void PeerConnection::GetOptionsForUnifiedPlanOffer(
3568 const RTCOfferAnswerOptions& offer_answer_options,
3569 cricket::MediaSessionOptions* session_options) {
3570 // Rules for generating an offer are dictated by JSEP sections 5.2.1 (Initial
3571 // Offers) and 5.2.2 (Subsequent Offers).
3572 RTC_DCHECK_EQ(session_options->media_description_options.size(), 0);
3573 const ContentInfos& local_contents =
3574 (local_description() ? local_description()->description()->contents()
3575 : ContentInfos());
3576 const ContentInfos& remote_contents =
3577 (remote_description() ? remote_description()->description()->contents()
3578 : ContentInfos());
3579 // The mline indices that can be recycled. New transceivers should reuse these
3580 // slots first.
3581 std::queue<size_t> recycleable_mline_indices;
3582 // Track the MIDs used in previous offer/answer exchanges and the current
3583 // offer so that new, unique MIDs are generated.
3584 std::set<std::string> used_mids = seen_mids_;
3585 // First, go through each media section that exists in either the local or
3586 // remote description and generate a media section in this offer for the
3587 // associated transceiver. If a media section can be recycled, generate a
3588 // default, rejected media section here that can be later overwritten.
3589 for (size_t i = 0;
3590 i < std::max(local_contents.size(), remote_contents.size()); ++i) {
3591 // Either |local_content| or |remote_content| is non-null.
3592 const ContentInfo* local_content =
3593 (i < local_contents.size() ? &local_contents[i] : nullptr);
3594 const ContentInfo* remote_content =
3595 (i < remote_contents.size() ? &remote_contents[i] : nullptr);
3596 bool had_been_rejected = (local_content && local_content->rejected) ||
3597 (remote_content && remote_content->rejected);
3598 const std::string& mid =
3599 (local_content ? local_content->name : remote_content->name);
3600 cricket::MediaType media_type =
3601 (local_content ? local_content->media_description()->type()
3602 : remote_content->media_description()->type());
3603 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
3604 media_type == cricket::MEDIA_TYPE_VIDEO) {
3605 auto transceiver = GetAssociatedTransceiver(mid);
3606 RTC_CHECK(transceiver);
3607 // A media section is considered eligible for recycling if it is marked as
3608 // rejected in either the local or remote description.
Seth Hampsonae8a90a2018-02-13 15:33:48 -08003609 if (had_been_rejected && transceiver->stopped()) {
Steve Antondcc3c022017-12-22 16:02:54 -08003610 session_options->media_description_options.push_back(
Steve Anton69470252018-02-09 11:43:08 -08003611 cricket::MediaDescriptionOptions(transceiver->media_type(), mid,
3612 RtpTransceiverDirection::kInactive,
3613 /*stopped=*/true));
Steve Antondcc3c022017-12-22 16:02:54 -08003614 recycleable_mline_indices.push(i);
3615 } else {
3616 session_options->media_description_options.push_back(
3617 GetMediaDescriptionOptionsForTransceiver(transceiver, mid));
3618 // CreateOffer shouldn't really cause any state changes in
3619 // PeerConnection, but we need a way to match new transceivers to new
3620 // media sections in SetLocalDescription and JSEP specifies this is done
3621 // by recording the index of the media section generated for the
3622 // transceiver in the offer.
3623 transceiver->internal()->set_mline_index(i);
3624 }
3625 } else {
3626 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antonfa2260d2017-12-28 16:38:23 -08003627 RTC_CHECK(GetDataMid());
3628 if (had_been_rejected || mid != *GetDataMid()) {
3629 session_options->media_description_options.push_back(
3630 GetMediaDescriptionOptionsForRejectedData(mid));
3631 } else {
3632 session_options->media_description_options.push_back(
3633 GetMediaDescriptionOptionsForActiveData(mid));
3634 }
Steve Antondcc3c022017-12-22 16:02:54 -08003635 }
3636 }
3637 // Next, look for transceivers that are newly added (that is, are not stopped
3638 // and not associated). Reuse media sections marked as recyclable first,
3639 // otherwise append to the end of the offer. New media sections should be
3640 // added in the order they were added to the PeerConnection.
3641 for (auto transceiver : transceivers_) {
3642 if (transceiver->mid() || transceiver->stopped()) {
3643 continue;
3644 }
3645 size_t mline_index;
3646 if (!recycleable_mline_indices.empty()) {
3647 mline_index = recycleable_mline_indices.front();
3648 recycleable_mline_indices.pop();
3649 session_options->media_description_options[mline_index] =
3650 GetMediaDescriptionOptionsForTransceiver(transceiver,
3651 AllocateMid(&used_mids));
3652 } else {
3653 mline_index = session_options->media_description_options.size();
3654 session_options->media_description_options.push_back(
3655 GetMediaDescriptionOptionsForTransceiver(transceiver,
3656 AllocateMid(&used_mids)));
3657 }
3658 // See comment above for why CreateOffer changes the transceiver's state.
3659 transceiver->internal()->set_mline_index(mline_index);
3660 }
Steve Antonfa2260d2017-12-28 16:38:23 -08003661 // Lastly, add a m-section if we have local data channels and an m section
3662 // does not already exist.
3663 if (!GetDataMid() && HasDataChannels()) {
3664 session_options->media_description_options.push_back(
3665 GetMediaDescriptionOptionsForActiveData(AllocateMid(&used_mids)));
3666 }
Steve Antondcc3c022017-12-22 16:02:54 -08003667}
3668
3669void PeerConnection::GetOptionsForAnswer(
3670 const RTCOfferAnswerOptions& offer_answer_options,
3671 cricket::MediaSessionOptions* session_options) {
3672 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
3673
3674 if (IsUnifiedPlan()) {
3675 GetOptionsForUnifiedPlanAnswer(offer_answer_options, session_options);
3676 } else {
3677 GetOptionsForPlanBAnswer(offer_answer_options, session_options);
3678 }
3679
Steve Antonfa2260d2017-12-28 16:38:23 -08003680 // Intentionally unset the data channel type for RTP data channel. Otherwise
3681 // the RTP data channels would be successfully negotiated by default and the
3682 // unit tests in WebRtcDataBrowserTest will fail when building with chromium.
3683 // We want to leave RTP data channels broken, so people won't try to use them.
3684 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
3685 session_options->data_channel_type = data_channel_type();
3686 }
3687
Steve Antondcc3c022017-12-22 16:02:54 -08003688 // Apply ICE renomination flag.
3689 for (auto& options : session_options->media_description_options) {
3690 options.transport_options.enable_ice_renomination =
3691 configuration_.enable_ice_renomination;
3692 }
zhihuang8f65cdf2016-05-06 18:40:30 -07003693
3694 session_options->rtcp_cname = rtcp_cname_;
jbauchcb560652016-08-04 05:20:32 -07003695 session_options->crypto_options = factory_->options().crypto_options;
Steve Antone831b8c2018-02-01 12:22:16 -08003696 session_options->is_unified_plan = IsUnifiedPlan();
deadbeefab9b2d12015-10-14 11:33:11 -07003697}
3698
Steve Antondcc3c022017-12-22 16:02:54 -08003699void PeerConnection::GetOptionsForPlanBAnswer(
3700 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07003701 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07003702 // Figure out transceiver directional preferences.
3703 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
3704 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
3705
3706 // By default, generate sendrecv/recvonly m= sections. The direction is also
3707 // restricted by the direction in the offer.
3708 bool recv_audio = true;
3709 bool recv_video = true;
3710
3711 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-22 16:02:54 -08003712 if (offer_answer_options.offer_to_receive_audio !=
3713 RTCOfferAnswerOptions::kUndefined) {
3714 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
deadbeef0ed85b22016-02-23 17:24:52 -08003715 }
Steve Antondcc3c022017-12-22 16:02:54 -08003716 if (offer_answer_options.offer_to_receive_video !=
3717 RTCOfferAnswerOptions::kUndefined) {
3718 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003719 }
3720
3721 rtc::Optional<size_t> audio_index;
3722 rtc::Optional<size_t> video_index;
3723 rtc::Optional<size_t> data_index;
Steve Antondffead82018-02-06 10:31:29 -08003724
3725 // Generate m= sections that match those in the offer.
3726 // Note that mediasession.cc will handle intersection our preferred
3727 // direction with the offered direction.
3728 GenerateMediaDescriptionOptions(
3729 remote_description(),
3730 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
3731 RtpTransceiverDirectionFromSendRecv(send_video, recv_video), &audio_index,
3732 &video_index, &data_index, session_options);
zhihuang1c378ed2017-08-17 14:10:50 -07003733
3734 cricket::MediaDescriptionOptions* audio_media_description_options =
3735 !audio_index ? nullptr
3736 : &session_options->media_description_options[*audio_index];
3737 cricket::MediaDescriptionOptions* video_media_description_options =
3738 !video_index ? nullptr
3739 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 14:10:50 -07003740
Steve Anton4171afb2017-11-20 10:20:22 -08003741 AddRtpSenderOptions(GetSendersInternal(), audio_media_description_options,
zhihuang1c378ed2017-08-17 14:10:50 -07003742 video_media_description_options);
Steve Antondcc3c022017-12-22 16:02:54 -08003743}
zhihuangaf388472016-11-02 16:49:48 -07003744
Steve Antondcc3c022017-12-22 16:02:54 -08003745void PeerConnection::GetOptionsForUnifiedPlanAnswer(
3746 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
3747 cricket::MediaSessionOptions* session_options) {
3748 // Rules for generating an answer are dictated by JSEP sections 5.3.1 (Initial
3749 // Answers) and 5.3.2 (Subsequent Answers).
3750 RTC_DCHECK(remote_description());
3751 RTC_DCHECK(remote_description()->GetType() == SdpType::kOffer);
3752 for (const ContentInfo& content :
3753 remote_description()->description()->contents()) {
3754 cricket::MediaType media_type = content.media_description()->type();
3755 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
3756 media_type == cricket::MEDIA_TYPE_VIDEO) {
3757 auto transceiver = GetAssociatedTransceiver(content.name);
3758 RTC_CHECK(transceiver);
3759 session_options->media_description_options.push_back(
3760 GetMediaDescriptionOptionsForTransceiver(transceiver, content.name));
3761 } else {
3762 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antondbf9d032018-01-19 15:23:40 -08003763 // Reject all data sections if data channels are disabled.
3764 // Reject a data section if it has already been rejected.
3765 // Reject all data sections except for the first one.
3766 if (data_channel_type_ == cricket::DCT_NONE || content.rejected ||
3767 content.name != *GetDataMid()) {
Steve Antonfa2260d2017-12-28 16:38:23 -08003768 session_options->media_description_options.push_back(
3769 GetMediaDescriptionOptionsForRejectedData(content.name));
3770 } else {
3771 session_options->media_description_options.push_back(
3772 GetMediaDescriptionOptionsForActiveData(content.name));
3773 }
Steve Antondcc3c022017-12-22 16:02:54 -08003774 }
3775 }
htaa2a49d92016-03-04 02:51:39 -08003776}
3777
zhihuang1c378ed2017-08-17 14:10:50 -07003778void PeerConnection::GenerateMediaDescriptionOptions(
3779 const SessionDescriptionInterface* session_desc,
Steve Anton1d03a752017-11-27 14:30:09 -08003780 RtpTransceiverDirection audio_direction,
3781 RtpTransceiverDirection video_direction,
zhihuang1c378ed2017-08-17 14:10:50 -07003782 rtc::Optional<size_t>* audio_index,
3783 rtc::Optional<size_t>* video_index,
3784 rtc::Optional<size_t>* data_index,
htaa2a49d92016-03-04 02:51:39 -08003785 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07003786 for (const cricket::ContentInfo& content :
3787 session_desc->description()->contents()) {
3788 if (IsAudioContent(&content)) {
3789 // If we already have an audio m= section, reject this extra one.
3790 if (*audio_index) {
3791 session_options->media_description_options.push_back(
3792 cricket::MediaDescriptionOptions(
3793 cricket::MEDIA_TYPE_AUDIO, content.name,
Steve Anton1d03a752017-11-27 14:30:09 -08003794 RtpTransceiverDirection::kInactive, true));
zhihuang1c378ed2017-08-17 14:10:50 -07003795 } else {
3796 session_options->media_description_options.push_back(
3797 cricket::MediaDescriptionOptions(
3798 cricket::MEDIA_TYPE_AUDIO, content.name, audio_direction,
Steve Anton1d03a752017-11-27 14:30:09 -08003799 audio_direction == RtpTransceiverDirection::kInactive));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003800 *audio_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07003801 }
3802 } else if (IsVideoContent(&content)) {
3803 // If we already have an video m= section, reject this extra one.
3804 if (*video_index) {
3805 session_options->media_description_options.push_back(
3806 cricket::MediaDescriptionOptions(
3807 cricket::MEDIA_TYPE_VIDEO, content.name,
Steve Anton1d03a752017-11-27 14:30:09 -08003808 RtpTransceiverDirection::kInactive, true));
zhihuang1c378ed2017-08-17 14:10:50 -07003809 } else {
3810 session_options->media_description_options.push_back(
3811 cricket::MediaDescriptionOptions(
3812 cricket::MEDIA_TYPE_VIDEO, content.name, video_direction,
Steve Anton1d03a752017-11-27 14:30:09 -08003813 video_direction == RtpTransceiverDirection::kInactive));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003814 *video_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07003815 }
3816 } else {
3817 RTC_DCHECK(IsDataContent(&content));
3818 // If we already have an data m= section, reject this extra one.
3819 if (*data_index) {
3820 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08003821 GetMediaDescriptionOptionsForRejectedData(content.name));
zhihuang1c378ed2017-08-17 14:10:50 -07003822 } else {
3823 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08003824 GetMediaDescriptionOptionsForActiveData(content.name));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003825 *data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07003826 }
3827 }
htaa2a49d92016-03-04 02:51:39 -08003828 }
deadbeefab9b2d12015-10-14 11:33:11 -07003829}
3830
Steve Antonfa2260d2017-12-28 16:38:23 -08003831cricket::MediaDescriptionOptions
3832PeerConnection::GetMediaDescriptionOptionsForActiveData(
3833 const std::string& mid) const {
3834 // Direction for data sections is meaningless, but legacy endpoints might
3835 // expect sendrecv.
3836 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
3837 RtpTransceiverDirection::kSendRecv,
3838 /*stopped=*/false);
3839 AddRtpDataChannelOptions(rtp_data_channels_, &options);
3840 return options;
3841}
3842
3843cricket::MediaDescriptionOptions
3844PeerConnection::GetMediaDescriptionOptionsForRejectedData(
3845 const std::string& mid) const {
3846 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
3847 RtpTransceiverDirection::kInactive,
3848 /*stopped=*/true);
3849 AddRtpDataChannelOptions(rtp_data_channels_, &options);
3850 return options;
3851}
3852
3853rtc::Optional<std::string> PeerConnection::GetDataMid() const {
3854 switch (data_channel_type_) {
3855 case cricket::DCT_RTP:
3856 if (!rtp_data_channel_) {
3857 return rtc::nullopt;
3858 }
3859 return rtp_data_channel_->content_name();
3860 case cricket::DCT_SCTP:
3861 return sctp_content_name_;
3862 default:
3863 return rtc::nullopt;
3864 }
3865}
3866
Steve Anton4171afb2017-11-20 10:20:22 -08003867void PeerConnection::RemoveSenders(cricket::MediaType media_type) {
3868 UpdateLocalSenders(std::vector<cricket::StreamParams>(), media_type);
3869 UpdateRemoteSendersList(std::vector<cricket::StreamParams>(), false,
deadbeefbda7e0b2015-12-08 17:13:40 -08003870 media_type, nullptr);
deadbeeffaac4972015-11-12 15:33:07 -08003871}
3872
Steve Anton4171afb2017-11-20 10:20:22 -08003873void PeerConnection::UpdateRemoteSendersList(
deadbeefab9b2d12015-10-14 11:33:11 -07003874 const cricket::StreamParamsVec& streams,
Steve Anton4171afb2017-11-20 10:20:22 -08003875 bool default_sender_needed,
deadbeefab9b2d12015-10-14 11:33:11 -07003876 cricket::MediaType media_type,
3877 StreamCollection* new_streams) {
Steve Anton4171afb2017-11-20 10:20:22 -08003878 std::vector<RtpSenderInfo>* current_senders =
3879 GetRemoteSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07003880
Steve Anton4171afb2017-11-20 10:20:22 -08003881 // Find removed senders. I.e., senders where the sender id or ssrc don't match
deadbeeffac06552015-11-25 11:26:01 -08003882 // the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08003883 for (auto sender_it = current_senders->begin();
3884 sender_it != current_senders->end();
3885 /* incremented manually */) {
3886 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07003887 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08003888 cricket::GetStreamBySsrc(streams, info.first_ssrc);
3889 bool sender_exists = params && params->id == info.sender_id;
deadbeefbda7e0b2015-12-08 17:13:40 -08003890 // If this is a default track, and we still need it, don't remove it.
Seth Hampson845e8782018-03-02 11:34:10 -08003891 if ((info.stream_id == kDefaultStreamId && default_sender_needed) ||
Steve Anton4171afb2017-11-20 10:20:22 -08003892 sender_exists) {
3893 ++sender_it;
deadbeefbda7e0b2015-12-08 17:13:40 -08003894 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08003895 OnRemoteSenderRemoved(info, media_type);
3896 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07003897 }
3898 }
3899
Steve Anton4171afb2017-11-20 10:20:22 -08003900 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07003901 for (const cricket::StreamParams& params : streams) {
Seth Hampson845e8782018-03-02 11:34:10 -08003902 // |params.id| is the sender id and the stream id uses the first of
3903 // |params.stream_ids|.
3904 // TODO(bugs.webrtc.org/7932): Add support for multiple stream ids.
3905 const std::string& stream_id =
3906 (!params.stream_ids().empty() ? params.stream_ids()[0] : "");
Steve Anton4171afb2017-11-20 10:20:22 -08003907 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07003908 uint32_t ssrc = params.first_ssrc();
3909
3910 rtc::scoped_refptr<MediaStreamInterface> stream =
Seth Hampson845e8782018-03-02 11:34:10 -08003911 remote_streams_->find(stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07003912 if (!stream) {
3913 // This is a new MediaStream. Create a new remote MediaStream.
perkjd61bf802016-03-24 03:16:19 -07003914 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
Seth Hampson845e8782018-03-02 11:34:10 -08003915 MediaStream::Create(stream_id));
deadbeefab9b2d12015-10-14 11:33:11 -07003916 remote_streams_->AddStream(stream);
3917 new_streams->AddStream(stream);
3918 }
3919
Steve Anton4171afb2017-11-20 10:20:22 -08003920 const RtpSenderInfo* sender_info =
Seth Hampson845e8782018-03-02 11:34:10 -08003921 FindSenderInfo(*current_senders, stream_id, sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08003922 if (!sender_info) {
Seth Hampson845e8782018-03-02 11:34:10 -08003923 current_senders->push_back(RtpSenderInfo(stream_id, sender_id, ssrc));
Steve Anton4171afb2017-11-20 10:20:22 -08003924 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07003925 }
3926 }
deadbeefbda7e0b2015-12-08 17:13:40 -08003927
Steve Anton4171afb2017-11-20 10:20:22 -08003928 // Add default sender if necessary.
3929 if (default_sender_needed) {
deadbeefbda7e0b2015-12-08 17:13:40 -08003930 rtc::scoped_refptr<MediaStreamInterface> default_stream =
Seth Hampson845e8782018-03-02 11:34:10 -08003931 remote_streams_->find(kDefaultStreamId);
deadbeefbda7e0b2015-12-08 17:13:40 -08003932 if (!default_stream) {
3933 // Create the new default MediaStream.
perkjd61bf802016-03-24 03:16:19 -07003934 default_stream = MediaStreamProxy::Create(
Seth Hampson845e8782018-03-02 11:34:10 -08003935 rtc::Thread::Current(), MediaStream::Create(kDefaultStreamId));
deadbeefbda7e0b2015-12-08 17:13:40 -08003936 remote_streams_->AddStream(default_stream);
3937 new_streams->AddStream(default_stream);
3938 }
Steve Anton4171afb2017-11-20 10:20:22 -08003939 std::string default_sender_id = (media_type == cricket::MEDIA_TYPE_AUDIO)
3940 ? kDefaultAudioSenderId
3941 : kDefaultVideoSenderId;
Seth Hampson845e8782018-03-02 11:34:10 -08003942 const RtpSenderInfo* default_sender_info =
3943 FindSenderInfo(*current_senders, kDefaultStreamId, default_sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08003944 if (!default_sender_info) {
3945 current_senders->push_back(
Seth Hampson845e8782018-03-02 11:34:10 -08003946 RtpSenderInfo(kDefaultStreamId, default_sender_id, 0));
Steve Anton4171afb2017-11-20 10:20:22 -08003947 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefbda7e0b2015-12-08 17:13:40 -08003948 }
3949 }
deadbeefab9b2d12015-10-14 11:33:11 -07003950}
3951
Steve Anton4171afb2017-11-20 10:20:22 -08003952void PeerConnection::OnRemoteSenderAdded(const RtpSenderInfo& sender_info,
3953 cricket::MediaType media_type) {
Seth Hampson845e8782018-03-02 11:34:10 -08003954 MediaStreamInterface* stream = remote_streams_->find(sender_info.stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07003955
3956 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 10:20:22 -08003957 CreateAudioReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07003958 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 10:20:22 -08003959 CreateVideoReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07003960 } else {
nisseeb4ca4e2017-01-12 02:24:27 -08003961 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07003962 }
3963}
3964
Steve Anton4171afb2017-11-20 10:20:22 -08003965void PeerConnection::OnRemoteSenderRemoved(const RtpSenderInfo& sender_info,
3966 cricket::MediaType media_type) {
Seth Hampson845e8782018-03-02 11:34:10 -08003967 MediaStreamInterface* stream = remote_streams_->find(sender_info.stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07003968
Henrik Boström933d8b02017-10-10 10:05:16 -07003969 rtc::scoped_refptr<RtpReceiverInterface> receiver;
deadbeefab9b2d12015-10-14 11:33:11 -07003970 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
perkjd61bf802016-03-24 03:16:19 -07003971 // When the MediaEngine audio channel is destroyed, the RemoteAudioSource
3972 // will be notified which will end the AudioRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08003973 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07003974 rtc::scoped_refptr<AudioTrackInterface> audio_track =
Steve Anton4171afb2017-11-20 10:20:22 -08003975 stream->FindAudioTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07003976 if (audio_track) {
deadbeefab9b2d12015-10-14 11:33:11 -07003977 stream->RemoveTrack(audio_track);
deadbeefab9b2d12015-10-14 11:33:11 -07003978 }
3979 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
perkjd61bf802016-03-24 03:16:19 -07003980 // Stopping or destroying a VideoRtpReceiver will end the
3981 // VideoRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08003982 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07003983 rtc::scoped_refptr<VideoTrackInterface> video_track =
Steve Anton4171afb2017-11-20 10:20:22 -08003984 stream->FindVideoTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07003985 if (video_track) {
perkjd61bf802016-03-24 03:16:19 -07003986 // There's no guarantee the track is still available, e.g. the track may
3987 // have been removed from the stream by an application.
deadbeefab9b2d12015-10-14 11:33:11 -07003988 stream->RemoveTrack(video_track);
deadbeefab9b2d12015-10-14 11:33:11 -07003989 }
3990 } else {
nisseede5da42017-01-12 05:15:36 -08003991 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07003992 }
Henrik Boström933d8b02017-10-10 10:05:16 -07003993 if (receiver) {
3994 observer_->OnRemoveTrack(receiver);
3995 }
deadbeefab9b2d12015-10-14 11:33:11 -07003996}
3997
3998void PeerConnection::UpdateEndedRemoteMediaStreams() {
3999 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams_to_remove;
4000 for (size_t i = 0; i < remote_streams_->count(); ++i) {
4001 MediaStreamInterface* stream = remote_streams_->at(i);
4002 if (stream->GetAudioTracks().empty() && stream->GetVideoTracks().empty()) {
4003 streams_to_remove.push_back(stream);
4004 }
4005 }
4006
Taylor Brandstetter98cde262016-05-31 13:02:21 -07004007 for (auto& stream : streams_to_remove) {
deadbeefab9b2d12015-10-14 11:33:11 -07004008 remote_streams_->RemoveStream(stream);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07004009 observer_->OnRemoveStream(std::move(stream));
deadbeefab9b2d12015-10-14 11:33:11 -07004010 }
4011}
4012
Steve Anton4171afb2017-11-20 10:20:22 -08004013void PeerConnection::UpdateLocalSenders(
deadbeefab9b2d12015-10-14 11:33:11 -07004014 const std::vector<cricket::StreamParams>& streams,
4015 cricket::MediaType media_type) {
Steve Anton4171afb2017-11-20 10:20:22 -08004016 std::vector<RtpSenderInfo>* current_senders = GetLocalSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004017
Seth Hampson845e8782018-03-02 11:34:10 -08004018 // Find removed tracks. I.e., tracks where the track id, stream id or ssrc
deadbeefab9b2d12015-10-14 11:33:11 -07004019 // don't match the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08004020 for (auto sender_it = current_senders->begin();
4021 sender_it != current_senders->end();
4022 /* incremented manually */) {
4023 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07004024 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08004025 cricket::GetStreamBySsrc(streams, info.first_ssrc);
4026 if (!params || params->id != info.sender_id ||
Seth Hampson845e8782018-03-02 11:34:10 -08004027 params->first_stream_id() != info.stream_id) {
Steve Anton4171afb2017-11-20 10:20:22 -08004028 OnLocalSenderRemoved(info, media_type);
4029 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07004030 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08004031 ++sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07004032 }
4033 }
4034
Steve Anton4171afb2017-11-20 10:20:22 -08004035 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07004036 for (const cricket::StreamParams& params : streams) {
4037 // The sync_label is the MediaStream label and the |stream.id| is the
Steve Anton4171afb2017-11-20 10:20:22 -08004038 // sender id.
Seth Hampson845e8782018-03-02 11:34:10 -08004039 const std::string& stream_id = params.first_stream_id();
Steve Anton4171afb2017-11-20 10:20:22 -08004040 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07004041 uint32_t ssrc = params.first_ssrc();
Steve Anton4171afb2017-11-20 10:20:22 -08004042 const RtpSenderInfo* sender_info =
Seth Hampson845e8782018-03-02 11:34:10 -08004043 FindSenderInfo(*current_senders, stream_id, sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08004044 if (!sender_info) {
Seth Hampson845e8782018-03-02 11:34:10 -08004045 current_senders->push_back(RtpSenderInfo(stream_id, sender_id, ssrc));
Steve Anton4171afb2017-11-20 10:20:22 -08004046 OnLocalSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004047 }
4048 }
4049}
4050
Steve Anton4171afb2017-11-20 10:20:22 -08004051void PeerConnection::OnLocalSenderAdded(const RtpSenderInfo& sender_info,
4052 cricket::MediaType media_type) {
4053 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08004054 if (!sender) {
Steve Anton4171afb2017-11-20 10:20:22 -08004055 RTC_LOG(LS_WARNING) << "An unknown RtpSender with id "
4056 << sender_info.sender_id
Mirko Bonadei675513b2017-11-09 11:09:25 +01004057 << " has been configured in the local description.";
deadbeefab9b2d12015-10-14 11:33:11 -07004058 return;
4059 }
4060
deadbeeffac06552015-11-25 11:26:01 -08004061 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004062 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
Jonas Olsson45cc8902018-02-13 10:37:07 +01004063 " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08004064 return;
deadbeefab9b2d12015-10-14 11:33:11 -07004065 }
deadbeeffac06552015-11-25 11:26:01 -08004066
Seth Hampson845e8782018-03-02 11:34:10 -08004067 sender->internal()->set_stream_id(sender_info.stream_id);
Steve Anton4171afb2017-11-20 10:20:22 -08004068 sender->internal()->SetSsrc(sender_info.first_ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07004069}
4070
Steve Anton4171afb2017-11-20 10:20:22 -08004071void PeerConnection::OnLocalSenderRemoved(const RtpSenderInfo& sender_info,
4072 cricket::MediaType media_type) {
4073 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08004074 if (!sender) {
4075 // This is the normal case. I.e., RemoveStream has been called and the
deadbeefab9b2d12015-10-14 11:33:11 -07004076 // SessionDescriptions has been renegotiated.
4077 return;
4078 }
deadbeeffac06552015-11-25 11:26:01 -08004079
4080 // A sender has been removed from the SessionDescription but it's still
4081 // associated with the PeerConnection. This only occurs if the SDP doesn't
4082 // match with the calls to CreateSender, AddStream and RemoveStream.
4083 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004084 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
Jonas Olsson45cc8902018-02-13 10:37:07 +01004085 " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08004086 return;
deadbeefab9b2d12015-10-14 11:33:11 -07004087 }
deadbeeffac06552015-11-25 11:26:01 -08004088
Steve Anton4171afb2017-11-20 10:20:22 -08004089 sender->internal()->SetSsrc(0);
deadbeefab9b2d12015-10-14 11:33:11 -07004090}
4091
4092void PeerConnection::UpdateLocalRtpDataChannels(
4093 const cricket::StreamParamsVec& streams) {
4094 std::vector<std::string> existing_channels;
4095
4096 // Find new and active data channels.
4097 for (const cricket::StreamParams& params : streams) {
4098 // |it->sync_label| is actually the data channel label. The reason is that
4099 // we use the same naming of data channels as we do for
4100 // MediaStreams and Tracks.
4101 // For MediaStreams, the sync_label is the MediaStream label and the
4102 // track label is the same as |streamid|.
Seth Hampson845e8782018-03-02 11:34:10 -08004103 const std::string& channel_label = params.first_stream_id();
deadbeefab9b2d12015-10-14 11:33:11 -07004104 auto data_channel_it = rtp_data_channels_.find(channel_label);
nisse7ce109a2017-01-31 00:57:56 -08004105 if (data_channel_it == rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004106 RTC_LOG(LS_ERROR) << "channel label not found";
deadbeefab9b2d12015-10-14 11:33:11 -07004107 continue;
4108 }
4109 // Set the SSRC the data channel should use for sending.
4110 data_channel_it->second->SetSendSsrc(params.first_ssrc());
4111 existing_channels.push_back(data_channel_it->first);
4112 }
4113
4114 UpdateClosingRtpDataChannels(existing_channels, true);
4115}
4116
4117void PeerConnection::UpdateRemoteRtpDataChannels(
4118 const cricket::StreamParamsVec& streams) {
4119 std::vector<std::string> existing_channels;
4120
4121 // Find new and active data channels.
4122 for (const cricket::StreamParams& params : streams) {
4123 // The data channel label is either the mslabel or the SSRC if the mslabel
4124 // does not exist. Ex a=ssrc:444330170 mslabel:test1.
Seth Hampson845e8782018-03-02 11:34:10 -08004125 std::string label = params.first_stream_id().empty()
deadbeefab9b2d12015-10-14 11:33:11 -07004126 ? rtc::ToString(params.first_ssrc())
Seth Hampson845e8782018-03-02 11:34:10 -08004127 : params.first_stream_id();
deadbeefab9b2d12015-10-14 11:33:11 -07004128 auto data_channel_it = rtp_data_channels_.find(label);
4129 if (data_channel_it == rtp_data_channels_.end()) {
4130 // This is a new data channel.
4131 CreateRemoteRtpDataChannel(label, params.first_ssrc());
4132 } else {
4133 data_channel_it->second->SetReceiveSsrc(params.first_ssrc());
4134 }
4135 existing_channels.push_back(label);
4136 }
4137
4138 UpdateClosingRtpDataChannels(existing_channels, false);
4139}
4140
4141void PeerConnection::UpdateClosingRtpDataChannels(
4142 const std::vector<std::string>& active_channels,
4143 bool is_local_update) {
4144 auto it = rtp_data_channels_.begin();
4145 while (it != rtp_data_channels_.end()) {
4146 DataChannel* data_channel = it->second;
4147 if (std::find(active_channels.begin(), active_channels.end(),
4148 data_channel->label()) != active_channels.end()) {
4149 ++it;
4150 continue;
4151 }
4152
4153 if (is_local_update) {
4154 data_channel->SetSendSsrc(0);
4155 } else {
4156 data_channel->RemotePeerRequestClose();
4157 }
4158
4159 if (data_channel->state() == DataChannel::kClosed) {
4160 rtp_data_channels_.erase(it);
4161 it = rtp_data_channels_.begin();
4162 } else {
4163 ++it;
4164 }
4165 }
4166}
4167
4168void PeerConnection::CreateRemoteRtpDataChannel(const std::string& label,
4169 uint32_t remote_ssrc) {
4170 rtc::scoped_refptr<DataChannel> channel(
4171 InternalCreateDataChannel(label, nullptr));
4172 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004173 RTC_LOG(LS_WARNING) << "Remote peer requested a DataChannel but"
Jonas Olsson45cc8902018-02-13 10:37:07 +01004174 "CreateDataChannel failed.";
deadbeefab9b2d12015-10-14 11:33:11 -07004175 return;
4176 }
4177 channel->SetReceiveSsrc(remote_ssrc);
deadbeefa601f5c2016-06-06 14:27:39 -07004178 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
4179 DataChannelProxy::Create(signaling_thread(), channel);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07004180 observer_->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07004181}
4182
4183rtc::scoped_refptr<DataChannel> PeerConnection::InternalCreateDataChannel(
4184 const std::string& label,
4185 const InternalDataChannelInit* config) {
4186 if (IsClosed()) {
4187 return nullptr;
4188 }
Steve Anton75737c02017-11-06 10:37:17 -08004189 if (data_channel_type() == cricket::DCT_NONE) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004190 RTC_LOG(LS_ERROR)
deadbeefab9b2d12015-10-14 11:33:11 -07004191 << "InternalCreateDataChannel: Data is not supported in this call.";
4192 return nullptr;
4193 }
4194 InternalDataChannelInit new_config =
4195 config ? (*config) : InternalDataChannelInit();
Steve Anton75737c02017-11-06 10:37:17 -08004196 if (data_channel_type() == cricket::DCT_SCTP) {
deadbeefab9b2d12015-10-14 11:33:11 -07004197 if (new_config.id < 0) {
4198 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08004199 if ((GetSctpSslRole(&role)) &&
deadbeefab9b2d12015-10-14 11:33:11 -07004200 !sid_allocator_.AllocateSid(role, &new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004201 RTC_LOG(LS_ERROR)
4202 << "No id can be allocated for the SCTP data channel.";
deadbeefab9b2d12015-10-14 11:33:11 -07004203 return nullptr;
4204 }
4205 } else if (!sid_allocator_.ReserveSid(new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004206 RTC_LOG(LS_ERROR) << "Failed to create a SCTP data channel "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004207 "because the id is already in use or out of range.";
deadbeefab9b2d12015-10-14 11:33:11 -07004208 return nullptr;
4209 }
4210 }
4211
Steve Anton75737c02017-11-06 10:37:17 -08004212 rtc::scoped_refptr<DataChannel> channel(
4213 DataChannel::Create(this, data_channel_type(), label, new_config));
deadbeefab9b2d12015-10-14 11:33:11 -07004214 if (!channel) {
4215 sid_allocator_.ReleaseSid(new_config.id);
4216 return nullptr;
4217 }
4218
4219 if (channel->data_channel_type() == cricket::DCT_RTP) {
4220 if (rtp_data_channels_.find(channel->label()) != rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004221 RTC_LOG(LS_ERROR) << "DataChannel with label " << channel->label()
4222 << " already exists.";
deadbeefab9b2d12015-10-14 11:33:11 -07004223 return nullptr;
4224 }
4225 rtp_data_channels_[channel->label()] = channel;
4226 } else {
4227 RTC_DCHECK(channel->data_channel_type() == cricket::DCT_SCTP);
4228 sctp_data_channels_.push_back(channel);
4229 channel->SignalClosed.connect(this,
4230 &PeerConnection::OnSctpDataChannelClosed);
4231 }
4232
Steve Anton2d8609c2018-01-23 16:38:46 -08004233 SignalDataChannelCreated_(channel.get());
deadbeefab9b2d12015-10-14 11:33:11 -07004234 return channel;
4235}
4236
4237bool PeerConnection::HasDataChannels() const {
4238 return !rtp_data_channels_.empty() || !sctp_data_channels_.empty();
4239}
4240
4241void PeerConnection::AllocateSctpSids(rtc::SSLRole role) {
4242 for (const auto& channel : sctp_data_channels_) {
4243 if (channel->id() < 0) {
4244 int sid;
4245 if (!sid_allocator_.AllocateSid(role, &sid)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004246 RTC_LOG(LS_ERROR) << "Failed to allocate SCTP sid.";
deadbeefab9b2d12015-10-14 11:33:11 -07004247 continue;
4248 }
4249 channel->SetSctpSid(sid);
4250 }
4251 }
4252}
4253
4254void PeerConnection::OnSctpDataChannelClosed(DataChannel* channel) {
deadbeefbd292462015-12-14 18:15:29 -08004255 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeefab9b2d12015-10-14 11:33:11 -07004256 for (auto it = sctp_data_channels_.begin(); it != sctp_data_channels_.end();
4257 ++it) {
4258 if (it->get() == channel) {
4259 if (channel->id() >= 0) {
4260 sid_allocator_.ReleaseSid(channel->id());
4261 }
deadbeefbd292462015-12-14 18:15:29 -08004262 // Since this method is triggered by a signal from the DataChannel,
4263 // we can't free it directly here; we need to free it asynchronously.
4264 sctp_data_channels_to_free_.push_back(*it);
deadbeefab9b2d12015-10-14 11:33:11 -07004265 sctp_data_channels_.erase(it);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07004266 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_FREE_DATACHANNELS,
4267 nullptr);
deadbeefab9b2d12015-10-14 11:33:11 -07004268 return;
4269 }
4270 }
4271}
4272
deadbeefab9b2d12015-10-14 11:33:11 -07004273void PeerConnection::OnDataChannelDestroyed() {
4274 // Use a temporary copy of the RTP/SCTP DataChannel list because the
4275 // DataChannel may callback to us and try to modify the list.
4276 std::map<std::string, rtc::scoped_refptr<DataChannel>> temp_rtp_dcs;
4277 temp_rtp_dcs.swap(rtp_data_channels_);
4278 for (const auto& kv : temp_rtp_dcs) {
4279 kv.second->OnTransportChannelDestroyed();
4280 }
4281
4282 std::vector<rtc::scoped_refptr<DataChannel>> temp_sctp_dcs;
4283 temp_sctp_dcs.swap(sctp_data_channels_);
4284 for (const auto& channel : temp_sctp_dcs) {
4285 channel->OnTransportChannelDestroyed();
4286 }
4287}
4288
4289void PeerConnection::OnDataChannelOpenMessage(
4290 const std::string& label,
4291 const InternalDataChannelInit& config) {
4292 rtc::scoped_refptr<DataChannel> channel(
4293 InternalCreateDataChannel(label, &config));
4294 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004295 RTC_LOG(LS_ERROR) << "Failed to create DataChannel from the OPEN message.";
deadbeefab9b2d12015-10-14 11:33:11 -07004296 return;
4297 }
4298
deadbeefa601f5c2016-06-06 14:27:39 -07004299 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
4300 DataChannelProxy::Create(signaling_thread(), channel);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07004301 observer_->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07004302}
4303
Steve Anton4171afb2017-11-20 10:20:22 -08004304rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
4305PeerConnection::GetAudioTransceiver() const {
4306 // This method only works with Plan B SDP, where there is a single
4307 // audio/video transceiver.
4308 RTC_DCHECK(!IsUnifiedPlan());
4309 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08004310 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004311 return transceiver;
4312 }
4313 }
4314 RTC_NOTREACHED();
4315 return nullptr;
4316}
4317
4318rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
4319PeerConnection::GetVideoTransceiver() const {
4320 // This method only works with Plan B SDP, where there is a single
4321 // audio/video transceiver.
4322 RTC_DCHECK(!IsUnifiedPlan());
4323 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08004324 if (transceiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004325 return transceiver;
4326 }
4327 }
4328 RTC_NOTREACHED();
4329 return nullptr;
4330}
4331
4332// TODO(bugs.webrtc.org/7600): Remove this when multiple transceivers with
4333// individual transceiver directions are supported.
zhihuang1c378ed2017-08-17 14:10:50 -07004334bool PeerConnection::HasRtpSender(cricket::MediaType type) const {
Steve Anton4171afb2017-11-20 10:20:22 -08004335 switch (type) {
4336 case cricket::MEDIA_TYPE_AUDIO:
4337 return !GetAudioTransceiver()->internal()->senders().empty();
4338 case cricket::MEDIA_TYPE_VIDEO:
4339 return !GetVideoTransceiver()->internal()->senders().empty();
4340 case cricket::MEDIA_TYPE_DATA:
4341 return false;
4342 }
4343 RTC_NOTREACHED();
4344 return false;
zhihuang1c378ed2017-08-17 14:10:50 -07004345}
4346
Steve Anton4171afb2017-11-20 10:20:22 -08004347rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
4348PeerConnection::FindSenderForTrack(MediaStreamTrackInterface* track) const {
4349 for (auto transceiver : transceivers_) {
4350 for (auto sender : transceiver->internal()->senders()) {
4351 if (sender->track() == track) {
4352 return sender;
4353 }
4354 }
4355 }
4356 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08004357}
4358
Steve Anton4171afb2017-11-20 10:20:22 -08004359rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
4360PeerConnection::FindSenderById(const std::string& sender_id) const {
4361 for (auto transceiver : transceivers_) {
4362 for (auto sender : transceiver->internal()->senders()) {
4363 if (sender->id() == sender_id) {
4364 return sender;
4365 }
4366 }
4367 }
4368 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07004369}
4370
Steve Anton4171afb2017-11-20 10:20:22 -08004371rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
4372PeerConnection::FindReceiverById(const std::string& receiver_id) const {
4373 for (auto transceiver : transceivers_) {
4374 for (auto receiver : transceiver->internal()->receivers()) {
4375 if (receiver->id() == receiver_id) {
4376 return receiver;
4377 }
4378 }
4379 }
4380 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07004381}
4382
Steve Anton4171afb2017-11-20 10:20:22 -08004383std::vector<PeerConnection::RtpSenderInfo>*
4384PeerConnection::GetRemoteSenderInfos(cricket::MediaType media_type) {
4385 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
4386 media_type == cricket::MEDIA_TYPE_VIDEO);
4387 return (media_type == cricket::MEDIA_TYPE_AUDIO)
4388 ? &remote_audio_sender_infos_
4389 : &remote_video_sender_infos_;
4390}
4391
4392std::vector<PeerConnection::RtpSenderInfo>* PeerConnection::GetLocalSenderInfos(
deadbeefab9b2d12015-10-14 11:33:11 -07004393 cricket::MediaType media_type) {
4394 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
4395 media_type == cricket::MEDIA_TYPE_VIDEO);
Steve Anton4171afb2017-11-20 10:20:22 -08004396 return (media_type == cricket::MEDIA_TYPE_AUDIO) ? &local_audio_sender_infos_
4397 : &local_video_sender_infos_;
deadbeefab9b2d12015-10-14 11:33:11 -07004398}
4399
Steve Anton4171afb2017-11-20 10:20:22 -08004400const PeerConnection::RtpSenderInfo* PeerConnection::FindSenderInfo(
4401 const std::vector<PeerConnection::RtpSenderInfo>& infos,
Seth Hampson845e8782018-03-02 11:34:10 -08004402 const std::string& stream_id,
Steve Anton4171afb2017-11-20 10:20:22 -08004403 const std::string sender_id) const {
4404 for (const RtpSenderInfo& sender_info : infos) {
Seth Hampson845e8782018-03-02 11:34:10 -08004405 if (sender_info.stream_id == stream_id &&
Steve Anton4171afb2017-11-20 10:20:22 -08004406 sender_info.sender_id == sender_id) {
4407 return &sender_info;
deadbeefab9b2d12015-10-14 11:33:11 -07004408 }
4409 }
4410 return nullptr;
4411}
4412
4413DataChannel* PeerConnection::FindDataChannelBySid(int sid) const {
4414 for (const auto& channel : sctp_data_channels_) {
4415 if (channel->id() == sid) {
4416 return channel;
4417 }
4418 }
4419 return nullptr;
4420}
4421
deadbeef91dd5672016-05-18 16:55:30 -07004422bool PeerConnection::InitializePortAllocator_n(
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004423 const RTCConfiguration& configuration) {
4424 cricket::ServerAddresses stun_servers;
4425 std::vector<cricket::RelayServerConfig> turn_servers;
deadbeef293e9262017-01-11 12:28:30 -08004426 if (ParseIceServers(configuration.servers, &stun_servers, &turn_servers) !=
4427 RTCErrorType::NONE) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004428 return false;
4429 }
4430
Taylor Brandstetterf8e65772016-06-27 17:20:15 -07004431 port_allocator_->Initialize();
4432
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004433 // To handle both internal and externally created port allocator, we will
4434 // enable BUNDLE here.
4435 int portallocator_flags = port_allocator_->flags();
4436 portallocator_flags |= cricket::PORTALLOCATOR_ENABLE_SHARED_SOCKET |
zhihuangb09b3f92017-03-07 14:40:51 -08004437 cricket::PORTALLOCATOR_ENABLE_IPV6 |
4438 cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI;
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004439 // If the disable-IPv6 flag was specified, we'll not override it
4440 // by experiment.
4441 if (configuration.disable_ipv6) {
4442 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
sprangc1b57a12017-02-28 08:50:47 -08004443 } else if (webrtc::field_trial::FindFullName("WebRTC-IPv6Default")
4444 .find("Disabled") == 0) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004445 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
4446 }
4447
zhihuangb09b3f92017-03-07 14:40:51 -08004448 if (configuration.disable_ipv6_on_wifi) {
4449 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI);
Mirko Bonadei675513b2017-11-09 11:09:25 +01004450 RTC_LOG(LS_INFO) << "IPv6 candidates on Wi-Fi are disabled.";
zhihuangb09b3f92017-03-07 14:40:51 -08004451 }
4452
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004453 if (configuration.tcp_candidate_policy == kTcpCandidatePolicyDisabled) {
4454 portallocator_flags |= cricket::PORTALLOCATOR_DISABLE_TCP;
Mirko Bonadei675513b2017-11-09 11:09:25 +01004455 RTC_LOG(LS_INFO) << "TCP candidates are disabled.";
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004456 }
4457
honghaiz60347052016-05-31 18:29:12 -07004458 if (configuration.candidate_network_policy ==
4459 kCandidateNetworkPolicyLowCost) {
4460 portallocator_flags |= cricket::PORTALLOCATOR_DISABLE_COSTLY_NETWORKS;
Mirko Bonadei675513b2017-11-09 11:09:25 +01004461 RTC_LOG(LS_INFO) << "Do not gather candidates on high-cost networks";
honghaiz60347052016-05-31 18:29:12 -07004462 }
4463
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +01004464 if (configuration.disable_link_local_networks) {
4465 portallocator_flags |= cricket::PORTALLOCATOR_DISABLE_LINK_LOCAL_NETWORKS;
4466 RTC_LOG(LS_INFO) << "Disable candidates on link-local network interfaces.";
4467 }
4468
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004469 port_allocator_->set_flags(portallocator_flags);
4470 // No step delay is used while allocating ports.
4471 port_allocator_->set_step_delay(cricket::kMinimumStepDelay);
4472 port_allocator_->set_candidate_filter(
4473 ConvertIceTransportTypeToCandidateFilter(configuration.type));
deadbeefd21eab32017-07-26 16:50:11 -07004474 port_allocator_->set_max_ipv6_networks(configuration.max_ipv6_networks);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004475
4476 // Call this last since it may create pooled allocator sessions using the
4477 // properties set above.
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08004478 port_allocator_->SetConfiguration(
4479 stun_servers, turn_servers, configuration.ice_candidate_pool_size,
4480 configuration.prune_turn_ports, configuration.turn_customizer,
4481 configuration.stun_candidate_keepalive_interval);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004482 return true;
4483}
4484
deadbeef91dd5672016-05-18 16:55:30 -07004485bool PeerConnection::ReconfigurePortAllocator_n(
deadbeef293e9262017-01-11 12:28:30 -08004486 const cricket::ServerAddresses& stun_servers,
4487 const std::vector<cricket::RelayServerConfig>& turn_servers,
4488 IceTransportsType type,
4489 int candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02004490 bool prune_turn_ports,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08004491 webrtc::TurnCustomizer* turn_customizer,
4492 rtc::Optional<int> stun_candidate_keepalive_interval) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004493 port_allocator_->set_candidate_filter(
deadbeef293e9262017-01-11 12:28:30 -08004494 ConvertIceTransportTypeToCandidateFilter(type));
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004495 // Call this last since it may create pooled allocator sessions using the
4496 // candidate filter set above.
deadbeef6de92f92016-12-12 18:49:32 -08004497 return port_allocator_->SetConfiguration(
Jonas Orelandbdcee282017-10-10 14:01:40 +02004498 stun_servers, turn_servers, candidate_pool_size, prune_turn_ports,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08004499 turn_customizer, stun_candidate_keepalive_interval);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004500}
4501
Steve Antonba818672017-11-06 10:21:57 -08004502cricket::ChannelManager* PeerConnection::channel_manager() const {
4503 return factory_->channel_manager();
4504}
4505
4506MetricsObserverInterface* PeerConnection::metrics_observer() const {
4507 return uma_observer_;
4508}
4509
Elad Alon99c3fe52017-10-13 16:29:40 +02004510bool PeerConnection::StartRtcEventLog_w(
Bjorn Tereliusde939432017-11-20 17:38:14 +01004511 std::unique_ptr<RtcEventLogOutput> output,
4512 int64_t output_period_ms) {
zhihuang77985012017-02-07 15:45:16 -08004513 if (!event_log_) {
4514 return false;
4515 }
Bjorn Tereliusde939432017-11-20 17:38:14 +01004516 return event_log_->StartLogging(std::move(output), output_period_ms);
ivoc14d5dbe2016-07-04 07:06:55 -07004517}
4518
4519void PeerConnection::StopRtcEventLog_w() {
zhihuang77985012017-02-07 15:45:16 -08004520 if (event_log_) {
4521 event_log_->StopLogging();
4522 }
ivoc14d5dbe2016-07-04 07:06:55 -07004523}
nisseeaabdf62017-05-05 02:23:02 -07004524
Steve Anton75737c02017-11-06 10:37:17 -08004525cricket::BaseChannel* PeerConnection::GetChannel(
4526 const std::string& content_name) {
Steve Antondcc3c022017-12-22 16:02:54 -08004527 for (auto transceiver : transceivers_) {
4528 cricket::BaseChannel* channel = transceiver->internal()->channel();
4529 if (channel && channel->content_name() == content_name) {
4530 return channel;
4531 }
Steve Anton75737c02017-11-06 10:37:17 -08004532 }
4533 if (rtp_data_channel() &&
4534 rtp_data_channel()->content_name() == content_name) {
4535 return rtp_data_channel();
4536 }
4537 return nullptr;
4538}
4539
4540bool PeerConnection::GetSctpSslRole(rtc::SSLRole* role) {
4541 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004542 RTC_LOG(LS_INFO)
4543 << "Local and Remote descriptions must be applied to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004544 "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08004545 return false;
4546 }
4547 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004548 RTC_LOG(LS_INFO) << "Non-rejected SCTP m= section is needed to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004549 "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08004550 return false;
4551 }
4552
4553 return transport_controller_->GetSslRole(*sctp_transport_name_, role);
4554}
4555
4556bool PeerConnection::GetSslRole(const std::string& content_name,
4557 rtc::SSLRole* role) {
4558 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004559 RTC_LOG(LS_INFO)
4560 << "Local and Remote descriptions must be applied to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004561 "SSL Role of the session.";
Steve Anton75737c02017-11-06 10:37:17 -08004562 return false;
4563 }
4564
4565 return transport_controller_->GetSslRole(GetTransportName(content_name),
4566 role);
4567}
4568
Steve Antonf8470812017-12-04 10:46:21 -08004569void PeerConnection::SetSessionError(SessionError error,
4570 const std::string& error_desc) {
4571 RTC_DCHECK_RUN_ON(signaling_thread());
4572 if (error != session_error_) {
4573 session_error_ = error;
4574 session_error_desc_ = error_desc;
Steve Anton75737c02017-11-06 10:37:17 -08004575 }
4576}
4577
Steve Anton3828c062017-12-06 10:34:51 -08004578RTCError PeerConnection::UpdateSessionState(SdpType type,
Steve Anton8a006912017-12-04 15:25:56 -08004579 cricket::ContentSource source) {
4580 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08004581
4582 // If there's already a pending error then no state transition should happen.
4583 // But all call-sites should be verifying this before calling us!
Steve Antonf8470812017-12-04 10:46:21 -08004584 RTC_DCHECK(session_error() == SessionError::kNone);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004585
4586 // If this is an answer then we know whether to BUNDLE or not. If both the
4587 // local and remote side have agreed to BUNDLE, go ahead and enable it.
Steve Anton3828c062017-12-06 10:34:51 -08004588 if (type == SdpType::kAnswer) {
Steve Anton75737c02017-11-06 10:37:17 -08004589 const cricket::ContentGroup* local_bundle =
4590 local_description()->description()->GetGroupByName(
4591 cricket::GROUP_TYPE_BUNDLE);
4592 const cricket::ContentGroup* remote_bundle =
4593 remote_description()->description()->GetGroupByName(
4594 cricket::GROUP_TYPE_BUNDLE);
4595 if (local_bundle && remote_bundle) {
4596 // The answerer decides the transport to bundle on.
4597 const cricket::ContentGroup* answer_bundle =
4598 (source == cricket::CS_LOCAL ? local_bundle : remote_bundle);
4599 if (!EnableBundle(*answer_bundle)) {
Steve Anton8a006912017-12-04 15:25:56 -08004600 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
4601 kEnableBundleFailed);
Steve Anton75737c02017-11-06 10:37:17 -08004602 }
4603 }
Steve Anton75737c02017-11-06 10:37:17 -08004604 }
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004605
4606 // Only push down the transport description after potentially enabling BUNDLE;
4607 // we don't want to push down a description on a transport about to be
4608 // destroyed.
Steve Anton3828c062017-12-06 10:34:51 -08004609 RTCError error = PushdownTransportDescription(source, type);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004610 if (!error.ok()) {
4611 return error;
4612 }
4613
4614 // If this is answer-ish we're ready to let media flow.
Steve Anton3828c062017-12-06 10:34:51 -08004615 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Antoned10bd92017-12-05 10:52:59 -08004616 EnableSending();
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004617 }
4618
4619 // Update the signaling state according to the specified state machine (see
4620 // https://w3c.github.io/webrtc-pc/#rtcsignalingstate-enum).
Steve Anton3828c062017-12-06 10:34:51 -08004621 if (type == SdpType::kOffer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004622 ChangeSignalingState(source == cricket::CS_LOCAL
4623 ? PeerConnectionInterface::kHaveLocalOffer
4624 : PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton3828c062017-12-06 10:34:51 -08004625 } else if (type == SdpType::kPrAnswer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004626 ChangeSignalingState(source == cricket::CS_LOCAL
4627 ? PeerConnectionInterface::kHaveLocalPrAnswer
4628 : PeerConnectionInterface::kHaveRemotePrAnswer);
4629 } else {
Steve Anton3828c062017-12-06 10:34:51 -08004630 RTC_DCHECK(type == SdpType::kAnswer);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004631 ChangeSignalingState(PeerConnectionInterface::kStable);
4632 }
4633
4634 // Update internal objects according to the session description's media
4635 // descriptions.
Steve Anton3828c062017-12-06 10:34:51 -08004636 error = PushdownMediaDescription(type, source);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004637 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08004638 return error;
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004639 }
4640
Steve Anton8a006912017-12-04 15:25:56 -08004641 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08004642}
4643
Steve Anton8a006912017-12-04 15:25:56 -08004644RTCError PeerConnection::PushdownMediaDescription(
Steve Anton3828c062017-12-06 10:34:51 -08004645 SdpType type,
Steve Anton8a006912017-12-04 15:25:56 -08004646 cricket::ContentSource source) {
Steve Antoned10bd92017-12-05 10:52:59 -08004647 const SessionDescriptionInterface* sdesc =
4648 (source == cricket::CS_LOCAL ? local_description()
4649 : remote_description());
Steve Anton75737c02017-11-06 10:37:17 -08004650 RTC_DCHECK(sdesc);
Steve Antoned10bd92017-12-05 10:52:59 -08004651
4652 // Push down the new SDP media section for each audio/video transceiver.
4653 for (auto transceiver : transceivers_) {
Steve Anton75737c02017-11-06 10:37:17 -08004654 const ContentInfo* content_info =
Steve Antoned10bd92017-12-05 10:52:59 -08004655 FindMediaSectionForTransceiver(transceiver, sdesc);
4656 cricket::BaseChannel* channel = transceiver->internal()->channel();
4657 if (!channel || !content_info || content_info->rejected) {
Steve Anton75737c02017-11-06 10:37:17 -08004658 continue;
4659 }
4660 const MediaContentDescription* content_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08004661 content_info->media_description();
Steve Antoned10bd92017-12-05 10:52:59 -08004662 if (!content_desc) {
4663 continue;
4664 }
4665 std::string error;
4666 bool success =
4667 (source == cricket::CS_LOCAL)
Steve Anton3828c062017-12-06 10:34:51 -08004668 ? channel->SetLocalContent(content_desc, type, &error)
4669 : channel->SetRemoteContent(content_desc, type, &error);
Steve Antoned10bd92017-12-05 10:52:59 -08004670 if (!success) {
4671 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, std::move(error));
4672 }
4673 }
4674
4675 // If using the RtpDataChannel, push down the new SDP section for it too.
4676 if (rtp_data_channel_) {
4677 const ContentInfo* data_content =
4678 cricket::GetFirstDataContent(sdesc->description());
4679 if (data_content && !data_content->rejected) {
4680 const MediaContentDescription* data_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08004681 data_content->media_description();
Steve Antoned10bd92017-12-05 10:52:59 -08004682 if (data_desc) {
4683 std::string error;
4684 bool success =
4685 (source == cricket::CS_LOCAL)
Steve Anton3828c062017-12-06 10:34:51 -08004686 ? rtp_data_channel_->SetLocalContent(data_desc, type, &error)
4687 : rtp_data_channel_->SetRemoteContent(data_desc, type,
Steve Antoned10bd92017-12-05 10:52:59 -08004688 &error);
4689 if (!success) {
4690 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
4691 std::move(error));
4692 }
Steve Anton75737c02017-11-06 10:37:17 -08004693 }
4694 }
4695 }
Steve Antoned10bd92017-12-05 10:52:59 -08004696
Steve Anton75737c02017-11-06 10:37:17 -08004697 // Need complete offer/answer with an SCTP m= section before starting SCTP,
4698 // according to https://tools.ietf.org/html/draft-ietf-mmusic-sctp-sdp-19
4699 if (sctp_transport_ && local_description() && remote_description() &&
4700 cricket::GetFirstDataContent(local_description()->description()) &&
4701 cricket::GetFirstDataContent(remote_description()->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08004702 bool success = network_thread()->Invoke<bool>(
Steve Anton75737c02017-11-06 10:37:17 -08004703 RTC_FROM_HERE,
4704 rtc::Bind(&PeerConnection::PushdownSctpParameters_n, this, source));
Steve Anton8a006912017-12-04 15:25:56 -08004705 if (!success) {
4706 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
4707 "Failed to push down SCTP parameters.");
4708 }
Steve Anton75737c02017-11-06 10:37:17 -08004709 }
Steve Antoned10bd92017-12-05 10:52:59 -08004710
Steve Anton8a006912017-12-04 15:25:56 -08004711 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08004712}
4713
4714bool PeerConnection::PushdownSctpParameters_n(cricket::ContentSource source) {
4715 RTC_DCHECK(network_thread()->IsCurrent());
4716 RTC_DCHECK(local_description());
4717 RTC_DCHECK(remote_description());
4718 // Apply the SCTP port (which is hidden inside a DataCodec structure...)
4719 // When we support "max-message-size", that would also be pushed down here.
4720 return sctp_transport_->Start(
4721 GetSctpPort(local_description()->description()),
4722 GetSctpPort(remote_description()->description()));
4723}
4724
Steve Anton8a006912017-12-04 15:25:56 -08004725RTCError PeerConnection::PushdownTransportDescription(
4726 cricket::ContentSource source,
Steve Anton3828c062017-12-06 10:34:51 -08004727 SdpType type) {
Steve Anton8a006912017-12-04 15:25:56 -08004728 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08004729
Steve Anton8a006912017-12-04 15:25:56 -08004730 const SessionDescriptionInterface* sdesc =
4731 (source == cricket::CS_LOCAL ? local_description()
4732 : remote_description());
4733 RTC_DCHECK(sdesc);
4734 for (const cricket::TransportInfo& tinfo :
4735 sdesc->description()->transport_infos()) {
4736 std::string error;
4737 bool success;
4738 if (source == cricket::CS_LOCAL) {
4739 success = transport_controller_->SetLocalTransportDescription(
Steve Anton3828c062017-12-06 10:34:51 -08004740 tinfo.content_name, tinfo.description, type, &error);
Steve Anton8a006912017-12-04 15:25:56 -08004741 } else {
4742 success = transport_controller_->SetRemoteTransportDescription(
Steve Anton3828c062017-12-06 10:34:51 -08004743 tinfo.content_name, tinfo.description, type, &error);
Steve Anton8a006912017-12-04 15:25:56 -08004744 }
4745 if (!success) {
Steve Antondcc3c022017-12-22 16:02:54 -08004746 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
4747 "Failed to push down transport description for " +
4748 tinfo.content_name + ": " + error);
Steve Anton75737c02017-11-06 10:37:17 -08004749 }
4750 }
4751
Steve Anton8a006912017-12-04 15:25:56 -08004752 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08004753}
4754
4755bool PeerConnection::GetTransportDescription(
4756 const SessionDescription* description,
4757 const std::string& content_name,
4758 cricket::TransportDescription* tdesc) {
4759 if (!description || !tdesc) {
4760 return false;
4761 }
4762 const TransportInfo* transport_info =
4763 description->GetTransportInfoByName(content_name);
4764 if (!transport_info) {
4765 return false;
4766 }
4767 *tdesc = transport_info->description;
4768 return true;
4769}
4770
4771bool PeerConnection::EnableBundle(const cricket::ContentGroup& bundle) {
4772 const std::string* first_content_name = bundle.FirstContentName();
4773 if (!first_content_name) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004774 RTC_LOG(LS_WARNING) << "Tried to BUNDLE with no contents.";
Steve Anton75737c02017-11-06 10:37:17 -08004775 return false;
4776 }
4777 const std::string& transport_name = *first_content_name;
4778
4779 auto maybe_set_transport = [this, bundle,
4780 transport_name](cricket::BaseChannel* ch) {
4781 if (!ch || !bundle.HasContentName(ch->content_name())) {
Steve Antoned10bd92017-12-05 10:52:59 -08004782 return;
Steve Anton75737c02017-11-06 10:37:17 -08004783 }
4784
4785 std::string old_transport_name = ch->transport_name();
4786 if (old_transport_name == transport_name) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004787 RTC_LOG(LS_INFO) << "BUNDLE already enabled for " << ch->content_name()
4788 << " on " << transport_name << ".";
Steve Antoned10bd92017-12-05 10:52:59 -08004789 return;
Steve Anton75737c02017-11-06 10:37:17 -08004790 }
4791
4792 cricket::DtlsTransportInternal* rtp_dtls_transport =
4793 transport_controller_->CreateDtlsTransport(
4794 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4795 bool need_rtcp = (ch->rtcp_dtls_transport() != nullptr);
4796 cricket::DtlsTransportInternal* rtcp_dtls_transport = nullptr;
4797 if (need_rtcp) {
4798 rtcp_dtls_transport = transport_controller_->CreateDtlsTransport(
4799 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
4800 }
4801
4802 ch->SetTransports(rtp_dtls_transport, rtcp_dtls_transport);
Mirko Bonadei675513b2017-11-09 11:09:25 +01004803 RTC_LOG(LS_INFO) << "Enabled BUNDLE for " << ch->content_name() << " on "
4804 << transport_name << ".";
Steve Anton75737c02017-11-06 10:37:17 -08004805 transport_controller_->DestroyDtlsTransport(
4806 old_transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4807 // If the channel needs rtcp, it means that the channel used to have a
4808 // rtcp transport which needs to be deleted now.
4809 if (need_rtcp) {
4810 transport_controller_->DestroyDtlsTransport(
4811 old_transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
4812 }
Steve Anton75737c02017-11-06 10:37:17 -08004813 };
4814
Steve Antoned10bd92017-12-05 10:52:59 -08004815 for (auto transceiver : transceivers_) {
4816 maybe_set_transport(transceiver->internal()->channel());
Steve Anton75737c02017-11-06 10:37:17 -08004817 }
Steve Antoned10bd92017-12-05 10:52:59 -08004818 maybe_set_transport(rtp_data_channel_);
4819
Steve Anton75737c02017-11-06 10:37:17 -08004820 // For SCTP, transport creation/deletion happens here instead of in the
4821 // object itself.
4822 if (sctp_transport_) {
4823 RTC_DCHECK(sctp_transport_name_);
4824 RTC_DCHECK(sctp_content_name_);
4825 if (transport_name != *sctp_transport_name_ &&
4826 bundle.HasContentName(*sctp_content_name_)) {
4827 network_thread()->Invoke<void>(
4828 RTC_FROM_HERE, rtc::Bind(&PeerConnection::ChangeSctpTransport_n, this,
4829 transport_name));
4830 }
4831 }
4832
4833 return true;
4834}
4835
Steve Anton75737c02017-11-06 10:37:17 -08004836cricket::IceConfig PeerConnection::ParseIceConfig(
4837 const PeerConnectionInterface::RTCConfiguration& config) const {
4838 cricket::ContinualGatheringPolicy gathering_policy;
4839 // TODO(honghaiz): Add the third continual gathering policy in
4840 // PeerConnectionInterface and map it to GATHER_CONTINUALLY_AND_RECOVER.
4841 switch (config.continual_gathering_policy) {
4842 case PeerConnectionInterface::GATHER_ONCE:
4843 gathering_policy = cricket::GATHER_ONCE;
4844 break;
4845 case PeerConnectionInterface::GATHER_CONTINUALLY:
4846 gathering_policy = cricket::GATHER_CONTINUALLY;
4847 break;
4848 default:
4849 RTC_NOTREACHED();
4850 gathering_policy = cricket::GATHER_ONCE;
4851 }
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08004852
Steve Anton75737c02017-11-06 10:37:17 -08004853 cricket::IceConfig ice_config;
4854 ice_config.receiving_timeout = config.ice_connection_receiving_timeout;
4855 ice_config.prioritize_most_likely_candidate_pairs =
4856 config.prioritize_most_likely_ice_candidate_pairs;
4857 ice_config.backup_connection_ping_interval =
4858 config.ice_backup_candidate_pair_ping_interval;
4859 ice_config.continual_gathering_policy = gathering_policy;
4860 ice_config.presume_writable_when_fully_relayed =
4861 config.presume_writable_when_fully_relayed;
4862 ice_config.ice_check_min_interval = config.ice_check_min_interval;
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08004863 ice_config.stun_keepalive_interval = config.stun_candidate_keepalive_interval;
Steve Anton75737c02017-11-06 10:37:17 -08004864 ice_config.regather_all_networks_interval_range =
4865 config.ice_regather_interval_range;
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08004866 ice_config.network_preference = config.network_preference;
Steve Anton75737c02017-11-06 10:37:17 -08004867 return ice_config;
4868}
4869
Steve Anton75737c02017-11-06 10:37:17 -08004870bool PeerConnection::GetLocalTrackIdBySsrc(uint32_t ssrc,
4871 std::string* track_id) {
4872 if (!local_description()) {
4873 return false;
4874 }
4875 return webrtc::GetTrackIdBySsrc(local_description()->description(), ssrc,
4876 track_id);
4877}
4878
4879bool PeerConnection::GetRemoteTrackIdBySsrc(uint32_t ssrc,
4880 std::string* track_id) {
4881 if (!remote_description()) {
4882 return false;
4883 }
4884 return webrtc::GetTrackIdBySsrc(remote_description()->description(), ssrc,
4885 track_id);
4886}
4887
4888bool PeerConnection::SendData(const cricket::SendDataParams& params,
4889 const rtc::CopyOnWriteBuffer& payload,
4890 cricket::SendDataResult* result) {
4891 if (!rtp_data_channel_ && !sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004892 RTC_LOG(LS_ERROR) << "SendData called when rtp_data_channel_ "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004893 "and sctp_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08004894 return false;
4895 }
4896 return rtp_data_channel_
4897 ? rtp_data_channel_->SendData(params, payload, result)
4898 : network_thread()->Invoke<bool>(
4899 RTC_FROM_HERE,
4900 Bind(&cricket::SctpTransportInternal::SendData,
4901 sctp_transport_.get(), params, payload, result));
4902}
4903
4904bool PeerConnection::ConnectDataChannel(DataChannel* webrtc_data_channel) {
4905 if (!rtp_data_channel_ && !sctp_transport_) {
4906 // Don't log an error here, because DataChannels are expected to call
4907 // ConnectDataChannel in this state. It's the only way to initially tell
4908 // whether or not the underlying transport is ready.
4909 return false;
4910 }
4911 if (rtp_data_channel_) {
4912 rtp_data_channel_->SignalReadyToSendData.connect(
4913 webrtc_data_channel, &DataChannel::OnChannelReady);
4914 rtp_data_channel_->SignalDataReceived.connect(webrtc_data_channel,
4915 &DataChannel::OnDataReceived);
4916 } else {
4917 SignalSctpReadyToSendData.connect(webrtc_data_channel,
4918 &DataChannel::OnChannelReady);
4919 SignalSctpDataReceived.connect(webrtc_data_channel,
4920 &DataChannel::OnDataReceived);
4921 SignalSctpStreamClosedRemotely.connect(
4922 webrtc_data_channel, &DataChannel::OnStreamClosedRemotely);
4923 }
4924 return true;
4925}
4926
4927void PeerConnection::DisconnectDataChannel(DataChannel* webrtc_data_channel) {
4928 if (!rtp_data_channel_ && !sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004929 RTC_LOG(LS_ERROR)
4930 << "DisconnectDataChannel called when rtp_data_channel_ and "
4931 "sctp_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08004932 return;
4933 }
4934 if (rtp_data_channel_) {
4935 rtp_data_channel_->SignalReadyToSendData.disconnect(webrtc_data_channel);
4936 rtp_data_channel_->SignalDataReceived.disconnect(webrtc_data_channel);
4937 } else {
4938 SignalSctpReadyToSendData.disconnect(webrtc_data_channel);
4939 SignalSctpDataReceived.disconnect(webrtc_data_channel);
4940 SignalSctpStreamClosedRemotely.disconnect(webrtc_data_channel);
4941 }
4942}
4943
4944void PeerConnection::AddSctpDataStream(int sid) {
4945 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004946 RTC_LOG(LS_ERROR)
4947 << "AddSctpDataStream called when sctp_transport_ is NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08004948 return;
4949 }
4950 network_thread()->Invoke<void>(
4951 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::OpenStream,
4952 sctp_transport_.get(), sid));
4953}
4954
4955void PeerConnection::RemoveSctpDataStream(int sid) {
4956 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004957 RTC_LOG(LS_ERROR) << "RemoveSctpDataStream called when sctp_transport_ is "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004958 "NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08004959 return;
4960 }
4961 network_thread()->Invoke<void>(
4962 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::ResetStream,
4963 sctp_transport_.get(), sid));
4964}
4965
4966bool PeerConnection::ReadyToSendData() const {
4967 return (rtp_data_channel_ && rtp_data_channel_->ready_to_send_data()) ||
4968 sctp_ready_to_send_data_;
4969}
4970
Qingsi Wang72a43a12018-02-20 16:03:18 -08004971cricket::CandidateStatsList PeerConnection::GetPooledCandidateStats() const {
4972 cricket::CandidateStatsList candidate_states_list;
4973 port_allocator_->GetCandidateStatsFromPooledSessions(&candidate_states_list);
4974 return candidate_states_list;
4975}
4976
Steve Anton5dfde182018-02-06 10:34:40 -08004977std::map<std::string, std::string> PeerConnection::GetTransportNamesByMid()
4978 const {
4979 std::map<std::string, std::string> transport_names_by_mid;
4980 for (auto transceiver : transceivers_) {
4981 cricket::BaseChannel* channel = transceiver->internal()->channel();
4982 if (channel) {
4983 transport_names_by_mid[channel->content_name()] =
4984 channel->transport_name();
4985 }
Steve Anton75737c02017-11-06 10:37:17 -08004986 }
Steve Anton5dfde182018-02-06 10:34:40 -08004987 if (rtp_data_channel_) {
4988 transport_names_by_mid[rtp_data_channel_->content_name()] =
4989 rtp_data_channel_->transport_name();
Steve Anton75737c02017-11-06 10:37:17 -08004990 }
4991 if (sctp_transport_) {
Steve Anton5dfde182018-02-06 10:34:40 -08004992 transport_names_by_mid[*sctp_content_name_] = *sctp_transport_name_;
Steve Anton75737c02017-11-06 10:37:17 -08004993 }
Steve Anton5dfde182018-02-06 10:34:40 -08004994 return transport_names_by_mid;
Steve Anton75737c02017-11-06 10:37:17 -08004995}
4996
Steve Anton5dfde182018-02-06 10:34:40 -08004997std::map<std::string, cricket::TransportStats>
4998PeerConnection::GetTransportStatsByNames(
4999 const std::set<std::string>& transport_names) {
5000 if (!network_thread()->IsCurrent()) {
5001 return network_thread()
5002 ->Invoke<std::map<std::string, cricket::TransportStats>>(
5003 RTC_FROM_HERE,
5004 [&] { return GetTransportStatsByNames(transport_names); });
Steve Anton75737c02017-11-06 10:37:17 -08005005 }
Steve Anton5dfde182018-02-06 10:34:40 -08005006 std::map<std::string, cricket::TransportStats> transport_stats_by_name;
5007 for (const std::string& transport_name : transport_names) {
5008 cricket::TransportStats transport_stats;
5009 bool success =
5010 transport_controller_->GetStats(transport_name, &transport_stats);
5011 if (success) {
5012 transport_stats_by_name[transport_name] = std::move(transport_stats);
5013 } else {
5014 RTC_LOG(LS_ERROR) << "Failed to get transport stats for transport_name="
5015 << transport_name;
5016 }
5017 }
5018 return transport_stats_by_name;
Steve Anton75737c02017-11-06 10:37:17 -08005019}
5020
5021bool PeerConnection::GetLocalCertificate(
5022 const std::string& transport_name,
5023 rtc::scoped_refptr<rtc::RTCCertificate>* certificate) {
5024 return transport_controller_->GetLocalCertificate(transport_name,
5025 certificate);
5026}
5027
Taylor Brandstetterc3928662018-02-23 13:04:51 -08005028std::unique_ptr<rtc::SSLCertChain> PeerConnection::GetRemoteSSLCertChain(
Steve Anton75737c02017-11-06 10:37:17 -08005029 const std::string& transport_name) {
Taylor Brandstetterc3928662018-02-23 13:04:51 -08005030 return transport_controller_->GetRemoteSSLCertChain(transport_name);
Steve Anton75737c02017-11-06 10:37:17 -08005031}
5032
5033cricket::DataChannelType PeerConnection::data_channel_type() const {
5034 return data_channel_type_;
5035}
5036
5037bool PeerConnection::IceRestartPending(const std::string& content_name) const {
5038 return pending_ice_restarts_.find(content_name) !=
5039 pending_ice_restarts_.end();
5040}
5041
Steve Anton75737c02017-11-06 10:37:17 -08005042bool PeerConnection::NeedsIceRestart(const std::string& content_name) const {
5043 return transport_controller_->NeedsIceRestart(content_name);
5044}
5045
5046void PeerConnection::OnCertificateReady(
5047 const rtc::scoped_refptr<rtc::RTCCertificate>& certificate) {
5048 transport_controller_->SetLocalCertificate(certificate);
5049}
5050
5051void PeerConnection::OnDtlsSrtpSetupFailure(cricket::BaseChannel*, bool rtcp) {
Steve Antonf8470812017-12-04 10:46:21 -08005052 SetSessionError(SessionError::kTransport,
5053 rtcp ? kDtlsSrtpSetupFailureRtcp : kDtlsSrtpSetupFailureRtp);
Steve Anton75737c02017-11-06 10:37:17 -08005054}
5055
5056void PeerConnection::OnTransportControllerConnectionState(
5057 cricket::IceConnectionState state) {
5058 switch (state) {
5059 case cricket::kIceConnectionConnecting:
5060 // If the current state is Connected or Completed, then there were
5061 // writable channels but now there are not, so the next state must
5062 // be Disconnected.
5063 // kIceConnectionConnecting is currently used as the default,
5064 // un-connected state by the TransportController, so its only use is
5065 // detecting disconnections.
5066 if (ice_connection_state_ ==
5067 PeerConnectionInterface::kIceConnectionConnected ||
5068 ice_connection_state_ ==
5069 PeerConnectionInterface::kIceConnectionCompleted) {
5070 SetIceConnectionState(
5071 PeerConnectionInterface::kIceConnectionDisconnected);
5072 }
5073 break;
5074 case cricket::kIceConnectionFailed:
5075 SetIceConnectionState(PeerConnectionInterface::kIceConnectionFailed);
5076 break;
5077 case cricket::kIceConnectionConnected:
Mirko Bonadei675513b2017-11-09 11:09:25 +01005078 RTC_LOG(LS_INFO) << "Changing to ICE connected state because "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005079 "all transports are writable.";
Steve Anton75737c02017-11-06 10:37:17 -08005080 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
5081 break;
5082 case cricket::kIceConnectionCompleted:
Mirko Bonadei675513b2017-11-09 11:09:25 +01005083 RTC_LOG(LS_INFO) << "Changing to ICE completed state because "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005084 "all transports are complete.";
Steve Anton75737c02017-11-06 10:37:17 -08005085 if (ice_connection_state_ !=
5086 PeerConnectionInterface::kIceConnectionConnected) {
5087 // If jumping directly from "checking" to "connected",
5088 // signal "connected" first.
5089 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
5090 }
5091 SetIceConnectionState(PeerConnectionInterface::kIceConnectionCompleted);
5092 if (metrics_observer()) {
5093 ReportTransportStats();
5094 }
5095 break;
5096 default:
5097 RTC_NOTREACHED();
5098 }
5099}
5100
5101void PeerConnection::OnTransportControllerCandidatesGathered(
5102 const std::string& transport_name,
5103 const cricket::Candidates& candidates) {
5104 RTC_DCHECK(signaling_thread()->IsCurrent());
5105 int sdp_mline_index;
5106 if (!GetLocalCandidateMediaIndex(transport_name, &sdp_mline_index)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005107 RTC_LOG(LS_ERROR)
5108 << "OnTransportControllerCandidatesGathered: content name "
5109 << transport_name << " not found";
Steve Anton75737c02017-11-06 10:37:17 -08005110 return;
5111 }
5112
5113 for (cricket::Candidates::const_iterator citer = candidates.begin();
5114 citer != candidates.end(); ++citer) {
5115 // Use transport_name as the candidate media id.
5116 std::unique_ptr<JsepIceCandidate> candidate(
5117 new JsepIceCandidate(transport_name, sdp_mline_index, *citer));
5118 if (local_description()) {
5119 mutable_local_description()->AddCandidate(candidate.get());
5120 }
5121 OnIceCandidate(std::move(candidate));
5122 }
5123}
5124
5125void PeerConnection::OnTransportControllerCandidatesRemoved(
5126 const std::vector<cricket::Candidate>& candidates) {
5127 RTC_DCHECK(signaling_thread()->IsCurrent());
5128 // Sanity check.
5129 for (const cricket::Candidate& candidate : candidates) {
5130 if (candidate.transport_name().empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005131 RTC_LOG(LS_ERROR) << "OnTransportControllerCandidatesRemoved: "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005132 "empty content name in candidate "
Mirko Bonadei675513b2017-11-09 11:09:25 +01005133 << candidate.ToString();
Steve Anton75737c02017-11-06 10:37:17 -08005134 return;
5135 }
5136 }
5137
5138 if (local_description()) {
5139 mutable_local_description()->RemoveCandidates(candidates);
5140 }
5141 OnIceCandidatesRemoved(candidates);
5142}
5143
5144void PeerConnection::OnTransportControllerDtlsHandshakeError(
5145 rtc::SSLHandshakeError error) {
5146 if (metrics_observer()) {
5147 metrics_observer()->IncrementEnumCounter(
5148 webrtc::kEnumCounterDtlsHandshakeError, static_cast<int>(error),
5149 static_cast<int>(rtc::SSLHandshakeError::MAX_VALUE));
5150 }
5151}
5152
Steve Antoned10bd92017-12-05 10:52:59 -08005153void PeerConnection::EnableSending() {
5154 for (auto transceiver : transceivers_) {
5155 cricket::BaseChannel* channel = transceiver->internal()->channel();
5156 if (channel && !channel->enabled()) {
5157 channel->Enable(true);
5158 }
Steve Anton75737c02017-11-06 10:37:17 -08005159 }
5160
Steve Anton4171afb2017-11-20 10:20:22 -08005161 if (rtp_data_channel_ && !rtp_data_channel_->enabled()) {
Steve Anton75737c02017-11-06 10:37:17 -08005162 rtp_data_channel_->Enable(true);
Steve Anton4171afb2017-11-20 10:20:22 -08005163 }
Steve Anton75737c02017-11-06 10:37:17 -08005164}
5165
5166// Returns the media index for a local ice candidate given the content name.
5167bool PeerConnection::GetLocalCandidateMediaIndex(
5168 const std::string& content_name,
5169 int* sdp_mline_index) {
5170 if (!local_description() || !sdp_mline_index) {
5171 return false;
5172 }
5173
5174 bool content_found = false;
5175 const ContentInfos& contents = local_description()->description()->contents();
5176 for (size_t index = 0; index < contents.size(); ++index) {
5177 if (contents[index].name == content_name) {
5178 *sdp_mline_index = static_cast<int>(index);
5179 content_found = true;
5180 break;
5181 }
5182 }
5183 return content_found;
5184}
5185
5186bool PeerConnection::UseCandidatesInSessionDescription(
5187 const SessionDescriptionInterface* remote_desc) {
5188 if (!remote_desc) {
5189 return true;
5190 }
5191 bool ret = true;
5192
5193 for (size_t m = 0; m < remote_desc->number_of_mediasections(); ++m) {
5194 const IceCandidateCollection* candidates = remote_desc->candidates(m);
5195 for (size_t n = 0; n < candidates->count(); ++n) {
5196 const IceCandidateInterface* candidate = candidates->at(n);
5197 bool valid = false;
5198 if (!ReadyToUseRemoteCandidate(candidate, remote_desc, &valid)) {
5199 if (valid) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005200 RTC_LOG(LS_INFO)
5201 << "UseCandidatesInSessionDescription: Not ready to use "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005202 "candidate.";
Steve Anton75737c02017-11-06 10:37:17 -08005203 }
5204 continue;
5205 }
5206 ret = UseCandidate(candidate);
5207 if (!ret) {
5208 break;
5209 }
5210 }
5211 }
5212 return ret;
5213}
5214
5215bool PeerConnection::UseCandidate(const IceCandidateInterface* candidate) {
5216 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
5217 size_t remote_content_size =
5218 remote_description()->description()->contents().size();
5219 if (mediacontent_index >= remote_content_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005220 RTC_LOG(LS_ERROR) << "UseCandidate: Invalid candidate media index.";
Steve Anton75737c02017-11-06 10:37:17 -08005221 return false;
5222 }
5223
5224 cricket::ContentInfo content =
5225 remote_description()->description()->contents()[mediacontent_index];
5226 std::vector<cricket::Candidate> candidates;
5227 candidates.push_back(candidate->candidate());
5228 // Invoking BaseSession method to handle remote candidates.
5229 std::string error;
5230 if (transport_controller_->AddRemoteCandidates(content.name, candidates,
5231 &error)) {
5232 // Candidates successfully submitted for checking.
5233 if (ice_connection_state_ == PeerConnectionInterface::kIceConnectionNew ||
5234 ice_connection_state_ ==
5235 PeerConnectionInterface::kIceConnectionDisconnected) {
5236 // If state is New, then the session has just gotten its first remote ICE
5237 // candidates, so go to Checking.
5238 // If state is Disconnected, the session is re-using old candidates or
5239 // receiving additional ones, so go to Checking.
5240 // If state is Connected, stay Connected.
5241 // TODO(bemasc): If state is Connected, and the new candidates are for a
5242 // newly added transport, then the state actually _should_ move to
5243 // checking. Add a way to distinguish that case.
5244 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
5245 }
5246 // TODO(bemasc): If state is Completed, go back to Connected.
5247 } else {
5248 if (!error.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005249 RTC_LOG(LS_WARNING) << error;
Steve Anton75737c02017-11-06 10:37:17 -08005250 }
5251 }
5252 return true;
5253}
5254
5255void PeerConnection::RemoveUnusedChannels(const SessionDescription* desc) {
Steve Anton75737c02017-11-06 10:37:17 -08005256 // Destroy video channel first since it may have a pointer to the
5257 // voice channel.
5258 const cricket::ContentInfo* video_info = cricket::GetFirstVideoContent(desc);
Steve Anton6fec8802017-12-04 10:37:29 -08005259 if (!video_info || video_info->rejected) {
5260 DestroyTransceiverChannel(GetVideoTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08005261 }
5262
Steve Anton6fec8802017-12-04 10:37:29 -08005263 const cricket::ContentInfo* audio_info = cricket::GetFirstAudioContent(desc);
5264 if (!audio_info || audio_info->rejected) {
5265 DestroyTransceiverChannel(GetAudioTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08005266 }
5267
5268 const cricket::ContentInfo* data_info = cricket::GetFirstDataContent(desc);
5269 if (!data_info || data_info->rejected) {
Steve Anton6fec8802017-12-04 10:37:29 -08005270 DestroyDataChannel();
Steve Anton75737c02017-11-06 10:37:17 -08005271 }
5272}
5273
Steve Antoneda6ccd2017-12-04 10:21:55 -08005274std::string PeerConnection::GetTransportNameForMediaSection(
5275 const std::string& mid,
5276 const cricket::ContentGroup* bundle_group) const {
5277 if (!bundle_group) {
5278 return mid;
Steve Anton75737c02017-11-06 10:37:17 -08005279 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005280 const std::string* first_content_name = bundle_group->FirstContentName();
Steve Anton75737c02017-11-06 10:37:17 -08005281 if (!first_content_name) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005282 RTC_LOG(LS_WARNING) << "Tried to BUNDLE with no contents.";
Steve Antoneda6ccd2017-12-04 10:21:55 -08005283 return mid;
Steve Anton75737c02017-11-06 10:37:17 -08005284 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005285 if (!bundle_group->HasContentName(mid)) {
5286 RTC_LOG(LS_WARNING) << mid << " is not part of any bundle group";
5287 return mid;
Steve Anton75737c02017-11-06 10:37:17 -08005288 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005289 RTC_LOG(LS_INFO) << "Bundling " << mid << " on " << *first_content_name;
5290 return *first_content_name;
Steve Anton75737c02017-11-06 10:37:17 -08005291}
5292
Steve Antondcc3c022017-12-22 16:02:54 -08005293RTCErrorOr<const cricket::ContentGroup*> PeerConnection::GetEarlyBundleGroup(
5294 const SessionDescription& desc) const {
Steve Anton75737c02017-11-06 10:37:17 -08005295 const cricket::ContentGroup* bundle_group = nullptr;
5296 if (configuration_.bundle_policy ==
5297 PeerConnectionInterface::kBundlePolicyMaxBundle) {
Steve Antondcc3c022017-12-22 16:02:54 -08005298 bundle_group = desc.GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton75737c02017-11-06 10:37:17 -08005299 if (!bundle_group) {
Steve Anton8a006912017-12-04 15:25:56 -08005300 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5301 "max-bundle configured but session description "
5302 "has no BUNDLE group");
Steve Anton75737c02017-11-06 10:37:17 -08005303 }
5304 }
Steve Antondcc3c022017-12-22 16:02:54 -08005305 return std::move(bundle_group);
5306}
5307
5308RTCError PeerConnection::CreateChannels(const SessionDescription& desc) {
5309 auto bundle_group_or_error = GetEarlyBundleGroup(desc);
5310 if (!bundle_group_or_error.ok()) {
5311 return bundle_group_or_error.MoveError();
5312 }
5313 const cricket::ContentGroup* bundle_group = bundle_group_or_error.MoveValue();
Steve Anton75737c02017-11-06 10:37:17 -08005314
Steve Antoneda6ccd2017-12-04 10:21:55 -08005315 // Creating the media channels and transport proxies.
Steve Antondcc3c022017-12-22 16:02:54 -08005316 const cricket::ContentInfo* voice = cricket::GetFirstAudioContent(&desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08005317 if (voice && !voice->rejected &&
5318 !GetAudioTransceiver()->internal()->channel()) {
5319 cricket::VoiceChannel* voice_channel = CreateVoiceChannel(
5320 voice->name,
5321 GetTransportNameForMediaSection(voice->name, bundle_group));
5322 if (!voice_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08005323 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5324 "Failed to create voice channel.");
Steve Antoneda6ccd2017-12-04 10:21:55 -08005325 }
5326 GetAudioTransceiver()->internal()->SetChannel(voice_channel);
5327 }
5328
Steve Antondcc3c022017-12-22 16:02:54 -08005329 const cricket::ContentInfo* video = cricket::GetFirstVideoContent(&desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08005330 if (video && !video->rejected &&
5331 !GetVideoTransceiver()->internal()->channel()) {
5332 cricket::VideoChannel* video_channel = CreateVideoChannel(
5333 video->name,
5334 GetTransportNameForMediaSection(video->name, bundle_group));
5335 if (!video_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08005336 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5337 "Failed to create video channel.");
Steve Anton75737c02017-11-06 10:37:17 -08005338 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005339 GetVideoTransceiver()->internal()->SetChannel(video_channel);
Steve Anton75737c02017-11-06 10:37:17 -08005340 }
5341
Steve Antondcc3c022017-12-22 16:02:54 -08005342 const cricket::ContentInfo* data = cricket::GetFirstDataContent(&desc);
Steve Anton75737c02017-11-06 10:37:17 -08005343 if (data_channel_type_ != cricket::DCT_NONE && data && !data->rejected &&
5344 !rtp_data_channel_ && !sctp_transport_) {
Steve Antoneda6ccd2017-12-04 10:21:55 -08005345 if (!CreateDataChannel(data->name, GetTransportNameForMediaSection(
5346 data->name, bundle_group))) {
Steve Anton8a006912017-12-04 15:25:56 -08005347 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5348 "Failed to create data channel.");
Steve Anton75737c02017-11-06 10:37:17 -08005349 }
5350 }
5351
Steve Anton8a006912017-12-04 15:25:56 -08005352 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08005353}
5354
Steve Anton4171afb2017-11-20 10:20:22 -08005355// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08005356cricket::VoiceChannel* PeerConnection::CreateVoiceChannel(
5357 const std::string& mid,
5358 const std::string& transport_name) {
Steve Anton75737c02017-11-06 10:37:17 -08005359 cricket::DtlsTransportInternal* rtp_dtls_transport =
5360 transport_controller_->CreateDtlsTransport(
5361 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5362 cricket::DtlsTransportInternal* rtcp_dtls_transport = nullptr;
5363 if (configuration_.rtcp_mux_policy !=
5364 PeerConnectionInterface::kRtcpMuxPolicyRequire) {
5365 rtcp_dtls_transport = transport_controller_->CreateDtlsTransport(
5366 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
5367 }
5368
5369 cricket::VoiceChannel* voice_channel = channel_manager()->CreateVoiceChannel(
5370 call_.get(), configuration_.media_config, rtp_dtls_transport,
Steve Antoneda6ccd2017-12-04 10:21:55 -08005371 rtcp_dtls_transport, signaling_thread(), mid, SrtpRequired(),
5372 audio_options_);
Steve Anton75737c02017-11-06 10:37:17 -08005373 if (!voice_channel) {
5374 transport_controller_->DestroyDtlsTransport(
5375 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5376 if (rtcp_dtls_transport) {
5377 transport_controller_->DestroyDtlsTransport(
5378 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
5379 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005380 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08005381 }
Steve Anton75737c02017-11-06 10:37:17 -08005382 voice_channel->SignalRtcpMuxFullyActive.connect(
5383 this, &PeerConnection::DestroyRtcpTransport_n);
5384 voice_channel->SignalDtlsSrtpSetupFailure.connect(
5385 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08005386 voice_channel->SignalSentPacket.connect(this,
5387 &PeerConnection::OnSentPacket_w);
Steve Anton4171afb2017-11-20 10:20:22 -08005388
Steve Antoneda6ccd2017-12-04 10:21:55 -08005389 return voice_channel;
Steve Anton75737c02017-11-06 10:37:17 -08005390}
5391
Steve Anton4171afb2017-11-20 10:20:22 -08005392// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08005393cricket::VideoChannel* PeerConnection::CreateVideoChannel(
5394 const std::string& mid,
5395 const std::string& transport_name) {
Steve Anton75737c02017-11-06 10:37:17 -08005396 cricket::DtlsTransportInternal* rtp_dtls_transport =
5397 transport_controller_->CreateDtlsTransport(
5398 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5399 cricket::DtlsTransportInternal* rtcp_dtls_transport = nullptr;
5400 if (configuration_.rtcp_mux_policy !=
5401 PeerConnectionInterface::kRtcpMuxPolicyRequire) {
5402 rtcp_dtls_transport = transport_controller_->CreateDtlsTransport(
5403 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
5404 }
5405
5406 cricket::VideoChannel* video_channel = channel_manager()->CreateVideoChannel(
5407 call_.get(), configuration_.media_config, rtp_dtls_transport,
Steve Antoneda6ccd2017-12-04 10:21:55 -08005408 rtcp_dtls_transport, signaling_thread(), mid, SrtpRequired(),
5409 video_options_);
Steve Anton75737c02017-11-06 10:37:17 -08005410
5411 if (!video_channel) {
5412 transport_controller_->DestroyDtlsTransport(
5413 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5414 if (rtcp_dtls_transport) {
5415 transport_controller_->DestroyDtlsTransport(
5416 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
5417 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005418 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08005419 }
Steve Anton75737c02017-11-06 10:37:17 -08005420 video_channel->SignalRtcpMuxFullyActive.connect(
5421 this, &PeerConnection::DestroyRtcpTransport_n);
5422 video_channel->SignalDtlsSrtpSetupFailure.connect(
5423 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08005424 video_channel->SignalSentPacket.connect(this,
5425 &PeerConnection::OnSentPacket_w);
Steve Anton4171afb2017-11-20 10:20:22 -08005426
Steve Antoneda6ccd2017-12-04 10:21:55 -08005427 return video_channel;
Steve Anton75737c02017-11-06 10:37:17 -08005428}
5429
Steve Antoneda6ccd2017-12-04 10:21:55 -08005430bool PeerConnection::CreateDataChannel(const std::string& mid,
5431 const std::string& transport_name) {
Steve Anton75737c02017-11-06 10:37:17 -08005432 bool sctp = (data_channel_type_ == cricket::DCT_SCTP);
5433 if (sctp) {
5434 if (!sctp_factory_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005435 RTC_LOG(LS_ERROR)
Steve Anton75737c02017-11-06 10:37:17 -08005436 << "Trying to create SCTP transport, but didn't compile with "
5437 "SCTP support (HAVE_SCTP)";
5438 return false;
5439 }
5440 if (!network_thread()->Invoke<bool>(
5441 RTC_FROM_HERE, rtc::Bind(&PeerConnection::CreateSctpTransport_n,
Steve Antoneda6ccd2017-12-04 10:21:55 -08005442 this, mid, transport_name))) {
Steve Anton75737c02017-11-06 10:37:17 -08005443 return false;
5444 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005445 for (const auto& channel : sctp_data_channels_) {
5446 channel->OnTransportChannelCreated();
5447 }
Steve Anton75737c02017-11-06 10:37:17 -08005448 } else {
Steve Anton75737c02017-11-06 10:37:17 -08005449 cricket::DtlsTransportInternal* rtp_dtls_transport =
5450 transport_controller_->CreateDtlsTransport(
5451 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5452 cricket::DtlsTransportInternal* rtcp_dtls_transport = nullptr;
5453 if (configuration_.rtcp_mux_policy !=
5454 PeerConnectionInterface::kRtcpMuxPolicyRequire) {
5455 rtcp_dtls_transport = transport_controller_->CreateDtlsTransport(
5456 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
5457 }
5458
5459 rtp_data_channel_ = channel_manager()->CreateRtpDataChannel(
5460 configuration_.media_config, rtp_dtls_transport, rtcp_dtls_transport,
Steve Antoneda6ccd2017-12-04 10:21:55 -08005461 signaling_thread(), mid, SrtpRequired());
Steve Anton75737c02017-11-06 10:37:17 -08005462
5463 if (!rtp_data_channel_) {
5464 transport_controller_->DestroyDtlsTransport(
5465 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5466 if (rtcp_dtls_transport) {
5467 transport_controller_->DestroyDtlsTransport(
5468 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
5469 }
5470 return false;
5471 }
5472
5473 rtp_data_channel_->SignalRtcpMuxFullyActive.connect(
5474 this, &PeerConnection::DestroyRtcpTransport_n);
5475 rtp_data_channel_->SignalDtlsSrtpSetupFailure.connect(
5476 this, &PeerConnection::OnDtlsSrtpSetupFailure);
5477 rtp_data_channel_->SignalSentPacket.connect(
5478 this, &PeerConnection::OnSentPacket_w);
5479 }
5480
Steve Anton75737c02017-11-06 10:37:17 -08005481 return true;
5482}
5483
5484Call::Stats PeerConnection::GetCallStats() {
5485 if (!worker_thread()->IsCurrent()) {
5486 return worker_thread()->Invoke<Call::Stats>(
5487 RTC_FROM_HERE, rtc::Bind(&PeerConnection::GetCallStats, this));
5488 }
5489 if (call_) {
5490 return call_->GetStats();
5491 } else {
5492 return Call::Stats();
5493 }
5494}
5495
Steve Anton75737c02017-11-06 10:37:17 -08005496bool PeerConnection::CreateSctpTransport_n(const std::string& content_name,
5497 const std::string& transport_name) {
5498 RTC_DCHECK(network_thread()->IsCurrent());
5499 RTC_DCHECK(sctp_factory_);
5500 cricket::DtlsTransportInternal* tc =
5501 transport_controller_->CreateDtlsTransport_n(
5502 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5503 sctp_transport_ = sctp_factory_->CreateSctpTransport(tc);
5504 RTC_DCHECK(sctp_transport_);
5505 sctp_invoker_.reset(new rtc::AsyncInvoker());
5506 sctp_transport_->SignalReadyToSendData.connect(
5507 this, &PeerConnection::OnSctpTransportReadyToSendData_n);
5508 sctp_transport_->SignalDataReceived.connect(
5509 this, &PeerConnection::OnSctpTransportDataReceived_n);
5510 sctp_transport_->SignalStreamClosedRemotely.connect(
5511 this, &PeerConnection::OnSctpStreamClosedRemotely_n);
Oskar Sundbom9b28a032017-11-16 10:53:30 +01005512 sctp_transport_name_ = transport_name;
5513 sctp_content_name_ = content_name;
Steve Anton75737c02017-11-06 10:37:17 -08005514 return true;
5515}
5516
5517void PeerConnection::ChangeSctpTransport_n(const std::string& transport_name) {
5518 RTC_DCHECK(network_thread()->IsCurrent());
5519 RTC_DCHECK(sctp_transport_);
5520 RTC_DCHECK(sctp_transport_name_);
5521 std::string old_sctp_transport_name = *sctp_transport_name_;
Oskar Sundbom9b28a032017-11-16 10:53:30 +01005522 sctp_transport_name_ = transport_name;
Steve Anton75737c02017-11-06 10:37:17 -08005523 cricket::DtlsTransportInternal* tc =
5524 transport_controller_->CreateDtlsTransport_n(
5525 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5526 sctp_transport_->SetTransportChannel(tc);
5527 transport_controller_->DestroyDtlsTransport_n(
5528 old_sctp_transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5529}
5530
5531void PeerConnection::DestroySctpTransport_n() {
5532 RTC_DCHECK(network_thread()->IsCurrent());
5533 sctp_transport_.reset(nullptr);
Taylor Brandstetter389a97c2018-01-03 16:26:06 -08005534 transport_controller_->DestroyDtlsTransport_n(
5535 *sctp_transport_name_, cricket::ICE_CANDIDATE_COMPONENT_RTP);
Steve Anton75737c02017-11-06 10:37:17 -08005536 sctp_content_name_.reset();
5537 sctp_transport_name_.reset();
5538 sctp_invoker_.reset(nullptr);
5539 sctp_ready_to_send_data_ = false;
5540}
5541
5542void PeerConnection::OnSctpTransportReadyToSendData_n() {
5543 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5544 RTC_DCHECK(network_thread()->IsCurrent());
5545 // Note: Cannot use rtc::Bind here because it will grab a reference to
5546 // PeerConnection and potentially cause PeerConnection to live longer than
5547 // expected. It is safe not to grab a reference since the sctp_invoker_ will
5548 // be destroyed before PeerConnection is destroyed, and at that point all
5549 // pending tasks will be cleared.
5550 sctp_invoker_->AsyncInvoke<void>(RTC_FROM_HERE, signaling_thread(), [this] {
5551 OnSctpTransportReadyToSendData_s(true);
5552 });
5553}
5554
5555void PeerConnection::OnSctpTransportReadyToSendData_s(bool ready) {
5556 RTC_DCHECK(signaling_thread()->IsCurrent());
5557 sctp_ready_to_send_data_ = ready;
5558 SignalSctpReadyToSendData(ready);
5559}
5560
5561void PeerConnection::OnSctpTransportDataReceived_n(
5562 const cricket::ReceiveDataParams& params,
5563 const rtc::CopyOnWriteBuffer& payload) {
5564 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5565 RTC_DCHECK(network_thread()->IsCurrent());
5566 // Note: Cannot use rtc::Bind here because it will grab a reference to
5567 // PeerConnection and potentially cause PeerConnection to live longer than
5568 // expected. It is safe not to grab a reference since the sctp_invoker_ will
5569 // be destroyed before PeerConnection is destroyed, and at that point all
5570 // pending tasks will be cleared.
5571 sctp_invoker_->AsyncInvoke<void>(
5572 RTC_FROM_HERE, signaling_thread(), [this, params, payload] {
5573 OnSctpTransportDataReceived_s(params, payload);
5574 });
5575}
5576
5577void PeerConnection::OnSctpTransportDataReceived_s(
5578 const cricket::ReceiveDataParams& params,
5579 const rtc::CopyOnWriteBuffer& payload) {
5580 RTC_DCHECK(signaling_thread()->IsCurrent());
5581 if (params.type == cricket::DMT_CONTROL && IsOpenMessage(payload)) {
5582 // Received OPEN message; parse and signal that a new data channel should
5583 // be created.
5584 std::string label;
5585 InternalDataChannelInit config;
5586 config.id = params.ssrc;
5587 if (!ParseDataChannelOpenMessage(payload, &label, &config)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005588 RTC_LOG(LS_WARNING) << "Failed to parse the OPEN message for sid "
5589 << params.ssrc;
Steve Anton75737c02017-11-06 10:37:17 -08005590 return;
5591 }
5592 config.open_handshake_role = InternalDataChannelInit::kAcker;
5593 OnDataChannelOpenMessage(label, config);
5594 } else {
5595 // Otherwise just forward the signal.
5596 SignalSctpDataReceived(params, payload);
5597 }
5598}
5599
5600void PeerConnection::OnSctpStreamClosedRemotely_n(int sid) {
5601 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5602 RTC_DCHECK(network_thread()->IsCurrent());
5603 sctp_invoker_->AsyncInvoke<void>(
5604 RTC_FROM_HERE, signaling_thread(),
5605 rtc::Bind(&sigslot::signal1<int>::operator(),
5606 &SignalSctpStreamClosedRemotely, sid));
5607}
5608
5609// Returns false if bundle is enabled and rtcp_mux is disabled.
5610bool PeerConnection::ValidateBundleSettings(const SessionDescription* desc) {
5611 bool bundle_enabled = desc->HasGroup(cricket::GROUP_TYPE_BUNDLE);
5612 if (!bundle_enabled)
5613 return true;
5614
5615 const cricket::ContentGroup* bundle_group =
5616 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
5617 RTC_DCHECK(bundle_group != NULL);
5618
5619 const cricket::ContentInfos& contents = desc->contents();
5620 for (cricket::ContentInfos::const_iterator citer = contents.begin();
5621 citer != contents.end(); ++citer) {
5622 const cricket::ContentInfo* content = (&*citer);
5623 RTC_DCHECK(content != NULL);
5624 if (bundle_group->HasContentName(content->name) && !content->rejected &&
Steve Anton5adfafd2017-12-20 16:34:00 -08005625 content->type == MediaProtocolType::kRtp) {
Steve Anton75737c02017-11-06 10:37:17 -08005626 if (!HasRtcpMuxEnabled(content))
5627 return false;
5628 }
5629 }
5630 // RTCP-MUX is enabled in all the contents.
5631 return true;
5632}
5633
5634bool PeerConnection::HasRtcpMuxEnabled(const cricket::ContentInfo* content) {
Steve Antonb1c1de12017-12-21 15:14:30 -08005635 return content->media_description()->rtcp_mux();
Steve Anton75737c02017-11-06 10:37:17 -08005636}
5637
Steve Anton8a006912017-12-04 15:25:56 -08005638RTCError PeerConnection::ValidateSessionDescription(
Steve Anton75737c02017-11-06 10:37:17 -08005639 const SessionDescriptionInterface* sdesc,
Steve Anton8a006912017-12-04 15:25:56 -08005640 cricket::ContentSource source) {
Steve Antonf8470812017-12-04 10:46:21 -08005641 if (session_error() != SessionError::kNone) {
Steve Anton8a006912017-12-04 15:25:56 -08005642 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
Steve Anton75737c02017-11-06 10:37:17 -08005643 }
5644
5645 if (!sdesc || !sdesc->description()) {
Steve Anton8a006912017-12-04 15:25:56 -08005646 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidSdp);
Steve Anton75737c02017-11-06 10:37:17 -08005647 }
5648
Steve Anton3828c062017-12-06 10:34:51 -08005649 SdpType type = sdesc->GetType();
5650 if ((source == cricket::CS_LOCAL && !ExpectSetLocalDescription(type)) ||
5651 (source == cricket::CS_REMOTE && !ExpectSetRemoteDescription(type))) {
Steve Anton8a006912017-12-04 15:25:56 -08005652 LOG_AND_RETURN_ERROR(
5653 RTCErrorType::INVALID_PARAMETER,
5654 "Called in wrong state: " + GetSignalingStateString(signaling_state()));
Steve Anton75737c02017-11-06 10:37:17 -08005655 }
5656
5657 // Verify crypto settings.
5658 std::string crypto_error;
Steve Anton8a006912017-12-04 15:25:56 -08005659 if (webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED ||
5660 dtls_enabled_) {
Harald Alvestrand194939b2018-01-24 16:04:13 +01005661 RTCError crypto_error =
5662 VerifyCrypto(sdesc->description(), dtls_enabled_, uma_observer_);
Steve Anton8a006912017-12-04 15:25:56 -08005663 if (!crypto_error.ok()) {
5664 return crypto_error;
5665 }
Steve Anton75737c02017-11-06 10:37:17 -08005666 }
5667
5668 // Verify ice-ufrag and ice-pwd.
5669 if (!VerifyIceUfragPwdPresent(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08005670 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5671 kSdpWithoutIceUfragPwd);
Steve Anton75737c02017-11-06 10:37:17 -08005672 }
5673
5674 if (!ValidateBundleSettings(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08005675 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5676 kBundleWithoutRtcpMux);
Steve Anton75737c02017-11-06 10:37:17 -08005677 }
5678
5679 // TODO(skvlad): When the local rtcp-mux policy is Require, reject any
5680 // m-lines that do not rtcp-mux enabled.
5681
5682 // Verify m-lines in Answer when compared against Offer.
Steve Anton3828c062017-12-06 10:34:51 -08005683 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Seth Hampsonae8a90a2018-02-13 15:33:48 -08005684 // With an answer we want to compare the new answer session description with
5685 // the offer's session description from the current negotiation.
Steve Anton75737c02017-11-06 10:37:17 -08005686 const cricket::SessionDescription* offer_desc =
5687 (source == cricket::CS_LOCAL) ? remote_description()->description()
5688 : local_description()->description();
Seth Hampsonae8a90a2018-02-13 15:33:48 -08005689 if (!MediaSectionsHaveSameCount(*offer_desc, *sdesc->description()) ||
5690 !MediaSectionsInSameOrder(*offer_desc, nullptr, *sdesc->description(),
5691 type)) {
Steve Anton8a006912017-12-04 15:25:56 -08005692 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5693 kMlineMismatchInAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08005694 }
5695 } else {
Steve Anton75737c02017-11-06 10:37:17 -08005696 // The re-offers should respect the order of m= sections in current
5697 // description. See RFC3264 Section 8 paragraph 4 for more details.
Seth Hampsonae8a90a2018-02-13 15:33:48 -08005698 // With a re-offer, either the current local or current remote descriptions
5699 // could be the most up to date, so we would like to check against both of
5700 // them if they exist. It could be the case that one of them has a 0 port
5701 // for a media section, but the other does not. This is important to check
5702 // against in the case that we are recycling an m= section.
5703 const cricket::SessionDescription* current_desc = nullptr;
5704 const cricket::SessionDescription* secondary_current_desc = nullptr;
5705 if (local_description()) {
5706 current_desc = local_description()->description();
5707 if (remote_description()) {
5708 secondary_current_desc = remote_description()->description();
5709 }
5710 } else if (remote_description()) {
5711 current_desc = remote_description()->description();
5712 }
Steve Anton75737c02017-11-06 10:37:17 -08005713 if (current_desc &&
Seth Hampsonae8a90a2018-02-13 15:33:48 -08005714 !MediaSectionsInSameOrder(*current_desc, secondary_current_desc,
5715 *sdesc->description(), type)) {
Steve Anton8a006912017-12-04 15:25:56 -08005716 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5717 kMlineMismatchInSubsequentOffer);
Steve Anton75737c02017-11-06 10:37:17 -08005718 }
5719 }
5720
Steve Anton8a006912017-12-04 15:25:56 -08005721 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08005722}
5723
Steve Anton3828c062017-12-06 10:34:51 -08005724bool PeerConnection::ExpectSetLocalDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08005725 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08005726 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08005727 return (state == PeerConnectionInterface::kStable) ||
5728 (state == PeerConnectionInterface::kHaveLocalOffer);
Steve Anton20393062017-12-04 16:24:52 -08005729 } else {
Steve Anton3828c062017-12-06 10:34:51 -08005730 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08005731 return (state == PeerConnectionInterface::kHaveRemoteOffer) ||
5732 (state == PeerConnectionInterface::kHaveLocalPrAnswer);
5733 }
5734}
5735
Steve Anton3828c062017-12-06 10:34:51 -08005736bool PeerConnection::ExpectSetRemoteDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08005737 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08005738 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08005739 return (state == PeerConnectionInterface::kStable) ||
5740 (state == PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton20393062017-12-04 16:24:52 -08005741 } else {
Steve Anton3828c062017-12-06 10:34:51 -08005742 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08005743 return (state == PeerConnectionInterface::kHaveLocalOffer) ||
5744 (state == PeerConnectionInterface::kHaveRemotePrAnswer);
5745 }
5746}
5747
Steve Antonf8470812017-12-04 10:46:21 -08005748const char* PeerConnection::SessionErrorToString(SessionError error) const {
5749 switch (error) {
5750 case SessionError::kNone:
5751 return "ERROR_NONE";
5752 case SessionError::kContent:
5753 return "ERROR_CONTENT";
5754 case SessionError::kTransport:
5755 return "ERROR_TRANSPORT";
5756 }
5757 RTC_NOTREACHED();
5758 return "";
5759}
5760
Steve Anton75737c02017-11-06 10:37:17 -08005761std::string PeerConnection::GetSessionErrorMsg() {
5762 std::ostringstream desc;
Steve Antonf8470812017-12-04 10:46:21 -08005763 desc << kSessionError << SessionErrorToString(session_error()) << ". ";
5764 desc << kSessionErrorDesc << session_error_desc() << ".";
Steve Anton75737c02017-11-06 10:37:17 -08005765 return desc.str();
5766}
5767
Steve Anton8e20f172018-03-06 10:55:04 -08005768void PeerConnection::ReportSdpFormatReceived(
5769 const SessionDescriptionInterface& remote_offer) {
5770 if (!uma_observer_) {
5771 return;
5772 }
5773 int num_audio_mlines = 0;
5774 int num_video_mlines = 0;
5775 int num_audio_tracks = 0;
5776 int num_video_tracks = 0;
5777 for (const ContentInfo& content : remote_offer.description()->contents()) {
5778 cricket::MediaType media_type = content.media_description()->type();
5779 int num_tracks = std::max(
5780 1, static_cast<int>(content.media_description()->streams().size()));
5781 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
5782 num_audio_mlines += 1;
5783 num_audio_tracks += num_tracks;
5784 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
5785 num_video_mlines += 1;
5786 num_video_tracks += num_tracks;
5787 }
5788 }
5789 SdpFormatReceived format = kSdpFormatReceivedNoTracks;
5790 if (num_audio_mlines > 1 || num_video_mlines > 1) {
5791 format = kSdpFormatReceivedComplexUnifiedPlan;
5792 } else if (num_audio_tracks > 1 || num_video_tracks > 1) {
5793 format = kSdpFormatReceivedComplexPlanB;
5794 } else if (num_audio_tracks > 0 || num_video_tracks > 0) {
5795 format = kSdpFormatReceivedSimple;
5796 }
5797 uma_observer_->IncrementEnumCounter(kEnumCounterSdpFormatReceived, format,
5798 kSdpFormatReceivedMax);
5799}
5800
Steve Anton0ffaaa22018-02-23 10:31:30 -08005801void PeerConnection::ReportNegotiatedSdpSemantics(
5802 const SessionDescriptionInterface& answer) {
5803 if (!uma_observer_) {
5804 return;
5805 }
5806 switch (answer.description()->msid_signaling()) {
5807 case 0:
5808 uma_observer_->IncrementEnumCounter(kEnumCounterSdpSemanticNegotiated,
5809 kSdpSemanticNegotiatedNone,
5810 kSdpSemanticNegotiatedMax);
5811 break;
5812 case cricket::kMsidSignalingMediaSection:
5813 uma_observer_->IncrementEnumCounter(kEnumCounterSdpSemanticNegotiated,
5814 kSdpSemanticNegotiatedUnifiedPlan,
5815 kSdpSemanticNegotiatedMax);
5816 break;
5817 case cricket::kMsidSignalingSsrcAttribute:
5818 uma_observer_->IncrementEnumCounter(kEnumCounterSdpSemanticNegotiated,
5819 kSdpSemanticNegotiatedPlanB,
5820 kSdpSemanticNegotiatedMax);
5821 break;
5822 case cricket::kMsidSignalingMediaSection |
5823 cricket::kMsidSignalingSsrcAttribute:
5824 uma_observer_->IncrementEnumCounter(kEnumCounterSdpSemanticNegotiated,
5825 kSdpSemanticNegotiatedMixed,
5826 kSdpSemanticNegotiatedMax);
5827 break;
5828 default:
5829 RTC_NOTREACHED();
5830 }
5831}
5832
Steve Anton75737c02017-11-06 10:37:17 -08005833// We need to check the local/remote description for the Transport instead of
5834// the session, because a new Transport added during renegotiation may have
5835// them unset while the session has them set from the previous negotiation.
5836// Not doing so may trigger the auto generation of transport description and
5837// mess up DTLS identity information, ICE credential, etc.
5838bool PeerConnection::ReadyToUseRemoteCandidate(
5839 const IceCandidateInterface* candidate,
5840 const SessionDescriptionInterface* remote_desc,
5841 bool* valid) {
5842 *valid = true;
5843
5844 const SessionDescriptionInterface* current_remote_desc =
5845 remote_desc ? remote_desc : remote_description();
5846
5847 if (!current_remote_desc) {
5848 return false;
5849 }
5850
5851 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
5852 size_t remote_content_size =
5853 current_remote_desc->description()->contents().size();
5854 if (mediacontent_index >= remote_content_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005855 RTC_LOG(LS_ERROR)
5856 << "ReadyToUseRemoteCandidate: Invalid candidate media index "
5857 << mediacontent_index;
Steve Anton75737c02017-11-06 10:37:17 -08005858
5859 *valid = false;
5860 return false;
5861 }
5862
5863 cricket::ContentInfo content =
5864 current_remote_desc->description()->contents()[mediacontent_index];
5865
5866 const std::string transport_name = GetTransportName(content.name);
5867 if (transport_name.empty()) {
5868 return false;
5869 }
5870 return transport_controller_->ReadyForRemoteCandidates(transport_name);
5871}
5872
5873bool PeerConnection::SrtpRequired() const {
5874 return dtls_enabled_ ||
5875 webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED;
5876}
5877
5878void PeerConnection::OnTransportControllerGatheringState(
5879 cricket::IceGatheringState state) {
5880 RTC_DCHECK(signaling_thread()->IsCurrent());
5881 if (state == cricket::kIceGatheringGathering) {
5882 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringGathering);
5883 } else if (state == cricket::kIceGatheringComplete) {
5884 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringComplete);
5885 }
5886}
5887
5888void PeerConnection::ReportTransportStats() {
Steve Antonc7b964c2018-02-01 14:39:45 -08005889 std::map<std::string, std::set<cricket::MediaType>>
5890 media_types_by_transport_name;
5891 for (auto transceiver : transceivers_) {
5892 if (transceiver->internal()->channel()) {
5893 const std::string& transport_name =
5894 transceiver->internal()->channel()->transport_name();
5895 media_types_by_transport_name[transport_name].insert(
Steve Anton69470252018-02-09 11:43:08 -08005896 transceiver->media_type());
Steve Antonc7b964c2018-02-01 14:39:45 -08005897 }
Steve Anton75737c02017-11-06 10:37:17 -08005898 }
5899 if (rtp_data_channel()) {
Steve Antonc7b964c2018-02-01 14:39:45 -08005900 media_types_by_transport_name[rtp_data_channel()->transport_name()].insert(
5901 cricket::MEDIA_TYPE_DATA);
Steve Anton75737c02017-11-06 10:37:17 -08005902 }
5903 if (sctp_transport_name_) {
Steve Antonc7b964c2018-02-01 14:39:45 -08005904 media_types_by_transport_name[*sctp_transport_name_].insert(
5905 cricket::MEDIA_TYPE_DATA);
Steve Anton75737c02017-11-06 10:37:17 -08005906 }
Steve Antonc7b964c2018-02-01 14:39:45 -08005907 for (const auto& entry : media_types_by_transport_name) {
5908 const std::string& transport_name = entry.first;
5909 const std::set<cricket::MediaType> media_types = entry.second;
Steve Anton75737c02017-11-06 10:37:17 -08005910 cricket::TransportStats stats;
Steve Antonc7b964c2018-02-01 14:39:45 -08005911 if (transport_controller_->GetStats(transport_name, &stats)) {
Steve Anton75737c02017-11-06 10:37:17 -08005912 ReportBestConnectionState(stats);
Steve Antonc7b964c2018-02-01 14:39:45 -08005913 ReportNegotiatedCiphers(stats, media_types);
Steve Anton75737c02017-11-06 10:37:17 -08005914 }
5915 }
5916}
5917// Walk through the ConnectionInfos to gather best connection usage
5918// for IPv4 and IPv6.
5919void PeerConnection::ReportBestConnectionState(
5920 const cricket::TransportStats& stats) {
5921 RTC_DCHECK(metrics_observer());
Steve Antonc7b964c2018-02-01 14:39:45 -08005922 for (const cricket::TransportChannelStats& channel_stats :
5923 stats.channel_stats) {
5924 for (const cricket::ConnectionInfo& connection_info :
5925 channel_stats.connection_infos) {
5926 if (!connection_info.best_connection) {
Steve Anton75737c02017-11-06 10:37:17 -08005927 continue;
5928 }
5929
5930 PeerConnectionEnumCounterType type = kPeerConnectionEnumCounterMax;
Steve Antonc7b964c2018-02-01 14:39:45 -08005931 const cricket::Candidate& local = connection_info.local_candidate;
5932 const cricket::Candidate& remote = connection_info.remote_candidate;
Steve Anton75737c02017-11-06 10:37:17 -08005933
5934 // Increment the counter for IceCandidatePairType.
5935 if (local.protocol() == cricket::TCP_PROTOCOL_NAME ||
5936 (local.type() == RELAY_PORT_TYPE &&
5937 local.relay_protocol() == cricket::TCP_PROTOCOL_NAME)) {
5938 type = kEnumCounterIceCandidatePairTypeTcp;
5939 } else if (local.protocol() == cricket::UDP_PROTOCOL_NAME) {
5940 type = kEnumCounterIceCandidatePairTypeUdp;
5941 } else {
5942 RTC_CHECK(0);
5943 }
5944 metrics_observer()->IncrementEnumCounter(
5945 type, GetIceCandidatePairCounter(local, remote),
5946 kIceCandidatePairMax);
5947
5948 // Increment the counter for IP type.
5949 if (local.address().family() == AF_INET) {
5950 metrics_observer()->IncrementEnumCounter(
5951 kEnumCounterAddressFamily, kBestConnections_IPv4,
5952 kPeerConnectionAddressFamilyCounter_Max);
5953
5954 } else if (local.address().family() == AF_INET6) {
5955 metrics_observer()->IncrementEnumCounter(
5956 kEnumCounterAddressFamily, kBestConnections_IPv6,
5957 kPeerConnectionAddressFamilyCounter_Max);
5958 } else {
5959 RTC_CHECK(0);
5960 }
5961
5962 return;
5963 }
5964 }
5965}
5966
5967void PeerConnection::ReportNegotiatedCiphers(
Steve Antonc7b964c2018-02-01 14:39:45 -08005968 const cricket::TransportStats& stats,
5969 const std::set<cricket::MediaType>& media_types) {
Steve Anton75737c02017-11-06 10:37:17 -08005970 RTC_DCHECK(metrics_observer());
5971 if (!dtls_enabled_ || stats.channel_stats.empty()) {
5972 return;
5973 }
5974
5975 int srtp_crypto_suite = stats.channel_stats[0].srtp_crypto_suite;
5976 int ssl_cipher_suite = stats.channel_stats[0].ssl_cipher_suite;
5977 if (srtp_crypto_suite == rtc::SRTP_INVALID_CRYPTO_SUITE &&
5978 ssl_cipher_suite == rtc::TLS_NULL_WITH_NULL_NULL) {
5979 return;
5980 }
5981
Steve Antonc7b964c2018-02-01 14:39:45 -08005982 for (cricket::MediaType media_type : media_types) {
5983 PeerConnectionEnumCounterType srtp_counter_type;
5984 PeerConnectionEnumCounterType ssl_counter_type;
5985 switch (media_type) {
5986 case cricket::MEDIA_TYPE_AUDIO:
5987 srtp_counter_type = kEnumCounterAudioSrtpCipher;
5988 ssl_counter_type = kEnumCounterAudioSslCipher;
5989 break;
5990 case cricket::MEDIA_TYPE_VIDEO:
5991 srtp_counter_type = kEnumCounterVideoSrtpCipher;
5992 ssl_counter_type = kEnumCounterVideoSslCipher;
5993 break;
5994 case cricket::MEDIA_TYPE_DATA:
5995 srtp_counter_type = kEnumCounterDataSrtpCipher;
5996 ssl_counter_type = kEnumCounterDataSslCipher;
5997 break;
5998 default:
5999 RTC_NOTREACHED();
6000 continue;
6001 }
6002 if (srtp_crypto_suite != rtc::SRTP_INVALID_CRYPTO_SUITE) {
6003 metrics_observer()->IncrementSparseEnumCounter(srtp_counter_type,
6004 srtp_crypto_suite);
6005 }
6006 if (ssl_cipher_suite != rtc::TLS_NULL_WITH_NULL_NULL) {
6007 metrics_observer()->IncrementSparseEnumCounter(ssl_counter_type,
6008 ssl_cipher_suite);
6009 }
Steve Anton75737c02017-11-06 10:37:17 -08006010 }
6011}
6012
6013void PeerConnection::OnSentPacket_w(const rtc::SentPacket& sent_packet) {
6014 RTC_DCHECK(worker_thread()->IsCurrent());
6015 RTC_DCHECK(call_);
6016 call_->OnSentPacket(sent_packet);
6017}
6018
6019const std::string PeerConnection::GetTransportName(
6020 const std::string& content_name) {
6021 cricket::BaseChannel* channel = GetChannel(content_name);
Steve Anton6fec8802017-12-04 10:37:29 -08006022 if (channel) {
6023 return channel->transport_name();
Steve Anton75737c02017-11-06 10:37:17 -08006024 }
Steve Anton6fec8802017-12-04 10:37:29 -08006025 if (sctp_transport_) {
6026 RTC_DCHECK(sctp_content_name_);
6027 RTC_DCHECK(sctp_transport_name_);
6028 if (content_name == *sctp_content_name_) {
6029 return *sctp_transport_name_;
6030 }
6031 }
6032 // Return an empty string if failed to retrieve the transport name.
6033 return "";
Steve Anton75737c02017-11-06 10:37:17 -08006034}
6035
6036void PeerConnection::DestroyRtcpTransport_n(const std::string& transport_name) {
6037 RTC_DCHECK(network_thread()->IsCurrent());
6038 transport_controller_->DestroyDtlsTransport_n(
6039 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
6040}
6041
Steve Anton6fec8802017-12-04 10:37:29 -08006042void PeerConnection::DestroyTransceiverChannel(
6043 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
6044 transceiver) {
6045 RTC_DCHECK(transceiver);
Steve Anton75737c02017-11-06 10:37:17 -08006046
Steve Anton6fec8802017-12-04 10:37:29 -08006047 cricket::BaseChannel* channel = transceiver->internal()->channel();
6048 if (channel) {
6049 transceiver->internal()->SetChannel(nullptr);
6050 DestroyBaseChannel(channel);
Steve Anton75737c02017-11-06 10:37:17 -08006051 }
6052}
6053
6054void PeerConnection::DestroyDataChannel() {
Steve Anton6fec8802017-12-04 10:37:29 -08006055 if (rtp_data_channel_) {
6056 OnDataChannelDestroyed();
6057 DestroyBaseChannel(rtp_data_channel_);
6058 rtp_data_channel_ = nullptr;
6059 }
6060
6061 // Note: Cannot use rtc::Bind to create a functor to invoke because it will
6062 // grab a reference to this PeerConnection. If this is called from the
6063 // PeerConnection destructor, the RefCountedObject vtable will have already
6064 // been destroyed (since it is a subclass of PeerConnection) and using
6065 // rtc::Bind will cause "Pure virtual function called" error to appear.
6066
6067 if (sctp_transport_) {
6068 OnDataChannelDestroyed();
6069 network_thread()->Invoke<void>(RTC_FROM_HERE,
6070 [this] { DestroySctpTransport_n(); });
6071 }
6072}
6073
6074void PeerConnection::DestroyBaseChannel(cricket::BaseChannel* channel) {
6075 RTC_DCHECK(channel);
6076 RTC_DCHECK(channel->rtp_dtls_transport());
6077
6078 // Need to cache these before destroying the base channel so that we do not
6079 // access uninitialized memory.
6080 const std::string transport_name =
6081 channel->rtp_dtls_transport()->transport_name();
6082 const bool need_to_delete_rtcp = (channel->rtcp_dtls_transport() != nullptr);
6083
6084 switch (channel->media_type()) {
6085 case cricket::MEDIA_TYPE_AUDIO:
6086 channel_manager()->DestroyVoiceChannel(
6087 static_cast<cricket::VoiceChannel*>(channel));
6088 break;
6089 case cricket::MEDIA_TYPE_VIDEO:
6090 channel_manager()->DestroyVideoChannel(
6091 static_cast<cricket::VideoChannel*>(channel));
6092 break;
6093 case cricket::MEDIA_TYPE_DATA:
6094 channel_manager()->DestroyRtpDataChannel(
6095 static_cast<cricket::RtpDataChannel*>(channel));
6096 break;
6097 default:
6098 RTC_NOTREACHED() << "Unknown media type: " << channel->media_type();
6099 break;
6100 }
6101
6102 // |channel| can no longer be used.
6103
Steve Anton75737c02017-11-06 10:37:17 -08006104 transport_controller_->DestroyDtlsTransport(
6105 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
6106 if (need_to_delete_rtcp) {
6107 transport_controller_->DestroyDtlsTransport(
6108 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
6109 }
6110}
6111
Harald Alvestrand89061872018-01-02 14:08:34 +01006112void PeerConnection::ClearStatsCache() {
6113 if (stats_collector_) {
6114 stats_collector_->ClearCachedStatsReport();
6115 }
6116}
6117
henrike@webrtc.org28e20752013-07-10 00:45:36 +00006118} // namespace webrtc